diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 00000000..7f3c6ab9 --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,2 @@ +# Format Ruby with syntax_tree +887fbe07a5f0e6d6ec55291c766457c3cf752b9f diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index d3ab2271..0ee7f84e 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -186,6 +186,32 @@ The packaging test expects the program to be refused on a tmux that lacks a listed capability and to succeed on one that has them all, and the docs export gives each page the release it needs in `tmux_releases`. +Format Ruby source at 100 columns and examples at 80, then refresh the copied +examples and API source links: + +```console +$ mise exec -- bundle exec scripts/format +``` + +Run the same read-only format check as CI: + +```console +$ mise exec -- bundle exec scripts/format --check +``` + +Standard formats and lints the Ruby files under `scripts/`. + +The shared width check reads tracked Markdown and example files. Download the +[pinned checker][example-width-checker] and run it from the checkout with +Python 3.11 or newer: + +```console +$ python3 /path/to/check_example_width.py --root . +``` + +[example-width-checker]: https://raw.githubusercontent.com/libtmux/.github/bd3bae79572512da032287202d74c8da03b5967b/actions/check-example-width/check_example_width.py + + Check unstaged changes for whitespace errors: ```console diff --git a/.github/WRITING.md b/.github/WRITING.md index 5e7bf63c..5c211a13 100644 --- a/.github/WRITING.md +++ b/.github/WRITING.md @@ -70,6 +70,8 @@ lines. Omit narration of surrounding code, duplicated counts or defaults, and history recorded by Git. Preserve tool directives and markers such as `# frozen_string_literal: true` and `# docs:begin` / `# docs:end`. +### Code blocks + Code blocks are paste-and-run units enforced by `test/unit/readme_blocks_test.rb` and `test/integration/readme_commands_test.rb`: @@ -81,6 +83,93 @@ Code blocks are paste-and-run units enforced by - Tag source fences with their language and wrap displayed code lines within 80 columns. +## Examples + + + +An example is code written for a reader: a program under `examples/`, code in +a doc comment or docstring, and every fenced block in a README or docs page. +Shell blocks also follow [Code blocks](#code-blocks). + +The text between the shared markers is the same in every libtmux port. +Change it in all of them together. + +### Width + +- **Examples stay within 80 columns.** They render in fixed-width boxes that + scroll sideways, and 80 columns fits a libtmux.org code block in a + laptop-width window. Comments inside examples wrap at 80 too. +- **The width check enforces it.** It reads the tracked files that + `.github/example-width.toml` names and fails on a wider line. It measures + the whole source line, so code in a doc comment counts its indent and + comment marker. It skips output (a fence tagged `text`, and what a + `console` block prints), hidden setup lines, and a line that is only a URL; + an untagged fence counts as code. +- **A line that must stay wider is listed there with its reason.** An entry + that no longer matches a line fails the check, so no stale entry stays. +- **The formatter's width is the hard limit for all other source.** Example + directories set their formatter to 80 where the formatter takes a width. + +### Reaching 80 + +- **Change the code, not the line breaks.** A formatter rejoins any line that + fits its width. Name a sub-expression, use a short example name, hide setup + the reader does not need, or print less. +- **Break at the outermost level when a break is still needed:** after an + opening parenthesis with one argument per line, one call per line in a + chain, one field per line in a literal. +- **Put a comment on its own line above the code it explains.** Never trail + one after code in an example, unless the repository's example runner reads + it there, as with an assertion marker. +- **Break a long string at a word boundary,** never inside a tmux format + (`#{...}`) or an escape sequence; the joined text stays the same. +- **Continue a long command in a `console` block the way its shell does:** + `\` after a `$ ` prompt, a backtick after `PS> `, one flag per continuation + line. + +### What never breaks + +- **Output a test compares.** Wrapping it changes what the test expects. +- **A block copied from a source file.** Fix the width in the source and run + the sync command; never edit the copy. +- **Marker lines and URLs,** which tools and readers take whole. + + + +### In this repository + +- **Hard limit:** Syntax Tree formats Ruby examples at 80 columns. Run + `bundle exec scripts/format --check` to check the format. The shared + width action checks the files listed in `.github/example-width.toml`. +- **Not formatted:** Markdown fences, Ruby comments, and YAML example + files still count toward the width limit. +- **Runs, compiles, exempt:** An `` marker names a + source in `examples/manifest.json`. The excerpt copies the whole source + or a named `# docs:begin NAME` region. Run + `scripts/examples/examples --check` to verify copied excerpts. The + installed-gem tests run the Ruby programs. Console and output fences + use no marker. +- **Compared output and copied blocks:** Keep expected output verbatim. + Edit the source and run `bundle exec scripts/format` to refresh excerpts + and API source links. + +Bad, over 80: + +```ruby +script = + 'printf "%s:%s" "$EXAMPLE_CONTEXT" "$TMUX_PANE"; printf "\\000\\377" >&2; exit 9' +``` + +Good, each command has its own line: + +```ruby +script = [ + 'printf "%s:%s" "$EXAMPLE_CONTEXT" "$TMUX_PANE"', + 'printf "\\000\\377" >&2', + "exit 9" +].join("; ") +``` + ## Commits, changelogs, and releases Follow the scoped commit and pull request rules in diff --git a/.github/example-width.toml b/.github/example-width.toml new file mode 100644 index 00000000..698b01c7 --- /dev/null +++ b/.github/example-width.toml @@ -0,0 +1,22 @@ +width = 80 +markdown = ["**/*.md"] +sources = ["examples/**/*.rb", "examples/**/*.yaml", "examples/**/*.json"] +allow_ceiling = 1 +shared_digest = "872d3f4cb1eb2b5cd9c5b7adc9cd140a153e4bbed3cb5bd0b7400a905e6dae4d" + +[[exclude]] +glob = "examples/manifest.json" +reason = "machine-read index whose output strings the example tests compare byte for byte; its line breaks cannot change" + +[[exclude]] +glob = "scripts/examples/examples" +reason = "Ruby maintainer command that verifies published examples" + +[[exclude]] +glob = "scripts/examples/tests/example_manifest_test.rb" +reason = "unit tests for the manifest checker" + +[[allow]] +path = ".github/WRITING.md" +line = " 'printf \"%s:%s\" \"$EXAMPLE_CONTEXT\" \"$TMUX_PANE\"; printf \"\\\\000\\\\377\" >&2; exit 9'" +reason = "the Bad example in the port block; it shows the width problem the Good example fixes" diff --git a/.github/workflows/compatibility.yml b/.github/workflows/compatibility.yml index 78ef28b5..e539f1c5 100644 --- a/.github/workflows/compatibility.yml +++ b/.github/workflows/compatibility.yml @@ -117,6 +117,10 @@ jobs: with: ruby-version: '4.0.7' bundler-cache: true + - name: Check Ruby formatting + run: bundle exec scripts/format --check + - name: Check example width + uses: libtmux/.github/actions/check-example-width@bd3bae79572512da032287202d74c8da03b5967b - name: Install consumer test prerequisites uses: libtmux/.github/actions/apt-get@30f81842b1e639ea4e25f93f1f2543504178e228 with: diff --git a/AGENTS.md b/AGENTS.md index 957b239a..956c981f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -22,6 +22,7 @@ requested work. [.github/CONTRIBUTING.md](.github/CONTRIBUTING.md). - Documentation, user-facing text, comments, and commit messages: [.github/WRITING.md](.github/WRITING.md). +- Code examples: [Examples](.github/WRITING.md#examples). - Support scripts: what may stay, their language, layout and checks: [.github/SCRIPTS.md](.github/SCRIPTS.md). diff --git a/CHANGELOG.md b/CHANGELOG.md index 225ee9f2..102faee7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,9 @@ at one version, so a release has a section in each changelog. ## 0.1.4 (unreleased) +- Format Ruby source and check that published examples fit within + 80 columns. (#19) + ## 0.1.3 (2026-12-05) Core and Async can wait for visible pane text with a deadline. On tmux 3.7 diff --git a/Gemfile b/Gemfile index 11ee473c..606f7098 100644 --- a/Gemfile +++ b/Gemfile @@ -2,9 +2,7 @@ source "https://rubygems.org" -%w[libtmux libtmux-async libtmux-mcp libtmux-workspace].each do |name| - gemspec path: "gems/#{name}" -end +%w[libtmux libtmux-async libtmux-mcp libtmux-workspace].each { |name| gemspec path: "gems/#{name}" } group :test do gem "fcntl", "~> 1.3" @@ -18,3 +16,7 @@ end gem "rake", "~> 13.3" gem "rbs", "~> 3.10" gem "yard", "~> 0.9" + +group :development do + gem "syntax_tree", "~> 6.3" +end diff --git a/Gemfile.lock b/Gemfile.lock index 80cbefc9..2802cd2c 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -80,6 +80,7 @@ GEM parser (3.3.13.0) ast (~> 2.4.1) racc + prettier_print (1.2.1) prism (1.9.0) psych (5.5.0) date @@ -125,6 +126,8 @@ GEM lint_roller (~> 1.1) rubocop-performance (~> 1.26.0) stringio (3.2.0) + syntax_tree (6.3.0) + prettier_print (>= 1.2.0) tmpdir (0.3.1) fileutils tsort (0.2.0) @@ -150,6 +153,7 @@ DEPENDENCIES rake (~> 13.3) rbs (~> 3.10) standard (~> 1.57) + syntax_tree (~> 6.3) yard (~> 0.9) CHECKSUMS @@ -184,6 +188,7 @@ CHECKSUMS optparse (0.8.1) sha256=42bea10d53907ccff4f080a69991441d611fbf8733b60ed1ce9ee365ce03bd1a parallel (2.3.0) sha256=f75a3e904101ce6a1ccb6b8dc800cbafd42166d83330192438dcf29395167a6f parser (3.3.13.0) sha256=e02f9b63c2fe05b0c68f692ba4df89b3cb113b663964f75d988fbebfd6c3deca + prettier_print (1.2.1) sha256=a72838b5f23facff21f90a5423cdcdda19e4271092b41f4ea7f50b83929e6ff9 prism (1.9.0) sha256=7b530c6a9f92c24300014919c9dcbc055bf4cdf51ec30aed099b06cd6674ef85 psych (5.5.0) sha256=4b245bbbd0f3238df8ccee766ebc1a6b062b10e4ee1d3284eb588739ba156a0a racc (1.8.1) sha256=4a7f6929691dbec8b5209a0b373bc2614882b55fc5d2e447a21aaa691303d62f @@ -201,6 +206,7 @@ CHECKSUMS standard-custom (1.0.2) sha256=424adc84179a074f1a2a309bb9cf7cd6bfdb2b6541f20c6bf9436c0ba22a652b standard-performance (1.9.0) sha256=49483d31be448292951d80e5e67cdcb576c2502103c7b40aec6f1b6e9c88e3f2 stringio (3.2.0) sha256=c37cb2e58b4ffbd33fe5cd948c05934af997b36e0b6ca6fdf43afa234cf222e1 + syntax_tree (6.3.0) sha256=56e25a9692c798ec94c5442fe94c5e94af76bef91edc8bb02052cbdecf35f13d tmpdir (0.3.1) sha256=908e9729bb31ce104ba27fc03cfc8293a7f858a8dc9e3a1d7cfd112919a3513d tsort (0.2.0) sha256=9650a793f6859a43b6641671278f79cfead60ac714148aabe4e3f0060480089f unicode-display_width (3.3.0) sha256=4b7aa66a4b11db50f6f7e98411215cd0dd10eaecb665d36eec5bcacb3fa0b613 diff --git a/README.md b/README.md index aaec5a72..34871bc7 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,7 @@ def wait_until(message) end end -command = [RbConfig.ruby, "-e", <<~'RUBY'] +greeting_command = [RbConfig.ruby, "-e", <<~'RUBY'] $stdout.sync = true puts "What is your name?" name = STDIN.gets or exit 1 @@ -67,9 +67,12 @@ RUBY LibTmux::Server.start do |server| server.options(scope: :window).set("remain-on-exit", true) - pane = server.new_session( - name: "greeting", command: command, receipt: true - ).pane + pane = + server.new_session( + name: "greeting", + command: greeting_command, + receipt: true + ).pane wait_until("CLI did not prompt for a name") do |remaining| lines = pane.capture(timeout: remaining).text.lines(chomp: true) @@ -78,15 +81,19 @@ LibTmux::Server.start do |server| pane.send_text("Ada") pane.send_keys("Enter") - status = wait_until("CLI did not report an exit status") do |remaining| - state = pane.snapshot(timeout: remaining) - state.dead_status if state.dead? - end + status = + wait_until("CLI did not report an exit status") do |remaining| + state = pane.snapshot(timeout: remaining) + state.dead_status if state.dead? + end raise "CLI exited with status #{status}" unless status == 0 - greeting = pane.capture(start: "-").text.lines(chomp: true).find do |line| - line == "Hello, Ada!" - end + greeting = + pane + .capture(start: "-") + .text + .lines(chomp: true) + .find { |line| line == "Hello, Ada!" } raise "CLI did not greet Ada" unless greeting puts greeting end @@ -115,18 +122,22 @@ Create a session, add a window, split it, and print each window with its panes: ```ruby require "libtmux" -snapshot = LibTmux::Server.start do |server| - session = server.new_session( - name: "work", window_name: "main", command: ["/bin/cat"] - ) - window = session.new_window(name: "logs", command: ["/bin/cat"]) - window.split(direction: :horizontal, size: "40%", command: ["/bin/cat"]) - - server.snapshot -end +snapshot = + LibTmux::Server.start do |server| + session = + server.new_session( + name: "work", + window_name: "main", + command: ["/bin/cat"] + ) + window = session.new_window(name: "logs", command: ["/bin/cat"]) + window.split(direction: :horizontal, size: "40%", command: ["/bin/cat"]) + + server.snapshot + end snapshot.windows.each do |window| - puts "#{window.name}: #{window.panes.map(&:id).join(', ')}" + puts "#{window.name}: #{window.panes.map(&:id).join(", ")}" end ``` @@ -170,9 +181,7 @@ LibTmux::Server.start do |server| pane.send_keys("Enter") line = nil 50.times do - line = pane.capture.text.lines(chomp: true).find do |text| - text == "café" - end + line = pane.capture.text.lines(chomp: true).find { |text| text == "café" } break if line sleep 0.1 end @@ -203,15 +212,19 @@ locally and make no tmux calls: ```ruby require "libtmux" -snapshot = LibTmux::Server.start do |server| - session = server.new_session( - name: "work", window_name: "main", command: ["/bin/cat"] - ) - window = session.new_window(name: "logs", command: ["/bin/cat"]) - window.split(direction: :horizontal, size: "40%", command: ["/bin/cat"]) - - server.snapshot -end +snapshot = + LibTmux::Server.start do |server| + session = + server.new_session( + name: "work", + window_name: "main", + command: ["/bin/cat"] + ) + window = session.new_window(name: "logs", command: ["/bin/cat"]) + window.split(direction: :horizontal, size: "40%", command: ["/bin/cat"]) + + server.snapshot + end panes = snapshot.panes active_ids = panes.where(active: true).map(&:id) @@ -221,8 +234,8 @@ panes_by_window = panes.group_by { |pane| pane.window.name } logs = snapshot.windows.one(name: "logs") missing = snapshot.windows.one_or_nil(name: "missing") -puts "active: #{active_ids.join(', ')}" -puts "wide: #{wide_panes.map(&:id).join(', ')}" +puts "active: #{active_ids.join(", ")}" +puts "wide: #{wide_panes.map(&:id).join(", ")}" puts "logs panes: #{logs.panes.length}" puts "missing: #{missing.inspect}" ``` @@ -258,11 +271,11 @@ require "libtmux" LibTmux::Server.start do |server| server.new_session(name: "work", command: ["/bin/cat"]) - criteria = {active: true} + criteria = { active: true } plan = server.explain_panes(where: criteria) puts "tmux reads: #{plan.fetch(:capture)}" - puts "tmux filters: #{plan.fetch(:pushed) || 'nothing'}" - puts "Ruby filters: #{plan.fetch(:residual).fetch('where').keys.join(', ')}" + puts "tmux filters: #{plan.fetch(:pushed) || "nothing"}" + puts "Ruby filters: #{plan.fetch(:residual).fetch("where").keys.join(", ")}" puts "matching panes: #{server.search_panes(where: criteria).length}" end ``` @@ -294,9 +307,12 @@ hold as it was. [`Session#snapshot`][session-snapshot] and require "libtmux" LibTmux::Server.start do |server| - session = server.new_session( - name: "work", window_name: "editor", command: ["/bin/cat"] - ) + session = + server.new_session( + name: "work", + window_name: "editor", + command: ["/bin/cat"] + ) window = session.list_windows.fetch(0) held = window.snapshot @@ -332,14 +348,18 @@ require "libtmux" LibTmux::Server.start do |server| server.new_session(name: "work", command: ["/bin/cat"]) - group = server.run_group([ - ["set-option", "-g", "@before", "kept"], - ["select-pane", "-t", "%4294967294"], - ["set-option", "-g", "@after", "never run"] - ]) + group = + server.run_group( + [ + %w[set-option -g @before kept], + %w[select-pane -t %4294967294], + ["set-option", "-g", "@after", "never run"] + ] + ) puts "success: #{group.success?}" - puts "steps: #{group.steps.map { |step| step.fetch(:outcome) }.join(', ')}" - puts "@before: #{server.options(scope: :session).get('@before').as(:string)}" + puts "steps: #{group.steps.map { |step| step.fetch(:outcome) }.join(", ")}" + before = server.options(scope: :session).get("@before").as(:string) + puts "@before: #{before}" end ``` @@ -527,9 +547,10 @@ LibTmux::Server.start do |server| Async do |parent| LibTmux::Async.open(parent: parent, server: server) do |scope| refs = scope.server.list_panes.map(&:ref) - screens = scope.map(refs, concurrency: 2) do |ref| - scope.server.pane(ref).capture - end + screens = + scope.map(refs, concurrency: 2) do |ref| + scope.server.pane(ref).capture + end puts "captured panes: #{screens.length}" puts "all succeeded: #{screens.all?(&:success?)}" end diff --git a/Rakefile b/Rakefile index 4b49959c..994f04e2 100644 --- a/Rakefile +++ b/Rakefile @@ -30,17 +30,22 @@ end namespace :release do %w[prepare verify publish dry_run github].each do |operation| - desc({"prepare" => "Build and retain the complete release artifact set", - "verify" => "Verify retained release artifacts without network access", - "publish" => "Publish verified artifacts from the trusted tag workflow", - "github" => "Create or complete the GitHub release from retained artifacts", - "dry_run" => "Build, verify and test installed artifacts without uploading"}.fetch(operation)) - task operation, [:tag, :commit] do |_, args| + desc( + { + "prepare" => "Build and retain the complete release artifact set", + "verify" => "Verify retained release artifacts without network access", + "publish" => "Publish verified artifacts from the trusted tag workflow", + "github" => "Create or complete the GitHub release from retained artifacts", + "dry_run" => "Build, verify and test installed artifacts without uploading" + }.fetch(operation) + ) + task operation, %i[tag commit] do |_, args| require "open3" load "scripts/release/release.rb" unless defined?(GemRelease) tag = args[:tag] || ENV["RELEASE_TAG"] # A dry run on a branch has no tag, so it rehearses the checkout's version. - tag ||= "v#{Gem::Specification.load('gems/libtmux/libtmux.gemspec').version}" if operation == "dry_run" + tag ||= "v#{Gem::Specification.load("gems/libtmux/libtmux.gemspec").version}" if operation == + "dry_run" tag ||= ENV.fetch("RELEASE_TAG") commit = args[:commit] || ENV["RELEASE_COMMIT"] unless commit @@ -58,13 +63,18 @@ namespace :release do manifest = release.publish(tag: tag, commit: commit) else release = GemRelease.new(__dir__) - manifest = release.public_send(operation == "dry_run" ? :prepare : operation, tag: tag, commit: commit) + manifest = + release.public_send( + operation == "dry_run" ? :prepare : operation, + tag: tag, + commit: commit + ) end if operation == "dry_run" - sh({"LIBTMUX_RELEASE_DIR" => "pkg/release"}, Gem.ruby, "scripts/check", "packaging") + sh({ "LIBTMUX_RELEASE_DIR" => "pkg/release" }, Gem.ruby, "scripts/check", "packaging") release.verify(tag: tag, commit: commit) end - puts "#{operation}: #{manifest.fetch('tag')} at #{manifest.fetch('commit')}" + puts "#{operation}: #{manifest.fetch("tag")} at #{manifest.fetch("commit")}" end end end diff --git a/docs/recipes.md b/docs/recipes.md index 84ea3c06..e3627e44 100644 --- a/docs/recipes.md +++ b/docs/recipes.md @@ -21,13 +21,14 @@ the captured records after closing the server. ```ruby require "libtmux" -panes = LibTmux::Server.start do |server| - session = server.new_session(name: "capture", command: ["/bin/cat"]) - session.new_window(name: "second", command: ["/bin/cat"]) - captured = server.snapshot.panes - session.new_window(name: "later", command: ["/bin/cat"]) - captured -end +panes = + LibTmux::Server.start do |server| + session = server.new_session(name: "capture", command: ["/bin/cat"]) + session.new_window(name: "second", command: ["/bin/cat"]) + captured = server.snapshot.panes + session.new_window(name: "later", command: ["/bin/cat"]) + captured + end first = panes.one(id: panes.first.id) puts "captured panes: #{panes.size}" @@ -53,10 +54,15 @@ bytes. require "libtmux" LibTmux::Server.start do |server| - receipt = server.new_session( - name: "layout", command: ["/bin/sh"], receipt: true, - environment: {"ENV" => "/dev/null"} - ) + receipt = + server.new_session( + name: "layout", + command: ["/bin/sh"], + receipt: true, + environment: { + "ENV" => "/dev/null" + } + ) pane = receipt.pane side = pane.split(direction: :horizontal, size: "40%", command: ["/bin/cat"]) receipt.window.select_layout("tiled") @@ -66,17 +72,17 @@ LibTmux::Server.start do |server| end expected = "pane prête" - send_command = lambda do - pane.send_text("printf '\\n%s %s\\n' 'pane' 'prête'") - pane.send_keys("Enter") - end + send_command = + lambda do + pane.send_text("printf '\\n%s %s\\n' 'pane' 'prête'") + pane.send_keys("Enter") + end deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 5 if server.supports_control? server.open_control(session: receipt.entity.ref) do |control| control.exchange("display-message -p ready") - output = control.subscribe( - pane_id: pane.id, max_bytes: 8192, max_events: 32 - ) + output = + control.subscribe(pane_id: pane.id, max_bytes: 8192, max_events: 32) send_command.call received = +"".b until received.include?(expected.b) @@ -125,8 +131,8 @@ LibTmux::Server.start do |server| session.link_window(window.ref, index: 4) session.link_window(window.ref, index: 9) links = session.list_window_links - puts "indexes: #{links.map(&:index).join(', ')}" - puts "windows: #{links.map { |link| link.window.id }.uniq.join(', ')}" + puts "indexes: #{links.map(&:index).join(", ")}" + puts "windows: #{links.map { |link| link.window.id }.uniq.join(", ")}" end ``` @@ -143,12 +149,16 @@ require "libtmux" LibTmux::Server.start do |server| server.new_session(name: "work", command: ["/bin/cat"]) cancellation = LibTmux::Cancellation.new - waiting = Thread.new do - server.run(["wait-for", "-S", "ready", ";", "wait-for", "held"], - timeout: 5, cancel: cancellation) - rescue LibTmux::Cancelled => error - error - end + waiting = + Thread.new do + server.run( + %w[wait-for -S ready ; wait-for held], + timeout: 5, + cancel: cancellation + ) + rescue LibTmux::Cancelled => error + error + end server.wait_for("ready", timeout: 5) cancellation.cancel failure = waiting.value @@ -185,17 +195,18 @@ LibTmux::Server.start do |server| server.new_session(name: "async", command: ["/bin/cat"]) Async do |parent| LibTmux::Async.open(parent: parent, server: server) do |scope| - waiting = parent.async do - scope.server.run(["wait-for", "-S", "ready", ";", "wait-for", "held"], - timeout: 5) - rescue LibTmux::Cancelled => error - error - end + waiting = + parent.async do + scope.server.run(%w[wait-for -S ready ; wait-for held], timeout: 5) + rescue LibTmux::Cancelled => error + error + end scope.server.wait_for("ready", timeout: 5) panes = scope.server.list_panes.map(&:ref) - captures = scope.map(panes, concurrency: 2) do |ref| - scope.server.pane(ref).capture - end + captures = + scope.map(panes, concurrency: 2) do |ref| + scope.server.pane(ref).capture + end raise "A pane capture failed" unless captures.all?(&:success?) puts "captures: #{captures.length}" @@ -261,8 +272,9 @@ LibTmux::Server.start do |server| rescue LibTmux::SubscriptionOverflow end gap = tail.next(timeout: 5) - raise "Expected an output gap with dropped bytes" unless gap.kind == :gap && - gap.dropped_bytes.positive? + unless gap.kind == :gap && gap.dropped_bytes.positive? + raise "Expected an output gap with dropped bytes" + end end end ``` @@ -279,14 +291,18 @@ require "libtmux" LibTmux::Server.start do |server| server.new_session(name: "work", command: ["/bin/cat"]) - group = server.run_group([ - ["set-option", "-g", "@before", "kept"], - ["select-pane", "-t", "%4294967294"], - ["set-option", "-g", "@after", "never run"] - ]) + group = + server.run_group( + [ + %w[set-option -g @before kept], + %w[select-pane -t %4294967294], + ["set-option", "-g", "@after", "never run"] + ] + ) puts "success: #{group.success?}" - puts "steps: #{group.steps.map { |step| step.fetch(:outcome) }.join(', ')}" - puts "@before: #{server.options(scope: :session).get('@before').as(:string)}" + puts "steps: #{group.steps.map { |step| step.fetch(:outcome) }.join(", ")}" + before = server.options(scope: :session).get("@before").as(:string) + puts "@before: #{before}" end ``` @@ -355,35 +371,63 @@ LibTmux::Server.start do |server| LibTmux::Async.open(parent: parent, server: server) do |scope| IO.pipe do |requests, send_request| IO.pipe do |receive_reply, replies| - app = LibTmux::MCP::Application.new( - server: scope.server, endpoint_name: "example" - ) - begin - transport = LibTmux::MCP::StdioTransport.new( - server: app.sdk_server, parent: parent, input: requests, - output: replies + app = + LibTmux::MCP::Application.new( + server: scope.server, + endpoint_name: "example" ) + begin + transport = + LibTmux::MCP::StdioTransport.new( + server: app.sdk_server, + parent: parent, + input: requests, + output: replies + ) runner = parent.async { transport.run } - request = lambda do |id, method, params, timeout:| - frame = {jsonrpc: "2.0", id: id, method: method, params: params} - send_request.puts(JSON.generate(frame)) - line = parent.with_timeout(timeout) { receive_reply.readline } - reply = JSON.parse(line) - raise "Expected reply #{id}" unless reply.fetch("id") == id - - reply.fetch("result") - end - initialized = request.call(1, "initialize", { - protocolVersion: "2025-11-25", capabilities: {}, - clientInfo: {name: "recipe", version: "1"} - }, timeout: 10) - puts "protocol version: #{initialized.fetch('protocolVersion')}" - send_request.puts(JSON.generate( - {jsonrpc: "2.0", method: "notifications/initialized"} - )) - snapshot = request.call(2, "tools/call", { - name: "tmux_snapshot", arguments: {entity: "pane"} - }, timeout: 5) + request = + lambda do |id, method, params, timeout:| + frame = { + jsonrpc: "2.0", + id: id, + method: method, + params: params + } + send_request.puts(JSON.generate(frame)) + line = parent.with_timeout(timeout) { receive_reply.readline } + reply = JSON.parse(line) + raise "Expected reply #{id}" unless reply.fetch("id") == id + + reply.fetch("result") + end + initialized = + request.call( + 1, + "initialize", + { + protocolVersion: "2025-11-25", + capabilities: { + }, + clientInfo: { + name: "recipe", + version: "1" + } + }, + timeout: 10 + ) + puts "protocol version: #{initialized.fetch("protocolVersion")}" + send_request.puts( + JSON.generate( + { jsonrpc: "2.0", method: "notifications/initialized" } + ) + ) + snapshot = + request.call( + 2, + "tools/call", + { name: "tmux_snapshot", arguments: { entity: "pane" } }, + timeout: 5 + ) data = snapshot.fetch("structuredContent").fetch("data") panes = data.fetch("items") puts "panes: #{panes.length}" @@ -419,32 +463,51 @@ require "timeout" LibTmux::Server.start do |server| server.new_session(name: "protocol", command: ["/bin/cat"]) executable = Gem.bin_path("libtmux-mcp", "libtmux-mcp") - command = [Gem.ruby, "-W:no-experimental", executable, - "--socket", server.endpoint.socket_path] + command = [ + Gem.ruby, + "-W:no-experimental", + executable, + "--socket", + server.endpoint.socket_path + ] Open3.popen3(*command, pgroup: true) do |input, output, errors, child| - request = lambda do |id, method, params = {}, timeout:| - frame = {jsonrpc: "2.0", id: id, method: method, params: params} - input.puts(JSON.generate(frame)) - reply = JSON.parse(Timeout.timeout(timeout) { output.readline }) - raise "Expected reply #{id} for #{method}" unless reply.fetch("id") == id - - reply.fetch("result") - rescue Timeout::Error - raise "Timed out waiting for #{method} after #{timeout} seconds" - rescue EOFError - raise "MCP closed before replying to #{method}" - end + request = + lambda do |id, method, params = {}, timeout:| + frame = { jsonrpc: "2.0", id: id, method: method, params: params } + input.puts(JSON.generate(frame)) + reply = JSON.parse(Timeout.timeout(timeout) { output.readline }) + unless reply.fetch("id") == id + raise "Expected reply #{id} for #{method}" + end - initialization = request.call(1, "initialize", { - protocolVersion: "2025-11-25", capabilities: {}, - clientInfo: {name: "recipe", version: "1"} - }, timeout: 10) - puts "initialized: #{initialization.fetch('protocolVersion')}" - input.puts(JSON.generate( - {jsonrpc: "2.0", method: "notifications/initialized"} - )) + reply.fetch("result") + rescue Timeout::Error + raise "Timed out waiting for #{method} after #{timeout} seconds" + rescue EOFError + raise "MCP closed before replying to #{method}" + end + + initialization = + request.call( + 1, + "initialize", + { + protocolVersion: "2025-11-25", + capabilities: { + }, + clientInfo: { + name: "recipe", + version: "1" + } + }, + timeout: 10 + ) + puts "initialized: #{initialization.fetch("protocolVersion")}" + input.puts( + JSON.generate({ jsonrpc: "2.0", method: "notifications/initialized" }) + ) tools = request.call(2, "tools/list", timeout: 5).fetch("tools") - puts "tools: #{tools.map { |tool| tool.fetch('name') }.sort.join(', ')}" + puts "tools: #{tools.map { |tool| tool.fetch("name") }.sort.join(", ")}" input.close raise "MCP did not exit after EOF" unless child.join(2) raise "MCP exited #{child.value.exitstatus}" unless child.value.success? @@ -510,7 +573,7 @@ Dir.mktmpdir("workspace-") do |directory| result = plan.apply(server: server) puts "applied: #{result.success?}" sessions = server.list_sessions.map { |session| session.snapshot.name } - puts "sessions: #{sessions.join(', ')}" + puts "sessions: #{sessions.join(", ")}" end end ``` @@ -527,19 +590,25 @@ require "libtmux/workspace" LibTmux::Server.start do |server| server.new_session(name: "borrowed", command: ["/bin/cat"]) - document = {session_name: "crowded", - windows: [{window_name: "small", panes: Array.new(40) { {} }}]} - crowded = LibTmux::Workspace.parse(JSON.generate(document), - format: :json, base_directory: __dir__) + document = { + session_name: "crowded", + windows: [{ window_name: "small", panes: Array.new(40) { {} } }] + } + crowded = + LibTmux::Workspace.parse( + JSON.generate(document), + format: :json, + base_directory: __dir__ + ) begin crowded.plan.apply(server: server, compensate: true) rescue LibTmux::Workspace::ApplyError => error puts "failed action: #{error.result.failed_action}" - puts "created a session: #{error.result.created_refs.key?('session')}" + puts "created a session: #{error.result.created_refs.key?("session")}" puts "compensation: #{error.result.compensation}" end sessions = server.list_sessions.map { |session| session.snapshot.name } - puts "sessions: #{sessions.join(', ')}" + puts "sessions: #{sessions.join(", ")}" end ``` diff --git a/docs/reference/api.md b/docs/reference/api.md index 0d879c0f..11c2f5de 100644 --- a/docs/reference/api.md +++ b/docs/reference/api.md @@ -27,108 +27,108 @@ type checking. See [signature proof](behavior.md#signature-proof). | Method | Declared return | Contract | | --- | --- | --- | -| [.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) | +| [.open](../../gems/libtmux-async/lib/libtmux/async.rb#L44) | `T` | [Async scope](behavior.md#async-scope) | +| [.run_program](../../gems/libtmux-async/lib/libtmux/async.rb#L40) | `::LibTmux::Program::Result` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [.start_program](../../gems/libtmux-async/lib/libtmux/async.rb#L35) | `::LibTmux::Program` / `T` | [Owned terminal programs](behavior.md#owned-terminal-programs) | ## LibTmux::Async::ControlConnection | Method | Declared return | Contract | | --- | --- | --- | -| [#cleanup_errors](../../gems/libtmux/lib/libtmux/control.rb#L336) | `::Array[::String]` | [Control connections](behavior.md#control-connections) | -| [#close](../../gems/libtmux-async/lib/libtmux/async/control.rb#L160) | `nil` | [Control connections](behavior.md#control-connections) | -| [#closed?](../../gems/libtmux-async/lib/libtmux/async/control.rb#L191) | `bool` | [Control connections](behavior.md#control-connections) | -| [#diagnostics](../../gems/libtmux/lib/libtmux/control.rb#L566) | `{ admitted_requests: ::Integer, incomplete_requests: ::Integer, queued_requests: ::Integer, writing_requests: ::Integer, awaiting_reply: ::Integer, reserved_wire_bytes: ::Integer, retained_reply_bytes: ::Integer, stderr_received_bytes: ::Integer, subscription_count: ::Integer, stopping: bool, finished: bool, cleanup_error_count: ::Integer, limits: { max_requests: ::Integer, max_command_bytes: ::Integer, max_queue_bytes: ::Integer, max_line_bytes: ::Integer, max_reply_bytes: ::Integer, max_stderr_bytes: ::Integer, max_subscriptions: ::Integer } }` | [Diagnostics](behavior.md#diagnostics) | -| [#events](../../gems/libtmux/lib/libtmux/control.rb#L336) | `::LibTmux::Async::ControlSubscription` | [Control connections](behavior.md#control-connections) | -| [#exchange](../../gems/libtmux/lib/libtmux/control.rb#L435) | `::LibTmux::GuardedReply` | [Control connections](behavior.md#control-connections) | -| [#generation](../../gems/libtmux/lib/libtmux/control.rb#L336) | `::String` | [Control connections](behavior.md#control-connections) | -| [#inspect](../../gems/libtmux/lib/libtmux/control.rb#L579) | `::String` | [Control connections](behavior.md#control-connections) | -| [#pause_output](../../gems/libtmux/lib/libtmux/control.rb#L502) | `::LibTmux::GuardedReply` | [Control flow](behavior.md#control-flow) | -| [#pid](../../gems/libtmux/lib/libtmux/control.rb#L336) | `::Integer` | [Control connections](behavior.md#control-connections) | -| [#previous_generation](../../gems/libtmux/lib/libtmux/control.rb#L336) | `::String?` | [Control connections](behavior.md#control-connections) | -| [#resume_output](../../gems/libtmux/lib/libtmux/control.rb#L506) | `::LibTmux::GuardedReply` | [Control flow](behavior.md#control-flow) | -| [#subscribe](../../gems/libtmux/lib/libtmux/control.rb#L510) | `::LibTmux::Async::ControlSubscription` | [Control connections](behavior.md#control-connections) | +| [#cleanup_errors](../../gems/libtmux/lib/libtmux/control.rb#L429) | `::Array[::String]` | [Control connections](behavior.md#control-connections) | +| [#close](../../gems/libtmux-async/lib/libtmux/async/control.rb#L178) | `nil` | [Control connections](behavior.md#control-connections) | +| [#closed?](../../gems/libtmux-async/lib/libtmux/async/control.rb#L214) | `bool` | [Control connections](behavior.md#control-connections) | +| [#diagnostics](../../gems/libtmux/lib/libtmux/control.rb#L726) | `{ admitted_requests: ::Integer, incomplete_requests: ::Integer, queued_requests: ::Integer, writing_requests: ::Integer, awaiting_reply: ::Integer, reserved_wire_bytes: ::Integer, retained_reply_bytes: ::Integer, stderr_received_bytes: ::Integer, subscription_count: ::Integer, stopping: bool, finished: bool, cleanup_error_count: ::Integer, limits: { max_requests: ::Integer, max_command_bytes: ::Integer, max_queue_bytes: ::Integer, max_line_bytes: ::Integer, max_reply_bytes: ::Integer, max_stderr_bytes: ::Integer, max_subscriptions: ::Integer } }` | [Diagnostics](behavior.md#diagnostics) | +| [#events](../../gems/libtmux/lib/libtmux/control.rb#L429) | `::LibTmux::Async::ControlSubscription` | [Control connections](behavior.md#control-connections) | +| [#exchange](../../gems/libtmux/lib/libtmux/control.rb#L565) | `::LibTmux::GuardedReply` | [Control connections](behavior.md#control-connections) | +| [#generation](../../gems/libtmux/lib/libtmux/control.rb#L429) | `::String` | [Control connections](behavior.md#control-connections) | +| [#inspect](../../gems/libtmux/lib/libtmux/control.rb#L747) | `::String` | [Control connections](behavior.md#control-connections) | +| [#pause_output](../../gems/libtmux/lib/libtmux/control.rb#L641) | `::LibTmux::GuardedReply` | [Control flow](behavior.md#control-flow) | +| [#pid](../../gems/libtmux/lib/libtmux/control.rb#L429) | `::Integer` | [Control connections](behavior.md#control-connections) | +| [#previous_generation](../../gems/libtmux/lib/libtmux/control.rb#L429) | `::String?` | [Control connections](behavior.md#control-connections) | +| [#resume_output](../../gems/libtmux/lib/libtmux/control.rb#L645) | `::LibTmux::GuardedReply` | [Control flow](behavior.md#control-flow) | +| [#subscribe](../../gems/libtmux/lib/libtmux/control.rb#L649) | `::LibTmux::Async::ControlSubscription` | [Control connections](behavior.md#control-connections) | ## LibTmux::Async::ControlSubscription | Method | Declared return | Contract | | --- | --- | --- | -| [#close](../../gems/libtmux/lib/libtmux/control.rb#L145) | `nil` | [Control subscriptions](behavior.md#control-subscriptions) | -| [#closed?](../../gems/libtmux/lib/libtmux/control.rb#L156) | `bool` | [Control subscriptions](behavior.md#control-subscriptions) | -| [#diagnostics](../../gems/libtmux/lib/libtmux/control.rb#L163) | `{ queued_events: ::Integer, retained_event_bytes: ::Integer, gap_pending: bool, overflowed: bool, closed: bool, mode: :reliable \| :tail, limits: { max_bytes: ::Integer, max_events: ::Integer } }` | [Diagnostics](behavior.md#diagnostics) | -| [#each](../../gems/libtmux/lib/libtmux/control.rb#L131) | `self` / `::Enumerator[::LibTmux::ControlEvent, self]` | [Control subscriptions](behavior.md#control-subscriptions) | -| [#generation](../../gems/libtmux/lib/libtmux/control.rb#L88) | `::String?` | [Control subscriptions](behavior.md#control-subscriptions) | -| [#inspect](../../gems/libtmux/lib/libtmux/control.rb#L173) | `::String` | [Control subscriptions](behavior.md#control-subscriptions) | +| [#close](../../gems/libtmux/lib/libtmux/control.rb#L178) | `nil` | [Control subscriptions](behavior.md#control-subscriptions) | +| [#closed?](../../gems/libtmux/lib/libtmux/control.rb#L189) | `bool` | [Control subscriptions](behavior.md#control-subscriptions) | +| [#diagnostics](../../gems/libtmux/lib/libtmux/control.rb#L196) | `{ queued_events: ::Integer, retained_event_bytes: ::Integer, gap_pending: bool, overflowed: bool, closed: bool, mode: :reliable \| :tail, limits: { max_bytes: ::Integer, max_events: ::Integer } }` | [Diagnostics](behavior.md#diagnostics) | +| [#each](../../gems/libtmux/lib/libtmux/control.rb#L163) | `self` / `::Enumerator[::LibTmux::ControlEvent, self]` | [Control subscriptions](behavior.md#control-subscriptions) | +| [#generation](../../gems/libtmux/lib/libtmux/control.rb#L110) | `::String?` | [Control subscriptions](behavior.md#control-subscriptions) | +| [#inspect](../../gems/libtmux/lib/libtmux/control.rb#L211) | `::String` | [Control subscriptions](behavior.md#control-subscriptions) | | [#next](../../gems/libtmux-async/lib/libtmux/async/control.rb#L24) | `::LibTmux::ControlEvent` | [Control subscriptions](behavior.md#control-subscriptions) | ## LibTmux::Async::Scope | Method | Declared return | Contract | | --- | --- | --- | -| [#close](../../gems/libtmux-async/lib/libtmux/async/scope.rb#L36) | `nil` | [Async scope](behavior.md#async-scope) | -| [#closed?](../../gems/libtmux-async/lib/libtmux/async/scope.rb#L81) | `bool` | [Async scope](behavior.md#async-scope) | -| [#diagnostics](../../gems/libtmux-async/lib/libtmux/async/scope.rb#L89) | `::LibTmux::Async::scope_diagnostics` | [Diagnostics](behavior.md#diagnostics) | -| [#map](../../gems/libtmux-async/lib/libtmux/async/scope.rb#L104) | `::Array[Output]` | [Async map](behavior.md#async-map) | -| [#server](../../gems/libtmux-async/lib/libtmux/async/scope.rb#L11) | `::LibTmux::Async::Server` | [Async scope](behavior.md#async-scope) | -| [.new](../../gems/libtmux-async/lib/libtmux/async/scope.rb#L13) | `::LibTmux::Async::Scope` | [Async scope](behavior.md#async-scope) | +| [#close](../../gems/libtmux-async/lib/libtmux/async/scope.rb#L83) | `nil` | [Async scope](behavior.md#async-scope) | +| [#closed?](../../gems/libtmux-async/lib/libtmux/async/scope.rb#L137) | `bool` | [Async scope](behavior.md#async-scope) | +| [#diagnostics](../../gems/libtmux-async/lib/libtmux/async/scope.rb#L145) | `::LibTmux::Async::scope_diagnostics` | [Diagnostics](behavior.md#diagnostics) | +| [#map](../../gems/libtmux-async/lib/libtmux/async/scope.rb#L175) | `::Array[Output]` | [Async map](behavior.md#async-map) | +| [#server](../../gems/libtmux-async/lib/libtmux/async/scope.rb#L21) | `::LibTmux::Async::Server` | [Async scope](behavior.md#async-scope) | +| [.new](../../gems/libtmux-async/lib/libtmux/async/scope.rb#L23) | `::LibTmux::Async::Scope` | [Async scope](behavior.md#async-scope) | ## LibTmux::Async::Server | 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#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) | +| [#attach](../../gems/libtmux-async/lib/libtmux/async/server.rb#L57) | `bot` | [Async unsupported operations](behavior.md#async-unsupported-operations) | +| [#capabilities](../../gems/libtmux/lib/libtmux/server.rb#L256) | `::LibTmux::Capabilities` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#close](../../gems/libtmux-async/lib/libtmux/async/server.rb#L23) | `nil` | [Async scope](behavior.md#async-scope) | +| [#delete_buffer](../../gems/libtmux/lib/libtmux/operations.rb#L89) | `::LibTmux::CommandResult` | [Buffers](behavior.md#buffers) | +| [#diagnostics](../../gems/libtmux-async/lib/libtmux/async/server.rb#L28) | `::LibTmux::Async::scope_diagnostics` | [Diagnostics](behavior.md#diagnostics) | +| [#display](../../gems/libtmux/lib/libtmux/operations.rb#L20) | `::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#L409) | `::Hash[::Symbol, untyped]` | [Source query plans](behavior.md#source-query-plans) | +| [#environment](../../gems/libtmux/lib/libtmux/operations.rb#L118) | `::String?` | [Environment](behavior.md#environment) | +| [#explain_panes](../../gems/libtmux/lib/libtmux/server.rb#L463) | `::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#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#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#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) | +| [#kill](../../gems/libtmux/lib/libtmux/server.rb#L332) | `::LibTmux::CommandResult` | [Killing daemons](behavior.md#killing-daemons) | +| [#list_buffers](../../gems/libtmux/lib/libtmux/operations.rb#L93) | `::Array[{ name: ::String, size: ::Integer }]` | [Buffers](behavior.md#buffers) | +| [#list_clients](../../gems/libtmux/lib/libtmux/operations.rb#L130) | `::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#L384) | `::Array[::LibTmux::Pane]` | [Live acquisition](behavior.md#live-acquisition) | +| [#list_sessions](../../gems/libtmux/lib/libtmux/server.rb#L376) | `::Array[::LibTmux::Session]` | [Live acquisition](behavior.md#live-acquisition) | +| [#list_window_links](../../gems/libtmux/lib/libtmux/operations.rb#L106) | `::Array[::LibTmux::WindowLink]` | [Live acquisition](behavior.md#live-acquisition) | +| [#list_windows](../../gems/libtmux/lib/libtmux/server.rb#L380) | `::Array[::LibTmux::Window]` | [Live acquisition](behavior.md#live-acquisition) | +| [#new_session](../../gems/libtmux/lib/libtmux/server.rb#L343) | `::LibTmux::CreationReceipt` / `::LibTmux::Session` | [Creation](behavior.md#creation) | +| [#open_control](../../gems/libtmux-async/lib/libtmux/async/server.rb#L32) | `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#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) | +| [#pane](../../gems/libtmux/lib/libtmux/server.rb#L396) | `::LibTmux::Pane` | [Live handles](behavior.md#live-handles) | +| [#program_support](../../gems/libtmux/lib/libtmux/program.rb#L570) | `{ 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#L85) | `::LibTmux::CommandResult` | [Buffers](behavior.md#buffers) | +| [#run](../../gems/libtmux-async/lib/libtmux/async/server.rb#L19) | `::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#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#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) | -| [#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#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#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) | -| [.start](../../gems/libtmux-async/lib/libtmux/async/server.rb#L57) | `bot` | [Async unsupported operations](behavior.md#async-unsupported-operations) | +| [#search_panes](../../gems/libtmux/lib/libtmux/server.rb#L459) | `::LibTmux::Selection[::LibTmux::PaneSnapshot]` | [Source query execution](behavior.md#source-query-execution) | +| [#session](../../gems/libtmux/lib/libtmux/server.rb#L388) | `::LibTmux::Session` | [Live handles](behavior.md#live-handles) | +| [#set_environment](../../gems/libtmux/lib/libtmux/operations.rb#L114) | `::LibTmux::CommandResult` | [Environment](behavior.md#environment) | +| [#snapshot](../../gems/libtmux/lib/libtmux/server.rb#L453) | `::LibTmux::Snapshot` | [Snapshot acquisition](behavior.md#snapshot-acquisition) | +| [#source_file](../../gems/libtmux/lib/libtmux/operations.rb#L56) | `::LibTmux::CommandResult` | [Source files](behavior.md#source-files) | +| [#start_program](../../gems/libtmux/lib/libtmux/program.rb#L580) | `::LibTmux::Program` / `T` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#supports_control?](../../gems/libtmux/lib/libtmux/server.rb#L248) | `bool` | [Borrowed bindings](behavior.md#borrowed-bindings) | +| [#switch_client](../../gems/libtmux/lib/libtmux/terminal.rb#L40) | `::LibTmux::CommandResult` | [Client switching](behavior.md#client-switching) | +| [#tmux_version](../../gems/libtmux/lib/libtmux/server.rb#L243) | `::String` | [Borrowed bindings](behavior.md#borrowed-bindings) | +| [#unset_environment](../../gems/libtmux/lib/libtmux/operations.rb#L122) | `::LibTmux::CommandResult` | [Environment](behavior.md#environment) | +| [#wait_for](../../gems/libtmux/lib/libtmux/operations.rb#L61) | `::LibTmux::CommandResult` | [Wait channels](behavior.md#wait-channels) | +| [#window](../../gems/libtmux/lib/libtmux/server.rb#L392) | `::LibTmux::Window` | [Live handles](behavior.md#live-handles) | +| [#window_link](../../gems/libtmux/lib/libtmux/operations.rb#L110) | `::LibTmux::WindowLink` | [Live handles](behavior.md#live-handles) | +| [#write_buffer](../../gems/libtmux/lib/libtmux/operations.rb#L72) | `::LibTmux::CommandResult` | [Buffers](behavior.md#buffers) | +| [.open](../../gems/libtmux-async/lib/libtmux/async/server.rb#L71) | `bot` | [Async unsupported operations](behavior.md#async-unsupported-operations) | +| [.start](../../gems/libtmux-async/lib/libtmux/async/server.rb#L64) | `bot` | [Async unsupported operations](behavior.md#async-unsupported-operations) | | [.valid_terminal_type?](../../gems/libtmux/lib/libtmux/terminal.rb#L34) | `bool` | [Terminal attachment](behavior.md#terminal-attachment) | ## LibTmux::Cancellation | Method | Declared return | Contract | | --- | --- | --- | -| [#cancel](../../gems/libtmux/lib/libtmux/process.rb#L53) | `void` | [Cancellation tokens](behavior.md#cancellation-tokens) | -| [#cancelled?](../../gems/libtmux/lib/libtmux/process.rb#L63) | `bool` | [Cancellation tokens](behavior.md#cancellation-tokens) | -| [#close](../../gems/libtmux/lib/libtmux/process.rb#L68) | `void` | [Cancellation tokens](behavior.md#cancellation-tokens) | -| [#reader](../../gems/libtmux/lib/libtmux/process.rb#L44) | `::IO` | [Cancellation tokens](behavior.md#cancellation-tokens) | -| [.new](../../gems/libtmux/lib/libtmux/process.rb#L46) | `::LibTmux::Cancellation` | [Cancellation tokens](behavior.md#cancellation-tokens) | +| [#cancel](../../gems/libtmux/lib/libtmux/process.rb#L58) | `void` | [Cancellation tokens](behavior.md#cancellation-tokens) | +| [#cancelled?](../../gems/libtmux/lib/libtmux/process.rb#L68) | `bool` | [Cancellation tokens](behavior.md#cancellation-tokens) | +| [#close](../../gems/libtmux/lib/libtmux/process.rb#L73) | `void` | [Cancellation tokens](behavior.md#cancellation-tokens) | +| [#reader](../../gems/libtmux/lib/libtmux/process.rb#L49) | `::IO` | [Cancellation tokens](behavior.md#cancellation-tokens) | +| [.new](../../gems/libtmux/lib/libtmux/process.rb#L51) | `::LibTmux::Cancellation` | [Cancellation tokens](behavior.md#cancellation-tokens) | ## LibTmux::Cancelled @@ -148,16 +148,16 @@ type checking. See [signature proof](behavior.md#signature-proof). | Method | Declared return | Contract | | --- | --- | --- | -| [#binding_key](../../gems/libtmux/lib/libtmux/capabilities.rb#L42) | `::String` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [#feature](../../gems/libtmux/lib/libtmux/capabilities.rb#L61) | `::LibTmux::Capabilities::Feature` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [#features](../../gems/libtmux/lib/libtmux/capabilities.rb#L42) | `::Array[::LibTmux::Capabilities::Feature]` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [#pid](../../gems/libtmux/lib/libtmux/capabilities.rb#L42) | `::Integer` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [#start_time](../../gems/libtmux/lib/libtmux/capabilities.rb#L42) | `::Integer` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [#supports?](../../gems/libtmux/lib/libtmux/capabilities.rb#L65) | `bool` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [#to_h](../../gems/libtmux/lib/libtmux/capabilities.rb#L73) | `::Hash[::String, untyped]` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [#version](../../gems/libtmux/lib/libtmux/capabilities.rb#L42) | `::String` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [#workaround](../../gems/libtmux/lib/libtmux/capabilities.rb#L68) | `::LibTmux::Capabilities::Workaround` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [#workarounds](../../gems/libtmux/lib/libtmux/capabilities.rb#L42) | `::Array[::LibTmux::Capabilities::Workaround]` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#binding_key](../../gems/libtmux/lib/libtmux/capabilities.rb#L58) | `::String` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#feature](../../gems/libtmux/lib/libtmux/capabilities.rb#L94) | `::LibTmux::Capabilities::Feature` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#features](../../gems/libtmux/lib/libtmux/capabilities.rb#L58) | `::Array[::LibTmux::Capabilities::Feature]` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#pid](../../gems/libtmux/lib/libtmux/capabilities.rb#L58) | `::Integer` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#start_time](../../gems/libtmux/lib/libtmux/capabilities.rb#L58) | `::Integer` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#supports?](../../gems/libtmux/lib/libtmux/capabilities.rb#L98) | `bool` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#to_h](../../gems/libtmux/lib/libtmux/capabilities.rb#L106) | `::Hash[::String, untyped]` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#version](../../gems/libtmux/lib/libtmux/capabilities.rb#L58) | `::String` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#workaround](../../gems/libtmux/lib/libtmux/capabilities.rb#L101) | `::LibTmux::Capabilities::Workaround` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#workarounds](../../gems/libtmux/lib/libtmux/capabilities.rb#L58) | `::Array[::LibTmux::Capabilities::Workaround]` | [Daemon capabilities](behavior.md#daemon-capabilities) | ## LibTmux::Capabilities::Command @@ -165,7 +165,7 @@ type checking. See [signature proof](behavior.md#signature-proof). | --- | --- | --- | | [#command](../../gems/libtmux/lib/libtmux/capabilities.rb#L11) | `::String` | [Daemon capabilities](behavior.md#daemon-capabilities) | | [#flags](../../gems/libtmux/lib/libtmux/capabilities.rb#L11) | `::Array[::String]` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [#to_h](../../gems/libtmux/lib/libtmux/capabilities.rb#L12) | `::Hash[::String, untyped]` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#to_h](../../gems/libtmux/lib/libtmux/capabilities.rb#L13) | `::Hash[::String, untyped]` | [Daemon capabilities](behavior.md#daemon-capabilities) | | [.inspect](../../gems/libtmux/lib/libtmux/capabilities.rb#L11) | `::String` | [Daemon capabilities](behavior.md#daemon-capabilities) | | [.members](../../gems/libtmux/lib/libtmux/capabilities.rb#L11) | `::Array[::Symbol]` | [Daemon capabilities](behavior.md#daemon-capabilities) | @@ -173,37 +173,37 @@ type checking. See [signature proof](behavior.md#signature-proof). | Method | Declared return | Contract | | --- | --- | --- | -| [#apis](../../gems/libtmux/lib/libtmux/capabilities.rb#L17) | `::Array[::String]` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [#commands](../../gems/libtmux/lib/libtmux/capabilities.rb#L17) | `::Array[::LibTmux::Capabilities::Command]` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [#error](../../gems/libtmux/lib/libtmux/capabilities.rb#L17) | `::String?` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [#except](../../gems/libtmux/lib/libtmux/capabilities.rb#L17) | `::Array[::String]` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [#handling](../../gems/libtmux/lib/libtmux/capabilities.rb#L17) | `:refuse \| :fallback \| :repair` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [#id](../../gems/libtmux/lib/libtmux/capabilities.rb#L17) | `::String` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [#name](../../gems/libtmux/lib/libtmux/capabilities.rb#L17) | `::String` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [#since](../../gems/libtmux/lib/libtmux/capabilities.rb#L17) | `::String` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [#summary](../../gems/libtmux/lib/libtmux/capabilities.rb#L17) | `::String` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [#supported](../../gems/libtmux/lib/libtmux/capabilities.rb#L17) | `bool` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [#supported?](../../gems/libtmux/lib/libtmux/capabilities.rb#L19) | `bool` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [#to_h](../../gems/libtmux/lib/libtmux/capabilities.rb#L21) | `::Hash[::String, untyped]` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [.inspect](../../gems/libtmux/lib/libtmux/capabilities.rb#L17) | `::String` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [.members](../../gems/libtmux/lib/libtmux/capabilities.rb#L17) | `::Array[::Symbol]` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#apis](../../gems/libtmux/lib/libtmux/capabilities.rb#L18) | `::Array[::String]` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#commands](../../gems/libtmux/lib/libtmux/capabilities.rb#L18) | `::Array[::LibTmux::Capabilities::Command]` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#error](../../gems/libtmux/lib/libtmux/capabilities.rb#L18) | `::String?` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#except](../../gems/libtmux/lib/libtmux/capabilities.rb#L18) | `::Array[::String]` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#handling](../../gems/libtmux/lib/libtmux/capabilities.rb#L18) | `:refuse \| :fallback \| :repair` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#id](../../gems/libtmux/lib/libtmux/capabilities.rb#L18) | `::String` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#name](../../gems/libtmux/lib/libtmux/capabilities.rb#L18) | `::String` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#since](../../gems/libtmux/lib/libtmux/capabilities.rb#L18) | `::String` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#summary](../../gems/libtmux/lib/libtmux/capabilities.rb#L18) | `::String` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#supported](../../gems/libtmux/lib/libtmux/capabilities.rb#L18) | `bool` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#supported?](../../gems/libtmux/lib/libtmux/capabilities.rb#L31) | `bool` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#to_h](../../gems/libtmux/lib/libtmux/capabilities.rb#L33) | `::Hash[::String, untyped]` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [.inspect](../../gems/libtmux/lib/libtmux/capabilities.rb#L18) | `::String` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [.members](../../gems/libtmux/lib/libtmux/capabilities.rb#L18) | `::Array[::Symbol]` | [Daemon capabilities](behavior.md#daemon-capabilities) | ## LibTmux::Capabilities::Workaround | Method | Declared return | Contract | | --- | --- | --- | -| [#active](../../gems/libtmux/lib/libtmux/capabilities.rb#L30) | `bool` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [#active?](../../gems/libtmux/lib/libtmux/capabilities.rb#L32) | `bool` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [#apis](../../gems/libtmux/lib/libtmux/capabilities.rb#L30) | `::Array[::String]` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [#commands](../../gems/libtmux/lib/libtmux/capabilities.rb#L30) | `::Array[::LibTmux::Capabilities::Command]` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [#handling](../../gems/libtmux/lib/libtmux/capabilities.rb#L30) | `:refuse \| :repair` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [#id](../../gems/libtmux/lib/libtmux/capabilities.rb#L30) | `::String` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [#name](../../gems/libtmux/lib/libtmux/capabilities.rb#L30) | `::String` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [#releases](../../gems/libtmux/lib/libtmux/capabilities.rb#L30) | `::Array[::String]` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [#summary](../../gems/libtmux/lib/libtmux/capabilities.rb#L30) | `::String` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [#to_h](../../gems/libtmux/lib/libtmux/capabilities.rb#L34) | `::Hash[::String, untyped]` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [.inspect](../../gems/libtmux/lib/libtmux/capabilities.rb#L30) | `::String` | [Daemon capabilities](behavior.md#daemon-capabilities) | -| [.members](../../gems/libtmux/lib/libtmux/capabilities.rb#L30) | `::Array[::Symbol]` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#active](../../gems/libtmux/lib/libtmux/capabilities.rb#L44) | `bool` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#active?](../../gems/libtmux/lib/libtmux/capabilities.rb#L46) | `bool` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#apis](../../gems/libtmux/lib/libtmux/capabilities.rb#L44) | `::Array[::String]` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#commands](../../gems/libtmux/lib/libtmux/capabilities.rb#L44) | `::Array[::LibTmux::Capabilities::Command]` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#handling](../../gems/libtmux/lib/libtmux/capabilities.rb#L44) | `:refuse \| :repair` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#id](../../gems/libtmux/lib/libtmux/capabilities.rb#L44) | `::String` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#name](../../gems/libtmux/lib/libtmux/capabilities.rb#L44) | `::String` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#releases](../../gems/libtmux/lib/libtmux/capabilities.rb#L44) | `::Array[::String]` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#summary](../../gems/libtmux/lib/libtmux/capabilities.rb#L44) | `::String` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#to_h](../../gems/libtmux/lib/libtmux/capabilities.rb#L48) | `::Hash[::String, untyped]` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [.inspect](../../gems/libtmux/lib/libtmux/capabilities.rb#L44) | `::String` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [.members](../../gems/libtmux/lib/libtmux/capabilities.rb#L44) | `::Array[::Symbol]` | [Daemon capabilities](behavior.md#daemon-capabilities) | ## LibTmux::CapacityError @@ -223,45 +223,45 @@ type checking. See [signature proof](behavior.md#signature-proof). | Method | Declared return | Contract | | --- | --- | --- | -| [#==](../../gems/libtmux/lib/libtmux/snapshot.rb#L40) | `bool` | [Captured records](behavior.md#captured-records) | +| [#==](../../gems/libtmux/lib/libtmux/snapshot.rb#L44) | `bool` | [Captured records](behavior.md#captured-records) | | [#capture_id](../../gems/libtmux/lib/libtmux/snapshot.rb#L10) | `::String` | [Captured records](behavior.md#captured-records) | -| [#eql?](../../gems/libtmux/lib/libtmux/snapshot.rb#L40) | `bool` | [Captured records](behavior.md#captured-records) | -| [#hash](../../gems/libtmux/lib/libtmux/snapshot.rb#L46) | `::Integer` | [Captured records](behavior.md#captured-records) | -| [#inspect](../../gems/libtmux/lib/libtmux/snapshot.rb#L50) | `::String` | [Captured records](behavior.md#captured-records) | -| [#raw](../../gems/libtmux/lib/libtmux/snapshot.rb#L34) | `::String?` | [Captured records](behavior.md#captured-records) | -| [#ref](../../gems/libtmux/lib/libtmux/snapshot.rb#L26) | `::LibTmux::EntityRef` | [Captured records](behavior.md#captured-records) | +| [#eql?](../../gems/libtmux/lib/libtmux/snapshot.rb#L44) | `bool` | [Captured records](behavior.md#captured-records) | +| [#hash](../../gems/libtmux/lib/libtmux/snapshot.rb#L50) | `::Integer` | [Captured records](behavior.md#captured-records) | +| [#inspect](../../gems/libtmux/lib/libtmux/snapshot.rb#L54) | `::String` | [Captured records](behavior.md#captured-records) | +| [#raw](../../gems/libtmux/lib/libtmux/snapshot.rb#L38) | `::String?` | [Captured records](behavior.md#captured-records) | +| [#ref](../../gems/libtmux/lib/libtmux/snapshot.rb#L29) | `::LibTmux::EntityRef` | [Captured records](behavior.md#captured-records) | ## LibTmux::ClientSnapshot | Method | Declared return | Contract | | --- | --- | --- | -| [#==](../../gems/libtmux/lib/libtmux/snapshot.rb#L40) | `bool` | [Captured records](behavior.md#captured-records) | +| [#==](../../gems/libtmux/lib/libtmux/snapshot.rb#L44) | `bool` | [Captured records](behavior.md#captured-records) | | [#capture_id](../../gems/libtmux/lib/libtmux/snapshot.rb#L10) | `::String` | [Captured records](behavior.md#captured-records) | -| [#control_mode](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `bool` | [Captured records](behavior.md#captured-records) | -| [#control_mode?](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `bool` | [Captured records](behavior.md#captured-records) | -| [#created](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `::Integer` | [Captured records](behavior.md#captured-records) | -| [#eql?](../../gems/libtmux/lib/libtmux/snapshot.rb#L40) | `bool` | [Captured records](behavior.md#captured-records) | -| [#hash](../../gems/libtmux/lib/libtmux/snapshot.rb#L46) | `::Integer` | [Captured records](behavior.md#captured-records) | -| [#height](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `::Integer?` | [Captured records](behavior.md#captured-records) | -| [#inspect](../../gems/libtmux/lib/libtmux/snapshot.rb#L50) | `::String` | [Captured records](behavior.md#captured-records) | -| [#name](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `::String` | [Captured records](behavior.md#captured-records) | -| [#pid](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `::Integer` | [Captured records](behavior.md#captured-records) | -| [#raw](../../gems/libtmux/lib/libtmux/snapshot.rb#L34) | `::String?` | [Captured records](behavior.md#captured-records) | -| [#read_only](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `bool` | [Captured records](behavior.md#captured-records) | -| [#read_only?](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `bool` | [Captured records](behavior.md#captured-records) | -| [#ref](../../gems/libtmux/lib/libtmux/snapshot.rb#L26) | `::LibTmux::EntityRef` | [Captured records](behavior.md#captured-records) | -| [#session](../../gems/libtmux/lib/libtmux/snapshot.rb#L152) | `::LibTmux::SessionSnapshot?` | [Captured records](behavior.md#captured-records) | -| [#session_id](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `::String?` | [Captured records](behavior.md#captured-records) | -| [#tty](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `::String?` | [Captured records](behavior.md#captured-records) | -| [#utf8](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `bool` | [Captured records](behavior.md#captured-records) | -| [#utf8?](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `bool` | [Captured records](behavior.md#captured-records) | -| [#width](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `::Integer` | [Captured records](behavior.md#captured-records) | +| [#control_mode](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `bool` | [Captured records](behavior.md#captured-records) | +| [#control_mode?](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `bool` | [Captured records](behavior.md#captured-records) | +| [#created](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `::Integer` | [Captured records](behavior.md#captured-records) | +| [#eql?](../../gems/libtmux/lib/libtmux/snapshot.rb#L44) | `bool` | [Captured records](behavior.md#captured-records) | +| [#hash](../../gems/libtmux/lib/libtmux/snapshot.rb#L50) | `::Integer` | [Captured records](behavior.md#captured-records) | +| [#height](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `::Integer?` | [Captured records](behavior.md#captured-records) | +| [#inspect](../../gems/libtmux/lib/libtmux/snapshot.rb#L54) | `::String` | [Captured records](behavior.md#captured-records) | +| [#name](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `::String` | [Captured records](behavior.md#captured-records) | +| [#pid](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `::Integer` | [Captured records](behavior.md#captured-records) | +| [#raw](../../gems/libtmux/lib/libtmux/snapshot.rb#L38) | `::String?` | [Captured records](behavior.md#captured-records) | +| [#read_only](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `bool` | [Captured records](behavior.md#captured-records) | +| [#read_only?](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `bool` | [Captured records](behavior.md#captured-records) | +| [#ref](../../gems/libtmux/lib/libtmux/snapshot.rb#L29) | `::LibTmux::EntityRef` | [Captured records](behavior.md#captured-records) | +| [#session](../../gems/libtmux/lib/libtmux/snapshot.rb#L195) | `::LibTmux::SessionSnapshot?` | [Captured records](behavior.md#captured-records) | +| [#session_id](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `::String?` | [Captured records](behavior.md#captured-records) | +| [#tty](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `::String?` | [Captured records](behavior.md#captured-records) | +| [#utf8](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `bool` | [Captured records](behavior.md#captured-records) | +| [#utf8?](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `bool` | [Captured records](behavior.md#captured-records) | +| [#width](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `::Integer` | [Captured records](behavior.md#captured-records) | ## LibTmux::ClientWhere | Method | Declared return | Contract | | --- | --- | --- | -| [.build](../../gems/libtmux/lib/libtmux/criteria.rb#L405) | `::LibTmux::FilterExpr` | [Criteria](behavior.md#criteria) | +| [.build](../../gems/libtmux/lib/libtmux/criteria.rb#L512) | `::LibTmux::FilterExpr` | [Criteria](behavior.md#criteria) | ## LibTmux::ClosedError @@ -288,9 +288,9 @@ type checking. See [signature proof](behavior.md#signature-proof). | [#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) | -| [#result](../../gems/libtmux/lib/libtmux/errors.rb#L66) | `::LibTmux::CommandResult?` | [Errors](behavior.md#errors) | +| [#result](../../gems/libtmux/lib/libtmux/errors.rb#L97) | `::LibTmux::CommandResult?` | [Errors](behavior.md#errors) | | [#text](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::String?` | [Errors](behavior.md#errors) | -| [.new](../../gems/libtmux/lib/libtmux/errors.rb#L68) | `::LibTmux::CommandError` | [Errors](behavior.md#errors) | +| [.new](../../gems/libtmux/lib/libtmux/errors.rb#L99) | `::LibTmux::CommandError` | [Errors](behavior.md#errors) | ## LibTmux::CommandResult @@ -299,7 +299,7 @@ type checking. See [signature proof](behavior.md#signature-proof). | [#argv](../../gems/libtmux/lib/libtmux/process.rb#L8) | `::Array[::String]` | [Command evidence](behavior.md#command-evidence) | | [#delivery](../../gems/libtmux/lib/libtmux/process.rb#L24) | `:observed` | [Command evidence](behavior.md#command-evidence) | | [#elapsed_seconds](../../gems/libtmux/lib/libtmux/process.rb#L8) | `::Float` | [Command evidence](behavior.md#command-evidence) | -| [#inspect](../../gems/libtmux/lib/libtmux/process.rb#L38) | `::String` | [Command evidence](behavior.md#command-evidence) | +| [#inspect](../../gems/libtmux/lib/libtmux/process.rb#L43) | `::String` | [Command evidence](behavior.md#command-evidence) | | [#pid](../../gems/libtmux/lib/libtmux/process.rb#L8) | `::Integer` | [Command evidence](behavior.md#command-evidence) | | [#status](../../gems/libtmux/lib/libtmux/process.rb#L8) | `::Process::Status` | [Command evidence](behavior.md#command-evidence) | | [#stderr](../../gems/libtmux/lib/libtmux/process.rb#L8) | `::String` | [Command evidence](behavior.md#command-evidence) | @@ -312,29 +312,29 @@ type checking. See [signature proof](behavior.md#signature-proof). | Method | Declared return | Contract | | --- | --- | --- | -| [#cleanup_errors](../../gems/libtmux/lib/libtmux/control.rb#L336) | `::Array[::String]` | [Control connections](behavior.md#control-connections) | -| [#close](../../gems/libtmux/lib/libtmux/control.rb#L529) | `nil` | [Control connections](behavior.md#control-connections) | -| [#closed?](../../gems/libtmux/lib/libtmux/control.rb#L558) | `bool` | [Control connections](behavior.md#control-connections) | -| [#diagnostics](../../gems/libtmux/lib/libtmux/control.rb#L566) | `{ admitted_requests: ::Integer, incomplete_requests: ::Integer, queued_requests: ::Integer, writing_requests: ::Integer, awaiting_reply: ::Integer, reserved_wire_bytes: ::Integer, retained_reply_bytes: ::Integer, stderr_received_bytes: ::Integer, subscription_count: ::Integer, stopping: bool, finished: bool, cleanup_error_count: ::Integer, limits: { max_requests: ::Integer, max_command_bytes: ::Integer, max_queue_bytes: ::Integer, max_line_bytes: ::Integer, max_reply_bytes: ::Integer, max_stderr_bytes: ::Integer, max_subscriptions: ::Integer } }` | [Diagnostics](behavior.md#diagnostics) | -| [#events](../../gems/libtmux/lib/libtmux/control.rb#L336) | `::LibTmux::ControlSubscription` | [Control connections](behavior.md#control-connections) | -| [#exchange](../../gems/libtmux/lib/libtmux/control.rb#L435) | `::LibTmux::GuardedReply` | [Control connections](behavior.md#control-connections) | -| [#generation](../../gems/libtmux/lib/libtmux/control.rb#L336) | `::String` | [Control connections](behavior.md#control-connections) | -| [#inspect](../../gems/libtmux/lib/libtmux/control.rb#L579) | `::String` | [Control connections](behavior.md#control-connections) | -| [#pause_output](../../gems/libtmux/lib/libtmux/control.rb#L502) | `::LibTmux::GuardedReply` | [Control flow](behavior.md#control-flow) | -| [#pid](../../gems/libtmux/lib/libtmux/control.rb#L336) | `::Integer` | [Control connections](behavior.md#control-connections) | -| [#previous_generation](../../gems/libtmux/lib/libtmux/control.rb#L336) | `::String?` | [Control connections](behavior.md#control-connections) | -| [#resume_output](../../gems/libtmux/lib/libtmux/control.rb#L506) | `::LibTmux::GuardedReply` | [Control flow](behavior.md#control-flow) | -| [#subscribe](../../gems/libtmux/lib/libtmux/control.rb#L510) | `::LibTmux::ControlSubscription` | [Control connections](behavior.md#control-connections) | +| [#cleanup_errors](../../gems/libtmux/lib/libtmux/control.rb#L429) | `::Array[::String]` | [Control connections](behavior.md#control-connections) | +| [#close](../../gems/libtmux/lib/libtmux/control.rb#L678) | `nil` | [Control connections](behavior.md#control-connections) | +| [#closed?](../../gems/libtmux/lib/libtmux/control.rb#L718) | `bool` | [Control connections](behavior.md#control-connections) | +| [#diagnostics](../../gems/libtmux/lib/libtmux/control.rb#L726) | `{ admitted_requests: ::Integer, incomplete_requests: ::Integer, queued_requests: ::Integer, writing_requests: ::Integer, awaiting_reply: ::Integer, reserved_wire_bytes: ::Integer, retained_reply_bytes: ::Integer, stderr_received_bytes: ::Integer, subscription_count: ::Integer, stopping: bool, finished: bool, cleanup_error_count: ::Integer, limits: { max_requests: ::Integer, max_command_bytes: ::Integer, max_queue_bytes: ::Integer, max_line_bytes: ::Integer, max_reply_bytes: ::Integer, max_stderr_bytes: ::Integer, max_subscriptions: ::Integer } }` | [Diagnostics](behavior.md#diagnostics) | +| [#events](../../gems/libtmux/lib/libtmux/control.rb#L429) | `::LibTmux::ControlSubscription` | [Control connections](behavior.md#control-connections) | +| [#exchange](../../gems/libtmux/lib/libtmux/control.rb#L565) | `::LibTmux::GuardedReply` | [Control connections](behavior.md#control-connections) | +| [#generation](../../gems/libtmux/lib/libtmux/control.rb#L429) | `::String` | [Control connections](behavior.md#control-connections) | +| [#inspect](../../gems/libtmux/lib/libtmux/control.rb#L747) | `::String` | [Control connections](behavior.md#control-connections) | +| [#pause_output](../../gems/libtmux/lib/libtmux/control.rb#L641) | `::LibTmux::GuardedReply` | [Control flow](behavior.md#control-flow) | +| [#pid](../../gems/libtmux/lib/libtmux/control.rb#L429) | `::Integer` | [Control connections](behavior.md#control-connections) | +| [#previous_generation](../../gems/libtmux/lib/libtmux/control.rb#L429) | `::String?` | [Control connections](behavior.md#control-connections) | +| [#resume_output](../../gems/libtmux/lib/libtmux/control.rb#L645) | `::LibTmux::GuardedReply` | [Control flow](behavior.md#control-flow) | +| [#subscribe](../../gems/libtmux/lib/libtmux/control.rb#L649) | `::LibTmux::ControlSubscription` | [Control connections](behavior.md#control-connections) | ## LibTmux::ControlEvent | Method | Declared return | Contract | | --- | --- | --- | -| [#bytesize](../../gems/libtmux/lib/libtmux/control.rb#L68) | `::Integer` | [Control evidence](behavior.md#control-evidence) | +| [#bytesize](../../gems/libtmux/lib/libtmux/control.rb#L86) | `::Integer` | [Control evidence](behavior.md#control-evidence) | | [#data](../../gems/libtmux/lib/libtmux/control.rb#L56) | `::String?` | [Control evidence](behavior.md#control-evidence) | | [#dropped_bytes](../../gems/libtmux/lib/libtmux/control.rb#L56) | `::Integer?` | [Control evidence](behavior.md#control-evidence) | | [#generation](../../gems/libtmux/lib/libtmux/control.rb#L56) | `::String?` | [Control evidence](behavior.md#control-evidence) | -| [#inspect](../../gems/libtmux/lib/libtmux/control.rb#L72) | `::String` | [Control evidence](behavior.md#control-evidence) | +| [#inspect](../../gems/libtmux/lib/libtmux/control.rb#L90) | `::String` | [Control evidence](behavior.md#control-evidence) | | [#kind](../../gems/libtmux/lib/libtmux/control.rb#L56) | `::Symbol` | [Control evidence](behavior.md#control-evidence) | | [#lost_sequences](../../gems/libtmux/lib/libtmux/control.rb#L56) | `::Array[::Integer]?` | [Control evidence](behavior.md#control-evidence) | | [#pane_id](../../gems/libtmux/lib/libtmux/control.rb#L56) | `::String?` | [Control evidence](behavior.md#control-evidence) | @@ -342,20 +342,20 @@ type checking. See [signature proof](behavior.md#signature-proof). | [#raw](../../gems/libtmux/lib/libtmux/control.rb#L56) | `::String` | [Control evidence](behavior.md#control-evidence) | | [#reason](../../gems/libtmux/lib/libtmux/control.rb#L56) | `::Symbol?` | [Control evidence](behavior.md#control-evidence) | | [#sequence](../../gems/libtmux/lib/libtmux/control.rb#L56) | `::Integer?` | [Control evidence](behavior.md#control-evidence) | -| [.new](../../gems/libtmux/lib/libtmux/control.rb#L59) | `::LibTmux::ControlEvent` | [Control evidence](behavior.md#control-evidence) | +| [.new](../../gems/libtmux/lib/libtmux/control.rb#L67) | `::LibTmux::ControlEvent` | [Control evidence](behavior.md#control-evidence) | ## LibTmux::ControlSubscription | Method | Declared return | Contract | | --- | --- | --- | -| [#close](../../gems/libtmux/lib/libtmux/control.rb#L145) | `nil` | [Control subscriptions](behavior.md#control-subscriptions) | -| [#closed?](../../gems/libtmux/lib/libtmux/control.rb#L156) | `bool` | [Control subscriptions](behavior.md#control-subscriptions) | -| [#diagnostics](../../gems/libtmux/lib/libtmux/control.rb#L163) | `{ queued_events: ::Integer, retained_event_bytes: ::Integer, gap_pending: bool, overflowed: bool, closed: bool, mode: :reliable \| :tail, limits: { max_bytes: ::Integer, max_events: ::Integer } }` | [Diagnostics](behavior.md#diagnostics) | -| [#each](../../gems/libtmux/lib/libtmux/control.rb#L131) | `self` / `::Enumerator[::LibTmux::ControlEvent, self]` | [Control subscriptions](behavior.md#control-subscriptions) | -| [#generation](../../gems/libtmux/lib/libtmux/control.rb#L88) | `::String?` | [Control subscriptions](behavior.md#control-subscriptions) | -| [#inspect](../../gems/libtmux/lib/libtmux/control.rb#L173) | `::String` | [Control subscriptions](behavior.md#control-subscriptions) | -| [#next](../../gems/libtmux/lib/libtmux/control.rb#L103) | `::LibTmux::ControlEvent` | [Control subscriptions](behavior.md#control-subscriptions) | -| [.new](../../gems/libtmux/lib/libtmux/control.rb#L90) | `::LibTmux::ControlSubscription` | [Control subscriptions](behavior.md#control-subscriptions) | +| [#close](../../gems/libtmux/lib/libtmux/control.rb#L178) | `nil` | [Control subscriptions](behavior.md#control-subscriptions) | +| [#closed?](../../gems/libtmux/lib/libtmux/control.rb#L189) | `bool` | [Control subscriptions](behavior.md#control-subscriptions) | +| [#diagnostics](../../gems/libtmux/lib/libtmux/control.rb#L196) | `{ queued_events: ::Integer, retained_event_bytes: ::Integer, gap_pending: bool, overflowed: bool, closed: bool, mode: :reliable \| :tail, limits: { max_bytes: ::Integer, max_events: ::Integer } }` | [Diagnostics](behavior.md#diagnostics) | +| [#each](../../gems/libtmux/lib/libtmux/control.rb#L163) | `self` / `::Enumerator[::LibTmux::ControlEvent, self]` | [Control subscriptions](behavior.md#control-subscriptions) | +| [#generation](../../gems/libtmux/lib/libtmux/control.rb#L110) | `::String?` | [Control subscriptions](behavior.md#control-subscriptions) | +| [#inspect](../../gems/libtmux/lib/libtmux/control.rb#L211) | `::String` | [Control subscriptions](behavior.md#control-subscriptions) | +| [#next](../../gems/libtmux/lib/libtmux/control.rb#L133) | `::LibTmux::ControlEvent` | [Control subscriptions](behavior.md#control-subscriptions) | +| [.new](../../gems/libtmux/lib/libtmux/control.rb#L112) | `::LibTmux::ControlSubscription` | [Control subscriptions](behavior.md#control-subscriptions) | ## LibTmux::CreationReceipt @@ -385,43 +385,43 @@ type checking. See [signature proof](behavior.md#signature-proof). | Method | Declared return | Contract | | --- | --- | --- | -| [#==](../../gems/libtmux/lib/libtmux/endpoint.rb#L56) | `bool` | [Endpoints](behavior.md#endpoints) | -| [#eql?](../../gems/libtmux/lib/libtmux/endpoint.rb#L56) | `bool` | [Endpoints](behavior.md#endpoints) | +| [#==](../../gems/libtmux/lib/libtmux/endpoint.rb#L63) | `bool` | [Endpoints](behavior.md#endpoints) | +| [#eql?](../../gems/libtmux/lib/libtmux/endpoint.rb#L63) | `bool` | [Endpoints](behavior.md#endpoints) | | [#executable](../../gems/libtmux/lib/libtmux/endpoint.rb#L18) | `::String` | [Endpoints](behavior.md#endpoints) | -| [#hash](../../gems/libtmux/lib/libtmux/endpoint.rb#L61) | `::Integer` | [Endpoints](behavior.md#endpoints) | -| [#inspect](../../gems/libtmux/lib/libtmux/endpoint.rb#L65) | `::String` | [Endpoints](behavior.md#endpoints) | +| [#hash](../../gems/libtmux/lib/libtmux/endpoint.rb#L68) | `::Integer` | [Endpoints](behavior.md#endpoints) | +| [#inspect](../../gems/libtmux/lib/libtmux/endpoint.rb#L72) | `::String` | [Endpoints](behavior.md#endpoints) | | [#socket_path](../../gems/libtmux/lib/libtmux/endpoint.rb#L18) | `::String` | [Endpoints](behavior.md#endpoints) | -| [.from_env](../../gems/libtmux/lib/libtmux/endpoint.rb#L51) | `::LibTmux::Endpoint` | [Endpoints](behavior.md#endpoints) | +| [.from_env](../../gems/libtmux/lib/libtmux/endpoint.rb#L58) | `::LibTmux::Endpoint` | [Endpoints](behavior.md#endpoints) | | [.new](../../gems/libtmux/lib/libtmux/endpoint.rb#L20) | `::LibTmux::Endpoint` | [Endpoints](behavior.md#endpoints) | ## LibTmux::Entity | Method | Declared return | Contract | | --- | --- | --- | -| [#==](../../gems/libtmux/lib/libtmux/entity.rb#L78) | `bool` | [Live handles](behavior.md#live-handles) | -| [#display](../../gems/libtmux/lib/libtmux/operations.rb#L254) | `::LibTmux::CommandResult` | [Formats](behavior.md#formats) | -| [#eql?](../../gems/libtmux/lib/libtmux/entity.rb#L78) | `bool` | [Live handles](behavior.md#live-handles) | -| [#hash](../../gems/libtmux/lib/libtmux/entity.rb#L83) | `::Integer` | [Live handles](behavior.md#live-handles) | -| [#hooks](../../gems/libtmux/lib/libtmux/operations.rb#L250) | `::LibTmux::Hooks` | [Options and hooks](behavior.md#options-and-hooks) | -| [#id](../../gems/libtmux/lib/libtmux/entity.rb#L70) | `::String` | [Live handles](behavior.md#live-handles) | -| [#inspect](../../gems/libtmux/lib/libtmux/entity.rb#L91) | `::String` | [Live handles](behavior.md#live-handles) | -| [#kill](../../gems/libtmux/lib/libtmux/entity.rb#L87) | `::LibTmux::CommandResult` | [Entity removal](behavior.md#entity-removal) | -| [#options](../../gems/libtmux/lib/libtmux/operations.rb#L246) | `::LibTmux::Options` | [Options and hooks](behavior.md#options-and-hooks) | -| [#ref](../../gems/libtmux/lib/libtmux/entity.rb#L61) | `::LibTmux::EntityRef` | [Live handles](behavior.md#live-handles) | -| [#server](../../gems/libtmux/lib/libtmux/entity.rb#L61) | `::LibTmux::Server` | [Live handles](behavior.md#live-handles) | -| [#snapshot](../../gems/libtmux/lib/libtmux/entity.rb#L74) | `::LibTmux::CapturedRecord` | [Snapshot acquisition](behavior.md#snapshot-acquisition) | +| [#==](../../gems/libtmux/lib/libtmux/entity.rb#L88) | `bool` | [Live handles](behavior.md#live-handles) | +| [#display](../../gems/libtmux/lib/libtmux/operations.rb#L391) | `::LibTmux::CommandResult` | [Formats](behavior.md#formats) | +| [#eql?](../../gems/libtmux/lib/libtmux/entity.rb#L88) | `bool` | [Live handles](behavior.md#live-handles) | +| [#hash](../../gems/libtmux/lib/libtmux/entity.rb#L93) | `::Integer` | [Live handles](behavior.md#live-handles) | +| [#hooks](../../gems/libtmux/lib/libtmux/operations.rb#L387) | `::LibTmux::Hooks` | [Options and hooks](behavior.md#options-and-hooks) | +| [#id](../../gems/libtmux/lib/libtmux/entity.rb#L80) | `::String` | [Live handles](behavior.md#live-handles) | +| [#inspect](../../gems/libtmux/lib/libtmux/entity.rb#L106) | `::String` | [Live handles](behavior.md#live-handles) | +| [#kill](../../gems/libtmux/lib/libtmux/entity.rb#L97) | `::LibTmux::CommandResult` | [Entity removal](behavior.md#entity-removal) | +| [#options](../../gems/libtmux/lib/libtmux/operations.rb#L383) | `::LibTmux::Options` | [Options and hooks](behavior.md#options-and-hooks) | +| [#ref](../../gems/libtmux/lib/libtmux/entity.rb#L71) | `::LibTmux::EntityRef` | [Live handles](behavior.md#live-handles) | +| [#server](../../gems/libtmux/lib/libtmux/entity.rb#L71) | `::LibTmux::Server` | [Live handles](behavior.md#live-handles) | +| [#snapshot](../../gems/libtmux/lib/libtmux/entity.rb#L84) | `::LibTmux::CapturedRecord` | [Snapshot acquisition](behavior.md#snapshot-acquisition) | ## LibTmux::EntityRef | Method | Declared return | Contract | | --- | --- | --- | -| [#==](../../gems/libtmux/lib/libtmux/entity.rb#L45) | `bool` | [Entity references](behavior.md#entity-references) | +| [#==](../../gems/libtmux/lib/libtmux/entity.rb#L54) | `bool` | [Entity references](behavior.md#entity-references) | | [#binding_key](../../gems/libtmux/lib/libtmux/entity.rb#L22) | `::String` | [Entity references](behavior.md#entity-references) | -| [#eql?](../../gems/libtmux/lib/libtmux/entity.rb#L45) | `bool` | [Entity references](behavior.md#entity-references) | -| [#hash](../../gems/libtmux/lib/libtmux/entity.rb#L51) | `::Integer` | [Entity references](behavior.md#entity-references) | +| [#eql?](../../gems/libtmux/lib/libtmux/entity.rb#L54) | `bool` | [Entity references](behavior.md#entity-references) | +| [#hash](../../gems/libtmux/lib/libtmux/entity.rb#L61) | `::Integer` | [Entity references](behavior.md#entity-references) | | [#id](../../gems/libtmux/lib/libtmux/entity.rb#L22) | `::String` | [Entity references](behavior.md#entity-references) | | [#index](../../gems/libtmux/lib/libtmux/entity.rb#L22) | `::Integer?` | [Entity references](behavior.md#entity-references) | -| [#inspect](../../gems/libtmux/lib/libtmux/entity.rb#L55) | `::String` | [Entity references](behavior.md#entity-references) | +| [#inspect](../../gems/libtmux/lib/libtmux/entity.rb#L65) | `::String` | [Entity references](behavior.md#entity-references) | | [#kind](../../gems/libtmux/lib/libtmux/entity.rb#L22) | `:session \| :window \| :pane \| :window_link` | [Entity references](behavior.md#entity-references) | | [#session_id](../../gems/libtmux/lib/libtmux/entity.rb#L22) | `::String?` | [Entity references](behavior.md#entity-references) | @@ -457,18 +457,18 @@ type checking. See [signature proof](behavior.md#signature-proof). | Method | Declared return | Contract | | --- | --- | --- | -| [#===](../../gems/libtmux/lib/libtmux/criteria.rb#L95) | `bool` | [Criteria](behavior.md#criteria) | -| [#and](../../gems/libtmux/lib/libtmux/criteria.rb#L83) | `::LibTmux::FilterExpr` | [Criteria](behavior.md#criteria) | -| [#call](../../gems/libtmux/lib/libtmux/criteria.rb#L95) | `bool` | [Criteria](behavior.md#criteria) | -| [#entity](../../gems/libtmux/lib/libtmux/criteria.rb#L32) | `::Symbol` | [Criteria](behavior.md#criteria) | -| [#inspect](../../gems/libtmux/lib/libtmux/criteria.rb#L119) | `::String` | [Criteria](behavior.md#criteria) | -| [#not](../../gems/libtmux/lib/libtmux/criteria.rb#L91) | `::LibTmux::FilterExpr` | [Criteria](behavior.md#criteria) | -| [#or](../../gems/libtmux/lib/libtmux/criteria.rb#L87) | `::LibTmux::FilterExpr` | [Criteria](behavior.md#criteria) | -| [#to_h](../../gems/libtmux/lib/libtmux/criteria.rb#L105) | `::Hash[::String, untyped]` | [Criteria](behavior.md#criteria) | -| [#to_json](../../gems/libtmux/lib/libtmux/criteria.rb#L111) | `::String` | [Criteria](behavior.md#criteria) | -| [#to_proc](../../gems/libtmux/lib/libtmux/criteria.rb#L101) | `^(untyped) -> bool` | [Criteria](behavior.md#criteria) | -| [.build](../../gems/libtmux/lib/libtmux/criteria.rb#L34) | `::LibTmux::FilterExpr` | [Criteria](behavior.md#criteria) | -| [.from_json](../../gems/libtmux/lib/libtmux/criteria.rb#L54) | `::LibTmux::FilterExpr` | [Criteria](behavior.md#criteria) | +| [#===](../../gems/libtmux/lib/libtmux/criteria.rb#L120) | `bool` | [Criteria](behavior.md#criteria) | +| [#and](../../gems/libtmux/lib/libtmux/criteria.rb#L108) | `::LibTmux::FilterExpr` | [Criteria](behavior.md#criteria) | +| [#call](../../gems/libtmux/lib/libtmux/criteria.rb#L120) | `bool` | [Criteria](behavior.md#criteria) | +| [#entity](../../gems/libtmux/lib/libtmux/criteria.rb#L51) | `::Symbol` | [Criteria](behavior.md#criteria) | +| [#inspect](../../gems/libtmux/lib/libtmux/criteria.rb#L151) | `::String` | [Criteria](behavior.md#criteria) | +| [#not](../../gems/libtmux/lib/libtmux/criteria.rb#L116) | `::LibTmux::FilterExpr` | [Criteria](behavior.md#criteria) | +| [#or](../../gems/libtmux/lib/libtmux/criteria.rb#L112) | `::LibTmux::FilterExpr` | [Criteria](behavior.md#criteria) | +| [#to_h](../../gems/libtmux/lib/libtmux/criteria.rb#L130) | `::Hash[::String, untyped]` | [Criteria](behavior.md#criteria) | +| [#to_json](../../gems/libtmux/lib/libtmux/criteria.rb#L139) | `::String` | [Criteria](behavior.md#criteria) | +| [#to_proc](../../gems/libtmux/lib/libtmux/criteria.rb#L126) | `^(untyped) -> bool` | [Criteria](behavior.md#criteria) | +| [.build](../../gems/libtmux/lib/libtmux/criteria.rb#L53) | `::LibTmux::FilterExpr` | [Criteria](behavior.md#criteria) | +| [.from_json](../../gems/libtmux/lib/libtmux/criteria.rb#L73) | `::LibTmux::FilterExpr` | [Criteria](behavior.md#criteria) | | [.json_schema](../../gems/libtmux/lib/libtmux/criteria.rb#L11) | `::Hash[::String, untyped]` | [Criteria](behavior.md#criteria) | ## LibTmux::GroupResult @@ -510,11 +510,11 @@ type checking. See [signature proof](behavior.md#signature-proof). | Method | Declared return | Contract | | --- | --- | --- | -| [#get](../../gems/libtmux/lib/libtmux/options.rb#L194) | `::LibTmux::OptionValue` | [Options and hooks](behavior.md#options-and-hooks) | -| [#list](../../gems/libtmux/lib/libtmux/options.rb#L66) | `::Array[::LibTmux::OptionValue]` | [Options and hooks](behavior.md#options-and-hooks) | -| [#run](../../gems/libtmux/lib/libtmux/options.rb#L204) | `::LibTmux::CommandResult` | [Options and hooks](behavior.md#options-and-hooks) | -| [#set](../../gems/libtmux/lib/libtmux/options.rb#L198) | `::LibTmux::CommandResult` | [Options and hooks](behavior.md#options-and-hooks) | -| [#unset](../../gems/libtmux/lib/libtmux/options.rb#L132) | `::LibTmux::CommandResult` | [Options and hooks](behavior.md#options-and-hooks) | +| [#get](../../gems/libtmux/lib/libtmux/options.rb#L288) | `::LibTmux::OptionValue` | [Options and hooks](behavior.md#options-and-hooks) | +| [#list](../../gems/libtmux/lib/libtmux/options.rb#L81) | `::Array[::LibTmux::OptionValue]` | [Options and hooks](behavior.md#options-and-hooks) | +| [#run](../../gems/libtmux/lib/libtmux/options.rb#L306) | `::LibTmux::CommandResult` | [Options and hooks](behavior.md#options-and-hooks) | +| [#set](../../gems/libtmux/lib/libtmux/options.rb#L292) | `::LibTmux::CommandResult` | [Options and hooks](behavior.md#options-and-hooks) | +| [#unset](../../gems/libtmux/lib/libtmux/options.rb#L200) | `::LibTmux::CommandResult` | [Options and hooks](behavior.md#options-and-hooks) | ## LibTmux::IncompleteSnapshotError @@ -556,39 +556,39 @@ type checking. See [signature proof](behavior.md#signature-proof). | [#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#L31) | `::LibTmux::InvalidFilterError` | [Errors](behavior.md#errors) | +| [.new](../../gems/libtmux/lib/libtmux/errors.rb#L40) | `::LibTmux::InvalidFilterError` | [Errors](behavior.md#errors) | ## LibTmux::MCP::Application | Method | Declared return | Contract | | --- | --- | --- | -| [#accept_shell](../../gems/libtmux-mcp/lib/libtmux/mcp/application.rb#L111) | `::LibTmux::EntityRef` | [MCP application](behavior.md#mcp-application) | -| [#call](../../gems/libtmux-mcp/lib/libtmux/mcp/application.rb#L117) | `untyped` | [MCP application](behavior.md#mcp-application) | -| [#close](../../gems/libtmux-mcp/lib/libtmux/mcp/application.rb#L202) | `nil` | [MCP application](behavior.md#mcp-application) | -| [#inspect](../../gems/libtmux-mcp/lib/libtmux/mcp/application.rb#L198) | `::String` | [MCP application](behavior.md#mcp-application) | -| [#invite_shell](../../gems/libtmux-mcp/lib/libtmux/mcp/application.rb#L104) | `::LibTmux::MCP::_ShellInvitation` | [MCP application](behavior.md#mcp-application) | -| [#sdk_server](../../gems/libtmux-mcp/lib/libtmux/mcp/application.rb#L94) | `untyped` | [MCP application](behavior.md#mcp-application) | -| [#tools](../../gems/libtmux-mcp/lib/libtmux/mcp/application.rb#L48) | `::Array[untyped]` | [MCP application](behavior.md#mcp-application) | -| [.new](../../gems/libtmux-mcp/lib/libtmux/mcp/application.rb#L50) | `::LibTmux::MCP::Application` | [MCP application](behavior.md#mcp-application) | +| [#accept_shell](../../gems/libtmux-mcp/lib/libtmux/mcp/application.rb#L178) | `::LibTmux::EntityRef` | [MCP application](behavior.md#mcp-application) | +| [#call](../../gems/libtmux-mcp/lib/libtmux/mcp/application.rb#L184) | `untyped` | [MCP application](behavior.md#mcp-application) | +| [#close](../../gems/libtmux-mcp/lib/libtmux/mcp/application.rb#L332) | `nil` | [MCP application](behavior.md#mcp-application) | +| [#inspect](../../gems/libtmux-mcp/lib/libtmux/mcp/application.rb#L328) | `::String` | [MCP application](behavior.md#mcp-application) | +| [#invite_shell](../../gems/libtmux-mcp/lib/libtmux/mcp/application.rb#L167) | `::LibTmux::MCP::_ShellInvitation` | [MCP application](behavior.md#mcp-application) | +| [#sdk_server](../../gems/libtmux-mcp/lib/libtmux/mcp/application.rb#L136) | `untyped` | [MCP application](behavior.md#mcp-application) | +| [#tools](../../gems/libtmux-mcp/lib/libtmux/mcp/application.rb#L53) | `::Array[untyped]` | [MCP application](behavior.md#mcp-application) | +| [.new](../../gems/libtmux-mcp/lib/libtmux/mcp/application.rb#L55) | `::LibTmux::MCP::Application` | [MCP application](behavior.md#mcp-application) | ## LibTmux::MCP::CLI | Method | Declared return | Contract | | --- | --- | --- | -| [#run](../../gems/libtmux-mcp/lib/libtmux/mcp/cli.rb#L30) | `::Integer` | [MCP CLI](behavior.md#mcp-cli) | -| [.run](../../gems/libtmux-mcp/lib/libtmux/mcp/cli.rb#L16) | `::Integer` | [MCP CLI](behavior.md#mcp-cli) | +| [#run](../../gems/libtmux-mcp/lib/libtmux/mcp/cli.rb#L45) | `::Integer` | [MCP CLI](behavior.md#mcp-cli) | +| [.run](../../gems/libtmux-mcp/lib/libtmux/mcp/cli.rb#L17) | `::Integer` | [MCP CLI](behavior.md#mcp-cli) | ## LibTmux::MCP::StdioTransport | Method | Declared return | Contract | | --- | --- | --- | -| [#close](../../gems/libtmux-mcp/lib/libtmux/mcp/stdio_transport.rb#L103) | `nil` | [MCP transport](behavior.md#mcp-transport) | -| [#closed?](../../gems/libtmux-mcp/lib/libtmux/mcp/stdio_transport.rb#L124) | `bool` | [MCP transport](behavior.md#mcp-transport) | -| [#run](../../gems/libtmux-mcp/lib/libtmux/mcp/stdio_transport.rb#L82) | `nil` | [MCP transport](behavior.md#mcp-transport) | -| [#send_notification](../../gems/libtmux-mcp/lib/libtmux/mcp/stdio_transport.rb#L153) | `bool` | [MCP transport](behavior.md#mcp-transport) | -| [#send_request](../../gems/libtmux-mcp/lib/libtmux/mcp/stdio_transport.rb#L160) | `bot` | [MCP transport](behavior.md#mcp-transport) | -| [#send_response](../../gems/libtmux-mcp/lib/libtmux/mcp/stdio_transport.rb#L128) | `nil` | [MCP transport](behavior.md#mcp-transport) | -| [.new](../../gems/libtmux-mcp/lib/libtmux/mcp/stdio_transport.rb#L53) | `::LibTmux::MCP::StdioTransport` | [MCP transport](behavior.md#mcp-transport) | +| [#close](../../gems/libtmux-mcp/lib/libtmux/mcp/stdio_transport.rb#L141) | `nil` | [MCP transport](behavior.md#mcp-transport) | +| [#closed?](../../gems/libtmux-mcp/lib/libtmux/mcp/stdio_transport.rb#L162) | `bool` | [MCP transport](behavior.md#mcp-transport) | +| [#run](../../gems/libtmux-mcp/lib/libtmux/mcp/stdio_transport.rb#L118) | `nil` | [MCP transport](behavior.md#mcp-transport) | +| [#send_notification](../../gems/libtmux-mcp/lib/libtmux/mcp/stdio_transport.rb#L197) | `bool` | [MCP transport](behavior.md#mcp-transport) | +| [#send_request](../../gems/libtmux-mcp/lib/libtmux/mcp/stdio_transport.rb#L204) | `bot` | [MCP transport](behavior.md#mcp-transport) | +| [#send_response](../../gems/libtmux-mcp/lib/libtmux/mcp/stdio_transport.rb#L166) | `nil` | [MCP transport](behavior.md#mcp-transport) | +| [.new](../../gems/libtmux-mcp/lib/libtmux/mcp/stdio_transport.rb#L64) | `::LibTmux::MCP::StdioTransport` | [MCP transport](behavior.md#mcp-transport) | ## LibTmux::MultipleMatchesError @@ -622,9 +622,9 @@ type checking. See [signature proof](behavior.md#signature-proof). | Method | Declared return | Contract | | --- | --- | --- | -| [.hooks](../../gems/libtmux/lib/libtmux/option_catalog.rb#L52) | `::Hash[::String, ::LibTmux::OptionCatalog::Hook]` | [Option catalog](behavior.md#option-catalog) | -| [.options](../../gems/libtmux/lib/libtmux/option_catalog.rb#L49) | `::Hash[::String, ::LibTmux::OptionCatalog::Option]` | [Option catalog](behavior.md#option-catalog) | -| [.tmux_version](../../gems/libtmux/lib/libtmux/option_catalog.rb#L46) | `::String` | [Option catalog](behavior.md#option-catalog) | +| [.hooks](../../gems/libtmux/lib/libtmux/option_catalog.rb#L61) | `::Hash[::String, ::LibTmux::OptionCatalog::Hook]` | [Option catalog](behavior.md#option-catalog) | +| [.options](../../gems/libtmux/lib/libtmux/option_catalog.rb#L58) | `::Hash[::String, ::LibTmux::OptionCatalog::Option]` | [Option catalog](behavior.md#option-catalog) | +| [.tmux_version](../../gems/libtmux/lib/libtmux/option_catalog.rb#L55) | `::String` | [Option catalog](behavior.md#option-catalog) | ## LibTmux::OptionCatalog::Hook @@ -660,10 +660,10 @@ type checking. See [signature proof](behavior.md#signature-proof). | Method | Declared return | Contract | | --- | --- | --- | -| [#get](../../gems/libtmux/lib/libtmux/options.rb#L103) | `::LibTmux::OptionValue` | [Options and hooks](behavior.md#options-and-hooks) | -| [#list](../../gems/libtmux/lib/libtmux/options.rb#L66) | `::Array[::LibTmux::OptionValue]` | [Options and hooks](behavior.md#options-and-hooks) | -| [#set](../../gems/libtmux/lib/libtmux/options.rb#L121) | `::LibTmux::CommandResult` | [Options and hooks](behavior.md#options-and-hooks) | -| [#unset](../../gems/libtmux/lib/libtmux/options.rb#L132) | `::LibTmux::CommandResult` | [Options and hooks](behavior.md#options-and-hooks) | +| [#get](../../gems/libtmux/lib/libtmux/options.rb#L149) | `::LibTmux::OptionValue` | [Options and hooks](behavior.md#options-and-hooks) | +| [#list](../../gems/libtmux/lib/libtmux/options.rb#L81) | `::Array[::LibTmux::OptionValue]` | [Options and hooks](behavior.md#options-and-hooks) | +| [#set](../../gems/libtmux/lib/libtmux/options.rb#L175) | `::LibTmux::CommandResult` | [Options and hooks](behavior.md#options-and-hooks) | +| [#unset](../../gems/libtmux/lib/libtmux/options.rb#L200) | `::LibTmux::CommandResult` | [Options and hooks](behavior.md#options-and-hooks) | ## LibTmux::OutcomeUnknown @@ -683,34 +683,34 @@ type checking. See [signature proof](behavior.md#signature-proof). | Method | Declared return | Contract | | --- | --- | --- | -| [#==](../../gems/libtmux/lib/libtmux/entity.rb#L78) | `bool` | [Live handles](behavior.md#live-handles) | -| [#break_out](../../gems/libtmux/lib/libtmux/operations.rb#L358) | `::LibTmux::Window` | [Entity mutation](behavior.md#entity-mutation) | -| [#capture](../../gems/libtmux/lib/libtmux/entity.rb#L351) | `::LibTmux::CommandResult` | [Pane input and capture](behavior.md#pane-input-and-capture) | -| [#copy_command](../../gems/libtmux/lib/libtmux/operations.rb#L426) | `::LibTmux::CommandResult` | [Copy mode](behavior.md#copy-mode) | -| [#copy_mode](../../gems/libtmux/lib/libtmux/operations.rb#L410) | `::LibTmux::CommandResult` | [Copy mode](behavior.md#copy-mode) | -| [#display](../../gems/libtmux/lib/libtmux/operations.rb#L254) | `::LibTmux::CommandResult` | [Formats](behavior.md#formats) | -| [#eql?](../../gems/libtmux/lib/libtmux/entity.rb#L78) | `bool` | [Live handles](behavior.md#live-handles) | -| [#hash](../../gems/libtmux/lib/libtmux/entity.rb#L83) | `::Integer` | [Live handles](behavior.md#live-handles) | -| [#hooks](../../gems/libtmux/lib/libtmux/operations.rb#L250) | `::LibTmux::Hooks` | [Options and hooks](behavior.md#options-and-hooks) | -| [#id](../../gems/libtmux/lib/libtmux/entity.rb#L70) | `::String` | [Live handles](behavior.md#live-handles) | -| [#inspect](../../gems/libtmux/lib/libtmux/entity.rb#L91) | `::String` | [Live handles](behavior.md#live-handles) | -| [#join](../../gems/libtmux/lib/libtmux/operations.rb#L347) | `::LibTmux::CommandResult` | [Entity mutation](behavior.md#entity-mutation) | -| [#kill](../../gems/libtmux/lib/libtmux/entity.rb#L87) | `::LibTmux::CommandResult` | [Entity removal](behavior.md#entity-removal) | -| [#move](../../gems/libtmux/lib/libtmux/operations.rb#L351) | `::LibTmux::CommandResult` | [Entity mutation](behavior.md#entity-mutation) | -| [#options](../../gems/libtmux/lib/libtmux/operations.rb#L246) | `::LibTmux::Options` | [Options and hooks](behavior.md#options-and-hooks) | -| [#paste](../../gems/libtmux/lib/libtmux/operations.rb#L388) | `::LibTmux::CommandResult` | [Pane input and capture](behavior.md#pane-input-and-capture) | -| [#pipe](../../gems/libtmux/lib/libtmux/operations.rb#L398) | `::LibTmux::CommandResult` | [Pane pipes](behavior.md#pane-pipes) | -| [#ref](../../gems/libtmux/lib/libtmux/entity.rb#L61) | `::LibTmux::EntityRef` | [Live handles](behavior.md#live-handles) | -| [#resize](../../gems/libtmux/lib/libtmux/operations.rb#L325) | `::LibTmux::CommandResult` | [Entity mutation](behavior.md#entity-mutation) | -| [#respawn](../../gems/libtmux/lib/libtmux/operations.rb#L381) | `::LibTmux::CommandResult` | [Entity mutation](behavior.md#entity-mutation) | -| [#select](../../gems/libtmux/lib/libtmux/operations.rb#L321) | `::LibTmux::CommandResult` | [Entity mutation](behavior.md#entity-mutation) | -| [#send_keys](../../gems/libtmux/lib/libtmux/entity.rb#L381) | `::LibTmux::CommandResult` | [Pane input and capture](behavior.md#pane-input-and-capture) | -| [#send_text](../../gems/libtmux/lib/libtmux/entity.rb#L375) | `::LibTmux::CommandResult` | [Pane input and capture](behavior.md#pane-input-and-capture) | -| [#server](../../gems/libtmux/lib/libtmux/entity.rb#L61) | `::LibTmux::Server` | [Live handles](behavior.md#live-handles) | -| [#snapshot](../../gems/libtmux/lib/libtmux/entity.rb#L74) | `::LibTmux::PaneSnapshot` | [Snapshot acquisition](behavior.md#snapshot-acquisition) | -| [#split](../../gems/libtmux/lib/libtmux/entity.rb#L346) | `::LibTmux::Pane` | [Creation](behavior.md#creation) | -| [#swap](../../gems/libtmux/lib/libtmux/operations.rb#L343) | `::LibTmux::CommandResult` | [Entity mutation](behavior.md#entity-mutation) | -| [#wait_for_text](../../gems/libtmux/lib/libtmux/text_wait.rb#L22) | `::LibTmux::TextWait::Result` | [Pane text waits](behavior.md#pane-text-waits) | +| [#==](../../gems/libtmux/lib/libtmux/entity.rb#L88) | `bool` | [Live handles](behavior.md#live-handles) | +| [#break_out](../../gems/libtmux/lib/libtmux/operations.rb#L590) | `::LibTmux::Window` | [Entity mutation](behavior.md#entity-mutation) | +| [#capture](../../gems/libtmux/lib/libtmux/entity.rb#L438) | `::LibTmux::CommandResult` | [Pane input and capture](behavior.md#pane-input-and-capture) | +| [#copy_command](../../gems/libtmux/lib/libtmux/operations.rb#L718) | `::LibTmux::CommandResult` | [Copy mode](behavior.md#copy-mode) | +| [#copy_mode](../../gems/libtmux/lib/libtmux/operations.rb#L687) | `::LibTmux::CommandResult` | [Copy mode](behavior.md#copy-mode) | +| [#display](../../gems/libtmux/lib/libtmux/operations.rb#L391) | `::LibTmux::CommandResult` | [Formats](behavior.md#formats) | +| [#eql?](../../gems/libtmux/lib/libtmux/entity.rb#L88) | `bool` | [Live handles](behavior.md#live-handles) | +| [#hash](../../gems/libtmux/lib/libtmux/entity.rb#L93) | `::Integer` | [Live handles](behavior.md#live-handles) | +| [#hooks](../../gems/libtmux/lib/libtmux/operations.rb#L387) | `::LibTmux::Hooks` | [Options and hooks](behavior.md#options-and-hooks) | +| [#id](../../gems/libtmux/lib/libtmux/entity.rb#L80) | `::String` | [Live handles](behavior.md#live-handles) | +| [#inspect](../../gems/libtmux/lib/libtmux/entity.rb#L106) | `::String` | [Live handles](behavior.md#live-handles) | +| [#join](../../gems/libtmux/lib/libtmux/operations.rb#L565) | `::LibTmux::CommandResult` | [Entity mutation](behavior.md#entity-mutation) | +| [#kill](../../gems/libtmux/lib/libtmux/entity.rb#L97) | `::LibTmux::CommandResult` | [Entity removal](behavior.md#entity-removal) | +| [#move](../../gems/libtmux/lib/libtmux/operations.rb#L576) | `::LibTmux::CommandResult` | [Entity mutation](behavior.md#entity-mutation) | +| [#options](../../gems/libtmux/lib/libtmux/operations.rb#L383) | `::LibTmux::Options` | [Options and hooks](behavior.md#options-and-hooks) | +| [#paste](../../gems/libtmux/lib/libtmux/operations.rb#L658) | `::LibTmux::CommandResult` | [Pane input and capture](behavior.md#pane-input-and-capture) | +| [#pipe](../../gems/libtmux/lib/libtmux/operations.rb#L668) | `::LibTmux::CommandResult` | [Pane pipes](behavior.md#pane-pipes) | +| [#ref](../../gems/libtmux/lib/libtmux/entity.rb#L71) | `::LibTmux::EntityRef` | [Live handles](behavior.md#live-handles) | +| [#resize](../../gems/libtmux/lib/libtmux/operations.rb#L523) | `::LibTmux::CommandResult` | [Entity mutation](behavior.md#entity-mutation) | +| [#respawn](../../gems/libtmux/lib/libtmux/operations.rb#L647) | `::LibTmux::CommandResult` | [Entity mutation](behavior.md#entity-mutation) | +| [#select](../../gems/libtmux/lib/libtmux/operations.rb#L514) | `::LibTmux::CommandResult` | [Entity mutation](behavior.md#entity-mutation) | +| [#send_keys](../../gems/libtmux/lib/libtmux/entity.rb#L493) | `::LibTmux::CommandResult` | [Pane input and capture](behavior.md#pane-input-and-capture) | +| [#send_text](../../gems/libtmux/lib/libtmux/entity.rb#L482) | `::LibTmux::CommandResult` | [Pane input and capture](behavior.md#pane-input-and-capture) | +| [#server](../../gems/libtmux/lib/libtmux/entity.rb#L71) | `::LibTmux::Server` | [Live handles](behavior.md#live-handles) | +| [#snapshot](../../gems/libtmux/lib/libtmux/entity.rb#L84) | `::LibTmux::PaneSnapshot` | [Snapshot acquisition](behavior.md#snapshot-acquisition) | +| [#split](../../gems/libtmux/lib/libtmux/entity.rb#L414) | `::LibTmux::Pane` | [Creation](behavior.md#creation) | +| [#swap](../../gems/libtmux/lib/libtmux/operations.rb#L556) | `::LibTmux::CommandResult` | [Entity mutation](behavior.md#entity-mutation) | +| [#wait_for_text](../../gems/libtmux/lib/libtmux/text_wait.rb#L20) | `::LibTmux::TextWait::Result` | [Pane text waits](behavior.md#pane-text-waits) | ## LibTmux::PaneDied @@ -723,72 +723,72 @@ type checking. See [signature proof](behavior.md#signature-proof). | [#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) | -| [#reason](../../gems/libtmux/lib/libtmux/errors.rb#L53) | `:pane_exited \| :pane_gone \| :server_gone` | [Pane text waits](behavior.md#pane-text-waits) | +| [#reason](../../gems/libtmux/lib/libtmux/errors.rb#L81) | `:pane_exited \| :pane_gone \| :server_gone` | [Pane text waits](behavior.md#pane-text-waits) | | [#text](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::String` | [Errors](behavior.md#errors) | ## LibTmux::PaneSnapshot | Method | Declared return | Contract | | --- | --- | --- | -| [#==](../../gems/libtmux/lib/libtmux/snapshot.rb#L40) | `bool` | [Captured records](behavior.md#captured-records) | -| [#active](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `bool` | [Captured records](behavior.md#captured-records) | -| [#active?](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `bool` | [Captured records](behavior.md#captured-records) | +| [#==](../../gems/libtmux/lib/libtmux/snapshot.rb#L44) | `bool` | [Captured records](behavior.md#captured-records) | +| [#active](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `bool` | [Captured records](behavior.md#captured-records) | +| [#active?](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `bool` | [Captured records](behavior.md#captured-records) | | [#capture_id](../../gems/libtmux/lib/libtmux/snapshot.rb#L10) | `::String` | [Captured records](behavior.md#captured-records) | -| [#current_command](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `::String` | [Captured records](behavior.md#captured-records) | -| [#current_path](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `::String?` | [Captured records](behavior.md#captured-records) | -| [#dead](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `bool` | [Captured records](behavior.md#captured-records) | -| [#dead?](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `bool` | [Captured records](behavior.md#captured-records) | -| [#dead_status](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `::Integer?` | [Captured records](behavior.md#captured-records) | -| [#eql?](../../gems/libtmux/lib/libtmux/snapshot.rb#L40) | `bool` | [Captured records](behavior.md#captured-records) | -| [#hash](../../gems/libtmux/lib/libtmux/snapshot.rb#L46) | `::Integer` | [Captured records](behavior.md#captured-records) | -| [#height](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `::Integer` | [Captured records](behavior.md#captured-records) | -| [#id](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `::String` | [Captured records](behavior.md#captured-records) | -| [#index](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `::Integer` | [Captured records](behavior.md#captured-records) | -| [#inspect](../../gems/libtmux/lib/libtmux/snapshot.rb#L50) | `::String` | [Captured records](behavior.md#captured-records) | -| [#pid](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `::Integer?` | [Captured records](behavior.md#captured-records) | -| [#raw](../../gems/libtmux/lib/libtmux/snapshot.rb#L34) | `::String?` | [Captured records](behavior.md#captured-records) | -| [#ref](../../gems/libtmux/lib/libtmux/snapshot.rb#L26) | `::LibTmux::EntityRef` | [Captured records](behavior.md#captured-records) | -| [#title](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `::String` | [Captured records](behavior.md#captured-records) | -| [#width](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `::Integer` | [Captured records](behavior.md#captured-records) | -| [#window](../../gems/libtmux/lib/libtmux/snapshot.rb#L152) | `::LibTmux::WindowSnapshot` | [Captured records](behavior.md#captured-records) | -| [#window_id](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `::String` | [Captured records](behavior.md#captured-records) | +| [#current_command](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `::String` | [Captured records](behavior.md#captured-records) | +| [#current_path](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `::String?` | [Captured records](behavior.md#captured-records) | +| [#dead](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `bool` | [Captured records](behavior.md#captured-records) | +| [#dead?](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `bool` | [Captured records](behavior.md#captured-records) | +| [#dead_status](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `::Integer?` | [Captured records](behavior.md#captured-records) | +| [#eql?](../../gems/libtmux/lib/libtmux/snapshot.rb#L44) | `bool` | [Captured records](behavior.md#captured-records) | +| [#hash](../../gems/libtmux/lib/libtmux/snapshot.rb#L50) | `::Integer` | [Captured records](behavior.md#captured-records) | +| [#height](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `::Integer` | [Captured records](behavior.md#captured-records) | +| [#id](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `::String` | [Captured records](behavior.md#captured-records) | +| [#index](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `::Integer` | [Captured records](behavior.md#captured-records) | +| [#inspect](../../gems/libtmux/lib/libtmux/snapshot.rb#L54) | `::String` | [Captured records](behavior.md#captured-records) | +| [#pid](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `::Integer?` | [Captured records](behavior.md#captured-records) | +| [#raw](../../gems/libtmux/lib/libtmux/snapshot.rb#L38) | `::String?` | [Captured records](behavior.md#captured-records) | +| [#ref](../../gems/libtmux/lib/libtmux/snapshot.rb#L29) | `::LibTmux::EntityRef` | [Captured records](behavior.md#captured-records) | +| [#title](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `::String` | [Captured records](behavior.md#captured-records) | +| [#width](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `::Integer` | [Captured records](behavior.md#captured-records) | +| [#window](../../gems/libtmux/lib/libtmux/snapshot.rb#L195) | `::LibTmux::WindowSnapshot` | [Captured records](behavior.md#captured-records) | +| [#window_id](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `::String` | [Captured records](behavior.md#captured-records) | ## LibTmux::PaneWhere | Method | Declared return | Contract | | --- | --- | --- | -| [.build](../../gems/libtmux/lib/libtmux/criteria.rb#L405) | `::LibTmux::FilterExpr` | [Criteria](behavior.md#criteria) | +| [.build](../../gems/libtmux/lib/libtmux/criteria.rb#L512) | `::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) | +| [#capture_screen](../../gems/libtmux/lib/libtmux/program.rb#L209) | `::LibTmux::Program::Screen` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#close](../../gems/libtmux/lib/libtmux/program.rb#L241) | `nil` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#inspect](../../gems/libtmux/lib/libtmux/program.rb#L269) | `::String` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#resize](../../gems/libtmux/lib/libtmux/program.rb#L229) | `::LibTmux::CommandResult` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#screen](../../gems/libtmux/lib/libtmux/program.rb#L204) | `::String` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#send_keys](../../gems/libtmux/lib/libtmux/program.rb#L223) | `::LibTmux::CommandResult` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#send_text](../../gems/libtmux/lib/libtmux/program.rb#L217) | `::LibTmux::CommandResult` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#wait](../../gems/libtmux/lib/libtmux/program.rb#L179) | `::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) | +| [#exit_status](../../gems/libtmux/lib/libtmux/program.rb#L48) | `::Integer?` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#inspect](../../gems/libtmux/lib/libtmux/program.rb#L61) | `::String` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#screen](../../gems/libtmux/lib/libtmux/program.rb#L48) | `::String` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#screen_truncated?](../../gems/libtmux/lib/libtmux/program.rb#L57) | `bool` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#signal](../../gems/libtmux/lib/libtmux/program.rb#L48) | `::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) | +| [#inspect](../../gems/libtmux/lib/libtmux/program.rb#L41) | `::String` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#text](../../gems/libtmux/lib/libtmux/program.rb#L29) | `::String` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#truncated?](../../gems/libtmux/lib/libtmux/program.rb#L37) | `bool` | [Owned terminal programs](behavior.md#owned-terminal-programs) | ## LibTmux::Program::ScreenGeometryError @@ -841,46 +841,46 @@ 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#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#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) | +| [#attach](../../gems/libtmux/lib/libtmux/terminal.rb#L53) | `::LibTmux::TerminalResult` | [Terminal attachment](behavior.md#terminal-attachment) | +| [#capabilities](../../gems/libtmux/lib/libtmux/server.rb#L256) | `::LibTmux::Capabilities` | [Daemon capabilities](behavior.md#daemon-capabilities) | +| [#close](../../gems/libtmux/lib/libtmux/server.rb#L272) | `nil` | [Closing bindings](behavior.md#closing-bindings) | +| [#delete_buffer](../../gems/libtmux/lib/libtmux/operations.rb#L89) | `::LibTmux::CommandResult` | [Buffers](behavior.md#buffers) | +| [#diagnostics](../../gems/libtmux/lib/libtmux/server.rb#L315) | `{ 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#L20) | `::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#L409) | `::Hash[::Symbol, untyped]` | [Source query plans](behavior.md#source-query-plans) | +| [#environment](../../gems/libtmux/lib/libtmux/operations.rb#L118) | `::String?` | [Environment](behavior.md#environment) | +| [#explain_panes](../../gems/libtmux/lib/libtmux/server.rb#L463) | `::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#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#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#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) | +| [#kill](../../gems/libtmux/lib/libtmux/server.rb#L332) | `::LibTmux::CommandResult` | [Killing daemons](behavior.md#killing-daemons) | +| [#list_buffers](../../gems/libtmux/lib/libtmux/operations.rb#L93) | `::Array[{ name: ::String, size: ::Integer }]` | [Buffers](behavior.md#buffers) | +| [#list_clients](../../gems/libtmux/lib/libtmux/operations.rb#L130) | `::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#L384) | `::Array[::LibTmux::Pane]` | [Live acquisition](behavior.md#live-acquisition) | +| [#list_sessions](../../gems/libtmux/lib/libtmux/server.rb#L376) | `::Array[::LibTmux::Session]` | [Live acquisition](behavior.md#live-acquisition) | +| [#list_window_links](../../gems/libtmux/lib/libtmux/operations.rb#L106) | `::Array[::LibTmux::WindowLink]` | [Live acquisition](behavior.md#live-acquisition) | +| [#list_windows](../../gems/libtmux/lib/libtmux/server.rb#L380) | `::Array[::LibTmux::Window]` | [Live acquisition](behavior.md#live-acquisition) | +| [#new_session](../../gems/libtmux/lib/libtmux/server.rb#L343) | `::LibTmux::CreationReceipt` / `::LibTmux::Session` | [Creation](behavior.md#creation) | +| [#open_control](../../gems/libtmux/lib/libtmux/server.rb#L400) | `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#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#L249) | `::LibTmux::CommandResult` | [Raw commands](behavior.md#raw-commands) | +| [#pane](../../gems/libtmux/lib/libtmux/server.rb#L396) | `::LibTmux::Pane` | [Live handles](behavior.md#live-handles) | +| [#program_support](../../gems/libtmux/lib/libtmux/program.rb#L570) | `{ 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#L85) | `::LibTmux::CommandResult` | [Buffers](behavior.md#buffers) | +| [#run](../../gems/libtmux/lib/libtmux/server.rb#L268) | `::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#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#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) | -| [#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#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#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) | +| [#search_panes](../../gems/libtmux/lib/libtmux/server.rb#L459) | `::LibTmux::Selection[::LibTmux::PaneSnapshot]` | [Source query execution](behavior.md#source-query-execution) | +| [#session](../../gems/libtmux/lib/libtmux/server.rb#L388) | `::LibTmux::Session` | [Live handles](behavior.md#live-handles) | +| [#set_environment](../../gems/libtmux/lib/libtmux/operations.rb#L114) | `::LibTmux::CommandResult` | [Environment](behavior.md#environment) | +| [#snapshot](../../gems/libtmux/lib/libtmux/server.rb#L453) | `::LibTmux::Snapshot` | [Snapshot acquisition](behavior.md#snapshot-acquisition) | +| [#source_file](../../gems/libtmux/lib/libtmux/operations.rb#L56) | `::LibTmux::CommandResult` | [Source files](behavior.md#source-files) | +| [#start_program](../../gems/libtmux/lib/libtmux/program.rb#L580) | `::LibTmux::Program` / `T` | [Owned terminal programs](behavior.md#owned-terminal-programs) | +| [#supports_control?](../../gems/libtmux/lib/libtmux/server.rb#L248) | `bool` | [Borrowed bindings](behavior.md#borrowed-bindings) | +| [#switch_client](../../gems/libtmux/lib/libtmux/terminal.rb#L40) | `::LibTmux::CommandResult` | [Client switching](behavior.md#client-switching) | +| [#tmux_version](../../gems/libtmux/lib/libtmux/server.rb#L243) | `::String` | [Borrowed bindings](behavior.md#borrowed-bindings) | +| [#unset_environment](../../gems/libtmux/lib/libtmux/operations.rb#L122) | `::LibTmux::CommandResult` | [Environment](behavior.md#environment) | +| [#wait_for](../../gems/libtmux/lib/libtmux/operations.rb#L61) | `::LibTmux::CommandResult` | [Wait channels](behavior.md#wait-channels) | +| [#window](../../gems/libtmux/lib/libtmux/server.rb#L392) | `::LibTmux::Window` | [Live handles](behavior.md#live-handles) | +| [#window_link](../../gems/libtmux/lib/libtmux/operations.rb#L110) | `::LibTmux::WindowLink` | [Live handles](behavior.md#live-handles) | +| [#write_buffer](../../gems/libtmux/lib/libtmux/operations.rb#L72) | `::LibTmux::CommandResult` | [Buffers](behavior.md#buffers) | | [.new](../../gems/libtmux/lib/libtmux/server.rb#L183) | `::LibTmux::Server` | [Borrowed bindings](behavior.md#borrowed-bindings) | | [.open](../../gems/libtmux/lib/libtmux/server.rb#L151) | `T` / `::LibTmux::Server` | [Borrowed bindings](behavior.md#borrowed-bindings) | | [.start](../../gems/libtmux/lib/libtmux/owned.rb#L12) | `::LibTmux::Server` / `T` | [Owned daemons](behavior.md#owned-daemons) | @@ -890,73 +890,73 @@ type checking. See [signature proof](behavior.md#signature-proof). | Method | Declared return | Contract | | --- | --- | --- | -| [#==](../../gems/libtmux/lib/libtmux/entity.rb#L78) | `bool` | [Live handles](behavior.md#live-handles) | -| [#display](../../gems/libtmux/lib/libtmux/operations.rb#L254) | `::LibTmux::CommandResult` | [Formats](behavior.md#formats) | -| [#environment](../../gems/libtmux/lib/libtmux/operations.rb#L286) | `::String?` | [Environment](behavior.md#environment) | -| [#eql?](../../gems/libtmux/lib/libtmux/entity.rb#L78) | `bool` | [Live handles](behavior.md#live-handles) | -| [#hash](../../gems/libtmux/lib/libtmux/entity.rb#L83) | `::Integer` | [Live handles](behavior.md#live-handles) | -| [#hooks](../../gems/libtmux/lib/libtmux/operations.rb#L250) | `::LibTmux::Hooks` | [Options and hooks](behavior.md#options-and-hooks) | -| [#id](../../gems/libtmux/lib/libtmux/entity.rb#L70) | `::String` | [Live handles](behavior.md#live-handles) | -| [#inspect](../../gems/libtmux/lib/libtmux/entity.rb#L91) | `::String` | [Live handles](behavior.md#live-handles) | -| [#kill](../../gems/libtmux/lib/libtmux/operations.rb#L261) | `::LibTmux::CommandResult` | [Entity removal](behavior.md#entity-removal) | -| [#link_window](../../gems/libtmux/lib/libtmux/operations.rb#L275) | `::LibTmux::CommandResult` | [Window links](behavior.md#window-links) | -| [#list_panes](../../gems/libtmux/lib/libtmux/entity.rb#L169) | `::Array[::LibTmux::Pane]` | [Live acquisition](behavior.md#live-acquisition) | -| [#list_window_links](../../gems/libtmux/lib/libtmux/operations.rb#L271) | `::Array[::LibTmux::WindowLink]` | [Live acquisition](behavior.md#live-acquisition) | -| [#list_windows](../../gems/libtmux/lib/libtmux/entity.rb#L165) | `::Array[::LibTmux::Window]` | [Live acquisition](behavior.md#live-acquisition) | -| [#new_window](../../gems/libtmux/lib/libtmux/entity.rb#L160) | `::LibTmux::CreationReceipt` / `::LibTmux::Window` | [Creation](behavior.md#creation) | -| [#options](../../gems/libtmux/lib/libtmux/operations.rb#L246) | `::LibTmux::Options` | [Options and hooks](behavior.md#options-and-hooks) | -| [#ref](../../gems/libtmux/lib/libtmux/entity.rb#L61) | `::LibTmux::EntityRef` | [Live handles](behavior.md#live-handles) | -| [#rename](../../gems/libtmux/lib/libtmux/operations.rb#L267) | `::LibTmux::CommandResult` | [Entity mutation](behavior.md#entity-mutation) | -| [#server](../../gems/libtmux/lib/libtmux/entity.rb#L61) | `::LibTmux::Server` | [Live handles](behavior.md#live-handles) | -| [#set_environment](../../gems/libtmux/lib/libtmux/operations.rb#L282) | `::LibTmux::CommandResult` | [Environment](behavior.md#environment) | -| [#snapshot](../../gems/libtmux/lib/libtmux/entity.rb#L74) | `::LibTmux::SessionSnapshot` | [Snapshot acquisition](behavior.md#snapshot-acquisition) | -| [#unset_environment](../../gems/libtmux/lib/libtmux/operations.rb#L290) | `::LibTmux::CommandResult` | [Environment](behavior.md#environment) | +| [#==](../../gems/libtmux/lib/libtmux/entity.rb#L88) | `bool` | [Live handles](behavior.md#live-handles) | +| [#display](../../gems/libtmux/lib/libtmux/operations.rb#L391) | `::LibTmux::CommandResult` | [Formats](behavior.md#formats) | +| [#environment](../../gems/libtmux/lib/libtmux/operations.rb#L450) | `::String?` | [Environment](behavior.md#environment) | +| [#eql?](../../gems/libtmux/lib/libtmux/entity.rb#L88) | `bool` | [Live handles](behavior.md#live-handles) | +| [#hash](../../gems/libtmux/lib/libtmux/entity.rb#L93) | `::Integer` | [Live handles](behavior.md#live-handles) | +| [#hooks](../../gems/libtmux/lib/libtmux/operations.rb#L387) | `::LibTmux::Hooks` | [Options and hooks](behavior.md#options-and-hooks) | +| [#id](../../gems/libtmux/lib/libtmux/entity.rb#L80) | `::String` | [Live handles](behavior.md#live-handles) | +| [#inspect](../../gems/libtmux/lib/libtmux/entity.rb#L106) | `::String` | [Live handles](behavior.md#live-handles) | +| [#kill](../../gems/libtmux/lib/libtmux/operations.rb#L398) | `::LibTmux::CommandResult` | [Entity removal](behavior.md#entity-removal) | +| [#link_window](../../gems/libtmux/lib/libtmux/operations.rb#L424) | `::LibTmux::CommandResult` | [Window links](behavior.md#window-links) | +| [#list_panes](../../gems/libtmux/lib/libtmux/entity.rb#L205) | `::Array[::LibTmux::Pane]` | [Live acquisition](behavior.md#live-acquisition) | +| [#list_window_links](../../gems/libtmux/lib/libtmux/operations.rb#L420) | `::Array[::LibTmux::WindowLink]` | [Live acquisition](behavior.md#live-acquisition) | +| [#list_windows](../../gems/libtmux/lib/libtmux/entity.rb#L201) | `::Array[::LibTmux::Window]` | [Live acquisition](behavior.md#live-acquisition) | +| [#new_window](../../gems/libtmux/lib/libtmux/entity.rb#L175) | `::LibTmux::CreationReceipt` / `::LibTmux::Window` | [Creation](behavior.md#creation) | +| [#options](../../gems/libtmux/lib/libtmux/operations.rb#L383) | `::LibTmux::Options` | [Options and hooks](behavior.md#options-and-hooks) | +| [#ref](../../gems/libtmux/lib/libtmux/entity.rb#L71) | `::LibTmux::EntityRef` | [Live handles](behavior.md#live-handles) | +| [#rename](../../gems/libtmux/lib/libtmux/operations.rb#L411) | `::LibTmux::CommandResult` | [Entity mutation](behavior.md#entity-mutation) | +| [#server](../../gems/libtmux/lib/libtmux/entity.rb#L71) | `::LibTmux::Server` | [Live handles](behavior.md#live-handles) | +| [#set_environment](../../gems/libtmux/lib/libtmux/operations.rb#L438) | `::LibTmux::CommandResult` | [Environment](behavior.md#environment) | +| [#snapshot](../../gems/libtmux/lib/libtmux/entity.rb#L84) | `::LibTmux::SessionSnapshot` | [Snapshot acquisition](behavior.md#snapshot-acquisition) | +| [#unset_environment](../../gems/libtmux/lib/libtmux/operations.rb#L461) | `::LibTmux::CommandResult` | [Environment](behavior.md#environment) | ## LibTmux::SessionSnapshot | Method | Declared return | Contract | | --- | --- | --- | -| [#==](../../gems/libtmux/lib/libtmux/snapshot.rb#L40) | `bool` | [Captured records](behavior.md#captured-records) | -| [#attached](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `::Integer` | [Captured records](behavior.md#captured-records) | +| [#==](../../gems/libtmux/lib/libtmux/snapshot.rb#L44) | `bool` | [Captured records](behavior.md#captured-records) | +| [#attached](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `::Integer` | [Captured records](behavior.md#captured-records) | | [#capture_id](../../gems/libtmux/lib/libtmux/snapshot.rb#L10) | `::String` | [Captured records](behavior.md#captured-records) | -| [#created](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `::Integer` | [Captured records](behavior.md#captured-records) | -| [#current_window](../../gems/libtmux/lib/libtmux/snapshot.rb#L152) | `::LibTmux::WindowSnapshot?` | [Captured records](behavior.md#captured-records) | -| [#eql?](../../gems/libtmux/lib/libtmux/snapshot.rb#L40) | `bool` | [Captured records](behavior.md#captured-records) | -| [#hash](../../gems/libtmux/lib/libtmux/snapshot.rb#L46) | `::Integer` | [Captured records](behavior.md#captured-records) | -| [#id](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `::String` | [Captured records](behavior.md#captured-records) | -| [#inspect](../../gems/libtmux/lib/libtmux/snapshot.rb#L50) | `::String` | [Captured records](behavior.md#captured-records) | -| [#name](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `::String` | [Captured records](behavior.md#captured-records) | -| [#panes](../../gems/libtmux/lib/libtmux/snapshot.rb#L152) | `::LibTmux::Selection[::LibTmux::PaneSnapshot]` | [Captured records](behavior.md#captured-records) | -| [#raw](../../gems/libtmux/lib/libtmux/snapshot.rb#L34) | `::String?` | [Captured records](behavior.md#captured-records) | -| [#ref](../../gems/libtmux/lib/libtmux/snapshot.rb#L26) | `::LibTmux::EntityRef` | [Captured records](behavior.md#captured-records) | -| [#window_count](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `::Integer` | [Captured records](behavior.md#captured-records) | -| [#window_links](../../gems/libtmux/lib/libtmux/snapshot.rb#L152) | `::LibTmux::Selection[::LibTmux::WindowLinkSnapshot]` | [Captured records](behavior.md#captured-records) | -| [#windows](../../gems/libtmux/lib/libtmux/snapshot.rb#L152) | `::LibTmux::Selection[::LibTmux::WindowSnapshot]` | [Captured records](behavior.md#captured-records) | +| [#created](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `::Integer` | [Captured records](behavior.md#captured-records) | +| [#current_window](../../gems/libtmux/lib/libtmux/snapshot.rb#L195) | `::LibTmux::WindowSnapshot?` | [Captured records](behavior.md#captured-records) | +| [#eql?](../../gems/libtmux/lib/libtmux/snapshot.rb#L44) | `bool` | [Captured records](behavior.md#captured-records) | +| [#hash](../../gems/libtmux/lib/libtmux/snapshot.rb#L50) | `::Integer` | [Captured records](behavior.md#captured-records) | +| [#id](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `::String` | [Captured records](behavior.md#captured-records) | +| [#inspect](../../gems/libtmux/lib/libtmux/snapshot.rb#L54) | `::String` | [Captured records](behavior.md#captured-records) | +| [#name](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `::String` | [Captured records](behavior.md#captured-records) | +| [#panes](../../gems/libtmux/lib/libtmux/snapshot.rb#L195) | `::LibTmux::Selection[::LibTmux::PaneSnapshot]` | [Captured records](behavior.md#captured-records) | +| [#raw](../../gems/libtmux/lib/libtmux/snapshot.rb#L38) | `::String?` | [Captured records](behavior.md#captured-records) | +| [#ref](../../gems/libtmux/lib/libtmux/snapshot.rb#L29) | `::LibTmux::EntityRef` | [Captured records](behavior.md#captured-records) | +| [#window_count](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `::Integer` | [Captured records](behavior.md#captured-records) | +| [#window_links](../../gems/libtmux/lib/libtmux/snapshot.rb#L195) | `::LibTmux::Selection[::LibTmux::WindowLinkSnapshot]` | [Captured records](behavior.md#captured-records) | +| [#windows](../../gems/libtmux/lib/libtmux/snapshot.rb#L195) | `::LibTmux::Selection[::LibTmux::WindowSnapshot]` | [Captured records](behavior.md#captured-records) | ## LibTmux::SessionWhere | Method | Declared return | Contract | | --- | --- | --- | -| [.build](../../gems/libtmux/lib/libtmux/criteria.rb#L405) | `::LibTmux::FilterExpr` | [Criteria](behavior.md#criteria) | +| [.build](../../gems/libtmux/lib/libtmux/criteria.rb#L512) | `::LibTmux::FilterExpr` | [Criteria](behavior.md#criteria) | ## LibTmux::Snapshot | Method | Declared return | Contract | | --- | --- | --- | -| [#binding_key](../../gems/libtmux/lib/libtmux/snapshot.rb#L158) | `::String` | [Captured records](behavior.md#captured-records) | -| [#capture_id](../../gems/libtmux/lib/libtmux/snapshot.rb#L158) | `::String` | [Captured records](behavior.md#captured-records) | -| [#clients](../../gems/libtmux/lib/libtmux/snapshot.rb#L223) | `::LibTmux::Selection[::LibTmux::ClientSnapshot]` | [Captured records](behavior.md#captured-records) | -| [#coverage](../../gems/libtmux/lib/libtmux/snapshot.rb#L158) | `::Hash[::Symbol, untyped]` | [Captured records](behavior.md#captured-records) | -| [#finished_at](../../gems/libtmux/lib/libtmux/snapshot.rb#L158) | `::Float` | [Captured records](behavior.md#captured-records) | -| [#inspect](../../gems/libtmux/lib/libtmux/snapshot.rb#L235) | `::String` | [Captured records](behavior.md#captured-records) | -| [#panes](../../gems/libtmux/lib/libtmux/snapshot.rb#L215) | `::LibTmux::Selection[::LibTmux::PaneSnapshot]` | [Captured records](behavior.md#captured-records) | -| [#reads](../../gems/libtmux/lib/libtmux/snapshot.rb#L158) | `::Array[::Hash[::Symbol, untyped]]` | [Captured records](behavior.md#captured-records) | -| [#resolve](../../gems/libtmux/lib/libtmux/snapshot.rb#L227) | `::LibTmux::CapturedRecord` | [Captured records](behavior.md#captured-records) | -| [#server_info](../../gems/libtmux/lib/libtmux/snapshot.rb#L158) | `::Hash[::Symbol, untyped]` | [Captured records](behavior.md#captured-records) | -| [#sessions](../../gems/libtmux/lib/libtmux/snapshot.rb#L207) | `::LibTmux::Selection[::LibTmux::SessionSnapshot]` | [Captured records](behavior.md#captured-records) | -| [#started_at](../../gems/libtmux/lib/libtmux/snapshot.rb#L158) | `::Float` | [Captured records](behavior.md#captured-records) | -| [#window_links](../../gems/libtmux/lib/libtmux/snapshot.rb#L219) | `::LibTmux::Selection[::LibTmux::WindowLinkSnapshot]` | [Captured records](behavior.md#captured-records) | -| [#windows](../../gems/libtmux/lib/libtmux/snapshot.rb#L211) | `::LibTmux::Selection[::LibTmux::WindowSnapshot]` | [Captured records](behavior.md#captured-records) | +| [#binding_key](../../gems/libtmux/lib/libtmux/snapshot.rb#L200) | `::String` | [Captured records](behavior.md#captured-records) | +| [#capture_id](../../gems/libtmux/lib/libtmux/snapshot.rb#L200) | `::String` | [Captured records](behavior.md#captured-records) | +| [#clients](../../gems/libtmux/lib/libtmux/snapshot.rb#L297) | `::LibTmux::Selection[::LibTmux::ClientSnapshot]` | [Captured records](behavior.md#captured-records) | +| [#coverage](../../gems/libtmux/lib/libtmux/snapshot.rb#L200) | `::Hash[::Symbol, untyped]` | [Captured records](behavior.md#captured-records) | +| [#finished_at](../../gems/libtmux/lib/libtmux/snapshot.rb#L200) | `::Float` | [Captured records](behavior.md#captured-records) | +| [#inspect](../../gems/libtmux/lib/libtmux/snapshot.rb#L311) | `::String` | [Captured records](behavior.md#captured-records) | +| [#panes](../../gems/libtmux/lib/libtmux/snapshot.rb#L289) | `::LibTmux::Selection[::LibTmux::PaneSnapshot]` | [Captured records](behavior.md#captured-records) | +| [#reads](../../gems/libtmux/lib/libtmux/snapshot.rb#L200) | `::Array[::Hash[::Symbol, untyped]]` | [Captured records](behavior.md#captured-records) | +| [#resolve](../../gems/libtmux/lib/libtmux/snapshot.rb#L301) | `::LibTmux::CapturedRecord` | [Captured records](behavior.md#captured-records) | +| [#server_info](../../gems/libtmux/lib/libtmux/snapshot.rb#L200) | `::Hash[::Symbol, untyped]` | [Captured records](behavior.md#captured-records) | +| [#sessions](../../gems/libtmux/lib/libtmux/snapshot.rb#L281) | `::LibTmux::Selection[::LibTmux::SessionSnapshot]` | [Captured records](behavior.md#captured-records) | +| [#started_at](../../gems/libtmux/lib/libtmux/snapshot.rb#L200) | `::Float` | [Captured records](behavior.md#captured-records) | +| [#window_links](../../gems/libtmux/lib/libtmux/snapshot.rb#L293) | `::LibTmux::Selection[::LibTmux::WindowLinkSnapshot]` | [Captured records](behavior.md#captured-records) | +| [#windows](../../gems/libtmux/lib/libtmux/snapshot.rb#L285) | `::LibTmux::Selection[::LibTmux::WindowSnapshot]` | [Captured records](behavior.md#captured-records) | ## LibTmux::SubscriptionOverflow @@ -969,9 +969,9 @@ type checking. See [signature proof](behavior.md#signature-proof). | [#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) | -| [#sequence](../../gems/libtmux/lib/libtmux/control.rb#L78) | `::Integer?` | [Errors](behavior.md#errors) | +| [#sequence](../../gems/libtmux/lib/libtmux/control.rb#L96) | `::Integer?` | [Errors](behavior.md#errors) | | [#text](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::String?` | [Errors](behavior.md#errors) | -| [.new](../../gems/libtmux/lib/libtmux/control.rb#L80) | `::LibTmux::SubscriptionOverflow` | [Errors](behavior.md#errors) | +| [.new](../../gems/libtmux/lib/libtmux/control.rb#L98) | `::LibTmux::SubscriptionOverflow` | [Errors](behavior.md#errors) | ## LibTmux::Support @@ -1053,110 +1053,110 @@ type checking. See [signature proof](behavior.md#signature-proof). | Method | Declared return | Contract | | --- | --- | --- | -| [#==](../../gems/libtmux/lib/libtmux/entity.rb#L78) | `bool` | [Live handles](behavior.md#live-handles) | -| [#display](../../gems/libtmux/lib/libtmux/operations.rb#L254) | `::LibTmux::CommandResult` | [Formats](behavior.md#formats) | -| [#eql?](../../gems/libtmux/lib/libtmux/entity.rb#L78) | `bool` | [Live handles](behavior.md#live-handles) | -| [#hash](../../gems/libtmux/lib/libtmux/entity.rb#L83) | `::Integer` | [Live handles](behavior.md#live-handles) | -| [#hooks](../../gems/libtmux/lib/libtmux/operations.rb#L250) | `::LibTmux::Hooks` | [Options and hooks](behavior.md#options-and-hooks) | -| [#id](../../gems/libtmux/lib/libtmux/entity.rb#L70) | `::String` | [Live handles](behavior.md#live-handles) | -| [#inspect](../../gems/libtmux/lib/libtmux/entity.rb#L91) | `::String` | [Live handles](behavior.md#live-handles) | -| [#kill](../../gems/libtmux/lib/libtmux/entity.rb#L87) | `::LibTmux::CommandResult` | [Entity removal](behavior.md#entity-removal) | -| [#list_panes](../../gems/libtmux/lib/libtmux/entity.rb#L230) | `::Array[::LibTmux::Pane]` | [Live acquisition](behavior.md#live-acquisition) | -| [#options](../../gems/libtmux/lib/libtmux/operations.rb#L246) | `::LibTmux::Options` | [Options and hooks](behavior.md#options-and-hooks) | -| [#ref](../../gems/libtmux/lib/libtmux/entity.rb#L61) | `::LibTmux::EntityRef` | [Live handles](behavior.md#live-handles) | -| [#rename](../../gems/libtmux/lib/libtmux/operations.rb#L296) | `::LibTmux::CommandResult` | [Entity mutation](behavior.md#entity-mutation) | -| [#resize](../../gems/libtmux/lib/libtmux/operations.rb#L307) | `::LibTmux::CommandResult` | [Entity mutation](behavior.md#entity-mutation) | -| [#respawn](../../gems/libtmux/lib/libtmux/operations.rb#L300) | `::LibTmux::CommandResult` | [Entity mutation](behavior.md#entity-mutation) | -| [#select_layout](../../gems/libtmux/lib/libtmux/entity.rb#L239) | `::LibTmux::CommandResult` | [Entity mutation](behavior.md#entity-mutation) | -| [#server](../../gems/libtmux/lib/libtmux/entity.rb#L61) | `::LibTmux::Server` | [Live handles](behavior.md#live-handles) | -| [#snapshot](../../gems/libtmux/lib/libtmux/entity.rb#L74) | `::LibTmux::WindowSnapshot` | [Snapshot acquisition](behavior.md#snapshot-acquisition) | -| [#split](../../gems/libtmux/lib/libtmux/entity.rb#L234) | `::LibTmux::Pane` | [Creation](behavior.md#creation) | +| [#==](../../gems/libtmux/lib/libtmux/entity.rb#L88) | `bool` | [Live handles](behavior.md#live-handles) | +| [#display](../../gems/libtmux/lib/libtmux/operations.rb#L391) | `::LibTmux::CommandResult` | [Formats](behavior.md#formats) | +| [#eql?](../../gems/libtmux/lib/libtmux/entity.rb#L88) | `bool` | [Live handles](behavior.md#live-handles) | +| [#hash](../../gems/libtmux/lib/libtmux/entity.rb#L93) | `::Integer` | [Live handles](behavior.md#live-handles) | +| [#hooks](../../gems/libtmux/lib/libtmux/operations.rb#L387) | `::LibTmux::Hooks` | [Options and hooks](behavior.md#options-and-hooks) | +| [#id](../../gems/libtmux/lib/libtmux/entity.rb#L80) | `::String` | [Live handles](behavior.md#live-handles) | +| [#inspect](../../gems/libtmux/lib/libtmux/entity.rb#L106) | `::String` | [Live handles](behavior.md#live-handles) | +| [#kill](../../gems/libtmux/lib/libtmux/entity.rb#L97) | `::LibTmux::CommandResult` | [Entity removal](behavior.md#entity-removal) | +| [#list_panes](../../gems/libtmux/lib/libtmux/entity.rb#L266) | `::Array[::LibTmux::Pane]` | [Live acquisition](behavior.md#live-acquisition) | +| [#options](../../gems/libtmux/lib/libtmux/operations.rb#L383) | `::LibTmux::Options` | [Options and hooks](behavior.md#options-and-hooks) | +| [#ref](../../gems/libtmux/lib/libtmux/entity.rb#L71) | `::LibTmux::EntityRef` | [Live handles](behavior.md#live-handles) | +| [#rename](../../gems/libtmux/lib/libtmux/operations.rb#L472) | `::LibTmux::CommandResult` | [Entity mutation](behavior.md#entity-mutation) | +| [#resize](../../gems/libtmux/lib/libtmux/operations.rb#L492) | `::LibTmux::CommandResult` | [Entity mutation](behavior.md#entity-mutation) | +| [#respawn](../../gems/libtmux/lib/libtmux/operations.rb#L481) | `::LibTmux::CommandResult` | [Entity mutation](behavior.md#entity-mutation) | +| [#select_layout](../../gems/libtmux/lib/libtmux/entity.rb#L294) | `::LibTmux::CommandResult` | [Entity mutation](behavior.md#entity-mutation) | +| [#server](../../gems/libtmux/lib/libtmux/entity.rb#L71) | `::LibTmux::Server` | [Live handles](behavior.md#live-handles) | +| [#snapshot](../../gems/libtmux/lib/libtmux/entity.rb#L84) | `::LibTmux::WindowSnapshot` | [Snapshot acquisition](behavior.md#snapshot-acquisition) | +| [#split](../../gems/libtmux/lib/libtmux/entity.rb#L270) | `::LibTmux::Pane` | [Creation](behavior.md#creation) | ## LibTmux::WindowLink | Method | Declared return | Contract | | --- | --- | --- | -| [#==](../../gems/libtmux/lib/libtmux/entity.rb#L78) | `bool` | [Live handles](behavior.md#live-handles) | -| [#display](../../gems/libtmux/lib/libtmux/entity.rb#L426) | `::LibTmux::CommandResult` | [Formats](behavior.md#formats) | -| [#eql?](../../gems/libtmux/lib/libtmux/entity.rb#L78) | `bool` | [Live handles](behavior.md#live-handles) | -| [#hash](../../gems/libtmux/lib/libtmux/entity.rb#L83) | `::Integer` | [Live handles](behavior.md#live-handles) | -| [#hooks](../../gems/libtmux/lib/libtmux/entity.rb#L434) | `::LibTmux::Hooks` | [Options and hooks](behavior.md#options-and-hooks) | -| [#id](../../gems/libtmux/lib/libtmux/entity.rb#L70) | `::String` | [Live handles](behavior.md#live-handles) | -| [#index](../../gems/libtmux/lib/libtmux/entity.rb#L389) | `::Integer` | [Live handles](behavior.md#live-handles) | -| [#inspect](../../gems/libtmux/lib/libtmux/entity.rb#L91) | `::String` | [Live handles](behavior.md#live-handles) | -| [#kill](../../gems/libtmux/lib/libtmux/entity.rb#L409) | `::LibTmux::CommandResult` | [Window links](behavior.md#window-links) | -| [#move](../../gems/libtmux/lib/libtmux/entity.rb#L413) | `::LibTmux::CommandResult` | [Window links](behavior.md#window-links) | -| [#options](../../gems/libtmux/lib/libtmux/entity.rb#L430) | `::LibTmux::Options` | [Options and hooks](behavior.md#options-and-hooks) | -| [#ref](../../gems/libtmux/lib/libtmux/entity.rb#L61) | `::LibTmux::EntityRef` | [Live handles](behavior.md#live-handles) | -| [#select](../../gems/libtmux/lib/libtmux/entity.rb#L401) | `::LibTmux::CommandResult` | [Window links](behavior.md#window-links) | -| [#server](../../gems/libtmux/lib/libtmux/entity.rb#L61) | `::LibTmux::Server` | [Live handles](behavior.md#live-handles) | -| [#session](../../gems/libtmux/lib/libtmux/entity.rb#L397) | `::LibTmux::Session` | [Live handles](behavior.md#live-handles) | -| [#snapshot](../../gems/libtmux/lib/libtmux/entity.rb#L74) | `::LibTmux::WindowLinkSnapshot` | [Snapshot acquisition](behavior.md#snapshot-acquisition) | -| [#swap](../../gems/libtmux/lib/libtmux/entity.rb#L420) | `::LibTmux::CommandResult` | [Window links](behavior.md#window-links) | -| [#unlink](../../gems/libtmux/lib/libtmux/entity.rb#L405) | `::LibTmux::CommandResult` | [Window links](behavior.md#window-links) | -| [#window](../../gems/libtmux/lib/libtmux/entity.rb#L393) | `::LibTmux::Window` | [Live handles](behavior.md#live-handles) | +| [#==](../../gems/libtmux/lib/libtmux/entity.rb#L88) | `bool` | [Live handles](behavior.md#live-handles) | +| [#display](../../gems/libtmux/lib/libtmux/entity.rb#L579) | `::LibTmux::CommandResult` | [Formats](behavior.md#formats) | +| [#eql?](../../gems/libtmux/lib/libtmux/entity.rb#L88) | `bool` | [Live handles](behavior.md#live-handles) | +| [#hash](../../gems/libtmux/lib/libtmux/entity.rb#L93) | `::Integer` | [Live handles](behavior.md#live-handles) | +| [#hooks](../../gems/libtmux/lib/libtmux/entity.rb#L597) | `::LibTmux::Hooks` | [Options and hooks](behavior.md#options-and-hooks) | +| [#id](../../gems/libtmux/lib/libtmux/entity.rb#L80) | `::String` | [Live handles](behavior.md#live-handles) | +| [#index](../../gems/libtmux/lib/libtmux/entity.rb#L506) | `::Integer` | [Live handles](behavior.md#live-handles) | +| [#inspect](../../gems/libtmux/lib/libtmux/entity.rb#L106) | `::String` | [Live handles](behavior.md#live-handles) | +| [#kill](../../gems/libtmux/lib/libtmux/entity.rb#L540) | `::LibTmux::CommandResult` | [Window links](behavior.md#window-links) | +| [#move](../../gems/libtmux/lib/libtmux/entity.rb#L551) | `::LibTmux::CommandResult` | [Window links](behavior.md#window-links) | +| [#options](../../gems/libtmux/lib/libtmux/entity.rb#L590) | `::LibTmux::Options` | [Options and hooks](behavior.md#options-and-hooks) | +| [#ref](../../gems/libtmux/lib/libtmux/entity.rb#L71) | `::LibTmux::EntityRef` | [Live handles](behavior.md#live-handles) | +| [#select](../../gems/libtmux/lib/libtmux/entity.rb#L518) | `::LibTmux::CommandResult` | [Window links](behavior.md#window-links) | +| [#server](../../gems/libtmux/lib/libtmux/entity.rb#L71) | `::LibTmux::Server` | [Live handles](behavior.md#live-handles) | +| [#session](../../gems/libtmux/lib/libtmux/entity.rb#L514) | `::LibTmux::Session` | [Live handles](behavior.md#live-handles) | +| [#snapshot](../../gems/libtmux/lib/libtmux/entity.rb#L84) | `::LibTmux::WindowLinkSnapshot` | [Snapshot acquisition](behavior.md#snapshot-acquisition) | +| [#swap](../../gems/libtmux/lib/libtmux/entity.rb#L567) | `::LibTmux::CommandResult` | [Window links](behavior.md#window-links) | +| [#unlink](../../gems/libtmux/lib/libtmux/entity.rb#L529) | `::LibTmux::CommandResult` | [Window links](behavior.md#window-links) | +| [#window](../../gems/libtmux/lib/libtmux/entity.rb#L510) | `::LibTmux::Window` | [Live handles](behavior.md#live-handles) | ## LibTmux::WindowLinkSnapshot | Method | Declared return | Contract | | --- | --- | --- | -| [#==](../../gems/libtmux/lib/libtmux/snapshot.rb#L40) | `bool` | [Captured records](behavior.md#captured-records) | -| [#active](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `bool` | [Captured records](behavior.md#captured-records) | -| [#active?](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `bool` | [Captured records](behavior.md#captured-records) | +| [#==](../../gems/libtmux/lib/libtmux/snapshot.rb#L44) | `bool` | [Captured records](behavior.md#captured-records) | +| [#active](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `bool` | [Captured records](behavior.md#captured-records) | +| [#active?](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `bool` | [Captured records](behavior.md#captured-records) | | [#capture_id](../../gems/libtmux/lib/libtmux/snapshot.rb#L10) | `::String` | [Captured records](behavior.md#captured-records) | -| [#eql?](../../gems/libtmux/lib/libtmux/snapshot.rb#L40) | `bool` | [Captured records](behavior.md#captured-records) | -| [#hash](../../gems/libtmux/lib/libtmux/snapshot.rb#L46) | `::Integer` | [Captured records](behavior.md#captured-records) | -| [#index](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `::Integer` | [Captured records](behavior.md#captured-records) | -| [#inspect](../../gems/libtmux/lib/libtmux/snapshot.rb#L50) | `::String` | [Captured records](behavior.md#captured-records) | -| [#raw](../../gems/libtmux/lib/libtmux/snapshot.rb#L34) | `::String?` | [Captured records](behavior.md#captured-records) | -| [#ref](../../gems/libtmux/lib/libtmux/snapshot.rb#L26) | `::LibTmux::EntityRef` | [Captured records](behavior.md#captured-records) | -| [#session](../../gems/libtmux/lib/libtmux/snapshot.rb#L152) | `::LibTmux::SessionSnapshot` | [Captured records](behavior.md#captured-records) | -| [#session_id](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `::String` | [Captured records](behavior.md#captured-records) | -| [#window](../../gems/libtmux/lib/libtmux/snapshot.rb#L152) | `::LibTmux::WindowSnapshot` | [Captured records](behavior.md#captured-records) | -| [#window_id](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `::String` | [Captured records](behavior.md#captured-records) | +| [#eql?](../../gems/libtmux/lib/libtmux/snapshot.rb#L44) | `bool` | [Captured records](behavior.md#captured-records) | +| [#hash](../../gems/libtmux/lib/libtmux/snapshot.rb#L50) | `::Integer` | [Captured records](behavior.md#captured-records) | +| [#index](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `::Integer` | [Captured records](behavior.md#captured-records) | +| [#inspect](../../gems/libtmux/lib/libtmux/snapshot.rb#L54) | `::String` | [Captured records](behavior.md#captured-records) | +| [#raw](../../gems/libtmux/lib/libtmux/snapshot.rb#L38) | `::String?` | [Captured records](behavior.md#captured-records) | +| [#ref](../../gems/libtmux/lib/libtmux/snapshot.rb#L29) | `::LibTmux::EntityRef` | [Captured records](behavior.md#captured-records) | +| [#session](../../gems/libtmux/lib/libtmux/snapshot.rb#L195) | `::LibTmux::SessionSnapshot` | [Captured records](behavior.md#captured-records) | +| [#session_id](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `::String` | [Captured records](behavior.md#captured-records) | +| [#window](../../gems/libtmux/lib/libtmux/snapshot.rb#L195) | `::LibTmux::WindowSnapshot` | [Captured records](behavior.md#captured-records) | +| [#window_id](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `::String` | [Captured records](behavior.md#captured-records) | ## LibTmux::WindowLinkWhere | Method | Declared return | Contract | | --- | --- | --- | -| [.build](../../gems/libtmux/lib/libtmux/criteria.rb#L405) | `::LibTmux::FilterExpr` | [Criteria](behavior.md#criteria) | +| [.build](../../gems/libtmux/lib/libtmux/criteria.rb#L512) | `::LibTmux::FilterExpr` | [Criteria](behavior.md#criteria) | ## LibTmux::WindowSnapshot | Method | Declared return | Contract | | --- | --- | --- | -| [#==](../../gems/libtmux/lib/libtmux/snapshot.rb#L40) | `bool` | [Captured records](behavior.md#captured-records) | -| [#active_pane](../../gems/libtmux/lib/libtmux/snapshot.rb#L152) | `::LibTmux::PaneSnapshot?` | [Captured records](behavior.md#captured-records) | +| [#==](../../gems/libtmux/lib/libtmux/snapshot.rb#L44) | `bool` | [Captured records](behavior.md#captured-records) | +| [#active_pane](../../gems/libtmux/lib/libtmux/snapshot.rb#L195) | `::LibTmux::PaneSnapshot?` | [Captured records](behavior.md#captured-records) | | [#capture_id](../../gems/libtmux/lib/libtmux/snapshot.rb#L10) | `::String` | [Captured records](behavior.md#captured-records) | -| [#eql?](../../gems/libtmux/lib/libtmux/snapshot.rb#L40) | `bool` | [Captured records](behavior.md#captured-records) | -| [#hash](../../gems/libtmux/lib/libtmux/snapshot.rb#L46) | `::Integer` | [Captured records](behavior.md#captured-records) | -| [#height](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `::Integer` | [Captured records](behavior.md#captured-records) | -| [#id](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `::String` | [Captured records](behavior.md#captured-records) | -| [#inspect](../../gems/libtmux/lib/libtmux/snapshot.rb#L50) | `::String` | [Captured records](behavior.md#captured-records) | -| [#layout](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `::String` | [Captured records](behavior.md#captured-records) | -| [#name](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `::String` | [Captured records](behavior.md#captured-records) | -| [#pane_count](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `::Integer` | [Captured records](behavior.md#captured-records) | -| [#panes](../../gems/libtmux/lib/libtmux/snapshot.rb#L152) | `::LibTmux::Selection[::LibTmux::PaneSnapshot]` | [Captured records](behavior.md#captured-records) | -| [#raw](../../gems/libtmux/lib/libtmux/snapshot.rb#L34) | `::String?` | [Captured records](behavior.md#captured-records) | -| [#ref](../../gems/libtmux/lib/libtmux/snapshot.rb#L26) | `::LibTmux::EntityRef` | [Captured records](behavior.md#captured-records) | -| [#width](../../gems/libtmux/lib/libtmux/snapshot.rb#L148) | `::Integer` | [Captured records](behavior.md#captured-records) | -| [#window_links](../../gems/libtmux/lib/libtmux/snapshot.rb#L152) | `::LibTmux::Selection[::LibTmux::WindowLinkSnapshot]` | [Captured records](behavior.md#captured-records) | +| [#eql?](../../gems/libtmux/lib/libtmux/snapshot.rb#L44) | `bool` | [Captured records](behavior.md#captured-records) | +| [#hash](../../gems/libtmux/lib/libtmux/snapshot.rb#L50) | `::Integer` | [Captured records](behavior.md#captured-records) | +| [#height](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `::Integer` | [Captured records](behavior.md#captured-records) | +| [#id](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `::String` | [Captured records](behavior.md#captured-records) | +| [#inspect](../../gems/libtmux/lib/libtmux/snapshot.rb#L54) | `::String` | [Captured records](behavior.md#captured-records) | +| [#layout](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `::String` | [Captured records](behavior.md#captured-records) | +| [#name](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `::String` | [Captured records](behavior.md#captured-records) | +| [#pane_count](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `::Integer` | [Captured records](behavior.md#captured-records) | +| [#panes](../../gems/libtmux/lib/libtmux/snapshot.rb#L195) | `::LibTmux::Selection[::LibTmux::PaneSnapshot]` | [Captured records](behavior.md#captured-records) | +| [#raw](../../gems/libtmux/lib/libtmux/snapshot.rb#L38) | `::String?` | [Captured records](behavior.md#captured-records) | +| [#ref](../../gems/libtmux/lib/libtmux/snapshot.rb#L29) | `::LibTmux::EntityRef` | [Captured records](behavior.md#captured-records) | +| [#width](../../gems/libtmux/lib/libtmux/snapshot.rb#L189) | `::Integer` | [Captured records](behavior.md#captured-records) | +| [#window_links](../../gems/libtmux/lib/libtmux/snapshot.rb#L195) | `::LibTmux::Selection[::LibTmux::WindowLinkSnapshot]` | [Captured records](behavior.md#captured-records) | ## LibTmux::WindowWhere | Method | Declared return | Contract | | --- | --- | --- | -| [.build](../../gems/libtmux/lib/libtmux/criteria.rb#L405) | `::LibTmux::FilterExpr` | [Criteria](behavior.md#criteria) | +| [.build](../../gems/libtmux/lib/libtmux/criteria.rb#L512) | `::LibTmux::FilterExpr` | [Criteria](behavior.md#criteria) | ## LibTmux::Workspace | Method | Declared return | Contract | | --- | --- | --- | -| [#inspect](../../gems/libtmux-workspace/lib/libtmux/workspace.rb#L74) | `::String` | [Workspace parsing](behavior.md#workspace-parsing) | -| [#plan](../../gems/libtmux-workspace/lib/libtmux/workspace.rb#L70) | `::LibTmux::Workspace::Plan` | [Workspace parsing](behavior.md#workspace-parsing) | -| [#to_h](../../gems/libtmux-workspace/lib/libtmux/workspace.rb#L66) | `::Hash[::String, untyped]` | [Workspace parsing](behavior.md#workspace-parsing) | -| [.load](../../gems/libtmux-workspace/lib/libtmux/workspace.rb#L23) | `::LibTmux::Workspace` | [Workspace parsing](behavior.md#workspace-parsing) | -| [.parse](../../gems/libtmux-workspace/lib/libtmux/workspace.rb#L46) | `::LibTmux::Workspace` | [Workspace parsing](behavior.md#workspace-parsing) | +| [#inspect](../../gems/libtmux-workspace/lib/libtmux/workspace.rb#L114) | `::String` | [Workspace parsing](behavior.md#workspace-parsing) | +| [#plan](../../gems/libtmux-workspace/lib/libtmux/workspace.rb#L110) | `::LibTmux::Workspace::Plan` | [Workspace parsing](behavior.md#workspace-parsing) | +| [#to_h](../../gems/libtmux-workspace/lib/libtmux/workspace.rb#L106) | `::Hash[::String, untyped]` | [Workspace parsing](behavior.md#workspace-parsing) | +| [.load](../../gems/libtmux-workspace/lib/libtmux/workspace.rb#L35) | `::LibTmux::Workspace` | [Workspace parsing](behavior.md#workspace-parsing) | +| [.parse](../../gems/libtmux-workspace/lib/libtmux/workspace.rb#L74) | `::LibTmux::Workspace` | [Workspace parsing](behavior.md#workspace-parsing) | ## LibTmux::Workspace::ApplyError @@ -1166,13 +1166,13 @@ type checking. See [signature proof](behavior.md#signature-proof). | [#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) | -| [#failure_class](../../gems/libtmux-workspace/lib/libtmux/workspace/apply.rb#L43) | `::String` | [Workspace results](behavior.md#workspace-results) | +| [#failure_class](../../gems/libtmux-workspace/lib/libtmux/workspace/apply.rb#L75) | `::String` | [Workspace results](behavior.md#workspace-results) | | [#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) | -| [#result](../../gems/libtmux-workspace/lib/libtmux/workspace/apply.rb#L43) | `::LibTmux::Workspace::ApplyResult` | [Workspace results](behavior.md#workspace-results) | +| [#result](../../gems/libtmux-workspace/lib/libtmux/workspace/apply.rb#L75) | `::LibTmux::Workspace::ApplyResult` | [Workspace results](behavior.md#workspace-results) | | [#text](../../gems/libtmux/lib/libtmux/errors.rb#L5) | `::String?` | [Errors](behavior.md#errors) | -| [.new](../../gems/libtmux-workspace/lib/libtmux/workspace/apply.rb#L45) | `::LibTmux::Workspace::ApplyError` | [Workspace results](behavior.md#workspace-results) | +| [.new](../../gems/libtmux-workspace/lib/libtmux/workspace/apply.rb#L77) | `::LibTmux::Workspace::ApplyError` | [Workspace results](behavior.md#workspace-results) | ## LibTmux::Workspace::ApplyResult @@ -1185,10 +1185,10 @@ type checking. See [signature proof](behavior.md#signature-proof). | [#effects](../../gems/libtmux-workspace/lib/libtmux/workspace/apply.rb#L7) | `::Array[::LibTmux::Workspace::ApplyResult::Effect]` | [Workspace results](behavior.md#workspace-results) | | [#failed_action](../../gems/libtmux-workspace/lib/libtmux/workspace/apply.rb#L7) | `::Symbol?` | [Workspace results](behavior.md#workspace-results) | | [#failed_step](../../gems/libtmux-workspace/lib/libtmux/workspace/apply.rb#L7) | `::Integer?` | [Workspace results](behavior.md#workspace-results) | -| [#inspect](../../gems/libtmux-workspace/lib/libtmux/workspace/apply.rb#L27) | `::String` | [Workspace results](behavior.md#workspace-results) | -| [#success?](../../gems/libtmux-workspace/lib/libtmux/workspace/apply.rb#L19) | `bool` | [Workspace results](behavior.md#workspace-results) | -| [#to_h](../../gems/libtmux-workspace/lib/libtmux/workspace/apply.rb#L31) | `::Hash[::String, untyped]` | [Workspace results](behavior.md#workspace-results) | -| [#uncertain?](../../gems/libtmux-workspace/lib/libtmux/workspace/apply.rb#L23) | `bool` | [Workspace results](behavior.md#workspace-results) | +| [#inspect](../../gems/libtmux-workspace/lib/libtmux/workspace/apply.rb#L45) | `::String` | [Workspace results](behavior.md#workspace-results) | +| [#success?](../../gems/libtmux-workspace/lib/libtmux/workspace/apply.rb#L37) | `bool` | [Workspace results](behavior.md#workspace-results) | +| [#to_h](../../gems/libtmux-workspace/lib/libtmux/workspace/apply.rb#L49) | `::Hash[::String, untyped]` | [Workspace results](behavior.md#workspace-results) | +| [#uncertain?](../../gems/libtmux-workspace/lib/libtmux/workspace/apply.rb#L41) | `bool` | [Workspace results](behavior.md#workspace-results) | ## LibTmux::Workspace::ApplyResult::Effect @@ -1206,7 +1206,7 @@ type checking. See [signature proof](behavior.md#signature-proof). | Method | Declared return | Contract | | --- | --- | --- | -| [#run](../../gems/libtmux-workspace/lib/libtmux/workspace/cli.rb#L21) | `::Integer` | [Workspace CLI](behavior.md#workspace-cli) | +| [#run](../../gems/libtmux-workspace/lib/libtmux/workspace/cli.rb#L26) | `::Integer` | [Workspace CLI](behavior.md#workspace-cli) | | [.run](../../gems/libtmux-workspace/lib/libtmux/workspace/cli.rb#L10) | `::Integer` | [Workspace CLI](behavior.md#workspace-cli) | ## LibTmux::Workspace::ConfigError @@ -1221,7 +1221,7 @@ type checking. See [signature proof](behavior.md#signature-proof). | [#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-workspace/lib/libtmux/workspace.rb#L17) | `::LibTmux::Workspace::ConfigError` | [Workspace parsing](behavior.md#workspace-parsing) | +| [.new](../../gems/libtmux-workspace/lib/libtmux/workspace.rb#L23) | `::LibTmux::Workspace::ConfigError` | [Workspace parsing](behavior.md#workspace-parsing) | ## LibTmux::Workspace::ConflictError @@ -1241,13 +1241,13 @@ type checking. See [signature proof](behavior.md#signature-proof). | Method | Declared return | Contract | | --- | --- | --- | -| [#apply](../../gems/libtmux-workspace/lib/libtmux/workspace/plan.rb#L44) | `::LibTmux::Workspace::ApplyResult` | [Workspace apply](behavior.md#workspace-apply) | -| [#inspect](../../gems/libtmux-workspace/lib/libtmux/workspace/plan.rb#L40) | `::String` | [Workspace plans](behavior.md#workspace-plans) | -| [#mode](../../gems/libtmux-workspace/lib/libtmux/workspace/plan.rb#L11) | `:offline_create \| :captured_create` | [Workspace plans](behavior.md#workspace-plans) | -| [#preconditions](../../gems/libtmux-workspace/lib/libtmux/workspace/plan.rb#L11) | `::Hash[::String, ::String?]` | [Workspace plans](behavior.md#workspace-plans) | -| [#steps](../../gems/libtmux-workspace/lib/libtmux/workspace/plan.rb#L11) | `::Array[::LibTmux::Workspace::Plan::Step]` | [Workspace plans](behavior.md#workspace-plans) | -| [#to_h](../../gems/libtmux-workspace/lib/libtmux/workspace/plan.rb#L31) | `::Hash[::String, untyped]` | [Workspace plans](behavior.md#workspace-plans) | -| [.new](../../gems/libtmux-workspace/lib/libtmux/workspace/plan.rb#L13) | `::LibTmux::Workspace::Plan` | [Workspace plans](behavior.md#workspace-plans) | +| [#apply](../../gems/libtmux-workspace/lib/libtmux/workspace/plan.rb#L65) | `::LibTmux::Workspace::ApplyResult` | [Workspace apply](behavior.md#workspace-apply) | +| [#inspect](../../gems/libtmux-workspace/lib/libtmux/workspace/plan.rb#L61) | `::String` | [Workspace plans](behavior.md#workspace-plans) | +| [#mode](../../gems/libtmux-workspace/lib/libtmux/workspace/plan.rb#L12) | `:offline_create \| :captured_create` | [Workspace plans](behavior.md#workspace-plans) | +| [#preconditions](../../gems/libtmux-workspace/lib/libtmux/workspace/plan.rb#L12) | `::Hash[::String, ::String?]` | [Workspace plans](behavior.md#workspace-plans) | +| [#steps](../../gems/libtmux-workspace/lib/libtmux/workspace/plan.rb#L12) | `::Array[::LibTmux::Workspace::Plan::Step]` | [Workspace plans](behavior.md#workspace-plans) | +| [#to_h](../../gems/libtmux-workspace/lib/libtmux/workspace/plan.rb#L41) | `::Hash[::String, untyped]` | [Workspace plans](behavior.md#workspace-plans) | +| [.new](../../gems/libtmux-workspace/lib/libtmux/workspace/plan.rb#L14) | `::LibTmux::Workspace::Plan` | [Workspace plans](behavior.md#workspace-plans) | ## LibTmux::Workspace::Plan::Step @@ -1256,7 +1256,7 @@ type checking. See [signature proof](behavior.md#signature-proof). | [#arguments](../../gems/libtmux-workspace/lib/libtmux/workspace/plan.rb#L6) | `::Hash[::String, untyped]` | [Workspace plans](behavior.md#workspace-plans) | | [#effect](../../gems/libtmux-workspace/lib/libtmux/workspace/plan.rb#L6) | `::Symbol` | [Workspace plans](behavior.md#workspace-plans) | | [#id](../../gems/libtmux-workspace/lib/libtmux/workspace/plan.rb#L6) | `::Integer` | [Workspace plans](behavior.md#workspace-plans) | -| [#inspect](../../gems/libtmux-workspace/lib/libtmux/workspace/plan.rb#L7) | `::String` | [Workspace plans](behavior.md#workspace-plans) | +| [#inspect](../../gems/libtmux-workspace/lib/libtmux/workspace/plan.rb#L8) | `::String` | [Workspace plans](behavior.md#workspace-plans) | | [#operation](../../gems/libtmux-workspace/lib/libtmux/workspace/plan.rb#L6) | `::Symbol` | [Workspace plans](behavior.md#workspace-plans) | | [#produces](../../gems/libtmux-workspace/lib/libtmux/workspace/plan.rb#L6) | `::Array[::String]` | [Workspace plans](behavior.md#workspace-plans) | | [#target](../../gems/libtmux-workspace/lib/libtmux/workspace/plan.rb#L6) | `::String` | [Workspace plans](behavior.md#workspace-plans) | diff --git a/docs/reference/behavior.md b/docs/reference/behavior.md index f9e7d173..aa4163f7 100644 --- a/docs/reference/behavior.md +++ b/docs/reference/behavior.md @@ -655,10 +655,10 @@ position = catalog.options.fetch("status-position") created = catalog.hooks.fetch("pane-created") puts "tmux source: #{catalog.tmux_version}" -puts "history-limit: #{history.type}, #{history.scopes.join(', ')}, " \ - "#{history.range}" -puts "status-position: #{position.choices.join(', ')}" -puts "pane-created: #{created.scopes.join(', ')}" +puts "history-limit: #{history.type}, #{history.scopes.join(", ")}, " \ + "#{history.range}" +puts "status-position: #{position.choices.join(", ")}" +puts "pane-created: #{created.scopes.join(", ")}" ``` @@ -1259,16 +1259,21 @@ require "libtmux" require "rbconfig" command = [ - RbConfig.ruby, "-e", "warn ARGV.fetch(0); exit 7", + 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:") +diagnostic = + result + .screen + .lines(chomp: true) + .find { |line| line.start_with?("Migration stopped:") } +unless result.exit_status == 7 && diagnostic + raise "Expected a migration failure with a diagnostic" end -raise "Expected a migration failure with a diagnostic" unless - result.exit_status == 7 && diagnostic puts "Exit #{result.exit_status}. #{diagnostic}" ``` @@ -1294,8 +1299,14 @@ LibTmux::Server.start do |server| 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 + reply = + result + .screen + .lines(chomp: true) + .find { |line| line == "Received: café" } + unless reply && result.exit_status == 0 + raise "Missing confirmation from the program" + end puts reply end end diff --git a/docs/releasing.md b/docs/releasing.md index f70c7d14..9e39f8ad 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -66,7 +66,8 @@ Commit the preparation changes. From that clean commit, build and exercise the prospective release without a tag or registry access: ```console -$ /usr/bin/time -p mise exec -- bundle exec rake 'release:dry_run[v]' +$ /usr/bin/time -p \ + mise exec -- bundle exec rake 'release:dry_run[v]' ``` This builds all four gems into `pkg/release/`, records their source commit @@ -102,7 +103,8 @@ normal checks passed on master; the release workflow itself runs the whole table on the tag before it publishes: ```console -$ mise exec -- bundle exec scripts/release/release-ci check "$(git rev-parse HEAD)" +$ mise exec -- bundle exec scripts/release/release-ci check \ + "$(git rev-parse HEAD)" ``` Create the annotated version tag: diff --git a/examples/api/async_capabilities.rb b/examples/api/async_capabilities.rb index eaba08f2..f106cf82 100644 --- a/examples/api/async_capabilities.rb +++ b/examples/api/async_capabilities.rb @@ -9,7 +9,8 @@ Async do |parent| LibTmux::Async.open(parent: parent, server: server) do |scope| report = scope.server.capabilities - puts "Control mode requires tmux #{report.feature('control-mode').since}" + control = report.feature("control-mode") + puts "Control mode requires tmux #{control.since}" end end.wait end diff --git a/examples/api/async_control.rb b/examples/api/async_control.rb index b64f054c..48e6431e 100644 --- a/examples/api/async_control.rb +++ b/examples/api/async_control.rb @@ -10,14 +10,18 @@ window = session.list_windows.fetch(0) Async do |parent| LibTmux::Async.open(parent: parent, server: server) do |scope| - scope.server.open_control(session: session.ref) do |control| - reply = control.exchange("display-message -p ready", timeout: 5) - puts "reply: #{reply.blocks.last.body.strip}" - events = control.events - window.rename("renamed") - event = events.next(timeout: 5) until event&.raw&.start_with?("%window-renamed") - puts "event: #{event.raw.strip}" - end + scope + .server + .open_control(session: session.ref) do |control| + reply = control.exchange("display-message -p ready", timeout: 5) + puts "reply: #{reply.blocks.last.body.strip}" + events = control.events + window.rename("renamed") + event = events.next(timeout: 5) until event&.raw&.start_with?( + "%window-renamed" + ) + puts "event: #{event.raw.strip}" + end end end.wait end diff --git a/examples/api/async_run.rb b/examples/api/async_run.rb index e32f352a..4f0dbd76 100644 --- a/examples/api/async_run.rb +++ b/examples/api/async_run.rb @@ -9,11 +9,12 @@ server.new_session(name: "work", command: ["/bin/cat"]) Async do |parent| LibTmux::Async.open(parent: parent, server: server) do |scope| - waiting = parent.async do - scope.server.run(["wait-for", "-S", "ready", ";", "wait-for", "held"], timeout: 5) - rescue LibTmux::Cancelled => error - error - end + waiting = + parent.async do + scope.server.run(%w[wait-for -S ready ; wait-for held], timeout: 5) + rescue LibTmux::Cancelled => error + error + end scope.server.wait_for("ready", timeout: 5) waiting.cancel failure = waiting.wait diff --git a/examples/api/async_scope.rb b/examples/api/async_scope.rb index 280d42b5..a7d638c2 100644 --- a/examples/api/async_scope.rb +++ b/examples/api/async_scope.rb @@ -11,9 +11,10 @@ Async do |parent| LibTmux::Async.open(parent: parent, server: server) do |scope| refs = scope.server.list_panes.map(&:ref) - screens = scope.map(refs, concurrency: 2) do |ref| - scope.server.pane(ref).capture - end + screens = + scope.map(refs, concurrency: 2) do |ref| + scope.server.pane(ref).capture + end puts "captured panes: #{screens.length}" puts "all succeeded: #{screens.all?(&:success?)}" end diff --git a/examples/api/cancellation.rb b/examples/api/cancellation.rb index 16f26abf..1159c66f 100644 --- a/examples/api/cancellation.rb +++ b/examples/api/cancellation.rb @@ -7,12 +7,16 @@ LibTmux::Server.start do |server| server.new_session(name: "work", command: ["/bin/cat"]) cancellation = LibTmux::Cancellation.new - waiting = Thread.new do - server.run(["wait-for", "-S", "ready", ";", "wait-for", "held"], - timeout: 5, cancel: cancellation) - rescue LibTmux::Cancelled => error - error - end + waiting = + Thread.new do + server.run( + %w[wait-for -S ready ; wait-for held], + timeout: 5, + cancel: cancellation + ) + rescue LibTmux::Cancelled => error + error + end server.wait_for("ready", timeout: 5) cancellation.cancel failure = waiting.value diff --git a/examples/api/capture.rb b/examples/api/capture.rb index a4b3f8f5..cb2840d0 100644 --- a/examples/api/capture.rb +++ b/examples/api/capture.rb @@ -16,7 +16,7 @@ def wait_until(message) end end -command = [RbConfig.ruby, "-e", <<~'RUBY'] +greeting_command = [RbConfig.ruby, "-e", <<~'RUBY'] $stdout.sync = true puts "What is your name?" name = STDIN.gets or exit 1 @@ -25,9 +25,12 @@ def wait_until(message) LibTmux::Server.start do |server| server.options(scope: :window).set("remain-on-exit", true) - pane = server.new_session( - name: "greeting", command: command, receipt: true - ).pane + pane = + server.new_session( + name: "greeting", + command: greeting_command, + receipt: true + ).pane wait_until("CLI did not prompt for a name") do |remaining| lines = pane.capture(timeout: remaining).text.lines(chomp: true) @@ -36,15 +39,19 @@ def wait_until(message) pane.send_text("Ada") pane.send_keys("Enter") - status = wait_until("CLI did not report an exit status") do |remaining| - state = pane.snapshot(timeout: remaining) - state.dead_status if state.dead? - end + status = + wait_until("CLI did not report an exit status") do |remaining| + state = pane.snapshot(timeout: remaining) + state.dead_status if state.dead? + end raise "CLI exited with status #{status}" unless status == 0 - greeting = pane.capture(start: "-").text.lines(chomp: true).find do |line| - line == "Hello, Ada!" - end + greeting = + pane + .capture(start: "-") + .text + .lines(chomp: true) + .find { |line| line == "Hello, Ada!" } raise "CLI did not greet Ada" unless greeting puts greeting end diff --git a/examples/api/explain_panes.rb b/examples/api/explain_panes.rb index 91ec37dc..94f3bd0c 100644 --- a/examples/api/explain_panes.rb +++ b/examples/api/explain_panes.rb @@ -6,11 +6,11 @@ LibTmux::Server.start do |server| server.new_session(name: "work", command: ["/bin/cat"]) - criteria = {active: true} + criteria = { active: true } plan = server.explain_panes(where: criteria) puts "tmux reads: #{plan.fetch(:capture)}" - puts "tmux filters: #{plan.fetch(:pushed) || 'nothing'}" - puts "Ruby filters: #{plan.fetch(:residual).fetch('where').keys.join(', ')}" + puts "tmux filters: #{plan.fetch(:pushed) || "nothing"}" + puts "Ruby filters: #{plan.fetch(:residual).fetch("where").keys.join(", ")}" puts "matching panes: #{server.search_panes(where: criteria).length}" end # docs:end main diff --git a/examples/api/link_window.rb b/examples/api/link_window.rb index b8a913a4..bd3a312b 100644 --- a/examples/api/link_window.rb +++ b/examples/api/link_window.rb @@ -10,8 +10,8 @@ session.link_window(window.ref, index: 4) session.link_window(window.ref, index: 9) links = session.list_window_links - puts "indexes: #{links.map(&:index).join(', ')}" - puts "windows: #{links.map { |link| link.window.id }.uniq.join(', ')}" + puts "indexes: #{links.map(&:index).join(", ")}" + puts "windows: #{links.map { |link| link.window.id }.uniq.join(", ")}" end # docs:end main rescue StandardError => error diff --git a/examples/api/list_panes.rb b/examples/api/list_panes.rb index ec10d76c..879b6b03 100644 --- a/examples/api/list_panes.rb +++ b/examples/api/list_panes.rb @@ -4,7 +4,8 @@ begin LibTmux::Server.start do |server| - work = server.new_session(name: "work", command: ["/bin/cat"], receipt: true) + work = + server.new_session(name: "work", command: ["/bin/cat"], receipt: true) work.pane.split(direction: :horizontal, command: ["/bin/cat"]) server.new_session(name: "other", command: ["/bin/cat"]) puts "server panes: #{server.list_panes.length}" diff --git a/examples/api/list_sessions.rb b/examples/api/list_sessions.rb index 4f4b1d36..dcdca4cb 100644 --- a/examples/api/list_sessions.rb +++ b/examples/api/list_sessions.rb @@ -8,7 +8,7 @@ server.new_session(name: "work", command: ["/bin/cat"]) server.new_session(name: "logs", command: ["/bin/cat"]) sessions = server.list_sessions - puts "sessions: #{sessions.map(&:id).sort.join(', ')}" + puts "sessions: #{sessions.map(&:id).sort.join(", ")}" end # docs:end main rescue StandardError => error diff --git a/examples/api/new_session.rb b/examples/api/new_session.rb index 392ded2a..7ccc2c82 100644 --- a/examples/api/new_session.rb +++ b/examples/api/new_session.rb @@ -5,9 +5,13 @@ require "libtmux" LibTmux::Server.start do |server| - created = server.new_session( - name: "work", window_name: "main", command: ["/bin/cat"], receipt: true - ) + created = + server.new_session( + name: "work", + window_name: "main", + command: ["/bin/cat"], + receipt: true + ) ref = created.entity.ref puts "session: #{ref.id}" puts "name: #{server.session(ref).snapshot.name}" diff --git a/examples/api/option_catalog.rb b/examples/api/option_catalog.rb index 83362144..a62624bf 100644 --- a/examples/api/option_catalog.rb +++ b/examples/api/option_catalog.rb @@ -9,8 +9,8 @@ created = catalog.hooks.fetch("pane-created") puts "tmux source: #{catalog.tmux_version}" -puts "history-limit: #{history.type}, #{history.scopes.join(', ')}, " \ - "#{history.range}" -puts "status-position: #{position.choices.join(', ')}" -puts "pane-created: #{created.scopes.join(', ')}" +puts "history-limit: #{history.type}, #{history.scopes.join(", ")}, " \ + "#{history.range}" +puts "status-position: #{position.choices.join(", ")}" +puts "pane-created: #{created.scopes.join(", ")}" # docs:end main diff --git a/examples/api/options.rb b/examples/api/options.rb index 11d1ade1..1f372485 100644 --- a/examples/api/options.rb +++ b/examples/api/options.rb @@ -11,7 +11,7 @@ puts "history-limit: #{limit.as(:integer)}" puts "inherited: #{limit.inherited?}" session.hooks.set("after-new-window", command: "display-message created") - puts "hook: #{session.hooks.get('after-new-window').as(:string)}" + puts "hook: #{session.hooks.get("after-new-window").as(:string)}" end # docs:end main rescue StandardError => error diff --git a/examples/api/owned_program.rb b/examples/api/owned_program.rb index c3cf5500..c8734c8b 100644 --- a/examples/api/owned_program.rb +++ b/examples/api/owned_program.rb @@ -6,16 +6,21 @@ require "rbconfig" command = [ - RbConfig.ruby, "-e", "warn ARGV.fetch(0); exit 7", + 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:") + diagnostic = + result + .screen + .lines(chomp: true) + .find { |line| line.start_with?("Migration stopped:") } + unless result.exit_status == 7 && diagnostic + raise "Expected a migration failure with a diagnostic" end - raise "Expected a migration failure with a diagnostic" unless - result.exit_status == 7 && diagnostic puts "Exit #{result.exit_status}. #{diagnostic}" # docs:end main diff --git a/examples/api/owned_program_input.rb b/examples/api/owned_program_input.rb index 58d2ee4f..3d54e064 100644 --- a/examples/api/owned_program_input.rb +++ b/examples/api/owned_program_input.rb @@ -11,8 +11,14 @@ 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 + reply = + result + .screen + .lines(chomp: true) + .find { |line| line == "Received: café" } + unless reply && result.exit_status == 0 + raise "Missing confirmation from the program" + end puts reply end end diff --git a/examples/api/query.rb b/examples/api/query.rb index 57ac714e..91119a64 100644 --- a/examples/api/query.rb +++ b/examples/api/query.rb @@ -5,14 +5,15 @@ require "libtmux" LibTmux::Server.start do |server| - work = server.new_session(name: "work", command: ["/bin/cat"], receipt: true) + work = + server.new_session(name: "work", command: ["/bin/cat"], receipt: true) server.new_session(name: "logs", command: ["/bin/cat"]) snapshot = server.snapshot session = snapshot.sessions.where(name: "work").one puts "matching session: #{session.name}" missing = snapshot.sessions.one_or_nil(name: "missing") puts "missing session: #{missing.nil?}" - panes = server.search_panes(where: {id: work.pane.id}) + panes = server.search_panes(where: { id: work.pane.id }) puts "matching pane: #{panes.one.id}" end # docs:end main diff --git a/examples/api/run_group.rb b/examples/api/run_group.rb index e8135d59..4c286bb6 100644 --- a/examples/api/run_group.rb +++ b/examples/api/run_group.rb @@ -6,14 +6,18 @@ LibTmux::Server.start do |server| server.new_session(name: "work", command: ["/bin/cat"]) - group = server.run_group([ - ["set-option", "-g", "@before", "kept"], - ["select-pane", "-t", "%4294967294"], - ["set-option", "-g", "@after", "never run"] - ]) + group = + server.run_group( + [ + %w[set-option -g @before kept], + %w[select-pane -t %4294967294], + ["set-option", "-g", "@after", "never run"] + ] + ) puts "success: #{group.success?}" - puts "steps: #{group.steps.map { |step| step.fetch(:outcome) }.join(', ')}" - puts "@before: #{server.options(scope: :session).get('@before').as(:string)}" + puts "steps: #{group.steps.map { |step| step.fetch(:outcome) }.join(", ")}" + before = server.options(scope: :session).get("@before").as(:string) + puts "@before: #{before}" end # docs:end main rescue StandardError => error diff --git a/examples/api/run_to_exit.rb b/examples/api/run_to_exit.rb index 2c8060f6..ca121dfb 100644 --- a/examples/api/run_to_exit.rb +++ b/examples/api/run_to_exit.rb @@ -8,17 +8,19 @@ hooks = server.hooks(scope: :session) hooks.set("pane-died", command: "wait-for -S build-finished") worker = [RbConfig.ruby, "-e", "warn ARGV.fetch(0); exit 7", "Missing résumé"] - pane = server.new_session( - name: "build", command: worker, receipt: true - ).pane + pane = server.new_session(name: "build", command: worker, receipt: true).pane server.wait_for("build-finished", timeout: 5) state = pane.snapshot - raise "Build pane did not report an exit status" unless state.dead? && state.dead_status + unless state.dead? && state.dead_status + raise "Build pane did not report an exit status" + end lines = pane.capture(start: "-").text.lines(chomp: true) diagnostic = lines.find { |line| line == "Missing résumé" } - raise "Expected the failed build and its diagnostic" unless state.dead_status == 7 && diagnostic + unless state.dead_status == 7 && diagnostic + raise "Expected the failed build and its diagnostic" + end puts "Exit #{state.dead_status}: #{diagnostic}" end diff --git a/examples/api/select_layout.rb b/examples/api/select_layout.rb index 13a4de4b..6afb4589 100644 --- a/examples/api/select_layout.rb +++ b/examples/api/select_layout.rb @@ -3,9 +3,14 @@ require "libtmux" LibTmux::Server.start do |server| - created = server.new_session( - name: "work", command: ["/bin/cat"], width: 81, height: 24, receipt: true - ) + created = + server.new_session( + name: "work", + command: ["/bin/cat"], + width: 81, + height: 24, + receipt: true + ) window = created.window window.split(direction: :vertical, command: ["/bin/cat"]) window.select_layout(:even_horizontal) @@ -14,5 +19,5 @@ widths = layout.panes.map(&:width) full_height = layout.panes.all? { |pane| pane.height == layout.height } raise "Expected two equal columns" unless widths == [40, 40] && full_height - puts "Pane widths: #{widths.join(', ')}" + puts "Pane widths: #{widths.join(", ")}" end diff --git a/examples/api/split_resize.rb b/examples/api/split_resize.rb index 93df034b..25746f41 100644 --- a/examples/api/split_resize.rb +++ b/examples/api/split_resize.rb @@ -13,9 +13,7 @@ pane.send_keys("Enter") line = nil 50.times do - line = pane.capture.text.lines(chomp: true).find do |text| - text == "café" - end + line = pane.capture.text.lines(chomp: true).find { |text| text == "café" } break if line sleep 0.1 end diff --git a/examples/api/text_wait.rb b/examples/api/text_wait.rb index 739916d3..6d69e314 100644 --- a/examples/api/text_wait.rb +++ b/examples/api/text_wait.rb @@ -10,13 +10,21 @@ RUBY LibTmux::Server.start do |server| - pane = server.new_session(name: "reply", command: [Gem.ruby, "-e", program], - receipt: true).pane + pane = + server.new_session( + name: "reply", + command: [Gem.ruby, "-e", program], + receipt: true + ).pane pane.send_text("green") pane.send_keys("Enter") reply = "Reply from the fixture" result = pane.wait_for_text(reply) - puts result.text.lines(chomp: true).map(&:rstrip).find { |line| line == reply } + puts result + .text + .lines(chomp: true) + .map(&:rstrip) + .find { |line| line == reply } end # docs:end main diff --git a/examples/api/workspace_apply.rb b/examples/api/workspace_apply.rb index 2fb49adf..1e3087d2 100644 --- a/examples/api/workspace_apply.rb +++ b/examples/api/workspace_apply.rb @@ -29,7 +29,7 @@ result = plan.apply(server: server) puts "applied: #{result.success?}" sessions = server.list_sessions.map { |session| session.snapshot.name } - puts "sessions: #{sessions.join(', ')}" + puts "sessions: #{sessions.join(", ")}" end end # docs:end main diff --git a/examples/api/workspace_failure.rb b/examples/api/workspace_failure.rb index c72e021d..f7c7b756 100644 --- a/examples/api/workspace_failure.rb +++ b/examples/api/workspace_failure.rb @@ -8,19 +8,25 @@ LibTmux::Server.start do |server| server.new_session(name: "borrowed", command: ["/bin/cat"]) - document = {session_name: "crowded", - windows: [{window_name: "small", panes: Array.new(40) { {} }}]} - crowded = LibTmux::Workspace.parse(JSON.generate(document), - format: :json, base_directory: __dir__) + document = { + session_name: "crowded", + windows: [{ window_name: "small", panes: Array.new(40) { {} } }] + } + crowded = + LibTmux::Workspace.parse( + JSON.generate(document), + format: :json, + base_directory: __dir__ + ) begin crowded.plan.apply(server: server, compensate: true) rescue LibTmux::Workspace::ApplyError => error puts "failed action: #{error.result.failed_action}" - puts "created a session: #{error.result.created_refs.key?('session')}" + puts "created a session: #{error.result.created_refs.key?("session")}" puts "compensation: #{error.result.compensation}" end sessions = server.list_sessions.map { |session| session.snapshot.name } - puts "sessions: #{sessions.join(', ')}" + puts "sessions: #{sessions.join(", ")}" end # docs:end main rescue StandardError => error diff --git a/examples/async_cancel.rb b/examples/async_cancel.rb index 16b6fa5e..5d591540 100644 --- a/examples/async_cancel.rb +++ b/examples/async_cancel.rb @@ -8,17 +8,18 @@ server.new_session(name: "async", command: ["/bin/cat"]) Async do |parent| LibTmux::Async.open(parent: parent, server: server) do |scope| - waiting = parent.async do - scope.server.run(["wait-for", "-S", "ready", ";", "wait-for", "held"], - timeout: 5) - rescue LibTmux::Cancelled => error - error - end + waiting = + parent.async do + scope.server.run(%w[wait-for -S ready ; wait-for held], timeout: 5) + rescue LibTmux::Cancelled => error + error + end scope.server.wait_for("ready", timeout: 5) panes = scope.server.list_panes.map(&:ref) - captures = scope.map(panes, concurrency: 2) do |ref| - scope.server.pane(ref).capture - end + captures = + scope.map(panes, concurrency: 2) do |ref| + scope.server.pane(ref).capture + end raise "A pane capture failed" unless captures.all?(&:success?) puts "captures: #{captures.length}" diff --git a/examples/cancel.rb b/examples/cancel.rb index eb073131..249ddd57 100644 --- a/examples/cancel.rb +++ b/examples/cancel.rb @@ -9,19 +9,31 @@ cancellation = LibTmux::Cancellation.new waiting = nil begin - waiting = Thread.new do - server.run(["wait-for", "-S", "ready", ";", "wait-for", "held"], - timeout: 0.5, cancel: cancellation) - rescue LibTmux::Cancelled => error - error - end + waiting = + Thread.new do + server.run( + %w[wait-for -S ready ; wait-for held], + timeout: 0.5, + cancel: cancellation + ) + rescue LibTmux::Cancelled => error + error + end server.wait_for("ready", timeout: 0.5) cancellation.cancel failure = waiting.value Example.check(failure.is_a?(LibTmux::Cancelled), "cancellation lost") - Example.check(failure.delivery == :possibly_sent, "a cancelled command was reported as not sent") - Example.raises(Errno::ECHILD) { Process.waitpid(failure.pid, Process::WNOHANG) } - Example.check(server.diagnostics.fetch(:admitted_requests).zero?, "client remains admitted") + Example.check( + failure.delivery == :possibly_sent, + "a cancelled command was reported as not sent" + ) + Example.raises(Errno::ECHILD) do + Process.waitpid(failure.pid, Process::WNOHANG) + end + Example.check( + server.diagnostics.fetch(:admitted_requests).zero?, + "client remains admitted" + ) ensure begin cancellation.cancel diff --git a/examples/control_overflow.rb b/examples/control_overflow.rb index 4d9c79ac..87b714fd 100644 --- a/examples/control_overflow.rb +++ b/examples/control_overflow.rb @@ -35,8 +35,9 @@ rescue LibTmux::SubscriptionOverflow end gap = tail.next(timeout: 5) - raise "Expected an output gap with dropped bytes" unless gap.kind == :gap && - gap.dropped_bytes.positive? + unless gap.kind == :gap && gap.dropped_bytes.positive? + raise "Expected an output gap with dropped bytes" + end end end # docs:end main diff --git a/examples/failed_group.rb b/examples/failed_group.rb index d935e1a9..56a95a66 100644 --- a/examples/failed_group.rb +++ b/examples/failed_group.rb @@ -5,14 +5,29 @@ Example.run("failed_group") do |server| server.new_session(name: "group", command: ["/bin/cat"]) # docs:begin main - group = server.run_group([ - ["set-option", "-g", "@before", "retained"], - ["select-pane", "-t", "%4294967294"], - ["set-option", "-g", "@after", "not-executed"] - ]) + group = + server.run_group( + [ + %w[set-option -g @before retained], + %w[select-pane -t %4294967294], + %w[set-option -g @after not-executed] + ] + ) Example.check(!group.success?, "failing group succeeded") - Example.check(group.steps.all? { |step| step.fetch(:outcome) == :unknown }, "expected unknown outcomes for individual steps") - Example.check(server.options(scope: :session).get("@before").raw == "retained", "earlier effect rolled back") - Example.check(server.options(scope: :session).list.none? { |option| option.name == "@after" }, "later step executed") + Example.check( + group.steps.all? { |step| step.fetch(:outcome) == :unknown }, + "expected unknown outcomes for individual steps" + ) + Example.check( + server.options(scope: :session).get("@before").raw == "retained", + "earlier effect rolled back" + ) + Example.check( + server + .options(scope: :session) + .list + .none? { |option| option.name == "@after" }, + "later step executed" + ) # docs:end main end diff --git a/examples/job_resume.rb b/examples/job_resume.rb index c5ae64a6..fe817066 100644 --- a/examples/job_resume.rb +++ b/examples/job_resume.rb @@ -8,41 +8,57 @@ class InventoryJob VERSION = 1 - STAGES = {"normalize" => "normalized.json", "summarize" => "summary.json"}.freeze + STAGES = { + "normalize" => "normalized.json", + "summarize" => "summary.json" + }.freeze def self.worker(stage, source, destination, option = nil) - result = case stage - when "normalize" - File.readlines(source, encoding: "UTF-8", chomp: true).map do |line| - name, quantity = line.split("\t", 2) - raise ArgumentError, "Expected a name and count separated by a tab" if name.to_s.strip.empty? || !quantity - - [name.strip.capitalize, Integer(quantity, 10)] - end - when "summarize" - if option == "--fail" - puts "injected failure in summarize (résumé)" - return 23 + result = + case stage + when "normalize" + File + .readlines(source, encoding: "UTF-8", chomp: true) + .map do |line| + name, quantity = line.split("\t", 2) + if name.to_s.strip.empty? || !quantity + raise ArgumentError, + "Expected a name and count separated by a tab" + end + + [name.strip.capitalize, Integer(quantity, 10)] + end + when "summarize" + if option == "--fail" + puts "injected failure in summarize (résumé)" + return 23 + end + totals = Hash.new(0) + JSON + .parse(File.read(source, encoding: "UTF-8")) + .each { |name, quantity| totals[name] += quantity } + totals.sort.to_h + else + raise ArgumentError, "Unknown inventory worker" end - totals = Hash.new(0) - JSON.parse(File.read(source, encoding: "UTF-8")).each { |name, quantity| totals[name] += quantity } - totals.sort.to_h - else - raise ArgumentError, "Unknown inventory worker" - end File.write(destination, JSON.generate(result) + "\n") 0 end def initialize(input, state, fail_summarize:) - @input, @state, @fail_summarize = input, File.expand_path(state), fail_summarize + @input, @state, @fail_summarize = + input, + File.expand_path(state), + fail_summarize @checkpoint = File.join(@state, "checkpoint.json") end def run FileUtils.mkdir_p(@state) File.open(File.join(@state, "job.lock"), "a") do |lock| - raise "This state directory is in use" unless lock.flock(File::LOCK_EX | File::LOCK_NB) + unless lock.flock(File::LOCK_EX | File::LOCK_NB) + raise "This state directory is in use" + end Dir.mktmpdir("libtmux-ruby-job-", @state) do |scratch| source = File.join(scratch, "input.tsv") @@ -52,9 +68,10 @@ def run checkpoints = read_checkpoints STAGES.each do |stage, filename| output = File.join(@state, filename) - key = {"input" => input_hash, "source" => source_hash} + key = { "input" => input_hash, "source" => source_hash } artifact_hash = File.file?(output) ? digest(output) : nil - if artifact_hash && checkpoints[stage] == key.merge("artifact" => artifact_hash) + if artifact_hash && + checkpoints[stage] == key.merge("artifact" => artifact_hash) puts "#{stage} cached" else candidate = File.join(scratch, filename) @@ -65,7 +82,11 @@ def run checkpoints[stage] = key.merge("artifact" => artifact_hash) File.rename(candidate, output) staged_checkpoint = File.join(scratch, "checkpoint.json") - File.write(staged_checkpoint, JSON.generate({"version" => VERSION, "stages" => checkpoints}) + "\n") + File.write( + staged_checkpoint, + JSON.generate({ "version" => VERSION, "stages" => checkpoints }) + + "\n" + ) File.rename(staged_checkpoint, @checkpoint) puts "#{stage} completed" end @@ -88,7 +109,10 @@ def digest(path) def read_checkpoints data = JSON.parse(File.read(@checkpoint, encoding: "UTF-8")) - return data["stages"] if data.is_a?(Hash) && data["version"] == VERSION && data["stages"].is_a?(Hash) + if data.is_a?(Hash) && data["version"] == VERSION && + data["stages"].is_a?(Hash) + return data["stages"] + end {} rescue Errno::ENOENT, JSON::ParserError @@ -97,11 +121,21 @@ def read_checkpoints def run_stage(stage, source, destination) unless @server - @server = LibTmux::Server.start(executable: ENV.fetch("LIBTMUX_TEST_TMUX", "tmux")) + @server = + LibTmux::Server.start( + executable: ENV.fetch("LIBTMUX_TEST_TMUX", "tmux") + ) @server.options(scope: :window).set("remain-on-exit", "on") @session = @server.new_session(name: "inventory", command: ["/bin/cat"]) end - command = [Gem.ruby, File.expand_path(__FILE__), "--worker", stage, source, destination] + command = [ + Gem.ruby, + File.expand_path(__FILE__), + "--worker", + stage, + source, + destination + ] command << "--fail" if stage == "summarize" && @fail_summarize channel = "inventory-#{stage}-exited" @server.hooks.set("pane-died", command: "wait-for -S #{channel}") @@ -114,7 +148,15 @@ def run_stage(stage, source, destination) status = snapshot.dead_status return 0 if status == 0 - warn(status ? "#{stage} exited with status #{status}" : "#{stage} ended without an exit status") + warn( + ( + if status + "#{stage} exited with status #{status}" + else + "#{stage} ended without an exit status" + end + ) + ) warn pane.capture(start: -32, join: true).text(invalid: :replace).rstrip status || 1 rescue LibTmux::DeadlineExceeded @@ -124,9 +166,7 @@ def run_stage(stage, source, destination) end begin - if ARGV.first == "--worker" - exit InventoryJob.worker(*ARGV.drop(1)) - end + exit InventoryJob.worker(*ARGV.drop(1)) if ARGV.first == "--worker" options = ARGV.drop(2) if ARGV.length < 2 || ![[], ["--fail-summarize"]].include?(options) abort "usage: ruby job_resume.rb INPUT STATE_DIRECTORY [--fail-summarize]" diff --git a/examples/layout_io.rb b/examples/layout_io.rb index 9fae1033..f4e648de 100644 --- a/examples/layout_io.rb +++ b/examples/layout_io.rb @@ -4,10 +4,15 @@ require "libtmux" LibTmux::Server.start do |server| - receipt = server.new_session( - name: "layout", command: ["/bin/sh"], receipt: true, - environment: {"ENV" => "/dev/null"} - ) + receipt = + server.new_session( + name: "layout", + command: ["/bin/sh"], + receipt: true, + environment: { + "ENV" => "/dev/null" + } + ) pane = receipt.pane side = pane.split(direction: :horizontal, size: "40%", command: ["/bin/cat"]) receipt.window.select_layout("tiled") @@ -17,17 +22,17 @@ end expected = "pane prête" - send_command = lambda do - pane.send_text("printf '\\n%s %s\\n' 'pane' 'prête'") - pane.send_keys("Enter") - end + send_command = + lambda do + pane.send_text("printf '\\n%s %s\\n' 'pane' 'prête'") + pane.send_keys("Enter") + end deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 5 if server.supports_control? server.open_control(session: receipt.entity.ref) do |control| control.exchange("display-message -p ready") - output = control.subscribe( - pane_id: pane.id, max_bytes: 8192, max_events: 32 - ) + output = + control.subscribe(pane_id: pane.id, max_bytes: 8192, max_events: 32) send_command.call received = +"".b until received.include?(expected.b) diff --git a/examples/list_filter.rb b/examples/list_filter.rb index 055214a4..7be54df8 100644 --- a/examples/list_filter.rb +++ b/examples/list_filter.rb @@ -3,13 +3,14 @@ # docs:begin main require "libtmux" -panes = LibTmux::Server.start do |server| - session = server.new_session(name: "capture", command: ["/bin/cat"]) - session.new_window(name: "second", command: ["/bin/cat"]) - captured = server.snapshot.panes - session.new_window(name: "later", command: ["/bin/cat"]) - captured -end +panes = + LibTmux::Server.start do |server| + session = server.new_session(name: "capture", command: ["/bin/cat"]) + session.new_window(name: "second", command: ["/bin/cat"]) + captured = server.snapshot.panes + session.new_window(name: "later", command: ["/bin/cat"]) + captured + end first = panes.one(id: panes.first.id) puts "captured panes: #{panes.size}" diff --git a/examples/mcp_client.json b/examples/mcp_client.json index 80593b56..c7d5b302 100644 --- a/examples/mcp_client.json +++ b/examples/mcp_client.json @@ -2,7 +2,11 @@ "mcpServers": { "tmux": { "command": "libtmux-mcp", - "args": ["--socket-name", "agent", "--start-session", "work", "--endpoint", "dev"] + "args": [ + "--socket-name", "agent", + "--start-session", "work", + "--endpoint", "dev" + ] } } } diff --git a/examples/mcp_in_process.rb b/examples/mcp_in_process.rb index 6c80e653..6c82fbc7 100644 --- a/examples/mcp_in_process.rb +++ b/examples/mcp_in_process.rb @@ -11,35 +11,63 @@ LibTmux::Async.open(parent: parent, server: server) do |scope| IO.pipe do |requests, send_request| IO.pipe do |receive_reply, replies| - app = LibTmux::MCP::Application.new( - server: scope.server, endpoint_name: "example" - ) - begin - transport = LibTmux::MCP::StdioTransport.new( - server: app.sdk_server, parent: parent, input: requests, - output: replies + app = + LibTmux::MCP::Application.new( + server: scope.server, + endpoint_name: "example" ) + begin + transport = + LibTmux::MCP::StdioTransport.new( + server: app.sdk_server, + parent: parent, + input: requests, + output: replies + ) runner = parent.async { transport.run } - request = lambda do |id, method, params, timeout:| - frame = {jsonrpc: "2.0", id: id, method: method, params: params} - send_request.puts(JSON.generate(frame)) - line = parent.with_timeout(timeout) { receive_reply.readline } - reply = JSON.parse(line) - raise "Expected reply #{id}" unless reply.fetch("id") == id + request = + lambda do |id, method, params, timeout:| + frame = { + jsonrpc: "2.0", + id: id, + method: method, + params: params + } + send_request.puts(JSON.generate(frame)) + line = parent.with_timeout(timeout) { receive_reply.readline } + reply = JSON.parse(line) + raise "Expected reply #{id}" unless reply.fetch("id") == id - reply.fetch("result") - end - initialized = request.call(1, "initialize", { - protocolVersion: "2025-11-25", capabilities: {}, - clientInfo: {name: "recipe", version: "1"} - }, timeout: 10) - puts "protocol version: #{initialized.fetch('protocolVersion')}" - send_request.puts(JSON.generate( - {jsonrpc: "2.0", method: "notifications/initialized"} - )) - snapshot = request.call(2, "tools/call", { - name: "tmux_snapshot", arguments: {entity: "pane"} - }, timeout: 5) + reply.fetch("result") + end + initialized = + request.call( + 1, + "initialize", + { + protocolVersion: "2025-11-25", + capabilities: { + }, + clientInfo: { + name: "recipe", + version: "1" + } + }, + timeout: 10 + ) + puts "protocol version: #{initialized.fetch("protocolVersion")}" + send_request.puts( + JSON.generate( + { jsonrpc: "2.0", method: "notifications/initialized" } + ) + ) + snapshot = + request.call( + 2, + "tools/call", + { name: "tmux_snapshot", arguments: { entity: "pane" } }, + timeout: 5 + ) data = snapshot.fetch("structuredContent").fetch("data") panes = data.fetch("items") puts "panes: #{panes.length}" diff --git a/examples/mcp_protocol.rb b/examples/mcp_protocol.rb index 2ce4c9be..09681125 100644 --- a/examples/mcp_protocol.rb +++ b/examples/mcp_protocol.rb @@ -11,54 +11,142 @@ Async do |parent| LibTmux::Async.open(parent: parent, server: server) do |scope| # docs:begin main - application = LibTmux::MCP::Application.new(server: scope.server, endpoint_name: "example") + application = + LibTmux::MCP::Application.new( + server: scope.server, + endpoint_name: "example" + ) sdk = application.sdk_server input, client_input = IO.pipe client_output, output = IO.pipe - transport = LibTmux::MCP::StdioTransport.new(server: sdk, parent: parent, input: input, output: output) + transport = + LibTmux::MCP::StdioTransport.new( + server: sdk, + parent: parent, + input: input, + output: output + ) runner = parent.async { transport.run } # docs:end main - send_request = lambda do |id, method, params = {}| - client_input.write(JSON.generate({jsonrpc: "2.0", id: id, method: method, params: params}) + "\n") - end + send_request = + lambda do |id, method, params = {}| + client_input.write( + JSON.generate( + { jsonrpc: "2.0", id: id, method: method, params: params } + ) + "\n" + ) + end reader = Example::FrameReader.new(client_output) - receive = lambda do |stage, timeout: Example::MCP_RESPONSE_TIMEOUT| - JSON.parse(reader.read("in-process MCP #{stage}", timeout: timeout)) - end - envelope = {"io.modelcontextprotocol/protocolVersion" => "2026-07-28", - "io.modelcontextprotocol/clientCapabilities" => {}} + receive = + lambda do |stage, timeout: Example::MCP_RESPONSE_TIMEOUT| + JSON.parse(reader.read("in-process MCP #{stage}", timeout: timeout)) + end + envelope = { + "io.modelcontextprotocol/protocolVersion" => "2026-07-28", + "io.modelcontextprotocol/clientCapabilities" => { + } + } send_request.call(1, "server/discover") - discovery = receive.call("server/discover", timeout: Example::MCP_STARTUP_TIMEOUT) - Example.check(discovery.dig("result", "supportedVersions") == ["2026-07-28"], "protocol discovery failed") - send_request.call(2, "tools/call", {name: "tmux_capabilities", arguments: {}, _meta: envelope}) - capabilities = receive.call("tmux_capabilities").dig("result", "structuredContent", "data") - authored_profile = capabilities.fetch("authored_run").fetch("availability") - Example.check(capabilities.fetch("endpoint") == "example", "endpoint alias differs") - send_request.call(3, "tools/call", {name: "tmux_snapshot", arguments: {entity: "pane"}, _meta: envelope}) - snapshot = receive.call("tmux_snapshot").dig("result", "structuredContent", "data") + discovery = + receive.call("server/discover", timeout: Example::MCP_STARTUP_TIMEOUT) + Example.check( + discovery.dig("result", "supportedVersions") == ["2026-07-28"], + "protocol discovery failed" + ) + send_request.call( + 2, + "tools/call", + { name: "tmux_capabilities", arguments: {}, _meta: envelope } + ) + capabilities = + receive.call("tmux_capabilities").dig( + "result", + "structuredContent", + "data" + ) + authored_profile = + capabilities.fetch("authored_run").fetch("availability") + Example.check( + capabilities.fetch("endpoint") == "example", + "endpoint alias differs" + ) + send_request.call( + 3, + "tools/call", + { + name: "tmux_snapshot", + arguments: { + entity: "pane" + }, + _meta: envelope + } + ) + snapshot = + receive.call("tmux_snapshot").dig("result", "structuredContent", "data") Example.check(snapshot.fetch("items").length == 1, "protocol read failed") - Example.check(application.call("tmux_close", {}).structured_content.dig("error", "code") == "policy_denied", "default policy permits mutation") + Example.check( + application + .call("tmux_close", {}) + .structured_content + .dig("error", "code") == "policy_denied", + "default policy permits mutation" + ) cancellations = Queue.new - sdk.define_custom_method(method_name: "example/wait") do |_, server_context:| - scope.server.run(["wait-for", "-S", "protocol-ready", ";", "wait-for", "protocol-held"], timeout: 0.5) - {finished: true} + sdk.define_custom_method( + method_name: "example/wait" + ) do |_, server_context:| + scope.server.run( + %w[wait-for -S protocol-ready ; wait-for protocol-held], + timeout: 0.5 + ) + { finished: true } rescue LibTmux::Cancelled => failure cancellations << failure - {cancelled: true} + { cancelled: true } end - send_request.call(4, "example/wait", {_meta: envelope}) + send_request.call(4, "example/wait", { _meta: envelope }) scope.server.wait_for("protocol-ready", timeout: 0.5) - client_input.write(JSON.generate({jsonrpc: "2.0", method: "notifications/cancelled", params: {requestId: 4}}) + "\n") - send_request.call(5, "tools/call", {name: "tmux_capabilities", arguments: {}, _meta: envelope}) - Example.check(receive.call("tmux_capabilities after cancellation").fetch("id") == 5, "cancelled request blocked protocol reader") + client_input.write( + JSON.generate( + { + jsonrpc: "2.0", + method: "notifications/cancelled", + params: { + requestId: 4 + } + } + ) + "\n" + ) + send_request.call( + 5, + "tools/call", + { name: "tmux_capabilities", arguments: {}, _meta: envelope } + ) + Example.check( + receive.call("tmux_capabilities after cancellation").fetch("id") == 5, + "cancelled request blocked protocol reader" + ) failure = parent.with_timeout(0.5) { cancellations.pop } - Example.check(failure.delivery == :possibly_sent, "cancellation claimed no dispatch") - Example.raises(Errno::ECHILD) { Process.waitpid(failure.pid, Process::WNOHANG) } + Example.check( + failure.delivery == :possibly_sent, + "cancellation claimed no dispatch" + ) + Example.raises(Errno::ECHILD) do + Process.waitpid(failure.pid, Process::WNOHANG) + end ensure failure = $! - cleanup = [-> { client_input&.close unless client_input&.closed? }, - -> { runner&.wait(timeout: 0.5) }, -> { transport&.close }, -> { application&.close }] - cleanup.concat([input, output, client_output].compact.map { |io| -> { io.close unless io.closed? } }) + cleanup = [ + -> { client_input&.close unless client_input&.closed? }, + -> { runner&.wait(timeout: 0.5) }, + -> { transport&.close }, + -> { application&.close } + ] + cleanup.concat( + [input, output, client_output].compact.map do |io| + -> { io.close unless io.closed? } + end + ) cleanup.each do |action| action.call rescue Exception => error @@ -86,76 +174,239 @@ example_ready() { print -r -- ready >&$example_control } zle -N zle-line-init example_ready ZSH - shell = server.new_session(name: "enrolled-example", cwd: directory, - command: ["/usr/bin/env", "ZDOTDIR=#{directory}", "/bin/zsh", "-d", "-i"]) + shell = + server.new_session( + name: "enrolled-example", + cwd: directory, + command: [ + "/usr/bin/env", + "ZDOTDIR=#{directory}", + "/bin/zsh", + "-d", + "-i" + ] + ) shell_pane = shell.list_panes.first - Example.check(listener.wait_readable(Example::MCP_STARTUP_TIMEOUT), "example shell did not connect") + Example.check( + listener.wait_readable(Example::MCP_STARTUP_TIMEOUT), + "example shell did not connect" + ) channel = listener.accept shell_reader = Example::FrameReader.new(channel) - message = shell_reader.read("shell setup initialization", timeout: Example::MCP_STARTUP_TIMEOUT) + message = + shell_reader.read( + "shell setup initialization", + timeout: Example::MCP_STARTUP_TIMEOUT + ) Example.check(message == "initializing", "shell setup did not initialize") enrollment_arguments = ["--enroll-pane", "#{shell_pane.id}=#{setup}"] end # docs:begin cli executable = Gem.bin_path("libtmux-mcp", "libtmux-mcp") - Open3.popen3(Gem.ruby, "-W:no-experimental", executable, "--socket", server.endpoint.socket_path, - "--tmux", Example.executable, "--endpoint", "installed", "--enable-tool", "tmux_create", "--enable-tool", "tmux_send", - "--enable-tool", "tmux_close", "--enable-tool", "tmux_run", *enrollment_arguments) do |input, output, errors, process| + Open3.popen3( + Gem.ruby, + "-W:no-experimental", + executable, + "--socket", + server.endpoint.socket_path, + "--tmux", + Example.executable, + "--endpoint", + "installed", + "--enable-tool", + "tmux_create", + "--enable-tool", + "tmux_send", + "--enable-tool", + "tmux_close", + "--enable-tool", + "tmux_run", + *enrollment_arguments + ) do |input, output, errors, process| reader = Example::FrameReader.new(output, child: process) - request = lambda do |id, method, params = {}, timeout: Example::MCP_RESPONSE_TIMEOUT| - input.write(JSON.generate({jsonrpc: "2.0", id: id, method: method, params: params}) + "\n") - stage = "installed MCP #{method} (request #{id})" - response = JSON.parse(reader.read(stage, timeout: timeout)) - Example.check(response.fetch("id") == id, "#{stage} returned a different request ID") - response.fetch("result") - end - request.call(1, "initialize", {protocolVersion: "2025-11-25", capabilities: {}, - clientInfo: {name: "recipe", version: "1"}}, timeout: Example::MCP_STARTUP_TIMEOUT) - input.write(JSON.generate({jsonrpc: "2.0", method: "notifications/initialized"}) + "\n") - names = request.call(2, "tools/list").fetch("tools").map { |tool| tool.fetch("name") } - Example.check(names.sort == %w[tmux_capabilities tmux_close tmux_create tmux_run tmux_send tmux_snapshot], "tool policy differs") - created = request.call(3, "tools/call", {name: "tmux_create", arguments: { - kind: "session", name: "via-protocol", argv: ["/bin/cat"]}}).fetch("structuredContent") + response_timeout = Example::MCP_RESPONSE_TIMEOUT + request = + lambda do |id, method, params = {}, timeout: response_timeout| + input.write( + JSON.generate( + { jsonrpc: "2.0", id: id, method: method, params: params } + ) + "\n" + ) + stage = "installed MCP #{method} (request #{id})" + response = JSON.parse(reader.read(stage, timeout: timeout)) + Example.check( + response.fetch("id") == id, + "#{stage} returned a different request ID" + ) + response.fetch("result") + end + client_capabilities = {} + client_info = { name: "recipe", version: "1" } + request.call( + 1, + "initialize", + { + protocolVersion: "2025-11-25", + capabilities: client_capabilities, + clientInfo: client_info + }, + timeout: Example::MCP_STARTUP_TIMEOUT + ) + input.write( + JSON.generate({ jsonrpc: "2.0", method: "notifications/initialized" }) + + "\n" + ) + names = + request + .call(2, "tools/list") + .fetch("tools") + .map { |tool| tool.fetch("name") } + Example.check( + names.sort == + %w[ + tmux_capabilities + tmux_close + tmux_create + tmux_run + tmux_send + tmux_snapshot + ], + "tool policy differs" + ) + created = + request.call( + 3, + "tools/call", + { + name: "tmux_create", + arguments: { + kind: "session", + name: "via-protocol", + argv: ["/bin/cat"] + } + } + ).fetch("structuredContent") Example.check(created.fetch("ok"), "protocol creation failed") data = created.fetch("data") pane = data.fetch("created").find { |ref| ref.fetch("kind") == "pane" } - sent = request.call(4, "tools/call", {name: "tmux_send", arguments: { - target: pane, input: {type: "text", text: "literal;"}}}).fetch("structuredContent") - Example.check(sent.fetch("data").fetch("completion") == "dispatch_only", "send claimed shell completion") + sent = + request.call( + 4, + "tools/call", + { + name: "tmux_send", + arguments: { + target: pane, + input: { + type: "text", + text: "literal;" + } + } + } + ).fetch("structuredContent") + Example.check( + sent.fetch("data").fetch("completion") == "dispatch_only", + "send claimed shell completion" + ) target = pane if channel - Example.check(File.stat(setup).mode & 0o777 == 0o600, "enrollment setup permissions differ") + Example.check( + File.stat(setup).mode & 0o777 == 0o600, + "enrollment setup permissions differ" + ) channel.puts(setup) - message = shell_reader.read("shell enrollment acknowledgement", timeout: Example::MCP_RESPONSE_TIMEOUT) + message = + shell_reader.read( + "shell enrollment acknowledgement", + timeout: Example::MCP_RESPONSE_TIMEOUT + ) Example.check(message == "ready", "shell enrollment was not acknowledged") target = pane.merge("id" => shell_pane.id) end - script = 'printf "%s:%s" "$EXAMPLE_CONTEXT" "$TMUX_PANE"; printf "\\000\\377" >&2; exit 9' - run = request.call(5, "tools/call", {name: "tmux_run", arguments: { - target: target, script: script, stdout_limit: 128, stderr_limit: 2}}).fetch("structuredContent") + script = [ + 'printf "%s:%s" "$EXAMPLE_CONTEXT" "$TMUX_PANE"', + 'printf "\\000\\377" >&2', + "exit 9" + ].join("; ") + run = + request.call( + 5, + "tools/call", + { + name: "tmux_run", + arguments: { + target: target, + script: script, + stdout_limit: 128, + stderr_limit: 2 + } + } + ).fetch("structuredContent") if channel Example.check(run.fetch("ok"), "installed authored run failed") result = run.fetch("data") - Example.check(result.fetch("stdout").fetch("data") == "installed:#{shell_pane.id}", "authored shell context differs") - Example.check(result.fetch("stderr") == {"encoding" => "base64", "data" => "AP8=", "bytes" => 2, "truncated" => false}, "authored bytes differ") - Example.check(result.fetch("completion") == {"state" => "exited", "exit_status" => 9, "signal" => nil}, "native completion differs") - Example.check(result.fetch("authorization").fetch("state") == "authorized", "authorization receipt missing") + Example.check( + result.fetch("stdout").fetch("data") == "installed:#{shell_pane.id}", + "authored shell context differs" + ) + Example.check( + result.fetch("stderr") == + { + "encoding" => "base64", + "data" => "AP8=", + "bytes" => 2, + "truncated" => false + }, + "authored bytes differ" + ) + Example.check( + result.fetch("completion") == + { "state" => "exited", "exit_status" => 9, "signal" => nil }, + "native completion differs" + ) + Example.check( + result.fetch("authorization").fetch("state") == "authorized", + "authorization receipt missing" + ) else - Example.check(run.dig("error", "code") == "unsupported" && run.dig("error", "delivery") == "not_sent", "unsupported enrollment did not refuse") + Example.check( + run.dig("error", "code") == "unsupported" && + run.dig("error", "delivery") == "not_sent", + "unsupported enrollment did not refuse" + ) end - closed = request.call(6, "tools/call", {name: "tmux_close", arguments: {target: data.fetch("entity")}}) - Example.check(closed.fetch("structuredContent").fetch("ok"), "protocol close failed") + closed = + request.call( + 6, + "tools/call", + { name: "tmux_close", arguments: { target: data.fetch("entity") } } + ) + Example.check( + closed.fetch("structuredContent").fetch("ok"), + "protocol close failed" + ) input.close - Example.check(process.join(Example::MCP_SHUTDOWN_TIMEOUT), "installed MCP did not exit after EOF") - Example.check(process.value.success? && errors.read_nonblock(1, exception: false).nil?, "MCP executable failed") + Example.check( + process.join(Example::MCP_SHUTDOWN_TIMEOUT), + "installed MCP did not exit after EOF" + ) + Example.check( + process.value.success? && errors.read_nonblock(1, exception: false).nil?, + "MCP executable failed" + ) Example.check(!File.exist?(setup), "enrollment setup survived EOF") ensure Example.reap_protocol_child(input, process) end # docs:end cli shell&.kill - Example.check(server.list_sessions.size == 1, "CLI EOF changed the borrowed server") + Example.check( + server.list_sessions.size == 1, + "CLI EOF changed the borrowed server" + ) ensure [channel, listener].compact.each { |io| io.close unless io.closed? } - [ready_path, shell_config].compact.each { |path| File.unlink(path) if File.exist?(path) } + [ready_path, shell_config].compact.each do |path| + File.unlink(path) if File.exist?(path) + end end diff --git a/examples/mcp_stdio.rb b/examples/mcp_stdio.rb index b69bfc46..0ab1d9db 100644 --- a/examples/mcp_stdio.rb +++ b/examples/mcp_stdio.rb @@ -9,32 +9,51 @@ LibTmux::Server.start do |server| server.new_session(name: "protocol", command: ["/bin/cat"]) executable = Gem.bin_path("libtmux-mcp", "libtmux-mcp") - command = [Gem.ruby, "-W:no-experimental", executable, - "--socket", server.endpoint.socket_path] + command = [ + Gem.ruby, + "-W:no-experimental", + executable, + "--socket", + server.endpoint.socket_path + ] Open3.popen3(*command, pgroup: true) do |input, output, errors, child| - request = lambda do |id, method, params = {}, timeout:| - frame = {jsonrpc: "2.0", id: id, method: method, params: params} - input.puts(JSON.generate(frame)) - reply = JSON.parse(Timeout.timeout(timeout) { output.readline }) - raise "Expected reply #{id} for #{method}" unless reply.fetch("id") == id + request = + lambda do |id, method, params = {}, timeout:| + frame = { jsonrpc: "2.0", id: id, method: method, params: params } + input.puts(JSON.generate(frame)) + reply = JSON.parse(Timeout.timeout(timeout) { output.readline }) + unless reply.fetch("id") == id + raise "Expected reply #{id} for #{method}" + end - reply.fetch("result") - rescue Timeout::Error - raise "Timed out waiting for #{method} after #{timeout} seconds" - rescue EOFError - raise "MCP closed before replying to #{method}" - end + reply.fetch("result") + rescue Timeout::Error + raise "Timed out waiting for #{method} after #{timeout} seconds" + rescue EOFError + raise "MCP closed before replying to #{method}" + end - initialization = request.call(1, "initialize", { - protocolVersion: "2025-11-25", capabilities: {}, - clientInfo: {name: "recipe", version: "1"} - }, timeout: 10) - puts "initialized: #{initialization.fetch('protocolVersion')}" - input.puts(JSON.generate( - {jsonrpc: "2.0", method: "notifications/initialized"} - )) + initialization = + request.call( + 1, + "initialize", + { + protocolVersion: "2025-11-25", + capabilities: { + }, + clientInfo: { + name: "recipe", + version: "1" + } + }, + timeout: 10 + ) + puts "initialized: #{initialization.fetch("protocolVersion")}" + input.puts( + JSON.generate({ jsonrpc: "2.0", method: "notifications/initialized" }) + ) tools = request.call(2, "tools/list", timeout: 5).fetch("tools") - puts "tools: #{tools.map { |tool| tool.fetch('name') }.sort.join(', ')}" + puts "tools: #{tools.map { |tool| tool.fetch("name") }.sort.join(", ")}" input.close raise "MCP did not exit after EOF" unless child.join(2) raise "MCP exited #{child.value.exitstatus}" unless child.value.success? diff --git a/examples/quickstart.rb b/examples/quickstart.rb index db35e948..1c6c1ec6 100644 --- a/examples/quickstart.rb +++ b/examples/quickstart.rb @@ -11,18 +11,22 @@ # docs:begin main require "libtmux" - snapshot = LibTmux::Server.start do |server| - session = server.new_session( - name: "work", window_name: "main", command: ["/bin/cat"] - ) - window = session.new_window(name: "logs", command: ["/bin/cat"]) - window.split(direction: :horizontal, size: "40%", command: ["/bin/cat"]) + snapshot = + LibTmux::Server.start do |server| + session = + server.new_session( + name: "work", + window_name: "main", + command: ["/bin/cat"] + ) + window = session.new_window(name: "logs", command: ["/bin/cat"]) + window.split(direction: :horizontal, size: "40%", command: ["/bin/cat"]) - server.snapshot - end + server.snapshot + end snapshot.windows.each do |window| - puts "#{window.name}: #{window.panes.map(&:id).join(', ')}" + puts "#{window.name}: #{window.panes.map(&:id).join(", ")}" end # docs:end main @@ -32,15 +36,19 @@ # docs:begin queries require "libtmux" - snapshot = LibTmux::Server.start do |server| - session = server.new_session( - name: "work", window_name: "main", command: ["/bin/cat"] - ) - window = session.new_window(name: "logs", command: ["/bin/cat"]) - window.split(direction: :horizontal, size: "40%", command: ["/bin/cat"]) + snapshot = + LibTmux::Server.start do |server| + session = + server.new_session( + name: "work", + window_name: "main", + command: ["/bin/cat"] + ) + window = session.new_window(name: "logs", command: ["/bin/cat"]) + window.split(direction: :horizontal, size: "40%", command: ["/bin/cat"]) - server.snapshot - end + server.snapshot + end panes = snapshot.panes active_ids = panes.where(active: true).map(&:id) @@ -50,17 +58,33 @@ logs = snapshot.windows.one(name: "logs") missing = snapshot.windows.one_or_nil(name: "missing") - puts "active: #{active_ids.join(', ')}" - puts "wide: #{wide_panes.map(&:id).join(', ')}" + puts "active: #{active_ids.join(", ")}" + puts "wide: #{wide_panes.map(&:id).join(", ")}" puts "logs panes: #{logs.panes.length}" puts "missing: #{missing.inspect}" # docs:end queries - Example.check(output.string == "main: %0\nlogs: %1, %2\n", "unexpected window listing") - Example.check(queries_output.string == "active: %0, %1\nwide: %0, %1\nlogs panes: 2\nmissing: nil\n", "unexpected queries") - Example.check(panes.size == 3 && active_ids.size == 2, "unexpected pane selection") - Example.check(wide_panes.map(&:id) == panes.where(width: {gte: 40}).map(&:id), "block selection differs") - Example.check(panes_by_window.transform_values(&:size) == {"main" => 1, "logs" => 2}, "unexpected pane groups") + Example.check( + output.string == "main: %0\nlogs: %1, %2\n", + "unexpected window listing" + ) + Example.check( + queries_output.string == + "active: %0, %1\nwide: %0, %1\nlogs panes: 2\nmissing: nil\n", + "unexpected queries" + ) + Example.check( + panes.size == 3 && active_ids.size == 2, + "unexpected pane selection" + ) + Example.check( + wide_panes.map(&:id) == panes.where(width: { gte: 40 }).map(&:id), + "block selection differs" + ) + Example.check( + panes_by_window.transform_values(&:size) == { "main" => 1, "logs" => 2 }, + "unexpected pane groups" + ) Example.check(logs.panes.size == 2 && missing.nil?, "unexpected exact lookup") ensure $stdout = original_stdout diff --git a/examples/refresh.rb b/examples/refresh.rb index 943ffacd..0e2f92cb 100644 --- a/examples/refresh.rb +++ b/examples/refresh.rb @@ -12,9 +12,12 @@ require "libtmux" LibTmux::Server.start do |server| - session = server.new_session( - name: "work", window_name: "editor", command: ["/bin/cat"] - ) + session = + server.new_session( + name: "work", + window_name: "editor", + command: ["/bin/cat"] + ) window = session.list_windows.fetch(0) held = window.snapshot diff --git a/examples/support.rb b/examples/support.rb index 812b7a85..ed6f99d5 100644 --- a/examples/support.rb +++ b/examples/support.rb @@ -22,18 +22,31 @@ def read(stage, timeout:) ending = @buffer.index("\n") return @buffer.slice!(0, ending + 1).chomp if ending - raise "#{stage} exceeded the frame byte limit" if @buffer.bytesize >= MAX_BYTES + if @buffer.bytesize >= MAX_BYTES + raise "#{stage} exceeded the frame byte limit" + end elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started remaining = timeout - elapsed unless remaining.positive? - raise "#{stage} did not return a complete frame after #{format("%.2f", elapsed)}s#{child_state}" + message = "#{stage} did not return a complete frame" + raise "#{message} after #{format("%.2f", elapsed)}s#{child_state}" end - case (chunk = @io.read_nonblock([16_384, MAX_BYTES - @buffer.bytesize].min, exception: false)) - when :wait_readable then @io.wait_readable(remaining) - when nil then raise "#{stage} closed before returning a complete frame#{child_state}" - else @buffer << chunk + case ( + chunk = + @io.read_nonblock( + [16_384, MAX_BYTES - @buffer.bytesize].min, + exception: false + ) + ) + when :wait_readable + @io.wait_readable(remaining) + when nil + message = "#{stage} closed before returning a complete frame" + raise "#{message}#{child_state}" + else + @buffer << chunk end end end @@ -83,7 +96,10 @@ def self.control?(server) end def self.refuses_control(server, session) - error = raises(LibTmux::UnsupportedFeatureError) { server.open_control(session: session.ref) } + error = + raises(LibTmux::UnsupportedFeatureError) do + server.open_control(session: session.ref) + end check(error.delivery == :not_sent, "control refusal reported a dispatch") check(server.list_clients.empty?, "a control client attached") end @@ -92,7 +108,7 @@ def self.run(name) path = pid = nil LibTmux::Server.start(executable: executable) do |server| path = server.endpoint.socket_path - pid = Integer(server.run(["display-message", "-p", '#{pid}']).text, 10) + pid = Integer(server.run(%w[display-message -p #{pid}]).text, 10) yield server end check(!File.exist?(File.dirname(path)), "owned directory survived close") diff --git a/examples/window_links.rb b/examples/window_links.rb index 8fff5408..6b73fd07 100644 --- a/examples/window_links.rb +++ b/examples/window_links.rb @@ -10,9 +10,15 @@ session.link_window(window.ref, index: 9) links = session.list_window_links Example.check(links.map(&:index) == [0, 4, 9], "link indexes differ") - Example.check(links.map { |link| link.window.ref }.uniq == [window.ref], "window identity split") + Example.check( + links.map { |link| link.window.ref }.uniq == [window.ref], + "window identity split" + ) Example.check(links.map(&:ref).uniq.length == 3, "link contexts collapsed") links.find { |link| link.index == 9 }.select - Example.check(session.display('#{window_index}').text == "9\n", "wrong current link") + Example.check( + session.display('#{window_index}').text == "9\n", + "wrong current link" + ) # docs:end main end diff --git a/examples/workspace_apply.rb b/examples/workspace_apply.rb index 01061487..c194bc1c 100644 --- a/examples/workspace_apply.rb +++ b/examples/workspace_apply.rb @@ -12,34 +12,86 @@ Example.check(server.list_sessions.size == 1, "planning changed tmux") result = plan.apply(server: server) Example.check(result.success?, "workspace apply failed") - Example.check(result.effects.any? { |effect| effect.outcome == :dispatch_only }, "expected a record of shell command dispatch") - crowded = LibTmux::Workspace.parse(JSON.generate({ - session_name: "crowded", windows: [{window_name: "small", panes: Array.new(40) { {} }}] - }), format: :json, base_directory: __dir__) - error = Example.raises(LibTmux::Workspace::ApplyError) do - crowded.plan.apply(server: server, compensate: true) - end - Example.check(!error.result.created_refs.empty?, "failure lost partial creation ledger") - Example.check(error.result.compensation == :completed, "owned compensation failed") - Example.check(server.list_sessions.map(&:ref).include?(borrowed.ref), "borrowed session was removed") + Example.check( + result.effects.any? { |effect| effect.outcome == :dispatch_only }, + "expected a record of shell command dispatch" + ) + crowded = + LibTmux::Workspace.parse( + JSON.generate( + { + session_name: "crowded", + windows: [{ window_name: "small", panes: Array.new(40) { {} } }] + } + ), + format: :json, + base_directory: __dir__ + ) + error = + Example.raises(LibTmux::Workspace::ApplyError) do + crowded.plan.apply(server: server, compensate: true) + end + Example.check( + !error.result.created_refs.empty?, + "failure lost partial creation ledger" + ) + Example.check( + error.result.compensation == :completed, + "owned compensation failed" + ) + Example.check( + server.list_sessions.map(&:ref).include?(borrowed.ref), + "borrowed session was removed" + ) # docs:end main executable = Gem.bin_path("libtmux-workspace", "libtmux-workspace") %w[validate plan].each do |operation| - output, status = Open3.capture2e(Gem.ruby, executable, operation, "--json", File.join(__dir__, "workspace.yaml")) - Example.check(status.success? && JSON.parse(output).is_a?(Hash), "installed CLI #{operation} failed") + output, status = + Open3.capture2e( + Gem.ruby, + executable, + operation, + "--json", + File.join(__dir__, "workspace.yaml") + ) + Example.check( + status.success? && JSON.parse(output).is_a?(Hash), + "installed CLI #{operation} failed" + ) end result.created_refs.fetch("session").then { |ref| server.session(ref).kill } if Example.control?(server) server.open_control(session: borrowed.ref) do |control| control.exchange("display-message -p ready") - selector = server.list_clients.find { |client| client.fetch(:pid) == control.pid }.fetch(:name) - output, status = Open3.capture2e(Gem.ruby, executable, "load", "--json", "--socket", server.endpoint.socket_path, - "--switch", selector, File.join(__dir__, "workspace.yaml")) + selector = + server + .list_clients + .find { |client| client.fetch(:pid) == control.pid } + .fetch(:name) + output, status = + Open3.capture2e( + Gem.ruby, + executable, + "load", + "--json", + "--socket", + server.endpoint.socket_path, + "--switch", + selector, + File.join(__dir__, "workspace.yaml") + ) applied = JSON.parse(output) - Example.check(status.success? && applied.fetch("success"), "installed CLI load/switch failed") - client = server.list_clients.find { |entry| entry.fetch(:pid) == control.pid } - Example.check(client.fetch(:session_id) == applied.fetch("created_refs").fetch("session").fetch("id"), - "installed CLI did not switch the explicit current client") + Example.check( + status.success? && applied.fetch("success"), + "installed CLI load/switch failed" + ) + client = + server.list_clients.find { |entry| entry.fetch(:pid) == control.pid } + Example.check( + client.fetch(:session_id) == + applied.fetch("created_refs").fetch("session").fetch("id"), + "installed CLI did not switch the explicit current client" + ) end else Example.refuses_control(server, borrowed) diff --git a/gems/libtmux-async/README.md b/gems/libtmux-async/README.md index 406f2d36..2b8b8f3b 100644 --- a/gems/libtmux-async/README.md +++ b/gems/libtmux-async/README.md @@ -65,9 +65,10 @@ LibTmux::Server.start do |server| Async do |parent| LibTmux::Async.open(parent: parent, server: server) do |scope| refs = scope.server.list_panes.map(&:ref) - screens = scope.map(refs, concurrency: 2) do |ref| - scope.server.pane(ref).capture - end + screens = + scope.map(refs, concurrency: 2) do |ref| + scope.server.pane(ref).capture + end puts "captured panes: #{screens.length}" puts "all succeeded: #{screens.all?(&:success?)}" end @@ -107,11 +108,12 @@ LibTmux::Server.start do |server| server.new_session(name: "work", command: ["/bin/cat"]) Async do |parent| LibTmux::Async.open(parent: parent, server: server) do |scope| - waiting = parent.async do - scope.server.run(["wait-for", "-S", "ready", ";", "wait-for", "held"], timeout: 5) - rescue LibTmux::Cancelled => error - error - end + waiting = + parent.async do + scope.server.run(%w[wait-for -S ready ; wait-for held], timeout: 5) + rescue LibTmux::Cancelled => error + error + end scope.server.wait_for("ready", timeout: 5) waiting.cancel failure = waiting.wait @@ -186,7 +188,8 @@ LibTmux::Server.start do |server| Async do |parent| LibTmux::Async.open(parent: parent, server: server) do |scope| report = scope.server.capabilities - puts "Control mode requires tmux #{report.feature('control-mode').since}" + control = report.feature("control-mode") + puts "Control mode requires tmux #{control.since}" end end.wait end @@ -218,14 +221,18 @@ LibTmux::Server.start do |server| window = session.list_windows.fetch(0) Async do |parent| LibTmux::Async.open(parent: parent, server: server) do |scope| - scope.server.open_control(session: session.ref) do |control| - reply = control.exchange("display-message -p ready", timeout: 5) - puts "reply: #{reply.blocks.last.body.strip}" - events = control.events - window.rename("renamed") - event = events.next(timeout: 5) until event&.raw&.start_with?("%window-renamed") - puts "event: #{event.raw.strip}" - end + scope + .server + .open_control(session: session.ref) do |control| + reply = control.exchange("display-message -p ready", timeout: 5) + puts "reply: #{reply.blocks.last.body.strip}" + events = control.events + window.rename("renamed") + event = events.next(timeout: 5) until event&.raw&.start_with?( + "%window-renamed" + ) + puts "event: #{event.raw.strip}" + end end end.wait end diff --git a/gems/libtmux-async/lib/libtmux/async.rb b/gems/libtmux-async/lib/libtmux/async.rb index 8dd1feb1..2ed882b7 100644 --- a/gems/libtmux-async/lib/libtmux/async.rb +++ b/gems/libtmux-async/lib/libtmux/async.rb @@ -21,7 +21,10 @@ def self.attach_cleanup(error, details) error.__send__(:attach_cleanup_errors, details) else error.extend(CleanupDetails) - error.instance_variable_set(:@async_cleanup_errors, ((error.async_cleanup_errors || []) + details).freeze) + error.instance_variable_set( + :@async_cleanup_errors, + ((error.async_cleanup_errors || []) + details).freeze + ) end rescue FrozenError, TypeError nil diff --git a/gems/libtmux-async/lib/libtmux/async/control.rb b/gems/libtmux-async/lib/libtmux/async/control.rb index c4df187d..4ef75075 100644 --- a/gems/libtmux-async/lib/libtmux/async/control.rb +++ b/gems/libtmux-async/lib/libtmux/async/control.rb @@ -45,7 +45,9 @@ def next(timeout: nil) raise StopIteration if @closed end remaining = deadline && deadline - clock - raise DeadlineExceeded.new("control event deadline elapsed", phase: :subscription) if remaining && remaining <= 0 + if remaining && remaining <= 0 + raise DeadlineExceeded.new("control event deadline elapsed", phase: :subscription) + end if remaining ::Async::Task.current.with_timeout(remaining) { @changed.wait } @@ -76,15 +78,26 @@ def initialize(scope:, binding:, session_id:, reconnect: nil, **limits) @writer_changed = ::Async::Notification.new @startup_changed = ::Async::Notification.new @exchanges, @exchange_changed = {}, ::Async::Notification.new - initialize_state(binding_key: binding.key, session_id: session_id, reconnect: reconnect, **limits) - @driver = ControlDriver.new(self, scope, binding.command_prefix + ["-C", "attach-session", "-t", session_id]) + initialize_state( + binding_key: binding.key, + session_id: session_id, + reconnect: reconnect, + **limits + ) + @driver = + ControlDriver.new( + self, + scope, + binding.command_prefix + ["-C", "attach-session", "-t", session_id] + ) @worker = ::Async::Task.new(scope.__send__(:parent)) { @driver.call } end def exchange_request(line, timeout:, cancel:, flow: nil) ensure_owner unless line.is_a?(String) && !line.empty? && !line.b.match?(/[\x00\r\n]/n) - raise ArgumentError, "control input must be one nonempty raw command line without NUL or line endings" + raise ArgumentError, + "control input must be one nonempty raw command line without NUL or line endings" end unless timeout.is_a?(Numeric) && timeout.finite? && timeout.positive? raise ArgumentError, "control timeout must be positive and finite" @@ -92,7 +105,9 @@ def exchange_request(line, timeout:, cancel:, flow: nil) if cancel && (!cancel.respond_to?(:reader) || !cancel.respond_to?(:cancelled?)) raise ArgumentError, "cancel must provide a reader and cancellation state" end - raise CapacityError.new("control command exceeds its byte limit", phase: :admission) if line.bytesize > @max_command + if line.bytesize > @max_command + raise CapacityError.new("control command exceeds its byte limit", phase: :admission) + end Internal::NativeGuard.check_line(line, @release) deadline = clock + timeout @@ -101,16 +116,19 @@ def exchange_request(line, timeout:, cancel:, flow: nil) watcher = failure = nil begin if cancel - watcher = ::Async::Task.new(::Async::Task.current) do - begin - Fiber.scheduler.io_wait(cancel.reader, IO::READABLE) unless cancel.cancelled? - abort_request(request, Cancelled, "control request cancelled") if cancel.cancelled? - rescue ::Async::Cancel - nil - rescue IOError, SystemCallError - abort_request(request, TransportError, "control cancellation reader failed") + watcher = + ::Async::Task.new(::Async::Task.current) do + begin + Fiber.scheduler.io_wait(cancel.reader, IO::READABLE) unless cancel.cancelled? + if cancel.cancelled? + abort_request(request, Cancelled, "control request cancelled") + end + rescue ::Async::Cancel + nil + rescue IOError, SystemCallError + abort_request(request, TransportError, "control cancellation reader failed") + end end - end watcher.run end loop do @@ -183,7 +201,12 @@ def close(timeout: 0.5) end errors.concat(@cleanup_errors) unless errors.empty? - raise TransportError.new("Async control cleanup failed", phase: :retire, pid: @pid, cleanup_errors: errors) + raise TransportError.new( + "Async control cleanup failed", + phase: :retire, + pid: @pid, + cleanup_errors: errors + ) end nil end @@ -196,14 +219,18 @@ def closed? def start @worker.run - ::Async::Task.current.with_timeout(0.4) do - @startup_changed.wait until @pid || @transport_failure || @worker.finished? - end + ::Async::Task + .current + .with_timeout(0.4) do + @startup_changed.wait until @pid || @transport_failure || @worker.finished? + end if !@pid && @transport_failure errors = [] @scope.__send__(:join_task, @worker, clock + 0.4, errors) errors.concat(@cleanup_errors) - self.class.__send__(:attach_cleanup_details, @transport_failure, errors) unless errors.empty? + unless errors.empty? + self.class.__send__(:attach_cleanup_details, @transport_failure, errors) + end raise @transport_failure end @@ -211,7 +238,8 @@ def start end def retired? - (!@worker || @worker.finished?) && (!@driver || @driver.retired?) && (!@exchanges || @exchanges.empty?) + (!@worker || @worker.finished?) && (!@driver || @driver.retired?) && + (!@exchanges || @exchanges.empty?) end def ensure_owner @@ -248,8 +276,16 @@ def finish_transport(failure, errors = nil) @stopping = true @requests.values.each do |request| type = failure ? failure.class : ClosedError - complete(request, error: type.new(failure ? failure.message : "control connection closed", - delivery: request.offset.zero? ? :not_sent : :possibly_sent, phase: :control, pid: @pid)) + complete( + request, + error: + type.new( + failure ? failure.message : "control connection closed", + delivery: request.offset.zero? ? :not_sent : :possibly_sent, + phase: :control, + pid: @pid + ) + ) end @queue.clear @replies.clear @@ -260,8 +296,15 @@ def finish_transport(failure, errors = nil) class ControlDriver < ProcessDriver def initialize(connection, scope, argv) - super(scope, nil, argv.freeze, "".b, Float::INFINITY, nil, - {cleanup_timeout: 0.4, drain_timeout: 0.1}) + super( + scope, + nil, + argv.freeze, + "".b, + Float::INFINITY, + nil, + { cleanup_timeout: 0.4, drain_timeout: 0.1 } + ) @connection = connection end @@ -277,9 +320,13 @@ def call start_task do until @child.observed? || @child.observation_error @child.reader.read_nonblock(16_384, exception: false) - Fiber.scheduler.io_wait(@child.reader, IO::READABLE) unless @child.observed? || @child.observation_error + unless @child.observed? || @child.observation_error + Fiber.scheduler.io_wait(@child.reader, IO::READABLE) + end + end + if @child.observation_error + raise TransportError.new("control exit observation failed", phase: :wait, pid: @pid) end - raise TransportError.new("control exit observation failed", phase: :wait, pid: @pid) if @child.observation_error @exit_deadline = clock + 0.1 end @@ -288,7 +335,12 @@ def call if @exit_deadline remaining = @exit_deadline - clock - raise TransportError.new("control client exited while a pipe remained open", phase: :read) unless remaining.positive? + unless remaining.positive? + raise TransportError.new( + "control client exited while a pipe remained open", + phase: :read + ) + end ::Async::Task.current.with_timeout(remaining) { @changed.wait } else @@ -296,7 +348,18 @@ def call end end rescue Exception => error - failure = error.is_a?(Error) ? error : TransportError.new("Async control transport failed (#{error.class})", phase: :read, pid: @pid) + failure = + ( + if error.is_a?(Error) + error + else + TransportError.new( + "Async control transport failed (#{error.class})", + phase: :read, + pid: @pid + ) + end + ) ensure @connection.__send__(:finish_transport, failure) errors = cleanup @@ -314,7 +377,8 @@ def read_control loop do data = @stdout.read_nonblock(16_384, exception: false) case data - when :wait_readable then Fiber.scheduler.io_wait(@stdout, IO::READABLE) + when :wait_readable + Fiber.scheduler.io_wait(@stdout, IO::READABLE) when nil @connection.instance_variable_get(:@parser).finish raise TransportError.new("control client output closed", phase: :read, pid: @pid) @@ -329,8 +393,10 @@ def read_errors loop do data = @stderr.read_nonblock(16_384, exception: false) case data - when :wait_readable then Fiber.scheduler.io_wait(@stderr, IO::READABLE) - when nil then return + when :wait_readable + Fiber.scheduler.io_wait(@stderr, IO::READABLE) + when nil + return when String @connection.__send__(:receive_stderr, data.bytesize) end @@ -344,7 +410,11 @@ def write_control @connection.instance_variable_get(:@writer_changed).wait next end - written = @writer.write_nonblock(request.wire.byteslice(request.offset, 16_384), exception: false) + written = + @writer.write_nonblock( + request.wire.byteslice(request.offset, 16_384), + exception: false + ) if written == :wait_writable Fiber.scheduler.io_wait(@writer, IO::WRITABLE) else diff --git a/gems/libtmux-async/lib/libtmux/async/process.rb b/gems/libtmux-async/lib/libtmux/async/process.rb index 7f563992..5cf85a79 100644 --- a/gems/libtmux-async/lib/libtmux/async/process.rb +++ b/gems/libtmux-async/lib/libtmux/async/process.rb @@ -53,7 +53,12 @@ def call if failure Async.__send__(:attach_cleanup, failure, errors) elsif !failure && !errors.empty? - failure = TransportError.new("Async command cleanup failed", **details(:retire), cleanup_errors: errors) + failure = + TransportError.new( + "Async command cleanup failed", + **details(:retire), + cleanup_errors: errors + ) end end raise failure if failure @@ -107,8 +112,12 @@ def cleanup else errors << "owned client reaping remains pending after cleanup deadline" end - errors << "child observation failed (#{@child.observation_error.class})" if @child.observation_error - errors << "child reaping failed (#{@child.retirement_error.class})" if @child.retirement_error + if @child.observation_error + errors << "child observation failed (#{@child.observation_error.class})" + end + if @child.retirement_error + errors << "child reaping failed (#{@child.retirement_error.class})" + end @child.close end @tasks.each do |task| @@ -125,7 +134,11 @@ def cleanup end def details(phase) - {delivery: @result || @status ? :observed : (@pid ? :possibly_sent : :not_sent), phase: phase, pid: @pid} + { + delivery: @result || @status ? :observed : (@pid ? :possibly_sent : :not_sent), + phase: phase, + pid: @pid + } end private @@ -142,9 +155,7 @@ def watch_cancellation return unless @cancel start_task do - until @cancel.cancelled? - Fiber.scheduler.io_wait(@cancel.reader, IO::READABLE) - end + Fiber.scheduler.io_wait(@cancel.reader, IO::READABLE) until @cancel.cancelled? @cancelled = true @scope.__send__(:notify) end @@ -165,7 +176,10 @@ def check_budget(phase) end def pipe - IO.pipe.tap { |pair| pair.each(&:binmode); @streams.concat(pair) } + IO.pipe.tap do |pair| + pair.each(&:binmode) + @streams.concat(pair) + end end def spawn @@ -175,32 +189,47 @@ def spawn @stderr, error = pipe @child = Internal::OwnedChild.new begin - @pid = Process.spawn({"TMUX" => nil, "TMUX_PANE" => nil}, [@argv.first, @argv.first], *@argv.drop(1), - in: input, out: output, err: error, close_others: true) + @pid = + Process.spawn( + { "TMUX" => nil, "TMUX_PANE" => nil }, + [@argv.first, @argv.first], + *@argv.drop(1), + in: input, + out: output, + err: error, + close_others: true + ) ensure @child.spawned(@pid) end [input, output, error].each(&:close) end rescue IOError, SystemCallError => error - raise TransportError.new("could not start command (#{error.class})", **details(:spawn)), cause: nil + raise TransportError.new("could not start command (#{error.class})", **details(:spawn)), + cause: nil end def start_task(&block) - task = ::Async::Task.new(::Async::Task.current) do - begin - block.call - rescue ::Async::Cancel - @failure ||= Cancelled.new("command I/O task was cancelled", **details(:read)) unless @retiring - rescue IOError, SystemCallError => error - @failure ||= TransportError.new("command I/O failed (#{error.class})", **details(:read)) unless @retiring - rescue Exception => error - @failure ||= error unless @retiring - ensure - @changed.signal - @scope.__send__(:notify) + task = + ::Async::Task.new(::Async::Task.current) do + begin + block.call + rescue ::Async::Cancel + @failure ||= + Cancelled.new("command I/O task was cancelled", **details(:read)) unless @retiring + rescue IOError, SystemCallError => error + @failure ||= + TransportError.new( + "command I/O failed (#{error.class})", + **details(:read) + ) unless @retiring + rescue Exception => error + @failure ||= error unless @retiring + ensure + @changed.signal + @scope.__send__(:notify) + end end - end @tasks << task task.run task @@ -225,11 +254,16 @@ def read_stream(io, stream) loop do 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 nil + break + when :wait_readable + Fiber.scheduler.io_wait(io, IO::READABLE) when String - appended = buffer.append(bytes) { |retained| @scope.__send__(:retain_output, @ticket, retained) } - raise CapacityError.new("command #{stream} exceeded its byte limit", **details(:read)) unless appended + appended = + buffer.append(bytes) { |retained| @scope.__send__(:retain_output, @ticket, retained) } + unless appended + raise CapacityError.new("command #{stream} exceeded its byte limit", **details(:read)) + end end end @finished_reads += 1 @@ -255,13 +289,18 @@ def write_input def update_exit if @child.observation_error - raise TransportError.new("command exit observation failed (#{@child.observation_error.class})", **details(:wait)) + raise TransportError.new( + "command exit observation failed (#{@child.observation_error.class})", + **details(:wait) + ) end if @child.observed? @drain_deadline ||= clock + @limits.fetch(:drain_timeout) @child.finish_signalling end - raise TransportError.new("command reaping failed", **details(:wait)) if @child.retirement_error + if @child.retirement_error + raise TransportError.new("command reaping failed", **details(:wait)) + end @status = @child.status @changed.signal @@ -274,8 +313,14 @@ def drive raise @failure if @failure if @status && @finished_reads == 2 check_budget(:publish) - @result = CommandResult.new(**@buffers.transform_values(&:bytes), 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 22105514..01e6d714 100644 --- a/gems/libtmux-async/lib/libtmux/async/scope.rb +++ b/gems/libtmux-async/lib/libtmux/async/scope.rb @@ -5,28 +5,75 @@ module LibTmux module Async class Scope - Request = Struct.new(:bytes, :task, :execution, :result, :error, :active, :output_bytes, keyword_init: true) + Request = + Struct.new( + :bytes, + :task, + :execution, + :result, + :error, + :active, + :output_bytes, + keyword_init: true + ) private_constant :Request attr_reader :server - def initialize(parent:, server:, concurrency: 4, max_requests: 32, max_controls: 4, max_queue_bytes: 1 << 22, - max_output_bytes: 1 << 23, stdout_limit: 1 << 20, stderr_limit: 1 << 18, - input_limit: 1 << 20, argv_limit: 1 << 18, cleanup_timeout: 0.5, drain_timeout: 0.5) - unless ::Async::Task.current? && parent.is_a?(::Async::Task) && !parent.finished? && parent.root.equal?(Fiber.scheduler) + def initialize( + parent:, + server:, + concurrency: 4, + max_requests: 32, + max_controls: 4, + max_queue_bytes: 1 << 22, + max_output_bytes: 1 << 23, + stdout_limit: 1 << 20, + stderr_limit: 1 << 18, + input_limit: 1 << 20, + argv_limit: 1 << 18, + cleanup_timeout: 0.5, + drain_timeout: 0.5 + ) + unless ::Async::Task.current? && parent.is_a?(::Async::Task) && !parent.finished? && + parent.root.equal?(Fiber.scheduler) raise ArgumentError, "parent must be a live task on the current Async scheduler" end - [concurrency, max_requests, max_controls, max_queue_bytes, max_output_bytes, stdout_limit, stderr_limit, input_limit, argv_limit].each do |value| - raise ArgumentError, "scope limits must be positive Integers" unless value.is_a?(Integer) && value.positive? + [ + concurrency, + max_requests, + max_controls, + max_queue_bytes, + max_output_bytes, + stdout_limit, + stderr_limit, + input_limit, + argv_limit + ].each do |value| + unless value.is_a?(Integer) && value.positive? + raise ArgumentError, "scope limits must be positive Integers" + end end [cleanup_timeout, drain_timeout].each do |value| - raise ArgumentError, "cleanup deadlines must be positive and finite" unless value.is_a?(Numeric) && value.finite? && value.positive? + unless value.is_a?(Numeric) && value.finite? && value.positive? + raise ArgumentError, "cleanup deadlines must be positive and finite" + end end @parent, @thread, @pid, @scheduler = parent, Thread.current, Process.pid, Fiber.scheduler - @concurrency, @max_requests, @max_queue, @max_output = concurrency, max_requests, max_queue_bytes, max_output_bytes + @concurrency, @max_requests, @max_queue, @max_output = + concurrency, + max_requests, + max_queue_bytes, + max_output_bytes @controls, @max_controls = [], max_controls - @limits = {stdout: stdout_limit, stderr: stderr_limit, input: input_limit, argv: argv_limit, - cleanup_timeout: cleanup_timeout, drain_timeout: drain_timeout}.freeze + @limits = { + stdout: stdout_limit, + stderr: stderr_limit, + input: input_limit, + argv: argv_limit, + cleanup_timeout: cleanup_timeout, + drain_timeout: drain_timeout + }.freeze @requests, @waiting, @maps = [], [], [] @active = @queued_bytes = @output_bytes = 0 @changed = ::Async::Notification.new @@ -36,7 +83,10 @@ def initialize(parent:, server:, concurrency: 4, max_requests: 32, max_controls: def close ensure_owner if @maps.flatten.include?(::Async::Task.current?) - raise ClosedError.new("cannot close an Async scope from its active map worker", phase: :retire) + raise ClosedError.new( + "cannot close an Async scope from its active map worker", + phase: :retire + ) end @closed = true deadline = clock + @limits.fetch(:cleanup_timeout) * 2 @@ -73,7 +123,13 @@ def close errors << "request ownership remains pending" end end - raise TransportError.new("Async scope cleanup failed", phase: :retire, cleanup_errors: errors) unless errors.empty? + unless errors.empty? + raise TransportError.new( + "Async scope cleanup failed", + phase: :retire, + cleanup_errors: errors + ) + end nil end @@ -88,20 +144,41 @@ def closed? # Valid after close on the owning thread, process and scheduler. def diagnostics ensure_owner - {transport: :async_process, closed: !!@closed, admitted_requests: @requests.length, + { + transport: :async_process, + closed: !!@closed, + admitted_requests: @requests.length, reserved_process_slots: @requests.length, - waiting_requests: @waiting.length, active_process_slots: @active, - reserved_request_bytes: @queued_bytes, retained_output_bytes: @output_bytes, - control_connections: @controls.count { |control| !control.__send__(:retired?) }, maps: @maps.length, - limits: {concurrency: @concurrency, max_requests: @max_requests, max_controls: @max_controls, - max_queue_bytes: @max_queue, max_output_bytes: @max_output, - stdout_limit: @limits.fetch(:stdout), stderr_limit: @limits.fetch(:stderr), - input_limit: @limits.fetch(:input), argv_limit: @limits.fetch(:argv), - cleanup_timeout: @limits.fetch(:cleanup_timeout), drain_timeout: @limits.fetch(:drain_timeout), - close_timeout: @limits.fetch(:cleanup_timeout) * 2}.freeze}.freeze + waiting_requests: @waiting.length, + active_process_slots: @active, + reserved_request_bytes: @queued_bytes, + retained_output_bytes: @output_bytes, + control_connections: @controls.count { |control| !control.__send__(:retired?) }, + maps: @maps.length, + limits: { + concurrency: @concurrency, + max_requests: @max_requests, + max_controls: @max_controls, + max_queue_bytes: @max_queue, + max_output_bytes: @max_output, + stdout_limit: @limits.fetch(:stdout), + stderr_limit: @limits.fetch(:stderr), + input_limit: @limits.fetch(:input), + argv_limit: @limits.fetch(:argv), + cleanup_timeout: @limits.fetch(:cleanup_timeout), + drain_timeout: @limits.fetch(:drain_timeout), + close_timeout: @limits.fetch(:cleanup_timeout) * 2 + }.freeze + }.freeze end - def map(values, concurrency: @concurrency, max_items: 1024, max_bytes: @max_output, result_bytes: nil) + def map( + values, + concurrency: @concurrency, + max_items: 1024, + max_bytes: @max_output, + result_bytes: nil + ) ensure_open unless concurrency.is_a?(Integer) && concurrency.positive? && concurrency <= @max_requests raise ArgumentError, "map concurrency must fit scope admission capacity" @@ -110,7 +187,9 @@ def map(values, concurrency: @concurrency, max_items: 1024, max_bytes: @max_outp raise ArgumentError, "map limits must be positive Integers" end raise ArgumentError, "map requires a block" unless block_given? - raise ArgumentError, "result_bytes must be callable" if result_bytes && !result_bytes.respond_to?(:call) + if result_bytes && !result_bytes.respond_to?(:call) + raise ArgumentError, "result_bytes must be callable" + end source = values.to_enum tasks, results = [], [] @@ -119,40 +198,48 @@ def map(values, concurrency: @concurrency, max_items: 1024, max_bytes: @max_outp failure = nil begin concurrency.times do - task = ::Async::Task.new(@parent) do - begin - loop do - break if failure - value = begin - source.next - rescue StopIteration - break - end - index = next_index - raise CapacityError.new("ordered map item limit reached", phase: :admission) if index >= max_items - - next_index += 1 - result = yield value - bytes = result_bytes ? result_bytes.call(result) : retained_bytes(result) - unless bytes.is_a?(Integer) && bytes >= 0 - raise ArgumentError, "result_bytes must return a nonnegative Integer" + task = + ::Async::Task.new(@parent) do + begin + loop do + break if failure + value = + begin + source.next + rescue StopIteration + break + end + index = next_index + if index >= max_items + raise CapacityError.new("ordered map item limit reached", phase: :admission) + end + + next_index += 1 + result = yield value + bytes = result_bytes ? result_bytes.call(result) : retained_bytes(result) + unless bytes.is_a?(Integer) && bytes >= 0 + raise ArgumentError, "result_bytes must return a nonnegative Integer" + end + if retained + bytes > max_bytes || @output_bytes + bytes > @max_output + raise CapacityError.new( + "ordered map retained output limit reached", + phase: :read, + delivery: :observed + ) + end + retained += bytes + @output_bytes += bytes + results[index] = result end - if retained + bytes > max_bytes || @output_bytes + bytes > @max_output - raise CapacityError.new("ordered map retained output limit reached", phase: :read, delivery: :observed) + rescue Exception => error + if failure && error.is_a?(Error) + Async.__send__(:attach_cleanup, failure, error.cleanup_errors) end - retained += bytes - @output_bytes += bytes - results[index] = result + failure ||= error + ensure + notify end - rescue Exception => error - if failure && error.is_a?(Error) - Async.__send__(:attach_cleanup, failure, error.cleanup_errors) - end - failure ||= error - ensure - notify end - end tasks << task task.run end @@ -172,7 +259,12 @@ def map(values, concurrency: @concurrency, max_items: 1024, max_bytes: @max_outp if failure Async.__send__(:attach_cleanup, failure, errors) elsif !failure && !errors.empty? - failure = TransportError.new("ordered map cleanup failed", phase: :retire, cleanup_errors: errors) + failure = + TransportError.new( + "ordered map cleanup failed", + phase: :retire, + cleanup_errors: errors + ) end end raise failure if failure @@ -188,12 +280,20 @@ def open_control(binding:, session_id:, **options) ensure_open Internal::TmuxVersion.require_control(binding.release) @controls.reject!(&:closed?) - raise CapacityError.new("Async control capacity is exhausted", phase: :admission) if @controls.length >= @max_controls + if @controls.length >= @max_controls + raise CapacityError.new("Async control capacity is exhausted", phase: :admission) + end control = ControlConnection.allocate @controls << control begin - control.__send__(:initialize, scope: self, binding: binding, session_id: session_id, **options) + control.__send__( + :initialize, + scope: self, + binding: binding, + session_id: session_id, + **options + ) control.__send__(:start) rescue Exception @controls.delete(control) if control.__send__(:retired?) @@ -236,84 +336,126 @@ def cancel_task(task, deadline, errors) def retained_bytes(value) nodes = 0 visiting = {} - measure = lambda do |item, depth| - nodes += 1 - if nodes > 2048 || depth > 32 - raise CapacityError.new("ordered map result structure limit reached", phase: :read, delivery: :observed) - end - case item - when nil, true, false, Float then 8 - when Integer then [8, (item.bit_length + 7) / 8].max - when Symbol then item.to_s.bytesize - when String then item.bytesize - when CommandResult then measure.call([item.stdout, item.stderr, item.argv], depth + 1) - when Array, Hash - if visiting[item.object_id] - raise CapacityError.new("ordered map result contains a cycle", phase: :read, delivery: :observed) + measure = + lambda do |item, depth| + nodes += 1 + if nodes > 2048 || depth > 32 + raise CapacityError.new( + "ordered map result structure limit reached", + phase: :read, + delivery: :observed + ) end - visiting[item.object_id] = true - begin - if item.is_a?(Array) - 8 + item.sum { |child| measure.call(child, depth + 1) } - else - 8 + item.sum { |key, child| measure.call(key, depth + 1) + measure.call(child, depth + 1) } + case item + when nil, true, false, Float + 8 + when Integer + [8, (item.bit_length + 7) / 8].max + when Symbol + item.to_s.bytesize + when String + item.bytesize + when CommandResult + measure.call([item.stdout, item.stderr, item.argv], depth + 1) + when Array, Hash + if visiting[item.object_id] + raise CapacityError.new( + "ordered map result contains a cycle", + phase: :read, + delivery: :observed + ) end - ensure - visiting.delete(item.object_id) + visiting[item.object_id] = true + begin + if item.is_a?(Array) + 8 + item.sum { |child| measure.call(child, depth + 1) } + else + 8 + + item.sum do |key, child| + measure.call(key, depth + 1) + measure.call(child, depth + 1) + end + end + ensure + visiting.delete(item.object_id) + end + else + raise UnsupportedFeatureError.new( + "ordered map application results require a result_bytes estimator", + phase: :read, + delivery: :observed + ) end - else - raise UnsupportedFeatureError.new("ordered map application results require a result_bytes estimator", phase: :read, delivery: :observed) end - end measure.call(value, 0) end def ensure_owner - unless Process.pid == @pid && Thread.current.equal?(@thread) && Fiber.scheduler.equal?(@scheduler) - raise ClosedError.new("Async scope belongs to another thread, process or scheduler", phase: :admission) + unless Process.pid == @pid && Thread.current.equal?(@thread) && + Fiber.scheduler.equal?(@scheduler) + raise ClosedError.new( + "Async scope belongs to another thread, process or scheduler", + phase: :admission + ) end end def ensure_open ensure_owner - raise ClosedError.new("Async scope is closed", phase: :admission) if @closed || @parent.finished? + if @closed || @parent.finished? + raise ClosedError.new("Async scope is closed", phase: :admission) + end end 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 - unless argv.is_a?(Array) && !argv.empty? && argv.all? { |arg| arg.is_a?(String) && !arg.include?("\0") } + unless argv.is_a?(Array) && !argv.empty? && + argv.all? { |arg| arg.is_a?(String) && !arg.include?("\0") } raise ArgumentError, "argv must be a nonempty Array of Strings without NUL" end raise ArgumentError, "input must be a String" unless input.is_a?(String) if cancel && (!cancel.respond_to?(:reader) || !cancel.respond_to?(:cancelled?)) raise ArgumentError, "cancel must provide a reader and cancellation state" end - raise Cancelled.new("command cancelled before admission", phase: :admission) if cancel&.cancelled? - raise DeadlineExceeded.new("command deadline elapsed before admission", phase: :admission) if clock >= deadline + if cancel&.cancelled? + raise Cancelled.new("command cancelled before admission", phase: :admission) + end + if clock >= deadline + raise DeadlineExceeded.new("command deadline elapsed before admission", phase: :admission) + end argv_bytes = argv.sum { |arg| arg.bytesize + 1 } bytes = input.bytesize + argv_bytes if input.bytesize > @limits.fetch(:input) || argv_bytes > @limits.fetch(:argv) || - @requests.length >= @max_requests || @queued_bytes + bytes > @max_queue + @requests.length >= @max_requests || @queued_bytes + bytes > @max_queue raise CapacityError.new("Async request admission limit reached", phase: :admission) end ticket = Request.new(bytes: bytes, output_bytes: 0) @requests << ticket @waiting << ticket @queued_bytes += bytes - ticket.execution = ProcessDriver.new(self, ticket, argv.map { |arg| arg.dup.freeze }.freeze, - input.b.freeze, deadline, cancel, @limits, stdout_tail: stdout_tail) - ticket.task = ::Async::Task.new(@parent) do - begin - ticket.result = ticket.execution.call - rescue Exception => error - ticket.error = error - ensure - notify + ticket.execution = + ProcessDriver.new( + self, + ticket, + argv.map { |arg| arg.dup.freeze }.freeze, + input.b.freeze, + deadline, + cancel, + @limits, + stdout_tail: stdout_tail + ) + ticket.task = + ::Async::Task.new(@parent) do + begin + ticket.result = ticket.execution.call + rescue Exception => error + ticket.error = error + ensure + notify + end end - end begin ticket.task.run ticket.task.wait @@ -324,7 +466,9 @@ def execute(argv, input: "".b, timeout: 5.0, cancel: nil, stdout_tail: nil) deadline = clock + @limits.fetch(:cleanup_timeout) * 2 cancel_task(ticket.task, deadline, errors) join_task(ticket.task, deadline, errors) - ticket.error = failure || ticket.error || Cancelled.new("command caller was cancelled", **ticket.execution.details(:read)) + ticket.error = + failure || ticket.error || + Cancelled.new("command caller was cancelled", **ticket.execution.details(:read)) Async.__send__(:attach_cleanup, ticket.error, errors) end end @@ -341,7 +485,9 @@ def acquire(ticket, deadline, check_cancel) loop do check_cancel.call(:admission) raise ClosedError.new("Async scope is closed", phase: :admission) if @closed - raise DeadlineExceeded.new("command deadline elapsed in admission", phase: :admission) if clock >= deadline + if clock >= deadline + raise DeadlineExceeded.new("command deadline elapsed in admission", phase: :admission) + end if @waiting.first.equal?(ticket) && @active < @concurrency @waiting.shift @@ -368,7 +514,10 @@ def release_active(ticket) def retain_output(ticket, bytes) if @output_bytes + bytes > @max_output - raise CapacityError.new("Async retained output limit reached", **ticket.execution.details(:read)) + raise CapacityError.new( + "Async retained output limit reached", + **ticket.execution.details(:read) + ) end @output_bytes += bytes ticket.output_bytes += bytes diff --git a/gems/libtmux-async/lib/libtmux/async/server.rb b/gems/libtmux-async/lib/libtmux/async/server.rb index 82d822cf..260bb0d9 100644 --- a/gems/libtmux-async/lib/libtmux/async/server.rb +++ b/gems/libtmux-async/lib/libtmux/async/server.rb @@ -5,11 +5,15 @@ module Async class Server < LibTmux::Server def initialize(scope, source) raise ArgumentError, "scope must be a LibTmux::Async::Scope" unless scope.is_a?(Scope) - raise ArgumentError, "server must be a bound LibTmux::Server" unless source.is_a?(LibTmux::Server) + unless source.is_a?(LibTmux::Server) + raise ArgumentError, "server must be a bound LibTmux::Server" + end @scope, @source = scope, source @mutex = Mutex.new - source.__send__(:with_bound_endpoint) { |endpoint, pin, release| @endpoint, @pin, @release = endpoint, pin, release } + source.__send__(:with_bound_endpoint) do |endpoint, pin, release| + @endpoint, @pin, @release = endpoint, pin, release + end end def run(argv, input: "".b, timeout: 5.0, cancel: nil) @@ -51,31 +55,56 @@ def open_control(session:, **options) end def attach(**) - raise UnsupportedFeatureError.new("interactive terminal attachment requires the blocking core facade", phase: :admission) + raise UnsupportedFeatureError.new( + "interactive terminal attachment requires the blocking core facade", + phase: :admission + ) end def self.start(**) - raise UnsupportedFeatureError.new("create an owned core server before opening its Async scope", phase: :admission) + raise UnsupportedFeatureError.new( + "create an owned core server before opening its Async scope", + phase: :admission + ) end def self.open(**) - raise UnsupportedFeatureError.new("open the core server, then call LibTmux::Async.open(server:) to get an Async facade", phase: :admission) + raise UnsupportedFeatureError.new( + "open the core server, then call LibTmux::Async.open(server:) to get an Async facade", + phase: :admission + ) end private_class_method :new private - def dispatch(argv, input: "".b, timeout: 5.0, cancel: nil, repaired_break: false, stdout_tail: nil) + def dispatch( + argv, + input: "".b, + timeout: 5.0, + cancel: nil, + repaired_break: false, + stdout_tail: nil + ) ensure_owner ensure_open validate_argv(argv) - raise ArgumentError, "raw commands cannot override endpoint flags" if argv.first.start_with?("-") + if argv.first.start_with?("-") + raise ArgumentError, "raw commands cannot override endpoint flags" + end 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, stdout_tail: stdout_tail) + 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/libtmux-async.gemspec b/gems/libtmux-async/libtmux-async.gemspec index 7c9017cb..eb76d259 100644 --- a/gems/libtmux-async/libtmux-async.gemspec +++ b/gems/libtmux-async/libtmux-async.gemspec @@ -7,7 +7,8 @@ Gem::Specification.new do |spec| spec.version = LibTmux::Async::VERSION spec.authors = ["libtmux contributors"] spec.summary = "Optional Async integration for libtmux" - spec.description = "Run concurrent libtmux commands and bounded control subscriptions inside application-owned Async tasks." + spec.description = + "Run concurrent libtmux commands and bounded control subscriptions inside application-owned Async tasks." spec.homepage = "https://github.com/libtmux/libtmux-ruby" spec.license = "MIT" spec.required_ruby_version = ">= 3.3" @@ -18,8 +19,11 @@ Gem::Specification.new do |spec| } spec.require_paths = ["lib"] spec.files = %w[ - LICENSE README.md CHANGELOG.md - assets/logo.svg assets/logo.png + LICENSE + README.md + CHANGELOG.md + assets/logo.svg + assets/logo.png lib/libtmux/async.rb lib/libtmux/async/version.rb lib/libtmux/async/process.rb diff --git a/gems/libtmux-mcp/README.md b/gems/libtmux-mcp/README.md index 62c69fc2..9756de8e 100644 --- a/gems/libtmux-mcp/README.md +++ b/gems/libtmux-mcp/README.md @@ -99,7 +99,11 @@ A client that reads a JSON configuration, such as Claude Desktop's "mcpServers": { "tmux": { "command": "libtmux-mcp", - "args": ["--socket-name", "agent", "--start-session", "work", "--endpoint", "dev"] + "args": [ + "--socket-name", "agent", + "--start-session", "work", + "--endpoint", "dev" + ] } } } @@ -321,11 +325,21 @@ boundaries. ```ruby -application = LibTmux::MCP::Application.new(server: scope.server, endpoint_name: "example") +application = + LibTmux::MCP::Application.new( + server: scope.server, + endpoint_name: "example" + ) sdk = application.sdk_server input, client_input = IO.pipe client_output, output = IO.pipe -transport = LibTmux::MCP::StdioTransport.new(server: sdk, parent: parent, input: input, output: output) +transport = + LibTmux::MCP::StdioTransport.new( + server: sdk, + parent: parent, + input: input, + output: output + ) runner = parent.async { transport.run } ``` diff --git a/gems/libtmux-mcp/lib/libtmux/mcp/application.rb b/gems/libtmux-mcp/lib/libtmux/mcp/application.rb index b0bf7e59..20ca8d36 100644 --- a/gems/libtmux-mcp/lib/libtmux/mcp/application.rb +++ b/gems/libtmux-mcp/lib/libtmux/mcp/application.rb @@ -34,7 +34,12 @@ def close @token.close @token = nil rescue Exception => error - ProcessIdentity.attach_cleanup(failure, ["cancellation token retirement failed (#{error.class})"]) if failure + if failure + ProcessIdentity.attach_cleanup( + failure, + ["cancellation token retirement failed (#{error.class})"] + ) + end failure ||= error end end @@ -47,64 +52,126 @@ def close attr_reader :tools - def initialize(server:, endpoint_name:, enabled_tools: Catalog::READ_ONLY, - max_captures: 16, max_capture_bytes: 1 << 23, capture_ttl: 30, - request_timeout: 5, max_response_bytes: 1 << 20) - raise ArgumentError, "MCP requires an application-owned Async server facade" unless server.is_a?(LibTmux::Async::Server) - unless endpoint_name.is_a?(String) && /\A[A-Za-z0-9][A-Za-z0-9_.-]{0,127}\z/.match?(endpoint_name) + def initialize( + server:, + endpoint_name:, + enabled_tools: Catalog::READ_ONLY, + max_captures: 16, + max_capture_bytes: 1 << 23, + capture_ttl: 30, + request_timeout: 5, + max_response_bytes: 1 << 20 + ) + unless server.is_a?(LibTmux::Async::Server) + raise ArgumentError, "MCP requires an application-owned Async server facade" + end + unless endpoint_name.is_a?(String) && + /\A[A-Za-z0-9][A-Za-z0-9_.-]{0,127}\z/.match?(endpoint_name) raise ArgumentError, "endpoint_name must be a public endpoint alias" end unless enabled_tools.is_a?(Array) && (enabled_tools - Catalog::NAMES).empty? raise ArgumentError, "enabled_tools must name implemented catalog tools" end - unless [max_captures, max_capture_bytes, max_response_bytes].all? { |n| n.is_a?(Integer) && n.positive? } + unless [max_captures, max_capture_bytes, max_response_bytes].all? { |n| + n.is_a?(Integer) && n.positive? + } raise ArgumentError, "MCP capacity limits must be positive Integers" end - if (enabled_tools & Catalog::MUTATIONS).any? && max_response_bytes < Catalog::MIN_MUTATION_RESPONSE_BYTES + if (enabled_tools & Catalog::MUTATIONS).any? && + max_response_bytes < Catalog::MIN_MUTATION_RESPONSE_BYTES raise ArgumentError, "MCP mutation response capacity must be at least 4096 bytes" end - unless [capture_ttl, request_timeout].all? { |n| n.is_a?(Numeric) && n.finite? && n.positive? } + unless [capture_ttl, request_timeout].all? { |n| + n.is_a?(Numeric) && n.finite? && n.positive? + } raise ArgumentError, "MCP deadlines must be positive and finite" end @server, @endpoint = server, endpoint_name.dup.freeze @enabled = Catalog::NAMES.select { |name| enabled_tools.include?(name) }.freeze - @limits = {"max_captures" => max_captures, "max_capture_bytes" => max_capture_bytes, - "capture_ttl_seconds" => capture_ttl, "request_timeout_seconds" => request_timeout, - "max_response_bytes" => max_response_bytes, "max_mutation_bytes" => Catalog::MUTATION_BYTES, + @limits = { + "max_captures" => max_captures, + "max_capture_bytes" => max_capture_bytes, + "capture_ttl_seconds" => capture_ttl, + "request_timeout_seconds" => request_timeout, + "max_response_bytes" => max_response_bytes, + "max_mutation_bytes" => Catalog::MUTATION_BYTES, "max_observers" => max_captures, - "max_enrollments" => 8, "default_enrollment_seconds" => 60, "max_enrollment_seconds" => 300, - "max_script_bytes" => 65_536, "default_run_output_bytes" => 65_536, "max_run_output_bytes" => 262_144, - "min_mutation_response_bytes" => Catalog::MIN_MUTATION_RESPONSE_BYTES}.freeze + "max_enrollments" => 8, + "default_enrollment_seconds" => 60, + "max_enrollment_seconds" => 300, + "max_script_bytes" => 65_536, + "default_run_output_bytes" => 65_536, + "max_run_output_bytes" => 262_144, + "min_mutation_response_bytes" => Catalog::MIN_MUTATION_RESPONSE_BYTES + }.freeze @thread, @pid, @scheduler = Thread.current, Process.pid, Fiber.scheduler @captures, @retained_bytes = {}, 0 @observers, @retiring = [], [] @calls, @calls_changed = {}, ::Async::Notification.new @parent = ::Async::Task.current application = self - @tools = @enabled.map do |name| - CatalogTool.define(name: name, description: Catalog.description(name), - input_schema: Catalog.input(name), output_schema: Catalog.output(name), meta: Catalog.meta(name), - annotations: {read_only_hint: false, destructive_hint: Catalog::MUTATIONS.include?(name), idempotent_hint: false, open_world_hint: false}) do |server_context: nil, **arguments| - application.call(name, arguments, cancellation: server_context&.cancellation) - end - end.freeze + @tools = + @enabled + .map do |name| + CatalogTool.define( + name: name, + description: Catalog.description(name), + input_schema: Catalog.input(name), + output_schema: Catalog.output(name), + meta: Catalog.meta(name), + annotations: { + read_only_hint: false, + destructive_hint: Catalog::MUTATIONS.include?(name), + idempotent_hint: false, + open_world_hint: false + } + ) do |server_context: nil, **arguments| + application.call(name, arguments, cancellation: server_context&.cancellation) + end + end + .freeze @by_name = @tools.to_h { |tool| [tool.name_value, tool] }.freeze end def sdk_server - ::MCP::Server.new(name: "libtmux", version: VERSION, tools: tools, - instructions: "Use discovery before operations. Captured metadata is interval evidence, not an atomic snapshot.", - configuration: ::MCP::Configuration.new(validate_tool_call_arguments: false, validate_tool_call_results: true), - capabilities: {tools: {listChanged: false}}, ttl_ms: 0, cache_scope: "private").tap do |sdk| - Resources.new(application: self, endpoint_name: @endpoint, enabled_tools: @enabled, - max_response_bytes: @limits.fetch("max_response_bytes")).install(sdk) - end + ::MCP::Server + .new( + name: "libtmux", + version: VERSION, + tools: tools, + instructions: + "Use discovery before operations. Captured metadata is interval evidence, not an atomic snapshot.", + configuration: + ::MCP::Configuration.new( + validate_tool_call_arguments: false, + validate_tool_call_results: true + ), + capabilities: { + tools: { + listChanged: false + } + }, + ttl_ms: 0, + cache_scope: "private" + ) + .tap do |sdk| + Resources.new( + application: self, + endpoint_name: @endpoint, + enabled_tools: @enabled, + max_response_bytes: @limits.fetch("max_response_bytes") + ).install(sdk) + end end def invite_shell(reference, timeout: nil, expires_in: 60, cancellation: nil) shell_request(cancellation) do |registry, token| - registry.invite(reference, timeout: timeout || @limits.fetch("request_timeout_seconds"), - expires_in: expires_in, cancel: token) + registry.invite( + reference, + timeout: timeout || @limits.fetch("request_timeout_seconds"), + expires_in: expires_in, + cancel: token + ) end end @@ -115,12 +182,17 @@ def accept_shell(invitation, timeout: nil, cancellation: nil) end def call(name, arguments = {}, cancellation: nil) - unless Process.pid == @pid && Thread.current.equal?(@thread) && Fiber.scheduler.equal?(@scheduler) + unless Process.pid == @pid && Thread.current.equal?(@thread) && + Fiber.scheduler.equal?(@scheduler) raise ClosedError.new("MCP application belongs to another scheduler", phase: :admission) end - return failure_response("policy_denied", "The configured policy denies this operation.") unless @enabled.include?(name) + unless @enabled.include?(name) + return failure_response("policy_denied", "The configured policy denies this operation.") + end return failure_response("closed", "The application is closed.") if @closed - return failure_response("capacity", "Request cleanup remains pending.") unless @retiring.empty? + unless @retiring.empty? + return failure_response("capacity", "Request cleanup remains pending.") + end begin tool = @by_name.fetch(name) @@ -128,71 +200,129 @@ def call(name, arguments = {}, cancellation: nil) tool.output_schema_value begin wire = JSON.generate(arguments) - raise CapacityError.new("MCP input exceeds its byte limit", phase: :admission) if wire.bytesize > 1 << 20 - arguments = JSON.parse(wire, max_nesting: 68, allow_nan: false, allow_duplicate_key: false) + if wire.bytesize > 1 << 20 + raise CapacityError.new("MCP input exceeds its byte limit", phase: :admission) + end + arguments = + JSON.parse(wire, max_nesting: 68, allow_nan: false, allow_duplicate_key: false) input_schema.validate_arguments(arguments) rescue ::MCP::Tool::InputSchema::ValidationError message = tool.invalid_arguments_message(arguments).byteslice(0, 256).scrub("") return failure_response("invalid_input", message) rescue JSON::JSONError - return failure_response("invalid_input", "Arguments must be valid JSON within the nesting limit.") + return( + failure_response( + "invalid_input", + "Arguments must be valid JSON within the nesting limit." + ) + ) end token = Internal::Cancellation.new @calls[token] = ::Async::Task.current callback = cancellation&.on_cancel { token.cancel } raise Cancelled.new("MCP request was cancelled", phase: :admission) if token.cancelled? - result = case name - when "tmux_capabilities" then capabilities(token) - when "tmux_snapshot" then snapshot(arguments, token) - when "tmux_capture" then capture_screen(arguments, token) - when "tmux_wait" then wait_for_observation(arguments, token) - when "tmux_run" then run_script(arguments, token) - else - mutation = Mutation.new(server: @server, arguments: arguments, timeout: @limits.fetch("request_timeout_seconds"), - cancel: token, max_snapshot_bytes: [@limits.fetch("max_capture_bytes"), 1 << 20].min) - mutation.call(name) - end - structured = {"ok" => true, "data" => result} + result = + case name + when "tmux_capabilities" + capabilities(token) + when "tmux_snapshot" + snapshot(arguments, token) + when "tmux_capture" + capture_screen(arguments, token) + when "tmux_wait" + wait_for_observation(arguments, token) + when "tmux_run" + run_script(arguments, token) + else + mutation = + Mutation.new( + server: @server, + arguments: arguments, + timeout: @limits.fetch("request_timeout_seconds"), + cancel: token, + max_snapshot_bytes: [@limits.fetch("max_capture_bytes"), 1 << 20].min + ) + mutation.call(name) + end + structured = { "ok" => true, "data" => result } validate_response_size(structured) tool.output_schema_value.validate_result(structured) - ::MCP::Tool::Response.new([{type: "text", text: "#{name} completed; structuredContent contains the result."}], structured_content: structured) + ::MCP::Tool::Response.new( + [{ type: "text", text: "#{name} completed; structuredContent contains the result." }], + structured_content: structured + ) ensure finish_request(token, cancellation, callback, primary: $!) end rescue CursorError, Observation::StaleCursor - failure_response("stale_cursor", "The cursor is unknown, expired, or outside its captured result.") - rescue LibTmux::Error, SystemCallError, IOError, ArgumentError, JSON::JSONError, ::MCP::Tool::OutputSchema::ValidationError => error - code = {InvalidFilterError => "invalid_filter", FieldDecodeError => "decode_error", - IncompleteSnapshotError => "incomplete_snapshot", Cancelled => "cancelled", - DeadlineExceeded => "deadline", CapacityError => "capacity", TargetNotFoundError => "stale_target", - CommandError => "command_failed", UnsupportedFeatureError => "unsupported", ClosedError => "closed", - Observation::LostObservation => "observation_lost", Observation::PaneDied => "pane_died"}.fetch(error.class, "transport_error") - delivery = if error.respond_to?(:delivery) - mutation ? mutation.delivery(error) : error.delivery - else - token ? :possibly_sent : :not_sent - end + failure_response( + "stale_cursor", + "The cursor is unknown, expired, or outside its captured result." + ) + rescue LibTmux::Error, + SystemCallError, + IOError, + ArgumentError, + JSON::JSONError, + ::MCP::Tool::OutputSchema::ValidationError => error + code = { + InvalidFilterError => "invalid_filter", + FieldDecodeError => "decode_error", + IncompleteSnapshotError => "incomplete_snapshot", + Cancelled => "cancelled", + DeadlineExceeded => "deadline", + CapacityError => "capacity", + TargetNotFoundError => "stale_target", + CommandError => "command_failed", + UnsupportedFeatureError => "unsupported", + ClosedError => "closed", + Observation::LostObservation => "observation_lost", + Observation::PaneDied => "pane_died" + }.fetch(error.class, "transport_error") + delivery = + if error.respond_to?(:delivery) + mutation ? mutation.delivery(error) : error.delivery + else + token ? :possibly_sent : :not_sent + end delivery = :observed if result - effects = if name == "tmux_run" - receipt = result && result["authorization"] || (error.run_receipt if error.respond_to?(:run_receipt)) - delivery = error.run_delivery || delivery if error.respond_to?(:run_delivery) - completion = result && result["completion"] || (error.run_completion if error.respond_to?(:run_completion)) - {"state" => receipt ? "known" : delivery == :not_sent ? "none" : "unknown", "authorization" => receipt, - "completion" => completion || {"state" => "unobserved"}} - elsif Catalog::MUTATIONS.include?(name) - created = result && result["created"] - {"state" => created ? "known" : delivery == :not_sent ? "none" : "unknown", "created" => created || []} - end - message = if delivery == :not_sent && LibTmux::Internal::TmuxVersion.refusal?(error) - LibTmux::Internal::TmuxVersion.hint - elsif error.is_a?(Observation::PaneDied) - "The pane, or its tmux server, ended before the awaited text appeared." - else - "The operation could not establish its requested result." - end - failure_response(code, message, delivery.to_s, effects: effects, - capture: (error.capture if error.is_a?(Observation::PaneDied))) + effects = + if name == "tmux_run" + receipt = + result && result["authorization"] || + (error.run_receipt if error.respond_to?(:run_receipt)) + delivery = error.run_delivery || delivery if error.respond_to?(:run_delivery) + completion = + result && result["completion"] || + (error.run_completion if error.respond_to?(:run_completion)) + { + "state" => receipt ? "known" : delivery == :not_sent ? "none" : "unknown", + "authorization" => receipt, + "completion" => completion || { "state" => "unobserved" } + } + elsif Catalog::MUTATIONS.include?(name) + created = result && result["created"] + { + "state" => created ? "known" : delivery == :not_sent ? "none" : "unknown", + "created" => created || [] + } + end + message = + if delivery == :not_sent && LibTmux::Internal::TmuxVersion.refusal?(error) + LibTmux::Internal::TmuxVersion.hint + elsif error.is_a?(Observation::PaneDied) + "The pane, or its tmux server, ended before the awaited text appeared." + else + "The operation could not establish its requested result." + end + failure_response( + code, + message, + delivery.to_s, + effects: effects, + capture: (error.capture if error.is_a?(Observation::PaneDied)) + ) end def inspect @@ -200,11 +330,15 @@ def inspect end def close - unless Process.pid == @pid && Thread.current.equal?(@thread) && Fiber.scheduler.equal?(@scheduler) + unless Process.pid == @pid && Thread.current.equal?(@thread) && + Fiber.scheduler.equal?(@scheduler) raise ClosedError.new("MCP application belongs to another scheduler", phase: :retire) end if @calls.value?(::Async::Task.current) - raise ClosedError.new("cannot close an MCP application from its active request", phase: :retire) + raise ClosedError.new( + "cannot close an MCP application from its active request", + phase: :retire + ) end @closed = true errors = [] @@ -246,7 +380,11 @@ def close end @retiring.dup.each do |resource| begin - resource.is_a?(Observation) ? resource.close(timeout: [deadline - clock, 0].max) : resource.close + if resource.is_a?(Observation) + resource.close(timeout: [deadline - clock, 0].max) + else + resource.close + end @observers.delete(resource) @retiring.delete(resource) rescue Exception => error @@ -258,7 +396,13 @@ def close ProcessIdentity.attach_cleanup(interrupted, errors) unless errors.empty? raise interrupted end - raise TransportError.new("MCP application cleanup remains pending", phase: :retire, cleanup_errors: errors) unless errors.empty? + unless errors.empty? + raise TransportError.new( + "MCP application cleanup remains pending", + phase: :retire, + cleanup_errors: errors + ) + end nil end @@ -266,12 +410,20 @@ def close private def shell_request(cancellation) - unless Process.pid == @pid && Thread.current.equal?(@thread) && Fiber.scheduler.equal?(@scheduler) + unless Process.pid == @pid && Thread.current.equal?(@thread) && + Fiber.scheduler.equal?(@scheduler) raise ClosedError.new("MCP application belongs to another scheduler", phase: :admission) end - raise UnsupportedFeatureError.new("shell enrollment is disabled by policy", phase: :admission) unless @enabled.include?("tmux_run") + unless @enabled.include?("tmux_run") + raise UnsupportedFeatureError.new( + "shell enrollment is disabled by policy", + phase: :admission + ) + end raise ClosedError.new("MCP application is closed", phase: :admission) if @closed - raise CapacityError.new("request cleanup remains pending", phase: :admission) unless @retiring.empty? + unless @retiring.empty? + raise CapacityError.new("request cleanup remains pending", phase: :admission) + end token = Internal::Cancellation.new @calls[token] = ::Async::Task.current @@ -298,7 +450,12 @@ def finish_request(token, cancellation, callback, primary:) elsif error.is_a?(::Async::Cancel) failure = error else - failure = TransportError.new("request cleanup remains pending", phase: :retire, cleanup_errors: details) + failure = + TransportError.new( + "request cleanup remains pending", + phase: :retire, + cleanup_errors: details + ) end ensure @calls.delete(token) if token @@ -308,41 +465,77 @@ def finish_request(token, cancellation, callback, primary:) end def shell_registry - @shells ||= EnrollmentRegistry.new(server: @server, parent: @parent, max_enrollments: @limits.fetch("max_enrollments")) + @shells ||= + EnrollmentRegistry.new( + server: @server, + parent: @parent, + max_enrollments: @limits.fetch("max_enrollments") + ) end def run_script(arguments, token) - stdout_limit, stderr_limit = arguments.fetch("stdout_limit", 65_536), arguments.fetch("stderr_limit", 65_536) + stdout_limit, stderr_limit = + arguments.fetch("stdout_limit", 65_536), + arguments.fetch("stderr_limit", 65_536) if 4096 + 6 * (stdout_limit + stderr_limit) > @limits.fetch("max_response_bytes") raise CapacityError.new("authored output exceeds response reservation", phase: :admission) end target = arguments.fetch("target") - reference = @server.__send__(:with_bound_endpoint) do |_endpoint, pin| - unless target.fetch("generation") == pin.key - raise TargetNotFoundError.new("authored target belongs to another binding", phase: :admission) + reference = + @server.__send__(:with_bound_endpoint) do |_endpoint, pin| + unless target.fetch("generation") == pin.key + raise TargetNotFoundError.new( + "authored target belongs to another binding", + phase: :admission + ) + end + EntityRef.__send__(:new, binding_key: pin.key, kind: :pane, id: target.fetch("id")) end - EntityRef.__send__(:new, binding_key: pin.key, kind: :pane, id: target.fetch("id")) - end - result = shell_registry.run(reference, script: arguments.fetch("script"), timeout: @limits.fetch("request_timeout_seconds"), - cancel: token, stdout_limit: stdout_limit, stderr_limit: stderr_limit) - {"target" => target, "authorization" => result.receipt, - "completion" => {"state" => result.signal ? "signaled" : "exited", "exit_status" => result.exit_status, "signal" => result.signal}, - "stdout" => run_bytes(result.stdout), "stderr" => run_bytes(result.stderr)} + result = + shell_registry.run( + reference, + script: arguments.fetch("script"), + timeout: @limits.fetch("request_timeout_seconds"), + cancel: token, + stdout_limit: stdout_limit, + stderr_limit: stderr_limit + ) + { + "target" => target, + "authorization" => result.receipt, + "completion" => { + "state" => result.signal ? "signaled" : "exited", + "exit_status" => result.exit_status, + "signal" => result.signal + }, + "stdout" => run_bytes(result.stdout), + "stderr" => run_bytes(result.stderr) + } end def run_bytes(bytes) text = bytes.dup.force_encoding(Encoding::UTF_8) valid = text.valid_encoding? - {"encoding" => valid ? "utf-8" : "base64", "data" => valid ? text : [bytes].pack("m0"), - "bytes" => bytes.bytesize, "truncated" => false} + { + "encoding" => valid ? "utf-8" : "base64", + "data" => valid ? text : [bytes].pack("m0"), + "bytes" => bytes.bytesize, + "truncated" => false + } end def observation(arguments, cancel) if !@retiring.empty? || @observers.length >= @limits.fetch("max_observers") raise CapacityError.new("observation admission is full or retiring", phase: :admission) end - observer = Observation.new(server: @server, arguments: arguments, timeout: @limits.fetch("request_timeout_seconds"), - cancel: cancel, max_snapshot_bytes: [@limits.fetch("max_capture_bytes"), 1 << 20].min) + observer = + Observation.new( + server: @server, + arguments: arguments, + timeout: @limits.fetch("request_timeout_seconds"), + cancel: cancel, + max_snapshot_bytes: [@limits.fetch("max_capture_bytes"), 1 << 20].min + ) @observers << observer observer end @@ -354,14 +547,21 @@ def capture_screen(arguments, cancel) raise CursorError, "screen cursor capture is unavailable" end observer = observation(arguments, cancel) - result, entry = observer.capture(previous: previous, expires: clock + @limits.fetch("capture_ttl_seconds")) + result, entry = + observer.capture( + previous: previous, + expires: clock + @limits.fetch("capture_ttl_seconds") + ) @retiring << entry if entry - validate_response_size({"ok" => true, "data" => result}) + validate_response_size({ "ok" => true, "data" => result }) if entry raise ClosedError.new("MCP application closed during capture", phase: :read) if @closed - raise CapacityError.new("screen capture exceeds retention bytes", delivery: :observed) if entry.bytes > @limits.fetch("max_capture_bytes") + if entry.bytes > @limits.fetch("max_capture_bytes") + raise CapacityError.new("screen capture exceeds retention bytes", delivery: :observed) + end - while @captures.length >= @limits.fetch("max_captures") || @retained_bytes + entry.bytes > @limits.fetch("max_capture_bytes") + while @captures.length >= @limits.fetch("max_captures") || + @retained_bytes + entry.bytes > @limits.fetch("max_capture_bytes") evict(@captures.keys.first) end @captures[entry.capture_id] = entry @@ -386,7 +586,11 @@ def retire_observation(observer, entry = nil) errors = [] [observer, entry].compact.each do |resource| begin - resource.is_a?(Observation) ? resource.close(timeout: resource.cleanup_remaining) : resource.close + if resource.is_a?(Observation) + resource.close(timeout: resource.cleanup_remaining) + else + resource.close + end @observers.delete(resource) @retiring.delete(resource) rescue Exception => error @@ -401,36 +605,66 @@ def retire_observation(observer, entry = nil) elsif primary ProcessIdentity.attach_cleanup(primary, errors) elsif !primary - raise TransportError.new("observation cleanup remains pending", phase: :retire, cleanup_errors: errors) + raise TransportError.new( + "observation cleanup remains pending", + phase: :retire, + cleanup_errors: errors + ) end end def acquire(cancel) - @server.snapshot(timeout: @limits.fetch("request_timeout_seconds"), cancel: cancel, - clients: true, max_bytes: [@limits.fetch("max_capture_bytes"), 1 << 20].min, max_rows: 4096) + @server.snapshot( + timeout: @limits.fetch("request_timeout_seconds"), + cancel: cancel, + clients: true, + max_bytes: [@limits.fetch("max_capture_bytes"), 1 << 20].min, + max_rows: 4096 + ) end def identity(snapshot) - {"generation" => snapshot.binding_key, "pid" => snapshot.server_info.fetch(:pid), - "start_time" => snapshot.server_info.fetch(:start_time), "tmux_version" => snapshot.server_info.fetch(:version)} + { + "generation" => snapshot.binding_key, + "pid" => snapshot.server_info.fetch(:pid), + "start_time" => snapshot.server_info.fetch(:start_time), + "tmux_version" => snapshot.server_info.fetch(:version) + } end def capabilities(cancel) - report = @server.capabilities(timeout: @limits.fetch("request_timeout_seconds"), cancel: cancel) + report = + @server.capabilities(timeout: @limits.fetch("request_timeout_seconds"), cancel: cancel) observation = Observation.capabilities(report.version) data = report.to_h - optional = data.delete("features").map do |feature| - feature.merge("available" => feature.fetch("supported")).except("supported") - end - data.merge("optional_features" => optional, "endpoint" => @endpoint, "enabled_tools" => @enabled, - "criteria_schema" => FilterExpr.json_schema, "limits" => @limits, - "owns_daemon" => false, "resource_subscriptions" => false, + optional = + data + .delete("features") + .map do |feature| + feature.merge("available" => feature.fetch("supported")).except("supported") + end + data.merge( + "optional_features" => optional, + "endpoint" => @endpoint, + "enabled_tools" => @enabled, + "criteria_schema" => FilterExpr.json_schema, + "limits" => @limits, + "owns_daemon" => false, + "resource_subscriptions" => false, "observation" => observation, - "authored_run" => {"availability" => observation.fetch("process_cursor"), - "shell_profile" => "zsh-5.9-zle", "enrollment" => "explicit_source", - "authorization" => "exact_generation_at_queue_grant", "stdin" => "closed", - "persistent_shell_changes" => false, "descendant_termination" => "unobserved", - "requirements" => observation.fetch("requirements") + ["explicit idle/empty ZLE enrollment", "installed Ruby/core helper dependencies"]}) + "authored_run" => { + "availability" => observation.fetch("process_cursor"), + "shell_profile" => "zsh-5.9-zle", + "enrollment" => "explicit_source", + "authorization" => "exact_generation_at_queue_grant", + "stdin" => "closed", + "persistent_shell_changes" => false, + "descendant_termination" => "unobserved", + "requirements" => + observation.fetch("requirements") + + ["explicit idle/empty ZLE enrollment", "installed Ruby/core helper dependencies"] + } + ) end def snapshot(arguments, cancel) @@ -440,51 +674,97 @@ def snapshot(arguments, cancel) capture = @captures.fetch(key) { raise CursorError, "cursor capture is unavailable" } raise CursorError, "cursor has another capture kind" unless capture.is_a?(Capture) offset = Integer(position, 10) - raise CursorError, "cursor offset is outside the capture" unless offset.positive? && offset < capture.rows.length + unless offset.positive? && offset < capture.rows.length + raise CursorError, "cursor offset is outside the capture" + end return page(key, capture, offset) end entity = arguments.fetch("entity").to_sym - expression = if arguments["criteria"] - FilterExpr.from_json(JSON.generate(arguments.fetch("criteria"))) - else - FilterExpr.build(entity) + expression = + if arguments["criteria"] + FilterExpr.from_json(JSON.generate(arguments.fetch("criteria"))) + else + FilterExpr.build(entity) + end + unless expression.entity == entity + raise InvalidFilterError, "criteria entity does not match acquisition" end - raise InvalidFilterError, "criteria entity does not match acquisition" unless expression.entity == entity snapshot = acquire(cancel) - selection = snapshot.public_send({session: :sessions, window: :windows, pane: :panes, - window_link: :window_links, client: :clients}.fetch(entity)).where(expression) + selection = + snapshot.public_send( + { + session: :sessions, + window: :windows, + pane: :panes, + window_link: :window_links, + client: :clients + }.fetch(entity) + ).where(expression) bytes = 0 - rows = selection.map do |record| - fields = Internal::Catalog.entity(entity).fields.values.to_h { |field| [field.wire_name, record.public_send(field.name)] } - reference = if entity == :client - nil - else - ref = record.ref - {"generation" => ref.binding_key, "kind" => ref.kind.to_s, "id" => ref.id}.tap do |value| - if entity == :window_link - value["session_id"], value["index"] = ref.session_id, ref.index + rows = + selection.map do |record| + fields = + Internal::Catalog + .entity(entity) + .fields + .values + .to_h { |field| [field.wire_name, record.public_send(field.name)] } + reference = + if entity == :client + nil + else + ref = record.ref + { + "generation" => ref.binding_key, + "kind" => ref.kind.to_s, + "id" => ref.id + }.tap do |value| + if entity == :window_link + value["session_id"], value["index"] = ref.session_id, ref.index + end + end end + row = { "kind" => entity.to_s, "fields" => fields, "ref" => reference } + bytes += JSON.generate(row).bytesize + if bytes > @limits.fetch("max_capture_bytes") + raise CapacityError.new( + "captured records exceed retention bytes", + delivery: :observed + ) end + row end - row = {"kind" => entity.to_s, "fields" => fields, "ref" => reference} - bytes += JSON.generate(row).bytesize - raise CapacityError.new("captured records exceed retention bytes", delivery: :observed) if bytes > @limits.fetch("max_capture_bytes") - row - end - metadata = {"capture_id" => snapshot.capture_id, "server_identity" => identity(snapshot), - "entity" => entity.to_s, "coverage" => Internal::Catalog.kinds.to_h { |kind| [kind.to_s, "complete"] }, - "interval" => {"clock" => "monotonic_seconds", "started" => snapshot.started_at, - "finished" => snapshot.finished_at, "reads" => snapshot.reads.length}} + metadata = { + "capture_id" => snapshot.capture_id, + "server_identity" => identity(snapshot), + "entity" => entity.to_s, + "coverage" => Internal::Catalog.kinds.to_h { |kind| [kind.to_s, "complete"] }, + "interval" => { + "clock" => "monotonic_seconds", + "started" => snapshot.started_at, + "finished" => snapshot.finished_at, + "reads" => snapshot.reads.length + } + } bytes += JSON.generate(metadata).bytesize - raise CapacityError.new("capture exceeds retention bytes", delivery: :observed) if bytes > @limits.fetch("max_capture_bytes") + if bytes > @limits.fetch("max_capture_bytes") + raise CapacityError.new("capture exceeds retention bytes", delivery: :observed) + end key = SecureRandom.hex(16) - capture = Capture.new(rows: freeze_tree(rows), metadata: freeze_tree(metadata), limit: arguments.fetch("limit", 50), - expires: clock + @limits.fetch("capture_ttl_seconds"), bytes: bytes) + capture = + Capture.new( + rows: freeze_tree(rows), + metadata: freeze_tree(metadata), + limit: arguments.fetch("limit", 50), + expires: clock + @limits.fetch("capture_ttl_seconds"), + bytes: bytes + ) first_page = page(key, capture, 0) - validate_response_size({"ok" => true, "data" => first_page}) + validate_response_size({ "ok" => true, "data" => first_page }) raise ClosedError.new("MCP application closed during capture", phase: :read) if @closed - while @captures.length >= @limits.fetch("max_captures") || @retained_bytes + bytes > @limits.fetch("max_capture_bytes") + while @captures.length >= @limits.fetch("max_captures") || + @retained_bytes + bytes > @limits.fetch("max_capture_bytes") evict(@captures.keys.first) end @captures[key] = capture @@ -494,16 +774,23 @@ def snapshot(arguments, cancel) def validate_response_size(structured) if JSON.generate(structured).bytesize > @limits.fetch("max_response_bytes") - raise CapacityError.new("MCP response exceeds its byte limit", phase: :read, delivery: :observed) + raise CapacityError.new( + "MCP response exceeds its byte limit", + phase: :read, + delivery: :observed + ) end end def page(key, capture, offset) items = capture.rows.slice(offset, capture.limit) || [] next_position = offset + items.length - capture.metadata.merge("items" => items, "truncated" => next_position < capture.rows.length).tap do |result| - result["next_cursor"] = "#{key}:#{next_position}" if next_position < capture.rows.length - end + capture + .metadata + .merge("items" => items, "truncated" => next_position < capture.rows.length) + .tap do |result| + result["next_cursor"] = "#{key}:#{next_position}" if next_position < capture.rows.length + end end def prune @@ -519,18 +806,29 @@ def evict(key) def freeze_tree(value) case value - when Hash then value.each { |key, child| key.freeze; freeze_tree(child) } - when Array then value.each { |child| freeze_tree(child) } + when Hash + value.each do |key, child| + key.freeze + freeze_tree(child) + end + when Array + value.each { |child| freeze_tree(child) } end value.freeze end def failure_response(code, message, delivery = "not_sent", effects: nil, capture: nil) - details = {"code" => code, "message" => message, "delivery" => delivery} + details = { "code" => code, "message" => message, "delivery" => delivery } details["effects"] = effects if effects details["capture"] = capture if capture - ::MCP::Tool::Response.new([{type: "text", text: message}], error: true, - structured_content: {"ok" => false, "error" => details}) + ::MCP::Tool::Response.new( + [{ type: "text", text: message }], + error: true, + structured_content: { + "ok" => false, + "error" => details + } + ) end def clock diff --git a/gems/libtmux-mcp/lib/libtmux/mcp/catalog.rb b/gems/libtmux-mcp/lib/libtmux/mcp/catalog.rb index 8210930c..789bcbe5 100644 --- a/gems/libtmux-mcp/lib/libtmux/mcp/catalog.rb +++ b/gems/libtmux-mcp/lib/libtmux/mcp/catalog.rb @@ -28,113 +28,371 @@ module Catalog def self.meta(name) toolset, process_reach, tmux_effects = CAPABILITIES.fetch(name) - {CAPABILITY_KEY => {"toolset" => toolset, "processReach" => process_reach, "tmuxEffects" => tmux_effects.dup}} + { + CAPABILITY_KEY => { + "toolset" => toolset, + "processReach" => process_reach, + "tmuxEffects" => tmux_effects.dup + } + } end def self.object(properties, required = properties.keys) - {"type" => "object", "properties" => properties, "required" => required, "additionalProperties" => false} + { + "type" => "object", + "properties" => properties, + "required" => required, + "additionalProperties" => false + } end def self.text - {"type" => "string"} + { "type" => "string" } end def self.input(name) return object({}) if name == "tmux_capabilities" if name == "tmux_run" - return object({"target" => reference("pane"), "script" => mutation_text, - "stdout_limit" => {"type" => "integer", "minimum" => 0, "maximum" => 262144}, - "stderr_limit" => {"type" => "integer", "minimum" => 0, "maximum" => 262144}}, %w[target script]) + return( + object( + { + "target" => reference("pane"), + "script" => mutation_text, + "stdout_limit" => { + "type" => "integer", + "minimum" => 0, + "maximum" => 262_144 + }, + "stderr_limit" => { + "type" => "integer", + "minimum" => 0, + "maximum" => 262_144 + } + }, + %w[target script] + ) + ) end return mutation_input(name) if MUTATIONS.include?(name) return observation_input(name) if OBSERVATIONS.include?(name) criteria = FilterExpr.json_schema - object({"entity" => {"enum" => Internal::Catalog.kinds.map(&:to_s)}, - "criteria" => {"oneOf" => criteria.fetch("oneOf")}, - "limit" => {"type" => "integer", "minimum" => 1, "maximum" => 200}, - "cursor" => {"type" => "string", "pattern" => "^[a-f0-9]{32}:[0-9]{1,10}$", "maxLength" => 43}}, []).merge( - "$defs" => criteria.fetch("$defs"), "oneOf" => [ - {"required" => ["entity"], "not" => {"required" => ["cursor"]}}, - {"required" => ["cursor"], "not" => {"anyOf" => %w[entity criteria limit].map { |key| {"required" => [key]} }}} - ]) + object( + { + "entity" => { + "enum" => Internal::Catalog.kinds.map(&:to_s) + }, + "criteria" => { + "oneOf" => criteria.fetch("oneOf") + }, + "limit" => { + "type" => "integer", + "minimum" => 1, + "maximum" => 200 + }, + "cursor" => { + "type" => "string", + "pattern" => "^[a-f0-9]{32}:[0-9]{1,10}$", + "maxLength" => 43 + } + }, + [] + ).merge( + "$defs" => criteria.fetch("$defs"), + "oneOf" => [ + { "required" => ["entity"], "not" => { "required" => ["cursor"] } }, + { + "required" => ["cursor"], + "not" => { + "anyOf" => %w[entity criteria limit].map { |key| { "required" => [key] } } + } + } + ] + ) end def self.identity - object({"generation" => text, "pid" => {"type" => "integer"}, - "start_time" => {"type" => "integer"}, "tmux_version" => text}) + object( + { + "generation" => text, + "pid" => { + "type" => "integer" + }, + "start_time" => { + "type" => "integer" + }, + "tmux_version" => text + } + ) end def self.feature_properties - {"id" => text, "name" => text, "summary" => text, - "handling" => {"enum" => %w[refuse fallback repair]}, - "apis" => {"type" => "array", "items" => text}, - "commands" => {"type" => "array", "items" => object({"command" => text, - "flags" => {"type" => "array", "items" => text}})}} + { + "id" => text, + "name" => text, + "summary" => text, + "handling" => { + "enum" => %w[refuse fallback repair] + }, + "apis" => { + "type" => "array", + "items" => text + }, + "commands" => { + "type" => "array", + "items" => + object({ "command" => text, "flags" => { "type" => "array", "items" => text } }) + } + } end def self.feature_decision - object(feature_properties.merge("since" => text, "error" => {"type" => %w[string null]}, - "except" => {"type" => "array", "items" => text}, "available" => {"type" => "boolean"})) + object( + feature_properties.merge( + "since" => text, + "error" => { + "type" => %w[string null] + }, + "except" => { + "type" => "array", + "items" => text + }, + "available" => { + "type" => "boolean" + } + ) + ) end def self.workaround_decision - object(feature_properties.merge("releases" => {"type" => "array", "items" => text}, - "active" => {"type" => "boolean"})) + object( + feature_properties.merge( + "releases" => { + "type" => "array", + "items" => text + }, + "active" => { + "type" => "boolean" + } + ) + ) end def self.capture_limits - {"max_lines" => {"type" => "integer", "minimum" => 1, "maximum" => 1000}, - "max_bytes" => {"type" => "integer", "minimum" => 1, "maximum" => 262144}, - "history_lines" => {"type" => "integer", "minimum" => 0, "maximum" => 1000}} + { + "max_lines" => { + "type" => "integer", + "minimum" => 1, + "maximum" => 1000 + }, + "max_bytes" => { + "type" => "integer", + "minimum" => 1, + "maximum" => 262_144 + }, + "history_lines" => { + "type" => "integer", + "minimum" => 0, + "maximum" => 1000 + } + } end def self.observation_input(name) if name == "tmux_capture" - {"oneOf" => [object(capture_limits.merge("target" => reference("pane"), "track" => {"type" => "boolean"}), ["target"]), - object({"target" => reference("pane"), "cursor" => text.merge("pattern" => "^[a-f0-9]{32}$", "maxLength" => 32)})]} + { + "oneOf" => [ + object( + capture_limits.merge( + "target" => reference("pane"), + "track" => { + "type" => "boolean" + } + ), + ["target"] + ), + object( + { + "target" => reference("pane"), + "cursor" => text.merge("pattern" => "^[a-f0-9]{32}$", "maxLength" => 32) + } + ) + ] + } else - {"oneOf" => [object(capture_limits.merge("target" => reference("pane"), - "timeout" => {"type" => "number", "exclusiveMinimum" => 0, "maximum" => 60}, - "condition" => {"oneOf" => [object({"type" => {"const" => "screen_contains"}, - "text" => text.merge("minLength" => 1, "maxLength" => 4096)}), object({"type" => {"const" => "process_exit"}})]}), %w[target condition])]} + { + "oneOf" => [ + object( + capture_limits.merge( + "target" => reference("pane"), + "timeout" => { + "type" => "number", + "exclusiveMinimum" => 0, + "maximum" => 60 + }, + "condition" => { + "oneOf" => [ + object( + { + "type" => { + "const" => "screen_contains" + }, + "text" => text.merge("minLength" => 1, "maxLength" => 4096) + } + ), + object({ "type" => { "const" => "process_exit" } }) + ] + } + ), + %w[target condition] + ) + ] + } end end def self.capture_output - common = {"target" => reference("pane"), "capture_id" => text, - "process_generation" => {"type" => ["string", "null"]}, - "encoding" => {"enum" => %w[utf-8 base64]}, "row_count" => {"type" => "integer", "minimum" => 0, "maximum" => 1000}, - "bytes" => {"type" => "integer", "minimum" => 0, "maximum" => 262144}, - "truncated" => {"type" => "boolean"}, "history_continuity" => {"const" => "unknown"}, - "interval" => object({"clock" => {"const" => "monotonic_seconds"}, "started" => {"type" => "number"}, "finished" => {"type" => "number"}}), - "scope" => object(capture_limits), "next_cursor" => text} - rows = {"type" => "array", "maxItems" => 1000, "items" => text} + common = { + "target" => reference("pane"), + "capture_id" => text, + "process_generation" => { + "type" => %w[string null] + }, + "encoding" => { + "enum" => %w[utf-8 base64] + }, + "row_count" => { + "type" => "integer", + "minimum" => 0, + "maximum" => 1000 + }, + "bytes" => { + "type" => "integer", + "minimum" => 0, + "maximum" => 262_144 + }, + "truncated" => { + "type" => "boolean" + }, + "history_continuity" => { + "const" => "unknown" + }, + "interval" => + object( + { + "clock" => { + "const" => "monotonic_seconds" + }, + "started" => { + "type" => "number" + }, + "finished" => { + "type" => "number" + } + } + ), + "scope" => object(capture_limits), + "next_cursor" => text + } + rows = { "type" => "array", "maxItems" => 1000, "items" => text } required = common.keys - ["next_cursor"] - {"oneOf" => [object(common.merge("mode" => {"const" => "snapshot"}, "rows" => rows), required + %w[mode rows]), - object(common.merge("mode" => {"const" => "delta"}, "base_capture_id" => text, "reset" => {"type" => "boolean"}, - "splice" => object({"start" => {"type" => "integer", "minimum" => 0}, "delete" => {"type" => "integer", "minimum" => 0}, "rows" => rows})), - required + %w[mode base_capture_id reset splice next_cursor])]} + { + "oneOf" => [ + object( + common.merge("mode" => { "const" => "snapshot" }, "rows" => rows), + required + %w[mode rows] + ), + object( + common.merge( + "mode" => { + "const" => "delta" + }, + "base_capture_id" => text, + "reset" => { + "type" => "boolean" + }, + "splice" => + object( + { + "start" => { + "type" => "integer", + "minimum" => 0 + }, + "delete" => { + "type" => "integer", + "minimum" => 0 + }, + "rows" => rows + } + ) + ), + required + %w[mode base_capture_id reset splice next_cursor] + ) + ] + } end def self.wait_output - {"oneOf" => [object({"target" => reference("pane"), "condition" => {"const" => "screen_contains"}, "capture" => capture_output}), - object({"target" => reference("pane"), "condition" => {"const" => "process_exit"}, "process_generation" => text, - "observed_at" => {"type" => "number"}, "exit_status" => {"const" => "unobserved"}})]} + { + "oneOf" => [ + object( + { + "target" => reference("pane"), + "condition" => { + "const" => "screen_contains" + }, + "capture" => capture_output + } + ), + object( + { + "target" => reference("pane"), + "condition" => { + "const" => "process_exit" + }, + "process_generation" => text, + "observed_at" => { + "type" => "number" + }, + "exit_status" => { + "const" => "unobserved" + } + } + ) + ] + } end def self.reference(kind = nil) kinds = kind ? [kind] : %w[session window pane window_link] - {"oneOf" => kinds.map do |entity| - prefix = {"session" => "\\$", "window" => "@", "pane" => "%", "window_link" => "@"}.fetch(entity) - properties = {"generation" => text.merge("minLength" => 1, "maxLength" => 128), "kind" => {"const" => entity}, - "id" => text.merge("pattern" => "^#{prefix}[0-9]+$", "maxLength" => 32)} - if entity == "window_link" - properties.merge!("session_id" => text.merge("pattern" => "^\\$[0-9]+$", "maxLength" => 32), - "index" => {"type" => "integer", "minimum" => 0}) - end - object(properties) - end} + { + "oneOf" => + kinds.map do |entity| + prefix = { + "session" => "\\$", + "window" => "@", + "pane" => "%", + "window_link" => "@" + }.fetch(entity) + properties = { + "generation" => text.merge("minLength" => 1, "maxLength" => 128), + "kind" => { + "const" => entity + }, + "id" => text.merge("pattern" => "^#{prefix}[0-9]+$", "maxLength" => 32) + } + if entity == "window_link" + properties.merge!( + "session_id" => text.merge("pattern" => "^\\$[0-9]+$", "maxLength" => 32), + "index" => { + "type" => "integer", + "minimum" => 0 + } + ) + end + object(properties) + end + } end def self.mutation_text @@ -144,133 +402,470 @@ def self.mutation_text def self.mutation_input(name) case name when "tmux_send" - {"oneOf" => [object({"target" => reference("pane"), "input" => {"oneOf" => [ - object({"type" => {"const" => "text"}, "text" => mutation_text}), - object({"type" => {"const" => "keys"}, "keys" => {"type" => "array", "minItems" => 1, "maxItems" => 256, - "items" => mutation_text.merge("minLength" => 1)}}) - ]}})]} + { + "oneOf" => [ + object( + { + "target" => reference("pane"), + "input" => { + "oneOf" => [ + object({ "type" => { "const" => "text" }, "text" => mutation_text }), + object( + { + "type" => { + "const" => "keys" + }, + "keys" => { + "type" => "array", + "minItems" => 1, + "maxItems" => 256, + "items" => mutation_text.merge("minLength" => 1) + } + } + ) + ] + } + } + ) + ] + } when "tmux_close" - {"oneOf" => [object({"target" => {"oneOf" => %w[session window pane].flat_map { |kind| reference(kind).fetch("oneOf") }}})]} + { + "oneOf" => [ + object( + { + "target" => { + "oneOf" => + %w[session window pane].flat_map { |kind| reference(kind).fetch("oneOf") } + } + } + ) + ] + } when "tmux_create" - common = {"argv" => {"type" => "array", "minItems" => 1, "maxItems" => 256, - "prefixItems" => [mutation_text.merge("minLength" => 1)], "items" => mutation_text}, + common = { + "argv" => { + "type" => "array", + "minItems" => 1, + "maxItems" => 256, + "prefixItems" => [mutation_text.merge("minLength" => 1)], + "items" => mutation_text + }, "cwd" => mutation_text.merge("minLength" => 1), - "environment" => {"type" => "object", "maxProperties" => 128, - "propertyNames" => {"pattern" => "^[A-Za-z_][A-Za-z0-9_]*$"}, "additionalProperties" => mutation_text}} - positive = {"type" => "integer", "minimum" => 1, "maximum" => (1 << 31) - 1} - {"oneOf" => [ - object(common.merge("kind" => {"const" => "session"}, "name" => mutation_text.merge("minLength" => 1), - "window_name" => mutation_text.merge("minLength" => 1), "width" => positive, "height" => positive), %w[kind name argv]), - object(common.merge("kind" => {"const" => "window"}, "parent" => reference("session"), - "name" => mutation_text.merge("minLength" => 1), "index" => {"type" => "integer", "minimum" => 0, "maximum" => (1 << 31) - 1}, - "focus" => {"type" => "boolean"}), %w[kind parent name argv]), - object(common.merge("kind" => {"const" => "pane"}, "parent" => reference("pane"), - "direction" => {"enum" => %w[horizontal vertical]}, "size" => {"oneOf" => [positive, - {"type" => "string", "pattern" => "^(?:[1-9][0-9]?|100)%$"}]}, - "focus" => {"type" => "boolean"}), %w[kind parent direction argv]) - ]} + "environment" => { + "type" => "object", + "maxProperties" => 128, + "propertyNames" => { + "pattern" => "^[A-Za-z_][A-Za-z0-9_]*$" + }, + "additionalProperties" => mutation_text + } + } + positive = { "type" => "integer", "minimum" => 1, "maximum" => (1 << 31) - 1 } + { + "oneOf" => [ + object( + common.merge( + "kind" => { + "const" => "session" + }, + "name" => mutation_text.merge("minLength" => 1), + "window_name" => mutation_text.merge("minLength" => 1), + "width" => positive, + "height" => positive + ), + %w[kind name argv] + ), + object( + common.merge( + "kind" => { + "const" => "window" + }, + "parent" => reference("session"), + "name" => mutation_text.merge("minLength" => 1), + "index" => { + "type" => "integer", + "minimum" => 0, + "maximum" => (1 << 31) - 1 + }, + "focus" => { + "type" => "boolean" + } + ), + %w[kind parent name argv] + ), + object( + common.merge( + "kind" => { + "const" => "pane" + }, + "parent" => reference("pane"), + "direction" => { + "enum" => %w[horizontal vertical] + }, + "size" => { + "oneOf" => [ + positive, + { "type" => "string", "pattern" => "^(?:[1-9][0-9]?|100)%$" } + ] + }, + "focus" => { + "type" => "boolean" + } + ), + %w[kind parent direction argv] + ) + ] + } end end def self.record - {"oneOf" => Internal::Catalog.kinds.map do |kind| - fields = Internal::Catalog.entity(kind).fields.values.to_h do |field| - type = {text: "string", integer: "integer", boolean: "boolean"}.fetch(field.type) - schema = {"type" => field.nullable ? [type, "null"] : type} - schema["minimum"] = field.min if field.min - schema["maximum"] = field.max if field.max - [field.wire_name, schema] - end - object({"kind" => {"const" => kind.to_s}, "fields" => object(fields), - "ref" => kind == :client ? {"type" => "null"} : reference(kind.to_s)}) - end} + { + "oneOf" => + Internal::Catalog.kinds.map do |kind| + fields = + Internal::Catalog + .entity(kind) + .fields + .values + .to_h do |field| + type = { text: "string", integer: "integer", boolean: "boolean" }.fetch( + field.type + ) + schema = { "type" => field.nullable ? [type, "null"] : type } + schema["minimum"] = field.min if field.min + schema["maximum"] = field.max if field.max + [field.wire_name, schema] + end + object( + { + "kind" => { + "const" => kind.to_s + }, + "fields" => object(fields), + "ref" => kind == :client ? { "type" => "null" } : reference(kind.to_s) + } + ) + end + } end def self.output(name) - payload = if name == "tmux_run" - object({"target" => reference("pane"), "authorization" => authorization, - "completion" => run_completion, "stdout" => run_bytes, "stderr" => run_bytes}) - elsif MUTATIONS.include?(name) - mutation_output(name) - elsif name == "tmux_capture" - capture_output - elsif name == "tmux_wait" - wait_output - elsif name == "tmux_capabilities" - object({"endpoint" => text, "server_identity" => identity, - "optional_features" => {"type" => "array", "items" => feature_decision}, - "workarounds" => {"type" => "array", "items" => workaround_decision}, - "enabled_tools" => {"type" => "array", "items" => text}, - "criteria_schema" => {"type" => "object"}, - "limits" => {"type" => "object", "additionalProperties" => {"type" => "number"}}, - "owns_daemon" => {"const" => false}, "resource_subscriptions" => {"const" => false}, - "authored_run" => object({"availability" => {"enum" => %w[conditional unsupported]}, - "shell_profile" => {"const" => "zsh-5.9-zle"}, "enrollment" => {"const" => "explicit_source"}, - "authorization" => {"const" => "exact_generation_at_queue_grant"}, - "stdin" => {"const" => "closed"}, "persistent_shell_changes" => {"const" => false}, - "descendant_termination" => {"const" => "unobserved"}, - "requirements" => {"type" => "array", "items" => text}}), - "observation" => object({"screen" => {"const" => "bounded_rows"}, "history_continuity" => {"const" => "unknown"}, - "process_cursor" => {"enum" => %w[conditional unsupported]}, "requirements" => {"type" => "array", "items" => text}, - "wait_conditions" => {"type" => "array", "items" => {"enum" => %w[screen_contains process_exit]}}})}) - else - object({"capture_id" => text, "server_identity" => identity, - "entity" => {"enum" => Internal::Catalog.kinds.map(&:to_s)}, - "items" => {"type" => "array", "items" => record, "maxItems" => 200}, - "coverage" => {"type" => "object", "additionalProperties" => {"enum" => %w[complete unloaded]}}, - "interval" => object({"clock" => {"const" => "monotonic_seconds"}, - "started" => {"type" => "number"}, "finished" => {"type" => "number"}, - "reads" => {"type" => "integer", "minimum" => 0}}), - "truncated" => {"type" => "boolean"}, "next_cursor" => text}, - %w[capture_id server_identity entity items coverage interval truncated]) - end - {"type" => "object", "oneOf" => [object({"ok" => {"const" => true}, "data" => payload}), - object({"ok" => {"const" => false}, "error" => object({"code" => text, - "message" => text, "delivery" => {"enum" => %w[not_sent possibly_sent observed]}, - "effects" => name == "tmux_run" ? run_effects : effects}.merge(name == "tmux_wait" ? {"capture" => capture_output} : {}), - %w[code message delivery])})]} + payload = + if name == "tmux_run" + object( + { + "target" => reference("pane"), + "authorization" => authorization, + "completion" => run_completion, + "stdout" => run_bytes, + "stderr" => run_bytes + } + ) + elsif MUTATIONS.include?(name) + mutation_output(name) + elsif name == "tmux_capture" + capture_output + elsif name == "tmux_wait" + wait_output + elsif name == "tmux_capabilities" + object( + { + "endpoint" => text, + "server_identity" => identity, + "optional_features" => { + "type" => "array", + "items" => feature_decision + }, + "workarounds" => { + "type" => "array", + "items" => workaround_decision + }, + "enabled_tools" => { + "type" => "array", + "items" => text + }, + "criteria_schema" => { + "type" => "object" + }, + "limits" => { + "type" => "object", + "additionalProperties" => { + "type" => "number" + } + }, + "owns_daemon" => { + "const" => false + }, + "resource_subscriptions" => { + "const" => false + }, + "authored_run" => + object( + { + "availability" => { + "enum" => %w[conditional unsupported] + }, + "shell_profile" => { + "const" => "zsh-5.9-zle" + }, + "enrollment" => { + "const" => "explicit_source" + }, + "authorization" => { + "const" => "exact_generation_at_queue_grant" + }, + "stdin" => { + "const" => "closed" + }, + "persistent_shell_changes" => { + "const" => false + }, + "descendant_termination" => { + "const" => "unobserved" + }, + "requirements" => { + "type" => "array", + "items" => text + } + } + ), + "observation" => + object( + { + "screen" => { + "const" => "bounded_rows" + }, + "history_continuity" => { + "const" => "unknown" + }, + "process_cursor" => { + "enum" => %w[conditional unsupported] + }, + "requirements" => { + "type" => "array", + "items" => text + }, + "wait_conditions" => { + "type" => "array", + "items" => { + "enum" => %w[screen_contains process_exit] + } + } + } + ) + } + ) + else + object( + { + "capture_id" => text, + "server_identity" => identity, + "entity" => { + "enum" => Internal::Catalog.kinds.map(&:to_s) + }, + "items" => { + "type" => "array", + "items" => record, + "maxItems" => 200 + }, + "coverage" => { + "type" => "object", + "additionalProperties" => { + "enum" => %w[complete unloaded] + } + }, + "interval" => + object( + { + "clock" => { + "const" => "monotonic_seconds" + }, + "started" => { + "type" => "number" + }, + "finished" => { + "type" => "number" + }, + "reads" => { + "type" => "integer", + "minimum" => 0 + } + } + ), + "truncated" => { + "type" => "boolean" + }, + "next_cursor" => text + }, + %w[capture_id server_identity entity items coverage interval truncated] + ) + end + { + "type" => "object", + "oneOf" => [ + object({ "ok" => { "const" => true }, "data" => payload }), + object( + { + "ok" => { + "const" => false + }, + "error" => + object( + { + "code" => text, + "message" => text, + "delivery" => { + "enum" => %w[not_sent possibly_sent observed] + }, + "effects" => name == "tmux_run" ? run_effects : effects + }.merge(name == "tmux_wait" ? { "capture" => capture_output } : {}), + %w[code message delivery] + ) + } + ) + ] + } end def self.authorization token = text.merge("pattern" => "^[a-f0-9]{32}$", "maxLength" => 32) - object({"state" => {"const" => "authorized"}, "run_id" => token, - "script_digest" => text.merge("pattern" => "^[a-f0-9]{64}$", "maxLength" => 64), - "server_generation" => text.merge("minLength" => 1, "maxLength" => 128), - "pane_id" => text.merge("pattern" => "^%[0-9]+$", "maxLength" => 32), - "enrollment_generation" => token, "process_generation" => token}) + object( + { + "state" => { + "const" => "authorized" + }, + "run_id" => token, + "script_digest" => text.merge("pattern" => "^[a-f0-9]{64}$", "maxLength" => 64), + "server_generation" => text.merge("minLength" => 1, "maxLength" => 128), + "pane_id" => text.merge("pattern" => "^%[0-9]+$", "maxLength" => 32), + "enrollment_generation" => token, + "process_generation" => token + } + ) end def self.run_completion - {"oneOf" => [object({"state" => {"const" => "exited"}, - "exit_status" => {"type" => "integer", "minimum" => 0, "maximum" => 255}, "signal" => {"type" => "null"}}), - object({"state" => {"const" => "signaled"}, "exit_status" => {"type" => "null"}, - "signal" => {"type" => "integer", "minimum" => 1, "maximum" => 255}})]} + { + "oneOf" => [ + object( + { + "state" => { + "const" => "exited" + }, + "exit_status" => { + "type" => "integer", + "minimum" => 0, + "maximum" => 255 + }, + "signal" => { + "type" => "null" + } + } + ), + object( + { + "state" => { + "const" => "signaled" + }, + "exit_status" => { + "type" => "null" + }, + "signal" => { + "type" => "integer", + "minimum" => 1, + "maximum" => 255 + } + } + ) + ] + } end def self.run_bytes - object({"encoding" => {"enum" => %w[utf-8 base64]}, "data" => text.merge("maxLength" => 349528), - "bytes" => {"type" => "integer", "minimum" => 0, "maximum" => 262144}, "truncated" => {"const" => false}}) + object( + { + "encoding" => { + "enum" => %w[utf-8 base64] + }, + "data" => text.merge("maxLength" => 349_528), + "bytes" => { + "type" => "integer", + "minimum" => 0, + "maximum" => 262_144 + }, + "truncated" => { + "const" => false + } + } + ) end def self.run_effects - object({"state" => {"enum" => %w[none known unknown]}, - "authorization" => {"oneOf" => [authorization, {"type" => "null"}]}, - "completion" => {"oneOf" => [object({"state" => {"const" => "unobserved"}}), *run_completion.fetch("oneOf")]}}) + object( + { + "state" => { + "enum" => %w[none known unknown] + }, + "authorization" => { + "oneOf" => [authorization, { "type" => "null" }] + }, + "completion" => { + "oneOf" => [ + object({ "state" => { "const" => "unobserved" } }), + *run_completion.fetch("oneOf") + ] + } + } + ) end def self.effects - object({"state" => {"enum" => %w[none known unknown]}, - "created" => {"type" => "array", "maxItems" => 3, "items" => reference}}) + object( + { + "state" => { + "enum" => %w[none known unknown] + }, + "created" => { + "type" => "array", + "maxItems" => 3, + "items" => reference + } + } + ) end def self.mutation_output(name) if name == "tmux_create" - object({"entity" => reference, "created" => {"type" => "array", "minItems" => 1, "maxItems" => 3, "items" => reference}, - "delivery" => {"const" => "observed"}, "program_completion" => {"const" => "unobserved"}}) + object( + { + "entity" => reference, + "created" => { + "type" => "array", + "minItems" => 1, + "maxItems" => 3, + "items" => reference + }, + "delivery" => { + "const" => "observed" + }, + "program_completion" => { + "const" => "unobserved" + } + } + ) else - properties = {"target" => reference, "delivery" => {"const" => "observed"}, - "client_exit_status" => {"const" => 0}} - properties["completion"] = {"const" => "dispatch_only"} if name == "tmux_send" + properties = { + "target" => reference, + "delivery" => { + "const" => "observed" + }, + "client_exit_status" => { + "const" => 0 + } + } + properties["completion"] = { "const" => "dispatch_only" } if name == "tmux_send" object(properties) end end diff --git a/gems/libtmux-mcp/lib/libtmux/mcp/catalog_tool.rb b/gems/libtmux-mcp/lib/libtmux/mcp/catalog_tool.rb index b0508a42..40734c23 100644 --- a/gems/libtmux-mcp/lib/libtmux/mcp/catalog_tool.rb +++ b/gems/libtmux-mcp/lib/libtmux/mcp/catalog_tool.rb @@ -32,8 +32,12 @@ def invalid_arguments_message(arguments) unless (arguments.keys - fields).empty? return "Unexpected property. Use #{fields.join(", ")}." end - return "Provide entity or cursor." unless arguments.key?("entity") || arguments.key?("cursor") - return "Provide cursor alone to continue a capture." if arguments.key?("cursor") && arguments.size > 1 + unless arguments.key?("entity") || arguments.key?("cursor") + return "Provide entity or cursor." + end + if arguments.key?("cursor") && arguments.size > 1 + return "Provide cursor alone to continue a capture." + end @input_diagnostics ||= JSONSchemer.schema(@input_definition, format: false) issue = @input_diagnostics.validate(arguments).first @@ -48,9 +52,12 @@ def invalid_arguments_message(arguments) schema = issue.fetch("schema") case issue.fetch("type") - when "enum" then "#{pointer} must be one of #{schema.fetch("enum").join(", ")}." - when "minimum" then "#{pointer} must be at least #{schema.fetch("minimum")}." - when "maximum" then "#{pointer} must be at most #{schema.fetch("maximum")}." + when "enum" + "#{pointer} must be one of #{schema.fetch("enum").join(", ")}." + when "minimum" + "#{pointer} must be at least #{schema.fetch("minimum")}." + when "maximum" + "#{pointer} must be at most #{schema.fetch("maximum")}." else if issue["x-error"] || issue["i18n"] "#{pointer} must match the advertised schema." diff --git a/gems/libtmux-mcp/lib/libtmux/mcp/cli.rb b/gems/libtmux-mcp/lib/libtmux/mcp/cli.rb index 51d82b85..a0e923d1 100644 --- a/gems/libtmux-mcp/lib/libtmux/mcp/cli.rb +++ b/gems/libtmux-mcp/lib/libtmux/mcp/cli.rb @@ -7,7 +7,8 @@ module LibTmux module MCP class CLI # The tmux server --start-session asked for did not come up. - class StartError < StandardError; end + class StartError < StandardError + end private_constant :StartError SESSION_NAME = /\A[A-Za-z0-9][A-Za-z0-9_-]{0,127}\z/ @@ -18,11 +19,25 @@ def self.run(arguments, input: $stdin, out: $stdout, err: $stderr, environment: end def initialize(arguments, input, output, error, environment = ENV) - @arguments, @input, @output, @error, @environment = arguments.dup, input, output, error, environment - @options = {endpoint_name: "local", executable: "tmux", tools: Catalog::READ_ONLY.dup, - timeout: 5.0, concurrency: 4, max_requests: 32, max_frame_bytes: 1 << 20, - max_output_bytes: 1 << 22, max_response_bytes: 1 << 20, - enrollments: [], enrollment_timeout: 60.0} + @arguments, @input, @output, @error, @environment = + arguments.dup, + input, + output, + error, + environment + @options = { + endpoint_name: "local", + executable: "tmux", + tools: Catalog::READ_ONLY.dup, + timeout: 5.0, + concurrency: 4, + max_requests: 32, + max_frame_bytes: 1 << 20, + max_output_bytes: 1 << 22, + max_response_bytes: 1 << 20, + enrollments: [], + enrollment_timeout: 60.0 + } @setup_files, @enrollment_tasks = [], [] end private_class_method :new @@ -44,15 +59,24 @@ def run rescue StartError => error report("MCP #{error.message}.", 1, failure: error) rescue StandardError => error - if error.is_a?(LibTmux::UnsupportedFeatureError) && error.phase == :admission && error.delivery == :not_sent + if error.is_a?(LibTmux::UnsupportedFeatureError) && error.phase == :admission && + error.delivery == :not_sent report("MCP refused to start: #{error.message}.", 1, failure: error) else - report("MCP execution failed (#{error.class}); dispatched effects may remain.", 1, failure: error) + report( + "MCP execution failed (#{error.class}); dispatched effects may remain.", + 1, + failure: error + ) end end end.wait rescue OptionParser::ParseError, ArgumentError => error - report(@invalid_endpoint || "Invalid arguments; use --help for supported options.", 2, failure: error) + report( + @invalid_endpoint || "Invalid arguments; use --help for supported options.", + 2, + failure: error + ) rescue Interrupt, LibTmux::Cancelled => error report("MCP interrupted; dispatched effects may remain.", 130, failure: error) rescue StandardError => error @@ -66,8 +90,12 @@ def run def build_endpoint socket_path = @options[:socket_path] socket_path = expand_socket(socket_path) unless socket_path.nil? || socket_path.empty? - Endpoint.new(socket_path: socket_path, socket_name: @options[:socket_name], - executable: @options.fetch(:executable), environment: @environment) + Endpoint.new( + socket_path: socket_path, + socket_name: @options[:socket_name], + executable: @options.fetch(:executable), + environment: @environment + ) rescue ArgumentError => error @invalid_endpoint = "Invalid arguments: #{error.message}." raise @@ -77,7 +105,8 @@ def build_endpoint def expand_socket(socket) File.expand_path(socket) rescue ArgumentError - raise ArgumentError, "--socket cannot be expanded to a path; its leading ~ names no home directory" + raise ArgumentError, + "--socket cannot be expanded to a path; its leading ~ names no home directory" end def serve(endpoint, task) @@ -93,7 +122,10 @@ def serve(endpoint, task) stop_started_server(endpoint, started) rescue Exception => error if failure - ProcessIdentity.attach_cleanup(failure, ["MCP could not stop the tmux server it started (#{error.class})"]) + ProcessIdentity.attach_cleanup( + failure, + ["MCP could not stop the tmux server it started (#{error.class})"] + ) else failure = error end @@ -113,11 +145,44 @@ def start_session(endpoint) directory = File.dirname(endpoint.socket_path) # tmux makes this directory itself for a socket named with -L, not for -S. - Dir.mkdir(directory, 0o700) if File.basename(directory) == "tmux-#{Process.uid}" && !File.exist?(directory) - argv = [endpoint.executable, "-S", endpoint.socket_path, "-f", File::NULL, "new-session", "-d", "-s", name] - result = Internal::ProcessExecutor.new.run(argv, timeout: @options.fetch(:timeout), discard_stdout: true) - reason = result.stderr.dup.force_encoding(Encoding::UTF_8).scrub.lines.first.to_s.gsub(/[[:cntrl:]]/, " ").strip.byteslice(0, 200).to_s.scrub - failure = StartError.new("could not start session #{name}: #{reason.empty? ? 'tmux started no server' : reason}") + if File.basename(directory) == "tmux-#{Process.uid}" && !File.exist?(directory) + Dir.mkdir(directory, 0o700) + end + argv = [ + endpoint.executable, + "-S", + endpoint.socket_path, + "-f", + File::NULL, + "new-session", + "-d", + "-s", + name + ] + result = + Internal::ProcessExecutor.new.run( + argv, + timeout: @options.fetch(:timeout), + discard_stdout: true + ) + reason = + result + .stderr + .dup + .force_encoding(Encoding::UTF_8) + .scrub + .lines + .first + .to_s + .gsub(/[[:cntrl:]]/, " ") + .strip + .byteslice(0, 200) + .to_s + .scrub + failure = + StartError.new( + "could not start session #{name}: #{reason.empty? ? "tmux started no server" : reason}" + ) raise failure unless result.success? begin @@ -149,7 +214,9 @@ def server_pid(server) # Stops the server this process started, and only that one: when the # socket now answers with another pid, the one it started is already gone. def stop_started_server(endpoint, pid) - Server.open(endpoint: endpoint) { |server| server.kill(timeout: @options.fetch(:timeout)) if server_pid(server) == pid } + Server.open(endpoint: endpoint) do |server| + server.kill(timeout: @options.fetch(:timeout)) if server_pid(server) == pid + end rescue TargetNotFoundError nil end @@ -157,21 +224,38 @@ def stop_started_server(endpoint, pid) def serve_endpoint(endpoint, task) Server.open(endpoint: endpoint) do |server| LibTmux::Async.open(server: server, parent: task) do |scope| - app = Application.new(server: scope.server, endpoint_name: @options.fetch(:endpoint_name), - enabled_tools: @options.fetch(:tools).uniq, request_timeout: @options.fetch(:timeout), - max_response_bytes: @options.fetch(:max_response_bytes)) + app = + Application.new( + server: scope.server, + endpoint_name: @options.fetch(:endpoint_name), + enabled_tools: @options.fetch(:tools).uniq, + request_timeout: @options.fetch(:timeout), + max_response_bytes: @options.fetch(:max_response_bytes) + ) failure = transport = nil begin prepare_enrollments(app, scope.server, task) - transport = StdioTransport.new(server: app.sdk_server, parent: task, input: @input, output: @output, - concurrency: @options.fetch(:concurrency), max_requests: @options.fetch(:max_requests), - max_frame_bytes: @options.fetch(:max_frame_bytes), max_output_bytes: @options.fetch(:max_output_bytes), - request_timeout: @options.fetch(:timeout)) + transport = + StdioTransport.new( + server: app.sdk_server, + parent: task, + input: @input, + output: @output, + concurrency: @options.fetch(:concurrency), + max_requests: @options.fetch(:max_requests), + max_frame_bytes: @options.fetch(:max_frame_bytes), + max_output_bytes: @options.fetch(:max_output_bytes), + request_timeout: @options.fetch(:timeout) + ) transport.run rescue Exception => error failure = error ensure - [-> { transport&.close }, -> { close_enrollments }, -> { app.close }].each do |cleanup| + [ + -> { transport&.close }, + -> { close_enrollments }, + -> { app.close } + ].each do |cleanup| begin cleanup.call rescue Exception => error @@ -191,33 +275,50 @@ def serve_endpoint(endpoint, task) def prepare_enrollments(app, server, task) return if @options.fetch(:enrollments).empty? - panes = server.list_panes(timeout: @options.fetch(:timeout)).to_h { |pane| [pane.id, pane.ref] } - @options.fetch(:enrollments).each do |id, path| - reference = panes[id] - raise TargetNotFoundError.new("enrollment pane does not exist", phase: :admission) unless reference + panes = + server.list_panes(timeout: @options.fetch(:timeout)).to_h { |pane| [pane.id, pane.ref] } + @options + .fetch(:enrollments) + .each do |id, path| + reference = panes[id] + unless reference + raise TargetNotFoundError.new("enrollment pane does not exist", phase: :admission) + end - invitation = app.invite_shell(reference, timeout: @options.fetch(:timeout), - expires_in: @options.fetch(:enrollment_timeout)) - arguments = invitation.shell_arguments.map do |value| - raise ArgumentError if value.include?("\0") || value.include?("\n") || value.include?("\r") + invitation = + app.invite_shell( + reference, + timeout: @options.fetch(:timeout), + expires_in: @options.fetch(:enrollment_timeout) + ) + arguments = + invitation.shell_arguments.map do |value| + if value.include?("\0") || value.include?("\n") || value.include?("\r") + raise ArgumentError + end - "'#{value.gsub("'") { %q('\'') }}'" - end - owned = publish_setup_file(path, "source #{arguments.join(' ')}\n") - child = ::Async::Task.new(task) do - begin - app.accept_shell(invitation) - rescue LibTmux::Cancelled, ::Async::Cancel => error - diagnostic("Shell enrollment was cancelled.", failure: error) unless @enrollment_stopping - rescue StandardError => error - diagnostic("Shell enrollment failed (#{error.class}).", failure: error) unless @enrollment_stopping - ensure - remove_setup_file(owned) - end + "'#{value.gsub("'") { %q('\'') }}'" + end + owned = publish_setup_file(path, "source #{arguments.join(" ")}\n") + child = + ::Async::Task.new(task) do + begin + app.accept_shell(invitation) + rescue LibTmux::Cancelled, ::Async::Cancel => error + unless @enrollment_stopping + diagnostic("Shell enrollment was cancelled.", failure: error) + end + rescue StandardError => error + unless @enrollment_stopping + diagnostic("Shell enrollment failed (#{error.class}).", failure: error) + end + ensure + remove_setup_file(owned) + end + end + @enrollment_tasks << child + child.run end - @enrollment_tasks << child - child.run - end end def publish_setup_file(path, command) @@ -255,12 +356,15 @@ def close_enrollments errors = [] interrupted = nil deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 0.5 - actions = @enrollment_tasks.map do |child| - lambda do - child.cancel unless child.finished? - child.wait(timeout: [deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC), 0].max) + actions = + @enrollment_tasks.map do |child| + lambda do + child.cancel unless child.finished? + child.wait( + timeout: [deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC), 0].max + ) + end end - end actions.concat(@setup_files.dup.map { |owned| -> { remove_setup_file(owned) } }) actions.each do |action| begin @@ -279,61 +383,133 @@ def close_enrollments ProcessIdentity.attach_cleanup(interrupted, errors) unless errors.empty? raise interrupted end - raise TransportError.new("shell setup cleanup remains pending", phase: :retire, cleanup_errors: errors) unless errors.empty? + unless errors.empty? + raise TransportError.new( + "shell setup cleanup remains pending", + phase: :retire, + cleanup_errors: errors + ) + end nil end def parser - @parser ||= OptionParser.new do |options| - options.banner = "Usage: libtmux-mcp [--socket PATH | --socket-name NAME] [options]" - options.on("--socket PATH", "Borrow the tmux server at this Unix socket", - "Default: LIBTMUX_SOCKET_PATH, then LIBTMUX_SOCKET, then the", - "server TMUX names, then tmux's default socket") { |value| @options[:socket_path] = value } - options.on("--socket-name NAME", "Borrow the tmux server with this socket name", - "Not with --socket") { |value| @options[:socket_name] = value } - options.on("--start-session NAME", "When no tmux server answers at the socket, start one with an", - "empty configuration that holds session NAME, and stop it at", - "exit. A server that answers is borrowed as it is") { |value| @options[:start_session] = value } - options.on("--keep", "With --start-session, leave the server it started running at exit") { @options[:keep] = true } - options.on("--endpoint NAME", "Public endpoint alias (default: local)") { |value| @options[:endpoint_name] = value } - options.on("--tmux EXECUTABLE", "Resolve and pin this tmux executable at startup") { |value| @options[:executable] = value } - options.on("--enable-tool NAME", "Enable one additional tool; repeat as needed") { |value| @options.fetch(:tools) << value } - options.on("--enroll-pane %ID=FILE", "Write a private zsh setup file for this exact pane; requires tmux_run") do |value| - id, path = value.split("=", 2) - raise ArgumentError unless id && /\A%\d+\z/.match?(id) && path && !path.empty? && path.bytesize <= 4096 && !/[\0\r\n]/.match?(path) + @parser ||= + OptionParser.new do |options| + options.banner = "Usage: libtmux-mcp [--socket PATH | --socket-name NAME] [options]" + options.on( + "--socket PATH", + "Borrow the tmux server at this Unix socket", + "Default: LIBTMUX_SOCKET_PATH, then LIBTMUX_SOCKET, then the", + "server TMUX names, then tmux's default socket" + ) { |value| @options[:socket_path] = value } + options.on( + "--socket-name NAME", + "Borrow the tmux server with this socket name", + "Not with --socket" + ) { |value| @options[:socket_name] = value } + options.on( + "--start-session NAME", + "When no tmux server answers at the socket, start one with an", + "empty configuration that holds session NAME, and stop it at", + "exit. A server that answers is borrowed as it is" + ) { |value| @options[:start_session] = value } + options.on( + "--keep", + "With --start-session, leave the server it started running at exit" + ) { @options[:keep] = true } + options.on("--endpoint NAME", "Public endpoint alias (default: local)") do |value| + @options[:endpoint_name] = value + end + options.on( + "--tmux EXECUTABLE", + "Resolve and pin this tmux executable at startup" + ) { |value| @options[:executable] = value } + options.on( + "--enable-tool NAME", + "Enable one additional tool; repeat as needed" + ) { |value| @options.fetch(:tools) << value } + options.on( + "--enroll-pane %ID=FILE", + "Write a private zsh setup file for this exact pane; requires tmux_run" + ) do |value| + id, path = value.split("=", 2) + unless id && /\A%\d+\z/.match?(id) && path && !path.empty? && path.bytesize <= 4096 && + !/[\0\r\n]/.match?(path) + raise ArgumentError + end - @options.fetch(:enrollments) << [id.freeze, File.expand_path(path).freeze].freeze + @options.fetch(:enrollments) << [id.freeze, File.expand_path(path).freeze].freeze + end + options.on( + "--enrollment-timeout SECONDS", + Float, + "Setup file lifetime, at most 300 seconds (default: 60)" + ) { |value| @options[:enrollment_timeout] = value } + options.on("--timeout SECONDS", Float, "Total request deadline (default: 5)") do |value| + @options[:timeout] = value + end + options.on("--concurrency COUNT", Integer, "Active requests (default: 4)") do |value| + @options[:concurrency] = value + end + options.on( + "--max-requests COUNT", + Integer, + "Active plus waiting requests (default: 32)" + ) { |value| @options[:max_requests] = value } + options.on( + "--max-frame-bytes BYTES", + Integer, + "Input frame limit (default: 1048576)" + ) { |value| @options[:max_frame_bytes] = value } + options.on( + "--max-output-bytes BYTES", + Integer, + "Queued protocol output limit (default: 4194304)" + ) { |value| @options[:max_output_bytes] = value } + options.on( + "--max-response-bytes BYTES", + Integer, + "Structured tool response limit (default: 1048576)" + ) { |value| @options[:max_response_bytes] = value } + options.on("--version", "Print the gem version") { @options[:version] = true } + options.on("-h", "--help", "Show supported options") { @options[:help] = true } end - options.on("--enrollment-timeout SECONDS", Float, "Setup file lifetime, at most 300 seconds (default: 60)") { |value| @options[:enrollment_timeout] = value } - options.on("--timeout SECONDS", Float, "Total request deadline (default: 5)") { |value| @options[:timeout] = value } - options.on("--concurrency COUNT", Integer, "Active requests (default: 4)") { |value| @options[:concurrency] = value } - options.on("--max-requests COUNT", Integer, "Active plus waiting requests (default: 32)") { |value| @options[:max_requests] = value } - options.on("--max-frame-bytes BYTES", Integer, "Input frame limit (default: 1048576)") { |value| @options[:max_frame_bytes] = value } - options.on("--max-output-bytes BYTES", Integer, "Queued protocol output limit (default: 4194304)") { |value| @options[:max_output_bytes] = value } - options.on("--max-response-bytes BYTES", Integer, "Structured tool response limit (default: 1048576)") { |value| @options[:max_response_bytes] = value } - options.on("--version", "Print the gem version") { @options[:version] = true } - options.on("-h", "--help", "Show supported options") { @options[:help] = true } - end end def validate_arguments raise ArgumentError unless @arguments.empty? raise ArgumentError if @options[:socket_path] && @options[:socket_name] - raise ArgumentError if @options[:start_session] && !SESSION_NAME.match?(@options[:start_session]) + if @options[:start_session] && !SESSION_NAME.match?(@options[:start_session]) + raise ArgumentError + end raise ArgumentError if @options[:keep] && !@options[:start_session] - raise ArgumentError unless @options.fetch(:tools).all? { |name| Catalog::NAMES.include?(name) } - raise ArgumentError unless /\A[A-Za-z0-9][A-Za-z0-9_.-]{0,127}\z/.match?(@options.fetch(:endpoint_name)) - raise ArgumentError unless @options.fetch(:timeout).finite? && @options.fetch(:timeout).positive? + unless @options.fetch(:tools).all? { |name| Catalog::NAMES.include?(name) } + raise ArgumentError + end + unless /\A[A-Za-z0-9][A-Za-z0-9_.-]{0,127}\z/.match?(@options.fetch(:endpoint_name)) + raise ArgumentError + end + unless @options.fetch(:timeout).finite? && @options.fetch(:timeout).positive? + raise ArgumentError + end lifetime = @options.fetch(:enrollment_timeout) raise ArgumentError unless lifetime.finite? && lifetime.positive? && lifetime <= 300 enrollments = @options.fetch(:enrollments) raise ArgumentError unless enrollments.length <= 8 - raise ArgumentError unless enrollments.map(&:first).uniq.length == enrollments.length && enrollments.map(&:last).uniq.length == enrollments.length - raise ArgumentError if !enrollments.empty? && !@options.fetch(:tools).include?("tmux_run") - %i[concurrency max_requests max_frame_bytes max_output_bytes max_response_bytes].each do |key| - raise ArgumentError unless @options.fetch(key).positive? + unless enrollments.map(&:first).uniq.length == enrollments.length && + enrollments.map(&:last).uniq.length == enrollments.length + raise ArgumentError end + raise ArgumentError if !enrollments.empty? && !@options.fetch(:tools).include?("tmux_run") + %i[ + concurrency + max_requests + max_frame_bytes + max_output_bytes + max_response_bytes + ].each { |key| raise ArgumentError unless @options.fetch(key).positive? } raise ArgumentError unless [@input, @output].all? { |io| io.is_a?(IO) && !io.closed? } end @@ -345,7 +521,9 @@ def report(message, status, failure: nil) def diagnostic(message, failure: nil) @error.puts(message) rescue Exception => error - ProcessIdentity.attach_cleanup(failure, ["MCP diagnostic failed (#{error.class})"]) if failure + if failure + ProcessIdentity.attach_cleanup(failure, ["MCP diagnostic failed (#{error.class})"]) + end nil end end diff --git a/gems/libtmux-mcp/lib/libtmux/mcp/enrollment.rb b/gems/libtmux-mcp/lib/libtmux/mcp/enrollment.rb index c48e3aef..bedf7491 100644 --- a/gems/libtmux-mcp/lib/libtmux/mcp/enrollment.rb +++ b/gems/libtmux-mcp/lib/libtmux/mcp/enrollment.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true -require 'libtmux/mcp/observation' -require 'digest/sha2' +require "libtmux/mcp/observation" +require "digest/sha2" module LibTmux module MCP @@ -32,7 +32,12 @@ def close begin File.unlink(@path) if File.exist?(@path) rescue Exception => error - ProcessIdentity.attach_cleanup(failure, ["socket path retirement failed (#{error.class})"]) if failure + if failure + ProcessIdentity.attach_cleanup( + failure, + ["socket path retirement failed (#{error.class})"] + ) + end failure ||= error end raise failure if failure @@ -41,13 +46,15 @@ def close class Channel def initialize(io) - @io, @buffer = io, +''.b + @io, @buffer = io, +"".b end attr_reader :io def write(line, budget) - raise ProtocolError.new('enrollment frame exceeds its limit', phase: :write) if line.bytesize > 1024 || line.include?("\n") + if line.bytesize > 1024 || line.include?("\n") + raise ProtocolError.new("enrollment frame exceeds its limit", phase: :write) + end write_bytes("#{line}\n".b, budget) end @@ -75,7 +82,11 @@ def read_bytes(length, budget) elsif bytes result << bytes else - raise ClosedError.new('shell protocol channel closed', phase: :read, delivery: :possibly_sent) + raise ClosedError.new( + "shell protocol channel closed", + phase: :read, + delivery: :possibly_sent + ) end end result.freeze @@ -86,7 +97,9 @@ def read(budget) if (ending = @buffer.index("\n")) return @buffer.slice!(0, ending + 1).chomp end - raise ProtocolError.new('enrollment frame exceeds its limit', phase: :read) if @buffer.bytesize >= 1024 + if @buffer.bytesize >= 1024 + raise ProtocolError.new("enrollment frame exceeds its limit", phase: :read) + end remaining = budget.options.fetch(:timeout) bytes = @io.read_nonblock(1024 - @buffer.bytesize, exception: false) @@ -95,7 +108,7 @@ def read(budget) elsif bytes @buffer << bytes else - raise ClosedError.new('shell protocol channel closed', phase: :read) + raise ClosedError.new("shell protocol channel closed", phase: :read) end end end @@ -108,22 +121,46 @@ def close class Invitation attr_reader :reference, :capture, :listener, :path, :token, :expires_at - def initialize(reference:, capture:, listener:, path:, expires_at: Process.clock_gettime(Process::CLOCK_MONOTONIC) + 60) + def initialize( + reference:, + capture:, + listener:, + path:, + expires_at: Process.clock_gettime(Process::CLOCK_MONOTONIC) + 60 + ) @reference, @capture, @listener, @path = reference, capture, listener, path.freeze @token = SecureRandom.hex(16).freeze @expires_at = expires_at end def shell_arguments - raise ClosedError.new('shell invitation is closed', phase: :admission) if @released - raise DeadlineExceeded.new('shell invitation expired', phase: :admission) if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= @expires_at + raise ClosedError.new("shell invitation is closed", phase: :admission) if @released + if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= @expires_at + raise DeadlineExceeded.new("shell invitation expired", phase: :admission) + end - roots = %w[libtmux fiddle digest].flat_map { |name| Gem.loaded_specs.fetch(name).full_require_paths } - roots.concat([RbConfig::CONFIG.fetch('rubylibdir'), RbConfig::CONFIG.fetch('rubyarchdir')]) - raise UnsupportedFeatureError.new('helper load paths are unsupported', phase: :admission) if roots.any? { |path| path.include?(File::PATH_SEPARATOR) } + roots = + %w[libtmux fiddle digest].flat_map do |name| + Gem.loaded_specs.fetch(name).full_require_paths + end + roots.concat( + [RbConfig::CONFIG.fetch("rubylibdir"), RbConfig::CONFIG.fetch("rubyarchdir")] + ) + if roots.any? { |path| path.include?(File::PATH_SEPARATOR) } + raise UnsupportedFeatureError.new( + "helper load paths are unsupported", + phase: :admission + ) + end - [File.expand_path('shell/integration.zsh', __dir__), @path, @token, Gem.ruby, - File.expand_path('shell/prepare.rb', __dir__), roots.uniq.join(File::PATH_SEPARATOR)].map { |value| value.dup.freeze }.freeze + [ + File.expand_path("shell/integration.zsh", __dir__), + @path, + @token, + Gem.ruby, + File.expand_path("shell/prepare.rb", __dir__), + roots.uniq.join(File::PATH_SEPARATOR) + ].map { |value| value.dup.freeze }.freeze end def inspect @@ -159,7 +196,12 @@ class Prepared attr_reader :reference, :run_id, :process_generation, :receipt, :completion def initialize(registry, enrollment, digest, listener, path) - @registry, @enrollment, @digest, @listener, @path = registry, enrollment, digest.freeze, listener, path + @registry, @enrollment, @digest, @listener, @path = + registry, + enrollment, + digest.freeze, + listener, + path @reference = enrollment.reference @process_generation = enrollment.capture.process.generation @run_id, @token = SecureRandom.hex(16).freeze, SecureRandom.hex(16).freeze @@ -169,16 +211,25 @@ def initialize(registry, enrollment, digest, listener, path) def prepare(budget) @identity.ensure_live! - deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + budget.options.fetch(:timeout) + deadline = + Process.clock_gettime(Process::CLOCK_MONOTONIC) + budget.options.fetch(:timeout) @sent = true - @enrollment.channel.write("P #{@run_id} #{@token} #{[@path].pack('m0')} #{deadline} #{@digest}", budget) + @enrollment.channel.write( + "P #{@run_id} #{@token} #{[@path].pack("m0")} #{deadline} #{@digest}", + budget + ) @channel = Channel.new(@registry.__send__(:accept_socket, @listener, budget)) - response = @channel.read(budget).split(' ') + response = @channel.read(budget).split(" ") expected = [@run_id, @token, @digest, @identity.pid.to_s] unless response.drop(1) == expected && %w[READY REFUSED].include?(response.first) - raise ProtocolError.new('prepared helper identity is invalid', phase: :admission) + raise ProtocolError.new("prepared helper identity is invalid", phase: :admission) + end + if response.first == "REFUSED" + raise UnsupportedFeatureError.new( + "shell editor is not idle and empty", + phase: :admission + ) end - raise UnsupportedFeatureError.new('shell editor is not idle and empty', phase: :admission) if response.first == 'REFUSED' @identity.ensure_live! self @@ -189,21 +240,37 @@ def authorized? end def authorize(timeout: 0.5, cancel: nil) - raise ClosedError.new('prepared authorization is single use', phase: :admission) if @attempted || @closed + if @attempted || @closed + raise ClosedError.new("prepared authorization is single use", phase: :admission) + end @attempted = true @registry.__send__(:perform, timeout, cancel) do |budget| - @identity.ensure_live! - @registry.__send__(:guard, @reference, @identity, budget, @authorization) { @grant_attempted = true } - @receipt = {'state' => 'authorized', 'run_id' => @run_id, 'script_digest' => @digest, - 'server_generation' => @reference.binding_key, 'pane_id' => @reference.id, - 'enrollment_generation' => @enrollment.epoch, 'process_generation' => @process_generation}.transform_values(&:freeze).freeze - @identity.ensure_live! - @channel.write("GRANT #{@run_id} #{@token} #{@digest}", budget) - expected = "AUTHORIZED #{@run_id} #{@token} #{@digest}" - raise ProtocolError.new('prepared helper acknowledgement is invalid', phase: :read, delivery: :possibly_sent) unless @channel.read(budget) == expected + @identity.ensure_live! + @registry.__send__(:guard, @reference, @identity, budget, @authorization) do + @grant_attempted = true + end + @receipt = { + "state" => "authorized", + "run_id" => @run_id, + "script_digest" => @digest, + "server_generation" => @reference.binding_key, + "pane_id" => @reference.id, + "enrollment_generation" => @enrollment.epoch, + "process_generation" => @process_generation + }.transform_values(&:freeze).freeze + @identity.ensure_live! + @channel.write("GRANT #{@run_id} #{@token} #{@digest}", budget) + expected = "AUTHORIZED #{@run_id} #{@token} #{@digest}" + unless @channel.read(budget) == expected + raise ProtocolError.new( + "prepared helper acknowledgement is invalid", + phase: :read, + delivery: :possibly_sent + ) + end - @receipt + @receipt end end @@ -212,33 +279,74 @@ def grant_attempted? end def execute(script, stdout_limit:, stderr_limit:, timeout:, cancel: nil) - raise ClosedError.new('prepared script is not authorized or has already been sent', phase: :admission) unless @receipt && !@executed && !@closed + unless @receipt && !@executed && !@closed + raise ClosedError.new( + "prepared script is not authorized or has already been sent", + phase: :admission + ) + end @executed = true @registry.__send__(:perform, timeout, cancel) do |operation| - @channel.write("SCRIPT #{@run_id} #{@token} #{@digest} #{script.bytesize} #{stdout_limit} #{stderr_limit}", operation) + @channel.write( + "SCRIPT #{@run_id} #{@token} #{@digest} #{script.bytesize} #{stdout_limit} #{stderr_limit}", + operation + ) @channel.write_bytes(script, operation) - response = @channel.read(operation).split(' ') + response = @channel.read(operation).split(" ") unless response[1, 3] == [@run_id, @token, @digest] - raise ProtocolError.new('script response identity is invalid', phase: :read, delivery: :possibly_sent) + raise ProtocolError.new( + "script response identity is invalid", + phase: :read, + delivery: :possibly_sent + ) end - if response.first == 'ERROR' && response.length == 6 - klass = {'capacity' => CapacityError, 'deadline' => DeadlineExceeded, 'cancelled' => Cancelled, - 'protocol' => ProtocolError, 'unknown' => OutcomeUnknown}.fetch(response[4], OutcomeUnknown) - cleanup = response[5] == 'clean' ? [] : ['authored child retirement was incomplete'] - raise klass.new('authored script did not establish completion', phase: :read, delivery: :possibly_sent, cleanup_errors: cleanup) + if response.first == "ERROR" && response.length == 6 + klass = { + "capacity" => CapacityError, + "deadline" => DeadlineExceeded, + "cancelled" => Cancelled, + "protocol" => ProtocolError, + "unknown" => OutcomeUnknown + }.fetch(response[4], OutcomeUnknown) + cleanup = response[5] == "clean" ? [] : ["authored child retirement was incomplete"] + raise klass.new( + "authored script did not establish completion", + phase: :read, + delivery: :possibly_sent, + cleanup_errors: cleanup + ) end - unless response.length == 8 && response.first == 'RESULT' && %w[EXIT SIGNAL].include?(response[4]) && response[5, 3].all? { |value| /\A\d{1,9}\z/.match?(value) } - raise ProtocolError.new('script completion frame is invalid', phase: :read, delivery: :possibly_sent) + unless response.length == 8 && response.first == "RESULT" && + %w[EXIT SIGNAL].include?(response[4]) && + response[5, 3].all? { |value| /\A\d{1,9}\z/.match?(value) } + raise ProtocolError.new( + "script completion frame is invalid", + phase: :read, + delivery: :possibly_sent + ) end status, out_length, err_length = response[5, 3].map(&:to_i) - if out_length > stdout_limit || err_length > stderr_limit || status > 255 || (response[4] == 'SIGNAL' && status.zero?) - raise ProtocolError.new('script completion exceeds its limits', phase: :read, delivery: :possibly_sent) + if out_length > stdout_limit || err_length > stderr_limit || status > 255 || + (response[4] == "SIGNAL" && status.zero?) + raise ProtocolError.new( + "script completion exceeds its limits", + phase: :read, + delivery: :possibly_sent + ) end - @completion = {'state' => response[4] == 'EXIT' ? 'exited' : 'signaled', - 'exit_status' => response[4] == 'EXIT' ? status : nil, 'signal' => response[4] == 'SIGNAL' ? status : nil}.freeze - Result.new(stdout: @channel.read_bytes(out_length, operation), stderr: @channel.read_bytes(err_length, operation), - exit_status: response[4] == 'EXIT' ? status : nil, signal: response[4] == 'SIGNAL' ? status : nil, receipt: @receipt) + @completion = { + "state" => response[4] == "EXIT" ? "exited" : "signaled", + "exit_status" => response[4] == "EXIT" ? status : nil, + "signal" => response[4] == "SIGNAL" ? status : nil + }.freeze + Result.new( + stdout: @channel.read_bytes(out_length, operation), + stderr: @channel.read_bytes(err_length, operation), + exit_status: response[4] == "EXIT" ? status : nil, + signal: response[4] == "SIGNAL" ? status : nil, + receipt: @receipt + ) end end @@ -253,9 +361,11 @@ def close(timeout: 0.4) @done = true end if @sent && !@done - response = @enrollment.channel.read(@registry.__send__(:budget, timeout, nil)).split(' ') - unless response.length == 3 && response[0, 2] == ['DONE', @run_id] && /\A\d+\z/.match?(response[2]) - raise ProtocolError.new('prepared helper retirement is invalid', phase: :retire) + response = + @enrollment.channel.read(@registry.__send__(:budget, timeout, nil)).split(" ") + unless response.length == 3 && response[0, 2] == ["DONE", @run_id] && + /\A\d+\z/.match?(response[2]) + raise ProtocolError.new("prepared helper retirement is invalid", phase: :retire) end @done = true end @@ -269,44 +379,74 @@ def close(timeout: 0.4) end def initialize(server:, parent:, max_enrollments: 8) - unless server.is_a?(LibTmux::Async::Server) && parent.is_a?(::Async::Task) && !parent.finished? && parent.root.equal?(Fiber.scheduler) - raise ArgumentError, 'enrollment requires an application-owned Async server and live parent task' + unless server.is_a?(LibTmux::Async::Server) && parent.is_a?(::Async::Task) && + !parent.finished? && parent.root.equal?(Fiber.scheduler) + raise ArgumentError, + "enrollment requires an application-owned Async server and live parent task" + end + unless max_enrollments.is_a?(Integer) && max_enrollments.positive? + raise ArgumentError, "enrollment capacity must be positive" end - raise ArgumentError, 'enrollment capacity must be positive' unless max_enrollments.is_a?(Integer) && max_enrollments.positive? @server, @parent, @capacity = server, parent, max_enrollments @thread, @pid, @scheduler = Thread.current, Process.pid, Fiber.scheduler @pending, @enrollments, @prepared = [], {}, [] @reservations, @retiring, @accepting = {}, [], {} @calls, @runs, @watchers, @changed = {}, {}, [], ::Async::Notification.new - @directory = Dir.mktmpdir('libtmux-ruby-enrollment-') + @directory = Dir.mktmpdir("libtmux-ruby-enrollment-") end def inspect "#<#{self.class} closed=#{!!@closed}>" end - def run(reference, script:, timeout: 0.5, cancel: nil, stdout_limit: 65_536, stderr_limit: 65_536) + def run( + reference, + script:, + timeout: 0.5, + cancel: nil, + stdout_limit: 65_536, + stderr_limit: 65_536 + ) ensure_open unless script.is_a?(String) && script.bytesize <= 65_536 && !script.include?("\0") - raise ArgumentError, 'script must contain at most 65536 bytes without NUL' + raise ArgumentError, "script must contain at most 65536 bytes without NUL" end - unless [stdout_limit, stderr_limit].all? { |value| value.is_a?(Integer) && value.between?(0, 262_144) } - raise ArgumentError, 'script output limits must be integers between 0 and 262144' + unless [stdout_limit, stderr_limit].all? { |value| + value.is_a?(Integer) && value.between?(0, 262_144) + } + raise ArgumentError, "script output limits must be integers between 0 and 262144" end script = script.b.freeze run_owner = ::Async::Task.current - raise CapacityError.new('authored run capacity is full', phase: :admission) if @runs.length >= @capacity || @runs.key?(run_owner) + if @runs.length >= @capacity || @runs.key?(run_owner) + raise CapacityError.new("authored run capacity is full", phase: :admission) + end @runs[run_owner] = true owned_run = true operation = budget(timeout, cancel) - prepared = prepare(reference, script_digest: Digest::SHA256.hexdigest(script), **operation.options) + prepared = + prepare(reference, script_digest: Digest::SHA256.hexdigest(script), **operation.options) prepared.authorize(**operation.options) - prepared.execute(script, stdout_limit: stdout_limit, stderr_limit: stderr_limit, **operation.options) + prepared.execute( + script, + stdout_limit: stdout_limit, + stderr_limit: stderr_limit, + **operation.options + ) rescue Exception => error error.extend(RunReceipt) - error.instance_variable_set(:@run_delivery, prepared&.grant_attempted? ? error.respond_to?(:delivery) && error.delivery || :possibly_sent : :not_sent) + error.instance_variable_set( + :@run_delivery, + ( + if prepared&.grant_attempted? + error.respond_to?(:delivery) && error.delivery || :possibly_sent + else + :not_sent + end + ) + ) if prepared&.receipt error.instance_variable_set(:@run_receipt, prepared.receipt) error.instance_variable_set(:@run_completion, prepared.completion) @@ -320,12 +460,18 @@ def run(reference, script:, timeout: 0.5, cancel: nil, stdout_limit: 65_536, std prepared.close rescue Exception => cleanup if primary - ProcessIdentity.attach_cleanup(primary, ["authored helper retirement failed (#{cleanup.class})"]) + ProcessIdentity.attach_cleanup( + primary, + ["authored helper retirement failed (#{cleanup.class})"] + ) else cleanup.extend(RunReceipt) cleanup.instance_variable_set(:@run_receipt, prepared.receipt) cleanup.instance_variable_set(:@run_completion, prepared.completion) - cleanup.instance_variable_set(:@run_delivery, prepared.completion ? :observed : :possibly_sent) + cleanup.instance_variable_set( + :@run_delivery, + prepared.completion ? :observed : :possibly_sent + ) raise end end @@ -340,48 +486,74 @@ def run(reference, script:, timeout: 0.5, cancel: nil, stdout_limit: 65_536, std def invite(reference, timeout: 0.5, cancel: nil, expires_in: 60) ensure_open - unless expires_in.is_a?(Numeric) && expires_in.finite? && expires_in.positive? && expires_in <= 300 - raise ArgumentError, 'shell invitation lifetime must be positive and at most 300 seconds' + unless expires_in.is_a?(Numeric) && expires_in.finite? && expires_in.positive? && + expires_in <= 300 + raise ArgumentError, "shell invitation lifetime must be positive and at most 300 seconds" end perform(timeout, cancel) do |operation| - @server.__send__(:target, reference, :pane) - @pending.dup.each do |pending| - next if @accepting.key?(pending) || clock < pending.expires_at - - retire([pending]) - @pending.delete(pending) - @reservations.delete(pending.reference) - end - if @reservations.length + @enrollments.length >= @capacity || @reservations.key?(reference) || @enrollments.key?(reference) - raise CapacityError.new('shell enrollment capacity is full', phase: :admission) - end - reservation = Object.new - @reservations[reference] = reservation - token = Internal::Cancellation.new - observer = Observation.new(server: @server, arguments: {'target' => wire(reference), 'track' => true, - 'max_lines' => 1, 'max_bytes' => 1}, timeout: operation.options.fetch(:timeout), cancel: cancel || token, max_snapshot_bytes: 1 << 20) - _result, capture = observer.capture(expires: Float::INFINITY) - path = File.join(@directory, SecureRandom.hex(12)) - socket = SocketLease.new(path) - @retiring << socket - listener = socket.bind - invitation = Invitation.new(reference: reference, capture: capture, listener: listener, path: path, expires_at: clock + expires_in) - @pending << invitation - @retiring.delete(socket) - invitation - ensure - begin - retire([observer, token, *(invitation ? [] : [socket, capture])].compact, primary: $!) + @server.__send__(:target, reference, :pane) + @pending.dup.each do |pending| + next if @accepting.key?(pending) || clock < pending.expires_at + + retire([pending]) + @pending.delete(pending) + @reservations.delete(pending.reference) + end + if @reservations.length + @enrollments.length >= @capacity || + @reservations.key?(reference) || @enrollments.key?(reference) + raise CapacityError.new("shell enrollment capacity is full", phase: :admission) + end + reservation = Object.new + @reservations[reference] = reservation + token = Internal::Cancellation.new + observer = + Observation.new( + server: @server, + arguments: { + "target" => wire(reference), + "track" => true, + "max_lines" => 1, + "max_bytes" => 1 + }, + timeout: operation.options.fetch(:timeout), + cancel: cancel || token, + max_snapshot_bytes: 1 << 20 + ) + _result, capture = observer.capture(expires: Float::INFINITY) + path = File.join(@directory, SecureRandom.hex(12)) + socket = SocketLease.new(path) + @retiring << socket + listener = socket.bind + invitation = + Invitation.new( + reference: reference, + capture: capture, + listener: listener, + path: path, + expires_at: clock + expires_in + ) + @pending << invitation + @retiring.delete(socket) + invitation ensure - @reservations.delete(reference) if reservation && !invitation && @reservations[reference].equal?(reservation) - end + begin + retire([observer, token, *(invitation ? [] : [socket, capture])].compact, primary: $!) + ensure + if reservation && !invitation && @reservations[reference].equal?(reservation) + @reservations.delete(reference) + end + end end end def accept(invitation, timeout: nil, cancel: nil) ensure_open - raise ArgumentError, 'invitation is not pending in this registry' unless @pending.include?(invitation) - raise CapacityError.new('shell invitation already has an acceptor', phase: :admission) if @accepting.key?(invitation) + unless @pending.include?(invitation) + raise ArgumentError, "invitation is not pending in this registry" + end + if @accepting.key?(invitation) + raise CapacityError.new("shell invitation already has an acceptor", phase: :admission) + end @accepting[invitation] = true accepted_slot = true @@ -393,21 +565,26 @@ def accept(invitation, timeout: nil, cancel: nil) channel = Channel.new(accept_socket(invitation.listener, operation)) identity = invitation.capture.process identity.ensure_live! - peer_pid = if RUBY_PLATFORM.include?('darwin') - channel.io.getsockopt(0, 0x002).int # SOL_LOCAL / LOCAL_PEERPID; generation remains the native lease. - else - channel.io.getsockopt(Socket::SOL_SOCKET, Socket::SO_PEERCRED).data.unpack1('i') - end - hello = channel.read(operation).split(' ') - unless peer_pid == identity.pid && hello.length == 4 && hello[0, 2] == ['ZLE1', invitation.token] && - /\A5\.9(?:\.\d+)?\z/.match?(hello[2]) && hello[3] == invitation.reference.id - raise UnsupportedFeatureError.new('shell enrollment identity or profile is unsupported', phase: :admission) + peer_pid = + if RUBY_PLATFORM.include?("darwin") + channel.io.getsockopt(0, 0x002).int # SOL_LOCAL / LOCAL_PEERPID; generation remains the native lease. + else + channel.io.getsockopt(Socket::SOL_SOCKET, Socket::SO_PEERCRED).data.unpack1("i") + end + hello = channel.read(operation).split(" ") + unless peer_pid == identity.pid && hello.length == 4 && + hello[0, 2] == ["ZLE1", invitation.token] && + /\A5\.9(?:\.\d+)?\z/.match?(hello[2]) && hello[3] == invitation.reference.id + raise UnsupportedFeatureError.new( + "shell enrollment identity or profile is unsupported", + phase: :admission + ) end guard(invitation.reference, identity, operation) enrollment = Enrollment.new(invitation.reference, invitation.capture, channel) @enrollments[enrollment.reference] = enrollment retire([invitation]) - channel.write_bytes('A', operation) + channel.write_bytes("A", operation) acknowledged = true enrollment end @@ -415,7 +592,9 @@ def accept(invitation, timeout: nil, cancel: nil) if accepted_slot begin unless acknowledged - @enrollments.delete(invitation.reference) if @enrollments[invitation.reference].equal?(enrollment) + if @enrollments[invitation.reference].equal?(enrollment) + @enrollments.delete(invitation.reference) + end retire([enrollment || channel, invitation].compact, primary: $!) end ensure @@ -429,58 +608,68 @@ def accept(invitation, timeout: nil, cancel: nil) def prepare(reference, script_digest:, timeout: 0.5, cancel: nil) ensure_open unless script_digest.is_a?(String) && /\A[0-9a-f]{64}\z/.match?(script_digest) - raise ArgumentError, 'script_digest must be a SHA256 hex digest' + raise ArgumentError, "script_digest must be a SHA256 hex digest" end enrollment = @enrollments[reference] - raise UnsupportedFeatureError.new('pane has no enrolled shell', phase: :admission) unless enrollment - raise CapacityError.new('shell already has an active preparation', phase: :admission) if enrollment.prepared + unless enrollment + raise UnsupportedFeatureError.new("pane has no enrolled shell", phase: :admission) + end + if enrollment.prepared + raise CapacityError.new("shell already has an active preparation", phase: :admission) + end perform(timeout, cancel) do |operation| - raise CapacityError.new('shell already has an active preparation', phase: :admission) if enrollment.prepared - path = File.join(@directory, SecureRandom.hex(12)) - socket = SocketLease.new(path) - @retiring << socket - listener = socket.bind - prepared = Prepared.new(self, enrollment, script_digest.dup, listener, path) - enrollment.prepared = prepared - @prepared << prepared - @retiring.delete(socket) - prepared.prepare(operation) - rescue Exception => error - begin - prepared ? prepared.close : retire([socket].compact, primary: error) - rescue Exception => cleanup - ProcessIdentity.attach_cleanup(error, ["prepared helper retirement failed (#{cleanup.class})"]) - end - raise + if enrollment.prepared + raise CapacityError.new("shell already has an active preparation", phase: :admission) + end + path = File.join(@directory, SecureRandom.hex(12)) + socket = SocketLease.new(path) + @retiring << socket + listener = socket.bind + prepared = Prepared.new(self, enrollment, script_digest.dup, listener, path) + enrollment.prepared = prepared + @prepared << prepared + @retiring.delete(socket) + prepared.prepare(operation) + rescue Exception => error + begin + prepared ? prepared.close : retire([socket].compact, primary: error) + rescue Exception => cleanup + ProcessIdentity.attach_cleanup( + error, + ["prepared helper retirement failed (#{cleanup.class})"] + ) + end + raise end end def close(timeout: 0.5) ensure_owner unless timeout.is_a?(Numeric) && timeout.finite? && timeout.between?(0, 0.5) - raise ArgumentError, 'enrollment cleanup timeout must be between 0 and 0.5 seconds' + raise ArgumentError, "enrollment cleanup timeout must be between 0 and 0.5 seconds" end if @calls.key?(::Async::Task.current) || @runs.key?(::Async::Task.current) - raise ClosedError.new('cannot close enrollment from an active request', phase: :retire) + raise ClosedError.new("cannot close enrollment from an active request", phase: :retire) end @closed = true deadline = clock + timeout errors, interrupted = [], nil - attempt = lambda do |label, &work| - begin - work.call - rescue ::Async::Cancel => error - interrupted ||= error - retry if clock < deadline - errors << "#{label} remains pending" - rescue Exception => error - errors << "#{label} failed (#{error.class})" + attempt = + lambda do |label, &work| + begin + work.call + rescue ::Async::Cancel => error + interrupted ||= error + retry if clock < deadline + errors << "#{label} remains pending" + rescue Exception => error + errors << "#{label} failed (#{error.class})" + end end - end (@calls.keys + @runs.keys).uniq.each do |task| - attempt.call('request cancellation') { task.cancel unless task.finished? } + attempt.call("request cancellation") { task.cancel unless task.finished? } end until (@calls.empty? && @runs.empty?) || clock >= deadline begin @@ -493,17 +682,19 @@ def close(timeout: 0.5) end if @calls.empty? && @runs.empty? @watchers.dup.each do |watcher| - attempt.call('cancellation watcher retirement') do + attempt.call("cancellation watcher retirement") do watcher.cancel unless watcher.finished? watcher.wait(timeout: [deadline - clock, 0].max) unless watcher.finished? @watchers.delete(watcher) if watcher.finished? end end @prepared.dup.each do |prepared| - attempt.call('prepared shell retirement') { prepared.close(timeout: [deadline - clock, 0].max) } + attempt.call("prepared shell retirement") do + prepared.close(timeout: [deadline - clock, 0].max) + end end @pending.dup.each do |invitation| - attempt.call('invitation retirement') do + attempt.call("invitation retirement") do invitation.close @pending.delete(invitation) @reservations.delete(invitation.reference) @@ -512,26 +703,40 @@ def close(timeout: 0.5) @enrollments.dup.each do |reference, enrollment| next if enrollment.prepared - attempt.call('enrollment retirement') do + attempt.call("enrollment retirement") do enrollment.close @enrollments.delete(reference) end end @retiring.dup.each do |resource| - attempt.call('shell resource retirement') do - resource.is_a?(Observation) ? resource.close(timeout: [deadline - clock, 0].max) : resource.close + attempt.call("shell resource retirement") do + if resource.is_a?(Observation) + resource.close(timeout: [deadline - clock, 0].max) + else + resource.close + end @retiring.delete(resource) end end else - errors << 'admitted shell requests remain active' + errors << "admitted shell requests remain active" + end + if errors.empty? + attempt.call("enrollment directory retirement") do + Dir.rmdir(@directory) if Dir.exist?(@directory) + end end - attempt.call('enrollment directory retirement') { Dir.rmdir(@directory) if Dir.exist?(@directory) } if errors.empty? if interrupted ProcessIdentity.attach_cleanup(interrupted, errors) unless errors.empty? raise interrupted end - raise TransportError.new('shell enrollment cleanup remains pending', phase: :retire, cleanup_errors: errors) unless errors.empty? + unless errors.empty? + raise TransportError.new( + "shell enrollment cleanup remains pending", + phase: :retire, + cleanup_errors: errors + ) + end nil end @@ -546,7 +751,12 @@ def retire(resources, primary: nil) @retiring.delete(resource) rescue Exception => error @retiring << resource unless @retiring.include?(resource) - ProcessIdentity.attach_cleanup(failure, ["shell resource cleanup failed (#{error.class})"]) if failure + if failure + ProcessIdentity.attach_cleanup( + failure, + ["shell resource cleanup failed (#{error.class})"] + ) + end failure ||= error end end @@ -557,26 +767,42 @@ def perform(timeout, cancel) ensure_open owner = ::Async::Task.current if @calls.length >= @capacity * 2 || @watchers.length >= @capacity * 2 - raise CapacityError.new('shell protocol request capacity is full', phase: :admission) + raise CapacityError.new("shell protocol request capacity is full", phase: :admission) + end + if @calls.key?(owner) + raise ClosedError.new("nested shell protocol request", phase: :admission) + end + if cancel&.cancelled? + raise Cancelled.new("shell protocol request cancelled", phase: :admission) end - raise ClosedError.new('nested shell protocol request', phase: :admission) if @calls.key?(owner) - raise Cancelled.new('shell protocol request cancelled', phase: :admission) if cancel&.cancelled? @calls[owner] = true armed = true watcher = failure = result = nil begin - watcher = if cancel - ::Async::Task.new(@parent) do - Fiber.scheduler.io_wait(cancel.reader, IO::READABLE) unless cancel.cancelled? - owner.cancel if armed && cancel.cancelled? + watcher = + if cancel + ::Async::Task.new(@parent) do + Fiber.scheduler.io_wait(cancel.reader, IO::READABLE) unless cancel.cancelled? + owner.cancel if armed && cancel.cancelled? + end end - end @watchers << watcher if watcher watcher&.run result = yield budget(timeout, cancel) rescue ::Async::Cancel => error - failure = (@closed || cancel&.cancelled?) ? Cancelled.new('shell protocol request cancelled', phase: :admission, delivery: :possibly_sent) : error + failure = + ( + if (@closed || cancel&.cancelled?) + Cancelled.new( + "shell protocol request cancelled", + phase: :admission, + delivery: :possibly_sent + ) + else + error + end + ) rescue Exception => error failure = error ensure @@ -590,8 +816,14 @@ def perform(timeout, cancel) failure ||= error retry if clock < deadline rescue Exception => error - ProcessIdentity.attach_cleanup(failure, ["cancellation watcher cleanup failed (#{error.class})"]) if failure - failure ||= TransportError.new('cancellation watcher cleanup remains pending', phase: :retire) + if failure + ProcessIdentity.attach_cleanup( + failure, + ["cancellation watcher cleanup failed (#{error.class})"] + ) + end + failure ||= + TransportError.new("cancellation watcher cleanup remains pending", phase: :retire) ensure @watchers.delete(watcher) if watcher.finished? end @@ -610,7 +842,7 @@ def discard(enrollment) end def wire(ref) - {'generation' => ref.binding_key, 'kind' => 'pane', 'id' => ref.id} + { "generation" => ref.binding_key, "kind" => "pane", "id" => ref.id } end def release(prepared) @@ -634,31 +866,47 @@ def accept_socket(listener, operation) def guard(reference, identity, operation, nonce = nil) identity.ensure_live! - names = @server.__send__(:builtin_spellings, 'if-shell', 'wait-for', budget: operation) - predicate = "\#{&&:\#{==:\#{pane_id},#{reference.id}},\#{&&:\#{==:\#{pane_pid},#{identity.pid}},\#{&&:\#{==:\#{pane_dead_status},},\#{==:\#{pane_dead_signal},}}}}" - branch = if nonce - [@server.__send__(:tmux_command, [names.fetch('wait-for'), '-S', nonce]), - @server.__send__(:tmux_command, [names.fetch('wait-for'), nonce])].join(' ; ') - else - '' - end - failure = @server.__send__(:tmux_command, [names.fetch('wait-for')]) + names = @server.__send__(:builtin_spellings, "if-shell", "wait-for", budget: operation) + predicate = + "\#{&&:\#{==:\#{pane_id},#{reference.id}},\#{&&:\#{==:\#{pane_pid},#{identity.pid}},\#{&&:\#{==:\#{pane_dead_status},},\#{==:\#{pane_dead_signal},}}}}" + branch = + if nonce + [ + @server.__send__(:tmux_command, [names.fetch("wait-for"), "-S", nonce]), + @server.__send__(:tmux_command, [names.fetch("wait-for"), nonce]) + ].join(" ; ") + else + "" + end + failure = @server.__send__(:tmux_command, [names.fetch("wait-for")]) yield if block_given? - @server.__send__(:execute_typed, [names.fetch('if-shell'), '-F', '-t', reference.id, predicate, branch, failure], **operation.options) + @server.__send__( + :execute_typed, + [names.fetch("if-shell"), "-F", "-t", reference.id, predicate, branch, failure], + **operation.options + ) rescue CommandError => error - raise TargetNotFoundError.new('enrolled shell no longer belongs to the pane', phase: :admission, delivery: :not_sent), cause: nil + raise TargetNotFoundError.new( + "enrolled shell no longer belongs to the pane", + phase: :admission, + delivery: :not_sent + ), + cause: nil end def ensure_owner - unless Process.pid == @pid && Thread.current.equal?(@thread) && Fiber.scheduler.equal?(@scheduler) - raise ClosedError.new('shell enrollment belongs to another scheduler', phase: :admission) + unless Process.pid == @pid && Thread.current.equal?(@thread) && + Fiber.scheduler.equal?(@scheduler) + raise ClosedError.new("shell enrollment belongs to another scheduler", phase: :admission) end end def ensure_open ensure_owner - raise ClosedError.new('shell enrollment is closed', phase: :admission) if @closed - raise CapacityError.new('shell resource retirement remains pending', phase: :admission) unless @retiring.empty? + raise ClosedError.new("shell enrollment is closed", phase: :admission) if @closed + unless @retiring.empty? + raise CapacityError.new("shell resource retirement remains pending", phase: :admission) + end end def clock diff --git a/gems/libtmux-mcp/lib/libtmux/mcp/mutations.rb b/gems/libtmux-mcp/lib/libtmux/mcp/mutations.rb index 93cba43c..a9465071 100644 --- a/gems/libtmux-mcp/lib/libtmux/mcp/mutations.rb +++ b/gems/libtmux-mcp/lib/libtmux/mcp/mutations.rb @@ -9,28 +9,42 @@ def initialize(server:, arguments:, timeout:, cancel:, max_snapshot_bytes:) @deadline = clock + timeout @max_snapshot_bytes = max_snapshot_bytes bytes = 0 - visit = lambda do |value| - case value - when String then bytes += value.bytesize - when Array then value.each { |item| visit.call(item) } - when Hash then value.each { |key, item| visit.call(key); visit.call(item) } + visit = + lambda do |value| + case value + when String + bytes += value.bytesize + when Array + value.each { |item| visit.call(item) } + when Hash + value.each do |key, item| + visit.call(key) + visit.call(item) + end + end + if bytes > Catalog::MUTATION_BYTES + raise CapacityError.new( + "MCP mutation input exceeds its byte limit", + phase: :admission + ) + end end - raise CapacityError.new("MCP mutation input exceeds its byte limit", phase: :admission) if bytes > Catalog::MUTATION_BYTES - end visit.call(arguments) end def call(name) case name - when "tmux_create" then create + when "tmux_create" + create when "tmux_send" target = resolve(@arguments.fetch("target")) input = @arguments.fetch("input") - result = if input.fetch("type") == "text" - dispatch { |budget| target.send_text(input.fetch("text"), **budget) } - else - dispatch { |budget| target.send_keys(*input.fetch("keys"), **budget) } - end + result = + if input.fetch("type") == "text" + dispatch { |budget| target.send_text(input.fetch("text"), **budget) } + else + dispatch { |budget| target.send_keys(*input.fetch("keys"), **budget) } + end outcome(target, result).merge("completion" => "dispatch_only") when "tmux_close" target = resolve(@arguments.fetch("target")) @@ -52,9 +66,11 @@ def options raise Cancelled.new("MCP mutation was cancelled", phase: :admission) if @cancel.cancelled? remaining = @deadline - clock - raise DeadlineExceeded.new("MCP mutation deadline elapsed", phase: :admission) unless remaining.positive? + unless remaining.positive? + raise DeadlineExceeded.new("MCP mutation deadline elapsed", phase: :admission) + end - {timeout: remaining, cancel: @cancel} + { timeout: remaining, cancel: @cancel } end def dispatch @@ -66,53 +82,100 @@ def dispatch def resolve(reference) snapshot = @server.snapshot(**options, max_bytes: @max_snapshot_bytes, max_rows: 4096) unless reference.fetch("generation") == snapshot.binding_key - raise TargetNotFoundError.new("target belongs to another server binding", phase: :admission) + raise TargetNotFoundError.new( + "target belongs to another server binding", + phase: :admission + ) end kind = reference.fetch("kind") - records = snapshot.public_send({"session" => :sessions, "window" => :windows, "pane" => :panes}.fetch(kind)) + records = + snapshot.public_send( + { "session" => :sessions, "window" => :windows, "pane" => :panes }.fetch(kind) + ) record = records.find { |item| item.id == reference.fetch("id") } - raise TargetNotFoundError.new("target is not present in this server binding", phase: :admission) unless record + unless record + raise TargetNotFoundError.new( + "target is not present in this server binding", + phase: :admission + ) + end @server.public_send(kind, record.ref) end def create values = @arguments - common = {command: values.fetch("argv"), cwd: values["cwd"], environment: values.fetch("environment", {})} - created = case values.fetch("kind") - when "session" - dispatch do |budget| - @server.new_session(name: values.fetch("name"), window_name: values["window_name"], - width: values["width"], height: values["height"], receipt: true, **common, **budget) + common = { + command: values.fetch("argv"), + cwd: values["cwd"], + environment: values.fetch("environment", {}) + } + created = + case values.fetch("kind") + when "session" + dispatch do |budget| + @server.new_session( + name: values.fetch("name"), + window_name: values["window_name"], + width: values["width"], + height: values["height"], + receipt: true, + **common, + **budget + ) + end + when "window" + parent = resolve(values.fetch("parent")) + dispatch do |budget| + parent.new_window( + name: values.fetch("name"), + index: values["index"], + focus: values.fetch("focus", false), + receipt: true, + **common, + **budget + ) + end + when "pane" + parent = resolve(values.fetch("parent")) + dispatch do |budget| + parent.split( + direction: values.fetch("direction").to_sym, + size: values["size"], + focus: values.fetch("focus", false), + **common, + **budget + ) + end end - when "window" - parent = resolve(values.fetch("parent")) - dispatch do |budget| - parent.new_window(name: values.fetch("name"), index: values["index"], - focus: values.fetch("focus", false), receipt: true, **common, **budget) - end - when "pane" - parent = resolve(values.fetch("parent")) - dispatch do |budget| - parent.split(direction: values.fetch("direction").to_sym, - size: values["size"], focus: values.fetch("focus", false), **common, **budget) + entities = + if created.is_a?(CreationReceipt) + [created.entity, created.window, created.pane].uniq + else + [created] end - end - entities = if created.is_a?(CreationReceipt) - [created.entity, created.window, created.pane].uniq - else - [created] - end - {"entity" => reference(entities.first), "created" => entities.map { |entity| reference(entity) }, - "delivery" => "observed", "program_completion" => "unobserved"} + { + "entity" => reference(entities.first), + "created" => entities.map { |entity| reference(entity) }, + "delivery" => "observed", + "program_completion" => "unobserved" + } end def reference(entity) - {"generation" => entity.ref.binding_key, "kind" => entity.ref.kind.to_s, "id" => entity.id} + { + "generation" => entity.ref.binding_key, + "kind" => entity.ref.kind.to_s, + "id" => entity.id + } end def outcome(target, result) - {"target" => reference(target), "delivery" => result.delivery.to_s, "client_exit_status" => result.status.exitstatus} + { + "target" => reference(target), + "delivery" => result.delivery.to_s, + "client_exit_status" => result.status.exitstatus + } end end private_constant :Mutation diff --git a/gems/libtmux-mcp/lib/libtmux/mcp/observation.rb b/gems/libtmux-mcp/lib/libtmux/mcp/observation.rb index 50a65b5c..b2a9c0fe 100644 --- a/gems/libtmux-mcp/lib/libtmux/mcp/observation.rb +++ b/gems/libtmux-mcp/lib/libtmux/mcp/observation.rb @@ -21,25 +21,50 @@ def initialize(message, capture:, **details) module CleanupDetails attr_reader :mcp_cleanup_errors end - Capture = Data.define(:rows, :capture_id, :reference, :options, :process, :expires, :bytes, :encoding) do - def close - process.close + Capture = + Data.define( + :rows, + :capture_id, + :reference, + :options, + :process, + :expires, + :bytes, + :encoding + ) do + def close + process.close + end end - end - Retirement = Data.define(:owner, :tasks, :subscription, :control) do - def complete? - tasks.all?(&:finished?) && (!subscription || subscription.closed?) && (!control || control.closed?) - end + Retirement = + Data.define(:owner, :tasks, :subscription, :control) do + def complete? + tasks.all?(&:finished?) && (!subscription || subscription.closed?) && + (!control || control.closed?) + end - def close(deadline:) - errors = owner.__send__(:retire_attempt, tasks, subscription: subscription, control: control, deadline: deadline) - errors << "observation consumers remain pending" unless complete? - raise TransportError.new("observation consumers are still retiring", phase: :retire, cleanup_errors: errors) unless errors.empty? + def close(deadline:) + errors = + owner.__send__( + :retire_attempt, + tasks, + subscription: subscription, + control: control, + deadline: deadline + ) + errors << "observation consumers remain pending" unless complete? + unless errors.empty? + raise TransportError.new( + "observation consumers are still retiring", + phase: :retire, + cleanup_errors: errors + ) + end - nil + nil + end end - end def self.supported_release?(version) LibTmux::Internal::TmuxVersion.require_supported(version) @@ -55,25 +80,42 @@ def self.preflight_hooks?(release) end def self.capabilities(version) - native = case RUBY_PLATFORM - when /\A(?:x86_64|aarch64)-linux/ - ["64-bit Linux with peer pidfds (kernel >= 6.6)", "same PID namespace and matching procfs"] - when /\A(?:x86_64|arm64)-darwin/ - ["64-bit Darwin with kqueue NOTE_EXIT/NOTE_REAP", "fresh pinned-route daemon identity"] - end + native = + case RUBY_PLATFORM + when /\A(?:x86_64|aarch64)-linux/ + [ + "64-bit Linux with peer pidfds (kernel >= 6.6)", + "same PID namespace and matching procfs" + ] + when /\A(?:x86_64|arm64)-darwin/ + ["64-bit Darwin with kqueue NOTE_EXIT/NOTE_REAP", "fresh pinned-route daemon identity"] + end conditional = native && Fiddle::SIZEOF_LONG == 8 && supported_release?(version) - {"screen" => "bounded_rows", "history_continuity" => "unknown", + { + "screen" => "bounded_rows", + "history_continuity" => "unknown", "process_cursor" => conditional ? "conditional" : "unsupported", - "requirements" => ["tmux >= #{LibTmux::Internal::TmuxVersion::MINIMUM}", *(native || ["supported 64-bit Linux or Darwin process identity backend"]), - "live pane process", "empty effective capture hook", "stable capture-hook configuration on tmux < 3.5", - "screen_contains waits use control events from tmux #{LibTmux::Internal::TmuxVersion::CONTROL_MINIMUM} and poll the screen before it"], - "wait_conditions" => %w[screen_contains process_exit]} + "requirements" => [ + "tmux >= #{LibTmux::Internal::TmuxVersion::MINIMUM}", + *(native || ["supported 64-bit Linux or Darwin process identity backend"]), + "live pane process", + "empty effective capture hook", + "stable capture-hook configuration on tmux < 3.5", + "screen_contains waits use control events from tmux #{LibTmux::Internal::TmuxVersion::CONTROL_MINIMUM} and poll the screen before it" + ], + "wait_conditions" => %w[screen_contains process_exit] + } end def initialize(server:, arguments:, timeout:, cancel:, max_snapshot_bytes:) @server, @arguments, @cancel = server, arguments, cancel @started = clock - @budget = server.__send__(:operation_budget, [timeout, arguments.fetch("timeout", timeout)].min, cancel) + @budget = + server.__send__( + :operation_budget, + [timeout, arguments.fetch("timeout", timeout)].min, + cancel + ) @max_snapshot_bytes = max_snapshot_bytes @owned = [] @retirements = [] @@ -100,7 +142,13 @@ def close(timeout: 0.4) errors.concat(error.cleanup_errors) if error.is_a?(LibTmux::Error) end end - raise TransportError.new("observer resources remain pending", phase: :retire, cleanup_errors: errors) unless errors.empty? + unless errors.empty? + raise TransportError.new( + "observer resources remain pending", + phase: :retire, + cleanup_errors: errors + ) + end nil end @@ -112,52 +160,75 @@ def cleanup_remaining def capture(previous: nil, expires:) identity = entry = nil - response = with_cancellation do - reference = @arguments.fetch("target").transform_values { |value| value.is_a?(String) ? value.dup : value } - if previous - raise StaleCursor, "cursor target differs" unless reference == previous.reference - - identity = previous.process.retain - @owned << identity - end - snapshot, pane = resolve(reference) - tracked = previous || @arguments.fetch("track", false) - if tracked - require_tracking(snapshot) - identity ||= acquire_identity(snapshot, pane) - identity.ensure_live! - end - limits = previous ? previous.options : defaults - rows, encoding, truncated = read_rows(snapshot, pane, limits, identity) - id = SecureRandom.hex(16) - result = state(reference, rows, encoding, truncated, limits, identity, id) - if previous - prefix = 0 - suffix = 0 - if previous.encoding == encoding - prefix += 1 while prefix < [rows.length, previous.rows.length].min && rows[prefix] == previous.rows[prefix] - suffix += 1 while suffix < [rows.length, previous.rows.length].min - prefix && rows[-suffix - 1] == previous.rows[-suffix - 1] + response = + with_cancellation do + reference = + @arguments + .fetch("target") + .transform_values { |value| value.is_a?(String) ? value.dup : value } + if previous + raise StaleCursor, "cursor target differs" unless reference == previous.reference + + identity = previous.process.retain + @owned << identity end - result.delete("rows") - result.merge!("mode" => "delta", "base_capture_id" => previous.capture_id, - "reset" => prefix.zero? && suffix.zero?, "splice" => {"start" => prefix, - "delete" => previous.rows.length - prefix - suffix, "rows" => rows.slice(prefix, rows.length - prefix - suffix)}) - end - if tracked - result["next_cursor"] = id - entry = Capture.new(rows: rows, capture_id: id.freeze, reference: freeze_tree(reference), - options: freeze_tree(limits), process: identity, expires: expires, - bytes: rows.sum(&:bytesize) + JSON.generate(reference).bytesize + 256, encoding: encoding) - @owned.delete(identity) - @owned << entry - identity = nil + snapshot, pane = resolve(reference) + tracked = previous || @arguments.fetch("track", false) + if tracked + require_tracking(snapshot) + identity ||= acquire_identity(snapshot, pane) + identity.ensure_live! + end + limits = previous ? previous.options : defaults + rows, encoding, truncated = read_rows(snapshot, pane, limits, identity) + id = SecureRandom.hex(16) + result = state(reference, rows, encoding, truncated, limits, identity, id) + if previous + prefix = 0 + suffix = 0 + if previous.encoding == encoding + prefix += 1 while prefix < [rows.length, previous.rows.length].min && + rows[prefix] == previous.rows[prefix] + suffix += 1 while suffix < [rows.length, previous.rows.length].min - prefix && + rows[-suffix - 1] == previous.rows[-suffix - 1] + end + result.delete("rows") + result.merge!( + "mode" => "delta", + "base_capture_id" => previous.capture_id, + "reset" => prefix.zero? && suffix.zero?, + "splice" => { + "start" => prefix, + "delete" => previous.rows.length - prefix - suffix, + "rows" => rows.slice(prefix, rows.length - prefix - suffix) + } + ) + end + if tracked + result["next_cursor"] = id + entry = + Capture.new( + rows: rows, + capture_id: id.freeze, + reference: freeze_tree(reference), + options: freeze_tree(limits), + process: identity, + expires: expires, + bytes: rows.sum(&:bytesize) + JSON.generate(reference).bytesize + 256, + encoding: encoding + ) + @owned.delete(identity) + @owned << entry + identity = nil + end + [result, entry] end - [result, entry] - end @owned.delete(entry) response rescue TargetNotFoundError, CommandError => error - raise StaleCursor.new("cursor process changed", delivery: error.delivery), cause: nil if previous + if previous + raise StaleCursor.new("cursor process changed", delivery: error.delivery), cause: nil + end raise ensure @@ -178,147 +249,240 @@ def wait tasks = [] failure = response = nil begin - response = with_cancellation do - reference = @arguments.fetch("target") - condition = @arguments.fetch("condition") - snapshot, pane = resolve(reference) - require_tracking(snapshot) - # Daemons below 3.7 take no control client, so a screen wait polls the pane. - polling = condition.fetch("type") == "screen_contains" && !@server.supports_control? - identity = acquire_identity(snapshot, pane) - if condition.fetch("type") == "screen_contains" && !polling - link = snapshot.window_links.find { |item| item.window_id == pane.window_id } - raise TargetNotFoundError.new("pane has no observable session", phase: :admission) unless link - - session = snapshot.sessions.find { |item| item.id == link.session_id } - control = @server.open_control(session: session.ref) - subscription = control.subscribe(pane_id: pane.id, max_bytes: 1 << 18, max_events: 256) - # A completed private boundary proves attach input is being read. - line = @server.__send__(:tmux_command, [spellings.fetch("if-shell"), "-F", "0", ""]) - control.exchange(line, **@budget.options) - end - limits = defaults - # A pane or server that ends mid-read ends the wait as PaneDied, with - # the last rows read, unless the read failed for another reason. - pane_died = lambda do - rows, encoding, truncated = latest - PaneDied.new("observed pane process exited", phase: :observation, delivery: :observed, - capture: state(reference, rows, encoding, truncated, limits, identity, SecureRandom.hex(16))) - end - read = lambda do - begin - latest = read_rows(snapshot, pane, limits, identity, true) - rescue TargetNotFoundError, CommandError, TransportError - raise if latest.nil? - - raise unless ended?(identity) + response = + with_cancellation do + reference = @arguments.fetch("target") + condition = @arguments.fetch("condition") + snapshot, pane = resolve(reference) + require_tracking(snapshot) + # Daemons below 3.7 take no control client, so a screen wait polls the pane. + polling = condition.fetch("type") == "screen_contains" && !@server.supports_control? + identity = acquire_identity(snapshot, pane) + if condition.fetch("type") == "screen_contains" && !polling + link = snapshot.window_links.find { |item| item.window_id == pane.window_id } + unless link + raise TargetNotFoundError.new("pane has no observable session", phase: :admission) + end - raise pane_died.call + session = snapshot.sessions.find { |item| item.id == link.session_id } + control = @server.open_control(session: session.ref) + subscription = + control.subscribe(pane_id: pane.id, max_bytes: 1 << 18, max_events: 256) + # A completed private boundary proves attach input is being read. + line = @server.__send__(:tmux_command, [spellings.fetch("if-shell"), "-F", "0", ""]) + control.exchange(line, **@budget.options) end - end - rows, encoding, truncated = read.call - if condition.fetch("type") == "screen_contains" && contains?(rows, encoding, condition.fetch("text")) - next {"target" => reference, "condition" => "screen_contains", - "capture" => state(reference, rows, encoding, truncated, limits, identity, SecureRandom.hex(16))} - end - changed = ::Async::Notification.new - pending = nil - weights = {read: 0, stream_ended: 1, exited: 2, server_exited: 2} - weigh = ->(value) { value.is_a?(Exception) ? 3 : weights.fetch(value) } - wake = lambda do |value| - pending = value if pending.nil? || weigh.call(value) > weigh.call(pending) - changed.signal - end - [[identity.io, :exited], [identity.peer, :server_exited]].each do |io, event| - task = ::Async::Task.new(::Async::Task.current) do - Fiber.scheduler.io_wait(io, IO::READABLE) - wake.call(event) - rescue ::Async::Cancel - nil - rescue StandardError => error - wake.call(error) - end - tasks << task - task.run - end - if polling - task = ::Async::Task.new(::Async::Task.current) do - loop do - ::Async::Task.current.sleep(POLL_SECONDS) - wake.call(:read) + limits = defaults + # A pane or server that ends mid-read ends the wait as PaneDied, with + # the last rows read, unless the read failed for another reason. + pane_died = + lambda do + rows, encoding, truncated = latest + PaneDied.new( + "observed pane process exited", + phase: :observation, + delivery: :observed, + capture: + state( + reference, + rows, + encoding, + truncated, + limits, + identity, + SecureRandom.hex(16) + ) + ) end - rescue ::Async::Cancel - nil - rescue StandardError => error - wake.call(error) - end - tasks << task - task.run - end - if subscription - task = ::Async::Task.new(::Async::Task.current) do - # Kernel#loop would swallow the StopIteration that ends the stream. - while true + read = + lambda do begin - event = subscription.next(timeout: @budget.options.fetch(:timeout)) - rescue StopIteration - wake.call(:stream_ended) - break - end - if event.kind == :gap - wake.call(LostObservation.new("screen observation has a gap", phase: :observation, delivery: :observed)) - break + latest = read_rows(snapshot, pane, limits, identity, true) + rescue TargetNotFoundError, CommandError, TransportError + raise if latest.nil? + + raise unless ended?(identity) + + raise pane_died.call end - wake.call(:read) if event.kind == :output end - rescue ::Async::Cancel - nil - rescue StandardError => error - wake.call(error) + rows, encoding, truncated = read.call + if condition.fetch("type") == "screen_contains" && + contains?(rows, encoding, condition.fetch("text")) + next( + { + "target" => reference, + "condition" => "screen_contains", + "capture" => + state( + reference, + rows, + encoding, + truncated, + limits, + identity, + SecureRandom.hex(16) + ) + } + ) end - tasks << task - task.run - end - loop do - remaining = @budget.options.fetch(:timeout) - ::Async::Task.current.with_timeout(remaining) { changed.wait } unless pending - event, pending = pending, nil - raise event if event.is_a?(Exception) - - if event == :stream_ended - # A stopped second client keeps a killed server alive after the - # stream ends, so ask the daemon instead of waiting for its process. - raise pane_died.call if ended?(identity) - - raise LostObservation.new("screen observation ended", phase: :observation, delivery: :observed) + changed = ::Async::Notification.new + pending = nil + weights = { read: 0, stream_ended: 1, exited: 2, server_exited: 2 } + weigh = ->(value) { value.is_a?(Exception) ? 3 : weights.fetch(value) } + wake = + lambda do |value| + pending = value if pending.nil? || weigh.call(value) > weigh.call(pending) + changed.signal + end + [[identity.io, :exited], [identity.peer, :server_exited]].each do |io, event| + task = + ::Async::Task.new(::Async::Task.current) do + Fiber.scheduler.io_wait(io, IO::READABLE) + wake.call(event) + rescue ::Async::Cancel + nil + rescue StandardError => error + wake.call(error) + end + tasks << task + task.run end - if event == :exited || event == :server_exited - if condition.fetch("type") == "process_exit" - begin - identity.peer_alive! - rescue TargetNotFoundError - raise LostObservation.new("tmux process ended", phase: :observation, delivery: :observed), cause: nil + if polling + task = + ::Async::Task.new(::Async::Task.current) do + loop do + ::Async::Task.current.sleep(POLL_SECONDS) + wake.call(:read) + end + rescue ::Async::Cancel + nil + rescue StandardError => error + wake.call(error) end - break {"target" => reference, "condition" => "process_exit", "process_generation" => identity.generation, - "observed_at" => clock, "exit_status" => "unobserved"} + tasks << task + task.run + end + if subscription + task = + ::Async::Task.new(::Async::Task.current) do + # Kernel#loop would swallow the StopIteration that ends the stream. + while true + begin + event = subscription.next(timeout: @budget.options.fetch(:timeout)) + rescue StopIteration + wake.call(:stream_ended) + break + end + if event.kind == :gap + wake.call( + LostObservation.new( + "screen observation has a gap", + phase: :observation, + delivery: :observed + ) + ) + break + end + wake.call(:read) if event.kind == :output + end + rescue ::Async::Cancel + nil + rescue StandardError => error + wake.call(error) + end + tasks << task + task.run + end + loop do + remaining = @budget.options.fetch(:timeout) + ::Async::Task.current.with_timeout(remaining) { changed.wait } unless pending + event, pending = pending, nil + raise event if event.is_a?(Exception) + + if event == :stream_ended + # A stopped second client keeps a killed server alive after the + # stream ends, so ask the daemon instead of waiting for its process. + raise pane_died.call if ended?(identity) + + raise LostObservation.new( + "screen observation ended", + phase: :observation, + delivery: :observed + ) + end + if event == :exited || event == :server_exited + if condition.fetch("type") == "process_exit" + begin + identity.peer_alive! + rescue TargetNotFoundError + raise LostObservation.new( + "tmux process ended", + phase: :observation, + delivery: :observed + ), + cause: nil + end + break( + { + "target" => reference, + "condition" => "process_exit", + "process_generation" => identity.generation, + "observed_at" => clock, + "exit_status" => "unobserved" + } + ) + end + # The last output may have landed just before the end. + rows, encoding, truncated = read.call + if contains?(rows, encoding, condition.fetch("text")) + break( + { + "target" => reference, + "condition" => "screen_contains", + "capture" => + state( + reference, + rows, + encoding, + truncated, + limits, + identity, + SecureRandom.hex(16) + ) + } + ) + end + raise pane_died.call end - # The last output may have landed just before the end. rows, encoding, truncated = read.call if contains?(rows, encoding, condition.fetch("text")) - break {"target" => reference, "condition" => "screen_contains", - "capture" => state(reference, rows, encoding, truncated, limits, identity, SecureRandom.hex(16))} + break( + { + "target" => reference, + "condition" => "screen_contains", + "capture" => + state( + reference, + rows, + encoding, + truncated, + limits, + identity, + SecureRandom.hex(16) + ) + } + ) end - raise pane_died.call - end - rows, encoding, truncated = read.call - if contains?(rows, encoding, condition.fetch("text")) - break {"target" => reference, "condition" => "screen_contains", - "capture" => state(reference, rows, encoding, truncated, limits, identity, SecureRandom.hex(16))} end end - end rescue ::Async::TimeoutError - failure = DeadlineExceeded.new("observation deadline elapsed", phase: :observation, delivery: :observed) + failure = + DeadlineExceeded.new( + "observation deadline elapsed", + phase: :observation, + delivery: :observed + ) rescue Exception => error failure = error ensure @@ -330,7 +494,12 @@ def wait end unless errors.empty? attach_cleanup(failure, errors) if failure - failure ||= TransportError.new("observation cleanup failed", phase: :retire, cleanup_errors: errors) + failure ||= + TransportError.new( + "observation cleanup failed", + phase: :retire, + cleanup_errors: errors + ) end end raise failure if failure @@ -342,7 +511,8 @@ def wait # What a daemon that is killed, or shutting down behind a stopped client, # tells a client. - SERVER_GONE = /\A(?:no server running|server exited unexpectedly|error connecting to .*\((?:No such file or directory|Connection refused)\))/ + SERVER_GONE = + /\A(?:no server running|server exited unexpectedly|error connecting to .*\((?:No such file or directory|Connection refused)\))/ # True when the pane process is gone or the daemon says it is gone. # An inconclusive probe, such as a failed spawn, is not an end. @@ -378,8 +548,14 @@ def acquire_identity(snapshot, pane) # tmux 3.8 reports no PID for a dead pane; there is no process to bind. raise TargetNotFoundError.new("pane process has exited", phase: :admission) if pane.pid.nil? - identity = ProcessIdentity.acquire(@server, server_pid: snapshot.server_info.fetch(:pid), pane_pid: pane.pid, - budget: @budget, on_retire: ->(resource) { @owned << resource }) + identity = + ProcessIdentity.acquire( + @server, + server_pid: snapshot.server_info.fetch(:pid), + pane_pid: pane.pid, + budget: @budget, + on_retire: ->(resource) { @owned << resource } + ) @owned << identity identity end @@ -389,15 +565,22 @@ def clock end def defaults - {"max_lines" => @arguments.fetch("max_lines", 200), "max_bytes" => @arguments.fetch("max_bytes", 65536), - "history_lines" => @arguments.fetch("history_lines", 0)} + { + "max_lines" => @arguments.fetch("max_lines", 200), + "max_bytes" => @arguments.fetch("max_bytes", 65_536), + "history_lines" => @arguments.fetch("history_lines", 0) + } end def resolve(reference) - snapshot = @server.snapshot(**@budget.options, max_bytes: @max_snapshot_bytes, max_rows: 4096) + snapshot = + @server.snapshot(**@budget.options, max_bytes: @max_snapshot_bytes, max_rows: 4096) pane = snapshot.panes.find { |record| record.id == reference.fetch("id") } unless reference.fetch("generation") == snapshot.binding_key && pane - raise TargetNotFoundError.new("pane reference is outside this live binding", phase: :admission) + raise TargetNotFoundError.new( + "pane reference is outside this live binding", + phase: :admission + ) end [snapshot, pane] end @@ -405,8 +588,10 @@ def resolve(reference) def require_tracking(snapshot) return if self.class.supported_release?(snapshot.server_info.fetch(:version)) - raise UnsupportedFeatureError.new("process cursors require tmux #{LibTmux::Internal::TmuxVersion::MINIMUM} or newer", - phase: :admission) + raise UnsupportedFeatureError.new( + "process cursors require tmux #{LibTmux::Internal::TmuxVersion::MINIMUM} or newer", + phase: :admission + ) end # +joined+ joins wrapped rows into the lines the program wrote, so a wait @@ -415,40 +600,93 @@ def read_rows(snapshot, pane, limits, identity, joined = false) identity&.ensure_live! names = spellings link = snapshot.window_links.find { |item| item.window_id == pane.window_id } - raise TargetNotFoundError.new("pane has no observable session", phase: :admission) unless link + unless link + raise TargetNotFoundError.new("pane has no observable session", phase: :admission) + end target = "#{link.session_id}:.#{pane.id}" guard = "\#{&&:\#{==:\#{session_id},#{link.session_id}},\#{==:\#{pane_id},#{pane.id}}}" - guard = "\#{&&:#{guard},\#{&&:\#{==:\#{pane_pid},#{identity.pid}},\#{&&:\#{==:\#{pane_dead_status},},\#{==:\#{pane_dead_signal},}}}}" if identity - body = @server.__send__(:tmux_command, [names.fetch("capture-pane"), "-p", *(joined ? ["-J"] : []), "-t", target, - "-S", (-limits.fetch("history_lines")).to_s, "-E", "-"]) + guard = + "\#{&&:#{guard},\#{&&:\#{==:\#{pane_pid},#{identity.pid}},\#{&&:\#{==:\#{pane_dead_status},},\#{==:\#{pane_dead_signal},}}}}" if identity + body = + @server.__send__( + :tmux_command, + [ + names.fetch("capture-pane"), + "-p", + *(joined ? ["-J"] : []), + "-t", + target, + "-S", + (-limits.fetch("history_lines")).to_s, + "-E", + "-" + ] + ) # The selected false branch fails parsing, independently of screen bytes. failure = @server.__send__(:tmux_command, [names.fetch("capture-pane"), "-t"]) - body = @server.__send__(:tmux_command, [names.fetch("if-shell"), "-F", "-t", target, guard, body, failure]) + body = + @server.__send__( + :tmux_command, + [names.fetch("if-shell"), "-F", "-t", target, guard, body, failure] + ) hook_error = "libtmux-hook-refused-#{SecureRandom.hex(16)}" hook_failure = @server.__send__(:tmux_command, [hook_error]) begin # Configuration must stay stable between this preflight and capture. release = LibTmux::Internal::TmuxVersion.parse(snapshot.server_info.fetch(:version)) if self.class.preflight_hooks?(release) - hooks = @server.__send__(:execute_typed, - [names.fetch("show-options"), "-A", "-v", "-t", target, "after-capture-pane"], **@budget.options) + hooks = + @server.__send__( + :execute_typed, + [names.fetch("show-options"), "-A", "-v", "-t", target, "after-capture-pane"], + **@budget.options + ) unless hooks.stdout.empty? - raise UnsupportedFeatureError.new("capture hooks prevent isolated screen output", phase: :read) + raise UnsupportedFeatureError.new( + "capture hooks prevent isolated screen output", + phase: :read + ) end end - result = @server.__send__(:execute_typed, [names.fetch("if-shell"), "-F", "-t", target, - '#{==:#{after-capture-pane},}', body, hook_failure], **@budget.options) + result = + @server.__send__( + :execute_typed, + [ + names.fetch("if-shell"), + "-F", + "-t", + target, + '#{==:#{after-capture-pane},}', + body, + hook_failure + ], + **@budget.options + ) rescue CommandError => error if error.result&.stderr&.include?(hook_error) - raise UnsupportedFeatureError.new("capture hooks prevent isolated screen output", phase: :read, delivery: error.delivery), cause: nil + raise UnsupportedFeatureError.new( + "capture hooks prevent isolated screen output", + phase: :read, + delivery: error.delivery + ), + cause: nil end - raise TargetNotFoundError.new("screen target or process changed", phase: :read, delivery: error.delivery), cause: nil + raise TargetNotFoundError.new( + "screen target or process changed", + phase: :read, + delivery: error.delivery + ), + cause: nil end # capture-pane -p prints a newline even for a blank screen; an empty # successful if-shell response does not prove that capture ran. unless result.stdout.end_with?("\n") - raise TargetNotFoundError.new("screen capture did not return complete rows", phase: :read, delivery: :observed) + raise TargetNotFoundError.new( + "screen capture did not return complete rows", + phase: :read, + delivery: :observed + ) end identity&.ensure_live! @budget.options @@ -456,17 +694,28 @@ def read_rows(snapshot, pane, limits, identity, joined = false) rows = original.last(limits.fetch("max_lines")) bytes = rows.join.b truncated = rows.length != original.length || bytes.bytesize > limits.fetch("max_bytes") - bytes = bytes.byteslice(-limits.fetch("max_bytes"), limits.fetch("max_bytes")) if bytes.bytesize > limits.fetch("max_bytes") + bytes = + bytes.byteslice(-limits.fetch("max_bytes"), limits.fetch("max_bytes")) if bytes.bytesize > + limits.fetch("max_bytes") utf8 = bytes.dup.force_encoding(Encoding::UTF_8) encoding = utf8.valid_encoding? ? "utf-8" : "base64" - rows = (encoding == "utf-8" ? utf8 : bytes).lines.map do |row| - (encoding == "utf-8" ? row : [row].pack("m0")).freeze - end.freeze + rows = + (encoding == "utf-8" ? utf8 : bytes) + .lines + .map { |row| (encoding == "utf-8" ? row : [row].pack("m0")).freeze } + .freeze [rows, encoding, truncated] end def spellings - @spellings ||= @server.__send__(:builtin_spellings, "if-shell", "capture-pane", "show-options", budget: @budget) + @spellings ||= + @server.__send__( + :builtin_spellings, + "if-shell", + "capture-pane", + "show-options", + budget: @budget + ) end def contains?(rows, encoding, text) @@ -475,32 +724,55 @@ def contains?(rows, encoding, text) def state(reference, rows, encoding, truncated, limits, identity, id) bytes = rows.sum { |row| encoding == "utf-8" ? row.bytesize : row.unpack1("m0").bytesize } - {"mode" => "snapshot", "target" => reference, "capture_id" => id, - "process_generation" => identity&.generation, "rows" => rows, "encoding" => encoding, - "row_count" => rows.length, "bytes" => bytes, "truncated" => truncated, - "history_continuity" => "unknown", "scope" => limits, - "interval" => {"clock" => "monotonic_seconds", "started" => @started, "finished" => clock}} + { + "mode" => "snapshot", + "target" => reference, + "capture_id" => id, + "process_generation" => identity&.generation, + "rows" => rows, + "encoding" => encoding, + "row_count" => rows.length, + "bytes" => bytes, + "truncated" => truncated, + "history_continuity" => "unknown", + "scope" => limits, + "interval" => { + "clock" => "monotonic_seconds", + "started" => @started, + "finished" => clock + } + } end def with_cancellation owner = ::Async::Task.current armed = true watcher_error = nil - watcher = ::Async::Task.new(owner) do - Fiber.scheduler.io_wait(@cancel.reader, IO::READABLE) unless @cancel.cancelled? - owner.cancel if armed && @cancel.cancelled? - rescue IOError, SystemCallError - if armed - watcher_error = TransportError.new("cancellation observation failed", phase: :observation) - owner.cancel + watcher = + ::Async::Task.new(owner) do + Fiber.scheduler.io_wait(@cancel.reader, IO::READABLE) unless @cancel.cancelled? + owner.cancel if armed && @cancel.cancelled? + rescue IOError, SystemCallError + if armed + watcher_error = + TransportError.new("cancellation observation failed", phase: :observation) + owner.cancel + end end - end failure = result = nil begin watcher.run result = yield rescue ::Async::Cancel => error - failure = watcher_error || (@cancel.cancelled? ? Cancelled.new("observation cancelled", phase: :read, delivery: :possibly_sent) : error) + failure = + watcher_error || + ( + if @cancel.cancelled? + Cancelled.new("observation cancelled", phase: :read, delivery: :possibly_sent) + else + error + end + ) rescue Exception => error failure = error ensure @@ -508,7 +780,12 @@ def with_cancellation errors = retire([watcher]) unless errors.empty? attach_cleanup(failure, errors) if failure - failure ||= TransportError.new("cancellation observer cleanup failed", phase: :retire, cleanup_errors: errors) + failure ||= + TransportError.new( + "cancellation observer cleanup failed", + phase: :retire, + cleanup_errors: errors + ) end end raise failure if failure @@ -517,7 +794,13 @@ def with_cancellation end def retire(tasks, subscription: nil, control: nil) - group = Retirement.new(owner: self, tasks: tasks.dup, subscription: subscription, control: control) + group = + Retirement.new( + owner: self, + tasks: tasks.dup, + subscription: subscription, + control: control + ) @retirements << group group.close(deadline: clock + cleanup_remaining) [] @@ -576,14 +859,22 @@ def attach_cleanup(failure, errors) failure.__send__(:attach_cleanup_errors, errors) else failure.extend(CleanupDetails) - failure.instance_variable_set(:@mcp_cleanup_errors, ((failure.mcp_cleanup_errors || []) + errors).freeze) + failure.instance_variable_set( + :@mcp_cleanup_errors, + ((failure.mcp_cleanup_errors || []) + errors).freeze + ) end end def freeze_tree(value) case value - when Hash then value.each { |key, item| key.freeze; freeze_tree(item) } - when Array then value.each { |item| freeze_tree(item) } + when Hash + value.each do |key, item| + key.freeze + freeze_tree(item) + end + when Array + value.each { |item| freeze_tree(item) } end value.freeze end diff --git a/gems/libtmux-mcp/lib/libtmux/mcp/process_identity.rb b/gems/libtmux-mcp/lib/libtmux/mcp/process_identity.rb index 6284fbc8..65bae2a6 100644 --- a/gems/libtmux-mcp/lib/libtmux/mcp/process_identity.rb +++ b/gems/libtmux-mcp/lib/libtmux/mcp/process_identity.rb @@ -18,7 +18,10 @@ def self.attach_cleanup(failure, errors) failure.__send__(:attach_cleanup_errors, errors) else failure.extend(CleanupDetails) - failure.instance_variable_set(:@mcp_cleanup_errors, ((failure.mcp_cleanup_errors || []) + errors).freeze) + failure.instance_variable_set( + :@mcp_cleanup_errors, + ((failure.mcp_cleanup_errors || []) + errors).freeze + ) end end @@ -51,7 +54,13 @@ def close @ios.delete(io) if io.closed? end end - raise TransportError.new("native observer cleanup failed", phase: :retire, cleanup_errors: errors) unless errors.empty? + unless errors.empty? + raise TransportError.new( + "native observer cleanup failed", + phase: :retire, + cleanup_errors: errors + ) + end nil end @@ -60,16 +69,29 @@ def close attr_reader :io, :peer, :generation, :pid def self.native(name, arguments, result) - unless /\A(?:(?:x86_64|aarch64)-linux|(?:x86_64|arm64)-darwin)/.match?(RUBY_PLATFORM) && Fiddle::SIZEOF_LONG == 8 - raise UnsupportedFeatureError.new("process cursors require 64-bit Linux or Darwin", phase: :admission) + unless /\A(?:(?:x86_64|aarch64)-linux|(?:x86_64|arm64)-darwin)/.match?(RUBY_PLATFORM) && + Fiddle::SIZEOF_LONG == 8 + raise UnsupportedFeatureError.new( + "process cursors require 64-bit Linux or Darwin", + phase: :admission + ) end Fiddle::Function.new(Fiddle::Handle::DEFAULT[name], arguments, result) rescue Fiddle::DLError - raise UnsupportedFeatureError.new("native process cursor support is unavailable", phase: :admission), cause: nil + raise UnsupportedFeatureError.new( + "native process cursor support is unavailable", + phase: :admission + ), + cause: nil end def self.readable?(io) - poll = native("poll", [Fiddle::TYPE_VOIDP, Fiddle::TYPE_LONG, Fiddle::TYPE_INT], Fiddle::TYPE_INT) + poll = + native( + "poll", + [Fiddle::TYPE_VOIDP, Fiddle::TYPE_LONG, Fiddle::TYPE_INT], + Fiddle::TYPE_INT + ) data = [io.fileno, 1, 0].pack("iss") # Retry one interrupted nonblocking check without consuming readiness. 2.times do @@ -78,11 +100,17 @@ def self.readable?(io) errno = Fiddle.last_error next if errno == Errno::EINTR::Errno - raise TransportError.new("process descriptor poll failed (errno #{errno})", phase: :read) + raise TransportError.new( + "process descriptor poll failed (errno #{errno})", + phase: :read + ) end events = data.unpack("iss").last if (events & 0x28).positive? # POLLERR | POLLNVAL are not process exits. - raise TransportError.new("process descriptor poll returned an invalid event", phase: :read) + raise TransportError.new( + "process descriptor poll returned an invalid event", + phase: :read + ) end return (events & 0x11).positive? # POLLIN | POLLHUP retain terminal readiness. end @@ -97,27 +125,38 @@ def self.procfs_namespace valid = statfs.call(status.fileno, buffer).zero? && buffer.unpack1("l!") == 0x9fa0 rows = status.read(65_537).lines.grep(/^NSpid:/) valid &&= rows.length == 1 && rows.first.split.drop(1) == [Process.pid.to_s] - raise UnsupportedFeatureError.new("process cursors require procfs in the caller PID namespace", phase: :admission) unless valid + unless valid + raise UnsupportedFeatureError.new( + "process cursors require procfs in the caller PID namespace", + phase: :admission + ) + end end File.open("/proc/self/ns/pid") rescue SystemCallError, IOError - raise UnsupportedFeatureError.new("process namespace evidence is unavailable", phase: :admission), cause: nil + raise UnsupportedFeatureError.new( + "process namespace evidence is unavailable", + phase: :admission + ), + cause: nil end def self.acquire(server, server_pid:, pane_pid:, budget:, on_retire: nil) resources = Resources.new failure = identity = nil begin - pane, peer = if RUBY_PLATFORM.include?("darwin") - acquire_darwin(server, server_pid, pane_pid, budget, resources) - else - acquire_linux(server, server_pid, pane_pid, budget, resources) - end + pane, peer = + if RUBY_PLATFORM.include?("darwin") + acquire_darwin(server, server_pid, pane_pid, budget, resources) + else + acquire_linux(server, server_pid, pane_pid, budget, resources) + end identity = new(pane, peer, pane_pid) resources.release(pane, peer) identity.ensure_live! rescue Errno::ENOPROTOOPT, Errno::EINVAL, Errno::EPERM, Errno::EACCES, Errno::ENOENT - failure = UnsupportedFeatureError.new("peer process identity is unavailable", phase: :admission) + failure = + UnsupportedFeatureError.new("peer process identity is unavailable", phase: :admission) rescue Exception => error failure = error ensure @@ -161,12 +200,20 @@ def self.acquire_linux(server, server_pid, pane_pid, budget, resources) peer.close_on_exec = true peer_pid = socket.getsockopt(Socket::SOL_SOCKET, Socket::SO_PEERCRED).data.unpack1("i") unless peer_pid == server_pid && !readable?(peer) - raise UnsupportedFeatureError.new("socket peer identity does not establish the tmux process", phase: :admission) + raise UnsupportedFeatureError.new( + "socket peer identity does not establish the tmux process", + phase: :admission + ) end other_namespace = resources.add(File.open("/proc/#{peer_pid}/ns/pid")) - same_namespace = [own_namespace.stat.dev, own_namespace.stat.ino] == [other_namespace.stat.dev, other_namespace.stat.ino] + same_namespace = + [own_namespace.stat.dev, own_namespace.stat.ino] == + [other_namespace.stat.dev, other_namespace.stat.ino] unless same_namespace && !readable?(peer) - raise UnsupportedFeatureError.new("tmux and observer PID namespaces differ", phase: :admission) + raise UnsupportedFeatureError.new( + "tmux and observer PID namespaces differ", + phase: :admission + ) end opener = native("pidfd_open", [Fiddle::TYPE_INT, Fiddle::TYPE_INT], Fiddle::TYPE_INT) descriptor = opener.call(pane_pid, 0) @@ -177,7 +224,10 @@ def self.acquire_linux(server, server_pid, pane_pid, budget, resources) elsif error == Errno::ESRCH::Errno raise TargetNotFoundError.new("pane process is unavailable", phase: :admission) end - raise UnsupportedFeatureError.new("pane process identity is unavailable", phase: :admission) + raise UnsupportedFeatureError.new( + "pane process identity is unavailable", + phase: :admission + ) end pane = resources.add(IO.for_fd(descriptor)) @@ -194,9 +244,17 @@ def self.acquire_darwin(server, server_pid, pane_pid, budget, resources) # Registration may find a recycled PID. A fresh pinned-route reply must # name that same daemon while its retained process observer stays live. argv, marker = LibTmux::Internal::TmuxVersion.identity_argv(%w[pid]) - reported = LibTmux::Internal::TmuxVersion.parse_identity(server.run(argv, **budget.options), marker, 1).first + reported = + LibTmux::Internal::TmuxVersion.parse_identity( + server.run(argv, **budget.options), + marker, + 1 + ).first unless reported == server_pid.to_s && !readable?(peer) - raise UnsupportedFeatureError.new("bound response does not establish the tmux process", phase: :admission) + raise UnsupportedFeatureError.new( + "bound response does not establish the tmux process", + phase: :admission + ) end budget.options pane = process_events(pane_pid, resources) @@ -206,11 +264,24 @@ def self.acquire_darwin(server, server_pid, pane_pid, budget, resources) def self.process_events(pid, resources) create = native("kqueue", [], Fiddle::TYPE_INT) - register = native("kevent", [Fiddle::TYPE_INT, Fiddle::TYPE_VOIDP, Fiddle::TYPE_INT, - Fiddle::TYPE_VOIDP, Fiddle::TYPE_INT, Fiddle::TYPE_VOIDP], Fiddle::TYPE_INT) + register = + native( + "kevent", + [ + Fiddle::TYPE_INT, + Fiddle::TYPE_VOIDP, + Fiddle::TYPE_INT, + Fiddle::TYPE_VOIDP, + Fiddle::TYPE_INT, + Fiddle::TYPE_VOIDP + ], + Fiddle::TYPE_INT + ) descriptor = create.call if descriptor.negative? - if [Errno::EMFILE::Errno, Errno::ENFILE::Errno, Errno::ENOMEM::Errno].include?(Fiddle.last_error) + if [Errno::EMFILE::Errno, Errno::ENFILE::Errno, Errno::ENOMEM::Errno].include?( + Fiddle.last_error + ) raise CapacityError.new("process observer capacity exhausted", phase: :admission) end raise UnsupportedFeatureError.new("process observation is unavailable", phase: :admission) @@ -253,7 +324,11 @@ def close def peer_alive! if @references.zero? || self.class.readable?(@peer) - raise TargetNotFoundError.new("retained tmux process is unavailable", phase: :read, delivery: :observed) + raise TargetNotFoundError.new( + "retained tmux process is unavailable", + phase: :read, + delivery: :observed + ) end end @@ -263,7 +338,13 @@ def exited? end def ensure_live! - raise TargetNotFoundError.new("retained pane process exited", phase: :read, delivery: :observed) if exited? + if exited? + raise TargetNotFoundError.new( + "retained pane process exited", + phase: :read, + delivery: :observed + ) + end end end private_constant :ProcessIdentity diff --git a/gems/libtmux-mcp/lib/libtmux/mcp/resources.rb b/gems/libtmux-mcp/lib/libtmux/mcp/resources.rb index 40c0d515..38a7f970 100644 --- a/gems/libtmux-mcp/lib/libtmux/mcp/resources.rb +++ b/gems/libtmux-mcp/lib/libtmux/mcp/resources.rb @@ -4,25 +4,44 @@ module LibTmux module MCP class Resources def initialize(application:, endpoint_name:, enabled_tools:, max_response_bytes:) - @application, @endpoint, @enabled, @max_bytes = application, endpoint_name, enabled_tools, max_response_bytes + @application, @endpoint, @enabled, @max_bytes = + application, + endpoint_name, + enabled_tools, + max_response_bytes end def install(server) - server.capabilities[:resources] = {subscribe: false, listChanged: false} + server.capabilities[:resources] = { subscribe: false, listChanged: false } if @enabled.include?("tmux_snapshot") prefix = "tmux://{endpoint}/{generation}/snapshots/{entity}" - server.resource_templates.concat([ - ::MCP::ResourceTemplate.new(uri_template: prefix, name: "tmux_metadata", mime_type: "application/json", - description: "Acquire metadata through tmux_snapshot with its default page limit. Encode every URI component; generation must match discovery. Reports capture interval and truncation."), - ::MCP::ResourceTemplate.new(uri_template: "#{prefix}/pages/{cursor}", name: "tmux_metadata_page", mime_type: "application/json", - description: "Read a retained tmux_snapshot page without refreshing it. Encode the cursor component; endpoint, generation and entity must match its captured query.") - ]) + server.resource_templates.concat( + [ + ::MCP::ResourceTemplate.new( + uri_template: prefix, + name: "tmux_metadata", + mime_type: "application/json", + description: + "Acquire metadata through tmux_snapshot with its default page limit. Encode every URI component; generation must match discovery. Reports capture interval and truncation." + ), + ::MCP::ResourceTemplate.new( + uri_template: "#{prefix}/pages/{cursor}", + name: "tmux_metadata_page", + mime_type: "application/json", + description: + "Read a retained tmux_snapshot page without refreshing it. Encode the cursor component; endpoint, generation and entity must match its captured query." + ) + ] + ) end if @enabled.include?("tmux_capture") server.resource_templates << ::MCP::ResourceTemplate.new( uri_template: "tmux://{endpoint}/{generation}/panes/{pane_id}/screen", - name: "tmux_screen", mime_type: "text/plain", - description: "Capture an exact pane through tmux_capture with its default byte/line bounds, without cursor tracking. Percent-encode pane IDs. Invalid UTF-8 is an application/octet-stream blob; _meta includes capture interval, truncation and unknown history continuity.") + name: "tmux_screen", + mime_type: "text/plain", + description: + "Capture an exact pane through tmux_capture with its default byte/line bounds, without cursor tracking. Percent-encode pane IDs. Invalid UTF-8 is an application/octet-stream blob; _meta includes capture interval, truncation and unknown history continuity." + ) end server.resources_read_handler do |params, server_context: nil| read(params[:uri], cancellation: server_context&.cancellation) @@ -35,10 +54,17 @@ def install(server) def decode(component) return unless component && component.match?(/\A(?:[A-Za-z0-9._~-]|%[0-9A-F]{2})+\z/) - value = component.gsub(/%([0-9A-F]{2})/) { [$1.to_i(16)].pack("C") }.force_encoding(Encoding::UTF_8) + value = + component + .gsub(/%([0-9A-F]{2})/) { [$1.to_i(16)].pack("C") } + .force_encoding(Encoding::UTF_8) return unless value.valid_encoding? - encoded = value.bytes.map { |byte| (byte.chr.match?(/[A-Za-z0-9._~-]/) ? byte.chr : "%%%02X" % byte) }.join + encoded = + value + .bytes + .map { |byte| (byte.chr.match?(/[A-Za-z0-9._~-]/) ? byte.chr : "%%%02X" % byte) } + .join value if encoded == component end @@ -46,20 +72,31 @@ def read(uri, cancellation:) unless uri.is_a?(String) && uri.valid_encoding? && uri.bytesize <= 1024 error("invalid_input", "The resource URI is invalid.", protocol: true) end - match = /\Atmux:\/\/([^\/]+)\/([^\/]+)\/(snapshots|panes)\/([^\/]+)(?:\/(pages|screen)(?:\/([^\/]+))?)?\z/.match(uri) + match = + %r{\Atmux://([^/]+)/([^/]+)/(snapshots|panes)/([^/]+)(?:/(pages|screen)(?:/([^/]+))?)?\z}.match( + uri + ) error("invalid_input", "The resource URI is invalid.", protocol: true) unless match - endpoint, generation, collection, target, suffix, cursor = match.captures.map { |part| part && decode(part) } + endpoint, generation, collection, target, suffix, cursor = + match.captures.map { |part| part && decode(part) } unless endpoint == @endpoint && generation && generation.bytesize <= 128 && - (!match[6] || cursor) + (!match[6] || cursor) error("invalid_input", "The resource URI is invalid.", protocol: true) end if collection == "snapshots" && Internal::Catalog.kinds.map(&:to_s).include?(target) && - (suffix.nil? || (suffix == "pages" && cursor)) + (suffix.nil? || (suffix == "pages" && cursor)) name = "tmux_snapshot" - arguments = cursor ? {"cursor" => cursor} : {"entity" => target} - elsif collection == "panes" && target&.match?(/\A%[0-9]+\z/) && suffix == "screen" && cursor.nil? + arguments = cursor ? { "cursor" => cursor } : { "entity" => target } + elsif collection == "panes" && target&.match?(/\A%[0-9]+\z/) && suffix == "screen" && + cursor.nil? name = "tmux_capture" - arguments = {"target" => {"generation" => generation, "kind" => "pane", "id" => target}} + arguments = { + "target" => { + "generation" => generation, + "kind" => "pane", + "id" => target + } + } else error("invalid_input", "The resource URI is invalid.", protocol: true) end @@ -70,13 +107,18 @@ def read(uri, cancellation:) end data = response.fetch("data") if name == "tmux_snapshot" - unless data.fetch("server_identity").fetch("generation") == generation && data.fetch("entity") == target - error("stale_target", "The resource generation or captured entity does not match.", delivery: "observed") + unless data.fetch("server_identity").fetch("generation") == generation && + data.fetch("entity") == target + error( + "stale_target", + "The resource generation or captured entity does not match.", + delivery: "observed" + ) end - contents = [{uri: uri, mimeType: "application/json", text: JSON.generate(response)}] + contents = [{ uri: uri, mimeType: "application/json", text: JSON.generate(response) }] else metadata = data.reject { |key, _| key == "rows" } - contents = [{uri: uri, _meta: {"io.github.libtmux/capture" => metadata}}] + contents = [{ uri: uri, _meta: { "io.github.libtmux/capture" => metadata } }] if data.fetch("encoding") == "utf-8" contents.first.merge!(mimeType: "text/plain", text: data.fetch("rows").join) else @@ -91,9 +133,13 @@ def read(uri, cancellation:) end def error(code, message, protocol: false, details: nil, delivery: "not_sent") - raise ::MCP::Server::RequestHandlerError.new(message, nil, - error_code: protocol ? -32602 : -32000, - error_data: details || {"code" => code, "message" => message, "delivery" => delivery}) + raise ::MCP::Server::RequestHandlerError.new( + message, + nil, + error_code: protocol ? -32_602 : -32_000, + error_data: + details || { "code" => code, "message" => message, "delivery" => delivery } + ) end end private_constant :Resources diff --git a/gems/libtmux-mcp/lib/libtmux/mcp/shell/prepare.rb b/gems/libtmux-mcp/lib/libtmux/mcp/shell/prepare.rb index f0ced167..2331885e 100644 --- a/gems/libtmux-mcp/lib/libtmux/mcp/shell/prepare.rb +++ b/gems/libtmux-mcp/lib/libtmux/mcp/shell/prepare.rb @@ -1,25 +1,25 @@ # frozen_string_literal: true -require 'socket' -require 'digest/sha2' -require 'libtmux/process' +require "socket" +require "digest/sha2" +require "libtmux/process" # This process is launched with explicit installed load paths and disabled gems. class AuthoredShellHelper def initialize(socket, deadline) - @socket, @deadline, @buffer = socket, deadline, +''.b + @socket, @deadline, @buffer = socket, deadline, +"".b end def remaining value = @deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC) - raise LibTmux::DeadlineExceeded.new('helper deadline expired') unless value.positive? + raise LibTmux::DeadlineExceeded.new("helper deadline expired") unless value.positive? value end def read_line until (ending = @buffer.index("\n")) - raise LibTmux::ProtocolError.new('helper frame is too large') if @buffer.bytesize >= 1024 + raise LibTmux::ProtocolError.new("helper frame is too large") if @buffer.bytesize >= 1024 read_more(1024 - @buffer.bytesize) end @@ -61,65 +61,94 @@ def read_more(limit) begin path, token, deadline_text, run_id, digest, readiness = ARGV - path = path.unpack1('m0') - raise ArgumentError unless ARGV.length == 6 && /\A[0-9a-f]{32}\z/.match?(token) && - /\A[0-9a-f]{32}\z/.match?(run_id) && /\A[0-9a-f]{64}\z/.match?(digest) + path = path.unpack1("m0") + unless ARGV.length == 6 && /\A[0-9a-f]{32}\z/.match?(token) && + /\A[0-9a-f]{32}\z/.match?(run_id) && /\A[0-9a-f]{64}\z/.match?(digest) + raise ArgumentError + end deadline = Float(deadline_text) raise ArgumentError unless deadline.finite? socket = UNIXSocket.new(path) wire = AuthoredShellHelper.new(socket, deadline) - prefix = readiness == 'ready' ? 'READY' : 'REFUSED' + prefix = readiness == "ready" ? "READY" : "REFUSED" wire.write("#{prefix} #{run_id} #{token} #{digest} #{Process.ppid}\n") - exit 72 unless readiness == 'ready' - raise LibTmux::ProtocolError.new('invalid helper grant') unless wire.read_line == "GRANT #{run_id} #{token} #{digest}" + exit 72 unless readiness == "ready" + unless wire.read_line == "GRANT #{run_id} #{token} #{digest}" + raise LibTmux::ProtocolError.new("invalid helper grant") + end wire.write("AUTHORIZED #{run_id} #{token} #{digest}\n") - fields = wire.read_line.split(' ') - unless fields.length == 7 && fields[0, 4] == ['SCRIPT', run_id, token, digest] && fields[4, 3].all? { |value| /\A\d{1,6}\z/.match?(value) } - raise LibTmux::ProtocolError.new('invalid helper script envelope') + fields = wire.read_line.split(" ") + unless fields.length == 7 && fields[0, 4] == ["SCRIPT", run_id, token, digest] && + fields[4, 3].all? { |value| /\A\d{1,6}\z/.match?(value) } + raise LibTmux::ProtocolError.new("invalid helper script envelope") end length, stdout_limit, stderr_limit = fields[4, 3].map(&:to_i) unless length <= 65_536 && stdout_limit <= 262_144 && stderr_limit <= 262_144 - raise LibTmux::ProtocolError.new('invalid helper script limits') + raise LibTmux::ProtocolError.new("invalid helper script limits") end script = wire.read_bytes(length) unless !script.include?("\0") && Digest::SHA256.hexdigest(script) == digest - raise LibTmux::ProtocolError.new('helper script digest mismatch') + raise LibTmux::ProtocolError.new("helper script digest mismatch") end cancellation = LibTmux::Internal::Cancellation.new wake_reader, wake_writer = IO.pipe - watcher = Thread.new do - ready = IO.select([socket, wake_reader]) - if ready.first.include?(socket) - # EOF or unsolicited client bytes revoke this helper's outstanding work. - socket.read_nonblock(1, exception: false) - cancellation.cancel + watcher = + Thread.new do + ready = IO.select([socket, wake_reader]) + if ready.first.include?(socket) + # EOF or unsolicited client bytes revoke this helper's outstanding work. + socket.read_nonblock(1, exception: false) + cancellation.cancel + end end - end - environment = %w[TMUX TMUX_PANE].filter_map { |name| "#{name}=#{ENV.fetch(name)}" if ENV.key?(name) } - result = LibTmux::Internal::ProcessExecutor.new(stdout_limit: stdout_limit, stderr_limit: stderr_limit, - cleanup_timeout: 0.25, drain_timeout: 0.25).run(['/usr/bin/env', *environment, '/bin/sh', '-c', script], - timeout: wire.remaining, cancel: cancellation) - wake_writer.write_nonblock('x', exception: false) + environment = + %w[TMUX TMUX_PANE].filter_map { |name| "#{name}=#{ENV.fetch(name)}" if ENV.key?(name) } + result = + LibTmux::Internal::ProcessExecutor.new( + stdout_limit: stdout_limit, + stderr_limit: stderr_limit, + cleanup_timeout: 0.25, + drain_timeout: 0.25 + ).run( + ["/usr/bin/env", *environment, "/bin/sh", "-c", script], + timeout: wire.remaining, + cancel: cancellation + ) + wake_writer.write_nonblock("x", exception: false) unless watcher.join(0.25) - raise LibTmux::TransportError.new('helper cancellation watcher remains active', cleanup_errors: ['watcher retirement remains pending']) + raise LibTmux::TransportError.new( + "helper cancellation watcher remains active", + cleanup_errors: ["watcher retirement remains pending"] + ) end watcher = nil - kind, status = result.status.exited? ? ['EXIT', result.status.exitstatus] : ['SIGNAL', result.status.termsig] - wire.write("RESULT #{run_id} #{token} #{digest} #{kind} #{status} #{result.stdout.bytesize} #{result.stderr.bytesize}\n") + kind, status = + result.status.exited? ? ["EXIT", result.status.exitstatus] : ["SIGNAL", result.status.termsig] + wire.write( + "RESULT #{run_id} #{token} #{digest} #{kind} #{status} #{result.stdout.bytesize} #{result.stderr.bytesize}\n" + ) wire.write(result.stdout) wire.write(result.stderr) rescue LibTmux::Error => error - code = case error - when LibTmux::CapacityError then 'capacity' - when LibTmux::DeadlineExceeded then 'deadline' - when LibTmux::Cancelled then 'cancelled' - when LibTmux::ProtocolError then 'protocol' - else 'unknown' - end + code = + case error + when LibTmux::CapacityError + "capacity" + when LibTmux::DeadlineExceeded + "deadline" + when LibTmux::Cancelled + "cancelled" + when LibTmux::ProtocolError + "protocol" + else + "unknown" + end begin - wire&.write("ERROR #{run_id} #{token} #{digest} #{code} #{error.cleanup_errors.empty? ? 'clean' : 'pending'}\n") + wire&.write( + "ERROR #{run_id} #{token} #{digest} #{code} #{error.cleanup_errors.empty? ? "clean" : "pending"}\n" + ) rescue StandardError # The client observes unknown completion when the bounded channel is gone. end @@ -128,7 +157,7 @@ def read_more(limit) exit 77 ensure if watcher - wake_writer.write_nonblock('x', exception: false) + wake_writer.write_nonblock("x", exception: false) retired = watcher.join(0.25) end [wake_reader, wake_writer, socket].compact.each { |io| io.close unless io.closed? } diff --git a/gems/libtmux-mcp/lib/libtmux/mcp/stdio_transport.rb b/gems/libtmux-mcp/lib/libtmux/mcp/stdio_transport.rb index d3fa7d16..762f4086 100644 --- a/gems/libtmux-mcp/lib/libtmux/mcp/stdio_transport.rb +++ b/gems/libtmux-mcp/lib/libtmux/mcp/stdio_transport.rb @@ -11,7 +11,18 @@ module MCP class StdioTransport < ::MCP::Transport RequestExpired = Class.new(Exception) WriteExpired = Class.new(Exception) - Ticket = Struct.new(:request, :bytes, :deadline, :task, :active, :cancellation, :callback, :state, keyword_init: true) + Ticket = + Struct.new( + :request, + :bytes, + :deadline, + :task, + :active, + :cancellation, + :callback, + :state, + keyword_init: true + ) Frame = Struct.new(:bytes, :state, keyword_init: true) module CleanupDetails attr_reader :mcp_cleanup_errors @@ -50,27 +61,52 @@ def lookup_in_flight(id) end private_constant :Session, :ModernSession - def initialize(server:, parent:, input:, output:, concurrency: 4, max_requests: 32, - max_frame_bytes: 1 << 20, max_request_bytes: 1 << 22, max_output_bytes: 1 << 22, - request_timeout: 30, write_timeout: 0.5, cleanup_timeout: 0.5) - unless parent.is_a?(::Async::Task) && !parent.finished? && parent.root.equal?(Fiber.scheduler) + def initialize( + server:, + parent:, + input:, + output:, + concurrency: 4, + max_requests: 32, + max_frame_bytes: 1 << 20, + max_request_bytes: 1 << 22, + max_output_bytes: 1 << 22, + request_timeout: 30, + write_timeout: 0.5, + cleanup_timeout: 0.5 + ) + unless parent.is_a?(::Async::Task) && !parent.finished? && + parent.root.equal?(Fiber.scheduler) raise ArgumentError, "parent must be a live task on the current Async scheduler" end raise ArgumentError, "server must be an MCP SDK Server" unless server.is_a?(::MCP::Server) unless [input, output].all? { |io| io.is_a?(IO) && !io.closed? } raise ArgumentError, "input and output must be open IO streams" end - [concurrency, max_requests, max_frame_bytes, max_request_bytes, max_output_bytes].each do |value| - raise ArgumentError, "transport limits must be positive Integers" unless value.is_a?(Integer) && value.positive? + [ + concurrency, + max_requests, + max_frame_bytes, + max_request_bytes, + max_output_bytes + ].each do |value| + unless value.is_a?(Integer) && value.positive? + raise ArgumentError, "transport limits must be positive Integers" + end end [request_timeout, write_timeout, cleanup_timeout].each do |value| - raise ArgumentError, "transport deadlines must be positive and finite" unless value.is_a?(Numeric) && value.finite? && value.positive? + unless value.is_a?(Numeric) && value.finite? && value.positive? + raise ArgumentError, "transport deadlines must be positive and finite" + end end @parent, @input, @output = parent, input, output @thread, @pid, @scheduler = Thread.current, Process.pid, Fiber.scheduler @concurrency, @max_requests = concurrency, max_requests @max_frame, @max_request, @max_output = max_frame_bytes, max_request_bytes, max_output_bytes - @request_timeout, @write_timeout, @cleanup_timeout = request_timeout, write_timeout, cleanup_timeout + @request_timeout, @write_timeout, @cleanup_timeout = + request_timeout, + write_timeout, + cleanup_timeout @tickets, @waiting, @by_id, @by_task, @frames = [], [], {}, {}, [] @active = @request_bytes = @output_bytes = 0 @changed, @writable = ::Async::Notification.new, ::Async::Notification.new @@ -81,7 +117,9 @@ def initialize(server:, parent:, input:, output:, concurrency: 4, max_requests: def run ensure_owner - raise ClosedError.new("transport cannot be restarted", phase: :admission) if @runner || @closed + if @runner || @closed + raise ClosedError.new("transport cannot be restarted", phase: :admission) + end @runner = ::Async::Task.current begin @@ -127,7 +165,9 @@ def closed? def send_response(message) ensure_owner - raise ClosedError.new("transport output is closed", phase: :write) if @closed || @writer_done + if @closed || @writer_done + raise ClosedError.new("transport output is closed", phase: :write) + end ticket = @by_task[::Async::Task.current?] raise RequestExpired if ticket && !ticket.state[:expired] && clock >= ticket.deadline @@ -136,7 +176,11 @@ def send_response(message) raise RequestExpired if ticket && !ticket.state[:expired] && clock >= ticket.deadline if @output_bytes + bytes.bytesize > @max_output || @frames.length >= @max_requests * 4 - raise CapacityError.new("MCP output queue limit reached", phase: :write, delivery: :possibly_sent) + raise CapacityError.new( + "MCP output queue limit reached", + phase: :write, + delivery: :possibly_sent + ) end state = ticket&.state return nil if state && state[:cancelled] @@ -153,12 +197,15 @@ def send_response(message) def send_notification(method, params = nil, related_request_id: nil, **) return false if related_request_id && @by_id[related_request_id]&.state&.fetch(:cancelled) - send_response({jsonrpc: "2.0", method: method, params: params}.compact) + send_response({ jsonrpc: "2.0", method: method, params: params }.compact) true end def send_request(*) - raise UnsupportedFeatureError.new("server-initiated MCP requests are not supported by this transport", phase: :admission) + raise UnsupportedFeatureError.new( + "server-initiated MCP requests are not supported by this transport", + phase: :admission + ) end private @@ -168,21 +215,26 @@ def clock end def ensure_owner - unless Process.pid == @pid && Thread.current.equal?(@thread) && Fiber.scheduler.equal?(@scheduler) - raise ClosedError.new("MCP transport belongs to another scheduler, thread or process", phase: :admission) + unless Process.pid == @pid && Thread.current.equal?(@thread) && + Fiber.scheduler.equal?(@scheduler) + raise ClosedError.new( + "MCP transport belongs to another scheduler, thread or process", + phase: :admission + ) end end def child_task(&block) - task = ::Async::Task.new(@parent) do - block.call - rescue ::Async::Cancel - nil - rescue Exception => error - fail_transport(error) - ensure - @changed.signal - end + task = + ::Async::Task.new(@parent) do + block.call + rescue ::Async::Cancel + nil + rescue Exception => error + fail_transport(error) + ensure + @changed.signal + end task end @@ -197,7 +249,8 @@ def read_loop loop do break if @stopping - chunk = @input.read_nonblock([16_384, @max_frame + 1 - buffer.bytesize].min, exception: false) + chunk = + @input.read_nonblock([16_384, @max_frame + 1 - buffer.bytesize].min, exception: false) if chunk == :wait_readable @scheduler.io_wait(@input, IO::READABLE) next @@ -207,12 +260,16 @@ def read_loop buffer << chunk.b while (ending = buffer.index("\n")) frame = buffer.slice!(0, ending + 1) - raise CapacityError.new("MCP input frame limit reached", phase: :read) if frame.bytesize > @max_frame + if frame.bytesize > @max_frame + raise CapacityError.new("MCP input frame limit reached", phase: :read) + end receive(frame) break if @stopping end - raise CapacityError.new("MCP input frame limit reached", phase: :read) if buffer.bytesize >= @max_frame + if buffer.bytesize >= @max_frame + raise CapacityError.new("MCP input frame limit reached", phase: :read) + end ::Async::Task.current.yield end receive(buffer) unless buffer.empty? || @stopping @@ -229,7 +286,8 @@ def receive(frame) send_response(@session.handle(nil)) return end - if parsed[:jsonrpc] == "2.0" && !parsed.key?(:id) && parsed[:method] == ::MCP::Methods::NOTIFICATIONS_CANCELLED + if parsed[:jsonrpc] == "2.0" && !parsed.key?(:id) && + parsed[:method] == ::MCP::Methods::NOTIFICATIONS_CANCELLED @session.handle(parsed) id = parsed[:params][:requestId] if parsed[:params].is_a?(Hash) ticket = @by_id[id] @@ -238,14 +296,22 @@ def receive(frame) end id = parsed[:id] if id && @by_id.key?(id) - send_response(error_response(id, -32600, "Request ID is already in flight")) + send_response(error_response(id, -32_600, "Request ID is already in flight")) return end if @tickets.length >= @max_requests || @request_bytes + frame.bytesize > @max_request - send_response(error_response(id, -32000, "MCP request capacity reached")) if id + send_response(error_response(id, -32_000, "MCP request capacity reached")) if id return end - ticket = Ticket.new(request: parsed, bytes: frame.bytesize, deadline: clock + @request_timeout, state: {cancelled: false}) + ticket = + Ticket.new( + request: parsed, + bytes: frame.bytesize, + deadline: clock + @request_timeout, + state: { + cancelled: false + } + ) ticket.task = ::Async::Task.new(@parent) { dispatch(ticket) } @tickets << ticket @waiting << ticket @@ -275,7 +341,10 @@ def dispatch(ticket) response = request_session(ticket.request).handle(ticket.request) raise RequestExpired if clock >= ticket.deadline if !@session.era && response.is_a?(Hash) && !response.key?(:error) && - (ticket.request[:method] == ::MCP::Methods::SERVER_DISCOVER || ::MCP::RequestEnvelope.modern?(ticket.request[:params])) + ( + ticket.request[:method] == ::MCP::Methods::SERVER_DISCOVER || + ::MCP::RequestEnvelope.modern?(ticket.request[:params]) + ) @session.lock_era!(:modern) end send_response(response) if response && !ticket.state[:cancelled] @@ -283,7 +352,9 @@ def dispatch(ticket) rescue RequestExpired ticket.state[:expired] = true if ticket.request[:id] && !ticket.state[:cancelled] && !@stopping - send_response(error_response(ticket.request[:id], -32000, "MCP request deadline elapsed")) + send_response( + error_response(ticket.request[:id], -32_000, "MCP request deadline elapsed") + ) end rescue ::Async::Cancel nil @@ -306,8 +377,14 @@ def release_ticket(ticket) end def request_session(request) - if @session.era == :modern || request[:method] == ::MCP::Methods::SERVER_DISCOVER || ::MCP::RequestEnvelope.modern?(request[:params]) - ModernSession.new(server: @server, transport: self, connection: @session, era: @session.era) + if @session.era == :modern || request[:method] == ::MCP::Methods::SERVER_DISCOVER || + ::MCP::RequestEnvelope.modern?(request[:params]) + ModernSession.new( + server: @server, + transport: self, + connection: @session, + era: @session.era + ) else @session end @@ -326,18 +403,28 @@ def stop_ticket(ticket, retry_cancel: false) return if was_cancelled && !retry_cancel ticket.state[:cancelled] = true - ticket.cancellation.cancel(reason: "Request stopped") if !was_cancelled && ticket.cancellation && !ticket.cancellation.cancelled? + if !was_cancelled && ticket.cancellation && !ticket.cancellation.cancelled? + ticket.cancellation.cancel(reason: "Request stopped") + end ticket.task.cancel if ticket.task && !ticket.task.finished? end def error_response(id, code, message) - JsonRpcHandler.error_response(id: id, id_validation_pattern: JsonRpcHandler::DEFAULT_ALLOWED_ID_CHARACTERS, - error: {code: code, message: message}) + JsonRpcHandler.error_response( + id: id, + id_validation_pattern: JsonRpcHandler::DEFAULT_ALLOWED_ID_CHARACTERS, + error: { + code: code, + message: message + } + ) end def encode(message) if message.is_a?(String) - raise CapacityError.new("MCP output frame limit reached", phase: :write) if message.bytesize >= @max_output + if message.bytesize >= @max_output + raise CapacityError.new("MCP output frame limit reached", phase: :write) + end message = JSON.parse(message, max_nesting: 32) end @@ -353,52 +440,70 @@ def encode(message) def measure(message) bytes, nodes = 1, 0 # Include the framing newline before allocating JSON. - spend = lambda do |amount| - bytes += amount - raise CapacityError.new("MCP output frame limit reached", phase: :write) if bytes > @max_output - end - string = lambda do |value| - unless value.valid_encoding? && (value.encoding == Encoding::UTF_8 || value.ascii_only?) - raise ProtocolError.new("MCP response text must be UTF-8", phase: :write) - end - spend.call(2) - value.each_byte do |byte| - spend.call(case byte - when 34, 92, 8, 9, 10, 12, 13 then 2 - when 0...32 then 6 - else 1 - end) + spend = + lambda do |amount| + bytes += amount + if bytes > @max_output + raise CapacityError.new("MCP output frame limit reached", phase: :write) + end end - end - visit = lambda do |value, depth| - nodes += 1 - if depth > 32 || nodes > 65_536 - raise CapacityError.new("MCP response structure limit reached", phase: :write) + string = + lambda do |value| + unless value.valid_encoding? && (value.encoding == Encoding::UTF_8 || value.ascii_only?) + raise ProtocolError.new("MCP response text must be UTF-8", phase: :write) + end + spend.call(2) + value.each_byte do |byte| + spend.call( + case byte + when 34, 92, 8, 9, 10, 12, 13 + 2 + when 0...32 + 6 + else + 1 + end + ) + end end - case value - when String then string.call(value) - when Symbol then string.call(value.to_s) - when Integer then spend.call([1, value.bit_length].max + (value.negative? ? 1 : 0)) - when nil, true then spend.call(4) - when false then spend.call(5) - when Float - raise ProtocolError.new("MCP response numbers must be finite", phase: :write) unless value.finite? - spend.call(32) - when Array - spend.call(2 + [0, value.length - 1].max) - value.each { |item| visit.call(item, depth + 1) } - when Hash - spend.call(2 + [0, value.length - 1].max + value.length) - value.each do |key, item| - unless key.is_a?(String) || key.is_a?(Symbol) - raise ProtocolError.new("MCP response keys must be text", phase: :write) + visit = + lambda do |value, depth| + nodes += 1 + if depth > 32 || nodes > 65_536 + raise CapacityError.new("MCP response structure limit reached", phase: :write) + end + case value + when String + string.call(value) + when Symbol + string.call(value.to_s) + when Integer + spend.call([1, value.bit_length].max + (value.negative? ? 1 : 0)) + when nil, true + spend.call(4) + when false + spend.call(5) + when Float + unless value.finite? + raise ProtocolError.new("MCP response numbers must be finite", phase: :write) end - visit.call(key, depth + 1) - visit.call(item, depth + 1) + spend.call(32) + when Array + spend.call(2 + [0, value.length - 1].max) + value.each { |item| visit.call(item, depth + 1) } + when Hash + spend.call(2 + [0, value.length - 1].max + value.length) + value.each do |key, item| + unless key.is_a?(String) || key.is_a?(Symbol) + raise ProtocolError.new("MCP response keys must be text", phase: :write) + end + visit.call(key, depth + 1) + visit.call(item, depth + 1) + end + else + raise ProtocolError.new("MCP response contains unsupported data", phase: :write) end - else raise ProtocolError.new("MCP response contains unsupported data", phase: :write) end - end visit.call(message, 0) end @@ -414,27 +519,39 @@ def write_loop next if frame.state && frame.state[:cancelled] deadline = clock + @write_timeout - ::Async::Task.current.with_timeout(@write_timeout, WriteExpired) do - offset = 0 - while offset < frame.bytes.bytesize - raise WriteExpired if clock >= deadline - - written = @output.write_nonblock(frame.bytes.byteslice(offset, 16_384), exception: false) - if written == :wait_writable - @scheduler.io_wait(@output, IO::WRITABLE) - else - offset += written + ::Async::Task + .current + .with_timeout(@write_timeout, WriteExpired) do + offset = 0 + while offset < frame.bytes.bytesize + raise WriteExpired if clock >= deadline + + written = + @output.write_nonblock(frame.bytes.byteslice(offset, 16_384), exception: false) + if written == :wait_writable + @scheduler.io_wait(@output, IO::WRITABLE) + else + offset += written + end end end - end ensure @output_bytes -= frame.bytes.bytesize end end rescue WriteExpired - raise DeadlineExceeded.new("MCP output consumer exceeded its deadline", phase: :write, delivery: :possibly_sent) + raise DeadlineExceeded.new( + "MCP output consumer exceeded its deadline", + phase: :write, + delivery: :possibly_sent + ) rescue IOError, SystemCallError => error - raise TransportError.new("MCP output failed (#{error.class})", phase: :write, delivery: :possibly_sent), cause: nil + raise TransportError.new( + "MCP output failed (#{error.class})", + phase: :write, + delivery: :possibly_sent + ), + cause: nil end def retire @@ -442,7 +559,9 @@ def retire errors = [] @stopping = true cleanup_action(deadline, errors) { @reader.cancel if @reader && !@reader.finished? } - @tickets.dup.each { |ticket| cleanup_action(deadline, errors) { stop_ticket(ticket, retry_cancel: true) } } + @tickets.dup.each do |ticket| + cleanup_action(deadline, errors) { stop_ticket(ticket, retry_cancel: true) } + end @tickets.dup.each do |ticket| join_owned(ticket.task, deadline, errors) release_ticket(ticket) if ticket.task.finished? @@ -470,7 +589,10 @@ def attach_cleanup(error, details) error.__send__(:attach_cleanup_errors, details) else error.extend(CleanupDetails) - error.instance_variable_set(:@mcp_cleanup_errors, ((error.mcp_cleanup_errors || []) + details).freeze) + error.instance_variable_set( + :@mcp_cleanup_errors, + ((error.mcp_cleanup_errors || []) + details).freeze + ) end rescue FrozenError, TypeError nil @@ -492,7 +614,9 @@ def join_owned(task, deadline, errors) cleanup_action(deadline, errors) { task.wait(timeout: [deadline - clock, 0].max) } unless task.finished? cleanup_action(deadline, errors) { task.cancel unless task.finished? } - cleanup_action(deadline, errors) { task.wait(timeout: [deadline - clock, 0].max) unless task.finished? } + cleanup_action(deadline, errors) do + task.wait(timeout: [deadline - clock, 0].max) unless task.finished? + end end end diff --git a/gems/libtmux-mcp/libtmux-mcp.gemspec b/gems/libtmux-mcp/libtmux-mcp.gemspec index 3e1499be..3ecf3af9 100644 --- a/gems/libtmux-mcp/libtmux-mcp.gemspec +++ b/gems/libtmux-mcp/libtmux-mcp.gemspec @@ -7,7 +7,8 @@ Gem::Specification.new do |spec| spec.version = LibTmux::MCP::VERSION spec.authors = ["libtmux contributors"] spec.summary = "MCP consumer package for libtmux" - spec.description = "Expose tmux snapshots, captures and explicitly enabled mutations through an MCP stdio server." + spec.description = + "Expose tmux snapshots, captures and explicitly enabled mutations through an MCP stdio server." spec.homepage = "https://github.com/libtmux/libtmux-ruby" spec.license = "MIT" spec.required_ruby_version = ">= 3.3" @@ -20,8 +21,11 @@ Gem::Specification.new do |spec| spec.bindir = "exe" spec.executables = ["libtmux-mcp"] spec.files = %w[ - LICENSE README.md CHANGELOG.md - assets/logo.svg assets/logo.png + LICENSE + README.md + CHANGELOG.md + assets/logo.svg + assets/logo.png exe/libtmux-mcp lib/libtmux/mcp.rb lib/libtmux/mcp/version.rb diff --git a/gems/libtmux-workspace/README.md b/gems/libtmux-workspace/README.md index c74459cc..aa68bfa8 100644 --- a/gems/libtmux-workspace/README.md +++ b/gems/libtmux-workspace/README.md @@ -226,7 +226,7 @@ Dir.mktmpdir("workspace-") do |directory| result = plan.apply(server: server) puts "applied: #{result.success?}" sessions = server.list_sessions.map { |session| session.snapshot.name } - puts "sessions: #{sessions.join(', ')}" + puts "sessions: #{sessions.join(", ")}" end end ``` @@ -269,19 +269,25 @@ require "libtmux/workspace" LibTmux::Server.start do |server| server.new_session(name: "borrowed", command: ["/bin/cat"]) - document = {session_name: "crowded", - windows: [{window_name: "small", panes: Array.new(40) { {} }}]} - crowded = LibTmux::Workspace.parse(JSON.generate(document), - format: :json, base_directory: __dir__) + document = { + session_name: "crowded", + windows: [{ window_name: "small", panes: Array.new(40) { {} } }] + } + crowded = + LibTmux::Workspace.parse( + JSON.generate(document), + format: :json, + base_directory: __dir__ + ) begin crowded.plan.apply(server: server, compensate: true) rescue LibTmux::Workspace::ApplyError => error puts "failed action: #{error.result.failed_action}" - puts "created a session: #{error.result.created_refs.key?('session')}" + puts "created a session: #{error.result.created_refs.key?("session")}" puts "compensation: #{error.result.compensation}" end sessions = server.list_sessions.map { |session| session.snapshot.name } - puts "sessions: #{sessions.join(', ')}" + puts "sessions: #{sessions.join(", ")}" end ``` diff --git a/gems/libtmux-workspace/lib/libtmux/workspace.rb b/gems/libtmux-workspace/lib/libtmux/workspace.rb index 67c48f7c..719d3492 100644 --- a/gems/libtmux-workspace/lib/libtmux/workspace.rb +++ b/gems/libtmux-workspace/lib/libtmux/workspace.rb @@ -9,49 +9,89 @@ module LibTmux class Workspace PROFILE = "libtmux-ruby.workspace" CONFIG_VERSION = 1 - LIMITS = {max_bytes: 1 << 20, max_depth: 32, max_nodes: 10_000, - max_string_bytes: 1 << 16, max_windows: 128, max_panes: 1024}.freeze + LIMITS = { + max_bytes: 1 << 20, + max_depth: 32, + max_nodes: 10_000, + max_string_bytes: 1 << 16, + max_windows: 128, + max_panes: 1024 + }.freeze private_constant :LIMITS class ConfigError < LibTmux::Error def initialize(message = "invalid workspace configuration", path: "$", expected: nil) - super("#{message} at #{path}#{expected ? "; expected #{expected}" : ''}", path: path, expected: expected, phase: :workspace) + super( + "#{message} at #{path}#{expected ? "; expected #{expected}" : ""}", + path: path, + expected: expected, + phase: :workspace + ) end end - class ConflictError < LibTmux::Error; end + class ConflictError < LibTmux::Error + end def self.load(path, format: nil, **options) unless path.is_a?(String) && !path.empty? && !path.include?("\0") raise ArgumentError, "workspace path must be a nonempty String without NUL" end filename = File.expand_path(path) - format ||= case File.extname(filename).downcase - when ".json" then :json - when ".yaml", ".yml" then :yaml - else raise ConfigError.new("workspace file format is unknown", expected: "JSON/YAML extension or explicit format") - end + format ||= + case File.extname(filename).downcase + when ".json" + :json + when ".yaml", ".yml" + :yaml + else + raise ConfigError.new( + "workspace file format is unknown", + expected: "JSON/YAML extension or explicit format" + ) + end limit = options.fetch(:max_bytes, LIMITS.fetch(:max_bytes)) - raise ArgumentError, "workspace byte limit must be a positive integer" unless limit.is_a?(Integer) && limit.positive? - - bytes = File.open(filename, File::RDONLY | File::NONBLOCK) do |file| - raise ConfigError.new("invalid workspace file", expected: "regular configuration file") unless file.stat.file? - file.binmode - file.read(limit + 1) || "" + unless limit.is_a?(Integer) && limit.positive? + raise ArgumentError, "workspace byte limit must be a positive integer" end + + bytes = + File.open(filename, File::RDONLY | File::NONBLOCK) do |file| + unless file.stat.file? + raise ConfigError.new("invalid workspace file", expected: "regular configuration file") + end + file.binmode + file.read(limit + 1) || "" + end parse(bytes, format: format, base_directory: File.dirname(filename), **options) rescue SystemCallError - raise ConfigError.new("workspace file could not be read", expected: "readable configuration file"), cause: nil + raise ConfigError.new( + "workspace file could not be read", + expected: "readable configuration file" + ), + cause: nil end - def self.parse(bytes, format:, base_directory:, expand_environment: false, environment: {}, **limits) - unless (limits.keys - LIMITS.keys).empty? && limits.values.all? { |value| value.is_a?(Integer) && value.positive? } + def self.parse( + bytes, + format:, + base_directory:, + expand_environment: false, + environment: {}, + **limits + ) + unless (limits.keys - LIMITS.keys).empty? && + limits.values.all? { |value| value.is_a?(Integer) && value.positive? } raise ArgumentError, "workspace limits must be known positive integers" end bounds = LIMITS.merge(limits).freeze document = Document.new(bounds).parse(bytes, format) - config = Normalizer.new(base_directory, expand_environment, environment, bounds).normalize(document) + config = + Normalizer.new(base_directory, expand_environment, environment, bounds).normalize(document) if JSON.generate(config).bytesize > bounds.fetch(:max_bytes) - raise ConfigError.new("normalized workspace exceeds its wire byte limit", expected: "bounded canonical JSON") + raise ConfigError.new( + "normalized workspace exceeds its wire byte limit", + expected: "bounded canonical JSON" + ) end Document.new(bounds).validate_tree(config) new(config) @@ -72,7 +112,7 @@ def plan(snapshot: nil) end def inspect - "#<#{self.class} profile=#{PROFILE} version=#{CONFIG_VERSION} windows=#{@config.fetch('windows').length}>" + "#<#{self.class} profile=#{PROFILE} version=#{CONFIG_VERSION} windows=#{@config.fetch("windows").length}>" end end end diff --git a/gems/libtmux-workspace/lib/libtmux/workspace/apply.rb b/gems/libtmux-workspace/lib/libtmux/workspace/apply.rb index 975296fd..d26d5ed9 100644 --- a/gems/libtmux-workspace/lib/libtmux/workspace/apply.rb +++ b/gems/libtmux-workspace/lib/libtmux/workspace/apply.rb @@ -4,14 +4,32 @@ module LibTmux class Workspace class ApplyResult Effect = Data.define(:step_id, :action, :outcome) - attr_reader :completed_steps, :created_refs, :effects, :failed_step, :failed_action, - :compensation, :cleanup_errors + attr_reader :completed_steps, + :created_refs, + :effects, + :failed_step, + :failed_action, + :compensation, + :cleanup_errors - def initialize(completed_steps:, created_refs:, effects:, failed_step:, failed_action:, - uncertain:, compensation:, cleanup_errors:) - @completed_steps, @created_refs, @effects = completed_steps.dup.freeze, created_refs.dup.freeze, effects.dup.freeze + def initialize( + completed_steps:, + created_refs:, + effects:, + failed_step:, + failed_action:, + uncertain:, + compensation:, + cleanup_errors: + ) + @completed_steps, @created_refs, @effects = + completed_steps.dup.freeze, + created_refs.dup.freeze, + effects.dup.freeze @failed_step, @failed_action, @uncertain = failed_step, failed_action, uncertain - @compensation, @cleanup_errors = compensation, cleanup_errors.map { |error| error.dup.freeze }.freeze + @compensation, @cleanup_errors = + compensation, + cleanup_errors.map { |error| error.dup.freeze }.freeze freeze end private_class_method :new @@ -29,13 +47,27 @@ def inspect end def to_h - {"success" => success?, "completed_steps" => completed_steps, - "created_refs" => created_refs.transform_values do |ref| - {"binding_key" => ref.binding_key, "kind" => ref.kind.to_s, "id" => ref.id} - end, - "effects" => effects.map { |effect| {"step_id" => effect.step_id, "action" => effect.action.to_s, "outcome" => effect.outcome.to_s} }, - "failed_step" => failed_step, "failed_action" => failed_action&.to_s, - "uncertain" => uncertain?, "compensation" => compensation.to_s, "cleanup_errors" => cleanup_errors} + { + "success" => success?, + "completed_steps" => completed_steps, + "created_refs" => + created_refs.transform_values do |ref| + { "binding_key" => ref.binding_key, "kind" => ref.kind.to_s, "id" => ref.id } + end, + "effects" => + effects.map do |effect| + { + "step_id" => effect.step_id, + "action" => effect.action.to_s, + "outcome" => effect.outcome.to_s + } + end, + "failed_step" => failed_step, + "failed_action" => failed_action&.to_s, + "uncertain" => uncertain?, + "compensation" => compensation.to_s, + "cleanup_errors" => cleanup_errors + } end end @@ -44,21 +76,32 @@ class ApplyError < LibTmux::Error def initialize(result, failure) @result, @failure_class = result, failure.class.name.freeze - delivery = result.uncertain? ? :possibly_sent : (result.effects.empty? ? :not_sent : :observed) + delivery = + result.uncertain? ? :possibly_sent : (result.effects.empty? ? :not_sent : :observed) if result.failed_action == :check_directories && failure.is_a?(ConfigError) message, path, expected = failure.message, failure.path, failure.expected else message = "workspace apply failed during #{result.failed_action} (#{failure_class})" end - super(message, path: path, expected: expected, phase: :apply, - delivery: delivery, cleanup_errors: result.cleanup_errors) + super( + message, + path: path, + expected: expected, + phase: :apply, + delivery: delivery, + cleanup_errors: result.cleanup_errors + ) end end class ApplyExecution def initialize(plan, server, timeout, cancel, compensate) - raise ArgumentError, "workspace apply requires a Server" unless server.is_a?(LibTmux::Server) - raise ArgumentError, "workspace timeout must be finite" unless timeout.is_a?(Numeric) && timeout.finite? + unless server.is_a?(LibTmux::Server) + raise ArgumentError, "workspace apply requires a Server" + end + unless timeout.is_a?(Numeric) && timeout.finite? + raise ArgumentError, "workspace timeout must be finite" + end raise ArgumentError, "compensate must be boolean" unless [true, false].include?(compensate) if cancel && !(cancel.respond_to?(:reader) && cancel.respond_to?(:cancelled?)) raise ArgumentError, "cancel must provide a cancellation reader and state" @@ -84,7 +127,9 @@ def call checkpoint rescue Exception => error failure = error - @uncertain = @pending && @mutation && (!error.is_a?(LibTmux::Error) || error.delivery != :not_sent) + @uncertain = + @pending && @mutation && + (!error.is_a?(LibTmux::Error) || error.delivery != :not_sent) ensure compensate if failure && @compensate end @@ -92,9 +137,18 @@ def call rescue Exception => deferred failure ||= deferred end - result = ApplyResult.__send__(:new, completed_steps: @completed, created_refs: @created, - effects: @effects, failed_step: failure && @step&.id, failed_action: failure && @action, - uncertain: !!@uncertain, compensation: @compensation, cleanup_errors: @cleanup_errors) + result = + ApplyResult.__send__( + :new, + completed_steps: @completed, + created_refs: @created, + effects: @effects, + failed_step: failure && @step&.id, + failed_action: failure && @action, + uncertain: !!@uncertain, + compensation: @compensation, + cleanup_errors: @cleanup_errors + ) raise ApplyError.new(result, failure), cause: nil if failure result @@ -103,27 +157,36 @@ def call private def preflight - snapshot = action(:capture_preconditions, mutation: false) { |options| @server.snapshot(**options) } + snapshot = + action(:capture_preconditions, mutation: false) { |options| @server.snapshot(**options) } expected = @plan.preconditions.fetch("binding_key") if expected && expected != snapshot.binding_key raise ConflictError.new("workspace plan belongs to another server binding", phase: :apply) end if snapshot.sessions.where(name: @plan.preconditions.fetch("session_name_absent")).exists? - raise ConflictError.new("workspace creation requires an absent session name", phase: :apply) + raise ConflictError.new( + "workspace creation requires an absent session name", + phase: :apply + ) end action(:check_directories, mutation: false) { check_directories } end def check_directories steps = @plan.steps.select { |step| step.arguments.key?("cwd") } - steps.uniq { |step| step.arguments.fetch("cwd") }.each do |step| - directory = step.arguments.fetch("cwd") - next if File.directory?(directory) && File.executable?(directory) + steps + .uniq { |step| step.arguments.fetch("cwd") } + .each do |step| + directory = step.arguments.fetch("cwd") + next if File.directory?(directory) && File.executable?(directory) - _, window, pane = step.produces.last.split(":") - raise ConfigError.new("workspace start_directory is unavailable", - path: "$.windows[#{window}].panes[#{pane}]", expected: "existing accessible directory") - end + _, window, pane = step.produces.last.split(":") + raise ConfigError.new( + "workspace start_directory is unavailable", + path: "$.windows[#{window}].panes[#{pane}]", + expected: "existing accessible directory" + ) + end end def perform(step) @@ -133,58 +196,104 @@ def perform(step) when :create_session action(:create_session) do |options| assignments = args.fetch("pane_environment").map { |name, value| "#{name}=#{value}" } - receipt = @server.new_session(name: args.fetch("name"), window_name: args.fetch("window_name"), - cwd: args.fetch("cwd"), environment: args.fetch("environment"), - command: ["/usr/bin/env", "--", *assignments, "/bin/sh"], receipt: true, **options) + receipt = + @server.new_session( + name: args.fetch("name"), + window_name: args.fetch("window_name"), + cwd: args.fetch("cwd"), + environment: args.fetch("environment"), + command: ["/usr/bin/env", "--", *assignments, "/bin/sh"], + receipt: true, + **options + ) remember("session", receipt.entity) remember(step.produces[1], receipt.window) remember(step.produces[2], receipt.pane) end when :create_window action(:create_window) do |options| - receipt = target.new_window(name: args.fetch("name"), index: args.fetch("index"), command: ["/bin/sh"], - cwd: args.fetch("cwd"), environment: args.fetch("environment"), focus: false, receipt: true, **options) + receipt = + target.new_window( + name: args.fetch("name"), + index: args.fetch("index"), + command: ["/bin/sh"], + cwd: args.fetch("cwd"), + environment: args.fetch("environment"), + focus: false, + receipt: true, + **options + ) remember(step.produces.first, receipt.window) remember(step.produces[1], receipt.pane) end when :split_pane action(:split_pane) do |options| - pane = target.split(direction: args.fetch("direction").to_sym, size: args["size"], command: ["/bin/sh"], - cwd: args.fetch("cwd"), environment: args.fetch("environment"), focus: false, **options) + pane = + target.split( + direction: args.fetch("direction").to_sym, + size: args["size"], + command: ["/bin/sh"], + cwd: args.fetch("cwd"), + environment: args.fetch("environment"), + focus: false, + **options + ) remember(step.produces.first, pane) end when :move_initial_window link = link_for(target) if link.index != args.fetch("index") - action(:move_initial_window) { |options| link.move(session: @entities.fetch("session").ref, index: args.fetch("index"), **options) } + action(:move_initial_window) do |options| + link.move( + session: @entities.fetch("session").ref, + index: args.fetch("index"), + **options + ) + end end when :set_session_option, :set_window_option - action(step.operation) { |options| target.options.set(args.fetch("name"), args.fetch("value"), **options) } + action(step.operation) do |options| + target.options.set(args.fetch("name"), args.fetch("value"), **options) + end when :unset_session_option, :unset_window_option action(step.operation) { |options| target.options.unset(args.fetch("name"), **options) } when :select_layout action(:select_layout) { |options| target.select_layout(args.fetch("layout"), **options) } when :send_command - action(:insert_command_text, outcome: :dispatch_only) { |options| target.send_text(args.fetch("command"), **options) } - action(:dispatch_command, outcome: :dispatch_only) { |options| target.send_keys("Enter", **options) } + action(:insert_command_text, outcome: :dispatch_only) do |options| + target.send_text(args.fetch("command"), **options) + end + action(:dispatch_command, outcome: :dispatch_only) do |options| + target.send_keys("Enter", **options) + end when :select_pane action(:select_pane) { |options| target.select(**options) } when :select_window link = link_for(target) action(:select_window) { |options| link.select(**options) } else - raise UnsupportedFeatureError.new("workspace plan operation is unsupported", phase: :apply) + raise UnsupportedFeatureError.new( + "workspace plan operation is unsupported", + phase: :apply + ) end end def link_for(window) - links = action(:acquire_window_link, mutation: false) { |options| @entities.fetch("session").list_window_links(**options) } + links = + action(:acquire_window_link, mutation: false) do |options| + @entities.fetch("session").list_window_links(**options) + end only(links.select { |link| link.id == window.id }) end def only(values) unless values.length == 1 - raise ConflictError.new("created workspace topology changed during apply", phase: :apply, delivery: :observed) + raise ConflictError.new( + "created workspace topology changed during apply", + phase: :apply, + delivery: :observed + ) end values.first end @@ -200,11 +309,18 @@ def action(name, mutation: true, outcome: :observed) checkpoint raise Cancelled.new("workspace apply was cancelled", phase: :apply) if @cancel&.cancelled? remaining = @deadline - clock - raise DeadlineExceeded.new("workspace apply deadline elapsed", phase: :apply) unless remaining.positive? + unless remaining.positive? + raise DeadlineExceeded.new("workspace apply deadline elapsed", phase: :apply) + end @pending = true - result = Thread.handle_interrupt(Exception => :on_blocking) { yield(timeout: remaining, cancel: @cancel) } - @effects << ApplyResult::Effect.new(step_id: @step&.id, action: name, outcome: outcome) if mutation + result = + Thread.handle_interrupt(Exception => :on_blocking) do + yield(timeout: remaining, cancel: @cancel) + end + if mutation + @effects << ApplyResult::Effect.new(step_id: @step&.id, action: name, outcome: outcome) + end @pending = false checkpoint result @@ -221,7 +337,9 @@ def compensate 2.times do begin remaining = deadline - clock - raise DeadlineExceeded.new("workspace compensation deadline elapsed") unless remaining.positive? + unless remaining.positive? + raise DeadlineExceeded.new("workspace compensation deadline elapsed") + end windows = @created.values.select { |ref| ref.kind == :window } panes = @created.values.select { |ref| ref.kind == :pane } diff --git a/gems/libtmux-workspace/lib/libtmux/workspace/cli.rb b/gems/libtmux-workspace/lib/libtmux/workspace/cli.rb index 137bbd8f..6d621602 100644 --- a/gems/libtmux-workspace/lib/libtmux/workspace/cli.rb +++ b/gems/libtmux-workspace/lib/libtmux/workspace/cli.rb @@ -12,9 +12,14 @@ def self.run(arguments, out: $stdout, err: $stderr, directory: Dir.pwd, environm end def initialize(arguments, out, err, directory, environment) - @arguments, @out, @err, @directory, @environment = arguments.dup, out, err, directory, environment + @arguments, @out, @err, @directory, @environment = + arguments.dup, + out, + err, + directory, + environment @json = @arguments.include?("--json") - @options = {timeout: 5.0, environment: {}, expand_environment: false, compensate: false} + @options = { timeout: 5.0, environment: {}, expand_environment: false, compensate: false } end private_class_method :new @@ -25,11 +30,13 @@ def run command = @arguments.shift raise ArgumentError unless %w[validate plan load attach].include?(command) - @arguments.take_while { |argument| argument != "--" }.each_with_index do |argument, index| - next unless argument == "--switch" - value = @arguments[index + 1] - raise OptionParser::MissingArgument, "--switch" if !value || value.start_with?("-") - end + @arguments + .take_while { |argument| argument != "--" } + .each_with_index do |argument, index| + next unless argument == "--switch" + value = @arguments[index + 1] + raise OptionParser::MissingArgument, "--switch" if !value || value.start_with?("-") + end parser.parse!(@arguments) return help if @options[:help] return version if @options[:version] @@ -39,13 +46,24 @@ def run validate_arguments(command) term = attachment_term if @options[:attach] file = configuration_file - workspace = Workspace.load(file, expand_environment: @options.fetch(:expand_environment), environment: @options.fetch(:environment)) + workspace = + Workspace.load( + file, + expand_environment: @options.fetch(:expand_environment), + environment: @options.fetch(:environment) + ) case command when "validate" - emit({"valid" => true, "profile" => PROFILE, "version" => CONFIG_VERSION}, "Workspace configuration is valid.") + emit( + { "valid" => true, "profile" => PROFILE, "version" => CONFIG_VERSION }, + "Workspace configuration is valid." + ) when "plan" if @options[:live] - plan = with_server { |server| workspace.plan(snapshot: server.snapshot(timeout: @options.fetch(:timeout))) } + plan = + with_server do |server| + workspace.plan(snapshot: server.snapshot(timeout: @options.fetch(:timeout))) + end emit(plan.to_h, human_plan(plan)) else plan = workspace.plan @@ -53,27 +71,47 @@ def run end when "load" with_server do |server| - @result = workspace.plan.apply(server: server, timeout: @options.fetch(:timeout), compensate: @options.fetch(:compensate)) + @result = + workspace.plan.apply( + server: server, + timeout: @options.fetch(:timeout), + compensate: @options.fetch(:compensate) + ) if @options[:switch] - server.switch_client(client: @options.fetch(:switch), session: @result.created_refs.fetch("session"), - timeout: @options.fetch(:timeout)) + server.switch_client( + client: @options.fetch(:switch), + session: @result.created_refs.fetch("session"), + timeout: @options.fetch(:timeout) + ) end if @options[:attach] terminal = attachment_terminal - raise TransportError.new("interactive terminal required", phase: :terminal) unless terminal - - result = server.attach(session: @result.created_refs.fetch("session"), terminal: terminal, term: term) - raise TransportError.new("attached terminal client failed", phase: :terminal) unless result.success? + unless terminal + raise TransportError.new("interactive terminal required", phase: :terminal) + end + + result = + server.attach( + session: @result.created_refs.fetch("session"), + terminal: terminal, + term: term + ) + unless result.success? + raise TransportError.new("attached terminal client failed", phase: :terminal) + end end end - emit(@result.to_h, "Workspace created; #{@result.completed_steps.length} steps completed. Shell commands were dispatched.") + emit( + @result.to_h, + "Workspace created; #{@result.completed_steps.length} steps completed. Shell commands were dispatched." + ) end 0 rescue Workspace::ConfigError => error report(error, kind: "configuration", status: 2) rescue Workspace::ApplyError => error @result = error.result - interrupted = ["Interrupt", "LibTmux::Cancelled"].include?(error.failure_class) + interrupted = %w[Interrupt LibTmux::Cancelled].include?(error.failure_class) status = interrupted ? 130 : (@result.uncertain? || !@result.effects.empty? ? 3 : 1) report(error, kind: interrupted ? "interrupted" : "application", status: status) rescue OptionParser::ParseError, ArgumentError, KeyError @@ -81,36 +119,65 @@ def run rescue Interrupt, LibTmux::Cancelled => error report(error, kind: "interrupted", status: 130) rescue LibTmux::Error, SystemCallError, IOError => error - report(error, kind: version_refusal?(error) ? "tmux_unsupported" : "execution", status: @result ? 3 : 1) + report( + error, + kind: version_refusal?(error) ? "tmux_unsupported" : "execution", + status: @result ? 3 : 1 + ) end private def parser - @parser ||= OptionParser.new do |options| - options.banner = "Usage: libtmux-workspace validate|plan|load [options] [FILE]\n" \ - " libtmux-workspace attach --socket PATH [--timeout SECONDS] SESSION_ID" - options.on("--json", "Write structured JSON to stdout") { @json = true } - options.on("--socket PATH", "Existing tmux server socket for load, plan --live or attach", - "Required for attach. Otherwise defaults to LIBTMUX_SOCKET_PATH,", - "then LIBTMUX_SOCKET, then the", - "server TMUX names, then tmux's default socket") { |value| @options[:socket] = value } - options.on("--live", "Acquire a snapshot before planning") { @options[:live] = true } - options.on("--timeout SECONDS", Float, "Per-operation apply/capture/switch/session lookup deadline (default: 5)") { |value| @options[:timeout] = value } - options.on("--compensate", "Attempt guarded cleanup of positively created resources on failure") { @options[:compensate] = true } - options.on("--attach", "Attach after load using the terminal on stdin and stdout") { @options[:attach] = true } - options.on("--switch CLIENT", "Switch the explicit current client after successful load") { |value| @options[:switch] = value } - options.on("--expand-environment", "Expand ${NAME} in paths/environment using explicit --env values") { @options[:expand_environment] = true } - options.on("--env NAME=VALUE", "Supply a substitution value or HOME for ~ in start_directory") do |value| - name, contents = value.split("=", 2) - raise ArgumentError unless contents && /\A[A-Za-z_][A-Za-z0-9_]*\z/.match?(name) - raise ArgumentError if @options.fetch(:environment).key?(name) - - @options.fetch(:environment)[name] = contents + @parser ||= + OptionParser.new do |options| + options.banner = + "Usage: libtmux-workspace validate|plan|load [options] [FILE]\n" \ + " libtmux-workspace attach --socket PATH [--timeout SECONDS] SESSION_ID" + options.on("--json", "Write structured JSON to stdout") { @json = true } + options.on( + "--socket PATH", + "Existing tmux server socket for load, plan --live or attach", + "Required for attach. Otherwise defaults to LIBTMUX_SOCKET_PATH,", + "then LIBTMUX_SOCKET, then the", + "server TMUX names, then tmux's default socket" + ) { |value| @options[:socket] = value } + options.on("--live", "Acquire a snapshot before planning") { @options[:live] = true } + options.on( + "--timeout SECONDS", + Float, + "Per-operation apply/capture/switch/session lookup deadline (default: 5)" + ) { |value| @options[:timeout] = value } + options.on( + "--compensate", + "Attempt guarded cleanup of positively created resources on failure" + ) { @options[:compensate] = true } + options.on("--attach", "Attach after load using the terminal on stdin and stdout") do + @options[:attach] = true + end + options.on( + "--switch CLIENT", + "Switch the explicit current client after successful load" + ) { |value| @options[:switch] = value } + options.on( + "--expand-environment", + "Expand ${NAME} in paths/environment using explicit --env values" + ) { @options[:expand_environment] = true } + options.on( + "--env NAME=VALUE", + "Supply a substitution value or HOME for ~ in start_directory" + ) do |value| + name, contents = value.split("=", 2) + raise ArgumentError unless contents && /\A[A-Za-z_][A-Za-z0-9_]*\z/.match?(name) + raise ArgumentError if @options.fetch(:environment).key?(name) + + @options.fetch(:environment)[name] = contents + end + options.on("-h", "--help", "Show supported commands and options") do + @options[:help] = true + end + options.on("--version", "Show the installed gem version") { @options[:version] = true } end - options.on("-h", "--help", "Show supported commands and options") { @options[:help] = true } - options.on("--version", "Show the installed gem version") { @options[:version] = true } - end end def help @@ -125,13 +192,17 @@ def version def validate_arguments(command) raise ArgumentError if @arguments.length > 1 - raise ArgumentError unless @options.fetch(:timeout).finite? && @options.fetch(:timeout).positive? + unless @options.fetch(:timeout).finite? && @options.fetch(:timeout).positive? + raise ArgumentError + end raise ArgumentError if @options[:attach] && @options[:switch] if @options[:switch] client = @options.fetch(:switch) raise ArgumentError unless client.bytesize.between?(1, 1024) && !client.b.include?("\0") end - raise ArgumentError if command != "load" && (@options[:attach] || @options[:switch] || @options[:compensate]) + if command != "load" && (@options[:attach] || @options[:switch] || @options[:compensate]) + raise ArgumentError + end raise ArgumentError if @options[:live] && command != "plan" live = %w[load attach].include?(command) || @options[:live] raise ArgumentError if @options.key?(:socket) && @options[:socket].empty? @@ -139,8 +210,9 @@ def validate_arguments(command) end def attach_existing - if @json || @options.values_at(:live, :attach, :switch, :compensate, :expand_environment).any? || - !@options.fetch(:environment).empty? + if @json || + @options.values_at(:live, :attach, :switch, :compensate, :expand_environment).any? || + !@options.fetch(:environment).empty? @argument_message = "Attach accepts --socket and --timeout; use --help for usage." raise ArgumentError end @@ -156,15 +228,24 @@ def attach_existing end validate_arguments("attach") terminal = attachment_terminal - return attachment_error("Attach requires an interactive terminal on stdin and stdout.") unless terminal + unless terminal + return attachment_error("Attach requires an interactive terminal on stdin and stdout.") + end term = attachment_term with_server do |server| - session = server.list_sessions(timeout: @options.fetch(:timeout)).find { |candidate| candidate.id == id } - return attachment_error("The session ID was not found on the selected tmux server.") unless session + session = + server + .list_sessions(timeout: @options.fetch(:timeout)) + .find { |candidate| candidate.id == id } + unless session + return attachment_error("The session ID was not found on the selected tmux server.") + end result = server.attach(session: session.ref, terminal: terminal, term: term) - return attachment_error("The tmux terminal client failed to attach.") unless result.success? + unless result.success? + return attachment_error("The tmux terminal client failed to attach.") + end end 0 end @@ -182,7 +263,9 @@ def attachment_terminal return unless input.tty? && @out.is_a?(IO) && @out.tty? && input.stat.rdev == @out.stat.rdev # tmux needs the actual terminal device on both streams. - [input, @out].find { |stream| (stream.fcntl(Fcntl::F_GETFL) & Fcntl::O_ACCMODE) == Fcntl::O_RDWR } + [input, @out].find do |stream| + (stream.fcntl(Fcntl::F_GETFL) & Fcntl::O_ACCMODE) == Fcntl::O_RDWR + end end def attachment_error(message) @@ -193,9 +276,13 @@ def attachment_error(message) def configuration_file return File.expand_path(@arguments.first, @directory) if @arguments.first - candidates = %w[.tmuxp.yaml .tmuxp.yml .tmuxp.json].map { |name| File.join(@directory, name) }.select { |path| File.exist?(path) } + candidates = + %w[.tmuxp.yaml .tmuxp.yml .tmuxp.json] + .map { |name| File.join(@directory, name) } + .select { |path| File.exist?(path) } unless candidates.length == 1 - @argument_message = "Provide a configuration file; discovery requires exactly one .tmuxp.yaml, .tmuxp.yml or .tmuxp.json." + @argument_message = + "Provide a configuration file; discovery requires exactly one .tmuxp.yaml, .tmuxp.yml or .tmuxp.json." raise ArgumentError end candidates.first @@ -208,7 +295,10 @@ def with_server(&block) # --socket wins; otherwise the core reads the variables, TMUX and tmux's default. def endpoint socket = @options[:socket] - LibTmux::Endpoint.new(socket_path: (expand_socket(socket) if socket), environment: @environment) + LibTmux::Endpoint.new( + socket_path: (expand_socket(socket) if socket), + environment: @environment + ) rescue ArgumentError => error @argument_message = "Invalid arguments: #{error.message}." raise @@ -218,12 +308,17 @@ def endpoint def expand_socket(socket) File.expand_path(socket, @directory) rescue ArgumentError - raise ArgumentError, "--socket cannot be expanded to a path; its leading ~ names no home directory" + raise ArgumentError, + "--socket cannot be expanded to a path; its leading ~ names no home directory" end def human_plan(plan) - (["#{plan.mode}: #{plan.steps.length} ordered steps"] + - plan.steps.map { |step| "#{step.id}. #{step.operation} #{step.target} (#{step.effect})" }).join("\n") + ( + ["#{plan.mode}: #{plan.steps.length} ordered steps"] + + plan.steps.map do |step| + "#{step.id}. #{step.operation} #{step.target} (#{step.effect})" + end + ).join("\n") end def emit(value, human) @@ -233,7 +328,8 @@ def emit(value, human) # A refusal before dispatch sent nothing, and its message says what to # change, so it replaces the generic failure line. def pre_dispatch_refusal?(error) - error.is_a?(LibTmux::UnsupportedFeatureError) && error.phase == :admission && error.delivery == :not_sent + error.is_a?(LibTmux::UnsupportedFeatureError) && error.phase == :admission && + error.delivery == :not_sent end # Only a refusal that names the tmux floor carries the machine code. @@ -242,14 +338,16 @@ def version_refusal?(error) end def report(error, kind:, status:) - message = if kind == "arguments" - @argument_message || "Invalid arguments; use --help for supported options." - elsif error.is_a?(Workspace::ConfigError) || error.is_a?(Workspace::ApplyError) || pre_dispatch_refusal?(error) - error.message - else - "Workspace #{kind} failed#{error ? " (#{error.class})" : ''}." - end - value = {"error" => {"kind" => kind, "message" => message, "exit_status" => status}} + message = + if kind == "arguments" + @argument_message || "Invalid arguments; use --help for supported options." + elsif error.is_a?(Workspace::ConfigError) || error.is_a?(Workspace::ApplyError) || + pre_dispatch_refusal?(error) + error.message + else + "Workspace #{kind} failed#{error ? " (#{error.class})" : ""}." + end + value = { "error" => { "kind" => kind, "message" => message, "exit_status" => status } } if error.is_a?(LibTmux::Error) value.fetch("error")["delivery"] = error.delivery.to_s value.fetch("error")["phase"] = error.phase&.to_s diff --git a/gems/libtmux-workspace/lib/libtmux/workspace/document.rb b/gems/libtmux-workspace/lib/libtmux/workspace/document.rb index d355ac03..de0d158a 100644 --- a/gems/libtmux-workspace/lib/libtmux/workspace/document.rb +++ b/gems/libtmux-workspace/lib/libtmux/workspace/document.rb @@ -37,22 +37,27 @@ def scalar(value, anchor, tag, plain, quoted, *) fail_input("YAML without tags or anchors") if anchor || tag visit fail_input("bounded UTF-8 scalar") if value.bytesize > @limits.fetch(:max_string_bytes) - decoded = if !plain || quoted - value - else - case value - when "true" then true - when "false" then false - when "null", "~", "" then nil - when /\A-?(?:0|[1-9][0-9]*)\z/ - fail_input("bounded integer token") if value.bytesize > 20 - Integer(value, 10) - when /\A-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\z/ - fail_input("bounded scalar token") if value.bytesize > 32 - Float(value) - else value + decoded = + if !plain || quoted + value + else + case value + when "true" + true + when "false" + false + when "null", "~", "" + nil + when /\A-?(?:0|[1-9][0-9]*)\z/ + fail_input("bounded integer token") if value.bytesize > 20 + Integer(value, 10) + when /\A-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\z/ + fail_input("bounded scalar token") if value.bytesize > 32 + Float(value) + else + value + end end - end append(decoded) end @@ -67,7 +72,7 @@ def container(value, anchor, tag) visit fail_input("bounded document depth") if @stack.length >= @limits.fetch(:max_depth) append(value) - @stack << {value: value, key: nil} + @stack << { value: value, key: nil } end def visit @@ -109,21 +114,32 @@ def parse(bytes, format) end text = bytes.dup.force_encoding(Encoding::UTF_8) invalid("UTF-8 document") unless text.valid_encoding? - value = case format - when :json - preflight_json(text) - JSON.parse(text, max_nesting: @limits.fetch(:max_depth), allow_nan: false, allow_duplicate_key: false) - when :yaml - handler = YAMLHandler.new(@limits) - Psych::Parser.new(handler).parse(text) - handler.result - else - raise ArgumentError, "workspace format must be :json or :yaml" - end + value = + case format + when :json + preflight_json(text) + JSON.parse( + text, + max_nesting: @limits.fetch(:max_depth), + allow_nan: false, + allow_duplicate_key: false + ) + when :yaml + handler = YAMLHandler.new(@limits) + Psych::Parser.new(handler).parse(text) + handler.result + else + raise ArgumentError, "workspace format must be :json or :yaml" + end validate_tree(value) value rescue JSON::ParserError, JSON::NestingError, Psych::Exception, EncodingError - raise ConfigError.new("invalid workspace syntax", path: "$", expected: "data-only bounded JSON or YAML"), cause: nil + raise ConfigError.new( + "invalid workspace syntax", + path: "$", + expected: "data-only bounded JSON or YAML" + ), + cause: nil end def validate_tree(value) @@ -153,12 +169,15 @@ def preflight_json(text) nodes += 1 depth += 1 invalid("bounded document depth") if depth > @limits.fetch(:max_depth) - when 125, 93 then depth -= 1 - when 32, 9, 10, 13, 44, 58 then nil + when 125, 93 + depth -= 1 + when 32, 9, 10, 13, 44, 58 + nil else nodes += 1 first = index - index += 1 while index < text.bytesize && ![32, 9, 10, 13, 44, 93, 125].include?(text.getbyte(index)) + index += 1 while index < text.bytesize && + ![32, 9, 10, 13, 44, 93, 125].include?(text.getbyte(index)) invalid("bounded scalar token") if index - first > 32 index -= 1 end @@ -178,11 +197,16 @@ def validate(value, depth = 0) validate(key, depth + 1) validate(child, depth + 1) end - when Array then value.each { |child| validate(child, depth + 1) } + when Array + value.each { |child| validate(child, depth + 1) } when String - invalid("bounded UTF-8 scalar") if value.bytesize > @limits.fetch(:max_string_bytes) || !value.valid_encoding? - when Integer, Float, true, false, nil then nil - else invalid("plain data values") + if value.bytesize > @limits.fetch(:max_string_bytes) || !value.valid_encoding? + invalid("bounded UTF-8 scalar") + end + when Integer, Float, true, false, nil + nil + else + invalid("plain data values") end end diff --git a/gems/libtmux-workspace/lib/libtmux/workspace/normalizer.rb b/gems/libtmux-workspace/lib/libtmux/workspace/normalizer.rb index f3a6284d..1b97286e 100644 --- a/gems/libtmux-workspace/lib/libtmux/workspace/normalizer.rb +++ b/gems/libtmux-workspace/lib/libtmux/workspace/normalizer.rb @@ -8,19 +8,39 @@ class Normalizer WINDOW = (COMMON + %w[window_name window_index panes focus layout options]).freeze PANE = (COMMON + %w[focus split size]).freeze LAYOUTS = %w[even-horizontal even-vertical main-horizontal main-vertical tiled].freeze - SESSION_OPTIONS = {"base-index" => :index, "status" => :boolean, "mouse" => :boolean, - "renumber-windows" => :boolean, "history-limit" => :index, - "status-interval" => :index, "status-position" => %w[top bottom], + SESSION_OPTIONS = { + "base-index" => :index, + "status" => :boolean, + "mouse" => :boolean, + "renumber-windows" => :boolean, + "history-limit" => :index, + "status-interval" => :index, + "status-position" => %w[top bottom], "status-justify" => %w[left centre right absolute-centre], - "default-terminal" => :unsupported}.freeze - WINDOW_OPTIONS = {"automatic-rename" => :boolean, "allow-rename" => :boolean, - "remain-on-exit" => :boolean, "synchronize-panes" => :boolean, - "aggressive-resize" => :boolean, "pane-base-index" => :pane_index, - "main-pane-width" => :index, "main-pane-height" => :index, - "window-status-format" => :text, "window-status-current-format" => :text, - "pane-border-status" => %w[off top bottom]}.freeze + "default-terminal" => :unsupported + }.freeze + WINDOW_OPTIONS = { + "automatic-rename" => :boolean, + "allow-rename" => :boolean, + "remain-on-exit" => :boolean, + "synchronize-panes" => :boolean, + "aggressive-resize" => :boolean, + "pane-base-index" => :pane_index, + "main-pane-width" => :index, + "main-pane-height" => :index, + "window-status-format" => :text, + "window-status-current-format" => :text, + "pane-border-status" => %w[off top bottom] + }.freeze BLANK_PANE = %w[blank pane].freeze - private_constant :COMMON, :ROOT, :WINDOW, :PANE, :LAYOUTS, :SESSION_OPTIONS, :WINDOW_OPTIONS, :BLANK_PANE + private_constant :COMMON, + :ROOT, + :WINDOW, + :PANE, + :LAYOUTS, + :SESSION_OPTIONS, + :WINDOW_OPTIONS, + :BLANK_PANE def initialize(base, expand, environment, limits) @limits, @expand, @expanded_bytes = limits, expand, 0 @@ -39,15 +59,31 @@ def initialize(base, expand, environment, limits) def normalize(input) object(input, ROOT, "$") if input.key?("profile") || input.key?("version") - unless input["profile"] == PROFILE && input["version"].is_a?(Integer) && input["version"] == CONFIG_VERSION + unless input["profile"] == PROFILE && input["version"].is_a?(Integer) && + input["version"] == CONFIG_VERSION fail_at("$", "#{PROFILE} version #{CONFIG_VERSION}, with both envelope fields") end end - name = name(input.fetch("session_name") { fail_at("$.session_name", "session name") }, "$.session_name") - root = common(input, {"start_directory" => @base, "environment" => {}, - "shell_command_before" => [], "shell_command" => []}, "$") + name = + name( + input.fetch("session_name") { fail_at("$.session_name", "session name") }, + "$.session_name" + ) + root = + common( + input, + { + "start_directory" => @base, + "environment" => { + }, + "shell_command_before" => [], + "shell_command" => [] + }, + "$" + ) root_options = options(input.fetch("options", {}), SESSION_OPTIONS, "$.options") - inherited_options = options(input.fetch("window_options", {}), WINDOW_OPTIONS, "$.window_options") + inherited_options = + options(input.fetch("window_options", {}), WINDOW_OPTIONS, "$.window_options") windows = input["windows"] unless windows.is_a?(Array) && windows.length.between?(1, @limits.fetch(:max_windows)) fail_at("$.windows", "nonempty bounded window array") @@ -63,18 +99,19 @@ def normalize(input) explicit[value] = true end next_index = root_options.fetch("base-index", 0) - normalized = windows.each_with_index.map do |window, position| - path = "$.windows[#{position}]" - if window.key?("window_index") - assigned = window.fetch("window_index") - else - next_index += 1 while explicit.key?(next_index) || indexes.key?(next_index) - assigned = index(next_index, "#{path}.window_index") - next_index += 1 + normalized = + windows.each_with_index.map do |window, position| + path = "$.windows[#{position}]" + if window.key?("window_index") + assigned = window.fetch("window_index") + else + next_index += 1 while explicit.key?(next_index) || indexes.key?(next_index) + assigned = index(next_index, "#{path}.window_index") + next_index += 1 + end + indexes[assigned] = true + normalize_window(window, root, inherited_options, assigned, path) end - indexes[assigned] = true - normalize_window(window, root, inherited_options, assigned, path) - end choose_focus(normalized, "$.windows") # Canonical exports carry commands only at leaves. Reloading must not # prepend already inherited commands a second time. @@ -84,29 +121,45 @@ def normalize(input) window["shell_command_before"] = [] window["shell_command"] = [] end - freeze_tree(root.merge("profile" => PROFILE, "version" => CONFIG_VERSION, - "session_name" => name, "options" => root_options, - "window_options" => inherited_options, "windows" => normalized)) + freeze_tree( + root.merge( + "profile" => PROFILE, + "version" => CONFIG_VERSION, + "session_name" => name, + "options" => root_options, + "window_options" => inherited_options, + "windows" => normalized + ) + ) end private def normalize_window(input, parent, inherited_options, assigned, path) value = common(input, parent, path) - value["window_name"] = name(input.fetch("window_name") { fail_at("#{path}.window_name", "window name") }, "#{path}.window_name") + value["window_name"] = name( + input.fetch("window_name") { fail_at("#{path}.window_name", "window name") }, + "#{path}.window_name" + ) value["window_index"] = assigned value["focus"] = boolean(input.fetch("focus", false), "#{path}.focus") - value["options"] = inherited_options.merge(options(input.fetch("options", {}), WINDOW_OPTIONS, "#{path}.options")) + value["options"] = inherited_options.merge( + options(input.fetch("options", {}), WINDOW_OPTIONS, "#{path}.options") + ) layout = input["layout"] - fail_at("#{path}.layout", "supported named layout") if input.key?("layout") && !LAYOUTS.include?(layout) + if input.key?("layout") && !LAYOUTS.include?(layout) + fail_at("#{path}.layout", "supported named layout") + end value["layout"] = layout if layout panes = input["panes"] fail_at("#{path}.panes", "nonempty pane array") unless panes.is_a?(Array) && !panes.empty? @pane_count += panes.length - fail_at("#{path}.panes", "bounded total pane count") if @pane_count > @limits.fetch(:max_panes) + if @pane_count > @limits.fetch(:max_panes) + fail_at("#{path}.panes", "bounded total pane count") + end value["panes"] = panes.each_with_index.map do |pane, position| child_path = "#{path}.panes[#{position}]" - pane = {"shell_command" => pane} if pane.is_a?(String) + pane = { "shell_command" => pane } if pane.is_a?(String) object(pane, PANE, child_path) child = common(pane, value, child_path) child["focus"] = boolean(pane.fetch("focus", false), "#{child_path}.focus") @@ -114,13 +167,18 @@ def normalize_window(input, parent, inherited_options, assigned, path) fail_at(child_path, "split geometry only for subsequent panes") end direction = pane.fetch("split", "vertical") - fail_at("#{child_path}.split", "horizontal or vertical") unless %w[horizontal vertical].include?(direction) + unless %w[horizontal vertical].include?(direction) + fail_at("#{child_path}.split", "horizontal or vertical") + end child["split"] = direction unless position.zero? if pane.key?("size") size = pane["size"] - valid = (size.is_a?(Integer) && size.between?(1, (1 << 31) - 1)) || - (size.is_a?(String) && /\A(?:[1-9]|[1-9][0-9])%\z/.match?(size)) - fail_at("#{child_path}.size", "positive cell count or percentage between 1% and 99%") unless valid + valid = + (size.is_a?(Integer) && size.between?(1, (1 << 31) - 1)) || + (size.is_a?(String) && /\A(?:[1-9]|[1-9][0-9])%\z/.match?(size)) + unless valid + fail_at("#{child_path}.size", "positive cell count or percentage between 1% and 99%") + end fail_at("#{child_path}.size", "split size without a final named layout") if layout child["size"] = size end @@ -133,13 +191,30 @@ def normalize_window(input, parent, inherited_options, assigned, path) def common(input, parent, path) directory = parent.fetch("start_directory") if input.key?("start_directory") - directory = start_directory(input["start_directory"], directory, "#{path}.start_directory") + directory = + start_directory(input["start_directory"], directory, "#{path}.start_directory") end - inherited_environment = parent.fetch("environment").merge(environment_map(input.fetch("environment", {}), "#{path}.environment")) - before = parent.fetch("shell_command_before") + commands(input.fetch("shell_command_before", []), "#{path}.shell_command_before") - command = input.key?("shell_command") ? commands(input["shell_command"], "#{path}.shell_command") : parent.fetch("shell_command") - result = {"start_directory" => directory, "environment" => inherited_environment, - "shell_command_before" => before, "shell_command" => command} + inherited_environment = + parent.fetch("environment").merge( + environment_map(input.fetch("environment", {}), "#{path}.environment") + ) + before = + parent.fetch("shell_command_before") + + commands(input.fetch("shell_command_before", []), "#{path}.shell_command_before") + command = + ( + if input.key?("shell_command") + commands(input["shell_command"], "#{path}.shell_command") + else + parent.fetch("shell_command") + end + ) + result = { + "start_directory" => directory, + "environment" => inherited_environment, + "shell_command_before" => before, + "shell_command" => command + } account(result, path) result end @@ -147,7 +222,9 @@ def common(input, parent, path) def start_directory(input, parent, path) value = expand(text(input, path, empty: false), path) if value.start_with?("~") - fail_at(path, "~ or ~/path for home expansion") unless value == "~" || value.start_with?("~/") + unless value == "~" || value.start_with?("~/") + fail_at(path, "~ or ~/path for home expansion") + end home = @environment["HOME"] fail_at(path, "absolute HOME in the supplied environment") unless home&.start_with?("/") @@ -161,9 +238,15 @@ def object(value, allowed, path) fail_at(path, "configuration object") unless value.is_a?(Hash) unknown = value.keys - allowed unless unknown.empty? - known_unsupported = %w[before_script plugins hooks erb callback callbacks].find { |key| unknown.include?(key) } + known_unsupported = + %w[before_script plugins hooks erb callback callbacks].find do |key| + unknown.include?(key) + end failure_path = known_unsupported ? "#{path}.#{known_unsupported}" : path - fail_at(failure_path, "supported data-only fields; move callbacks or hooks into explicit application code") + fail_at( + failure_path, + "supported data-only fields; move callbacks or hooks into explicit application code" + ) end end @@ -186,20 +269,27 @@ def expand(value, path) return value unless @expand output, offset = +"", 0 - append = lambda do |chunk| - fail_at(path, "bounded expanded value") if output.bytesize + chunk.bytesize > @limits.fetch(:max_string_bytes) - output << chunk - end + append = + lambda do |chunk| + if output.bytesize + chunk.bytesize > @limits.fetch(:max_string_bytes) + fail_at(path, "bounded expanded value") + end + output << chunk + end value.scan(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/) do match = Regexp.last_match append.call(value[offset...match.begin(0)]) - replacement = @environment.fetch(match[1]) { fail_at(path, "explicit substitution value for every variable") } + replacement = + @environment.fetch(match[1]) do + fail_at(path, "explicit substitution value for every variable") + end append.call(replacement) offset = match.end(0) end append.call(value[offset..]) @expanded_bytes += output.bytesize - if output.bytesize > @limits.fetch(:max_string_bytes) || @expanded_bytes > @limits.fetch(:max_bytes) + if output.bytesize > @limits.fetch(:max_string_bytes) || + @expanded_bytes > @limits.fetch(:max_bytes) fail_at(path, "bounded expanded values") end output @@ -207,10 +297,17 @@ def expand(value, path) def account(value, path) @normalized_nodes += 1 - fail_at(path, "bounded normalized node count") if @normalized_nodes > @limits.fetch(:max_nodes) + if @normalized_nodes > @limits.fetch(:max_nodes) + fail_at(path, "bounded normalized node count") + end case value - when Hash then value.each { |key, child| account(key, path); account(child, path) } - when Array then value.each { |child| account(child, path) } + when Hash + value.each do |key, child| + account(key, path) + account(child, path) + end + when Array + value.each { |child| account(child, path) } when String @normalized_bytes += value.bytesize fail_at(path, "bounded normalized bytes") if @normalized_bytes > @limits.fetch(:max_bytes) @@ -220,7 +317,8 @@ def account(value, path) def text(value, path, empty: true) fail_at(path, "UTF-8 text") unless value.is_a?(String) result = value.dup.force_encoding(Encoding::UTF_8) - unless result.valid_encoding? && !result.include?("\0") && (empty || !result.empty?) && result.bytesize <= @limits.fetch(:max_string_bytes) + unless result.valid_encoding? && !result.include?("\0") && (empty || !result.empty?) && + result.bytesize <= @limits.fetch(:max_string_bytes) fail_at(path, "bounded UTF-8 text without NUL") end result @@ -249,7 +347,9 @@ def boolean(value, path) end def index(value, path, maximum = (1 << 31) - 1) - fail_at(path, "integer index from zero through #{maximum}") unless value.is_a?(Integer) && value.between?(0, maximum) + unless value.is_a?(Integer) && value.between?(0, maximum) + fail_at(path, "integer index from zero through #{maximum}") + end value end @@ -258,15 +358,20 @@ def options(value, catalog, path) value.to_h do |key, item| type = catalog[key] fail_at(path, "supported options for this scope") unless type && type != :unsupported - converted = case type - when :boolean then boolean(item, "#{path}.#{key}") - when :index then index(item, "#{path}.#{key}") - when :pane_index then index(item, "#{path}.#{key}", 65535) - when :text then text(item, "#{path}.#{key}") - else - fail_at("#{path}.#{key}", "declared option choice") unless type.include?(item) - item.dup - end + converted = + case type + when :boolean + boolean(item, "#{path}.#{key}") + when :index + index(item, "#{path}.#{key}") + when :pane_index + index(item, "#{path}.#{key}", 65_535) + when :text + text(item, "#{path}.#{key}") + else + fail_at("#{path}.#{key}", "declared option choice") unless type.include?(item) + item.dup + end [key.dup, converted] end end @@ -279,10 +384,14 @@ def choose_focus(values, path) def freeze_tree(value) case value - when Hash then value.to_h { |key, item| [key.dup.freeze, freeze_tree(item)] }.freeze - when Array then value.map { |item| freeze_tree(item) }.freeze - when String then value.dup.freeze - else value + when Hash + value.to_h { |key, item| [key.dup.freeze, freeze_tree(item)] }.freeze + when Array + value.map { |item| freeze_tree(item) }.freeze + when String + value.dup.freeze + else + value end end diff --git a/gems/libtmux-workspace/lib/libtmux/workspace/plan.rb b/gems/libtmux-workspace/lib/libtmux/workspace/plan.rb index 8fdc4f6d..6d5fbfd4 100644 --- a/gems/libtmux-workspace/lib/libtmux/workspace/plan.rb +++ b/gems/libtmux-workspace/lib/libtmux/workspace/plan.rb @@ -3,11 +3,12 @@ module LibTmux class Workspace class Plan - Step = Data.define(:id, :operation, :target, :arguments, :produces, :effect) do - def inspect - "#<#{self.class} id=#{id} operation=#{operation} effect=#{effect}>" + Step = + Data.define(:id, :operation, :target, :arguments, :produces, :effect) do + def inspect + "#<#{self.class} id=#{id} operation=#{operation} effect=#{effect}>" + end end - end attr_reader :mode, :preconditions, :steps def initialize(workspace, snapshot: nil) @@ -17,11 +18,20 @@ def initialize(workspace, snapshot: nil) @configuration = workspace.to_h name = @configuration.fetch("session_name") if snapshot && snapshot.sessions.where(name: name).exists? - raise ConflictError.new("workspace creation requires an absent session name", phase: :plan) + raise ConflictError.new( + "workspace creation requires an absent session name", + phase: :plan + ) end @mode = snapshot ? :captured_create : :offline_create - @preconditions = immutable({"session_name_absent" => name, - "binding_key" => snapshot&.binding_key, "capture_id" => snapshot&.capture_id}) + @preconditions = + immutable( + { + "session_name_absent" => name, + "binding_key" => snapshot&.binding_key, + "capture_id" => snapshot&.capture_id + } + ) @steps = [] build @steps.freeze @@ -29,12 +39,23 @@ def initialize(workspace, snapshot: nil) end def to_h - {"profile" => PROFILE, "version" => CONFIG_VERSION, "mode" => mode.to_s, + { + "profile" => PROFILE, + "version" => CONFIG_VERSION, + "mode" => mode.to_s, "preconditions" => preconditions, - "steps" => steps.map do |step| - {"id" => step.id, "operation" => step.operation.to_s, "target" => step.target, - "arguments" => step.arguments, "produces" => step.produces, "effect" => step.effect.to_s} - end} + "steps" => + steps.map do |step| + { + "id" => step.id, + "operation" => step.operation.to_s, + "target" => step.target, + "arguments" => step.arguments, + "produces" => step.produces, + "effect" => step.effect.to_s + } + end + } end def inspect @@ -50,72 +71,151 @@ def apply(server:, timeout: 5.0, cancel: nil, compensate: false) def build windows = @configuration.fetch("windows") initial = windows.first.fetch("panes").first - add(:create_session, "session", {"name" => @configuration.fetch("session_name"), - "window_name" => windows.first.fetch("window_name"), "cwd" => initial.fetch("start_directory"), - "session_cwd" => @configuration.fetch("start_directory"), - "environment" => @configuration.fetch("environment"), "pane_environment" => initial.fetch("environment")}, - produces: ["session", "window:0", "pane:0:0"], effect: :creation) - add(:set_session_option, "session", {"name" => "renumber-windows", "value" => false}) - add(:set_window_option, "window:0", {"name" => "synchronize-panes", "value" => false}) - add(:move_initial_window, "window:0", {"session" => "session", "index" => windows.first.fetch("window_index")}) - @configuration.fetch("options").sort.each do |name, value| - add(:set_session_option, "session", {"name" => name, "value" => value}) unless name == "renumber-windows" - end + add( + :create_session, + "session", + { + "name" => @configuration.fetch("session_name"), + "window_name" => windows.first.fetch("window_name"), + "cwd" => initial.fetch("start_directory"), + "session_cwd" => @configuration.fetch("start_directory"), + "environment" => @configuration.fetch("environment"), + "pane_environment" => initial.fetch("environment") + }, + produces: %w[session window:0 pane:0:0], + effect: :creation + ) + add(:set_session_option, "session", { "name" => "renumber-windows", "value" => false }) + add(:set_window_option, "window:0", { "name" => "synchronize-panes", "value" => false }) + add( + :move_initial_window, + "window:0", + { "session" => "session", "index" => windows.first.fetch("window_index") } + ) + @configuration + .fetch("options") + .sort + .each do |name, value| + unless name == "renumber-windows" + add(:set_session_option, "session", { "name" => name, "value" => value }) + end + end windows.each_with_index do |window, position| unless position.zero? pane = window.fetch("panes").first - add(:create_window, "session", {"name" => window.fetch("window_name"), "index" => window.fetch("window_index"), - "cwd" => pane.fetch("start_directory"), "environment" => pane.fetch("environment"), "focus" => false}, - produces: ["window:#{position}", "pane:#{position}:0"], effect: :creation) - add(:set_window_option, "window:#{position}", {"name" => "synchronize-panes", "value" => false}) - end - window.fetch("panes").each_with_index do |pane, pane_position| - next if pane_position.zero? - add(:split_pane, "pane:#{position}:#{pane_position - 1}", - {"direction" => pane.fetch("split"), "size" => pane["size"], "cwd" => pane.fetch("start_directory"), - "environment" => pane.fetch("environment"), "focus" => false}, - produces: ["pane:#{position}:#{pane_position}"], effect: :creation) + add( + :create_window, + "session", + { + "name" => window.fetch("window_name"), + "index" => window.fetch("window_index"), + "cwd" => pane.fetch("start_directory"), + "environment" => pane.fetch("environment"), + "focus" => false + }, + produces: ["window:#{position}", "pane:#{position}:0"], + effect: :creation + ) + add( + :set_window_option, + "window:#{position}", + { "name" => "synchronize-panes", "value" => false } + ) end + window + .fetch("panes") + .each_with_index do |pane, pane_position| + next if pane_position.zero? + add( + :split_pane, + "pane:#{position}:#{pane_position - 1}", + { + "direction" => pane.fetch("split"), + "size" => pane["size"], + "cwd" => pane.fetch("start_directory"), + "environment" => pane.fetch("environment"), + "focus" => false + }, + produces: ["pane:#{position}:#{pane_position}"], + effect: :creation + ) + end end windows.each_with_index do |window, position| - window.fetch("options").sort.each do |name, value| - next if name == "synchronize-panes" - add(:set_window_option, "window:#{position}", {"name" => name, "value" => value}) - end - add(:select_layout, "window:#{position}", {"layout" => window.fetch("layout")}) if window["layout"] - window.fetch("panes").each_with_index do |pane, pane_position| - (pane.fetch("shell_command_before") + pane.fetch("shell_command")).each do |command| - add(:send_command, "pane:#{position}:#{pane_position}", {"command" => command}, effect: :dispatch_only) + window + .fetch("options") + .sort + .each do |name, value| + next if name == "synchronize-panes" + add(:set_window_option, "window:#{position}", { "name" => name, "value" => value }) end + if window["layout"] + add(:select_layout, "window:#{position}", { "layout" => window.fetch("layout") }) end + window + .fetch("panes") + .each_with_index do |pane, pane_position| + (pane.fetch("shell_command_before") + pane.fetch("shell_command")).each do |command| + add( + :send_command, + "pane:#{position}:#{pane_position}", + { "command" => command }, + effect: :dispatch_only + ) + end + end if window.fetch("options").key?("synchronize-panes") - add(:set_window_option, "window:#{position}", {"name" => "synchronize-panes", "value" => window.fetch("options").fetch("synchronize-panes")}) + add( + :set_window_option, + "window:#{position}", + { + "name" => "synchronize-panes", + "value" => window.fetch("options").fetch("synchronize-panes") + } + ) else - add(:unset_window_option, "window:#{position}", {"name" => "synchronize-panes"}) + add(:unset_window_option, "window:#{position}", { "name" => "synchronize-panes" }) end pane_focus = window.fetch("panes").index { |pane| pane.fetch("focus") } add(:select_pane, "pane:#{position}:#{pane_focus}", {}) end selected = windows.index { |window| window.fetch("focus") } - add(:select_window, "window:#{selected}", {"session" => "session"}) + add(:select_window, "window:#{selected}", { "session" => "session" }) if @configuration.fetch("options").key?("renumber-windows") - add(:set_session_option, "session", {"name" => "renumber-windows", "value" => @configuration.fetch("options").fetch("renumber-windows")}) + add( + :set_session_option, + "session", + { + "name" => "renumber-windows", + "value" => @configuration.fetch("options").fetch("renumber-windows") + } + ) else - add(:unset_session_option, "session", {"name" => "renumber-windows"}) + add(:unset_session_option, "session", { "name" => "renumber-windows" }) end end def add(operation, target, arguments, produces: [], effect: :configuration) - @steps << Step.new(id: @steps.length + 1, operation: operation, target: target.freeze, - arguments: immutable(arguments), produces: immutable(produces), effect: effect) + @steps << Step.new( + id: @steps.length + 1, + operation: operation, + target: target.freeze, + arguments: immutable(arguments), + produces: immutable(produces), + effect: effect + ) end def immutable(value) case value - when Hash then value.to_h { |key, child| [key.dup.freeze, immutable(child)] }.freeze - when Array then value.map { |child| immutable(child) }.freeze - when String then value.dup.freeze - else value + when Hash + value.to_h { |key, child| [key.dup.freeze, immutable(child)] }.freeze + when Array + value.map { |child| immutable(child) }.freeze + when String + value.dup.freeze + else + value end end end diff --git a/gems/libtmux-workspace/libtmux-workspace.gemspec b/gems/libtmux-workspace/libtmux-workspace.gemspec index fe0afb1d..5b53041f 100644 --- a/gems/libtmux-workspace/libtmux-workspace.gemspec +++ b/gems/libtmux-workspace/libtmux-workspace.gemspec @@ -7,7 +7,8 @@ Gem::Specification.new do |spec| spec.version = LibTmux::Workspace::VERSION spec.authors = ["libtmux contributors"] spec.summary = "Data-only workspace consumer package for libtmux" - spec.description = "Validate YAML or JSON workspace configurations, inspect creation plans and apply them to tmux." + spec.description = + "Validate YAML or JSON workspace configurations, inspect creation plans and apply them to tmux." spec.homepage = "https://github.com/libtmux/libtmux-ruby" spec.license = "MIT" spec.required_ruby_version = ">= 3.3" @@ -20,8 +21,11 @@ Gem::Specification.new do |spec| spec.bindir = "exe" spec.executables = ["libtmux-workspace"] spec.files = %w[ - LICENSE README.md CHANGELOG.md - assets/logo.svg assets/logo.png + LICENSE + README.md + CHANGELOG.md + assets/logo.svg + assets/logo.png exe/libtmux-workspace lib/libtmux/workspace.rb lib/libtmux/workspace/apply.rb diff --git a/gems/libtmux/README.md b/gems/libtmux/README.md index 70b2e3e8..1dff3b75 100644 --- a/gems/libtmux/README.md +++ b/gems/libtmux/README.md @@ -66,18 +66,22 @@ window with its panes: ```ruby require "libtmux" -snapshot = LibTmux::Server.start do |server| - session = server.new_session( - name: "work", window_name: "main", command: ["/bin/cat"] - ) - window = session.new_window(name: "logs", command: ["/bin/cat"]) - window.split(direction: :horizontal, size: "40%", command: ["/bin/cat"]) - - server.snapshot -end +snapshot = + LibTmux::Server.start do |server| + session = + server.new_session( + name: "work", + window_name: "main", + command: ["/bin/cat"] + ) + window = session.new_window(name: "logs", command: ["/bin/cat"]) + window.split(direction: :horizontal, size: "40%", command: ["/bin/cat"]) + + server.snapshot + end snapshot.windows.each do |window| - puts "#{window.name}: #{window.panes.map(&:id).join(', ')}" + puts "#{window.name}: #{window.panes.map(&:id).join(", ")}" end ``` @@ -118,7 +122,7 @@ LibTmux::Server.start do |server| server.new_session(name: "work", command: ["/bin/cat"]) server.new_session(name: "logs", command: ["/bin/cat"]) sessions = server.list_sessions - puts "sessions: #{sessions.map(&:id).sort.join(', ')}" + puts "sessions: #{sessions.map(&:id).sort.join(", ")}" end ``` @@ -143,15 +147,19 @@ make no tmux calls: ```ruby require "libtmux" -snapshot = LibTmux::Server.start do |server| - session = server.new_session( - name: "work", window_name: "main", command: ["/bin/cat"] - ) - window = session.new_window(name: "logs", command: ["/bin/cat"]) - window.split(direction: :horizontal, size: "40%", command: ["/bin/cat"]) - - server.snapshot -end +snapshot = + LibTmux::Server.start do |server| + session = + server.new_session( + name: "work", + window_name: "main", + command: ["/bin/cat"] + ) + window = session.new_window(name: "logs", command: ["/bin/cat"]) + window.split(direction: :horizontal, size: "40%", command: ["/bin/cat"]) + + server.snapshot + end panes = snapshot.panes active_ids = panes.where(active: true).map(&:id) @@ -161,8 +169,8 @@ panes_by_window = panes.group_by { |pane| pane.window.name } logs = snapshot.windows.one(name: "logs") missing = snapshot.windows.one_or_nil(name: "missing") -puts "active: #{active_ids.join(', ')}" -puts "wide: #{wide_panes.map(&:id).join(', ')}" +puts "active: #{active_ids.join(", ")}" +puts "wide: #{wide_panes.map(&:id).join(", ")}" puts "logs panes: #{logs.panes.length}" puts "missing: #{missing.inspect}" ``` @@ -195,14 +203,15 @@ fields match `where:`. This program also uses the snapshot queries above: require "libtmux" LibTmux::Server.start do |server| - work = server.new_session(name: "work", command: ["/bin/cat"], receipt: true) + work = + server.new_session(name: "work", command: ["/bin/cat"], receipt: true) server.new_session(name: "logs", command: ["/bin/cat"]) snapshot = server.snapshot session = snapshot.sessions.where(name: "work").one puts "matching session: #{session.name}" missing = snapshot.sessions.one_or_nil(name: "missing") puts "missing session: #{missing.nil?}" - panes = server.search_panes(where: {id: work.pane.id}) + panes = server.search_panes(where: { id: work.pane.id }) puts "matching pane: #{panes.one.id}" end ``` @@ -227,11 +236,11 @@ require "libtmux" LibTmux::Server.start do |server| server.new_session(name: "work", command: ["/bin/cat"]) - criteria = {active: true} + criteria = { active: true } plan = server.explain_panes(where: criteria) puts "tmux reads: #{plan.fetch(:capture)}" - puts "tmux filters: #{plan.fetch(:pushed) || 'nothing'}" - puts "Ruby filters: #{plan.fetch(:residual).fetch('where').keys.join(', ')}" + puts "tmux filters: #{plan.fetch(:pushed) || "nothing"}" + puts "Ruby filters: #{plan.fetch(:residual).fetch("where").keys.join(", ")}" puts "matching panes: #{server.search_panes(where: criteria).length}" end ``` @@ -261,9 +270,13 @@ effective name from a snapshot. require "libtmux" LibTmux::Server.start do |server| - created = server.new_session( - name: "work", window_name: "main", command: ["/bin/cat"], receipt: true - ) + created = + server.new_session( + name: "work", + window_name: "main", + command: ["/bin/cat"], + receipt: true + ) ref = created.entity.ref puts "session: #{ref.id}" puts "name: #{server.session(ref).snapshot.name}" @@ -352,7 +365,7 @@ def wait_until(message) end end -command = [RbConfig.ruby, "-e", <<~'RUBY'] +greeting_command = [RbConfig.ruby, "-e", <<~'RUBY'] $stdout.sync = true puts "What is your name?" name = STDIN.gets or exit 1 @@ -361,9 +374,12 @@ RUBY LibTmux::Server.start do |server| server.options(scope: :window).set("remain-on-exit", true) - pane = server.new_session( - name: "greeting", command: command, receipt: true - ).pane + pane = + server.new_session( + name: "greeting", + command: greeting_command, + receipt: true + ).pane wait_until("CLI did not prompt for a name") do |remaining| lines = pane.capture(timeout: remaining).text.lines(chomp: true) @@ -372,15 +388,19 @@ LibTmux::Server.start do |server| pane.send_text("Ada") pane.send_keys("Enter") - status = wait_until("CLI did not report an exit status") do |remaining| - state = pane.snapshot(timeout: remaining) - state.dead_status if state.dead? - end + status = + wait_until("CLI did not report an exit status") do |remaining| + state = pane.snapshot(timeout: remaining) + state.dead_status if state.dead? + end raise "CLI exited with status #{status}" unless status == 0 - greeting = pane.capture(start: "-").text.lines(chomp: true).find do |line| - line == "Hello, Ada!" - end + greeting = + pane + .capture(start: "-") + .text + .lines(chomp: true) + .find { |line| line == "Hello, Ada!" } raise "CLI did not greet Ada" unless greeting puts greeting end @@ -449,14 +469,22 @@ program = <<~'RUBY' RUBY LibTmux::Server.start do |server| - pane = server.new_session(name: "reply", command: [Gem.ruby, "-e", program], - receipt: true).pane + pane = + server.new_session( + name: "reply", + command: [Gem.ruby, "-e", program], + receipt: true + ).pane pane.send_text("green") pane.send_keys("Enter") reply = "Reply from the fixture" result = pane.wait_for_text(reply) - puts result.text.lines(chomp: true).map(&:rstrip).find { |line| line == reply } + puts result + .text + .lines(chomp: true) + .map(&:rstrip) + .find { |line| line == reply } end ``` @@ -528,12 +556,16 @@ require "libtmux" LibTmux::Server.start do |server| server.new_session(name: "work", command: ["/bin/cat"]) cancellation = LibTmux::Cancellation.new - waiting = Thread.new do - server.run(["wait-for", "-S", "ready", ";", "wait-for", "held"], - timeout: 5, cancel: cancellation) - rescue LibTmux::Cancelled => error - error - end + waiting = + Thread.new do + server.run( + %w[wait-for -S ready ; wait-for held], + timeout: 5, + cancel: cancellation + ) + rescue LibTmux::Cancelled => error + error + end server.wait_for("ready", timeout: 5) cancellation.cancel failure = waiting.value @@ -583,8 +615,8 @@ LibTmux::Server.start do |server| session.link_window(window.ref, index: 4) session.link_window(window.ref, index: 9) links = session.list_window_links - puts "indexes: #{links.map(&:index).join(', ')}" - puts "windows: #{links.map { |link| link.window.id }.uniq.join(', ')}" + puts "indexes: #{links.map(&:index).join(", ")}" + puts "windows: #{links.map { |link| link.window.id }.uniq.join(", ")}" end ``` @@ -625,7 +657,7 @@ LibTmux::Server.start do |server| puts "history-limit: #{limit.as(:integer)}" puts "inherited: #{limit.inherited?}" session.hooks.set("after-new-window", command: "display-message created") - puts "hook: #{session.hooks.get('after-new-window').as(:string)}" + puts "hook: #{session.hooks.get("after-new-window").as(:string)}" end ``` @@ -723,14 +755,18 @@ require "libtmux" LibTmux::Server.start do |server| server.new_session(name: "work", command: ["/bin/cat"]) - group = server.run_group([ - ["set-option", "-g", "@before", "kept"], - ["select-pane", "-t", "%4294967294"], - ["set-option", "-g", "@after", "never run"] - ]) + group = + server.run_group( + [ + %w[set-option -g @before kept], + %w[select-pane -t %4294967294], + ["set-option", "-g", "@after", "never run"] + ] + ) puts "success: #{group.success?}" - puts "steps: #{group.steps.map { |step| step.fetch(:outcome) }.join(', ')}" - puts "@before: #{server.options(scope: :session).get('@before').as(:string)}" + puts "steps: #{group.steps.map { |step| step.fetch(:outcome) }.join(", ")}" + before = server.options(scope: :session).get("@before").as(:string) + puts "@before: #{before}" end ``` @@ -795,9 +831,10 @@ LibTmux::Server.start do |server| Async do |parent| LibTmux::Async.open(parent: parent, server: server) do |scope| refs = scope.server.list_panes.map(&:ref) - screens = scope.map(refs, concurrency: 2) do |ref| - scope.server.pane(ref).capture - end + screens = + scope.map(refs, concurrency: 2) do |ref| + scope.server.pane(ref).capture + end puts "captured panes: #{screens.length}" puts "all succeeded: #{screens.all?(&:success?)}" end diff --git a/gems/libtmux/lib/libtmux/capabilities.rb b/gems/libtmux/lib/libtmux/capabilities.rb index f6090a83..c8e66eeb 100644 --- a/gems/libtmux/lib/libtmux/capabilities.rb +++ b/gems/libtmux/lib/libtmux/capabilities.rb @@ -8,51 +8,84 @@ module LibTmux # observation after that server changes or closes, never mutation authority. class Capabilities # A native command and the flags a feature depends on. - Command = Data.define(:command, :flags) do - def to_h = super.transform_keys(&:to_s) - private_class_method :new, :[] - end + Command = + Data.define(:command, :flags) do + def to_h = super.transform_keys(&:to_s) + private_class_method :new, :[] + end # A library feature, its requirement, and this daemon's support decision. - Feature = Data.define(:id, :name, :summary, :since, :handling, :error, - :apis, :commands, :except, :supported) do - def supported? = supported + Feature = + Data.define( + :id, + :name, + :summary, + :since, + :handling, + :error, + :apis, + :commands, + :except, + :supported + ) do + def supported? = supported - def to_h - super.transform_keys(&:to_s).merge("handling" => handling.to_s, - "commands" => commands.map(&:to_h)) - end + def to_h + super.transform_keys(&:to_s).merge( + "handling" => handling.to_s, + "commands" => commands.map(&:to_h) + ) + end - private_class_method :new, :[] - end + private_class_method :new, :[] + end # A release-specific repair or refusal, including whether it applies here. - Workaround = Data.define(:id, :name, :summary, :releases, :handling, - :apis, :commands, :active) do - def active? = active + Workaround = + Data.define(:id, :name, :summary, :releases, :handling, :apis, :commands, :active) do + def active? = active - def to_h - super.transform_keys(&:to_s).merge("handling" => handling.to_s, - "commands" => commands.map(&:to_h)) - end + def to_h + super.transform_keys(&:to_s).merge( + "handling" => handling.to_s, + "commands" => commands.map(&:to_h) + ) + end - private_class_method :new, :[] - end + private_class_method :new, :[] + end attr_reader :binding_key, :pid, :start_time, :version, :features, :workarounds def initialize(binding_key:, pid:, start_time:, release:) @binding_key, @pid, @start_time = binding_key.dup.freeze, pid, start_time @version = release.text.dup.freeze - @features = Internal::Capabilities::CAPABILITIES.map do |entry| - Feature.__send__(:new, **entry.to_h.transform_keys(&:to_sym), - error: entry.error, except: entry.except, handling: entry.handling, - commands: commands(entry.commands), supported: entry.available?(release)) - end.freeze - @workarounds = Internal::Capabilities::WORKAROUNDS.map do |entry| - Workaround.__send__(:new, **entry.to_h.transform_keys(&:to_sym), - handling: entry.handling, commands: commands(entry.commands), active: entry.applies?(release)) - end.freeze + @features = + Internal::Capabilities::CAPABILITIES + .map do |entry| + Feature.__send__( + :new, + **entry.to_h.transform_keys(&:to_sym), + error: entry.error, + except: entry.except, + handling: entry.handling, + commands: commands(entry.commands), + supported: entry.available?(release) + ) + end + .freeze + @workarounds = + Internal::Capabilities::WORKAROUNDS + .map do |entry| + Workaround.__send__( + :new, + **entry.to_h.transform_keys(&:to_sym), + handling: entry.handling, + commands: commands(entry.commands), + active: entry.applies?(release) + ) + end + .freeze freeze end private_class_method :new @@ -71,15 +104,24 @@ def workaround(id) # A fresh JSON-compatible projection; its containers do not own the report. def to_h - {"server_identity" => {"generation" => binding_key, "pid" => pid, - "start_time" => start_time, "tmux_version" => version}, - "features" => features.map(&:to_h), "workarounds" => workarounds.map(&:to_h)} + { + "server_identity" => { + "generation" => binding_key, + "pid" => pid, + "start_time" => start_time, + "tmux_version" => version + }, + "features" => features.map(&:to_h), + "workarounds" => workarounds.map(&:to_h) + } end private def commands(entries) - entries.map { |entry| Command.__send__(:new, command: entry.command, flags: entry.flags) }.freeze + entries + .map { |entry| Command.__send__(:new, command: entry.command, flags: entry.flags) } + .freeze end end @@ -96,138 +138,273 @@ module Capabilities ERROR = "LibTmux::UnsupportedFeatureError" # A tmux command and the single-letter flags a record depends on. - Command = Data.define(:command, :flags) do - def initialize(command:, flags: []) - super(command: command, flags: flags.freeze) - end + Command = + Data.define(:command, :flags) do + def initialize(command:, flags: []) + super(command: command, flags: flags.freeze) + end - def to_h - flags.empty? ? {"command" => command} : {"command" => command, "flags" => flags} + def to_h + flags.empty? ? { "command" => command } : { "command" => command, "flags" => flags } + end end - end # Something the library can do from tmux release +since+ on. Below it, # or on an +except+ release, +handling+ says what the library does. - Capability = Data.define(:id, :name, :summary, :since, :handling, :error, :apis, :commands, :except) do - def initialize(id:, name:, summary:, since:, handling:, apis:, commands:, error: nil, except: []) - super(id: id, name: name, summary: summary, since: since, handling: handling, error: error, - apis: apis.freeze, commands: commands.freeze, except: except.freeze) - end + Capability = + Data.define(:id, :name, :summary, :since, :handling, :error, :apis, :commands, :except) do + def initialize( + id:, + name:, + summary:, + since:, + handling:, + apis:, + commands:, + error: nil, + except: [] + ) + super( + id: id, + name: name, + summary: summary, + since: since, + handling: handling, + error: error, + apis: apis.freeze, + commands: commands.freeze, + except: except.freeze + ) + end - # True when +release+ (an Internal::TmuxVersion::Release) offers it. - def available?(release) - release >= Internal::TmuxVersion.parse(since) && !except.include?(release.text) - end + # True when +release+ (an Internal::TmuxVersion::Release) offers it. + def available?(release) + release >= Internal::TmuxVersion.parse(since) && !except.include?(release.text) + end - def to_h - {"id" => id, "name" => name, "summary" => summary, "since" => since, - "handling" => handling.to_s}.tap do |hash| - hash["error"] = error if error - hash["except"] = except unless except.empty? - hash["apis"] = apis - hash["commands"] = commands.map(&:to_h) + def to_h + { + "id" => id, + "name" => name, + "summary" => summary, + "since" => since, + "handling" => handling.to_s + }.tap do |hash| + hash["error"] = error if error + hash["except"] = except unless except.empty? + hash["apis"] = apis + hash["commands"] = commands.map(&:to_h) + end end end - end # A defect on exact tmux releases that the library refuses or repairs. - Workaround = Data.define(:id, :name, :summary, :releases, :handling, :apis, :commands) do - def initialize(id:, name:, summary:, releases:, handling:, apis:, commands:) - super(id: id, name: name, summary: summary, releases: releases.freeze, handling: handling, - apis: apis.freeze, commands: commands.freeze) - end + Workaround = + Data.define(:id, :name, :summary, :releases, :handling, :apis, :commands) do + def initialize(id:, name:, summary:, releases:, handling:, apis:, commands:) + super( + id: id, + name: name, + summary: summary, + releases: releases.freeze, + handling: handling, + apis: apis.freeze, + commands: commands.freeze + ) + end - # True when +release+ is one of the affected releases. - def applies?(release) - releases.include?(release.text) - end + # True when +release+ is one of the affected releases. + def applies?(release) + releases.include?(release.text) + end - def to_h - {"id" => id, "name" => name, "summary" => summary, "releases" => releases, - "handling" => handling.to_s, "apis" => apis, "commands" => commands.map(&:to_h)} + def to_h + { + "id" => id, + "name" => name, + "summary" => summary, + "releases" => releases, + "handling" => handling.to_s, + "apis" => apis, + "commands" => commands.map(&:to_h) + } + end end - end # Public methods that send a tmux command line the caller wrote. The # command guard reads each line, so a capability it consults can refuse # a command through any of them, and only for the command it gates. RUN_CHANNELS = %w[ - LibTmux::Server#run LibTmux::Server#run_group LibTmux::Async::Server#run LibTmux::Async::Server#run_group + LibTmux::Server#run + LibTmux::Server#run_group + LibTmux::Async::Server#run + LibTmux::Async::Server#run_group ].freeze # The control-client channels, which reach a capability only on a tmux # that accepts control clients. - CONTROL_CHANNELS = %w[LibTmux::ControlConnection#exchange LibTmux::Async::ControlConnection#exchange].freeze + 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, + 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: %w[ + 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"], - commands: [Command.new(command: "attach-session")]), - Capability.new(id: "buffer-delete-named", name: "Named buffer deletion", since: "3.4", handling: :refuse, error: ERROR, + apis: %w[LibTmux::Server#open_control LibTmux::Async::Server#open_control], + commands: [Command.new(command: "attach-session")] + ), + Capability.new( + id: "buffer-delete-named", + name: "Named buffer deletion", + since: "3.4", + handling: :refuse, + error: ERROR, summary: "Delete one paste buffer by name without risking another buffer.", - apis: ["LibTmux::Server#delete_buffer", "LibTmux::Async::Server#delete_buffer", *RUN_CHANNELS], - commands: [Command.new(command: "delete-buffer", flags: ["-b"])]), - Capability.new(id: "buffer-rename", name: "Buffer rename", since: "3.4", handling: :refuse, error: ERROR, + apis: [ + "LibTmux::Server#delete_buffer", + "LibTmux::Async::Server#delete_buffer", + *RUN_CHANNELS + ], + commands: [Command.new(command: "delete-buffer", flags: ["-b"])] + ), + Capability.new( + id: "buffer-rename", + name: "Buffer rename", + since: "3.4", + handling: :refuse, + error: ERROR, summary: "Rename a paste buffer without risking another buffer.", apis: RUN_CHANNELS, - commands: [Command.new(command: "set-buffer", flags: ["-b", "-n"])]), - Capability.new(id: "layout-without-checksum", name: "Layouts without a checksum", since: "3.4", - handling: :refuse, error: ERROR, + commands: [Command.new(command: "set-buffer", flags: %w[-b -n])] + ), + Capability.new( + id: "layout-without-checksum", + name: "Layouts without a checksum", + since: "3.4", + handling: :refuse, + error: ERROR, summary: "Apply a layout string or a named layout that tmux validates before use.", apis: ["LibTmux::Window#select_layout", *RUN_CHANNELS], - commands: [Command.new(command: "select-layout")]), - Capability.new(id: "layout-mirrored-main", name: "Mirrored main layouts", since: "3.5", - handling: :refuse, error: ERROR, + commands: [Command.new(command: "select-layout")] + ), + Capability.new( + id: "layout-mirrored-main", + name: "Mirrored main layouts", + since: "3.5", + handling: :refuse, + error: ERROR, summary: "Apply main-horizontal-mirrored and main-vertical-mirrored.", apis: ["LibTmux::Window#select_layout"], - commands: [Command.new(command: "select-layout")]), - Capability.new(id: "layout-json", name: "JSON layout strings", since: "3.8", - handling: :refuse, error: ERROR, + commands: [Command.new(command: "select-layout")] + ), + Capability.new( + id: "layout-json", + name: "JSON layout strings", + since: "3.8", + handling: :refuse, + error: ERROR, summary: "Apply a layout saved in the JSON form tmux reports.", apis: ["LibTmux::Window#select_layout", *RUN_CHANNELS, *CONTROL_CHANNELS], - commands: [Command.new(command: "select-layout")]), - Capability.new(id: "clipboard-query", name: "Clipboard query", since: "3.6a", handling: :refuse, error: ERROR, + commands: [Command.new(command: "select-layout")] + ), + Capability.new( + id: "clipboard-query", + name: "Clipboard query", + since: "3.6a", + handling: :refuse, + error: ERROR, summary: "Ask an attached client's terminal for its clipboard with refresh-client -l.", apis: [*RUN_CHANNELS, *CONTROL_CHANNELS], - commands: [Command.new(command: "refresh-client", flags: ["-l"])]) + commands: [Command.new(command: "refresh-client", flags: ["-l"])] + ) ].freeze WORKAROUNDS = [ - Workaround.new(id: "break-pane-misnames-windows", name: "break-pane window naming", releases: ["3.7"], + Workaround.new( + id: "break-pane-misnames-windows", + name: "break-pane window naming", + releases: ["3.7"], handling: :repair, - summary: "break-pane gets the new window wrong on exactly tmux 3.7; Pane#break_out names it again, and raw break-pane is refused. A nested break-pane is not checked and stops an exact 3.7 daemon: name every one with -n, which avoids the crash while 3.7 still ignores the name, or upgrade to 3.7a.", + summary: + "break-pane gets the new window wrong on exactly tmux 3.7; Pane#break_out names it again, and raw break-pane is refused. A nested break-pane is not checked and stops an exact 3.7 daemon: name every one with -n, which avoids the crash while 3.7 still ignores the name, or upgrade to 3.7a.", apis: ["LibTmux::Pane#break_out", *RUN_CHANNELS, *CONTROL_CHANNELS], - commands: [Command.new(command: "break-pane")]), - Workaround.new(id: "split-window-percent-size", name: "split-window -p", releases: ["3.4"], + commands: [Command.new(command: "break-pane")] + ), + Workaround.new( + id: "split-window-percent-size", + name: "split-window -p", + releases: ["3.4"], handling: :refuse, summary: "split-window -p is broken on tmux 3.4; use -l N%.", apis: RUN_CHANNELS, - commands: [Command.new(command: "split-window", flags: ["-p"])]), - Workaround.new(id: "name-separators-rejected", name: "Colon and dot in names", releases: ["3.7"], + commands: [Command.new(command: "split-window", flags: ["-p"])] + ), + Workaround.new( + id: "name-separators-rejected", + name: "Colon and dot in names", + releases: ["3.7"], handling: :refuse, - summary: "tmux 3.7 rejects ':' and '.' in session and window names; the library refuses them before dispatch, typed or raw.", - apis: ["LibTmux::Server#new_session", "LibTmux::Async::Server#new_session", "LibTmux::Session#new_window", "LibTmux::Session#rename", - "LibTmux::Window#rename", *RUN_CHANNELS], - commands: [Command.new(command: "new-session", flags: ["-s"]), Command.new(command: "new-window", flags: ["-n"]), - Command.new(command: "rename-session"), Command.new(command: "rename-window")]) + summary: + "tmux 3.7 rejects ':' and '.' in session and window names; the library refuses them before dispatch, typed or raw.", + apis: [ + "LibTmux::Server#new_session", + "LibTmux::Async::Server#new_session", + "LibTmux::Session#new_window", + "LibTmux::Session#rename", + "LibTmux::Window#rename", + *RUN_CHANNELS + ], + commands: [ + Command.new(command: "new-session", flags: ["-s"]), + Command.new(command: "new-window", flags: ["-n"]), + Command.new(command: "rename-session"), + Command.new(command: "rename-window") + ] + ) ].freeze module_function # The record gating +id+; raises KeyError for an id the registry lacks. - def capability(id) = CAPABILITIES.find { |entry| entry.id == id } || raise(KeyError, "no capability #{id}") + def capability(id) = + CAPABILITIES.find { |entry| entry.id == id } || raise(KeyError, "no capability #{id}") - def workaround(id) = WORKAROUNDS.find { |entry| entry.id == id } || raise(KeyError, "no workaround #{id}") + def workaround(id) = + WORKAROUNDS.find { |entry| entry.id == id } || raise(KeyError, "no workaround #{id}") # The manifest the docs site reads. The floor is the supported minimum. def manifest - {"schema" => SCHEMA, "port" => PORT, "floor" => {"minimum" => Internal::TmuxVersion::MINIMUM}, - "capabilities" => CAPABILITIES.map(&:to_h), "workarounds" => WORKAROUNDS.map(&:to_h)} + { + "schema" => SCHEMA, + "port" => PORT, + "floor" => { + "minimum" => Internal::TmuxVersion::MINIMUM + }, + "capabilities" => CAPABILITIES.map(&:to_h), + "workarounds" => WORKAROUNDS.map(&:to_h) + } end # The exact text of capabilities.json: deterministic, with a final newline. diff --git a/gems/libtmux/lib/libtmux/capture.rb b/gems/libtmux/lib/libtmux/capture.rb index e1eb37b0..da3462a9 100644 --- a/gems/libtmux/lib/libtmux/capture.rb +++ b/gems/libtmux/lib/libtmux/capture.rb @@ -12,30 +12,52 @@ def initialize(server, binding_key:) @binding_key = binding_key.dup.freeze end - def call(timeout: 5.0, cancel: nil, clients: false, max_bytes: 1 << 20, - max_rows: 10_000, max_field_bytes: 1 << 16) + def call( + timeout: 5.0, + cancel: nil, + clients: false, + max_bytes: 1 << 20, + max_rows: 10_000, + max_field_bytes: 1 << 16 + ) unless timeout.is_a?(Numeric) && timeout.finite? raise ArgumentError, "capture timeout must be finite" end - unless [max_bytes, max_rows, max_field_bytes].all? { |value| value.is_a?(Integer) && value.positive? } + unless [max_bytes, max_rows, max_field_bytes].all? { |value| + value.is_a?(Integer) && value.positive? + } raise ArgumentError, "capture limits must be positive integers" end - unless clients == true || clients == false - raise ArgumentError, "clients must be a Boolean" - end + raise ArgumentError, "clients must be a Boolean" unless clients == true || clients == false if cancel && !(cancel.respond_to?(:cancelled?) && cancel.respond_to?(:reader)) raise ArgumentError, "cancel must be a cancellation token" end started_at = monotonic - budget = {deadline: started_at + timeout, cancel: cancel, max_bytes: max_bytes, - max_rows: max_rows, max_field_bytes: max_field_bytes, bytes: 0, rows: 0, reads: []} + budget = { + deadline: started_at + timeout, + cancel: cancel, + max_bytes: max_bytes, + max_rows: max_rows, + max_field_bytes: max_field_bytes, + bytes: 0, + rows: 0, + reads: [] + } server_info = acquire_server_info(budget) 2.times do |attempt| rows = acquire_rows(budget, attempt + 1, clients) check_budget(budget) begin - snapshot = Snapshot.__send__(:new, rows: rows, binding_key: @binding_key, - started_at: started_at, finished_at: monotonic, reads: budget.fetch(:reads), server_info: server_info) + snapshot = + Snapshot.__send__( + :new, + rows: rows, + binding_key: @binding_key, + started_at: started_at, + finished_at: monotonic, + reads: budget.fetch(:reads), + server_info: server_info + ) check_budget(budget) return snapshot rescue InconsistentSnapshotError @@ -54,7 +76,12 @@ def acquire_server_info(budget) rescue UnsupportedFeatureError => error raise UnsupportedFeatureError.new(error.message, delivery: :observed, phase: :capture) end - identity.merge(capabilities: {metadata: :byte_counted, field_baseline: TmuxVersion::MINIMUM}) + identity.merge( + capabilities: { + metadata: :byte_counted, + field_baseline: TmuxVersion::MINIMUM + } + ) end # The identity travels in the probe's error text so that no user hook fires. @@ -66,8 +93,14 @@ def read_identity(budget) identity = TmuxVersion.parse_daemon_identity(result, marker, phase: :capture) budget[:bytes] += result.stderr.bytesize budget[:rows] += 1 - budget.fetch(:reads) << {source: :server, attempt: 1, started_at: started_at, finished_at: monotonic, - bytes: result.stderr.bytesize, rows: 1} + budget.fetch(:reads) << { + source: :server, + attempt: 1, + started_at: started_at, + finished_at: monotonic, + bytes: result.stderr.bytesize, + rows: 1 + } identity end @@ -77,31 +110,45 @@ def acquire_rows(budget, attempt, clients) # tmux has no windows or panes without a session. Their list commands # nevertheless require a default target, so the complete empty root # supplies this evidence without treating command failures as emptiness. - rows = {session: sessions, window: [], window_link: [], pane: []} + rows = { session: sessions, window: [], window_link: [], pane: [] } rows[:client] = [] if clients return rows end window_fields = Catalog.entity(:window).fields.values link_fields = Catalog.entity(:window_link).fields.values - combined = read(budget, :window_link, attempt, - ["list-windows", "-a", "-F", framing((window_fields + link_fields).map(&:format))], - window_fields.length + link_fields.length) + combined = + read( + budget, + :window_link, + attempt, + ["list-windows", "-a", "-F", framing((window_fields + link_fields).map(&:format))], + window_fields.length + link_fields.length + ) windows = [] links = [] combined.each do |row| windows << window_fields.map(&:name).zip(row.take(window_fields.length)).to_h links << link_fields.map(&:name).zip(row.drop(window_fields.length)).to_h end - rows = {session: sessions, window: windows, window_link: links, - pane: catalog_read(budget, :pane, attempt, ["list-panes", "-a"])} + rows = { + session: sessions, + window: windows, + window_link: links, + pane: catalog_read(budget, :pane, attempt, %w[list-panes -a]) + } rows[:client] = catalog_read(budget, :client, attempt, ["list-clients"]) if clients rows end def catalog_read(budget, kind, attempt, command) fields = Catalog.entity(kind).fields.values - read(budget, kind, attempt, command + ["-F", framing(fields.map(&:format))], fields.length) - .map { |row| fields.map(&:name).zip(row).to_h } + read( + budget, + kind, + attempt, + command + ["-F", framing(fields.map(&:format))], + fields.length + ).map { |row| fields.map(&:name).zip(row).to_h } end def framing(formats) @@ -111,17 +158,35 @@ def framing(formats) def read(budget, source, attempt, argv, field_count) started_at = monotonic remaining = check_budget(budget) - result = @server.__send__(:execute_typed, argv, timeout: remaining, cancel: budget.fetch(:cancel)) + result = + @server.__send__(:execute_typed, argv, timeout: remaining, cancel: budget.fetch(:cancel)) finished_at = monotonic budget[:bytes] += result.stdout.bytesize - capacity("capture exceeds its total byte limit") if budget.fetch(:bytes) > budget.fetch(:max_bytes) + if budget.fetch(:bytes) > budget.fetch(:max_bytes) + capacity("capture exceeds its total byte limit") + end remaining_rows = budget.fetch(:max_rows) - budget.fetch(:rows) - capacity("capture exceeds its total row limit") if remaining_rows <= 0 && !result.stdout.empty? - rows = Metadata.decode(result.stdout, fields: field_count, quoted: true, max_bytes: budget.fetch(:max_bytes), - max_rows: [remaining_rows, 1].max, max_field_bytes: budget.fetch(:max_field_bytes)) + if remaining_rows <= 0 && !result.stdout.empty? + capacity("capture exceeds its total row limit") + end + rows = + Metadata.decode( + result.stdout, + fields: field_count, + quoted: true, + max_bytes: budget.fetch(:max_bytes), + max_rows: [remaining_rows, 1].max, + max_field_bytes: budget.fetch(:max_field_bytes) + ) budget[:rows] += rows.length - budget.fetch(:reads) << {source: source, attempt: attempt, started_at: started_at, - finished_at: finished_at, bytes: result.stdout.bytesize, rows: rows.length} + budget.fetch(:reads) << { + source: source, + attempt: attempt, + started_at: started_at, + finished_at: finished_at, + bytes: result.stdout.bytesize, + rows: rows.length + } rows end @@ -132,7 +197,11 @@ def check_budget(budget) end remaining = budget.fetch(:deadline) - monotonic unless remaining.positive? - raise DeadlineExceeded.new("capture exceeded its deadline", delivery: delivery, phase: :capture) + raise DeadlineExceeded.new( + "capture exceeded its deadline", + delivery: delivery, + phase: :capture + ) end remaining end diff --git a/gems/libtmux/lib/libtmux/catalog.rb b/gems/libtmux/lib/libtmux/catalog.rb index 2ce8fc11..0e4eb6ce 100644 --- a/gems/libtmux/lib/libtmux/catalog.rb +++ b/gems/libtmux/lib/libtmux/catalog.rb @@ -6,10 +6,24 @@ module LibTmux module Internal # Names and bounds are explicit: wire spelling is not Ruby case conversion. module Catalog - Field = Data.define(:id, :name, :wire_name, :type, :nullable, :empty_is_null, :min, :max, - :operators, :format, :min_version, :scope, :capture_requirements) - Relation = Data.define(:name, :wire_name, :target, :cardinality, :nullable, - :capture_requirements) + Field = + Data.define( + :id, + :name, + :wire_name, + :type, + :nullable, + :empty_is_null, + :min, + :max, + :operators, + :format, + :min_version, + :scope, + :capture_requirements + ) + Relation = + Data.define(:name, :wire_name, :target, :cardinality, :nullable, :capture_requirements) Schema = Data.define(:kind, :wire_entity, :fields, :relations) EQUALITY = %i[equals not in].freeze @@ -21,88 +35,388 @@ module Catalog TIME_MAX = (1 << 63) - 1 private_constant :EQUALITY, :INTEGER, :TEXT, :UINT_MAX, :INT_MAX, :TIME_MIN, :TIME_MAX - def self.field(scope, id, name, wire_name, format, type, nullable: false, empty_is_null: false, min: nil, max: nil, operators: nil) - Field.new(id: id, name: name, wire_name: wire_name, format: format, type: type, - nullable: nullable, empty_is_null: empty_is_null, min: min, max: max, - operators: operators || {text: TEXT, integer: INTEGER, boolean: EQUALITY}.fetch(type), - min_version: Internal::TmuxVersion::MINIMUM, scope: scope, capture_requirements: [scope].freeze) + def self.field( + scope, + id, + name, + wire_name, + format, + type, + nullable: false, + empty_is_null: false, + min: nil, + max: nil, + operators: nil + ) + Field.new( + id: id, + name: name, + wire_name: wire_name, + format: format, + type: type, + nullable: nullable, + empty_is_null: empty_is_null, + min: min, + max: max, + operators: operators || { text: TEXT, integer: INTEGER, boolean: EQUALITY }.fetch(type), + min_version: Internal::TmuxVersion::MINIMUM, + scope: scope, + capture_requirements: [scope].freeze + ) end private_class_method :field def self.relation(name, wire_name, target, cardinality, *requirements, nullable: false) - Relation.new(name: name, wire_name: wire_name, target: target, cardinality: cardinality, - nullable: nullable, capture_requirements: requirements.freeze) + Relation.new( + name: name, + wire_name: wire_name, + target: target, + cardinality: cardinality, + nullable: nullable, + capture_requirements: requirements.freeze + ) end private_class_method :relation def self.schema(kind, wire_entity, fields, relations) - Schema.new(kind: kind, wire_entity: wire_entity, + Schema.new( + kind: kind, + wire_entity: wire_entity, fields: fields.to_h { |field| [field.name, field] }.freeze, - relations: relations.to_h { |relation| [relation.name, relation] }.freeze) + relations: relations.to_h { |relation| [relation.name, relation] }.freeze + ) end private_class_method :schema # The minimum supported tmux is the capture baseline, not a claim about first introduction. SCHEMAS = { - session: schema(:session, "session", [ - field(:session, "session.id", :id, "id", "session_id", :text, operators: EQUALITY), - field(:session, "session.name", :name, "name", "session_name", :text), - field(:session, "session.created", :created, "created", "session_created", :integer, min: TIME_MIN, max: TIME_MAX), - field(:session, "session.attached", :attached, "attached", "session_attached", :integer, min: 0, max: UINT_MAX), - field(:session, "session.window_count", :window_count, "windowCount", "session_windows", :integer, min: 0, max: UINT_MAX) - ], [ - relation(:windows, "windows", :window, :many, :window_link, :window), - relation(:window_links, "windowLinks", :window_link, :many, :window_link), - relation(:panes, "panes", :pane, :many, :window_link, :window, :pane), - relation(:current_window, "currentWindow", :window, :one, :window_link, :window, nullable: true) - ]), - window: schema(:window, "window", [ - field(:window, "window.id", :id, "id", "window_id", :text, operators: EQUALITY), - field(:window, "window.name", :name, "name", "window_name", :text), - field(:window, "window.width", :width, "width", "window_width", :integer, min: 0, max: UINT_MAX), - field(:window, "window.height", :height, "height", "window_height", :integer, min: 0, max: UINT_MAX), - field(:window, "window.pane_count", :pane_count, "paneCount", "window_panes", :integer, min: 0, max: UINT_MAX), - field(:window, "window.layout", :layout, "layout", "window_layout", :text) - ], [ - relation(:panes, "panes", :pane, :many, :pane), - relation(:window_links, "windowLinks", :window_link, :many, :window_link), - relation(:active_pane, "activePane", :pane, :one, :pane, nullable: true) - ]), - pane: schema(:pane, "pane", [ - field(:pane, "pane.id", :id, "id", "pane_id", :text, operators: EQUALITY), - field(:pane, "pane.window_id", :window_id, "windowId", "window_id", :text, operators: EQUALITY), - field(:pane, "pane.index", :index, "index", "pane_index", :integer, min: 0, max: UINT_MAX), - field(:pane, "pane.pid", :pid, "pid", "pane_pid", :integer, nullable: true, empty_is_null: true, min: 0, max: INT_MAX), - field(:pane, "pane.current_command", :current_command, "currentCommand", "pane_current_command", :text), - field(:pane, "pane.current_path", :current_path, "currentPath", "pane_current_path", :text, nullable: true, empty_is_null: true), - field(:pane, "pane.title", :title, "title", "pane_title", :text), - field(:pane, "pane.active", :active, "active", "pane_active", :boolean), - field(:pane, "pane.dead", :dead, "dead", "pane_dead", :boolean), - field(:pane, "pane.dead_status", :dead_status, "deadStatus", "pane_dead_status", :integer, nullable: true, empty_is_null: true, min: 0, max: 255), - field(:pane, "pane.width", :width, "width", "pane_width", :integer, min: 0, max: UINT_MAX), - field(:pane, "pane.height", :height, "height", "pane_height", :integer, min: 0, max: UINT_MAX) - ], [relation(:window, "window", :window, :one, :window)]), - window_link: schema(:window_link, "window_link", [ - field(:window_link, "window_link.session_id", :session_id, "sessionId", "session_id", :text, operators: EQUALITY), - field(:window_link, "window_link.window_id", :window_id, "windowId", "window_id", :text, operators: EQUALITY), - field(:window_link, "window_link.index", :index, "index", "window_index", :integer, min: 0, max: INT_MAX), - field(:window_link, "window_link.active", :active, "active", "window_active", :boolean) - ], [ - relation(:session, "session", :session, :one, :session), - relation(:window, "window", :window, :one, :window) - ]), - client: schema(:client, "client", [ - field(:client, "client.name", :name, "name", "client_name", :text), - field(:client, "client.pid", :pid, "pid", "client_pid", :integer, min: 0, max: INT_MAX), - field(:client, "client.created", :created, "created", "client_created", :integer, min: TIME_MIN, max: TIME_MAX), - field(:client, "client.tty", :tty, "tty", "client_tty", :text, nullable: true, empty_is_null: true), - field(:client, "client.session_id", :session_id, "sessionId", "session_id", :text, nullable: true, empty_is_null: true, operators: EQUALITY), - field(:client, "client.width", :width, "width", "client_width", :integer, min: 0, max: UINT_MAX), - field(:client, "client.height", :height, "height", "client_height", :integer, nullable: true, empty_is_null: true, min: 0, max: UINT_MAX), - field(:client, "client.read_only", :read_only, "readOnly", "client_readonly", :boolean), - field(:client, "client.utf8", :utf8, "utf8", "client_utf8", :boolean), - field(:client, "client.control_mode", :control_mode, "controlMode", "client_control_mode", :boolean) - ], [relation(:session, "session", :session, :one, :session, nullable: true)]) + session: + schema( + :session, + "session", + [ + field(:session, "session.id", :id, "id", "session_id", :text, operators: EQUALITY), + field(:session, "session.name", :name, "name", "session_name", :text), + field( + :session, + "session.created", + :created, + "created", + "session_created", + :integer, + min: TIME_MIN, + max: TIME_MAX + ), + field( + :session, + "session.attached", + :attached, + "attached", + "session_attached", + :integer, + min: 0, + max: UINT_MAX + ), + field( + :session, + "session.window_count", + :window_count, + "windowCount", + "session_windows", + :integer, + min: 0, + max: UINT_MAX + ) + ], + [ + relation(:windows, "windows", :window, :many, :window_link, :window), + relation(:window_links, "windowLinks", :window_link, :many, :window_link), + relation(:panes, "panes", :pane, :many, :window_link, :window, :pane), + relation( + :current_window, + "currentWindow", + :window, + :one, + :window_link, + :window, + nullable: true + ) + ] + ), + window: + schema( + :window, + "window", + [ + field(:window, "window.id", :id, "id", "window_id", :text, operators: EQUALITY), + field(:window, "window.name", :name, "name", "window_name", :text), + field( + :window, + "window.width", + :width, + "width", + "window_width", + :integer, + min: 0, + max: UINT_MAX + ), + field( + :window, + "window.height", + :height, + "height", + "window_height", + :integer, + min: 0, + max: UINT_MAX + ), + field( + :window, + "window.pane_count", + :pane_count, + "paneCount", + "window_panes", + :integer, + min: 0, + max: UINT_MAX + ), + field(:window, "window.layout", :layout, "layout", "window_layout", :text) + ], + [ + relation(:panes, "panes", :pane, :many, :pane), + relation(:window_links, "windowLinks", :window_link, :many, :window_link), + relation(:active_pane, "activePane", :pane, :one, :pane, nullable: true) + ] + ), + pane: + schema( + :pane, + "pane", + [ + field(:pane, "pane.id", :id, "id", "pane_id", :text, operators: EQUALITY), + field( + :pane, + "pane.window_id", + :window_id, + "windowId", + "window_id", + :text, + operators: EQUALITY + ), + field( + :pane, + "pane.index", + :index, + "index", + "pane_index", + :integer, + min: 0, + max: UINT_MAX + ), + field( + :pane, + "pane.pid", + :pid, + "pid", + "pane_pid", + :integer, + nullable: true, + empty_is_null: true, + min: 0, + max: INT_MAX + ), + field( + :pane, + "pane.current_command", + :current_command, + "currentCommand", + "pane_current_command", + :text + ), + field( + :pane, + "pane.current_path", + :current_path, + "currentPath", + "pane_current_path", + :text, + nullable: true, + empty_is_null: true + ), + field(:pane, "pane.title", :title, "title", "pane_title", :text), + field(:pane, "pane.active", :active, "active", "pane_active", :boolean), + field(:pane, "pane.dead", :dead, "dead", "pane_dead", :boolean), + field( + :pane, + "pane.dead_status", + :dead_status, + "deadStatus", + "pane_dead_status", + :integer, + nullable: true, + empty_is_null: true, + min: 0, + max: 255 + ), + field( + :pane, + "pane.width", + :width, + "width", + "pane_width", + :integer, + min: 0, + max: UINT_MAX + ), + field( + :pane, + "pane.height", + :height, + "height", + "pane_height", + :integer, + min: 0, + max: UINT_MAX + ) + ], + [relation(:window, "window", :window, :one, :window)] + ), + window_link: + schema( + :window_link, + "window_link", + [ + field( + :window_link, + "window_link.session_id", + :session_id, + "sessionId", + "session_id", + :text, + operators: EQUALITY + ), + field( + :window_link, + "window_link.window_id", + :window_id, + "windowId", + "window_id", + :text, + operators: EQUALITY + ), + field( + :window_link, + "window_link.index", + :index, + "index", + "window_index", + :integer, + min: 0, + max: INT_MAX + ), + field( + :window_link, + "window_link.active", + :active, + "active", + "window_active", + :boolean + ) + ], + [ + relation(:session, "session", :session, :one, :session), + relation(:window, "window", :window, :one, :window) + ] + ), + client: + schema( + :client, + "client", + [ + field(:client, "client.name", :name, "name", "client_name", :text), + field( + :client, + "client.pid", + :pid, + "pid", + "client_pid", + :integer, + min: 0, + max: INT_MAX + ), + field( + :client, + "client.created", + :created, + "created", + "client_created", + :integer, + min: TIME_MIN, + max: TIME_MAX + ), + field( + :client, + "client.tty", + :tty, + "tty", + "client_tty", + :text, + nullable: true, + empty_is_null: true + ), + field( + :client, + "client.session_id", + :session_id, + "sessionId", + "session_id", + :text, + nullable: true, + empty_is_null: true, + operators: EQUALITY + ), + field( + :client, + "client.width", + :width, + "width", + "client_width", + :integer, + min: 0, + max: UINT_MAX + ), + field( + :client, + "client.height", + :height, + "height", + "client_height", + :integer, + nullable: true, + empty_is_null: true, + min: 0, + max: UINT_MAX + ), + field( + :client, + "client.read_only", + :read_only, + "readOnly", + "client_readonly", + :boolean + ), + field(:client, "client.utf8", :utf8, "utf8", "client_utf8", :boolean), + field( + :client, + "client.control_mode", + :control_mode, + "controlMode", + "client_control_mode", + :boolean + ) + ], + [relation(:session, "session", :session, :one, :session, nullable: true)] + ) }.freeze private_constant :SCHEMAS diff --git a/gems/libtmux/lib/libtmux/child.rb b/gems/libtmux/lib/libtmux/child.rb index ed145233..d8ba3646 100644 --- a/gems/libtmux/lib/libtmux/child.rb +++ b/gems/libtmux/lib/libtmux/child.rb @@ -73,7 +73,9 @@ def join(timeout) def signal(name) @mutex.synchronize do - return nil unless @pid && !@signalling_finished && !@observation_error.is_a?(Errno::ECHILD) + unless @pid && !@signalling_finished && !@observation_error.is_a?(Errno::ECHILD) + return nil + end Process.kill(name, @pid) end @@ -98,7 +100,9 @@ def close end def detach - raise ArgumentError, "only a forked child may detach its observer" if Process.pid == @creator_pid + if Process.pid == @creator_pid + raise ArgumentError, "only a forked child may detach its observer" + end [@reader, @writer].each { |io| io.close unless io.closed? } end diff --git a/gems/libtmux/lib/libtmux/control.rb b/gems/libtmux/lib/libtmux/control.rb index 6a221f5b..b15da28c 100644 --- a/gems/libtmux/lib/libtmux/control.rb +++ b/gems/libtmux/lib/libtmux/control.rb @@ -53,11 +53,29 @@ def inspect end class ControlEvent - attr_reader :kind, :raw, :data, :pane_id, :sequence, :generation, - :lost_sequences, :dropped_bytes, :reason, :previous_generation - - def initialize(kind:, raw:, data: nil, pane_id: nil, sequence: nil, generation: nil, - lost_sequences: nil, dropped_bytes: 0, reason: nil, previous_generation: nil) + attr_reader :kind, + :raw, + :data, + :pane_id, + :sequence, + :generation, + :lost_sequences, + :dropped_bytes, + :reason, + :previous_generation + + def initialize( + kind:, + raw:, + data: nil, + pane_id: nil, + sequence: nil, + generation: nil, + lost_sequences: nil, + dropped_bytes: 0, + reason: nil, + previous_generation: nil + ) @kind, @raw, @data = kind, raw.b.freeze, data&.b&.freeze @pane_id, @sequence, @generation = pane_id&.dup&.freeze, sequence, generation&.dup&.freeze @lost_sequences, @dropped_bytes = lost_sequences&.dup&.freeze, dropped_bytes @@ -79,7 +97,11 @@ class SubscriptionOverflow < CapacityError def initialize(sequence:) @sequence = sequence - super("control subscription exceeded its buffer limit", delivery: :observed, phase: :subscription) + super( + "control subscription exceeded its buffer limit", + delivery: :observed, + phase: :subscription + ) end end @@ -87,11 +109,19 @@ class ControlSubscription include Enumerable attr_reader :generation - def initialize(max_bytes: 1 << 20, max_events: 1024, mode: :reliable, pane_id: nil, generation: nil) + def initialize( + max_bytes: 1 << 20, + max_events: 1024, + mode: :reliable, + pane_id: nil, + generation: nil + ) unless [max_bytes, max_events].all? { |limit| limit.is_a?(Integer) && limit.positive? } raise ArgumentError, "subscription limits must be positive integers" end - raise ArgumentError, "subscription mode must be reliable or tail" unless [:reliable, :tail].include?(mode) + unless %i[reliable tail].include?(mode) + raise ArgumentError, "subscription mode must be reliable or tail" + end @max_bytes, @max_events, @mode, @pane_id = max_bytes, max_events, mode, pane_id @owner_pid = Process.pid @@ -121,7 +151,9 @@ def next(timeout: nil) raise StopIteration if @closed remaining = deadline && deadline - clock - raise DeadlineExceeded.new("control event deadline elapsed", phase: :subscription) if remaining && remaining <= 0 + if remaining && remaining <= 0 + raise DeadlineExceeded.new("control event deadline elapsed", phase: :subscription) + end @changed.wait(@mutex, remaining) end @@ -132,11 +164,12 @@ def each return enum_for(__method__) unless block_given? while true - event = begin - self.next - rescue StopIteration - break - end + event = + begin + self.next + rescue StopIteration + break + end yield event end self @@ -163,21 +196,31 @@ def closed? def diagnostics ensure_owner @mutex.synchronize do - {queued_events: @queue.length, retained_event_bytes: @bytes, - gap_pending: !@gap.nil?, overflowed: @failure.is_a?(SubscriptionOverflow), - closed: @closed, mode: @mode, - limits: {max_bytes: @max_bytes, max_events: @max_events}.freeze}.freeze + { + queued_events: @queue.length, + retained_event_bytes: @bytes, + gap_pending: !@gap.nil?, + overflowed: @failure.is_a?(SubscriptionOverflow), + closed: @closed, + mode: @mode, + limits: { max_bytes: @max_bytes, max_events: @max_events }.freeze + }.freeze end end def inspect - "#<#{self.class} mode=#{@mode} #{@closed ? 'closed' : 'open'}>" + "#<#{self.class} mode=#{@mode} #{@closed ? "closed" : "open"}>" end private def ensure_owner - raise ClosedError.new("control subscription belongs to another process", phase: :subscription) unless Process.pid == @owner_pid + unless Process.pid == @owner_pid + raise ClosedError.new( + "control subscription belongs to another process", + phase: :subscription + ) + end end def clock @@ -192,11 +235,13 @@ def publish(event) @mutex.synchronize do return if @closed - if @mode == :reliable && (@bytes + event.bytesize > @max_bytes || @queue.length >= @max_events) + if @mode == :reliable && + (@bytes + event.bytesize > @max_bytes || @queue.length >= @max_events) @failure = SubscriptionOverflow.new(sequence: event.sequence) @closed = true else - while !@queue.empty? && (@bytes + event.bytesize > @max_bytes || @queue.length >= @max_events) + while !@queue.empty? && + (@bytes + event.bytesize > @max_bytes || @queue.length >= @max_events) dropped = @queue.shift @bytes -= dropped.bytesize record_gap(dropped) @@ -222,11 +267,20 @@ def finish(failure = nil) def record_gap(event) first = @gap ? @gap.lost_sequences.first : event.sequence - unknown_loss = (@gap && @gap.dropped_bytes.nil?) || (event.kind == :gap && event.dropped_bytes.nil?) + unknown_loss = + (@gap && @gap.dropped_bytes.nil?) || (event.kind == :gap && event.dropped_bytes.nil?) bytes = unknown_loss ? nil : (@gap&.dropped_bytes || 0) + event.bytesize - @gap = ControlEvent.new(kind: :gap, raw: "".b, sequence: event.sequence, - generation: event.generation, lost_sequences: [first, event.sequence], dropped_bytes: bytes, - reason: :overflow, previous_generation: @gap&.previous_generation || event.previous_generation) + @gap = + ControlEvent.new( + kind: :gap, + raw: "".b, + sequence: event.sequence, + generation: event.generation, + lost_sequences: [first, event.sequence], + dropped_bytes: bytes, + reason: :overflow, + previous_generation: @gap&.previous_generation || event.previous_generation + ) end end @@ -245,35 +299,53 @@ def initialize(max_line_bytes: 1 << 18, max_frame_bytes: 1 << 20) def feed(bytes) # Callers feed bounded read chunks; retained data is checked per line. - bytes.b.each_line("\n") do |part| - @pending << part - raise CapacityError.new("control line exceeds its byte limit", phase: :read) if @pending.bytesize > @max_line - next unless @pending.end_with?("\n") - - line, @pending = @pending, +"".b - match = GUARD.match(line) - tuple = match && match.captures.drop(1).map(&:to_i) - if @guard - @frame_bytes += line.bytesize - raise CapacityError.new("control frame exceeds its byte limit", phase: :read) if @frame_bytes > @max_frame - - if match && match[1] != "begin" && tuple == @guard - yield GuardedBlock.new(guard: @guard, body: @body, - terminator: match[1].to_sym, bytesize: @frame_bytes, opening: @opening, closing: line) - @guard = @body = nil - else - @body << line + bytes + .b + .each_line("\n") do |part| + @pending << part + if @pending.bytesize > @max_line + raise CapacityError.new("control line exceeds its byte limit", phase: :read) end - elsif match - raise ProtocolError.new("control closing guard has no opening guard", phase: :read) unless match[1] == "begin" + next unless @pending.end_with?("\n") + + line, @pending = @pending, +"".b + match = GUARD.match(line) + tuple = match && match.captures.drop(1).map(&:to_i) + if @guard + @frame_bytes += line.bytesize + if @frame_bytes > @max_frame + raise CapacityError.new("control frame exceeds its byte limit", phase: :read) + end - @guard, @body, @frame_bytes = tuple, +"".b, line.bytesize - @opening = line - raise CapacityError.new("control frame exceeds its byte limit", phase: :read) if @frame_bytes > @max_frame - else - yield event(line) + if match && match[1] != "begin" && tuple == @guard + yield( + GuardedBlock.new( + guard: @guard, + body: @body, + terminator: match[1].to_sym, + bytesize: @frame_bytes, + opening: @opening, + closing: line + ) + ) + @guard = @body = nil + else + @body << line + end + elsif match + unless match[1] == "begin" + raise ProtocolError.new("control closing guard has no opening guard", phase: :read) + end + + @guard, @body, @frame_bytes = tuple, +"".b, line.bytesize + @opening = line + if @frame_bytes > @max_frame + raise CapacityError.new("control frame exceeds its byte limit", phase: :read) + end + else + yield event(line) + end end - end end def finish @@ -292,8 +364,13 @@ def event(line) elsif line.start_with?("%output ", "%extended-output ") raise ProtocolError.new("malformed control output event", phase: :read) elsif (match = /\A%(pause|continue) (%[0-9]+)\n\z/n.match(line)) - ControlEvent.new(kind: :gap, raw: line, pane_id: match[2], - reason: match[1] == "pause" ? :pause : :resume, dropped_bytes: nil) + ControlEvent.new( + kind: :gap, + raw: line, + pane_id: match[2], + reason: match[1] == "pause" ? :pause : :resume, + dropped_bytes: nil + ) elsif line.start_with?("%pause ", "%continue ") raise ProtocolError.new("malformed control flow event", phase: :read) else @@ -329,8 +406,24 @@ module CleanupDetails attr_reader :control_cleanup_errors end - Request = Struct.new(:id, :wire, :offset, :start_marker, :end_marker, :started, - :blocks, :bytes, :reader, :writer, :result, :error, :flow, :flow_reported, keyword_init: true) + Request = + Struct.new( + :id, + :wire, + :offset, + :start_marker, + :end_marker, + :started, + :blocks, + :bytes, + :reader, + :writer, + :result, + :error, + :flow, + :flow_reported, + keyword_init: true + ) private_constant :Request, :CleanupDetails attr_reader :pid, :generation, :previous_generation, :events, :cleanup_errors @@ -379,25 +472,47 @@ def self.attach_cleanup_details(error, details) # the connection; callers never hold a binding to pass here. private_class_method :new, :open - def initialize(binding:, session_id:, reconnect: nil, max_requests: 32, max_command_bytes: 1 << 18, - max_queue_bytes: 1 << 20, max_line_bytes: 1 << 18, max_reply_bytes: 1 << 20, - max_stderr_bytes: 1 << 18, max_subscriptions: 32) - initialize_state(binding_key: binding.key, session_id: session_id, reconnect: reconnect, - max_requests: max_requests, max_command_bytes: max_command_bytes, - max_queue_bytes: max_queue_bytes, max_line_bytes: max_line_bytes, max_reply_bytes: max_reply_bytes, - max_stderr_bytes: max_stderr_bytes, max_subscriptions: max_subscriptions) + def initialize( + binding:, + session_id:, + reconnect: nil, + max_requests: 32, + max_command_bytes: 1 << 18, + max_queue_bytes: 1 << 20, + max_line_bytes: 1 << 18, + max_reply_bytes: 1 << 20, + max_stderr_bytes: 1 << 18, + max_subscriptions: 32 + ) + initialize_state( + binding_key: binding.key, + session_id: session_id, + reconnect: reconnect, + max_requests: max_requests, + max_command_bytes: max_command_bytes, + max_queue_bytes: max_queue_bytes, + max_line_bytes: max_line_bytes, + max_reply_bytes: max_reply_bytes, + max_stderr_bytes: max_stderr_bytes, + max_subscriptions: max_subscriptions + ) error = nil begin Thread.handle_interrupt(Exception => :never) do begin process_wait = Internal::ProcessWait.new prefix = binding.command_prefix - release = binding.release || Internal::TmuxVersion.connected(prefix) do |probe| - Internal::ProcessExecutor.new.run(probe, timeout: 5.0) - end + release = + binding.release || + Internal::TmuxVersion.connected(prefix) do |probe| + Internal::ProcessExecutor.new.run(probe, timeout: 5.0) + end Internal::TmuxVersion.require_control(release) @release = release - @pin = Internal::SocketIdentity.new(Endpoint.new(socket_path: prefix.last, executable: prefix.first)) + @pin = + Internal::SocketIdentity.new( + Endpoint.new(socket_path: prefix.last, executable: prefix.first) + ) @wake_reader, @wake_writer = pipe input_reader, @input = pipe @output, output_writer = pipe @@ -406,9 +521,19 @@ def initialize(binding:, session_id:, reconnect: nil, max_requests: 32, max_comm @exit_reader = @child.reader @resources << @exit_reader begin - @pid = Process.spawn({"TMUX" => nil, "TMUX_PANE" => nil}, - *@pin.command_prefix, "-C", "attach-session", "-t", session_id, - in: input_reader, out: output_writer, err: error_writer, close_others: true) + @pid = + Process.spawn( + { "TMUX" => nil, "TMUX_PANE" => nil }, + *@pin.command_prefix, + "-C", + "attach-session", + "-t", + session_id, + in: input_reader, + out: output_writer, + err: error_writer, + close_others: true + ) ensure @child.spawned(@pid) end @@ -418,7 +543,10 @@ def initialize(binding:, session_id:, reconnect: nil, max_requests: 32, max_comm rescue Exception => failure error = failure if @worker - @mutex.synchronize { @stopping = true; wake(@wake_writer) } + @mutex.synchronize do + @stopping = true + wake(@wake_writer) + end @worker.join(0.5) else cleanup @@ -428,7 +556,9 @@ def initialize(binding:, session_id:, reconnect: nil, max_requests: 32, max_comm rescue Exception => deferred error ||= deferred end - self.class.send(:attach_cleanup_details, error, @cleanup_errors) if error && !@cleanup_errors.empty? + if error && !@cleanup_errors.empty? + self.class.send(:attach_cleanup_details, error, @cleanup_errors) + end raise error if error end @@ -439,12 +569,15 @@ def exchange(line, timeout: 5, cancel: nil) def exchange_request(line, timeout:, cancel:, flow: nil) ensure_owner unless line.is_a?(String) && !line.empty? && !line.b.match?(/[\x00\r\n]/n) - raise ArgumentError, "control input must be one nonempty raw command line without NUL or line endings" + raise ArgumentError, + "control input must be one nonempty raw command line without NUL or line endings" end unless timeout.is_a?(Numeric) && timeout.finite? && timeout.positive? raise ArgumentError, "control timeout must be positive and finite" end - raise CapacityError.new("control command exceeds its byte limit", phase: :admission) if line.bytesize > @max_command + if line.bytesize > @max_command + raise CapacityError.new("control command exceeds its byte limit", phase: :admission) + end # A raw line reaches the daemon like Server#run's argv, so it gets the # same literal-command refusals. @@ -478,7 +611,13 @@ def exchange_request(line, timeout:, cancel:, flow: nil) begin abort_request(request, Cancelled, "control request interrupted") rescue Exception => cleanup - self.class.send(:attach_cleanup_details, error, ["control request cleanup failed (#{cleanup.class})"]) if error + if error + self.class.send( + :attach_cleanup_details, + error, + ["control request cleanup failed (#{cleanup.class})"] + ) + end error ||= cleanup ensure @mutex.synchronize do @@ -513,13 +652,23 @@ def subscribe(pane_id: nil, mode: :reliable, max_bytes: 1 << 20, max_events: 102 raise ArgumentError, "pane subscription must use an exact pane ID" end @mutex.synchronize do - raise ClosedError.new("control connection is closed", phase: :admission) if @stopping || @finished + if @stopping || @finished + raise ClosedError.new("control connection is closed", phase: :admission) + end @subscriptions.reject!(&:closed?) - raise CapacityError.new("control subscription limit reached", phase: :admission) if @subscriptions.length >= @max_subscriptions + if @subscriptions.length >= @max_subscriptions + raise CapacityError.new("control subscription limit reached", phase: :admission) + end - subscription = build_subscription(pane_id: pane_id, mode: mode, max_bytes: max_bytes, max_events: max_events, - generation: @generation) + subscription = + build_subscription( + pane_id: pane_id, + mode: mode, + max_bytes: max_bytes, + max_events: max_events, + generation: @generation + ) subscription.send(:publish, @reconnect_gap) if @reconnect_gap @subscriptions << subscription subscription @@ -541,10 +690,21 @@ def close(timeout: 0.5) Thread.handle_interrupt(Exception => :never) do request_close unless !@worker || @worker.join(timeout) - failure = TransportError.new("control reader did not retire within its cleanup deadline", phase: :cleanup, pid: @pid) + failure = + TransportError.new( + "control reader did not retire within its cleanup deadline", + phase: :cleanup, + pid: @pid + ) end unless @cleanup_errors.empty? - failure ||= TransportError.new("control cleanup failed", phase: :cleanup, pid: @pid, cleanup_errors: @cleanup_errors) + failure ||= + TransportError.new( + "control cleanup failed", + phase: :cleanup, + pid: @pid, + cleanup_errors: @cleanup_errors + ) end end rescue Exception => deferred @@ -566,36 +726,63 @@ def closed? def diagnostics ensure_owner @mutex.synchronize do - {admitted_requests: @request_pipes.length, incomplete_requests: @requests.length, - queued_requests: @queue.length, writing_requests: @writing ? 1 : 0, - awaiting_reply: @replies.length, reserved_wire_bytes: @queued_bytes, - retained_reply_bytes: @retained_reply_bytes, stderr_received_bytes: @stderr_bytes, - subscription_count: @subscriptions.length, stopping: !!@stopping, - finished: !!@finished, cleanup_error_count: @cleanup_errors.length, - limits: @diagnostic_limits}.freeze + { + admitted_requests: @request_pipes.length, + incomplete_requests: @requests.length, + queued_requests: @queue.length, + writing_requests: @writing ? 1 : 0, + awaiting_reply: @replies.length, + reserved_wire_bytes: @queued_bytes, + retained_reply_bytes: @retained_reply_bytes, + stderr_received_bytes: @stderr_bytes, + subscription_count: @subscriptions.length, + stopping: !!@stopping, + finished: !!@finished, + cleanup_error_count: @cleanup_errors.length, + limits: @diagnostic_limits + }.freeze end end def inspect - "#<#{self.class} pid=#{@pid} generation=#{@generation} #{@stopping || @finished ? 'closed' : 'open'}>" + "#<#{self.class} pid=#{@pid} generation=#{@generation} #{@stopping || @finished ? "closed" : "open"}>" end private - def initialize_state(binding_key:, session_id:, reconnect: nil, max_requests: 32, max_command_bytes: 1 << 18, - max_queue_bytes: 1 << 20, max_line_bytes: 1 << 18, max_reply_bytes: 1 << 20, - max_stderr_bytes: 1 << 18, max_subscriptions: 32) + def initialize_state( + binding_key:, + session_id:, + reconnect: nil, + max_requests: 32, + max_command_bytes: 1 << 18, + max_queue_bytes: 1 << 20, + max_line_bytes: 1 << 18, + max_reply_bytes: 1 << 20, + max_stderr_bytes: 1 << 18, + max_subscriptions: 32 + ) unless session_id.is_a?(String) && /\A\$[0-9]+\z/.match?(session_id) raise ArgumentError, "control session must be an exact session ID" end - limits = [max_requests, max_command_bytes, max_queue_bytes, max_line_bytes, - max_reply_bytes, max_stderr_bytes, max_subscriptions] - raise ArgumentError, "control limits must be positive integers" unless limits.all? { |n| n.is_a?(Integer) && n.positive? } + limits = [ + max_requests, + max_command_bytes, + max_queue_bytes, + max_line_bytes, + max_reply_bytes, + max_stderr_bytes, + max_subscriptions + ] + unless limits.all? { |n| n.is_a?(Integer) && n.positive? } + raise ArgumentError, "control limits must be positive integers" + end if reconnect unless reconnect.is_a?(ControlConnection) && reconnect.closed? && - reconnect.instance_variable_get(:@binding_key) == binding_key && - reconnect.instance_variable_get(:@session_id) == session_id - raise ArgumentError, "reconnect requires a retired control connection for the same binding and session" + reconnect.instance_variable_get(:@binding_key) == binding_key && + reconnect.instance_variable_get(:@session_id) == session_id + raise ArgumentError, + "reconnect requires a retired control connection for the same binding and session" end @previous_generation = reconnect.generation end @@ -608,16 +795,36 @@ def initialize_state(binding_key:, session_id:, reconnect: nil, max_requests: 32 @next_id, @queued_bytes, @sequence, @retained_reply_bytes = 0, 0, 0, 0 if @previous_generation @sequence += 1 - @reconnect_gap = ControlEvent.new(kind: :gap, raw: "".b, sequence: @sequence, - generation: @generation, previous_generation: @previous_generation, reason: :reconnect, dropped_bytes: nil) + @reconnect_gap = + ControlEvent.new( + kind: :gap, + raw: "".b, + sequence: @sequence, + generation: @generation, + previous_generation: @previous_generation, + reason: :reconnect, + dropped_bytes: nil + ) end @max_requests, @max_command, @max_queue = max_requests, max_command_bytes, max_queue_bytes - @max_reply, @max_stderr, @max_subscriptions = max_reply_bytes, max_stderr_bytes, max_subscriptions - @diagnostic_limits = {max_requests: max_requests, max_command_bytes: max_command_bytes, - max_queue_bytes: max_queue_bytes, max_line_bytes: max_line_bytes, - max_reply_bytes: max_reply_bytes, max_stderr_bytes: max_stderr_bytes, - max_subscriptions: max_subscriptions}.freeze - @parser = Internal::ControlParser.new(max_line_bytes: max_line_bytes, max_frame_bytes: max_reply_bytes) + @max_reply, @max_stderr, @max_subscriptions = + max_reply_bytes, + max_stderr_bytes, + max_subscriptions + @diagnostic_limits = { + max_requests: max_requests, + max_command_bytes: max_command_bytes, + max_queue_bytes: max_queue_bytes, + max_line_bytes: max_line_bytes, + max_reply_bytes: max_reply_bytes, + max_stderr_bytes: max_stderr_bytes, + max_subscriptions: max_subscriptions + }.freeze + @parser = + Internal::ControlParser.new( + max_line_bytes: max_line_bytes, + max_frame_bytes: max_reply_bytes + ) @stderr_bytes, @cleanup_errors = 0, [].freeze @events = subscribe end @@ -631,11 +838,18 @@ def change_output(pane_id, state, timeout, cancel) raise ArgumentError, "control output target must be an exact pane ID" end flow = [pane_id.dup.freeze, state == "pause" ? :pause : :resume].freeze - exchange_request("refresh-client -A '#{pane_id}:#{state}'", timeout: timeout, cancel: cancel, flow: flow) + exchange_request( + "refresh-client -A '#{pane_id}:#{state}'", + timeout: timeout, + cancel: cancel, + flow: flow + ) end def ensure_owner - raise ClosedError.new("control connection belongs to another process", phase: :admission) unless Process.pid == @owner_pid + unless Process.pid == @owner_pid + raise ClosedError.new("control connection belongs to another process", phase: :admission) + end end def clock @@ -643,12 +857,18 @@ def clock end def pipe - IO.pipe.tap { |pair| @resources.concat(pair); pair.each(&:binmode) } + IO.pipe.tap do |pair| + @resources.concat(pair) + pair.each(&:binmode) + end end def request_close ensure_owner - @mutex.synchronize { @stopping = true; wake(@wake_writer) } + @mutex.synchronize do + @stopping = true + wake(@wake_writer) + end nil end @@ -678,8 +898,12 @@ def abort_request(request, type, message) def admit(line, cancel, flow: nil) @mutex.synchronize do - raise ClosedError.new("control connection is closed", phase: :admission) if @stopping || @finished - raise Cancelled.new("control request cancelled before admission", phase: :admission) if cancel&.cancelled? + if @stopping || @finished + raise ClosedError.new("control connection is closed", phase: :admission) + end + if cancel&.cancelled? + raise Cancelled.new("control request cancelled before admission", phase: :admission) + end start_marker = "libtmux_boundary_#{SecureRandom.hex(24)}" end_marker = "libtmux_boundary_#{SecureRandom.hex(24)}" @@ -689,9 +913,20 @@ def admit(line, cancel, flow: nil) end reader, writer = IO.pipe begin - request = Request.new(id: (@next_id += 1), wire: wire, offset: 0, - start_marker: start_marker, end_marker: end_marker, started: false, - blocks: [], bytes: 0, reader: reader, writer: writer, flow: flow) + request = + Request.new( + id: (@next_id += 1), + wire: wire, + offset: 0, + start_marker: start_marker, + end_marker: end_marker, + started: false, + blocks: [], + bytes: 0, + reader: reader, + writer: writer, + flow: flow + ) rescue Exception [reader, writer].each { |io| io.close unless io.closed? } raise @@ -709,8 +944,15 @@ def complete(request, result: nil, error: nil) return if request.result || request.error if request.flow && !request.flow_reported && request.offset.positive? - publish_event(ControlEvent.new(kind: :gap, raw: "".b, pane_id: request.flow.first, - reason: request.flow.last == :pause ? :pause_requested : :resume_requested, dropped_bytes: nil)) + publish_event( + ControlEvent.new( + kind: :gap, + raw: "".b, + pane_id: request.flow.first, + reason: request.flow.last == :pause ? :pause_requested : :resume_requested, + dropped_bytes: nil + ) + ) request.flow_reported = true end @@ -726,10 +968,17 @@ def run loop do writing = pending_write break if @mutex.synchronize { @stopping } - raise TransportError.new("control client exited while a pipe remained open", phase: :read) if exit_deadline && clock >= exit_deadline + if exit_deadline && clock >= exit_deadline + raise TransportError.new("control client exited while a pipe remained open", phase: :read) + end - ready = IO.select(streams + [@wake_reader, @exit_reader], writing ? [@input] : nil, - nil, exit_deadline && [exit_deadline - clock, 0].max) + ready = + IO.select( + streams + [@wake_reader, @exit_reader], + writing ? [@input] : nil, + nil, + exit_deadline && [exit_deadline - clock, 0].max + ) next unless ready ready[0].each do |io| @@ -738,7 +987,10 @@ def run next elsif io == @exit_reader if @child.observation_error - raise TransportError.new("control exit observation failed (#{@child.observation_error.class})", phase: :wait) + raise TransportError.new( + "control exit observation failed (#{@child.observation_error.class})", + phase: :wait + ) end exit_deadline ||= clock + 0.1 next @@ -760,22 +1012,38 @@ def run @mutex.synchronize do request = @writing if request && !@stopping - sent = @input.write_nonblock(request.wire.byteslice(request.offset, 16_384), exception: false) + sent = + @input.write_nonblock( + request.wire.byteslice(request.offset, 16_384), + exception: false + ) request.offset += sent if sent.is_a?(Integer) end end end end rescue Exception => error - failure = error.is_a?(Error) ? error : TransportError.new("control transport failed (#{error.class})", phase: :read) + failure = + ( + if error.is_a?(Error) + error + else + TransportError.new("control transport failed (#{error.class})", phase: :read) + end + ) ensure Thread.handle_interrupt(Exception => :never) do @mutex.synchronize do @stopping = true @requests.values.each do |request| type = failure ? failure.class : ClosedError - error = type.new(failure ? failure.message : "control connection closed", - delivery: request.offset.zero? ? :not_sent : :possibly_sent, phase: :control, pid: @pid) + error = + type.new( + failure ? failure.message : "control connection closed", + delivery: request.offset.zero? ? :not_sent : :possibly_sent, + phase: :control, + pid: @pid + ) complete(request, error: error) end @queue.clear @@ -806,14 +1074,23 @@ def receive(record) request = @replies.first if record.is_a?(GuardedBlock) && request if marker?(record, request.start_marker) - raise ProtocolError.new("duplicate control start boundary", phase: :read) if request.started + if request.started + raise ProtocolError.new("duplicate control start boundary", phase: :read) + end request.started = true return elsif marker?(record, request.end_marker) - raise ProtocolError.new("control end boundary preceded its start", phase: :read) unless request.started + unless request.started + raise ProtocolError.new("control end boundary preceded its start", phase: :read) + end - reply = GuardedReply.new(request_id: request.id, blocks: request.blocks, generation: @generation) + reply = + GuardedReply.new( + request_id: request.id, + blocks: request.blocks, + generation: @generation + ) complete(request, result: reply) @replies.shift return @@ -830,11 +1107,12 @@ def receive(record) end end if request&.flow && record.is_a?(ControlEvent) && record.kind == :gap && - record.pane_id == request.flow.first && record.reason == request.flow.last + record.pane_id == request.flow.first && record.reason == request.flow.last request.flow_reported = true end publish_event(record) - @stopping = true if record.is_a?(ControlEvent) && (record.raw == "%exit\n".b || record.raw.start_with?("%exit ")) + @stopping = true if record.is_a?(ControlEvent) && + (record.raw == "%exit\n".b || record.raw.start_with?("%exit ")) end end @@ -849,15 +1127,28 @@ def receive_stderr(bytes) def publish_event(record) @sequence += 1 - event = if record.is_a?(GuardedBlock) - ControlEvent.new(kind: :unattributed_block, raw: record.raw, - sequence: @sequence, generation: @generation) - else - ControlEvent.new(kind: record.kind, raw: record.raw, data: record.data, pane_id: record.pane_id, - sequence: @sequence, generation: @generation, reason: record.reason, - previous_generation: record.previous_generation, lost_sequences: record.lost_sequences, - dropped_bytes: record.dropped_bytes) - end + event = + if record.is_a?(GuardedBlock) + ControlEvent.new( + kind: :unattributed_block, + raw: record.raw, + sequence: @sequence, + generation: @generation + ) + else + ControlEvent.new( + kind: record.kind, + raw: record.raw, + data: record.data, + pane_id: record.pane_id, + sequence: @sequence, + generation: @generation, + reason: record.reason, + previous_generation: record.previous_generation, + lost_sequences: record.lost_sequences, + dropped_bytes: record.dropped_bytes + ) + end @subscriptions.each { |subscription| subscription.send(:publish, event) } end @@ -869,26 +1160,33 @@ def marker?(block, marker) def cleanup errors = [] deadline = clock + 0.4 - attempt = lambda do |label, &operation| - operation.call - rescue Exception => error - errors << "#{label} failed (#{error.class})" - end + attempt = + lambda do |label, &operation| + operation.call + rescue Exception => error + errors << "#{label} failed (#{error.class})" + end attempt.call("control input close") { @input.close if @input && !@input.closed? } if @pid attempt.call("control client termination") { signal("TERM") } attempt.call("control client forced termination") { signal("KILL") } unless @child.observed? @child.finish_signalling attempt.call("control exit observer join") do - errors << "control client reap deferred after cleanup deadline" unless @child.join([deadline - clock, 0].max) + unless @child.join([deadline - clock, 0].max) + errors << "control client reap deferred after cleanup deadline" + end end else attempt.call("control exit observer join") { @child&.join([deadline - clock, 0].max) } end @resources.each { |io| attempt.call("control pipe close") { io.close unless io.closed? } } attempt.call("control route close") { @pin&.close } - errors << "control exit observation failed (#{@child.observation_error.class})" if @child&.observation_error - errors << "control fallback reap failed (#{@child.retirement_error.class})" if @child&.retirement_error + if @child&.observation_error + errors << "control exit observation failed (#{@child.observation_error.class})" + end + if @child&.retirement_error + errors << "control fallback reap failed (#{@child.retirement_error.class})" + end @cleanup_errors = errors.freeze end diff --git a/gems/libtmux/lib/libtmux/criteria.rb b/gems/libtmux/lib/libtmux/criteria.rb index 63c5c847..783f65f9 100644 --- a/gems/libtmux/lib/libtmux/criteria.rb +++ b/gems/libtmux/lib/libtmux/criteria.rb @@ -9,25 +9,44 @@ module LibTmux class FilterExpr # Runtime validation also enforces byte, node, depth and duplicate-key limits. def self.json_schema - JSON.parse(File.binread(File.expand_path("../../schema/where-v1.json", __dir__)), freeze: true) + JSON.parse( + File.binread(File.expand_path("../../schema/where-v1.json", __dir__)), + freeze: true + ) end PROFILE = "libtmux-ruby.where" VERSION = 1 OMITTED = Object.new.freeze OPERATORS = { - equals: "equals", not: "not", in: "in", lt: "lt", lte: "lte", - gt: "gt", gte: "gte", contains: "contains", starts_with: "startsWith", - ends_with: "endsWith", some: "some", every: "every", none: "none", - is: "is", is_not: "isNot" + equals: "equals", + not: "not", + in: "in", + lt: "lt", + lte: "lte", + gt: "gt", + gte: "gte", + contains: "contains", + starts_with: "startsWith", + ends_with: "endsWith", + some: "some", + every: "every", + none: "none", + is: "is", + is_not: "isNot" }.freeze MAX_DEPTH = 32 MAX_NODES = 2048 MAX_MEMBERS = 1024 MAX_STRING_BYTES = 65_536 MAX_BYTES = 262_144 - private_constant :OMITTED, :OPERATORS, :MAX_DEPTH, :MAX_NODES, :MAX_MEMBERS, - :MAX_STRING_BYTES, :MAX_BYTES + private_constant :OMITTED, + :OPERATORS, + :MAX_DEPTH, + :MAX_NODES, + :MAX_MEMBERS, + :MAX_STRING_BYTES, + :MAX_BYTES attr_reader :entity @@ -55,16 +74,22 @@ def self.from_json(input) unless input.is_a?(String) && input.bytesize <= MAX_BYTES raise InvalidFilterError.new(expected: "JSON string of at most #{MAX_BYTES} bytes") end - data = JSON.parse(input, max_nesting: MAX_DEPTH * 2 + 4, - allow_nan: false, allow_duplicate_key: false) + data = + JSON.parse( + input, + max_nesting: MAX_DEPTH * 2 + 4, + allow_nan: false, + allow_duplicate_key: false + ) required = %w[profile version entity where] - unless data.is_a?(Hash) && data.keys.sort == required.sort && - data["profile"] == PROFILE && data["version"].is_a?(Integer) && data["version"] == VERSION + unless data.is_a?(Hash) && data.keys.sort == required.sort && data["profile"] == PROFILE && + data["version"].is_a?(Integer) && data["version"] == VERSION raise InvalidFilterError.new(expected: "#{PROFILE} version #{VERSION} envelope") end - entity = %i[session window pane window_link client].find do |kind| - Internal::Catalog.entity(kind).wire_entity == data["entity"] - end + entity = + %i[session window pane window_link client].find do |kind| + Internal::Catalog.entity(kind).wire_entity == data["entity"] + end raise InvalidFilterError.new(path: "$.entity", expected: "declared entity") unless entity schema = Internal::Catalog.entity(entity) @@ -103,15 +128,22 @@ def to_proc end def to_h - {"profile" => PROFILE, "version" => VERSION, - "entity" => Internal::Catalog.entity(entity).wire_entity, - "where" => wire_tree(Internal::Catalog.entity(entity), @tree)} + { + "profile" => PROFILE, + "version" => VERSION, + "entity" => Internal::Catalog.entity(entity).wire_entity, + "where" => wire_tree(Internal::Catalog.entity(entity), @tree) + } end def to_json(*arguments) output = JSON.generate(to_h, *arguments) if output.bytesize > MAX_BYTES - raise InvalidFilterError.new(entity: entity, expected: "wire envelope of at most #{MAX_BYTES} bytes", phase: :serialize) + raise InvalidFilterError.new( + entity: entity, + expected: "wire envelope of at most #{MAX_BYTES} bytes", + phase: :serialize + ) end output end @@ -148,7 +180,9 @@ def preflight_tree(record, schema, tree, path = "$") child_path = "#{path}.#{name}" case name when :and, :or - condition.each_with_index { |child, index| preflight_tree(record, schema, child, "#{child_path}[#{index}]") } + condition.each_with_index do |child, index| + preflight_tree(record, schema, child, "#{child_path}[#{index}]") + end when :not preflight_tree(record, schema, condition, child_path) else @@ -157,8 +191,13 @@ def preflight_tree(record, schema, tree, path = "$") begin record.__send__(:read_field, name) rescue FieldDecodeError - raise FieldDecodeError.new("captured field cannot be decoded at #{child_path}", - entity: entity, path: child_path, expected: "valid captured #{schema.fields.fetch(name).type}", phase: :evaluate) + raise FieldDecodeError.new( + "captured field cannot be decoded at #{child_path}", + entity: entity, + path: child_path, + expected: "valid captured #{schema.fields.fetch(name).type}", + phase: :evaluate + ) end else relation = schema.relations.fetch(name) @@ -169,7 +208,12 @@ def preflight_tree(record, schema, tree, path = "$") next if child_tree.nil? children.each do |child| - preflight_tree(child, Internal::Catalog.entity(relation.target), child_tree, "#{child_path}.#{operator}") + preflight_tree( + child, + Internal::Catalog.entity(relation.target), + child_tree, + "#{child_path}.#{operator}" + ) end end end @@ -180,17 +224,25 @@ def preflight_tree(record, schema, tree, path = "$") def require_complete(record, category, name, path) return if record.__send__(:"#{category}_coverage", name) == :complete - raise IncompleteSnapshotError.new("required #{category} was not completely captured at #{path}", - entity: entity, path: path, expected: "complete captured #{category}", phase: :evaluate) + raise IncompleteSnapshotError.new( + "required #{category} was not completely captured at #{path}", + entity: entity, + path: path, + expected: "complete captured #{category}", + phase: :evaluate + ) end def matches(record, tree) schema = Internal::Catalog.entity(record.__send__(:entity_kind)) tree.all? do |name, condition| case name - when :and then condition.all? { |child| matches(record, child) } - when :or then condition.any? { |child| matches(record, child) } - when :not then !matches(record, condition) + when :and + condition.all? { |child| matches(record, child) } + when :or + condition.any? { |child| matches(record, child) } + when :not + !matches(record, condition) else if schema.fields.key?(name) scalar_matches(record.__send__(:read_field, name), condition) @@ -198,11 +250,16 @@ def matches(record, tree) value = record.__send__(:read_relation, name) condition.all? do |operator, child| case operator - when :some then value.any? { |item| matches(item, child) } - when :every then value.all? { |item| matches(item, child) } - when :none then value.none? { |item| matches(item, child) } - when :is then child.nil? ? value.nil? : !value.nil? && matches(value, child) - when :is_not then child.nil? ? !value.nil? : value.nil? || !matches(value, child) + when :some + value.any? { |item| matches(item, child) } + when :every + value.all? { |item| matches(item, child) } + when :none + value.none? { |item| matches(item, child) } + when :is + child.nil? ? value.nil? : !value.nil? && matches(value, child) + when :is_not + child.nil? ? !value.nil? : value.nil? || !matches(value, child) end end end @@ -213,16 +270,26 @@ def matches(record, tree) def scalar_matches(value, condition) condition.all? do |operator, expected| case operator - when :equals then value == expected - when :not then !scalar_matches(value, expected) - when :in then expected.include?(value) - when :lt then !value.nil? && value < expected - when :lte then !value.nil? && value <= expected - when :gt then !value.nil? && value > expected - when :gte then !value.nil? && value >= expected - when :contains then !value.nil? && value.include?(expected) - when :starts_with then !value.nil? && value.start_with?(expected) - when :ends_with then !value.nil? && value.end_with?(expected) + when :equals + value == expected + when :not + !scalar_matches(value, expected) + when :in + expected.include?(value) + when :lt + !value.nil? && value < expected + when :lte + !value.nil? && value <= expected + when :gt + !value.nil? && value > expected + when :gte + !value.nil? && value >= expected + when :contains + !value.nil? && value.include?(expected) + when :starts_with + !value.nil? && value.start_with?(expected) + when :ends_with + !value.nil? && value.end_with?(expected) end end end @@ -230,29 +297,41 @@ def scalar_matches(value, condition) def wire_tree(schema, tree) tree.to_h do |name, condition| case name - when :and, :or then [name.to_s, condition.map { |child| wire_tree(schema, child) }] - when :not then ["not", wire_tree(schema, condition)] + when :and, :or + [name.to_s, condition.map { |child| wire_tree(schema, child) }] + when :not + ["not", wire_tree(schema, condition)] else if (field = schema.fields[name]) [field.wire_name, wire_scalar(condition)] else relation = schema.relations.fetch(name) child_schema = Internal::Catalog.entity(relation.target) - [relation.wire_name, condition.to_h { |op, child| [OPERATORS.fetch(op), child.nil? ? nil : wire_tree(child_schema, child)] }] + [ + relation.wire_name, + condition.to_h do |op, child| + [OPERATORS.fetch(op), child.nil? ? nil : wire_tree(child_schema, child)] + end + ] end end end end def wire_scalar(condition) - condition.to_h { |op, value| [OPERATORS.fetch(op), op == :not ? wire_scalar(value) : duplicate_value(value)] } + condition.to_h do |op, value| + [OPERATORS.fetch(op), op == :not ? wire_scalar(value) : duplicate_value(value)] + end end def duplicate_value(value) case value - when Array then value.map { |item| duplicate_value(item) } - when String then value.dup - else value + when Array + value.map { |item| duplicate_value(item) } + when String + value.dup + else + value end end @@ -277,8 +356,12 @@ def normalize(schema, input, path = "$", depth = 0) when :and, :or fail_at(child_path, "array of criteria") unless value.is_a?(Array) fail_at(child_path, "bounded criteria array") if value.length > MAX_NODES - value.each_with_index.map { |child, index| normalize(schema, child, "#{child_path}[#{index}]", depth + 1) }.freeze - when :not then normalize(schema, value, child_path, depth + 1) + value + .each_with_index + .map { |child, index| normalize(schema, child, "#{child_path}[#{index}]", depth + 1) } + .freeze + when :not + normalize(schema, value, child_path, depth + 1) else if (field = schema.fields[name]) scalar(field, value, child_path, depth + 1) @@ -294,7 +377,9 @@ def normalize(schema, input, path = "$", depth = 0) def visit(path, depth) @nodes += 1 - fail_at(path, "depth <= #{MAX_DEPTH} and nodes <= #{MAX_NODES}") if depth > MAX_DEPTH || @nodes > MAX_NODES + if depth > MAX_DEPTH || @nodes > MAX_NODES + fail_at(path, "depth <= #{MAX_DEPTH} and nodes <= #{MAX_NODES}") + end end def lookup(key, schema) @@ -307,14 +392,16 @@ def lookup(key, schema) return field.name if (!@wire && text == field.name.to_s) || text == field.wire_name end schema.relations.each_value do |relation| - return relation.name if (!@wire && text == relation.name.to_s) || text == relation.wire_name + if (!@wire && text == relation.name.to_s) || text == relation.wire_name + return relation.name + end end nil end def scalar(field, input, path, depth) visit(path, depth) - input = {equals: input} unless input.is_a?(Hash) + input = { equals: input } unless input.is_a?(Hash) fail_at(path, "nonempty scalar operator object") if input.empty? output = {} input.each do |key, value| @@ -323,13 +410,20 @@ def scalar(field, input, path, depth) current_path = "#{path}.#{op}" fail_at(current_path, "one spelling of each operator") if output.key?(op) output[op] = case op - when :not then scalar(field, value, current_path, depth + 1) + when :not + scalar(field, value, current_path, depth + 1) when :in unless value.is_a?(Array) && value.length <= MAX_MEMBERS fail_at(current_path, "array of at most #{MAX_MEMBERS} members") end - value.each_with_index.map { |item, index| literal(field, item, "#{current_path}[#{index}]", nullable: true) }.freeze - else literal(field, value, current_path, nullable: op == :equals) + value + .each_with_index + .map do |item, index| + literal(field, item, "#{current_path}[#{index}]", nullable: true) + end + .freeze + else + literal(field, value, current_path, nullable: op == :equals) end end output.freeze @@ -346,10 +440,17 @@ def relation(relation, input, path, depth) child_path = "#{path}.#{op}" fail_at(child_path, "one spelling of each operator") if output.key?(op) if value.nil? - fail_at(child_path, "criteria object for nonnullable relation") unless relation.nullable && relation.cardinality == :one + unless relation.nullable && relation.cardinality == :one + fail_at(child_path, "criteria object for nonnullable relation") + end output[op] = nil else - output[op] = normalize(Internal::Catalog.entity(relation.target), value, child_path, depth + 1) + output[op] = normalize( + Internal::Catalog.entity(relation.target), + value, + child_path, + depth + 1 + ) end end output.freeze @@ -371,7 +472,8 @@ def literal(field, value, path, nullable:) case field.type when :integer - unless value.is_a?(Integer) && (!field.min || value >= field.min) && (!field.max || value <= field.max) + unless value.is_a?(Integer) && (!field.min || value >= field.min) && + (!field.max || value <= field.max) fail_at(path, "integer within catalog bounds") end value @@ -399,8 +501,13 @@ def fail_at(path, expected) private_constant :Normalizer end - {SessionWhere: :session, WindowWhere: :window, PaneWhere: :pane, - WindowLinkWhere: :window_link, ClientWhere: :client}.each do |name, entity| + { + SessionWhere: :session, + WindowWhere: :window, + PaneWhere: :pane, + WindowLinkWhere: :window_link, + ClientWhere: :client + }.each do |name, entity| builder = Module.new builder.define_singleton_method(:build) do |*arguments, **keywords, &block| FilterExpr.build(entity, *arguments, **keywords, &block) diff --git a/gems/libtmux/lib/libtmux/endpoint.rb b/gems/libtmux/lib/libtmux/endpoint.rb index 80fe6ff4..f184ef7c 100644 --- a/gems/libtmux/lib/libtmux/endpoint.rb +++ b/gems/libtmux/lib/libtmux/endpoint.rb @@ -17,7 +17,13 @@ module LibTmux class Endpoint attr_reader :executable, :socket_path - def initialize(socket_path: nil, socket_name: nil, executable: "tmux", socket_directory: nil, environment: ENV) + def initialize( + socket_path: nil, + socket_name: nil, + executable: "tmux", + socket_directory: nil, + environment: ENV + ) unless socket_path.nil? || socket_name.nil? raise ArgumentError, "choose at most one socket_path or socket_name" end @@ -29,10 +35,11 @@ def initialize(socket_path: nil, socket_name: nil, executable: "tmux", socket_di if socket_name label = origin || "socket_name" validate_string(socket_name, label) - if socket_name.include?("/") || [".", ".."].include?(socket_name) + if socket_name.include?("/") || %w[. ..].include?(socket_name) raise ArgumentError, "#{label} must be a single filename" end - directory = socket_directory || Internal::SocketChoice.present(environment["TMUX_TMPDIR"]) || "/tmp" + directory = + socket_directory || Internal::SocketChoice.present(environment["TMUX_TMPDIR"]) || "/tmp" validate_string(directory, "socket_directory") path_label = socket_directory ? "socket_directory" : "TMUX_TMPDIR" socket_path = File.join(directory, "tmux-#{Process.uid}", socket_name) @@ -73,7 +80,8 @@ def inspect def expand(path, label, base = nil) base ? File.expand_path(path, base) : File.expand_path(path) rescue ArgumentError - raise ArgumentError, "#{label} cannot be expanded to a path; its leading ~ names no home directory" + raise ArgumentError, + "#{label} cannot be expanded to a path; its leading ~ names no home directory" end def validate_string(value, name) @@ -83,13 +91,15 @@ def validate_string(value, name) end def resolve_executable(value) - candidates = if value.include?(File::SEPARATOR) - [expand(value, "executable")] - else - ENV.fetch("PATH", "").split(File::PATH_SEPARATOR).map do |directory| - expand(value, "executable", directory.empty? ? Dir.pwd : directory) + candidates = + if value.include?(File::SEPARATOR) + [expand(value, "executable")] + else + ENV + .fetch("PATH", "") + .split(File::PATH_SEPARATOR) + .map { |directory| expand(value, "executable", directory.empty? ? Dir.pwd : directory) } end - end candidates.find { |path| File.file?(path) && File.executable?(path) } || raise(ArgumentError, "tmux executable is unavailable") end @@ -117,7 +127,7 @@ def call(environment) # the socket path before the first comma of one that does not. def tmux(environment) inside = present(environment["TMUX"]) - return [nil, "default", nil] if inside.nil? || inside.start_with?(",") + return nil, "default", nil if inside.nil? || inside.start_with?(",") [inside.split(",", 2).first, nil, "TMUX"] end @@ -144,7 +154,10 @@ def initialize(endpoint) begin source = File.realpath(endpoint.socket_path) unless File.lstat(source).socket? - raise TargetNotFoundError.new("the selected endpoint is not a Unix socket", phase: :bind) + raise TargetNotFoundError.new( + "the selected endpoint is not a Unix socket", + phase: :bind + ) end make_route(source) @stat = File.lstat(@route) @@ -164,7 +177,9 @@ def initialize(endpoint) end if error begin - Thread.handle_interrupt(Exception => :never) { cleanup_after_failure(error) } unless cleanup_attempted + unless cleanup_attempted + Thread.handle_interrupt(Exception => :never) { cleanup_after_failure(error) } + end rescue Exception # A second deferred cancellation cannot replace the original failure. end @@ -180,7 +195,10 @@ def record_release(release) def command_prefix @mutex.synchronize do if @closed || Process.pid != @owner_pid - raise ClosedError.new("the server binding is closed or belongs to another process", phase: :admission) + raise ClosedError.new( + "the server binding is closed or belongs to another process", + phase: :admission + ) end current = File.lstat(@route) unless current.socket? && [current.dev, current.ino] == [@stat.dev, @stat.ino] @@ -188,7 +206,10 @@ def command_prefix end @prefix rescue Errno::ENOENT - raise TargetNotFoundError.new("the retained server route is unavailable", phase: :admission) + raise TargetNotFoundError.new( + "the retained server route is unavailable", + phase: :admission + ) end end @@ -205,7 +226,7 @@ def close end def inspect - "#<#{self.class} #{@closed ? 'closed' : 'bound'}>" + "#<#{self.class} #{@closed ? "closed" : "bound"}>" end private @@ -223,7 +244,10 @@ def binding_error(failure) when Errno::ENOENT, Errno::ECONNREFUSED TargetNotFoundError.new("the selected tmux endpoint is unavailable", phase: :bind) when SystemCallError - UnsupportedFeatureError.new("cannot retain a private route to this Unix socket", phase: :bind) + UnsupportedFeatureError.new( + "cannot retain a private route to this Unix socket", + phase: :bind + ) else failure end @@ -238,7 +262,10 @@ def make_route(source) if @route.bytesize > 103 remove_route next if index < roots.length - 1 - raise UnsupportedFeatureError.new("the private Unix socket path exceeds the platform limit", phase: :bind) + raise UnsupportedFeatureError.new( + "the private Unix socket path exceeds the platform limit", + phase: :bind + ) end begin File.link(source, @route) diff --git a/gems/libtmux/lib/libtmux/entity.rb b/gems/libtmux/lib/libtmux/entity.rb index f7c7caf9..3c846daa 100644 --- a/gems/libtmux/lib/libtmux/entity.rb +++ b/gems/libtmux/lib/libtmux/entity.rb @@ -22,16 +22,25 @@ class EntityRef attr_reader :binding_key, :kind, :id, :session_id, :index def initialize(binding_key:, kind:, id:, session_id: nil, index: nil) - prefix = {session: "$", window: "@", pane: "%", window_link: "@"}.fetch(kind) + prefix = { session: "$", window: "@", pane: "%", window_link: "@" }.fetch(kind) unless id.is_a?(String) && id.match?(/\A#{Regexp.escape(prefix)}\d+\z/) - raise ProtocolError.new("tmux returned an invalid #{kind} ID", delivery: :observed, phase: :decode) + raise ProtocolError.new( + "tmux returned an invalid #{kind} ID", + delivery: :observed, + phase: :decode + ) end @binding_key = binding_key.dup.freeze @kind = kind @id = id.dup.freeze if kind == :window_link - unless session_id.is_a?(String) && session_id.match?(/\A\$\d+\z/) && index.is_a?(Integer) && index >= 0 - raise ProtocolError.new("tmux returned invalid window link context", delivery: :observed, phase: :decode) + unless session_id.is_a?(String) && session_id.match?(/\A\$\d+\z/) && index.is_a?(Integer) && + index >= 0 + raise ProtocolError.new( + "tmux returned invalid window link context", + delivery: :observed, + phase: :decode + ) end @session_id = session_id.dup.freeze @index = index @@ -43,8 +52,9 @@ def initialize(binding_key:, kind:, id:, session_id: nil, index: nil) private_class_method :new def ==(other) - other.is_a?(EntityRef) && [binding_key, kind, id, session_id, index] == - [other.binding_key, other.kind, other.id, other.session_id, other.index] + other.is_a?(EntityRef) && + [binding_key, kind, id, session_id, index] == + [other.binding_key, other.kind, other.id, other.session_id, other.index] end alias eql? == @@ -85,7 +95,12 @@ def hash end def kill(timeout: 5.0, cancel: nil) - server.__send__(:execute_typed, ["kill-#{ref.kind}", "-t", target], timeout: timeout, cancel: cancel) + server.__send__( + :execute_typed, + ["kill-#{ref.kind}", "-t", target], + timeout: timeout, + cancel: cancel + ) end def inspect @@ -157,9 +172,30 @@ def target # # - Expand a format: {Entity#display} class Session < Entity - def new_window(name: nil, command: nil, index: nil, cwd: nil, environment: {}, focus: false, receipt: false, timeout: 5.0, cancel: nil) - server.__send__(:create_window, ref, name: name, command: command, index: index, - cwd: cwd, environment: environment, focus: focus, receipt: receipt, timeout: timeout, cancel: cancel) + def new_window( + name: nil, + command: nil, + index: nil, + cwd: nil, + environment: {}, + focus: false, + receipt: false, + timeout: 5.0, + cancel: nil + ) + server.__send__( + :create_window, + ref, + name: name, + command: command, + index: index, + cwd: cwd, + environment: environment, + focus: focus, + receipt: receipt, + timeout: timeout, + cancel: cancel + ) end def list_windows(timeout: 5.0, cancel: nil) @@ -231,9 +267,28 @@ def list_panes(timeout: 5.0, cancel: nil) server.__send__(:list_entities, :pane, ["-t", target], timeout: timeout, cancel: cancel) end - def split(direction:, command: nil, size: nil, cwd: nil, environment: {}, focus: false, timeout: 5.0, cancel: nil) - server.__send__(:split_window, ref, direction: direction, command: command, size: size, - cwd: cwd, environment: environment, focus: focus, timeout: timeout, cancel: cancel) + def split( + direction:, + command: nil, + size: nil, + cwd: nil, + environment: {}, + focus: false, + timeout: 5.0, + cancel: nil + ) + server.__send__( + :split_window, + ref, + direction: direction, + command: command, + size: size, + cwd: cwd, + environment: environment, + focus: focus, + timeout: timeout, + cancel: cancel + ) end def select_layout(layout, timeout: 5.0, cancel: nil) @@ -249,14 +304,20 @@ def select_layout(layout, timeout: 5.0, cancel: nil) json = Internal::Capabilities.capability("layout-json") release = server.__send__(:tmux_release) unless json.available?(release) - raise UnsupportedFeatureError.new("JSON layouts require tmux #{json.since} or newer " \ - "(connected version #{release.text})", phase: :admission, delivery: :not_sent) + raise UnsupportedFeatureError.new( + "JSON layouts require tmux #{json.since} or newer " \ + "(connected version #{release.text})", + phase: :admission, + delivery: :not_sent + ) end saved = true end unless LAYOUTS.include?(value) || saved choices = (LAYOUTS + MIRRORED_LAYOUTS).select { |name| name.start_with?(value) } - raise ArgumentError, "layout must be a native name or a saved layout" if value.empty? || choices.empty? + if value.empty? || choices.empty? + raise ArgumentError, "layout must be a native name or a saved layout" + end if choices.any? { |name| MIRRORED_LAYOUTS.include?(name) } release = server.__send__(:tmux_release) @@ -264,7 +325,10 @@ def select_layout(layout, timeout: 5.0, cancel: nil) unless mirrored.available?(release) choices &= LAYOUTS if choices.empty? - raise UnsupportedFeatureError.new("mirrored layouts require tmux #{mirrored.since}+", phase: :admission) + raise UnsupportedFeatureError.new( + "mirrored layouts require tmux #{mirrored.since}+", + phase: :admission + ) end end end @@ -273,7 +337,11 @@ def select_layout(layout, timeout: 5.0, cancel: nil) value = choices.first end - server.__send__(:execute_typed, ["select-layout", "-t", target, "--", value], **budget.options) + server.__send__( + :execute_typed, + ["select-layout", "-t", target, "--", value], + **budget.options + ) end end @@ -343,45 +411,94 @@ def select_layout(layout, timeout: 5.0, cancel: nil) # - Hooks: {Entity#hooks} # - Expand a format: {Entity#display} class Pane < Entity - def split(direction:, command: nil, size: nil, cwd: nil, environment: {}, focus: false, timeout: 5.0, cancel: nil) - server.__send__(:split_window, ref, direction: direction, command: command, size: size, - cwd: cwd, environment: environment, focus: focus, timeout: timeout, cancel: cancel) - end - - def capture(start: nil, finish: nil, join: false, escapes: false, escape_bytes: false, preserve_trailing: false, - trim_trailing: false, alternate: false, mode_screen: false, pending: false, timeout: 5.0, cancel: nil) + def split( + direction:, + command: nil, + size: nil, + cwd: nil, + environment: {}, + focus: false, + timeout: 5.0, + cancel: nil + ) + server.__send__( + :split_window, + ref, + direction: direction, + command: command, + size: size, + cwd: cwd, + environment: environment, + focus: focus, + timeout: timeout, + cancel: cancel + ) + end + + def capture( + start: nil, + finish: nil, + join: false, + escapes: false, + escape_bytes: false, + preserve_trailing: false, + trim_trailing: false, + alternate: false, + mode_screen: false, + pending: false, + timeout: 5.0, + cancel: nil + ) budget = server.__send__(:operation_budget, timeout, cancel) if [alternate, mode_screen, pending].count { |value| value } > 1 raise ArgumentError, "alternate, mode_screen and pending captures are mutually exclusive" end arguments = ["capture-pane", "-p", "-t", target] - {"-S" => start, "-E" => finish}.each do |flag, value| + { "-S" => start, "-E" => finish }.each do |flag, value| next if value.nil? - raise ArgumentError, "capture ranges must be integers or '-'" unless value.is_a?(Integer) || value == "-" + unless value.is_a?(Integer) || value == "-" + raise ArgumentError, "capture ranges must be integers or '-'" + end arguments.concat([flag, value.to_s]) end - {"T" => trim_trailing, "M" => mode_screen}.each do |flag, enabled| + { "T" => trim_trailing, "M" => mode_screen }.each do |flag, enabled| next unless enabled server.__send__(:require_command_flag, "capture-pane", flag, budget: budget) arguments << "-#{flag}" end - {"-J" => join, "-e" => escapes, "-C" => escape_bytes, "-N" => preserve_trailing, - "-a" => alternate, "-P" => pending}.each { |flag, enabled| arguments << flag if enabled } + { + "-J" => join, + "-e" => escapes, + "-C" => escape_bytes, + "-N" => preserve_trailing, + "-a" => alternate, + "-P" => pending + }.each { |flag, enabled| arguments << flag if enabled } server.__send__(:execute_typed, arguments, **budget.options) end def send_text(text, timeout: 5.0, cancel: nil) raise ArgumentError, "text must be a String" unless text.is_a?(String) - server.__send__(:execute_typed, ["send-keys", "-l", "-t", target, "--", text], timeout: timeout, cancel: cancel) + server.__send__( + :execute_typed, + ["send-keys", "-l", "-t", target, "--", text], + timeout: timeout, + cancel: cancel + ) end def send_keys(*keys, timeout: 5.0, cancel: nil) raise ArgumentError, "provide at least one key name" if keys.empty? - server.__send__(:execute_typed, ["send-keys", "-t", target, "--", *keys], timeout: timeout, cancel: cancel) + server.__send__( + :execute_typed, + ["send-keys", "-t", target, "--", *keys], + timeout: timeout, + cancel: cancel + ) end end @@ -399,40 +516,89 @@ def session end def select(timeout: 5.0, cancel: nil) - server.__send__(:execute_link, [ref], "select-window", ["-t", context], timeout: timeout, cancel: cancel) + server.__send__( + :execute_link, + [ref], + "select-window", + ["-t", context], + timeout: timeout, + cancel: cancel + ) end def unlink(force: false, timeout: 5.0, cancel: nil) - server.__send__(:execute_link, [ref], "unlink-window", [*(force ? ["-k"] : []), "-t", context], timeout: timeout, cancel: cancel) + server.__send__( + :execute_link, + [ref], + "unlink-window", + [*(force ? ["-k"] : []), "-t", context], + timeout: timeout, + cancel: cancel + ) end def kill(timeout: 5.0, cancel: nil) - server.__send__(:execute_link, [ref], "kill-window", ["-t", context], timeout: timeout, cancel: cancel) + server.__send__( + :execute_link, + [ref], + "kill-window", + ["-t", context], + timeout: timeout, + cancel: cancel + ) end def move(session:, index:, timeout: 5.0, cancel: nil) - raise ArgumentError, "index must be a nonnegative Integer" unless index.is_a?(Integer) && index >= 0 + unless index.is_a?(Integer) && index >= 0 + raise ArgumentError, "index must be a nonnegative Integer" + end destination = server.__send__(:target, session, :session) - server.__send__(:execute_link, [ref], "move-window", ["-d", "-s", context, "-t", "#{destination}:#{index}"], timeout: timeout, cancel: cancel) + server.__send__( + :execute_link, + [ref], + "move-window", + ["-d", "-s", context, "-t", "#{destination}:#{index}"], + timeout: timeout, + cancel: cancel + ) end def swap(other, timeout: 5.0, cancel: nil) server.__send__(:target, other, :window_link) - server.__send__(:execute_link, [ref, other], "swap-window", - ["-d", "-s", context, "-t", "#{other.session_id}:#{other.index}"], timeout: timeout, cancel: cancel) + server.__send__( + :execute_link, + [ref, other], + "swap-window", + ["-d", "-s", context, "-t", "#{other.session_id}:#{other.index}"], + timeout: timeout, + cancel: cancel + ) end def display(format, timeout: 5.0, cancel: nil) - server.__send__(:execute_link, [ref], "display-message", ["-p", "-t", context, "--", format], timeout: timeout, cancel: cancel) + server.__send__( + :execute_link, + [ref], + "display-message", + ["-p", "-t", context, "--", format], + timeout: timeout, + cancel: cancel + ) end def options - raise UnsupportedFeatureError.new("link-scoped options are not implemented; use an explicit window handle", phase: :admission) + raise UnsupportedFeatureError.new( + "link-scoped options are not implemented; use an explicit window handle", + phase: :admission + ) end def hooks - raise UnsupportedFeatureError.new("link-scoped hooks are not implemented; use an explicit window handle", phase: :admission) + raise UnsupportedFeatureError.new( + "link-scoped hooks are not implemented; use an explicit window handle", + phase: :admission + ) end private diff --git a/gems/libtmux/lib/libtmux/errors.rb b/gems/libtmux/lib/libtmux/errors.rb index 7c586048..34eede1c 100644 --- a/gems/libtmux/lib/libtmux/errors.rb +++ b/gems/libtmux/lib/libtmux/errors.rb @@ -4,7 +4,16 @@ module LibTmux class Error < StandardError attr_reader :delivery, :phase, :pid, :cleanup_errors, :entity, :path, :expected, :text - def initialize(message, delivery: :not_sent, phase: nil, pid: nil, cleanup_errors: [], entity: nil, path: nil, expected: nil) + def initialize( + message, + delivery: :not_sent, + phase: nil, + pid: nil, + cleanup_errors: [], + entity: nil, + path: nil, + expected: nil + ) super(message) @delivery = delivery @phase = phase @@ -29,32 +38,54 @@ def attach_wait_text(text) class InvalidFilterError < Error def initialize(message = "invalid filter", entity: nil, path: "$", expected: nil, **details) - super("#{message} at #{path}#{expected ? "; expected #{expected}" : ""}", - entity: entity, path: path, expected: expected, **details) + super( + "#{message} at #{path}#{expected ? "; expected #{expected}" : ""}", + entity: entity, + path: path, + expected: expected, + **details + ) end end - class IncompleteSnapshotError < Error; end - class InconsistentSnapshotError < Error; end - class NoMatchError < Error; end - class MultipleMatchesError < Error; end - class TargetNotFoundError < Error; end - class FieldDecodeError < Error; end - class UnsupportedFeatureError < Error; end - class TransportError < Error; end - class ProtocolError < Error; end - class CapacityError < Error; end - class DeadlineExceeded < Error; end - class Cancelled < Error; end - class OutcomeUnknown < Error; end - class ClosedError < Error; end + class IncompleteSnapshotError < Error + end + class InconsistentSnapshotError < Error + end + class NoMatchError < Error + end + class MultipleMatchesError < Error + end + class TargetNotFoundError < Error + end + class FieldDecodeError < Error + end + class UnsupportedFeatureError < Error + end + class TransportError < Error + end + class ProtocolError < Error + end + class CapacityError < Error + end + class DeadlineExceeded < Error + end + class Cancelled < Error + end + class OutcomeUnknown < Error + end + class ClosedError < Error + end # The pane or server ended before a text wait matched. class PaneDied < Error attr_reader :reason def initialize(reason, text) - message = {pane_exited: "pane process exited", pane_gone: "pane was removed", - server_gone: "tmux server stopped"}.fetch(reason) + message = { + pane_exited: "pane process exited", + pane_gone: "pane was removed", + server_gone: "tmux server stopped" + }.fetch(reason) super(message, phase: :read, delivery: :observed) @reason = reason attach_wait_text(text) @@ -67,7 +98,7 @@ class CommandError < Error def initialize(message = "tmux command failed", result: nil, **details) @result = result - super(message, **{delivery: result&.delivery || :not_sent, pid: result&.pid}.merge(details)) + super(message, **{ delivery: result&.delivery || :not_sent, pid: result&.pid }.merge(details)) end end end diff --git a/gems/libtmux/lib/libtmux/group.rb b/gems/libtmux/lib/libtmux/group.rb index 38245598..78c92f63 100644 --- a/gems/libtmux/lib/libtmux/group.rb +++ b/gems/libtmux/lib/libtmux/group.rb @@ -9,7 +9,7 @@ class GroupResult def initialize(result, count) @result = result - @steps = Array.new(count) { |index| {index: index, outcome: :unknown}.freeze }.freeze + @steps = Array.new(count) { |index| { index: index, outcome: :unknown }.freeze }.freeze freeze end private_class_method :new @@ -40,13 +40,14 @@ def run_group(commands, input: "".b, timeout: 5.0, cancel: nil) if commands.length > 128 raise CapacityError.new("command group exceeds 128 members", phase: :admission) end - encoded = commands.map do |command| - validate_argv(command) - if command.first.start_with?("-") - raise ArgumentError, "group members cannot override endpoint flags" + encoded = + commands.map do |command| + validate_argv(command) + if command.first.start_with?("-") + raise ArgumentError, "group members cannot override endpoint flags" + end + encode_arguments(command) end - encode_arguments(command) - end argv = [] encoded.each_with_index do |command, index| argv << ";" unless index.zero? diff --git a/gems/libtmux/lib/libtmux/metadata.rb b/gems/libtmux/lib/libtmux/metadata.rb index 9bf91f4f..e3a2c98b 100644 --- a/gems/libtmux/lib/libtmux/metadata.rb +++ b/gems/libtmux/lib/libtmux/metadata.rb @@ -14,25 +14,45 @@ def format(fields) # q doubles literal backslashes before tmux 3.5's VIS_NOSLASH output # escaping. Decode that transport layer before using original byte lengths. def unquote(value) - escapes = {"a" => "\a", "b" => "\b", "t" => "\t", "n" => "\n", "v" => "\v", - "f" => "\f", "r" => "\r", "s" => " ", "E" => "\e"} - value.b.gsub(/\\([0-7]{3}|.)/nm) do - escaped = Regexp.last_match(1) - if escaped.match?(/\A[0-7]{3}\z/) - byte = escaped.to_i(8) - protocol_error("invalid metadata byte escape") if byte > 255 - byte.chr(Encoding::BINARY) - else - escapes.fetch(escaped, escaped) + escapes = { + "a" => "\a", + "b" => "\b", + "t" => "\t", + "n" => "\n", + "v" => "\v", + "f" => "\f", + "r" => "\r", + "s" => " ", + "E" => "\e" + } + value + .b + .gsub(/\\([0-7]{3}|.)/nm) do + escaped = Regexp.last_match(1) + if escaped.match?(/\A[0-7]{3}\z/) + byte = escaped.to_i(8) + protocol_error("invalid metadata byte escape") if byte > 255 + byte.chr(Encoding::BINARY) + else + escapes.fetch(escaped, escaped) + end end - end end - def decode(bytes, fields:, max_field_bytes: 1 << 20, max_bytes: 1 << 20, max_rows: 10_000, quoted: false) + def decode( + bytes, + fields:, + max_field_bytes: 1 << 20, + max_bytes: 1 << 20, + max_rows: 10_000, + quoted: false + ) unless bytes.is_a?(String) && fields.is_a?(Integer) && fields.between?(1, 64) raise ArgumentError, "metadata requires String bytes and between 1 and 64 fields" end - unless [max_field_bytes, max_bytes, max_rows].all? { |limit| limit.is_a?(Integer) && limit.positive? } + unless [max_field_bytes, max_bytes, max_rows].all? { |limit| + limit.is_a?(Integer) && limit.positive? + } raise ArgumentError, "metadata limits must be positive integers" end capacity_error("metadata output exceeds its byte limit") if bytes.bytesize > max_bytes @@ -42,28 +62,29 @@ def decode(bytes, fields:, max_field_bytes: 1 << 20, max_bytes: 1 << 20, max_row offset = 0 while offset < bytes.bytesize capacity_error("metadata exceeds its row limit") if rows.length >= max_rows - row = Array.new(fields) do - length = 0 - digits = 0 - loop do - byte = bytes.getbyte(offset) - if byte == 58 && digits.positive? + row = + Array.new(fields) do + length = 0 + digits = 0 + loop do + byte = bytes.getbyte(offset) + if byte == 58 && digits.positive? + offset += 1 + break + end + unless byte && byte.between?(48, 57) && digits < 9 + protocol_error("invalid metadata length prefix") + end + length = length * 10 + byte - 48 + digits += 1 offset += 1 - break end - unless byte && byte.between?(48, 57) && digits < 9 - protocol_error("invalid metadata length prefix") - end - length = length * 10 + byte - 48 - digits += 1 - offset += 1 + capacity_error("metadata field exceeds its byte limit") if length > max_field_bytes + protocol_error("truncated metadata field") if offset + length > bytes.bytesize + value = bytes.byteslice(offset, length).freeze + offset += length + value end - capacity_error("metadata field exceeds its byte limit") if length > max_field_bytes - protocol_error("truncated metadata field") if offset + length > bytes.bytesize - value = bytes.byteslice(offset, length).freeze - offset += length - value - end protocol_error("missing metadata row terminator") unless bytes.getbyte(offset) == 10 offset += 1 rows << row.freeze diff --git a/gems/libtmux/lib/libtmux/native_guard.rb b/gems/libtmux/lib/libtmux/native_guard.rb index 57bdd435..cc23560c 100644 --- a/gems/libtmux/lib/libtmux/native_guard.rb +++ b/gems/libtmux/lib/libtmux/native_guard.rb @@ -15,25 +15,99 @@ module Internal # an abbreviation that is ambiguous on any supported release counts as # ambiguous. module NativeGuard - COMMANDS = [ - "attach-session", "bind-key", "break-pane", "capture-pane", "choose-buffer", - "choose-client", "choose-tree", "clear-history", "clear-prompt-history", "clock-mode", - "command-prompt", "confirm-before", "copy-mode", "customize-mode", "delete-buffer", - "detach-client", "display-menu", "display-message", "display-popup", "display-panes", - "find-window", "has-session", "if-shell", "join-pane", "kill-pane", "kill-server", - "kill-session", "kill-window", "last-pane", "last-window", "link-window", "list-buffers", - "list-clients", "list-commands", "list-keys", "list-panes", "list-sessions", - "list-windows", "load-buffer", "lock-client", "lock-server", "lock-session", "move-pane", - "move-window", "new-pane", "new-session", "new-window", "next-layout", "next-window", - "paste-buffer", "pipe-pane", "previous-layout", "previous-window", "refresh-client", - "rename-session", "rename-window", "resize-pane", "resize-window", "respawn-pane", - "respawn-window", "rotate-window", "run-shell", "save-buffer", "select-layout", - "select-pane", "select-window", "send-keys", "send-prefix", "server-access", - "set-buffer", "set-environment", "set-hook", "set-option", "set-window-option", - "show-buffer", "show-environment", "show-hooks", "show-messages", "show-options", - "show-prompt-history", "show-window-options", "source-file", "split-window", - "start-server", "suspend-client", "swap-pane", "swap-window", "switch-client", - "switch-mode", "unbind-key", "unlink-window", "wait-for" + COMMANDS = %w[ + attach-session + bind-key + break-pane + capture-pane + choose-buffer + choose-client + choose-tree + clear-history + clear-prompt-history + clock-mode + command-prompt + confirm-before + copy-mode + customize-mode + delete-buffer + detach-client + display-menu + display-message + display-popup + display-panes + find-window + has-session + if-shell + join-pane + kill-pane + kill-server + kill-session + kill-window + last-pane + last-window + link-window + list-buffers + list-clients + list-commands + list-keys + list-panes + list-sessions + list-windows + load-buffer + lock-client + lock-server + lock-session + move-pane + move-window + new-pane + new-session + new-window + next-layout + next-window + paste-buffer + pipe-pane + previous-layout + previous-window + refresh-client + rename-session + rename-window + resize-pane + resize-window + respawn-pane + respawn-window + rotate-window + run-shell + save-buffer + select-layout + select-pane + select-window + send-keys + send-prefix + server-access + set-buffer + set-environment + set-hook + set-option + set-window-option + show-buffer + show-environment + show-hooks + show-messages + show-options + show-prompt-history + show-window-options + source-file + split-window + start-server + suspend-client + swap-pane + swap-window + switch-client + switch-mode + unbind-key + unlink-window + wait-for ].freeze ALIASES = { "attach" => "attach-session", @@ -150,19 +224,28 @@ def check_items(items, release, repaired_break: false) case command when "delete-buffer" gate = Internal::Capabilities.capability("buffer-delete-named") - refuse("exact named-buffer deletion", gate.since, release) if !gate.available?(release) && flags(item, command).key?("b") + if !gate.available?(release) && flags(item, command).key?("b") + refuse("exact named-buffer deletion", gate.since, release) + end when "set-buffer" given = flags(item, command) gate = Internal::Capabilities.capability("buffer-rename") - refuse("exact named-buffer rename", gate.since, release) if !gate.available?(release) && given.key?("b") && given.key?("n") + if !gate.available?(release) && given.key?("b") && given.key?("n") + refuse("exact named-buffer rename", gate.since, release) + end when "break-pane" - if Internal::Capabilities.workaround("break-pane-misnames-windows").applies?(release) && !(repaired_break && flags(item, command).key?("n")) + if Internal::Capabilities.workaround("break-pane-misnames-windows").applies?(release) && + !(repaired_break && flags(item, command).key?("n")) refuse_raw_break(release) end when "split-window" - if Internal::Capabilities.workaround("split-window-percent-size").applies?(release) && flags(item, command).key?("p") - raise UnsupportedFeatureError.new("split-window -p is broken on tmux #{release.text}; use -l with a percentage", - phase: :admission, delivery: :not_sent) + if Internal::Capabilities.workaround("split-window-percent-size").applies?(release) && + flags(item, command).key?("p") + raise UnsupportedFeatureError.new( + "split-window -p is broken on tmux #{release.text}; use -l with a percentage", + phase: :admission, + delivery: :not_sent + ) end when "select-layout" check_layout(item, command, release) @@ -179,7 +262,9 @@ def check_items(items, release, repaired_break: false) # tmux-256color terminal for its clipboard, and 3.4 through 3.6 # stop when that client leaves before its terminal answers. gate = Internal::Capabilities.capability("clipboard-query") - refuse("refresh-client -l", gate.since, release) if !gate.available?(release) && flags(item, command).key?("l") + if !gate.available?(release) && flags(item, command).key?("l") + refuse("refresh-client -l", gate.since, release) + end end end nil @@ -211,10 +296,11 @@ def parse_line(line) depth = 0 chars = line.each_char.to_a index = 0 - finish = lambda do - result.last << word if word - word = nil - end + finish = + lambda do + result.last << word if word + word = nil + end while index < chars.length char = chars[index] if depth.positive? @@ -234,7 +320,8 @@ def parse_line(line) end else case char - when /\s/ then finish.call + when /\s/ + finish.call when "'", '"' word ||= +"" quote = char @@ -282,16 +369,18 @@ def flags(item, command) token = rest.shift break if token == "--" || !token.start_with?("-") || token == "-" - token[1..].each_char.with_index(1) do |flag, index| - position = spec.index(flag) - next unless position + token[1..] + .each_char + .with_index(1) do |flag, index| + position = spec.index(flag) + next unless position - if spec[position + 1] == ":" - given[flag] = token[(index + 1)..].empty? ? rest.shift : token[(index + 1)..] - break + if spec[position + 1] == ":" + given[flag] = token[(index + 1)..].empty? ? rest.shift : token[(index + 1)..] + break + end + given[flag] = true end - given[flag] = true - end end given end @@ -305,13 +394,15 @@ def operands(item, command) return rest if !token.start_with?("-") || token == "-" rest.shift - token[1..].each_char.with_index(1) do |flag, index| - position = spec.index(flag) - next unless position && spec[position + 1] == ":" + token[1..] + .each_char + .with_index(1) do |flag, index| + position = spec.index(flag) + next unless position && spec[position + 1] == ":" - rest.shift if token[(index + 1)..].empty? - break - end + rest.shift if token[(index + 1)..].empty? + break + end end rest end @@ -322,9 +413,14 @@ def operands(item, command) def check_layout(item, command, release) given = flags(item, command) json = Internal::Capabilities.capability("layout-json") - if !json.available?(release) && operands(item, command).first.to_s.start_with?("{") && given.slice("E", "n", "p").empty? - raise UnsupportedFeatureError.new("JSON layouts require tmux #{json.since} or newer " \ - "(connected version #{release.text})", phase: :admission, delivery: :not_sent) + if !json.available?(release) && operands(item, command).first.to_s.start_with?("{") && + given.slice("E", "n", "p").empty? + raise UnsupportedFeatureError.new( + "JSON layouts require tmux #{json.since} or newer " \ + "(connected version #{release.text})", + phase: :admission, + delivery: :not_sent + ) end return if Internal::Capabilities.capability("layout-without-checksum").available?(release) @@ -334,26 +430,42 @@ def check_layout(item, command, release) return if layout.nil? || layout.match?(/\A[0-9a-fA-F]{4},[\s\S]+/) return if !given.key?("o") && PRESETS.count { |name| name.start_with?(layout) } == 1 - raise UnsupportedFeatureError.new("an invalid layout is refused before dispatch on tmux #{release.text}; " \ - "use a unique built-in layout name or a serialized layout", phase: :admission, delivery: :not_sent) + raise UnsupportedFeatureError.new( + "an invalid layout is refused before dispatch on tmux #{release.text}; " \ + "use a unique built-in layout name or a serialized layout", + phase: :admission, + delivery: :not_sent + ) end def check_name(name, release) return unless name.is_a?(String) && name.match?(/[:.]/) - return unless Internal::Capabilities.workaround("name-separators-rejected").applies?(release) + unless Internal::Capabilities.workaround("name-separators-rejected").applies?(release) + return + end - raise UnsupportedFeatureError.new("tmux 3.7 rejects ':' and '.' in session and window names", - phase: :admission, delivery: :not_sent) + raise UnsupportedFeatureError.new( + "tmux 3.7 rejects ':' and '.' in session and window names", + phase: :admission, + delivery: :not_sent + ) end def refuse(what, floor, release) - raise UnsupportedFeatureError.new("#{what} requires tmux #{floor} or newer (connected version #{release.text})", - phase: :admission, delivery: :not_sent) + raise UnsupportedFeatureError.new( + "#{what} requires tmux #{floor} or newer (connected version #{release.text})", + phase: :admission, + delivery: :not_sent + ) end def refuse_raw_break(release) - raise UnsupportedFeatureError.new("break-pane is unsafe on tmux #{release.text}; use Pane#break_out, " \ - "which names the window, or upgrade to 3.7a", phase: :admission, delivery: :not_sent) + raise UnsupportedFeatureError.new( + "break-pane is unsafe on tmux #{release.text}; use Pane#break_out, " \ + "which names the window, or upgrade to 3.7a", + phase: :admission, + delivery: :not_sent + ) end end end diff --git a/gems/libtmux/lib/libtmux/operations.rb b/gems/libtmux/lib/libtmux/operations.rb index 253d218c..0dc52b6b 100644 --- a/gems/libtmux/lib/libtmux/operations.rb +++ b/gems/libtmux/lib/libtmux/operations.rb @@ -9,16 +9,20 @@ def options(scope: :server) end def hooks(scope: :session) - raise ArgumentError, "hooks use session or window scope" unless [:session, :window].include?(scope) + unless %i[session window].include?(scope) + raise ArgumentError, "hooks use session or window scope" + end Hooks.__send__(:new, self, scope: scope) end # Formats are intentionally executable tmux formats, not literal text. def display(format, target: nil, timeout: 5.0, cancel: nil) - return window_link(target).display(format, timeout: timeout, cancel: cancel) if target.is_a?(EntityRef) && target.kind == :window_link + if target.is_a?(EntityRef) && target.kind == :window_link + return window_link(target).display(format, timeout: timeout, cancel: cancel) + end - args = ["display-message", "-p"] + args = %w[display-message -p] if target id = self.target(target, target.kind) args.concat(["-t", id]) @@ -33,10 +37,20 @@ def display(format, target: nil, timeout: 5.0, cancel: nil) prefix = "#{id.bytesize}:#{id}" unless result.stdout.start_with?(prefix) - raise TargetNotFoundError.new("display target no longer exists", phase: :command, delivery: :observed) + raise TargetNotFoundError.new( + "display target no longer exists", + phase: :command, + delivery: :observed + ) end - CommandResult.new(stdout: result.stdout.byteslice(prefix.bytesize..), stderr: result.stderr, - status: result.status, elapsed_seconds: result.elapsed_seconds, pid: result.pid, argv: result.argv) + CommandResult.new( + stdout: result.stdout.byteslice(prefix.bytesize..), + stderr: result.stderr, + status: result.status, + elapsed_seconds: result.elapsed_seconds, + pid: result.pid, + argv: result.argv + ) end def source_file(path, timeout: 5.0, cancel: nil) @@ -45,9 +59,10 @@ def source_file(path, timeout: 5.0, cancel: nil) # Retiring the client cannot remove a dispatched waiter from tmux's queue. def wait_for(channel, action: :wait, timeout: 5.0, cancel: nil) - flag = {wait: nil, signal: "-S", lock: "-L", unlock: "-U"}.fetch(action) do - raise ArgumentError, "action must be :wait, :signal, :lock or :unlock" - end + flag = + { wait: nil, signal: "-S", lock: "-L", unlock: "-U" }.fetch(action) do + raise ArgumentError, "action must be :wait, :signal, :lock or :unlock" + end execute_typed(["wait-for", *[flag].compact, "--", channel], timeout: timeout, cancel: cancel) end @@ -59,7 +74,12 @@ def write_buffer(name:, data:, timeout: 5.0, cancel: nil) raise UnsupportedFeatureError.new("tmux cannot write a zero-byte buffer", phase: :admission) end - execute_typed(["load-buffer", "-b", name, "--", "-"], input: data, timeout: timeout, cancel: cancel) + execute_typed( + ["load-buffer", "-b", name, "--", "-"], + input: data, + timeout: timeout, + cancel: cancel + ) end def read_buffer(name, timeout: 5.0, cancel: nil) @@ -71,10 +91,16 @@ def delete_buffer(name, timeout: 5.0, cancel: nil) end def list_buffers(timeout: 5.0, cancel: nil) - result = execute_typed(["list-buffers", "-F", metadata_format(%w[buffer_name buffer_size])], timeout: timeout, cancel: cancel) - Internal::Metadata.decode(result.stdout, fields: 2, quoted: true).map do |name, size| - {name: name, size: decode_integer(size, "buffer size")}.freeze - end.freeze + result = + execute_typed( + ["list-buffers", "-F", metadata_format(%w[buffer_name buffer_size])], + timeout: timeout, + cancel: cancel + ) + Internal::Metadata + .decode(result.stdout, fields: 2, quoted: true) + .map { |name, size| { name: name, size: decode_integer(size, "buffer size") }.freeze } + .freeze end def list_window_links(timeout: 5.0, cancel: nil) @@ -94,19 +120,41 @@ def environment(name, hidden: false, timeout: 5.0, cancel: nil) end def unset_environment(name, timeout: 5.0, cancel: nil) - execute_typed(["set-environment", "-g", "-u", "--", environment_name(name)], timeout: timeout, cancel: cancel) + execute_typed( + ["set-environment", "-g", "-u", "--", environment_name(name)], + timeout: timeout, + cancel: cancel + ) end def list_clients(timeout: 5.0, cancel: nil) fields = %w[client_name client_pid client_created client_tty session_id client_control_mode] - result = execute_typed(["list-clients", "-F", metadata_format(fields)], timeout: timeout, cancel: cancel) - Internal::Metadata.decode(result.stdout, fields: fields.length, quoted: true).map do |name, pid, created, tty, session_id, control| - unless ["0", "1"].include?(control) - raise FieldDecodeError.new("client control mode is malformed", phase: :decode, delivery: :observed) + result = + execute_typed( + ["list-clients", "-F", metadata_format(fields)], + timeout: timeout, + cancel: cancel + ) + Internal::Metadata + .decode(result.stdout, fields: fields.length, quoted: true) + .map do |name, pid, created, tty, session_id, control| + unless %w[0 1].include?(control) + raise FieldDecodeError.new( + "client control mode is malformed", + phase: :decode, + delivery: :observed + ) + end + { + name: name, + pid: decode_integer(pid, "client PID"), + created: decode_integer(created, "client creation time"), + tty: tty.empty? ? nil : tty, + session_id: session_id.empty? ? nil : session_id, + control: control == "1" + }.freeze end - {name: name, pid: decode_integer(pid, "client PID"), created: decode_integer(created, "client creation time"), - tty: tty.empty? ? nil : tty, session_id: session_id.empty? ? nil : session_id, control: control == "1"}.freeze - end.freeze + .freeze end private @@ -122,37 +170,70 @@ def execute_link(refs, command, arguments, timeout: 5.0, cancel: nil, budget: ni failure = tmux_command([names.fetch("display-message"), "-p", "--", marker]) body = tmux_command([names.fetch(command), *arguments]) refs.reverse_each do |ref| - guard = "\#{&&:\#{==:\#{session_id},#{ref.session_id}},\#{&&:\#{==:\#{window_index},#{ref.index}},\#{==:\#{window_id},#{ref.id}}}}" - body = tmux_command([names.fetch("if-shell"), "-F", "-t", "#{ref.session_id}:#{ref.index}", guard, body, failure]) + guard = + "\#{&&:\#{==:\#{session_id},#{ref.session_id}},\#{&&:\#{==:\#{window_index},#{ref.index}},\#{==:\#{window_id},#{ref.id}}}}" + body = + tmux_command( + [ + names.fetch("if-shell"), + "-F", + "-t", + "#{ref.session_id}:#{ref.index}", + guard, + body, + failure + ] + ) end # One command string is parsed by tmux; it never passes through a shell. result = execute_typed([names.fetch("if-shell"), "-F", "1", body], **budget.options) if result.stdout == "#{marker}\n" - raise TargetNotFoundError.new("window link was removed or replaced", phase: :command, delivery: :observed) + raise TargetNotFoundError.new( + "window link was removed or replaced", + phase: :command, + delivery: :observed + ) end result end def builtin_spellings(*commands, budget:) inventory = options(scope: :server).list(name: "command-alias", **budget.options) - unless !inventory.empty? && inventory.all? { |option| option.name == "command-alias" && option.array? } - raise UnsupportedFeatureError.new("tmux command alias inventory is unavailable", phase: :admission) - end - aliases = inventory.filter_map do |option| - option.raw.split("=", 2).first if option.present? + unless !inventory.empty? && + inventory.all? { |option| option.name == "command-alias" && option.array? } + raise UnsupportedFeatureError.new( + "tmux command alias inventory is unavailable", + phase: :admission + ) end - result = execute_typed(["list-commands", "-F", metadata_format(%w[command_list_name command_list_alias])], **budget.options) + aliases = inventory.filter_map { |option| option.raw.split("=", 2).first if option.present? } + result = + execute_typed( + ["list-commands", "-F", metadata_format(%w[command_list_name command_list_alias])], + **budget.options + ) catalog = Internal::Metadata.decode(result.stdout, fields: 2, quoted: true).to_h commands.uniq.to_h do |name| - candidates = [name, catalog[name], *(1...name.length).map { |length| name[0, length] }.reverse].compact - spelling = candidates.find do |candidate| - next false if aliases.include?(candidate) - - exact_alias = catalog.find { |_key, value| value == candidate }&.first - matching = exact_alias ? [exact_alias] : catalog.keys.select { |key| key.start_with?(candidate) } - matching == [name] || candidate == name + candidates = [ + name, + catalog[name], + *(1...name.length).map { |length| name[0, length] }.reverse + ].compact + spelling = + candidates.find do |candidate| + next false if aliases.include?(candidate) + + exact_alias = catalog.find { |_key, value| value == candidate }&.first + matching = + exact_alias ? [exact_alias] : catalog.keys.select { |key| key.start_with?(candidate) } + matching == [name] || candidate == name + end + unless spelling + raise UnsupportedFeatureError.new( + "all builtin spellings of #{name} are aliased", + phase: :admission + ) end - raise UnsupportedFeatureError.new("all builtin spellings of #{name} are aliased", phase: :admission) unless spelling [name, spelling] end @@ -170,15 +251,24 @@ def kill_session_with_windows(ref, expected, expected_panes, timeout:, cancel:) ids = expected.map { |window| target(window, :window) }.uniq pane_ids = expected_panes.map { |pane| target(pane, :pane) }.uniq names = builtin_spellings("if-shell", "display-message", "kill-session", budget: budget) - allowed = ids.empty? ? "0" : "\#{m/r:^(#{ids.join('|')})$,\#{window_id}}" - allowed_panes = pane_ids.empty? ? "0" : "\#{m/r:^(#{pane_ids.join('|')})$,\#{pane_id}}" - guard = "\#{&&:\#{==:\#{session_id},#{id}},\#{==:\#{W:\#{?#{allowed},,w}\#{P:\#{?#{allowed_panes},,p}}},}}" + allowed = ids.empty? ? "0" : "\#{m/r:^(#{ids.join("|")})$,\#{window_id}}" + allowed_panes = pane_ids.empty? ? "0" : "\#{m/r:^(#{pane_ids.join("|")})$,\#{pane_id}}" + guard = + "\#{&&:\#{==:\#{session_id},#{id}},\#{==:\#{W:\#{?#{allowed},,w}\#{P:\#{?#{allowed_panes},,p}}},}}" marker = "libtmux-membership-#{SecureRandom.hex(16)}" failure = tmux_command([names.fetch("display-message"), "-p", "--", marker]) body = tmux_command([names.fetch("kill-session"), "-t", id]) - result = execute_typed([names.fetch("if-shell"), "-F", "-t", id, guard, body, failure], **budget.options) + result = + execute_typed( + [names.fetch("if-shell"), "-F", "-t", id, guard, body, failure], + **budget.options + ) if result.stdout == "#{marker}\n" - raise TargetNotFoundError.new("session contains windows or panes outside the expected ownership sets", phase: :command, delivery: :observed) + raise TargetNotFoundError.new( + "session contains windows or panes outside the expected ownership sets", + phase: :command, + delivery: :observed + ) end result end @@ -200,23 +290,52 @@ def decode_integer(value, label) end def require_command_flag(command, flag, budget:) - result = execute_typed(["list-commands", "-F", metadata_format(%w[command_list_name command_list_usage]), command], **budget.options) + result = + execute_typed( + [ + "list-commands", + "-F", + metadata_format(%w[command_list_name command_list_usage]), + command + ], + **budget.options + ) commands = Internal::Metadata.decode(result.stdout, fields: 2, quoted: true).to_h - usage = commands.fetch(command) do - raise UnsupportedFeatureError.new("tmux does not advertise #{command}", phase: :admission) - end + usage = + commands.fetch(command) do + raise UnsupportedFeatureError.new("tmux does not advertise #{command}", phase: :admission) + end unless usage.scan(/\[-([A-Za-z]+)(?:\]|\s)/).flatten.any? { |flags| flags.include?(flag) } - raise UnsupportedFeatureError.new("tmux does not advertise #{command} -#{flag}", phase: :admission) + raise UnsupportedFeatureError.new( + "tmux does not advertise #{command} -#{flag}", + phase: :admission + ) end end def acquire_links(flags, timeout: 5.0, cancel: nil) - result = execute_typed(["list-windows", *flags, "-F", metadata_format(%w[session_id window_index window_id])], timeout: timeout, cancel: cancel) - Internal::Metadata.decode(result.stdout, fields: 3, quoted: true).map do |session_id, index, id| - ref = EntityRef.__send__(:new, binding_key: @pin.key, kind: :window_link, id: id, - session_id: session_id, index: decode_integer(index, "window index")) - WindowLink.__send__(:new, self, ref) - end.sort_by { |link| [link.ref.session_id[1..].to_i, link.index] }.freeze + result = + execute_typed( + ["list-windows", *flags, "-F", metadata_format(%w[session_id window_index window_id])], + timeout: timeout, + cancel: cancel + ) + Internal::Metadata + .decode(result.stdout, fields: 3, quoted: true) + .map do |session_id, index, id| + ref = + EntityRef.__send__( + :new, + binding_key: @pin.key, + kind: :window_link, + id: id, + session_id: session_id, + index: decode_integer(index, "window index") + ) + WindowLink.__send__(:new, self, ref) + end + .sort_by { |link| [link.ref.session_id[1..].to_i, link.index] } + .freeze end def environment_name(name) @@ -227,18 +346,36 @@ def environment_name(name) end def mutate_environment(flags, name, value, hidden:, timeout: 5.0, cancel: nil) - execute_typed(["set-environment", *flags, *(hidden ? ["-h"] : []), "--", environment_name(name), value], timeout: timeout, cancel: cancel) + execute_typed( + ["set-environment", *flags, *(hidden ? ["-h"] : []), "--", environment_name(name), value], + timeout: timeout, + cancel: cancel + ) end def read_environment(flags, name, hidden:, timeout: 5.0, cancel: nil) name = environment_name(name) - result = execute_typed(["show-environment", "-s", *flags, *(hidden ? ["-h"] : []), "--", name], timeout: timeout, cancel: cancel) + result = + execute_typed( + ["show-environment", "-s", *flags, *(hidden ? ["-h"] : []), "--", name], + timeout: timeout, + cancel: cancel + ) return nil if result.stdout == "unset #{name};\n" prefix, suffix = "#{name}=\"", "\"; export #{name};\n" unless result.stdout.start_with?(prefix) && result.stdout.end_with?(suffix) - raise ProtocolError.new("tmux returned an unexpected environment record", phase: :decode, delivery: :observed) + raise ProtocolError.new( + "tmux returned an unexpected environment record", + phase: :decode, + delivery: :observed + ) end - Internal::Metadata.unquote(result.stdout.byteslice(prefix.bytesize, result.stdout.bytesize - prefix.bytesize - suffix.bytesize)).freeze + Internal::Metadata.unquote( + result.stdout.byteslice( + prefix.bytesize, + result.stdout.bytesize - prefix.bytesize - suffix.bytesize + ) + ).freeze end end @@ -261,11 +398,23 @@ class Session def kill(expected_windows: nil, expected_panes: nil, timeout: 5.0, cancel: nil) return super(timeout: timeout, cancel: cancel) if expected_windows.nil? && expected_panes.nil? - server.__send__(:kill_session_with_windows, ref, expected_windows, expected_panes, timeout: timeout, cancel: cancel) + server.__send__( + :kill_session_with_windows, + ref, + expected_windows, + expected_panes, + timeout: timeout, + cancel: cancel + ) end def rename(name, timeout: 5.0, cancel: nil) - server.__send__(:execute_typed, ["rename-session", "-t", target, "--", server.__send__(:literal_name, name)], timeout: timeout, cancel: cancel) + server.__send__( + :execute_typed, + ["rename-session", "-t", target, "--", server.__send__(:literal_name, name)], + timeout: timeout, + cancel: cancel + ) end def list_window_links(timeout: 5.0, cancel: nil) @@ -273,66 +422,130 @@ def list_window_links(timeout: 5.0, cancel: nil) end def link_window(window, index:, timeout: 5.0, cancel: nil) - raise ArgumentError, "index must be a nonnegative Integer" unless index.is_a?(Integer) && index >= 0 + unless index.is_a?(Integer) && index >= 0 + raise ArgumentError, "index must be a nonnegative Integer" + end source = server.__send__(:target, window, :window) - server.__send__(:execute_typed, ["link-window", "-d", "-s", source, "-t", "#{target}:#{index}"], timeout: timeout, cancel: cancel) + server.__send__( + :execute_typed, + ["link-window", "-d", "-s", source, "-t", "#{target}:#{index}"], + timeout: timeout, + cancel: cancel + ) end def set_environment(name, value, hidden: false, timeout: 5.0, cancel: nil) - server.__send__(:mutate_environment, ["-t", target], name, value, hidden: hidden, timeout: timeout, cancel: cancel) + server.__send__( + :mutate_environment, + ["-t", target], + name, + value, + hidden: hidden, + timeout: timeout, + cancel: cancel + ) end def environment(name, hidden: false, timeout: 5.0, cancel: nil) - server.__send__(:read_environment, ["-t", target], name, hidden: hidden, timeout: timeout, cancel: cancel) + server.__send__( + :read_environment, + ["-t", target], + name, + hidden: hidden, + timeout: timeout, + cancel: cancel + ) end def unset_environment(name, timeout: 5.0, cancel: nil) - server.__send__(:execute_typed, ["set-environment", "-t", target, "-u", "--", server.__send__(:environment_name, name)], timeout: timeout, cancel: cancel) + server.__send__( + :execute_typed, + ["set-environment", "-t", target, "-u", "--", server.__send__(:environment_name, name)], + timeout: timeout, + cancel: cancel + ) end end class Window def rename(name, timeout: 5.0, cancel: nil) - server.__send__(:execute_typed, ["rename-window", "-t", target, "--", server.__send__(:literal_name, name)], timeout: timeout, cancel: cancel) + server.__send__( + :execute_typed, + ["rename-window", "-t", target, "--", server.__send__(:literal_name, name)], + timeout: timeout, + cancel: cancel + ) end def respawn(command:, kill: false, cwd: nil, environment: {}, timeout: 5.0, cancel: nil) budget = server.__send__(:operation_budget, timeout, cancel) args = ["respawn-window", "-t", target, *(kill ? ["-k"] : [])] args.concat(server.__send__(:creation_options, cwd: cwd, environment: environment)) - server.__send__(:execute_typed, [*args, "--", *server.__send__(:pane_command, command)], **budget.options) + server.__send__( + :execute_typed, + [*args, "--", *server.__send__(:pane_command, command)], + **budget.options + ) end def resize(width: nil, height: nil, timeout: 5.0, cancel: nil) - dimensions = {"-x" => width, "-y" => height}.flat_map do |flag, value| - next [] if value.nil? - raise ArgumentError, "dimensions must be positive Integers" unless value.is_a?(Integer) && value.positive? - - [flag, value.to_s] - end + dimensions = + { "-x" => width, "-y" => height }.flat_map do |flag, value| + next [] if value.nil? + unless value.is_a?(Integer) && value.positive? + raise ArgumentError, "dimensions must be positive Integers" + end + + [flag, value.to_s] + end raise ArgumentError, "provide width or height" if dimensions.empty? - server.__send__(:execute_typed, ["resize-window", "-t", target, *dimensions], timeout: timeout, cancel: cancel) + server.__send__( + :execute_typed, + ["resize-window", "-t", target, *dimensions], + timeout: timeout, + cancel: cancel + ) end end class Pane def select(timeout: 5.0, cancel: nil) - server.__send__(:execute_typed, ["select-pane", "-t", target], timeout: timeout, cancel: cancel) - end - - def resize(width: nil, height: nil, direction: nil, amount: 1, zoom: false, timeout: 5.0, cancel: nil) + server.__send__( + :execute_typed, + ["select-pane", "-t", target], + timeout: timeout, + cancel: cancel + ) + end + + def resize( + width: nil, + height: nil, + direction: nil, + amount: 1, + zoom: false, + timeout: 5.0, + cancel: nil + ) args = ["resize-pane", "-t", target] - {"-x" => width, "-y" => height}.each do |flag, value| + { "-x" => width, "-y" => height }.each do |flag, value| next if value.nil? - raise ArgumentError, "dimensions must be positive Integers" unless value.is_a?(Integer) && value.positive? + unless value.is_a?(Integer) && value.positive? + raise ArgumentError, "dimensions must be positive Integers" + end args.concat([flag, value.to_s]) end if direction - flag = {left: "-L", right: "-R", up: "-U", down: "-D"}.fetch(direction) { raise ArgumentError, "invalid resize direction" } - raise ArgumentError, "amount must be a positive Integer" unless amount.is_a?(Integer) && amount.positive? + flag = + { left: "-L", right: "-R", up: "-U", down: "-D" }.fetch(direction) do + raise ArgumentError, "invalid resize direction" + end + unless amount.is_a?(Integer) && amount.positive? + raise ArgumentError, "amount must be a positive Integer" + end args.concat([flag, amount.to_s]) end @@ -341,15 +554,34 @@ def resize(width: nil, height: nil, direction: nil, amount: 1, zoom: false, time end def swap(other, timeout: 5.0, cancel: nil) - server.__send__(:execute_typed, ["swap-pane", "-d", "-s", target, "-t", server.__send__(:target, other, :pane)], timeout: timeout, cancel: cancel) + server.__send__( + :execute_typed, + ["swap-pane", "-d", "-s", target, "-t", server.__send__(:target, other, :pane)], + timeout: timeout, + cancel: cancel + ) end def join(other, direction:, before: false, timeout: 5.0, cancel: nil) - reposition("join-pane", other, direction: direction, before: before, timeout: timeout, cancel: cancel) + reposition( + "join-pane", + other, + direction: direction, + before: before, + timeout: timeout, + cancel: cancel + ) end def move(other, direction:, before: false, timeout: 5.0, cancel: nil) - reposition("move-pane", other, direction: direction, before: before, timeout: timeout, cancel: cancel) + reposition( + "move-pane", + other, + direction: direction, + before: before, + timeout: timeout, + cancel: cancel + ) end # Exact tmux 3.7 ignores -n on break-pane and crashes without it, so the @@ -359,21 +591,55 @@ def break_out(session:, name:, timeout: 5.0, cancel: nil) budget = server.__send__(:operation_budget, timeout, cancel) destination = server.__send__(:target, session, :session) literal = server.__send__(:literal_name, name) - repaired = Internal::Capabilities.workaround("break-pane-misnames-windows").applies?(server.__send__(:tmux_release)) - result = server.__send__(:execute_typed, ["break-pane", "-d", "-P", "-F", server.__send__(:id_format, :window), - "-s", target, "-t", "#{destination}:", "-n", literal], repaired_break: repaired, **budget.options) + repaired = + Internal::Capabilities.workaround("break-pane-misnames-windows").applies?( + server.__send__(:tmux_release) + ) + result = + server.__send__( + :execute_typed, + [ + "break-pane", + "-d", + "-P", + "-F", + server.__send__(:id_format, :window), + "-s", + target, + "-t", + "#{destination}:", + "-n", + literal + ], + repaired_break: repaired, + **budget.options + ) id = result.stdout.empty? ? nil : result.stdout if id.nil? - located = server.__send__(:execute_typed, ["list-panes", "-t", target, "-F", server.__send__(:id_format, :window)], - **budget.options) + located = + server.__send__( + :execute_typed, + ["list-panes", "-t", target, "-F", server.__send__(:id_format, :window)], + **budget.options + ) id = located.stdout.lines.first.to_s end rows = Internal::Metadata.decode(id, fields: 1, max_rows: 1) - raise ProtocolError.new("tmux did not return the broken-out window ID", delivery: :observed, phase: :decode) unless rows.length == 1 + unless rows.length == 1 + raise ProtocolError.new( + "tmux did not return the broken-out window ID", + delivery: :observed, + phase: :decode + ) + end window = server.__send__(:build_entity, :window, rows.first.first) if repaired - server.__send__(:execute_typed, ["rename-window", "-t", window.id, "--", literal], **budget.options) + server.__send__( + :execute_typed, + ["rename-window", "-t", window.id, "--", literal], + **budget.options + ) end window end @@ -382,7 +648,11 @@ def respawn(command:, kill: false, cwd: nil, environment: {}, timeout: 5.0, canc budget = server.__send__(:operation_budget, timeout, cancel) args = ["respawn-pane", "-t", target, *(kill ? ["-k"] : [])] args.concat(server.__send__(:creation_options, cwd: cwd, environment: environment)) - server.__send__(:execute_typed, [*args, "--", *server.__send__(:pane_command, command)], **budget.options) + server.__send__( + :execute_typed, + [*args, "--", *server.__send__(:pane_command, command)], + **budget.options + ) end def paste(buffer:, delete: false, bracketed: false, separator: nil, timeout: 5.0, cancel: nil) @@ -395,7 +665,14 @@ def paste(buffer:, delete: false, bracketed: false, separator: nil, timeout: 5.0 # The shell command and its format expansion are explicitly requested here. # only_if_closed follows tmux -o: an existing pipe is closed, not retained. - def pipe(shell_command: nil, input: false, output: true, only_if_closed: false, timeout: 5.0, cancel: nil) + def pipe( + shell_command: nil, + input: false, + output: true, + only_if_closed: false, + timeout: 5.0, + cancel: nil + ) if shell_command && !input && !output raise ArgumentError, "a pipe command requires input or output" end @@ -407,10 +684,25 @@ def pipe(shell_command: nil, input: false, output: true, only_if_closed: false, server.__send__(:execute_typed, args, timeout: timeout, cancel: cancel) end - def copy_mode(scroll_up: false, exit_on_bottom: false, mouse_drag: false, cancel_mode: false, page_down: false, source: nil, timeout: 5.0, cancel: nil) + def copy_mode( + scroll_up: false, + exit_on_bottom: false, + mouse_drag: false, + cancel_mode: false, + page_down: false, + source: nil, + timeout: 5.0, + cancel: nil + ) budget = server.__send__(:operation_budget, timeout, cancel) args = ["copy-mode", "-t", target] - {"u" => scroll_up, "e" => exit_on_bottom, "M" => mouse_drag, "q" => cancel_mode, "d" => page_down}.each do |flag, enabled| + { + "u" => scroll_up, + "e" => exit_on_bottom, + "M" => mouse_drag, + "q" => cancel_mode, + "d" => page_down + }.each do |flag, enabled| next unless enabled server.__send__(:require_command_flag, "copy-mode", flag, budget: budget) @@ -424,13 +716,21 @@ def copy_mode(scroll_up: false, exit_on_bottom: false, mouse_drag: false, cancel end def copy_command(command, *arguments, timeout: 5.0, cancel: nil) - server.__send__(:execute_typed, ["send-keys", "-X", "-t", target, "--", command, *arguments], timeout: timeout, cancel: cancel) + server.__send__( + :execute_typed, + ["send-keys", "-X", "-t", target, "--", command, *arguments], + timeout: timeout, + cancel: cancel + ) end private def reposition(command, other, direction:, before:, timeout:, cancel:) - flag = {horizontal: "-h", vertical: "-v"}.fetch(direction) { raise ArgumentError, "invalid split direction" } + flag = + { horizontal: "-h", vertical: "-v" }.fetch(direction) do + raise ArgumentError, "invalid split direction" + end args = [command, "-d", flag, "-s", target, "-t", server.__send__(:target, other, :pane)] args << "-b" if before server.__send__(:execute_typed, args, timeout: timeout, cancel: cancel) diff --git a/gems/libtmux/lib/libtmux/option_catalog.rb b/gems/libtmux/lib/libtmux/option_catalog.rb index 5abfdce5..a9d9b2ea 100644 --- a/gems/libtmux/lib/libtmux/option_catalog.rb +++ b/gems/libtmux/lib/libtmux/option_catalog.rb @@ -36,10 +36,19 @@ def initialize(name, scopes) private_class_method :new end - data = JSON.parse(File.binread(File.expand_path("../../schema/option-catalog.json", __dir__)), freeze: true) + data = + JSON.parse( + File.binread(File.expand_path("../../schema/option-catalog.json", __dir__)), + freeze: true + ) TMUX_VERSION = data.fetch("tmux_version") - OPTIONS = data.fetch("options").to_h { |name, definition| [name, Option.__send__(:new, name, definition)] }.freeze - HOOKS = data.fetch("hooks").to_h { |name, scopes| [name, Hook.__send__(:new, name, scopes)] }.freeze + OPTIONS = + data + .fetch("options") + .to_h { |name, definition| [name, Option.__send__(:new, name, definition)] } + .freeze + HOOKS = + data.fetch("hooks").to_h { |name, scopes| [name, Hook.__send__(:new, name, scopes)] }.freeze private_constant :TMUX_VERSION, :OPTIONS, :HOOKS # The source release for both catalogs, independent of any connected daemon. diff --git a/gems/libtmux/lib/libtmux/options.rb b/gems/libtmux/lib/libtmux/options.rb index 300f09dd..4b1c21cb 100644 --- a/gems/libtmux/lib/libtmux/options.rb +++ b/gems/libtmux/lib/libtmux/options.rb @@ -26,22 +26,36 @@ def present? def as(type) case type - when :bytes then raw + when :bytes + raw when :string text = raw.dup.force_encoding(Encoding::UTF_8) - raise FieldDecodeError.new("option is not valid UTF-8", phase: :decode, delivery: :observed) unless text.valid_encoding? + unless text.valid_encoding? + raise FieldDecodeError.new( + "option is not valid UTF-8", + phase: :decode, + delivery: :observed + ) + end text.freeze when :integer - raise FieldDecodeError.new("option is not an integer", phase: :decode, delivery: :observed) unless raw.match?(/\A-?\d+\z/) + unless raw.match?(/\A-?\d+\z/) + raise FieldDecodeError.new( + "option is not an integer", + phase: :decode, + delivery: :observed + ) + end Integer(raw, 10) when :boolean - return true if ["on", "1"].include?(raw) - return false if ["off", "0"].include?(raw) + return true if %w[on 1].include?(raw) + return false if %w[off 0].include?(raw) raise FieldDecodeError.new("option is not a boolean", phase: :decode, delivery: :observed) - else raise ArgumentError, "type must be :bytes, :string, :integer or :boolean" + else + raise ArgumentError, "type must be :bytes, :string, :integer or :boolean" end end end @@ -50,7 +64,8 @@ def as(type) # option types, scopes and allowed values, see {OptionCatalog.options}. class Options # tmux prints the user option name as-is and its value as one args_escape token. - USER_OPTION_RECORD = / + USER_OPTION_RECORD = + / \A(@[^\n]*)[ ] ("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|(?:[^\s"'\\]|\\[^\s])+) \n\z @@ -66,7 +81,10 @@ def initialize(server, ref: nil, scope: nil) def list(name: nil, inherited: false, timeout: 5.0, cancel: nil) hooks = is_a?(Hooks) if inherited && hooks - raise UnsupportedFeatureError.new("inherited hook acquisition is not implemented", phase: :admission) + raise UnsupportedFeatureError.new( + "inherited hook acquisition is not implemented", + phase: :admission + ) end command = hooks ? "show-hooks" : "show-options" args = [command, *scope_flags] @@ -74,30 +92,58 @@ def list(name: nil, inherited: false, timeout: 5.0, cancel: nil) args.concat(["--", option_name(name)]) if name result = @server.__send__(:execute_typed, args, timeout: timeout, cancel: cancel) user_keys = {} - result.stdout.lines.map do |line| - user_option = !hooks && line.start_with?("@") - pattern = user_option ? USER_OPTION_RECORD : /\A(@[^\s\[\]]*|[^\s\[\]*]+)(?:\[(\d+)\])?(\*)?(?: (.*))?\n\z/n - match = pattern.match(line) - raise ProtocolError.new("malformed escaped option record", phase: :decode, delivery: :observed) unless match - - if user_option - key, value = match.captures - index = nil - # Only named reads print inherited user options and append '*'. - parent = inherited && name ? key == "#{name.b}*" : false - key = name.b if parent - if user_keys[key] - raise ProtocolError.new("duplicate user option record", phase: :decode, delivery: :observed) + result + .stdout + .lines + .map do |line| + user_option = !hooks && line.start_with?("@") + pattern = + ( + if user_option + USER_OPTION_RECORD + else + /\A(@[^\s\[\]]*|[^\s\[\]*]+)(?:\[(\d+)\])?(\*)?(?: (.*))?\n\z/n + end + ) + match = pattern.match(line) + unless match + raise ProtocolError.new( + "malformed escaped option record", + phase: :decode, + delivery: :observed + ) end - user_keys[key] = true - else - key, index, parent_marker, value = match.captures - parent = !parent_marker.nil? + + if user_option + key, value = match.captures + index = nil + # Only named reads print inherited user options and append '*'. + parent = inherited && name ? key == "#{name.b}*" : false + key = name.b if parent + if user_keys[key] + raise ProtocolError.new( + "duplicate user option record", + phase: :decode, + delivery: :observed + ) + end + user_keys[key] = true + else + key, index, parent_marker, value = match.captures + parent = !parent_marker.nil? + end + raw = hooks ? (value || "".b) : decode_escaped(value || "".b) + OptionValue.__send__( + :new, + name: key, + index: index && Integer(index, 10), + raw: raw, + inherited: parent, + array: !index.nil? || value.nil?, + present: !value.nil? + ) end - raw = hooks ? (value || "".b) : decode_escaped(value || "".b) - OptionValue.__send__(:new, name: key, index: index && Integer(index, 10), raw: raw, - inherited: parent, array: !index.nil? || value.nil?, present: !value.nil?) - end.freeze + .freeze end def get(name, index: nil, inherited: true, timeout: 5.0, cancel: nil) @@ -109,39 +155,66 @@ def get(name, index: nil, inherited: true, timeout: 5.0, cancel: nil) values = list(name: name, inherited: inherited, timeout: timeout, cancel: cancel) values = values.select { |value| value.index == index } unless index.nil? if values.empty? - raise NoMatchError.new("option is absent at the requested scope", phase: :decode, delivery: :observed) + raise NoMatchError.new( + "option is absent at the requested scope", + phase: :decode, + delivery: :observed + ) end unless values.length == 1 - raise MultipleMatchesError.new("option has multiple array entries; provide an index", phase: :decode, delivery: :observed) + raise MultipleMatchesError.new( + "option has multiple array entries; provide an index", + phase: :decode, + delivery: :observed + ) end values.first end def set(name, value, index: nil, append: false, timeout: 5.0, cancel: nil) - value = case value - when true then "on" - when false then "off" - when Integer then value.to_s - when String then value - else raise ArgumentError, "option value must be String, Integer or boolean" - end - mutate("set-option", name, value, index: index, append: append, timeout: timeout, cancel: cancel) + value = + case value + when true + "on" + when false + "off" + when Integer + value.to_s + when String + value + else + raise ArgumentError, "option value must be String, Integer or boolean" + end + mutate( + "set-option", + name, + value, + index: index, + append: append, + timeout: timeout, + cancel: cancel + ) end def unset(name, index: nil, timeout: 5.0, cancel: nil) command = is_a?(Hooks) ? "set-hook" : "set-option" - @server.__send__(:execute_typed, [command, *scope_flags, "-u", "--", option_name(indexed_name(name, index))], timeout: timeout, cancel: cancel) + @server.__send__( + :execute_typed, + [command, *scope_flags, "-u", "--", option_name(indexed_name(name, index))], + timeout: timeout, + cancel: cancel + ) end private def scope_flags if @ref - flags = {session: [], window: ["-w"], pane: ["-p"]}.fetch(@ref.kind) + flags = { session: [], window: ["-w"], pane: ["-p"] }.fetch(@ref.kind) [*flags, "-t", @server.__send__(:target, @ref, @ref.kind)] else - {server: ["-s"], session: ["-g"], window: ["-g", "-w"]}.fetch(@scope) do + { server: ["-s"], session: ["-g"], window: %w[-g -w] }.fetch(@scope) do raise ArgumentError, "scope must be :server, :session or :window" end end @@ -157,7 +230,9 @@ def option_name(name) def indexed_name(name, index) return name if index.nil? - raise ArgumentError, "index must be a nonnegative Integer" unless index.is_a?(Integer) && index >= 0 + unless index.is_a?(Integer) && index >= 0 + raise ArgumentError, "index must be a nonnegative Integer" + end "#{name}[#{index}]" end @@ -165,18 +240,37 @@ def indexed_name(name, index) def mutate(command, name, value, index:, append:, timeout:, cancel:) args = [command, *scope_flags] args << "-a" if append - @server.__send__(:execute_typed, [*args, "--", option_name(indexed_name(name, index)), value], timeout: timeout, cancel: cancel) + @server.__send__( + :execute_typed, + [*args, "--", option_name(indexed_name(name, index)), value], + timeout: timeout, + cancel: cancel + ) end # show-options uses args_escape (VIS_OCTAL|VIS_CSTYLE), not shell escaping. def decode_escaped(value) if value.start_with?("'", '"') unless value.end_with?(value.byteslice(0, 1)) && value.bytesize >= 2 - raise ProtocolError.new("unterminated escaped option value", phase: :decode, delivery: :observed) + raise ProtocolError.new( + "unterminated escaped option value", + phase: :decode, + delivery: :observed + ) end value = value.byteslice(1, value.bytesize - 2) end - escapes = {"a" => "\a", "b" => "\b", "t" => "\t", "n" => "\n", "v" => "\v", "f" => "\f", "r" => "\r", "s" => " ", "E" => "\e"} + escapes = { + "a" => "\a", + "b" => "\b", + "t" => "\t", + "n" => "\n", + "v" => "\v", + "f" => "\f", + "r" => "\r", + "s" => " ", + "E" => "\e" + } value.gsub(/\\([0-7]{3}|.)/n) do escaped = Regexp.last_match(1) if escaped.match?(/\A[0-7]{3}\z/) @@ -198,11 +292,24 @@ def get(name, index: nil, inherited: false, timeout: 5.0, cancel: nil) def set(name, command:, index: nil, append: false, timeout: 5.0, cancel: nil) raise ArgumentError, "command must be a String" unless command.is_a?(String) - mutate("set-hook", name, command, index: index, append: append, timeout: timeout, cancel: cancel) + mutate( + "set-hook", + name, + command, + index: index, + append: append, + timeout: timeout, + cancel: cancel + ) end def run(name, timeout: 5.0, cancel: nil) - @server.__send__(:execute_typed, ["set-hook", *scope_flags, "-R", "--", option_name(name)], timeout: timeout, cancel: cancel) + @server.__send__( + :execute_typed, + ["set-hook", *scope_flags, "-R", "--", option_name(name)], + timeout: timeout, + cancel: cancel + ) end end end diff --git a/gems/libtmux/lib/libtmux/owned.rb b/gems/libtmux/lib/libtmux/owned.rb index 15619583..81cd67ef 100644 --- a/gems/libtmux/lib/libtmux/owned.rb +++ b/gems/libtmux/lib/libtmux/owned.rb @@ -33,7 +33,9 @@ def initialize(executable:, config:, timeout:, cancel:) raise ArgumentError, "config must be a nonempty filename without NUL" end config = config ? File.expand_path(config) : File::NULL - raise ArgumentError, "config must be a readable regular file" unless File.file?(config) && File.readable?(config) || config == File::NULL + unless File.file?(config) && File.readable?(config) || config == File::NULL + raise ArgumentError, "config must be a readable regular file" + end @owner_pid = Process.pid @mutex = Mutex.new @@ -45,9 +47,13 @@ def initialize(executable:, config:, timeout:, cancel:) begin check_cancel(cancel) @directory = Dir.mktmpdir("libtmux-ruby-server-") - @endpoint = Endpoint.new(socket_path: File.join(@directory, "socket"), executable: executable) + @endpoint = + Endpoint.new(socket_path: File.join(@directory, "socket"), executable: executable) if @endpoint.socket_path.bytesize > 103 - raise UnsupportedFeatureError.new("owned Unix socket path exceeds the platform limit", phase: :startup) + raise UnsupportedFeatureError.new( + "owned Unix socket path exceeds the platform limit", + phase: :startup + ) end Internal::TmuxVersion.executable(@endpoint.executable) do |argv| ProcessExecutor.new.run(argv, timeout: deadline - clock, cancel: cancel) @@ -58,11 +64,29 @@ def initialize(executable:, config:, timeout:, cancel:) begin check_cancel(cancel) check_deadline(deadline) - pid = Process.spawn({"TMUX" => nil, "TMUX_PANE" => nil}, - @endpoint.executable, "-u", "-D", *@readiness.arguments, "-S", @endpoint.socket_path, "-f", config, - in: File::NULL, out: File::NULL, err: File::NULL, close_others: true, **@readiness.spawn_options) + pid = + Process.spawn( + { "TMUX" => nil, "TMUX_PANE" => nil }, + @endpoint.executable, + "-u", + "-D", + *@readiness.arguments, + "-S", + @endpoint.socket_path, + "-f", + config, + in: File::NULL, + out: File::NULL, + err: File::NULL, + close_others: true, + **@readiness.spawn_options + ) rescue SystemCallError, IOError => error - raise TransportError.new("owned daemon could not start (#{error.class})", phase: :spawn), cause: nil + raise TransportError.new( + "owned daemon could not start (#{error.class})", + phase: :spawn + ), + cause: nil ensure @child.spawned(pid) end @@ -116,7 +140,11 @@ def close @child.finish_signalling end unless @child.join((deadline - clock).clamp(0, 0.5)) - raise DeadlineExceeded.new("owned daemon has not retired; retry close", phase: :retire, pid: @child.pid) + raise DeadlineExceeded.new( + "owned daemon has not retired; retry close", + phase: :retire, + pid: @child.pid + ) end end attempt(errors, "observer close") { @child.close } if @child.complete? @@ -124,7 +152,9 @@ def close if !@child || @child.complete? attempt(errors, "startup log removal") { @readiness&.remove_files(@child&.pid) } attempt(errors, "socket removal") do - File.unlink(@endpoint.socket_path) if @endpoint && File.exist?(@endpoint.socket_path) + if @endpoint && File.exist?(@endpoint.socket_path) + File.unlink(@endpoint.socket_path) + end end attempt(errors, "owned directory removal") do Dir.rmdir(@directory) if @directory && File.exist?(@directory) @@ -138,8 +168,13 @@ def close @observer_fault_reported = true end unless errors.empty? - raise TransportError.new("owned daemon cleanup failed", phase: :retire, - pid: @child&.pid, delivery: @child&.pid ? :possibly_sent : :not_sent, cleanup_errors: errors) + raise TransportError.new( + "owned daemon cleanup failed", + phase: :retire, + pid: @child&.pid, + delivery: @child&.pid ? :possibly_sent : :not_sent, + cleanup_errors: errors + ) end end end @@ -151,8 +186,12 @@ def close def await_ready(deadline, cancel) loop do if @child.observed? || @child.observation_error || @child.complete? - raise TransportError.new("owned tmux daemon exited before becoming ready", phase: :startup, - pid: @child.pid, delivery: :possibly_sent) + raise TransportError.new( + "owned tmux daemon exited before becoming ready", + phase: :startup, + pid: @child.pid, + delivery: :possibly_sent + ) end if @readiness.ready?(@child) check_deadline(deadline) @@ -166,22 +205,35 @@ def await_ready(deadline, cancel) IO.select(readers, nil, nil, [deadline - clock, 0].max) end rescue IOError, SystemCallError - raise TransportError.new("owned daemon readiness failed", phase: :startup, - pid: @child.pid, delivery: :possibly_sent), cause: nil + raise TransportError.new( + "owned daemon readiness failed", + phase: :startup, + pid: @child.pid, + delivery: :possibly_sent + ), + cause: nil end def check_cancel(cancel) return unless cancel&.cancelled? - raise Cancelled.new("owned daemon startup cancelled", phase: :startup, - delivery: @child&.pid ? :possibly_sent : :not_sent, pid: @child&.pid) + raise Cancelled.new( + "owned daemon startup cancelled", + phase: :startup, + delivery: @child&.pid ? :possibly_sent : :not_sent, + pid: @child&.pid + ) end def check_deadline(deadline) return if clock < deadline - raise DeadlineExceeded.new("owned daemon startup exceeded deadline", phase: :startup, - delivery: @child&.pid ? :possibly_sent : :not_sent, pid: @child&.pid) + raise DeadlineExceeded.new( + "owned daemon startup exceeded deadline", + phase: :startup, + delivery: @child&.pid ? :possibly_sent : :not_sent, + pid: @child&.pid + ) end def clock @@ -207,7 +259,13 @@ def initialize(executable: "tmux", config: nil, timeout: 5.0, cancel: nil, **opt begin Thread.handle_interrupt(Exception => :never) do @startup_budget = operation_budget(timeout, cancel) - @daemon = OwnedDaemon.new(executable: executable, config: config, timeout: timeout, cancel: cancel) + @daemon = + OwnedDaemon.new( + executable: executable, + config: config, + timeout: timeout, + cancel: cancel + ) super(endpoint: @daemon.endpoint, **options) @binding_ready = true @startup_budget.options @@ -217,7 +275,12 @@ def initialize(executable: "tmux", config: nil, timeout: 5.0, cancel: nil, **opt begin Thread.handle_interrupt(Exception => :never) { close } rescue Exception => cleanup - failure.__send__(:attach_cleanup_errors, ["owned daemon close failed (#{cleanup.class})"]) if failure.is_a?(Error) + if failure.is_a?(Error) + failure.__send__( + :attach_cleanup_errors, + ["owned daemon close failed (#{cleanup.class})"] + ) + end end raise failure ensure @@ -241,7 +304,12 @@ def close begin @daemon&.close rescue Exception => cleanup - failure.__send__(:attach_cleanup_errors, ["owned daemon close failed (#{cleanup.class})"]) if failure.is_a?(Error) + if failure.is_a?(Error) + failure.__send__( + :attach_cleanup_errors, + ["owned daemon close failed (#{cleanup.class})"] + ) + end failure ||= cleanup end end diff --git a/gems/libtmux/lib/libtmux/process.rb b/gems/libtmux/lib/libtmux/process.rb index 1de5af17..b5d51c4f 100644 --- a/gems/libtmux/lib/libtmux/process.rb +++ b/gems/libtmux/lib/libtmux/process.rb @@ -26,13 +26,18 @@ def delivery end def text(invalid: :strict) - raise ArgumentError, "invalid text policy" unless [:strict, :replace].include?(invalid) + raise ArgumentError, "invalid text policy" unless %i[strict replace].include?(invalid) text = stdout.dup.force_encoding(Encoding::UTF_8) return text.scrub if invalid == :replace return text if text.valid_encoding? - raise FieldDecodeError.new("command stdout is not valid UTF-8", delivery: delivery, phase: :decode, pid: pid) + raise FieldDecodeError.new( + "command stdout is not valid UTF-8", + delivery: delivery, + phase: :decode, + pid: pid + ) end def inspect @@ -69,22 +74,24 @@ def close return detach unless @creator_pid == Process.pid cancel - @mutex.synchronize do - [@reader, @writer].each { |io| io.close unless io.closed? } - end + @mutex.synchronize { [@reader, @writer].each { |io| io.close unless io.closed? } } end private def detach - raise ArgumentError, "only a forked child may detach this token" if @creator_pid == Process.pid + if @creator_pid == Process.pid + raise ArgumentError, "only a forked child may detach this token" + end [@reader, @writer].each { |io| io.close unless io.closed? } nil end def ensure_owner - raise ClosedError.new("cancellation token belongs to another process", phase: :admission) unless @creator_pid == Process.pid + unless @creator_pid == Process.pid + raise ClosedError.new("cancellation token belongs to another process", phase: :admission) + end end end @@ -121,14 +128,30 @@ def append(chunk) 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) + 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| - raise ArgumentError, "byte limits must be nonnegative integers" unless limit.is_a?(Integer) && limit >= 0 + unless limit.is_a?(Integer) && limit >= 0 + raise ArgumentError, "byte limits must be nonnegative integers" + end end [cleanup_timeout, drain_timeout].each do |timeout| - raise ArgumentError, "cleanup and drain deadlines must be positive and finite" unless timeout.is_a?(Numeric) && timeout.finite? && timeout.positive? + unless timeout.is_a?(Numeric) && timeout.finite? && timeout.positive? + raise ArgumentError, "cleanup and drain deadlines must be positive and finite" + end end - @limits = {stdout: stdout_limit, stderr: stderr_limit, input: input_limit, argv: argv_limit}.freeze + @limits = { + stdout: stdout_limit, + stderr: stderr_limit, + input: input_limit, + argv: argv_limit + }.freeze @cleanup_timeout = cleanup_timeout @drain_timeout = drain_timeout end @@ -136,23 +159,60 @@ 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, stdout_tail: nil) - Execution.new(argv, input, env, timeout, cancel, @limits, @cleanup_timeout, @drain_timeout, - discard_stdout, stdout_tail).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, stdout_tail) + 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") } + 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" end raise ArgumentError, "input must be a String" unless input.is_a?(String) - raise ArgumentError, "timeout must be finite" unless timeout.is_a?(Numeric) && timeout.finite? - if input.bytesize > limits.fetch(:input) || argv.sum { |argument| argument.bytesize + 1 } > limits.fetch(:argv) - raise CapacityError.new("command input exceeded its byte limit", delivery: :not_sent, phase: :admission) + unless timeout.is_a?(Numeric) && timeout.finite? + raise ArgumentError, "timeout must be finite" + end + if input.bytesize > limits.fetch(:input) || + argv.sum { |argument| argument.bytesize + 1 } > limits.fetch(:argv) + raise CapacityError.new( + "command input exceeded its byte limit", + delivery: :not_sent, + phase: :admission + ) end @argv = argv.map { |argument| argument.dup.freeze }.freeze @@ -166,8 +226,10 @@ def initialize(argv, input, env, timeout, cancel, limits, cleanup_timeout, drain @discard_stdout = discard_stdout @process_wait = ProcessWait.new @owned = [] - @buffers = {stdout: CommandOutput.new(limits.fetch(:stdout), tail: stdout_tail), - stderr: CommandOutput.new(limits.fetch(:stderr))} + @buffers = { + stdout: CommandOutput.new(limits.fetch(:stdout), tail: stdout_tail), + stderr: CommandOutput.new(limits.fetch(:stderr)) + } @offset = 0 end @@ -188,7 +250,12 @@ def call if error.is_a?(Error) error.send(:attach_cleanup_errors, cleanup_errors) elsif error.nil? && !cleanup_errors.empty? - error = TransportError.new("command cleanup failed", **details(:retire), cleanup_errors: cleanup_errors) + error = + TransportError.new( + "command cleanup failed", + **details(:retire), + cleanup_errors: cleanup_errors + ) end end end @@ -226,19 +293,28 @@ def spawn @exit_reader = @child.reader @owned << @exit_reader begin - @pid = Process.spawn(@env, [@argv.first, @argv.first], *@argv.drop(1), - in: child_input, out: child_output, err: child_error, close_others: true) + @pid = + Process.spawn( + @env, + [@argv.first, @argv.first], + *@argv.drop(1), + in: child_input, + out: child_output, + err: child_error, + close_others: true + ) ensure @child.spawned(@pid) end [child_input, child_output, child_error].each(&:close) @input_writer.close if @input.empty? rescue SystemCallError, IOError => error - raise TransportError.new("could not start command (#{error.class})", **details(:spawn)), cause: nil + raise TransportError.new("could not start command (#{error.class})", **details(:spawn)), + cause: nil end def communicate - reading = {@error_reader => :stderr} + reading = { @error_reader => :stderr } reading[@output_reader] = :stdout if @output_reader loop do return result if @status && reading.empty? @@ -274,7 +350,8 @@ def communicate end rescue SystemCallError, IOError => error check_cancel(:read) unless @status - raise TransportError.new("command I/O failed (#{error.class})", **details(:read)), cause: nil + raise TransportError.new("command I/O failed (#{error.class})", **details(:read)), + cause: nil end def read_output(io, reading) @@ -306,16 +383,27 @@ def check_cancel(phase) def check_deadline(phase) deadline = [@deadline, @drain_deadline || @deadline].min - raise DeadlineExceeded.new("command deadline exceeded", **details(phase)) if monotonic >= deadline + if monotonic >= deadline + raise DeadlineExceeded.new("command deadline exceeded", **details(phase)) + end end def details(phase) - {delivery: @status ? :observed : (@pid ? :possibly_sent : :not_sent), phase: phase, pid: @pid} + { + delivery: @status ? :observed : (@pid ? :possibly_sent : :not_sent), + phase: phase, + pid: @pid + } end def result - CommandResult.new(**@buffers.transform_values(&:bytes), 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 @@ -343,8 +431,12 @@ def retire else errors << "owned client cleanup remains pending after its deadline" end - errors << "command exit observation failed (#{@child.observation_error.class})" if @child.observation_error - errors << "command fallback reap failed (#{@child.retirement_error.class})" if @child.retirement_error + if @child.observation_error + errors << "command exit observation failed (#{@child.observation_error.class})" + end + if @child.retirement_error + errors << "command fallback reap failed (#{@child.retirement_error.class})" + end errors rescue StandardError => error errors << "command waiter failed (#{error.class})" diff --git a/gems/libtmux/lib/libtmux/process_wait.rb b/gems/libtmux/lib/libtmux/process_wait.rb index 1f20afa2..1485d5d2 100644 --- a/gems/libtmux/lib/libtmux/process_wait.rb +++ b/gems/libtmux/lib/libtmux/process_wait.rb @@ -13,7 +13,10 @@ class ProcessWait def initialize unless Fiddle::SIZEOF_INT == 4 - raise UnsupportedFeatureError.new("native process waiting requires a 32-bit C int", phase: :admission) + raise UnsupportedFeatureError.new( + "native process waiting requires a 32-bit C int", + phase: :admission + ) end # Native wait.h values differ: Linux WNOWAIT=0x01000000, Darwin=0x20. @@ -23,21 +26,32 @@ def initialize @information_size = 128 # Linux siginfo_t has a fixed 128-byte ABI. when /darwin/ @options = WEXITED | 0x00000020 - @information_size = 6 * Fiddle::SIZEOF_INT + 2 * Fiddle::SIZEOF_VOIDP + 8 * Fiddle::SIZEOF_LONG + @information_size = + 6 * Fiddle::SIZEOF_INT + 2 * Fiddle::SIZEOF_VOIDP + 8 * Fiddle::SIZEOF_LONG else - raise UnsupportedFeatureError.new("native process waiting is unavailable on this platform", phase: :admission) + raise UnsupportedFeatureError.new( + "native process waiting is unavailable on this platform", + phase: :admission + ) end - @waitid = Fiddle::Function.new(Fiddle::Handle::DEFAULT["waitid"], - [Fiddle::TYPE_INT, Fiddle::TYPE_INT, Fiddle::TYPE_VOIDP, Fiddle::TYPE_INT], - Fiddle::TYPE_INT, need_gvl: false) + @waitid = + Fiddle::Function.new( + Fiddle::Handle::DEFAULT["waitid"], + [Fiddle::TYPE_INT, Fiddle::TYPE_INT, Fiddle::TYPE_VOIDP, Fiddle::TYPE_INT], + Fiddle::TYPE_INT, + need_gvl: false + ) verify_available rescue Fiddle::DLError - raise UnsupportedFeatureError.new("native waitid is unavailable", phase: :admission), cause: nil + raise UnsupportedFeatureError.new("native waitid is unavailable", phase: :admission), + cause: nil end def observe(pid) - raise ArgumentError, "child PID must be a positive integer" unless pid.is_a?(Integer) && pid.positive? + unless pid.is_a?(Integer) && pid.positive? + raise ArgumentError, "child PID must be a positive integer" + end Fiddle::Pointer.malloc(@information_size, Fiddle::RUBY_FREE) do |information| loop do @@ -59,7 +73,10 @@ def verify_available status = @waitid.call(P_PID, Process.pid, information, @options | WNOHANG) return if status == -1 && Fiddle.last_error == Errno::ECHILD::Errno end - raise UnsupportedFeatureError.new("native non-reaping process observation is unavailable", phase: :admission) + raise UnsupportedFeatureError.new( + "native non-reaping process observation is unavailable", + phase: :admission + ) end end end diff --git a/gems/libtmux/lib/libtmux/program.rb b/gems/libtmux/lib/libtmux/program.rb index 0034de04..a334b0c8 100644 --- a/gems/libtmux/lib/libtmux/program.rb +++ b/gems/libtmux/lib/libtmux/program.rb @@ -21,7 +21,8 @@ def self.run_program(argv, **options) # 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 + class ScreenGeometryError < CapacityError + end # A UTF-8 capture of the retained rows. Truncation records the byte cap. class Screen @@ -67,20 +68,38 @@ def inspect 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 + 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) } + factory.start_program(argv, **options, **budget.options) do |program| + program.wait(**budget.options) + end 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) + 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 server.nil? || server.is_a?(Server) + raise ArgumentError, "server must be a LibTmux::Server" + end unless history_lines.is_a?(Integer) && (0..HISTORY_LINES).cover?(history_lines) raise ArgumentError, "history_lines must be between 0 and #{HISTORY_LINES}" end @@ -112,7 +131,8 @@ def self.start_with(adapter, argv, server: nil, executable: "tmux", cwd: nil, en 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) } + 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 @@ -166,7 +186,8 @@ def wait(timeout: 5.0, cancel: nil) # 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 + 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)) @@ -208,8 +229,13 @@ def send_keys(*keys, timeout: 5.0, cancel: nil) 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) + guarded( + "resize-window", + ["-t", @window.id, "-x", width.to_s, "-y", height.to_s], + window: @window.id, + timeout: timeout, + cancel: cancel + ) end def close @@ -250,14 +276,26 @@ 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]) + 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) + 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) + 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 @@ -319,23 +357,50 @@ def launch(argv, cwd, environment, width, height, budget) @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) + File.open(File.join(@directory, "argv"), "wb", 0o600) do |io| + io.write(argv.map(&:b).join("\0".b)) + end + @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 + 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 + 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 @@ -345,10 +410,18 @@ def launch(argv, cwd, environment, width, height, budget) @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) + 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) + raise OutcomeUnknown.new( + "program supervisor disconnected during launch", + phase: :spawn, + delivery: :possibly_sent + ) end def open_candidate(name, target, budget) @@ -367,8 +440,13 @@ def open_candidate(name, target, budget) 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) + 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 @@ -383,7 +461,9 @@ def claim_pending(budget) 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 + if @handshake.bytesize > 24 + raise ProtocolError.new("invalid program helper identity", phase: :admission) + end end unless @handshake.match?(/\A[1-9]\d*\n\z/) raise ProtocolError.new("invalid program helper PID", phase: :admission) @@ -410,15 +490,28 @@ def read_status 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 + unless part + raise OutcomeUnknown.new( + "program supervisor closed before reporting exit", + phase: :command, + delivery: :possibly_sent + ) + end @status_bytes << part - raise ProtocolError.new("program supervisor sent an oversized result", phase: :decode) if @status_bytes.bytesize > 48 + if @status_bytes.bytesize > 48 + raise ProtocolError.new("program supervisor sent an oversized result", phase: :decode) + end 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) + @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] @@ -435,20 +528,39 @@ def guarded(command, arguments, pane: @pane.id, pid: @pid, window: nil, **option 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) + 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) + 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) + 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) + 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 + if @closing || @closed || @creator != Process.pid + raise ClosedError.new("program is closed", phase: :admission) + end @server.__send__(:with_bound_endpoint) { nil } end end @@ -458,7 +570,11 @@ class Server 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 + identity.merge( + binding_key: @pin.key, + since: capability.since, + supported: capability.available?(@release) + ).freeze end def start_program(argv, **options, &block) @@ -471,8 +587,12 @@ 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") + 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 4b841978..9f8333f6 100644 --- a/gems/libtmux/lib/libtmux/server.rb +++ b/gems/libtmux/lib/libtmux/server.rb @@ -180,8 +180,16 @@ def self.open(**options) result end - def initialize(endpoint: nil, socket_path: nil, socket_name: nil, executable: "tmux", max_requests: 32, max_controls: 4, close_timeout: 0.5, - version_timeout: 5.0) + def initialize( + endpoint: nil, + socket_path: nil, + socket_name: nil, + executable: "tmux", + max_requests: 32, + max_controls: 4, + close_timeout: 0.5, + version_timeout: 5.0 + ) if endpoint && (socket_path || socket_name || executable != "tmux") raise ArgumentError, "endpoint cannot be combined with socket or executable options" end @@ -200,7 +208,9 @@ def initialize(endpoint: nil, socket_path: nil, socket_name: nil, executable: "t raise ArgumentError, "version_timeout must be positive and finite" end - @endpoint = endpoint || Endpoint.new(socket_path: socket_path, socket_name: socket_name, executable: executable) + @endpoint = + endpoint || + Endpoint.new(socket_path: socket_path, socket_name: socket_name, executable: executable) @owner_pid = Process.pid @max_requests = max_requests @max_controls = max_controls @@ -213,12 +223,16 @@ 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) do |argv| - @executor.run(argv, **version_probe_options(version_timeout), discard_stdout: true) - end + @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, **version_probe_options(version_timeout)), marker) + Internal::TmuxVersion.verify_fence( + @executor.run(@pin.command_prefix + argv, **version_probe_options(version_timeout)), + marker + ) rescue Exception @pin.close raise @@ -241,8 +255,13 @@ def supports_control? # reporting cached support. Async facades use their fiber-aware dispatch. def capabilities(timeout: 5.0, cancel: nil) identity = bound_daemon_identity(timeout: timeout, cancel: cancel) - Capabilities.__send__(:new, binding_key: @pin.key, pid: identity.fetch(:pid), - start_time: identity.fetch(:start_time), release: @release) + Capabilities.__send__( + :new, + binding_key: @pin.key, + pid: identity.fetch(:pid), + start_time: identity.fetch(:start_time), + release: @release + ) end # Raw tmux arguments retain tmux's separators and format semantics. @@ -273,7 +292,11 @@ def close until @requests.empty? remaining = deadline - monotonic unless remaining.positive? - raise DeadlineExceeded.new("server clients have not retired; retry close", phase: :retire, delivery: :possibly_sent) + raise DeadlineExceeded.new( + "server clients have not retired; retry close", + phase: :retire, + delivery: :possibly_sent + ) end @idle.wait(@mutex, remaining) end @@ -292,10 +315,17 @@ def close def diagnostics ensure_owner @mutex.synchronize do - {admitted_requests: @requests.length, reserved_process_slots: @requests.length, - control_connections: @controls.length, closed: @closed, - limits: {max_requests: @max_requests, max_controls: @max_controls, - close_timeout: @close_timeout}.freeze}.freeze + { + admitted_requests: @requests.length, + reserved_process_slots: @requests.length, + control_connections: @controls.length, + closed: @closed, + limits: { + max_requests: @max_requests, + max_controls: @max_controls, + close_timeout: @close_timeout + }.freeze + }.freeze end end @@ -310,19 +340,37 @@ def kill(timeout: 5.0, cancel: nil) # Read `session.snapshot.name` for the effective name and retain # `session.ref` for subsequent targeting by ID. # @raise [UnsupportedFeatureError] if exact tmux 3.7 refuses punctuation - def new_session(name: nil, command: nil, width: nil, height: nil, window_name: nil, cwd: nil, environment: {}, receipt: false, timeout: 5.0, cancel: nil) + def new_session( + name: nil, + command: nil, + width: nil, + height: nil, + window_name: nil, + cwd: nil, + environment: {}, + receipt: false, + timeout: 5.0, + cancel: nil + ) budget = operation_budget(timeout, cancel) arguments = ["new-session", "-d", "-P", "-F", creation_format(:session, receipt)] arguments.concat(["-s", literal_name(name)]) unless name.nil? arguments.concat(["-n", literal_name(window_name)]) if window_name - {"-x" => width, "-y" => height}.each do |flag, value| + { "-x" => width, "-y" => height }.each do |flag, value| next if value.nil? - raise ArgumentError, "dimensions must be positive integers" unless value.is_a?(Integer) && value.positive? + unless value.is_a?(Integer) && value.positive? + raise ArgumentError, "dimensions must be positive integers" + end arguments.concat([flag, value.to_s]) end arguments.concat(creation_options(cwd: cwd, environment: environment)) - create_entity(:session, arguments + creation_command(command), receipt: receipt, **budget.options) + create_entity( + :session, + arguments + creation_command(command), + receipt: receipt, + **budget.options + ) end def list_sessions(timeout: 5.0, cancel: nil) @@ -364,7 +412,8 @@ def open_control(session:, **options) if @controls.length >= @max_controls raise CapacityError.new("server control capacity is exhausted", phase: :admission) end - connection = ControlConnection.__send__(:new, binding: @pin, session_id: session_id, **options) + connection = + ControlConnection.__send__(:new, binding: @pin, session_id: session_id, **options) @controls << connection end if block_given? @@ -382,7 +431,12 @@ def open_control(session:, **options) connection.close(timeout: [@close_timeout, 0.5].min) @mutex.synchronize { @controls.delete(connection) } rescue Exception => cleanup - failure.__send__(:attach_cleanup_errors, ["control close failed (#{cleanup.class})"]) if failure.is_a?(Error) + if failure.is_a?(Error) + failure.__send__( + :attach_cleanup_errors, + ["control close failed (#{cleanup.class})"] + ) + end failure ||= cleanup end end @@ -413,12 +467,14 @@ def explain_panes(where: {}, pushdown: :auto) private def version_probe_options(timeout) - {timeout: timeout} + { timeout: timeout } end class OperationBudget def initialize(timeout, cancel, clock) - raise ArgumentError, "timeout must be finite" unless timeout.is_a?(Numeric) && timeout.finite? + unless timeout.is_a?(Numeric) && timeout.finite? + raise ArgumentError, "timeout must be finite" + end if cancel && (!cancel.respond_to?(:reader) || !cancel.respond_to?(:cancelled?)) raise ArgumentError, "cancel must provide a cancellation reader and state" end @@ -429,14 +485,20 @@ def initialize(timeout, cancel, clock) def options delivery = @dispatched ? :possibly_sent : :not_sent - raise Cancelled.new("operation was cancelled", phase: :admission, delivery: delivery) if @cancel&.cancelled? + if @cancel&.cancelled? + raise Cancelled.new("operation was cancelled", phase: :admission, delivery: delivery) + end remaining = @deadline - @clock.call unless remaining.positive? - raise DeadlineExceeded.new("operation deadline elapsed", phase: :admission, delivery: delivery) + raise DeadlineExceeded.new( + "operation deadline elapsed", + phase: :admission, + delivery: delivery + ) end @dispatched = true - {timeout: remaining, cancel: @cancel} + { timeout: remaining, cancel: @cancel } end end private_constant :OperationBudget @@ -511,18 +573,17 @@ def perform_request(cancel:) @requests[owned] = Thread.current end if cancel - watcher = Thread.new do - Thread.current.report_on_exception = false - IO.select([cancel.reader, owned.reader]) unless cancel.cancelled? - owned.cancel if cancel.cancelled? - rescue IOError, SystemCallError - owned.cancel - end + watcher = + Thread.new do + Thread.current.report_on_exception = false + IO.select([cancel.reader, owned.reader]) unless cancel.cancelled? + owned.cancel if cancel.cancelled? + rescue IOError, SystemCallError + owned.cancel + end end view = CancellationView.new(owned, cancel) - Thread.handle_interrupt(Exception => :immediate) do - result = yield view - end + Thread.handle_interrupt(Exception => :immediate) { result = yield view } rescue Exception => error failure = error ensure @@ -531,8 +592,13 @@ def perform_request(cancel:) if failure.is_a?(Error) failure.__send__(:attach_cleanup_errors, cleanup_errors) elsif failure.nil? - failure = TransportError.new("server request cleanup failed", phase: :retire, - delivery: result ? :observed : :possibly_sent, cleanup_errors: cleanup_errors) + failure = + TransportError.new( + "server request cleanup failed", + phase: :retire, + delivery: result ? :observed : :possibly_sent, + cleanup_errors: cleanup_errors + ) end end end @@ -572,7 +638,8 @@ def ensure_open end def validate_argv(argv) - unless argv.is_a?(Array) && !argv.empty? && argv.all? { |value| value.is_a?(String) && !value.include?("\0") } + unless argv.is_a?(Array) && !argv.empty? && + argv.all? { |value| value.is_a?(String) && !value.include?("\0") } raise ArgumentError, "argv must be a nonempty Array of Strings without NUL" end end @@ -582,39 +649,60 @@ def bound_daemon_identity(timeout:, cancel:) result = dispatch(arguments, timeout: timeout, cancel: cancel) identity = Internal::TmuxVersion.parse_daemon_identity(result, marker) unless identity.fetch(:version) == @release.text - raise ProtocolError.new("tmux did not report the bound daemon identity", delivery: :observed, phase: :decode) + raise ProtocolError.new( + "tmux did not report the bound daemon identity", + delivery: :observed, + phase: :decode + ) end identity 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, stdout_tail: nil) + def dispatch( + argv, + input: "".b, + timeout: 5.0, + cancel: nil, + repaired_break: false, + stdout_tail: nil + ) ensure_owner started = monotonic validate_argv(argv) - raise ArgumentError, "raw commands cannot override endpoint flags" if argv.first.start_with?("-") + if argv.first.start_with?("-") + raise ArgumentError, "raw commands cannot override endpoint flags" + end raise ArgumentError, "timeout must be finite" unless timeout.is_a?(Numeric) && timeout.finite? Internal::NativeGuard.check(argv, @release, repaired_break: repaired_break) 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, stdout_tail: stdout_tail) + result = + @executor.run( + @pin.command_prefix + fence + argv, + input: input, + 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, stdout_tail: nil, **options) arguments = encode_arguments(arguments) - result = if repaired_break || stdout_tail - dispatch(arguments, repaired_break: repaired_break, stdout_tail: stdout_tail, **options) - else - run(arguments, **options) - end + 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 - reason = line.force_encoding(Encoding::UTF_8).scrub("?").gsub(/[[:cntrl:]\p{Cf}\p{Zl}\p{Zp}]/, "?") + reason = + line.force_encoding(Encoding::UTF_8).scrub("?").gsub(/[[:cntrl:]\p{Cf}\p{Zl}\p{Zp}]/, "?") message += ": #{reason}" unless reason.empty? raise CommandError.new(message, result: result, phase: :command) end @@ -634,9 +722,13 @@ def literal_name(name) end # Exact tmux 3.7 rejects these in session and window names, so the # refusal comes before any effect. - if Internal::Capabilities.workaround("name-separators-rejected").applies?(@release) && name.match?(/[:.]/) - raise UnsupportedFeatureError.new("tmux 3.7 rejects ':' and '.' in session and window names", - phase: :admission, delivery: :not_sent) + if Internal::Capabilities.workaround("name-separators-rejected").applies?(@release) && + name.match?(/[:.]/) + raise UnsupportedFeatureError.new( + "tmux 3.7 rejects ':' and '.' in session and window names", + phase: :admission, + delivery: :not_sent + ) end name.gsub("#", "##") end @@ -657,7 +749,10 @@ def target(ref, kind) ensure_owner @mutex.synchronize { ensure_open } unless ref.is_a?(EntityRef) && ref.kind == kind && ref.binding_key == @pin.key - raise TargetNotFoundError.new("target does not belong to this server binding", phase: :admission) + raise TargetNotFoundError.new( + "target does not belong to this server binding", + phase: :admission + ) end ref.id end @@ -668,7 +763,7 @@ def resolve(ref, kind) end def entity_class(kind) - {session: Session, window: Window, pane: Pane, window_link: WindowLink}.fetch(kind) + { session: Session, window: Window, pane: Pane, window_link: WindowLink }.fetch(kind) end def build_entity(kind, id) @@ -692,19 +787,33 @@ def create_entity(kind, arguments, receipt: false, **options) result = execute_typed(arguments, **options) kinds = receipt ? (kind == :session ? %i[session window pane] : %i[window pane]) : [kind] rows = Internal::Metadata.decode(result.stdout, fields: kinds.length, max_rows: 1) - raise ProtocolError.new("tmux did not return the created #{kind} ID", delivery: :observed, phase: :decode) unless rows.length == 1 + unless rows.length == 1 + raise ProtocolError.new( + "tmux did not return the created #{kind} ID", + delivery: :observed, + phase: :decode + ) + end entities = kinds.zip(rows.first).to_h { |child, id| [child, build_entity(child, id)] } return entities.fetch(kind) unless receipt - CreationReceipt.__send__(:new, entity: entities.fetch(kind), window: entities.fetch(:window), - pane: entities.fetch(:pane), result: result) + CreationReceipt.__send__( + :new, + entity: entities.fetch(kind), + window: entities.fetch(:window), + pane: entities.fetch(:pane), + result: result + ) end def list_entities(kind, options, global: false, timeout: 5.0, cancel: nil) budget = operation_budget(timeout, cancel) result = execute_typed(["list-#{kind}s", *options, "-F", id_format(kind)], **budget.options) - entities = Internal::Metadata.decode(result.stdout, fields: 1).map { |row| build_entity(kind, row.first) } + entities = + Internal::Metadata + .decode(result.stdout, fields: 1) + .map { |row| build_entity(kind, row.first) } entities = entities.uniq.sort_by { |entity| entity.id[1..].to_i } if global entities.freeze rescue CommandError => error @@ -722,7 +831,9 @@ def creation_options(cwd:, environment:) raise ArgumentError, "cwd must be a nonempty String without NUL" end directory = File.expand_path(cwd) - raise ArgumentError, "cwd must name an existing accessible directory" unless File.directory?(directory) && File.executable?(directory) + unless File.directory?(directory) && File.executable?(directory) + raise ArgumentError, "cwd must name an existing accessible directory" + end # tmux expands -c as a format, while -e values are literal. arguments.concat(["-c", directory.gsub("#", "##")]) @@ -739,7 +850,18 @@ def creation_options(cwd:, environment:) arguments end - def create_window(ref, name:, command:, index: nil, cwd: nil, environment: {}, focus: false, receipt: false, timeout: 5.0, cancel: nil) + def create_window( + ref, + name:, + command:, + index: nil, + cwd: nil, + environment: {}, + focus: false, + receipt: false, + timeout: 5.0, + cancel: nil + ) budget = operation_budget(timeout, cancel) unless index.nil? || (index.is_a?(Integer) && index.between?(0, (1 << 31) - 1)) raise ArgumentError, "index must be a nonnegative 32-bit Integer" @@ -748,27 +870,60 @@ def create_window(ref, name:, command:, index: nil, cwd: nil, environment: {}, f destination = target(ref, :session) destination += ":#{index}" unless index.nil? - arguments = ["new-window", *(focus ? [] : ["-d"]), "-P", "-F", creation_format(:window, receipt), "-t", destination] + arguments = [ + "new-window", + *(focus ? [] : ["-d"]), + "-P", + "-F", + creation_format(:window, receipt), + "-t", + destination + ] arguments.concat(["-n", literal_name(name)]) unless name.nil? arguments.concat(creation_options(cwd: cwd, environment: environment)) - create_entity(:window, arguments + creation_command(command), receipt: receipt, **budget.options) - end - - def split_window(ref, direction:, command:, size: nil, cwd: nil, environment: {}, focus: false, timeout: 5.0, cancel: nil) + create_entity( + :window, + arguments + creation_command(command), + receipt: receipt, + **budget.options + ) + end + + def split_window( + ref, + direction:, + command:, + size: nil, + cwd: nil, + environment: {}, + focus: false, + timeout: 5.0, + cancel: nil + ) budget = operation_budget(timeout, cancel) - flag = {horizontal: "-h", vertical: "-v"}.fetch(direction) do - raise ArgumentError, "direction must be :horizontal or :vertical" - end + flag = + { horizontal: "-h", vertical: "-v" }.fetch(direction) do + raise ArgumentError, "direction must be :horizontal or :vertical" + end unless size.nil? || (size.is_a?(Integer) && size.between?(1, (1 << 31) - 1)) || - (size.is_a?(String) && size.match?(/\A(?:[1-9][0-9]?|100)%\z/)) + (size.is_a?(String) && size.match?(/\A(?:[1-9][0-9]?|100)%\z/)) raise ArgumentError, "size must be positive cells or a percentage from 1% to 100%" end raise ArgumentError, "focus must be boolean" unless [true, false].include?(focus) - unless ref.is_a?(EntityRef) && [:window, :pane].include?(ref.kind) + unless ref.is_a?(EntityRef) && %i[window pane].include?(ref.kind) raise ArgumentError, "split target must be a window or pane ref" end - arguments = ["split-window", *(focus ? [] : ["-d"]), flag, "-P", "-F", id_format(:pane), "-t", target(ref, ref.kind)] + arguments = [ + "split-window", + *(focus ? [] : ["-d"]), + flag, + "-P", + "-F", + id_format(:pane), + "-t", + target(ref, ref.kind) + ] arguments.concat(["-l", size.to_s]) if size arguments.concat(creation_options(cwd: cwd, environment: environment)) create_entity(:pane, arguments + creation_command(command), **budget.options) diff --git a/gems/libtmux/lib/libtmux/snapshot.rb b/gems/libtmux/lib/libtmux/snapshot.rb index 00a55064..be397764 100644 --- a/gems/libtmux/lib/libtmux/snapshot.rb +++ b/gems/libtmux/lib/libtmux/snapshot.rb @@ -15,9 +15,12 @@ def initialize(graph, kind, raw_values, coverage) @capture_id = graph.capture_id @raw_values = raw_values @coverage = coverage - @values = raw_values.to_h do |name, raw| - [name, decode(Internal::Catalog.entity(kind).fields.fetch(name), raw)] - end.freeze + @values = + raw_values + .to_h do |name, raw| + [name, decode(Internal::Catalog.entity(kind).fields.fetch(name), raw)] + end + .freeze @ref = make_ref unless kind == :client freeze end @@ -25,7 +28,8 @@ def initialize(graph, kind, raw_values, coverage) def ref if entity_kind == :client - raise UnsupportedFeatureError, "client observations have no generation-safe command reference" + raise UnsupportedFeatureError, + "client observations have no generation-safe command reference" end @ref @@ -59,15 +63,19 @@ def inspect def identity case entity_kind - when :window_link then [read_field(:session_id), read_field(:index), read_field(:window_id)] - when :client then [read_field(:name), read_field(:pid), read_field(:created)] - else read_field(:id) + when :window_link + [read_field(:session_id), read_field(:index), read_field(:window_id)] + when :client + [read_field(:name), read_field(:pid), read_field(:created)] + else + read_field(:id) end end def field_coverage(name) Internal::Catalog.entity(entity_kind).fields.fetch(name) - state = @coverage.fetch(:fields, {}).fetch(name) { @raw_values.key?(name) ? :complete : :unloaded } + state = + @coverage.fetch(:fields, {}).fetch(name) { @raw_values.key?(name) ? :complete : :unloaded } state == :complete && !@raw_values.key?(name) ? :unloaded : state end @@ -81,7 +89,11 @@ def read_field(name) ensure_coverage(field_coverage(name)) value = @values.fetch(name) if value.equal?(INVALID_TEXT) - raise FieldDecodeError.new("invalid UTF-8 in #{entity_kind}.#{name}", delivery: :observed, phase: :decode) + raise FieldDecodeError.new( + "invalid UTF-8 in #{entity_kind}.#{name}", + delivery: :observed, + phase: :decode + ) end value end @@ -93,18 +105,32 @@ def read_relation(name) def ensure_coverage(state) case state - when :complete then nil - when :unsupported then raise UnsupportedFeatureError, "captured value is unsupported" - else raise IncompleteSnapshotError, "captured value is #{state}" + when :complete + nil + when :unsupported + raise UnsupportedFeatureError, "captured value is unsupported" + else + raise IncompleteSnapshotError, "captured value is #{state}" end end def make_ref if entity_kind == :window_link - EntityRef.__send__(:new, binding_key: @graph.binding_key, kind: entity_kind, - id: read_field(:window_id), session_id: read_field(:session_id), index: read_field(:index)) + EntityRef.__send__( + :new, + binding_key: @graph.binding_key, + kind: entity_kind, + id: read_field(:window_id), + session_id: read_field(:session_id), + index: read_field(:index) + ) else - EntityRef.__send__(:new, binding_key: @graph.binding_key, kind: entity_kind, id: read_field(:id)) + EntityRef.__send__( + :new, + binding_key: @graph.binding_key, + kind: entity_kind, + id: read_field(:id) + ) end end @@ -130,48 +156,86 @@ def decode(field, raw) end def decode_error(field) - raise FieldDecodeError.new("invalid #{field.type} in #{field.id}", delivery: :observed, phase: :decode) + raise FieldDecodeError.new( + "invalid #{field.type} in #{field.id}", + delivery: :observed, + phase: :decode + ) end end - class SessionSnapshot < CapturedRecord; end - class WindowSnapshot < CapturedRecord; end - class PaneSnapshot < CapturedRecord; end - class WindowLinkSnapshot < CapturedRecord; end - class ClientSnapshot < CapturedRecord; end + class SessionSnapshot < CapturedRecord + end + class WindowSnapshot < CapturedRecord + end + class PaneSnapshot < CapturedRecord + end + class WindowLinkSnapshot < CapturedRecord + end + class ClientSnapshot < CapturedRecord + end { - session: SessionSnapshot, window: WindowSnapshot, pane: PaneSnapshot, - window_link: WindowLinkSnapshot, client: ClientSnapshot + session: SessionSnapshot, + window: WindowSnapshot, + pane: PaneSnapshot, + window_link: WindowLinkSnapshot, + client: ClientSnapshot }.each do |kind, type| - Internal::Catalog.entity(kind).fields.each_value do |field| - type.define_method(field.name) { read_field(field.name) } - type.alias_method(:"#{field.name}?", field.name) if field.type == :boolean - end - Internal::Catalog.entity(kind).relations.each_key do |name| - type.define_method(name) { read_relation(name) } - end + Internal::Catalog + .entity(kind) + .fields + .each_value do |field| + type.define_method(field.name) { read_field(field.name) } + type.alias_method(:"#{field.name}?", field.name) if field.type == :boolean + end + Internal::Catalog + .entity(kind) + .relations + .each_key { |name| type.define_method(name) { read_relation(name) } } end # A validated graph observed over an interval, with no transport reference. class Snapshot - attr_reader :capture_id, :binding_key, :started_at, :finished_at, :reads, :server_info, :coverage - - def initialize(rows:, binding_key:, started_at:, finished_at:, reads:, server_info:, coverage: {}) + attr_reader :capture_id, + :binding_key, + :started_at, + :finished_at, + :reads, + :server_info, + :coverage + + def initialize( + rows:, + binding_key:, + started_at:, + finished_at:, + reads:, + server_info:, + coverage: {} + ) @capture_id = SecureRandom.hex(16).freeze @binding_key = binding_key.dup.freeze @started_at = started_at @finished_at = finished_at - unless [started_at, finished_at].all? { |time| time.is_a?(Numeric) && time.finite? } && finished_at >= started_at + unless [started_at, finished_at].all? { |time| time.is_a?(Numeric) && time.finite? } && + finished_at >= started_at raise ArgumentError, "capture interval must be finite and ordered" end @reads = own(reads) @server_info = own(server_info) @coverage = own(coverage) validate_coverage - @source_coverage = Internal::Catalog.kinds.to_h do |kind| - [kind, @coverage.fetch(kind, {}).fetch(:source) { rows.key?(kind) ? :complete : :unloaded }] - end.freeze + @source_coverage = + Internal::Catalog + .kinds + .to_h do |kind| + [ + kind, + @coverage.fetch(kind, {}).fetch(:source) { rows.key?(kind) ? :complete : :unloaded } + ] + end + .freeze @indexes = {} @raw_rows = {} rows.each do |kind, source| @@ -181,13 +245,20 @@ def initialize(rows:, binding_key:, started_at:, finished_at:, reads:, server_in source.each do |row| unknown = row.keys - schema.fields.keys raise ArgumentError, "unknown captured field" unless unknown.empty? - raw = row.to_h do |name, value| - raise ArgumentError, "captured fields must be byte Strings or nil" unless value.nil? || value.is_a?(String) - [name, value&.b&.freeze] - end.freeze + raw = + row + .to_h do |name, value| + unless value.nil? || value.is_a?(String) + raise ArgumentError, "captured fields must be byte Strings or nil" + end + [name, value&.b&.freeze] + end + .freeze record = record_type(kind).__send__(:new, self, kind, raw, record_coverage(kind, raw)) key = own(record.__send__(:identity)) - inconsistent("conflicting repeated #{kind} rows") if raw_index.key?(key) && raw_index.fetch(key) != raw + if raw_index.key?(key) && raw_index.fetch(key) != raw + inconsistent("conflicting repeated #{kind} rows") + end raw_index[key] ||= raw index[key] ||= record end @@ -197,7 +268,10 @@ def initialize(rows:, binding_key:, started_at:, finished_at:, reads:, server_in @indexes.freeze @raw_rows.freeze @panes_by_window = group_records(:pane, :window_id) { |record| record.index } - @links_by_window = group_records(:window_link, :window_id) { |record| [numeric_id(record.session_id), record.index] } + @links_by_window = + group_records(:window_link, :window_id) do |record| + [numeric_id(record.session_id), record.index] + end @links_by_session = group_records(:window_link, :session_id) { |record| record.index } validate_graph freeze @@ -229,7 +303,9 @@ def resolve(ref) raise TargetNotFoundError, "reference does not belong to this capture binding" end key = ref.kind == :window_link ? [ref.session_id, ref.index, ref.id] : ref.id - @indexes.fetch(ref.kind, {}).fetch(key) { raise TargetNotFoundError, "reference is absent from capture" } + @indexes + .fetch(ref.kind, {}) + .fetch(key) { raise TargetNotFoundError, "reference is absent from capture" } end def inspect @@ -244,47 +320,69 @@ def inspect def own(value) case value - when String then value.dup.freeze - when Hash then value.to_h { |key, item| [own(key), own(item)] }.freeze - when Array then value.map { |item| own(item) }.freeze - when Symbol, Integer, Float, true, false, nil then value - else raise ArgumentError, "capture metadata must contain plain immutable values" + when String + value.dup.freeze + when Hash + value.to_h { |key, item| [own(key), own(item)] }.freeze + when Array + value.map { |item| own(item) }.freeze + when Symbol, Integer, Float, true, false, nil + value + else + raise ArgumentError, "capture metadata must contain plain immutable values" end end def validate_coverage @coverage.each do |kind, spec| schema = Internal::Catalog.entity(kind) - raise ArgumentError, "unknown coverage attribute" unless (spec.keys - %i[source fields relations records]).empty? + unless (spec.keys - %i[source fields relations records]).empty? + raise ArgumentError, "unknown coverage attribute" + end validate_coverage_spec(schema, spec) spec.fetch(:records, {}).each_value { |record| validate_coverage_spec(schema, record) } end end def validate_coverage_spec(schema, spec) - raise ArgumentError, "invalid source coverage" if spec.key?(:source) && !STATES.include?(spec[:source]) - {fields: schema.fields, relations: schema.relations}.each do |name, catalog| - spec.fetch(name, {}).each do |key, state| - raise ArgumentError, "invalid captured coverage" unless catalog.key?(key) && STATES.include?(state) - end + if spec.key?(:source) && !STATES.include?(spec[:source]) + raise ArgumentError, "invalid source coverage" + end + { fields: schema.fields, relations: schema.relations }.each do |name, catalog| + spec + .fetch(name, {}) + .each do |key, state| + unless catalog.key?(key) && STATES.include?(state) + raise ArgumentError, "invalid captured coverage" + end + end end end def record_coverage(kind, raw) spec = @coverage.fetch(kind, {}) - key = if kind == :window_link - [raw[:session_id], raw[:index]&.to_i, raw[:window_id]] - elsif kind == :client - [raw[:name], raw[:pid]&.to_i, raw[:created]&.to_i] - else raw[:id] - end + key = + if kind == :window_link + [raw[:session_id], raw[:index]&.to_i, raw[:window_id]] + elsif kind == :client + [raw[:name], raw[:pid]&.to_i, raw[:created]&.to_i] + else + raw[:id] + end local = spec.fetch(:records, {}).fetch(key, {}) - %i[fields relations].to_h { |name| [name, spec.fetch(name, {}).merge(local.fetch(name, {})).freeze] }.freeze + %i[fields relations] + .to_h { |name| [name, spec.fetch(name, {}).merge(local.fetch(name, {})).freeze] } + .freeze end def record_type(kind) - {session: SessionSnapshot, window: WindowSnapshot, pane: PaneSnapshot, - window_link: WindowLinkSnapshot, client: ClientSnapshot}.fetch(kind) + { + session: SessionSnapshot, + window: WindowSnapshot, + pane: PaneSnapshot, + window_link: WindowLinkSnapshot, + client: ClientSnapshot + }.fetch(kind) end def records(kind) @@ -297,13 +395,17 @@ def source_coverage(kind) def collection(kind) ensure_complete(source_coverage(kind)) - ordered = records(kind).sort_by do |record| - case kind - when :window_link then [numeric_id(record.session_id), record.index] - when :client then [record.pid, record.created, record.raw(:name)] - else numeric_id(record.id) + ordered = + records(kind).sort_by do |record| + case kind + when :window_link + [numeric_id(record.session_id), record.index] + when :client + [record.pid, record.created, record.raw(:name)] + else + numeric_id(record.id) + end end - end selection(ordered, kind) end @@ -316,8 +418,10 @@ def numeric_id(id) end def group_records(kind, field) - records(kind).group_by { |record| record.__send__(:read_field, field) } - .transform_values { |group| group.sort_by { |record| yield record }.freeze }.freeze + records(kind) + .group_by { |record| record.__send__(:read_field, field) } + .transform_values { |group| group.sort_by { |record| yield record }.freeze } + .freeze end def relation_coverage(record, relation) @@ -331,10 +435,13 @@ def relation_coverage(record, relation) return :unloaded if states.include?(:unloaded) return :incomplete if states.include?(:incomplete) - children = case [record.__send__(:entity_kind), relation.name] - when [:window, :active_pane] then @panes_by_window.fetch(record.id, EMPTY) - when [:session, :current_window] then @links_by_session.fetch(record.id, EMPTY) - end + children = + case [record.__send__(:entity_kind), relation.name] + when %i[window active_pane] + @panes_by_window.fetch(record.id, EMPTY) + when %i[session current_window] + @links_by_session.fetch(record.id, EMPTY) + end if children states = children.map { |child| child.__send__(:field_coverage, :active) } return :unsupported if states.include?(:unsupported) @@ -347,25 +454,35 @@ def relation_coverage(record, relation) def read_relation(record, name) kind = record.__send__(:entity_kind) case [kind, name] - when [:pane, :window], [:window_link, :window] + when %i[pane window], %i[window_link window] @indexes.fetch(:window).fetch(record.window_id) - when [:window_link, :session] + when %i[window_link session] @indexes.fetch(:session).fetch(record.session_id) - when [:client, :session] + when %i[client session] record.session_id && @indexes.fetch(:session).fetch(record.session_id) - when [:window, :panes] + when %i[window panes] selection(@panes_by_window.fetch(record.id, EMPTY), :pane) - when [:window, :window_links] + when %i[window window_links] selection(@links_by_window.fetch(record.id, EMPTY), :window_link) - when [:window, :active_pane] + when %i[window active_pane] @panes_by_window.fetch(record.id, EMPTY).find(&:active?) - when [:session, :window_links] + when %i[session window_links] selection(@links_by_session.fetch(record.id, EMPTY), :window_link) - when [:session, :windows] - selection(@links_by_session.fetch(record.id, EMPTY).map { |link| @indexes.fetch(:window).fetch(link.window_id) }, :window) - when [:session, :panes] - selection(@links_by_session.fetch(record.id, EMPTY).flat_map { |link| @panes_by_window.fetch(link.window_id, EMPTY) }, :pane) - when [:session, :current_window] + when %i[session windows] + selection( + @links_by_session + .fetch(record.id, EMPTY) + .map { |link| @indexes.fetch(:window).fetch(link.window_id) }, + :window + ) + when %i[session panes] + selection( + @links_by_session + .fetch(record.id, EMPTY) + .flat_map { |link| @panes_by_window.fetch(link.window_id, EMPTY) }, + :pane + ) + when %i[session current_window] link = @links_by_session.fetch(record.id, EMPTY).find(&:active?) link && @indexes.fetch(:window).fetch(link.window_id) end @@ -407,11 +524,16 @@ def validate_edge(kind, id) def validate_count(record, field, children) return unless record.__send__(:field_coverage, field) == :complete - inconsistent("captured child count changed") unless record.__send__(:read_field, field) == children.size + unless record.__send__(:read_field, field) == children.size + inconsistent("captured child count changed") + end end def validate_active(children) - return if children.empty? || children.any? { |child| child.__send__(:field_coverage, :active) != :complete } + if children.empty? || + children.any? { |child| child.__send__(:field_coverage, :active) != :complete } + return + end inconsistent("captured active child changed") unless children.count(&:active?) == 1 end diff --git a/gems/libtmux/lib/libtmux/socket_readiness.rb b/gems/libtmux/lib/libtmux/socket_readiness.rb index 0b2cb562..6fde2473 100644 --- a/gems/libtmux/lib/libtmux/socket_readiness.rb +++ b/gems/libtmux/lib/libtmux/socket_readiness.rb @@ -12,8 +12,12 @@ class InotifyReadinessEvents def initialize(directory, mask: 0x00000004) libc = Fiddle::Handle::DEFAULT init = Fiddle::Function.new(libc["inotify_init1"], [Fiddle::TYPE_INT], Fiddle::TYPE_INT) - add = Fiddle::Function.new(libc["inotify_add_watch"], - [Fiddle::TYPE_INT, Fiddle::TYPE_VOIDP, Fiddle::TYPE_INT], Fiddle::TYPE_INT) + add = + Fiddle::Function.new( + libc["inotify_add_watch"], + [Fiddle::TYPE_INT, Fiddle::TYPE_VOIDP, Fiddle::TYPE_INT], + Fiddle::TYPE_INT + ) fd = init.call(Fcntl::O_NONBLOCK) raise SystemCallError.new("inotify_init1", Fiddle.last_error) if fd.negative? @@ -34,14 +38,33 @@ def drain(pid) events = [] while offset < bytes.bytesize header = bytes.byteslice(offset, 16) - raise ProtocolError.new("truncated socket readiness event", phase: :startup, pid: pid, delivery: :possibly_sent) unless header.bytesize == 16 + unless header.bytesize == 16 + raise ProtocolError.new( + "truncated socket readiness event", + phase: :startup, + pid: pid, + delivery: :possibly_sent + ) + end descriptor, mask, _, size = header.unpack("iIII") if mask & 0x00004000 != 0 # IN_Q_OVERFLOW - raise CapacityError.new("socket readiness events overflowed", phase: :startup, pid: pid, delivery: :possibly_sent) + raise CapacityError.new( + "socket readiness events overflowed", + phase: :startup, + pid: pid, + delivery: :possibly_sent + ) end name = bytes.byteslice(offset + 16, size) - raise ProtocolError.new("truncated socket readiness name", phase: :startup, pid: pid, delivery: :possibly_sent) unless name && name.bytesize == size + unless name && name.bytesize == size + raise ProtocolError.new( + "truncated socket readiness name", + phase: :startup, + pid: pid, + delivery: :possibly_sent + ) + end events << [mask, name.delete("\0")] if descriptor == @watch offset += 16 + size @@ -49,7 +72,8 @@ def drain(pid) events end - def watch_file(_io); end + def watch_file(_io) + end def close @reader.close if @reader && !@reader.closed? @@ -61,12 +85,26 @@ class KqueueReadinessEvents def initialize(directory) unless Fiddle::SIZEOF_VOIDP == 8 - raise UnsupportedFeatureError.new("owned daemon readiness requires 64-bit Darwin", phase: :startup) + raise UnsupportedFeatureError.new( + "owned daemon readiness requires 64-bit Darwin", + phase: :startup + ) end libc = Fiddle::Handle::DEFAULT create = Fiddle::Function.new(libc["kqueue"], [], Fiddle::TYPE_INT) - @kevent = Fiddle::Function.new(libc["kevent"], [Fiddle::TYPE_INT, Fiddle::TYPE_VOIDP, - Fiddle::TYPE_INT, Fiddle::TYPE_VOIDP, Fiddle::TYPE_INT, Fiddle::TYPE_VOIDP], Fiddle::TYPE_INT) + @kevent = + Fiddle::Function.new( + libc["kevent"], + [ + Fiddle::TYPE_INT, + Fiddle::TYPE_VOIDP, + Fiddle::TYPE_INT, + Fiddle::TYPE_VOIDP, + Fiddle::TYPE_INT, + Fiddle::TYPE_VOIDP + ], + Fiddle::TYPE_INT + ) fd = create.call raise SystemCallError.new("kqueue", Fiddle.last_error) if fd.negative? @@ -101,7 +139,12 @@ def drain(pid) _, _, flags, notes, error, = buffer.byteslice(index * 32, 32).unpack("QsS I qQ") raise SystemCallError.new("kevent event", error) if flags & 0x4000 != 0 if notes & 0x61 != 0 - raise TransportError.new("owned startup log changed identity", phase: :startup, pid: pid, delivery: :possibly_sent) + raise TransportError.new( + "owned startup log changed identity", + phase: :startup, + pid: pid, + delivery: :possibly_sent + ) end end end @@ -123,7 +166,10 @@ class SocketReadiness def self.new(directory) return LogSocketReadiness.new(directory) if RUBY_PLATFORM.include?("darwin") unless RUBY_PLATFORM.include?("linux") - raise UnsupportedFeatureError.new("owned daemon readiness requires Linux or Darwin", phase: :startup) + raise UnsupportedFeatureError.new( + "owned daemon readiness requires Linux or Darwin", + phase: :startup + ) end super @@ -136,7 +182,8 @@ def initialize(directory) def reader = @events.reader def arguments = [] def spawn_options = {} - def remove_files(_pid); end + def remove_files(_pid) + end def ready?(child) # tmux's initial chmod follows bind/listen; no client can cause it yet. @@ -155,18 +202,22 @@ class LogSocketReadiness def initialize(directory) @directory, @bytes_read, @tail = directory, 0, +"".b - @events = if RUBY_PLATFORM.include?("darwin") - KqueueReadinessEvents.new(directory) - elsif RUBY_PLATFORM.include?("linux") - InotifyReadinessEvents.new(directory, mask: 0x00000102) # IN_CREATE|IN_MODIFY - else - raise UnsupportedFeatureError.new("owned log readiness requires Linux or Darwin", phase: :startup) - end + @events = + if RUBY_PLATFORM.include?("darwin") + KqueueReadinessEvents.new(directory) + elsif RUBY_PLATFORM.include?("linux") + InotifyReadinessEvents.new(directory, mask: 0x00000102) # IN_CREATE|IN_MODIFY + else + raise UnsupportedFeatureError.new( + "owned log readiness requires Linux or Darwin", + phase: :startup + ) + end end def reader = @events.reader def arguments = ["-v"] - def spawn_options = {chdir: @directory} + def spawn_options = { chdir: @directory } def stopped? = !!@stopped def ready?(child) @@ -175,13 +226,22 @@ def ready?(child) @events.drain(child.pid) unless @log begin - @log = File.open(File.join(@directory, "tmux-server-#{child.pid}.log"), File::RDONLY | File::NOFOLLOW) + @log = + File.open( + File.join(@directory, "tmux-server-#{child.pid}.log"), + File::RDONLY | File::NOFOLLOW + ) rescue Errno::ENOENT return false end @log.close_on_exec = true unless @log.stat.file? - raise ProtocolError.new("owned startup log is not a regular file", phase: :startup, pid: child.pid, delivery: :possibly_sent) + raise ProtocolError.new( + "owned startup log is not a regular file", + phase: :startup, + pid: child.pid, + delivery: :possibly_sent + ) end # Register before reading: an append between registration and EOF stays queued. @events.watch_file(@log) @@ -189,7 +249,12 @@ def ready?(child) while (bytes = @log.read(16_384)) @bytes_read += bytes.bytesize if @bytes_read > LIMIT - raise CapacityError.new("owned startup log exceeded byte limit", phase: :startup, pid: child.pid, delivery: :possibly_sent) + raise CapacityError.new( + "owned startup log exceeded byte limit", + phase: :startup, + pid: child.pid, + delivery: :possibly_sent + ) end text = @tail + bytes if !@stopping && text.match?(/(?:\A|\n)\d+\.\d+ server loop enter\n/n) @@ -231,6 +296,9 @@ def close end end - private_constant :InotifyReadinessEvents, :KqueueReadinessEvents, :SocketReadiness, :LogSocketReadiness + private_constant :InotifyReadinessEvents, + :KqueueReadinessEvents, + :SocketReadiness, + :LogSocketReadiness end end diff --git a/gems/libtmux/lib/libtmux/source_query.rb b/gems/libtmux/lib/libtmux/source_query.rb index e138dcba..267940b1 100644 --- a/gems/libtmux/lib/libtmux/source_query.rb +++ b/gems/libtmux/lib/libtmux/source_query.rb @@ -6,8 +6,13 @@ module LibTmux module Internal # Capturing all relation evidence is the conservative source plan. class SourceQuery - COLLECTIONS = {session: :sessions, window: :windows, pane: :panes, - window_link: :window_links, client: :clients}.freeze + COLLECTIONS = { + session: :sessions, + window: :windows, + pane: :panes, + window_link: :window_links, + client: :clients + }.freeze private_constant :COLLECTIONS def initialize(entity, where:, pushdown: :auto) @@ -18,11 +23,28 @@ def initialize(entity, where:, pushdown: :auto) @entity = entity @collection = COLLECTIONS.fetch(entity) @pushdown = pushdown - reasons = pushdown == :never ? [] : ["no tmux predicate compiler has passed differential verification"] - @explanation = freeze_tree({entity: entity, requested_pushdown: pushdown, - capture: :full_graph, capture_requirements: %i[session window window_link pane] + (entity == :client ? [:client] : []), - pushed: nil, residual: @expression.to_h, executable: pushdown != :required, - rejected_optimization_reasons: reasons}) + reasons = + ( + if pushdown == :never + [] + else + ["no tmux predicate compiler has passed differential verification"] + end + ) + @explanation = + freeze_tree( + { + entity: entity, + requested_pushdown: pushdown, + capture: :full_graph, + capture_requirements: + %i[session window window_link pane] + (entity == :client ? [:client] : []), + pushed: nil, + residual: @expression.to_h, + executable: pushdown != :required, + rejected_optimization_reasons: reasons + } + ) freeze end @@ -36,7 +58,10 @@ def inspect def execute(server, **options) if @pushdown == :required - raise UnsupportedFeatureError.new("required pushdown has no verified exact compiler; use :auto or :never", phase: :plan) + raise UnsupportedFeatureError.new( + "required pushdown has no verified exact compiler; use :auto or :never", + phase: :plan + ) end options = options.merge(clients: true) if @entity == :client server.snapshot(**options).public_send(@collection).where(@expression) @@ -46,10 +71,14 @@ def execute(server, **options) def freeze_tree(value) case value - when Hash then value.to_h { |key, child| [key, freeze_tree(child)] }.freeze - when Array then value.map { |child| freeze_tree(child) }.freeze - when String then value.dup.freeze - else value + when Hash + value.to_h { |key, child| [key, freeze_tree(child)] }.freeze + when Array + value.map { |child| freeze_tree(child) }.freeze + when String + value.dup.freeze + else + value end end end diff --git a/gems/libtmux/lib/libtmux/terminal.rb b/gems/libtmux/lib/libtmux/terminal.rb index e0684208..ca0b0292 100644 --- a/gems/libtmux/lib/libtmux/terminal.rb +++ b/gems/libtmux/lib/libtmux/terminal.rb @@ -32,7 +32,8 @@ def inspect class Server # Checks a TERM value before opening a server or attaching a client. def self.valid_terminal_type?(value) - value.is_a?(String) && value.ascii_only? && /\A[A-Za-z0-9][A-Za-z0-9_.+-]{0,127}\z/.match?(value) + value.is_a?(String) && value.ascii_only? && + /\A[A-Za-z0-9][A-Za-z0-9_.+-]{0,127}\z/.match?(value) end # Resolves the literal selector at dispatch; it is not a client reference. @@ -55,17 +56,18 @@ def attach(session:, terminal:, term:, read_only: false, timeout: nil, cancel: n unless terminal.is_a?(IO) && !terminal.closed? && terminal.tty? raise ArgumentError, "terminal must be an open caller-owned TTY" end - unless Server.valid_terminal_type?(term) - raise ArgumentError, "term must name a terminal type" - end + raise ArgumentError, "term must name a terminal type" unless Server.valid_terminal_type?(term) raise ArgumentError, "read_only must be Boolean" unless [true, false].include?(read_only) unless timeout.nil? || (timeout.is_a?(Numeric) && timeout.finite? && timeout.positive?) raise ArgumentError, "terminal timeout must be positive and finite, or nil" end - argv = @pin.command_prefix + ["attach-session", "-E", *(read_only ? ["-r"] : []), "-t", session_id] + argv = + @pin.command_prefix + ["attach-session", "-E", *(read_only ? ["-r"] : []), "-t", session_id] perform_request(cancel: cancel) do |view| - Internal.const_get(:TerminalExecution, false).new(argv, terminal, term, - timeout && timeout - (monotonic - started), view).call + Internal + .const_get(:TerminalExecution, false) + .new(argv, terminal, term, timeout && timeout - (monotonic - started), view) + .call end end end @@ -90,10 +92,21 @@ def call @mode = @tty.console_mode @child = OwnedChild.new begin - @pid = Process.spawn({"TMUX" => nil, "TMUX_PANE" => nil, "TERM" => @term}, - *@argv, in: @tty, out: @tty, err: @tty, close_others: true) + @pid = + Process.spawn( + { "TMUX" => nil, "TMUX_PANE" => nil, "TERM" => @term }, + *@argv, + in: @tty, + out: @tty, + err: @tty, + close_others: true + ) rescue SystemCallError, IOError => error - raise TransportError.new("terminal client could not start (#{error.class})", **details(:spawn)), cause: nil + raise TransportError.new( + "terminal client could not start (#{error.class})", + **details(:spawn) + ), + cause: nil ensure @child.spawned(@pid) end @@ -105,7 +118,12 @@ def call if failure.is_a?(Error) failure.__send__(:attach_cleanup_errors, errors) elsif !failure && !errors.empty? - failure = TransportError.new("terminal cleanup failed", **details(:retire), cleanup_errors: errors) + failure = + TransportError.new( + "terminal cleanup failed", + **details(:retire), + cleanup_errors: errors + ) end end end @@ -129,12 +147,22 @@ def await_exit if @child.complete? raise @child.retirement_error if @child.retirement_error - return TerminalResult.__send__(:new, status: @child.status, pid: @pid, elapsed_seconds: clock - @started) + return( + TerminalResult.__send__( + :new, + status: @child.status, + pid: @pid, + elapsed_seconds: clock - @started + ) + ) end check_cancel unless @retire_deadline deadline = @retire_deadline || @deadline if deadline && clock >= deadline - raise DeadlineExceeded.new("terminal client exceeded its deadline", **details(:terminal)) + raise DeadlineExceeded.new( + "terminal client exceeded its deadline", + **details(:terminal) + ) end readers = [@child.reader] readers << @cancel.reader unless @retire_deadline @@ -143,7 +171,11 @@ def await_exit end end rescue SystemCallError, IOError => error - raise TransportError.new("terminal process observation failed (#{error.class})", **details(:terminal)), cause: nil + raise TransportError.new( + "terminal process observation failed (#{error.class})", + **details(:terminal) + ), + cause: nil end def retire @@ -180,7 +212,9 @@ def attempt(errors, operation) end def check_cancel - raise Cancelled.new("terminal attachment cancelled", **details(:terminal)) if @cancel.cancelled? + if @cancel.cancelled? + raise Cancelled.new("terminal attachment cancelled", **details(:terminal)) + end end def check_deadline @@ -190,7 +224,7 @@ def check_deadline end def details(phase) - {phase: phase, pid: @pid, delivery: @pid ? :possibly_sent : :not_sent} + { phase: phase, pid: @pid, delivery: @pid ? :possibly_sent : :not_sent } end def clock diff --git a/gems/libtmux/lib/libtmux/text_wait.rb b/gems/libtmux/lib/libtmux/text_wait.rb index 6991e2ad..e03931cc 100644 --- a/gems/libtmux/lib/libtmux/text_wait.rb +++ b/gems/libtmux/lib/libtmux/text_wait.rb @@ -7,9 +7,7 @@ module LibTmux module TextWait # The joined screen and whether its first capture matched the needle. - Result = Data.define(:text, :matched_at_entry) do - private_class_method :new, :[] - end + Result = Data.define(:text, :matched_at_entry) { private_class_method :new, :[] } end class Pane @@ -35,7 +33,8 @@ def wait_for_text(text, interval: 0.1, timeout: 5.0, cancel: nil) loop do argv, marker = Internal::TmuxVersion.identity_argv(%w[pane_id pane_dead]) probe = [argv.first, "-t", pane_id, *argv.drop(1)] - result = server.run(["capture-pane", "-p", "-J", "-t", pane_id, ";", *probe], **budget.options) + result = + server.run(["capture-pane", "-p", "-J", "-t", pane_id, ";", *probe], **budget.options) screen, ending = text_wait_frame(result, marker, pane_id) last_text = screen if screen matched = last_text.include?(needle) @@ -44,9 +43,7 @@ def wait_for_text(text, interval: 0.1, timeout: 5.0, cancel: nil) if matched return TextWait::Result.__send__(:new, text: last_text, matched_at_entry: first_read) end - if ending - raise PaneDied.__send__(:new, ending, last_text) - end + raise PaneDied.__send__(:new, ending, last_text) if ending text_wait_pause([interval, remaining].min, cancel) first_read = false @@ -65,35 +62,34 @@ def text_wait_frame(result, marker, pane_id) if state # The parse error in stderr carries state independently of screen bytes. unless result.stdout.end_with?("\n") && (state[1] != pane_id || state[2]) - raise ProtocolError.new("tmux did not return a complete pane capture", phase: :read, delivery: :observed) + raise ProtocolError.new( + "tmux did not return a complete pane capture", + phase: :read, + delivery: :observed + ) end - ending = if state[1] != pane_id - :pane_gone - elsif state[2] == "1" - :pane_exited - end - return [result.text.freeze, ending] + ending = + if state[1] != pane_id + :pane_gone + elsif state[2] == "1" + :pane_exited + end + return result.text.freeze, ending end # A failed capture can print hook output without reading the screen. - if Internal::TmuxVersion.daemon_loss_delivery(result) - return [nil, :server_gone] - end + return nil, :server_gone if Internal::TmuxVersion.daemon_loss_delivery(result) if stderr.start_with?("no current target\n") || - stderr.match?(/\Acan't find (?:pane|window|session): #{Regexp.escape(pane_id)}\n/n) - return [nil, :pane_gone] + stderr.match?(/\Acan't find (?:pane|window|session): #{Regexp.escape(pane_id)}\n/n) + return nil, :pane_gone end raise CommandError.new("tmux could not read the pane screen", result: result, phase: :read) end def text_wait_pause(duration, cancel) - if cancel - cancel.reader.wait_readable(duration) - else - sleep(duration) - end + cancel ? cancel.reader.wait_readable(duration) : sleep(duration) rescue IOError raise unless cancel&.cancelled? end diff --git a/gems/libtmux/lib/libtmux/tmux_version.rb b/gems/libtmux/lib/libtmux/tmux_version.rb index 03c64921..64a01e7f 100644 --- a/gems/libtmux/lib/libtmux/tmux_version.rb +++ b/gems/libtmux/lib/libtmux/tmux_version.rb @@ -18,7 +18,8 @@ module TmuxVersion # X.Y-rcN candidates, and next-X.Y development builds. Anything else, # including master and openbsd-*, is not a release number. The candidate # number is bounded so that it can never outrank the release it precedes. - PATTERN = /\A(?:next-(?\d+)\.(?\d+)|(?\d+)\.(?\d+)(?:(?[a-z])|(?-rc(?\d{1,3})?))?)\z/ + PATTERN = + /\A(?:next-(?\d+)\.(?\d+)|(?\d+)\.(?\d+)(?:(?[a-z])|(?-rc(?\d{1,3})?))?)\z/ # tmux resolves a command-alias entry by exact name before it resolves a # command, so the full names run-shell and if-shell can be hijacked by # one alias, as the existing link guards avoid with builtin_spellings. @@ -28,12 +29,14 @@ module TmuxVersion # sharing it, refuses the server instead of silently disabling the fence. FENCE_COMMAND = "if-shel" PROBE_COMMAND = "run-shel" - ABSENT = /\A(?:no server running(?: on [^\n]+)?|error connecting to [^\n]+ \((?:No such file or directory|Connection refused)\))\n?\z/n + 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. - PRE_3_2_ANSWER = /\A(?:usage: run-shell \[-b\] \[-t target-pane\] shell-command|server version is too old for client)\n\z/ + PRE_3_2_ANSWER = + /\A(?:usage: run-shell \[-b\] \[-t target-pane\] shell-command|server version is too old for client)\n\z/ REMEDY = "upgrade tmux and restart the server, or pin the previous libtmux release" # Marks the refusals that mean "this daemon is not the supported one", # so a caller that cannot show the full message can still name the floor. @@ -44,19 +47,20 @@ module TmuxVersion # names: next-X.Y < X.Y-rc < X.Y-rcN < X.Y < X.Ya. STABLE = 1 << 20 - Release = Data.define(:text, :key) do - include Comparable + Release = + Data.define(:text, :key) do + include Comparable - # True only for the numbered release itself, not a patch letter, - # candidate or development build of it. - def exactly?(major, minor) - key == [major, minor, 0, STABLE] - end + # True only for the numbered release itself, not a patch letter, + # candidate or development build of it. + def exactly?(major, minor) + key == [major, minor, 0, STABLE] + end - def <=>(other) - key <=> other.key if other.is_a?(Release) + def <=>(other) + key <=> other.key if other.is_a?(Release) + end end - end module_function @@ -64,13 +68,14 @@ def parse(value, source: "the daemon") match = value.is_a?(String) && PATTERN.match(value) raise unrecognized(value, source) unless match - key = if match[:next_major] - [match[:next_major].to_i, match[:next_minor].to_i, 0, 0] - else - patch = match[:patch] ? match[:patch].ord - 96 : 0 - kind = match[:candidate] ? 1 + match[:number].to_i : STABLE - [match[:major].to_i, match[:minor].to_i, patch, kind] - end + key = + if match[:next_major] + [match[:next_major].to_i, match[:next_minor].to_i, 0, 0] + else + patch = match[:patch] ? match[:patch].ord - 96 : 0 + kind = match[:candidate] ? 1 + match[:number].to_i : STABLE + [match[:major].to_i, match[:minor].to_i, patch, kind] + end Release.new(text: value.dup.freeze, key: key.freeze) end @@ -78,8 +83,11 @@ def require_supported(value, minimum: MINIMUM, source: "the daemon") release = parse(value, source: source) if (release <=> parse(minimum)).negative? reported = (source == "the daemon") ? "connected version" : "#{source} reports" - raise UnsupportedFeatureError.new("tmux #{minimum} or newer is required (#{reported} #{release.text}); #{REMEDY}", - phase: :admission, expected: EXPECTED) + raise UnsupportedFeatureError.new( + "tmux #{minimum} or newer is required (#{reported} #{release.text}); #{REMEDY}", + phase: :admission, + expected: EXPECTED + ) end release end @@ -88,18 +96,31 @@ def require_supported(value, minimum: MINIMUM, source: "the daemon") # long report cannot flood the message. def unrecognized(value, source) shown = value.is_a?(String) ? value.byteslice(0, 64).scrub("?") : value - UnsupportedFeatureError.new("tmux version is unrecognized (#{source} reports #{shown.inspect}); " \ - "tmux #{MINIMUM} or newer is required; #{REMEDY}", phase: :admission, expected: EXPECTED) + UnsupportedFeatureError.new( + "tmux version is unrecognized (#{source} reports #{shown.inspect}); " \ + "tmux #{MINIMUM} or newer is required; #{REMEDY}", + phase: :admission, + expected: EXPECTED + ) end # Control clients crash tmux servers older than 3.7 while they attach. def require_control(release) - raise UnsupportedFeatureError.new("control connections need a version-checked server", phase: :admission) unless release + unless release + raise UnsupportedFeatureError.new( + "control connections need a version-checked server", + phase: :admission + ) + end return release unless (release <=> parse(CONTROL_MINIMUM)).negative? - raise UnsupportedFeatureError.new("control connections require tmux #{CONTROL_MINIMUM} or newer " \ - "(connected version #{release.text})", phase: :admission, delivery: :not_sent) + raise UnsupportedFeatureError.new( + "control connections require tmux #{CONTROL_MINIMUM} or newer " \ + "(connected version #{release.text})", + phase: :admission, + delivery: :not_sent + ) end # Reads the daemon behind +prefix+. The block runs the argv and returns a @@ -111,18 +132,30 @@ def connected(prefix) marker = "libtmux-version-#{SecureRandom.hex(16)}-" result = yield(prefix + [PROBE_COMMAND, "-C", marker + '#{version}']) stderr = result.stderr.dup.force_encoding(Encoding::UTF_8) - if !result.success? && result.stdout.empty? && (match = /\Aunknown command: #{Regexp.escape(marker)}([^\n]+)\n\z/.match(stderr)) + if !result.success? && result.stdout.empty? && + (match = /\Aunknown command: #{Regexp.escape(marker)}([^\n]+)\n\z/.match(stderr)) return require_supported(match[1]) end if !result.success? && result.stdout.empty? && PRE_3_2_ANSWER.match?(stderr) - raise UnsupportedFeatureError.new("tmux #{MINIMUM} or newer is required (the connected daemon is older than 3.2); #{REMEDY}", - phase: :admission, expected: EXPECTED) + raise UnsupportedFeatureError.new( + "tmux #{MINIMUM} or newer is required (the connected daemon is older than 3.2); #{REMEDY}", + phase: :admission, + expected: EXPECTED + ) end if daemon_loss_delivery(result) - raise TargetNotFoundError.new("no tmux server is running at the selected endpoint", phase: :admission) + raise TargetNotFoundError.new( + "no tmux server is running at the selected endpoint", + phase: :admission + ) end - raise CommandError.new("tmux did not report a daemon version", result: result, phase: :admission, delivery: :not_sent) + raise CommandError.new( + "tmux did not report a daemon version", + result: result, + phase: :admission, + delivery: :not_sent + ) rescue Error => error raise not_sent(error), cause: nil end @@ -139,7 +172,12 @@ def daemon_loss_delivery(result) def executable(path) result = yield([path, "-V"]) unless result.success? - raise CommandError.new("tmux did not report its version", result: result, phase: :admission, delivery: :not_sent) + raise CommandError.new( + "tmux did not report its version", + result: result, + phase: :admission, + delivery: :not_sent + ) end names = ["tmux", File.basename(path)].uniq.map { |name| Regexp.escape(name.b) }.join("|") @@ -164,7 +202,11 @@ def parse_identity(result, marker, count) match = /\Aunknown command: #{Regexp.escape(marker.b)}([^\n ]*)\n\z/n.match(stderr) values = match && match[1].split(",", -1) unless !result.success? && result.stdout.empty? && values && values.length == count - raise ProtocolError.new("tmux did not report the requested identity", delivery: :observed, phase: :decode) + raise ProtocolError.new( + "tmux did not report the requested identity", + delivery: :observed, + phase: :decode + ) end values.map(&:freeze) @@ -177,11 +219,18 @@ def daemon_identity_argv def parse_daemon_identity(result, marker, phase: :decode) version, pid, start_time = parse_identity(result, marker, 3) unless pid.match?(/\A[1-9][0-9]{0,9}\z/n) && start_time.match?(/\A-?[0-9]{1,19}\z/n) - raise ProtocolError.new("invalid tmux daemon identity metadata", phase: phase, delivery: :observed) + raise ProtocolError.new( + "invalid tmux daemon identity metadata", + phase: phase, + delivery: :observed + ) end - {version: version.dup.force_encoding(Encoding::UTF_8).freeze, - pid: Integer(pid, 10), start_time: Integer(start_time, 10)} + { + version: version.dup.force_encoding(Encoding::UTF_8).freeze, + pid: Integer(pid, 10), + start_time: Integer(start_time, 10) + } end # Leading commands for one dispatch. A daemon that no longer reports @@ -202,17 +251,32 @@ def fence_check_argv end def verify_fence(result, marker) - return result if !result.success? && result.stdout.empty? && result.stderr.b == "unknown command: #{marker}\n".b + if !result.success? && result.stdout.empty? && + result.stderr.b == "unknown command: #{marker}\n".b + return result + end - raise UnsupportedFeatureError.new("a tmux command-alias or command shadows #{FENCE_COMMAND} or " \ - "#{PROBE_COMMAND}; remove it before opening a server", phase: :admission, delivery: :not_sent) + raise UnsupportedFeatureError.new( + "a tmux command-alias or command shadows #{FENCE_COMMAND} or " \ + "#{PROBE_COMMAND}; remove it before opening a server", + phase: :admission, + delivery: :not_sent + ) end def check_fence(result, marker, release) - return result unless result.stderr.b.each_line.any? { |line| line.chomp == "unknown command: #{marker}".b } + unless result.stderr.b.each_line.any? { |line| + line.chomp == "unknown command: #{marker}".b + } + return result + end - raise UnsupportedFeatureError.new("the tmux daemon no longer reports #{release.text}; reopen the server", - phase: :admission, delivery: :not_sent, expected: EXPECTED) + raise UnsupportedFeatureError.new( + "the tmux daemon no longer reports #{release.text}; reopen the server", + phase: :admission, + delivery: :not_sent, + expected: EXPECTED + ) end # True for the refusals that name the supported floor: an unsupported, @@ -230,9 +294,16 @@ def hint # A failed probe sent nothing, whatever stage it failed in, so only the # delivery is forced; the error keeps its own phase. def not_sent(error) - details = {delivery: :not_sent, phase: error.phase, pid: error.pid, cleanup_errors: error.cleanup_errors, - expected: error.expected} - return error.class.new(error.message, result: error.result, **details) if error.is_a?(CommandError) + details = { + delivery: :not_sent, + phase: error.phase, + pid: error.pid, + cleanup_errors: error.cleanup_errors, + expected: error.expected + } + if error.is_a?(CommandError) + return error.class.new(error.message, result: error.result, **details) + end error.class.new(error.message, **details) end diff --git a/gems/libtmux/libexec/program_child.rb b/gems/libtmux/libexec/program_child.rb index 5799bc33..df9c3504 100644 --- a/gems/libtmux/libexec/program_child.rb +++ b/gems/libtmux/libexec/program_child.rb @@ -51,6 +51,7 @@ 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. diff --git a/gems/libtmux/libtmux.gemspec b/gems/libtmux/libtmux.gemspec index af46e349..d2fa72d6 100644 --- a/gems/libtmux/libtmux.gemspec +++ b/gems/libtmux/libtmux.gemspec @@ -7,7 +7,8 @@ Gem::Specification.new do |spec| spec.version = LibTmux::VERSION spec.authors = ["libtmux contributors"] spec.summary = "Ruby tmux orchestration core" - spec.description = "Manage tmux sessions, windows and panes with Ruby handles, immutable snapshots and control connections." + spec.description = + "Manage tmux sessions, windows and panes with Ruby handles, immutable snapshots and control connections." spec.homepage = "https://github.com/libtmux/libtmux-ruby" spec.license = "MIT" spec.required_ruby_version = ">= 3.3" @@ -18,8 +19,11 @@ Gem::Specification.new do |spec| } spec.require_paths = ["lib"] spec.files = %w[ - LICENSE README.md CHANGELOG.md - assets/logo.svg assets/logo.png + LICENSE + README.md + CHANGELOG.md + assets/logo.svg + assets/logo.png lib/libtmux.rb lib/libtmux/version.rb lib/libtmux/tmux_version.rb diff --git a/scripts/export-docs/README.md b/scripts/export-docs/README.md index 963c4f44..6dd4e090 100644 --- a/scripts/export-docs/README.md +++ b/scripts/export-docs/README.md @@ -34,5 +34,6 @@ inventory, the package links, the example files and determinism. It builds the YARD registry, so `scripts/check` runs it in the packaging suite. ```console -$ bundle exec ruby -Itest scripts/export-docs/tests/packaging/docs_export_test.rb +$ bundle exec ruby -Itest \ + scripts/export-docs/tests/packaging/docs_export_test.rb ``` diff --git a/scripts/format b/scripts/format new file mode 100755 index 00000000..6ccfc9dc --- /dev/null +++ b/scripts/format @@ -0,0 +1,47 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +require "open3" + +# scripts/format format Ruby and refresh examples and API links +# scripts/format --check report formatting changes without writing files + +Dir.chdir(File.expand_path("..", __dir__)) + +SOURCE_WIDTH = 100 +EXAMPLE_WIDTH = 80 +MAX_PASSES = 5 + +abort "usage: scripts/format [--check]" unless ARGV.empty? || ARGV == ["--check"] +check = ARGV == ["--check"] + +tracked, status = Open3.capture2("git", "ls-files", "-z") +abort "git ls-files failed" unless status.success? +ruby_files = tracked.split("\0").select do |path| + # Standard formats maintainer scripts through scripts/lint/lint. + next false if path.start_with?("scripts/") || !File.file?(path) + path.end_with?(".rb", ".gemspec") || + %w[Gemfile Rakefile].include?(path) || + File.open(path, "rb", &:gets).to_s.start_with?("#!/usr/bin/env ruby") +end +examples, source = ruby_files.partition { |path| path.start_with?("examples/") } +groups = {SOURCE_WIDTH => source, EXAMPLE_WIDTH => examples}.reject { |_, files| files.empty? } +stree = Gem.bin_path("syntax_tree", "stree") +format = ->(verb, width, files) { system(Gem.ruby, stree, verb, "--print-width=#{width}", *files) } +clean = lambda do + groups.map { |width, files| format.call("check", width, files) }.all? +end + +exit(clean.call ? 0 : 1) if check + +# A first write can expose another wrap. Check for a stable result. +MAX_PASSES.times do + break if clean.call + groups.each do |width, files| + abort "formatting Ruby at #{width} columns failed" unless format.call("write", width, files) + end +end +abort "formatter did not converge in #{MAX_PASSES} passes" unless clean.call + +system(Gem.ruby, "scripts/examples/examples", "--write", exception: true) +system(Gem.ruby, "scripts/types", "--write", exception: true) diff --git a/scripts/version-check/README.md b/scripts/version-check/README.md index 72c65fcf..5f95b82e 100644 --- a/scripts/version-check/README.md +++ b/scripts/version-check/README.md @@ -24,5 +24,6 @@ the environment and deadline each check gets, the exit status of an unknown check, and that a test past its deadline stops with status 124. ```console -$ bundle exec scripts/check unit scripts/version-check/tests/version_check_test.rb +$ bundle exec scripts/check unit \ + scripts/version-check/tests/version_check_test.rb ``` diff --git a/test/integration/async_test.rb b/test/integration/async_test.rb index 087800d3..fd078488 100644 --- a/test/integration/async_test.rb +++ b/test/integration/async_test.rb @@ -18,7 +18,9 @@ def test_pending_capability_discovery_yields_and_cancellation_reaps_its_client LibTmuxTest::TmuxFixture.open do |fixture| listener = UNIXServer.new(File.join(File.dirname(fixture.socket_path), "capability-ready")) wrapper = File.join(File.dirname(fixture.socket_path), "capability-client") - LibTmuxTest::StubExecutable.write(wrapper, <<~'RUBY', READY: listener.path, CLIENT: fixture.executable) + LibTmuxTest::StubExecutable.write( + wrapper, + <<~'RUBY', require "socket" if ARGV.any? { |argument| argument.start_with?("libtmux-identity-") } UNIXSocket.open(READY) do |peer| @@ -28,16 +30,20 @@ def test_pending_capability_discovery_yields_and_cancellation_reaps_its_client end exec CLIENT, *ARGV RUBY + READY: listener.path, + CLIENT: fixture.executable + ) LibTmux::Server.open(socket_path: fixture.socket_path, executable: wrapper) do |source| Async do |parent| parent.with_timeout(0.5) do LibTmux::Async.open(parent: parent, server: source) do |scope| token = LibTmux::Cancellation.new - request = parent.async do - scope.server.capabilities(cancel: token) - rescue LibTmux::Cancelled => failure - failure - end + request = + parent.async do + scope.server.capabilities(cancel: token) + rescue LibTmux::Cancelled => failure + failure + end peer = listener.accept pid = Integer(peer.gets, 10) assert_equal :responsive, parent.async { :responsive }.wait @@ -69,11 +75,10 @@ def test_process_facade_yields_to_the_client_that_releases_a_wait parent.with_timeout(0.5) do LibTmux::Async.open(parent: parent, server: source) do |scope| assert_equal ref, scope.server.pane(ref).ref - waiting = parent.async do - scope.server.run(["wait-for", "-S", "async-ready", ";", "wait-for", "async-held"]) - end - assert scope.server.run(["wait-for", "async-ready"]).success? - assert scope.server.run(["wait-for", "-S", "async-held"]).success? + waiting = + parent.async { scope.server.run(%w[wait-for -S async-ready ; wait-for async-held]) } + assert scope.server.run(%w[wait-for async-ready]).success? + assert scope.server.run(%w[wait-for -S async-held]).success? result = waiting.wait assert result.success? assert_equal :observed, result.delivery @@ -81,16 +86,17 @@ def test_process_facade_yields_to_the_client_that_releases_a_wait end end end.wait - assert source.run(["has-session", "-t", "$0"]).success? + assert source.run(%w[has-session -t $0]).success? end end end def test_facade_built_by_a_scope_sets_what_its_hooks_read with_scope do |scope, _parent| - reads = %i[run dispatch ensure_owner ensure_open].flat_map do |hook| - LibTmuxTest::IvarReach.new(LibTmux::Async::Server).walk(hook, only_core: false).reads.keys - end + reads = + %i[run dispatch ensure_owner ensure_open].flat_map do |hook| + LibTmuxTest::IvarReach.new(LibTmux::Async::Server).walk(hook, only_core: false).reads.keys + end unset = reads.uniq.select { |ivar| scope.server.instance_variable_get(ivar).nil? } assert_empty unset, "facade hooks read variables the scope-built facade leaves unset" end @@ -102,14 +108,17 @@ def test_binary_pipe_flood_and_partial_input_stay_on_the_scheduler_thread owner = Thread.current owners = [] retained_output = 0 - trace = TracePoint.new(:call, :c_call, :return) do |event| - if event.event == :return && event.self.equal?(scope) && event.method_id == :retain_output - retained_output = scope.diagnostics.fetch(:retained_output_bytes) - elsif [:read_nonblock, :write_nonblock].include?(event.method_id) && - caller_locations(1, 8).any? { |location| location.path.end_with?("libtmux/async/process.rb") } - owners << Thread.current + trace = + TracePoint.new(:call, :c_call, :return) do |event| + if event.event == :return && event.self.equal?(scope) && event.method_id == :retain_output + retained_output = scope.diagnostics.fetch(:retained_output_bytes) + elsif %i[read_nonblock write_nonblock].include?(event.method_id) && + caller_locations(1, 8).any? do |location| + location.path.end_with?("libtmux/async/process.rb") + end + owners << Thread.current + end end - end code = <<~RUBY STDIN.binmode; STDOUT.binmode; STDERR.binmode out = Thread.new { STDOUT.write("\\xFF".b * 131072) } @@ -129,7 +138,8 @@ def test_binary_pipe_flood_and_partial_input_stay_on_the_scheduler_thread assert result.stdout.frozen? assert result.stderr.frozen? refute_empty owners - assert owners.all? { |thread| thread.equal?(owner) }, "a pipe reader or writer escaped the scheduler thread" + assert owners.all? { |thread| thread.equal?(owner) }, + "a pipe reader or writer escaped the scheduler thread" assert_raises(Errno::ECHILD) { Process.waitpid(result.pid, Process::WNOHANG) } ensure trace&.disable @@ -141,15 +151,17 @@ def test_ordered_map_retains_input_order_after_out_of_order_completion assert scope.respond_to?(:map), "bounded ordered map is missing" released = Queue.new completed = [] - results = scope.map([0, 1], concurrency: 2) do |index| - if index.zero? - released.pop - end - scope.server.run(["display-message", "-p", index.to_s]).tap do - completed << index - released << true unless index.zero? + results = + scope.map([0, 1], concurrency: 2) do |index| + released.pop if index.zero? + scope + .server + .run(["display-message", "-p", index.to_s]) + .tap do + completed << index + released << true unless index.zero? + end end - end assert_equal ["0\n", "1\n"], results.map(&:text) assert_equal [1, 0], completed assert results.all?(&:success?) @@ -164,28 +176,46 @@ def test_admission_caps_four_children_and_thirty_two_requests refute initial.fetch(:closed) assert initial.frozen? assert initial.fetch(:limits).frozen? - assert_equal({concurrency: 4, max_requests: 32, max_controls: 4, - max_queue_bytes: 1 << 22, max_output_bytes: 1 << 23, - stdout_limit: 1 << 20, stderr_limit: 1 << 18, input_limit: 1 << 20, - argv_limit: 1 << 18, cleanup_timeout: 0.5, drain_timeout: 0.5, close_timeout: 1.0}, initial.fetch(:limits)) + assert_equal( + { + concurrency: 4, + max_requests: 32, + max_controls: 4, + max_queue_bytes: 1 << 22, + max_output_bytes: 1 << 23, + stdout_limit: 1 << 20, + stderr_limit: 1 << 18, + input_limit: 1 << 20, + argv_limit: 1 << 18, + cleanup_timeout: 0.5, + drain_timeout: 0.5, + close_timeout: 1.0 + }, + initial.fetch(:limits) + ) listener = UNIXServer.new(File.join(File.dirname(fixture.socket_path), "async-admission")) - code = 'require "socket"; UNIXSocket.open(ARGV.fetch(0)) { |io| io.write(Process.pid.to_s + "\\n"); io.read(1) }' - requests = 32.times.map do - parent.async do - scope.__send__(:execute, ruby(code) + [listener.path]) - rescue LibTmux::Cancelled => failure - failure + code = + 'require "socket"; UNIXSocket.open(ARGV.fetch(0)) { |io| io.write(Process.pid.to_s + "\\n"); io.read(1) }' + requests = + 32.times.map do + parent.async do + scope.__send__(:execute, ruby(code) + [listener.path]) + rescue LibTmux::Cancelled => failure + failure + end end - end clients = 4.times.map { listener.accept } pids = clients.map { |client| Integer(client.gets, 10) } - assert_equal :wait_readable, listener.accept_nonblock(exception: false), "more than four children were dispatched" + assert_equal :wait_readable, + listener.accept_nonblock(exception: false), + "more than four children were dispatched" occupied = scope.server.diagnostics assert_equal 32, occupied.fetch(:admitted_requests) assert_equal 32, occupied.fetch(:reserved_process_slots) assert_equal 28, occupied.fetch(:waiting_requests) assert_equal 4, occupied.fetch(:active_process_slots) - assert_equal 32 * (ruby(code) + [listener.path]).sum { |arg| arg.bytesize + 1 }, occupied.fetch(:reserved_request_bytes) + assert_equal 32 * (ruby(code) + [listener.path]).sum { |arg| arg.bytesize + 1 }, + occupied.fetch(:reserved_request_bytes) assert_equal 0, occupied.fetch(:retained_output_bytes) assert_equal 0, occupied.fetch(:control_connections) assert_equal 0, occupied.fetch(:maps) @@ -194,17 +224,20 @@ def test_admission_caps_four_children_and_thirty_two_requests error = assert_raises(LibTmux::CapacityError) { scope.__send__(:execute, ruby("exit")) } assert_equal :not_sent, error.delivery requests.drop(4).each(&:cancel) - requests.drop(4).each do |request| - failure = request.wait - assert_instance_of LibTmux::Cancelled, failure - assert_equal :not_sent, failure.delivery - assert_nil failure.pid - end + requests + .drop(4) + .each do |request| + failure = request.wait + assert_instance_of LibTmux::Cancelled, failure + assert_equal :not_sent, failure.delivery + assert_nil failure.pid + end pending = scope.diagnostics assert_equal 4, pending.fetch(:admitted_requests) assert_equal 0, pending.fetch(:waiting_requests) assert_equal 4, pending.fetch(:active_process_slots) - assert_equal occupied.fetch(:reserved_request_bytes) / 8, pending.fetch(:reserved_request_bytes) + assert_equal occupied.fetch(:reserved_request_bytes) / 8, + pending.fetch(:reserved_request_bytes) clients.each { |client| client.write("x") } assert requests.take(4).all? { |request| request.wait.success? } pids.each { |pid| assert_raises(Errno::ECHILD) { Process.waitpid(pid, Process::WNOHANG) } } @@ -230,20 +263,22 @@ def test_repeated_caller_cancellation_reaps_a_child_ignoring_term io.read(1) end RUBY - request = parent.async do - scope.__send__(:execute, ruby(code) + [listener.path]) - rescue LibTmux::Error => failure - failure - end + request = + parent.async do + scope.__send__(:execute, ruby(code) + [listener.path]) + rescue LibTmux::Error => failure + failure + end peer = listener.accept pid = Integer(peer.gets, 10) - trace = TracePoint.new(:c_call) do |event| - next unless event.method_id == :wait2 && !observer + trace = + TracePoint.new(:c_call) do |event| + next unless event.method_id == :wait2 && !observer - observer = Thread.current - notify.syswrite("reaping\n") - release.pop - end + observer = Thread.current + notify.syswrite("reaping\n") + release.pop + end trace.enable request.cancel assert_equal "reaping\n", reaping.gets @@ -260,7 +295,7 @@ def test_repeated_caller_cancellation_reaps_a_child_ignoring_term assert_equal 0, scope.diagnostics.fetch(:active_process_slots) assert_equal 0, scope.diagnostics.fetch(:admitted_requests) assert_raises(Errno::ECHILD) { Process.waitpid(pid, Process::WNOHANG) } - assert scope.server.run(["has-session", "-t", "$0"]).success? + assert scope.server.run(%w[has-session -t $0]).success? ensure trace&.disable release << true if release @@ -275,26 +310,40 @@ def test_repeated_caller_cancellation_reaps_a_child_ignoring_term def test_wrong_thread_closed_binding_and_byte_admission_are_refused closed_scope = nil with_scope(max_queue_bytes: 64) do |scope, parent| - failures = Thread.new do - [-> { scope.server.run(["list-sessions"]) }, -> { scope.server.diagnostics }].map do |operation| - operation.call - rescue LibTmux::ClosedError => error - error - end - end.value + failures = + Thread + .new do + [ + -> { scope.server.run(["list-sessions"]) }, + -> { scope.server.diagnostics } + ].map do |operation| + operation.call + rescue LibTmux::ClosedError => error + error + end + end + .value assert failures.all? { |error| error.is_a?(LibTmux::ClosedError) } - child = Process.fork do - scope.diagnostics - exit! 1 - rescue LibTmux::ClosedError - exit! 0 - end - assert Process.waitpid2(child).last.success?, "forked child read its inherited scope diagnostics" + child = + Process.fork do + scope.diagnostics + exit! 1 + rescue LibTmux::ClosedError + exit! 0 + end + assert Process.waitpid2(child).last.success?, + "forked child read its inherited scope diagnostics" assert_equal 64, scope.diagnostics.fetch(:limits).fetch(:max_queue_bytes) - error = assert_raises(LibTmux::CapacityError) { scope.__send__(:execute, ruby("exit"), input: "x" * 65) } + error = + assert_raises(LibTmux::CapacityError) do + scope.__send__(:execute, ruby("exit"), input: "x" * 65) + end assert_equal :not_sent, error.delivery assert_nil error.pid - error = assert_raises(LibTmux::DeadlineExceeded) { scope.__send__(:execute, ruby("exit"), timeout: 0) } + error = + assert_raises(LibTmux::DeadlineExceeded) do + scope.__send__(:execute, ruby("exit"), timeout: 0) + end assert_equal :not_sent, error.delivery before_close = scope.diagnostics scope.close @@ -314,13 +363,14 @@ def test_map_failure_survives_repeated_cancellation_while_siblings_retire observer = nil original = RuntimeError.new("first map failure") peer = pid = nil - trace = TracePoint.new(:c_call) do |event| - next unless event.method_id == :wait2 && !observer + trace = + TracePoint.new(:c_call) do |event| + next unless event.method_id == :wait2 && !observer - observer = Thread.current - notify.syswrite("reaping\n") - release.pop - end + observer = Thread.current + notify.syswrite("reaping\n") + release.pop + end trace.enable code = <<~RUBY require "socket" @@ -331,27 +381,28 @@ def test_map_failure_survives_repeated_cancellation_while_siblings_retire io.read(1) end RUBY - failure = assert_raises(RuntimeError) do - scope.map([0, 1], concurrency: 2) do |index| - if index.zero? - scope.__send__(:execute, ruby(code) + [listener.path]) - else - peer = listener.accept - pid = Integer(peer.gets, 10) - parent.async do - assert_equal "reaping\n", reaping.gets - parent.cancel - parent.cancel - ensure - release << true + failure = + assert_raises(RuntimeError) do + scope.map([0, 1], concurrency: 2) do |index| + if index.zero? + scope.__send__(:execute, ruby(code) + [listener.path]) + else + peer = listener.accept + pid = Integer(peer.gets, 10) + parent.async do + assert_equal "reaping\n", reaping.gets + parent.cancel + parent.cancel + ensure + release << true + end + raise original end - raise original end end - end assert_same original, failure assert_raises(Errno::ECHILD) { Process.waitpid(pid, Process::WNOHANG) } - assert scope.server.run(["has-session", "-t", "$0"]).success? + assert scope.server.run(%w[has-session -t $0]).success? ensure trace&.disable release << true if release @@ -369,29 +420,31 @@ def test_map_cancel_delivery_uses_the_same_bounded_retirement_deadline original = RuntimeError.new("original map failure") worker = started = nil attempts = 0 - trace = TracePoint.new(:call) do |event| - next unless event.method_id == :cancel && event.self.equal?(worker) - - started ||= Process.clock_gettime(Process::CLOCK_MONOTONIC) - attempts += 1 - if Process.clock_gettime(Process::CLOCK_MONOTONIC) - started > 0.05 - raise RuntimeError, "cancellation delivery ignored the cleanup deadline" + trace = + TracePoint.new(:call) do |event| + next unless event.method_id == :cancel && event.self.equal?(worker) + + started ||= Process.clock_gettime(Process::CLOCK_MONOTONIC) + attempts += 1 + if Process.clock_gettime(Process::CLOCK_MONOTONIC) - started > 0.05 + raise RuntimeError, "cancellation delivery ignored the cleanup deadline" + end + raise ::Async::Cancel end - raise ::Async::Cancel - end - failure = assert_raises(RuntimeError) do - trace.enable do - scope.map([0, 1], concurrency: 2) do |index| - if index.zero? - ready.wait until worker - raise original + failure = + assert_raises(RuntimeError) do + trace.enable do + scope.map([0, 1], concurrency: 2) do |index| + if index.zero? + ready.wait until worker + raise original + end + worker = ::Async::Task.current + ready.signal + waiting.wait end - worker = ::Async::Task.current - ready.signal - waiting.wait end end - end assert_same original, failure assert_operator attempts, :>=, 1 assert failure.async_cleanup_errors.any? { |detail| detail.include?("cancellation") } @@ -407,18 +460,19 @@ def test_observed_exit_wins_token_cancellation_before_reaping released = Queue.new handed_off = false observer = nil - trace = TracePoint.new(:call, :return, :c_call) do |event| - if event.event == :return && event.defined_class == LibTmux::Internal::OwnedChild && - event.method_id == :finish_signalling && !handed_off - handed_off = true - cancel.cancel - elsif event.event == :c_call && event.method_id == :wait2 && !observer - observer = Thread.current - released.pop - elsif event.event == :call && event.method_id == :io_wait && handed_off - released << true + trace = + TracePoint.new(:call, :return, :c_call) do |event| + if event.event == :return && event.defined_class == LibTmux::Internal::OwnedChild && + event.method_id == :finish_signalling && !handed_off + handed_off = true + cancel.cancel + elsif event.event == :c_call && event.method_id == :wait2 && !observer + observer = Thread.current + released.pop + elsif event.event == :call && event.method_id == :io_wait && handed_off + released << true + end end - end trace.enable result = scope.__send__(:execute, ruby('STDOUT.write("done")'), cancel: cancel) trace.disable @@ -435,18 +489,22 @@ def test_observed_exit_wins_token_cancellation_before_reaping def test_output_and_map_retention_limits_fail_with_owned_cleanup with_scope(stdout_limit: 64) do |scope, parent| - error = assert_raises(LibTmux::CapacityError) { scope.__send__(:execute, ruby('STDOUT.write("x" * 65536)')) } + error = + assert_raises(LibTmux::CapacityError) do + scope.__send__(:execute, ruby('STDOUT.write("x" * 65536)')) + end assert_equal :possibly_sent, error.delivery assert_raises(Errno::ECHILD) { Process.waitpid(error.pid, Process::WNOHANG) } assert_empty error.cleanup_errors - error = assert_raises(LibTmux::CapacityError) do - scope.map([1, 2], max_bytes: 8) do |index| - snapshot = scope.diagnostics - assert_equal 1, snapshot.fetch(:maps) - assert_equal (index - 1) * 5, snapshot.fetch(:retained_output_bytes) - "x" * 5 + error = + assert_raises(LibTmux::CapacityError) do + scope.map([1, 2], max_bytes: 8) do |index| + snapshot = scope.diagnostics + assert_equal 1, snapshot.fetch(:maps) + assert_equal (index - 1) * 5, snapshot.fetch(:retained_output_bytes) + "x" * 5 + end end - end assert_equal :observed, error.delivery assert_equal 0, scope.diagnostics.fetch(:retained_output_bytes) assert_equal 0, scope.diagnostics.fetch(:maps) @@ -455,7 +513,10 @@ def test_output_and_map_retention_limits_fail_with_owned_cleanup def test_map_nested_results_cannot_bypass_byte_or_structure_limits with_scope do |scope, parent| - error = assert_raises(LibTmux::CapacityError) { scope.map([1], max_bytes: 16) { {payload: ["x" * 32]} } } + error = + assert_raises(LibTmux::CapacityError) do + scope.map([1], max_bytes: 16) { { payload: ["x" * 32] } } + end assert_equal :observed, error.delivery cycle = [] cycle << cycle @@ -470,48 +531,61 @@ def test_request_constructor_failure_releases_reserved_admission with_scope(max_requests: 1) do |scope, parent| original = RuntimeError.new("request construction failed") driver = LibTmux::Async.const_get(:ProcessDriver, false) - trace = TracePoint.new(:call) do |event| - raise original if event.defined_class == driver && event.method_id == :initialize - end + trace = + TracePoint.new(:call) do |event| + raise original if event.defined_class == driver && event.method_id == :initialize + end trace.enable failure = assert_raises(RuntimeError) { scope.server.run(["list-sessions"]) } trace.disable assert_same original, failure - assert scope.server.run(["has-session", "-t", "$0"]).success? + assert scope.server.run(%w[has-session -t $0]).success? ensure trace&.disable end end def test_control_wait_and_guarded_replies_progress_with_independent_processes - assert defined?(LibTmux::Async::ControlConnection), "scheduler-owned control transport is missing" + assert defined?(LibTmux::Async::ControlConnection), + "scheduler-owned control transport is missing" with_scope(control: true) do |scope, parent| owner = Thread.current io_owners = [] - trace = TracePoint.new(:call, :c_call) do |event| - if [:read_nonblock, :write_nonblock].include?(event.method_id) && - caller_locations(1, 8).any? { |location| location.path.end_with?("libtmux/async/control.rb") } - io_owners << Thread.current + trace = + TracePoint.new(:call, :c_call) do |event| + if %i[read_nonblock write_nonblock].include?(event.method_id) && + caller_locations(1, 8).any? { |location| + location.path.end_with?("libtmux/async/control.rb") + } + io_owners << Thread.current + end end - end trace.enable session = scope.server.list_sessions.first.ref - scope.server.open_control(session: session) do |control| - waiting = parent.async { control.exchange('wait-for -S async-control-ready ; wait-for async-control-held ; display-message -p complete') } - assert scope.server.run(["wait-for", "async-control-ready"]).success? - assert scope.server.run(["wait-for", "-S", "async-control-held"]).success? - reply = waiting.wait - assert_equal :observed, reply.delivery - assert_equal "complete\n", reply.blocks.last.body - assert reply.blocks.all?(&:frozen?) - pid = control.pid - control.close - assert_raises(Errno::ECHILD) { Process.waitpid(pid, Process::WNOHANG) } - end + scope + .server + .open_control(session: session) do |control| + waiting = + parent.async do + control.exchange( + "wait-for -S async-control-ready ; wait-for async-control-held ; display-message -p complete" + ) + end + assert scope.server.run(%w[wait-for async-control-ready]).success? + assert scope.server.run(%w[wait-for -S async-control-held]).success? + reply = waiting.wait + assert_equal :observed, reply.delivery + assert_equal "complete\n", reply.blocks.last.body + assert reply.blocks.all?(&:frozen?) + pid = control.pid + control.close + assert_raises(Errno::ECHILD) { Process.waitpid(pid, Process::WNOHANG) } + end trace.disable refute_empty io_owners - assert io_owners.all? { |thread| thread.equal?(owner) }, "control pipe I/O escaped its scheduler thread" - assert scope.server.run(["has-session", "-t", "$0"]).success? + assert io_owners.all? { |thread| thread.equal?(owner) }, + "control pipe I/O escaped its scheduler thread" + assert scope.server.run(%w[has-session -t $0]).success? ensure trace&.disable end @@ -521,17 +595,23 @@ def test_control_shares_guard_attribution_and_fails_closed_on_corruption with_scope(control: true) do |scope, parent| scope.server.run(["set-option", "-s", "command-alias[99]", "probe=display-message -p alias"]) scope.server.run(["set-hook", "-g", "command-error", "display-message -p error-hook"]) - scope.server.open_control(session: scope.server.list_sessions.first.ref) do |control| - reply = control.exchange("probe ; kill-session -t does-not-exist ; display-message -p never") - assert_equal :boundary_window, reply.attribution - refute_respond_to reply, :success? - assert_includes reply.blocks.map(&:body).join, "alias\n" - refute_includes reply.blocks.map(&:body).join, "never\n" - assert reply.blocks.any? { |block| block.terminator == :error } - fake = control.exchange("display-message -p 'parse error: unknown command: libtmux_boundary_guess'") - assert_includes fake.blocks.map(&:body).join, "libtmux_boundary_guess" - assert_run_shell_routing(control, scope.server.snapshot.server_info.fetch(:version)) - end + scope + .server + .open_control(session: scope.server.list_sessions.first.ref) do |control| + reply = + control.exchange("probe ; kill-session -t does-not-exist ; display-message -p never") + assert_equal :boundary_window, reply.attribution + refute_respond_to reply, :success? + assert_includes reply.blocks.map(&:body).join, "alias\n" + refute_includes reply.blocks.map(&:body).join, "never\n" + assert reply.blocks.any? { |block| block.terminator == :error } + fake = + control.exchange( + "display-message -p 'parse error: unknown command: libtmux_boundary_guess'" + ) + assert_includes fake.blocks.map(&:body).join, "libtmux_boundary_guess" + assert_run_shell_routing(control, scope.server.snapshot.server_info.fetch(:version)) + end end end @@ -547,27 +627,37 @@ def test_control_pipeline_preserves_reply_ownership_and_cancel_delivery result = super(bytes.byteslice(0, 7), **options) if result.is_a?(Integer) sent << bytes.byteslice(0, result) - writer.write_nonblock("x") if /pipeline-second\nlibtmux_boundary_[0-9a-f]+\n\z/.match?(sent) + if /pipeline-second\nlibtmux_boundary_[0-9a-f]+\n\z/.match?(sent) + writer.write_nonblock("x") + end end result end - first = parent.async do - control.exchange("wait-for -S pipeline-ready ; wait-for pipeline-held ; display-message -p pipeline-first", timeout: 0.5, cancel: token) - rescue LibTmux::Error => error - error - end - assert scope.server.run(["wait-for", "pipeline-ready"]).success? - second = parent.async do - control.exchange("display-message -p pipeline-second", timeout: 0.5) - rescue LibTmux::Error => error - error - end - assert Fiber.scheduler.io_wait(reader, IO::READABLE, 0.2), "second request bytes waited for the first reply" + first = + parent.async do + control.exchange( + "wait-for -S pipeline-ready ; wait-for pipeline-held ; display-message -p pipeline-first", + timeout: 0.5, + cancel: token + ) + rescue LibTmux::Error => error + error + end + assert scope.server.run(%w[wait-for pipeline-ready]).success? + second = + parent.async do + control.exchange("display-message -p pipeline-second", timeout: 0.5) + rescue LibTmux::Error => error + error + end + assert Fiber.scheduler.io_wait(reader, IO::READABLE, 0.2), + "second request bytes waited for the first reply" refute first.finished? refute second.finished? assert_respond_to control, :diagnostics pending = control.diagnostics - assert_equal [2, 2, 2], pending.values_at(:admitted_requests, :incomplete_requests, :awaiting_reply) + assert_equal [2, 2, 2], + pending.values_at(:admitted_requests, :incomplete_requests, :awaiting_reply) assert_operator pending.fetch(:reserved_wire_bytes), :>, 0 assert pending.frozen? assert pending.fetch(:limits).frozen? @@ -576,15 +666,20 @@ def test_control_pipeline_preserves_reply_ownership_and_cancel_delivery failure, later = first.wait, second.wait assert_instance_of LibTmux::Cancelled, failure assert_instance_of LibTmux::ClosedError, later - assert_equal [:possibly_sent, :possibly_sent], [failure.delivery, later.delivery] + assert_equal %i[possibly_sent possibly_sent], [failure.delivery, later.delivery] else - assert scope.server.run(["wait-for", "-S", "pipeline-held"]).success? + assert scope.server.run(%w[wait-for -S pipeline-held]).success? assert_equal "pipeline-first\n", first.wait.blocks.map(&:body).join assert_equal "pipeline-second\n", second.wait.blocks.map(&:body).join end control.close - assert_equal [0, 0, 0, 0], control.diagnostics.values_at(:admitted_requests, - :incomplete_requests, :reserved_wire_bytes, :retained_reply_bytes) + assert_equal [0, 0, 0, 0], + control.diagnostics.values_at( + :admitted_requests, + :incomplete_requests, + :reserved_wire_bytes, + :retained_reply_bytes + ) assert control.diagnostics.fetch(:finished) assert_empty control.instance_variable_get(:@requests) assert_empty control.instance_variable_get(:@replies) @@ -601,38 +696,74 @@ def test_control_pipeline_preserves_reply_ownership_and_cancel_delivery def test_control_overflow_and_tail_gaps_do_not_block_replies with_scope(control: true) do |scope, parent| - scope.server.open_control(session: scope.server.list_sessions.first.ref) do |control| - reliable = control.subscribe(max_events: 1, max_bytes: 1024) - tail = control.subscribe(mode: :tail, max_events: 1, max_bytes: 1024) - 3.times { |index| scope.server.run(["rename-window", "-t", "@0", "async-window#{index}"]) } - assert_equal "alive\n", control.exchange("display-message -p alive").blocks.last.body - assert reliable.diagnostics.fetch(:overflowed) - assert tail.diagnostics.fetch(:gap_pending) - assert_equal 3, control.diagnostics.fetch(:subscription_count) - assert_instance_of LibTmux::ControlEvent, reliable.next(timeout: 0.5) - assert_raises(LibTmux::SubscriptionOverflow) { reliable.next(timeout: 0.5) } - gap = tail.next(timeout: 0.5) - assert_equal :gap, gap.kind - assert_operator gap.dropped_bytes, :>, 0 - assert_instance_of LibTmux::ControlEvent, tail.next(timeout: 0.5) - failure = Thread.new { control.exchange("display-message -p wrong") rescue $! }.value - assert_instance_of LibTmux::ClosedError, failure - assert_instance_of LibTmux::ClosedError, Thread.new { control.diagnostics rescue $! }.value - assert_instance_of LibTmux::ClosedError, Thread.new { reliable.diagnostics rescue $! }.value - end + scope + .server + .open_control(session: scope.server.list_sessions.first.ref) do |control| + reliable = control.subscribe(max_events: 1, max_bytes: 1024) + tail = control.subscribe(mode: :tail, max_events: 1, max_bytes: 1024) + 3.times do |index| + scope.server.run(["rename-window", "-t", "@0", "async-window#{index}"]) + end + assert_equal "alive\n", control.exchange("display-message -p alive").blocks.last.body + assert reliable.diagnostics.fetch(:overflowed) + assert tail.diagnostics.fetch(:gap_pending) + assert_equal 3, control.diagnostics.fetch(:subscription_count) + assert_instance_of LibTmux::ControlEvent, reliable.next(timeout: 0.5) + assert_raises(LibTmux::SubscriptionOverflow) { reliable.next(timeout: 0.5) } + gap = tail.next(timeout: 0.5) + assert_equal :gap, gap.kind + assert_operator gap.dropped_bytes, :>, 0 + assert_instance_of LibTmux::ControlEvent, tail.next(timeout: 0.5) + failure = + Thread + .new do + begin + control.exchange("display-message -p wrong") + rescue StandardError + $! + end + end + .value + assert_instance_of LibTmux::ClosedError, failure + assert_instance_of LibTmux::ClosedError, + Thread + .new { + begin + control.diagnostics + rescue StandardError + $! + end + } + .value + assert_instance_of LibTmux::ClosedError, + Thread + .new { + begin + reliable.diagnostics + rescue StandardError + $! + end + } + .value + end end end def test_control_dispatched_cancellation_retires_connection_and_owned_watchers with_scope(control: true) do |scope, parent| - control = scope.server.open_control(session: scope.server.list_sessions.first.ref, max_requests: 1) + control = + scope.server.open_control(session: scope.server.list_sessions.first.ref, max_requests: 1) token = LibTmux::Internal::Cancellation.new - request = parent.async do - control.exchange("wait-for -S async-abort-ready ; wait-for async-abort-held", cancel: token) - rescue LibTmux::Cancelled => failure - failure - end - assert scope.server.run(["wait-for", "async-abort-ready"]).success? + request = + parent.async do + control.exchange( + "wait-for -S async-abort-ready ; wait-for async-abort-held", + cancel: token + ) + rescue LibTmux::Cancelled => failure + failure + end + assert scope.server.run(%w[wait-for async-abort-ready]).success? assert_raises(LibTmux::CapacityError) { control.exchange("display-message -p excess") } token.cancel failure = request.wait @@ -640,7 +771,7 @@ def test_control_dispatched_cancellation_retires_connection_and_owned_watchers assert_equal :possibly_sent, failure.delivery control.close assert_raises(Errno::ECHILD) { Process.waitpid(control.pid, Process::WNOHANG) } - assert scope.server.run(["has-session", "-t", "$0"]).success? + assert scope.server.run(%w[has-session -t $0]).success? ensure token&.close end @@ -653,21 +784,23 @@ def test_scope_close_joins_control_exchange_cleanup_before_returning entered, release = Queue.new, Queue.new request = nil selected = false - trace = TracePoint.new(:call) do |event| - if event.defined_class == ::Async::Task && event.method_id == :cancel && - ::Async::Task.current?.equal?(request) && !selected - selected = true - entered << true - release.pop + trace = + TracePoint.new(:call) do |event| + if event.defined_class == ::Async::Task && event.method_id == :cancel && + ::Async::Task.current?.equal?(request) && !selected + selected = true + entered << true + release.pop + end end - end trace.enable request = parent.async { control.exchange("display-message -p complete", cancel: token) } entered.pop closer = parent.async { scope.close } control.instance_variable_get(:@worker).wait parent.yield - refute closer.finished?, "scope close returned while an exchange still owned completion pipes and a watcher" + refute closer.finished?, + "scope close returned while an exchange still owned completion pipes and a watcher" retiring = scope.diagnostics assert retiring.fetch(:closed) assert_equal 1, retiring.fetch(:control_connections) @@ -689,15 +822,17 @@ def test_scope_close_joins_control_exchange_cleanup_before_returning def test_async_drain_deadline_bounds_an_externally_retained_pipe with_scope(drain_timeout: 0.03) do |scope, parent, fixture| listener = UNIXServer.new(File.join(File.dirname(fixture.socket_path), "async-retained")) - code = 'require "socket"; UNIXSocket.open(ARGV.fetch(0)) { |io| io.send_io(STDOUT) }; STDOUT.write("prefix")' - request = parent.async do - scope.__send__(:execute, ruby(code) + [listener.path]) - rescue LibTmux::DeadlineExceeded => failure - failure - end + code = + 'require "socket"; UNIXSocket.open(ARGV.fetch(0)) { |io| io.send_io(STDOUT) }; STDOUT.write("prefix")' + request = + parent.async do + scope.__send__(:execute, ruby(code) + [listener.path]) + rescue LibTmux::DeadlineExceeded => failure + failure + end peer = listener.accept held = peer.recv_io - assert scope.server.run(["has-session", "-t", "$0"]).success? + assert scope.server.run(%w[has-session -t $0]).success? failure = request.wait assert_instance_of LibTmux::DeadlineExceeded, failure assert_equal :observed, failure.delivery @@ -714,19 +849,22 @@ def test_async_observer_failure_retains_and_reaps_its_real_child with_scope(cleanup_timeout: 0.08) do |scope, parent, fixture| listener = UNIXServer.new(File.join(File.dirname(fixture.socket_path), "async-observer")) release = Queue.new - trace = TracePoint.new(:call) do |event| - if event.defined_class == LibTmux::Internal::ProcessWait && event.method_id == :observe - release.pop - raise IOError, "observer failure" + trace = + TracePoint.new(:call) do |event| + if event.defined_class == LibTmux::Internal::ProcessWait && event.method_id == :observe + release.pop + raise IOError, "observer failure" + end end - end trace.enable - code = 'require "socket"; UNIXSocket.open(ARGV.fetch(0)) { |io| io.write(Process.pid.to_s + "\\n"); io.read(1) }' - request = parent.async do - scope.__send__(:execute, ruby(code) + [listener.path]) - rescue LibTmux::TransportError => failure - failure - end + code = + 'require "socket"; UNIXSocket.open(ARGV.fetch(0)) { |io| io.write(Process.pid.to_s + "\\n"); io.read(1) }' + request = + parent.async do + scope.__send__(:execute, ruby(code) + [listener.path]) + rescue LibTmux::TransportError => failure + failure + end peer = listener.accept pid = Integer(peer.gets, 10) trace.disable @@ -746,24 +884,31 @@ def test_async_observer_failure_retains_and_reaps_its_real_child def test_control_spawn_failure_is_reported_without_losing_admission with_scope(control: true) do |_scope, parent, fixture| executable = File.join(File.dirname(fixture.socket_path), "removed-async-client") - File.write(executable, "#!#{RbConfig.ruby} --disable=rubyopt,gems\nexec #{fixture.executable.inspect}, *ARGV\n") + File.write( + executable, + "#!#{RbConfig.ruby} --disable=rubyopt,gems\nexec #{fixture.executable.inspect}, *ARGV\n" + ) File.chmod(0o700, executable) LibTmux::Server.open(socket_path: fixture.socket_path, executable: executable) do |source| ref = source.list_sessions.first.ref saved_executable = "#{executable}.saved" File.rename(executable, saved_executable) LibTmux::Async.open(parent: parent, server: source, max_controls: 1) do |isolated| - pipes = lambda do - Dir.children("/dev/fd").filter_map do |descriptor| - stat = File.stat("/dev/fd/#{descriptor}") - [descriptor, stat.dev, stat.ino] if stat.pipe? - rescue Errno::ENOENT, Errno::EBADF - nil + pipes = + lambda do + Dir + .children("/dev/fd") + .filter_map do |descriptor| + stat = File.stat("/dev/fd/#{descriptor}") + [descriptor, stat.dev, stat.ino] if stat.pipe? + rescue Errno::ENOENT, Errno::EBADF + nil + end end - end 2.times do before = pipes.call - failure = assert_raises(LibTmux::TransportError) { isolated.server.open_control(session: ref) } + failure = + assert_raises(LibTmux::TransportError) { isolated.server.open_control(session: ref) } assert_equal :spawn, failure.phase assert_equal :not_sent, failure.delivery assert_nil failure.pid @@ -772,9 +917,12 @@ def test_control_spawn_failure_is_reported_without_losing_admission end File.rename(saved_executable, executable) - isolated.server.open_control(session: ref) do |control| - assert_equal "recovered\n", control.exchange("display-message -p recovered").blocks.last.body - end + isolated + .server + .open_control(session: ref) do |control| + assert_equal "recovered\n", + control.exchange("display-message -p recovered").blocks.last.body + end end end end @@ -790,13 +938,13 @@ def test_control_flow_and_explicit_reconnect_report_loss_on_the_owning_scope observer.exchange("display-message -p observer-ready", timeout: 0.5) assert_instance_of LibTmux::GuardedReply, control.pause_output(pane_id: "%0", timeout: 0.5) pause = stream.next(timeout: 0.5) - assert_includes [:pause, :pause_requested], pause.reason + assert_includes %i[pause pause_requested], pause.reason assert_nil pause.dropped_bytes scope.server.run(["send-keys", "-t", "%0", "-l", "async-missed\n"]) loop { break if witness.next(timeout: 0.5).data&.include?("async-missed") } control.resume_output(pane_id: "%0", timeout: 0.5) resume = stream.next(timeout: 0.5) - assert_includes [:resume, :resume_requested], resume.reason + assert_includes %i[resume resume_requested], resume.reason scope.server.run(["send-keys", "-t", "%0", "-l", "async-resumed\n"]) observed = +"".b loop do diff --git a/test/integration/capture_semantics_test.rb b/test/integration/capture_semantics_test.rb index 241ec08e..599f2b2c 100644 --- a/test/integration/capture_semantics_test.rb +++ b/test/integration/capture_semantics_test.rb @@ -20,9 +20,14 @@ def run(argv, **options) name, usage = LibTmux::Internal::Metadata.decode(result.stdout, fields: 2, quoted: true).first usage = usage.delete("MT") - LibTmux::CommandResult.new(stdout: "#{name.bytesize}:#{name}#{usage.bytesize}:#{usage}\n", - stderr: result.stderr, status: result.status, elapsed_seconds: result.elapsed_seconds, - pid: result.pid, argv: result.argv) + LibTmux::CommandResult.new( + stdout: "#{name.bytesize}:#{name}#{usage.bytesize}:#{usage}\n", + stderr: result.stderr, + status: result.status, + elapsed_seconds: result.elapsed_seconds, + pid: result.pid, + argv: result.argv + ) end end @@ -32,30 +37,63 @@ def test_capture_preserves_requested_screen_content_and_distinguishes_mode_and_a channel = nil begin LibTmux::Server.open(socket_path: fixture.socket_path) do |server| - session = server.new_session(name: "screens", command: screen_program(listener.path), width: 20, height: 8) + session = + server.new_session( + name: "screens", + command: screen_program(listener.path), + width: 20, + height: 8 + ) window = session.list_windows.first window.resize(width: 20, height: 8) pane = window.list_panes.first assert_equal "20:8\n", pane.display('#{pane_width}:#{pane_height}').text - usage = server.run(["list-commands", "-F", '#{command_list_usage}', "capture-pane"]).text + usage = server.run(%w[list-commands -F #{command_list_usage} capture-pane]).text flags = usage.scan(/\[-([A-Za-z]+)(?:\]|\s)/).flatten.join assert IO.select([listener], nil, nil, 0.5), "screen program did not connect" channel = listener.accept render(channel, "zero\r\n\e[31mRED\e[0m \r\nabcdefghijklmnopqrstUV\r\ntail\r\n") - assert_equal "zero\nRED\nabcdefghijklmnopqrst\nUV\ntail\n", pane.capture(start: 0, finish: 4).stdout + assert_equal "zero\nRED\nabcdefghijklmnopqrst\nUV\ntail\n", + pane.capture(start: 0, finish: 4).stdout joined = pane.capture(start: 2, finish: 3, join: true).stdout assert_match(/\AabcdefghijklmnopqrstUV *\n\z/, joined) - physical = pane.capture(start: 2, finish: 3, preserve_trailing: true, - trim_trailing: flags.include?("T")).stdout.lines.map(&:chomp) - assert_equal physical.join + "\n", pane.capture(start: 2, finish: 3, join: true, preserve_trailing: true).stdout + physical = + pane + .capture( + start: 2, + finish: 3, + preserve_trailing: true, + trim_trailing: flags.include?("T") + ) + .stdout + .lines + .map(&:chomp) + assert_equal physical.join + "\n", + pane.capture(start: 2, finish: 3, join: true, preserve_trailing: true).stdout if flags.include?("T") - assert_equal "RED \n", pane.capture(start: 1, finish: 1, preserve_trailing: true, trim_trailing: true).stdout + assert_equal "RED \n", + pane.capture( + start: 1, + finish: 1, + preserve_trailing: true, + trim_trailing: true + ).stdout else assert_raises(LibTmux::UnsupportedFeatureError) { pane.capture(trim_trailing: true) } - assert_equal "RED ", pane.capture(start: 1, finish: 1, preserve_trailing: true).stdout.byteslice(0, 5) + assert_equal "RED ", + pane + .capture(start: 1, finish: 1, preserve_trailing: true) + .stdout + .byteslice(0, 5) end assert_includes pane.capture(start: 1, finish: 1, escapes: true).stdout, "\e[31mRED" - assert_includes pane.capture(start: 1, finish: 1, escapes: true, escape_bytes: true).stdout, '\033[31mRED' + assert_includes pane.capture( + start: 1, + finish: 1, + escapes: true, + escape_bytes: true + ).stdout, + '\033[31mRED' assert_raises(LibTmux::CommandError) { pane.capture(alternate: true) } pane.copy_mode @@ -95,7 +133,9 @@ def test_capture_preserves_requested_screen_content_and_distinguishes_mode_and_a channel.write([pending.bytesize | 0x80000000].pack("N") + pending) deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 2 until pane.capture(pending: true).stdout == "#{pending}\n" - flunk "pending input did not reach the pane" if Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline + if Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline + flunk "pending input did not reach the pane" + end sleep 0.01 end end @@ -113,8 +153,9 @@ def test_unadvertised_capture_modes_refuse_before_capture_and_conflicting_screen LibTmuxTest::TmuxFixture.open do |fixture| LimitedCaptureServer.open(socket_path: fixture.socket_path) do |server| pane = server.list_panes.first - [:mode_screen, :trim_trailing].each do |option| - error = assert_raises(LibTmux::UnsupportedFeatureError) { pane.capture(**{option => true}) } + %i[mode_screen trim_trailing].each do |option| + error = + assert_raises(LibTmux::UnsupportedFeatureError) { pane.capture(**{ option => true }) } assert_equal :not_sent, error.delivery end assert_nil server.capture_calls @@ -132,7 +173,13 @@ def test_copy_source_scroll_selection_exit_and_mouse_context_have_observable_eff channel = nil begin LibTmux::Server.open(socket_path: fixture.socket_path) do |server| - session = server.new_session(name: "copy-source", command: screen_program(listener.path), width: 20, height: 8) + session = + server.new_session( + name: "copy-source", + command: screen_program(listener.path), + width: 20, + height: 8 + ) source = session.list_panes.first target = session.new_window(name: "copy-target", command: ["/bin/cat"]).list_panes.first server.run(["set-option", "-w", "-t", target.id, "mode-keys", "vi"]) @@ -148,12 +195,13 @@ def test_copy_source_scroll_selection_exit_and_mouse_context_have_observable_eff target.copy_command("copy-selection") assert_equal "line00\n", server.read_buffer(server.list_buffers.first.fetch(:name)).stdout - usage = server.run(["list-commands", "-F", '#{command_list_usage}', "copy-mode"]).text + usage = server.run(%w[list-commands -F #{command_list_usage} copy-mode]).text if usage.scan(/\[-([A-Za-z]+)(?:\]|\s)/).flatten.join.include?("d") target.copy_mode(page_down: true) assert_operator target.display('#{scroll_position}').text.to_i, :<, top else - failure = assert_raises(LibTmux::UnsupportedFeatureError) { target.copy_mode(page_down: true) } + failure = + assert_raises(LibTmux::UnsupportedFeatureError) { target.copy_mode(page_down: true) } assert_equal :not_sent, failure.delivery assert_equal top, target.display('#{scroll_position}').text.to_i end diff --git a/test/integration/control_test.rb b/test/integration/control_test.rb index ffb64b10..a5a8183b 100644 --- a/test/integration/control_test.rb +++ b/test/integration/control_test.rb @@ -13,13 +13,19 @@ class ControlIntegrationTest < Minitest::Test def with_control(**options) LibTmuxTest::TmuxFixture.open do |fixture| - pin = LibTmux::Internal::SocketIdentity.new(LibTmux::Endpoint.new(socket_path: fixture.socket_path)) + pin = + LibTmux::Internal::SocketIdentity.new( + LibTmux::Endpoint.new(socket_path: fixture.socket_path) + ) begin next unless require_control_binding(pin) - LibTmux::ControlConnection.__send__(:open, binding: pin, session_id: "$0", **options) do |connection| - yield fixture, pin, connection - end + LibTmux::ControlConnection.__send__( + :open, + binding: pin, + session_id: "$0", + **options + ) { |connection| yield fixture, pin, connection } ensure pin.close end @@ -30,7 +36,11 @@ def test_boundaries_preserve_groups_aliases_hooks_and_protocol_looking_payload with_control do |fixture, _, control| fixture.tmux("set-option", "-s", "command-alias[99]", "probe=display-message -p alias") fixture.tmux("set-hook", "-g", "command-error", "display-message -p error-hook") - reply = control.exchange("probe ; kill-session -t does-not-exist ; display-message -p never", timeout: 0.5) + reply = + control.exchange( + "probe ; kill-session -t does-not-exist ; display-message -p never", + timeout: 0.5 + ) assert_instance_of LibTmux::GuardedReply, reply assert_equal :boundary_window, reply.attribution refute_respond_to reply, :success? @@ -38,7 +48,11 @@ def test_boundaries_preserve_groups_aliases_hooks_and_protocol_looking_payload assert_includes body, "alias\n" refute_includes body, "never\n" assert reply.blocks.any? { |block| block.terminator == :error } - fake = control.exchange("display-message -p 'parse error: unknown command: libtmux_boundary_guess'", timeout: 0.5) + fake = + control.exchange( + "display-message -p 'parse error: unknown command: libtmux_boundary_guess'", + timeout: 0.5 + ) assert_includes fake.blocks.map(&:body).join, "libtmux_boundary_guess" assert_equal "ok\n", control.exchange("display-message -p ok", timeout: 0.5).blocks.last.body end @@ -61,7 +75,7 @@ def test_native_pause_and_resume_preserve_prefix_and_report_unknown_loss break if event.kind == :gap end assert_includes prefix.filter_map(&:data).join, "prefix-marker" - assert_includes [:pause, :pause_requested], prefix.last.reason + assert_includes %i[pause pause_requested], prefix.last.reason assert_nil prefix.last.dropped_bytes fixture.tmux("send-keys", "-t", "%0", "-l", "missed-marker\n") @@ -69,7 +83,7 @@ def test_native_pause_and_resume_preserve_prefix_and_report_unknown_loss reply = control.resume_output(pane_id: "%0", timeout: 0.5) refute_respond_to reply, :success? resumed = stream.next(timeout: 0.5) - assert_includes [:resume, :resume_requested], resumed.reason + assert_includes %i[resume resume_requested], resumed.reason assert_equal "%0", resumed.pane_id assert_nil resumed.dropped_bytes fixture.tmux("send-keys", "-t", "%0", "-l", "resumed-marker\n") @@ -93,13 +107,23 @@ def test_native_pause_and_resume_preserve_prefix_and_report_unknown_loss def test_explicit_reconnect_has_a_new_generation_and_gap_without_replay with_control do |fixture, pin, control| assert_raises(ArgumentError) do - LibTmux::ControlConnection.__send__(:new, binding: pin, session_id: "$0", reconnect: control) + LibTmux::ControlConnection.__send__( + :new, + binding: pin, + session_id: "$0", + reconnect: control + ) end control.exchange("new-window -d -n once", timeout: 0.5) old_generation, old_pid = control.generation, control.pid control.close assert_raises(Errno::ECHILD) { Process.waitpid(old_pid, Process::WNOHANG) } - LibTmux::ControlConnection.__send__(:open, binding: pin, session_id: "$0", reconnect: control) do |fresh| + LibTmux::ControlConnection.__send__( + :open, + binding: pin, + session_id: "$0", + reconnect: control + ) do |fresh| refute_equal old_generation, fresh.generation assert_equal old_generation, fresh.previous_generation [fresh.events, fresh.subscribe(pane_id: "%0")].each do |stream| @@ -115,9 +139,17 @@ def test_explicit_reconnect_has_a_new_generation_and_gap_without_replay reply = fresh.exchange(%q{list-windows -F '#{window_name}'}, timeout: 0.5) assert_equal 1, reply.blocks.flat_map { |block| block.body.lines }.count("once\n") end - other = LibTmux::Internal::SocketIdentity.new(LibTmux::Endpoint.new(socket_path: fixture.socket_path)) + other = + LibTmux::Internal::SocketIdentity.new( + LibTmux::Endpoint.new(socket_path: fixture.socket_path) + ) assert_raises(ArgumentError) do - LibTmux::ControlConnection.__send__(:new, binding: other, session_id: "$0", reconnect: control) + LibTmux::ControlConnection.__send__( + :new, + binding: other, + session_id: "$0", + reconnect: control + ) end ensure other&.close @@ -129,18 +161,24 @@ def test_cancelled_flow_request_reports_uncertain_loss_only_after_dispatch token = LibTmux::Internal::Cancellation.new stream = control.subscribe(pane_id: "%0") token.cancel - error = assert_raises(LibTmux::Cancelled) { control.pause_output(pane_id: "%0", cancel: token) } + error = + assert_raises(LibTmux::Cancelled) { control.pause_output(pane_id: "%0", cancel: token) } assert_equal :not_sent, error.delivery assert_raises(LibTmux::DeadlineExceeded) { stream.next(timeout: 0) } token.close token = LibTmux::Internal::Cancellation.new - fixture.tmux("set-option", "-s", "command-alias[99]", - "refresh-client=wait-for -S flow-started ; wait-for flow-held ; refresh") - task = Thread.new do - control.pause_output(pane_id: "%0", cancel: token, timeout: 0.5) - rescue LibTmux::Cancelled => failure - failure - end + fixture.tmux( + "set-option", + "-s", + "command-alias[99]", + "refresh-client=wait-for -S flow-started ; wait-for flow-held ; refresh" + ) + task = + Thread.new do + control.pause_output(pane_id: "%0", cancel: token, timeout: 0.5) + rescue LibTmux::Cancelled => failure + failure + end fixture.tmux("wait-for", "flow-started") token.cancel assert_equal :possibly_sent, task.value.delivery @@ -158,9 +196,13 @@ def test_cancelled_flow_request_reports_uncertain_loss_only_after_dispatch def test_wait_holds_boundary_until_an_independent_client_releases_it with_control do |fixture, _, control| - thread = Thread.new do - control.exchange("wait-for -S control-started ; wait-for control-release ; display-message -p released", timeout: 0.5) - end + thread = + Thread.new do + control.exchange( + "wait-for -S control-started ; wait-for control-release ; display-message -p released", + timeout: 0.5 + ) + end fixture.tmux("wait-for", "control-started") assert thread.alive?, "WAIT must keep the request boundary pending after its successful guard" fixture.tmux("wait-for", "-S", "control-release") @@ -174,7 +216,8 @@ def test_control_retains_server_binding_and_close_reaps_only_owned_client with_control do |fixture, pin, control| pid = control.pid pin.close - assert_equal "retained\n", control.exchange("display-message -p retained", timeout: 0.5).blocks.last.body + assert_equal "retained\n", + control.exchange("display-message -p retained", timeout: 0.5).blocks.last.body control.close assert_raises(Errno::ECHILD) { Process.waitpid(pid, Process::WNOHANG) } assert fixture.tmux("has-session", "-t", "fixture").last.success? @@ -184,8 +227,12 @@ def test_control_retains_server_binding_and_close_reaps_only_owned_client def test_pipeline_writes_complete_requests_before_prior_replies with_control do |fixture, _, control| - fixture.tmux("set-option", "-s", "command-alias[99]", - "pipeline-probe=wait-for -S pipeline-ready ; wait-for pipeline-held ; display-message -p pipeline-first ; kill-session -t missing ; display-message -p never") + fixture.tmux( + "set-option", + "-s", + "command-alias[99]", + "pipeline-probe=wait-for -S pipeline-ready ; wait-for pipeline-held ; display-message -p pipeline-first ; kill-session -t missing ; display-message -p never" + ) fixture.tmux("set-hook", "-g", "command-error", "display-message -p pipeline-hook") reader, writer = IO.pipe sent = +"".b @@ -194,13 +241,13 @@ def test_pipeline_writes_complete_requests_before_prior_replies result = super(bytes.byteslice(0, 7), **options) if result.is_a?(Integer) sent << bytes.byteslice(0, result) - writer.write_nonblock("x") if /pipeline-second\nlibtmux_boundary_[0-9a-f]+\n\z/.match?(sent) + if /pipeline-second\nlibtmux_boundary_[0-9a-f]+\n\z/.match?(sent) + writer.write_nonblock("x") + end end result end - first = Thread.new do - control.exchange("pipeline-probe", timeout: 0.5) - end + first = Thread.new { control.exchange("pipeline-probe", timeout: 0.5) } fixture.tmux("wait-for", "pipeline-ready") second = Thread.new { control.exchange("display-message -p pipeline-second", timeout: 0.5) } assert IO.select([reader], nil, nil, 0.2), "second request bytes waited for the first reply" @@ -208,7 +255,8 @@ def test_pipeline_writes_complete_requests_before_prior_replies assert second.alive?, "tmux must retain the second request behind WAIT" assert_respond_to control, :diagnostics pending = control.diagnostics - assert_equal [2, 2, 2], pending.values_at(:admitted_requests, :incomplete_requests, :awaiting_reply) + assert_equal [2, 2, 2], + pending.values_at(:admitted_requests, :incomplete_requests, :awaiting_reply) assert_equal 0, pending.fetch(:queued_requests) assert_operator pending.fetch(:reserved_wire_bytes), :>, 0 assert pending.frozen? @@ -220,8 +268,13 @@ def test_pipeline_writes_complete_requests_before_prior_replies refute_includes earlier.blocks.map(&:body).join, "never\n" assert earlier.blocks.any? { |block| block.terminator == :error } assert_equal "pipeline-second\n", second.value.blocks.map(&:body).join - assert_equal [0, 0, 0, 0], control.diagnostics.values_at(:admitted_requests, - :incomplete_requests, :reserved_wire_bytes, :retained_reply_bytes) + assert_equal [0, 0, 0, 0], + control.diagnostics.values_at( + :admitted_requests, + :incomplete_requests, + :reserved_wire_bytes, + :retained_reply_bytes + ) assert_empty control.instance_variable_get(:@requests) ensure fixture.tmux("wait-for", "-S", "pipeline-held") if first&.alive? @@ -235,7 +288,8 @@ def test_slow_subscriber_overflows_without_blocking_replies with_control do |fixture, _, control| events = control.subscribe(max_events: 1, max_bytes: 1024) 3.times { |index| fixture.tmux("rename-window", "-t", "@0", "window#{index}") } - assert_equal "alive\n", control.exchange("display-message -p alive", timeout: 0.5).blocks.last.body + assert_equal "alive\n", + control.exchange("display-message -p alive", timeout: 0.5).blocks.last.body assert_instance_of LibTmux::ControlEvent, events.next(timeout: 0.5) assert_raises(LibTmux::SubscriptionOverflow) { events.next(timeout: 0.5) } end @@ -244,21 +298,28 @@ def test_slow_subscriber_overflows_without_blocking_replies def test_dispatched_cancellation_closes_connection_and_preserves_server with_control do |fixture, _, control| entered, release = Queue.new, Queue.new - control.singleton_class.prepend(Module.new do - define_method(:receive) do |record| - if record.is_a?(LibTmux::GuardedBlock) && record.body == "cancelled-prefix\n" - entered << true - release.pop + control.singleton_class.prepend( + Module.new do + define_method(:receive) do |record| + if record.is_a?(LibTmux::GuardedBlock) && record.body == "cancelled-prefix\n" + entered << true + release.pop + end + super(record) end - super(record) end - end) + ) token = LibTmux::Internal::Cancellation.new - thread = Thread.new do - control.exchange("display-message -p cancelled-prefix ; wait-for -S cancellation-started ; wait-for blocked", timeout: 0.5, cancel: token) - rescue LibTmux::Cancelled => error - error - end + thread = + Thread.new do + control.exchange( + "display-message -p cancelled-prefix ; wait-for -S cancellation-started ; wait-for blocked", + timeout: 0.5, + cancel: token + ) + rescue LibTmux::Cancelled => error + error + end fixture.tmux("wait-for", "cancellation-started") entered.pop token.cancel @@ -270,9 +331,16 @@ def test_dispatched_cancellation_closes_connection_and_preserves_server retired = control.diagnostics assert retired.fetch(:stopping) assert retired.fetch(:finished) - assert_equal [0, 0, 0, 0, 0, 0, 0], retired.values_at(:admitted_requests, - :incomplete_requests, :queued_requests, :writing_requests, :awaiting_reply, - :reserved_wire_bytes, :retained_reply_bytes) + assert_equal [0, 0, 0, 0, 0, 0, 0], + retired.values_at( + :admitted_requests, + :incomplete_requests, + :queued_requests, + :writing_requests, + :awaiting_reply, + :reserved_wire_bytes, + :retained_reply_bytes + ) assert_equal 0, retired.fetch(:cleanup_error_count) assert fixture.tmux("has-session", "-t", "fixture").last.success? ensure @@ -292,16 +360,21 @@ def test_pending_admission_is_bounded_and_cancellation_before_admission_is_not_s with_control(max_requests: 1) do |fixture, _, control| token = LibTmux::Internal::Cancellation.new token.cancel - error = assert_raises(LibTmux::Cancelled) { control.exchange("display-message -p never", cancel: token) } + error = + assert_raises(LibTmux::Cancelled) do + control.exchange("display-message -p never", cancel: token) + end assert_equal :not_sent, error.delivery - thread = Thread.new do - control.exchange("wait-for -S capacity-started ; wait-for capacity-release", timeout: 0.5) - end + thread = + Thread.new do + control.exchange("wait-for -S capacity-started ; wait-for capacity-release", timeout: 0.5) + end fixture.tmux("wait-for", "capacity-started") assert_raises(LibTmux::CapacityError) { control.exchange("display-message -p excess") } fixture.tmux("wait-for", "-S", "capacity-release") assert_instance_of LibTmux::GuardedReply, thread.value - assert_equal "still-open\n", control.exchange("display-message -p still-open", timeout: 0.5).blocks.last.body + assert_equal "still-open\n", + control.exchange("display-message -p still-open", timeout: 0.5).blocks.last.body ensure token&.close thread&.join(0.5) @@ -311,21 +384,27 @@ def test_pending_admission_is_bounded_and_cancellation_before_admission_is_not_s def test_repeated_thread_cancellation_preserves_first_failure_during_retirement with_control do |fixture, _, control| cleanup_entered, cleanup_release = Queue.new, Queue.new - control.singleton_class.prepend(Module.new do - define_method(:abort_request) do |request, type, message| - if message == "control request interrupted" - cleanup_entered << true - cleanup_release.pop + control.singleton_class.prepend( + Module.new do + define_method(:abort_request) do |request, type, message| + if message == "control request interrupted" + cleanup_entered << true + cleanup_release.pop + end + super(request, type, message) end - super(request, type, message) end - end) + ) first = Interrupt.new("first cancellation") - thread = Thread.new do - control.exchange("wait-for -S interrupt-started ; wait-for interrupt-blocked", timeout: 0.5) - rescue Exception => failure - failure - end + thread = + Thread.new do + control.exchange( + "wait-for -S interrupt-started ; wait-for interrupt-blocked", + timeout: 0.5 + ) + rescue Exception => failure + failure + end fixture.tmux("wait-for", "interrupt-started") thread.raise(first) cleanup_entered.pop @@ -344,7 +423,9 @@ def test_detach_closes_pending_request_without_waiting_for_deadline with_control do |_, _, control| control.exchange("detach-client", timeout: 0.5) loop { break if control.events.next(timeout: 0.5).raw.start_with?("%exit") } - assert_raises(LibTmux::ClosedError) { control.exchange("display-message -p detached", timeout: 0.5) } + assert_raises(LibTmux::ClosedError) do + control.exchange("display-message -p detached", timeout: 0.5) + end control.close assert_raises(Errno::ECHILD) { Process.waitpid(control.pid, Process::WNOHANG) } end @@ -371,29 +452,36 @@ def test_forked_child_rejects_inherited_streams_and_detaches_all_local_pipes with_control do |_, _, control| stream = control.subscribe reader, writer = IO.pipe - child = fork do - reader.close - rejected = begin - stream.next(timeout: 0) - false - rescue LibTmux::ClosedError - true - rescue LibTmux::DeadlineExceeded - false + child = + fork do + reader.close + rejected = + begin + stream.next(timeout: 0) + false + rescue LibTmux::ClosedError + true + rescue LibTmux::DeadlineExceeded + false + end + control.close + writer.write(rejected ? "closed" : "wrong") + writer.close + exit! 0 end - control.close - writer.write(rejected ? "closed" : "wrong") - writer.close - exit! 0 - end writer.close assert IO.select([reader], nil, nil, 0.5), "fork check must report through its pipe" assert_equal "closed", reader.read Process.wait(child) - assert_equal "parent\n", control.exchange("display-message -p parent", timeout: 0.5).blocks.last.body + assert_equal "parent\n", + control.exchange("display-message -p parent", timeout: 0.5).blocks.last.body ensure [reader, writer].compact.each { |io| io.close unless io.closed? } - Process.wait(child) rescue Errno::ECHILD + begin + Process.wait(child) + rescue StandardError + Errno::ECHILD + end end end @@ -407,30 +495,45 @@ def test_late_exit_observation_failure_receives_final_retirement_token def check_failed_observation(late: false) LibTmuxTest::TmuxFixture.open do |fixture| - probe = LibTmux::Internal::SocketIdentity.new(LibTmux::Endpoint.new(socket_path: fixture.socket_path)) - supported = begin - require_control_binding(probe) - ensure - probe.close - end + probe = + LibTmux::Internal::SocketIdentity.new( + LibTmux::Endpoint.new(socket_path: fixture.socket_path) + ) + supported = + begin + require_control_binding(probe) + ensure + probe.close + end next unless supported original_rubyopt = ENV["RUBYOPT"] executable = File.join(File.dirname(fixture.socket_path), "control-child") - File.write(executable, "#!#{RbConfig.ruby} --disable=rubyopt,gems\nexec #{fixture.executable.inspect}, *ARGV unless ARGV.include?('-C') && ARGV.include?('attach-session')\ntrap('TERM') {}\nSTDOUT.write(\"ready\\n\"); STDOUT.flush\nIO.select([])\n") + File.write( + executable, + "#!#{RbConfig.ruby} --disable=rubyopt,gems\nexec #{fixture.executable.inspect}, *ARGV unless ARGV.include?('-C') && ARGV.include?('attach-session')\ntrap('TERM') {}\nSTDOUT.write(\"ready\\n\"); STDOUT.flush\nIO.select([])\n" + ) File.chmod(0o700, executable) ambient_startup = File.join(File.dirname(fixture.socket_path), "ambient-startup.rb") File.write(ambient_startup, "STDOUT.write(\"ambient startup\\n\"); STDOUT.flush\n") ENV["RUBYOPT"] = "-r#{ambient_startup}" - pin = LibTmux::Internal::SocketIdentity.new(LibTmux::Endpoint.new(socket_path: fixture.socket_path, executable: executable)) + pin = + LibTmux::Internal::SocketIdentity.new( + LibTmux::Endpoint.new(socket_path: fixture.socket_path, executable: executable) + ) gate = Queue.new wait_class = LibTmux::Internal::ProcessWait original_new = wait_class.method(:new) wait_class.define_singleton_method(:new) do - next original_new.call unless caller_locations(1, 1).first.path.end_with?("/libtmux/control.rb") + unless caller_locations(1, 1).first.path.end_with?("/libtmux/control.rb") + next original_new.call + end Object.new.tap do |observer| - observer.define_singleton_method(:observe) { |_| gate.pop; raise IOError, "observer injection" } + observer.define_singleton_method(:observe) do |_| + gate.pop + raise IOError, "observer injection" + end end end control = LibTmux::ControlConnection.__send__(:open, binding: pin, session_id: "$0") @@ -439,17 +542,20 @@ def check_failed_observation(late: false) ENV["RUBYOPT"] = original_rubyopt if late observer = control.instance_variable_get(:@child) - observer.singleton_class.prepend(Module.new do - define_method(:join) do |timeout| - gate << true - super(timeout) + observer.singleton_class.prepend( + Module.new do + define_method(:join) do |timeout| + gate << true + super(timeout) + end end - end) + ) else gate << true end error = assert_raises(LibTmux::TransportError) { control.close } - assert error.cleanup_errors.any? { |item| item.include?("observation") }, "cleanup must report the observer failure" + assert error.cleanup_errors.any? { |item| item.include?("observation") }, + "cleanup must report the observer failure" assert_raises(Errno::ECHILD) { Process.waitpid(control.pid, Process::WNOHANG) } ensure ENV["RUBYOPT"] = original_rubyopt @@ -466,28 +572,35 @@ def check_failed_observation(late: false) def test_completed_unconsumed_requests_still_count_against_admission with_control(max_requests: 1) do |_, _, control| cleanup_entered, cleanup_release = Queue.new, Queue.new - control.singleton_class.prepend(Module.new do - define_method(:abort_request) do |request, type, message| - if request.id == 1 && request.result && message == "control request interrupted" - cleanup_entered << true - cleanup_release.pop + control.singleton_class.prepend( + Module.new do + define_method(:abort_request) do |request, type, message| + if request.id == 1 && request.result && message == "control request interrupted" + cleanup_entered << true + cleanup_release.pop + end + super(request, type, message) end - super(request, type, message) end - end) + ) thread = Thread.new { control.exchange("display-message -p completed", timeout: 0.5) } cleanup_entered.pop assert_respond_to control, :diagnostics retained = control.diagnostics - assert_equal [1, 0, 0], retained.values_at(:admitted_requests, :incomplete_requests, :awaiting_reply) + assert_equal [1, 0, 0], + retained.values_at(:admitted_requests, :incomplete_requests, :awaiting_reply) assert_operator retained.fetch(:retained_reply_bytes), :>=, "completed\n".bytesize - assert_raises(LibTmux::CapacityError) { control.exchange("display-message -p excess", timeout: 0.5) } + assert_raises(LibTmux::CapacityError) do + control.exchange("display-message -p excess", timeout: 0.5) + end cleanup_release << true reply = thread.value assert_equal "completed\n", reply.blocks.last.body assert_equal reply.blocks.sum(&:bytesize), retained.fetch(:retained_reply_bytes) - assert_equal [0, 0], control.diagnostics.values_at(:reserved_wire_bytes, :retained_reply_bytes) - assert_equal "next\n", control.exchange("display-message -p next", timeout: 0.5).blocks.last.body + assert_equal [0, 0], + control.diagnostics.values_at(:reserved_wire_bytes, :retained_reply_bytes) + assert_equal "next\n", + control.exchange("display-message -p next", timeout: 0.5).blocks.last.body ensure cleanup_release << true thread&.join(0.5) diff --git a/test/integration/creation_receipt_test.rb b/test/integration/creation_receipt_test.rb index 87074167..8b19e95f 100644 --- a/test/integration/creation_receipt_test.rb +++ b/test/integration/creation_receipt_test.rb @@ -16,13 +16,23 @@ def test_creation_receipts_return_initial_children_in_the_command_reply assert receipt.result.success? assert_equal :observed, receipt.result.delivery assert receipt.frozen? - assert_equal 3, LibTmux::Internal::Metadata.decode(receipt.result.stdout, fields: 3).first.length + assert_equal 3, + LibTmux::Internal::Metadata + .decode(receipt.result.stdout, fields: 3) + .first + .length window = receipt.entity.new_window(name: "second", command: ["cat"], receipt: true) assert_instance_of LibTmux::Window, window.entity assert_same window.entity, window.window assert_equal [window.pane.ref], window.window.list_panes.map(&:ref) - assert_equal 2, LibTmux::Internal::Metadata.decode(window.result.stdout, fields: 2).first.length - assert_raises(ArgumentError) { server.new_session(name: "invalid", command: ["cat"], receipt: :yes) } + assert_equal 2, + LibTmux::Internal::Metadata + .decode(window.result.stdout, fields: 2) + .first + .length + assert_raises(ArgumentError) do + server.new_session(name: "invalid", command: ["cat"], receipt: :yes) + end end end end diff --git a/test/integration/creation_test.rb b/test/integration/creation_test.rb index 3d6c59b1..3c85ddb6 100644 --- a/test/integration/creation_test.rb +++ b/test/integration/creation_test.rb @@ -17,38 +17,89 @@ def test_creation_preserves_child_directory_environment_indexes_and_exact_split_ LibTmux::Server.open(socket_path: fixture.socket_path) do |server| command = child_command(receipt.path) literal = "#{'#{pid}'};=\n" - session = server.new_session(name: "workspace", command: command, window_name: 'initial #{pid};', - cwd: first_directory, environment: {"ROOT" => "root", "LITERAL" => literal}, width: 100, height: 30) + session = + server.new_session( + name: "workspace", + command: command, + window_name: 'initial #{pid};', + cwd: first_directory, + environment: { + "ROOT" => "root", + "LITERAL" => literal + }, + width: 100, + height: 30 + ) assert_equal [File.realpath(first_directory), "root", nil, literal], receive(receipt) initial = session.list_windows.first assert_equal "initial \#{pid};\n", initial.display('#{window_name}').text - window = session.new_window(name: "second", command: command, index: 4, focus: true, - cwd: second_directory, environment: {"CHILD" => "window"}) - assert_equal [File.realpath(second_directory), "root", "window", literal], receive(receipt) + window = + session.new_window( + name: "second", + command: command, + index: 4, + focus: true, + cwd: second_directory, + environment: { + "CHILD" => "window" + } + ) + assert_equal [File.realpath(second_directory), "root", "window", literal], + receive(receipt) assert_equal "4\n", window.display('#{window_index}').text assert_equal "#{window.id}\n", session.display('#{window_id}').text assert_raises(LibTmux::CommandError) { session.environment("CHILD") } pane = window.list_panes.first - sibling = pane.split(direction: :horizontal, size: 20, command: command, - cwd: first_directory, environment: {"ROOT" => "override", "CHILD" => "pane"}) - assert_equal [File.realpath(first_directory), "override", "pane", literal], receive(receipt) + sibling = + pane.split( + direction: :horizontal, + size: 20, + command: command, + cwd: first_directory, + environment: { + "ROOT" => "override", + "CHILD" => "pane" + } + ) + assert_equal [File.realpath(first_directory), "override", "pane", literal], + receive(receipt) assert_equal "20\n", sibling.display('#{pane_width}').text assert_equal "#{pane.id}\n", window.display('#{pane_id}').text sibling.select - split = pane.split(direction: :vertical, size: "25%", focus: true, command: command, - cwd: second_directory) + split = + pane.split( + direction: :vertical, + size: "25%", + focus: true, + command: command, + cwd: second_directory + ) assert_equal [File.realpath(second_directory), "root", nil, literal], receive(receipt) assert_equal pane.display('#{pane_width}').text, split.display('#{pane_width}').text refute_equal sibling.display('#{pane_width}').text, split.display('#{pane_width}').text - assert_operator split.display('#{pane_height}').text.to_i, :<, sibling.display('#{pane_height}').text.to_i + assert_operator split.display('#{pane_height}').text.to_i, + :<, + sibling.display('#{pane_height}').text.to_i assert_equal "#{split.id}\n", window.display('#{pane_id}').text - assert_raises(LibTmux::CommandError) { session.new_window(name: "collision", command: ["/bin/cat"], index: 4) } + assert_raises(LibTmux::CommandError) do + session.new_window(name: "collision", command: ["/bin/cat"], index: 4) + end assert_equal [initial.id, window.id], session.list_windows.map(&:id) - assert_raises(ArgumentError) { pane.split(direction: :horizontal, command: command, size: "0%") } - assert_raises(ArgumentError) { pane.split(direction: :horizontal, command: command, environment: {"ROOT" => nil}) } - assert_raises(ArgumentError) { session.new_window(name: "missing-dir", command: command, cwd: File.join(directory, "absent")) } + assert_raises(ArgumentError) do + pane.split(direction: :horizontal, command: command, size: "0%") + end + assert_raises(ArgumentError) do + pane.split(direction: :horizontal, command: command, environment: { "ROOT" => nil }) + end + assert_raises(ArgumentError) do + session.new_window( + name: "missing-dir", + command: command, + cwd: File.join(directory, "absent") + ) + end assert_equal [initial.id, window.id], session.list_windows.map(&:id) assert_equal 3, window.list_panes.length end @@ -72,15 +123,29 @@ def test_respawn_keeps_entity_identity_and_replaces_process_directory_and_enviro old_pid = sibling.display('#{pane_pid}').text assert_raises(LibTmux::CommandError) { sibling.respawn(command: ["/bin/cat"]) } assert_equal old_pid, sibling.display('#{pane_pid}').text - sibling.respawn(command: child_command(listener.path), kill: true, cwd: child_directory, - environment: {"ROOT" => "pane"}, timeout: 0.5) + sibling.respawn( + command: child_command(listener.path), + kill: true, + cwd: child_directory, + environment: { + "ROOT" => "pane" + }, + timeout: 0.5 + ) assert_equal [File.realpath(child_directory), "pane", nil, nil], receive(listener) refute_equal old_pid, sibling.display('#{pane_pid}').text assert_equal [original.id, sibling.id], window.list_panes.map(&:id) old_pid = original.display('#{pane_pid}').text - window.respawn(command: child_command(listener.path), kill: true, cwd: directory, - environment: {"ROOT" => "window"}, timeout: 0.5) + window.respawn( + command: child_command(listener.path), + kill: true, + cwd: directory, + environment: { + "ROOT" => "window" + }, + timeout: 0.5 + ) assert_equal [File.realpath(directory), "window", nil, nil], receive(listener) assert_equal [original.id], window.list_panes.map(&:id) refute_equal old_pid, original.display('#{pane_pid}').text @@ -102,15 +167,28 @@ def test_global_and_hidden_environment_control_child_inheritance server.set_environment("CHILD", "global secret", hidden: true) assert_equal "global", server.environment("ROOT") assert_equal "global secret", server.environment("CHILD", hidden: true) - session = server.new_session(name: "environment", command: child_command(listener.path), cwd: directory) + session = + server.new_session( + name: "environment", + command: child_command(listener.path), + cwd: directory + ) assert_equal [File.realpath(directory), "global", nil, nil], receive(listener) session.set_environment("ROOT", "session") session.set_environment("LITERAL", "session secret", hidden: true) assert_equal "session secret", session.environment("LITERAL", hidden: true) - session.new_window(name: "override", command: child_command(listener.path), cwd: directory) + session.new_window( + name: "override", + command: child_command(listener.path), + cwd: directory + ) assert_equal [File.realpath(directory), "session", nil, nil], receive(listener) session.unset_environment("ROOT") - session.new_window(name: "fallback", command: child_command(listener.path), cwd: directory) + session.new_window( + name: "fallback", + command: child_command(listener.path), + cwd: directory + ) assert_equal [File.realpath(directory), "global", nil, nil], receive(listener) server.unset_environment("CHILD") assert_raises(LibTmux::CommandError) { server.environment("CHILD", hidden: true) } @@ -124,7 +202,8 @@ def test_global_and_hidden_environment_control_child_inheritance private def child_command(path) - source = 'UNIXSocket.open(ARGV.fetch(0)) { |io| io.write(Marshal.dump([Dir.pwd, *ENV.values_at("ROOT", "CHILD", "LITERAL")])) }; STDIN.read' + source = + 'UNIXSocket.open(ARGV.fetch(0)) { |io| io.write(Marshal.dump([Dir.pwd, *ENV.values_at("ROOT", "CHILD", "LITERAL")])) }; STDIN.read' [Gem.ruby, "--disable=rubyopt,gems", "-rsocket", "-e", source, path] end diff --git a/test/integration/default_socket_test.rb b/test/integration/default_socket_test.rb index 95a9c2ed..d694c3e5 100644 --- a/test/integration/default_socket_test.rb +++ b/test/integration/default_socket_test.rb @@ -15,14 +15,21 @@ class DefaultSocketTest < Minitest::Test def test_the_path_variable_binds_the_server_at_that_path LibTmuxTest::TmuxFixture.open do |fixture| - assert_equal ["fixture"], sessions(environment: {"LIBTMUX_SOCKET_PATH" => fixture.socket_path}) + assert_equal ["fixture"], + sessions(environment: { "LIBTMUX_SOCKET_PATH" => fixture.socket_path }) end end def test_the_name_variable_binds_the_named_server_in_the_tmux_directory with_private_tmux_directory do |directory| start_tmux(directory, "-L", "named", session: "named") - assert_equal ["named"], sessions(environment: {"LIBTMUX_SOCKET" => "named", "TMUX_TMPDIR" => directory}) + assert_equal ["named"], + sessions( + environment: { + "LIBTMUX_SOCKET" => "named", + "TMUX_TMPDIR" => directory + } + ) end end @@ -30,7 +37,11 @@ def test_the_path_variable_wins_over_the_name_variable LibTmuxTest::TmuxFixture.open do |fixture| with_private_tmux_directory do |directory| start_tmux(directory, "-L", "named", session: "named") - variables = {"LIBTMUX_SOCKET_PATH" => fixture.socket_path, "LIBTMUX_SOCKET" => "named", "TMUX_TMPDIR" => directory} + variables = { + "LIBTMUX_SOCKET_PATH" => fixture.socket_path, + "LIBTMUX_SOCKET" => "named", + "TMUX_TMPDIR" => directory + } assert_equal ["fixture"], sessions(environment: variables) end end @@ -39,15 +50,20 @@ def test_the_path_variable_wins_over_the_name_variable def test_with_nothing_set_it_binds_the_default_server_of_the_tmux_directory with_private_tmux_directory do |directory| start_tmux(directory, session: "bare") - assert_equal ["bare"], sessions(environment: {"TMUX_TMPDIR" => directory}) + assert_equal ["bare"], sessions(environment: { "TMUX_TMPDIR" => directory }) end end def test_with_nothing_set_and_no_server_it_refuses_instead_of_starting_one with_private_tmux_directory do |directory| - error = assert_raises(LibTmux::TargetNotFoundError) { sessions(environment: {"TMUX_TMPDIR" => directory}) } + error = + assert_raises(LibTmux::TargetNotFoundError) do + sessions(environment: { "TMUX_TMPDIR" => directory }) + end assert_includes error.message, "endpoint is unavailable" - assert_empty Dir.glob(File.join(directory, "**", "*"), File::FNM_DOTMATCH).select { |path| File.socket?(path) } + assert_empty Dir + .glob(File.join(directory, "**", "*"), File::FNM_DOTMATCH) + .select { |path| File.socket?(path) } end end @@ -55,7 +71,7 @@ def test_inside_tmux_it_binds_the_server_tmux_names_and_not_the_default LibTmuxTest::TmuxFixture.open do |fixture| with_private_tmux_directory do |directory| start_tmux(directory, session: "bare") - inside = {"TMUX" => "#{fixture.socket_path},4321,0", "TMUX_TMPDIR" => directory} + inside = { "TMUX" => "#{fixture.socket_path},4321,0", "TMUX_TMPDIR" => directory } assert_equal ["fixture"], sessions(environment: inside) assert_equal ["bare"], sessions(environment: inside.merge("TMUX" => nil)) end @@ -66,7 +82,7 @@ def test_a_variable_wins_over_the_tmux_server LibTmuxTest::TmuxFixture.open do |fixture| with_private_tmux_directory do |directory| start_tmux(directory, "-L", "named", session: "named") - inside = {"TMUX" => "#{fixture.socket_path},4321,0", "TMUX_TMPDIR" => directory} + inside = { "TMUX" => "#{fixture.socket_path},4321,0", "TMUX_TMPDIR" => directory } assert_equal ["named"], sessions(environment: inside.merge("LIBTMUX_SOCKET" => "named")) end end @@ -79,9 +95,13 @@ def test_a_variable_wins_over_the_tmux_server # default server of whoever runs the suite. def sessions(environment:) Dir.mktmpdir("libtmux-ruby-empty-") do |empty| - endpoint = LibTmux::Endpoint.new(executable: EXECUTABLE, environment: {"TMUX_TMPDIR" => empty}.merge(environment).compact) + endpoint = + LibTmux::Endpoint.new( + executable: EXECUTABLE, + environment: { "TMUX_TMPDIR" => empty }.merge(environment).compact + ) LibTmux::Server.open(endpoint: endpoint) do |server| - server.run(["list-sessions", "-F", '#{session_name}']).text.lines.map(&:chomp) + server.run(%w[list-sessions -F #{session_name}]).text.lines.map(&:chomp) end end end @@ -92,18 +112,35 @@ def with_private_tmux_directory yield directory ensure if directory - Dir.glob(File.join(directory, "**", "*"), File::FNM_DOTMATCH).select { |path| File.socket?(path) }.each do |socket| - Open3.capture3(EXECUTABLE, "-S", socket, "kill-server") - end + Dir + .glob(File.join(directory, "**", "*"), File::FNM_DOTMATCH) + .select { |path| File.socket?(path) } + .each { |socket| Open3.capture3(EXECUTABLE, "-S", socket, "kill-server") } FileUtils.remove_entry(directory) end end def start_tmux(directory, *selector, session:) - environment = {"TMUX_TMPDIR" => directory, "TMUX" => nil, "TMUX_PANE" => nil, - "LIBTMUX_SOCKET" => nil, "LIBTMUX_SOCKET_PATH" => nil} - _, error, status = Open3.capture3(environment, EXECUTABLE, *selector, "-f", "/dev/null", - "new-session", "-d", "-s", session, "cat") + environment = { + "TMUX_TMPDIR" => directory, + "TMUX" => nil, + "TMUX_PANE" => nil, + "LIBTMUX_SOCKET" => nil, + "LIBTMUX_SOCKET_PATH" => nil + } + _, error, status = + Open3.capture3( + environment, + EXECUTABLE, + *selector, + "-f", + "/dev/null", + "new-session", + "-d", + "-s", + session, + "cat" + ) assert status.success?, "tmux could not start the #{session} server: #{error}" end end diff --git a/test/integration/fixture_test.rb b/test/integration/fixture_test.rb index 962b18b4..1585207d 100644 --- a/test/integration/fixture_test.rb +++ b/test/integration/fixture_test.rb @@ -7,16 +7,21 @@ class TmuxFixtureTest < Minitest::Test def test_explicit_executable_selects_both_owned_daemon_and_client - executable = ENV.fetch("LIBTMUX_TEST_TMUX") do - ENV.fetch("PATH").split(File::PATH_SEPARATOR).map { |part| File.join(part, "tmux") } - .find { |path| File.file?(path) && File.executable?(path) } - end + executable = + ENV.fetch("LIBTMUX_TEST_TMUX") do + ENV + .fetch("PATH") + .split(File::PATH_SEPARATOR) + .map { |part| File.join(part, "tmux") } + .find { |path| File.file?(path) && File.executable?(path) } + end launches = [] - trace = TracePoint.new(:call) do |event| - if event.defined_class == LibTmuxTest::TmuxFixture && event.method_id == :spawn_owned - launches << event.binding.local_variable_get(:arguments).first + trace = + TracePoint.new(:call) do |event| + if event.defined_class == LibTmuxTest::TmuxFixture && event.method_id == :spawn_owned + launches << event.binding.local_variable_get(:arguments).first + end end - end fixture = LibTmuxTest::TmuxFixture.new(executable: executable) trace.enable do fixture.start @@ -32,17 +37,24 @@ def test_explicit_executable_selects_both_owned_daemon_and_client def test_failed_observer_still_retires_its_real_child release = Queue.new - trace = TracePoint.new(:call) do |event| - if event.defined_class == LibTmux::Internal::ProcessWait && event.method_id == :observe - release.pop - raise IOError, "fixture observer failure" + trace = + TracePoint.new(:call) do |event| + if event.defined_class == LibTmux::Internal::ProcessWait && event.method_id == :observe + release.pop + raise IOError, "fixture observer failure" + end end - end fixture = LibTmuxTest::TmuxFixture.new fixture.start trace.enable - child = fixture.send(:spawn_owned, Gem.ruby, "--disable=rubyopt,gems", "-e", - 'trap("TERM") {}; STDOUT.write("ready\n"); STDOUT.flush; input, output = IO.pipe; input.read(1)') + child = + fixture.send( + :spawn_owned, + Gem.ruby, + "--disable=rubyopt,gems", + "-e", + 'trap("TERM") {}; STDOUT.write("ready\n"); STDOUT.flush; input, output = IO.pipe; input.read(1)' + ) fixture.instance_variable_get(:@clients)[child.last.pid] = child assert IO.select([child[1]], nil, nil, 0.5), "owned helper did not start" assert_equal "ready\n", child[1].gets @@ -124,17 +136,22 @@ def test_preserves_block_exception_and_reaps_owned_server directory = pid = nil failure = RuntimeError.new("fixture body failed") - assert_same failure, assert_raises(RuntimeError) { - LibTmuxTest::TmuxFixture.open do |fixture| - directory = File.dirname(fixture.socket_path) - pid = server_pid(fixture) - identity = LibTmux::Internal::ProcessExecutor.new.run(["ps", "-o", "ppid=", "-p", pid.to_s], timeout: 0.5) - assert identity.success? - parent = Integer(identity.text.strip, 10) - assert_equal Process.pid, parent, "fixture server must remain an owned child" - raise failure - end - } + assert_same failure, + assert_raises(RuntimeError) { + LibTmuxTest::TmuxFixture.open do |fixture| + directory = File.dirname(fixture.socket_path) + pid = server_pid(fixture) + identity = + LibTmux::Internal::ProcessExecutor.new.run( + ["ps", "-o", "ppid=", "-p", pid.to_s], + timeout: 0.5 + ) + assert identity.success? + parent = Integer(identity.text.strip, 10) + assert_equal Process.pid, parent, "fixture server must remain an owned child" + raise failure + end + } refute File.exist?(directory) assert_raises(Errno::ESRCH) { Process.kill(0, pid) } @@ -143,26 +160,28 @@ def test_preserves_block_exception_and_reaps_owned_server def test_cancellation_retires_a_dispatched_client_and_its_server started = Queue.new - worker = Thread.new do - Thread.current.report_on_exception = false - begin - LibTmuxTest::TmuxFixture.open do |fixture| - started << [fixture, server_pid(fixture)] - fixture.tmux("wait-for", "-S", "dispatched", ";", "wait-for", "unreleased") + worker = + Thread.new do + Thread.current.report_on_exception = false + begin + LibTmuxTest::TmuxFixture.open do |fixture| + started << [fixture, server_pid(fixture)] + fixture.tmux("wait-for", "-S", "dispatched", ";", "wait-for", "unreleased") + end + rescue Exception => error + started << error + raise end - rescue Exception => error - started << error - raise end - end startup = started.pop raise startup if startup.is_a?(Exception) fixture, pid = startup assert fixture.tmux("wait-for", "dispatched").last.success? - clients = fixture.instance_variable_get(:@clients_mutex).synchronize do - fixture.instance_variable_get(:@clients).keys - end + clients = + fixture + .instance_variable_get(:@clients_mutex) + .synchronize { fixture.instance_variable_get(:@clients).keys } assert_equal 1, clients.length, "expected one dispatched child client" worker.raise(Interrupt, "cancel fixture") assert_raises(Interrupt) { worker.join(0.5) } @@ -198,25 +217,37 @@ def test_cleanup_does_not_follow_a_replaced_socket_to_another_server def test_retirement_failure_does_not_skip_other_owned_resources fixture = nil resources = [] - error = assert_raises(LibTmuxTest::TmuxFixture::Error) do - LibTmuxTest::TmuxFixture.open do |owned| - fixture = owned - 2.times do |index| - client = owned.send(:spawn_owned, "tmux", - "-N", "-S", owned.socket_path, "wait-for", "-S", "client-#{index}", - ";", "wait-for", "unreleased") - client.first.close - resources << client - owned.instance_variable_get(:@clients)[client.last.pid] = client - assert owned.tmux("wait-for", "client-#{index}").last.success? - end - resources << owned.instance_variable_get(:@server) - owned.define_singleton_method(:retire) do |process| - super(process) - raise IOError, "private cleanup detail" if process.equal?(resources.first) + error = + assert_raises(LibTmuxTest::TmuxFixture::Error) do + LibTmuxTest::TmuxFixture.open do |owned| + fixture = owned + 2.times do |index| + client = + owned.send( + :spawn_owned, + "tmux", + "-N", + "-S", + owned.socket_path, + "wait-for", + "-S", + "client-#{index}", + ";", + "wait-for", + "unreleased" + ) + client.first.close + resources << client + owned.instance_variable_get(:@clients)[client.last.pid] = client + assert owned.tmux("wait-for", "client-#{index}").last.success? + end + resources << owned.instance_variable_get(:@server) + owned.define_singleton_method(:retire) do |process| + super(process) + raise IOError, "private cleanup detail" if process.equal?(resources.first) + end end end - end assert_equal 1, error.cleanup_errors.length assert_includes error.cleanup_errors.first, "IOError" @@ -237,16 +268,17 @@ def test_retirement_failure_does_not_skip_other_owned_resources def test_block_failure_survives_cleanup_failure_with_diagnostics fixture = nil failure = RuntimeError.new("original block failure") - error = assert_raises(RuntimeError) do - LibTmuxTest::TmuxFixture.open do |owned| - fixture = owned - owned.define_singleton_method(:retire) do |process| - super(process) - raise IOError, "retirement failed" + error = + assert_raises(RuntimeError) do + LibTmuxTest::TmuxFixture.open do |owned| + fixture = owned + owned.define_singleton_method(:retire) do |process| + super(process) + raise IOError, "retirement failed" + end + raise failure end - raise failure end - end assert_same failure, error assert_equal 1, error.fixture_cleanup_errors.length @@ -262,22 +294,23 @@ def test_repeated_interruption_during_cleanup_preserves_first_failure cleaning = Queue.new release = Queue.new failure = Interrupt.new("first cancellation") - worker = Thread.new do - Thread.current.report_on_exception = false - begin - LibTmuxTest::TmuxFixture.open do |owned| - ready << owned - owned.define_singleton_method(:retire) do |process| - cleaning << true - release.pop - super(process) + worker = + Thread.new do + Thread.current.report_on_exception = false + begin + LibTmuxTest::TmuxFixture.open do |owned| + ready << owned + owned.define_singleton_method(:retire) do |process| + cleaning << true + release.pop + super(process) + end + Queue.new.pop end - Queue.new.pop + rescue Exception => error + error end - rescue Exception => error - error end - end fixture = ready.pop(timeout: 0.5) assert fixture, "fixture did not reach its interruption barrier" worker.raise(failure) diff --git a/test/integration/group_test.rb b/test/integration/group_test.rb index 4e6c7695..f1fe2e7d 100644 --- a/test/integration/group_test.rb +++ b/test/integration/group_test.rb @@ -3,27 +3,32 @@ require_relative "../test_helper" require_relative "../support/tmux_fixture" require "libtmux" -require "libtmux/group" if File.exist?(File.expand_path("../../gems/libtmux/lib/libtmux/group.rb", __dir__)) +if File.exist?(File.expand_path("../../gems/libtmux/lib/libtmux/group.rb", __dir__)) + require "libtmux/group" +end class GroupTest < Minitest::Test def test_runtime_failure_keeps_earlier_effects_and_does_not_invent_step_statuses LibTmuxTest::TmuxFixture.open do |fixture| LibTmux::Server.open(socket_path: fixture.socket_path) do |server| - result = server.run_group([ - ["set-option", "-g", "@group-first", "literal;"], - ["select-pane", "-t", "%4294967294"], - ["set-option", "-g", "@group-last", "must-not-run"] - ]) + result = + server.run_group( + [ + %w[set-option -g @group-first literal;], + %w[select-pane -t %4294967294], + %w[set-option -g @group-last must-not-run] + ] + ) refute result.success? assert_equal :observed, result.delivery assert_equal 3, result.steps.size assert result.steps.frozen? assert result.steps.all? { |step| step.fetch(:outcome) == :unknown } - assert_equal "literal;\n", server.run(["show-options", "-g", "-v", "@group-first"]).text + assert_equal "literal;\n", server.run(%w[show-options -g -v @group-first]).text refute server.options(scope: :session).list.any? { |option| option.name == "@group-last" } assert_instance_of LibTmux::CommandResult, result.result refute_includes result.inspect, "literal" - success = server.run_group([["display-message", "-p", "a"], ["display-message", "-p", "b"]]) + success = server.run_group([%w[display-message -p a], %w[display-message -p b]]) assert success.success? assert_equal "a\nb\n", success.result.text assert success.steps.all? { |step| step.fetch(:outcome) == :unknown } @@ -34,10 +39,13 @@ def test_runtime_failure_keeps_earlier_effects_and_does_not_invent_step_statuses def test_group_validation_and_pre_cancel_refuse_before_any_effect LibTmuxTest::TmuxFixture.open do |fixture| LibTmux::Server.open(socket_path: fixture.socket_path) do |server| - command = ["set-option", "-g", "@group-never", "no"] - [[], [command, []], [command, ["display-message", "\0"]], [["-S", "unrelated"]]].each do |commands| - assert_raises(ArgumentError) { server.run_group(commands) } - end + command = %w[set-option -g @group-never no] + [ + [], + [command, []], + [command, ["display-message", "\0"]], + [%w[-S unrelated]] + ].each { |commands| assert_raises(ArgumentError) { server.run_group(commands) } } assert_raises(LibTmux::CapacityError) { server.run_group(Array.new(129, command)) } token = LibTmux::Internal::Cancellation.new begin @@ -56,16 +64,20 @@ def test_cancellation_retires_the_client_without_undoing_observed_earlier_effect LibTmuxTest::TmuxFixture.open do |fixture| LibTmux::Server.open(socket_path: fixture.socket_path) do |server| token = LibTmux::Internal::Cancellation.new - worker = Thread.new do - server.run_group([ - ["set-option", "-g", "@group-effect", "already-applied"], - ["wait-for", "-S", "group-ready"], - ["wait-for", "group-held"], - ["set-option", "-g", "@group-later", "uncertain"] - ], cancel: token) - rescue LibTmux::Cancelled => error - error - end + worker = + Thread.new do + server.run_group( + [ + %w[set-option -g @group-effect already-applied], + %w[wait-for -S group-ready], + %w[wait-for group-held], + %w[set-option -g @group-later uncertain] + ], + cancel: token + ) + rescue LibTmux::Cancelled => error + error + end begin assert fixture.tmux("wait-for", "group-ready").last.success? token.cancel @@ -74,7 +86,7 @@ def test_cancellation_retires_the_client_without_undoing_observed_earlier_effect assert_instance_of LibTmux::Cancelled, failure assert_equal :possibly_sent, failure.delivery assert_raises(Errno::ECHILD) { Process.waitpid(failure.pid, Process::WNOHANG) } - assert_equal "already-applied\n", server.run(["show-options", "-g", "-v", "@group-effect"]).text + assert_equal "already-applied\n", server.run(%w[show-options -g -v @group-effect]).text ensure token.cancel fixture.tmux("wait-for", "-S", "group-held") diff --git a/test/integration/identity_test.rb b/test/integration/identity_test.rb index 69bae905..154aae5e 100644 --- a/test/integration/identity_test.rb +++ b/test/integration/identity_test.rb @@ -12,24 +12,26 @@ def test_repeated_constructor_cancellation_preserves_the_first_failure first = Interrupt.new("first binding cancellation") later = Interrupt.new("later cleanup cancellation") directory = nil - interrupted = Class.new(LibTmux::Internal::SocketIdentity) do - define_method(:make_route) do |source| - super(source) - directory = @directory - ready << true - Thread.handle_interrupt(Exception => :immediate) { release.pop } + interrupted = + Class.new(LibTmux::Internal::SocketIdentity) do + define_method(:make_route) do |source| + super(source) + directory = @directory + ready << true + Thread.handle_interrupt(Exception => :immediate) { release.pop } + end + define_method(:remove_route) do + cleanup_ready << true + release.pop + super() + end end - define_method(:remove_route) do - cleanup_ready << true - release.pop - super() + worker = + Thread.new do + interrupted.new(LibTmux::Endpoint.new(socket_path: fixture.socket_path)) + rescue Exception => error + error end - end - worker = Thread.new do - interrupted.new(LibTmux::Endpoint.new(socket_path: fixture.socket_path)) - rescue Exception => error - error - end assert ready.pop(timeout: 0.5), "binding did not reach its cancellation barrier" worker.raise(first) assert cleanup_ready.pop(timeout: 0.5), "binding did not start cleanup" @@ -42,28 +44,34 @@ def test_repeated_constructor_cancellation_preserves_the_first_failure release << true if release worker&.kill if worker&.alive? worker&.join(0.5) - File.unlink(File.join(directory, "socket")) if directory && File.socket?(File.join(directory, "socket")) + if directory && File.socket?(File.join(directory, "socket")) + File.unlink(File.join(directory, "socket")) + end Dir.rmdir(directory) if directory && Dir.exist?(directory) end end def test_a_fork_cannot_use_or_retire_the_parent_binding LibTmuxTest::TmuxFixture.open do |fixture| - pin = LibTmux::Internal::SocketIdentity.new(LibTmux::Endpoint.new(socket_path: fixture.socket_path)) + pin = + LibTmux::Internal::SocketIdentity.new( + LibTmux::Endpoint.new(socket_path: fixture.socket_path) + ) reader, writer = IO.pipe - child = fork do - reader.close - begin - pin.command_prefix - writer.write("bad") - rescue LibTmux::ClosedError - pin.close - writer.write("ok") - ensure - writer.close + child = + fork do + reader.close + begin + pin.command_prefix + writer.write("bad") + rescue LibTmux::ClosedError + pin.close + writer.write("ok") + ensure + writer.close + end + exit! 0 end - exit! 0 - end writer.close assert IO.select([reader], nil, nil, 0.5), "forked binding did not settle" assert_equal "ok", reader.read(2) @@ -92,9 +100,10 @@ def test_symlinked_source_binds_its_socket_but_a_non_socket_source_is_refused File.unlink(selector) File.write(selector, "not a socket") assert route(pin, "has-session", "-t", "fixture").last.success? - error = assert_raises(LibTmux::TargetNotFoundError) do - LibTmux::Internal::SocketIdentity.new(LibTmux::Endpoint.new(socket_path: selector)) - end + error = + assert_raises(LibTmux::TargetNotFoundError) do + LibTmux::Internal::SocketIdentity.new(LibTmux::Endpoint.new(socket_path: selector)) + end refute_includes error.message, selector ensure pin.close @@ -106,17 +115,22 @@ def test_symlinked_source_binds_its_socket_but_a_non_socket_source_is_refused def test_constructor_interruption_removes_the_owned_route LibTmuxTest::TmuxFixture.open do |fixture| directory = nil - interrupted = Class.new(LibTmux::Internal::SocketIdentity) do - define_method(:make_route) do |source| - super(source) - directory = @directory - raise Interrupt, "cancel binding" + interrupted = + Class.new(LibTmux::Internal::SocketIdentity) do + define_method(:make_route) do |source| + super(source) + directory = @directory + raise Interrupt, "cancel binding" + end end + assert_raises(Interrupt) do + interrupted.new(LibTmux::Endpoint.new(socket_path: fixture.socket_path)) end - assert_raises(Interrupt) { interrupted.new(LibTmux::Endpoint.new(socket_path: fixture.socket_path)) } refute Dir.exist?(directory), "interrupted binding leaked its private directory" ensure - File.unlink(File.join(directory, "socket")) if directory && File.socket?(File.join(directory, "socket")) + if directory && File.socket?(File.join(directory, "socket")) + File.unlink(File.join(directory, "socket")) + end Dir.rmdir(directory) if directory && Dir.exist?(directory) end end @@ -125,30 +139,36 @@ def test_constructor_cleanup_failure_preserves_the_original_error LibTmuxTest::TmuxFixture.open do |fixture| directory = nil failure = LibTmux::ProtocolError.new("original binding failure") - failing = Class.new(LibTmux::Internal::SocketIdentity) do - define_method(:make_route) do |source| - super(source) - directory = @directory - File.write(File.join(directory, "occupied"), "owned fixture") - raise failure + failing = + Class.new(LibTmux::Internal::SocketIdentity) do + define_method(:make_route) do |source| + super(source) + directory = @directory + File.write(File.join(directory, "occupied"), "owned fixture") + raise failure + end + end + observed = + assert_raises(LibTmux::ProtocolError) do + failing.new(LibTmux::Endpoint.new(socket_path: fixture.socket_path)) end - end - observed = assert_raises(LibTmux::ProtocolError) do - failing.new(LibTmux::Endpoint.new(socket_path: fixture.socket_path)) - end assert_same failure, observed assert_equal 1, observed.cleanup_errors.length refute_includes observed.cleanup_errors.first, directory refute File.exist?(File.join(directory, "socket")) ensure - File.unlink(File.join(directory, "occupied")) if directory && File.exist?(File.join(directory, "occupied")) - File.unlink(File.join(directory, "socket")) if directory && File.socket?(File.join(directory, "socket")) + if directory && File.exist?(File.join(directory, "occupied")) + File.unlink(File.join(directory, "occupied")) + end + if directory && File.socket?(File.join(directory, "socket")) + File.unlink(File.join(directory, "socket")) + end Dir.rmdir(directory) if directory && Dir.exist?(directory) end end def route(pin, *args) - Open3.capture3({"TMUX" => nil, "TMUX_PANE" => nil}, *pin.command_prefix, *args) + Open3.capture3({ "TMUX" => nil, "TMUX_PANE" => nil }, *pin.command_prefix, *args) end def test_selector_replacement_cannot_redirect_a_bound_command @@ -205,7 +225,8 @@ def test_a_dead_pinned_socket_cannot_start_or_reach_a_replacement_server original_path = nil LibTmuxTest::TmuxFixture.open do |original| original_path = original.socket_path - pin = LibTmux::Internal::SocketIdentity.new(LibTmux::Endpoint.new(socket_path: original_path)) + pin = + LibTmux::Internal::SocketIdentity.new(LibTmux::Endpoint.new(socket_path: original_path)) # Keep the route outside fixture cleanup by selecting a same-filesystem directory. refute_equal File.dirname(original_path), File.dirname(pin.command_prefix.last) end diff --git a/test/integration/mcp_application_test.rb b/test/integration/mcp_application_test.rb index 27fcb57a..745f9864 100644 --- a/test/integration/mcp_application_test.rb +++ b/test/integration/mcp_application_test.rb @@ -3,7 +3,9 @@ require_relative "../test_helper" require_relative "../support/tmux_fixture" require "libtmux/mcp" -require "libtmux/mcp/application" if File.exist?(File.expand_path("../../gems/libtmux-mcp/lib/libtmux/mcp/application.rb", __dir__)) +if File.exist?(File.expand_path("../../gems/libtmux-mcp/lib/libtmux/mcp/application.rb", __dir__)) + require "libtmux/mcp/application" +end class McpApplicationTest < Minitest::Test def test_discovery_and_snapshot_pages_share_the_captured_query_and_enforce_policy @@ -17,28 +19,41 @@ def test_discovery_and_snapshot_pages_share_the_captured_query_and_enforce_polic capabilities = app.call("tmux_capabilities").structured_content assert capabilities.fetch("ok") assert_equal "test", capabilities.fetch("data").fetch("endpoint") - assert_equal %w[tmux_capabilities tmux_snapshot], capabilities.fetch("data").fetch("enabled_tools") - assert_equal LibTmux::FilterExpr.json_schema, capabilities.fetch("data").fetch("criteria_schema") + assert_equal %w[tmux_capabilities tmux_snapshot], + capabilities.fetch("data").fetch("enabled_tools") + assert_equal LibTmux::FilterExpr.json_schema, + capabilities.fetch("data").fetch("criteria_schema") report = scope.server.capabilities optional = capabilities.fetch("data").fetch("optional_features") assert_equal report.features.map(&:id), optional.map { |feature| feature.fetch("id") } optional.each do |feature| assert_equal report.supports?(feature.fetch("id")), feature.fetch("available") end - assert_equal report.to_h.fetch("workarounds"), capabilities.fetch("data").fetch("workarounds") + assert_equal report.to_h.fetch("workarounds"), + capabilities.fetch("data").fetch("workarounds") assert app.tools.first.call.structured_content.fetch("ok") - first = app.call("tmux_snapshot", {"entity" => "pane", "limit" => 1}).structured_content + first = + app.call("tmux_snapshot", { "entity" => "pane", "limit" => 1 }).structured_content assert first.fetch("ok") data = first.fetch("data") assert data.fetch("truncated") assert_equal 1, data.fetch("items").length session.new_window(name: "after-capture", command: ["cat"]) - second = app.call("tmux_snapshot", {"cursor" => data.fetch("next_cursor")}).structured_content.fetch("data") + second = + app + .call("tmux_snapshot", { "cursor" => data.fetch("next_cursor") }) + .structured_content + .fetch("data") assert_equal data.fetch("capture_id"), second.fetch("capture_id") refute second.fetch("truncated") assert_equal 1, second.fetch("items").length - assert_equal 2, [*data.fetch("items"), *second.fetch("items")].map { |item| item.fetch("ref").fetch("id") }.uniq.length - denied = app.call("tmux_close", {"anything" => "private"}) + assert_equal 2, + [*data.fetch("items"), *second.fetch("items")].map { |item| + item.fetch("ref").fetch("id") + } + .uniq + .length + denied = app.call("tmux_close", { "anything" => "private" }) assert denied.error? assert_equal "policy_denied", denied.structured_content.fetch("error").fetch("code") refute_includes JSON.generate(denied.to_h), "private" @@ -58,28 +73,81 @@ def test_invalid_criteria_foreign_and_expired_cursors_never_refresh_implicitly server.list_sessions.first.new_window(name: "second", command: ["cat"]) Async do |task| LibTmux::Async.open(server: server, parent: task) do |scope| - app = LibTmux::MCP::Application.new(server: scope.server, endpoint_name: "test", max_captures: 1) - first = app.call("tmux_snapshot", {"entity" => "pane", "limit" => 1}).structured_content.fetch("data") - app.call("tmux_snapshot", {"entity" => "session"}) - expired = app.call("tmux_snapshot", {"cursor" => first.fetch("next_cursor")}) + app = + LibTmux::MCP::Application.new( + server: scope.server, + endpoint_name: "test", + max_captures: 1 + ) + first = + app + .call("tmux_snapshot", { "entity" => "pane", "limit" => 1 }) + .structured_content + .fetch("data") + app.call("tmux_snapshot", { "entity" => "session" }) + expired = app.call("tmux_snapshot", { "cursor" => first.fetch("next_cursor") }) assert expired.error? assert_equal "stale_cursor", expired.structured_content.fetch("error").fetch("code") foreign = LibTmux::MCP::Application.new(server: scope.server, endpoint_name: "other") - assert foreign.call("tmux_snapshot", {"cursor" => first.fetch("next_cursor")}).error? + assert foreign.call("tmux_snapshot", { "cursor" => first.fetch("next_cursor") }).error? original = scope.server.method(:snapshot) - scope.server.define_singleton_method(:snapshot) { |**options| flunk "invalid filter performed tmux I/O" } + scope + .server + .define_singleton_method(:snapshot) do |**options| + flunk "invalid filter performed tmux I/O" + end begin - invalid = app.call("tmux_snapshot", {"entity" => "pane", "criteria" => - {"profile" => "foreign", "version" => 1, "entity" => "pane", "where" => {}}}) + invalid = + app.call( + "tmux_snapshot", + { + "entity" => "pane", + "criteria" => { + "profile" => "foreign", + "version" => 1, + "entity" => "pane", + "where" => { + } + } + } + ) assert invalid.error? sdk = app.sdk_server - sdk.handle({jsonrpc: "2.0", id: 1, method: "initialize", params: { - protocolVersion: "2025-11-25", capabilities: {}, clientInfo: {name: "test", version: "1"}}}) - response = sdk.handle({jsonrpc: "2.0", id: 2, method: "tools/call", params: { - name: "tmux_snapshot", arguments: {entity: "pane", PRIVATE_KEY_SENTINEL: "secret-value"}}}) + sdk.handle( + { + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { + protocolVersion: "2025-11-25", + capabilities: { + }, + clientInfo: { + name: "test", + version: "1" + } + } + } + ) + response = + sdk.handle( + { + jsonrpc: "2.0", + id: 2, + method: "tools/call", + params: { + name: "tmux_snapshot", + arguments: { + entity: "pane", + PRIVATE_KEY_SENTINEL: "secret-value" + } + } + } + ) normalized = JSON.parse(JSON.generate(response)) refute_includes JSON.generate(normalized), "PRIVATE_KEY_SENTINEL" - assert_equal "invalid_input", normalized.dig("result", "structuredContent", "error", "code") + assert_equal "invalid_input", + normalized.dig("result", "structuredContent", "error", "code") ensure scope.server.define_singleton_method(:snapshot, original) end @@ -95,16 +163,37 @@ def test_an_oversized_first_page_does_not_evict_a_usable_capture server.list_sessions.first.new_window(name: "second", command: ["cat"]) Async do |task| LibTmux::Async.open(server: server, parent: task) do |scope| - app = LibTmux::MCP::Application.new(server: scope.server, endpoint_name: "test", - max_captures: 1, max_response_bytes: 2048) - first = app.call("tmux_snapshot", {"entity" => "pane", "limit" => 1}).structured_content.fetch("data") - assert scope.server.run(["select-pane", "-t", first.fetch("items").first.fetch("ref").fetch("id"), "-T", "x" * 6000]).success? - oversized = app.call("tmux_snapshot", {"entity" => "pane"}) + app = + LibTmux::MCP::Application.new( + server: scope.server, + endpoint_name: "test", + max_captures: 1, + max_response_bytes: 2048 + ) + first = + app + .call("tmux_snapshot", { "entity" => "pane", "limit" => 1 }) + .structured_content + .fetch("data") + assert scope + .server + .run( + [ + "select-pane", + "-t", + first.fetch("items").first.fetch("ref").fetch("id"), + "-T", + "x" * 6000 + ] + ) + .success? + oversized = app.call("tmux_snapshot", { "entity" => "pane" }) assert oversized.error? assert_equal "capacity", oversized.structured_content.fetch("error").fetch("code") - next_page = app.call("tmux_snapshot", {"cursor" => first.fetch("next_cursor")}) + next_page = app.call("tmux_snapshot", { "cursor" => first.fetch("next_cursor") }) refute next_page.error? - assert_equal first.fetch("capture_id"), next_page.structured_content.fetch("data").fetch("capture_id") + assert_equal first.fetch("capture_id"), + next_page.structured_content.fetch("data").fetch("capture_id") end end.wait end diff --git a/test/integration/mcp_capture_test.rb b/test/integration/mcp_capture_test.rb index d16915c6..1b610210 100644 --- a/test/integration/mcp_capture_test.rb +++ b/test/integration/mcp_capture_test.rb @@ -35,14 +35,28 @@ def test_sdk_capture_retains_exact_bounded_states_and_rejects_foreign_or_respawn assert_equal first.fetch("process_generation"), delta.fetch("process_generation") other = target.merge("generation" => "another-binding") - assert_equal "stale_cursor", invoke(sdk, target: other, cursor: delta.fetch("next_cursor")).dig("error", "code") - assert_equal "invalid_input", invoke(sdk, target: target, cursor: delta.fetch("next_cursor"), max_bytes: 10).dig("error", "code") + assert_equal "stale_cursor", + invoke(sdk, target: other, cursor: delta.fetch("next_cursor")).dig( + "error", + "code" + ) + assert_equal "invalid_input", + invoke( + sdk, + target: target, + cursor: delta.fetch("next_cursor"), + max_bytes: 10 + ).dig("error", "code") pane.respawn(command: ["cat"], kill: true) - assert_equal "stale_cursor", invoke(sdk, target: target, cursor: delta.fetch("next_cursor")).dig("error", "code") + assert_equal "stale_cursor", + invoke(sdk, target: target, cursor: delta.fetch("next_cursor")).dig( + "error", + "code" + ) app.close app.close assert_equal "closed", invoke(sdk, target: target).dig("error", "code") - assert source.run(["has-session", "-t", "fixture"]).success? + assert source.run(%w[has-session -t fixture]).success? end end @@ -57,7 +71,8 @@ def test_screen_capture_refuses_after_hooks_and_preserves_split_utf8_bytes full = invoke(sdk, target: target, max_lines: 1).fetch("data") limited = invoke(sdk, target: target, max_lines: 1, max_bytes: 4).fetch("data") assert_equal "base64", limited.fetch("encoding") - assert_equal full.fetch("rows").join.b.byteslice(-4, 4), limited.fetch("rows").map { |row| row.unpack1("m0") }.join.b + assert_equal full.fetch("rows").join.b.byteslice(-4, 4), + limited.fetch("rows").map { |row| row.unpack1("m0") }.join.b assert limited.fetch("truncated") ["display-message -p not-screen", "wait-for capture-must-not-wait"].each do |command| session.hooks.set("after-capture-pane", command: command, index: 17) @@ -66,7 +81,11 @@ def test_screen_capture_refuses_after_hooks_and_preserves_split_utf8_bytes session.hooks.unset("after-capture-pane", index: 17) end session.hooks.unset("after-capture-pane") - scope.server.hooks.set("after-capture-pane", command: "display-message -p inherited-not-screen", index: 503) + scope.server.hooks.set( + "after-capture-pane", + command: "display-message -p inherited-not-screen", + index: 503 + ) refused = invoke(sdk, target: target) assert_equal "unsupported", refused.dig("error", "code"), refused.inspect @@ -80,7 +99,14 @@ def test_screen_capture_refuses_after_hooks_and_preserves_split_utf8_bytes def test_capture_refuses_a_session_link_removed_before_dispatch with_application do |app, sdk, scope, source| release = LibTmux::Internal::TmuxVersion.parse(source.snapshot.server_info.fetch(:version)) - phases = LibTmux::MCP.const_get(:Observation).preflight_hooks?(release) ? [:preflight, :capture] : [:capture] + phases = + ( + if LibTmux::MCP.const_get(:Observation).preflight_hooks?(release) + %i[preflight capture] + else + [:capture] + end + ) phases.each do |phase| first = scope.server.new_session(name: "context-#{phase}", command: ["cat"]) window = first.list_windows.first @@ -89,18 +115,27 @@ def test_capture_refuses_a_session_link_removed_before_dispatch second = scope.server.new_session(name: "other-context-#{phase}", command: ["cat"]) second.link_window(window.ref, index: 4) armed = true - scope.server.singleton_class.prepend(Module.new do - define_method(:execute_typed) do |argv, **options| - dispatch = phase == :preflight ? argv.last == 'after-capture-pane' : argv.include?('#{==:#{after-capture-pane},}') - if armed && dispatch - armed = false - run(["unlink-window", "-k", "-t", "#{first.id}:#{link.index}"]).tap do |result| - raise "fixture failed to remove capture context" unless result.success? + scope.server.singleton_class.prepend( + Module.new do + define_method(:execute_typed) do |argv, **options| + dispatch = + ( + if phase == :preflight + argv.last == "after-capture-pane" + else + argv.include?('#{==:#{after-capture-pane},}') + end + ) + if armed && dispatch + armed = false + run(["unlink-window", "-k", "-t", "#{first.id}:#{link.index}"]).tap do |result| + raise "fixture failed to remove capture context" unless result.success? + end end + super(argv, **options) end - super(argv, **options) end - end) + ) result = invoke(sdk, target: wire_ref(pane.ref)) assert_equal "stale_target", result.dig("error", "code"), result.inspect refute armed, "fixture missed the capture dispatch" @@ -113,11 +148,19 @@ def test_capture_refuses_a_session_link_removed_before_dispatch def with_application(**options) LibTmuxTest::TmuxFixture.open do |fixture| - LibTmux::Server.open(socket_path: fixture.socket_path, executable: fixture.executable) do |source| + LibTmux::Server.open( + socket_path: fixture.socket_path, + executable: fixture.executable + ) do |source| Async do |task| LibTmux::Async.open(server: source, parent: task) do |scope| - app = LibTmux::MCP::Application.new(server: scope.server, endpoint_name: "test", - enabled_tools: %w[tmux_capabilities tmux_snapshot tmux_capture tmux_wait], **options) + app = + LibTmux::MCP::Application.new( + server: scope.server, + endpoint_name: "test", + enabled_tools: %w[tmux_capabilities tmux_snapshot tmux_capture tmux_wait], + **options + ) begin yield app, app.sdk_server, scope, source ensure @@ -130,12 +173,23 @@ def with_application(**options) end def invoke(sdk, **arguments) - response = sdk.handle({jsonrpc: "2.0", id: 1, method: "tools/call", params: {name: "tmux_capture", arguments: arguments}}) + response = + sdk.handle( + { + jsonrpc: "2.0", + id: 1, + method: "tools/call", + params: { + name: "tmux_capture", + arguments: arguments + } + } + ) JSON.parse(JSON.generate(response)).fetch("result").fetch("structuredContent") end def wire_ref(ref) - {"generation" => ref.binding_key, "kind" => ref.kind.to_s, "id" => ref.id} + { "generation" => ref.binding_key, "kind" => ref.kind.to_s, "id" => ref.id } end # Control events order the wait on tmux 3.7 and newer; older daemons poll the @@ -145,26 +199,30 @@ def with_output(scope, pane, session: scope.server.list_sessions.first, expected yield deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 2 until pane.capture.stdout.include?(expected.b) - flunk "#{expected.inspect} did not reach the pane" if Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline + if Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline + flunk "#{expected.inspect} did not reach the pane" + end sleep 0.01 end return end - scope.server.open_control(session: session.ref) do |control| - events = control.subscribe(pane_id: pane.id) - control.exchange("display-message -p ready", timeout: 0.5) - yield - received = +"".b - deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 0.5 - loop do - event = events.next(timeout: deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)) - next unless event.kind == :output + scope + .server + .open_control(session: session.ref) do |control| + events = control.subscribe(pane_id: pane.id) + control.exchange("display-message -p ready", timeout: 0.5) + yield + received = +"".b + deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 0.5 + loop do + event = events.next(timeout: deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)) + next unless event.kind == :output - received << event.data - break unless expected && !received.include?(expected.b) + received << event.data + break unless expected && !received.include?(expected.b) + end + ensure + events&.close end - ensure - events&.close - end end end diff --git a/test/integration/mcp_cli_test.rb b/test/integration/mcp_cli_test.rb index d9a1d5e4..9865521a 100644 --- a/test/integration/mcp_cli_test.rb +++ b/test/integration/mcp_cli_test.rb @@ -44,33 +44,65 @@ def test_silent_initialize_names_the_stage_that_expired def test_explicit_enrollment_file_serves_protocol_and_retires_pending_accept_on_eof LibTmuxTest::TmuxFixture.open do |fixture| - LibTmux::Server.open(socket_path: fixture.socket_path, executable: fixture.executable) do |server| + LibTmux::Server.open( + socket_path: fixture.socket_path, + executable: fixture.executable + ) do |server| pane = server.list_panes.first setup = File.join(File.dirname(fixture.socket_path), "enroll shell's setup.zsh") reader, input = IO.pipe output, writer = IO.pipe errors = StringIO.new publications = [] - trace = TracePoint.new(:c_call) do |event| - if event.method_id == :write && event.self.is_a?(File) && File.dirname(event.self.path) == File.dirname(setup) - publications << File.exist?(setup) + trace = + TracePoint.new(:c_call) do |event| + if event.method_id == :write && event.self.is_a?(File) && + File.dirname(event.self.path) == File.dirname(setup) + publications << File.exist?(setup) + end end - end trace.enable - worker = Thread.new do - LibTmux::MCP::CLI.run(["--socket", fixture.socket_path, - "--tmux", fixture.executable, "--enable-tool", "tmux_run", - "--enroll-pane", "#{pane.id}=#{setup}"], input: reader, out: writer, err: errors) - ensure - writer.close - end + worker = + Thread.new do + LibTmux::MCP::CLI.run( + [ + "--socket", + fixture.socket_path, + "--tmux", + fixture.executable, + "--enable-tool", + "tmux_run", + "--enroll-pane", + "#{pane.id}=#{setup}" + ], + input: reader, + out: writer, + err: errors + ) + ensure + writer.close + end begin - send_frame(input, id: 1, method: "initialize", params: {protocolVersion: "2025-11-25", - capabilities: {}, clientInfo: {name: "test", version: "1"}}) + send_frame( + input, + id: 1, + method: "initialize", + params: { + protocolVersion: "2025-11-25", + capabilities: { + }, + clientInfo: { + name: "test", + version: "1" + } + } + ) initialized = frame(output, "initialize") trace.disable assert_equal "2025-11-25", initialized.dig("result", "protocolVersion") - assert_equal [false], publications, "setup was visible before its complete source command was written" + assert_equal [false], + publications, + "setup was visible before its complete source command was written" assert_equal 0o600, File.stat(setup).mode & 0o777 source = File.read(setup) assert_equal 1, source.lines.length @@ -104,28 +136,58 @@ def test_cli_serves_real_protocol_and_eof_preserves_the_borrowed_daemon output, writer = IO.pipe errors = StringIO.new application_closes = [] - trace = TracePoint.new(:call) do |event| - if event.defined_class == LibTmux::MCP::Application && event.method_id == :close - application_closes << Fiber.scheduler + trace = + TracePoint.new(:call) do |event| + if event.defined_class == LibTmux::MCP::Application && event.method_id == :close + application_closes << Fiber.scheduler + end + end + worker = + Thread.new do + LibTmux::MCP::CLI.run( + ["--socket", fixture.socket_path, "--endpoint", "test"], + input: reader, + out: writer, + err: errors + ) end - end - worker = Thread.new do - LibTmux::MCP::CLI.run(["--socket", fixture.socket_path, "--endpoint", "test"], - input: reader, out: writer, err: errors) - end begin - send_frame(input, id: 1, method: "initialize", params: {protocolVersion: "2025-11-25", - capabilities: {}, clientInfo: {name: "test", version: "1"}}) + send_frame( + input, + id: 1, + method: "initialize", + params: { + protocolVersion: "2025-11-25", + capabilities: { + }, + clientInfo: { + name: "test", + version: "1" + } + } + ) assert_equal "2025-11-25", frame(output, "initialize").dig("result", "protocolVersion") send_frame(input, method: "notifications/initialized") send_frame(input, id: 2, method: "tools/list") tools = frame(output, "tools/list").fetch("result").fetch("tools") assert_equal %w[tmux_capabilities tmux_snapshot], tools.map { |tool| tool.fetch("name") } tools.each do |tool| - assert_equal({"toolset" => "inspect", "processReach" => "none", "tmuxEffects" => ["observe"]}, - tool.dig("_meta", "com.git-pull.libtmux-mcp/capability"), "#{tool.fetch("name")} capability on the wire") + assert_equal( + { "toolset" => "inspect", "processReach" => "none", "tmuxEffects" => ["observe"] }, + tool.dig("_meta", "com.git-pull.libtmux-mcp/capability"), + "#{tool.fetch("name")} capability on the wire" + ) end - send_frame(input, id: 3, method: "tools/call", params: {name: "tmux_capabilities", arguments: {}}) + send_frame( + input, + id: 3, + method: "tools/call", + params: { + name: "tmux_capabilities", + arguments: { + } + } + ) result = frame(output, "tmux_capabilities").dig("result", "structuredContent") assert result.fetch("ok") assert_equal "test", result.fetch("data").fetch("endpoint") @@ -154,16 +216,47 @@ def test_cli_without_a_socket_flag_serves_the_server_the_environment_names output, writer = IO.pipe errors = StringIO.new # An unnamed socket would land in the fixture's directory, where no server runs. - environment = {"LIBTMUX_SOCKET_PATH" => fixture.socket_path, "TMUX_TMPDIR" => File.dirname(fixture.socket_path)} - worker = Thread.new do - LibTmux::MCP::CLI.run(["--endpoint", "test"], input: reader, out: writer, err: errors, environment: environment) - end + environment = { + "LIBTMUX_SOCKET_PATH" => fixture.socket_path, + "TMUX_TMPDIR" => File.dirname(fixture.socket_path) + } + worker = + Thread.new do + LibTmux::MCP::CLI.run( + %w[--endpoint test], + input: reader, + out: writer, + err: errors, + environment: environment + ) + end begin - send_frame(input, id: 1, method: "initialize", params: {protocolVersion: "2025-11-25", - capabilities: {}, clientInfo: {name: "test", version: "1"}}) + send_frame( + input, + id: 1, + method: "initialize", + params: { + protocolVersion: "2025-11-25", + capabilities: { + }, + clientInfo: { + name: "test", + version: "1" + } + } + ) assert_equal "2025-11-25", frame(output, "initialize").dig("result", "protocolVersion") send_frame(input, method: "notifications/initialized") - send_frame(input, id: 2, method: "tools/call", params: {name: "tmux_capabilities", arguments: {}}) + send_frame( + input, + id: 2, + method: "tools/call", + params: { + name: "tmux_capabilities", + arguments: { + } + } + ) result = frame(output, "tmux_capabilities").dig("result", "structuredContent") assert result.fetch("ok"), result.inspect assert_equal "test", result.fetch("data").fetch("endpoint") @@ -188,10 +281,21 @@ def test_cli_without_a_socket_flag_or_server_refuses_to_start_one output, writer = IO.pipe errors = StringIO.new begin - status = LibTmux::MCP::CLI.run([], input: reader, out: writer, err: errors, environment: {"TMUX_TMPDIR" => directory}) + status = + LibTmux::MCP::CLI.run( + [], + input: reader, + out: writer, + err: errors, + environment: { + "TMUX_TMPDIR" => directory + } + ) assert_equal 1, status assert_includes errors.string, "MCP execution failed" - assert_empty Dir.glob(File.join(directory, "**", "*"), File::FNM_DOTMATCH).select { |path| File.socket?(path) } + assert_empty Dir + .glob(File.join(directory, "**", "*"), File::FNM_DOTMATCH) + .select { |path| File.socket?(path) } ensure [reader, input, output, writer].each { |io| io.close unless io.closed? } end @@ -200,7 +304,10 @@ def test_cli_without_a_socket_flag_or_server_refuses_to_start_one def test_existing_setup_file_or_symlink_is_preserved_when_enrollment_startup_fails LibTmuxTest::TmuxFixture.open do |fixture| - LibTmux::Server.open(socket_path: fixture.socket_path, executable: fixture.executable) do |server| + LibTmux::Server.open( + socket_path: fixture.socket_path, + executable: fixture.executable + ) do |server| pane = server.list_panes.first other = pane.split(direction: :horizontal, command: ["cat"]) provisional = File.join(File.dirname(fixture.socket_path), "provisional-setup") @@ -212,10 +319,24 @@ def test_existing_setup_file_or_symlink_is_preserved_when_enrollment_startup_fai reader, input = IO.pipe output, writer = IO.pipe errors = StringIO.new - status = LibTmux::MCP::CLI.run(["--socket", fixture.socket_path, "--tmux", fixture.executable, - "--enable-tool", "tmux_run", "--enroll-pane", "#{pane.id}=#{provisional}", - "--enroll-pane", "#{other.id}=#{path}"], - input: reader, out: writer, err: errors) + status = + LibTmux::MCP::CLI.run( + [ + "--socket", + fixture.socket_path, + "--tmux", + fixture.executable, + "--enable-tool", + "tmux_run", + "--enroll-pane", + "#{pane.id}=#{provisional}", + "--enroll-pane", + "#{other.id}=#{path}" + ], + input: reader, + out: writer, + err: errors + ) assert_equal 1, status assert_equal "preserve this file\n", File.read(original) assert File.symlink?(link) @@ -249,54 +370,142 @@ def test_explicitly_sourced_cli_setup_runs_a_script_through_the_protocol test_ready() { print -r -- ready >&$test_control } zle -N zle-line-init test_ready ZSH - LibTmux::Server.open(socket_path: fixture.socket_path, executable: fixture.executable) do |server| - pane = server.new_session(name: "cli-shell", - command: ["/usr/bin/env", "ZDOTDIR=#{directory}", "/bin/zsh", "-d", "-i"]).list_panes.first + LibTmux::Server.open( + socket_path: fixture.socket_path, + executable: fixture.executable + ) do |server| + pane = + server + .new_session( + name: "cli-shell", + command: ["/usr/bin/env", "ZDOTDIR=#{directory}", "/bin/zsh", "-d", "-i"] + ) + .list_panes + .first assert listener.wait_readable(Example::MCP_STARTUP_TIMEOUT), "owned shell did not connect" channel = listener.accept - assert_equal "initializing", line(channel, "owned shell initialization", timeout: Example::MCP_STARTUP_TIMEOUT) + assert_equal "initializing", + line( + channel, + "owned shell initialization", + timeout: Example::MCP_STARTUP_TIMEOUT + ) reader, input = IO.pipe output, writer = IO.pipe errors = StringIO.new - worker = Thread.new do - LibTmux::MCP::CLI.run(["--socket", fixture.socket_path, "--tmux", fixture.executable, - "--enable-tool", "tmux_run", "--enroll-pane", "#{pane.id}=#{setup}"], - input: reader, out: writer, err: errors) - ensure - writer.close - end + worker = + Thread.new do + LibTmux::MCP::CLI.run( + [ + "--socket", + fixture.socket_path, + "--tmux", + fixture.executable, + "--enable-tool", + "tmux_run", + "--enroll-pane", + "#{pane.id}=#{setup}" + ], + input: reader, + out: writer, + err: errors + ) + ensure + writer.close + end begin - send_frame(input, id: 1, method: "initialize", params: {protocolVersion: "2025-11-25", - capabilities: {}, clientInfo: {name: "test", version: "1"}}) + send_frame( + input, + id: 1, + method: "initialize", + params: { + protocolVersion: "2025-11-25", + capabilities: { + }, + clientInfo: { + name: "test", + version: "1" + } + } + ) assert_equal "2025-11-25", frame(output, "initialize").dig("result", "protocolVersion") send_frame(input, method: "notifications/initialized") channel.puts(setup) - assert_equal "ready", line(channel, "shell enrollment acknowledgement", timeout: Example::MCP_RESPONSE_TIMEOUT) - send_frame(input, id: 2, method: "tools/call", params: {name: "tmux_capabilities", arguments: {}}) - capabilities = frame(output, "tmux_capabilities").dig("result", "structuredContent", "data") - target = {generation: capabilities.fetch("server_identity").fetch("generation"), kind: "pane", id: pane.id} + assert_equal "ready", + line( + channel, + "shell enrollment acknowledgement", + timeout: Example::MCP_RESPONSE_TIMEOUT + ) + send_frame( + input, + id: 2, + method: "tools/call", + params: { + name: "tmux_capabilities", + arguments: { + } + } + ) + capabilities = + frame(output, "tmux_capabilities").dig("result", "structuredContent", "data") + target = { + generation: capabilities.fetch("server_identity").fetch("generation"), + kind: "pane", + id: pane.id + } script = 'printf "%s:%s" "$LIBTMUX_CLI_CONTEXT" "$TMUX_PANE"; printf "\\377" >&2; exit 9' - send_frame(input, id: 3, method: "tools/call", params: {name: "tmux_run", arguments: {target: target, script: script}}) + send_frame( + input, + id: 3, + method: "tools/call", + params: { + name: "tmux_run", + arguments: { + target: target, + script: script + } + } + ) response = frame(output, "first tmux_run").dig("result", "structuredContent") assert response.fetch("ok"), response.inspect result = response.fetch("data") assert_equal "literal-context:#{pane.id}", result.fetch("stdout").fetch("data") - assert_equal({"encoding" => "base64", "data" => "/w==", "bytes" => 1, "truncated" => false}, result.fetch("stderr")) - assert_equal({"state" => "exited", "exit_status" => 9, "signal" => nil}, result.fetch("completion")) + assert_equal( + { "encoding" => "base64", "data" => "/w==", "bytes" => 1, "truncated" => false }, + result.fetch("stderr") + ) + assert_equal( + { "state" => "exited", "exit_status" => 9, "signal" => nil }, + result.fetch("completion") + ) assert_equal "authorized", result.fetch("authorization").fetch("state") - send_frame(input, id: 4, method: "tools/call", params: {name: "tmux_run", - arguments: {target: target, script: "printf ready", stdout_limit: 8, stderr_limit: 0}}) + send_frame( + input, + id: 4, + method: "tools/call", + params: { + name: "tmux_run", + arguments: { + target: target, + script: "printf ready", + stdout_limit: 8, + stderr_limit: 0 + } + } + ) repeated = frame(output, "second tmux_run").dig("result", "structuredContent") assert repeated.fetch("ok"), repeated.inspect assert_equal "ready", repeated.fetch("data").fetch("stdout").fetch("data") - refute_equal result.fetch("authorization").fetch("run_id"), repeated.fetch("data").fetch("authorization").fetch("run_id") + refute_equal result.fetch("authorization").fetch("run_id"), + repeated.fetch("data").fetch("authorization").fetch("run_id") input.close assert worker.join(0.5), "enrolled CLI did not retire after EOF" assert_equal 0, worker.value, errors.string assert_empty errors.string refute File.exist?(setup) assert_empty Dir[File.join(directory, ".libtmux-ruby-shell-*")] - assert server.run(["has-session", "-t", "cli-shell"]).success? + assert server.run(%w[has-session -t cli-shell]).success? assert_empty server.list_clients ensure input.close unless input.closed? @@ -322,7 +531,14 @@ def with_plain_shell end def tmux_at(socket, *arguments) - output, status = Open3.capture2e({"TMUX" => nil, "TMUX_PANE" => nil}, ENV.fetch("LIBTMUX_TEST_TMUX", "tmux"), "-S", socket, *arguments) + output, status = + Open3.capture2e( + { "TMUX" => nil, "TMUX_PANE" => nil }, + ENV.fetch("LIBTMUX_TEST_TMUX", "tmux"), + "-S", + socket, + *arguments + ) [output, status] end @@ -331,14 +547,33 @@ def serve_cli(arguments, environment: {}) reader, input = IO.pipe output, writer = IO.pipe errors = StringIO.new - worker = Thread.new do - LibTmux::MCP::CLI.run(arguments, input: reader, out: writer, err: errors, environment: environment) - ensure - writer.close - end + worker = + Thread.new do + LibTmux::MCP::CLI.run( + arguments, + input: reader, + out: writer, + err: errors, + environment: environment + ) + ensure + writer.close + end begin - send_frame(input, id: 1, method: "initialize", params: {protocolVersion: "2025-11-25", - capabilities: {}, clientInfo: {name: "test", version: "1"}}) + send_frame( + input, + id: 1, + method: "initialize", + params: { + protocolVersion: "2025-11-25", + capabilities: { + }, + clientInfo: { + name: "test", + version: "1" + } + } + ) assert_equal "2025-11-25", frame(output, "initialize").dig("result", "protocolVersion") send_frame(input, method: "notifications/initialized") yield @@ -358,14 +593,26 @@ def test_start_session_starts_the_server_it_serves_and_eof_stops_it with_plain_shell do Dir.mktmpdir("libtmux-ruby-start-") do |directory| socket = File.join(directory, "tmux-#{Process.uid}", "agent") - arguments = ["--socket-name", "agent", "--start-session", "work", "--tmux", ENV.fetch("LIBTMUX_TEST_TMUX", "tmux")] - status, errors = serve_cli(arguments, environment: {"TMUX_TMPDIR" => directory}) do - names, = tmux_at(socket, "list-sessions", "-F", "\#{session_name}") - assert_equal "work\n", names - end + arguments = [ + "--socket-name", + "agent", + "--start-session", + "work", + "--tmux", + ENV.fetch("LIBTMUX_TEST_TMUX", "tmux") + ] + status, errors = + serve_cli(arguments, environment: { "TMUX_TMPDIR" => directory }) do + names, = tmux_at(socket, "list-sessions", "-F", "\#{session_name}") + assert_equal "work\n", names + end assert_equal 0, status, errors assert_empty errors - assert_match(/no server running|error connecting/, tmux_at(socket, "list-sessions").first, "EOF left the server it started") + assert_match( + /no server running|error connecting/, + tmux_at(socket, "list-sessions").first, + "EOF left the server it started" + ) end end end @@ -374,9 +621,17 @@ def test_keep_leaves_the_server_it_started_running_after_eof with_plain_shell do Dir.mktmpdir("libtmux-ruby-start-") do |directory| socket = File.join(directory, "tmux-#{Process.uid}", "agent") - arguments = ["--socket-name", "agent", "--start-session", "work", "--keep", "--tmux", ENV.fetch("LIBTMUX_TEST_TMUX", "tmux")] + arguments = [ + "--socket-name", + "agent", + "--start-session", + "work", + "--keep", + "--tmux", + ENV.fetch("LIBTMUX_TEST_TMUX", "tmux") + ] begin - status, errors = serve_cli(arguments, environment: {"TMUX_TMPDIR" => directory}) { nil } + status, errors = serve_cli(arguments, environment: { "TMUX_TMPDIR" => directory }) { nil } assert_equal 0, status, errors assert_equal "work\n", tmux_at(socket, "list-sessions", "-F", "\#{session_name}").first ensure @@ -388,10 +643,18 @@ def test_keep_leaves_the_server_it_started_running_after_eof def test_start_session_borrows_a_server_that_already_answers_and_leaves_it_alone LibTmuxTest::TmuxFixture.open do |fixture| - arguments = ["--socket", fixture.socket_path, "--start-session", "work", "--tmux", fixture.executable] - status, errors = serve_cli(arguments) do - assert_equal "fixture\n", fixture.tmux("list-sessions", "-F", "\#{session_name}").first - end + arguments = [ + "--socket", + fixture.socket_path, + "--start-session", + "work", + "--tmux", + fixture.executable + ] + status, errors = + serve_cli(arguments) do + assert_equal "fixture\n", fixture.tmux("list-sessions", "-F", "\#{session_name}").first + end assert_equal 0, status, errors assert_equal "fixture\n", fixture.tmux("list-sessions", "-F", "\#{session_name}").first end @@ -404,11 +667,25 @@ def test_start_session_reports_a_server_tmux_could_not_start output, writer = IO.pipe errors = StringIO.new socket = File.join(directory, "missing", "socket") - status = LibTmux::MCP::CLI.run(["--socket", socket, "--start-session", "work", "--tmux", ENV.fetch("LIBTMUX_TEST_TMUX", "tmux")], - input: reader, out: writer, err: errors) + status = + LibTmux::MCP::CLI.run( + [ + "--socket", + socket, + "--start-session", + "work", + "--tmux", + ENV.fetch("LIBTMUX_TEST_TMUX", "tmux") + ], + input: reader, + out: writer, + err: errors + ) assert_equal 1, status assert_match(/MCP could not start session work/, errors.string) - assert_empty Dir.glob(File.join(directory, "**", "*"), File::FNM_DOTMATCH).select { |path| File.socket?(path) } + assert_empty Dir + .glob(File.join(directory, "**", "*"), File::FNM_DOTMATCH) + .select { |path| File.socket?(path) } ensure [reader, input, output, writer].each { |io| io.close unless io.closed? } end @@ -429,10 +706,14 @@ def with_protocol_peer(source) end def send_frame(io, **message) - io.write(JSON.generate({jsonrpc: "2.0", **message}) + "\n") + io.write(JSON.generate({ jsonrpc: "2.0", **message }) + "\n") end - def frame(io, stage, timeout: (stage == "initialize") ? Example::MCP_STARTUP_TIMEOUT : Example::MCP_RESPONSE_TIMEOUT) + def frame( + io, + stage, + timeout: (stage == "initialize") ? Example::MCP_STARTUP_TIMEOUT : Example::MCP_RESPONSE_TIMEOUT + ) JSON.parse(line(io, "MCP #{stage}", timeout: timeout)) end diff --git a/test/integration/mcp_cursor_identity_test.rb b/test/integration/mcp_cursor_identity_test.rb index 27990cc8..df2b08db 100644 --- a/test/integration/mcp_cursor_identity_test.rb +++ b/test/integration/mcp_cursor_identity_test.rb @@ -11,9 +11,13 @@ class MCPCursorIdentityTest < Minitest::Test def test_respawn_between_descriptor_acquisition_and_guard_rejects_even_if_old_process_survives with_application do |app, scope, fixture| listener = UNIXServer.new(File.join(File.dirname(fixture.socket_path), "old-process")) - program = 'require "socket"; trap("HUP") {}; socket=UNIXSocket.new(ARGV[0]); socket.puts("ready"); socket.gets' - pane = scope.server.list_panes.first.split(direction: :vertical, - command: [Gem.ruby, "--disable=rubyopt,gems", "-e", program, listener.path]) + program = + 'require "socket"; trap("HUP") {}; socket=UNIXSocket.new(ARGV[0]); socket.puts("ready"); socket.gets' + pane = + scope.server.list_panes.first.split( + direction: :vertical, + command: [Gem.ruby, "--disable=rubyopt,gems", "-e", program, listener.path] + ) connection = listener.accept assert_equal "ready\n", connection.gets klass = LibTmux::MCP.const_get(:ProcessIdentity) @@ -45,22 +49,37 @@ def test_respawn_between_descriptor_acquisition_and_guard_rejects_even_if_old_pr def test_reaped_leader_with_draining_output_rejects_reused_pid_and_foreign_identity with_application do |app, scope, fixture| listener = UNIXServer.new(File.join(File.dirname(fixture.socket_path), "leader")) - program = 'require "socket"; socket=UNIXSocket.new(ARGV[0]); socket.puts("ready"); socket.gets; STDOUT.write("x" * 1048576); STDOUT.flush; exit! 0' - pane = scope.server.list_panes.first.split(direction: :vertical, - command: [Gem.ruby, "--disable=rubyopt,gems", "-e", program, listener.path]) + program = + 'require "socket"; socket=UNIXSocket.new(ARGV[0]); socket.puts("ready"); socket.gets; STDOUT.write("x" * 1048576); STDOUT.flush; exit! 0' + pane = + scope.server.list_panes.first.split( + direction: :vertical, + command: [Gem.ruby, "--disable=rubyopt,gems", "-e", program, listener.path] + ) pane.options.set("remain-on-exit", true) connection = listener.accept assert_equal "ready\n", connection.gets sink_listener = UNIXServer.new(File.join(File.dirname(fixture.socket_path), "pipe-sink")) - sink_program = 'require "socket"; socket=UNIXSocket.new(ARGV[0]); socket.puts("ready"); socket.gets; STDIN.read' - pane.pipe(shell_command: [Gem.ruby, "--disable=rubyopt,gems", "-e", sink_program, sink_listener.path].shelljoin) + sink_program = + 'require "socket"; socket=UNIXSocket.new(ARGV[0]); socket.puts("ready"); socket.gets; STDIN.read' + pane.pipe( + shell_command: [ + Gem.ruby, + "--disable=rubyopt,gems", + "-e", + sink_program, + sink_listener.path + ].shelljoin + ) sink = sink_listener.accept assert_equal "ready\n", sink.gets connection.puts("write-and-exit") assert_equal "", connection.read # The control stream can close before tmux records the exit. status = fixture.wait_for_pane_exit_status(scope.server, pane.id) - assert_equal "0|0|\n", status, "the leader is reaped while its output pipe still has queued bytes" + assert_equal "0|0|\n", + status, + "the leader is reaped while its output pipe still has queued bytes" klass = LibTmux::MCP.const_get(:ProcessIdentity) original = klass.method(:acquire) # Emulate the kernel-reuse hazard with a real live descriptor but the @@ -87,7 +106,8 @@ def test_reaped_leader_with_draining_output_rejects_reused_pid_and_foreign_ident klass.define_singleton_method(:procfs_namespace) { File.open("/proc/self/ns/mnt") } end begin - failure = capture(app, scope.server.list_panes.find { |item| item.id != pane.id }, track: true) + failure = + capture(app, scope.server.list_panes.find { |item| item.id != pane.id }, track: true) assert_equal "unsupported", failure.dig("error", "code") ensure klass.define_singleton_method(:procfs_namespace, namespace) @@ -104,19 +124,27 @@ def test_reaped_leader_with_draining_output_rejects_reused_pid_and_foreign_ident def test_process_death_remains_readable_after_owned_child_is_reaped with_application do |_app, scope, fixture| listener = UNIXServer.new(File.join(File.dirname(fixture.socket_path), "retained-exit")) - code = 'require "socket"; UNIXSocket.open(ARGV.fetch(0)) { |io| io.puts(Process.pid); io.read(1) }' - request = ::Async::Task.current.async do - scope.__send__(:execute, [Gem.ruby, "--disable=rubyopt,gems", "-e", code, listener.path]) - end + code = + 'require "socket"; UNIXSocket.open(ARGV.fetch(0)) { |io| io.puts(Process.pid); io.read(1) }' + request = + ::Async::Task.current.async do + scope.__send__(:execute, [Gem.ruby, "--disable=rubyopt,gems", "-e", code, listener.path]) + end connection = pid = nil - ::Async::Task.current.with_timeout(0.5) do - connection = listener.accept - pid = Integer(connection.gets, 10) - end + ::Async::Task + .current + .with_timeout(0.5) do + connection = listener.accept + pid = Integer(connection.gets, 10) + end snapshot = scope.server.snapshot - identity = LibTmux::MCP.const_get(:ProcessIdentity).acquire(scope.server, - server_pid: snapshot.server_info.fetch(:pid), pane_pid: pid, - budget: scope.server.__send__(:operation_budget, 0.5, nil)) + identity = + LibTmux::MCP.const_get(:ProcessIdentity).acquire( + scope.server, + server_pid: snapshot.server_info.fetch(:pid), + pane_pid: pid, + budget: scope.server.__send__(:operation_budget, 0.5, nil) + ) klass = LibTmux::MCP.const_get(:ProcessIdentity) native = klass.method(:native) faults = [:interrupted] @@ -147,7 +175,7 @@ def test_process_death_remains_readable_after_owned_child_is_reaped assert_raises(Errno::ECHILD) { Process.waitpid(pid, Process::WNOHANG) } faults << :interrupted 2.times { assert identity.exited?, "terminal process readiness was consumed" } - [[:interrupted, :interrupted], [:failed], [:invalid]].each do |sequence| + [%i[interrupted interrupted], [:failed], [:invalid]].each do |sequence| faults.replace(sequence) error = assert_raises(LibTmux::TransportError) { identity.exited? } assert_equal :read, error.phase @@ -174,7 +202,8 @@ def test_retained_descriptors_share_cursor_branches_and_close_with_eviction_expi entry = app.instance_variable_get(:@captures).fetch(first.fetch("next_cursor")) identity = entry.process branch = capture(app, pane, cursor: first.fetch("next_cursor")).fetch("data") - assert_same identity, app.instance_variable_get(:@captures).fetch(branch.fetch("next_cursor")).process + assert_same identity, + app.instance_variable_get(:@captures).fetch(branch.fetch("next_cursor")).process capture(app, pane, track: true) refute identity.io.closed?, "evicting one immutable branch must preserve its other owner" capture(app, pane, track: true) @@ -182,7 +211,8 @@ def test_retained_descriptors_share_cursor_branches_and_close_with_eviction_expi assert identity.peer.closed? entries = app.instance_variable_get(:@captures).values app.define_singleton_method(:clock) { Process.clock_gettime(Process::CLOCK_MONOTONIC) + 60 } - assert_equal "stale_cursor", capture(app, pane, cursor: branch.fetch("next_cursor")).dig("error", "code") + assert_equal "stale_cursor", + capture(app, pane, cursor: branch.fetch("next_cursor")).dig("error", "code") entries.each { |retained| assert retained.process.io.closed? } capture(app, pane, track: true) entries = app.instance_variable_get(:@captures).values @@ -223,31 +253,33 @@ def test_acquisition_cleanup_failure_is_sanitized_and_keeps_retry_ownership pane = scope.server.list_panes.first held = nil allow_close = false - refuse_close = lambda do |io| - held = io - closer = io.method(:close) - io.define_singleton_method(:close) do - raise IOError, "PRIVATE OBSERVER CLEANUP" unless allow_close + refuse_close = + lambda do |io| + held = io + closer = io.method(:close) + io.define_singleton_method(:close) do + raise IOError, "PRIVATE OBSERVER CLEANUP" unless allow_close - closer.call - end - end - restore = if RUBY_PLATFORM.include?("darwin") - identity = LibTmux::MCP.const_get(:ProcessIdentity) - validate = identity.instance_method(:ensure_live!) - identity.define_method(:ensure_live!) do - validate.bind_call(self) - refuse_close.call(io) - raise LibTmux::TransportError.new("identity acquisition interrupted", phase: :admission) + closer.call + end end - -> { identity.define_method(:ensure_live!, validate) } - else - constructor = Socket.method(:new) - Socket.define_singleton_method(:new) do |*arguments| - constructor.call(*arguments).tap { |socket| refuse_close.call(socket) } + restore = + if RUBY_PLATFORM.include?("darwin") + identity = LibTmux::MCP.const_get(:ProcessIdentity) + validate = identity.instance_method(:ensure_live!) + identity.define_method(:ensure_live!) do + validate.bind_call(self) + refuse_close.call(io) + raise LibTmux::TransportError.new("identity acquisition interrupted", phase: :admission) + end + -> { identity.define_method(:ensure_live!, validate) } + else + constructor = Socket.method(:new) + Socket.define_singleton_method(:new) do |*arguments| + constructor.call(*arguments).tap { |socket| refuse_close.call(socket) } + end + -> { Socket.define_singleton_method(:new, constructor) } end - -> { Socket.define_singleton_method(:new, constructor) } - end begin result = capture(app, pane, track: true) assert_equal "transport_error", result.dig("error", "code"), result.inspect @@ -271,15 +303,27 @@ def test_acquisition_cleanup_failure_is_sanitized_and_keeps_retry_ownership def capture(app, pane, **options) ref = pane.ref - app.call("tmux_capture", {target: {generation: ref.binding_key, kind: "pane", id: ref.id}, **options}).structured_content + app.call( + "tmux_capture", + { target: { generation: ref.binding_key, kind: "pane", id: ref.id }, **options } + ).structured_content end def with_application(**options) LibTmuxTest::TmuxFixture.open do |fixture| - LibTmux::Server.open(socket_path: fixture.socket_path, executable: fixture.executable) do |source| + LibTmux::Server.open( + socket_path: fixture.socket_path, + executable: fixture.executable + ) do |source| Async do |task| LibTmux::Async.open(server: source, parent: task) do |scope| - app = LibTmux::MCP::Application.new(server: scope.server, endpoint_name: "test", enabled_tools: ["tmux_capture"], **options) + app = + LibTmux::MCP::Application.new( + server: scope.server, + endpoint_name: "test", + enabled_tools: ["tmux_capture"], + **options + ) begin require_process_cursor_support(scope) yield app, scope, fixture diff --git a/test/integration/mcp_enrollment_test.rb b/test/integration/mcp_enrollment_test.rb index 0c21fe8c..90c4ea05 100644 --- a/test/integration/mcp_enrollment_test.rb +++ b/test/integration/mcp_enrollment_test.rb @@ -1,13 +1,15 @@ # frozen_string_literal: true -require_relative '../test_helper' -require_relative '../support/tmux_fixture' -require_relative '../support/process_cursor_support' -require 'libtmux/async' -require 'socket' -require 'async/queue' -require 'digest' -require 'libtmux/mcp/enrollment' if File.file?(File.expand_path('../../gems/libtmux-mcp/lib/libtmux/mcp/enrollment.rb', __dir__)) +require_relative "../test_helper" +require_relative "../support/tmux_fixture" +require_relative "../support/process_cursor_support" +require "libtmux/async" +require "socket" +require "async/queue" +require "digest" +if File.file?(File.expand_path("../../gems/libtmux-mcp/lib/libtmux/mcp/enrollment.rb", __dir__)) + require "libtmux/mcp/enrollment" +end class MCPEnrollmentTest < Minitest::Test include LibTmuxTest::ProcessCursorSupport @@ -16,43 +18,53 @@ class MCPEnrollmentTest < Minitest::Test private_constant :FixtureHandoffExpired def test_enrolled_borrowed_shell_prepares_without_executing_and_observes_one_use_grant - assert LibTmux::MCP.const_defined?(:EnrollmentRegistry, false), 'explicit shell enrollment is not implemented' + assert LibTmux::MCP.const_defined?(:EnrollmentRegistry, false), + "explicit shell enrollment is not implemented" with_shell do |registry, pane, channel, scope, source| - digest = Digest::SHA256.hexdigest('exit 7') + digest = Digest::SHA256.hexdigest("exit 7") prepared = registry.prepare(pane.ref, script_digest: digest, timeout: 0.5) refute prepared.authorized? assert_equal pane.id, prepared.reference.id grant = prepared.authorize(timeout: 0.5) - assert_equal 'authorized', grant.fetch('state') - assert_equal digest, grant.fetch('script_digest') - assert_equal pane.ref.binding_key, grant.fetch('server_generation') - assert_equal prepared.process_generation, grant.fetch('process_generation') - assert_equal prepared.run_id, grant.fetch('run_id') + assert_equal "authorized", grant.fetch("state") + assert_equal digest, grant.fetch("script_digest") + assert_equal pane.ref.binding_key, grant.fetch("server_generation") + assert_equal prepared.process_generation, grant.fetch("process_generation") + assert_equal prepared.run_id, grant.fetch("run_id") assert prepared.authorized? nonce = prepared.instance_variable_get(:@authorization) - assert_raises(LibTmux::DeadlineExceeded) { scope.server.run(['wait-for', nonce], timeout: 0.03) } - scope.server.run(['wait-for', '-S', nonce]) + assert_raises(LibTmux::DeadlineExceeded) do + scope.server.run(["wait-for", nonce], timeout: 0.03) + end + scope.server.run(["wait-for", "-S", nonce]) assert_raises(LibTmux::ClosedError) { prepared.authorize(timeout: 0.5) } prepared.close registry.close - assert source.run(['has-session', '-t', 'enrolled']).success? + assert source.run(%w[has-session -t enrolled]).success? assert_empty scope.server.list_clients end end def test_partial_editor_refuses_without_changing_input_and_pregrant_cancel_has_no_authorization with_shell do |registry, pane, _channel, _scope, _source| - pane.send_text('unfinished-input') - failure = assert_raises(LibTmux::UnsupportedFeatureError) do - registry.prepare(pane.ref, script_digest: Digest::SHA256.hexdigest('exit 0'), timeout: 0.5) - end + pane.send_text("unfinished-input") + failure = + assert_raises(LibTmux::UnsupportedFeatureError) do + registry.prepare( + pane.ref, + script_digest: Digest::SHA256.hexdigest("exit 0"), + timeout: 0.5 + ) + end assert_equal :not_sent, failure.delivery - assert_includes pane.capture.text, 'unfinished-input' - pane.send_keys('C-u') - prepared = registry.prepare(pane.ref, script_digest: Digest::SHA256.hexdigest('exit 0'), timeout: 0.5) + assert_includes pane.capture.text, "unfinished-input" + pane.send_keys("C-u") + prepared = + registry.prepare(pane.ref, script_digest: Digest::SHA256.hexdigest("exit 0"), timeout: 0.5) token = LibTmux::Internal::Cancellation.new token.cancel - failure = assert_raises(LibTmux::Cancelled) { prepared.authorize(timeout: 0.5, cancel: token) } + failure = + assert_raises(LibTmux::Cancelled) { prepared.authorize(timeout: 0.5, cancel: token) } assert_equal :not_sent, failure.delivery refute prepared.authorized? prepared.close @@ -63,8 +75,9 @@ def test_partial_editor_refuses_without_changing_input_and_pregrant_cancel_has_n def test_respawn_before_grant_refuses_and_respawn_after_grant_keeps_the_original_recipient with_shell do |registry, pane, _channel, scope, _source| - prepared = registry.prepare(pane.ref, script_digest: Digest::SHA256.hexdigest('exit 0'), timeout: 0.5) - pane.respawn(command: ['cat'], kill: true) + prepared = + registry.prepare(pane.ref, script_digest: Digest::SHA256.hexdigest("exit 0"), timeout: 0.5) + pane.respawn(command: ["cat"], kill: true) failure = assert_raises(LibTmux::TargetNotFoundError) { prepared.authorize(timeout: 0.5) } assert_equal :not_sent, failure.delivery refute prepared.authorized? @@ -72,19 +85,20 @@ def test_respawn_before_grant_refuses_and_respawn_after_grant_keeps_the_original assert scope.server.snapshot.panes.find { |record| record.id == pane.id } end with_shell do |registry, pane, _channel, scope, _source| - prepared = registry.prepare(pane.ref, script_digest: Digest::SHA256.hexdigest('exit 0'), timeout: 0.5) + prepared = + registry.prepare(pane.ref, script_digest: Digest::SHA256.hexdigest("exit 0"), timeout: 0.5) old_pid = scope.server.snapshot.panes.find { |record| record.id == pane.id }.pid original = registry.method(:guard) registry.define_singleton_method(:guard) do |reference, identity, budget, nonce = nil| result = original.call(reference, identity, budget, nonce) - pane.respawn(command: ['cat'], kill: true) if nonce + pane.respawn(command: ["cat"], kill: true) if nonce result end receipt = prepared.authorize(timeout: 0.5) replacement = scope.server.snapshot.panes.find { |record| record.id == pane.id } refute_equal old_pid, replacement.pid - assert_equal prepared.process_generation, receipt.fetch('process_generation') - assert_equal 'authorized', receipt.fetch('state') + assert_equal prepared.process_generation, receipt.fetch("process_generation") + assert_equal "authorized", receipt.fetch("state") refute_includes pane.capture.text, prepared.run_id prepared.close end @@ -92,7 +106,8 @@ def test_respawn_before_grant_refuses_and_respawn_after_grant_keeps_the_original def test_cancellation_after_the_committed_grant_keeps_its_exact_effect_receipt with_shell do |registry, pane, _channel, _scope, _source| - prepared = registry.prepare(pane.ref, script_digest: Digest::SHA256.hexdigest('exit 0'), timeout: 0.5) + prepared = + registry.prepare(pane.ref, script_digest: Digest::SHA256.hexdigest("exit 0"), timeout: 0.5) token = LibTmux::Internal::Cancellation.new original = registry.method(:guard) registry.define_singleton_method(:guard) do |reference, identity, budget, nonce = nil| @@ -100,10 +115,11 @@ def test_cancellation_after_the_committed_grant_keeps_its_exact_effect_receipt token.cancel if nonce result end - failure = assert_raises(LibTmux::Cancelled) { prepared.authorize(timeout: 0.5, cancel: token) } + failure = + assert_raises(LibTmux::Cancelled) { prepared.authorize(timeout: 0.5, cancel: token) } assert_equal :possibly_sent, failure.delivery - assert_equal 'authorized', prepared.receipt.fetch('state') - assert_equal prepared.process_generation, prepared.receipt.fetch('process_generation') + assert_equal "authorized", prepared.receipt.fetch("state") + assert_equal prepared.process_generation, prepared.receipt.fetch("process_generation") prepared.close ensure token&.close @@ -112,113 +128,132 @@ def test_cancellation_after_the_committed_grant_keeps_its_exact_effect_receipt def test_close_cancels_a_busy_shell_preparation_and_prevents_delayed_authorization with_shell do |registry, pane, channel, _scope, source| - pane.send_text('test_busy') - pane.send_keys('Enter') - assert_equal 'busy', read_line(channel) + pane.send_text("test_busy") + pane.send_keys("Enter") + assert_equal "busy", read_line(channel) started = Async::Queue.new original = registry.method(:accept_socket) registry.define_singleton_method(:accept_socket) do |listener, budget| started.enqueue(true) original.call(listener, budget) end - pending = Async::Task.current.async do - registry.prepare(pane.ref, script_digest: Digest::SHA256.hexdigest('exit 0'), timeout: 0.5) - rescue Exception => error - error - end + pending = + Async::Task.current.async do + registry.prepare( + pane.ref, + script_digest: Digest::SHA256.hexdigest("exit 0"), + timeout: 0.5 + ) + rescue Exception => error + error + end Async::Task.current.with_timeout(0.5) { started.dequeue } registry.close - assert pending.finished?, 'registry close must retire its active preparation' + assert pending.finished?, "registry close must retire its active preparation" assert_instance_of LibTmux::Cancelled, pending.wait(timeout: 0.5) - pane.send_keys('Enter') - assert_equal 'busy-ended', read_line(channel) - assert_equal 'ready', read_line(channel) - assert source.run(['has-session', '-t', 'enrolled']).success? + pane.send_keys("Enter") + assert_equal "busy-ended", read_line(channel) + assert_equal "ready", read_line(channel) + assert source.run(%w[has-session -t enrolled]).success? end end def test_failed_enrollment_transfer_keeps_the_accepted_channel_and_identity_owned - acceptor = lambda do |registry, invitation| - accepted = nil - identity = invitation.capture.process - original_accept = registry.method(:accept_socket) - registry.define_singleton_method(:accept_socket) do |listener, budget| - accepted = original_accept.call(listener, budget) - end - original_close = invitation.listener.method(:close) - first = true - invitation.listener.define_singleton_method(:close) do - if first - first = false - raise IOError, 'injected listener close failure' + acceptor = + lambda do |registry, invitation| + accepted = nil + identity = invitation.capture.process + original_accept = registry.method(:accept_socket) + registry.define_singleton_method(:accept_socket) do |listener, budget| + accepted = original_accept.call(listener, budget) end - original_close.call + original_close = invitation.listener.method(:close) + first = true + invitation + .listener + .define_singleton_method(:close) do + if first + first = false + raise IOError, "injected listener close failure" + end + original_close.call + end + assert_raises(IOError) { registry.accept(invitation, timeout: 0.5) } + registry.close + assert accepted.closed?, + "accepted protocol channel must remain owned when invitation retirement fails" + assert identity.io.closed?, "the transferred native identity lease must remain owned" + nil + ensure + accepted&.close unless accepted&.closed? + identity&.close unless identity&.io&.closed? end - assert_raises(IOError) { registry.accept(invitation, timeout: 0.5) } - registry.close - assert accepted.closed?, 'accepted protocol channel must remain owned when invitation retirement fails' - assert identity.io.closed?, 'the transferred native identity lease must remain owned' - nil - ensure - accepted&.close unless accepted&.closed? - identity&.close unless identity&.io&.closed? - end - with_shell(acceptor: acceptor) { } + with_shell(acceptor: acceptor) {} end def test_pending_enrollment_rejects_duplicate_reference_before_capture - acceptor = lambda do |registry, invitation| - assert_raises(LibTmux::CapacityError) { registry.invite(invitation.reference, timeout: 0.5) } - registry.accept(invitation, timeout: 0.5) - end - with_shell(acceptor: acceptor) { } + acceptor = + lambda do |registry, invitation| + assert_raises(LibTmux::CapacityError) do + registry.invite(invitation.reference, timeout: 0.5) + end + registry.accept(invitation, timeout: 0.5) + end + with_shell(acceptor: acceptor) {} end def test_authored_script_preserves_context_separates_binary_output_and_reports_native_status with_shell(space_paths: true) do |registry, pane, _channel, _scope, _source, directory| - assert_respond_to registry, :run, 'authored execution has not been implemented' - script = %(printf '%s\n' "$PWD" "$LIBTMUX_RUN_TEST_VALUE" "$TMUX_PANE"; printf 'AUTHORIZED fake marker\n'; printf '\\000\\377\\n' >&2; exit 7) - result = registry.run(pane.ref, script: script, timeout: 0.5, stdout_limit: 8192, stderr_limit: 8192) - assert_equal "#{directory}\nliteral-value\n#{pane.id}\nAUTHORIZED fake marker\n".b, result.stdout + assert_respond_to registry, :run, "authored execution has not been implemented" + script = + %(printf '%s\n' "$PWD" "$LIBTMUX_RUN_TEST_VALUE" "$TMUX_PANE"; printf 'AUTHORIZED fake marker\n'; printf '\\000\\377\\n' >&2; exit 7) + result = + registry.run(pane.ref, script: script, timeout: 0.5, stdout_limit: 8192, stderr_limit: 8192) + assert_equal "#{directory}\nliteral-value\n#{pane.id}\nAUTHORIZED fake marker\n".b, + result.stdout assert_equal "\x00\xff\n".b, result.stderr assert_equal 7, result.exit_status assert_nil result.signal - assert_equal 'authorized', result.receipt.fetch('state') - assert_equal Digest::SHA256.hexdigest(script), result.receipt.fetch('script_digest') + assert_equal "authorized", result.receipt.fetch("state") + assert_equal Digest::SHA256.hexdigest(script), result.receipt.fetch("script_digest") end end def test_authored_output_overflow_and_cancel_do_not_invent_completion_or_allow_parallel_runs with_shell do |registry, pane, _channel, _scope, _source, directory| - failure = assert_raises(LibTmux::CapacityError) do - registry.run(pane.ref, script: "printf 123456789", timeout: 0.5, stdout_limit: 8) - end + failure = + assert_raises(LibTmux::CapacityError) do + registry.run(pane.ref, script: "printf 123456789", timeout: 0.5, stdout_limit: 8) + end assert_equal :possibly_sent, failure.delivery - assert_equal 'authorized', failure.run_receipt.fetch('state') + assert_equal "authorized", failure.run_receipt.fetch("state") - path = File.join(directory, 'script-ready') + path = File.join(directory, "script-ready") UNIXServer.open(path) do |listener| code = "s=UNIXSocket.new(ARGV.fetch(0));s.puts(Process.pid);s.read" - script = "exec #{[Gem.ruby, '--disable=rubyopt,gems', '-rsocket', '-e', code, path].map { |value| "'#{value.gsub("'", %q('\''))}'" }.join(' ')}" + script = + "exec #{[Gem.ruby, "--disable=rubyopt,gems", "-rsocket", "-e", code, path].map { |value| "'#{value.gsub("'", %q('\''))}'" }.join(" ")}" token = LibTmux::Internal::Cancellation.new - pending = Async::Task.current.async do - registry.run(pane.ref, script: script, timeout: 0.5, cancel: token) - rescue Exception => error - error - end - child = fixture_handoff('authored script connection') { listener.accept } - pid = Integer(read_line(child, stage: 'authored script PID')) - failure = assert_raises(LibTmux::CapacityError) do - registry.run(pane.ref, script: 'exit 0', timeout: 0.5) - end + pending = + Async::Task.current.async do + registry.run(pane.ref, script: script, timeout: 0.5, cancel: token) + rescue Exception => error + error + end + child = fixture_handoff("authored script connection") { listener.accept } + pid = Integer(read_line(child, stage: "authored script PID")) + failure = + assert_raises(LibTmux::CapacityError) do + registry.run(pane.ref, script: "exit 0", timeout: 0.5) + end assert_equal :not_sent, failure.delivery token.cancel - failure = fixture_handoff('authored cancellation retirement') { pending.wait } + failure = fixture_handoff("authored cancellation retirement") { pending.wait } assert_instance_of LibTmux::Cancelled, failure assert_equal :possibly_sent, failure.delivery - assert_equal 'authorized', failure.run_receipt.fetch('state') + assert_equal "authorized", failure.run_receipt.fetch("state") assert_raises(Errno::ESRCH) { Process.kill(0, pid) } - assert_nil fixture_handoff('authored script EOF') { child.read(1) } + assert_nil fixture_handoff("authored script EOF") { child.read(1) } ensure child&.close token&.close @@ -249,11 +284,12 @@ def test_registry_close_keeps_a_runs_final_helper_retirement_owned end prepared end - pending = Async::Task.current.async do - registry.run(pane.ref, script: 'exit 0', timeout: 0.5) - rescue Exception => error - error - end + pending = + Async::Task.current.async do + registry.run(pane.ref, script: "exit 0", timeout: 0.5) + rescue Exception => error + error + end Async::Task.current.with_timeout(0.5) { entered.dequeue } changed = registry.instance_variable_get(:@changed) original_wait = changed.method(:wait) @@ -261,19 +297,20 @@ def test_registry_close_keeps_a_runs_final_helper_retirement_owned waiting.enqueue(true) original_wait.call end - closing = Async::Task.current.async do - registry.close - rescue Exception => error - error - end + closing = + Async::Task.current.async do + registry.close + rescue Exception => error + error + end Async::Task.current.with_timeout(0.5) { waiting.dequeue } - assert_equal 1, closes, 'registry close must not race the active run cleanup' - refute closing.finished?, 'registry close must await the run cleanup owner' + assert_equal 1, closes, "registry close must not race the active run cleanup" + refute closing.finished?, "registry close must await the run cleanup owner" 2.times do closing.cancel Async::Task.current.with_timeout(0.5) { waiting.dequeue } end - refute closing.finished?, 'repeated cancellation must not abandon admitted cleanup' + refute closing.finished?, "repeated cancellation must not abandon admitted cleanup" release.enqueue(true) assert_instance_of Async::Cancel, pending.wait(timeout: 0.5) assert_instance_of Async::Cancel, closing.wait(timeout: 0.5) @@ -291,11 +328,14 @@ def test_cancellation_watcher_construction_failure_releases_request_admission with_shell do |registry, pane, _channel, _scope, _source| token = LibTmux::Internal::Cancellation.new original_new = Async::Task.method(:new) - Async::Task.define_singleton_method(:new) { |*| raise IOError, 'injected watcher construction failure' } + Async::Task.define_singleton_method(:new) do |*| + raise IOError, "injected watcher construction failure" + end assert_raises(IOError) do - registry.prepare(pane.ref, script_digest: Digest::SHA256.hexdigest('exit 0'), cancel: token) + registry.prepare(pane.ref, script_digest: Digest::SHA256.hexdigest("exit 0"), cancel: token) end - assert_empty registry.instance_variable_get(:@calls), 'failed watcher construction must release admission' + assert_empty registry.instance_variable_get(:@calls), + "failed watcher construction must release admission" ensure Async::Task.define_singleton_method(:new, original_new) if original_new registry.instance_variable_get(:@calls).delete(Async::Task.current) @@ -304,37 +344,126 @@ def test_cancellation_watcher_construction_failure_releases_request_admission end def test_public_enrollment_and_sdk_run_require_opt_in_and_preserve_completion_evidence - require 'libtmux/mcp' - with_shell(app_tools: ['tmux_run']) do |application, pane, _channel, scope, _source| - readonly = LibTmux::MCP::Application.new(server: scope.server, endpoint_name: 'readonly') - assert_raises(LibTmux::UnsupportedFeatureError) { readonly.invite_shell(pane.ref, timeout: 0.5) } - denied = readonly.call('tmux_run', {}).structured_content - assert_equal 'policy_denied', denied.fetch('error').fetch('code') + require "libtmux/mcp" + with_shell(app_tools: ["tmux_run"]) do |application, pane, _channel, scope, _source| + readonly = LibTmux::MCP::Application.new(server: scope.server, endpoint_name: "readonly") + assert_raises(LibTmux::UnsupportedFeatureError) do + readonly.invite_shell(pane.ref, timeout: 0.5) + end + denied = readonly.call("tmux_run", {}).structured_content + assert_equal "policy_denied", denied.fetch("error").fetch("code") sdk = application.sdk_server - sdk.handle({jsonrpc: '2.0', id: 1, method: 'initialize', params: {protocolVersion: '2026-07-28', capabilities: {}, clientInfo: {name: 'run-test', version: '1'}}}) + sdk.handle( + { + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { + protocolVersion: "2026-07-28", + capabilities: { + }, + clientInfo: { + name: "run-test", + version: "1" + } + } + } + ) script = "printf 'RESULT hostile output'; printf '\\377' >&2; exit 7" - reply = sdk.handle({jsonrpc: '2.0', id: 2, method: 'tools/call', params: {name: 'tmux_run', arguments: { - target: {generation: pane.ref.binding_key, kind: 'pane', id: pane.id}, script: script, stdout_limit: 64, stderr_limit: 64}}}) - structured = JSON.parse(JSON.generate(reply)).fetch('result').fetch('structuredContent') - assert_equal true, structured.fetch('ok') - data = structured.fetch('data') - assert_equal({'state' => 'exited', 'exit_status' => 7, 'signal' => nil}, data.fetch('completion')) - assert_equal({'encoding' => 'utf-8', 'data' => 'RESULT hostile output', 'bytes' => 21, 'truncated' => false}, data.fetch('stdout')) - assert_equal({'encoding' => 'base64', 'data' => '/w==', 'bytes' => 1, 'truncated' => false}, data.fetch('stderr')) - assert_equal 'authorized', data.fetch('authorization').fetch('state') - assert_equal Digest::SHA256.hexdigest(script), data.fetch('authorization').fetch('script_digest') - target = {generation: pane.ref.binding_key, kind: 'pane', id: pane.id} - overflow = sdk.handle({jsonrpc: '2.0', id: 3, method: 'tools/call', params: {name: 'tmux_run', arguments: { - target: target, script: "printf 'sensitive-overflow-marker'", stdout_limit: 1, stderr_limit: 0}}}) - error = JSON.parse(JSON.generate(overflow)).fetch('result').fetch('structuredContent').fetch('error') - assert_equal 'capacity', error.fetch('code') - assert_equal 'known', error.fetch('effects').fetch('state') - assert_equal({'state' => 'unobserved'}, error.fetch('effects').fetch('completion')) - refute_includes JSON.generate(error), 'sensitive-overflow-marker' - limited = LibTmux::MCP::Application.new(server: scope.server, endpoint_name: 'limited', enabled_tools: ['tmux_run'], max_response_bytes: 4096) - refused = limited.call('tmux_run', {'target' => target.transform_keys(&:to_s), 'script' => 'exit 0', 'stdout_limit' => 1, 'stderr_limit' => 0}).structured_content - assert_equal 'capacity', refused.fetch('error').fetch('code') - assert_equal({'state' => 'none', 'authorization' => nil, 'completion' => {'state' => 'unobserved'}}, refused.fetch('error').fetch('effects')) + reply = + sdk.handle( + { + jsonrpc: "2.0", + id: 2, + method: "tools/call", + params: { + name: "tmux_run", + arguments: { + target: { + generation: pane.ref.binding_key, + kind: "pane", + id: pane.id + }, + script: script, + stdout_limit: 64, + stderr_limit: 64 + } + } + } + ) + structured = JSON.parse(JSON.generate(reply)).fetch("result").fetch("structuredContent") + assert_equal true, structured.fetch("ok") + data = structured.fetch("data") + assert_equal( + { "state" => "exited", "exit_status" => 7, "signal" => nil }, + data.fetch("completion") + ) + assert_equal( + { + "encoding" => "utf-8", + "data" => "RESULT hostile output", + "bytes" => 21, + "truncated" => false + }, + data.fetch("stdout") + ) + assert_equal( + { "encoding" => "base64", "data" => "/w==", "bytes" => 1, "truncated" => false }, + data.fetch("stderr") + ) + assert_equal "authorized", data.fetch("authorization").fetch("state") + assert_equal Digest::SHA256.hexdigest(script), + data.fetch("authorization").fetch("script_digest") + target = { generation: pane.ref.binding_key, kind: "pane", id: pane.id } + overflow = + sdk.handle( + { + jsonrpc: "2.0", + id: 3, + method: "tools/call", + params: { + name: "tmux_run", + arguments: { + target: target, + script: "printf 'sensitive-overflow-marker'", + stdout_limit: 1, + stderr_limit: 0 + } + } + } + ) + error = + JSON + .parse(JSON.generate(overflow)) + .fetch("result") + .fetch("structuredContent") + .fetch("error") + assert_equal "capacity", error.fetch("code") + assert_equal "known", error.fetch("effects").fetch("state") + assert_equal({ "state" => "unobserved" }, error.fetch("effects").fetch("completion")) + refute_includes JSON.generate(error), "sensitive-overflow-marker" + limited = + LibTmux::MCP::Application.new( + server: scope.server, + endpoint_name: "limited", + enabled_tools: ["tmux_run"], + max_response_bytes: 4096 + ) + refused = + limited.call( + "tmux_run", + { + "target" => target.transform_keys(&:to_s), + "script" => "exit 0", + "stdout_limit" => 1, + "stderr_limit" => 0 + } + ).structured_content + assert_equal "capacity", refused.fetch("error").fetch("code") + assert_equal( + { "state" => "none", "authorization" => nil, "completion" => { "state" => "unobserved" } }, + refused.fetch("error").fetch("effects") + ) registry = application.instance_variable_get(:@shells) original_prepare = registry.method(:prepare) registry.define_singleton_method(:prepare) do |*arguments, **options| @@ -343,31 +472,51 @@ def test_public_enrollment_and_sdk_run_require_opt_in_and_preserve_completion_ev prepared.define_singleton_method(:close) do |**close_options| if first first = false - raise IOError, 'injected retirement failure after native completion' + raise IOError, "injected retirement failure after native completion" end original_close.call(**close_options) end prepared end - cleanup = sdk.handle({jsonrpc: '2.0', id: 4, method: 'tools/call', params: {name: 'tmux_run', arguments: { - target: target, script: 'exit 9', stdout_limit: 0, stderr_limit: 0}}}) - error = JSON.parse(JSON.generate(cleanup)).fetch('result').fetch('structuredContent').fetch('error') - assert_equal 'observed', error.fetch('delivery') - assert_equal 'authorized', error.fetch('effects').fetch('authorization').fetch('state') - assert_equal({'state' => 'exited', 'exit_status' => 9, 'signal' => nil}, error.fetch('effects').fetch('completion')) + cleanup = + sdk.handle( + { + jsonrpc: "2.0", + id: 4, + method: "tools/call", + params: { + name: "tmux_run", + arguments: { + target: target, + script: "exit 9", + stdout_limit: 0, + stderr_limit: 0 + } + } + } + ) + error = + JSON.parse(JSON.generate(cleanup)).fetch("result").fetch("structuredContent").fetch("error") + assert_equal "observed", error.fetch("delivery") + assert_equal "authorized", error.fetch("effects").fetch("authorization").fetch("state") + assert_equal( + { "state" => "exited", "exit_status" => 9, "signal" => nil }, + error.fetch("effects").fetch("completion") + ) unregisters = 0 cancellation = Object.new cancellation.define_singleton_method(:on_cancel) { |&_| :registration } cancellation.define_singleton_method(:off_cancel) do |_registration| unregisters += 1 - raise IOError, 'injected callback unregister failure' if unregisters == 1 + raise IOError, "injected callback unregister failure" if unregisters == 1 end - failure = assert_raises(LibTmux::CapacityError) do - application.invite_shell(pane.ref, cancellation: cancellation) - end - assert failure.cleanup_errors.any? { |message| message.include?('request retirement') } + failure = + assert_raises(LibTmux::CapacityError) do + application.invite_shell(pane.ref, cancellation: cancellation) + end + assert failure.cleanup_errors.any? { |message| message.include?("request retirement") } application.close - assert_equal 2, unregisters, 'application close must retry owned callback retirement' + assert_equal 2, unregisters, "application close must retry owned callback retirement" ensure limited&.close readonly&.close @@ -375,35 +524,72 @@ def test_public_enrollment_and_sdk_run_require_opt_in_and_preserve_completion_ev end def test_sdk_callback_retirement_after_result_preserves_native_completion - require 'libtmux/mcp' - with_shell(app_tools: ['tmux_run']) do |application, pane, _channel, _scope, _source| + require "libtmux/mcp" + with_shell(app_tools: ["tmux_run"]) do |application, pane, _channel, _scope, _source| sdk = application.sdk_server session = ::MCP::ServerSession.new(server: sdk, transport: Object.new) - session.handle({jsonrpc: '2.0', id: 1, method: 'initialize', params: { - protocolVersion: '2025-11-25', capabilities: {}, clientInfo: {name: 'retirement-test', version: '1'}}}) + session.handle( + { + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { + protocolVersion: "2025-11-25", + capabilities: { + }, + clientInfo: { + name: "retirement-test", + version: "1" + } + } + } + ) register = session.method(:register_in_flight) unregisters = 0 session.define_singleton_method(:register_in_flight) do |id| - register.call(id).tap do |cancellation| - original = cancellation.method(:off_cancel) - cancellation.define_singleton_method(:off_cancel) do |callback| - unregisters += 1 - raise IOError, 'injected unregister after native RESULT' if unregisters == 1 + register + .call(id) + .tap do |cancellation| + original = cancellation.method(:off_cancel) + cancellation.define_singleton_method(:off_cancel) do |callback| + unregisters += 1 + raise IOError, "injected unregister after native RESULT" if unregisters == 1 - original.call(callback) + original.call(callback) + end end - end end - reply = session.handle({jsonrpc: '2.0', id: 2, method: 'tools/call', params: { - name: 'tmux_run', arguments: {target: {generation: pane.ref.binding_key, kind: 'pane', id: pane.id}, - script: 'exit 11', stdout_limit: 0, stderr_limit: 0}}}) - structured = JSON.parse(JSON.generate(reply)).dig('result', 'structuredContent') - refute_nil structured, 'callback retirement discarded the structured completion receipt' - error = structured.fetch('error') - assert_equal 'transport_error', error.fetch('code') - assert_equal 'observed', error.fetch('delivery') - assert_equal 'authorized', error.fetch('effects').fetch('authorization').fetch('state') - assert_equal({'state' => 'exited', 'exit_status' => 11, 'signal' => nil}, error.fetch('effects').fetch('completion')) + reply = + session.handle( + { + jsonrpc: "2.0", + id: 2, + method: "tools/call", + params: { + name: "tmux_run", + arguments: { + target: { + generation: pane.ref.binding_key, + kind: "pane", + id: pane.id + }, + script: "exit 11", + stdout_limit: 0, + stderr_limit: 0 + } + } + } + ) + structured = JSON.parse(JSON.generate(reply)).dig("result", "structuredContent") + refute_nil structured, "callback retirement discarded the structured completion receipt" + error = structured.fetch("error") + assert_equal "transport_error", error.fetch("code") + assert_equal "observed", error.fetch("delivery") + assert_equal "authorized", error.fetch("effects").fetch("authorization").fetch("state") + assert_equal( + { "state" => "exited", "exit_status" => 11, "signal" => nil }, + error.fetch("effects").fetch("completion") + ) application.close assert_equal 2, unregisters end @@ -417,42 +603,63 @@ def test_failed_protocol_constructors_keep_native_references_and_socket_paths_ow before_paths = Dir.children(directory) original_hex, original_socket = SecureRandom.method(:hex), UNIXServer.method(:new) created = nil - SecureRandom.define_singleton_method(:hex) { |count| count == 32 ? raise(IOError, 'injected authorization allocation failure') : original_hex.call(count) } + SecureRandom.define_singleton_method(:hex) do |count| + if count == 32 + raise(IOError, "injected authorization allocation failure") + else + original_hex.call(count) + end + end UNIXServer.define_singleton_method(:new) { |*args| created = original_socket.call(*args) } - assert_raises(IOError) { registry.prepare(pane.ref, script_digest: Digest::SHA256.hexdigest('exit 0')) } - assert created.closed?, 'failed helper construction must close its provisional listener' + assert_raises(IOError) do + registry.prepare(pane.ref, script_digest: Digest::SHA256.hexdigest("exit 0")) + end + assert created.closed?, "failed helper construction must close its provisional listener" assert_equal before_paths, Dir.children(directory) assert_equal before_references, identity.instance_variable_get(:@references) SecureRandom.define_singleton_method(:hex, original_hex) UNIXServer.define_singleton_method(:new, original_socket) channel = registry.instance_variable_get(:@enrollments).fetch(pane.ref).channel channel.define_singleton_method(:write) do |_line, _budget| - io.write_nonblock('P ') - raise LibTmux::DeadlineExceeded.new('injected partial preparation write', delivery: :possibly_sent) + io.write_nonblock("P ") + raise LibTmux::DeadlineExceeded.new( + "injected partial preparation write", + delivery: :possibly_sent + ) + end + assert_raises(LibTmux::DeadlineExceeded) do + registry.prepare(pane.ref, script_digest: Digest::SHA256.hexdigest("exit 0")) end - assert_raises(LibTmux::DeadlineExceeded) { registry.prepare(pane.ref, script_digest: Digest::SHA256.hexdigest('exit 0')) } - assert channel.io.closed?, 'ambiguous preparation must retire the corrupted enrollment stream' + assert channel.io.closed?, "ambiguous preparation must retire the corrupted enrollment stream" refute registry.instance_variable_get(:@enrollments).key?(pane.ref) ensure SecureRandom.define_singleton_method(:hex, original_hex) if original_hex UNIXServer.define_singleton_method(:new, original_socket) if original_socket created&.close unless created&.closed? - (Dir.children(directory) - before_paths).each { |name| File.unlink(File.join(directory, name)) } if directory + if directory + (Dir.children(directory) - before_paths).each do |name| + File.unlink(File.join(directory, name)) + end + end identity.close if identity && identity.instance_variable_get(:@references) > before_references end - acceptor = lambda do |registry, invitation| - klass = LibTmux::MCP.const_get(:EnrollmentRegistry)::Enrollment - identity = invitation.capture.process - original_new = klass.method(:new) - klass.define_singleton_method(:new) { |*| raise IOError, 'injected enrollment construction failure' } - assert_raises(IOError) { registry.accept(invitation) } - assert identity.io.closed?, 'failed enrollment construction must release every native reference' - nil - ensure - klass.define_singleton_method(:new, original_new) - identity.close unless identity.io.closed? - end - with_shell(acceptor: acceptor) { } + acceptor = + lambda do |registry, invitation| + klass = LibTmux::MCP.const_get(:EnrollmentRegistry)::Enrollment + identity = invitation.capture.process + original_new = klass.method(:new) + klass.define_singleton_method(:new) do |*| + raise IOError, "injected enrollment construction failure" + end + assert_raises(IOError) { registry.accept(invitation) } + assert identity.io.closed?, + "failed enrollment construction must release every native reference" + nil + ensure + klass.define_singleton_method(:new, original_new) + identity.close unless identity.io.closed? + end + with_shell(acceptor: acceptor) {} end private @@ -464,8 +671,8 @@ def fixture_handoff(stage) flunk "#{stage} did not complete within 2 seconds\n#{(error.backtrace + stacks).join("\n")}" end - def read_line(io, stage: 'shell control frame') - result = +'' + def read_line(io, stage: "shell control frame") + result = +"" fixture_handoff(stage) do until result.end_with?("\n") value = io.read_nonblock(1, exception: false) @@ -482,14 +689,14 @@ def read_line(io, stage: 'shell control frame') end def with_shell(acceptor: nil, space_paths: false, app_tools: nil) - Dir.mktmpdir(space_paths ? '' : 'libtmux-ruby-enrollment-test-') do |directory| + Dir.mktmpdir(space_paths ? "" : "libtmux-ruby-enrollment-test-") do |directory| if space_paths - directory = File.join(directory, 'x y') + directory = File.join(directory, "x y") Dir.mkdir(directory) end - path = File.join(directory, 'test-control') + path = File.join(directory, "test-control") UNIXServer.open(path) do |listener| - File.write(File.join(directory, '.zshrc'), <<~ZSH) + File.write(File.join(directory, ".zshrc"), <<~ZSH) zmodload zsh/net/socket zsocket '#{path}' || exit 80 typeset -g test_control=$REPLY @@ -510,33 +717,73 @@ def with_shell(acceptor: nil, space_paths: false, app_tools: nil) zle -N zle-line-init test_ready ZSH LibTmuxTest::TmuxFixture.open do |fixture| - LibTmux::Server.open(socket_path: fixture.socket_path, executable: fixture.executable) do |source| + LibTmux::Server.open( + socket_path: fixture.socket_path, + executable: fixture.executable + ) do |source| Async do |task| LibTmux::Async.open(server: source, parent: task) do |scope| begin - previous_tmpdir = ENV['TMPDIR'] - begin - ENV['TMPDIR'] = directory if space_paths - registry = if app_tools - LibTmux::MCP::Application.new(server: scope.server, endpoint_name: 'enrolled', enabled_tools: app_tools, request_timeout: 0.5) - else - LibTmux::MCP.const_get(:EnrollmentRegistry).new(server: scope.server, parent: task) + previous_tmpdir = ENV["TMPDIR"] + begin + ENV["TMPDIR"] = directory if space_paths + registry = + if app_tools + LibTmux::MCP::Application.new( + server: scope.server, + endpoint_name: "enrolled", + enabled_tools: app_tools, + request_timeout: 0.5 + ) + else + LibTmux::MCP.const_get(:EnrollmentRegistry).new( + server: scope.server, + parent: task + ) + end + ensure + previous_tmpdir ? ENV["TMPDIR"] = previous_tmpdir : ENV.delete("TMPDIR") end - ensure - previous_tmpdir ? ENV['TMPDIR'] = previous_tmpdir : ENV.delete('TMPDIR') - end - pane = scope.server.new_session(name: 'enrolled', command: ['/usr/bin/env', "ZDOTDIR=#{directory}", '/bin/zsh', '-d', '-i']).list_panes.first - channel = fixture_handoff('enrollment shell connection') { listener.accept } - assert_equal 'initializing', read_line(channel, stage: 'enrollment shell initialization') - invitation = app_tools ? registry.invite_shell(pane.ref, timeout: 0.5) : registry.invite(pane.ref, timeout: 0.5) - fixture_handoff('enrollment shell invitation') { channel.puts invitation.shell_arguments } - enrollment = if app_tools - registry.accept_shell(invitation, timeout: 0.5) - else - acceptor ? acceptor.call(registry, invitation) : registry.accept(invitation, timeout: 0.5) - end - assert_equal pane.id, (app_tools ? enrollment : enrollment.reference).id if enrollment - assert_equal(enrollment ? 'ready' : 'refused', read_line(channel, stage: 'enrollment shell acknowledgement')) + pane = + scope + .server + .new_session( + name: "enrolled", + command: ["/usr/bin/env", "ZDOTDIR=#{directory}", "/bin/zsh", "-d", "-i"] + ) + .list_panes + .first + channel = fixture_handoff("enrollment shell connection") { listener.accept } + assert_equal "initializing", + read_line(channel, stage: "enrollment shell initialization") + invitation = + ( + if app_tools + registry.invite_shell(pane.ref, timeout: 0.5) + else + registry.invite(pane.ref, timeout: 0.5) + end + ) + fixture_handoff("enrollment shell invitation") do + channel.puts invitation.shell_arguments + end + enrollment = + if app_tools + registry.accept_shell(invitation, timeout: 0.5) + else + if acceptor + acceptor.call(registry, invitation) + else + registry.accept(invitation, timeout: 0.5) + end + end + if enrollment + assert_equal pane.id, (app_tools ? enrollment : enrollment.reference).id + end + assert_equal( + enrollment ? "ready" : "refused", + read_line(channel, stage: "enrollment shell acknowledgement") + ) yield registry, pane, channel, scope, source, directory ensure registry&.close diff --git a/test/integration/mcp_mutation_test.rb b/test/integration/mcp_mutation_test.rb index f3ad88e9..6b1583dc 100644 --- a/test/integration/mcp_mutation_test.rb +++ b/test/integration/mcp_mutation_test.rb @@ -9,56 +9,111 @@ class MCPMutationTest < Minitest::Test def test_opt_in_sdk_mutations_create_exact_entities_and_separate_text_from_keys with_application do |app, sdk, scope, source, fixture| - created = invoke(sdk, "tmux_create", kind: "session", name: 'literal-#{session_id};', - window_name: 'initial-#{pane_id};', argv: ["cat"]) + created = + invoke( + sdk, + "tmux_create", + kind: "session", + name: 'literal-#{session_id};', + window_name: 'initial-#{pane_id};', + argv: ["cat"] + ) assert created.fetch("ok"), created.inspect session = created.fetch("data").fetch("entity") assert_equal "session", session.fetch("kind") - assert_equal %w[session window pane], created.fetch("data").fetch("created").map { |ref| ref.fetch("kind") } + assert_equal %w[session window pane], + created.fetch("data").fetch("created").map { |ref| ref.fetch("kind") } assert_equal "unobserved", created.fetch("data").fetch("program_completion") result_file = File.join(File.dirname(fixture.socket_path), "received.json") - receiver = 'File.binwrite(ARGV[0], Marshal.dump([STDIN.gets, Dir.pwd, ENV["MCP_LITERAL"], ARGV[2]])); system("tmux", "-S", ARGV[1], "wait-for", "-S", "mcp-received"); STDIN.read' - window = invoke(sdk, "tmux_create", kind: "window", parent: session, name: 'window-#{window_id};', - index: 3, cwd: File.dirname(fixture.socket_path), environment: {MCP_LITERAL: "env;literal"}, - argv: [Gem.ruby, "--disable=rubyopt,gems", "-e", receiver, result_file, fixture.socket_path, "argv;literal"]) + receiver = + 'File.binwrite(ARGV[0], Marshal.dump([STDIN.gets, Dir.pwd, ENV["MCP_LITERAL"], ARGV[2]])); system("tmux", "-S", ARGV[1], "wait-for", "-S", "mcp-received"); STDIN.read' + window = + invoke( + sdk, + "tmux_create", + kind: "window", + parent: session, + name: 'window-#{window_id};', + index: 3, + cwd: File.dirname(fixture.socket_path), + environment: { + MCP_LITERAL: "env;literal" + }, + argv: [ + Gem.ruby, + "--disable=rubyopt,gems", + "-e", + receiver, + result_file, + fixture.socket_path, + "argv;literal" + ] + ) assert window.fetch("ok"), window.inspect window_data = window.fetch("data") pane = window_data.fetch("created").find { |ref| ref.fetch("kind") == "pane" } text = 'literal; #{pane_id} Enter' - sent = invoke(sdk, "tmux_send", target: pane, input: {type: "text", text: text}) + sent = invoke(sdk, "tmux_send", target: pane, input: { type: "text", text: text }) assert sent.fetch("ok"), sent.inspect assert_equal "dispatch_only", sent.fetch("data").fetch("completion") refute File.exist?(result_file) - assert invoke(sdk, "tmux_send", target: pane, input: {type: "keys", keys: ["Enter"]}).fetch("ok") + assert invoke(sdk, "tmux_send", target: pane, input: { type: "keys", keys: ["Enter"] }).fetch( + "ok" + ) scope.server.wait_for("mcp-received", timeout: 0.5) - assert_equal [text + "\n", File.realpath(File.dirname(fixture.socket_path)), "env;literal", "argv;literal"], Marshal.load(File.binread(result_file)) + assert_equal [ + text + "\n", + File.realpath(File.dirname(fixture.socket_path)), + "env;literal", + "argv;literal" + ], + Marshal.load(File.binread(result_file)) - split = invoke(sdk, "tmux_create", kind: "pane", parent: pane, direction: "vertical", size: "25%", argv: ["cat"]) + split = + invoke( + sdk, + "tmux_create", + kind: "pane", + parent: pane, + direction: "vertical", + size: "25%", + argv: ["cat"] + ) assert split.fetch("ok"), split.inspect split_ref = split.fetch("data").fetch("entity") assert_equal [split_ref], split.fetch("data").fetch("created") snapshot = scope.server.snapshot - assert_equal 'literal-#{session_id};', snapshot.sessions.find { |record| record.id == session.fetch("id") }.name - link = snapshot.window_links.find { |record| record.window_id == window_data.fetch("entity").fetch("id") } + assert_equal 'literal-#{session_id};', + snapshot.sessions.find { |record| record.id == session.fetch("id") }.name + link = + snapshot.window_links.find do |record| + record.window_id == window_data.fetch("entity").fetch("id") + end assert_equal 3, link.index - assert_equal pane.fetch("id"), snapshot.panes.find { |record| record.id == pane.fetch("id") }.id + assert_equal pane.fetch("id"), + snapshot.panes.find { |record| record.id == pane.fetch("id") }.id [split_ref, window_data.fetch("entity"), session].each do |ref| closed = invoke(sdk, "tmux_close", target: ref) assert closed.fetch("ok"), closed.inspect assert_equal 0, closed.fetch("data").fetch("client_exit_status") end - assert source.run(["has-session", "-t", "fixture"]).success? + assert source.run(%w[has-session -t fixture]).success? end end def test_default_policy_and_invalid_or_foreign_targets_refuse_before_mutation with_application do |app, sdk, scope, source, fixture| restricted = LibTmux::MCP::Application.new(server: scope.server, endpoint_name: "test") - list = restricted.sdk_server.handle({jsonrpc: "2.0", id: 1, method: "tools/list"}) - assert_equal %w[tmux_capabilities tmux_snapshot], list.fetch(:result).fetch(:tools).map { |tool| tool.fetch(:name) } + list = restricted.sdk_server.handle({ jsonrpc: "2.0", id: 1, method: "tools/list" }) + assert_equal %w[tmux_capabilities tmux_snapshot], + list.fetch(:result).fetch(:tools).map { |tool| tool.fetch(:name) } MUTATORS.each do |name| - assert_equal "policy_denied", restricted.call(name, {"PRIVATE_SENTINEL" => "secret"}).structured_content.dig("error", "code") + assert_equal "policy_denied", + restricted + .call(name, { "PRIVATE_SENTINEL" => "secret" }) + .structured_content + .dig("error", "code") end snapshot = scope.server.snapshot local = snapshot.panes.first.ref @@ -70,57 +125,119 @@ def test_default_policy_and_invalid_or_foreign_targets_refuse_before_mutation assert_equal "stale_target", denied.dig("error", "code") assert_equal "not_sent", denied.dig("error", "delivery") end - malformed = invoke(sdk, "tmux_send", target: pane, input: {type: "text", text: "private", keys: ["Enter"]}) + malformed = + invoke( + sdk, + "tmux_send", + target: pane, + input: { + type: "text", + text: "private", + keys: ["Enter"] + } + ) assert_equal "invalid_input", malformed.dig("error", "code") refute_includes JSON.generate(malformed), "private" assert_equal "invalid_input", invoke(sdk, "tmux_send", target: pane).dig("error", "code") missing = pane.merge("id" => "%999999999") - assert_equal "stale_target", invoke(sdk, "tmux_send", target: missing, input: {type: "text", text: "wrong target"}).dig("error", "code") + assert_equal "stale_target", + invoke( + sdk, + "tmux_send", + target: missing, + input: { + type: "text", + text: "wrong target" + } + ).dig("error", "code") acquired = 0 original = scope.server.method(:snapshot) - scope.server.define_singleton_method(:snapshot) { |**options| acquired += 1; original.call(**options) } + scope + .server + .define_singleton_method(:snapshot) do |**options| + acquired += 1 + original.call(**options) + end begin parent = wire_ref(snapshot.sessions.first.ref) [["valid", [""]], ["", ["cat"]]].each do |name, argv| - invalid = invoke(sdk, "tmux_create", kind: "window", parent: parent, name: name, argv: argv) + invalid = + invoke(sdk, "tmux_create", kind: "window", parent: parent, name: name, argv: argv) assert_equal "invalid_input", invalid.dig("error", "code") end - oversized = invoke(sdk, "tmux_send", target: pane, input: {type: "text", text: "é" * 32_769}) + oversized = + invoke(sdk, "tmux_send", target: pane, input: { type: "text", text: "é" * 32_769 }) assert_equal "capacity", oversized.dig("error", "code") assert_equal "none", oversized.dig("error", "effects", "state") cancelled = ::MCP::Cancellation.new(request_id: 30) cancelled.cancel - response = app.call("tmux_close", {"target" => pane}, cancellation: cancelled).structured_content + response = + app.call("tmux_close", { "target" => pane }, cancellation: cancelled).structured_content assert_equal "cancelled", response.dig("error", "code") assert_equal "not_sent", response.dig("error", "delivery") assert_equal 0, acquired ensure scope.server.define_singleton_method(:snapshot, original) end - assert source.run(["has-session", "-t", "fixture"]).success? + assert source.run(%w[has-session -t fixture]).success? end end def test_mutation_response_capacity_is_reserved_before_any_creation with_application do |app, sdk, scope, source, fixture| assert_raises(ArgumentError) do - LibTmux::MCP::Application.new(server: scope.server, endpoint_name: "small", enabled_tools: ["tmux_create"], max_response_bytes: 4095) + LibTmux::MCP::Application.new( + server: scope.server, + endpoint_name: "small", + enabled_tools: ["tmux_create"], + max_response_bytes: 4095 + ) end tool = app.tools.find { |entry| entry.name_value == "tmux_create" } - refs = [["session", "$"], ["window", "@"], ["pane", "%"]].map do |kind, prefix| - {"generation" => "\u0001" * 128, "kind" => kind, "id" => prefix + "9" * 31} - end - success = {"ok" => true, "data" => {"entity" => refs.first, "created" => refs, - "delivery" => "observed", "program_completion" => "unobserved"}} - failure = {"ok" => false, "error" => {"code" => "capacity", "message" => "The operation could not establish its requested result.", - "delivery" => "observed", "effects" => {"state" => "known", "created" => refs}}} + refs = + [%w[session $], %w[window @], %w[pane %]].map do |kind, prefix| + { "generation" => "\u0001" * 128, "kind" => kind, "id" => prefix + "9" * 31 } + end + success = { + "ok" => true, + "data" => { + "entity" => refs.first, + "created" => refs, + "delivery" => "observed", + "program_completion" => "unobserved" + } + } + failure = { + "ok" => false, + "error" => { + "code" => "capacity", + "message" => "The operation could not establish its requested result.", + "delivery" => "observed", + "effects" => { + "state" => "known", + "created" => refs + } + } + } [success, failure].each do |structured| tool.output_schema_value.validate_result(structured) - response = ::MCP::Tool::Response.new([{type: "text", text: "tmux_create completed; structuredContent contains the result."}], structured_content: structured) + response = + ::MCP::Tool::Response.new( + [ + { + type: "text", + text: "tmux_create completed; structuredContent contains the result." + } + ], + structured_content: structured + ) assert_operator JSON.generate(response.to_h).bytesize, :<=, 4096 end app.define_singleton_method(:validate_response_size) do |structured| - raise LibTmux::CapacityError.new("injected final response admission failure", delivery: :observed) + raise LibTmux::CapacityError.new( + "injected final response admission failure", + delivery: :observed + ) end result = invoke(sdk, "tmux_create", kind: "session", name: "known-effect", argv: ["cat"]) assert_equal "capacity", result.dig("error", "code") @@ -133,55 +250,112 @@ def test_mutation_response_capacity_is_reserved_before_any_creation def test_one_deadline_covers_acquisition_and_mutation_and_preserves_unknown_effects with_application(request_timeout: 0.1) do |app, sdk, scope, source, fixture| - diagnose = lambda do |phase, &operation| - operation.call - rescue LibTmux::Error => error - warn JSON.generate(test: name, phase: phase, error: error.class.name, message: error.message, - delivery: error.delivery, process_phase: error.phase, pid: error.pid, - cleanup_errors: error.cleanup_errors.map { |item| item.class.name }) - raise - end + diagnose = + lambda do |phase, &operation| + operation.call + rescue LibTmux::Error => error + warn JSON.generate( + test: name, + phase: phase, + error: error.class.name, + message: error.message, + delivery: error.delivery, + process_phase: error.phase, + pid: error.pid, + cleanup_errors: error.cleanup_errors.map { |item| item.class.name } + ) + raise + end parent = ::Async::Task.current - session = wire_ref(diagnose.call("initial snapshot") { scope.server.snapshot }.sessions.first.ref) + session = + wire_ref(diagnose.call("initial snapshot") { scope.server.snapshot }.sessions.first.ref) seen = [] - scope.server.define_singleton_method(:snapshot) do |**options| - seen << [:capture, options.fetch(:timeout), options.fetch(:cancel)] - super(**options) - end - scope.server.define_singleton_method(:create_window) do |ref, **options| - seen << [:mutation, options.fetch(:timeout), options.fetch(:cancel)] - super(ref, **options) - end - source.hooks.set("after-new-window", command: "wait-for -S mcp-created ; wait-for mcp-create-held", index: 93) + scope + .server + .define_singleton_method(:snapshot) do |**options| + seen << [:capture, options.fetch(:timeout), options.fetch(:cancel)] + super(**options) + end + scope + .server + .define_singleton_method(:create_window) do |ref, **options| + seen << [:mutation, options.fetch(:timeout), options.fetch(:cancel)] + super(ref, **options) + end + source.hooks.set( + "after-new-window", + command: "wait-for -S mcp-created ; wait-for mcp-create-held", + index: 93 + ) begin - pending = parent.async { invoke(sdk, "tmux_create", kind: "window", parent: session, name: "partial-effect", argv: ["cat"]) } + pending = + parent.async do + invoke( + sdk, + "tmux_create", + kind: "window", + parent: session, + name: "partial-effect", + argv: ["cat"] + ) + end diagnose.call("create readiness") { scope.server.wait_for("mcp-created", timeout: 0.5) } failure = diagnose.call("create pending result") { pending.wait(timeout: 0.5) } assert_equal "deadline", failure.dig("error", "code") assert_equal "possibly_sent", failure.dig("error", "delivery") - assert_equal({"state" => "unknown", "created" => []}, failure.dig("error", "effects")) + assert_equal({ "state" => "unknown", "created" => [] }, failure.dig("error", "effects")) assert_operator seen.fetch(1).fetch(1), :<, seen.fetch(0).fetch(1) assert_same seen.fetch(0).fetch(2), seen.fetch(1).fetch(2) - assert diagnose.call("created-window readback") { scope.server.run(["list-windows", "-a", "-F", '#{window_name}']) }.text.lines.any? { |line| line.chomp == "partial-effect" } + assert diagnose + .call("created-window readback") { + scope.server.run(%w[list-windows -a -F #{window_name}]) + } + .text + .lines + .any? { |line| line.chomp == "partial-effect" } ensure - diagnose.call("create-release cleanup") { scope.server.wait_for("mcp-create-held", action: :signal, timeout: 0.5) } + diagnose.call("create-release cleanup") do + scope.server.wait_for("mcp-create-held", action: :signal, timeout: 0.5) + end source.hooks.unset("after-new-window", index: 93) end # The snapshot reads the server identity with the run-shell probe. - source.options.set("command-alias", "run-shel=wait-for -S mcp-acquire-ready ; wait-for mcp-acquire-held ; run-shell", index: 93) + source.options.set( + "command-alias", + "run-shel=wait-for -S mcp-acquire-ready ; wait-for mcp-acquire-held ; run-shell", + index: 93 + ) begin - pending = parent.async { invoke(sdk, "tmux_create", kind: "window", parent: session, name: "never-dispatched", argv: ["cat"]) } - diagnose.call("acquisition readiness") { scope.server.wait_for("mcp-acquire-ready", timeout: 0.5) } + pending = + parent.async do + invoke( + sdk, + "tmux_create", + kind: "window", + parent: session, + name: "never-dispatched", + argv: ["cat"] + ) + end + diagnose.call("acquisition readiness") do + scope.server.wait_for("mcp-acquire-ready", timeout: 0.5) + end failure = diagnose.call("acquisition pending result") { pending.wait(timeout: 0.5) } assert_equal "deadline", failure.dig("error", "code") assert_equal "not_sent", failure.dig("error", "delivery") - assert_equal({"state" => "none", "created" => []}, failure.dig("error", "effects")) + assert_equal({ "state" => "none", "created" => [] }, failure.dig("error", "effects")) ensure - diagnose.call("acquisition-release cleanup") { scope.server.wait_for("mcp-acquire-held", action: :signal, timeout: 0.5) } + diagnose.call("acquisition-release cleanup") do + scope.server.wait_for("mcp-acquire-held", action: :signal, timeout: 0.5) + end source.options.unset("command-alias", index: 93) end - refute diagnose.call("final readback") { scope.server.run(["list-windows", "-a", "-F", '#{window_name}']) }.text.lines.any? { |line| line.chomp == "never-dispatched" } + refute diagnose + .call("final readback") { scope.server.run(%w[list-windows -a -F #{window_name}]) } + .text + .lines + .any? { |line| line.chomp == "never-dispatched" } end end @@ -192,11 +366,30 @@ def with_application(**options) LibTmux::Server.open(socket_path: fixture.socket_path) do |source| Async do |task| LibTmux::Async.open(server: source, parent: task) do |scope| - app = LibTmux::MCP::Application.new(server: scope.server, endpoint_name: "test", - enabled_tools: %w[tmux_capabilities tmux_snapshot] + MUTATORS, **options) + app = + LibTmux::MCP::Application.new( + server: scope.server, + endpoint_name: "test", + enabled_tools: %w[tmux_capabilities tmux_snapshot] + MUTATORS, + **options + ) sdk = app.sdk_server - sdk.handle({jsonrpc: "2.0", id: 1, method: "initialize", params: { - protocolVersion: "2025-11-25", capabilities: {}, clientInfo: {name: "test", version: "1"}}}) + sdk.handle( + { + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { + protocolVersion: "2025-11-25", + capabilities: { + }, + clientInfo: { + name: "test", + version: "1" + } + } + } + ) yield app, sdk, scope, source, fixture end end.wait @@ -205,11 +398,22 @@ def with_application(**options) end def invoke(sdk, name, **arguments) - response = sdk.handle({jsonrpc: "2.0", id: 2, method: "tools/call", params: {name: name, arguments: arguments}}) + response = + sdk.handle( + { + jsonrpc: "2.0", + id: 2, + method: "tools/call", + params: { + name: name, + arguments: arguments + } + } + ) JSON.parse(JSON.generate(response)).fetch("result").fetch("structuredContent") end def wire_ref(ref) - {"generation" => ref.binding_key, "kind" => ref.kind.to_s, "id" => ref.id} + { "generation" => ref.binding_key, "kind" => ref.kind.to_s, "id" => ref.id } end end diff --git a/test/integration/mcp_resources_test.rb b/test/integration/mcp_resources_test.rb index 2eb0a76a..dd68a549 100644 --- a/test/integration/mcp_resources_test.rb +++ b/test/integration/mcp_resources_test.rb @@ -6,12 +6,24 @@ class McpResourcesTest < Minitest::Test def request(sdk, method, params = {}) - JSON.parse(JSON.generate(sdk.handle({jsonrpc: "2.0", id: 2, method: method, params: params}))) + JSON.parse(JSON.generate(sdk.handle({ jsonrpc: "2.0", id: 2, method: method, params: params }))) end def initialized(app) app.sdk_server.tap do |sdk| - request(sdk, "initialize", {protocolVersion: "2025-11-25", capabilities: {}, clientInfo: {name: "test", version: "1"}}) + request( + sdk, + "initialize", + { + protocolVersion: "2025-11-25", + capabilities: { + }, + clientInfo: { + name: "test", + version: "1" + } + } + ) end end @@ -27,36 +39,75 @@ def test_metadata_resources_reuse_tool_pages_and_reject_foreign_generation_and_p refute_nil templates assert_equal 2, templates.length assert_equal ["application/json"], templates.map { |item| item.fetch("mimeType") }.uniq - first = app.call("tmux_snapshot", {"entity" => "pane", "limit" => 1}).structured_content.fetch("data") + first = + app + .call("tmux_snapshot", { "entity" => "pane", "limit" => 1 }) + .structured_content + .fetch("data") generation = first.fetch("server_identity").fetch("generation") prefix = "tmux://test/#{generation}/snapshots/pane" cursor = first.fetch("next_cursor").sub(":", "%3A") - result = request(sdk, "resources/read", {uri: "#{prefix}/pages/#{cursor}"}) + result = request(sdk, "resources/read", { uri: "#{prefix}/pages/#{cursor}" }) content = result.fetch("result").fetch("contents").fetch(0) assert_equal "application/json", content.fetch("mimeType") page = JSON.parse(content.fetch("text")).fetch("data") assert_equal first.fetch("capture_id"), page.fetch("capture_id") refute page.fetch("truncated") assert_equal 1, page.fetch("items").length - live = request(sdk, "resources/read", {uri: prefix}) - assert_equal 2, JSON.parse(live.dig("result", "contents", 0, "text")).dig("data", "items").length + live = request(sdk, "resources/read", { uri: prefix }) + assert_equal 2, + JSON + .parse(live.dig("result", "contents", 0, "text")) + .dig("data", "items") + .length other = prefix.sub(generation, "foreign-generation") - assert_equal "stale_target", request(sdk, "resources/read", {uri: other}).dig("error", "data", "code") - assert_equal "invalid_input", request(sdk, "resources/read", {uri: prefix + "/pages/%GG"}).dig("error", "data", "code") - invalid = request(sdk, "resources/read", {uri: "tmux://PRIVATE_PAYLOAD/invalid"}) + assert_equal "stale_target", + request(sdk, "resources/read", { uri: other }).dig("error", "data", "code") + assert_equal "invalid_input", + request(sdk, "resources/read", { uri: prefix + "/pages/%GG" }).dig( + "error", + "data", + "code" + ) + invalid = request(sdk, "resources/read", { uri: "tmux://PRIVATE_PAYLOAD/invalid" }) refute_includes JSON.generate(invalid), "PRIVATE_PAYLOAD" - denied = LibTmux::MCP::Application.new(server: scope.server, endpoint_name: "test", enabled_tools: []) + denied = + LibTmux::MCP::Application.new( + server: scope.server, + endpoint_name: "test", + enabled_tools: [] + ) denied_sdk = initialized(denied) - assert_equal "policy_denied", request(denied_sdk, "resources/read", {uri: prefix}).dig("error", "data", "code") + assert_equal "policy_denied", + request(denied_sdk, "resources/read", { uri: prefix }).dig( + "error", + "data", + "code" + ) pane_id = first.fetch("items").first.fetch("ref").fetch("id") - screen_uri = "tmux://test/#{generation}/panes/#{pane_id.sub('%', '%25')}/screen" - assert_equal "policy_denied", request(sdk, "resources/read", {uri: screen_uri}).dig("error", "data", "code") - observer = LibTmux::MCP::Application.new(server: scope.server, endpoint_name: "test", enabled_tools: ["tmux_capture"]) + screen_uri = "tmux://test/#{generation}/panes/#{pane_id.sub("%", "%25")}/screen" + assert_equal "policy_denied", + request(sdk, "resources/read", { uri: screen_uri }).dig( + "error", + "data", + "code" + ) + observer = + LibTmux::MCP::Application.new( + server: scope.server, + endpoint_name: "test", + enabled_tools: ["tmux_capture"] + ) observer_sdk = initialized(observer) - screen = request(observer_sdk, "resources/read", {uri: screen_uri}).dig("result", "contents", 0) + screen = + request(observer_sdk, "resources/read", { uri: screen_uri }).dig( + "result", + "contents", + 0 + ) refute_nil screen assert_equal "text/plain", screen.fetch("mimeType") metadata = screen.fetch("_meta").fetch("io.github.libtmux/capture") @@ -64,7 +115,12 @@ def test_metadata_resources_reuse_tool_pages_and_reject_foreign_generation_and_p assert_equal "unknown", metadata.fetch("history_continuity") assert_nil metadata.fetch("process_generation") malformed = screen_uri.sub("%25", "%") - assert_equal "invalid_input", request(observer_sdk, "resources/read", {uri: malformed}).dig("error", "data", "code") + assert_equal "invalid_input", + request(observer_sdk, "resources/read", { uri: malformed }).dig( + "error", + "data", + "code" + ) [app, denied, observer].each(&:close) end diff --git a/test/integration/mcp_transport_test.rb b/test/integration/mcp_transport_test.rb index a2f8b972..1c98fcb6 100644 --- a/test/integration/mcp_transport_test.rb +++ b/test/integration/mcp_transport_test.rb @@ -10,15 +10,28 @@ def test_sdk_modern_and_handshake_lifecycles_keep_envelopes_and_state_separate Async do |parent| %w[2024-11-05 2025-03-26 2025-06-18 2025-11-25].each do |version| with_transport(parent) do |transport, input, output| - send_frame(input, request(1, "initialize", protocolVersion: version, capabilities: {}, clientInfo: {name: "legacy", version: "1"})) + send_frame( + input, + request( + 1, + "initialize", + protocolVersion: version, + capabilities: { + }, + clientInfo: { + name: "legacy", + version: "1" + } + ) + ) assert_equal version, read_frame(parent, output).dig("result", "protocolVersion") - send_frame(input, {jsonrpc: "2.0", method: "notifications/initialized"}) + send_frame(input, { jsonrpc: "2.0", method: "notifications/initialized" }) send_frame(input, request(2, "custom/echo", value: "legacy")) response = read_frame(parent, output) assert_equal "legacy", response.dig("result", "value") refute response.fetch("result").key?("resultType") send_frame(input, request(3, "custom/echo", **modern_params(value: "wrong era"))) - assert_equal(-32600, read_frame(parent, output).dig("error", "code")) + assert_equal(-32_600, read_frame(parent, output).dig("error", "code")) end end with_transport(parent) do |transport, input, output| @@ -29,11 +42,33 @@ def test_sdk_modern_and_handshake_lifecycles_keep_envelopes_and_state_separate assert_equal "modern", result.fetch("value") assert_equal "complete", result.fetch("resultType") send_frame(input, request(3, "custom/echo", value: "missing envelope")) - assert_equal(-32602, read_frame(parent, output).dig("error", "code")) - send_frame(input, request(4, "initialize", protocolVersion: "2025-11-25", capabilities: {}, clientInfo: {name: "legacy", version: "1"})) - assert_equal(-32601, read_frame(parent, output).dig("error", "code")) - send_frame(input, request(5, "custom/echo", _meta: {"io.modelcontextprotocol/protocolVersion" => "2026-07-28"})) - assert_equal(-32602, read_frame(parent, output).dig("error", "code")) + assert_equal(-32_602, read_frame(parent, output).dig("error", "code")) + send_frame( + input, + request( + 4, + "initialize", + protocolVersion: "2025-11-25", + capabilities: { + }, + clientInfo: { + name: "legacy", + version: "1" + } + ) + ) + assert_equal(-32_601, read_frame(parent, output).dig("error", "code")) + send_frame( + input, + request( + 5, + "custom/echo", + _meta: { + "io.modelcontextprotocol/protocolVersion" => "2026-07-28" + } + ) + ) + assert_equal(-32_602, read_frame(parent, output).dig("error", "code")) end end.wait end @@ -49,8 +84,8 @@ def test_reader_receives_cancellation_during_real_tmux_wait_and_eof_settles_owne sdk = sdk_server sdk.define_custom_method(method_name: "custom/wait") do |params, server_context:| entered << [Thread.current, server_context.cancellation] - scope.server.run(["wait-for", "-S", "mcp-ready", ";", "wait-for", "mcp-held"], timeout: 0.5) - {finished: true} + scope.server.run(%w[wait-for -S mcp-ready ; wait-for mcp-held], timeout: 0.5) + { finished: true } rescue LibTmux::Cancelled => error cancelled << error raise @@ -61,11 +96,20 @@ def test_reader_receives_cancellation_during_real_tmux_wait_and_eof_settles_owne read_frame(parent, output) send_frame(input, request(2, "custom/wait", **modern_params)) scope.server.wait_for("mcp-ready", timeout: 0.5) - send_frame(input, request(3, "custom/echo", **modern_params(value: "concurrent reader"))) + send_frame( + input, + request(3, "custom/echo", **modern_params(value: "concurrent reader")) + ) assert_equal "concurrent reader", read_frame(parent, output).dig("result", "value") refute entered.first.last.cancelled? - send_frame(input, {jsonrpc: "2.0", method: "notifications/cancelled", params: {requestId: 2}}) - send_frame(input, request(4, "custom/echo", **modern_params(value: "reader progressed"))) + send_frame( + input, + { jsonrpc: "2.0", method: "notifications/cancelled", params: { requestId: 2 } } + ) + send_frame( + input, + request(4, "custom/echo", **modern_params(value: "reader progressed")) + ) response = read_frame(parent, output) assert_equal 4, response.fetch("id") assert_equal "reader progressed", response.dig("result", "value") @@ -75,9 +119,11 @@ def test_reader_receives_cancellation_during_real_tmux_wait_and_eof_settles_owne scope.server.wait_for("mcp-ready", timeout: 0.5) input.close end - assert source.run(["has-session", "-t", "fixture"]).success? + assert source.run(%w[has-session -t fixture]).success? assert_equal 2, cancelled.length - cancelled.each { |error| assert_raises(Errno::ECHILD) { Process.waitpid(error.pid, Process::WNOHANG) } } + cancelled.each do |error| + assert_raises(Errno::ECHILD) { Process.waitpid(error.pid, Process::WNOHANG) } + end assert_equal threads_before, Thread.list.length assert_equal fds_before, Dir.children("/proc/self/fd").length if fds_before ensure @@ -91,11 +137,29 @@ def test_reader_receives_cancellation_during_real_tmux_wait_and_eof_settles_owne def test_first_success_locks_the_era_and_modern_context_is_request_local Async do |parent| sdk = sdk_server - sdk.define_custom_method(method_name: "custom/held") { |_, server_context:| ::Async::Notification.new.wait } + sdk.define_custom_method(method_name: "custom/held") do |_, server_context:| + ::Async::Notification.new.wait + end with_transport(parent, server: sdk) do |_, input, output| send_frame(input, request(1, "custom/held", **modern_params)) - send_frame(input, request(2, "initialize", protocolVersion: "2025-11-25", capabilities: {}, clientInfo: {name: "legacy", version: "1"})) - send_frame(input, {jsonrpc: "2.0", method: "notifications/cancelled", params: {requestId: 1}}) + send_frame( + input, + request( + 2, + "initialize", + protocolVersion: "2025-11-25", + capabilities: { + }, + clientInfo: { + name: "legacy", + version: "1" + } + ) + ) + send_frame( + input, + { jsonrpc: "2.0", method: "notifications/cancelled", params: { requestId: 1 } } + ) assert_equal "2025-11-25", read_frame(parent, output).dig("result", "protocolVersion") end @@ -108,20 +172,27 @@ def test_first_success_locks_the_era_and_modern_context_is_request_local else release.signal end - {client: server_context.client_info&.dig(:name), capabilities: server_context.client_capabilities} + { + client: server_context.client_info&.dig(:name), + capabilities: server_context.client_capabilities + } end with_transport(parent, server: sdk) do |_, input, output| send_frame(input, request(1, "server/discover")) read_frame(parent, output) first = modern_params(wait: true) - first[:_meta]["io.modelcontextprotocol/clientInfo"] = {name: "first", version: "1"} - first[:_meta]["io.modelcontextprotocol/clientCapabilities"] = {first: {}} + first[:_meta]["io.modelcontextprotocol/clientInfo"] = { name: "first", version: "1" } + first[:_meta]["io.modelcontextprotocol/clientCapabilities"] = { first: {} } send_frame(input, request(2, "custom/context", **first)) parent.with_timeout(0.5) { ready.wait } send_frame(input, request(3, "custom/context", **modern_params)) - replies = 2.times.map { read_frame(parent, output) }.to_h { |entry| [entry.fetch("id"), entry.fetch("result")] } + replies = + 2 + .times + .map { read_frame(parent, output) } + .to_h { |entry| [entry.fetch("id"), entry.fetch("result")] } assert_equal "first", replies.fetch(2).fetch("client") - assert_equal({"first" => {}}, replies.fetch(2).fetch("capabilities")) + assert_equal({ "first" => {} }, replies.fetch(2).fetch("capabilities")) assert_nil replies.fetch(3).fetch("client") assert_equal({}, replies.fetch(3).fetch("capabilities")) end @@ -137,7 +208,13 @@ def test_queued_cancellation_and_admission_limits_preserve_reader_progress ::Async::Notification.new.wait {} end - with_transport(parent, server: sdk, concurrency: 1, max_requests: 2, max_request_bytes: 512) do |transport, input, output| + with_transport( + parent, + server: sdk, + concurrency: 1, + max_requests: 2, + max_request_bytes: 512 + ) do |transport, input, output| send_frame(input, request(1, "server/discover")) read_frame(parent, output) send_frame(input, request(2, "custom/held", **modern_params)) @@ -145,11 +222,17 @@ def test_queued_cancellation_and_admission_limits_preserve_reader_progress send_frame(input, request(4, "custom/echo", **modern_params(value: "full"))) refusal = read_frame(parent, output) assert_equal 4, refusal.fetch("id") - assert_equal(-32000, refusal.dig("error", "code")) - send_frame(input, {jsonrpc: "2.0", method: "notifications/cancelled", params: {requestId: 3}}) - send_frame(input, {jsonrpc: "2.0", method: "notifications/cancelled", params: {requestId: 2}}) + assert_equal(-32_000, refusal.dig("error", "code")) + send_frame( + input, + { jsonrpc: "2.0", method: "notifications/cancelled", params: { requestId: 3 } } + ) + send_frame( + input, + { jsonrpc: "2.0", method: "notifications/cancelled", params: { requestId: 2 } } + ) send_frame(input, request(5, "custom/echo", **modern_params(value: "x" * 600))) - assert_equal(-32000, read_frame(parent, output).dig("error", "code")) + assert_equal(-32_000, read_frame(parent, output).dig("error", "code")) send_frame(input, request(6, "custom/echo", **modern_params(value: "alive"))) assert_equal "alive", read_frame(parent, output).dig("result", "value") assert_equal 1, entered @@ -163,24 +246,25 @@ def test_request_deadline_releases_dispatch_capacity sdk.define_custom_method(method_name: "custom/held") { |_| ::Async::Notification.new.wait } with_transport(parent, server: sdk, request_timeout: 0.02) do |_, input, output| send_frame(input, request(1, "custom/held")) - assert_equal(-32000, read_frame(parent, output).dig("error", "code")) + assert_equal(-32_000, read_frame(parent, output).dig("error", "code")) send_frame(input, request(2, "custom/echo", value: "after deadline")) assert_equal "after deadline", read_frame(parent, output).dig("result", "value") end elapsed = 0 - sdk.define_custom_method(method_name: "custom/clock") { |_| elapsed += 1; {expired: true} } + sdk.define_custom_method(method_name: "custom/clock") do |_| + elapsed += 1 + { expired: true } + end with_transport(parent, server: sdk) do |transport, input, output| transport.define_singleton_method(:clock) { super() + elapsed } send_frame(input, request(1, "custom/clock")) - assert_equal(-32000, read_frame(parent, output).dig("error", "code")) + assert_equal(-32_000, read_frame(parent, output).dig("error", "code")) end with_transport(parent) do |transport, input, output| transport.define_singleton_method(:clock) { super() + elapsed } - transport.define_singleton_method(:encode) do |message| - super(message).tap { elapsed += 1 } - end + transport.define_singleton_method(:encode) { |message| super(message).tap { elapsed += 1 } } send_frame(input, request(1, "custom/echo", value: "encoding crossed deadline")) - assert_equal(-32000, read_frame(parent, output).dig("error", "code")) + assert_equal(-32_000, read_frame(parent, output).dig("error", "code")) end end.wait end @@ -189,11 +273,11 @@ def test_malformed_frames_use_sdk_errors_without_dispatching_batches Async do |parent| with_transport(parent) do |transport, input, output| input.write("{\n") - assert_equal(-32700, read_frame(parent, output).dig("error", "code")) + assert_equal(-32_700, read_frame(parent, output).dig("error", "code")) input.write("\xff\n".b) - assert_equal(-32700, read_frame(parent, output).dig("error", "code")) + assert_equal(-32_700, read_frame(parent, output).dig("error", "code")) send_frame(input, [request(1, "custom/echo", value: "batch")]) - assert_equal(-32600, read_frame(parent, output).dig("error", "code")) + assert_equal(-32_600, read_frame(parent, output).dig("error", "code")) send_frame(input, request(2, "custom/echo", value: "survived")) assert_equal "survived", read_frame(parent, output).dig("result", "value") end @@ -206,7 +290,7 @@ def test_input_and_output_byte_limits_and_slow_consumer_fail_with_bounded_cleanu with_transport(parent, max_frame_bytes: 64) { |_, input, _| input.write("x" * 65) } end sdk = sdk_server - sdk.define_custom_method(method_name: "custom/large") { |_| {value: "é" * 200_000} } + sdk.define_custom_method(method_name: "custom/large") { |_| { value: "é" * 200_000 } } assert_raises(LibTmux::CapacityError) do with_transport(parent, server: sdk, max_output_bytes: 512) do |_, input, _| send_frame(input, request(1, "custom/large")) @@ -218,29 +302,36 @@ def test_input_and_output_byte_limits_and_slow_consumer_fail_with_bounded_cleanu sdk.define_custom_method(method_name: "custom/held-large") do |_| handoffs << :request release.wait - {value: "é" * 200_000} + { value: "é" * 200_000 } end - deadline = assert_raises(LibTmux::DeadlineExceeded) do - with_transport(parent, server: sdk, max_output_bytes: 1 << 20, write_timeout: 0.1) do |transport, input, _, runner, writer| - writer.define_singleton_method(:write_nonblock) do |*args, **options| - super(*args, **options).tap do |result| - handoffs << :backpressure if result == :wait_writable + deadline = + assert_raises(LibTmux::DeadlineExceeded) do + with_transport( + parent, + server: sdk, + max_output_bytes: 1 << 20, + write_timeout: 0.1 + ) do |transport, input, _, runner, writer| + writer.define_singleton_method(:write_nonblock) do |*args, **options| + super(*args, **options).tap do |result| + handoffs << :backpressure if result == :wait_writable + end end + send_frame(input, request(1, "custom/held-large")) + await_handoff(parent, handoffs, :request) + begin + observer = + assert_raises(Minitest::Assertion) { observe_transport(runner, timeout: 0.01) } + assert_match(/Test observer timed out/, observer.message) + refute transport.closed? + ensure + release.signal + end + await_handoff(parent, handoffs, :backpressure) + assert_instance_of LibTmux::DeadlineExceeded, observe_transport(runner) + assert transport.closed? end - send_frame(input, request(1, "custom/held-large")) - await_handoff(parent, handoffs, :request) - begin - observer = assert_raises(Minitest::Assertion) { observe_transport(runner, timeout: 0.01) } - assert_match(/Test observer timed out/, observer.message) - refute transport.closed? - ensure - release.signal - end - await_handoff(parent, handoffs, :backpressure) - assert_instance_of LibTmux::DeadlineExceeded, observe_transport(runner) - assert transport.closed? end - end assert_equal :write, deadline.phase assert_equal :possibly_sent, deadline.delivery end.wait @@ -248,10 +339,13 @@ def test_input_and_output_byte_limits_and_slow_consumer_fail_with_bounded_cleanu def test_readiness_waits_use_the_scheduler_without_helper_threads calls = [] - trace = TracePoint.new(:call, :c_call) do |event| - calls << event.method_id if (event.self == IO && event.method_id == :select) || - (event.self == Thread && event.method_id == :new) - end + trace = + TracePoint.new(:call, :c_call) do |event| + if (event.self == IO && event.method_id == :select) || + (event.self == Thread && event.method_id == :new) + calls << event.method_id + end + end Async do |parent| trace.enable do with_transport(parent) do |_, input, output| @@ -265,9 +359,12 @@ def test_readiness_waits_use_the_scheduler_without_helper_threads def test_encoded_output_limit_is_checked_before_allocating_the_wire_frame Async do |parent| - [{value: "\u0001" * 30}, Array.new(100, "")].each do |message| + [{ value: "\u0001" * 30 }, Array.new(100, "")].each do |message| generated = [] - trace = TracePoint.new(:call, :c_call) { |event| generated << true if event.self == JSON && event.method_id == :generate } + trace = + TracePoint.new(:call, :c_call) do |event| + generated << true if event.self == JSON && event.method_id == :generate + end assert_raises(LibTmux::CapacityError) do with_transport(parent, max_output_bytes: 64) do |transport, _, _| trace.enable { transport.send_response(message) } @@ -287,7 +384,8 @@ def test_repeated_cancellation_completes_retirement_before_restoring_sdk_transpo retiring = false input, client_input = IO.pipe client_output, output = IO.pipe - transport = LibTmux::MCP::StdioTransport.new(server: sdk, parent: parent, input: input, output: output) + transport = + LibTmux::MCP::StdioTransport.new(server: sdk, parent: parent, input: input, output: output) transport.define_singleton_method(:read_loop) do super() ensure @@ -295,11 +393,12 @@ def test_repeated_cancellation_completes_retirement_before_restoring_sdk_transpo entered.signal release.wait end - runner = parent.async do - transport.run - rescue Exception => error - error - end + runner = + parent.async do + transport.run + rescue Exception => error + error + end begin send_frame(client_input, request(1, "custom/echo", value: "started")) assert_equal "started", read_frame(parent, client_output).dig("result", "value") @@ -331,14 +430,25 @@ def test_partial_task_startup_failure_retires_the_already_started_writer input, client_input = IO.pipe client_output, output = IO.pipe session_class = LibTmux::MCP::StdioTransport.const_get(:Session) - trace = TracePoint.new(:call) do |event| - raise NoMemoryError, "injected SDK session allocation failure" if event.method_id == :initialize && event.self.is_a?(session_class) - end + trace = + TracePoint.new(:call) do |event| + if event.method_id == :initialize && event.self.is_a?(session_class) + raise NoMemoryError, "injected SDK session allocation failure" + end + end assert_raises(NoMemoryError) do - trace.enable { LibTmux::MCP::StdioTransport.new(server: sdk, parent: parent, input: input, output: output) } + trace.enable do + LibTmux::MCP::StdioTransport.new( + server: sdk, + parent: parent, + input: input, + output: output + ) + end end assert_same previous, sdk.transport - transport = LibTmux::MCP::StdioTransport.new(server: sdk, parent: parent, input: input, output: output) + transport = + LibTmux::MCP::StdioTransport.new(server: sdk, parent: parent, input: input, output: output) count = 0 transport.define_singleton_method(:child_task) do |&block| count += 1 @@ -359,11 +469,13 @@ def test_partial_task_startup_failure_retires_the_already_started_writer assert_raises(NoMemoryError) do with_transport(parent) do |candidate, client, _, runner| failed = candidate - trace = TracePoint.new(:call) do |event| - if event.method_id == :run && candidate.instance_variable_get(:@by_task).key?(event.self) - raise NoMemoryError, "injected request fiber allocation failure" + trace = + TracePoint.new(:call) do |event| + if event.method_id == :run && + candidate.instance_variable_get(:@by_task).key?(event.self) + raise NoMemoryError, "injected request fiber allocation failure" + end end - end trace.enable do send_frame(client, request(1, "custom/echo", value: "never dispatched")) error = runner.wait(timeout: 0.5) @@ -398,29 +510,34 @@ def test_failed_retirement_retains_ownership_until_close_can_retry {} end primary = RuntimeError.new("injected primary failure") - observed = assert_raises(RuntimeError) do - with_transport(parent, server: sdk, cleanup_timeout: 0.02) do |transport, input, _, runner| - send_frame(input, request(1, "custom/cleanup")) - parent.with_timeout(0.5) { ready.wait until handler } - input.close - transport.instance_variable_set(:@failure, primary) - error = runner.wait(timeout: 0.5) - assert_same primary, error - refute_empty error.mcp_cleanup_errors - assert error.mcp_cleanup_errors.frozen? - refute transport.closed? - assert_same transport, sdk.transport - release.signal - handler.wait(timeout: 0.5) - transport.close - assert transport.closed? - assert_same previous, sdk.transport - ensure - release.signal - parent.yield - handler&.cancel + observed = + assert_raises(RuntimeError) do + with_transport( + parent, + server: sdk, + cleanup_timeout: 0.02 + ) do |transport, input, _, runner| + send_frame(input, request(1, "custom/cleanup")) + parent.with_timeout(0.5) { ready.wait until handler } + input.close + transport.instance_variable_set(:@failure, primary) + error = runner.wait(timeout: 0.5) + assert_same primary, error + refute_empty error.mcp_cleanup_errors + assert error.mcp_cleanup_errors.frozen? + refute transport.closed? + assert_same transport, sdk.transport + release.signal + handler.wait(timeout: 0.5) + transport.close + assert transport.closed? + assert_same previous, sdk.transport + ensure + release.signal + parent.yield + handler&.cancel + end end - end assert_same primary, observed end.wait end @@ -428,21 +545,34 @@ def test_failed_retirement_retains_ownership_until_close_can_retry private def sdk_server - sdk = ::MCP::Server.new(name: "transport-test", configuration: ::MCP::Configuration.new(exception_reporter: ->(*) {})) - sdk.define_custom_method(method_name: "custom/echo") { |params, server_context:| {value: params[:value]} } + sdk = + ::MCP::Server.new( + name: "transport-test", + configuration: ::MCP::Configuration.new(exception_reporter: ->(*) {}) + ) + sdk.define_custom_method(method_name: "custom/echo") do |params, server_context:| + { value: params[:value] } + end sdk end def with_transport(parent, server: sdk_server, **limits) input, client_input = IO.pipe client_output, output = IO.pipe - transport = LibTmux::MCP::StdioTransport.new(server: server, parent: parent, input: input, output: output, - **{request_timeout: 0.5}.merge(limits)) - runner = parent.async do - transport.run - rescue Exception => error - error - end + transport = + LibTmux::MCP::StdioTransport.new( + server: server, + parent: parent, + input: input, + output: output, + **{ request_timeout: 0.5 }.merge(limits) + ) + runner = + parent.async do + transport.run + rescue Exception => error + error + end failure = nil begin yield transport, client_input, client_output, runner, output @@ -475,11 +605,17 @@ def observe_transport(runner, timeout: 2) end def request(id, method, **params) - {jsonrpc: "2.0", id: id, method: method, params: params} + { jsonrpc: "2.0", id: id, method: method, params: params } end def modern_params(**params) - params.merge(_meta: {"io.modelcontextprotocol/protocolVersion" => "2026-07-28", "io.modelcontextprotocol/clientCapabilities" => {}}) + params.merge( + _meta: { + "io.modelcontextprotocol/protocolVersion" => "2026-07-28", + "io.modelcontextprotocol/clientCapabilities" => { + } + } + ) end def send_frame(input, frame) diff --git a/test/integration/mcp_wait_test.rb b/test/integration/mcp_wait_test.rb index 17632918..9a7af418 100644 --- a/test/integration/mcp_wait_test.rb +++ b/test/integration/mcp_wait_test.rb @@ -18,7 +18,10 @@ def test_wait_observes_screen_events_and_initial_process_exit target = wire_ref(pane.ref) if control_supported?(scope.server) ready = signal_after_first_capture(app) - pending = Async::Task.current.async { call(app, target, {type: "screen_contains", text: "event-visible"}) } + pending = + Async::Task.current.async do + call(app, target, { type: "screen_contains", text: "event-visible" }) + end await_ready(ready, pending) refute pending.finished? pane.send_text("event-visible") @@ -30,16 +33,21 @@ def test_wait_observes_screen_events_and_initial_process_exit assert_screen_wait_polls(app, scope) end - child = pane.split(direction: :vertical, command: [Gem.ruby, "--disable=rubyopt,gems", "-e", "STDIN.gets"]) + child = + pane.split( + direction: :vertical, + command: [Gem.ruby, "--disable=rubyopt,gems", "-e", "STDIN.gets"] + ) ready = signal_after_first_capture(app) - pending = Async::Task.current.async { call(app, wire_ref(child.ref), {type: "process_exit"}) } + pending = + Async::Task.current.async { call(app, wire_ref(child.ref), { type: "process_exit" }) } await_ready(ready, pending) child.send_keys("Enter") result = pending.wait(timeout: 0.5) assert result.fetch("ok"), "#{result.inspect}; #{@observation_failure.inspect}" assert_equal "process_exit", result.dig("data", "condition") assert_equal "unobserved", result.dig("data", "exit_status") - assert source.run(["has-session", "-t", "fixture"]).success? + assert source.run(%w[has-session -t fixture]).success? end end @@ -50,7 +58,15 @@ def test_deadline_and_sdk_cancellation_close_observers_without_terminating_pane if control_supported?(scope.server) ready = signal_after_first_capture(app) cancellation = ::MCP::Cancellation.new(request_id: 14) - pending = Async::Task.current.async { call(app, target, {type: "screen_contains", text: "never"}, cancellation: cancellation) } + pending = + Async::Task.current.async do + call( + app, + target, + { type: "screen_contains", text: "never" }, + cancellation: cancellation + ) + end await_ready(ready, pending) cancellation.cancel failure = pending.wait(timeout: 0.5) @@ -59,10 +75,10 @@ def test_deadline_and_sdk_cancellation_close_observers_without_terminating_pane else assert_screen_wait_cancels(app, scope) end - failure = call(app, target, {type: "process_exit"}, timeout: 0.1) + failure = call(app, target, { type: "process_exit" }, timeout: 0.1) assert_equal "deadline", failure.dig("error", "code") assert scope.server.snapshot.panes.any? { |entry| entry.id == pane.id && !entry.dead } - assert source.run(["has-session", "-t", "fixture"]).success? + assert source.run(%w[has-session -t fixture]).success? end end @@ -71,11 +87,14 @@ def test_control_gap_and_repeated_cancellation_retire_all_owned_observers pane = scope.server.list_panes.first control = nil factory = scope.server.method(:open_control) - scope.server.define_singleton_method(:open_control) do |**options| - control = factory.call(**options) - end + scope + .server + .define_singleton_method(:open_control) { |**options| control = factory.call(**options) } ready = signal_after_first_capture(app) - pending = Async::Task.current.async { call(app, wire_ref(pane.ref), {type: "screen_contains", text: "absent"}) } + pending = + Async::Task.current.async do + call(app, wire_ref(pane.ref), { type: "screen_contains", text: "absent" }) + end await_ready(ready, pending) begin control.pause_output(pane_id: pane.id, timeout: 0.5) @@ -88,11 +107,12 @@ def test_control_gap_and_repeated_cancellation_retire_all_owned_observers closing = Async::Queue.new held = Async::Queue.new ready = signal_after_first_capture(app) - pending = Async::Task.current.async do - call(app, wire_ref(pane.ref), {type: "screen_contains", text: "absent"}) - rescue Exception => error - error - end + pending = + Async::Task.current.async do + call(app, wire_ref(pane.ref), { type: "screen_contains", text: "absent" }) + rescue Exception => error + error + end await_ready(ready, pending) original = control.method(:close) first = true @@ -112,7 +132,7 @@ def test_control_gap_and_repeated_cancellation_retire_all_owned_observers assert control.closed? assert_raises(Errno::ECHILD) { Process.waitpid(control.pid, Process::WNOHANG) } assert_empty scope.server.list_clients - assert source.run(["has-session", "-t", "fixture"]).success? + assert source.run(%w[has-session -t fixture]).success? end end @@ -121,9 +141,14 @@ def test_pending_control_retirement_keeps_process_descriptors_until_application_ pane = scope.server.list_panes.first control = nil factory = scope.server.method(:open_control) - scope.server.define_singleton_method(:open_control) { |**options| control = factory.call(**options) } + scope + .server + .define_singleton_method(:open_control) { |**options| control = factory.call(**options) } ready = signal_after_first_capture(app) - pending = Async::Task.current.async { call(app, wire_ref(pane.ref), {type: "screen_contains", text: "finish-with-evidence"}) } + pending = + Async::Task.current.async do + call(app, wire_ref(pane.ref), { type: "screen_contains", text: "finish-with-evidence" }) + end await_ready(ready, pending) closer = control.method(:close) allow_close = false @@ -149,7 +174,7 @@ def test_pending_control_retirement_keeps_process_descriptors_until_application_ assert control.closed? assert identity.io.closed? assert_empty app.instance_variable_get(:@retiring) - assert source.run(["has-session", "-t", "fixture"]).success? + assert source.run(%w[has-session -t fixture]).success? ensure allow_close = true end @@ -160,16 +185,20 @@ def test_application_close_cancels_and_joins_an_active_wait_before_returning with_application(control: true) do |app, scope, source| pane = scope.server.list_panes.first ready = signal_after_first_capture(app) - pending = Async::Task.current.async { call(app, wire_ref(pane.ref), {type: "screen_contains", text: "not-present"}) } + pending = + Async::Task.current.async do + call(app, wire_ref(pane.ref), { type: "screen_contains", text: "not-present" }) + end await_ready(ready, pending) refute pending.finished? app.close - assert pending.finished?, "Application.close must join the admitted request's observer cleanup" + assert pending.finished?, + "Application.close must join the admitted request's observer cleanup" assert_equal "cancelled", pending.wait(timeout: 0.5).dig("error", "code") assert_empty app.instance_variable_get(:@observers) assert_empty app.instance_variable_get(:@retiring) assert_empty scope.server.list_clients - assert source.run(["has-session", "-t", "fixture"]).success? + assert source.run(%w[has-session -t fixture]).success? ensure pending.cancel unless pending&.finished? end @@ -180,9 +209,14 @@ def test_application_close_keeps_request_ownership_through_repeated_cancellation pane = scope.server.list_panes.first control = nil factory = scope.server.method(:open_control) - scope.server.define_singleton_method(:open_control) { |**options| control = factory.call(**options) } + scope + .server + .define_singleton_method(:open_control) { |**options| control = factory.call(**options) } ready = signal_after_first_capture(app) - pending = Async::Task.current.async { call(app, wire_ref(pane.ref), {type: "screen_contains", text: "not-present"}) } + pending = + Async::Task.current.async do + call(app, wire_ref(pane.ref), { type: "screen_contains", text: "not-present" }) + end await_ready(ready, pending) closing, release, waiting = Async::Queue.new, Async::Queue.new, Async::Queue.new original = control.method(:close) @@ -197,12 +231,18 @@ def test_application_close_keeps_request_ownership_through_repeated_cancellation waiting.enqueue(true) original_wait.call end - closer = Async::Task.current.async do - app.close - rescue Exception => error - error - end - Async::Task.current.with_timeout(0.5) { closing.dequeue; waiting.dequeue } + closer = + Async::Task.current.async do + app.close + rescue Exception => error + error + end + Async::Task + .current + .with_timeout(0.5) do + closing.dequeue + waiting.dequeue + end 2.times do closer.cancel Async::Task.current.with_timeout(0.5) { waiting.dequeue } @@ -215,7 +255,7 @@ def test_application_close_keeps_request_ownership_through_repeated_cancellation assert_empty app.instance_variable_get(:@calls) assert_empty app.instance_variable_get(:@observers) app.close - assert source.run(["has-session", "-t", "fixture"]).success? + assert source.run(%w[has-session -t fixture]).success? ensure release&.enqueue(true) pending.cancel unless pending&.finished? @@ -227,7 +267,10 @@ def test_wait_finds_text_that_the_pane_wrapped_across_rows pane = scope.server.list_panes.first width = scope.server.snapshot.panes.find { |entry| entry.id == pane.id }.width ready = signal_after_first_capture(app) - pending = Async::Task.current.async { call(app, wire_ref(pane.ref), {type: "screen_contains", text: "ABCDEFGHIJ"}) } + pending = + Async::Task.current.async do + call(app, wire_ref(pane.ref), { type: "screen_contains", text: "ABCDEFGHIJ" }) + end await_ready(ready, pending) refute pending.finished? # The echoed line is wider than the pane, so tmux wraps it between E and F. @@ -243,13 +286,16 @@ def test_wait_for_screen_text_ends_as_pane_died_with_the_output_so_far_when_the_ child = scope.server.list_panes.first.split(direction: :vertical, command: prints_and_waits) await_output_so_far(app, child) ready = signal_after_first_capture(app) - pending = Async::Task.current.async { call(app, wire_ref(child.ref), {type: "screen_contains", text: "never-printed"}) } + pending = + Async::Task.current.async do + call(app, wire_ref(child.ref), { type: "screen_contains", text: "never-printed" }) + end await_ready(ready, pending) refute pending.finished? child.kill failure = pending.wait(timeout: 1) assert_pane_died(failure) - assert source.run(["has-session", "-t", "fixture"]).success? + assert source.run(%w[has-session -t fixture]).success? end end @@ -257,12 +303,19 @@ def test_wait_for_screen_text_ends_as_pane_died_with_the_output_so_far_when_the_ with_application do |app, scope, source| # The pane ignores the hangup that follows the server, so only the # server's own exit tells the wait that the screen is gone. - child = scope.server.list_panes.first.split(direction: :vertical, command: prints_and_ignores_hangup) + child = + scope.server.list_panes.first.split( + direction: :vertical, + command: prints_and_ignores_hangup + ) await_output_so_far(app, child) pid = scope.server.snapshot.panes.find { |entry| entry.id == child.id }.pid begin ready = signal_after_first_capture(app) - pending = Async::Task.current.async { call(app, wire_ref(child.ref), {type: "screen_contains", text: "never-printed"}) } + pending = + Async::Task.current.async do + call(app, wire_ref(child.ref), { type: "screen_contains", text: "never-printed" }) + end await_ready(ready, pending) refute pending.finished? source.run(["kill-server"]) @@ -275,23 +328,50 @@ def test_wait_for_screen_text_ends_as_pane_died_with_the_output_so_far_when_the_ def test_wait_ends_as_pane_died_when_a_stopped_client_keeps_the_killed_server_alive with_application do |app, scope, _source| - child = scope.server.list_panes.first.split(direction: :vertical, command: prints_and_ignores_hangup) + child = + scope.server.list_panes.first.split( + direction: :vertical, + command: prints_and_ignores_hangup + ) await_output_so_far(app, child) pid = scope.server.snapshot.panes.find { |entry| entry.id == child.id }.pid - reader, writer, client = PTY.spawn({"TMUX" => nil}, @fixture.executable, "-S", @fixture.socket_path, "attach", "-t", "fixture") + reader, writer, client = + PTY.spawn( + { "TMUX" => nil }, + @fixture.executable, + "-S", + @fixture.socket_path, + "attach", + "-t", + "fixture" + ) killer = nil begin deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 2 - sleep 0.02 until scope.server.list_clients.any? { |entry| entry.fetch(:pid) == client } || - Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline + until scope.server.list_clients.any? { |entry| entry.fetch(:pid) == client } || + Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline + sleep 0.02 + end ready = signal_after_first_capture(app) - pending = Async::Task.current.async { call(app, wire_ref(child.ref), {type: "screen_contains", text: "never-printed"}) } + pending = + Async::Task.current.async do + call(app, wire_ref(child.ref), { type: "screen_contains", text: "never-printed" }) + end await_ready(ready, pending) refute pending.finished? # tmux stays up until every client leaves, and this one is stopped. Process.kill("STOP", client) - killer = Process.spawn({"TMUX" => nil}, @fixture.executable, "-S", @fixture.socket_path, "kill-server", - in: File::NULL, out: File::NULL, err: File::NULL) + killer = + Process.spawn( + { "TMUX" => nil }, + @fixture.executable, + "-S", + @fixture.socket_path, + "kill-server", + in: File::NULL, + out: File::NULL, + err: File::NULL + ) assert_pane_died(pending.wait(timeout: 2)) ensure begin @@ -315,13 +395,20 @@ def test_the_daemon_probe_behind_wait_results_fires_no_hook result = source.run(["set-hook", "-g", hook, "set-option -g @hook-fired #{hook}"]) assert result.success? || hook == "command-error", result.stderr end - observer = LibTmux::MCP.const_get(:Observation).new(server: scope.server, arguments: {}, timeout: 1, cancel: nil, - max_snapshot_bytes: 1 << 16) + observer = + LibTmux::MCP.const_get(:Observation).new( + server: scope.server, + arguments: { + }, + timeout: 1, + cancel: nil, + max_snapshot_bytes: 1 << 16 + ) assert_equal :alive, observer.__send__(:daemon_state) - assert_equal "", source.run(["show-options", "-gqv", "@hook-fired"]).stdout.to_s + assert_equal "", source.run(%w[show-options -gqv @hook-fired]).stdout.to_s # A command that does fire hooks proves the hooks above are live. - source.run(["display-message", "-p", "x"]) - refute_equal "", source.run(["show-options", "-gqv", "@hook-fired"]).stdout.to_s + source.run(%w[display-message -p x]) + refute_equal "", source.run(%w[show-options -gqv @hook-fired]).stdout.to_s ensure observer&.close end @@ -329,22 +416,37 @@ def test_the_daemon_probe_behind_wait_results_fires_no_hook def test_a_failed_daemon_probe_is_not_a_dead_daemon with_application do |app, scope, _source| - observer = LibTmux::MCP.const_get(:Observation).new(server: scope.server, arguments: {}, timeout: 1, cancel: nil, - max_snapshot_bytes: 1 << 16) + observer = + LibTmux::MCP.const_get(:Observation).new( + server: scope.server, + arguments: { + }, + timeout: 1, + cancel: nil, + max_snapshot_bytes: 1 << 16 + ) probe = ->(failure) do - scope.server.define_singleton_method(:run) do |argv, **| - raise failure if argv.first == "run-shel" + scope + .server + .define_singleton_method(:run) do |argv, **| + raise failure if argv.first == "run-shel" - super(argv) - end + super(argv) + end end probe.call(Errno::EMFILE.new) assert_equal :unknown, observer.__send__(:daemon_state) refute observer.__send__(:ended?, Struct.new(:io, :peer) { def exited? = false }.new) reply = Struct.new(:stderr, :stdout, :success?) - scope.server.define_singleton_method(:run) { |*, **| reply.new("server exited unexpectedly\n", "", false) } + scope + .server + .define_singleton_method(:run) do |*, **| + reply.new("server exited unexpectedly\n", "", false) + end assert_equal :gone, observer.__send__(:daemon_state) - scope.server.define_singleton_method(:run) { |*, **| reply.new("something else\n", "", false) } + scope + .server + .define_singleton_method(:run) { |*, **| reply.new("something else\n", "", false) } assert_equal :unknown, observer.__send__(:daemon_state) ensure observer&.close @@ -357,13 +459,18 @@ def test_wait_reports_a_lost_stream_not_pane_died_when_the_probe_cannot_run next unless control_supported?(scope.server) ready = signal_after_first_capture(app) - pending = Async::Task.current.async { call(app, wire_ref(pane.ref), {type: "screen_contains", text: "never-printed"}) } + pending = + Async::Task.current.async do + call(app, wire_ref(pane.ref), { type: "screen_contains", text: "never-printed" }) + end await_ready(ready, pending) - scope.server.define_singleton_method(:run) do |argv, **options| - raise Errno::EMFILE if argv.first == "run-shel" + scope + .server + .define_singleton_method(:run) do |argv, **options| + raise Errno::EMFILE if argv.first == "run-shel" - super(argv, **options) - end + super(argv, **options) + end clients = scope.server.list_clients assert source.run(["detach-client", "-t", clients.first.fetch(:name)]).success? failure = pending.wait(timeout: 2) @@ -375,7 +482,10 @@ def test_wait_reports_a_lost_stream_when_the_control_client_detaches_from_a_live with_application do |app, scope, source| pane = scope.server.list_panes.first ready = signal_after_first_capture(app) - pending = Async::Task.current.async { call(app, wire_ref(pane.ref), {type: "screen_contains", text: "never-printed"}) } + pending = + Async::Task.current.async do + call(app, wire_ref(pane.ref), { type: "screen_contains", text: "never-printed" }) + end await_ready(ready, pending) if control_supported?(scope.server) clients = scope.server.list_clients @@ -391,7 +501,7 @@ def test_wait_reports_a_lost_stream_when_the_control_client_detaches_from_a_live refute pending.finished? pending.cancel end - assert source.run(["has-session", "-t", "fixture"]).success? + assert source.run(%w[has-session -t fixture]).success? end end @@ -415,8 +525,15 @@ def signal_after_first_capture(app) observer.define_singleton_method(:wait) do wait.call rescue LibTmux::Error => error - test.instance_variable_set(:@observation_failure, - {class: error.class.name, message: error.message, phase: error.phase, cleanup_errors: error.cleanup_errors}) + test.instance_variable_set( + :@observation_failure, + { + class: error.class.name, + message: error.message, + phase: error.phase, + cleanup_errors: error.cleanup_errors + } + ) raise end original = observer.method(:read_rows) @@ -436,7 +553,10 @@ def signal_after_first_capture(app) def assert_screen_wait_polls(app, scope) pane = scope.server.list_panes.first ready = signal_after_first_capture(app) - pending = Async::Task.current.async { call(app, wire_ref(pane.ref), {type: "screen_contains", text: "polled-visible"}) } + pending = + Async::Task.current.async do + call(app, wire_ref(pane.ref), { type: "screen_contains", text: "polled-visible" }) + end await_ready(ready, pending) refute pending.finished? assert_empty scope.server.list_clients @@ -451,9 +571,15 @@ def assert_screen_wait_cancels(app, scope) pane = scope.server.list_panes.first ready = signal_after_first_capture(app) cancellation = ::MCP::Cancellation.new(request_id: 15) - pending = Async::Task.current.async do - call(app, wire_ref(pane.ref), {type: "screen_contains", text: "never-visible"}, cancellation: cancellation) - end + pending = + Async::Task.current.async do + call( + app, + wire_ref(pane.ref), + { type: "screen_contains", text: "never-visible" }, + cancellation: cancellation + ) + end await_ready(ready, pending) cancellation.cancel assert_equal "cancelled", pending.wait(timeout: 0.5).dig("error", "code") @@ -462,18 +588,29 @@ def assert_screen_wait_cancels(app, scope) # A pane program that prints a line and waits for input, as cat would. def prints_and_waits - [Gem.ruby, "--disable=rubyopt,gems", "-e", '$stdout.sync = true; puts "output-so-far"; $stdin.read'] + [ + Gem.ruby, + "--disable=rubyopt,gems", + "-e", + '$stdout.sync = true; puts "output-so-far"; $stdin.read' + ] end # The same program, ignoring the hangup tmux sends when the server exits. def prints_and_ignores_hangup - [Gem.ruby, "--disable=rubyopt,gems", "-e", 'trap("HUP", "IGNORE"); $stdout.sync = true; puts "output-so-far"; sleep'] + [ + Gem.ruby, + "--disable=rubyopt,gems", + "-e", + 'trap("HUP", "IGNORE"); $stdout.sync = true; puts "output-so-far"; sleep' + ] end # The program prints after its setup, so a pane that shows the line has # already ignored the hangup. def await_output_so_far(app, pane) - shown = call(app, wire_ref(pane.ref), {type: "screen_contains", text: "output-so-far"}, timeout: 2) + shown = + call(app, wire_ref(pane.ref), { type: "screen_contains", text: "output-so-far" }, timeout: 2) assert shown.fetch("ok"), shown.inspect end @@ -486,10 +623,18 @@ def assert_pane_died(failure) def with_application(control: false) LibTmuxTest::TmuxFixture.open do |fixture| @fixture = fixture - LibTmux::Server.open(socket_path: fixture.socket_path, executable: fixture.executable) do |source| + LibTmux::Server.open( + socket_path: fixture.socket_path, + executable: fixture.executable + ) do |source| Async do |task| LibTmux::Async.open(server: source, parent: task) do |scope| - app = LibTmux::MCP::Application.new(server: scope.server, endpoint_name: "test", enabled_tools: ["tmux_wait"]) + app = + LibTmux::MCP::Application.new( + server: scope.server, + endpoint_name: "test", + enabled_tools: ["tmux_wait"] + ) begin require_process_cursor_support(scope) if control && !control_supported?(scope.server) @@ -507,10 +652,14 @@ def with_application(control: false) end def call(app, target, condition, cancellation: nil, **options) - app.call("tmux_wait", {target: target, condition: condition, **options}, cancellation: cancellation).structured_content + app.call( + "tmux_wait", + { target: target, condition: condition, **options }, + cancellation: cancellation + ).structured_content end def wire_ref(ref) - {"generation" => ref.binding_key, "kind" => ref.kind.to_s, "id" => ref.id} + { "generation" => ref.binding_key, "kind" => ref.kind.to_s, "id" => ref.id } end end diff --git a/test/integration/operation_budget_test.rb b/test/integration/operation_budget_test.rb index cef28e2b..443b323e 100644 --- a/test/integration/operation_budget_test.rb +++ b/test/integration/operation_budget_test.rb @@ -38,13 +38,16 @@ def test_link_and_copy_preflights_share_the_original_operation_deadline AdvancingServer.open(socket_path: fixture.socket_path) do |server| pane = server.list_panes.first server.advance_after = "list-commands" - assert_raises(LibTmux::DeadlineExceeded) { pane.copy_mode(scroll_up: true, page_down: true, timeout: 0.5) } + assert_raises(LibTmux::DeadlineExceeded) do + pane.copy_mode(scroll_up: true, page_down: true, timeout: 0.5) + end assert_equal "0\n", pane.display('#{pane_in_mode}').text end AdvancingServer.open(socket_path: fixture.socket_path) do |server| pane = server.list_panes.first - usage = server.run(["list-commands", "-F", '#{command_list_usage}', "capture-pane"]).text - supported = usage.scan(/\[-([A-Za-z]+)(?:\]|\s)/).flatten.any? { |flags| flags.include?("M") } + usage = server.run(%w[list-commands -F #{command_list_usage} capture-pane]).text + supported = + usage.scan(/\[-([A-Za-z]+)(?:\]|\s)/).flatten.any? { |flags| flags.include?("M") } server.advance_after = "list-commands" failure = supported ? LibTmux::DeadlineExceeded : LibTmux::UnsupportedFeatureError assert_raises(failure) { pane.capture(mode_screen: true, timeout: 0.5) } @@ -59,12 +62,21 @@ def test_cancellation_retires_a_typed_link_preflight_blocked_in_a_hook window = session.new_window(name: "unselected", command: ["/bin/cat"]) link = session.list_window_links.find { |entry| entry.id == window.id } token = LibTmux::Internal::Cancellation.new - assert fixture.tmux("set-hook", "-g", "after-show-options[98]", "wait-for -S budget-ready ; wait-for budget-held").last.success? - request = Thread.new do - link.select(timeout: 0.5, cancel: token) - rescue StandardError => error - error - end + assert fixture + .tmux( + "set-hook", + "-g", + "after-show-options[98]", + "wait-for -S budget-ready ; wait-for budget-held" + ) + .last + .success? + request = + Thread.new do + link.select(timeout: 0.5, cancel: token) + rescue StandardError => error + error + end begin assert fixture.tmux("wait-for", "budget-ready").last.success? token.cancel @@ -86,7 +98,9 @@ def test_pipe_rejects_a_command_with_no_requested_direction_before_effects LibTmuxTest::TmuxFixture.open do |fixture| LibTmux::Server.open(socket_path: fixture.socket_path) do |server| pane = server.list_panes.first - assert_raises(ArgumentError) { pane.pipe(shell_command: "cat >/dev/null", input: false, output: false) } + assert_raises(ArgumentError) do + pane.pipe(shell_command: "cat >/dev/null", input: false, output: false) + end assert_equal "0\n", pane.display('#{pane_pipe}').text end end @@ -114,7 +128,9 @@ def test_workspace_followup_operations_honor_precancel_before_mutation -> { sibling.respawn(command: ["/bin/cat"], kill: true, timeout: 0.5, cancel: token) }, -> { sibling.swap(original.ref, timeout: 0.5, cancel: token) }, -> { sibling.pipe(shell_command: "cat >/dev/null", timeout: 0.5, cancel: token) }, - -> { server.write_buffer(name: "cancelled", data: "payload", timeout: 0.5, cancel: token) } + -> do + server.write_buffer(name: "cancelled", data: "payload", timeout: 0.5, cancel: token) + end ] operations.each do |operation| error = assert_raises(LibTmux::Cancelled, &operation) diff --git a/test/integration/operations_test.rb b/test/integration/operations_test.rb index 039e859b..754aef11 100644 --- a/test/integration/operations_test.rb +++ b/test/integration/operations_test.rb @@ -8,7 +8,8 @@ class OperationsTest < Minitest::Test def test_typed_command_failure_names_the_command_and_preserves_tmux_stderr with_server do |server, _fixture| server.new_session(name: "work", command: ["cat"]) - error = assert_raises(LibTmux::CommandError) { server.new_session(name: "work", command: ["cat"]) } + error = + assert_raises(LibTmux::CommandError) { server.new_session(name: "work", command: ["cat"]) } assert_equal "tmux new-session failed: duplicate session: work", error.message assert_equal "duplicate session: work\n".b, error.result.stderr assert_equal :observed, error.delivery @@ -18,9 +19,16 @@ def test_typed_command_failure_names_the_command_and_preserves_tmux_stderr def test_command_error_bounds_the_first_line_and_keeps_binary_evidence with_server do |server, _fixture| stderr = "path\e\xFF".b + ("x" * 300) + "\nsecond line" - original = server.run(["show-buffer", "-b", "missing"]) - result = LibTmux::CommandResult.new(stdout: original.stdout, stderr: stderr, - status: original.status, elapsed_seconds: original.elapsed_seconds, pid: original.pid, argv: original.argv) + original = server.run(%w[show-buffer -b missing]) + result = + LibTmux::CommandResult.new( + stdout: original.stdout, + stderr: stderr, + status: original.status, + elapsed_seconds: original.elapsed_seconds, + pid: original.pid, + argv: original.argv + ) server.define_singleton_method(:run) { |*| result } error = assert_raises(LibTmux::CommandError) { server.read_buffer("missing") } assert_equal "tmux save-buffer failed: path??" + ("x" * 234), error.message @@ -56,11 +64,15 @@ def test_options_hooks_and_environment_preserve_scope_sparse_indexes_and_bytes session.options.set("update-environment", "TWO", index: 7) rows = session.options.list(name: "update-environment") assert_equal [2, 7], rows.map(&:index) - assert_equal ["ONE", "TWO"], rows.map(&:raw) + assert_equal %w[ONE TWO], rows.map(&:raw) session.options.unset("update-environment", index: 2) assert_equal [7], session.options.list(name: "update-environment").map(&:index) assert_equal "TWO", session.options.get("update-environment", index: 7).raw - session.hooks.set("after-new-window", command: "set-option -t #{session.id} @hook ran", index: 4) + session.hooks.set( + "after-new-window", + command: "set-option -t #{session.id} @hook ran", + index: 4 + ) assert_equal [4], session.hooks.list(name: "after-new-window").map(&:index) session.hooks.run("after-new-window") assert_equal "ran".b, session.options.get("@hook").raw @@ -76,7 +88,7 @@ def test_bulk_option_reads_keep_literal_asterisks_in_user_option_names with_server do |server, fixture| session = server.list_sessions.first options = session.options - values = {"@stage" => "source", "@stage*" => "publish"} + values = { "@stage" => "source", "@stage*" => "publish" } values.each do |name, value| options.set(name, value) output, error, status = fixture.tmux("show-options", "-v", "-t", session.id, "--", name) @@ -101,7 +113,7 @@ def test_named_option_reads_distinguish_literal_asterisks_from_inheritance session = server.list_sessions.first options = session.options global = server.options(scope: :session) - {"@stage" => "source", "@stage*" => "publish"}.each do |name, value| + { "@stage" => "source", "@stage*" => "publish" }.each do |name, value| global.set(name, value) output, error, status = fixture.tmux("show-options", "-Av", "-t", session.id, "--", name) assert status.success?, error @@ -212,7 +224,8 @@ def test_buffer_bytes_capture_flags_and_copy_commands payload = "NUL\0\xff\n\n".b server.write_buffer(name: "literal ;", data: payload) assert_equal payload, server.read_buffer("literal ;").stdout - assert_equal [["literal ;", payload.bytesize]], server.list_buffers.map { |row| [row.fetch(:name), row.fetch(:size)] } + assert_equal [["literal ;", payload.bytesize]], + server.list_buffers.map { |row| [row.fetch(:name), row.fetch(:size)] } server.write_buffer(name: "paste", data: "one\ntwo\n") assert pane.paste(buffer: "paste", delete: true, separator: " ").success? assert_raises(LibTmux::CommandError) { server.read_buffer("paste") } @@ -221,7 +234,8 @@ def test_buffer_bytes_capture_flags_and_copy_commands assert_equal "1\n", pane.display('#{pane_in_mode}').text assert pane.copy_command("cancel").success? assert_equal "0\n", pane.display('#{pane_in_mode}').text - if LibTmux::Internal::TmuxVersion.parse(server.tmux_version) < LibTmux::Internal::TmuxVersion.parse("3.4") + if LibTmux::Internal::TmuxVersion.parse(server.tmux_version) < + LibTmux::Internal::TmuxVersion.parse("3.4") # Exact named-buffer deletion needs 3.4; the newest buffer is the only one left. server.run(["delete-buffer"]) else @@ -235,9 +249,10 @@ def test_zero_byte_write_preserves_an_existing_buffer with_server do |server, _fixture| server.write_buffer(name: "score", data: "old score") - error = assert_raises(LibTmux::UnsupportedFeatureError) do - server.write_buffer(name: "score", data: "".b) - end + error = + assert_raises(LibTmux::UnsupportedFeatureError) do + server.write_buffer(name: "score", data: "".b) + end assert_equal :admission, error.phase assert_equal :not_sent, error.delivery assert_equal "old score", server.read_buffer("score").stdout @@ -270,7 +285,8 @@ def test_manipulations_keep_entity_ids_and_link_context_explicit assert_equal "20\n", split.display('#{pane_width}').text positions = [split, pane].map { |entry| entry.display('#{pane_left}:#{pane_top}').stdout } split.swap(pane.ref) - assert_equal positions.reverse, [split, pane].map { |entry| entry.display('#{pane_left}:#{pane_top}').stdout } + assert_equal positions.reverse, + [split, pane].map { |entry| entry.display('#{pane_left}:#{pane_top}').stdout } split.select assert_equal "1\n", split.display('#{pane_active}').text destination = split.break_out(session: session.ref, name: "broken;") @@ -278,7 +294,9 @@ def test_manipulations_keep_entity_ids_and_link_context_explicit split.join(pane.ref, direction: :vertical) assert_equal [pane.id, split.id].sort, window.list_panes.map(&:id).sort split.move(pane.ref, direction: :horizontal, before: true) - assert_operator split.display('#{pane_left}').text.to_i, :<, pane.display('#{pane_left}').text.to_i + assert_operator split.display('#{pane_left}').text.to_i, + :<, + pane.display('#{pane_left}').text.to_i split.respawn(command: ["/bin/cat"], kill: true) session.link_window(window.ref, index: 8) session.link_window(window.ref, index: 9) @@ -310,15 +328,27 @@ def test_link_guard_rechecks_after_hook_wait_and_ignores_configured_command_alia server.options(scope: :server).set("command-alias", "if-shell=wait-for never", index: 90) server.options(scope: :server).set("command-alias", "select-window=wait-for never", index: 91) assert link.select.success? - assert fixture.tmux("set-hook", "-g", "after-show-options[99]", "wait-for -S link-ready ; wait-for link-release").last.success? - request = Thread.new do - link.unlink - rescue LibTmux::TargetNotFoundError => error - error - end + assert fixture + .tmux( + "set-hook", + "-g", + "after-show-options[99]", + "wait-for -S link-ready ; wait-for link-release" + ) + .last + .success? + request = + Thread.new do + link.unlink + rescue LibTmux::TargetNotFoundError => error + error + end begin assert fixture.tmux("wait-for", "link-ready").last.success? - assert fixture.tmux("link-window", "-k", "-s", replacement.id, "-t", "#{session.id}:8").last.success? + assert fixture + .tmux("link-window", "-k", "-s", replacement.id, "-t", "#{session.id}:8") + .last + .success? assert fixture.tmux("set-hook", "-gu", "after-show-options[99]").last.success? assert fixture.tmux("wait-for", "-S", "link-release").last.success? assert request.join(0.5), "link guard did not finish" @@ -340,11 +370,12 @@ def test_missing_alias_inventory_cannot_turn_a_guarded_mutation_into_false_succe link = session.list_window_links.find { |entry| entry.index == 8 } server.options.set("command-alias", "if-shell=", index: 90) server.options.set("command-alias", "show-options=show-options -v", index: 91) - outcome = begin - link.unlink(timeout: 0.5) - rescue LibTmux::UnsupportedFeatureError => error - error - end + outcome = + begin + link.unlink(timeout: 0.5) + rescue LibTmux::UnsupportedFeatureError => error + error + end assert_equal [0, 8], session.list_window_links.map(&:index) assert_instance_of LibTmux::UnsupportedFeatureError, outcome assert_equal :not_sent, outcome.delivery @@ -358,7 +389,8 @@ def test_swapping_distinct_window_links_preserves_windows_and_invalidates_old_oc other = session.new_window(name: "other", command: ["/bin/cat"]) first, second = session.list_window_links assert first.swap(second.ref, timeout: 0.5).success? - assert_equal [[0, other.id], [1, initial.id]], session.list_window_links.map { |link| [link.index, link.id] } + assert_equal [[0, other.id], [1, initial.id]], + session.list_window_links.map { |link| [link.index, link.id] } assert_raises(LibTmux::TargetNotFoundError) { first.select } assert_raises(LibTmux::TargetNotFoundError) { second.select } assert_equal "#{initial.id}\n", initial.display('#{window_id}').stdout @@ -391,33 +423,44 @@ def test_resize_zoom_and_layout_restore_geometry_without_changing_focus assert_equal "80:30\n", first.display('#{pane_width}:#{pane_height}').text first.resize(zoom: true) assert_equal "0\n", window.display('#{window_zoomed_flag}').text - assert_equal without_focus(layout), without_focus(window.display('#{window_layout}').text.strip) + assert_equal without_focus(layout), + without_focus(window.display('#{window_layout}').text.strip) second.select window.select_layout(:even_horizontal) - assert_equal [30, 30], window.list_panes.map { |pane| pane.display('#{pane_height}').text.to_i } + assert_equal [30, 30], + window.list_panes.map { |pane| pane.display('#{pane_height}').text.to_i } assert_equal "#{second.id}\n", window.display('#{pane_id}').text window.select_layout(layout) - assert_equal without_focus(layout), without_focus(window.display('#{window_layout}').text.strip) + assert_equal without_focus(layout), + without_focus(window.display('#{window_layout}').text.strip) assert_equal "#{second.id}\n", window.display('#{pane_id}').text ["not-a-layout", "", "abc", "deadbeef"].each do |invalid| assert_raises(ArgumentError) { window.select_layout(invalid) } end - invalid = layout.start_with?("{") ? '{"V":2' : "%04x" % (layout[0, 4].to_i(16) ^ 1) + layout[4..] + invalid = + layout.start_with?("{") ? '{"V":2' : "%04x" % (layout[0, 4].to_i(16) ^ 1) + layout[4..] assert_raises(LibTmux::CommandError) { window.select_layout(invalid) } - assert_equal without_focus(layout), without_focus(window.display('#{window_layout}').text.strip) + assert_equal without_focus(layout), + without_focus(window.display('#{window_layout}').text.strip) release = LibTmux::Internal::TmuxVersion.parse(server.display('#{version}').text.strip) if release >= LibTmux::Internal::TmuxVersion.parse("3.5") assert_raises(ArgumentError) { window.select_layout("main-h") } window.select_layout(:main_vertical_mirrored) - assert_operator first.display('#{pane_left}').text.to_i, :>, second.display('#{pane_left}').text.to_i + assert_operator first.display('#{pane_left}').text.to_i, + :>, + second.display('#{pane_left}').text.to_i else window.select_layout("main-h") - error = assert_raises(LibTmux::UnsupportedFeatureError) { window.select_layout(:main_vertical_mirrored) } + error = + assert_raises(LibTmux::UnsupportedFeatureError) do + window.select_layout(:main_vertical_mirrored) + end assert_equal :not_sent, error.delivery end window.select_layout(layout) - assert_equal without_focus(layout), without_focus(window.display('#{window_layout}').text.strip) + assert_equal without_focus(layout), + without_focus(window.display('#{window_layout}').text.strip) end end @@ -456,7 +499,10 @@ def test_source_file_and_wait_channels_preserve_literal_arguments_and_final_outc File.write(config, "set-option -g @source-loaded 'literal ; value'\n") assert server.source_file(config, timeout: 0.5).success? assert_equal "literal ; value", server.options(scope: :session).get("@source-loaded").raw - File.write(config, "set-option -g @source-loaded changed\nset-option -g nonexistent-option invalid\n") + File.write( + config, + "set-option -g @source-loaded changed\nset-option -g nonexistent-option invalid\n" + ) failure = assert_raises(LibTmux::CommandError) { server.source_file(config, timeout: 0.5) } assert_equal :observed, failure.delivery assert_equal "changed", server.options(scope: :session).get("@source-loaded").raw @@ -465,15 +511,21 @@ def test_source_file_and_wait_channels_preserve_literal_arguments_and_final_outc assert server.wait_for(channel, action: :signal, timeout: 0.5).success? assert server.wait_for(channel, timeout: 0.5).success? assert server.wait_for(channel, action: :lock, timeout: 0.5).success? - blocked = assert_raises(LibTmux::DeadlineExceeded) { server.wait_for(channel, action: :lock, timeout: 0.1) } + blocked = + assert_raises(LibTmux::DeadlineExceeded) do + server.wait_for(channel, action: :lock, timeout: 0.1) + end assert_equal :possibly_sent, blocked.delivery assert server.wait_for(channel, action: :unlock, timeout: 0.5).success? # Before tmux 3.8 the retired client's queued lock still acquires in tmux # after unlock; 3.8 drops it, so the channel is no longer locked. - if LibTmux::Internal::TmuxVersion.parse(server.tmux_version) < LibTmux::Internal::TmuxVersion.parse("3.8") + if LibTmux::Internal::TmuxVersion.parse(server.tmux_version) < + LibTmux::Internal::TmuxVersion.parse("3.8") assert server.wait_for(channel, action: :unlock, timeout: 0.5).success? else - assert_raises(LibTmux::CommandError) { server.wait_for(channel, action: :unlock, timeout: 0.5) } + assert_raises(LibTmux::CommandError) do + server.wait_for(channel, action: :unlock, timeout: 0.5) + end end assert server.wait_for(channel, action: :lock, timeout: 0.5).success? assert server.wait_for(channel, action: :unlock, timeout: 0.5).success? diff --git a/test/integration/option_scope_test.rb b/test/integration/option_scope_test.rb index 380c4f4a..96f23a6a 100644 --- a/test/integration/option_scope_test.rb +++ b/test/integration/option_scope_test.rb @@ -39,7 +39,10 @@ def test_builtin_inheritance_and_array_cardinality_preserve_scope_and_empty_valu session.options.set("update-environment", "ONE", index: 3) session.options.set("update-environment", "NINE", index: 9) assert_raises(LibTmux::MultipleMatchesError) { session.options.get("update-environment") } - missing = assert_raises(LibTmux::NoMatchError) { session.options.get("update-environment", index: 42) } + missing = + assert_raises(LibTmux::NoMatchError) do + session.options.get("update-environment", index: 42) + end assert_equal :observed, missing.delivery session.options.set("update-environment", "", index: 42) present_empty = session.options.get("update-environment", index: 42) @@ -47,11 +50,19 @@ def test_builtin_inheritance_and_array_cardinality_preserve_scope_and_empty_valu assert_equal "", present_empty.raw session.options.unset("update-environment", index: 42) session.options.set("update-environment", "TEN ELEVEN", append: true) - assert_equal [[0, "TEN"], [1, "ELEVEN"], [3, "ONE"], [9, "NINE"]], session.options.list(name: "update-environment").map { |entry| [entry.index, entry.raw] } + assert_equal [[0, "TEN"], [1, "ELEVEN"], [3, "ONE"], [9, "NINE"]], + session + .options + .list(name: "update-environment") + .map { |entry| [entry.index, entry.raw] } session.options.unset("update-environment", index: 9) assert_equal [0, 1, 3], session.options.list(name: "update-environment").map(&:index) session.options.set("update-environment", "REPLACED TWO") - assert_equal [[0, "REPLACED"], [1, "TWO"]], session.options.list(name: "update-environment").map { |entry| [entry.index, entry.raw] } + assert_equal [[0, "REPLACED"], [1, "TWO"]], + session + .options + .list(name: "update-environment") + .map { |entry| [entry.index, entry.raw] } end end @@ -60,7 +71,13 @@ def test_hook_arrays_execute_in_index_order_at_each_declared_scope session = server.list_sessions.first window = session.list_windows.first pane = window.list_panes.first - scopes = [server.hooks(scope: :session), server.hooks(scope: :window), session.hooks, window.hooks, pane.hooks] + scopes = [ + server.hooks(scope: :session), + server.hooks(scope: :window), + session.hooks, + window.hooks, + pane.hooks + ] scopes.each do |hooks| server.options(scope: :session).set("@hook-order", "") hooks.set("after-display-message", command: "set-option -ag @hook-order A", index: 2) diff --git a/test/integration/pane_io_test.rb b/test/integration/pane_io_test.rb index aee42ff4..42387cc8 100644 --- a/test/integration/pane_io_test.rb +++ b/test/integration/pane_io_test.rb @@ -35,8 +35,11 @@ def test_pipe_directions_preserve_bytes_and_toggle_closes_the_previous_pipe listener = UNIXServer.new(File.join(directory, "pipe")) pipe_reader = nil begin - script = 'UNIXSocket.open(ARGV.fetch(0)) { |io| io.write(ARGV.fetch(1) + "\n"); IO.copy_stream(STDIN, io) }' - command = [Gem.ruby, "--disable=rubyopt,gems", "-rsocket", "-e", script, listener.path].shelljoin + " '\#{pane_id}'" + script = + 'UNIXSocket.open(ARGV.fetch(0)) { |io| io.write(ARGV.fetch(1) + "\n"); IO.copy_stream(STDIN, io) }' + command = + [Gem.ruby, "--disable=rubyopt,gems", "-rsocket", "-e", script, listener.path].shelljoin + + " '\#{pane_id}'" assert pane.pipe(shell_command: command, timeout: 0.5).success? assert IO.select([listener], nil, nil, 0.5), "pipe process did not connect" pipe_reader = listener.accept @@ -53,11 +56,22 @@ def test_pipe_directions_preserve_bytes_and_toggle_closes_the_previous_pipe assert_equal :wait_readable, listener.accept_nonblock(exception: false) input = "input\0\xff\n".b - writer = [Gem.ruby, "--disable=rubyopt,gems", "-e", 'STDOUT.write([ARGV.fetch(0)].pack("H*"))', input.unpack1("H*")].shelljoin + writer = [ + Gem.ruby, + "--disable=rubyopt,gems", + "-e", + 'STDOUT.write([ARGV.fetch(0)].pack("H*"))', + input.unpack1("H*") + ].shelljoin assert pane.pipe(shell_command: writer, input: true, output: false, timeout: 0.5).success? assert_equal input, receive_input(channel, input.bytesize) - duplex = [Gem.ruby, "--disable=rubyopt,gems", "-e", 'STDOUT.sync = true; while (bytes = STDIN.readpartial(1024)); STDOUT.write(bytes); end'].shelljoin + duplex = [ + Gem.ruby, + "--disable=rubyopt,gems", + "-e", + "STDOUT.sync = true; while (bytes = STDIN.readpartial(1024)); STDOUT.write(bytes); end" + ].shelljoin assert pane.pipe(shell_command: duplex, input: true, output: true, timeout: 0.5).success? channel.write("O" + [payload.bytesize].pack("N") + payload) assert_equal payload, receive_input(channel, payload.bytesize) @@ -79,7 +93,8 @@ def with_pane channel = nil begin LibTmux::Server.open(socket_path: fixture.socket_path) do |server| - window = server.list_sessions.first.new_window(name: "io", command: program(listener.path)) + window = + server.list_sessions.first.new_window(name: "io", command: program(listener.path)) pane = window.list_panes.first assert IO.select([listener], nil, nil, 0.5), "pane program did not connect" channel = listener.accept diff --git a/test/integration/program_test.rb b/test/integration/program_test.rb index ee5f2d10..6ff8318d 100644 --- a/test/integration/program_test.rb +++ b/test/integration/program_test.rb @@ -31,7 +31,8 @@ def test_borrowed_daemon_keeps_its_other_sessions_and_configuration 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) + 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é" @@ -70,7 +71,8 @@ def test_borrowed_cancellation_retires_admitted_preparation native.call(reference, **options) end hold_preparation_peer do |held| - failure = assert_raises(LibTmux::Cancelled) { server.start_program(["/bin/true"], cancel: token) } + 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) @@ -100,7 +102,9 @@ def test_private_session_retains_history_when_borrowed_daemon_defaults_to_zero 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) } + assert_raises(ArgumentError) do + LibTmux.start_program(argv, executable: executable, history_lines: 101) + end return unless require_program_support(LibTmux.method(:run_program)) result = LibTmux.run_program(argv, executable: executable, height: 4, history_lines: 0) @@ -134,7 +138,9 @@ def test_a_respawned_pane_cannot_receive_input_or_be_destroyed_by_the_old_owner 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) do + program.send_text("belongs to the old program") + end assert_raises(LibTmux::TargetNotFoundError) { program.wait } program.close assert_equal [pane.id], server.list_panes.map(&:id) @@ -192,12 +198,16 @@ def test_daemon_disconnect_leaves_in_flight_input_and_retirement_uncertain 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.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) @@ -224,7 +234,9 @@ def test_same_start_command_respawn_cannot_reuse_a_completed_generation 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 + if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline + flunk "replacement did not exit" + end sleep 0.01 end assert_raises(LibTmux::TargetNotFoundError) { program.screen } @@ -244,7 +256,9 @@ def test_resize_refuses_when_the_pane_leaves_its_owned_window 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 } + sizes = -> do + server.run(%w[list-windows -a -F #{window_id}:#{window_width}x#{window_height}]).text + end 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 @@ -261,7 +275,11 @@ 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 + 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 } @@ -278,14 +296,14 @@ def test_screen_and_wait_preserve_completion_across_external_geometry_refusal 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 + assert_empty server.run(%w[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 + assert_equal "yes\n", server.run(%w[show-options -gqv @program-capture-ran]).text end assert_equal [neighbor.id], server.list_panes.map(&:id) end @@ -307,10 +325,15 @@ def test_closing_retires_a_descendant_that_ignores_hangup end sleep 2 RUBY - LibTmux.start_program([RbConfig.ruby, "-e", source, ready, escaped], executable: executable) do + 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 + if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline + flunk "descendant did not start" + end sleep 0.01 end end @@ -326,16 +349,17 @@ def test_outer_exception_does_not_hide_cleanup_failure 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 + 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 - :block_succeeded end - end assert_same cleanup_failure, actual end end @@ -343,7 +367,13 @@ def test_outer_exception_does_not_hide_cleanup_failure 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"] + 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 @@ -362,9 +392,11 @@ def test_fast_exit_keeps_literal_argv_and_final_utf8 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 - ) + 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 @@ -386,7 +418,9 @@ def test_async_wait_cancellation_leaves_input_and_other_waiters_available 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 + if Process.clock_gettime(Process::CLOCK_MONOTONIC) > ready + flunk "program did not show its prompt" + end end cancel = LibTmux::Cancellation.new @@ -451,9 +485,13 @@ 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 - ) + 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 @@ -472,7 +510,15 @@ def test_dense_combining_cells_keep_the_same_final_tail_as_native_capture 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) + native, status = + Open3.capture2( + executable, + "-N", + "-S", + server.endpoint.socket_path, + *capture, + binmode: true + ) assert status.success? assert_operator native.bytesize, :>, 1 << 20 @@ -513,8 +559,11 @@ def test_async_close_retries_when_scope_reports_incomplete_retirement original.call unless failed failed = true - raise LibTmux::TransportError.new("scope retirement incomplete", phase: :retire, - cleanup_errors: ["test request owner still pending"]) + 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 } @@ -539,11 +588,12 @@ def test_wait_racing_close_reports_a_typed_lifecycle_error 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 + 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 @@ -563,7 +613,9 @@ def test_terminal_interrupt_is_reported_as_the_program_signal 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 + if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline + flunk "program did not reach input" + end end program.send_keys("C-c") result = program.wait @@ -576,15 +628,16 @@ 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 + pid = + fork do + begin + program.close + program.screen + rescue LibTmux::ClosedError + exit! 0 + end + exit! 1 end - exit! 1 - end assert_predicate Process.waitpid2(pid).last, :success? program.send_text("owner still has its terminal") capture = program.capture_screen @@ -600,8 +653,15 @@ 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"}) + 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" @@ -631,11 +691,12 @@ 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 + 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 @@ -656,7 +717,9 @@ def assert_program_admission(launch) 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 } + launch.call(argv, executable: executable) do |program| + assert_equal 0, program.wait.exit_status + end assert_equal "started", File.read(marker) else refute_path_exists marker @@ -665,13 +728,18 @@ def assert_program_admission(launch) end # Below the minimum, exercise admission through the same public factory. - def require_program_support(launch = LibTmux.method(:start_program), argv: ["/bin/true"], **options) + 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] + error = + assert_raises(LibTmux::UnsupportedFeatureError) do + launch.call(argv, executable: executable, **options) { flunk "yielded a program owner" } + end + assert_equal %i[admission not_sent], [error.phase, error.delivery] assert_match(/owned terminal programs require tmux 3\.7 or newer/, error.message) false end @@ -679,12 +747,13 @@ def require_program_support(launch = LibTmux.method(:start_program), argv: ["/bi 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" + 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 + peer = event.return_value.fetch(1).dup + end trace.enable { yield -> { peer } } ensure peer&.close @@ -694,7 +763,7 @@ 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} + 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) } diff --git a/test/integration/query_test.rb b/test/integration/query_test.rb index 2ff3928c..9ca472d7 100644 --- a/test/integration/query_test.rb +++ b/test/integration/query_test.rb @@ -6,37 +6,45 @@ class QueryIntegrationTest < Minitest::Test def test_explicit_source_queries_match_local_captures_and_keep_complete_relations - source_type = Class.new(LibTmux::Server) do - attr_reader :calls + source_type = + Class.new(LibTmux::Server) do + attr_reader :calls - def run(...) - @calls = (@calls || 0) + 1 - super + def run(...) + @calls = (@calls || 0) + 1 + super + end end - end LibTmuxTest::TmuxFixture.open do |fixture| source_type.open(socket_path: fixture.socket_path) do |server| window = server.list_windows.fetch(0) window.split(direction: :horizontal, command: ["/bin/cat"]) before = server.calls - explanation = server.explain_panes(where: {index: {gte: 1}}, pushdown: :auto) + explanation = server.explain_panes(where: { index: { gte: 1 } }, pushdown: :auto) assert_equal before, server.calls assert_nil explanation.fetch(:pushed) - assert_raises(LibTmux::UnsupportedFeatureError) { server.search_panes(where: {}, pushdown: :required) } - assert_raises(LibTmux::InvalidFilterError) { server.search_panes(where: {active: "0"}) } + assert_raises(LibTmux::UnsupportedFeatureError) do + server.search_panes(where: {}, pushdown: :required) + end + assert_raises(LibTmux::InvalidFilterError) { server.search_panes(where: { active: "0" }) } assert_equal before, server.calls - expression = LibTmux::PaneWhere.build(index: {gte: 1}) + expression = LibTmux::PaneWhere.build(index: { gte: 1 }) local = server.snapshot.panes.where(expression) - result = server.search_panes(where: LibTmux::FilterExpr.from_json(expression.to_json), pushdown: :auto) + result = + server.search_panes( + where: LibTmux::FilterExpr.from_json(expression.to_json), + pushdown: :auto + ) assert_equal local.map(&:ref), result.map(&:ref) assert_equal [0, 1], result.one.window.panes.map(&:index) - assert_equal local.map(&:ref), server.search_panes(where: expression, pushdown: :never).map(&:ref) + assert_equal local.map(&:ref), + server.search_panes(where: expression, pushdown: :never).map(&:ref) reads = server.calls assert result.one.active? == true || result.one.active? == false result.one.window.panes.select(&:active?).one result.map(&:title) - result.where(index: {in: [1]}).exists? + result.where(index: { in: [1] }).exists? assert_equal reads, server.calls server.close assert_equal [0, 1], result.one.window.panes.map(&:index) diff --git a/test/integration/readme_commands_test.rb b/test/integration/readme_commands_test.rb index ab849cba..259e4a57 100644 --- a/test/integration/readme_commands_test.rb +++ b/test/integration/readme_commands_test.rb @@ -22,9 +22,7 @@ class ReadmeCommandsTest < Minitest::Test CATALOG = LibTmux::MCP.const_get(:Catalog) # What a README says a command shows or does, beyond exiting successfully. - CLAIMS = { - /list-windows -t work\z/ => /editor/ - }.freeze + CLAIMS = { /list-windows -t work\z/ => /editor/ }.freeze class Sandbox attr_reader :directory, :work @@ -40,21 +38,38 @@ def initialize(executable: nil) [work, home, bin, File.join(directory, "t")].each { |path| FileUtils.mkdir_p(path) } File.symlink(tmux, File.join(bin, "tmux")) %w[libtmux-mcp libtmux-workspace].each do |name| - LibTmuxTest::StubExecutable.write(File.join(bin, name), 'exec RUBY, "-W:no-experimental", EXECUTABLE, *ARGV', - RUBY: Gem.ruby, EXECUTABLE: Gem.bin_path(name, name)) + LibTmuxTest::StubExecutable.write( + File.join(bin, name), + 'exec RUBY, "-W:no-experimental", EXECUTABLE, *ARGV', + RUBY: Gem.ruby, + EXECUTABLE: Gem.bin_path(name, name) + ) end - @env = LibTmuxTest::Sandbox.scrub(ENV).merge( - "HOME" => home, "TMPDIR" => directory, "TMUX_TMPDIR" => File.join(directory, "t"), - "PATH" => "#{bin}#{File::PATH_SEPARATOR}#{ENV.fetch('PATH')}", "XDG_CONFIG_HOME" => File.join(home, ".config") - ) + @env = + LibTmuxTest::Sandbox.scrub(ENV).merge( + "HOME" => home, + "TMPDIR" => directory, + "TMUX_TMPDIR" => File.join(directory, "t"), + "PATH" => "#{bin}#{File::PATH_SEPARATOR}#{ENV.fetch("PATH")}", + "XDG_CONFIG_HOME" => File.join(home, ".config") + ) end def tmux - @tmux ||= begin - name = ENV.fetch("LIBTMUX_TEST_TMUX", "tmux") - candidates = name.include?(File::SEPARATOR) ? [name] : ENV.fetch("PATH").split(File::PATH_SEPARATOR).map { |dir| File.join(dir, name) } - candidates.find { |path| File.file?(path) && File.executable?(path) } or raise "tmux executable is unavailable" - end + @tmux ||= + begin + name = ENV.fetch("LIBTMUX_TEST_TMUX", "tmux") + candidates = + ( + if name.include?(File::SEPARATOR) + [name] + else + ENV.fetch("PATH").split(File::PATH_SEPARATOR).map { |dir| File.join(dir, name) } + end + ) + candidates.find { |path| File.file?(path) && File.executable?(path) } or + raise "tmux executable is unavailable" + end end def tmux_release @@ -64,14 +79,19 @@ def tmux_release Result = Struct.new(:stdout, :stderr, :status) def run(*command, input: "") - Open3.popen3(@env.merge(@variables), *command, chdir: work, pgroup: true) do |stdin, stdout, stderr, thread| + Open3.popen3( + @env.merge(@variables), + *command, + chdir: work, + pgroup: true + ) do |stdin, stdout, stderr, thread| stdin.write(input) stdin.close readers = [stdout, stderr].map { |io| Thread.new { io.read } } unless thread.join(DEADLINE) Process.kill("KILL", -thread.pid) thread.join - raise "#{command.join(' ')} did not finish in #{DEADLINE} seconds" + raise "#{command.join(" ")} did not finish in #{DEADLINE} seconds" end Result.new(readers[0].value, readers[1].value, thread.value) end @@ -93,7 +113,9 @@ def provide_socket @sockets = @sockets.to_i + 1 socket = File.join(directory, "env#{@sockets}.sock") created = run(tmux, "-S", socket, "-f", "/dev/null", "new-session", "-d", "-s", "existing") - raise "could not start the TMUX_SOCKET server: #{created.stderr}" unless created.status.success? + unless created.status.success? + raise "could not start the TMUX_SOCKET server: #{created.stderr}" + end @variables["TMUX_SOCKET"] = socket end @@ -110,9 +132,25 @@ def assign(command) # under the Unix socket limit; CI sets TMPDIR to /tmp for the same reason. def mcp(argv, where) executable = Gem.bin_path("libtmux-mcp", "libtmux-mcp") - Open3.popen3(@env.merge(@variables, "TMPDIR" => "/tmp"), Gem.ruby, "-W:no-experimental", executable, *argv, chdir: work) do |stdin, stdout, stderr, thread| - session = McpSession.new(stdin, stdout, stderr, "#{where}: libtmux-mcp #{argv.join(' ')}") - session.request("initialize", protocolVersion: "2025-11-25", capabilities: {}, clientInfo: {name: "readme", version: "1"}) + Open3.popen3( + @env.merge(@variables, "TMPDIR" => "/tmp"), + Gem.ruby, + "-W:no-experimental", + executable, + *argv, + chdir: work + ) do |stdin, stdout, stderr, thread| + session = McpSession.new(stdin, stdout, stderr, "#{where}: libtmux-mcp #{argv.join(" ")}") + session.request( + "initialize", + protocolVersion: "2025-11-25", + capabilities: { + }, + clientInfo: { + name: "readme", + version: "1" + } + ) session.notify("notifications/initialized") yield session stdin.close @@ -130,7 +168,8 @@ def close released = LibTmuxTest::Sandbox.release(directory, tmux: tmux) return if released.answering.empty? - message = "a server still answers at #{released.answering.join(', ')}, so #{File.basename(directory)} was kept" + message = + "a server still answers at #{released.answering.join(", ")}, so #{File.basename(directory)} was kept" raise Minitest::Assertion, message unless $! warn message @@ -143,16 +182,21 @@ def initialize(input, output, error, label) end def notify(method) - @input.write(JSON.generate({jsonrpc: "2.0", method: method}) + "\n") + @input.write(JSON.generate({ jsonrpc: "2.0", method: method }) + "\n") end def request(method, **params) @id += 1 - @input.write(JSON.generate({jsonrpc: "2.0", id: @id, method: method, params: params}) + "\n") + @input.write( + JSON.generate({ jsonrpc: "2.0", id: @id, method: method, params: params }) + "\n" + ) loop do - raise Minitest::Assertion, "#{@label}: no response to #{method}" unless IO.select([@output], nil, nil, DEADLINE) + unless IO.select([@output], nil, nil, DEADLINE) + raise Minitest::Assertion, "#{@label}: no response to #{method}" + end - line = @output.gets or raise Minitest::Assertion, "#{@label}: output closed during #{method}: #{@error.read}" + line = @output.gets or + raise Minitest::Assertion, "#{@label}: output closed during #{method}: #{@error.read}" message = JSON.parse(line) return message.fetch("result") if message["id"] == @id end @@ -163,12 +207,14 @@ def tools end def capabilities - request("tools/call", name: "tmux_capabilities", arguments: {}).fetch("structuredContent").fetch("data") + request("tools/call", name: "tmux_capabilities", arguments: {}).fetch( + "structuredContent" + ).fetch("data") end end Blocks::DOCUMENTS.each do |path| - define_method("test_commands_in_#{path.tr('/.-', '___')}_run_as_written") do + define_method("test_commands_in_#{path.tr("/.-", "___")}_run_as_written") do run_markdown(Blocks.read(path), path) end end @@ -180,9 +226,25 @@ def test_mcp_tool_table_states_the_defaults_the_server_serves assert_equal CATALOG::READ_ONLY.sort, table.select { |_, enabled| enabled }.keys.sort sandbox = Sandbox.new begin - assert sandbox.run(sandbox.tmux, "-L", "agent", "-f", "/dev/null", "new-session", "-d", "-s", "work").status.success? - everything = table.reject { |_, enabled| enabled }.keys.flat_map { |name| ["--enable-tool", name] } - sandbox.mcp(["--socket-name", "agent", *everything], "tool table") { |session| assert_equal table.keys.sort, session.tools.sort } + assert sandbox + .run( + sandbox.tmux, + "-L", + "agent", + "-f", + "/dev/null", + "new-session", + "-d", + "-s", + "work" + ) + .status + .success? + everything = + table.reject { |_, enabled| enabled }.keys.flat_map { |name| ["--enable-tool", name] } + sandbox.mcp(["--socket-name", "agent", *everything], "tool table") do |session| + assert_equal table.keys.sort, session.tools.sort + end ensure sandbox.close end @@ -193,33 +255,49 @@ def test_the_runner_keeps_its_directory_and_fails_when_kill_server_leaves_a_serv error = assert_raises(Minitest::Assertion) { sandbox.close } assert_includes error.message, "a server still answers at t/tmux-#{Process.uid}/agent" assert_includes error.message, "#{File.basename(sandbox.directory)} was kept" - assert File.directory?(sandbox.directory), "removed the directory of a server that was not stopped" + assert File.directory?(sandbox.directory), + "removed the directory of a server that was not stopped" end end def test_a_server_the_runner_cannot_stop_does_not_replace_the_failure_that_ended_the_test with_a_server_kill_server_leaves do |sandbox| - error = assert_raises(RuntimeError) do - raise "the failure the test ended with" - ensure - _, warned = capture_io { sandbox.close } - assert_includes warned, "#{File.basename(sandbox.directory)} was kept" - end + error = + assert_raises(RuntimeError) do + raise "the failure the test ended with" + ensure + _, warned = capture_io { sandbox.close } + assert_includes warned, "#{File.basename(sandbox.directory)} was kept" + end assert_equal "the failure the test ended with", error.message - assert File.directory?(sandbox.directory), "removed the directory of a server that was not stopped" + assert File.directory?(sandbox.directory), + "removed the directory of a server that was not stopped" end end def test_the_runner_hands_its_commands_no_variable_that_names_a_server - decoys = {"TMUX" => "/decoy/server,1,0", "TMUX_PANE" => "%9", "LIBTMUX_SOCKET" => "decoy", - "LIBTMUX_SOCKET_PATH" => "/decoy/path", "LIBTMUX_SOCKET_NAME" => "decoy"} + decoys = { + "TMUX" => "/decoy/server,1,0", + "TMUX_PANE" => "%9", + "LIBTMUX_SOCKET" => "decoy", + "LIBTMUX_SOCKET_PATH" => "/decoy/path", + "LIBTMUX_SOCKET_NAME" => "decoy" + } saved = decoys.keys.to_h { |name| [name, ENV.fetch(name, nil)] } sandbox = nil begin decoys.each { |name, value| ENV[name] = value } sandbox = Sandbox.new - names = sandbox.shell("env | sed -n -E 's/^(TMUX|TMUX_PANE|LIBTMUX_SOCKET[A-Z_]*)=.*/\\1/p'").stdout.lines.map(&:chomp) - own = sandbox.shell("test \"$TMUX_TMPDIR\" = #{Shellwords.escape(File.join(sandbox.directory, 't'))}") + names = + sandbox + .shell("env | sed -n -E 's/^(TMUX|TMUX_PANE|LIBTMUX_SOCKET[A-Z_]*)=.*/\\1/p'") + .stdout + .lines + .map(&:chomp) + own = + sandbox.shell( + "test \"$TMUX_TMPDIR\" = #{Shellwords.escape(File.join(sandbox.directory, "t"))}" + ) ensure saved.each { |name, value| ENV[name] = value } sandbox&.close @@ -237,16 +315,25 @@ def test_the_runner_rejects_what_the_readmes_must_not_do workspace = "```yaml\nsession_name: a\nwindows:\n - window_name: a\n panes: [{}]\n```\n" validate = "```console\n$ libtmux-workspace validate workspace.yaml\n```\n" - assert_match(/output differs/, refusal(workspace + validate + "```text\nWorkspace configuration is invalid.\n```\n")) + assert_match( + /output differs/, + refusal(workspace + validate + "```text\nWorkspace configuration is invalid.\n```\n") + ) invalid = "```yaml\nsession_name: a\nwindows: []\n```\n" assert_match(/validate workspace\.yaml/, refusal(invalid + validate)) start = "```console\n$ tmux -L control new-session -d\n```\n" wrong_default = "| [`tmux_capture`](#{Blocks::TOOL_PAGES}/tmux_capture/) | Enabled | x |\n" - assert_match(/tool table differs/, refusal(wrong_default + start + "```console\n$ libtmux-mcp --socket-name control\n```\n")) + assert_match( + /tool table differs/, + refusal(wrong_default + start + "```console\n$ libtmux-mcp --socket-name control\n```\n") + ) - assert_match(/Invalid arguments/, refusal(start + "```console\n$ libtmux-mcp --socket-name control --no-such-option\n```\n")) + assert_match( + /Invalid arguments/, + refusal(start + "```console\n$ libtmux-mcp --socket-name control --no-such-option\n```\n") + ) assert_match(/does not show a command/, refusal("Prose only.\n")) end @@ -263,7 +350,8 @@ def test_split_recipe_does_not_require_a_posix_login_shell def test_each_workspace_load_runs_against_a_server_of_its_own workspace = "```yaml\nsession_name: a\nwindows:\n - window_name: a\n panes: [{}]\n```\n" - load = "```console\n$ libtmux-workspace load \\\n --socket \"$TMUX_SOCKET\" \\\n workspace.yaml\n```\n" + load = + "```console\n$ libtmux-workspace load \\\n --socket \"$TMUX_SOCKET\" \\\n workspace.yaml\n```\n" run_markdown(workspace + load + load, "control.md") end @@ -271,7 +359,9 @@ def test_the_runner_omits_one_example_and_checks_the_following_command previous_tmux = ENV["LIBTMUX_TEST_TMUX"] Dir.mktmpdir("libtmux-ruby-readme-floor-") do |directory| commands = File.join(directory, "commands") - ENV["LIBTMUX_TEST_TMUX"] = LibTmuxTest::StubExecutable.write(File.join(directory, "tmux"), <<~'STUB', COMMANDS: commands) + ENV["LIBTMUX_TEST_TMUX"] = LibTmuxTest::StubExecutable.write( + File.join(directory, "tmux"), + <<~'STUB', File.open(COMMANDS, "a") { |file| file.puts(ARGV.join(" ")) } case ARGV when ["-V"] then puts "tmux 3.4" @@ -279,6 +369,8 @@ def test_the_runner_omits_one_example_and_checks_the_following_command else abort "unexpected tmux command: #{ARGV.inspect}" end STUB + COMMANDS: commands + ) markdown = <<~MARKDOWN ```console $ ruby capture.rb @@ -311,7 +403,20 @@ def with_a_server_kill_server_leaves STUB sandbox = Sandbox.new(executable: noop) begin - assert sandbox.run(sandbox.tmux, "-L", "agent", "-f", "/dev/null", "new-session", "-d", "-s", "work").status.success? + assert sandbox + .run( + sandbox.tmux, + "-L", + "agent", + "-f", + "/dev/null", + "new-session", + "-d", + "-s", + "work" + ) + .status + .success? yield sandbox ensure LibTmuxTest::Sandbox.release(sandbox.directory, tmux: real.tmux) @@ -330,21 +435,29 @@ def run_markdown(markdown, where) File.write(File.join(sandbox.work, "workspace.yaml"), yaml.lines.join("\n") + "\n") if yaml table = tool_table(markdown) sandbox.provide_socket if markdown.include?("$TMUX_SOCKET") - events = Blocks.steps(markdown).map { |step| [step.line, step] } + - Blocks.fences(markdown).select { |fence| fence.language == "json" }.map { |fence| [fence.line, fence] } + events = + Blocks.steps(markdown).map { |step| [step.line, step] } + + Blocks + .fences(markdown) + .select { |fence| fence.language == "json" } + .map { |fence| [fence.line, fence] } ran = false - events.sort_by(&:first).each do |line, event| - ran = true - if event.is_a?(Blocks::Fence) - configuration = JSON.parse(event.lines.join("\n")).fetch("mcpServers") - configuration.each_value do |server| - assert_equal "libtmux-mcp", server.fetch("command"), "#{where}:#{line}: not a libtmux-mcp client entry" - launch(sandbox, server.fetch("args"), table, "#{where}:#{line}") + events + .sort_by(&:first) + .each do |line, event| + ran = true + if event.is_a?(Blocks::Fence) + configuration = JSON.parse(event.lines.join("\n")).fetch("mcpServers") + configuration.each_value do |server| + assert_equal "libtmux-mcp", + server.fetch("command"), + "#{where}:#{line}: not a libtmux-mcp client entry" + launch(sandbox, server.fetch("args"), table, "#{where}:#{line}") + end + else + step(sandbox, event, table, "#{where}:#{line}") end - else - step(sandbox, event, table, "#{where}:#{line}") end - end assert ran, "#{where} does not show a command or client configuration to run" ensure sandbox&.close @@ -357,24 +470,31 @@ def step(sandbox, step, table, where) assert sandbox.assign(command).status.success?, "#{where}: #{command}" elsif words.first == "gem" nil # Names and flags are checked by test/unit/readme_blocks_test.rb; installing needs the network. - elsif words.first(5) == %w[mise exec -- bundle exec] && words[5] == "ruby" && words[6]&.start_with?("examples/") + elsif words.first(5) == %w[mise exec -- bundle exec] && words[5] == "ruby" && + words[6]&.start_with?("examples/") run_ruby_example(sandbox, File.join(Blocks::ROOT, words[6]), step, where) elsif words.first == "ruby" && words.length == 2 && (source = ruby_example(words[1])) # The page says to save the example above under that name; the example source is that program. run_ruby_example(sandbox, source, step, where) elsif words.first == "mise" nil # Checkout setup and builds; test/packaging builds and installs the artifacts. - elsif %w[claude codex].include?(words.first) && words[1, 2] == %w[mcp add] && words.include?("--") + elsif %w[claude codex].include?(words.first) && words[1, 2] == %w[mcp add] && + words.include?("--") server = words.drop(words.index("--") + 1) assert_equal "libtmux-mcp", server.first, "#{where}: not a libtmux-mcp client command" launch(sandbox, server.drop(1), table, where) elsif words.first == "libtmux-mcp" launch(sandbox, words.drop(1), table, where) elsif %w[tmux libtmux-workspace rm].include?(words.first) - sandbox.provide_socket if words.first == "libtmux-workspace" && words.include?("load") && sandbox.variable("TMUX_SOCKET") + if words.first == "libtmux-workspace" && words.include?("load") && + sandbox.variable("TMUX_SOCKET") + sandbox.provide_socket + end result = sandbox.shell(command) assert result.status.success?, "#{where}: #{command}\n#{result.stdout}#{result.stderr}" - assert_equal step.output, result.stdout, "#{where}: output differs from the page" if step.output + if step.output + assert_equal step.output, result.stdout, "#{where}: output differs from the page" + end inspect_output(command, words, result, where) else flunk "#{where}: no verifier for the command #{command}" @@ -388,7 +508,7 @@ def run_ruby_example(sandbox, source, step, where) if entry&.dig("api", "minimum_tmux") release = sandbox.tmux_release if (minimum = manifest.unmet_example_minimum(entry, release)) - warn "Omitted Ruby example #{entry.fetch('id')} in #{where} on tmux #{release.text}. It requires tmux #{minimum} or newer." + warn "Omitted Ruby example #{entry.fetch("id")} in #{where} on tmux #{release.text}. It requires tmux #{minimum} or newer." return end end @@ -398,12 +518,18 @@ def run_ruby_example(sandbox, source, step, where) end def ruby_example(name) - %w[examples examples/api].map { |dir| File.join(Blocks::ROOT, dir, name) }.find { |path| File.file?(path) } + %w[examples examples/api] + .map { |dir| File.join(Blocks::ROOT, dir, name) } + .find { |path| File.file?(path) } end def inspect_output(command, words, result, where) if words.first == "libtmux-workspace" && words.last == "--version" - expected = Gem::Specification.load(File.join(Blocks::ROOT, "gems/libtmux-workspace/libtmux-workspace.gemspec")).version.to_s + expected = + Gem::Specification + .load(File.join(Blocks::ROOT, "gems/libtmux-workspace/libtmux-workspace.gemspec")) + .version + .to_s assert_equal "#{expected}\n", result.stdout, "#{where}: version differs from the gem" end if words.include?("--json") @@ -411,7 +537,9 @@ def inspect_output(command, words, result, where) refute value.key?("error"), "#{where}: #{result.stdout}" assert value.fetch("success"), "#{where}: #{result.stdout}" if words[1] == "load" end - CLAIMS.each { |pattern, shown| assert_match shown, result.stdout, "#{where}: #{command}" if command.match?(pattern) } + CLAIMS.each do |pattern, shown| + assert_match shown, result.stdout, "#{where}: #{command}" if command.match?(pattern) + end end # Runs `libtmux-mcp ARGS` against the server the page started, over stdio. @@ -419,27 +547,41 @@ def launch(sandbox, argv, table, where) socket = sandbox.variable("TMUX_SOCKET") argv = argv.map { |word| word.gsub("$TMUX_SOCKET", socket.to_s) } options = argv.each_cons(2).to_h { |flag, value| [flag, value] } - enabled = CATALOG::READ_ONLY + argv.each_cons(2).filter_map { |flag, value| value if flag == "--enable-tool" } + enabled = + CATALOG::READ_ONLY + + argv.each_cons(2).filter_map { |flag, value| value if flag == "--enable-tool" } endpoint = options.fetch("--endpoint", "local") - setup = argv.each_cons(2).filter_map { |flag, value| value.split("=", 2).last if flag == "--enroll-pane" } + setup = + argv + .each_cons(2) + .filter_map { |flag, value| value.split("=", 2).last if flag == "--enroll-pane" } setup = setup.map { |name| File.expand_path(name, sandbox.work) } served = nil - flag = options.key?("--socket-name") ? ["-L", options["--socket-name"]] : ["-S", options["--socket"]] + flag = + options.key?("--socket-name") ? ["-L", options["--socket-name"]] : ["-S", options["--socket"]] # --start-session starts a server only when none answers, and then stops it at EOF unless --keep. answering = sandbox.run(sandbox.tmux, *flag, "has-session").status.success? - result = sandbox.mcp(argv, where) do |session| - served = session.tools.sort - assert_equal endpoint, session.capabilities.fetch("endpoint"), "#{where}: --endpoint is not the public alias" - setup.each do |file| - assert_equal 0o600, File.stat(file).mode & 0o777, "#{where}: setup file is not private" - assert File.read(file).start_with?("source "), "#{where}: setup file does not source the helper" + result = + sandbox.mcp(argv, where) do |session| + served = session.tools.sort + assert_equal endpoint, + session.capabilities.fetch("endpoint"), + "#{where}: --endpoint is not the public alias" + setup.each do |file| + assert_equal 0o600, File.stat(file).mode & 0o777, "#{where}: setup file is not private" + assert File.read(file).start_with?("source "), + "#{where}: setup file does not source the helper" + end end - end assert_equal enabled.uniq.sort, served, "#{where}: tools served differ from the tools enabled" unless table.empty? || argv.include?("--enable-tool") - assert_equal table.select { |_, on| on }.keys.sort, served, "#{where}: the tool table differs from the default tools" + assert_equal table.select { |_, on| on }.keys.sort, + served, + "#{where}: the tool table differs from the default tools" end - assert_equal 0, result.status&.exitstatus, "#{where}: EOF did not end the server: #{result.stderr}" + assert_equal 0, + result.status&.exitstatus, + "#{where}: EOF did not end the server: #{result.stderr}" assert_empty result.stderr, "#{where}: the server wrote to stderr" setup.each { |file| refute File.exist?(file), "#{where}: setup file survived EOF" } stops = options.key?("--start-session") && !answering && !argv.include?("--keep") @@ -453,9 +595,12 @@ def launch(sandbox, argv, table, where) # Tool name => enabled by default, from the rows of the Tools | Default table. def tool_table(markdown) - markdown.lines.grep(/\A\| .*\[`tmux_[a-z_]+`\].* \| (?:Enabled|Disabled) \|/).each_with_object({}) do |row, table| - state = row[/\| (Enabled|Disabled) \|/, 1] == "Enabled" - row.split(" | ").first.scan(/\[`(tmux_[a-z_]+)`\]/) { |(name)| table[name] = state } - end + markdown + .lines + .grep(/\A\| .*\[`tmux_[a-z_]+`\].* \| (?:Enabled|Disabled) \|/) + .each_with_object({}) do |row, table| + state = row[/\| (Enabled|Disabled) \|/, 1] == "Enabled" + row.split(" | ").first.scan(/\[`(tmux_[a-z_]+)`\]/) { |(name)| table[name] = state } + end end end diff --git a/test/integration/sandbox_test.rb b/test/integration/sandbox_test.rb index 2bc9026d..7652492a 100644 --- a/test/integration/sandbox_test.rb +++ b/test/integration/sandbox_test.rb @@ -27,7 +27,8 @@ def test_the_canary_rejects_a_client_whose_tmux_tmpdir_is_another_directory output, status = bare_client("TMUX_TMPDIR" => other) refute_predicate status, :success? refute looks_in_the_sandbox?(output) - assert output.include?(File.join(other, "tmux-#{Process.uid}", "default")), "the client did not name the path it looked in" + assert output.include?(File.join(other, "tmux-#{Process.uid}", "default")), + "the client did not name the path it looked in" end end @@ -36,7 +37,8 @@ def test_the_canary_rejects_a_client_that_inherits_a_server output, status = bare_client("TMUX" => "/lt-rb-canary-decoy/socket,1,0") refute_predicate status, :success? refute looks_in_the_sandbox?(output) - assert output.include?("/lt-rb-canary-decoy/socket"), "the client did not name the path it looked in" + assert output.include?("/lt-rb-canary-decoy/socket"), + "the client did not name the path it looked in" end def test_the_resolver_looks_where_a_client_looks @@ -49,8 +51,12 @@ def test_the_resolver_looks_where_a_client_looks def test_the_resolver_check_can_fail_because_the_default_moves_with_tmux_tmpdir require_sandbox - path = without_tmux_tmpdir { LibTmux::Endpoint.new(socket_name: "default", executable: EXECUTABLE).socket_path } - assert path == "/tmp/tmux-#{Process.uid}/default", "the resolver did not fall back to /tmp without TMUX_TMPDIR" + path = + without_tmux_tmpdir do + LibTmux::Endpoint.new(socket_name: "default", executable: EXECUTABLE).socket_path + end + assert path == "/tmp/tmux-#{Process.uid}/default", + "the resolver did not fall back to /tmp without TMUX_TMPDIR" refute path == default_socket, "the resolver ignored the missing TMUX_TMPDIR" end @@ -64,7 +70,8 @@ def test_a_server_opened_on_the_default_name_finds_nothing private def require_sandbox - assert_empty LibTmuxTest::Sandbox.violations(ENV), "refusing to start a client outside the sandbox" + assert_empty LibTmuxTest::Sandbox.violations(ENV), + "refusing to start a client outside the sandbox" end def bare_client(env = {}) diff --git a/test/integration/server_control_test.rb b/test/integration/server_control_test.rb index 8a069730..4d93a39c 100644 --- a/test/integration/server_control_test.rb +++ b/test/integration/server_control_test.rb @@ -15,17 +15,19 @@ def test_server_owns_bounded_control_clients_and_closes_pending_exchanges session = server.list_sessions.first control = server.open_control(session: session.ref) - assert_equal "ready\n", control.exchange("display-message -p ready", timeout: 0.5).blocks.last.body + assert_equal "ready\n", + control.exchange("display-message -p ready", timeout: 0.5).blocks.last.body assert_equal 1, server.diagnostics.fetch(:control_connections) assert_raises(LibTmux::CapacityError) { server.open_control(session: session.ref) } assert server.list_clients.any? { |client| client[:pid] == control.pid && client[:control] } control.close replacement = server.open_control(session: session.ref) - request = Thread.new do - replacement.exchange("wait-for -S scoped-ready ; wait-for scoped-held", timeout: 0.5) - rescue LibTmux::Error => error - error - end + request = + Thread.new do + replacement.exchange("wait-for -S scoped-ready ; wait-for scoped-held", timeout: 0.5) + rescue LibTmux::Error => error + error + end begin assert fixture.tmux("wait-for", "scoped-ready").last.success? server.close @@ -48,11 +50,20 @@ def test_control_block_preserves_result_exception_and_binding_checks session = server.list_sessions.first pid = nil - assert_equal :returned, server.open_control(session: session.ref) { |control| pid = control.pid; :returned } + assert_equal :returned, + server.open_control(session: session.ref) { |control| + pid = control.pid + :returned + } assert_raises(Errno::ECHILD) { Process.waitpid(pid, Process::WNOHANG) } original = RuntimeError.new("caller failure") - assert_same original, assert_raises(RuntimeError) { server.open_control(session: session.ref) { raise original } } - assert_raises(LibTmux::TargetNotFoundError) { server.open_control(session: server.list_windows.first.ref) } + assert_same original, + assert_raises(RuntimeError) { + server.open_control(session: session.ref) { raise original } + } + assert_raises(LibTmux::TargetNotFoundError) do + server.open_control(session: server.list_windows.first.ref) + end end end end diff --git a/test/integration/server_test.rb b/test/integration/server_test.rb index 9b61d2c4..d0993bb7 100644 --- a/test/integration/server_test.rb +++ b/test/integration/server_test.rb @@ -11,16 +11,19 @@ def test_omitted_creation_names_and_commands_use_tmux_defaults LibTmuxTest::TmuxFixture.open do |fixture| open_server(fixture) do |server| server.options(scope: :session).set("default-command", "exec /bin/cat") - native, _, status = fixture.tmux("new-window", "-d", "-P", "-F", '#{pane_start_command}', "-t", "fixture") + native, _, status = + fixture.tmux("new-window", "-d", "-P", "-F", '#{pane_start_command}', "-t", "fixture") assert status.success? assert_includes native, "/bin/cat" created = server.new_session(receipt: true) added = created.entity.new_window(name: nil, command: nil, receipt: true) - panes = [created.pane, added.pane, added.window.split(direction: :horizontal), - added.pane.split(direction: :vertical)] - panes.each do |pane| - assert_equal native, pane.display('#{pane_start_command}').text - end + panes = [ + created.pane, + added.pane, + added.window.split(direction: :horizontal), + added.pane.split(direction: :vertical) + ] + panes.each { |pane| assert_equal native, pane.display('#{pane_start_command}').text } refute_empty created.entity.snapshot.name refute_empty added.window.snapshot.name assert_raises(ArgumentError) { created.entity.new_window(command: []) } @@ -37,15 +40,22 @@ def test_literal_creation_topology_and_terminal_input name = "session \#{pid} ';" session = server.new_session(name: name, command: [executable], width: 80, height: 24) assert_match(/\A\$\d+\z/, session.id) - assert_equal "#{name}\n", server.run(["display-message", "-p", "-t", session.id, '#{session_name}']).text + assert_equal "#{name}\n", + server.run(["display-message", "-p", "-t", session.id, '#{session_name}']).text assert_equal ["$0", session.id], server.list_sessions.map(&:id) receipt = UNIXServer.new(File.join(File.dirname(fixture.socket_path), "receipt")) begin - code = 'line = STDIN.gets; UNIXSocket.open(ARGV.fetch(0)) { |io| io.write(line) }; STDIN.read' - window = session.new_window(name: "window \#{pane_id};", command: [Gem.ruby, "--disable=rubyopt,gems", "-rsocket", "-e", code, receipt.path]) + code = + "line = STDIN.gets; UNIXSocket.open(ARGV.fetch(0)) { |io| io.write(line) }; STDIN.read" + window = + session.new_window( + name: "window \#{pane_id};", + command: [Gem.ruby, "--disable=rubyopt,gems", "-rsocket", "-e", code, receipt.path] + ) assert_match(/\A@\d+\z/, window.id) - assert_equal "window \#{pane_id};\n", server.run(["display-message", "-p", "-t", window.id, '#{window_name}']).text + assert_equal "window \#{pane_id};\n", + server.run(["display-message", "-p", "-t", window.id, '#{window_name}']).text pane = window.list_panes.fetch(0) text = "C-a \#{pane_id};" assert pane.send_text(text).success? @@ -121,9 +131,10 @@ def test_dead_original_handles_cannot_dispatch_to_replaced_selector Dir.mkdir(File.dirname(original_path), 0o700) File.link(replacement.socket_path, original_path) assert_raises(LibTmux::Error) { server.capabilities } - failure = assert_raises(LibTmux::CommandError) do - server.new_session(name: "must-not-exist", command: ["/bin/cat"]) - end + failure = + assert_raises(LibTmux::CommandError) do + server.new_session(name: "must-not-exist", command: ["/bin/cat"]) + end refute failure.result.success? assert_equal :observed, failure.delivery refute replacement.tmux("has-session", "-t", "must-not-exist").last.success? @@ -138,11 +149,12 @@ def test_dead_original_handles_cannot_dispatch_to_replaced_selector def test_close_cancels_owned_clients_and_preserves_the_borrowed_daemon LibTmuxTest::TmuxFixture.open do |fixture| server = open_server(fixture) - request = Thread.new do - server.run(["wait-for", "-S", "ruby-ready", ";", "wait-for", "ruby-held"]) - rescue LibTmux::Cancelled => error - error - end + request = + Thread.new do + server.run(%w[wait-for -S ruby-ready ; wait-for ruby-held]) + rescue LibTmux::Cancelled => error + error + end begin assert fixture.tmux("wait-for", "ruby-ready").last.success? server.close @@ -169,7 +181,10 @@ def test_block_result_and_original_exception_survive_cleanup def test_pre_cancelled_request_never_attempts_spawn LibTmuxTest::TmuxFixture.open do |fixture| executable = File.join(File.dirname(fixture.socket_path), "removed-client") - File.write(executable, "#!#{RbConfig.ruby} --disable=rubyopt,gems\nexec #{fixture.executable.inspect}, *ARGV\n") + File.write( + executable, + "#!#{RbConfig.ruby} --disable=rubyopt,gems\nexec #{fixture.executable.inspect}, *ARGV\n" + ) File.chmod(0o700, executable) endpoint = LibTmux::Endpoint.new(socket_path: fixture.socket_path, executable: executable) LibTmux::Server.open(endpoint: endpoint) do |server| @@ -177,7 +192,8 @@ def test_pre_cancelled_request_never_attempts_spawn token = LibTmux::Internal::Cancellation.new begin token.cancel - failure = assert_raises(LibTmux::Cancelled) { server.run(["list-sessions"], cancel: token) } + failure = + assert_raises(LibTmux::Cancelled) { server.run(["list-sessions"], cancel: token) } assert_equal :not_sent, failure.delivery ensure token.close @@ -188,7 +204,12 @@ def test_pre_cancelled_request_never_attempts_spawn def test_admission_is_bounded_and_close_can_retry_after_its_deadline LibTmuxTest::TmuxFixture.open do |fixture| - server = LibTmux::Server.open(socket_path: fixture.socket_path, max_requests: 2, close_timeout: Float::MIN) + server = + LibTmux::Server.open( + socket_path: fixture.socket_path, + max_requests: 2, + close_timeout: Float::MIN + ) requests = [] begin 2.times do |index| @@ -201,8 +222,20 @@ def test_admission_is_bounded_and_close_can_retry_after_its_deadline end assert_respond_to server, :diagnostics active = server.diagnostics - assert_equal({admitted_requests: 2, reserved_process_slots: 2, control_connections: 0, - closed: false, limits: {max_requests: 2, max_controls: 4, close_timeout: Float::MIN}}, active) + assert_equal( + { + admitted_requests: 2, + reserved_process_slots: 2, + control_connections: 0, + closed: false, + limits: { + max_requests: 2, + max_controls: 4, + close_timeout: Float::MIN + } + }, + active + ) assert active.frozen? assert active.fetch(:limits).frozen? failure = assert_raises(LibTmux::CapacityError) { server.run(["list-sessions"]) } @@ -232,20 +265,22 @@ def test_repeated_interrupt_preserves_the_block_error_during_close LibTmuxTest::TmuxFixture.open do |fixture| entered = Queue.new release = Queue.new - type = Class.new(LibTmux::Server) do - define_method(:close) do - super() - entered << true - release.pop + type = + Class.new(LibTmux::Server) do + define_method(:close) do + super() + entered << true + release.pop + end end - end original = RuntimeError.new("first failure") deferred = RuntimeError.new("second failure") - worker = Thread.new do - type.open(socket_path: fixture.socket_path) { raise original } - rescue Exception => failure - failure - end + worker = + Thread.new do + type.open(socket_path: fixture.socket_path) { raise original } + rescue Exception => failure + failure + end begin entered.pop worker.raise(deferred) @@ -262,26 +297,28 @@ def test_repeated_interrupt_preserves_the_block_error_during_close def test_fork_close_cannot_cancel_a_parent_request LibTmuxTest::TmuxFixture.open do |fixture| server = open_server(fixture) - request = Thread.new do - server.run(["wait-for", "-S", "fork-ready", ";", "wait-for", "fork-held"]) - rescue LibTmux::Cancelled => failure - failure - end + request = + Thread.new do + server.run(%w[wait-for -S fork-ready ; wait-for fork-held]) + rescue LibTmux::Cancelled => failure + failure + end reader, writer = IO.pipe child = nil begin assert fixture.tmux("wait-for", "fork-ready").last.success? - child = fork do - reader.close - server.close - begin - server.run(["list-sessions"]) - exit! 1 - rescue LibTmux::ClosedError - writer.write("closed") - exit! 0 + child = + fork do + reader.close + server.close + begin + server.run(["list-sessions"]) + exit! 1 + rescue LibTmux::ClosedError + writer.write("closed") + exit! 0 + end end - end writer.close assert IO.select([reader], nil, nil, 0.5), "fork close blocked on parent requests" assert_equal "closed", reader.read diff --git a/test/integration/session_guard_test.rb b/test/integration/session_guard_test.rb index 18c30262..d9f577cb 100644 --- a/test/integration/session_guard_test.rb +++ b/test/integration/session_guard_test.rb @@ -13,9 +13,13 @@ def test_conditional_kill_refuses_unknown_windows_and_allows_proven_membership panes = owned.list_panes.map(&:ref) borrowed = server.list_sessions.find { |session| session.id != owned.id } borrowed_window = borrowed.list_windows.first - assert_raises(LibTmux::TargetNotFoundError) { owned.kill(expected_windows: [], expected_panes: []) } + assert_raises(LibTmux::TargetNotFoundError) do + owned.kill(expected_windows: [], expected_panes: []) + end owned.link_window(borrowed_window.ref, index: 9) - assert_raises(LibTmux::TargetNotFoundError) { owned.kill(expected_windows: expected, expected_panes: panes) } + assert_raises(LibTmux::TargetNotFoundError) do + owned.kill(expected_windows: expected, expected_panes: panes) + end assert_includes server.list_windows.map(&:ref), borrowed_window.ref owned.list_window_links.find { |link| link.id == borrowed_window.id }.unlink assert owned.kill(expected_windows: expected, expected_panes: panes).success? @@ -31,16 +35,35 @@ def test_guard_rechecks_panes_after_preflight_wait_and_bypasses_static_aliases borrowed = server.list_panes.first created = server.new_session(name: "guarded", command: ["cat"], receipt: true) server.options(scope: :server).set("command-alias", "if-shell=wait-for never", index: 90) - server.options(scope: :server).set("command-alias", "kill-session=wait-for never", index: 91) - assert fixture.tmux("set-hook", "-g", "after-show-options[99]", "wait-for -S ownership-ready ; wait-for ownership-release").last.success? - request = Thread.new do - created.entity.kill(expected_windows: [created.window.ref], expected_panes: [created.pane.ref]) - rescue LibTmux::TargetNotFoundError => error - error - end + server.options(scope: :server).set( + "command-alias", + "kill-session=wait-for never", + index: 91 + ) + assert fixture + .tmux( + "set-hook", + "-g", + "after-show-options[99]", + "wait-for -S ownership-ready ; wait-for ownership-release" + ) + .last + .success? + request = + Thread.new do + created.entity.kill( + expected_windows: [created.window.ref], + expected_panes: [created.pane.ref] + ) + rescue LibTmux::TargetNotFoundError => error + error + end begin assert fixture.tmux("wait-for", "ownership-ready").last.success? - assert fixture.tmux("join-pane", "-d", "-s", borrowed.id, "-t", created.pane.id).last.success? + assert fixture + .tmux("join-pane", "-d", "-s", borrowed.id, "-t", created.pane.id) + .last + .success? assert fixture.tmux("set-hook", "-gu", "after-show-options[99]").last.success? assert fixture.tmux("wait-for", "-S", "ownership-release").last.success? assert request.join(0.5), "ownership guard did not settle" diff --git a/test/integration/snapshot_test.rb b/test/integration/snapshot_test.rb index 6c8f7367..2e8615d9 100644 --- a/test/integration/snapshot_test.rb +++ b/test/integration/snapshot_test.rb @@ -7,7 +7,9 @@ require "pty" require "libtmux/control" require "socket" -require "libtmux/capture" if File.exist?(File.expand_path("../../gems/libtmux/lib/libtmux/capture.rb", __dir__)) +if File.exist?(File.expand_path("../../gems/libtmux/lib/libtmux/capture.rb", __dir__)) + require "libtmux/capture" +end class SnapshotIntegrationTest < Minitest::Test include LibTmuxTest::ControlSupport @@ -15,25 +17,26 @@ class SnapshotIntegrationTest < Minitest::Test def test_three_links_have_one_global_window_and_local_readers_outlive_server LibTmuxTest::TmuxFixture.open do |fixture| LibTmux::Server.open(socket_path: fixture.socket_path) do |server| - assert server.run(["link-window", "-s", "@0", "-t", "$0:5"]).success? - assert server.run(["link-window", "-s", "@0", "-t", "$0:10"]).success? + assert server.run(%w[link-window -s @0 -t $0:5]).success? + assert server.run(%w[link-window -s @0 -t $0:10]).success? capture = acquire(server, clients: true) assert_equal ["@0"], capture.windows.map(&:id) assert_equal ["%0"], capture.panes.map(&:id) assert_equal [0, 5, 10], capture.window_links.map(&:index) - assert_equal ["@0", "@0", "@0"], capture.sessions.one.windows.map(&:id) + assert_equal %w[@0 @0 @0], capture.sessions.one.windows.map(&:id) assert_equal 3, capture.window_links.map(&:ref).uniq.size assert_equal capture.window_links.first.ref, server.list_window_links.first.ref assert_empty capture.clients assert capture.finished_at >= capture.started_at assert_operator capture.server_info.fetch(:pid), :>, 0 assert capture.server_info.fetch(:version).frozen? - assert_equal %i[server session window_link pane client], capture.reads.map { |read| read.fetch(:source) } + assert_equal %i[server session window_link pane client], + capture.reads.map { |read| read.fetch(:source) } refreshed = acquire(server) assert_equal capture.panes.one.ref, refreshed.panes.one.ref refute_equal capture.panes.one, refreshed.panes.one server.close - assert_equal ["@0", "@0", "@0"], capture.sessions.one.windows.map(&:id) + assert_equal %w[@0 @0 @0], capture.sessions.one.windows.map(&:id) assert_equal ["%0"], capture.panes.one.window.panes.map(&:id) assert capture.panes.one.active? refute_empty capture.panes.one.current_command @@ -50,8 +53,23 @@ def test_embedded_newlines_and_invalid_utf8_are_preserved_in_metadata ready = UNIXServer.new(File.join(File.dirname(fixture.socket_path), "ready")) begin code = 'UNIXSocket.open(ARGV.fetch(0)) { |io| io.write("ready") }; STDIN.read' - assert server.run(["new-window", "-d", "-t", "$0", "-c", directory, "--", - Gem.ruby, "--disable=rubyopt,gems", "-rsocket", "-e", code, ready.path]).success? + assert server.run( + [ + "new-window", + "-d", + "-t", + "$0", + "-c", + directory, + "--", + Gem.ruby, + "--disable=rubyopt,gems", + "-rsocket", + "-e", + code, + ready.path + ] + ).success? assert IO.select([ready], nil, nil, 0.5), "pane did not announce its working directory" peer = ready.accept begin @@ -62,11 +80,12 @@ def test_embedded_newlines_and_invalid_utf8_are_preserved_in_metadata end # User options retain bytes that pane titles and some filesystems reject. assert server.run(["set-option", "-p", "-t", "%1", "@binary", payload]).success? - format = LibTmux::Internal::Metadata.format(["@binary", "pane_current_path"]) + format = LibTmux::Internal::Metadata.format(%w[@binary pane_current_path]) result = server.run(["list-panes", "-t", "@1", "-F", format]) assert result.success? canonical = File.realpath(directory).b - assert_equal [[payload, canonical]], LibTmux::Internal::Metadata.decode(result.stdout, fields: 2, quoted: true) + assert_equal [[payload, canonical]], + LibTmux::Internal::Metadata.decode(result.stdout, fields: 2, quoted: true) capture = acquire(server) pane = capture.panes.select { |record| record.id == "%1" }.one assert_equal canonical, pane.raw(:current_path) @@ -82,21 +101,22 @@ def test_embedded_newlines_and_invalid_utf8_are_preserved_in_metadata def test_a_real_capture_race_retries_once_and_persistent_races_raise LibTmuxTest::TmuxFixture.open do |fixture| - racing_server = Class.new(LibTmux::Server) do - attr_accessor :race_limit - attr_reader :race_count + racing_server = + Class.new(LibTmux::Server) do + attr_accessor :race_limit + attr_reader :race_count - private + private - def execute_typed(argv, **options) - result = super - if argv.first == "list-windows" && (@race_count || 0) < race_limit - @race_count = (@race_count || 0) + 1 - super(["new-window", "-d", "-t", "$0", "--", "/bin/cat"], **options) + def execute_typed(argv, **options) + result = super + if argv.first == "list-windows" && (@race_count || 0) < race_limit + @race_count = (@race_count || 0) + 1 + super(%w[new-window -d -t $0 -- /bin/cat], **options) + end + result end - result end - end racing_server.open(socket_path: fixture.socket_path) do |server| server.race_limit = 1 capture = acquire(server) @@ -133,7 +153,10 @@ def test_capture_bounds_are_checked_without_mutation def test_requested_clients_are_observations_and_empty_server_is_a_complete_graph LibTmuxTest::TmuxFixture.open do |fixture| - LibTmux::Server.open(socket_path: fixture.socket_path, executable: fixture.executable) do |server| + LibTmux::Server.open( + socket_path: fixture.socket_path, + executable: fixture.executable + ) do |server| pin = LibTmux::Internal::SocketIdentity.new(server.endpoint) begin if require_control_binding(pin) @@ -157,8 +180,8 @@ def test_requested_clients_are_observations_and_empty_server_is_a_complete_graph ensure pin.close end - assert server.run(["set-option", "-s", "exit-empty", "off"]).success? - assert server.run(["kill-session", "-t", "$0"]).success? + assert server.run(%w[set-option -s exit-empty off]).success? + assert server.run(%w[kill-session -t $0]).success? capture = acquire(server, clients: true) assert_empty capture.sessions assert_empty capture.windows @@ -176,14 +199,18 @@ def observe_terminal_client(server) PTY.open do |_master, terminal| terminal.winsize = [24, 80] session = server.list_sessions.first - worker = Thread.new do - server.attach(session: session.ref, terminal: terminal, term: "xterm", cancel: token) - rescue LibTmux::Cancelled - nil - end + worker = + Thread.new do + server.attach(session: session.ref, terminal: terminal, term: "xterm", cancel: token) + rescue LibTmux::Cancelled + nil + end begin deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 2 - sleep 0.01 until !server.list_clients.empty? || Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline + until !server.list_clients.empty? || + Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline + sleep 0.01 + end capture = acquire(server, clients: true) client = capture.clients.one assert_equal "$0", client.session_id diff --git a/test/integration/startup_test.rb b/test/integration/startup_test.rb index 1d96ce01..6cb7469e 100644 --- a/test/integration/startup_test.rb +++ b/test/integration/startup_test.rb @@ -3,7 +3,9 @@ require_relative "../test_helper" require_relative "../support/tmux_fixture" require "libtmux" -require "libtmux/owned" if File.exist?(File.expand_path("../../gems/libtmux/lib/libtmux/owned.rb", __dir__)) +if File.exist?(File.expand_path("../../gems/libtmux/lib/libtmux/owned.rb", __dir__)) + require "libtmux/owned" +end class StartupTest < Minitest::Test def test_log_readiness_disables_logging_before_exposing_the_owned_server @@ -16,12 +18,15 @@ def test_log_readiness_disables_logging_before_exposing_the_owned_server path = pid = nil LibTmux::Server.start(timeout: 0.5) do |server| path = File.dirname(server.endpoint.socket_path) - pid = Integer(server.run(["display-message", "-p", '#{pid}']).text) + pid = Integer(server.run(%w[display-message -p #{pid}]).text) assert log_readiness.stopped? assert_operator log_readiness.bytes_read, :>, 0 - assert_operator log_readiness.bytes_read, :<=, LibTmux::Internal.const_get(:LogSocketReadiness, false)::LIMIT + assert_operator log_readiness.bytes_read, + :<=, + LibTmux::Internal.const_get(:LogSocketReadiness, false)::LIMIT assert_empty Dir[File.join(path, "*.log")] - assert_equal "ready-without-logging\n", server.run(["display-message", "-p", "ready-without-logging"]).text + assert_equal "ready-without-logging\n", + server.run(%w[display-message -p ready-without-logging]).text assert_empty Dir[File.join(path, "*.log")] end assert_raises(Errno::ECHILD) { Process.waitpid(pid, Process::WNOHANG) } @@ -39,12 +44,18 @@ def test_oversized_startup_log_fails_closed_and_reaps_its_writer Dir.mktmpdir("libtmux-ruby-log-writer-") do |directory| executable = File.join(directory, "writer") record = File.join(directory, "owned-path") - File.write(executable, "#!#{RbConfig.ruby} --disable=rubyopt,gems\n" \ - "if ARGV == ['-V']; puts 'tmux 3.3a'; exit; end\n" \ - "File.write(#{record.inspect}, Dir.pwd)\n" \ - "File.binwrite(\"tmux-server-\#{Process.pid}.log\", 'x' * ((1 << 22) + 1))\nIO.select([])\n") + File.write( + executable, + "#!#{RbConfig.ruby} --disable=rubyopt,gems\n" \ + "if ARGV == ['-V']; puts 'tmux 3.3a'; exit; end\n" \ + "File.write(#{record.inspect}, Dir.pwd)\n" \ + "File.binwrite(\"tmux-server-\#{Process.pid}.log\", 'x' * ((1 << 22) + 1))\nIO.select([])\n" + ) File.chmod(0o700, executable) - error = assert_raises(LibTmux::CapacityError) { LibTmux::Server.start(executable: executable, timeout: 0.5) } + error = + assert_raises(LibTmux::CapacityError) do + LibTmux::Server.start(executable: executable, timeout: 0.5) + end assert_equal :possibly_sent, error.delivery assert_equal :startup, error.phase assert_raises(Errno::ECHILD) { Process.waitpid(error.pid, Process::WNOHANG) } @@ -65,7 +76,7 @@ def test_explicit_start_owns_an_empty_daemon_and_cleanup_preserves_borrowed_serv owned_path = server.endpoint.socket_path assert_equal 0o700, File.stat(File.dirname(owned_path)).mode & 0o777 assert_equal [], server.list_sessions.to_a - daemon_pid = Integer(server.run(["display-message", "-p", '#{pid}']).text) + daemon_pid = Integer(server.run(%w[display-message -p #{pid}]).text) assert_operator daemon_pid, :>, 0 created = server.new_session(name: "owned", command: ["cat"]) assert_equal [created.ref], server.list_sessions.map(&:ref) @@ -95,13 +106,14 @@ def test_global_listings_on_an_empty_and_a_populated_daemon def test_block_failure_and_pre_cancel_leave_no_owned_daemon_or_directory failure = RuntimeError.new("caller failure") path = pid = nil - observed = assert_raises(RuntimeError) do - LibTmux::Server.start do |server| - path = server.endpoint.socket_path - pid = Integer(server.run(["display-message", "-p", '#{pid}']).text) - raise failure + observed = + assert_raises(RuntimeError) do + LibTmux::Server.start do |server| + path = server.endpoint.socket_path + pid = Integer(server.run(%w[display-message -p #{pid}]).text) + raise failure + end end - end assert_same failure, observed assert_raises(Errno::ECHILD) { Process.waitpid(pid, Process::WNOHANG) } refute File.exist?(File.dirname(path)) @@ -119,9 +131,13 @@ def test_block_failure_and_pre_cancel_leave_no_owned_daemon_or_directory def test_early_daemon_exit_is_reported_and_reaped Dir.mktmpdir("libtmux-ruby-early-exit-") do |directory| executable = File.join(directory, "exit") - File.write(executable, "#!#{RbConfig.ruby} --disable=rubyopt,gems\nif ARGV == ['-V']; puts 'tmux 3.3a'; exit; end\nexit 1\n") + File.write( + executable, + "#!#{RbConfig.ruby} --disable=rubyopt,gems\nif ARGV == ['-V']; puts 'tmux 3.3a'; exit; end\nexit 1\n" + ) File.chmod(0o700, executable) - error = assert_raises(LibTmux::TransportError) { LibTmux::Server.start(executable: executable) } + error = + assert_raises(LibTmux::TransportError) { LibTmux::Server.start(executable: executable) } assert_equal :startup, error.phase assert_equal :possibly_sent, error.delivery assert_operator error.pid, :>, 0 @@ -135,11 +151,12 @@ def test_no_block_constructor_interrupt_retires_daemon_during_ownership_transfer constructor = daemon_class.method(:new) failure = Interrupt.new("cancel constructor transfer") owned = nil - factory = lambda do |**options| - owned = constructor.call(**options) - Thread.current.raise failure - owned - end + factory = + lambda do |**options| + owned = constructor.call(**options) + Thread.current.raise failure + owned + end begin daemon_class.define_singleton_method(:new, factory) observed = assert_raises(Interrupt) { LibTmux::Server.start } @@ -158,14 +175,22 @@ def test_cancel_after_spawn_retires_unready_child_and_owned_directory held_input, writer = IO.pipe original = Process.method(:spawn) path = nil - replacement = lambda do |*argv, **options| - next original.call(*argv, **options) if argv.include?("-V") + replacement = + lambda do |*argv, **options| + next original.call(*argv, **options) if argv.include?("-V") - path = argv.fetch(argv.index("-S") + 1) - child = original.call("/bin/cat", in: held_input, out: File::NULL, err: File::NULL, close_others: true) - token.cancel - child - end + path = argv.fetch(argv.index("-S") + 1) + child = + original.call( + "/bin/cat", + in: held_input, + out: File::NULL, + err: File::NULL, + close_others: true + ) + token.cancel + child + end begin Process.define_singleton_method(:spawn, replacement) error = assert_raises(LibTmux::Cancelled) { LibTmux::Server.start(cancel: token) } @@ -184,24 +209,25 @@ def test_repeated_interrupt_during_close_preserves_first_error_and_reaps entered, release = Queue.new, Queue.new first, second = Interrupt.new("first cancellation"), Interrupt.new("cleanup cancellation") path = pid = nil - worker = Thread.new do - LibTmux::Server.start do |server| - path = server.endpoint.socket_path - child = server.instance_variable_get(:@daemon).instance_variable_get(:@child) - pid = child.pid - original = child.method(:signal) - child.define_singleton_method(:signal) do |name| - if name == "TERM" - entered << true - release.pop + worker = + Thread.new do + LibTmux::Server.start do |server| + path = server.endpoint.socket_path + child = server.instance_variable_get(:@daemon).instance_variable_get(:@child) + pid = child.pid + original = child.method(:signal) + child.define_singleton_method(:signal) do |name| + if name == "TERM" + entered << true + release.pop + end + original.call(name) end - original.call(name) + raise first end - raise first + rescue Exception => error + error end - rescue Exception => error - error - end begin assert entered.pop(timeout: 0.5), "daemon close was not entered" worker.raise second @@ -219,19 +245,20 @@ def test_repeated_interrupt_during_close_preserves_first_error_and_reaps def test_forked_close_cannot_retire_parent_daemon LibTmux::Server.start do |server| reader, writer = IO.pipe - child = fork do - reader.close - server.close - writer.write("detached") - writer.close - exit! 0 - end + child = + fork do + reader.close + server.close + writer.write("detached") + writer.close + exit! 0 + end writer.close begin assert IO.select([reader], nil, nil, 0.5), "fork child did not detach" assert_equal "detached", reader.read assert Process.wait2(child).last.success? - assert server.run(["display-message", "-p", "still-owned"]).success? + assert server.run(%w[display-message -p still-owned]).success? assert File.socket?(server.endpoint.socket_path) ensure reader.close @@ -244,7 +271,9 @@ def test_retired_observer_fault_is_reported_once_and_close_remains_idempotent child = server.instance_variable_get(:@daemon).instance_variable_get(:@child) original = child.method(:observation_error) path = server.endpoint.socket_path - child.define_singleton_method(:observation_error) { Errno::EINVAL.new("native observer failure") } + child.define_singleton_method(:observation_error) do + Errno::EINVAL.new("native observer failure") + end begin error = assert_raises(LibTmux::TransportError) { server.close } refute_empty error.cleanup_errors diff --git a/test/integration/terminal_test.rb b/test/integration/terminal_test.rb index 86a7e1d2..6cae19e1 100644 --- a/test/integration/terminal_test.rb +++ b/test/integration/terminal_test.rb @@ -5,7 +5,9 @@ require "pty" require "io/console" require "libtmux" -require "libtmux/terminal" if File.exist?(File.expand_path("../../gems/libtmux/lib/libtmux/terminal.rb", __dir__)) +if File.exist?(File.expand_path("../../gems/libtmux/lib/libtmux/terminal.rb", __dir__)) + require "libtmux/terminal" +end class TerminalTest < Minitest::Test def test_terminal_type_can_be_checked_before_attaching @@ -24,32 +26,58 @@ def test_switch_client_uses_current_literal_selector_and_preserves_session_envir destination.set_environment("LIBTMUX_SWITCH_PROOF", "preserved") destination.options.set("update-environment", "LIBTMUX_SWITCH_PROOF") with_attached_client(server, fixture, source) do |client, _worker| - assert fixture.tmux("set-option", "-s", "command-alias[199]", "switch-client=display-message -p aliased").last.success? - result = server.switch_client(client: client.fetch(:name), session: destination.ref, timeout: 0.5) + assert fixture + .tmux( + "set-option", + "-s", + "command-alias[199]", + "switch-client=display-message -p aliased" + ) + .last + .success? + result = + server.switch_client( + client: client.fetch(:name), + session: destination.ref, + timeout: 0.5 + ) assert_instance_of LibTmux::CommandResult, result assert result.success? assert_empty result.stdout assert_equal destination.id, server.list_clients.fetch(0).fetch(:session_id) assert_equal "preserved", destination.environment("LIBTMUX_SWITCH_PROOF") - assert_raises(LibTmux::CommandError) { server.switch_client(client: "*", session: source.ref, timeout: 0.5) } + assert_raises(LibTmux::CommandError) do + server.switch_client(client: "*", session: source.ref, timeout: 0.5) + end assert_equal destination.id, server.list_clients.fetch(0).fetch(:session_id) [nil, "", "invalid\0client", "x" * 1025].each do |selector| - assert_raises(ArgumentError) { server.switch_client(client: selector, session: source.ref) } + assert_raises(ArgumentError) do + server.switch_client(client: selector, session: source.ref) + end end LibTmuxTest::TmuxFixture.open do |other| LibTmux::Server.open(socket_path: other.socket_path) do |foreign| - error = assert_raises(LibTmux::TargetNotFoundError) do - server.switch_client(client: client.fetch(:name), session: foreign.list_sessions.first.ref) - end + error = + assert_raises(LibTmux::TargetNotFoundError) do + server.switch_client( + client: client.fetch(:name), + session: foreign.list_sessions.first.ref + ) + end assert_equal :not_sent, error.delivery end end token = LibTmux::Internal::Cancellation.new begin token.cancel - error = assert_raises(LibTmux::Cancelled) do - server.switch_client(client: client.fetch(:name), session: source.ref, cancel: token) - end + error = + assert_raises(LibTmux::Cancelled) do + server.switch_client( + client: client.fetch(:name), + session: source.ref, + cancel: token + ) + end assert_equal :not_sent, error.delivery ensure token.close @@ -69,9 +97,14 @@ def test_vanished_switch_client_does_not_retarget_another_attached_client with_attached_client(server, fixture, source) do |survivor, _other_worker| assert fixture.tmux("detach-client", "-t", gone.fetch(:name)).last.success? assert worker.join(0.5), "detached client did not retire" - error = assert_raises(LibTmux::CommandError) do - server.switch_client(client: gone.fetch(:name), session: destination.ref, timeout: 0.5) - end + error = + assert_raises(LibTmux::CommandError) do + server.switch_client( + client: gone.fetch(:name), + session: destination.ref, + timeout: 0.5 + ) + end assert_equal :observed, error.delivery current = server.list_clients assert_equal [survivor.fetch(:name)], current.map { |client| client.fetch(:name) } @@ -91,8 +124,13 @@ def test_explicit_terminal_attach_and_user_detach_return_final_status PTY.open do |master, slave| slave.winsize = [24, 80] before = slave.echo? - assert server.run(["set-hook", "-g", "client-attached", "wait-for -S terminal-attached"]).success? - worker = Thread.new { server.attach(session: session.ref, terminal: slave, term: "xterm", timeout: 1) } + assert server.run( + ["set-hook", "-g", "client-attached", "wait-for -S terminal-attached"] + ).success? + worker = + Thread.new do + server.attach(session: session.ref, terminal: slave, term: "xterm", timeout: 1) + end begin assert fixture.tmux("wait-for", "terminal-attached").last.success? assert_equal 1, server.list_clients.length @@ -122,12 +160,15 @@ def test_server_close_cancels_only_its_terminal_client_and_restores_borrowed_tty slave.winsize = [24, 80] before = slave.echo? session = server.list_sessions.first - assert server.run(["set-hook", "-g", "client-attached", "wait-for -S terminal-close"]).success? - worker = Thread.new do - server.attach(session: session.ref, terminal: slave, term: "xterm") - rescue LibTmux::Cancelled => error - error - end + assert server.run( + ["set-hook", "-g", "client-attached", "wait-for -S terminal-close"] + ).success? + worker = + Thread.new do + server.attach(session: session.ref, terminal: slave, term: "xterm") + rescue LibTmux::Cancelled => error + error + end begin assert fixture.tmux("wait-for", "terminal-close").last.success? server.close @@ -152,15 +193,18 @@ def test_terminal_is_explicit_and_pre_cancel_does_not_attach LibTmux::Server.open(socket_path: fixture.socket_path) do |server| session = server.list_sessions.first File.open(File::NULL, "w") do |file| - assert_raises(ArgumentError) { server.attach(session: session.ref, terminal: file, term: "xterm") } + assert_raises(ArgumentError) do + server.attach(session: session.ref, terminal: file, term: "xterm") + end end PTY.open do |master, slave| token = LibTmux::Internal::Cancellation.new begin token.cancel - failure = assert_raises(LibTmux::Cancelled) do - server.attach(session: session.ref, terminal: slave, term: "xterm", cancel: token) - end + failure = + assert_raises(LibTmux::Cancelled) do + server.attach(session: session.ref, terminal: slave, term: "xterm", cancel: token) + end assert_equal :not_sent, failure.delivery assert_nil failure.pid assert_empty server.list_clients @@ -179,11 +223,14 @@ def test_spawn_failure_is_typed_redacted_and_retires_observer PTY.open do |master, slave| original = Process.method(:spawn) before = Thread.list - Process.define_singleton_method(:spawn) { |*args, **options| raise Errno::ENOENT, "private-executable-name" } + Process.define_singleton_method(:spawn) do |*args, **options| + raise Errno::ENOENT, "private-executable-name" + end begin - error = assert_raises(LibTmux::TransportError) do - server.attach(session: session.ref, terminal: slave, term: "xterm") - end + error = + assert_raises(LibTmux::TransportError) do + server.attach(session: session.ref, terminal: slave, term: "xterm") + end assert_equal :not_sent, error.delivery assert_equal :spawn, error.phase assert_nil error.pid @@ -204,12 +251,16 @@ def with_attached_client(server, fixture, session) token = LibTmux::Internal::Cancellation.new PTY.open do |_master, slave| slave.winsize = [24, 80] - assert fixture.tmux("set-hook", "-g", "client-attached", "wait-for -S switch-attached").last.success? - worker = Thread.new do - server.attach(session: session.ref, terminal: slave, term: "xterm", cancel: token) - rescue LibTmux::Cancelled => error - error - end + assert fixture + .tmux("set-hook", "-g", "client-attached", "wait-for -S switch-attached") + .last + .success? + worker = + Thread.new do + server.attach(session: session.ref, terminal: slave, term: "xterm", cancel: token) + rescue LibTmux::Cancelled => error + error + end begin assert fixture.tmux("wait-for", "switch-attached").last.success? client = server.list_clients.find { |entry| entry.fetch(:tty) == slave.path } diff --git a/test/integration/text_wait_test.rb b/test/integration/text_wait_test.rb index 340b6401..5f361123 100644 --- a/test/integration/text_wait_test.rb +++ b/test/integration/text_wait_test.rb @@ -67,7 +67,9 @@ def test_matches_a_distinct_reply_after_entry end def test_matches_text_across_wrapped_screen_rows - with_pane(program: "STDOUT.sync = true; puts #{("x" * 77 + READY).inspect}; STDIN.read") do |_server, _session, pane| + with_pane( + program: "STDOUT.sync = true; puts #{("x" * 77 + READY).inspect}; STDIN.read" + ) do |_server, _session, pane| refute_includes pane.capture.text, READY result = pane.wait_for_text(READY, timeout: 0.8) assert result.matched_at_entry @@ -79,11 +81,15 @@ def test_a_short_deadline_preserves_one_complete_capture with_pane do |server, session, pane| options = server.options(scope: :session) options.set("@wait-reads", 0) - session.hooks.set("after-capture-pane", command: %q[set-option -gF @wait-reads '#{e|+:#{@wait-reads},1}']) - - error = assert_raises(LibTmux::DeadlineExceeded) do - pane.wait_for_text(REPLY, interval: 3, timeout: 0.18) - end + session.hooks.set( + "after-capture-pane", + command: %q[set-option -gF @wait-reads '#{e|+:#{@wait-reads},1}'] + ) + + error = + assert_raises(LibTmux::DeadlineExceeded) do + pane.wait_for_text(REPLY, interval: 3, timeout: 0.18) + end assert_includes error.text, READY assert_equal "1", options.get("@wait-reads").raw end @@ -94,15 +100,15 @@ def test_match_after_the_deadline_preserves_the_capture_and_raises real_clock = server.method(:monotonic) advance = 0 server.define_singleton_method(:monotonic) { real_clock.call + advance } - match = TracePoint.new(:c_call) do |event| - if event.method_id == :include? && event.path.end_with?("/text_wait.rb") - advance = 1 + match = + TracePoint.new(:c_call) do |event| + advance = 1 if event.method_id == :include? && event.path.end_with?("/text_wait.rb") end - end - error = match.enable do - assert_raises(LibTmux::DeadlineExceeded) { pane.wait_for_text(READY, timeout: 0.4) } - end + error = + match.enable do + assert_raises(LibTmux::DeadlineExceeded) { pane.wait_for_text(READY, timeout: 0.4) } + end assert_equal 1, advance assert_includes error.text, READY @@ -113,25 +119,27 @@ def test_cancellation_during_an_async_pause_preserves_text_and_advances_a_siblin with_pane do |server, _session, pane| token = LibTmux::Cancellation.new spawned_during_pause = 0 - threads = TracePoint.new(:c_call) do |event| - if event.self == Thread && [:new, :start].include?(event.method_id) && - caller_locations.any? { |frame| frame.base_label == "text_wait_pause" } - spawned_during_pause += 1 + threads = + TracePoint.new(:c_call) do |event| + if event.self == Thread && %i[new start].include?(event.method_id) && + caller_locations.any? { |frame| frame.base_label == "text_wait_pause" } + spawned_during_pause += 1 + end end - end original_verbose = $VERBOSE original_warnings = Warning[:deprecated] - _, stderr = capture_io do - $VERBOSE = true - Warning[:deprecated] = true - threads.enable do - Async do |parent| - LibTmux::Async.open(parent: parent, server: server) do |scope| - check_async_pause(scope, parent, pane, token) - end - end.wait + _, stderr = + capture_io do + $VERBOSE = true + Warning[:deprecated] = true + threads.enable do + Async do |parent| + LibTmux::Async.open(parent: parent, server: server) do |scope| + check_async_pause(scope, parent, pane, token) + end + end.wait + end end - end assert_equal 0, spawned_during_pause refute_includes stderr, "Async::Task#sleep" ensure @@ -150,7 +158,7 @@ def test_typed_input_can_match_before_the_application_reads_it end def test_removed_pane_and_stopped_server_report_distinct_reasons - {pane_gone: :pane, server_gone: :server}.each do |reason, target| + { pane_gone: :pane, server_gone: :server }.each do |reason, target| with_pane do |server, _session, pane| error = wait_for_end(pane) { (target == :pane ? pane : server).kill } assert_equal reason, error.reason @@ -175,10 +183,12 @@ def test_a_failed_capture_keeps_only_the_last_complete_screen with_pane do |server, _session, pane| release = LibTmux::Internal::TmuxVersion.parse(server.tmux_version) command_error_hook = release >= LibTmux::Internal::TmuxVersion.parse("3.5") - unrelated_marker = "libtmux-identity-#{'0' * 32}-#{pane.id},0" + unrelated_marker = "libtmux-identity-#{"0" * 32}-#{pane.id},0" if command_error_hook - server.hooks(scope: :session).set("command-error", - command: "display-message -p #{REPLY.dump} ; run-shell -C #{unrelated_marker}") + server.hooks(scope: :session).set( + "command-error", + command: "display-message -p #{REPLY.dump} ; run-shell -C #{unrelated_marker}" + ) end ended = wait_for_end(pane) { pane.kill } @@ -214,14 +224,16 @@ def test_reports_when_a_retained_pane_process_exits pane.send_text("exit") pane.send_keys("Enter") - error = assert_raises(LibTmux::PaneDied) { pane.wait_for_text(REPLY, interval: 0.03, timeout: 1) } + error = + assert_raises(LibTmux::PaneDied) { pane.wait_for_text(REPLY, interval: 0.03, timeout: 1) } assert_equal :pane_exited, error.reason assert_equal pane.capture(join: true).text, error.text end end def test_wait_reads_the_visible_screen_when_scrollback_exceeds_the_output_limit - program = "STDOUT.write((('x' * 78) + \"\\n\") * 15_000); puts #{READY.inspect}; STDOUT.flush; STDIN.read" + program = + "STDOUT.write((('x' * 78) + \"\\n\") * 15_000); puts #{READY.inspect}; STDOUT.flush; STDIN.read" with_pane(program: program, history_limit: 16_000) do |_server, _session, pane| assert_raises(LibTmux::CapacityError) { pane.capture(start: "-", join: true) } result = pane.wait_for_text(READY, timeout: 0.8) @@ -234,13 +246,18 @@ def test_wait_runs_only_the_capture_hook_and_includes_its_printed_text %w[display-message list-panes show-options].each do |command| session.hooks.set("after-#{command}", command: "set-option -g @unexpected-#{command} yes") end - session.hooks.set("after-capture-pane", command: "display-message -p -t #{pane.id} captured-by-hook") + session.hooks.set( + "after-capture-pane", + command: "display-message -p -t #{pane.id} captured-by-hook" + ) result = pane.wait_for_text("captured-by-hook", timeout: 0.8) assert_includes result.text, READY assert_includes result.text, "captured-by-hook" # Remove the guards before querying their side effects. - %w[display-message list-panes show-options].each { |command| session.hooks.unset("after-#{command}") } + %w[display-message list-panes show-options].each do |command| + session.hooks.unset("after-#{command}") + end options = server.options(scope: :session).list refute options.any? { |value| value.name.start_with?("@unexpected-") } end @@ -266,25 +283,28 @@ def test_rejects_empty_text_and_keeps_other_timeout_errors_text_free def check_async_pause(scope, parent, pane, token) async_pane = scope.server.pane(pane.ref) paused = Async::Notification.new - pause = TracePoint.new(:call) do |event| - paused.signal if event.self.equal?(async_pane) && event.method_id == :text_wait_pause - end + pause = + TracePoint.new(:call) do |event| + paused.signal if event.self.equal?(async_pane) && event.method_id == :text_wait_pause + end worker = nil pause.enable do - worker = parent.async do - async_pane.wait_for_text(REPLY, interval: 4, timeout: 2, cancel: token) - rescue LibTmux::Cancelled => error - error - end + worker = + parent.async do + async_pane.wait_for_text(REPLY, interval: 4, timeout: 2, cancel: token) + rescue LibTmux::Cancelled => error + error + end parent.with_timeout(0.8) { paused.wait } end ticks = 0 - ticker = parent.async do - 3.times do - sleep(0.01) - ticks += 1 + ticker = + parent.async do + 3.times do + sleep(0.01) + ticks += 1 + end end - end parent.with_timeout(0.8) { ticker.wait } assert_equal 3, ticks assert worker.running? @@ -292,9 +312,10 @@ def check_async_pause(scope, parent, pane, token) error = parent.with_timeout(0.8) { worker.wait } assert_kind_of LibTmux::Cancelled, error assert_includes error.text, READY - timed_out = assert_raises(LibTmux::DeadlineExceeded) do - async_pane.wait_for_text(REPLY, interval: 0.03, timeout: 0.3) - end + timed_out = + assert_raises(LibTmux::DeadlineExceeded) do + async_pane.wait_for_text(REPLY, interval: 0.03, timeout: 0.3) + end assert_includes timed_out.text, READY assert_empty scope.server.list_clients end @@ -303,12 +324,20 @@ def with_pane(program: PROGRAM, history_limit: nil) LibTmuxTest::TmuxFixture.open do |fixture| LibTmux::Server.open(socket_path: fixture.socket_path) do |server| server.options(scope: :session).set("history-limit", history_limit) if history_limit - created = server.new_session(name: "text-wait", command: [Gem.ruby, "-e", program], - width: 80, height: 12, receipt: true) + created = + server.new_session( + name: "text-wait", + command: [Gem.ruby, "-e", program], + width: 80, + height: 12, + receipt: true + ) assert_respond_to created.pane, :wait_for_text deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 0.8 until created.pane.capture(join: true).text.include?(READY) - flunk "fixture did not draw #{READY.inspect}" if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline + if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline + flunk "fixture did not draw #{READY.inspect}" + end sleep 0.01 end yield server, created.entity, created.pane, fixture @@ -343,11 +372,12 @@ def wait_for_end(pane) token = LibTmux::Cancellation.new paused = Queue.new observe_pause(token) { paused << true } - wait = lambda do - pane.wait_for_text(REPLY, interval: 0.03, timeout: 0.8, cancel: token) - rescue LibTmux::PaneDied => error - error - end + wait = + lambda do + pane.wait_for_text(REPLY, interval: 0.03, timeout: 0.8, cancel: token) + rescue LibTmux::PaneDied => error + error + end with_waiting_thread(wait) do |worker| assert paused.pop(timeout: 0.7), "text wait did not complete its first read" yield @@ -360,8 +390,19 @@ def wait_for_end(pane) def with_stopped_control(fixture, session_id) child_input, keep_open = IO.pipe output, child_output = IO.pipe - pid = Process.spawn(fixture.executable, "-S", fixture.socket_path, "-C", "attach-session", "-t", session_id, - in: child_input, out: child_output, err: child_output) + pid = + Process.spawn( + fixture.executable, + "-S", + fixture.socket_path, + "-C", + "attach-session", + "-t", + session_id, + in: child_input, + out: child_output, + err: child_output + ) child_input.close child_output.close deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 0.7 @@ -383,7 +424,9 @@ def with_stopped_control(fixture, session_id) rescue Errno::ESRCH, Errno::ECHILD # The owned control client has already exited. ensure - [child_input, keep_open, output, child_output].compact.each { |io| io.close unless io.closed? } + [child_input, keep_open, output, child_output].compact.each do |io| + io.close unless io.closed? + end end end end diff --git a/test/integration/tmux_features_test.rb b/test/integration/tmux_features_test.rb index 24ff1784..8b96c11a 100644 --- a/test/integration/tmux_features_test.rb +++ b/test/integration/tmux_features_test.rb @@ -17,7 +17,8 @@ def test_public_capabilities_describe_the_bound_daemon_and_remain_immutable assert_instance_of LibTmux::Capabilities, report assert_equal server.tmux_version, report.version assert_equal fixture.tmux("display-message", "-p", '#{pid}').first.to_i, report.pid - assert_equal fixture.tmux("display-message", "-p", '#{start_time}').first.to_i, report.start_time + assert_equal fixture.tmux("display-message", "-p", '#{start_time}').first.to_i, + report.start_time registry = LibTmux::Internal::Capabilities release = LibTmux::Internal::TmuxVersion.parse(report.version) assert_equal registry::CAPABILITIES.map(&:id), report.features.map(&:id) @@ -68,9 +69,9 @@ def test_daemon_reports_accept_a_signed_start_time def test_daemon_reports_reject_an_oversize_pid with_daemon_identity_value("pid", "12345678901") do |server| snapshot_error = assert_raises(LibTmux::ProtocolError) { server.snapshot } - assert_equal [:capture, :observed], [snapshot_error.phase, snapshot_error.delivery] + assert_equal %i[capture observed], [snapshot_error.phase, snapshot_error.delivery] report_error = assert_raises(LibTmux::ProtocolError) { server.capabilities } - assert_equal [:decode, :observed], [report_error.phase, report_error.delivery] + assert_equal %i[decode observed], [report_error.phase, report_error.delivery] end end @@ -79,13 +80,17 @@ def test_control_clients_attach_only_to_tmux_3_7_and_newer session = server.list_sessions.first if control_supported?(server) server.open_control(session: session.ref) do |control| - assert_equal "ready\n", control.exchange("display-message -p ready", timeout: 0.5).blocks.last.body + assert_equal "ready\n", + control.exchange("display-message -p ready", timeout: 0.5).blocks.last.body end else refute require_control_support(server, session) Async do |parent| LibTmux::Async.open(parent: parent, server: server) do |scope| - error = assert_raises(LibTmux::UnsupportedFeatureError) { scope.server.open_control(session: session.ref) } + error = + assert_raises(LibTmux::UnsupportedFeatureError) do + scope.server.open_control(session: session.ref) + end assert_equal :not_sent, error.delivery end end.wait @@ -107,13 +112,15 @@ def test_named_buffer_deletion_and_rename_need_tmux_3_4 server.write_buffer(name: "target", data: "target") before = server.list_buffers.map { |buffer| buffer.fetch(:name) }.sort if release_before?(server, 3, 4) - [-> { server.delete_buffer("target") }, + [ + -> { server.delete_buffer("target") }, -> { server.run(%w[delete-buffer -b target]) }, -> { server.run(%w[deleteb -b target]) }, -> { server.run(%w[set-option -g @x 1 ; delete-buffer -b target]) }, - -> { server.run(%w[set-buffer -b target -n renamed]) }].each do |attempt| + -> { server.run(%w[set-buffer -b target -n renamed]) } + ].each do |attempt| error = assert_raises(LibTmux::UnsupportedFeatureError) { attempt.call } - assert_equal [:not_sent, :admission], [error.delivery, error.phase] + assert_equal %i[not_sent admission], [error.delivery, error.phase] assert_match(/requires tmux 3\.4 or newer/, error.message) end assert_equal before, server.list_buffers.map { |buffer| buffer.fetch(:name) }.sort @@ -136,10 +143,13 @@ def test_every_route_the_registry_names_refuses_named_buffer_deletion_before_tmu routes = { "LibTmux::Server#delete_buffer" => ->(target) { target.delete_buffer("target") }, "LibTmux::Server#run" => ->(target) { target.run(%w[delete-buffer -b target]) }, - "LibTmux::Server#run_group" => ->(target) { target.run_group([%w[display-message -p x], %w[delete-buffer -b target]]) } + "LibTmux::Server#run_group" => ->(target) do + target.run_group([%w[display-message -p x], %w[delete-buffer -b target]]) + end } named = LibTmux::Internal::Capabilities.capability("buffer-delete-named").apis - assert_equal named.map { |name| name.sub("LibTmux::Async::", "LibTmux::") }.uniq.sort, routes.keys.sort + assert_equal named.map { |name| name.sub("LibTmux::Async::", "LibTmux::") }.uniq.sort, + routes.keys.sort with_server do |server, _fixture| server.write_buffer(name: "target", data: "target") Async do |parent| @@ -149,7 +159,7 @@ def test_every_route_the_registry_names_refuses_named_buffer_deletion_before_tmu attempt = routes.fetch(name.sub("LibTmux::Async::", "LibTmux::")) if release_before?(server, 3, 4) error = assert_raises(LibTmux::UnsupportedFeatureError, name) { attempt.call(target) } - assert_equal [:not_sent, :admission], [error.delivery, error.phase], name + assert_equal %i[not_sent admission], [error.delivery, error.phase], name else attempt.call(target) server.write_buffer(name: "target", data: "target") @@ -164,16 +174,25 @@ def test_every_route_the_registry_names_refuses_named_buffer_deletion_before_tmu def test_break_out_names_the_window_and_reads_back_a_sole_pane with_server do |server, fixture| home = server.list_sessions.first - pane = home.list_windows.first.list_panes.first.split(direction: :vertical, command: ["/bin/cat"]) + pane = + home.list_windows.first.list_panes.first.split(direction: :vertical, command: ["/bin/cat"]) window = pane.break_out(session: home.ref, name: "broken") - assert_equal "broken", fixture.tmux("display-message", "-p", "-t", window.id, '#{window_name}').first.strip + assert_equal "broken", + fixture + .tmux("display-message", "-p", "-t", window.id, '#{window_name}') + .first + .strip assert_equal [pane.id], window.list_panes.map(&:id) other = server.new_session(name: "other", command: ["/bin/cat"]) second = other.new_window(name: "solo", command: ["/bin/cat"]) sole = second.list_panes.first moved = sole.break_out(session: home.ref, name: "relocated") - assert_equal "relocated", fixture.tmux("display-message", "-p", "-t", moved.id, '#{window_name}').first.strip + assert_equal "relocated", + fixture + .tmux("display-message", "-p", "-t", moved.id, '#{window_name}') + .first + .strip assert_includes moved.list_panes.map(&:id), sole.id end end @@ -182,7 +201,15 @@ def test_break_out_names_the_window_and_reads_back_a_sole_pane # and read-back reads that used it ran a user's hook as a side effect. def test_identity_and_readback_reads_fire_no_display_message_hook with_server do |server, fixture| - assert fixture.tmux("set-hook", "-g", "after-display-message", "set-option -g @hook-display fired ; wait-for -S hook-display").last.success? + assert fixture + .tmux( + "set-hook", + "-g", + "after-display-message", + "set-option -g @hook-display fired ; wait-for -S hook-display" + ) + .last + .success? snapshot = server.snapshot assert_equal snapshot.server_info.fetch(:version), server.capabilities.version assert_equal server.__send__(:tmux_release).text, snapshot.server_info.fetch(:version) @@ -202,8 +229,11 @@ def test_exact_tmux_3_7_refuses_raw_break_pane_without_effect pane = server.list_panes.first.split(direction: :vertical, command: ["/bin/cat"]) windows = server.list_windows.map(&:id) if exact_release?(server, 3, 7) - error = assert_raises(LibTmux::UnsupportedFeatureError) { server.run(["break-pane", "-d", "-s", pane.id]) } - assert_equal [:not_sent, :admission], [error.delivery, error.phase] + error = + assert_raises(LibTmux::UnsupportedFeatureError) do + server.run(["break-pane", "-d", "-s", pane.id]) + end + assert_equal %i[not_sent admission], [error.delivery, error.phase] assert_equal windows, server.list_windows.map(&:id) else assert server.run(["break-pane", "-d", "-s", pane.id]).success? @@ -223,11 +253,15 @@ def test_exact_tmux_3_7_refuses_break_pane_over_a_control_connection_and_the_dae lines = ["break-pane", "breakp -d", "break-p", "display-message -p ok ; break-pane"] if exact_release?(server, 3, 7) lines.each do |line| - error = assert_raises(LibTmux::UnsupportedFeatureError, line) { control.exchange(line, timeout: 1) } - assert_equal [:not_sent, :admission], [error.delivery, error.phase] + error = + assert_raises(LibTmux::UnsupportedFeatureError, line) do + control.exchange(line, timeout: 1) + end + assert_equal %i[not_sent admission], [error.delivery, error.phase] end assert_equal windows, server.list_windows.map(&:id) - assert_equal "alive\n", control.exchange("display-message -p alive", timeout: 1).blocks.last.body + assert_equal "alive\n", + control.exchange("display-message -p alive", timeout: 1).blocks.last.body else control.exchange("break-pane -d", timeout: 1) assert_equal windows.length + 1, server.list_windows.length @@ -245,11 +279,17 @@ def test_exact_tmux_3_7_refuses_break_pane_over_an_async_control_connection Async do |parent| LibTmux::Async.open(parent: parent, server: server) do |scope| - scope.server.open_control(session: session.ref) do |control| - error = assert_raises(LibTmux::UnsupportedFeatureError) { control.exchange("break-pane", timeout: 1) } - assert_equal [:not_sent, :admission], [error.delivery, error.phase] - assert_equal "alive\n", control.exchange("display-message -p alive", timeout: 1).blocks.last.body - end + scope + .server + .open_control(session: session.ref) do |control| + error = + assert_raises(LibTmux::UnsupportedFeatureError) do + control.exchange("break-pane", timeout: 1) + end + assert_equal %i[not_sent admission], [error.delivery, error.phase] + assert_equal "alive\n", + control.exchange("display-message -p alive", timeout: 1).blocks.last.body + end end end.wait assert fixture.tmux("has-session", "-t", "fixture").last.success? @@ -261,13 +301,21 @@ def test_exact_tmux_3_7_refuses_raw_names_with_colon_or_period_like_the_typed_ca session = server.list_sessions.first sessions = server.list_sessions.map(&:id) windows = server.list_windows.map(&:id) - raw = [%w[new-session -d -s a.b], %w[new -d -s c:d], %w[new-window -d -n a.b], %w[neww -d -n c:d], - ["rename-window", "-t", session.id, "a.b"], ["renamew", "-t", session.id, "a.b"], - ["rename-session", "-t", session.id, "a.b"], ["rename", "-t", session.id, "c:d"]] + raw = [ + %w[new-session -d -s a.b], + %w[new -d -s c:d], + %w[new-window -d -n a.b], + %w[neww -d -n c:d], + ["rename-window", "-t", session.id, "a.b"], + ["renamew", "-t", session.id, "a.b"], + ["rename-session", "-t", session.id, "a.b"], + ["rename", "-t", session.id, "c:d"] + ] if exact_release?(server, 3, 7) raw.each do |argv| - error = assert_raises(LibTmux::UnsupportedFeatureError, argv.join(" ")) { server.run(argv) } - assert_equal [:not_sent, :admission], [error.delivery, error.phase] + error = + assert_raises(LibTmux::UnsupportedFeatureError, argv.join(" ")) { server.run(argv) } + assert_equal %i[not_sent admission], [error.delivery, error.phase] end assert_equal sessions, server.list_sessions.map(&:id) assert_equal windows, server.list_windows.map(&:id) @@ -283,9 +331,14 @@ def test_session_names_with_colon_and_period_follow_the_daemon_release names = %w[item.v2 item:v2] if exact_release?(server, 3, 7) names.each do |name| - error = assert_raises(LibTmux::UnsupportedFeatureError) { server.new_session(name: name, command: ["/bin/cat"]) } - assert_equal [:not_sent, :admission], [error.delivery, error.phase] - assert_raises(LibTmux::UnsupportedFeatureError) { server.list_sessions.first.rename(name) } + error = + assert_raises(LibTmux::UnsupportedFeatureError) do + server.new_session(name: name, command: ["/bin/cat"]) + end + assert_equal %i[not_sent admission], [error.delivery, error.phase] + assert_raises(LibTmux::UnsupportedFeatureError) do + server.list_sessions.first.rename(name) + end _, error, status = fixture.tmux("new-session", "-d", "-s", name, "/bin/cat") refute status.success? assert_includes error, "invalid session name: #{name}" @@ -296,16 +349,18 @@ def test_session_names_with_colon_and_period_follow_the_daemon_release if release < LibTmux::Internal::TmuxVersion.parse("3.7") session = server.new_session(name: names.first, command: ["/bin/cat"]) assert_session_name(server, fixture, session.ref, "item_v2") - collision = assert_raises(LibTmux::CommandError) do - server.new_session(name: names.last, command: ["/bin/cat"]) - end + collision = + assert_raises(LibTmux::CommandError) do + server.new_session(name: names.last, command: ["/bin/cat"]) + end assert_includes collision.result.stderr, "duplicate session: item_v2" else - refs = names.map do |name| - session = server.new_session(name: name, command: ["/bin/cat"]) - assert_session_name(server, fixture, session.ref, name) - session.ref - end + refs = + names.map do |name| + session = server.new_session(name: name, command: ["/bin/cat"]) + assert_session_name(server, fixture, session.ref, name) + session.ref + end refute_equal refs.first, refs.last end end @@ -317,10 +372,14 @@ def test_session_names_with_colon_and_period_follow_the_daemon_release def test_percentage_splits_use_the_portable_size_flag_and_raw_p_is_refused_on_3_4 with_server do |server, _fixture| pane = server.list_panes.first - assert_kind_of LibTmux::Pane, pane.split(direction: :horizontal, size: "40%", command: ["/bin/cat"]) + assert_kind_of LibTmux::Pane, + pane.split(direction: :horizontal, size: "40%", command: ["/bin/cat"]) panes = server.list_panes.length if exact_release?(server, 3, 4) - error = assert_raises(LibTmux::UnsupportedFeatureError) { server.run(["split-window", "-d", "-p", "30", "-t", pane.id]) } + error = + assert_raises(LibTmux::UnsupportedFeatureError) do + server.run(["split-window", "-d", "-p", "30", "-t", pane.id]) + end assert_equal :not_sent, error.delivery assert_equal panes, server.list_panes.length else @@ -334,8 +393,11 @@ def test_malformed_layouts_are_refused_before_tmux_3_4_and_the_daemon_survives with_server do |server, fixture| window = server.list_windows.first if release_before?(server, 3, 4) - ["garbage", "zzzz,0x0"].each do |layout| - error = assert_raises(LibTmux::UnsupportedFeatureError) { server.run(["select-layout", "-t", window.id, layout]) } + %w[garbage zzzz,0x0].each do |layout| + error = + assert_raises(LibTmux::UnsupportedFeatureError) do + server.run(["select-layout", "-t", window.id, layout]) + end assert_equal :not_sent, error.delivery assert_raises(ArgumentError) { window.select_layout(layout) } end @@ -357,19 +419,31 @@ def test_json_layouts_apply_from_tmux_3_8_and_are_refused_before_it error = assert_raises(LibTmux::UnsupportedFeatureError) { window.select_layout(json) } assert_equal :not_sent, error.delivery assert_match(/JSON layouts require tmux 3\.8 or newer/, error.message) - raw = assert_raises(LibTmux::UnsupportedFeatureError) { server.run(["select-layout", "-t", window.id, json]) } + raw = + assert_raises(LibTmux::UnsupportedFeatureError) do + server.run(["select-layout", "-t", window.id, json]) + end assert_equal :not_sent, raw.delivery if server.supports_control? layout = fixture.tmux("display-message", "-p", "-t", window.id, "\#{window_layout}").first server.open_control(session: server.list_sessions.first.ref) do |control| line = "select-layout -t #{window.id} #{json}" - error = assert_raises(LibTmux::UnsupportedFeatureError) { control.exchange(line, timeout: 1) } - assert_equal [:not_sent, :admission], [error.delivery, error.phase] - assert_equal layout, fixture.tmux("display-message", "-p", "-t", window.id, "\#{window_layout}").first + error = + assert_raises(LibTmux::UnsupportedFeatureError) { control.exchange(line, timeout: 1) } + assert_equal %i[not_sent admission], [error.delivery, error.phase] + assert_equal layout, + fixture.tmux( + "display-message", + "-p", + "-t", + window.id, + "\#{window_layout}" + ).first end end else - saved = fixture.tmux("display-message", "-p", "-t", window.id, "\#{window_layout}").first.strip + saved = + fixture.tmux("display-message", "-p", "-t", window.id, "\#{window_layout}").first.strip assert saved.start_with?("{"), saved assert window.select_layout(saved).success? end @@ -389,7 +463,8 @@ def test_clipboard_query_is_refused_before_tmux_3_6a assert_equal :not_sent, error.delivery end else - refute server.run(%w[refresh-client -l]).success?, "with no client tmux reports no current client" + refute server.run(%w[refresh-client -l]).success?, + "with no client tmux reports no current client" end assert fixture.tmux("has-session", "-t", "fixture").last.success? end @@ -400,21 +475,30 @@ def test_clipboard_query_is_refused_before_tmux_3_6a def with_daemon_identity_value(field, value) LibTmuxTest::TmuxFixture.open do |fixture| wrapper = File.join(File.dirname(fixture.socket_path), "identity-tmux") - LibTmuxTest::StubExecutable.write(wrapper, <<~'RUBY', CLIENT: fixture.executable, FIELD: field, VALUE: value) + LibTmuxTest::StubExecutable.write( + wrapper, + <<~'RUBY', arguments = ARGV.map do |argument| argument.start_with?("libtmux-identity-") ? argument.gsub("\#{#{FIELD}}", VALUE) : argument end exec CLIENT, *arguments RUBY - LibTmux::Server.open(socket_path: fixture.socket_path, executable: wrapper) { |server| yield server } + CLIENT: fixture.executable, + FIELD: field, + VALUE: value + ) + LibTmux::Server.open(socket_path: fixture.socket_path, executable: wrapper) do |server| + yield server + end end end def with_server LibTmuxTest::TmuxFixture.open do |fixture| - LibTmux::Server.open(socket_path: fixture.socket_path, executable: fixture.executable) do |server| - yield server, fixture - end + LibTmux::Server.open( + socket_path: fixture.socket_path, + executable: fixture.executable + ) { |server| yield server, fixture } end end diff --git a/test/integration/tmux_version_check_test.rb b/test/integration/tmux_version_check_test.rb index 0967e5e8..6bc90636 100644 --- a/test/integration/tmux_version_check_test.rb +++ b/test/integration/tmux_version_check_test.rb @@ -27,13 +27,14 @@ def test_the_connected_daemon_decides_support_not_the_client if refused?(fixture) error = assert_raises(LibTmux::UnsupportedFeatureError) { open_server(fixture) } assert_match(/tmux 3\.3a or newer is required/, error.message) - assert_equal [:not_sent, :admission], [error.delivery, error.phase] + assert_equal %i[not_sent admission], [error.delivery, error.phase] else open_server(fixture) do |server| assert_equal ["$0"], server.list_sessions.map(&:id) report = server.capabilities assert_equal daemon_version(fixture), report.version - assert_equal RANKING.parse(report.version) >= RANKING.parse("3.8"), report.supports?("layout-json") + assert_equal RANKING.parse(report.version) >= RANKING.parse("3.8"), + report.supports?("layout-json") end end assert fixture.tmux("has-session", "-t", "fixture").last.success? @@ -46,12 +47,17 @@ def test_the_connected_daemon_decides_support_not_the_client # Only a local run without a lane is skipped. def test_the_selected_daemon_is_the_lane_under_test expected = ENV["LIBTMUX_VERSION_CHECK_EXPECT"] - skip "LIBTMUX_VERSION_CHECK_EXPECT names the lane in CI" if expected.nil? && !ENV["GITHUB_ACTIONS"] + if expected.nil? && !ENV["GITHUB_ACTIONS"] + skip "LIBTMUX_VERSION_CHECK_EXPECT names the lane in CI" + end with_fixture do |fixture| case expected - when "refused" then assert refused?(fixture) - when "supported" then refute refused?(fixture) - else flunk "LIBTMUX_VERSION_CHECK_EXPECT must be refused or supported, not #{expected.inspect}" + when "refused" + assert refused?(fixture) + when "supported" + refute refused?(fixture) + else + flunk "LIBTMUX_VERSION_CHECK_EXPECT must be refused or supported, not #{expected.inspect}" end end end @@ -60,8 +66,16 @@ def test_an_alias_named_for_the_fence_or_the_probe_refuses_the_server with_fixture do |fixture| next assert_refused(fixture) if refused?(fixture) - ["if-shel", "run-shel"].each do |name| - assert fixture.tmux("set-option", "-s", "command-alias[77]", "#{name}=display-message -p hijacked").last.success? + %w[if-shel run-shel].each do |name| + assert fixture + .tmux( + "set-option", + "-s", + "command-alias[77]", + "#{name}=display-message -p hijacked" + ) + .last + .success? error = assert_raises(LibTmux::Error, name) { open_server(fixture) } assert_equal :not_sent, error.delivery assert_equal :admission, error.phase @@ -78,7 +92,9 @@ def test_version_timeout_is_a_validated_option [0, -1, "5", Float::INFINITY].each do |value| assert_raises(ArgumentError) { open_server(fixture, version_timeout: value) } end - open_server(fixture, version_timeout: 10) { |server| assert_equal ["$0"], server.list_sessions.map(&:id) } + open_server(fixture, version_timeout: 10) do |server| + assert_equal ["$0"], server.list_sessions.map(&:id) + end end end @@ -87,10 +103,14 @@ def test_supported_daemons_keep_raw_batches_and_typed_reads next assert_refused(fixture) if refused?(fixture) open_server(fixture) do |server| assert_equal ["$0"], server.list_sessions.map(&:id) - result = server.run(["set-option", "-g", "@libtmux-version-check", "accepted;", "display-message", "-p", "--", '#{version}']) + result = + server.run( + %w[set-option -g @libtmux-version-check accepted; display-message -p -- #{version}] + ) assert result.success? assert_equal daemon_version(fixture), result.stdout.strip - assert_equal "accepted", fixture.tmux("show-option", "-gv", "@libtmux-version-check").first.strip + assert_equal "accepted", + fixture.tmux("show-option", "-gv", "@libtmux-version-check").first.strip end end end @@ -99,9 +119,21 @@ def test_unsupported_daemon_is_refused_by_the_workspace_and_mcp_entry_points_wit with_fixture do |fixture| next assert_supported(fixture) unless refused?(fixture) config = File.join(File.dirname(fixture.socket_path), "refused.json") - File.write(config, JSON.generate({session_name: "refused-workspace", windows: [{window_name: "one", panes: [{}]}]})) + File.write( + config, + JSON.generate( + { session_name: "refused-workspace", windows: [{ window_name: "one", panes: [{}] }] } + ) + ) out, err = StringIO.new, StringIO.new - status = LibTmux::Workspace::CLI.run(["load", config, "--json", "--socket", fixture.socket_path], out: out, err: err, environment: {}) + status = + LibTmux::Workspace::CLI.run( + ["load", config, "--json", "--socket", fixture.socket_path], + out: out, + err: err, + environment: { + } + ) refute_equal 0, status failure = JSON.parse(out.string).fetch("error") assert_equal "tmux_unsupported", failure.fetch("kind") @@ -111,7 +143,14 @@ def test_unsupported_daemon_is_refused_by_the_workspace_and_mcp_entry_points_wit refute fixture.tmux("has-session", "-t", "=refused-workspace").last.success? out, err = StringIO.new, StringIO.new - status = LibTmux::Workspace::CLI.run(["load", config, "--socket", fixture.socket_path], out: out, err: err, environment: {}) + status = + LibTmux::Workspace::CLI.run( + ["load", config, "--socket", fixture.socket_path], + out: out, + err: err, + environment: { + } + ) refute_equal 0, status assert_match(/tmux 3\.3a or newer is required/, err.string) assert_match(REMEDY, err.string) @@ -122,19 +161,29 @@ def test_unsupported_daemon_is_refused_by_the_workspace_and_mcp_entry_points_wit closed.close output, protocol = IO.pipe errors = StringIO.new - status = LibTmux::MCP::CLI.run(["--socket", fixture.socket_path, "--tmux", CLIENT], input: input, out: protocol, err: errors) + status = + LibTmux::MCP::CLI.run( + ["--socket", fixture.socket_path, "--tmux", CLIENT], + input: input, + out: protocol, + err: errors + ) protocol.close assert_equal 1, status assert_empty output.read assert_match(/MCP refused to start: tmux 3\.3a or newer is required/, errors.string) - assert_equal ["fixture"], fixture.tmux("list-sessions", "-F", '#{session_name}').first.lines.map(&:chomp) + assert_equal ["fixture"], + fixture.tmux("list-sessions", "-F", '#{session_name}').first.lines.map(&:chomp) end end def test_unsupported_daemon_is_refused_by_owned_startup_before_the_daemon_starts with_fixture do |fixture| next assert_supported(fixture) unless refused?(fixture) - error = assert_raises(LibTmux::UnsupportedFeatureError) { LibTmux::Server.start(executable: EXECUTABLE) } + error = + assert_raises(LibTmux::UnsupportedFeatureError) do + LibTmux::Server.start(executable: EXECUTABLE) + end assert_equal :not_sent, error.delivery end end @@ -147,12 +196,31 @@ def test_version_check_and_dispatch_fire_no_user_hooks next assert_refused(fixture) if refused?(fixture) # Read the release first: display-message fires the hook set below. release = RANKING.parse(daemon_version(fixture)) - assert fixture.tmux("set-hook", "-g", "after-display-message", "set-option -g @hook-display fired ; wait-for -S hook-display").last.success? - error_hook = fixture.tmux("set-hook", "-g", "command-error", "set-option -g @hook-error fired ; wait-for -S hook-error").last.success? - assert_equal release >= RANKING.parse("3.5"), error_hook, "command-error hooks exist from tmux 3.5" + assert fixture + .tmux( + "set-hook", + "-g", + "after-display-message", + "set-option -g @hook-display fired ; wait-for -S hook-display" + ) + .last + .success? + error_hook = + fixture + .tmux( + "set-hook", + "-g", + "command-error", + "set-option -g @hook-error fired ; wait-for -S hook-error" + ) + .last + .success? + assert_equal release >= RANKING.parse("3.5"), + error_hook, + "command-error hooks exist from tmux 3.5" open_server(fixture) do |server| assert_equal ["$0"], server.list_sessions.map(&:id) - assert server.run(["set-option", "-g", "@hook-probe", "ran"]).success? + assert server.run(%w[set-option -g @hook-probe ran]).success? assert_equal release.text, server.capabilities.version end assert_equal "", fixture.tmux("show-option", "-gqv", "@hook-display").first @@ -175,7 +243,9 @@ def test_a_dispatch_after_the_daemon_changes_is_refused_without_effects Dir.mktmpdir("libtmux-ruby-version-check-") do |directory| wrapper, claim = %w[selected-tmux claimed-version].map { |name| File.join(directory, name) } # Answers a version probe with the claimed release once CLAIM exists. - LibTmuxTest::StubExecutable.write(wrapper, <<~'STUB', CLAIM: claim, CLIENT: CLIENT_PATH.call) + LibTmuxTest::StubExecutable.write( + wrapper, + <<~'STUB', ARGV.each do |argument| name = argument.delete_suffix('#{version}') next unless argument.start_with?("libtmux-version-") && name != argument @@ -186,8 +256,16 @@ def test_a_dispatch_after_the_daemon_changes_is_refused_without_effects end exec CLIENT, *ARGV STUB - batch = ["set-option", "-g", "@libtmux-refused", "changed;", "new-session", "-d", "-s", "must-not-exist"] - sentinel = -> { [fixture.tmux("show-option", "-gqv", "@libtmux-refused").first, fixture.tmux("has-session", "-t", "=must-not-exist").last.success?] } + CLAIM: claim, + CLIENT: CLIENT_PATH.call + ) + batch = %w[set-option -g @libtmux-refused changed; new-session -d -s must-not-exist] + sentinel = -> do + [ + fixture.tmux("show-option", "-gqv", "@libtmux-refused").first, + fixture.tmux("has-session", "-t", "=must-not-exist").last.success? + ] + end # The probe reports the true release, so the same batch is dispatched. LibTmux::Server.open(socket_path: fixture.socket_path, executable: wrapper) do |server| @@ -201,10 +279,12 @@ def test_a_dispatch_after_the_daemon_changes_is_refused_without_effects File.write(claim, stale) LibTmux::Server.open(socket_path: fixture.socket_path, executable: wrapper) do |server| error = assert_raises(LibTmux::UnsupportedFeatureError) { server.run(batch) } - assert_equal [:not_sent, :admission], [error.delivery, error.phase] + assert_equal %i[not_sent admission], [error.delivery, error.phase] assert_match(/no longer reports #{Regexp.escape(stale)}/, error.message) assert_raises(LibTmux::UnsupportedFeatureError) { server.list_sessions } - assert_raises(LibTmux::UnsupportedFeatureError) { server.new_session(name: "must-not-exist", command: ["/bin/cat"]) } + assert_raises(LibTmux::UnsupportedFeatureError) do + server.new_session(name: "must-not-exist", command: ["/bin/cat"]) + end assert_raises(LibTmux::UnsupportedFeatureError) { server.snapshot } assert_raises(LibTmux::UnsupportedFeatureError) { server.capabilities } Async do |parent| @@ -212,16 +292,30 @@ def test_a_dispatch_after_the_daemon_changes_is_refused_without_effects assert_raises(LibTmux::UnsupportedFeatureError) { scope.server.run(batch) } assert_raises(LibTmux::UnsupportedFeatureError) { scope.server.list_sessions } assert_raises(LibTmux::UnsupportedFeatureError) { scope.server.capabilities } - app = LibTmux::MCP::Application.new(server: scope.server, endpoint_name: "test", enabled_tools: %w[tmux_snapshot tmux_capabilities]) + app = + LibTmux::MCP::Application.new( + server: scope.server, + endpoint_name: "test", + enabled_tools: %w[tmux_snapshot tmux_capabilities] + ) begin - failure = app.call("tmux_snapshot", {"entity" => "pane", "limit" => 1}).structured_content.fetch("error") - capability_failure = app.call("tmux_capabilities", {}).structured_content.fetch("error") - assert_equal %w[unsupported not_sent], capability_failure.values_at("code", "delivery") + failure = + app + .call("tmux_snapshot", { "entity" => "pane", "limit" => 1 }) + .structured_content + .fetch("error") + capability_failure = + app.call("tmux_capabilities", {}).structured_content.fetch("error") + assert_equal %w[unsupported not_sent], + capability_failure.values_at("code", "delivery") ensure app.close end assert_equal %w[unsupported not_sent], failure.values_at("code", "delivery") - assert_match(/\Atmux 3\.3a or newer is required.*upgrade tmux and restart the server\z/, failure.fetch("message")) + assert_match( + /\Atmux 3\.3a or newer is required.*upgrade tmux and restart the server\z/, + failure.fetch("message") + ) end end.wait end @@ -238,23 +332,37 @@ def test_every_client_spawn_for_a_bound_endpoint_refuses_to_start_a_daemon next assert_refused(fixture) if refused?(fixture) Dir.mktmpdir("libtmux-ruby-version-check-") do |directory| wrapper, calls = %w[selected-tmux calls].map { |name| File.join(directory, name) } - LibTmuxTest::StubExecutable.write(wrapper, <<~'STUB', CALLS: calls, CLIENT: CLIENT_PATH.call) + LibTmuxTest::StubExecutable.write( + wrapper, + <<~'STUB', File.write(CALLS, "#{ARGV.join(' ')}\n", mode: "a") exec CLIENT, *ARGV STUB + CALLS: calls, + CLIENT: CLIENT_PATH.call + ) control = RANKING.parse(daemon_version(fixture)) >= RANKING.parse(RANKING::CONTROL_MINIMUM) LibTmux::Server.open(socket_path: fixture.socket_path, executable: wrapper) do |server| server.list_sessions server.capabilities if control - server.open_control(session: server.list_sessions.first.ref) { |control_connection| control_connection.exchange("display-message -p control") } + server.open_control(session: server.list_sessions.first.ref) do |control_connection| + control_connection.exchange("display-message -p control") + end else - assert_raises(LibTmux::UnsupportedFeatureError) { server.open_control(session: server.list_sessions.first.ref) { |_| } } + assert_raises( + LibTmux::UnsupportedFeatureError + ) { server.open_control(session: server.list_sessions.first.ref) { |_| } } end PTY.open do |_master, slave| slave.winsize = [24, 80] assert_raises(LibTmux::DeadlineExceeded) do - server.attach(session: server.list_sessions.first.ref, terminal: slave, term: "xterm", timeout: 0.3) + server.attach( + session: server.list_sessions.first.ref, + terminal: slave, + term: "xterm", + timeout: 0.3 + ) end end end @@ -273,7 +381,8 @@ def test_a_pre_3_2_refusal_returns_while_a_descendant_holds_stdout_open Dir.mktmpdir("libtmux-ruby-version-check-") do |directory| socket = File.join(directory, "socket") UNIXServer.new(socket).close - wrapper, answer, holder = %w[selected-tmux answer holder].map { |name| File.join(directory, name) } + wrapper, answer, holder = + %w[selected-tmux answer holder].map { |name| File.join(directory, name) } # Leaves a descendant that inherits stdout, and answers on stderr. LibTmuxTest::StubExecutable.write(wrapper, <<~'STUB', ANSWER: answer, HOLDER: holder) File.write(HOLDER, spawn("sleep", "30", in: File::NULL, err: File::NULL).to_s) @@ -281,17 +390,26 @@ def test_a_pre_3_2_refusal_returns_while_a_descendant_holds_stdout_open exit 1 STUB begin - ["usage: run-shell [-b] [-t target-pane] shell-command\n", "server version is too old for client\n"].each do |stderr| + [ + "usage: run-shell [-b] [-t target-pane] shell-command\n", + "server version is too old for client\n" + ].each do |stderr| File.write(answer, stderr) started = Process.clock_gettime(Process::CLOCK_MONOTONIC) - error = assert_raises(LibTmux::UnsupportedFeatureError, stderr) { LibTmux::Server.open(socket_path: socket, executable: wrapper) } + error = + assert_raises(LibTmux::UnsupportedFeatureError, stderr) do + LibTmux::Server.open(socket_path: socket, executable: wrapper) + end assert_operator Process.clock_gettime(Process::CLOCK_MONOTONIC) - started, :<, 2.0 - assert_equal [:not_sent, :admission], [error.delivery, error.phase] + assert_equal %i[not_sent admission], [error.delivery, error.phase] assert_match(/older than 3\.2/, error.message) end File.write(answer, "usage: run-shell [-bC] [-d delay] [-t target-pane] [shell-command]\n") started = Process.clock_gettime(Process::CLOCK_MONOTONIC) - error = assert_raises(LibTmux::CommandError) { LibTmux::Server.open(socket_path: socket, executable: wrapper) } + error = + assert_raises(LibTmux::CommandError) do + LibTmux::Server.open(socket_path: socket, executable: wrapper) + end assert_operator Process.clock_gettime(Process::CLOCK_MONOTONIC) - started, :<, 2.0 assert_equal :not_sent, error.delivery ensure @@ -304,8 +422,11 @@ def test_owned_startup_checks_the_executable_before_every_daemon with_fixture do |fixture| next assert_refused(fixture) if refused?(fixture) Dir.mktmpdir("libtmux-ruby-version-check-") do |directory| - wrapper, calls, rejected = %w[selected-tmux calls rejected].map { |name| File.join(directory, name) } - LibTmuxTest::StubExecutable.write(wrapper, <<~'STUB', CALLS: calls, CLIENT: CLIENT_PATH.call, REJECTED: rejected) + wrapper, calls, rejected = + %w[selected-tmux calls rejected].map { |name| File.join(directory, name) } + LibTmuxTest::StubExecutable.write( + wrapper, + <<~'STUB', File.write(CALLS, "#{ARGV.join(' ')}\n", mode: "a") if ARGV.first == "-V" && File.exist?(REJECTED) puts "tmux 3.3" @@ -313,10 +434,17 @@ def test_owned_startup_checks_the_executable_before_every_daemon end exec CLIENT, *ARGV STUB + CALLS: calls, + CLIENT: CLIENT_PATH.call, + REJECTED: rejected + ) LibTmux::Server.start(executable: wrapper) { |server| assert server.owned? } File.write(rejected, "changed") File.write(calls, "") - error = assert_raises(LibTmux::UnsupportedFeatureError) { LibTmux::Server.start(executable: wrapper) } + error = + assert_raises(LibTmux::UnsupportedFeatureError) do + LibTmux::Server.start(executable: wrapper) + end assert_equal :not_sent, error.delivery assert_equal ["-V"], File.readlines(calls, chomp: true) end @@ -334,7 +462,10 @@ def test_owned_startup_accepts_renamed_and_binary_executable_names File.symlink(CLIENT_PATH.call, selected) rescue Errno::EILSEQ # APFS rejects file names that are not valid UTF-8. - raise unless RUBY_PLATFORM.include?("darwin") && !name.dup.force_encoding(Encoding::UTF_8).valid_encoding? + unless RUBY_PLATFORM.include?("darwin") && + !name.dup.force_encoding(Encoding::UTF_8).valid_encoding? + raise + end next end LibTmux::Server.start(executable: selected) { |server| assert server.owned? } @@ -350,9 +481,14 @@ def test_an_endpoint_without_a_running_daemon_is_not_supported Dir.mktmpdir("libtmux-ruby-version-check-") do |directory| socket = File.join(directory, "socket") UNIXServer.new(socket).close - error = assert_raises(LibTmux::TargetNotFoundError) { LibTmux::Server.open(socket_path: socket, executable: CLIENT) } - assert_equal [:not_sent, :admission], [error.delivery, error.phase] - assert_raises(LibTmux::TargetNotFoundError) { LibTmux::Server.open(socket_path: File.join(directory, "missing"), executable: CLIENT) } + error = + assert_raises(LibTmux::TargetNotFoundError) do + LibTmux::Server.open(socket_path: socket, executable: CLIENT) + end + assert_equal %i[not_sent admission], [error.delivery, error.phase] + assert_raises(LibTmux::TargetNotFoundError) do + LibTmux::Server.open(socket_path: File.join(directory, "missing"), executable: CLIENT) + end end end @@ -378,9 +514,11 @@ def plant_sentinels(fixture) def assert_sentinels_unchanged(fixture) assert_equal "planted", fixture.tmux("show-option", "-gqv", "@sentinel").first.strip - assert_equal ["sentinel"], fixture.tmux("list-buffers", "-F", '#{buffer_name}').first.lines.map(&:chomp) + assert_equal ["sentinel"], + fixture.tmux("list-buffers", "-F", '#{buffer_name}').first.lines.map(&:chomp) assert_equal "planted", fixture.tmux("show-buffer", "-b", "sentinel").first - assert_equal ["fixture"], fixture.tmux("list-sessions", "-F", '#{session_name}').first.lines.map(&:chomp) + assert_equal ["fixture"], + fixture.tmux("list-sessions", "-F", '#{session_name}').first.lines.map(&:chomp) end def with_fixture diff --git a/test/integration/workspace_cli_test.rb b/test/integration/workspace_cli_test.rb index 4cdbd11b..f050af20 100644 --- a/test/integration/workspace_cli_test.rb +++ b/test/integration/workspace_cli_test.rb @@ -17,24 +17,38 @@ def test_switch_selects_current_client_after_apply_and_retains_creations_on_fail token = LibTmux::Internal::Cancellation.new PTY.open do |_master, terminal| terminal.winsize = [24, 80] - assert fixture.tmux("set-hook", "-g", "client-attached", "wait-for -S cli-switch-attached").last.success? + assert fixture + .tmux("set-hook", "-g", "client-attached", "wait-for -S cli-switch-attached") + .last + .success? session = server.list_sessions.first - worker = Thread.new do - server.attach(session: session.ref, terminal: terminal, term: "xterm", cancel: token) - rescue LibTmux::Cancelled - nil - end + worker = + Thread.new do + server.attach(session: session.ref, terminal: terminal, term: "xterm", cancel: token) + rescue LibTmux::Cancelled + nil + end begin assert fixture.tmux("wait-for", "cli-switch-attached").last.success? selector = server.list_clients.fetch(0).fetch(:name) - status, value, diagnostics = cli(fixture, ["load", write_config(fixture, "switched"), "--switch", selector]) + status, value, diagnostics = + cli(fixture, ["load", write_config(fixture, "switched"), "--switch", selector]) assert_equal 0, status assert value.fetch("success") assert_empty diagnostics selected_id = value.fetch("created_refs").fetch("session").fetch("id") assert_equal selected_id, server.list_clients.fetch(0).fetch(:session_id) assert worker.alive?, "switch must not own or retire the selected client" - status, value, = cli(fixture, ["load", write_config(fixture, "missing-client"), "--switch", "private-missing-client"]) + status, value, = + cli( + fixture, + [ + "load", + write_config(fixture, "missing-client"), + "--switch", + "private-missing-client" + ] + ) assert_equal 3, status assert_equal "execution", value.fetch("error").fetch("kind") assert_equal 3, value.fetch("result").fetch("created_refs").length @@ -44,7 +58,8 @@ def test_switch_selects_current_client_after_apply_and_retains_creations_on_fail refute_includes JSON.generate(value), "private-missing-client" before = server.list_sessions.map(&:id) [["--switch"], ["--switch", ""], ["--attach", "--switch", selector]].each do |flags| - status, value, = cli(fixture, ["load", write_config(fixture, "invalid-switch"), *flags]) + status, value, = + cli(fixture, ["load", write_config(fixture, "invalid-switch"), *flags]) assert_equal 2, status refute value.key?("result") assert_equal before, server.list_sessions.map(&:id) @@ -65,7 +80,7 @@ def test_live_plan_detached_load_and_conflict_return_distinct_json_results LibTmuxTest::TmuxFixture.open do |fixture| file = write_config(fixture, "cli") valid = File.read(file) - invalid = JSON.parse(valid).merge("window_options" => {"pane-base-index" => 65536}) + invalid = JSON.parse(valid).merge("window_options" => { "pane-base-index" => 65_536 }) File.write(file, JSON.generate(invalid)) status, value, diagnostics = cli(fixture, ["load", file]) assert_equal 2, status @@ -137,29 +152,63 @@ def test_directory_availability_is_checked_only_when_loading def test_load_and_live_plan_without_a_socket_flag_use_the_server_the_environment_names LibTmuxTest::TmuxFixture.open do |fixture| # An unnamed socket would land in the fixture's directory, where no server runs. - environment = {"LIBTMUX_SOCKET_PATH" => fixture.socket_path, "TMUX_TMPDIR" => File.dirname(fixture.socket_path)} - status, value, diagnostics = cli(fixture, ["plan", "--live", write_config(fixture, "from-variable")], socket: false, environment: environment) + environment = { + "LIBTMUX_SOCKET_PATH" => fixture.socket_path, + "TMUX_TMPDIR" => File.dirname(fixture.socket_path) + } + status, value, diagnostics = + cli( + fixture, + ["plan", "--live", write_config(fixture, "from-variable")], + socket: false, + environment: environment + ) assert_equal 0, status assert_equal "captured_create", value.fetch("mode") assert_empty diagnostics - status, value, diagnostics = cli(fixture, ["load", write_config(fixture, "from-variable")], socket: false, environment: environment) + status, value, diagnostics = + cli( + fixture, + ["load", write_config(fixture, "from-variable")], + socket: false, + environment: environment + ) assert_equal 0, status assert_equal true, value.fetch("success") assert_empty diagnostics - assert_equal ["fixture", "from-variable"], fixture.tmux("list-sessions", "-F", '#{session_name}').first.lines.map(&:chomp).sort + assert_equal %w[fixture from-variable], + fixture + .tmux("list-sessions", "-F", '#{session_name}') + .first + .lines + .map(&:chomp) + .sort end end def test_load_without_a_socket_flag_or_server_fails_without_starting_one Dir.mktmpdir("libtmux-ruby-cli-") do |directory| file = File.join(directory, "workspace.json") - File.write(file, JSON.generate({session_name: "none", windows: [{window_name: "one", panes: [{}]}]})) + File.write( + file, + JSON.generate({ session_name: "none", windows: [{ window_name: "one", panes: [{}] }] }) + ) output, diagnostics = StringIO.new, StringIO.new - status = LibTmux::Workspace::CLI.run(["load", file, "--json"], out: output, err: diagnostics, directory: directory, - environment: {"TMUX_TMPDIR" => directory}) + status = + LibTmux::Workspace::CLI.run( + ["load", file, "--json"], + out: output, + err: diagnostics, + directory: directory, + environment: { + "TMUX_TMPDIR" => directory + } + ) assert_equal 1, status assert_equal "execution", JSON.parse(output.string).fetch("error").fetch("kind") - assert_empty Dir.glob(File.join(directory, "**", "*"), File::FNM_DOTMATCH).select { |path| File.socket?(path) } + assert_empty Dir + .glob(File.join(directory, "**", "*"), File::FNM_DOTMATCH) + .select { |path| File.socket?(path) } end end @@ -178,12 +227,13 @@ def test_partial_application_and_interrupt_keep_the_ledger_with_distinct_exit_co ensure LibTmux::Options.define_method(:set, original) end - trace = TracePoint.new(:return) do |point| - next unless point.self.is_a?(LibTmux::Server) && point.method_id == :new_session + trace = + TracePoint.new(:return) do |point| + next unless point.self.is_a?(LibTmux::Server) && point.method_id == :new_session - trace.disable - Thread.current.raise(Interrupt.new("private-interruption")) - end + trace.disable + Thread.current.raise(Interrupt.new("private-interruption")) + end begin trace.enable status, value, diagnostics = cli(fixture, ["load", write_config(fixture, "interrupted")]) @@ -213,7 +263,13 @@ def test_explicit_attach_owns_only_its_terminal_client_and_returns_after_user_de assert_match(/Workspace created/, display) end assert_empty fixture.tmux("list-clients").first - assert_equal ["attached", "fixture"], fixture.tmux("list-sessions", "-F", '#{session_name}').first.lines.map(&:chomp).sort + assert_equal %w[attached fixture], + fixture + .tmux("list-sessions", "-F", '#{session_name}') + .first + .lines + .map(&:chomp) + .sort end end @@ -221,20 +277,57 @@ def test_attach_reuses_exact_session_on_explicit_socket_from_controlling_termina LibTmuxTest::TmuxFixture.open do |fixture| LibTmuxTest::TmuxFixture.open do |decoy| assert fixture.tmux("set-option", "-g", "assume-paste-time", "0").last.success? - target, _, status = fixture.tmux("new-session", "-d", "-P", "-F", "\#{session_id}", "-s", "wanted", "cat") + target, _, status = + fixture.tmux("new-session", "-d", "-P", "-F", "\#{session_id}", "-s", "wanted", "cat") assert status.success? target = target.chomp before = workspace_layout(fixture) decoy_before = workspace_layout(decoy) - assert_equal 0, attach_and_detach(fixture, target, fixture.executable, "-S", fixture.socket_path, - "attach-session", "-t", target) - assert_equal 0, attach_and_detach(fixture, target, *workspace_command, "attach", "--socket", fixture.socket_path, - target, environment: {"LIBTMUX_SOCKET_PATH" => decoy.socket_path}) - read_only_input = [Gem.ruby, "-e", 'STDIN.reopen(IO.popen(["tty"], &:read).chomp, "r"); exec(*ARGV)', "--"] - assert_equal 0, attach_and_detach(fixture, target, *read_only_input, *workspace_command, "attach", "--socket", - fixture.socket_path, target) - assert_terminal_failure([*workspace_command, "attach", "--socket", decoy.socket_path, target], - /session ID was not found/) + assert_equal 0, + attach_and_detach( + fixture, + target, + fixture.executable, + "-S", + fixture.socket_path, + "attach-session", + "-t", + target + ) + assert_equal 0, + attach_and_detach( + fixture, + target, + *workspace_command, + "attach", + "--socket", + fixture.socket_path, + target, + environment: { + "LIBTMUX_SOCKET_PATH" => decoy.socket_path + } + ) + read_only_input = [ + Gem.ruby, + "-e", + 'STDIN.reopen(IO.popen(["tty"], &:read).chomp, "r"); exec(*ARGV)', + "--" + ] + assert_equal 0, + attach_and_detach( + fixture, + target, + *read_only_input, + *workspace_command, + "attach", + "--socket", + fixture.socket_path, + target + ) + assert_terminal_failure( + [*workspace_command, "attach", "--socket", decoy.socket_path, target], + /session ID was not found/ + ) assert_equal before, workspace_layout(fixture) assert_equal decoy_before, workspace_layout(decoy) assert_empty fixture.tmux("list-clients").first @@ -247,23 +340,27 @@ def test_attach_rejects_malformed_missing_and_redirected_targets_without_changin LibTmuxTest::TmuxFixture.open do |fixture| before = workspace_layout(fixture) command = [*workspace_command, "attach", "--socket", fixture.socket_path] - _, diagnostics, status = Open3.capture3({"TERM" => "xterm"}, *command, "fixture") + _, diagnostics, status = Open3.capture3({ "TERM" => "xterm" }, *command, "fixture") assert_equal 2, status.exitstatus assert_match(/numeric session ID/, diagnostics) - _, diagnostics, status = Open3.capture3({"TERM" => "xterm"}, *workspace_command, "attach", "$0") + _, diagnostics, status = + Open3.capture3({ "TERM" => "xterm" }, *workspace_command, "attach", "$0") assert_equal 2, status.exitstatus assert_match(/Provide --socket PATH/, diagnostics) - _, diagnostics, status = Open3.capture3({"TERM" => "xterm"}, *command, "--live", "$0") + _, diagnostics, status = Open3.capture3({ "TERM" => "xterm" }, *command, "--live", "$0") assert_equal 2, status.exitstatus assert_match(/Attach accepts --socket and --timeout/, diagnostics) - _, diagnostics, status = Open3.capture3({"TERM" => "xterm"}, *command, "$0") + _, diagnostics, status = Open3.capture3({ "TERM" => "xterm" }, *command, "$0") assert_equal 1, status.exitstatus assert_match(/interactive terminal/, diagnostics) redirect = [Gem.ruby, "-e", 'STDOUT.reopen(File::NULL, "w"); exec(*ARGV)', "--"] assert_terminal_failure(redirect + command + ["$0"], /interactive terminal/) assert_terminal_failure(command + ["$9999"], /session ID was not found/) missing_socket = File.join(File.dirname(fixture.socket_path), "missing") - assert_terminal_failure([*workspace_command, "attach", "--socket", missing_socket, "$0"], /Workspace execution failed/) + assert_terminal_failure( + [*workspace_command, "attach", "--socket", missing_socket, "$0"], + /Workspace execution failed/ + ) assert_equal before, workspace_layout(fixture) refute File.exist?(missing_socket) end @@ -275,7 +372,12 @@ def test_attach_and_load_refuse_invalid_term_without_changing_workspace file = write_config(fixture, "uncreated") socket = ["--socket", fixture.socket_path] load = [*workspace_command, "load", "--attach", "--json", *socket, file] - with_controlling_terminal(load, environment: {"TERM" => "invalid/type"}) do |output, _input, pid| + with_controlling_terminal( + load, + environment: { + "TERM" => "invalid/type" + } + ) do |output, _input, pid| diagnostics, status = read_terminal_exit(output, pid) assert_equal 2, status, diagnostics response = JSON.parse(diagnostics) @@ -284,7 +386,12 @@ def test_attach_and_load_refuse_invalid_term_without_changing_workspace end attach = [*workspace_command, "attach", *socket, "$0"] - with_controlling_terminal(attach, environment: {"TERM" => "invalid/type"}) do |output, _input, pid| + with_controlling_terminal( + attach, + environment: { + "TERM" => "invalid/type" + } + ) do |output, _input, pid| diagnostics, status = read_terminal_exit(output, pid) assert_equal 2, status, diagnostics assert_match(/Set TERM to the terminal type/, diagnostics) @@ -304,7 +411,12 @@ def workspace_command end def workspace_layout(fixture) - fixture.tmux("list-panes", "-a", "-F", "\#{session_id} \#{session_name} \#{window_id} \#{pane_id}").first + fixture.tmux( + "list-panes", + "-a", + "-F", + "\#{session_id} \#{session_name} \#{window_id} \#{pane_id}" + ).first end def attach_and_detach(fixture, target, *command, environment: {}) @@ -326,14 +438,23 @@ def assert_terminal_failure(command, expected) def write_config(fixture, name) file = File.join(File.dirname(fixture.socket_path), "#{name}.json") - File.write(file, JSON.generate({session_name: name, windows: [{window_name: "one", panes: [{}]}]})) + File.write( + file, + JSON.generate({ session_name: name, windows: [{ window_name: "one", panes: [{}] }] }) + ) file end def cli(fixture, arguments, socket: true, environment: {}) output, diagnostics = StringIO.new, StringIO.new flags = socket ? ["--socket", fixture.socket_path] : [] - status = LibTmux::Workspace::CLI.run([*arguments, "--json", *flags], out: output, err: diagnostics, environment: environment) + status = + LibTmux::Workspace::CLI.run( + [*arguments, "--json", *flags], + out: output, + err: diagnostics, + environment: environment + ) [status, JSON.parse(output.string), diagnostics.string] end end diff --git a/test/integration/workspace_test.rb b/test/integration/workspace_test.rb index 37408c1d..2b7c4f46 100644 --- a/test/integration/workspace_test.rb +++ b/test/integration/workspace_test.rb @@ -11,18 +11,26 @@ def test_history_limit_precedes_new_panes_and_preserves_native_initial_grid LibTmuxTest::TmuxFixture.open do |fixture| LibTmux::Server.open(socket_path: fixture.socket_path) do |server| inherited = server.options(scope: :session).get("history-limit").as(:integer) - source = {"session_name" => "history", "options" => {"history-limit" => 123}, "windows" => [ - {"window_name" => "first", "panes" => [{}, {}]}, - {"window_name" => "second", "panes" => [{}]} - ]} + source = { + "session_name" => "history", + "options" => { + "history-limit" => 123 + }, + "windows" => [ + { "window_name" => "first", "panes" => [{}, {}] }, + { "window_name" => "second", "panes" => [{}] } + ] + } result = workspace(source, File.dirname(fixture.socket_path)).plan.apply(server: server) assert result.success? - limits = %w[pane:0:0 pane:0:1 pane:1:0].map do |key| - server.pane(result.created_refs.fetch(key)).display('#{history_limit}').text.to_i - end + limits = + %w[pane:0:0 pane:0:1 pane:1:0].map do |key| + server.pane(result.created_refs.fetch(key)).display('#{history_limit}').text.to_i + end assert_equal [123, 123], limits.drop(1) release = LibTmux::Internal::TmuxVersion.parse(server.snapshot.server_info.fetch(:version)) - assert_equal release >= LibTmux::Internal::TmuxVersion.parse("3.7") ? 123 : inherited, limits.first + assert_equal release >= LibTmux::Internal::TmuxVersion.parse("3.7") ? 123 : inherited, + limits.first assert_equal inherited, server.options(scope: :session).get("history-limit").as(:integer) end end @@ -35,11 +43,29 @@ def test_apply_reuses_initial_entities_and_reports_dispatch_without_shell_comple begin LibTmux::Server.open(socket_path: fixture.socket_path) do |server| server.options(scope: :window).set("synchronize-panes", true) - source = {"session_name" => "workspace", "environment" => {"ROOT" => "root"}, "windows" => [ - {"window_name" => "first", "window_index" => 3, "layout" => "tiled", "panes" => [ - {"environment" => {"ROOT" => "pane"}, "shell_command" => receipt_command(listener.path)}, {}]}, - {"window_name" => "second", "window_index" => 7, "focus" => true, "panes" => [{}]} - ]} + source = { + "session_name" => "workspace", + "environment" => { + "ROOT" => "root" + }, + "windows" => [ + { + "window_name" => "first", + "window_index" => 3, + "layout" => "tiled", + "panes" => [ + { + "environment" => { + "ROOT" => "pane" + }, + "shell_command" => receipt_command(listener.path) + }, + {} + ] + }, + { "window_name" => "second", "window_index" => 7, "focus" => true, "panes" => [{}] } + ] + } plan = workspace(source, directory).plan(snapshot: server.snapshot) result = plan.apply(server: server) assert result.success? @@ -49,8 +75,10 @@ def test_apply_reuses_initial_entities_and_reports_dispatch_without_shell_comple assert_equal [3, 7], session.list_window_links.map(&:index) assert_equal 3, session.list_panes.length assert_equal "root", session.environment("ROOT") - assert_equal "#{result.created_refs.fetch('window:1').id}\n", session.display('#{window_id}').text - assert IO.select([listener], nil, nil, 0.5), "authored shell command did not send its receipt" + assert_equal "#{result.created_refs.fetch("window:1").id}\n", + session.display('#{window_id}').text + assert IO.select([listener], nil, nil, 0.5), + "authored shell command did not send its receipt" client = listener.accept begin assert_equal [File.realpath(directory), "pane"], Marshal.load(client.read) @@ -58,7 +86,8 @@ def test_apply_reuses_initial_entities_and_reports_dispatch_without_shell_comple client.close end assert_equal 1, result.effects.count { |effect| effect.action == :dispatch_command } - assert_equal :dispatch_only, result.effects.find { |effect| effect.action == :dispatch_command }.outcome + assert_equal :dispatch_only, + result.effects.find { |effect| effect.action == :dispatch_command }.outcome assert result.created_refs.frozen? refute_includes result.inspect, directory conflict = assert_raises(LibTmux::Workspace::ApplyError) { plan.apply(server: server) } @@ -75,7 +104,10 @@ def test_apply_reuses_initial_entities_and_reports_dispatch_without_shell_comple def test_initial_children_replaced_after_creation_are_never_attributed_as_created LibTmuxTest::TmuxFixture.open do |fixture| LibTmux::Server.open(socket_path: fixture.socket_path) do |server| - source = {"session_name" => "partial", "windows" => [{"window_name" => "one", "panes" => [{}]}]} + source = { + "session_name" => "partial", + "windows" => [{ "window_name" => "one", "panes" => [{}] }] + } plan = workspace(source, File.dirname(fixture.socket_path)).plan borrowed = server.list_window_links.fetch(0) original = server.method(:new_session) @@ -85,7 +117,10 @@ def test_initial_children_replaced_after_creation_are_never_attributed_as_create receipt.window.kill receipt end - error = assert_raises(LibTmux::Workspace::ApplyError) { plan.apply(server: server, compensate: true) } + error = + assert_raises(LibTmux::Workspace::ApplyError) do + plan.apply(server: server, compensate: true) + end assert_equal 3, error.result.created_refs.length refute_includes error.result.created_refs.values.map(&:id), borrowed.id assert_equal :failed, error.result.compensation @@ -97,12 +132,18 @@ def test_initial_children_replaced_after_creation_are_never_attributed_as_create def test_precancelled_apply_and_foreign_snapshot_refuse_before_creation LibTmuxTest::TmuxFixture.open do |fixture| LibTmux::Server.open(socket_path: fixture.socket_path) do |server| - source = {"session_name" => "refused", "windows" => [{"window_name" => "one", "panes" => [{}]}]} + source = { + "session_name" => "refused", + "windows" => [{ "window_name" => "one", "panes" => [{}] }] + } config = workspace(source, File.dirname(fixture.socket_path)) cancellation = LibTmux::Internal::Cancellation.new begin cancellation.cancel - error = assert_raises(LibTmux::Workspace::ApplyError) { config.plan.apply(server: server, cancel: cancellation) } + error = + assert_raises(LibTmux::Workspace::ApplyError) do + config.plan.apply(server: server, cancel: cancellation) + end assert_empty error.result.created_refs assert_equal :not_sent, error.delivery ensure @@ -126,10 +167,13 @@ def test_directory_preflight_identifies_the_affected_pane_without_showing_the_di directory = File.dirname(fixture.socket_path) file = File.join(directory, "private-not-a-directory") File.write(file, "") - source = {"session_name" => "refused", "windows" => [ - {"window_name" => "first", "panes" => [{}]}, - {"window_name" => "private-window-name", "start_directory" => file, "panes" => [{}]} - ]} + source = { + "session_name" => "refused", + "windows" => [ + { "window_name" => "first", "panes" => [{}] }, + { "window_name" => "private-window-name", "start_directory" => file, "panes" => [{}] } + ] + } LibTmux::Server.open(socket_path: fixture.socket_path) do |server| plan = workspace(source, directory).plan(snapshot: server.snapshot) error = assert_raises(LibTmux::Workspace::ApplyError) { plan.apply(server: server) } @@ -155,20 +199,27 @@ def test_directory_preflight_identifies_the_affected_pane_without_showing_the_di def test_lost_creation_reply_remains_uncertain_and_never_compensates_by_name LibTmuxTest::TmuxFixture.open do |fixture| LibTmux::Server.open(socket_path: fixture.socket_path) do |server| - source = {"session_name" => "unconfirmed", "windows" => [{"window_name" => "one", "panes" => [{}]}]} + source = { + "session_name" => "unconfirmed", + "windows" => [{ "window_name" => "one", "panes" => [{}] }] + } create = server.method(:new_session) server.define_singleton_method(:new_session) do |**options| create.call(**options) raise LibTmux::TransportError.new("private-lost-reply", delivery: :possibly_sent) end - error = assert_raises(LibTmux::Workspace::ApplyError) do - workspace(source, File.dirname(fixture.socket_path)).plan.apply(server: server, compensate: true) - end + error = + assert_raises(LibTmux::Workspace::ApplyError) do + workspace(source, File.dirname(fixture.socket_path)).plan.apply( + server: server, + compensate: true + ) + end assert error.result.uncertain? assert_equal :possibly_sent, error.delivery assert_equal :nothing_owned, error.result.compensation assert_empty error.result.created_refs - assert_equal ["fixture", "unconfirmed"], server.snapshot.sessions.map(&:name).sort + assert_equal %w[fixture unconfirmed], server.snapshot.sessions.map(&:name).sort refute_includes error.full_message, "private-lost-reply" end end @@ -177,23 +228,31 @@ def test_lost_creation_reply_remains_uncertain_and_never_compensates_by_name def test_pending_interrupt_records_creation_before_compensation_and_keeps_primary_failure LibTmuxTest::TmuxFixture.open do |fixture| LibTmux::Server.open(socket_path: fixture.socket_path) do |server| - source = {"session_name" => "interrupted", "windows" => [{"window_name" => "one", "panes" => [{}]}]} + source = { + "session_name" => "interrupted", + "windows" => [{ "window_name" => "one", "panes" => [{}] }] + } primary = Interrupt.new("private-first-interrupt") second = RuntimeError.new("private-second-interrupt") - trace = TracePoint.new(:return, :call) do |point| - next unless point.self == server || point.self.is_a?(LibTmux::Session) - if point.event == :return && point.method_id == :new_session - Thread.current.raise(primary) - elsif point.event == :call && point.method_id == :kill - trace.disable - Thread.current.raise(second) + trace = + TracePoint.new(:return, :call) do |point| + next unless point.self == server || point.self.is_a?(LibTmux::Session) + if point.event == :return && point.method_id == :new_session + Thread.current.raise(primary) + elsif point.event == :call && point.method_id == :kill + trace.disable + Thread.current.raise(second) + end end - end begin trace.enable - error = assert_raises(LibTmux::Workspace::ApplyError) do - workspace(source, File.dirname(fixture.socket_path)).plan.apply(server: server, compensate: true) - end + error = + assert_raises(LibTmux::Workspace::ApplyError) do + workspace(source, File.dirname(fixture.socket_path)).plan.apply( + server: server, + compensate: true + ) + end assert_equal "Interrupt", error.failure_class assert_equal 3, error.result.created_refs.length assert_equal :completed, error.result.compensation @@ -212,15 +271,23 @@ def test_compensation_preserves_a_borrowed_window_moved_into_the_created_session borrowed = server.list_window_links.fetch(0) original = LibTmux::Options.instance_method(:set) LibTmux::Options.define_method(:set) do |*arguments, **options| - new_session = server.list_sessions.find { |session| session.id != borrowed.ref.session_id } + new_session = + server.list_sessions.find { |session| session.id != borrowed.ref.session_id } borrowed.move(session: new_session.ref, index: 9) raise LibTmux::TransportError.new("acquisition failed", delivery: :not_sent) end begin - source = {"session_name" => "borrowed-survivor", "windows" => [{"window_name" => "one", "panes" => [{}]}]} - error = assert_raises(LibTmux::Workspace::ApplyError) do - workspace(source, File.dirname(fixture.socket_path)).plan.apply(server: server, compensate: true) - end + source = { + "session_name" => "borrowed-survivor", + "windows" => [{ "window_name" => "one", "panes" => [{}] }] + } + error = + assert_raises(LibTmux::Workspace::ApplyError) do + workspace(source, File.dirname(fixture.socket_path)).plan.apply( + server: server, + compensate: true + ) + end assert_equal :failed, error.result.compensation assert_includes server.list_windows.map(&:id), borrowed.id assert_equal 3, error.result.created_refs.length @@ -239,10 +306,17 @@ def test_compensation_removes_only_a_complete_positively_identified_new_topology raise LibTmux::TransportError.new("option dispatch failed", delivery: :not_sent) end begin - source = {"session_name" => "known", "windows" => [{"window_name" => "one", "panes" => [{}]}]} - error = assert_raises(LibTmux::Workspace::ApplyError) do - workspace(source, File.dirname(fixture.socket_path)).plan.apply(server: server, compensate: true) - end + source = { + "session_name" => "known", + "windows" => [{ "window_name" => "one", "panes" => [{}] }] + } + error = + assert_raises(LibTmux::Workspace::ApplyError) do + workspace(source, File.dirname(fixture.socket_path)).plan.apply( + server: server, + compensate: true + ) + end assert_equal 3, error.result.created_refs.length assert_equal [1], error.result.completed_steps assert_equal :completed, error.result.compensation @@ -265,10 +339,17 @@ def test_compensation_preserves_a_borrowed_pane_joined_into_a_created_window raise LibTmux::TransportError.new("option dispatch failed", delivery: :not_sent) end begin - source = {"session_name" => "borrowed-pane", "windows" => [{"window_name" => "one", "panes" => [{}]}]} - error = assert_raises(LibTmux::Workspace::ApplyError) do - workspace(source, File.dirname(fixture.socket_path)).plan.apply(server: server, compensate: true) - end + source = { + "session_name" => "borrowed-pane", + "windows" => [{ "window_name" => "one", "panes" => [{}] }] + } + error = + assert_raises(LibTmux::Workspace::ApplyError) do + workspace(source, File.dirname(fixture.socket_path)).plan.apply( + server: server, + compensate: true + ) + end assert_equal :failed, error.result.compensation assert_includes server.list_panes.map(&:id), borrowed.id refute_includes error.result.created_refs.values, borrowed.ref @@ -286,7 +367,8 @@ def workspace(source, directory) end def receipt_command(path) - source = 'UNIXSocket.open(ARGV.fetch(0)) { |io| io.write(Marshal.dump([Dir.pwd, ENV["ROOT"]])) }' + source = + 'UNIXSocket.open(ARGV.fetch(0)) { |io| io.write(Marshal.dump([Dir.pwd, ENV["ROOT"]])) }' [Gem.ruby, "--disable=rubyopt,gems", "-rsocket", "-e", source, path].shelljoin end end diff --git a/test/integration/workspace_tmuxp_test.rb b/test/integration/workspace_tmuxp_test.rb index 64380242..338a034b 100644 --- a/test/integration/workspace_tmuxp_test.rb +++ b/test/integration/workspace_tmuxp_test.rb @@ -21,18 +21,30 @@ def start(&block) def built(server) session = server.list_sessions.fetch(0) current = session.snapshot.current_window.id - windows = session.list_window_links.sort_by(&:index).map do |link| - window = link.window - snapshot = window.snapshot - layout = snapshot.layout - window.select_layout(layout_name(window)) if layout_name(window) - {"name" => snapshot.name, "index" => link.index, "focus" => snapshot.id == current, - "layout" => layout_name(window) && window.snapshot.layout == layout, - "panes" => window.list_panes.map do |pane| - {"focus" => pane.snapshot.active, "start_directory" => File.realpath(pane.display('#{pane_start_path}').text.chomp)} - end} - end - {"session" => session.snapshot.name, "windows" => windows} + windows = + session + .list_window_links + .sort_by(&:index) + .map do |link| + window = link.window + snapshot = window.snapshot + layout = snapshot.layout + window.select_layout(layout_name(window)) if layout_name(window) + { + "name" => snapshot.name, + "index" => link.index, + "focus" => snapshot.id == current, + "layout" => layout_name(window) && window.snapshot.layout == layout, + "panes" => + window.list_panes.map do |pane| + { + "focus" => pane.snapshot.active, + "start_directory" => File.realpath(pane.display('#{pane_start_path}').text.chomp) + } + end + } + end + { "session" => session.snapshot.name, "windows" => windows } end def layout_name(window) @@ -43,23 +55,50 @@ def layout_name(window) # with directories made real. def wanted(name, home: Catalog::HOME_DIRECTORY) base = File.realpath(File.dirname(Catalog.path(name))) - real = ->(directory) { File.realpath(directory.sub(Catalog::WORKSPACE_DIR, base).sub(Catalog::HOME, home)) } + real = ->(directory) do + File.realpath(directory.sub(Catalog::WORKSPACE_DIR, base).sub(Catalog::HOME, home)) + end tree = Catalog.port_expected(name) - {"session" => tree.dig("session", "name"), - "windows" => tree.fetch("windows").sort_by { |window| window.fetch("index") }.map do |window| - {"name" => window.fetch("name"), "index" => window.fetch("index"), "focus" => window.fetch("focus"), - "layout" => window["layout"] ? true : nil, - "panes" => window.fetch("panes").map { |pane| {"focus" => pane.fetch("focus"), "start_directory" => real.call(pane.fetch("start_directory"))} }} - end} + { + "session" => tree.dig("session", "name"), + "windows" => + tree + .fetch("windows") + .sort_by { |window| window.fetch("index") } + .map do |window| + { + "name" => window.fetch("name"), + "index" => window.fetch("index"), + "focus" => window.fetch("focus"), + "layout" => window["layout"] ? true : nil, + "panes" => + window + .fetch("panes") + .map do |pane| + { + "focus" => pane.fetch("focus"), + "start_directory" => real.call(pane.fetch("start_directory")) + } + end + } + end + } end Catalog::LOADED.each do |name| - define_method("test_#{name.delete_suffix('.yaml').tr('-', '_')}_builds_the_tree_tmuxp_documents") do + define_method( + "test_#{name.delete_suffix(".yaml").tr("-", "_")}_builds_the_tree_tmuxp_documents" + ) do Dir.mktmpdir("libtmux-ruby-workspace-home-") do |home| start do |server| workspace = Catalog.workspace(name, home: home) assert workspace.plan(snapshot: server.snapshot).apply(server: server).success? - @layouts = workspace.to_h.fetch("windows").each_with_index.to_h { |window, index| [server.list_windows.fetch(index).id, window["layout"]] } + @layouts = + workspace + .to_h + .fetch("windows") + .each_with_index + .to_h { |window, index| [server.list_windows.fetch(index).id, window["layout"]] } assert_equal wanted(name, home: home), built(server) end end @@ -69,11 +108,14 @@ def wanted(name, home: Catalog::HOME_DIRECTORY) def test_the_comparison_reports_a_tree_that_differs start do |server| Catalog.workspace("3-pane.yaml").plan(snapshot: server.snapshot).apply(server: server) - @layouts = {server.list_windows.fetch(0).id => "main-vertical"} + @layouts = { server.list_windows.fetch(0).id => "main-vertical" } tree = built(server) assert_equal wanted("3-pane.yaml"), tree refute_equal wanted("4-pane.yaml"), tree - refute_equal wanted("3-pane.yaml").tap { |expected| expected["windows"][0]["panes"][0]["focus"] = false }, tree + refute_equal wanted("3-pane.yaml").tap { |expected| + expected["windows"][0]["panes"][0]["focus"] = false + }, + tree end end end diff --git a/test/old_daemon/pre_3_2_refusal_test.rb b/test/old_daemon/pre_3_2_refusal_test.rb index 434a1e75..b2959690 100644 --- a/test/old_daemon/pre_3_2_refusal_test.rb +++ b/test/old_daemon/pre_3_2_refusal_test.rb @@ -24,18 +24,24 @@ def test_the_lane_runs_the_release_it_names assert_includes %w[3.0a 3.1c], EXPECT assert_equal "tmux #{EXPECT}", capture(DAEMON, "-V").strip refute_equal DAEMON, CLIENT - release = LibTmux::Internal::TmuxVersion.parse(capture(CLIENT, "-V").strip.delete_prefix("tmux ")) + release = + LibTmux::Internal::TmuxVersion.parse(capture(CLIENT, "-V").strip.delete_prefix("tmux ")) assert_operator release, :>=, LibTmux::Internal::TmuxVersion.parse("3.3a") end def test_the_old_daemon_is_refused_before_effects_without_waiting_for_its_stdout with_daemon do |socket| started = monotonic - error = assert_raises(LibTmux::UnsupportedFeatureError) { LibTmux::Server.open(socket_path: socket, executable: CLIENT) } + error = + assert_raises(LibTmux::UnsupportedFeatureError) do + LibTmux::Server.open(socket_path: socket, executable: CLIENT) + end assert_operator monotonic - started, :<, PROMPT_SECONDS - assert_equal [:not_sent, :admission], [error.delivery, error.phase] - assert_match(/tmux 3\.3a or newer is required \(the connected daemon is older than 3\.2\); upgrade tmux and restart the server/, - error.message) + assert_equal %i[not_sent admission], [error.delivery, error.phase] + assert_match( + /tmux 3\.3a or newer is required \(the connected daemon is older than 3\.2\); upgrade tmux and restart the server/, + error.message + ) assert_untouched(socket) end end @@ -47,7 +53,13 @@ def test_the_mcp_entry_point_reports_the_refusal_promptly output, protocol = IO.pipe errors = StringIO.new started = monotonic - status = LibTmux::MCP::CLI.run(["--socket", socket, "--tmux", CLIENT], input: input, out: protocol, err: errors) + status = + LibTmux::MCP::CLI.run( + ["--socket", socket, "--tmux", CLIENT], + input: input, + out: protocol, + err: errors + ) elapsed = monotonic - started protocol.close assert_equal 1, status @@ -59,7 +71,8 @@ def test_the_mcp_entry_point_reports_the_refusal_promptly end def test_owned_startup_refuses_the_old_executable_before_a_daemon_starts - error = assert_raises(LibTmux::UnsupportedFeatureError) { LibTmux::Server.start(executable: DAEMON) } + error = + assert_raises(LibTmux::UnsupportedFeatureError) { LibTmux::Server.start(executable: DAEMON) } assert_equal :not_sent, error.delivery assert_match(/the executable reports #{Regexp.escape(EXPECT)}/, error.message) end @@ -73,14 +86,34 @@ def with_daemon socket = File.join(directory, "socket") config = File.join(directory, "tmux.conf") File.write(config, "set-option -g default-shell /bin/sh\n") - environment = {"TMUX" => nil, "TMUX_PANE" => nil} - streams = {in: File::NULL, out: File.join(directory, "out"), err: File.join(directory, "err")} + environment = { "TMUX" => nil, "TMUX_PANE" => nil } + streams = { + in: File::NULL, + out: File.join(directory, "out"), + err: File.join(directory, "err") + } pid = nil begin - Process.wait(Process.spawn(environment, DAEMON, "-S", socket, "-f", config, "new-session", "-d", "-s", "fixture", "cat", **streams)) + Process.wait( + Process.spawn( + environment, + DAEMON, + "-S", + socket, + "-f", + config, + "new-session", + "-d", + "-s", + "fixture", + "cat", + **streams + ) + ) wait_for_socket(socket) pid = capture(DAEMON, "-S", socket, "display-message", "-p", '#{pid}').to_i - assert_equal EXPECT, capture(DAEMON, "-S", socket, "display-message", "-p", '#{version}').strip + assert_equal EXPECT, + capture(DAEMON, "-S", socket, "display-message", "-p", '#{version}').strip assert_equal "", old(socket, "set-option", "-g", "@sentinel", "planted") yield socket ensure @@ -101,7 +134,15 @@ def old(socket, *arguments) def capture(*command) Dir.mktmpdir("libtmux-ruby-capture-") do |directory| out = File.join(directory, "out") - Process.wait(Process.spawn({"TMUX" => nil, "TMUX_PANE" => nil}, *command, in: File::NULL, out: out, err: File::NULL)) + Process.wait( + Process.spawn( + { "TMUX" => nil, "TMUX_PANE" => nil }, + *command, + in: File::NULL, + out: out, + err: File::NULL + ) + ) File.read(out) end end diff --git a/test/packaging/package_test.rb b/test/packaging/package_test.rb index 784b0dca..6ffb941a 100644 --- a/test/packaging/package_test.rb +++ b/test/packaging/package_test.rb @@ -20,8 +20,13 @@ class PackageTest < Minitest::Test }.freeze def test_runtime_dependencies_accept_minor_updates_and_preserve_sibling_versions - floors = {"json" => "3.0.2", "psych" => "5.5.0", "mcp" => "1.5.1", - "async" => "2.46.0", "digest" => "3.2.1"} + floors = { + "json" => "3.0.2", + "psych" => "5.5.0", + "mcp" => "1.5.1", + "async" => "2.46.0", + "digest" => "3.2.1" + } IMPORTS.each_key do |name| spec = Gem::Specification.load(File.join(ROOT, "gems", name, "#{name}.gemspec")) spec.runtime_dependencies.each do |dependency| @@ -46,14 +51,15 @@ def test_installed_imports_use_declared_dependencies_without_starting_resources # A contributor can keep the installed examples in a directory named libtmux. directory = File.join(temporary, "libtmux") Dir.mkdir(directory) - artifacts = specs.to_h do |name, spec| - assert_equal "MIT", spec.license - assert_includes spec.files, "LICENSE" - assert spec.files.any? { |file| file.start_with?("sig/") }, "missing signatures: #{name}" - refute spec.files.any? { |file| file.start_with?("test/", "vendor/", "benchmark/") } - artifact = package_artifact(spec, directory, ROOT) - [name, artifact] - end + artifacts = + specs.to_h do |name, spec| + assert_equal "MIT", spec.license + assert_includes spec.files, "LICENSE" + assert spec.files.any? { |file| file.start_with?("sig/") }, "missing signatures: #{name}" + refute spec.files.any? { |file| file.start_with?("test/", "vendor/", "benchmark/") } + artifact = package_artifact(spec, directory, ROOT) + [name, artifact] + end IMPORTS.each do |name, import| home = File.join(directory, name) @@ -63,15 +69,27 @@ def test_installed_imports_use_declared_dependencies_without_starting_resources local, external = dependency_closure(specs.fetch(name), specs) external.each { |spec| copy_dependency(spec, home) } environment = { - "GEM_HOME" => home, "GEM_PATH" => home, "RUBYLIB" => nil, + "GEM_HOME" => home, + "GEM_PATH" => home, + "RUBYLIB" => nil, "LC_ALL" => "C", - "RUBYOPT" => nil, "BUNDLE_GEMFILE" => nil, "BUNDLE_BIN_PATH" => nil, - "BUNDLE_LOCKFILE" => nil, "BUNDLER_SETUP" => nil, - "TMUX" => nil, "TMUX_PANE" => nil + "RUBYOPT" => nil, + "BUNDLE_GEMFILE" => nil, + "BUNDLE_BIN_PATH" => nil, + "BUNDLE_LOCKFILE" => nil, + "BUNDLER_SETUP" => nil, + "TMUX" => nil, + "TMUX_PANE" => nil } local.each do |spec| - command = [Gem.ruby, File.join(RbConfig::CONFIG.fetch("bindir"), "gem"), - "install", "--local", "--no-document", artifacts.fetch(spec.name)] + command = [ + Gem.ruby, + File.join(RbConfig::CONFIG.fetch("bindir"), "gem"), + "install", + "--local", + "--no-document", + artifacts.fetch(spec.name) + ] output, status = Open3.capture2e(environment, *command, chdir: directory) assert status.success?, "#{name} installation failed: #{output}" end @@ -98,17 +116,50 @@ def test_installed_imports_use_declared_dependencies_without_starting_resources end RUBY guard = write_import_check(directory, specs, local) - output, status = Open3.capture2e(environment, Gem.ruby, "-r", guard, "-e", source, import, chdir: directory) + output, status = + Open3.capture2e( + environment, + Gem.ruby, + "-r", + guard, + "-e", + source, + import, + chdir: directory + ) assert status.success?, "#{name} import failed: #{output}" assert_empty output, "#{name} import wrote output" if name == "libtmux" - output, status = Open3.capture2e(environment, Gem.ruby, "-r", guard, "-I", File.join(ROOT, "gems/libtmux/lib"), - "-rlibtmux", "-e", "", chdir: directory) + output, status = + Open3.capture2e( + environment, + Gem.ruby, + "-r", + guard, + "-I", + File.join(ROOT, "gems/libtmux/lib"), + "-rlibtmux", + "-e", + "", + chdir: directory + ) assert_equal 2, status.exitstatus assert_includes output, "repository import: #{ROOT}/gems/libtmux/lib/" workspace = File.join(ROOT, "gems/libtmux-workspace/lib") - output, status = Open3.capture2e(environment, Gem.ruby, "-r", guard, "-I", workspace, - "-rlibtmux", "-rlibtmux/workspace/version", "-e", "", chdir: directory) + output, status = + Open3.capture2e( + environment, + Gem.ruby, + "-r", + guard, + "-I", + workspace, + "-rlibtmux", + "-rlibtmux/workspace/version", + "-e", + "", + chdir: directory + ) assert_equal 2, status.exitstatus, output assert_includes output, "repository import: #{workspace}/libtmux/workspace/version.rb" end @@ -126,9 +177,10 @@ def test_installed_example_minimum_does_not_skip_api_refusal_or_other_programs examples = File.join(root, "examples") destination = File.join(root, "run") FileUtils.mkdir_p([examples, destination]) - programs = [ - ["future", {"minimum_tmux" => "3.6"}, 'raise "the ineligible example ran"'], - ["control", {"capabilities" => ["control-mode"]}, <<~'RUBY'], + programs = + [ + ["future", { "minimum_tmux" => "3.6" }, 'raise "the ineligible example ran"'], + ["control", { "capabilities" => ["control-mode"] }, <<~'RUBY'], require "libtmux/errors" File.write("control-ran", "") begin @@ -137,14 +189,25 @@ def test_installed_example_minimum_does_not_skip_api_refusal_or_other_programs abort "#{error.class}: #{error.message}" end RUBY - ["ready", {}, 'File.write("ready-ran", ""); puts "ready"'] - ].map do |id, requirements, source| - File.write(File.join(examples, "#{id}.rb"), source) - {"id" => id, "path" => "examples/#{id}.rb", "gem" => "libtmux", "api" => {"output" => "ready\n", **requirements}} - end - File.write(File.join(examples, "manifest.json"), JSON.generate("version" => 2, "programs" => programs)) + ["ready", {}, 'File.write("ready-ran", ""); puts "ready"'] + ].map do |id, requirements, source| + File.write(File.join(examples, "#{id}.rb"), source) + { + "id" => id, + "path" => "examples/#{id}.rb", + "gem" => "libtmux", + "api" => { + "output" => "ready\n", + **requirements + } + } + end + File.write( + File.join(examples, "manifest.json"), + JSON.generate("version" => 2, "programs" => programs) + ) LibTmuxTest::StubExecutable.write(File.join(root, "tmux"), 'puts "tmux 3.4"') - environment = {"PATH" => "#{root}#{File::PATH_SEPARATOR}#{ENV.fetch('PATH')}"} + environment = { "PATH" => "#{root}#{File::PATH_SEPARATOR}#{ENV.fetch("PATH")}" } _, warnings = capture_io { run_installed_examples("libtmux", environment, destination, root) } assert_match(/future.*requires tmux 3\.6/, warnings) assert File.file?(File.join(destination, "control-ran")), "must still run the API refusal" @@ -158,7 +221,8 @@ def test_installed_job_recipe_requires_tmux_3_6 abort "expected a version query" unless ARGV == ["-V"] puts "tmux 3.4" STUB - _, warnings = capture_io { run_installed_job_recipe({"LIBTMUX_TEST_TMUX" => tmux}, directory) } + _, warnings = + capture_io { run_installed_job_recipe({ "LIBTMUX_TEST_TMUX" => tmux }, directory) } assert_match(/job_resume on tmux 3\.4.*requires tmux 3\.6/, warnings) assert_equal ["tmux"], Dir.children(directory) end @@ -184,12 +248,22 @@ def run_installed_job_recipe(environment, directory, *ruby_options) File.write(input, "Apple\t2\napple\t1\nPear\t4\n") Dir.mktmpdir("libtmux-ruby-recipe-", "/tmp") do |runtime| - invoke = lambda do |*options, **settings| - result = Open3.capture3(environment.merge("TMPDIR" => runtime, **settings), - Gem.ruby, *ruby_options, recipe, input, state, *options, chdir: directory) - assert_empty Dir.children(runtime), "recipe left an owned daemon directory" - result - end + invoke = + lambda do |*options, **settings| + result = + Open3.capture3( + environment.merge("TMPDIR" => runtime, **settings), + Gem.ruby, + *ruby_options, + recipe, + input, + state, + *options, + chdir: directory + ) + assert_empty Dir.children(runtime), "recipe left an owned daemon directory" + result + end output, error, status = invoke.call("--fail-summarize") assert_equal 23, status.exitstatus, output + error assert_includes output, "normalize completed" @@ -197,15 +271,17 @@ def run_installed_job_recipe(environment, directory, *ruby_options) assert_includes error.b, "injected failure in summarize (résumé)".b assert File.file?(normalized) refute File.exist?(summary) - assert_equal ["normalize"], JSON.parse(File.read(checkpoint, encoding: "UTF-8")).fetch("stages").keys + assert_equal ["normalize"], + JSON.parse(File.read(checkpoint, encoding: "UTF-8")).fetch("stages").keys output, error, status = invoke.call assert status.success?, error assert_includes output, "normalize cached" assert_includes output, "summarize completed" - assert_equal({"Apple" => 3, "Pear" => 4}, JSON.parse(File.read(summary, encoding: "UTF-8"))) + assert_equal({ "Apple" => 3, "Pear" => 4 }, JSON.parse(File.read(summary, encoding: "UTF-8"))) - output, error, status = invoke.call("LIBTMUX_TEST_TMUX" => File.join(directory, "never-start-tmux")) + output, error, status = + invoke.call("LIBTMUX_TEST_TMUX" => File.join(directory, "never-start-tmux")) assert status.success?, error assert_includes output, "normalize cached" assert_includes output, "summarize cached" @@ -215,7 +291,7 @@ def run_installed_job_recipe(environment, directory, *ruby_options) assert status.success?, error assert_includes output, "normalize completed" assert_includes output, "summarize completed" - assert_equal({"Apple" => 8, "Pêra" => 1}, JSON.parse(File.read(summary, encoding: "UTF-8"))) + assert_equal({ "Apple" => 8, "Pêra" => 1 }, JSON.parse(File.read(summary, encoding: "UTF-8"))) File.write(normalized, "corrupt artifact") output, error, status = invoke.call @@ -228,7 +304,7 @@ def run_installed_job_recipe(environment, directory, *ruby_options) assert status.success?, error assert_includes output, "normalize completed" assert_includes output, "summarize completed" - assert_equal({"Apple" => 8, "Pêra" => 1}, JSON.parse(File.read(summary, encoding: "UTF-8"))) + assert_equal({ "Apple" => 8, "Pêra" => 1 }, JSON.parse(File.read(summary, encoding: "UTF-8"))) end end @@ -282,9 +358,9 @@ def run_installed_shell_helper(environment, directory) end raise 'helper failed' unless worker.value.success? RUBY - output, status = Open3.capture2e(environment, Gem.ruby, '-W:no-experimental', '-e', source, chdir: directory) + output, status = + Open3.capture2e(environment, Gem.ruby, "-W:no-experimental", "-e", source, chdir: directory) assert status.success?, "installed authored helper closure failed: #{output}" - assert_empty output, 'installed authored helper wrote protocol data outside its socket' + assert_empty output, "installed authored helper wrote protocol data outside its socket" end - end diff --git a/test/packaging/workspace_cli_test.rb b/test/packaging/workspace_cli_test.rb index 61a1948f..d47efb75 100644 --- a/test/packaging/workspace_cli_test.rb +++ b/test/packaging/workspace_cli_test.rb @@ -24,45 +24,108 @@ def test_installed_executable_validates_plans_and_loads_without_repository_impor FileUtils.mkdir_p(File.join(home, "specifications")) local, external = dependency_closure(specs.fetch("libtmux-workspace"), specs) external.each { |spec| copy_dependency(spec, home) } - environment = {"GEM_HOME" => home, "GEM_PATH" => home, "RUBYLIB" => nil, - "RUBYOPT" => nil, "BUNDLE_GEMFILE" => nil, "BUNDLE_BIN_PATH" => nil, - "BUNDLE_LOCKFILE" => nil, "BUNDLER_SETUP" => nil, - "TMUX" => nil, "TMUX_PANE" => nil} + environment = { + "GEM_HOME" => home, + "GEM_PATH" => home, + "RUBYLIB" => nil, + "RUBYOPT" => nil, + "BUNDLE_GEMFILE" => nil, + "BUNDLE_BIN_PATH" => nil, + "BUNDLE_LOCKFILE" => nil, + "BUNDLER_SETUP" => nil, + "TMUX" => nil, + "TMUX_PANE" => nil + } local.each do |spec| artifact = package_artifact(spec, directory, ROOT) - output, status = Open3.capture2e(environment, Gem.ruby, File.join(RbConfig::CONFIG.fetch("bindir"), "gem"), - "install", "--local", "--no-document", artifact, chdir: directory) + output, status = + Open3.capture2e( + environment, + Gem.ruby, + File.join(RbConfig::CONFIG.fetch("bindir"), "gem"), + "install", + "--local", + "--no-document", + artifact, + chdir: directory + ) assert status.success?, "artifact installation failed: #{output}" end executable = File.join(home, "bin", "libtmux-workspace") assert File.file?(executable) ruby = [Gem.ruby, "-r", write_import_check(directory, specs, local)] - output, error, status = Open3.capture3(environment, *ruby, executable, "--version", chdir: directory) + output, error, status = + Open3.capture3(environment, *ruby, executable, "--version", chdir: directory) assert status.success?, "installed version failed: #{error}" - assert_equal "#{specs.fetch('libtmux-workspace').version}\n", output + assert_equal "#{specs.fetch("libtmux-workspace").version}\n", output assert_empty error config = File.join(directory, ".tmuxp.json") - File.write(config, JSON.generate({session_name: "installed", windows: [{window_name: "one", panes: [{}]}]})) + File.write( + config, + JSON.generate({ session_name: "installed", windows: [{ window_name: "one", panes: [{}] }] }) + ) %w[validate plan].each do |command| - output, error, status = Open3.capture3(environment, *ruby, executable, command, "--json", chdir: directory) + output, error, status = + Open3.capture3(environment, *ruby, executable, command, "--json", chdir: directory) assert status.success?, "installed #{command} failed: #{error}" assert_empty error value = JSON.parse(output) - assert_equal(command == "validate" ? true : "offline_create", command == "validate" ? value.fetch("valid") : value.fetch("mode")) + assert_equal( + command == "validate" ? true : "offline_create", + command == "validate" ? value.fetch("valid") : value.fetch("mode") + ) end LibTmuxTest::TmuxFixture.open do |fixture| - output, error, status = Open3.capture3(environment, *ruby, executable, "load", "--json", "--socket", fixture.socket_path, chdir: directory) + output, error, status = + Open3.capture3( + environment, + *ruby, + executable, + "load", + "--json", + "--socket", + fixture.socket_path, + chdir: directory + ) assert status.success?, "installed load failed: #{output} #{error}" assert_empty error value = JSON.parse(output) assert_equal true, value.fetch("success") assert_equal 3, value.fetch("created_refs").length - assert_equal ["fixture", "installed"], fixture.tmux("list-sessions", "-F", '#{session_name}').first.lines.map(&:chomp).sort + assert_equal %w[fixture installed], + fixture + .tmux("list-sessions", "-F", '#{session_name}') + .first + .lines + .map(&:chomp) + .sort assert_empty fixture.tmux("list-clients").first - File.write(config, JSON.generate({session_name: "missing-directory", - windows: [{window_name: "one", panes: [{}, {start_directory: "private-missing-directory"}]}]})) - output, error, status = Open3.capture3(environment, Gem.ruby, executable, "load", "--json", "--socket", fixture.socket_path, chdir: directory) + File.write( + config, + JSON.generate( + { + session_name: "missing-directory", + windows: [ + { + window_name: "one", + panes: [{}, { start_directory: "private-missing-directory" }] + } + ] + } + ) + ) + output, error, status = + Open3.capture3( + environment, + Gem.ruby, + executable, + "load", + "--json", + "--socket", + fixture.socket_path, + chdir: directory + ) assert_equal 1, status.exitstatus, error assert_empty error report = JSON.parse(output) @@ -74,10 +137,23 @@ def test_installed_executable_validates_plans_and_loads_without_repository_impor assert_nil report.dig("result", "failed_step") assert_empty report.dig("result", "effects") refute_includes output, "private-missing-directory" - assert_equal ["fixture", "installed"], fixture.tmux("list-sessions", "-F", '#{session_name}').first.lines.map(&:chomp).sort + assert_equal %w[fixture installed], + fixture + .tmux("list-sessions", "-F", '#{session_name}') + .first + .lines + .map(&:chomp) + .sort native_id = value.fetch("created_refs").fetch("session").fetch("id") - check_installed_attachment(fixture, config, [Gem.ruby, executable], environment, directory, native_id) + check_installed_attachment( + fixture, + config, + [Gem.ruby, executable], + environment, + directory, + native_id + ) end source = <<~'RUBY' require "libtmux/workspace/cli" @@ -105,30 +181,50 @@ def check_installed_attachment(fixture, config, command, environment, directory, assert_equal 0, read_terminal_exit(output, pid).last end - File.write(config, JSON.generate({session_name: "installed-attach", windows: [{window_name: "one", panes: [{}]}]})) + File.write( + config, + JSON.generate( + { session_name: "installed-attach", windows: [{ window_name: "one", panes: [{}] }] } + ) + ) load = [*command, "load", "--attach", "--json", "--socket", socket] - id = with_controlling_terminal(load, environment: environment, chdir: directory) do |output, input, pid| - wait_for_terminal_draw(output, marker) - drawn_id = fixture.tmux("list-clients", "-F", '#{session_id}').first.chomp - assert_equal "installed-attach", fixture.tmux("list-clients", "-F", '#{session_name}').first.chomp - input.write("\x02d") - display, status = read_terminal_exit(output, pid) - assert_equal 0, status, display - ledger = JSON.parse(display.lines.last) - assert_equal true, ledger.fetch("success") - assert_equal drawn_id, ledger.fetch("created_refs").fetch("session").fetch("id") - drawn_id - end + id = + with_controlling_terminal( + load, + environment: environment, + chdir: directory + ) do |output, input, pid| + wait_for_terminal_draw(output, marker) + drawn_id = fixture.tmux("list-clients", "-F", '#{session_id}').first.chomp + assert_equal "installed-attach", + fixture.tmux("list-clients", "-F", '#{session_name}').first.chomp + input.write("\x02d") + display, status = read_terminal_exit(output, pid) + assert_equal 0, status, display + ledger = JSON.parse(display.lines.last) + assert_equal true, ledger.fetch("success") + assert_equal drawn_id, ledger.fetch("created_refs").fetch("session").fetch("id") + drawn_id + end attach = [*command, "attach", "--socket", socket, id] - with_controlling_terminal(attach, environment: environment, chdir: directory) do |output, input, pid| + with_controlling_terminal( + attach, + environment: environment, + chdir: directory + ) do |output, input, pid| wait_for_terminal_draw(output, marker) assert_equal id, fixture.tmux("list-clients", "-F", '#{session_id}').first.chomp input.write("\x02d") assert_equal 0, read_terminal_exit(output, pid).last end - assert_equal ["fixture", "installed", "installed-attach"], - fixture.tmux("list-sessions", "-F", '#{session_name}').first.lines.map(&:chomp).sort + assert_equal %w[fixture installed installed-attach], + fixture + .tmux("list-sessions", "-F", '#{session_name}') + .first + .lines + .map(&:chomp) + .sort assert_empty fixture.tmux("list-clients").first end end diff --git a/test/support/control_assertions.rb b/test/support/control_assertions.rb index 2f6d032c..c2c8bac8 100644 --- a/test/support/control_assertions.rb +++ b/test/support/control_assertions.rb @@ -9,16 +9,18 @@ def assert_run_shell_routing(control, version) release = LibTmux::Internal::TmuxVersion.parse(version) if release < LibTmux::Internal::TmuxVersion.parse("3.5") # These releases put run-shell output in pane view mode. - copy_view = "send-keys -X history-top ; send-keys -X begin-selection ; " \ - "send-keys -X history-bottom ; send-keys -X end-of-line ; " \ - "send-keys -X copy-selection-and-cancel ; show-buffer" + copy_view = + "send-keys -X history-top ; send-keys -X begin-selection ; " \ + "send-keys -X history-bottom ; send-keys -X end-of-line ; " \ + "send-keys -X copy-selection-and-cancel ; show-buffer" output = control.exchange(copy_view, timeout: 0.5).blocks.map(&:body).join assert_includes output, "outside-reply" assert_includes output, "returned 17" control.exchange(%q{run-shell 'printf "%%end 1 1 1\n"'}, timeout: 0.5) output = control.exchange(copy_view, timeout: 0.5).blocks.map(&:body).join assert_includes output, "%end 1 1 1" - assert_equal "alive\n", control.exchange("display-message -p alive", timeout: 0.5).blocks.last.body + assert_equal "alive\n", + control.exchange("display-message -p alive", timeout: 0.5).blocks.last.body else observed = [] loop do @@ -27,9 +29,10 @@ def assert_run_shell_routing(control, version) break if event.raw.include?("returned 17") end assert_includes observed.join, "outside-reply" - error = assert_raises(LibTmux::ProtocolError) do - control.exchange(%q{run-shell 'printf "%%end 1 1 1\n"'}, timeout: 0.5) - end + error = + assert_raises(LibTmux::ProtocolError) do + control.exchange(%q{run-shell 'printf "%%end 1 1 1\n"'}, timeout: 0.5) + end assert_equal :possibly_sent, error.delivery assert_raises(LibTmux::ClosedError) { control.exchange("display-message -p later") } end diff --git a/test/support/control_support.rb b/test/support/control_support.rb index 716cb8aa..a55e6c9b 100644 --- a/test/support/control_support.rb +++ b/test/support/control_support.rb @@ -14,8 +14,11 @@ def require_control_support(server, session = nil) return true if control_supported?(server) session ||= server.list_sessions.first - error = assert_raises(LibTmux::UnsupportedFeatureError) { server.open_control(session: session.ref) } - assert_equal [:not_sent, :admission], [error.delivery, error.phase] + error = + assert_raises(LibTmux::UnsupportedFeatureError) do + server.open_control(session: session.ref) + end + assert_equal %i[not_sent admission], [error.delivery, error.phase] assert_match(/control connections require tmux 3\.7 or newer/, error.message) assert_empty server.list_clients false @@ -24,15 +27,17 @@ def require_control_support(server, session = nil) # The same check for a binding that no server checked, which probes the # daemon itself. def require_control_binding(pin) - release = LibTmux::Internal::TmuxVersion.connected(pin.command_prefix) do |argv| - LibTmux::Internal::ProcessExecutor.new.run(argv, timeout: 5.0) - end + release = + LibTmux::Internal::TmuxVersion.connected(pin.command_prefix) do |argv| + LibTmux::Internal::ProcessExecutor.new.run(argv, timeout: 5.0) + end return true if (release <=> LibTmux::Internal::TmuxVersion.parse("3.7")) >= 0 - error = assert_raises(LibTmux::UnsupportedFeatureError) do - LibTmux::ControlConnection.__send__(:new, binding: pin, session_id: "$0") - end - assert_equal [:not_sent, :admission], [error.delivery, error.phase] + error = + assert_raises(LibTmux::UnsupportedFeatureError) do + LibTmux::ControlConnection.__send__(:new, binding: pin, session_id: "$0") + end + assert_equal %i[not_sent admission], [error.delivery, error.phase] false end end diff --git a/test/support/controlling_terminal.rb b/test/support/controlling_terminal.rb index 4785e312..9dc8ed8f 100644 --- a/test/support/controlling_terminal.rb +++ b/test/support/controlling_terminal.rb @@ -27,9 +27,7 @@ def with_controlling_terminal(command, environment: {}, **options) def wait_for_terminal_draw(output, marker) display = +"".b - Timeout.timeout(5) do - display << output.readpartial(4096) until display.include?(marker) - end + Timeout.timeout(5) { display << output.readpartial(4096) until display.include?(marker) } rescue EOFError, Errno::EIO flunk "Terminal closed before drawing #{marker.inspect}: #{display.inspect}" rescue Timeout::Error diff --git a/test/support/installed_gems.rb b/test/support/installed_gems.rb index 01c373d4..3aeb0e8e 100644 --- a/test/support/installed_gems.rb +++ b/test/support/installed_gems.rb @@ -24,13 +24,16 @@ def write_import_check(directory, specs, local) suffixes = [] allowed = [] specs.each_value do |spec| - spec.lib_files.grep(/\.rb\z/).each do |file| - root = spec.require_paths.find { |path| file.start_with?(path + "/") } - next unless root - - suffixes << file.delete_prefix(root) - allowed << File.join("gems", spec.full_name, file) if local.include?(spec) - end + spec + .lib_files + .grep(/\.rb\z/) + .each do |file| + root = spec.require_paths.find { |path| file.start_with?(path + "/") } + next unless root + + suffixes << file.delete_prefix(root) + allowed << File.join("gems", spec.full_name, file) if local.include?(spec) + end end guard = File.join(directory, "check_installed_imports.rb") File.write(guard, <<~RUBY) @@ -53,21 +56,32 @@ def package_artifact(spec, directory, root) if ENV["LIBTMUX_RELEASE_DIR"] require "json" release = File.expand_path(ENV.fetch("LIBTMUX_RELEASE_DIR"), root) - raise "release artifacts must be in pkg/release" unless release == File.join(root, "pkg/release") + unless release == File.join(root, "pkg/release") + raise "release artifacts must be in pkg/release" + end unless @release_manifest load File.join(root, "scripts/release/release.rb") unless defined?(GemRelease) identity = JSON.parse(File.read(File.join(release, "release.json"))) - @release_manifest = GemRelease.new(root).verify(tag: identity.fetch("tag"), commit: identity.fetch("commit")) + @release_manifest = + GemRelease.new(root).verify( + tag: identity.fetch("tag"), + commit: identity.fetch("commit") + ) + end + artifact = + @release_manifest.fetch("artifacts").find { |entry| entry.fetch("name") == spec.name } + unless artifact.fetch("version") == spec.version.to_s + raise "release version differs from checkout" end - artifact = @release_manifest.fetch("artifacts").find { |entry| entry.fetch("name") == spec.name } - raise "release version differs from checkout" unless artifact.fetch("version") == spec.version.to_s return File.join(release, artifact.fetch("filename")) end artifact = File.join(directory, "#{spec.full_name}.gem") - Dir.chdir(File.join(root, "gems", spec.name)) { Gem::Package.build(spec, false, true, artifact) } + Dir.chdir(File.join(root, "gems", spec.name)) do + Gem::Package.build(spec, false, true, artifact) + end artifact end @@ -76,37 +90,56 @@ def run_installed_examples(package, environment, directory, root, *ruby_options) destination = File.join(directory, "examples") FileUtils.cp_r(File.join(root, "examples"), destination) unless File.directory?(destination) release = nil - manifest.data.fetch("programs").select { |entry| entry.fetch("gem") == package }.each do |entry| - declared = entry.dig("api", "capabilities").to_a - if !declared.empty? || entry.dig("api", "minimum_tmux") - release ||= ExampleManifest.executable_release("tmux", environment) - end - unavailable = declared.map { |id| LibTmux::Internal::Capabilities.capability(id) } - .reject { |capability| capability.available?(release) } - if unavailable.empty? && (minimum = manifest.unmet_example_minimum(entry, release)) - warn "Omitted installed example #{entry.fetch('id')} on tmux #{release.text}. It requires tmux #{minimum} or newer." - next - end - output, status = Open3.capture2e(environment.merge("LIBTMUX_EXAMPLE_INSTALLED" => "1"), - Gem.ruby, *ruby_options, "-W:no-experimental", File.join(directory, entry.fetch("path")), chdir: directory) - unless unavailable.empty? - # The program must reach the library's typed refusal. - assert_equal 1, status.exitstatus, "expected feature refusal in #{entry.fetch('id')}: #{output}" - assert_match(/LibTmux::UnsupportedFeatureError: /, output) - next + manifest + .data + .fetch("programs") + .select { |entry| entry.fetch("gem") == package } + .each do |entry| + declared = entry.dig("api", "capabilities").to_a + if !declared.empty? || entry.dig("api", "minimum_tmux") + release ||= ExampleManifest.executable_release("tmux", environment) + end + unavailable = + declared + .map { |id| LibTmux::Internal::Capabilities.capability(id) } + .reject { |capability| capability.available?(release) } + if unavailable.empty? && (minimum = manifest.unmet_example_minimum(entry, release)) + warn "Omitted installed example #{entry.fetch("id")} on tmux #{release.text}. It requires tmux #{minimum} or newer." + next + end + output, status = + Open3.capture2e( + environment.merge("LIBTMUX_EXAMPLE_INSTALLED" => "1"), + Gem.ruby, + *ruby_options, + "-W:no-experimental", + File.join(directory, entry.fetch("path")), + chdir: directory + ) + unless unavailable.empty? + # The program must reach the library's typed refusal. + assert_equal 1, + status.exitstatus, + "expected feature refusal in #{entry.fetch("id")}: #{output}" + assert_match(/LibTmux::UnsupportedFeatureError: /, output) + next + end + assert status.success?, "installed example #{entry.fetch("id")} failed: #{output}" + expected = entry["output"] || entry.dig("api", "output") || "PASS #{entry.fetch("id")}\n" + assert_equal expected.b, output.b end - assert status.success?, "installed example #{entry.fetch('id')} failed: #{output}" - expected = entry["output"] || entry.dig("api", "output") || "PASS #{entry.fetch('id')}\n" - assert_equal expected.b, output.b - end end def run_installed_recipe_blocks(package, environment, *ruby_options) root = File.expand_path("../..", __dir__) manifest = ExampleManifest.new(root).data - sources = manifest.fetch("snippets").to_h { |entry| [entry.fetch("id"), entry.fetch("source")] } + sources = + manifest.fetch("snippets").to_h { |entry| [entry.fetch("id"), entry.fetch("source")] } programs = manifest.fetch("programs").to_h { |entry| [entry.fetch("path"), entry] } - blocks = File.read(File.join(root, "docs/recipes.md"), encoding: "UTF-8").scan(/^\n```ruby\n(.*?)^```\n/m) + blocks = + File.read(File.join(root, "docs/recipes.md"), encoding: "UTF-8").scan( + %r{^\n```ruby\n(.*?)^```\n}m + ) refute_empty blocks blocks.each do |id, source| entry = programs.fetch(sources.fetch(id)) @@ -115,7 +148,15 @@ def run_installed_recipe_blocks(package, environment, *ruby_options) Dir.mktmpdir("libtmux-ruby-recipe-") do |directory| file = File.join(directory, "recipe.rb") File.binwrite(file, source) - output, status = Open3.capture2e(environment, Gem.ruby, *ruby_options, "-W:no-experimental", file, chdir: directory) + output, status = + Open3.capture2e( + environment, + Gem.ruby, + *ruby_options, + "-W:no-experimental", + file, + chdir: directory + ) assert status.success?, "copied recipe #{id} failed: #{output}" expected = entry["output"] || entry.dig("api", "output") assert_equal expected.b, output.b, id if expected @@ -129,31 +170,45 @@ def run_installed_type_consumer(package, environment, directory, guard) _local, dependencies = dependency_closure(Gem::Specification.find_by_name("rbs"), {}) dependencies.each { |spec| copy_dependency(spec, environment.fetch("GEM_HOME")) } consumer = File.join(directory, "type_consumer.rb") - FileUtils.cp(File.expand_path("../types/consumer.rb", __dir__), consumer) unless File.file?(consumer) - output, status = Open3.capture2e(environment, - Gem.ruby, "-r", guard, "-W:no-experimental", consumer, package, chdir: directory) + unless File.file?(consumer) + FileUtils.cp(File.expand_path("../types/consumer.rb", __dir__), consumer) + end + output, status = + Open3.capture2e( + environment, + Gem.ruby, + "-r", + guard, + "-W:no-experimental", + consumer, + package, + chdir: directory + ) assert status.success?, "installed signature consumer #{package} failed: #{output}" report = JSON.parse(output) assert_equal package, report.fetch("package") refute_empty report.fetch("exercised") assert_equal false, report.fetch("whole_program_static_check") - puts "Signature consumer #{package}: #{report.fetch('exercised').join(', ')}" + puts "Signature consumer #{package}: #{report.fetch("exercised").join(", ")}" end def dependency_closure(root, local_specs) ordered = [] visited = {} - visit = lambda do |spec| - return if visited[spec.name] - - visited[spec.name] = true - spec.runtime_dependencies.each do |dependency| - child = local_specs[dependency.name] || Gem::Specification.find_by_name(dependency.name, dependency.requirement) - assert dependency.matches_spec?(child), "unsatisfied #{dependency} for #{spec.name}" - visit.call(child) + visit = + lambda do |spec| + return if visited[spec.name] + + visited[spec.name] = true + spec.runtime_dependencies.each do |dependency| + child = + local_specs[dependency.name] || + Gem::Specification.find_by_name(dependency.name, dependency.requirement) + assert dependency.matches_spec?(child), "unsatisfied #{dependency} for #{spec.name}" + visit.call(child) + end + ordered << spec end - ordered << spec - end visit.call(root) ordered.partition { |spec| local_specs.key?(spec.name) } end diff --git a/test/support/ivar_reach.rb b/test/support/ivar_reach.rb index 4143bfb4..e595ba22 100644 --- a/test/support/ivar_reach.rb +++ b/test/support/ivar_reach.rb @@ -20,13 +20,25 @@ class IvarReach ATTR = %i[attr_reader attr_accessor].freeze SENDERS = %i[__send__ send public_send].freeze # `@x += 1` is left out: it reads @x first and fails while @x is unset. - WRITES = [Prism::InstanceVariableWriteNode, Prism::InstanceVariableTargetNode, Prism::InstanceVariableOrWriteNode, - Prism::InstanceVariableAndWriteNode].freeze - READS = [Prism::InstanceVariableReadNode, Prism::InstanceVariableAndWriteNode, Prism::InstanceVariableOperatorWriteNode].freeze + WRITES = [ + Prism::InstanceVariableWriteNode, + Prism::InstanceVariableTargetNode, + Prism::InstanceVariableOrWriteNode, + Prism::InstanceVariableAndWriteNode + ].freeze + READS = [ + Prism::InstanceVariableReadNode, + Prism::InstanceVariableAndWriteNode, + Prism::InstanceVariableOperatorWriteNode + ].freeze # Calls that block the calling thread or start a process outside the # scheduler-owned executor. - BLOCKING_CALLS = {Process: %i[spawn fork exec wait waitpid wait2 waitall detach], IO: %i[popen select], - Thread: %i[new start fork], Kernel: %i[spawn system fork exec]}.freeze + BLOCKING_CALLS = { + Process: %i[spawn fork exec wait waitpid wait2 waitall detach], + IO: %i[popen select], + Thread: %i[new start fork], + Kernel: %i[spawn system fork exec] + }.freeze BLOCKING_SELF_CALLS = %i[spawn system fork exec].freeze CLASS_BUILDERS = %w[new open start allocate].freeze BLOCKING_CONSTANTS = %i[ProcessExecutor Open3 PTY].freeze @@ -75,16 +87,23 @@ def walk(name, only_core:, owner: nil, path: []) def facade_writes walk(:initialize, only_core: false) owners = [@klass] - owners.concat(@klass.ancestors.drop(1).select { |mod| core?(mod) }) if @seen.include?(@klass.superclass.instance_method(:initialize)) + if @seen.include?(@klass.superclass.instance_method(:initialize)) + owners.concat(@klass.ancestors.drop(1).select { |mod| core?(mod) }) + end owners.each do |owner| (owner.instance_methods(false) + owner.private_instance_methods(false)).each do |name| node = definition(owner.instance_method(name)) - each_node(node) { |child| @writes << child.name if WRITES.any? { |kind| child.is_a?(kind) } } if node.is_a?(Prism::Node) + if node.is_a?(Prism::Node) + each_node(node) do |child| + @writes << child.name if WRITES.any? { |kind| child.is_a?(kind) } + end + end end end file = @klass.instance_method(:initialize).source_location.first each_node(parse(file)) do |child| - symbol = child.arguments&.arguments&.first if child.is_a?(Prism::CallNode) && child.name == :instance_variable_set + symbol = child.arguments&.arguments&.first if child.is_a?(Prism::CallNode) && + child.name == :instance_variable_set @writes << symbol.unescaped.to_sym if symbol.is_a?(Prism::SymbolNode) end @writes @@ -99,7 +118,8 @@ def each_node(node, &block) node.compact_child_nodes.each { |child| each_node(child, &block) } end - def core?(mod) = mod.name.to_s.start_with?("LibTmux::") && !mod.name.start_with?("LibTmux::Async::") + def core?(mod) = + mod.name.to_s.start_with?("LibTmux::") && !mod.name.start_with?("LibTmux::Async::") # LibTmux code, or an anonymous class or module (as in this helper's own tests). def libtmux?(mod) = mod.name.nil? || mod.name.start_with?("LibTmux") @@ -110,13 +130,21 @@ def definition(method) return unless file && File.file?(file) tree = parse(file) - find(tree) { |n| n.is_a?(Prism::DefNode) && n.location.start_line == line && n.name == method.original_name } || - attr_ivar(tree, method, line) + find(tree) do |n| + n.is_a?(Prism::DefNode) && n.location.start_line == line && n.name == method.original_name + end || attr_ivar(tree, method, line) end def attr_ivar(tree, method, line) - call = find(tree) { |n| n.is_a?(Prism::CallNode) && ATTR.include?(n.name) && n.location.start_line == line } - :"@#{method.original_name}" if call&.arguments&.arguments&.any? { |a| a.respond_to?(:unescaped) && a.unescaped.to_sym == method.original_name } + call = + find(tree) do |n| + n.is_a?(Prism::CallNode) && ATTR.include?(n.name) && n.location.start_line == line + end + if call&.arguments&.arguments&.any? { |a| + a.respond_to?(:unescaped) && a.unescaped.to_sym == method.original_name + } + :"@#{method.original_name}" + end end def find(node, &block) @@ -135,9 +163,13 @@ def guarded_ivars(node) guarded << child.name if WRITES.any? { |kind| child.is_a?(kind) } case child when Prism::DefinedNode - each_node(child) { |inner| guarded << inner.name if inner.is_a?(Prism::InstanceVariableReadNode) } + each_node(child) do |inner| + guarded << inner.name if inner.is_a?(Prism::InstanceVariableReadNode) + end when Prism::CallNode - guarded << child.receiver.name if child.safe_navigation? && child.receiver.is_a?(Prism::InstanceVariableReadNode) + if child.safe_navigation? && child.receiver.is_a?(Prism::InstanceVariableReadNode) + guarded << child.receiver.name + end argument = child.arguments&.arguments&.first if child.name == :instance_variable_defined? && argument.is_a?(Prism::SymbolNode) guarded << argument.unescaped.to_sym @@ -148,18 +180,27 @@ def guarded_ivars(node) end def visit(node, home, method_name, only_core, path) - if READS.any? { |kind| node.is_a?(kind) } && !@guarded.include?(node.name) && !@handed.include?(node.object_id) + if READS.any? { |kind| node.is_a?(kind) } && !@guarded.include?(node.name) && + !@handed.include?(node.object_id) @reads[node.name] ||= path end @writes << node.name if WRITES.any? { |kind| node.is_a?(kind) } case node - when Prism::CallNode then call(node, only_core, path) + when Prism::CallNode + call(node, only_core, path) when Prism::ConstantReadNode, Prism::ConstantPathNode @hazards["calls #{node.name}"] ||= path if BLOCKING_CONSTANTS.include?(node.name) - when Prism::XStringNode, Prism::InterpolatedXStringNode then @hazards["runs a backtick command"] ||= path + when Prism::XStringNode, Prism::InterpolatedXStringNode + @hazards["runs a backtick command"] ||= path when Prism::SuperNode, Prism::ForwardingSuperNode - parent = @klass.ancestors.drop_while { |a| a != home }.drop(1) - .find { |a| a.method_defined?(method_name, false) || a.private_method_defined?(method_name, false) } + parent = + @klass + .ancestors + .drop_while { |a| a != home } + .drop(1) + .find do |a| + a.method_defined?(method_name, false) || a.private_method_defined?(method_name, false) + end walk(method_name, only_core: only_core, owner: parent, path: path) if parent end node.compact_child_nodes.each { |child| visit(child, home, method_name, only_core, path) } @@ -167,7 +208,8 @@ def visit(node, home, method_name, only_core, path) def call(node, only_core, path) receiver = node.receiver - constant = receiver.name if receiver.is_a?(Prism::ConstantReadNode) || receiver.is_a?(Prism::ConstantPathNode) + constant = receiver.name if receiver.is_a?(Prism::ConstantReadNode) || + receiver.is_a?(Prism::ConstantPathNode) if constant && BLOCKING_CALLS.fetch(constant, []).include?(node.name) @hazards["calls #{constant}.#{node.name}"] ||= path elsif self_receiver?(node) && BLOCKING_SELF_CALLS.include?(node.name) @@ -178,11 +220,15 @@ def call(node, only_core, path) return unless self_receiver?(node) if overridden?(node.name) - node.arguments&.arguments&.each { |argument| @handed << argument.object_id if argument.is_a?(Prism::InstanceVariableReadNode) } + node.arguments&.arguments&.each do |argument| + @handed << argument.object_id if argument.is_a?(Prism::InstanceVariableReadNode) + end end if SENDERS.include?(node.name) target = node.arguments&.arguments&.first - walk(target.unescaped.to_sym, only_core: only_core, path: path) if target.is_a?(Prism::SymbolNode) + if target.is_a?(Prism::SymbolNode) + walk(target.unescaped.to_sym, only_core: only_core, path: path) + end else walk(node.name, only_core: only_core, path: path) end @@ -204,11 +250,16 @@ def overridden?(name) # constructor. Returns the builder name, or nil. def class_builder(node) receiver = node.receiver - return unless receiver.is_a?(Prism::CallNode) && receiver.name == :class && self_receiver?(receiver) + unless receiver.is_a?(Prism::CallNode) && receiver.name == :class && self_receiver?(receiver) + return + end return node.name.to_s if CLASS_BUILDERS.include?(node.name.to_s) target = node.arguments&.arguments&.first - target.unescaped if SENDERS.include?(node.name) && target.is_a?(Prism::SymbolNode) && CLASS_BUILDERS.include?(target.unescaped) + if SENDERS.include?(node.name) && target.is_a?(Prism::SymbolNode) && + CLASS_BUILDERS.include?(target.unescaped) + target.unescaped + end end end end diff --git a/test/support/process_cursor_support.rb b/test/support/process_cursor_support.rb index c6b0c441..034f3520 100644 --- a/test/support/process_cursor_support.rb +++ b/test/support/process_cursor_support.rb @@ -7,15 +7,20 @@ def require_process_cursor_support(scope) snapshot = scope.server.snapshot failure = lease = nil begin - lease = LibTmux::MCP.const_get(:ProcessIdentity).acquire(scope.server, - server_pid: snapshot.server_info.fetch(:pid), pane_pid: snapshot.panes.first.pid, - budget: scope.server.__send__(:operation_budget, 0.5, nil)) + lease = + LibTmux::MCP.const_get(:ProcessIdentity).acquire( + scope.server, + server_pid: snapshot.server_info.fetch(:pid), + pane_pid: snapshot.panes.first.pid, + budget: scope.server.__send__(:operation_budget, 0.5, nil) + ) rescue LibTmux::Error => error failure = error ensure lease&.close end - assert_nil failure, "Darwin process identity is required: #{failure&.class}: #{failure&.message}" + assert_nil failure, + "Darwin process identity is required: #{failure&.class}: #{failure&.message}" return true end failure = nil @@ -29,7 +34,8 @@ def require_process_cursor_support(scope) ensure [namespace, peer, *sockets].compact.each { |io| io.close unless io.closed? } end - assert_nil failure, "Linux process identity is required: #{failure&.class}: #{failure&.message}" + assert_nil failure, + "Linux process identity is required: #{failure&.class}: #{failure&.message}" true end end diff --git a/test/support/readme_blocks.rb b/test/support/readme_blocks.rb index f7fe6c65..5bcbde96 100644 --- a/test/support/readme_blocks.rb +++ b/test/support/readme_blocks.rb @@ -24,19 +24,21 @@ def read(path) def fences(markdown) found = [] open = nil - markdown.each_line.with_index(1) do |text, number| - line = text.chomp - if open - if line.match?(/\A```\s*\z/) - found << open - open = nil - else - open.lines << line + markdown + .each_line + .with_index(1) do |text, number| + line = text.chomp + if open + if line.match?(/\A```\s*\z/) + found << open + open = nil + else + open.lines << line + end + elsif (match = line.match(/\A```(\S*)\s*\z/)) + open = Fence.new(match[1], [], number) end - elsif (match = line.match(/\A```(\S*)\s*\z/)) - open = Fence.new(match[1], [], number) end - end raise ArgumentError, "unterminated code fence opened at line #{open.line}" if open found @@ -64,7 +66,8 @@ def command(fence) elsif line.start_with?("$ ") && words.empty? words << line.delete_prefix("$ ") else - raise ArgumentError, "console block at line #{fence.line} holds more than one command or its output" + raise ArgumentError, + "console block at line #{fence.line} holds more than one command or its output" end continued = line.end_with?("\\") words[-1] = words[-1].delete_suffix("\\").strip if continued @@ -100,27 +103,33 @@ def tool_link_problems(markdown, path, tools:) definitions = reference_definitions(markdown) linked = /\[`(tmux_[a-z_]+)`\](?:\(([^)]*)\)|\[([^\]]*)\])/ problems = [] - markdown.each_line.with_index(1) do |line, number| - line.scan(linked) do |name, target, label| - if label - target = definitions[label] - unless target - problems << "#{path}:#{number}: #{name} uses the undefined link label #{label}" - next + markdown + .each_line + .with_index(1) do |line, number| + line.scan(linked) do |name, target, label| + if label + target = definitions[label] + unless target + problems << "#{path}:#{number}: #{name} uses the undefined link label #{label}" + next + end end - end - expected = "#{TOOL_PAGES}/#{name}/" - next unless tools.include?(name) || target.start_with?("#{TOOL_PAGES}/") + expected = "#{TOOL_PAGES}/#{name}/" + next unless tools.include?(name) || target.start_with?("#{TOOL_PAGES}/") - problems << "#{path}:#{number}: #{name} links to #{target}, not #{expected}" unless target == expected - end - next unless line.match?(/\A\s*(?:\||[-*] |\d+\. )/) + unless target == expected + problems << "#{path}:#{number}: #{name} links to #{target}, not #{expected}" + end + end + next unless line.match?(/\A\s*(?:\||[-*] |\d+\. )/) - stripped = line.gsub(linked, "") - stripped.scan(/`(tmux_[a-z_]+)`/) do |(name)| - problems << "#{path}:#{number}: #{name} is not linked to its tool page" if tools.include?(name) + stripped = line.gsub(linked, "") + stripped.scan(/`(tmux_[a-z_]+)`/) do |(name)| + if tools.include?(name) + problems << "#{path}:#{number}: #{name} is not linked to its tool page" + end + end end - end problems end @@ -147,20 +156,27 @@ def reference_link_problems(markdown, path) # The id a heading gets, as scripts/docs and GitHub compute it. def heading_anchors(markdown) seen = Hash.new(0) - without_fences(markdown).lines.grep(/\A\#{1,6} /).map do |line| - text = line.sub(/\A\#+ /, "").strip - text = text.gsub(/\[([^\]]*)\](?:\([^)]*\)|\[[^\]]*\])/, '\1').delete("`") - id = text.downcase.gsub(/[^\p{Alnum}_\- ]/, "").tr(" ", "-") - count = seen[id] - seen[id] += 1 - count.zero? ? id : "#{id}-#{count}" - end + without_fences(markdown) + .lines + .grep(/\A\#{1,6} /) + .map do |line| + text = line.sub(/\A\#+ /, "").strip + text = text.gsub(/\[([^\]]*)\](?:\([^)]*\)|\[[^\]]*\])/, '\1').delete("`") + id = text.downcase.gsub(/[^\p{Alnum}_\- ]/, "").tr(" ", "-") + count = seen[id] + seen[id] += 1 + count.zero? ? id : "#{id}-#{count}" + end end # Each `](#anchor)` in the page lands on one of its headings. def anchor_problems(markdown, path) anchors = heading_anchors(markdown) - without_fences(markdown).scan(/\]\(#([^)]+)\)/).flatten.uniq.reject { |anchor| anchors.include?(anchor) } + without_fences(markdown) + .scan(/\]\(#([^)]+)\)/) + .flatten + .uniq + .reject { |anchor| anchors.include?(anchor) } .map { |anchor| "#{path}: no heading has the anchor ##{anchor}" } end @@ -168,11 +184,12 @@ def anchor_problems(markdown, path) # program's own README names in code, is one the executable prints. def flag_problems(markdown, path, program:, help:, prose: false) known = help.scan(/(? "libtmux", "libtmux-async" => "libtmux/async", "libtmux-mcp" => "libtmux/mcp", - "libtmux-workspace" => "libtmux/workspace"}.freeze + REQUIRES = { + "libtmux" => "libtmux", + "libtmux-async" => "libtmux/async", + "libtmux-mcp" => "libtmux/mcp", + "libtmux-workspace" => "libtmux/workspace" + }.freeze def gem_index_problems(markdown, path, gems:, link:) header = "| Gem | Require | Use it for |" - return ["#{path}: no #{header} index"] unless markdown.lines.any? { |line| line.chomp == header } + unless markdown.lines.any? { |line| line.chomp == header } + return ["#{path}: no #{header} index"] + end gems.filter_map do |name| row = markdown.lines.find { |line| line.start_with?("| #{format(link, name, name)} |") } next "#{path}: the index has no row for #{name}" unless row - "#{path}: the #{name} row does not give its require path" unless row.include?("| `#{REQUIRES.fetch(name)}` |") + unless row.include?("| `#{REQUIRES.fetch(name)}` |") + "#{path}: the #{name} row does not give its require path" + end end end @@ -223,7 +252,8 @@ def fence_link_problems(markdown, path) # follow the link with a colon and the gem's job in plain words. def gem_heading_problems(markdown, path, gems:) gems.filter_map do |name| - heading = /^#+ \[#{Regexp.escape(name)}\]\(#{Regexp.escape("#{GEM_TREE}/#{name}")}\)(?::\s\S.*)?\s*$/ + heading = + /^#+ \[#{Regexp.escape(name)}\]\(#{Regexp.escape("#{GEM_TREE}/#{name}")}\)(?::\s\S.*)?\s*$/ "#{path}: no heading links #{name} to #{GEM_TREE}/#{name}" unless markdown.match?(heading) end end diff --git a/test/support/replay.rb b/test/support/replay.rb index 8688f099..c5663eb7 100644 --- a/test/support/replay.rb +++ b/test/support/replay.rb @@ -26,8 +26,22 @@ def report file = file.delete_prefix("#{Dir.pwd}/") name = Regexp.escape("#{result.class_name}##{result.name}") tmux = ENV.fetch("LIBTMUX_TEST_TMUX", "tmux") - command = ["env", "-u", Sandbox::MARKER, "LIBTMUX_TEST_TMUX=#{tmux}", Gem.ruby, "-rbundler/setup", - "-Itest", "-rsupport/sandbox", "--", file, "--seed", options.fetch(:seed).to_s, "--name", "/\\A#{name}\\z/"] + command = [ + "env", + "-u", + Sandbox::MARKER, + "LIBTMUX_TEST_TMUX=#{tmux}", + Gem.ruby, + "-rbundler/setup", + "-Itest", + "-rsupport/sandbox", + "--", + file, + "--seed", + options.fetch(:seed).to_s, + "--name", + "/\\A#{name}\\z/" + ] io.puts("Replay: #{Shellwords.join(command)}") end end diff --git a/test/support/sandbox.rb b/test/support/sandbox.rb index 4c3ad172..b14fff49 100644 --- a/test/support/sandbox.rb +++ b/test/support/sandbox.rb @@ -11,7 +11,8 @@ module LibTmuxTest # of this run's own, and exits if either did not hold. A process started by # one that has entered joins its sandbox instead of making another. module Sandbox - class Refused < StandardError; end + class Refused < StandardError + end MARKER = "LIBTMUX_TEST_SANDBOX" PREFIX = "lt-rb-" @@ -27,18 +28,19 @@ class Refused < StandardError; end # leaked: every socket found under the sandbox, relative to it. # answering: those that still accepted a connection after the stop. - Release = Struct.new(:leaked, :answering) do - def clean? - leaked.empty? - end + Release = + Struct.new(:leaked, :answering) do + def clean? + leaked.empty? + end - def message(directory) - text = "libtmux-ruby tests left sockets in the sandbox: #{leaked.join(', ')}" - return text if answering.empty? + def message(directory) + text = "libtmux-ruby tests left sockets in the sandbox: #{leaked.join(", ")}" + return text if answering.empty? - "#{text}; a server still answers at #{answering.join(', ')}, so #{File.basename(directory)} was kept" + "#{text}; a server still answers at #{answering.join(", ")}, so #{File.basename(directory)} was kept" + end end - end class << self def ambient?(name) @@ -47,7 +49,12 @@ def ambient?(name) # Findings name variables, never values: a TMUX value names a server. def violations(env = ENV) - found = env.keys.select { |name| ambient?(name) && !env[name].nil? }.sort.map { |name| "#{name} is set" } + found = + env + .keys + .select { |name| ambient?(name) && !env[name].nil? } + .sort + .map { |name| "#{name} is set" } problem = directory_problem(env) found << problem if problem found @@ -97,7 +104,10 @@ def overlay(env = ENV, directory: ENV.fetch("TMUX_TMPDIR")) # server no test stopped. A link is not followed: its target is a socket # in some other tree. def leaks(directory) - Dir.glob("**/*", File::FNM_DOTMATCH, base: directory).select { |path| socket?(File.join(directory, path)) }.sort + Dir + .glob("**/*", File::FNM_DOTMATCH, base: directory) + .select { |path| socket?(File.join(directory, path)) } + .sort end # Stops the server behind each socket with that tmux and removes the @@ -125,10 +135,14 @@ def directory_problem(env) end def create(roots) - root = roots.find do |path| - path.bytesize + NAME_BYTES <= MAX_BYTES && File.directory?(path) && File.writable?(path) + root = + roots.find do |path| + path.bytesize + NAME_BYTES <= MAX_BYTES && File.directory?(path) && File.writable?(path) + end + unless root + raise Refused, + "no temporary directory is short enough for a tmux socket path; set TMPDIR to a shorter one" end - raise Refused, "no temporary directory is short enough for a tmux socket path; set TMPDIR to a shorter one" unless root Dir.mktmpdir(PREFIX, root) rescue SystemCallError @@ -149,7 +163,16 @@ def socket?(path) # would hold the run for as long as the client lives. The client is # killed once the wait is over and the socket then counts as answering. def kill_server(socket, tmux, wait) - pid = Process.spawn(scrub(ENV), tmux, "-S", socket, "kill-server", out: File::NULL, err: File::NULL) + pid = + Process.spawn( + scrub(ENV), + tmux, + "-S", + socket, + "kill-server", + out: File::NULL, + err: File::NULL + ) deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + wait until Process.wait(pid, Process::WNOHANG) if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline @@ -195,15 +218,16 @@ def answering?(socket) # registered after it would run first and remove the directory early. def clean_up_after(directory) owner = Process.pid - cleanup = lambda do - next unless Process.pid == owner + cleanup = + lambda do + next unless Process.pid == owner - released = release(directory) - next if released.clean? + released = release(directory) + next if released.clean? - warn released.message(directory) - exit 1 - end + warn released.message(directory) + exit 1 + end if defined?(Minitest) && Minitest.respond_to?(:after_run) Minitest.after_run(&cleanup) else diff --git a/test/support/tmux_fixture.rb b/test/support/tmux_fixture.rb index d825a38c..1dc54ff9 100644 --- a/test/support/tmux_fixture.rb +++ b/test/support/tmux_fixture.rb @@ -51,7 +51,7 @@ def value end private_constant :CleanupDetails, :OwnedChild - CLEAN_ENV = {"TMUX" => nil, "TMUX_PANE" => nil}.freeze + CLEAN_ENV = { "TMUX" => nil, "TMUX_PANE" => nil }.freeze DEADLINE_SECONDS = 0.5 private_constant :CLEAN_ENV, :DEADLINE_SECONDS @@ -102,11 +102,21 @@ def start File.write(config_path, "set-option -g default-shell /bin/sh\n") watch_socket do |readiness| # -D keeps the daemon as our child; its exit can be observed and reaped. - @server = spawn_owned(@executable, "-D", *readiness.arguments, "-S", @socket_path, - "-f", config_path, **readiness.spawn_options) + @server = + spawn_owned( + @executable, + "-D", + *readiness.arguments, + "-S", + @socket_path, + "-f", + config_path, + **readiness.spawn_options + ) @server.first.close end - _, error, status = capture("new-session", "-d", "-s", "fixture", "-x", "80", "-y", "24", "cat") + _, error, status = + capture("new-session", "-d", "-s", "fixture", "-x", "80", "-y", "24", "cat") raise Error, "tmux could not create fixture session: #{error}" unless status.success? end @@ -121,8 +131,17 @@ def wait_for_pane_exit_status(server, pane_id, timeout: 5.0) remaining = deadline - monotonic return status unless remaining.positive? - status = server.run(["display-message", "-p", "-t", pane_id, - '#{pane_dead}|#{pane_dead_status}|#{pane_dead_signal}'], timeout: remaining).text + status = + server.run( + [ + "display-message", + "-p", + "-t", + pane_id, + '#{pane_dead}|#{pane_dead_status}|#{pane_dead_signal}' + ], + timeout: remaining + ).text return status unless status == "0||\n" pause = [deadline - monotonic, 0.02].min @@ -139,10 +158,11 @@ def close begin Thread.handle_interrupt(Exception => :never) do unless @cleanup_complete - clients = @clients_mutex.synchronize do - @closed = true - @clients.dup - end + clients = + @clients_mutex.synchronize do + @closed = true + @clients.dup + end errors = [] attempt_cleanup(errors, "server termination") do # The socket may have been replaced. Cleanup follows the owned child. @@ -160,7 +180,8 @@ def close end @cleanup_errors = errors.freeze @cleanup_complete = errors.empty? - failure = Error.new("tmux fixture cleanup failed", cleanup_errors: errors) unless errors.empty? + failure = + Error.new("tmux fixture cleanup failed", cleanup_errors: errors) unless errors.empty? end end rescue Exception => deferred @@ -181,26 +202,31 @@ def capture(*arguments) @clients_mutex.synchronize do raise Error, "fixture is closed" if @closed - client = spawn_owned(@executable, "-N", "-S", @socket_path, "-f", "/dev/null", *arguments) + client = + spawn_owned(@executable, "-N", "-S", @socket_path, "-f", "/dev/null", *arguments) @clients[client.last.pid] = client end input, output, error, waiter = client input.close Thread.handle_interrupt(Exception => :immediate) do deadline = monotonic + DEADLINE_SECONDS - buffers = {output => +"".b, error => +"".b} + buffers = { output => +"".b, error => +"".b } reading = buffers.keys until reading.empty? wait_readable(reading, deadline).each do |io| bytes = io.read_nonblock(16_384, exception: false) case bytes - when nil then reading.delete(io) - when String then buffers.fetch(io) << bytes + when nil + reading.delete(io) + when String + buffers.fetch(io) << bytes end end end remaining = deadline - monotonic - raise Error, "tmux client exceeded fixture deadline" unless remaining.positive? && waiter.join(remaining) + unless remaining.positive? && waiter.join(remaining) + raise Error, "tmux client exceeded fixture deadline" + end result = [buffers.fetch(output), buffers.fetch(error), waiter.value] end @@ -234,8 +260,16 @@ def spawn_owned(*arguments, **options) output, child_output = IO.pipe.tap { |pair| streams.concat(pair) } error, child_error = IO.pipe.tap { |pair| streams.concat(pair) } streams.each(&:binmode) - pid = Process.spawn(CLEAN_ENV, *arguments, in: child_input, out: child_output, - err: child_error, close_others: true, **options) + pid = + Process.spawn( + CLEAN_ENV, + *arguments, + in: child_input, + out: child_output, + err: child_error, + close_others: true, + **options + ) observer.spawned(pid) [child_input, child_output, child_error].each(&:close) [input, output, error, observer] @@ -255,7 +289,9 @@ def spawn_owned(*arguments, **options) ensure observer.close end - attach_cleanup_details(failure, Error.new("spawn cleanup failed", cleanup_errors: errors)) unless errors.empty? + unless errors.empty? + attach_cleanup_details(failure, Error.new("spawn cleanup failed", cleanup_errors: errors)) + end raise failure end end @@ -294,9 +330,7 @@ def retire(process) @retirement_mutex.synchronize do *streams, waiter = process errors = [] - streams.each do |io| - attempt_cleanup(errors, "pipe close") { io.close unless io.closed? } - end + streams.each { |io| attempt_cleanup(errors, "pipe close") { io.close unless io.closed? } } attempt_cleanup(errors, "child retirement") do begin waiter.signal("KILL") unless waiter.join(0.1) @@ -323,7 +357,14 @@ def attach_cleanup_details(error, cleanup) return if error.frozen? previous = error.respond_to?(:fixture_cleanup_errors) ? error.fixture_cleanup_errors : [] - details = cleanup.is_a?(Error) ? cleanup.cleanup_errors : ["fixture cleanup failed (#{cleanup.class})"] + details = + ( + if cleanup.is_a?(Error) + cleanup.cleanup_errors + else + ["fixture cleanup failed (#{cleanup.class})"] + end + ) error.extend(CleanupDetails) error.instance_variable_set(:@fixture_cleanup_errors, (previous + details).freeze) rescue StandardError diff --git a/test/support/tmuxp_catalog.rb b/test/support/tmuxp_catalog.rb index ed027959..1a5e77b5 100644 --- a/test/support/tmuxp_catalog.rb +++ b/test/support/tmuxp_catalog.rb @@ -19,27 +19,48 @@ module TmuxpCatalog # tmuxp's examples this loader reads. LOADED = %w[ - 2-pane-vertical.yaml 3-pane.yaml 4-pane.yaml focus-window-and-panes.yaml main-pane-height.yaml - session-environment.yaml shorthands.yaml start-directory.yaml window-index.yaml + 2-pane-vertical.yaml + 3-pane.yaml + 4-pane.yaml + focus-window-and-panes.yaml + main-pane-height.yaml + session-environment.yaml + shorthands.yaml + start-directory.yaml + window-index.yaml ].freeze # tmuxp's examples this loader refuses, with the message each one raises. A # change in the loader fails the case until the entry is updated or removed. REFUSED = { - "2-pane-synchronized.yaml" => "invalid workspace configuration at $.windows[0]; expected supported data-only fields; move callbacks or hooks into explicit application code", - "blank-panes.yaml" => "invalid workspace configuration at $.windows[0].panes[0]; expected configuration object", - "env-variables.yaml" => "invalid workspace configuration at $.before_script; expected supported data-only fields; move callbacks or hooks into explicit application code", - "main-pane-height-percentage.yaml" => "invalid workspace configuration at $.windows[0].options.main-pane-height; expected integer index from zero through 2147483647", - "minimal.yaml" => "invalid workspace configuration at $.windows[0].window_name; expected window name", - "options.yaml" => "invalid workspace configuration at $; expected supported data-only fields; move callbacks or hooks into explicit application code", - "pane-shell.yaml" => "invalid workspace configuration at $.windows[0]; expected supported data-only fields; move callbacks or hooks into explicit application code", - "plugin-system.yaml" => "invalid workspace configuration at $.plugins; expected supported data-only fields; move callbacks or hooks into explicit application code", - "skip-send-pane-level.yaml" => "invalid workspace configuration at $.windows[0].window_name; expected window name", - "skip-send.yaml" => "invalid workspace configuration at $.windows[0].window_name; expected window name", - "sleep-pane-level.yaml" => "invalid workspace configuration at $.windows[0].window_name; expected window name", - "sleep-virtualenv.yaml" => "invalid workspace configuration at $.shell_command_before; expected UTF-8 text", - "sleep.yaml" => "invalid workspace configuration at $.windows[0].window_name; expected window name", - "suppress-history.yaml" => "invalid workspace configuration at $; expected supported data-only fields; move callbacks or hooks into explicit application code" + "2-pane-synchronized.yaml" => + "invalid workspace configuration at $.windows[0]; expected supported data-only fields; move callbacks or hooks into explicit application code", + "blank-panes.yaml" => + "invalid workspace configuration at $.windows[0].panes[0]; expected configuration object", + "env-variables.yaml" => + "invalid workspace configuration at $.before_script; expected supported data-only fields; move callbacks or hooks into explicit application code", + "main-pane-height-percentage.yaml" => + "invalid workspace configuration at $.windows[0].options.main-pane-height; expected integer index from zero through 2147483647", + "minimal.yaml" => + "invalid workspace configuration at $.windows[0].window_name; expected window name", + "options.yaml" => + "invalid workspace configuration at $; expected supported data-only fields; move callbacks or hooks into explicit application code", + "pane-shell.yaml" => + "invalid workspace configuration at $.windows[0]; expected supported data-only fields; move callbacks or hooks into explicit application code", + "plugin-system.yaml" => + "invalid workspace configuration at $.plugins; expected supported data-only fields; move callbacks or hooks into explicit application code", + "skip-send-pane-level.yaml" => + "invalid workspace configuration at $.windows[0].window_name; expected window name", + "skip-send.yaml" => + "invalid workspace configuration at $.windows[0].window_name; expected window name", + "sleep-pane-level.yaml" => + "invalid workspace configuration at $.windows[0].window_name; expected window name", + "sleep-virtualenv.yaml" => + "invalid workspace configuration at $.shell_command_before; expected UTF-8 text", + "sleep.yaml" => + "invalid workspace configuration at $.windows[0].window_name; expected window name", + "suppress-history.yaml" => + "invalid workspace configuration at $; expected supported data-only fields; move callbacks or hooks into explicit application code" }.freeze module_function @@ -53,7 +74,7 @@ def path(name) end def workspace(name, home: HOME_DIRECTORY) - LibTmux::Workspace.load(path(name), environment: {"HOME" => home}) + LibTmux::Workspace.load(path(name), environment: { "HOME" => home }) end def expected(name) @@ -68,26 +89,52 @@ def syntax def structure(workspace, name) base = File.dirname(path(name)) model = workspace.to_h - directory = lambda do |value| - if value == HOME_DIRECTORY then HOME - elsif value == base then WORKSPACE_DIR - elsif value.start_with?("#{base}/") then "#{WORKSPACE_DIR}#{value.delete_prefix(base)}" - else value + directory = + lambda do |value| + if value == HOME_DIRECTORY + HOME + elsif value == base + WORKSPACE_DIR + elsif value.start_with?("#{base}/") + "#{WORKSPACE_DIR}#{value.delete_prefix(base)}" + else + value + end end - end - {"source" => nil, - "session" => {"name" => model.fetch("session_name"), "start_directory" => directory.call(model.fetch("start_directory")), - "environment" => model.fetch("environment"), "options" => model.fetch("options")}, - "windows" => model.fetch("windows").map do |window| - {"name" => window.fetch("window_name"), "index" => window.fetch("window_index"), "layout" => window["layout"], - "focus" => window.fetch("focus"), "start_directory" => directory.call(window.fetch("start_directory")), - "options" => window.fetch("options"), - "panes" => window.fetch("panes").map do |pane| - {"focus" => pane.fetch("focus"), "start_directory" => directory.call(pane.fetch("start_directory")), - "environment" => pane.fetch("environment"), - "commands" => pane.fetch("shell_command_before") + pane.fetch("shell_command")} - end} - end} + { + "source" => nil, + "session" => { + "name" => model.fetch("session_name"), + "start_directory" => directory.call(model.fetch("start_directory")), + "environment" => model.fetch("environment"), + "options" => model.fetch("options") + }, + "windows" => + model + .fetch("windows") + .map do |window| + { + "name" => window.fetch("window_name"), + "index" => window.fetch("window_index"), + "layout" => window["layout"], + "focus" => window.fetch("focus"), + "start_directory" => directory.call(window.fetch("start_directory")), + "options" => window.fetch("options"), + "panes" => + window + .fetch("panes") + .map do |pane| + { + "focus" => pane.fetch("focus"), + "start_directory" => directory.call(pane.fetch("start_directory")), + "environment" => pane.fetch("environment"), + "commands" => + pane.fetch("shell_command_before") + pane.fetch("shell_command") + } + end + } + end + } end # An undeclared directory defaults to the file's directory in this port. @@ -102,10 +149,12 @@ def port_expected(name) # Yields the session, each window and each pane, which carry start_directory. def each_directory(tree, &block) block.call(tree["session"]) if tree["session"] - tree.fetch("windows").each do |window| - block.call(window) - window.fetch("panes").each(&block) - end + tree + .fetch("windows") + .each do |window| + block.call(window) + window.fetch("panes").each(&block) + end end end end diff --git a/test/types/consumer.rb b/test/types/consumer.rb index 9c22cdd3..ecfdf81f 100644 --- a/test/types/consumer.rb +++ b/test/types/consumer.rb @@ -16,7 +16,8 @@ def initialize spec = Gem::Specification.find_all_by_name(name).first loader.add(path: Pathname(File.join(spec.full_gem_path, "sig"))) if spec end - @builder = RBS::DefinitionBuilder.new(env: RBS::Environment.from_loader(loader).resolve_type_names) + @builder = + RBS::DefinitionBuilder.new(env: RBS::Environment.from_loader(loader).resolve_type_names) @exercised = [] end @@ -24,7 +25,8 @@ def call(as, receiver, method, *arguments, expected:, **keywords, &block) type = RBS::Parser.parse_type(as) klass = Object.const_get(type.name.to_s) singleton = type.is_a?(RBS::Types::ClassSingleton) - definition = singleton ? @builder.build_singleton(type.name) : @builder.build_instance(type.name) + definition = + singleton ? @builder.build_singleton(type.name) : @builder.build_instance(type.name) declared = definition.methods.fetch(method) { raise "missing signature: #{as} #{method}" } raise "signature is private: #{as} #{method}" unless declared.accessibility == :public overloads = declared.defs.map(&:type) @@ -32,21 +34,30 @@ def call(as, receiver, method, *arguments, expected:, **keywords, &block) substitution = RBS::Substitution.build(definition.type_params, type.args) overloads = overloads.map { |entry| entry.sub(substitution) } end - checker = RBS::Test::TypeCheck.new(self_class: singleton ? klass.singleton_class : klass, - instance_class: klass, class_class: klass.singleton_class, builder: @builder, - sample_size: nil, unchecked_classes: []) + checker = + RBS::Test::TypeCheck.new( + self_class: singleton ? klass.singleton_class : klass, + instance_class: klass, + class_class: klass.singleton_class, + builder: @builder, + sample_size: nil, + unchecked_classes: [] + ) spy = RBS::UnitTest::Spy.wrap(receiver, method) trace = nil spy.callback = ->(value) { trace = value } result = spy.wrapped_object.__send__(method, *arguments, **keywords, &block) - matches = overloads.any? { |entry| checker.method_call(method, entry, trace, errors: []).empty? } + matches = + overloads.any? { |entry| checker.method_call(method, entry, trace, errors: []).empty? } raise "call violates shipped signature: #{as} #{method}" unless matches concrete = RBS::Parser.parse_type(expected) if concrete.is_a?(RBS::Types::Bases::Any) || concrete.to_s.include?("Enumerator") raise "consumer expectation must be concrete and must not enumerate a stream" end - raise "return violates consumer expectation: #{as} #{method}" unless checker.value(result, concrete) - @exercised << "#{type.name}#{singleton ? '.' : '#'}#{method}" + unless checker.value(result, concrete) + raise "return violates consumer expectation: #{as} #{method}" + end + @exercised << "#{type.name}#{singleton ? "." : "#"}#{method}" @last = [checker, overloads, method, trace] result end @@ -54,7 +65,8 @@ def call(as, receiver, method, *arguments, expected:, **keywords, &block) def verify_rejects_wrong_return(value = Object.new) checker, overloads, method, trace = @last corrupted = trace.dup - corrupted.method_call = RBS::Test::ArgumentsReturn.return(arguments: trace.method_call.arguments, value: value) + corrupted.method_call = + RBS::Test::ArgumentsReturn.return(arguments: trace.method_call.arguments, value: value) if overloads.any? { |entry| checker.method_call(method, entry, corrupted, errors: []).empty? } raise "signature checker failed to reject a wrong implementation return" end @@ -62,21 +74,49 @@ def verify_rejects_wrong_return(value = Object.new) end package = ARGV.fetch(0) -imports = {"libtmux" => "libtmux", "libtmux-async" => "libtmux/async", - "libtmux-mcp" => "libtmux/mcp/cli", "libtmux-workspace" => "libtmux/workspace/cli"} +imports = { + "libtmux" => "libtmux", + "libtmux-async" => "libtmux/async", + "libtmux-mcp" => "libtmux/mcp/cli", + "libtmux-workspace" => "libtmux/workspace/cli" +} require imports.fetch(package) 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}") + 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::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") @@ -85,77 +125,235 @@ def verify_rejects_wrong_return(value = Object.new) :checked end end - capabilities = consumer.call("::LibTmux::Server", server, :capabilities, expected: "::LibTmux::Capabilities") + 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") + 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") + 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, - expected: "::LibTmux::CreationReceipt") - session = consumer.call("::LibTmux::CreationReceipt", receipt, :entity, expected: "::LibTmux::Session") + 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, + expected: "::LibTmux::CreationReceipt" + ) + session = + consumer.call("::LibTmux::CreationReceipt", receipt, :entity, expected: "::LibTmux::Session") pane = consumer.call("::LibTmux::CreationReceipt", receipt, :pane, expected: "::LibTmux::Pane") - consumer.call("::LibTmux::Session", session, :new_window, name: "second", command: ["/bin/cat"], expected: "::LibTmux::Window") - snapshot = consumer.call("::LibTmux::Server", server, :snapshot, expected: "::LibTmux::Snapshot") - {"Session" => [session, snapshot.panes.first], "Window" => [receipt.window, snapshot.sessions.first], - "Pane" => [pane, snapshot.windows.first], "WindowLink" => [session.list_window_links.first, snapshot.panes.first]}.each do |kind, (handle, wrong)| + consumer.call( + "::LibTmux::Session", + session, + :new_window, + name: "second", + command: ["/bin/cat"], + expected: "::LibTmux::Window" + ) + snapshot = + consumer.call("::LibTmux::Server", server, :snapshot, expected: "::LibTmux::Snapshot") + { + "Session" => [session, snapshot.panes.first], + "Window" => [receipt.window, snapshot.sessions.first], + "Pane" => [pane, snapshot.windows.first], + "WindowLink" => [session.list_window_links.first, snapshot.panes.first] + }.each do |kind, (handle, wrong)| consumer.call("::LibTmux::#{kind}", handle, :snapshot, expected: "::LibTmux::#{kind}Snapshot") consumer.verify_rejects_wrong_return(wrong) end - panes = consumer.call("::LibTmux::Snapshot", snapshot, :panes, expected: "::LibTmux::Selection[::LibTmux::PaneSnapshot]") - records = consumer.call("::LibTmux::Selection[::LibTmux::PaneSnapshot]", panes, :to_a, expected: "Array[::LibTmux::PaneSnapshot]") - expression = consumer.call("singleton(::LibTmux::PaneWhere)", LibTmux::PaneWhere, :build, {id: pane.id}, expected: "::LibTmux::FilterExpr") - selected = consumer.call("::LibTmux::Selection[::LibTmux::PaneSnapshot]", panes, :where, expression, - expected: "::LibTmux::Selection[::LibTmux::PaneSnapshot]") - record = consumer.call("::LibTmux::Selection[::LibTmux::PaneSnapshot]", selected, :one, expected: "::LibTmux::PaneSnapshot") + panes = + consumer.call( + "::LibTmux::Snapshot", + snapshot, + :panes, + expected: "::LibTmux::Selection[::LibTmux::PaneSnapshot]" + ) + records = + consumer.call( + "::LibTmux::Selection[::LibTmux::PaneSnapshot]", + panes, + :to_a, + expected: "Array[::LibTmux::PaneSnapshot]" + ) + expression = + consumer.call( + "singleton(::LibTmux::PaneWhere)", + LibTmux::PaneWhere, + :build, + { id: pane.id }, + expected: "::LibTmux::FilterExpr" + ) + selected = + consumer.call( + "::LibTmux::Selection[::LibTmux::PaneSnapshot]", + panes, + :where, + expression, + expected: "::LibTmux::Selection[::LibTmux::PaneSnapshot]" + ) + record = + consumer.call( + "::LibTmux::Selection[::LibTmux::PaneSnapshot]", + selected, + :one, + expected: "::LibTmux::PaneSnapshot" + ) consumer.call("::LibTmux::PaneSnapshot", record, :active?, expected: "bool") consumer.call("::LibTmux::PaneSnapshot", record, :dead_status, expected: "Integer?") consumer.call("::LibTmux::PaneSnapshot", record, :current_path, expected: "String?") consumer.call("::LibTmux::PaneSnapshot", record, :window, expected: "::LibTmux::WindowSnapshot") - consumer.call("::LibTmux::Selection[::LibTmux::PaneSnapshot]", panes, :one_or_nil, id: "%4294967294", expected: "nil") + consumer.call( + "::LibTmux::Selection[::LibTmux::PaneSnapshot]", + panes, + :one_or_nil, + id: "%4294967294", + expected: "nil" + ) options = consumer.call("::LibTmux::Session", session, :options, expected: "::LibTmux::Options") - consumer.call("::LibTmux::Options", options, :set, "@types", true, expected: "::LibTmux::CommandResult") - option = consumer.call("::LibTmux::Options", options, :get, "@types", expected: "::LibTmux::OptionValue") + consumer.call( + "::LibTmux::Options", + options, + :set, + "@types", + true, + expected: "::LibTmux::CommandResult" + ) + option = + consumer.call( + "::LibTmux::Options", + options, + :get, + "@types", + expected: "::LibTmux::OptionValue" + ) consumer.call("::LibTmux::OptionValue", option, :as, :boolean, expected: "bool") catalog = LibTmux::OptionCatalog consumer.call("singleton(::LibTmux::OptionCatalog)", catalog, :tmux_version, expected: "String") - definitions = consumer.call("singleton(::LibTmux::OptionCatalog)", catalog, :options, - expected: "Hash[String, ::LibTmux::OptionCatalog::Option]") - consumer.call("::LibTmux::OptionCatalog::Option", definitions.fetch("history-limit"), :range, expected: "Range[Integer]") - hooks = consumer.call("singleton(::LibTmux::OptionCatalog)", catalog, :hooks, - expected: "Hash[String, ::LibTmux::OptionCatalog::Hook]") - consumer.call("::LibTmux::OptionCatalog::Hook", hooks.fetch("pane-created"), :scopes, expected: "Array[Symbol]") + definitions = + consumer.call( + "singleton(::LibTmux::OptionCatalog)", + catalog, + :options, + expected: "Hash[String, ::LibTmux::OptionCatalog::Option]" + ) + consumer.call( + "::LibTmux::OptionCatalog::Option", + definitions.fetch("history-limit"), + :range, + expected: "Range[Integer]" + ) + hooks = + consumer.call( + "singleton(::LibTmux::OptionCatalog)", + catalog, + :hooks, + expected: "Hash[String, ::LibTmux::OptionCatalog::Hook]" + ) + consumer.call( + "::LibTmux::OptionCatalog::Hook", + hooks.fetch("pane-created"), + :scopes, + expected: "Array[Symbol]" + ) result = consumer.call("::LibTmux::Pane", pane, :capture, expected: "::LibTmux::CommandResult") consumer.call("::LibTmux::CommandResult", result, :stdout, expected: "String") consumer.call("::LibTmux::CommandResult", result, :success?, expected: "bool") consumer.verify_rejects_wrong_return pane.send_text("signature wait") - visible = consumer.call("::LibTmux::Pane", pane, :wait_for_text, "signature wait", expected: "::LibTmux::TextWait::Result") + visible = + consumer.call( + "::LibTmux::Pane", + pane, + :wait_for_text, + "signature wait", + expected: "::LibTmux::TextWait::Result" + ) consumer.call("::LibTmux::TextWait::Result", visible, :text, expected: "String") consumer.call("::LibTmux::TextWait::Result", visible, :matched_at_entry, expected: "bool") # Control clients attach only to tmux 3.7 and newer; older daemons refuse. control_daemon = server.supports_control? if control_daemon - consumer.call("::LibTmux::Server", server, :open_control, session: session.ref, expected: ":checked") do |control| - reply = consumer.call("::LibTmux::ControlConnection", control, :exchange, "display-message -p typed", expected: "::LibTmux::GuardedReply") - counters = consumer.call("::LibTmux::ControlConnection", control, :diagnostics, - expected: "Hash[Symbol, Integer | bool | Hash[Symbol, Integer]]") + consumer.call( + "::LibTmux::Server", + server, + :open_control, + session: session.ref, + expected: ":checked" + ) do |control| + reply = + consumer.call( + "::LibTmux::ControlConnection", + control, + :exchange, + "display-message -p typed", + expected: "::LibTmux::GuardedReply" + ) + counters = + consumer.call( + "::LibTmux::ControlConnection", + control, + :diagnostics, + expected: "Hash[Symbol, Integer | bool | Hash[Symbol, Integer]]" + ) raise "consumed reply is still retained" unless counters.fetch(:retained_reply_bytes).zero? - blocks = consumer.call("::LibTmux::GuardedReply", reply, :blocks, expected: "Array[::LibTmux::GuardedBlock]") + blocks = + consumer.call( + "::LibTmux::GuardedReply", + reply, + :blocks, + expected: "Array[::LibTmux::GuardedBlock]" + ) consumer.call("::LibTmux::GuardedBlock", blocks.last, :raw, expected: "String") client = server.list_clients.find { |entry| entry.fetch(:pid) == control.pid }.fetch(:name) - consumer.call("::LibTmux::Server", server, :switch_client, client: client, session: session.ref, - expected: "::LibTmux::CommandResult") - stream = consumer.call("::LibTmux::ControlConnection", control, :subscribe, max_events: 2, - expected: "::LibTmux::ControlSubscription") + consumer.call( + "::LibTmux::Server", + server, + :switch_client, + client: client, + session: session.ref, + expected: "::LibTmux::CommandResult" + ) + stream = + consumer.call( + "::LibTmux::ControlConnection", + control, + :subscribe, + max_events: 2, + expected: "::LibTmux::ControlSubscription" + ) consumer.call("::LibTmux::ControlSubscription", stream, :close, expected: "nil") - consumer.call("::LibTmux::ControlSubscription", stream, :diagnostics, - expected: "{queued_events: Integer, retained_event_bytes: Integer, gap_pending: bool, overflowed: bool, closed: bool, mode: :reliable | :tail, limits: Hash[Symbol, Integer]}") + consumer.call( + "::LibTmux::ControlSubscription", + stream, + :diagnostics, + expected: + "{queued_events: Integer, retained_event_bytes: Integer, gap_pending: bool, overflowed: bool, closed: bool, mode: :reliable | :tail, limits: Hash[Symbol, Integer]}" + ) :checked end else @@ -166,33 +364,110 @@ def verify_rejects_wrong_return(value = Object.new) nil end end - consumer.call("singleton(::LibTmux::ControlEvent)", LibTmux::ControlEvent, :new, - kind: :output, raw: "%output %0 typed\n", data: "typed", expected: "::LibTmux::ControlEvent") + consumer.call( + "singleton(::LibTmux::ControlEvent)", + LibTmux::ControlEvent, + :new, + kind: :output, + raw: "%output %0 typed\n", + data: "typed", + expected: "::LibTmux::ControlEvent" + ) raise "consumer fixture unexpectedly empty" unless records.length == 2 when "libtmux-async" 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") + 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") - consumer.call("::LibTmux::Async::Scope", scope, :diagnostics, expected: "::LibTmux::Async::scope_diagnostics") - consumer.call("::LibTmux::Server", facade, :diagnostics, - expected: "{reserved_process_slots: Integer, limits: {close_timeout: Numeric}}") - consumer.call("::LibTmux::Async::Server", facade, :diagnostics, expected: "::LibTmux::Async::scope_diagnostics") - panes = consumer.call("::LibTmux::Async::Server", facade, :list_panes, expected: "Array[::LibTmux::Pane]") - consumer.call("::LibTmux::Async::Scope", scope, :map, panes, concurrency: 2, expected: "Array[::LibTmux::CommandResult]") { |pane| pane.capture } + 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" + ) + consumer.call( + "::LibTmux::Async::Scope", + scope, + :diagnostics, + expected: "::LibTmux::Async::scope_diagnostics" + ) + consumer.call( + "::LibTmux::Server", + facade, + :diagnostics, + expected: "{reserved_process_slots: Integer, limits: {close_timeout: Numeric}}" + ) + consumer.call( + "::LibTmux::Async::Server", + facade, + :diagnostics, + expected: "::LibTmux::Async::scope_diagnostics" + ) + panes = + consumer.call( + "::LibTmux::Async::Server", + facade, + :list_panes, + expected: "Array[::LibTmux::Pane]" + ) + consumer.call( + "::LibTmux::Async::Scope", + scope, + :map, + panes, + concurrency: 2, + expected: "Array[::LibTmux::CommandResult]" + ) { |pane| pane.capture } if control_daemon - consumer.call("::LibTmux::Async::Server", facade, :open_control, session: session.ref, expected: ":checked") do |control| - consumer.call("::LibTmux::Async::ControlConnection", control, :exchange, "display-message -p typed", expected: "::LibTmux::GuardedReply") - client = facade.list_clients.find { |entry| entry.fetch(:pid) == control.pid }.fetch(:name) - consumer.call("::LibTmux::Async::Server", facade, :switch_client, client: client, session: session.ref, - expected: "::LibTmux::CommandResult") + consumer.call( + "::LibTmux::Async::Server", + facade, + :open_control, + session: session.ref, + expected: ":checked" + ) do |control| + consumer.call( + "::LibTmux::Async::ControlConnection", + control, + :exchange, + "display-message -p typed", + expected: "::LibTmux::GuardedReply" + ) + client = + facade.list_clients.find { |entry| entry.fetch(:pid) == control.pid }.fetch(:name) + consumer.call( + "::LibTmux::Async::Server", + facade, + :switch_client, + client: client, + session: session.ref, + expected: "::LibTmux::CommandResult" + ) :checked end else @@ -207,43 +482,153 @@ def verify_rejects_wrong_return(value = Object.new) end end.wait when "libtmux-workspace" - config = {session_name: "workspace-types", windows: [{window_name: "one", panes: [{}]}]} - workspace = consumer.call("singleton(::LibTmux::Workspace)", LibTmux::Workspace, :parse, - JSON.generate(config), format: :json, base_directory: Dir.pwd, expected: "::LibTmux::Workspace") - plan = consumer.call("::LibTmux::Workspace", workspace, :plan, expected: "::LibTmux::Workspace::Plan") - consumer.call("::LibTmux::Workspace::Plan", plan, :steps, expected: "Array[::LibTmux::Workspace::Plan::Step]") - result = consumer.call("::LibTmux::Workspace::Plan", plan, :apply, server: server, expected: "::LibTmux::Workspace::ApplyResult") - consumer.call("::LibTmux::Workspace::ApplyResult", result, :created_refs, expected: "Hash[String, ::LibTmux::EntityRef]") - effects = consumer.call("::LibTmux::Workspace::ApplyResult", result, :effects, expected: "Array[::LibTmux::Workspace::ApplyResult::Effect]") + config = { session_name: "workspace-types", windows: [{ window_name: "one", panes: [{}] }] } + workspace = + consumer.call( + "singleton(::LibTmux::Workspace)", + LibTmux::Workspace, + :parse, + JSON.generate(config), + format: :json, + base_directory: Dir.pwd, + expected: "::LibTmux::Workspace" + ) + plan = + consumer.call( + "::LibTmux::Workspace", + workspace, + :plan, + expected: "::LibTmux::Workspace::Plan" + ) + consumer.call( + "::LibTmux::Workspace::Plan", + plan, + :steps, + expected: "Array[::LibTmux::Workspace::Plan::Step]" + ) + result = + consumer.call( + "::LibTmux::Workspace::Plan", + plan, + :apply, + server: server, + expected: "::LibTmux::Workspace::ApplyResult" + ) + consumer.call( + "::LibTmux::Workspace::ApplyResult", + result, + :created_refs, + expected: "Hash[String, ::LibTmux::EntityRef]" + ) + effects = + consumer.call( + "::LibTmux::Workspace::ApplyResult", + result, + :effects, + expected: "Array[::LibTmux::Workspace::ApplyResult::Effect]" + ) effect = effects.first type = LibTmux::Workspace::ApplyResult::Effect - consumer.call("singleton(::LibTmux::Workspace::ApplyResult::Effect)", type, :new, - step_id: effect.step_id, action: effect.action, outcome: effect.outcome, expected: "::LibTmux::Workspace::ApplyResult::Effect") - consumer.call("singleton(::LibTmux::Workspace::ApplyResult::Effect)", type, :[], - effect.step_id, effect.action, effect.outcome, expected: "::LibTmux::Workspace::ApplyResult::Effect") - consumer.call("singleton(::LibTmux::Workspace::ApplyResult::Effect)", type, :members, expected: "Array[Symbol]") + consumer.call( + "singleton(::LibTmux::Workspace::ApplyResult::Effect)", + type, + :new, + step_id: effect.step_id, + action: effect.action, + outcome: effect.outcome, + expected: "::LibTmux::Workspace::ApplyResult::Effect" + ) + consumer.call( + "singleton(::LibTmux::Workspace::ApplyResult::Effect)", + type, + :[], + effect.step_id, + effect.action, + effect.outcome, + expected: "::LibTmux::Workspace::ApplyResult::Effect" + ) + consumer.call( + "singleton(::LibTmux::Workspace::ApplyResult::Effect)", + type, + :members, + expected: "Array[Symbol]" + ) step = plan.steps.first type = LibTmux::Workspace::Plan::Step - consumer.call("singleton(::LibTmux::Workspace::Plan::Step)", type, :[], step.id, step.operation, step.target, - step.arguments, step.produces, step.effect, expected: "::LibTmux::Workspace::Plan::Step") - consumer.call("singleton(::LibTmux::Workspace::Plan::Step)", type, :members, expected: "Array[Symbol]") - consumer.call("singleton(::LibTmux::Workspace::CLI)", LibTmux::Workspace::CLI, :run, ["--help"], - out: StringIO.new, err: StringIO.new, expected: "Integer") + consumer.call( + "singleton(::LibTmux::Workspace::Plan::Step)", + type, + :[], + step.id, + step.operation, + step.target, + step.arguments, + step.produces, + step.effect, + expected: "::LibTmux::Workspace::Plan::Step" + ) + consumer.call( + "singleton(::LibTmux::Workspace::Plan::Step)", + type, + :members, + expected: "Array[Symbol]" + ) + consumer.call( + "singleton(::LibTmux::Workspace::CLI)", + LibTmux::Workspace::CLI, + :run, + ["--help"], + out: StringIO.new, + err: StringIO.new, + expected: "Integer" + ) when "libtmux-mcp" server.new_session(name: "mcp-types", command: ["/bin/cat"]) Async do |parent| LibTmux::Async.open(parent: parent, server: server) do |scope| - app = consumer.call("singleton(::LibTmux::MCP::Application)", LibTmux::MCP::Application, :new, - server: scope.server, endpoint_name: "types", expected: "::LibTmux::MCP::Application") - consumer.call("::LibTmux::MCP::Application", app, :tools, expected: "Array[singleton(::MCP::Tool)]") + app = + consumer.call( + "singleton(::LibTmux::MCP::Application)", + LibTmux::MCP::Application, + :new, + server: scope.server, + endpoint_name: "types", + expected: "::LibTmux::MCP::Application" + ) + consumer.call( + "::LibTmux::MCP::Application", + app, + :tools, + expected: "Array[singleton(::MCP::Tool)]" + ) consumer.call("::LibTmux::MCP::Application", app, :sdk_server, expected: "::MCP::Server") - consumer.call("::LibTmux::MCP::Application", app, :call, "tmux_snapshot", {"entity" => "pane"}, expected: "::MCP::Tool::Response") + consumer.call( + "::LibTmux::MCP::Application", + app, + :call, + "tmux_snapshot", + { "entity" => "pane" }, + expected: "::MCP::Tool::Response" + ) end end.wait - consumer.call("singleton(::LibTmux::MCP::CLI)", LibTmux::MCP::CLI, :run, ["--help"], - out: StringIO.new, err: StringIO.new, expected: "Integer") + consumer.call( + "singleton(::LibTmux::MCP::CLI)", + LibTmux::MCP::CLI, + :run, + ["--help"], + out: StringIO.new, + err: StringIO.new, + expected: "Integer" + ) end end -puts JSON.generate({"package" => package, "exercised" => consumer.exercised.uniq.sort, - "proof" => "observed arguments, blocks and returns", "whole_program_static_check" => false}) +puts JSON.generate( + { + "package" => package, + "exercised" => consumer.exercised.uniq.sort, + "proof" => "observed arguments, blocks and returns", + "whole_program_static_check" => false + } + ) diff --git a/test/unit/async_surface_test.rb b/test/unit/async_surface_test.rb index 5453fd32..74619eba 100644 --- a/test/unit/async_surface_test.rb +++ b/test/unit/async_surface_test.rb @@ -11,10 +11,16 @@ class AsyncSurfaceTest < Minitest::Test # Classes in the namespace that subclass a core class and replace its # constructor. An error class keeps the core constructor and public `new`. def self.facades(namespace) - namespace.constants.map { |name| namespace.const_get(name) }.grep(Class).select do |klass| - klass.superclass.name.to_s.start_with?("LibTmux::") && !klass.superclass.name.start_with?("LibTmux::Async") && - !(klass < Exception) && klass.instance_method(:initialize).owner != klass.superclass.instance_method(:initialize).owner - end + namespace + .constants + .map { |name| namespace.const_get(name) } + .grep(Class) + .select do |klass| + klass.superclass.name.to_s.start_with?("LibTmux::") && + !klass.superclass.name.start_with?("LibTmux::Async") && !(klass < Exception) && + klass.instance_method(:initialize).owner != + klass.superclass.instance_method(:initialize).owner + end end CLASSES = facades(LibTmux::Async).freeze @@ -30,10 +36,11 @@ def self.facades(namespace) def test_async_server_refuses_the_core_factories_before_yielding %i[start open].each do |factory| - error = assert_raises(LibTmux::UnsupportedFeatureError) do - LibTmux::Async::Server.public_send(factory) { flunk "Async::Server.#{factory} yielded" } - end - assert_equal [:admission, :not_sent], [error.phase, error.delivery] + error = + assert_raises(LibTmux::UnsupportedFeatureError) do + LibTmux::Async::Server.public_send(factory) { flunk "Async::Server.#{factory} yielded" } + end + assert_equal %i[admission not_sent], [error.phase, error.delivery] end end @@ -44,18 +51,27 @@ def test_async_server_refuses_the_core_factories_before_yielding # block the scheduler thread, or build an object through the facade's # private constructor. Every LibTmux method on the class is a root. def test_code_the_facade_runs_reaches_only_state_it_builds - problems = CLASSES.flat_map do |klass| - set = LibTmuxTest::IvarReach.new(klass).facade_writes - (method_names(klass) - UNREACHABLE.fetch(klass, [])).flat_map do |name| - reach = LibTmuxTest::IvarReach.new(klass).walk(name, only_core: false) - unset = reach.reads.reject { |ivar, _| set.include?(ivar) }.map do |ivar, path| - "#{klass}##{name} reads #{ivar} via #{path.join(' -> ')}, which #{klass} never sets" + problems = + CLASSES.flat_map do |klass| + set = LibTmuxTest::IvarReach.new(klass).facade_writes + (method_names(klass) - UNREACHABLE.fetch(klass, [])).flat_map do |name| + reach = LibTmuxTest::IvarReach.new(klass).walk(name, only_core: false) + unset = + reach + .reads + .reject { |ivar, _| set.include?(ivar) } + .map do |ivar, path| + "#{klass}##{name} reads #{ivar} via #{path.join(" -> ")}, which #{klass} never sets" + end + unset + + reach.hazards.map do |hazard, path| + "#{klass}##{name} #{hazard} via #{path.join(" -> ")}" + end end - unset + reach.hazards.map { |hazard, path| "#{klass}##{name} #{hazard} via #{path.join(' -> ')}" } end - end - assert_empty problems, "code the facade runs reaches state or blocking calls the facade does not provide. " \ - "A core helper that no facade path calls belongs in UNREACHABLE." + assert_empty problems, + "code the facade runs reaches state or blocking calls the facade does not provide. " \ + "A core helper that no facade path calls belongs in UNREACHABLE." end def test_unreachable_helpers_stay_unreachable @@ -63,78 +79,117 @@ def test_unreachable_helpers_stay_unreachable reach = LibTmuxTest::IvarReach.new(klass) (method_names(klass) - names).each { |name| reach.walk(name, only_core: false) } assert_empty names & reach.visited, "#{klass} reaches a helper listed as unreachable" - names.each { |name| assert klass.private_method_defined?(name), "#{klass}##{name} no longer exists" } + names.each do |name| + assert klass.private_method_defined?(name), "#{klass}##{name} no longer exists" + end end end def test_the_reach_check_sees_planted_reads_and_blocking_calls - core = Class.new do - def initialize = @kept = 1 - def public_one = helper - def public_two = @kept - def public_three = Process.spawn("true") - def memoized = (@memo ||= {}).dup - def guarded = defined?(@maybe) ? @maybe : 0 - def local = (@buffer = []) && @buffer.length - def leaks = (guard_elsewhere; @lost.length) - def hands_over = notify(@unset) - def hands_elsewhere = report(@unset) - private def notify(value) = value - private def report(value) = value - def copy = self.class.open - def sends = __send__(:helper) - def counts = @count += 1 - def checked = instance_variable_defined?(:@maybe) ? @maybe : 0 - def shells = system("true") - def threads = Thread.new {} - def pipes = IO.popen("true") - def captures = Open3.capture2("true") - def terminals = PTY.spawn("true") - def allocates = self.class.allocate - def sends_new = self.class.__send__(:new) - attr_reader :exposed - alias_method :renamed, :public_one - private def guard_elsewhere = defined?(@lost) - private def helper = @lost.length - end - facade = Class.new(core) do - def initialize = @own = 1 - def tally = @ticks += 1 - private def notify(value) = value&.to_s - end + core = + Class.new do + def initialize = @kept = 1 + def public_one = helper + def public_two = @kept + def public_three = Process.spawn("true") + def memoized = (@memo ||= {}).dup + def guarded = defined?(@maybe) ? @maybe : 0 + def local = (@buffer = []) && @buffer.length + def leaks = + ( + guard_elsewhere + @lost.length + ) + def hands_over = notify(@unset) + def hands_elsewhere = report(@unset) + private def notify(value) = value + private def report(value) = value + def copy = self.class.open + def sends = __send__(:helper) + def counts = @count += 1 + def checked = instance_variable_defined?(:@maybe) ? @maybe : 0 + def shells = system("true") + def threads = Thread.new {} + def pipes = IO.popen("true") + def captures = Open3.capture2("true") + def terminals = PTY.spawn("true") + def allocates = self.class.allocate + def sends_new = self.class.__send__(:new) + attr_reader :exposed + alias_method :renamed, :public_one + private def guard_elsewhere = defined?(@lost) + private def helper = @lost.length + end + facade = + Class.new(core) do + def initialize = @own = 1 + def tally = @ticks += 1 + private def notify(value) = value&.to_s + end reads = LibTmuxTest::IvarReach.new(facade).walk(:public_one, only_core: false).reads - assert_equal({:@lost => %i[public_one helper]}, reads) - assert_equal({"calls Process.spawn" => %i[public_three]}, LibTmuxTest::IvarReach.new(facade).walk(:public_three, only_core: false).hazards) - %i[memoized guarded local].each { |name| assert_empty LibTmuxTest::IvarReach.new(facade).walk(name, only_core: false).reads, name } - assert_equal [:@lost], LibTmuxTest::IvarReach.new(facade).walk(:leaks, only_core: false).reads.keys - assert_equal [:@lost], LibTmuxTest::IvarReach.new(facade).walk(:renamed, only_core: false).reads.keys + assert_equal({ :@lost => %i[public_one helper] }, reads) + assert_equal( + { "calls Process.spawn" => %i[public_three] }, + LibTmuxTest::IvarReach.new(facade).walk(:public_three, only_core: false).hazards + ) + %i[memoized guarded local].each do |name| + assert_empty LibTmuxTest::IvarReach.new(facade).walk(name, only_core: false).reads, name + end + assert_equal [:@lost], + LibTmuxTest::IvarReach.new(facade).walk(:leaks, only_core: false).reads.keys + assert_equal [:@lost], + LibTmuxTest::IvarReach.new(facade).walk(:renamed, only_core: false).reads.keys assert_empty LibTmuxTest::IvarReach.new(facade).walk(:hands_over, only_core: false).reads - assert_equal [:@unset], LibTmuxTest::IvarReach.new(facade).walk(:hands_elsewhere, only_core: false).reads.keys - assert_equal ["builds an object through self.class.open"], LibTmuxTest::IvarReach.new(facade).walk(:copy, only_core: false).hazards.keys - assert_equal [:@lost], LibTmuxTest::IvarReach.new(facade).walk(:sends, only_core: false).reads.keys - assert_equal [:@count], LibTmuxTest::IvarReach.new(facade).walk(:counts, only_core: false).reads.keys - assert_equal [:@exposed], LibTmuxTest::IvarReach.new(facade).walk(:exposed, only_core: false).reads.keys + assert_equal [:@unset], + LibTmuxTest::IvarReach + .new(facade) + .walk(:hands_elsewhere, only_core: false) + .reads + .keys + assert_equal ["builds an object through self.class.open"], + LibTmuxTest::IvarReach.new(facade).walk(:copy, only_core: false).hazards.keys + assert_equal [:@lost], + LibTmuxTest::IvarReach.new(facade).walk(:sends, only_core: false).reads.keys + assert_equal [:@count], + LibTmuxTest::IvarReach.new(facade).walk(:counts, only_core: false).reads.keys + assert_equal [:@exposed], + LibTmuxTest::IvarReach.new(facade).walk(:exposed, only_core: false).reads.keys assert_empty LibTmuxTest::IvarReach.new(facade).walk(:checked, only_core: false).reads - {shells: "calls system", threads: "calls Thread.new", pipes: "calls IO.popen", captures: "calls Open3", - terminals: "calls PTY", allocates: "builds an object through self.class.allocate", - sends_new: "builds an object through self.class.new"}.each do |name, hazard| - assert_equal [hazard], LibTmuxTest::IvarReach.new(facade).walk(name, only_core: false).hazards.keys, name + { + shells: "calls system", + threads: "calls Thread.new", + pipes: "calls IO.popen", + captures: "calls Open3", + terminals: "calls PTY", + allocates: "builds an object through self.class.allocate", + sends_new: "builds an object through self.class.new" + }.each do |name, hazard| + assert_equal [hazard], + LibTmuxTest::IvarReach.new(facade).walk(name, only_core: false).hazards.keys, + name end assert_equal [:@own], LibTmuxTest::IvarReach.new(facade).facade_writes.to_a end def test_discovery_skips_error_classes_and_inherited_constructors namespace = Module.new - namespace.const_set(:Failure, Class.new(LibTmux::UnsupportedFeatureError) { def initialize(message = nil) = super }) + namespace.const_set( + :Failure, + Class.new(LibTmux::UnsupportedFeatureError) { def initialize(message = nil) = super } + ) namespace.const_set(:Alias, Class.new(LibTmux::Server)) - namespace.const_set(:Facade, Class.new(LibTmux::Server) { def initialize(scope) = @scope = scope }) + namespace.const_set( + :Facade, + Class.new(LibTmux::Server) { def initialize(scope) = @scope = scope } + ) assert_equal [namespace::Facade], self.class.facades(namespace) end def test_facade_overrides_the_transport_hooks_inherited_methods_rely_on HOOKS.each do |name| - assert_equal LibTmux::Async::Server, LibTmux::Async::Server.instance_method(name).owner, - "Async::Server##{name} falls through to the core" + assert_equal LibTmux::Async::Server, + LibTmux::Async::Server.instance_method(name).owner, + "Async::Server##{name} falls through to the core" end end @@ -146,12 +201,17 @@ def test_library_built_constructors_are_private end def test_facade_requires_a_scope - assert_raises(ArgumentError) { LibTmux::Async::Server.__send__(:new, nil, LibTmux::Server.allocate) } + assert_raises(ArgumentError) do + LibTmux::Async::Server.__send__(:new, nil, LibTmux::Server.allocate) + end end def test_facade_attach_is_refused facade = LibTmux::Async::Server.allocate - error = assert_raises(LibTmux::UnsupportedFeatureError) { facade.attach(session: nil, terminal: $stdout, term: "xterm") } + error = + assert_raises(LibTmux::UnsupportedFeatureError) do + facade.attach(session: nil, terminal: $stdout, term: "xterm") + end assert_equal :admission, error.phase end diff --git a/test/unit/capabilities_test.rb b/test/unit/capabilities_test.rb index f92280e0..f8e588af 100644 --- a/test/unit/capabilities_test.rb +++ b/test/unit/capabilities_test.rb @@ -21,7 +21,10 @@ def test_the_manifest_names_the_floor_and_has_unique_ids assert_equal "libtmux-capabilities/1", manifest.fetch("schema") assert_equal "ruby", manifest.fetch("port") assert_equal LibTmux::Support::MINIMUM, manifest.dig("floor", "minimum") - ids = (manifest.fetch("capabilities") + manifest.fetch("workarounds")).map { |entry| entry.fetch("id") } + ids = + (manifest.fetch("capabilities") + manifest.fetch("workarounds")).map do |entry| + entry.fetch("id") + end assert_equal ids.uniq, ids ids.each { |id| assert_match(/\A[a-z][a-z0-9]*(-[a-z0-9]+)*\z/, id) } end @@ -31,22 +34,24 @@ def test_every_refusal_names_the_error_and_every_flag_is_one_letter assert_equal "LibTmux::UnsupportedFeatureError", entry.error if entry.handling == :refuse assert_includes %i[refuse fallback repair], entry.handling end - (CAPABILITIES + WORKAROUNDS).flat_map(&:commands).each do |command| - command.flags.each { |flag| assert_match(/\A-[A-Za-z]\z/, flag) } - end + (CAPABILITIES + WORKAROUNDS) + .flat_map(&:commands) + .each { |command| command.flags.each { |flag| assert_match(/\A-[A-Za-z]\z/, flag) } } WORKAROUNDS.each { |entry| assert_includes %i[refuse repair], entry.handling } end def test_every_api_name_is_a_public_symbol - names = (CAPABILITIES + WORKAROUNDS).flat_map(&:apis) + - CAPABILITIES.filter_map(&:error) + names = (CAPABILITIES + WORKAROUNDS).flat_map(&:apis) + CAPABILITIES.filter_map(&:error) names.each do |name| owner, separator, method = name.partition(/[#.]/) constant = Object.const_get(owner) case separator - when "#" then assert constant.public_method_defined?(method), name - when "." then assert constant.respond_to?(method), name - else assert_kind_of Module, constant, name + when "#" + assert constant.public_method_defined?(method), name + when "." + assert constant.respond_to?(method), name + else + assert_kind_of Module, constant, name end end end @@ -64,9 +69,9 @@ def test_a_record_that_names_one_command_channel_names_its_twins # for the control channels. records = CAPABILITIES + REGISTRY::WORKAROUNDS [REGISTRY::RUN_CHANNELS, REGISTRY::CONTROL_CHANNELS].each do |channels| - records.select { |entry| (entry.apis & channels).any? }.each do |entry| - assert_empty channels - entry.apis, entry.id - end + records + .select { |entry| (entry.apis & channels).any? } + .each { |entry| assert_empty channels - entry.apis, entry.id } end assert records.any? { |entry| (entry.apis & REGISTRY::RUN_CHANNELS).any? } end diff --git a/test/unit/changelog_test.rb b/test/unit/changelog_test.rb index 30bc8938..428403ec 100644 --- a/test/unit/changelog_test.rb +++ b/test/unit/changelog_test.rb @@ -21,10 +21,18 @@ def shortfalls(root) lines = outside_fences(File.read(path)) problems = [] - problems << "#{name}: does not open with its own name" unless lines.include?("Notable changes to `#{name}`.") - problems << "#{name}: has no unreleased section" unless lines.any? { |line| line.match?(/\A## \S+ \(unreleased\)\z/) } - problems << "#{name}: gemspec does not ship CHANGELOG.md" unless spec_files(File.join(directory, "#{name}.gemspec")).include?("CHANGELOG.md") - problems << "#{name}: README does not link CHANGELOG.md" unless File.read(File.join(directory, "README.md")).include?("](CHANGELOG.md)") + unless lines.include?("Notable changes to `#{name}`.") + problems << "#{name}: does not open with its own name" + end + unless lines.any? { |line| line.match?(/\A## \S+ \(unreleased\)\z/) } + problems << "#{name}: has no unreleased section" + end + unless spec_files(File.join(directory, "#{name}.gemspec")).include?("CHANGELOG.md") + problems << "#{name}: gemspec does not ship CHANGELOG.md" + end + unless File.read(File.join(directory, "README.md")).include?("](CHANGELOG.md)") + problems << "#{name}: README does not link CHANGELOG.md" + end problems end end @@ -40,11 +48,13 @@ def spec_files(path) def outside_fences(text) fenced = false - text.lines(chomp: true).reject do |line| - toggled = line.match?(/\A {0,3}(```|~~~)/) - fenced = !fenced if toggled - toggled || fenced - end + text + .lines(chomp: true) + .reject do |line| + toggled = line.match?(/\A {0,3}(```|~~~)/) + fenced = !fenced if toggled + toggled || fenced + end end def test_every_gem_keeps_a_changelog_it_ships_and_links @@ -60,7 +70,10 @@ def test_a_gem_without_a_changelog_is_reported def test_another_gems_changelog_is_reported with_copy do |root| - FileUtils.cp(File.join(root, "gems/libtmux/CHANGELOG.md"), File.join(root, "gems/libtmux-mcp/CHANGELOG.md")) + FileUtils.cp( + File.join(root, "gems/libtmux/CHANGELOG.md"), + File.join(root, "gems/libtmux-mcp/CHANGELOG.md") + ) assert_equal ["libtmux-mcp: does not open with its own name"], shortfalls(root) end end @@ -70,7 +83,10 @@ def test_a_changelog_without_an_unreleased_section_is_reported path = File.join(root, "gems/libtmux-async/CHANGELOG.md") File.write(path, File.read(path).sub(/^## \S+ \(unreleased\)$/, "## 9.9.9 (2026-01-01)")) assert_equal ["libtmux-async: has no unreleased section"], shortfalls(root) - File.write(path, "Notable changes to `libtmux-async`.\n\n```markdown\n## 0.1.2 (unreleased)\n```\n") + File.write( + path, + "Notable changes to `libtmux-async`.\n\n```markdown\n## 0.1.2 (unreleased)\n```\n" + ) assert_equal ["libtmux-async: has no unreleased section"], shortfalls(root) end end @@ -78,7 +94,7 @@ def test_a_changelog_without_an_unreleased_section_is_reported def test_a_gemspec_that_stops_shipping_the_changelog_is_reported with_copy do |root| path = File.join(root, "gems/libtmux-workspace/libtmux-workspace.gemspec") - File.write(path, File.read(path).sub("LICENSE README.md CHANGELOG.md", "LICENSE README.md")) + File.open(path, "a") { |file| file.puts '.tap { |spec| spec.files -= ["CHANGELOG.md"] }' } assert_equal ["libtmux-workspace: gemspec does not ship CHANGELOG.md"], shortfalls(root) end end @@ -101,7 +117,9 @@ def with_copy %W[CHANGELOG.md README.md #{name}.gemspec].each do |file| FileUtils.cp(File.join(ROOT, "gems", name, file), File.join(root, "gems", name, file)) end - FileUtils.cp_r(File.join(ROOT, "gems", name, "lib"), File.join(root, "gems", name, "lib")) if File.directory?(File.join(ROOT, "gems", name, "lib")) + if File.directory?(File.join(ROOT, "gems", name, "lib")) + FileUtils.cp_r(File.join(ROOT, "gems", name, "lib"), File.join(root, "gems", name, "lib")) + end end yield root end diff --git a/test/unit/compatibility_workflow_test.rb b/test/unit/compatibility_workflow_test.rb index 5e403453..06a3cc8f 100644 --- a/test/unit/compatibility_workflow_test.rb +++ b/test/unit/compatibility_workflow_test.rb @@ -12,13 +12,22 @@ # one. Each rule has a mutation that has to be reported. class CompatibilityWorkflowTest < Minitest::Test ROOT = File.expand_path("../..", __dir__) - WORKFLOW = YAML.safe_load_file(File.join(ROOT, ".github/workflows/compatibility.yml"), aliases: false) + WORKFLOW = + YAML.safe_load_file(File.join(ROOT, ".github/workflows/compatibility.yml"), aliases: false) RELEASE = YAML.safe_load_file(File.join(ROOT, ".github/workflows/release.yml"), aliases: false) MANIFEST = CIManifest.load - MATRIX_OUTPUTS = {"cell" => "cells", "unsupported" => "unsupported", "development" => "development"}.freeze - FLAGS = {"release_artifacts" => "release_artifacts", "cell" => "run_cells", "unsupported" => "run_unsupported", - "development" => "run_development"}.freeze + MATRIX_OUTPUTS = { + "cell" => "cells", + "unsupported" => "unsupported", + "development" => "development" + }.freeze + FLAGS = { + "release_artifacts" => "release_artifacts", + "cell" => "run_cells", + "unsupported" => "run_unsupported", + "development" => "run_development" + }.freeze def self.copy(object) Marshal.load(Marshal.dump(object)) @@ -30,10 +39,14 @@ def self.triggers(workflow) def self.strings(object, skip = %w[description]) case object - when Hash then object.flat_map { |key, value| skip.include?(key) ? [] : strings(value, skip) } - when Array then object.flat_map { |value| strings(value, skip) } - when String then [object] - else [] + when Hash + object.flat_map { |key, value| skip.include?(key) ? [] : strings(value, skip) } + when Array + object.flat_map { |value| strings(value, skip) } + when String + [object] + else + [] end end @@ -50,7 +63,10 @@ def self.field_problems(workflow) result = CIPlan.plan(MANIFEST, event: "workflow_dispatch", scope: "full") MATRIX_OUTPUTS.flat_map do |job, output| emitted = result.fetch(output).flat_map(&:keys).uniq - read = strings(workflow.fetch("jobs").fetch(job)).flat_map { |text| text.scan(/matrix\.(\w+)/).flatten }.uniq + read = + strings(workflow.fetch("jobs").fetch(job)) + .flat_map { |text| text.scan(/matrix\.(\w+)/).flatten } + .uniq (read - emitted).map { |field| "#{job}: reads matrix.#{field}, which the plan does not emit" } end end @@ -58,70 +74,121 @@ def self.field_problems(workflow) def self.problems(workflow, release) found = field_problems(workflow) jobs = workflow.fetch("jobs") - names = CIManifest.supported(MANIFEST) + CIManifest.unsupported(MANIFEST) + MANIFEST.fetch("development").map { |entry| entry.fetch("tmux") } + names = + CIManifest.supported(MANIFEST) + CIManifest.unsupported(MANIFEST) + + MANIFEST.fetch("development").map { |entry| entry.fetch("tmux") } strings(workflow).each do |text| names.each do |name| - found << "the workflow names tmux #{name}, which only the manifest may" if text.match?(/(?(job) { chain.fetch(job).include?(name) || chain.fetch(job).any? { |parent| chain.key?(parent) && reaches.call(parent) } } + reaches = ->(job) do + chain.fetch(job).include?(name) || + chain.fetch(job).any? { |parent| chain.key?(parent) && reaches.call(parent) } + end (release.fetch("jobs").keys - [name]).each do |job| found << "release: #{job} must wait for the full compatibility run" unless reaches.call(job) end @@ -139,22 +206,50 @@ def self.build_problems(workflow) jobs = workflow.fetch("jobs") jobs.each do |name, job| steps_of(job).each do |step| - found << "#{name}: builds tmux in a run script; use #{BUILD_ACTION}" if step["run"].to_s.match?(%r{\./configure|\bmake\b|autogen\.sh}) + if step["run"].to_s.match?(%r{\./configure|\bmake\b|autogen\.sh}) + found << "#{name}: builds tmux in a run script; use #{BUILD_ACTION}" + end uses = step["uses"].to_s - found << "#{name}: #{BUILD_ACTION} must be pinned to a full commit SHA" if uses.start_with?("#{BUILD_ACTION}@") && !uses.match?(/@[0-9a-f]{40}\z/) + if uses.start_with?("#{BUILD_ACTION}@") && !uses.match?(/@[0-9a-f]{40}\z/) + found << "#{name}: #{BUILD_ACTION} must be pinned to a full commit SHA" + end end end BUILDING_JOBS.each do |name| - found << "#{name}: must build tmux with #{BUILD_ACTION}" unless steps_of(jobs.fetch(name)).any? { |step| step["uses"].to_s.start_with?("#{BUILD_ACTION}@") } + unless steps_of(jobs.fetch(name)).any? { |step| + step["uses"].to_s.start_with?("#{BUILD_ACTION}@") + } + found << "#{name}: must build tmux with #{BUILD_ACTION}" + end end found end BUILD_MUTATIONS = { - "a job builds tmux by hand again" => [->(w, _r) { w["jobs"]["cell"]["steps"] << {"run" => "./configure --prefix=/tmp/tmux && make install"} }, "cell: builds tmux in a run script"], - "a job runs autogen itself" => [->(w, _r) { w["jobs"]["development"]["steps"] << {"run" => "sh autogen.sh"} }, "development: builds tmux in a run script"], - "a job stops using the action" => [->(w, _r) { w["jobs"]["unsupported"]["steps"].reject! { |s| s["uses"].to_s.start_with?(BUILD_ACTION) } }, "unsupported: must build tmux with"], - "the action is pinned to a branch" => [->(w, _r) { w["jobs"]["cell"]["steps"].each { |s| s["uses"] = "#{BUILD_ACTION}@main" if s["uses"].to_s.start_with?(BUILD_ACTION) } }, "must be pinned to a full commit SHA"] + "a job builds tmux by hand again" => [ + ->(w, _r) do + w["jobs"]["cell"]["steps"] << { "run" => "./configure --prefix=/tmp/tmux && make install" } + end, + "cell: builds tmux in a run script" + ], + "a job runs autogen itself" => [ + ->(w, _r) { w["jobs"]["development"]["steps"] << { "run" => "sh autogen.sh" } }, + "development: builds tmux in a run script" + ], + "a job stops using the action" => [ + ->(w, _r) do + w["jobs"]["unsupported"]["steps"].reject! { |s| s["uses"].to_s.start_with?(BUILD_ACTION) } + end, + "unsupported: must build tmux with" + ], + "the action is pinned to a branch" => [ + ->(w, _r) do + w["jobs"]["cell"]["steps"].each do |s| + s["uses"] = "#{BUILD_ACTION}@main" if s["uses"].to_s.start_with?(BUILD_ACTION) + end + end, + "must be pinned to a full commit SHA" + ] }.freeze def test_every_tmux_build_comes_from_the_shared_action @@ -165,7 +260,8 @@ def test_a_build_mutation_is_reported BUILD_MUTATIONS.each do |description, (mutation, message)| workflow, = mutate(&mutation) problems = self.class.build_problems(workflow) - assert problems.any? { |problem| problem.include?(message) }, "#{description}: #{message} not in #{problems.inspect}" + assert problems.any? { |problem| problem.include?(message) }, + "#{description}: #{message} not in #{problems.inspect}" end end @@ -178,25 +274,47 @@ def self.session_problems(workflow, release) jobs = workflow.fetch("jobs") jobs.each do |name, job| sessions = steps_of(job).select { |step| step["uses"].to_s.start_with?(TMATE) } - found << "#{name}: a debugging session belongs only in the test jobs" if !sessions.empty? && !TEST_JOBS.include?(name) + if !sessions.empty? && !TEST_JOBS.include?(name) + found << "#{name}: a debugging session belongs only in the test jobs" + end next unless TEST_JOBS.include?(name) - found << "#{name}: must offer a session before the tests and one after a failure" unless sessions.length == 2 + unless sessions.length == 2 + found << "#{name}: must offer a session before the tests and one after a failure" + end sessions.each do |step| - found << "a debugging session must be pinned to a full commit SHA" unless step["uses"].match?(/\A#{TMATE}@[0-9a-f]{40}\z/) - found << "a debugging session must be limited to the actor" unless step.dig("with", "limit-access-to-actor") == true - found << "a debugging session needs its own time limit" unless step["timeout-minutes"].is_a?(Integer) - found << "a debugging session runs only on a dispatch, on the job the plan chose" unless - step["if"].to_s.include?("github.event_name == 'workflow_dispatch'") && step["if"].to_s.include?("matrix.tmate ==") + unless step["uses"].match?(/\A#{TMATE}@[0-9a-f]{40}\z/) + found << "a debugging session must be pinned to a full commit SHA" + end + unless step.dig("with", "limit-access-to-actor") == true + found << "a debugging session must be limited to the actor" + end + unless step["timeout-minutes"].is_a?(Integer) + found << "a debugging session needs its own time limit" + end + unless step["if"].to_s.include?("github.event_name == 'workflow_dispatch'") && + step["if"].to_s.include?("matrix.tmate ==") + found << "a debugging session runs only on a dispatch, on the job the plan chose" + end + end + unless job["timeout-minutes"].to_s.match?( + /\A\$\{\{ matrix\.tmate == 'off' && \d+ \|\| \d+ \}\}\z/ + ) + found << "#{name}: the job must cap its time and give the debugging job more" end - found << "#{name}: the job must cap its time and give the debugging job more" unless job["timeout-minutes"].to_s.match?(/\A\$\{\{ matrix\.tmate == 'off' && \d+ \|\| \d+ \}\}\z/) end inputs = triggers(workflow).dig("workflow_dispatch", "inputs") - found << "the tmate input must offer exactly the plan's modes and default to off" unless - inputs.dig("tmate", "options") == CIPlan::TMATE_MODES && inputs.dig("tmate", "default") == "off" + unless inputs.dig("tmate", "options") == CIPlan::TMATE_MODES && + inputs.dig("tmate", "default") == "off" + found << "the tmate input must offer exactly the plan's modes and default to off" + end plan_env = steps_of(jobs.fetch("plan")).filter_map { |step| step["env"] }.reduce({}, :merge) - found << "plan: must pass the tmate input through env" unless plan_env["TMATE"] == "${{ inputs.tmate }}" - found << "release: a release never opens a debugging session" if strings(release).any? { |text| text.include?(TMATE) } + unless plan_env["TMATE"] == "${{ inputs.tmate }}" + found << "plan: must pass the tmate input through env" + end + if strings(release).any? { |text| text.include?(TMATE) } + found << "release: a release never opens a debugging session" + end found end @@ -217,51 +335,253 @@ def test_the_workflows_follow_the_plan end MUTATIONS = { - "a tmux version returns to the workflow" => [->(w, _r) { w["jobs"]["cell"]["env"]["PINNED"] = "3.6" }, "names tmux 3.6"], - "the development commit returns to the workflow" => [->(w, _r) { w["jobs"]["development"]["env"]["REF"] = "next-3.9" }, "names tmux next-3.9"], - "a job reads a field the plan does not emit" => [->(w, _r) { w["jobs"]["cell"]["env"]["RUNNER"] = "${{ matrix.platform.runner }}" }, "cell: reads matrix.platform"], - "a matrix is listed again" => [->(w, _r) { w["jobs"]["cell"]["strategy"]["matrix"] = {"ruby" => ["4.0.7"]} }, "the matrix must come from the plan"], - "a matrix reads another output" => [->(w, _r) { w["jobs"]["unsupported"]["strategy"]["matrix"] = "${{ fromJSON(needs.plan.outputs.cells) }}" }, "unsupported: the matrix must come from the plan"], - "a job runs on a fixed image" => [->(w, _r) { w["jobs"]["cell"]["runs-on"] = "ubuntu-24.04" }, "must run on the image the plan chose"], - "a job stops waiting for the plan" => [->(w, _r) { w["jobs"]["development"].delete("needs") }, "development: must wait for the plan"], - "a job runs on an event instead of the plan" => [->(w, _r) { w["jobs"]["release_artifacts"]["if"] = "github.event_name != 'workflow_dispatch'" }, "release_artifacts: runs when the plan says so"], - "a job runs when another flag says so" => [->(w, _r) { w["jobs"]["unsupported"]["if"] = "needs.plan.outputs.run_cells == 'true'" }, "unsupported: runs when the plan says so"], - "the report is renamed" => [->(w, _r) { w["jobs"]["report"]["name"] = "Report" }, "keeps its name"], - "the report is skipped after a failure" => [->(w, _r) { w["jobs"]["report"].delete("if") }, "must run when a job it waits for failed"], - "the report forgets a job" => [->(w, _r) { w["jobs"]["report"]["needs"] -= ["development"] }, "must wait for every other job"], - "a job is added that the report does not wait for" => [->(w, _r) { w["jobs"]["extra"] = {"runs-on" => "ubuntu-24.04", "steps" => []} }, "must wait for every other job"], - "the report stops verifying the plan" => [->(w, _r) { w["jobs"]["report"]["steps"].reject! { |s| s["run"].to_s.include?("ci-plan verify") } }, "must verify the needs context"], - "the report requires every cell again" => [->(w, _r) { w["jobs"]["report"]["steps"].find { |s| s["run"].to_s.include?("matrix --merge") }["run"].sub!(' --only "$CELLS"', "") }, "must require the planned cells"], - "a dispatch shares its group with the push" => [->(w, _r) { w["concurrency"]["group"] = w["concurrency"]["group"].sub("inputs.scope && github.run_id || ", "") }, "must have its own concurrency group"], - "a pull request shares one group with every other" => [->(w, _r) { w["concurrency"]["group"] = w["concurrency"]["group"].sub("github.event_name == 'pull_request' && github.ref || ", "") }, "must keep their groups"], - "every run cancels its predecessor" => [->(w, _r) { w["concurrency"]["cancel-in-progress"] = true }, "only a pull request may cancel"], - "an input is dropped from the dispatch" => [->(w, _r) { CompatibilityWorkflowTest.triggers(w)["workflow_dispatch"]["inputs"].delete("ruby") }, "the dispatch inputs are not the plan's"], - "the scope input defaults to full" => [->(w, _r) { CompatibilityWorkflowTest.triggers(w)["workflow_dispatch"]["inputs"]["scope"]["default"] = "full" }, "default to edges"], - "the scope input offers another scope" => [->(w, _r) { CompatibilityWorkflowTest.triggers(w)["workflow_dispatch"]["inputs"]["scope"]["options"] = %w[edges full] }, "the plan's scopes"], - "the os input offers macOS" => [->(w, _r) { CompatibilityWorkflowTest.triggers(w)["workflow_dispatch"]["inputs"]["os"]["options"] << "macos-15" }, "the plan's runner images"], - "the workflow_call scope is optional" => [->(w, _r) { CompatibilityWorkflowTest.triggers(w)["workflow_call"]["inputs"]["scope"]["required"] = false }, "scope input must be required"], - "an input stops reaching the plan" => [->(w, _r) { w["jobs"]["plan"]["steps"].each { |s| s["env"]&.delete("RUBY") } }, "plan: the ruby input must reach the plan"], - "an input is used inline in a script" => [->(w, _r) { w["jobs"]["plan"]["steps"].last["run"] = 'ruby scripts/ci-plan/ci-plan plan --ruby "${{ inputs.ruby }}"' }, "only through env"], - "a macOS runner is added" => [->(w, _r) { w["jobs"]["extra"] = {"runs-on" => "macos-15"} }, "must not run on macOS"], - "the release stops calling compatibility" => [->(_w, r) { r["jobs"]["compatibility"]["uses"] = "./.github/workflows/docs.yml" }, "a job must call compatibility.yml"], - "the release asks for the edges" => [->(_w, r) { r["jobs"]["compatibility"]["with"]["scope"] = "edges" }, "must ask for scope full"], - "the release prepares without waiting" => [->(_w, r) { r["jobs"]["prepare"].delete("needs") }, "prepare must wait for the full compatibility run"], - "the upload skips the preparation" => [->(_w, r) { r["jobs"]["publish"]["needs"] = [] }, "publish must wait for the full compatibility run"] + "a tmux version returns to the workflow" => [ + ->(w, _r) { w["jobs"]["cell"]["env"]["PINNED"] = "3.6" }, + "names tmux 3.6" + ], + "the development commit returns to the workflow" => [ + ->(w, _r) { w["jobs"]["development"]["env"]["REF"] = "next-3.9" }, + "names tmux next-3.9" + ], + "a job reads a field the plan does not emit" => [ + ->(w, _r) { w["jobs"]["cell"]["env"]["RUNNER"] = "${{ matrix.platform.runner }}" }, + "cell: reads matrix.platform" + ], + "a matrix is listed again" => [ + ->(w, _r) { w["jobs"]["cell"]["strategy"]["matrix"] = { "ruby" => ["4.0.7"] } }, + "the matrix must come from the plan" + ], + "a matrix reads another output" => [ + ->(w, _r) do + w["jobs"]["unsupported"]["strategy"]["matrix"] = "${{ fromJSON(needs.plan.outputs.cells) }}" + end, + "unsupported: the matrix must come from the plan" + ], + "a job runs on a fixed image" => [ + ->(w, _r) { w["jobs"]["cell"]["runs-on"] = "ubuntu-24.04" }, + "must run on the image the plan chose" + ], + "a job stops waiting for the plan" => [ + ->(w, _r) { w["jobs"]["development"].delete("needs") }, + "development: must wait for the plan" + ], + "a job runs on an event instead of the plan" => [ + ->(w, _r) do + w["jobs"]["release_artifacts"]["if"] = "github.event_name != 'workflow_dispatch'" + end, + "release_artifacts: runs when the plan says so" + ], + "a job runs when another flag says so" => [ + ->(w, _r) { w["jobs"]["unsupported"]["if"] = "needs.plan.outputs.run_cells == 'true'" }, + "unsupported: runs when the plan says so" + ], + "the report is renamed" => [ + ->(w, _r) { w["jobs"]["report"]["name"] = "Report" }, + "keeps its name" + ], + "the report is skipped after a failure" => [ + ->(w, _r) { w["jobs"]["report"].delete("if") }, + "must run when a job it waits for failed" + ], + "the report forgets a job" => [ + ->(w, _r) { w["jobs"]["report"]["needs"] -= ["development"] }, + "must wait for every other job" + ], + "a job is added that the report does not wait for" => [ + ->(w, _r) { w["jobs"]["extra"] = { "runs-on" => "ubuntu-24.04", "steps" => [] } }, + "must wait for every other job" + ], + "the report stops verifying the plan" => [ + ->(w, _r) do + w["jobs"]["report"]["steps"].reject! { |s| s["run"].to_s.include?("ci-plan verify") } + end, + "must verify the needs context" + ], + "the report requires every cell again" => [ + ->(w, _r) do + w["jobs"]["report"]["steps"].find { |s| s["run"].to_s.include?("matrix --merge") }[ + "run" + ].sub!(' --only "$CELLS"', "") + end, + "must require the planned cells" + ], + "a dispatch shares its group with the push" => [ + ->(w, _r) do + w["concurrency"]["group"] = w["concurrency"]["group"].sub( + "inputs.scope && github.run_id || ", + "" + ) + end, + "must have its own concurrency group" + ], + "a pull request shares one group with every other" => [ + ->(w, _r) do + w["concurrency"]["group"] = w["concurrency"]["group"].sub( + "github.event_name == 'pull_request' && github.ref || ", + "" + ) + end, + "must keep their groups" + ], + "every run cancels its predecessor" => [ + ->(w, _r) { w["concurrency"]["cancel-in-progress"] = true }, + "only a pull request may cancel" + ], + "an input is dropped from the dispatch" => [ + ->(w, _r) do + CompatibilityWorkflowTest.triggers(w)["workflow_dispatch"]["inputs"].delete("ruby") + end, + "the dispatch inputs are not the plan's" + ], + "the scope input defaults to full" => [ + ->(w, _r) do + CompatibilityWorkflowTest.triggers(w)["workflow_dispatch"]["inputs"]["scope"][ + "default" + ] = "full" + end, + "default to edges" + ], + "the scope input offers another scope" => [ + ->(w, _r) do + CompatibilityWorkflowTest.triggers(w)["workflow_dispatch"]["inputs"]["scope"][ + "options" + ] = %w[edges full] + end, + "the plan's scopes" + ], + "the os input offers macOS" => [ + ->(w, _r) do + CompatibilityWorkflowTest.triggers(w)["workflow_dispatch"]["inputs"]["os"][ + "options" + ] << "macos-15" + end, + "the plan's runner images" + ], + "the workflow_call scope is optional" => [ + ->(w, _r) do + CompatibilityWorkflowTest.triggers(w)["workflow_call"]["inputs"]["scope"][ + "required" + ] = false + end, + "scope input must be required" + ], + "an input stops reaching the plan" => [ + ->(w, _r) { w["jobs"]["plan"]["steps"].each { |s| s["env"]&.delete("RUBY") } }, + "plan: the ruby input must reach the plan" + ], + "an input is used inline in a script" => [ + ->(w, _r) do + w["jobs"]["plan"]["steps"].last[ + "run" + ] = 'ruby scripts/ci-plan/ci-plan plan --ruby "${{ inputs.ruby }}"' + end, + "only through env" + ], + "a macOS runner is added" => [ + ->(w, _r) { w["jobs"]["extra"] = { "runs-on" => "macos-15" } }, + "must not run on macOS" + ], + "the release stops calling compatibility" => [ + ->(_w, r) { r["jobs"]["compatibility"]["uses"] = "./.github/workflows/docs.yml" }, + "a job must call compatibility.yml" + ], + "the release asks for the edges" => [ + ->(_w, r) { r["jobs"]["compatibility"]["with"]["scope"] = "edges" }, + "must ask for scope full" + ], + "the release prepares without waiting" => [ + ->(_w, r) { r["jobs"]["prepare"].delete("needs") }, + "prepare must wait for the full compatibility run" + ], + "the upload skips the preparation" => [ + ->(_w, r) { r["jobs"]["publish"]["needs"] = [] }, + "publish must wait for the full compatibility run" + ] }.freeze SESSION_MUTATIONS = { - "the session is not pinned to a commit" => [->(w, _r) { w["jobs"]["cell"]["steps"].each { |s| s["uses"] = "#{TMATE}@v3" if s["uses"].to_s.start_with?(TMATE) } }, "pinned to a full commit SHA"], - "the session is open to every collaborator" => [->(w, _r) { w["jobs"]["cell"]["steps"].each { |s| s["with"]["limit-access-to-actor"] = false if s["uses"].to_s.start_with?(TMATE) } }, "limited to the actor"], - "the session has no time limit of its own" => [->(w, _r) { w["jobs"]["development"]["steps"].each { |s| s.delete("timeout-minutes") if s["uses"].to_s.start_with?(TMATE) } }, "its own time limit"], - "the session runs on every event" => [->(w, _r) { w["jobs"]["unsupported"]["steps"].each { |s| s["if"] = "${{ matrix.tmate == 'before-tests' }}" if s["uses"].to_s.start_with?(TMATE) } }, "only on a dispatch"], - "the session runs on every job" => [->(w, _r) { w["jobs"]["cell"]["steps"].each { |s| s["if"] = "${{ github.event_name == 'workflow_dispatch' }}" if s["uses"].to_s.start_with?(TMATE) } }, "on the job the plan chose"], - "the session moves to the report" => [->(w, _r) { w["jobs"]["report"]["steps"] << {"uses" => "#{TMATE}@#{'a' * 40}"} }, "report: a debugging session belongs only in the test jobs"], - "a test job drops one session" => [->(w, _r) { w["jobs"]["cell"]["steps"].reject! { |s| s["name"] == "Open a tmate session after a failure" } }, "cell: must offer a session before the tests"], - "a test job's time ignores the session" => [->(w, _r) { w["jobs"]["unsupported"]["timeout-minutes"] = 10 }, "give the debugging job more"], - "the tmate input offers another mode" => [->(w, _r) { CompatibilityWorkflowTest.triggers(w)["workflow_dispatch"]["inputs"]["tmate"]["options"] = %w[off always] }, "the plan's modes"], - "the tmate input defaults to a session" => [->(w, _r) { CompatibilityWorkflowTest.triggers(w)["workflow_dispatch"]["inputs"]["tmate"]["default"] = "before-tests" }, "default to off"], - "the plan stops hearing the tmate input" => [->(w, _r) { w["jobs"]["plan"]["steps"].each { |s| s["env"]&.delete("TMATE") } }, "must pass the tmate input"], - "a session returns to the release" => [->(_w, r) { r["jobs"]["publish"]["steps"] << {"uses" => "#{TMATE}@#{'a' * 40}"} }, "a release never opens a debugging session"] + "the session is not pinned to a commit" => [ + ->(w, _r) do + w["jobs"]["cell"]["steps"].each do |s| + s["uses"] = "#{TMATE}@v3" if s["uses"].to_s.start_with?(TMATE) + end + end, + "pinned to a full commit SHA" + ], + "the session is open to every collaborator" => [ + ->(w, _r) do + w["jobs"]["cell"]["steps"].each do |s| + s["with"]["limit-access-to-actor"] = false if s["uses"].to_s.start_with?(TMATE) + end + end, + "limited to the actor" + ], + "the session has no time limit of its own" => [ + ->(w, _r) do + w["jobs"]["development"]["steps"].each do |s| + s.delete("timeout-minutes") if s["uses"].to_s.start_with?(TMATE) + end + end, + "its own time limit" + ], + "the session runs on every event" => [ + ->(w, _r) do + w["jobs"]["unsupported"]["steps"].each do |s| + s["if"] = "${{ matrix.tmate == 'before-tests' }}" if s["uses"].to_s.start_with?(TMATE) + end + end, + "only on a dispatch" + ], + "the session runs on every job" => [ + ->(w, _r) do + w["jobs"]["cell"]["steps"].each do |s| + s["if"] = "${{ github.event_name == 'workflow_dispatch' }}" if s["uses"].to_s.start_with?( + TMATE + ) + end + end, + "on the job the plan chose" + ], + "the session moves to the report" => [ + ->(w, _r) { w["jobs"]["report"]["steps"] << { "uses" => "#{TMATE}@#{"a" * 40}" } }, + "report: a debugging session belongs only in the test jobs" + ], + "a test job drops one session" => [ + ->(w, _r) do + w["jobs"]["cell"]["steps"].reject! do |s| + s["name"] == "Open a tmate session after a failure" + end + end, + "cell: must offer a session before the tests" + ], + "a test job's time ignores the session" => [ + ->(w, _r) { w["jobs"]["unsupported"]["timeout-minutes"] = 10 }, + "give the debugging job more" + ], + "the tmate input offers another mode" => [ + ->(w, _r) do + CompatibilityWorkflowTest.triggers(w)["workflow_dispatch"]["inputs"]["tmate"][ + "options" + ] = %w[off always] + end, + "the plan's modes" + ], + "the tmate input defaults to a session" => [ + ->(w, _r) do + CompatibilityWorkflowTest.triggers(w)["workflow_dispatch"]["inputs"]["tmate"][ + "default" + ] = "before-tests" + end, + "default to off" + ], + "the plan stops hearing the tmate input" => [ + ->(w, _r) { w["jobs"]["plan"]["steps"].each { |s| s["env"]&.delete("TMATE") } }, + "must pass the tmate input" + ], + "a session returns to the release" => [ + ->(_w, r) { r["jobs"]["publish"]["steps"] << { "uses" => "#{TMATE}@#{"a" * 40}" } }, + "a release never opens a debugging session" + ] }.freeze def test_the_debugging_session_is_safe @@ -280,7 +600,8 @@ def test_a_session_mutation_is_reported SESSION_MUTATIONS.each do |description, (mutation, message)| workflow, release = mutate(&mutation) problems = self.class.session_problems(workflow, release) - assert problems.any? { |problem| problem.include?(message) }, "#{description}: #{message} not in #{problems.inspect}" + assert problems.any? { |problem| problem.include?(message) }, + "#{description}: #{message} not in #{problems.inspect}" end end @@ -288,21 +609,29 @@ def test_a_mutation_is_reported MUTATIONS.each do |description, (mutation, message)| workflow, release = mutate(&mutation) problems = self.class.problems(workflow, release) - assert problems.any? { |problem| problem.include?(message) }, "#{description}: #{message} not in #{problems.inspect}" + assert problems.any? { |problem| problem.include?(message) }, + "#{description}: #{message} not in #{problems.inspect}" end end def test_the_unsupported_job_selects_its_test_through_the_version_check_script job = WORKFLOW.fetch("jobs").fetch("unsupported") runs = job.fetch("steps").map { |step| step["run"] }.compact - assert_includes runs, %(bundle exec scripts/version-check/version-check "$VERSION_CHECK" "$TMUX_VERSION") + assert_includes runs, + %(bundle exec scripts/version-check/version-check "$VERSION_CHECK" "$TMUX_VERSION") assert_equal "${{ matrix.check }}", job.fetch("env").fetch("VERSION_CHECK") assert_equal "${{ matrix.tmux }}", job.fetch("env").fetch("TMUX_VERSION") end def test_supported_cells_and_the_development_build_name_their_lane %w[cell development].each do |name| - assert_equal "supported", WORKFLOW.fetch("jobs").fetch(name).fetch("env").fetch("LIBTMUX_VERSION_CHECK_EXPECT"), name + assert_equal "supported", + WORKFLOW + .fetch("jobs") + .fetch(name) + .fetch("env") + .fetch("LIBTMUX_VERSION_CHECK_EXPECT"), + name end end @@ -317,10 +646,13 @@ def test_no_job_runs_on_macos def test_the_cell_names_follow_the_plan result = CIPlan.plan(MANIFEST, event: "workflow_dispatch", scope: "full") template = WORKFLOW.fetch("jobs").fetch("cell").fetch("name") - names = result.fetch("cells").map do |cell| - template.gsub(/\$\{\{ matrix\.(\w+) \}\}/) { cell.fetch(Regexp.last_match(1)) } - end - expected = CIPlan.job_names(result).grep(/\Alinux \//) + names = + result + .fetch("cells") + .map do |cell| + template.gsub(/\$\{\{ matrix\.(\w+) \}\}/) { cell.fetch(Regexp.last_match(1)) } + end + expected = CIPlan.job_names(result).grep(%r{\Alinux /}) assert_equal expected.sort, names.sort end @@ -338,10 +670,16 @@ def test_the_release_retry_step_runs_the_tested_script_and_no_gh_call restore = steps.find { |step| step["id"] == "restore" } refute_nil restore assert_equal "bundle exec scripts/release/release-ci restore pkg/release", restore.fetch("run") - RELEASE.fetch("jobs").each_value do |job| - job.fetch("steps", []).each { |step| refute_match(/\bgh\s/, step["run"].to_s) } - end - gate = steps.find { |step| step.dig("with", "name") == ReleaseCI::ARTIFACT && step["uses"].to_s.start_with?("actions/upload-artifact@") } + RELEASE + .fetch("jobs") + .each_value do |job| + job.fetch("steps", []).each { |step| refute_match(/\bgh\s/, step["run"].to_s) } + end + gate = + steps.find do |step| + step.dig("with", "name") == ReleaseCI::ARTIFACT && + step["uses"].to_s.start_with?("actions/upload-artifact@") + end assert_equal "steps.restore.outputs.retained != 'true'", gate.fetch("if") end diff --git a/test/unit/control_test.rb b/test/unit/control_test.rb index 893a7db4..e7b3a839 100644 --- a/test/unit/control_test.rb +++ b/test/unit/control_test.rb @@ -6,7 +6,8 @@ class ControlTest < Minitest::Test def test_incremental_guard_body_stays_bytes_and_protocol_looking_payload_is_data parser = LibTmux::Internal::ControlParser.new(max_line_bytes: 256, max_frame_bytes: 1024) - wire = "%begin 7 2 1\n%output %1 fake\n%end 7 99 1\n\xff\n%end 7 2 1\n%output %1 a\\000\\377\\134\n".b + wire = + "%begin 7 2 1\n%output %1 fake\n%end 7 99 1\n\xff\n%end 7 2 1\n%output %1 a\\000\\377\\134\n".b records = [] wire.each_byte { |byte| parser.feed(byte.chr.b) { |record| records << record } } parser.finish @@ -26,19 +27,23 @@ def test_incremental_guard_body_stays_bytes_and_protocol_looking_payload_is_data def test_extended_output_preserves_unknown_header_fields_and_pause_signals_loss parser = LibTmux::Internal::ControlParser.new records = [] - wire = "%extended-output %2 19 future : a\\303\\251\n%pause %2\n%continue %2\n%new-notification opaque\n".b + wire = + "%extended-output %2 19 future : a\\303\\251\n%pause %2\n%continue %2\n%new-notification opaque\n".b parser.feed(wire) { |record| records << record } assert_equal "a\xc3\xa9".b, records.first.data assert_equal wire.lines.first, records.first.raw - assert_equal [:output, :gap, :gap, :notice], records.map(&:kind) - assert_equal [:pause, :resume], records[1, 2].map(&:reason) - assert_equal ["%2", "%2"], records[1, 2].map(&:pane_id) + assert_equal %i[output gap gap notice], records.map(&:kind) + assert_equal %i[pause resume], records[1, 2].map(&:reason) + assert_equal %w[%2 %2], records[1, 2].map(&:pane_id) assert records[1, 2].all? { |event| event.dropped_bytes.nil? && event.lost_sequences.nil? } stream = LibTmux::ControlSubscription.new(pane_id: "%2") unrelated = LibTmux::ControlSubscription.new(pane_id: "%3") - records.each { |record| stream.send(:publish, record); unrelated.send(:publish, record) } - assert_equal [:output, :gap, :gap], 3.times.map { stream.next(timeout: 0).kind } + records.each do |record| + stream.send(:publish, record) + unrelated.send(:publish, record) + end + assert_equal %i[output gap gap], 3.times.map { stream.next(timeout: 0).kind } assert_raises(LibTmux::DeadlineExceeded) { unrelated.next(timeout: 0) } ensure stream&.close @@ -64,7 +69,8 @@ def test_observed_native_flow_gap_is_not_duplicated_at_the_request_boundary control.instance_variable_get(:@replies) << request parser = LibTmux::Internal::ControlParser.new parser.feed("%pause %0\n") { |record| control.send(:receive, record) } - reply = LibTmux::GuardedReply.new(request_id: request.id, blocks: [], generation: control.generation) + reply = + LibTmux::GuardedReply.new(request_id: request.id, blocks: [], generation: control.generation) control.send(:complete, request, result: reply) gap = control.events.next(timeout: 0) assert_equal :pause, gap.reason @@ -83,16 +89,25 @@ def test_connections_open_only_through_a_server def test_scope_preserves_original_failure_and_attaches_cleanup_diagnostics connection = Object.new - connection.define_singleton_method(:close) { raise LibTmux::TransportError, "cleanup injection" } + connection.define_singleton_method(:close) do + raise LibTmux::TransportError, "cleanup injection" + end factory = Class.new(LibTmux::ControlConnection) factory.define_singleton_method(:new) { |**_| connection } original = RuntimeError.new("original consumer failure") assert_same original, assert_raises(RuntimeError) { factory.__send__(:open) { raise original } } - assert_equal ["control cleanup failed (LibTmux::TransportError)"], original.control_cleanup_errors + assert_equal ["control cleanup failed (LibTmux::TransportError)"], + original.control_cleanup_errors end def test_malformed_or_unbounded_stream_fails_closed - ["%end 1 1 1\n", "%output %1 \\400\n", "%output %1 \\x\n", "%pause invalid\n", "%continue %1 trailing\n"].each do |wire| + [ + "%end 1 1 1\n", + "%output %1 \\400\n", + "%output %1 \\x\n", + "%pause invalid\n", + "%continue %1 trailing\n" + ].each do |wire| parser = LibTmux::Internal::ControlParser.new assert_raises(LibTmux::ProtocolError) { parser.feed(wire) {} } end @@ -108,13 +123,31 @@ def test_malformed_or_unbounded_stream_fails_closed def test_reliable_overflow_preserves_prefix_and_tail_reports_gap reliable = LibTmux::ControlSubscription.new(max_bytes: 100, max_events: 1) tail = LibTmux::ControlSubscription.new(max_bytes: 100, max_events: 1, mode: :tail) - events = (1..3).map { |seq| LibTmux::ControlEvent.new(kind: :notice, raw: "x".b, sequence: seq, generation: "g") } - events.each { |event| reliable.send(:publish, event); tail.send(:publish, event) } + events = + (1..3).map do |seq| + LibTmux::ControlEvent.new(kind: :notice, raw: "x".b, sequence: seq, generation: "g") + end + events.each do |event| + reliable.send(:publish, event) + tail.send(:publish, event) + end assert_respond_to reliable, :diagnostics prefix = reliable.diagnostics - assert_equal({queued_events: 1, retained_event_bytes: 1, gap_pending: false, - overflowed: true, closed: true, mode: :reliable, - limits: {max_bytes: 100, max_events: 1}}, prefix) + assert_equal( + { + queued_events: 1, + retained_event_bytes: 1, + gap_pending: false, + overflowed: true, + closed: true, + mode: :reliable, + limits: { + max_bytes: 100, + max_events: 1 + } + }, + prefix + ) assert prefix.frozen? assert prefix.fetch(:limits).frozen? assert_equal 1, tail.diagnostics.fetch(:queued_events) diff --git a/test/unit/criteria_test.rb b/test/unit/criteria_test.rb index 94b67851..c9407c7e 100644 --- a/test/unit/criteria_test.rb +++ b/test/unit/criteria_test.rb @@ -7,18 +7,24 @@ class CriteriaTest < Minitest::Test # Explicit field/edge coverage lets these cases isolate evaluation from I/O. - Record = Struct.new(:kind, :values, :edges, :coverage) do - private - - def entity_kind = kind - def read_field(name) = values.fetch(name) - def read_relation(name) = edges.fetch(name) - def field_coverage(name) = coverage.fetch(name, values.key?(name) ? :complete : :unloaded) - def relation_coverage(name) = coverage.fetch(name, edges.key?(name) ? :complete : :unloaded) - end + Record = + Struct.new(:kind, :values, :edges, :coverage) do + private + + def entity_kind = kind + def read_field(name) = values.fetch(name) + def read_relation(name) = edges.fetch(name) + def field_coverage(name) = coverage.fetch(name, values.key?(name) ? :complete : :unloaded) + def relation_coverage(name) = coverage.fetch(name, edges.key?(name) ? :complete : :unloaded) + end def pane(**values) - Record.new(:pane, {id: "%1", index: 0, active: false, current_command: "cat"}.merge(values), {}, {}) + Record.new( + :pane, + { id: "%1", index: 0, active: false, current_command: "cat" }.merge(values), + {}, + {} + ) end def panes(*records) @@ -27,11 +33,16 @@ def panes(*records) def test_empty_and_inactive_branches_still_validate_the_entire_schema empty = panes - [nil, {typo: true}, {active: "0"}, {index: 1.0}, {current_command: /cat/}, - {or: [{}, {index: {contains: "1"}}]}, {current_command: {regex: "cat"}}].each do |query| - assert_raises(LibTmux::InvalidFilterError) { empty.where(query) } - end - error = assert_raises(LibTmux::InvalidFilterError) { empty.where(or: [{}, {active: "0"}]) } + [ + nil, + { typo: true }, + { active: "0" }, + { index: 1.0 }, + { current_command: /cat/ }, + { or: [{}, { index: { contains: "1" } }] }, + { current_command: { regex: "cat" } } + ].each { |query| assert_raises(LibTmux::InvalidFilterError) { empty.where(query) } } + error = assert_raises(LibTmux::InvalidFilterError) { empty.where(or: [{}, { active: "0" }]) } assert_equal :pane, error.entity assert_equal "$.or[1].active.equals", error.path refute_match "private-secret", error.message @@ -47,29 +58,38 @@ def test_scalar_boolean_and_cardinality_semantics assert_same a, selection.one(current_command: "nvim") assert_nil selection.one_or_nil(current_command: "missing") assert selection.exists?(active: false) - assert_equal [b], selection.where(index: {gt: 3, lte: 12}).to_a - assert_equal [a], selection.where(current_command: {starts_with: "nv", ends_with: "im", contains: "vi"}).to_a - assert_equal [b], selection.where(index: {not: {in: [1, 2]}}).to_a + assert_equal [b], selection.where(index: { gt: 3, lte: 12 }).to_a + assert_equal [a], + selection.where( + current_command: { + starts_with: "nv", + ends_with: "im", + contains: "vi" + } + ).to_a + assert_equal [b], selection.where(index: { not: { in: [1, 2] } }).to_a assert_equal [a, b], selection.where(and: []).to_a assert_empty selection.where(or: []) assert_empty selection.where(not: {}) - assert_equal [a], selection.where(or: [{active: true}, {index: 99}]).to_a - assert_equal [b], selection.where(not: {active: true}).to_a + assert_equal [a], selection.where(or: [{ active: true }, { index: 99 }]).to_a + assert_equal [b], selection.where(not: { active: true }).to_a assert_raises(LibTmux::MultipleMatchesError) { panes(a, a).one(active: true) } end def test_aliases_are_explicit_and_conflicts_are_rejected a = pane(current_command: "nvim") assert_same a, panes(a).one("currentCommand" => "nvim") - assert_same a, panes(a).one("current_command" => {"startsWith" => "nv"}) + assert_same a, panes(a).one("current_command" => { "startsWith" => "nv" }) assert_raises(LibTmux::InvalidFilterError) do - panes(a).where(current_command: "cat", "currentCommand" => "nvim") + panes(a).where(:current_command => "cat", "currentCommand" => "nvim") + end + assert_raises(LibTmux::InvalidFilterError) do + panes(a).where(current_command: { :starts_with => "a", "startsWith" => "b" }) end - assert_raises(LibTmux::InvalidFilterError) { panes(a).where(current_command: {starts_with: "a", "startsWith" => "b"}) } end def test_immutable_expression_composition_and_callable_protocols - input = {current_command: {in: [+"cat"]}} + input = { current_command: { in: [+"cat"] } } expression = LibTmux::PaneWhere.build(input) input[:current_command][:in].first.replace("mutated") input.clear @@ -88,57 +108,66 @@ def test_immutable_expression_composition_and_callable_protocols def test_correlated_children_and_unmodified_graph_relations a, b = pane(active: true), pane(index: 1, current_command: "nvim") - window = Record.new(:window, {id: "@1"}, {panes: [a, b]}, {}) + window = Record.new(:window, { id: "@1" }, { panes: [a, b] }, {}) windows = LibTmux::Selection.new([window], entity: :window) - assert_empty windows.where(panes: {some: {active: true, current_command: "nvim"}}) - assert_equal [window], windows.where(panes: {some: {active: true}}).where(panes: {some: {current_command: "nvim"}}).to_a + assert_empty windows.where(panes: { some: { active: true, current_command: "nvim" } }) + assert_equal [window], + windows + .where(panes: { some: { active: true } }) + .where(panes: { some: { current_command: "nvim" } }) + .to_a assert_equal [a, b], window.edges[:panes] - empty = Record.new(:window, {}, {panes: []}, {}) + empty = Record.new(:window, {}, { panes: [] }, {}) selection = LibTmux::Selection.new([empty], entity: :window) - assert_empty selection.where(panes: {some: {active: true}}) - assert_equal [empty], selection.where(panes: {every: {active: true}}).to_a - assert_equal [empty], selection.where(panes: {none: {active: true}}).to_a + assert_empty selection.where(panes: { some: { active: true } }) + assert_equal [empty], selection.where(panes: { every: { active: true } }).to_a + assert_equal [empty], selection.where(panes: { none: { active: true } }).to_a end def test_preflight_cannot_hide_missing_evidence_behind_short_circuit a = pane a.coverage[:current_command] = :unsupported - [ {active: true, current_command: "cat"}, {or: [{}, {current_command: "cat"}]}, - {not: {active: true, current_command: "cat"}} ].each do |query| - assert_raises(LibTmux::IncompleteSnapshotError) { panes(a).where(query) } - end + [ + { active: true, current_command: "cat" }, + { or: [{}, { current_command: "cat" }] }, + { not: { active: true, current_command: "cat" } } + ].each { |query| assert_raises(LibTmux::IncompleteSnapshotError) { panes(a).where(query) } } b = pane b.coverage[:active] = :incomplete - window = Record.new(:window, {id: "@1"}, {panes: [pane, b]}, {}) + window = Record.new(:window, { id: "@1" }, { panes: [pane, b] }, {}) selection = LibTmux::Selection.new([window], entity: :window) - assert_raises(LibTmux::IncompleteSnapshotError) { selection.where(panes: {some: {active: false}}) } + assert_raises(LibTmux::IncompleteSnapshotError) do + selection.where(panes: { some: { active: false } }) + end window.coverage[:panes] = :unloaded - error = assert_raises(LibTmux::IncompleteSnapshotError) { selection.where(panes: {none: {}}) } + error = assert_raises(LibTmux::IncompleteSnapshotError) { selection.where(panes: { none: {} }) } assert_equal :window, error.entity assert_equal "$.panes", error.path assert_equal "complete captured relation", error.expected window.coverage[:panes] = :complete window.edges[:panes] = [] - assert_equal [window], selection.where(panes: {none: {active: true}}).to_a + assert_equal [window], selection.where(panes: { none: { active: true } }).to_a end def test_nullable_fields_and_relations_distinguish_absence_from_unloaded - absent, present = pane(dead_status: nil, current_path: nil), pane(dead_status: 0, current_path: "") + absent, present = + pane(dead_status: nil, current_path: nil), + pane(dead_status: 0, current_path: "") assert_equal [absent], panes(absent, present).where(dead_status: nil).to_a - assert_equal [present], panes(absent, present).where(dead_status: {not: nil}).to_a + assert_equal [present], panes(absent, present).where(dead_status: { not: nil }).to_a assert_equal [absent], panes(absent, present).where(current_path: nil).to_a assert_equal [present], panes(absent, present).where(current_path: "").to_a assert_raises(LibTmux::InvalidFilterError) { panes.where(active: nil) } - assert_raises(LibTmux::InvalidFilterError) { panes.where(dead_status: {gt: nil}) } - assert_raises(LibTmux::InvalidFilterError) { panes.where(window: {is: nil}) } - empty = Record.new(:window, {}, {active_pane: nil}, {}) - full = Record.new(:window, {}, {active_pane: pane(active: true)}, {}) + assert_raises(LibTmux::InvalidFilterError) { panes.where(dead_status: { gt: nil }) } + assert_raises(LibTmux::InvalidFilterError) { panes.where(window: { is: nil }) } + empty = Record.new(:window, {}, { active_pane: nil }, {}) + full = Record.new(:window, {}, { active_pane: pane(active: true) }, {}) windows = LibTmux::Selection.new([empty, full], entity: :window) - assert_equal [empty], windows.where(active_pane: {is: nil}).to_a - assert_equal [full], windows.where(active_pane: {is_not: nil}).to_a - assert_equal [empty], windows.where(active_pane: {is_not: {active: true}}).to_a + assert_equal [empty], windows.where(active_pane: { is: nil }).to_a + assert_equal [full], windows.where(active_pane: { is_not: nil }).to_a + assert_equal [empty], windows.where(active_pane: { is_not: { active: true } }).to_a empty.coverage[:active_pane] = :unloaded - assert_raises(LibTmux::IncompleteSnapshotError) { windows.where(active_pane: {is: nil}) } + assert_raises(LibTmux::IncompleteSnapshotError) { windows.where(active_pane: { is: nil }) } end def test_text_is_exact_utf8_and_serialized_values_do_not_mutate_expressions @@ -146,44 +175,77 @@ def test_text_is_exact_utf8_and_serialized_values_do_not_mutate_expressions assert_equal [a], panes(a, b).where(current_command: "é").to_a assert_empty panes(pane(current_command: "NVIM")).where(current_command: "nvim") assert_raises(LibTmux::InvalidFilterError) { panes.where(current_command: "\xff".b) } - expression = LibTmux::PaneWhere.build(current_command: {in: ["cat"]}) + expression = LibTmux::PaneWhere.build(current_command: { in: ["cat"] }) wire = expression.to_h wire.fetch("where").fetch("currentCommand").fetch("in").first.replace("changed") assert expression.call(pane) assert_equal [a], panes(a, b).select { |item| item.equal?(a) }.where(current_command: "é").to_a assert_raises(LibTmux::InvalidFilterError) do - LibTmux::FilterExpr.from_json('{"profile":"libtmux-ruby.where","version":1,"entity":"pane","where":{"active":true,"\\u0061ctive":false}}') + LibTmux::FilterExpr.from_json( + '{"profile":"libtmux-ruby.where","version":1,"entity":"pane","where":{"active":true,"\\u0061ctive":false}}' + ) end - assert_raises(LibTmux::InvalidFilterError) { LibTmux::PaneWhere.build(or: Array.new(2049) { {} }) } - error = assert_raises(LibTmux::InvalidFilterError) { LibTmux::FilterExpr.from_json('{"private-secret":invalid}') } + assert_raises(LibTmux::InvalidFilterError) do + LibTmux::PaneWhere.build(or: Array.new(2049) { {} }) + end + error = + assert_raises(LibTmux::InvalidFilterError) do + LibTmux::FilterExpr.from_json('{"private-secret":invalid}') + end assert_nil error.cause refute_includes error.full_message, "private-secret" end def test_captured_graph_decoding_and_per_record_coverage_preflight - rows = {pane: [ - {id: "%1", window_id: "@1", index: "0", active: "0", title: "private\xff".b}, - {id: "%2", window_id: "@1", index: "1", active: "1", title: "valid"} - ]} - graph = LibTmux::Snapshot.__send__(:new, rows: rows, binding_key: "binding", - started_at: 1.0, finished_at: 2.0, reads: [], server_info: {}) + rows = { + pane: [ + { id: "%1", window_id: "@1", index: "0", active: "0", title: "private\xff".b }, + { id: "%2", window_id: "@1", index: "1", active: "1", title: "valid" } + ] + } + graph = + LibTmux::Snapshot.__send__( + :new, + rows: rows, + binding_key: "binding", + started_at: 1.0, + finished_at: 2.0, + reads: [], + server_info: { + } + ) assert_equal ["%1"], graph.panes.where(index: 0).map(&:id) assert_equal ["%1"], graph.panes.select { |item| item.raw(:title).include?("\xff".b) }.map(&:id) - error = assert_raises(LibTmux::FieldDecodeError) { graph.panes.where(active: true, title: "valid") } + error = + assert_raises(LibTmux::FieldDecodeError) { graph.panes.where(active: true, title: "valid") } assert_equal :pane, error.entity assert_equal "$.title", error.path refute_includes error.message, "private" - assert_raises(LibTmux::IncompleteSnapshotError) { graph.panes.where(index: 99, window: {is: {name: "missing"}}) } - rows[:window] = [{id: "@1"}] - coverage = {pane: {records: {"%2" => {fields: {active: :incomplete}}}}} - partial = LibTmux::Snapshot.__send__(:new, rows: rows, binding_key: "binding", - started_at: 1.0, finished_at: 2.0, reads: [], server_info: {}, coverage: coverage) - assert_raises(LibTmux::IncompleteSnapshotError) { partial.windows.where(panes: {some: {active: false}}) } - assert_equal 2, partial.panes.where(index: {gte: 0}).first.window.panes.size + assert_raises(LibTmux::IncompleteSnapshotError) do + graph.panes.where(index: 99, window: { is: { name: "missing" } }) + end + rows[:window] = [{ id: "@1" }] + coverage = { pane: { records: { "%2" => { fields: { active: :incomplete } } } } } + partial = + LibTmux::Snapshot.__send__( + :new, + rows: rows, + binding_key: "binding", + started_at: 1.0, + finished_at: 2.0, + reads: [], + server_info: { + }, + coverage: coverage + ) + assert_raises(LibTmux::IncompleteSnapshotError) do + partial.windows.where(panes: { some: { active: false } }) + end + assert_equal 2, partial.panes.where(index: { gte: 0 }).first.window.panes.size end def test_wire_round_trip_rejects_duplicates_foreign_profiles_and_bounds - expr = LibTmux::PaneWhere.build(current_command: {starts_with: "nv"}, index: {gte: 2}) + expr = LibTmux::PaneWhere.build(current_command: { starts_with: "nv" }, index: { gte: 2 }) wire = expr.to_json assert_includes wire, '"profile":"libtmux-ruby.where"' assert_includes wire, '"currentCommand"' @@ -192,19 +254,26 @@ def test_wire_round_trip_rejects_duplicates_foreign_profiles_and_bounds assert_equal expr.to_h, loaded.to_h assert_equal expr.to_h, JSON.parse(JSON.generate(expr)) assert loaded.call(pane(current_command: "nvim", index: 12)) - [wire.sub("libtmux-ruby.where", "libtmux.where"), wire.sub('"version":1', '"version":2'), + [ + wire.sub("libtmux-ruby.where", "libtmux.where"), + wire.sub('"version":1', '"version":2'), wire.sub('"version":1', '"version":1,"version":1'), wire.sub('"currentCommand":', '"currentCommand":"cat","currentCommand":'), wire.sub('"currentCommand":', '"current_command":'), wire.sub('"startsWith":', '"starts_with":'), - wire.sub('"where":', '"extension":true,"where":')].each do |invalid| + wire.sub('"where":', '"extension":true,"where":') + ].each do |invalid| assert_raises(LibTmux::InvalidFilterError) { LibTmux::FilterExpr.from_json(invalid) } end - assert_raises(LibTmux::InvalidFilterError) { LibTmux::PaneWhere.build(index: {in: Array.new(1025, 1)}) } - assert_raises(LibTmux::InvalidFilterError) { LibTmux::PaneWhere.build(current_command: "x" * 65_537) } + assert_raises(LibTmux::InvalidFilterError) do + LibTmux::PaneWhere.build(index: { in: Array.new(1025, 1) }) + end + assert_raises(LibTmux::InvalidFilterError) do + LibTmux::PaneWhere.build(current_command: "x" * 65_537) + end assert_raises(LibTmux::InvalidFilterError) { LibTmux::PaneWhere.build(index: -1) } query = {} - 40.times { query = {not: query} } + 40.times { query = { not: query } } assert_raises(LibTmux::InvalidFilterError) { LibTmux::PaneWhere.build(query) } end diff --git a/test/unit/docs_workflow_test.rb b/test/unit/docs_workflow_test.rb index b8bdba60..7a129703 100644 --- a/test/unit/docs_workflow_test.rb +++ b/test/unit/docs_workflow_test.rb @@ -12,24 +12,30 @@ def test_preview_publication_uses_the_preview_role workflow = File.read(File.expand_path("../../.github/workflows/docs.yml", __dir__)) assert_includes workflow, - "role-arn: ${{ matrix.environment == 'docs-preview' && secrets.LIBTMUX_DOCS_PREVIEW_ROLE_ARN || secrets.LIBTMUX_DOCS_ROLE_ARN }}" + "role-arn: ${{ matrix.environment == 'docs-preview' && secrets.LIBTMUX_DOCS_PREVIEW_ROLE_ARN || secrets.LIBTMUX_DOCS_ROLE_ARN }}" end def test_source_exporter_and_docs_use_separate_checkouts build = workflow.fetch("jobs").fetch("build") steps = build.fetch("steps") checkouts = steps.select { |step| step.fetch("uses", "").start_with?("actions/checkout@") } - assert_equal %w[port docs-generator docs], checkouts.map { |step| step.fetch("with").fetch("path") } - assert_equal "${{ github.workspace }}/port", build.fetch("env").fetch("LIBTMUX_DOCS_CHECKOUT_RUBY") - assert_equal "${{ github.workspace }}/docs-generator", build.fetch("env").fetch("LIBTMUX_DOCS_GENERATOR_CHECKOUT") - snapshot = steps.index { |step| step.fetch("run", "").include?("publication-provenance.mjs snapshot") } + assert_equal %w[port docs-generator docs], + checkouts.map { |step| step.fetch("with").fetch("path") } + assert_equal "${{ github.workspace }}/port", + build.fetch("env").fetch("LIBTMUX_DOCS_CHECKOUT_RUBY") + assert_equal "${{ github.workspace }}/docs-generator", + build.fetch("env").fetch("LIBTMUX_DOCS_GENERATOR_CHECKOUT") + snapshot = + steps.index { |step| step.fetch("run", "").include?("publication-provenance.mjs snapshot") } exporter = steps.index { |step| step.fetch("name", "").start_with?("Export the selected") } assert snapshot && exporter && snapshot < exporter assert_equal "port", steps.fetch(exporter).fetch("working-directory") assert_includes steps.fetch(exporter).fetch("run"), '--source "$GITHUB_WORKSPACE/port"' tree = steps.find { |step| step.fetch("name", "").start_with?("Build the selected") } - assert_equal "${{ runner.temp }}/build-inputs.json", tree.fetch("env").fetch("LIBTMUX_DOCS_INPUT_SNAPSHOT") - assert_equal "${{ steps.source.outputs.sha }}", tree.fetch("env").fetch("LIBTMUX_DOCS_SOURCE_SHA") + assert_equal "${{ runner.temp }}/build-inputs.json", + tree.fetch("env").fetch("LIBTMUX_DOCS_INPUT_SNAPSHOT") + assert_equal "${{ steps.source.outputs.sha }}", + tree.fetch("env").fetch("LIBTMUX_DOCS_SOURCE_SHA") end def test_descriptor_uses_the_exact_content_upload @@ -37,14 +43,17 @@ def test_descriptor_uses_the_exact_content_upload steps = jobs.fetch("build").fetch("steps") content = steps.find { |step| step["id"] == "content" }.fetch("with") assert_equal true, content.fetch("include-hidden-files") - descriptor = steps.find { |step| step.fetch("run", "").include?("publication-provenance.mjs descriptor") } - assert_equal "${{ steps.content.outputs.artifact-id }}", descriptor.fetch("env").fetch("ARTIFACT_ID") - assert_equal "${{ steps.content.outputs.artifact-digest }}", descriptor.fetch("env").fetch("ARTIFACT_DIGEST") + descriptor = + steps.find { |step| step.fetch("run", "").include?("publication-provenance.mjs descriptor") } + assert_equal "${{ steps.content.outputs.artifact-id }}", + descriptor.fetch("env").fetch("ARTIFACT_ID") + assert_equal "${{ steps.content.outputs.artifact-digest }}", + descriptor.fetch("env").fetch("ARTIFACT_DIGEST") assert_equal content.fetch("name"), descriptor.fetch("env").fetch("ARTIFACT_NAME") - assert steps.any? { |step| step.dig("with", "name") == "#{content.fetch('name')}-publication" } + assert steps.any? { |step| step.dig("with", "name") == "#{content.fetch("name")}-publication" } docs = steps.find { |step| step.dig("with", "repository") == "libtmux/docs" } assert_match(/\A[0-9a-f]{40}\z/, docs.fetch("with").fetch("ref")) - assert jobs.fetch("publish").fetch("uses").end_with?("@#{docs.fetch('with').fetch('ref')}") + assert jobs.fetch("publish").fetch("uses").end_with?("@#{docs.fetch("with").fetch("ref")}") end def test_arbitrary_source_builds_do_not_restore_caches diff --git a/test/unit/endpoint_test.rb b/test/unit/endpoint_test.rb index 6bfadc36..c9700138 100644 --- a/test/unit/endpoint_test.rb +++ b/test/unit/endpoint_test.rb @@ -12,7 +12,9 @@ def test_rejects_conflicting_and_malformed_selectors_but_requires_no_socket assert_raises(ArgumentError) do LibTmux::Endpoint.new(socket_path: "/unused", socket_name: "unused") end - assert_raises(ArgumentError) { LibTmux::Endpoint.new(socket_directory: "/unused", environment: {}) } + assert_raises(ArgumentError) do + LibTmux::Endpoint.new(socket_directory: "/unused", environment: {}) + end ["", "../escape", "a/b", "nul\0"].each do |name| assert_raises(ArgumentError) { LibTmux::Endpoint.new(socket_name: name) } end @@ -32,20 +34,22 @@ def test_owns_configuration_and_does_not_follow_later_environment_changes end def test_ambient_selection_is_explicit_and_ignores_client_metadata - endpoint = LibTmux::Endpoint.from_env({"TMUX" => "/chosen/socket,1234,0"}) + endpoint = LibTmux::Endpoint.from_env({ "TMUX" => "/chosen/socket,1234,0" }) assert_equal "/chosen/socket", endpoint.socket_path named = LibTmux::Endpoint.new(socket_name: "named", socket_directory: "/explicit") assert_equal "/explicit/tmux-#{Process.uid}/named", named.socket_path end def test_the_path_variable_names_the_socket - assert_equal "/chosen/path.sock", endpoint("LIBTMUX_SOCKET_PATH" => "/chosen/path.sock").socket_path - assert_equal File.expand_path("relative.sock"), endpoint("LIBTMUX_SOCKET_PATH" => "relative.sock").socket_path + assert_equal "/chosen/path.sock", + endpoint("LIBTMUX_SOCKET_PATH" => "/chosen/path.sock").socket_path + assert_equal File.expand_path("relative.sock"), + endpoint("LIBTMUX_SOCKET_PATH" => "relative.sock").socket_path end def test_the_name_variable_names_a_socket_in_the_tmux_directory assert_equal "#{PRIVATE_DIRECTORY}/named", - endpoint("LIBTMUX_SOCKET" => "named", "TMUX_TMPDIR" => TMUX_DIRECTORY).socket_path + endpoint("LIBTMUX_SOCKET" => "named", "TMUX_TMPDIR" => TMUX_DIRECTORY).socket_path assert_equal "#{DEFAULT_DIRECTORY}/named", endpoint("LIBTMUX_SOCKET" => "named").socket_path end @@ -55,45 +59,75 @@ def test_the_path_variable_wins_when_both_variables_are_set end def test_a_blank_variable_counts_as_unset - assert_equal "#{DEFAULT_DIRECTORY}/named", endpoint("LIBTMUX_SOCKET_PATH" => "", "LIBTMUX_SOCKET" => "named").socket_path - assert_equal "#{DEFAULT_DIRECTORY}/default", endpoint("LIBTMUX_SOCKET_PATH" => "", "LIBTMUX_SOCKET" => "").socket_path - assert_equal "/inside/socket", endpoint("LIBTMUX_SOCKET" => "", "TMUX" => "/inside/socket,1,0").socket_path + assert_equal "#{DEFAULT_DIRECTORY}/named", + endpoint("LIBTMUX_SOCKET_PATH" => "", "LIBTMUX_SOCKET" => "named").socket_path + assert_equal "#{DEFAULT_DIRECTORY}/default", + endpoint("LIBTMUX_SOCKET_PATH" => "", "LIBTMUX_SOCKET" => "").socket_path + assert_equal "/inside/socket", + endpoint("LIBTMUX_SOCKET" => "", "TMUX" => "/inside/socket,1,0").socket_path assert_equal "#{DEFAULT_DIRECTORY}/default", endpoint("TMUX_TMPDIR" => "").socket_path end def test_inside_tmux_the_socket_in_tmux_is_the_default - assert_equal "/inside/socket", endpoint("TMUX" => "/inside/socket,4321,7", "TMUX_TMPDIR" => TMUX_DIRECTORY).socket_path + assert_equal "/inside/socket", + endpoint( + "TMUX" => "/inside/socket,4321,7", + "TMUX_TMPDIR" => TMUX_DIRECTORY + ).socket_path assert_equal "/inside/socket", endpoint("TMUX" => "/inside/socket").socket_path end def test_a_tmux_value_without_a_socket_path_is_ignored_as_tmux_ignores_it [",4321,7", ""].each do |value| - assert_equal "#{PRIVATE_DIRECTORY}/default", endpoint("TMUX" => value, "TMUX_TMPDIR" => TMUX_DIRECTORY).socket_path + assert_equal "#{PRIVATE_DIRECTORY}/default", + endpoint("TMUX" => value, "TMUX_TMPDIR" => TMUX_DIRECTORY).socket_path end end def test_with_nothing_set_the_default_socket_is_the_one_tmux_uses - assert_equal "#{PRIVATE_DIRECTORY}/default", endpoint("TMUX_TMPDIR" => TMUX_DIRECTORY).socket_path + assert_equal "#{PRIVATE_DIRECTORY}/default", + endpoint("TMUX_TMPDIR" => TMUX_DIRECTORY).socket_path assert_equal "#{DEFAULT_DIRECTORY}/default", endpoint.socket_path end def test_the_variables_win_over_the_tmux_socket assert_equal "/chosen/path.sock", - endpoint("LIBTMUX_SOCKET_PATH" => "/chosen/path.sock", "TMUX" => "/inside/socket,1,0").socket_path - assert_equal "#{DEFAULT_DIRECTORY}/named", endpoint("LIBTMUX_SOCKET" => "named", "TMUX" => "/inside/socket,1,0").socket_path + endpoint( + "LIBTMUX_SOCKET_PATH" => "/chosen/path.sock", + "TMUX" => "/inside/socket,1,0" + ).socket_path + assert_equal "#{DEFAULT_DIRECTORY}/named", + endpoint("LIBTMUX_SOCKET" => "named", "TMUX" => "/inside/socket,1,0").socket_path end def test_an_explicit_socket_ignores_every_variable - variables = {"LIBTMUX_SOCKET_PATH" => "/variable/path.sock", "LIBTMUX_SOCKET" => "variable", - "TMUX" => "/inside/socket,1,0", "TMUX_TMPDIR" => TMUX_DIRECTORY} - assert_equal "/explicit/path.sock", LibTmux::Endpoint.new(socket_path: "/explicit/path.sock", environment: variables).socket_path - assert_equal "#{PRIVATE_DIRECTORY}/explicit", LibTmux::Endpoint.new(socket_name: "explicit", environment: variables).socket_path + variables = { + "LIBTMUX_SOCKET_PATH" => "/variable/path.sock", + "LIBTMUX_SOCKET" => "variable", + "TMUX" => "/inside/socket,1,0", + "TMUX_TMPDIR" => TMUX_DIRECTORY + } + assert_equal "/explicit/path.sock", + LibTmux::Endpoint.new( + socket_path: "/explicit/path.sock", + environment: variables + ).socket_path + assert_equal "#{PRIVATE_DIRECTORY}/explicit", + LibTmux::Endpoint.new(socket_name: "explicit", environment: variables).socket_path assert_equal "/explicit/tmux-#{Process.uid}/explicit", - LibTmux::Endpoint.new(socket_name: "explicit", socket_directory: "/explicit", environment: variables).socket_path + LibTmux::Endpoint.new( + socket_name: "explicit", + socket_directory: "/explicit", + environment: variables + ).socket_path end def test_a_bad_variable_is_refused_by_name_without_echoing_its_value - [["LIBTMUX_SOCKET", "private-a/b"], ["LIBTMUX_SOCKET", ".."], ["LIBTMUX_SOCKET_PATH", "private-\0path"]].each do |name, value| + [ + %w[LIBTMUX_SOCKET private-a/b], + %w[LIBTMUX_SOCKET ..], + ["LIBTMUX_SOCKET_PATH", "private-\0path"] + ].each do |name, value| error = assert_raises(ArgumentError) { endpoint(name => value) } assert_includes error.message, name refute_includes error.message, "private-" @@ -102,11 +136,13 @@ def test_a_bad_variable_is_refused_by_name_without_echoing_its_value def test_a_path_that_cannot_expand_is_refused_by_name_without_naming_the_user user = "libtmux-ruby-no-such-user" - [[{socket_path: "~#{user}/x"}, "socket_path"], - [{environment: {"LIBTMUX_SOCKET_PATH" => "~#{user}/x"}}, "LIBTMUX_SOCKET_PATH"], - [{environment: {"TMUX" => "~#{user}/x,1,0"}}, "TMUX"], - [{socket_name: "named", socket_directory: "~#{user}"}, "socket_directory"], - [{environment: {"LIBTMUX_SOCKET" => "named", "TMUX_TMPDIR" => "~#{user}"}}, "TMUX_TMPDIR"]].each do |options, label| + [ + [{ socket_path: "~#{user}/x" }, "socket_path"], + [{ environment: { "LIBTMUX_SOCKET_PATH" => "~#{user}/x" } }, "LIBTMUX_SOCKET_PATH"], + [{ environment: { "TMUX" => "~#{user}/x,1,0" } }, "TMUX"], + [{ socket_name: "named", socket_directory: "~#{user}" }, "socket_directory"], + [{ environment: { "LIBTMUX_SOCKET" => "named", "TMUX_TMPDIR" => "~#{user}" } }, "TMUX_TMPDIR"] + ].each do |options, label| error = assert_raises(ArgumentError) { LibTmux::Endpoint.new(**options) } assert_includes error.message, label refute_includes error.message, user @@ -116,11 +152,16 @@ def test_a_path_that_cannot_expand_is_refused_by_name_without_naming_the_user def test_an_executable_that_cannot_expand_is_refused_without_naming_the_user user = "libtmux-ruby-no-such-user" ["~#{user}/tmux", "~#{user}"].each do |executable| - error = assert_raises(ArgumentError) { LibTmux::Endpoint.new(socket_path: "/unused", executable: executable) } + error = + assert_raises(ArgumentError) do + LibTmux::Endpoint.new(socket_path: "/unused", executable: executable) + end assert_includes error.message, "executable cannot be expanded" refute_includes error.message, user end - with_process_environment("PATH" => ["~#{user}/bin", ENV.fetch("PATH")].join(File::PATH_SEPARATOR)) do + with_process_environment( + "PATH" => ["~#{user}/bin", ENV.fetch("PATH")].join(File::PATH_SEPARATOR) + ) do error = assert_raises(ArgumentError) { LibTmux::Endpoint.new(socket_path: "/unused") } assert_includes error.message, "executable cannot be expanded" refute_includes error.message, user @@ -128,20 +169,32 @@ def test_an_executable_that_cannot_expand_is_refused_without_naming_the_user end def test_from_env_follows_tmux_alone_and_ignores_the_variables - variables = {"LIBTMUX_SOCKET_PATH" => "/variable/path.sock", "LIBTMUX_SOCKET" => "variable", "TMUX_TMPDIR" => TMUX_DIRECTORY} - assert_equal "/inside/socket", LibTmux::Endpoint.from_env(variables.merge("TMUX" => "/inside/socket,1,0")).socket_path + variables = { + "LIBTMUX_SOCKET_PATH" => "/variable/path.sock", + "LIBTMUX_SOCKET" => "variable", + "TMUX_TMPDIR" => TMUX_DIRECTORY + } + assert_equal "/inside/socket", + LibTmux::Endpoint.from_env( + variables.merge("TMUX" => "/inside/socket,1,0") + ).socket_path assert_equal "#{PRIVATE_DIRECTORY}/default", LibTmux::Endpoint.from_env(variables).socket_path - assert_equal "#{PRIVATE_DIRECTORY}/default", LibTmux::Endpoint.from_env(variables.merge("TMUX" => ",1,0")).socket_path + assert_equal "#{PRIVATE_DIRECTORY}/default", + LibTmux::Endpoint.from_env(variables.merge("TMUX" => ",1,0")).socket_path end def test_the_process_environment_is_the_default - with_process_environment("LIBTMUX_SOCKET_PATH" => "/process/path.sock", "LIBTMUX_SOCKET" => nil, "TMUX" => nil) do - assert_equal "/process/path.sock", LibTmux::Endpoint.new.socket_path - end - with_process_environment("LIBTMUX_SOCKET_PATH" => nil, "LIBTMUX_SOCKET" => "process", "TMUX" => nil, - "TMUX_TMPDIR" => TMUX_DIRECTORY) do - assert_equal "#{PRIVATE_DIRECTORY}/process", LibTmux::Endpoint.new.socket_path - end + with_process_environment( + "LIBTMUX_SOCKET_PATH" => "/process/path.sock", + "LIBTMUX_SOCKET" => nil, + "TMUX" => nil + ) { assert_equal "/process/path.sock", LibTmux::Endpoint.new.socket_path } + with_process_environment( + "LIBTMUX_SOCKET_PATH" => nil, + "LIBTMUX_SOCKET" => "process", + "TMUX" => nil, + "TMUX_TMPDIR" => TMUX_DIRECTORY + ) { assert_equal "#{PRIVATE_DIRECTORY}/process", LibTmux::Endpoint.new.socket_path } end private diff --git a/test/unit/mcp_catalog_tool_test.rb b/test/unit/mcp_catalog_tool_test.rb index ec35e670..51391ad3 100644 --- a/test/unit/mcp_catalog_tool_test.rb +++ b/test/unit/mcp_catalog_tool_test.rb @@ -8,7 +8,16 @@ class MCPCatalogToolTest < Minitest::Test TOOLSETS = %w[inspect manage execute teardown].freeze PROCESS_REACH = %w[none configured-process pane-input pane-command pane-program].freeze TMUX_EFFECTS = %w[observe change delete].freeze - ALL_TOOLS = %w[tmux_capabilities tmux_snapshot tmux_send tmux_create tmux_close tmux_run tmux_capture tmux_wait].freeze + ALL_TOOLS = %w[ + tmux_capabilities + tmux_snapshot + tmux_send + tmux_create + tmux_close + tmux_run + tmux_capture + tmux_wait + ].freeze CAPABILITIES = { "tmux_capabilities" => ["inspect", "none", %w[observe]], "tmux_snapshot" => ["inspect", "none", %w[observe]], @@ -21,16 +30,45 @@ class MCPCatalogToolTest < Minitest::Test }.freeze def test_tools_list_declares_object_schema_roots_for_the_negotiated_protocol - names = %w[tmux_capabilities tmux_snapshot tmux_send tmux_create tmux_close tmux_run tmux_capture tmux_wait] + names = %w[ + tmux_capabilities + tmux_snapshot + tmux_send + tmux_create + tmux_close + tmux_run + tmux_capture + tmux_wait + ] Async do - application = LibTmux::MCP::Application.new(server: LibTmux::Async::Server.allocate, - endpoint_name: "catalog", enabled_tools: names) + application = + LibTmux::MCP::Application.new( + server: LibTmux::Async::Server.allocate, + endpoint_name: "catalog", + enabled_tools: names + ) sdk = application.sdk_server - initialized = sdk.handle({jsonrpc: "2.0", id: 1, method: "initialize", - params: {protocolVersion: "2025-11-25", capabilities: {}, clientInfo: {name: "test", version: "1"}}}) + initialized = + sdk.handle( + { + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { + protocolVersion: "2025-11-25", + capabilities: { + }, + clientInfo: { + name: "test", + version: "1" + } + } + } + ) assert_equal "2025-11-25", initialized.fetch(:result).fetch(:protocolVersion) - response = JSON.parse(JSON.generate(sdk.handle({jsonrpc: "2.0", id: 2, method: "tools/list"}))) + response = + JSON.parse(JSON.generate(sdk.handle({ jsonrpc: "2.0", id: 2, method: "tools/list" }))) tools = response.fetch("result").fetch("tools") assert_equal names, tools.map { |tool| tool.fetch("name") } tools.each do |tool| @@ -45,15 +83,21 @@ def test_tools_list_declares_object_schema_roots_for_the_negotiated_protocol def test_handshake_does_not_compile_tool_schemas_but_listing_validates_and_memoizes_them constructions = 0 - trace = TracePoint.new(:call) do |event| - constructions += 1 if event.defined_class == ::MCP::Tool::Schema && event.method_id == :initialize - end + trace = + TracePoint.new(:call) do |event| + constructions += 1 if event.defined_class == ::MCP::Tool::Schema && + event.method_id == :initialize + end Async do trace.enable(target: ::MCP::Tool::Schema.instance_method(:initialize)) do - application = LibTmux::MCP::Application.new(server: LibTmux::Async::Server.allocate, - endpoint_name: "catalog", enabled_tools: %w[tmux_capabilities tmux_snapshot tmux_send tmux_create tmux_close]) + application = + LibTmux::MCP::Application.new( + server: LibTmux::Async::Server.allocate, + endpoint_name: "catalog", + enabled_tools: %w[tmux_capabilities tmux_snapshot tmux_send tmux_create tmux_close] + ) sdk = application.sdk_server - response = sdk.handle({jsonrpc: "2.0", id: 1, method: "server/discover"}) + response = sdk.handle({ jsonrpc: "2.0", id: 1, method: "server/discover" }) assert response.fetch(:result).key?(:supportedVersions) assert_equal 0, constructions, "discovery compiled unused tool schemas" @@ -63,7 +107,9 @@ def test_handshake_does_not_compile_tool_schemas_but_listing_validates_and_memoi assert_equal schemas, application.tools.map(&:to_h) assert_equal 10, constructions, "schema getters reconstructed validated schemas" tool = application.tools.find { |item| item.name_value == "tmux_send" } - assert_raises(::MCP::Tool::InputSchema::ValidationError) { tool.input_schema_value.validate_arguments({}) } + assert_raises(::MCP::Tool::InputSchema::ValidationError) do + tool.input_schema_value.validate_arguments({}) + end ensure application&.close end @@ -75,13 +121,20 @@ def test_handshake_does_not_compile_tool_schemas_but_listing_validates_and_memoi def test_malformed_output_schema_is_rejected_before_exposure_or_operation_dispatch catalog = LibTmux::MCP.const_get(:Catalog) original = catalog.method(:output) - catalog.define_singleton_method(:output) { |_name| {"type" => "invalid-schema-type"} } + catalog.define_singleton_method(:output) { |_name| { "type" => "invalid-schema-type" } } dispatches = 0 server = LibTmux::Async::Server.allocate - server.define_singleton_method(:snapshot) { |**_options| dispatches += 1; raise "operation dispatched" } + server.define_singleton_method(:snapshot) do |**_options| + dispatches += 1 + raise "operation dispatched" + end Async do - application = LibTmux::MCP::Application.new(server: server, endpoint_name: "catalog", - enabled_tools: ["tmux_capabilities"]) + application = + LibTmux::MCP::Application.new( + server: server, + endpoint_name: "catalog", + enabled_tools: ["tmux_capabilities"] + ) assert_raises(ArgumentError) { application.tools.first.to_h } response = application.call("tmux_capabilities").structured_content @@ -101,22 +154,46 @@ def test_snapshot_reports_schema_constraints_to_mcp_without_echoing_arguments Async do application = LibTmux::MCP::Application.new(server: server, endpoint_name: "catalog") sdk = application.sdk_server - sdk.handle({jsonrpc: "2.0", id: 1, method: "initialize", params: { - protocolVersion: "2025-11-25", capabilities: {}, clientInfo: {name: "test", version: "1"} - }}) - listing = sdk.handle({jsonrpc: "2.0", id: 2, method: "tools/list"}) - snapshot = listing.fetch(:result).fetch(:tools).find { |tool| tool.fetch(:name) == "tmux_snapshot" } + sdk.handle( + { + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { + protocolVersion: "2025-11-25", + capabilities: { + }, + clientInfo: { + name: "test", + version: "1" + } + } + } + ) + listing = sdk.handle({ jsonrpc: "2.0", id: 2, method: "tools/list" }) + snapshot = + listing.fetch(:result).fetch(:tools).find { |tool| tool.fetch(:name) == "tmux_snapshot" } assert_includes snapshot.fetch(:description), "cursor alone" cases = [ [{}, /entity or cursor/i], - [{entity: "pans"}, %r{/entity.*session, window, pane, window_link, client}], - [{entity: "pane", limit: 500}, %r{/limit.*at most 200}], - [{entity: "pane", cursor: "a" * 32 + ":1"}, /cursor alone/i], - [{entity: "pane", "PRIVATE_ARGUMENT" * 100 => "PRIVATE_VALUE"}, /unexpected property/i] + [{ entity: "pans" }, %r{/entity.*session, window, pane, window_link, client}], + [{ entity: "pane", limit: 500 }, %r{/limit.*at most 200}], + [{ entity: "pane", cursor: "a" * 32 + ":1" }, /cursor alone/i], + [{ :entity => "pane", "PRIVATE_ARGUMENT" * 100 => "PRIVATE_VALUE" }, /unexpected property/i] ] cases.each_with_index do |(arguments, expected), index| - reply = sdk.handle({jsonrpc: "2.0", id: index + 3, method: "tools/call", - params: {name: "tmux_snapshot", arguments: arguments}}) + reply = + sdk.handle( + { + jsonrpc: "2.0", + id: index + 3, + method: "tools/call", + params: { + name: "tmux_snapshot", + arguments: arguments + } + } + ) error = JSON.parse(JSON.generate(reply)).dig("result", "structuredContent", "error") assert_equal "invalid_input", error.fetch("code") assert_equal "not_sent", error.fetch("delivery") @@ -131,10 +208,13 @@ def test_snapshot_reports_schema_constraints_to_mcp_without_echoing_arguments def test_internal_argument_error_during_snapshot_is_a_transport_error server = LibTmux::Async::Server.allocate - server.define_singleton_method(:snapshot) { |**| raise ArgumentError, "PRIVATE OPERATION DETAILS" } + server.define_singleton_method(:snapshot) do |**| + raise ArgumentError, "PRIVATE OPERATION DETAILS" + end Async do application = LibTmux::MCP::Application.new(server: server, endpoint_name: "catalog") - error = application.call("tmux_snapshot", {entity: "pane"}).structured_content.fetch("error") + error = + application.call("tmux_snapshot", { entity: "pane" }).structured_content.fetch("error") assert_equal "transport_error", error.fetch("code") assert_equal "possibly_sent", error.fetch("delivery") refute_includes error.fetch("message"), "PRIVATE OPERATION DETAILS" @@ -148,21 +228,37 @@ def test_tools_list_states_the_capability_of_every_tool assert_equal ALL_TOOLS.sort, tools.map { |tool| tool.fetch("name") }.sort tools.each do |tool| toolset, process_reach, tmux_effects = CAPABILITIES.fetch(tool.fetch("name")) - assert_equal({"toolset" => toolset, "processReach" => process_reach, "tmuxEffects" => tmux_effects}, - tool.dig("_meta", CAPABILITY_KEY), "#{tool.fetch("name")} capability") + assert_equal( + { "toolset" => toolset, "processReach" => process_reach, "tmuxEffects" => tmux_effects }, + tool.dig("_meta", CAPABILITY_KEY), + "#{tool.fetch("name")} capability" + ) end assert_empty capability_problems(tools) end def test_capability_check_fails_a_missing_or_inconsistent_classification listed = listed_tools - assert_empty capability_problems(listed), "the check must pass on the real listing before it can fail" + assert_empty capability_problems(listed), + "the check must pass on the real listing before it can fail" mutations = { "tmux_send states no capability" => ["tmux_send", ->(tool) { tool.delete("_meta") }], - %(tmux_send has unknown toolset "admin") => ["tmux_send", ->(tool) { tool["_meta"][CAPABILITY_KEY]["toolset"] = "admin" }], - "tmux_snapshot is not observational inspect authority" => ["tmux_snapshot", ->(tool) { tool["_meta"][CAPABILITY_KEY]["processReach"] = "pane-input" }], - "tmux_close is not direct teardown authority" => ["tmux_close", ->(tool) { tool["_meta"][CAPABILITY_KEY]["tmuxEffects"] = %w[observe] }], - "tmux_run execute authority has no process reach" => ["tmux_run", ->(tool) { tool["_meta"][CAPABILITY_KEY]["processReach"] = "none" }] + %(tmux_send has unknown toolset "admin") => [ + "tmux_send", + ->(tool) { tool["_meta"][CAPABILITY_KEY]["toolset"] = "admin" } + ], + "tmux_snapshot is not observational inspect authority" => [ + "tmux_snapshot", + ->(tool) { tool["_meta"][CAPABILITY_KEY]["processReach"] = "pane-input" } + ], + "tmux_close is not direct teardown authority" => [ + "tmux_close", + ->(tool) { tool["_meta"][CAPABILITY_KEY]["tmuxEffects"] = %w[observe] } + ], + "tmux_run execute authority has no process reach" => [ + "tmux_run", + ->(tool) { tool["_meta"][CAPABILITY_KEY]["processReach"] = "none" } + ] } mutations.each do |problem, (name, mutate)| tools = JSON.parse(JSON.generate(listed)) @@ -176,12 +272,34 @@ def test_capability_check_fails_a_missing_or_inconsistent_classification def listed_tools(names = ALL_TOOLS) tools = nil Async do - application = LibTmux::MCP::Application.new(server: LibTmux::Async::Server.allocate, - endpoint_name: "catalog", enabled_tools: names) + application = + LibTmux::MCP::Application.new( + server: LibTmux::Async::Server.allocate, + endpoint_name: "catalog", + enabled_tools: names + ) sdk = application.sdk_server - sdk.handle({jsonrpc: "2.0", id: 1, method: "initialize", - params: {protocolVersion: "2025-11-25", capabilities: {}, clientInfo: {name: "test", version: "1"}}}) - tools = JSON.parse(JSON.generate(sdk.handle({jsonrpc: "2.0", id: 2, method: "tools/list"}))).fetch("result").fetch("tools") + sdk.handle( + { + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { + protocolVersion: "2025-11-25", + capabilities: { + }, + clientInfo: { + name: "test", + version: "1" + } + } + } + ) + tools = + JSON + .parse(JSON.generate(sdk.handle({ jsonrpc: "2.0", id: 2, method: "tools/list" }))) + .fetch("result") + .fetch("tools") ensure application&.close end.wait @@ -200,14 +318,25 @@ def capability_problems(tools) toolset, reach, effects = row.values_at("toolset", "processReach", "tmuxEffects") problems = [] problems << "#{name} has unknown toolset #{toolset.inspect}" unless TOOLSETS.include?(toolset) - problems << "#{name} has unknown processReach #{reach.inspect}" unless PROCESS_REACH.include?(reach) - unless effects.is_a?(Array) && !effects.empty? && effects.uniq == effects && (effects - TMUX_EFFECTS).empty? + unless PROCESS_REACH.include?(reach) + problems << "#{name} has unknown processReach #{reach.inspect}" + end + unless effects.is_a?(Array) && !effects.empty? && effects.uniq == effects && + (effects - TMUX_EFFECTS).empty? problems << "#{name} has unknown tmuxEffects #{effects.inspect}" end - problems << "#{name} is not observational inspect authority" if toolset == "inspect" && !(reach == "none" && effects == %w[observe]) - problems << "#{name} manage authority reaches a process" if toolset == "manage" && reach != "none" - problems << "#{name} execute authority has no process reach" if toolset == "execute" && reach == "none" - problems << "#{name} is not direct teardown authority" if toolset == "teardown" && !(reach == "none" && effects.include?("delete")) + if toolset == "inspect" && !(reach == "none" && effects == %w[observe]) + problems << "#{name} is not observational inspect authority" + end + if toolset == "manage" && reach != "none" + problems << "#{name} manage authority reaches a process" + end + if toolset == "execute" && reach == "none" + problems << "#{name} execute authority has no process reach" + end + if toolset == "teardown" && !(reach == "none" && effects.include?("delete")) + problems << "#{name} is not direct teardown authority" + end problems end end diff --git a/test/unit/mcp_cli_test.rb b/test/unit/mcp_cli_test.rb index dcea60d2..79c6777f 100644 --- a/test/unit/mcp_cli_test.rb +++ b/test/unit/mcp_cli_test.rb @@ -18,7 +18,11 @@ def test_broken_diagnostics_preserve_primary_failure_and_attempt_every_owner assert_same primary, raised end assert_equal %i[transport enrollments application scope server], events - assert_equal ["MCP cleanup failed (LibTmux::TransportError)", "MCP diagnostic failed (IOError)"], primary.mcp_cleanup_errors + assert_equal [ + "MCP cleanup failed (LibTmux::TransportError)", + "MCP diagnostic failed (IOError)" + ], + primary.mcp_cleanup_errors assert primary.mcp_cleanup_errors.frozen? end @@ -28,10 +32,19 @@ def test_broken_final_diagnostic_preserves_cli_status_after_cleanup assert_equal 2, LibTmux::MCP::CLI.run(%w[--socket private-path --socket-name other], err: error) input, output = IO.pipe - [[RuntimeError.new("private execution"), 1], [LibTmux::Cancelled.new("private cancellation"), 130]].each do |primary, status| + [ + [RuntimeError.new("private execution"), 1], + [LibTmux::Cancelled.new("private cancellation"), 130] + ].each do |primary, status| events = [] with_cli_owners(events, primary) do - assert_equal status, LibTmux::MCP::CLI.run(%w[--socket private-path], input: input, out: output, err: error) + assert_equal status, + LibTmux::MCP::CLI.run( + %w[--socket private-path], + input: input, + out: output, + err: error + ) end assert_equal %i[transport application scope server], events details = primary.is_a?(LibTmux::Error) ? primary.cleanup_errors : primary.mcp_cleanup_errors @@ -48,20 +61,44 @@ def test_help_version_and_invalid_arguments_do_not_open_an_endpoint refute_empty output.string assert_empty error.string end - [%w[--socket private-path --socket-name other], - %w[--socket private-path --timeout NaN], %w[--socket private-path --concurrency 0], + [ + %w[--socket private-path --socket-name other], + %w[--socket private-path --timeout NaN], + %w[--socket private-path --concurrency 0], %w[--socket private-path --enable-tool unrecognized], %w[--socket private-path --enroll-pane %0=private-setup], %w[--socket private-path --enable-tool tmux_run --enroll-pane name=private-setup], - %w[--socket private-path --enable-tool tmux_run --enroll-pane %0=private-one --enroll-pane %0=private-two], - %w[--socket private-path --enable-tool tmux_run --enroll-pane %0=private-one --enroll-pane %1=private-one], + %w[ + --socket + private-path + --enable-tool + tmux_run + --enroll-pane + %0=private-one + --enroll-pane + %0=private-two + ], + %w[ + --socket + private-path + --enable-tool + tmux_run + --enroll-pane + %0=private-one + --enroll-pane + %1=private-one + ], %w[--socket private-path --enrollment-timeout 301], %w[--socket private-path --keep], %w[--socket private-path --start-session], - %w[--socket private-path --start-session private:name], %w[--socket private-path --start-session private.name], - %w[--socket private-path --start-session -private], ["--socket", "private-path", "--start-session", ""], - ["--socket", "private-path", "--start-session", "private name"], ["--socket", "private-path", "--start-session", "p" * 129], - %w[--socket private-path --unknown private-value]].each do |arguments| + %w[--socket private-path --start-session private:name], + %w[--socket private-path --start-session private.name], + %w[--socket private-path --start-session -private], + ["--socket", "private-path", "--start-session", ""], + ["--socket", "private-path", "--start-session", "private name"], + ["--socket", "private-path", "--start-session", "p" * 129], + %w[--socket private-path --unknown private-value] + ].each do |arguments| output, error = StringIO.new, StringIO.new assert_equal 2, LibTmux::MCP::CLI.run(arguments, out: output, err: error) assert_empty output.string @@ -81,24 +118,45 @@ def test_a_flag_names_the_socket_and_the_variables_name_it_otherwise directory = "/private-tmux-tmpdir" inside = "/inside/socket,1,0" cases = [ - [%w[--socket /flag/path.sock], {"LIBTMUX_SOCKET_PATH" => "/variable/path.sock", "LIBTMUX_SOCKET" => "variable"}, "/flag/path.sock"], - [%w[--socket-name flag], {"LIBTMUX_SOCKET_PATH" => "/variable/path.sock"}, "#{directory}/tmux-#{Process.uid}/flag"], - [[], {"LIBTMUX_SOCKET_PATH" => "/variable/path.sock"}, "/variable/path.sock"], - [[], {"LIBTMUX_SOCKET" => "variable"}, "#{directory}/tmux-#{Process.uid}/variable"], - [[], {"LIBTMUX_SOCKET_PATH" => "/variable/path.sock", "LIBTMUX_SOCKET" => "variable"}, "/variable/path.sock"], - [[], {"TMUX" => inside}, "/inside/socket"], - [[], {"LIBTMUX_SOCKET" => "variable", "TMUX" => inside}, "#{directory}/tmux-#{Process.uid}/variable"], + [ + %w[--socket /flag/path.sock], + { "LIBTMUX_SOCKET_PATH" => "/variable/path.sock", "LIBTMUX_SOCKET" => "variable" }, + "/flag/path.sock" + ], + [ + %w[--socket-name flag], + { "LIBTMUX_SOCKET_PATH" => "/variable/path.sock" }, + "#{directory}/tmux-#{Process.uid}/flag" + ], + [[], { "LIBTMUX_SOCKET_PATH" => "/variable/path.sock" }, "/variable/path.sock"], + [[], { "LIBTMUX_SOCKET" => "variable" }, "#{directory}/tmux-#{Process.uid}/variable"], + [ + [], + { "LIBTMUX_SOCKET_PATH" => "/variable/path.sock", "LIBTMUX_SOCKET" => "variable" }, + "/variable/path.sock" + ], + [[], { "TMUX" => inside }, "/inside/socket"], + [ + [], + { "LIBTMUX_SOCKET" => "variable", "TMUX" => inside }, + "#{directory}/tmux-#{Process.uid}/variable" + ], [[], {}, "#{directory}/tmux-#{Process.uid}/default"] ] cases.each do |arguments, variables, socket| - status, endpoint, error = serve_stopped(arguments, variables.merge("TMUX_TMPDIR" => directory)) + status, endpoint, error = + serve_stopped(arguments, variables.merge("TMUX_TMPDIR" => directory)) assert_equal 1, status, error assert_equal socket, endpoint.socket_path, "#{arguments} #{variables.keys}" end end def test_a_bad_variable_is_refused_by_name_before_any_server_opens - status, endpoint, error = serve_stopped([], {"LIBTMUX_SOCKET" => "private-a/b", "TMUX_TMPDIR" => "/private-tmux-tmpdir"}) + status, endpoint, error = + serve_stopped( + [], + { "LIBTMUX_SOCKET" => "private-a/b", "TMUX_TMPDIR" => "/private-tmux-tmpdir" } + ) assert_equal 2, status assert_nil endpoint assert_includes error, "LIBTMUX_SOCKET" @@ -107,8 +165,11 @@ def test_a_bad_variable_is_refused_by_name_before_any_server_opens def test_a_socket_that_cannot_expand_is_refused_by_name_before_any_server_opens user = "libtmux-ruby-no-such-user" - private_directory = {"TMUX_TMPDIR" => "/private-tmux-tmpdir"} - [[%W[--socket ~#{user}/x], {}, "--socket"], [[], {"LIBTMUX_SOCKET_PATH" => "~#{user}/x"}, "LIBTMUX_SOCKET_PATH"]].each do |arguments, variables, name| + private_directory = { "TMUX_TMPDIR" => "/private-tmux-tmpdir" } + [ + [%W[--socket ~#{user}/x], {}, "--socket"], + [[], { "LIBTMUX_SOCKET_PATH" => "~#{user}/x" }, "LIBTMUX_SOCKET_PATH"] + ].each do |arguments, variables, name| status, endpoint, error = serve_stopped(arguments, private_directory.merge(variables)) assert_equal 2, status, name assert_nil endpoint, name @@ -119,8 +180,11 @@ def test_a_socket_that_cannot_expand_is_refused_by_name_before_any_server_opens def test_a_tmux_executable_that_cannot_expand_is_refused_by_name_before_any_server_opens user = "libtmux-ruby-no-such-user" - status, endpoint, error = serve_stopped(["--socket", "/flag/path.sock", "--tmux", "~#{user}/tmux"], - {"TMUX_TMPDIR" => "/private-tmux-tmpdir"}) + status, endpoint, error = + serve_stopped( + ["--socket", "/flag/path.sock", "--tmux", "~#{user}/tmux"], + { "TMUX_TMPDIR" => "/private-tmux-tmpdir" } + ) assert_equal 2, status assert_nil endpoint assert_includes error, "executable cannot be expanded" @@ -128,14 +192,19 @@ def test_a_tmux_executable_that_cannot_expand_is_refused_by_name_before_any_serv end def test_an_empty_socket_flag_is_still_refused - status, endpoint, error = serve_stopped(["--socket", ""], {"TMUX_TMPDIR" => "/private-tmux-tmpdir"}) + status, endpoint, error = + serve_stopped(["--socket", ""], { "TMUX_TMPDIR" => "/private-tmux-tmpdir" }) assert_equal 2, status assert_nil endpoint assert_includes error, "Invalid arguments" end def test_both_flags_are_refused_even_when_a_variable_names_a_socket - status, endpoint, error = serve_stopped(%w[--socket /flag/path.sock --socket-name flag], {"LIBTMUX_SOCKET" => "variable"}) + status, endpoint, error = + serve_stopped( + %w[--socket /flag/path.sock --socket-name flag], + { "LIBTMUX_SOCKET" => "variable" } + ) assert_equal 2, status assert_nil endpoint # The CLI refuses the pair itself, in the words of its flags, before the core can. @@ -155,7 +224,14 @@ def serve_stopped(arguments, environment) end input, output = IO.pipe error = StringIO.new - status = LibTmux::MCP::CLI.run(arguments, input: input, out: output, err: error, environment: environment) + status = + LibTmux::MCP::CLI.run( + arguments, + input: input, + out: output, + err: error, + environment: environment + ) [status, chosen.first, error.string] ensure LibTmux::Server.define_singleton_method(:open, original) @@ -176,16 +252,24 @@ def with_cli_owners(events, primary) end replacements = [ [LibTmux::Endpoint, :new, ->(**_options) { Object.new }], - [LibTmux::Server, :open, lambda do |**_options, &block| - block.call(server) - ensure - events << :server - end], - [LibTmux::Async, :open, lambda do |**_options, &block| - block.call(scope) - ensure - events << :scope - end], + [ + LibTmux::Server, + :open, + lambda do |**_options, &block| + block.call(server) + ensure + events << :server + end + ], + [ + LibTmux::Async, + :open, + lambda do |**_options, &block| + block.call(scope) + ensure + events << :scope + end + ], [LibTmux::MCP::Application, :new, ->(**_options) { app }], [LibTmux::MCP::StdioTransport, :new, ->(**_options) { transport }] ] diff --git a/test/unit/mcp_observation_test.rb b/test/unit/mcp_observation_test.rb index 31c294ed..9778ba18 100644 --- a/test/unit/mcp_observation_test.rb +++ b/test/unit/mcp_observation_test.rb @@ -20,20 +20,27 @@ def test_process_cursor_discovery_matches_native_backend_and_tmux_boundary assert_equal "unsupported", observation.capabilities("3.2a").fetch("process_cursor") assert_equal "unsupported", observation.capabilities("unknown").fetch("process_cursor") %w[3.3a 3.6b 3.7 next-3.7 3.8].each do |value| - assert_equal %w[screen_contains process_exit], observation.capabilities(value).fetch("wait_conditions") + assert_equal %w[screen_contains process_exit], + observation.capabilities(value).fetch("wait_conditions") end observation.send(:remove_const, :RUBY_PLATFORM) end observation.const_set(:RUBY_PLATFORM, "x64-mingw32") assert_equal "unsupported", observation.capabilities("3.7c").fetch("process_cursor") ensure - observation.send(:remove_const, :RUBY_PLATFORM) if observation&.const_defined?(:RUBY_PLATFORM, false) + if observation&.const_defined?(:RUBY_PLATFORM, false) + observation.send(:remove_const, :RUBY_PLATFORM) + end end def test_capture_hook_preflight_ranks_development_builds_below_3_5 observation = LibTmux::MCP.const_get(:Observation) parse = LibTmux::Internal::TmuxVersion.method(:parse) - %w[3.3a 3.4 next-3.5 3.5-rc 3.5-rc2].each { |value| assert observation.preflight_hooks?(parse.call(value)), value } - %w[3.5 3.5a 3.6 3.8 next-3.9].each { |value| refute observation.preflight_hooks?(parse.call(value)), value } + %w[3.3a 3.4 next-3.5 3.5-rc 3.5-rc2].each do |value| + assert observation.preflight_hooks?(parse.call(value)), value + end + %w[3.5 3.5a 3.6 3.8 next-3.9].each do |value| + refute observation.preflight_hooks?(parse.call(value)), value + end end end diff --git a/test/unit/metadata_test.rb b/test/unit/metadata_test.rb index 5206457b..98c0f152 100644 --- a/test/unit/metadata_test.rb +++ b/test/unit/metadata_test.rb @@ -18,11 +18,21 @@ def test_decodes_binary_lengths_before_recognizing_row_boundaries end def test_rejects_malformed_truncated_and_oversized_records - ["x:a\n", ":a\n", "1a\n", "2:a", "1:a", "1:aX", "1:a\nX", - "999999999999:a\n", "-1:a\n"].each do |wire| - error = assert_raises(LibTmux::ProtocolError) do - LibTmux::Internal::Metadata.decode(wire.b, fields: 1) - end + [ + "x:a\n", + ":a\n", + "1a\n", + "2:a", + "1:a", + "1:aX", + "1:a\nX", + "999999999999:a\n", + "-1:a\n" + ].each do |wire| + error = + assert_raises(LibTmux::ProtocolError) do + LibTmux::Internal::Metadata.decode(wire.b, fields: 1) + end assert_equal :decode, error.phase refute_includes error.message, wire end diff --git a/test/unit/native_guard_test.rb b/test/unit/native_guard_test.rb index a286da80..cbc75224 100644 --- a/test/unit/native_guard_test.rb +++ b/test/unit/native_guard_test.rb @@ -13,10 +13,11 @@ def release(text) end def refused(argv, text, **options) - error = assert_raises(LibTmux::UnsupportedFeatureError, "#{argv.inspect} on #{text}") do - guard.check(argv, release(text), **options) - end - assert_equal [:not_sent, :admission], [error.delivery, error.phase] + error = + assert_raises(LibTmux::UnsupportedFeatureError, "#{argv.inspect} on #{text}") do + guard.check(argv, release(text), **options) + end + assert_equal %i[not_sent admission], [error.delivery, error.phase] error end @@ -49,11 +50,11 @@ def test_buffer_forms_that_do_not_name_a_buffer_stay_available end def test_batches_are_read_item_by_item - refused(["set-option", "-g", "@a", "1", ";", "delete-buffer", "-b", "saved"], "3.3a") - refused(["set-option", "-g", "@a", "1;", "delete-buffer", "-b", "saved"], "3.3a") + refused(%w[set-option -g @a 1 ; delete-buffer -b saved], "3.3a") + refused(%w[set-option -g @a 1; delete-buffer -b saved], "3.3a") allowed(["set-option", "-g", "@a", "1\;", "delete-buffer"], "3.3a") allowed(["set-option", "-g", "@a", "x ; delete-buffer -b saved"], "3.3a") - allowed(["display-message", "-p", "--", "delete-buffer"], "3.3a") + allowed(%w[display-message -p -- delete-buffer], "3.3a") end def test_exact_tmux_3_7_refuses_raw_break_pane_but_not_the_repaired_call @@ -95,7 +96,8 @@ def test_json_layouts_are_refused_before_tmux_3_8 json = '{"V":2,"L":{}}' %w[3.3a 3.4 3.7c 3.7d].each do |text| error = refused(["select-layout", "-t", "%0", json], text) - assert_equal "JSON layouts require tmux 3.8 or newer (connected version #{text})", error.message + assert_equal "JSON layouts require tmux 3.8 or newer (connected version #{text})", + error.message end refused(["selectl", json], "3.7c") %w[3.8 next-3.9].each { |text| allowed(["select-layout", "-t", "%0", json], text) } @@ -109,10 +111,11 @@ def test_ambiguous_and_unknown_commands_are_not_guessed end def refused_line(line, text) - error = assert_raises(LibTmux::UnsupportedFeatureError, "#{line.inspect} on #{text}") do - guard.check_line(line, release(text)) - end - assert_equal [:not_sent, :admission], [error.delivery, error.phase] + error = + assert_raises(LibTmux::UnsupportedFeatureError, "#{line.inspect} on #{text}") do + guard.check_line(line, release(text)) + end + assert_equal %i[not_sent admission], [error.delivery, error.phase] error end @@ -121,20 +124,34 @@ def allowed_line(line, text) end def test_control_lines_are_read_the_way_tmux_parses_a_command_string - ["break-pane", "breakp -d", "break-p -n x", " break-pane", "display-message -p ok ; break-pane", - "display-message -p ok;break-pane", "'break-pane' -d", %q("break-pane"), - "break\\-pane", "display-message ok\\;x ; break-pane", "{ x } ; break-pane"].each do |line| - refused_line(line, "3.7") - end + [ + "break-pane", + "breakp -d", + "break-p -n x", + " break-pane", + "display-message -p ok ; break-pane", + "display-message -p ok;break-pane", + "'break-pane' -d", + %q("break-pane"), + "break\\-pane", + "display-message ok\\;x ; break-pane", + "{ x } ; break-pane" + ].each { |line| refused_line(line, "3.7") } allowed_line("display-message -p ok ;", "3.7") - ["break-pane", "breakp -d", "display-message -p ok ; break-pane"].each { |line| allowed_line(line, "3.7a") } + ["break-pane", "breakp -d", "display-message -p ok ; break-pane"].each do |line| + allowed_line(line, "3.7a") + end end def test_control_line_text_that_is_not_a_command_name_is_not_refused - ["display-message -p 'break-pane'", %q(display-message -p "x ; break-pane"), "display-message -p x\\;break-pane", - "set-option -g @x { break-pane }", "# break-pane", "display-message -p -- break-pane"].each do |line| - allowed_line(line, "3.7") - end + [ + "display-message -p 'break-pane'", + %q(display-message -p "x ; break-pane"), + "display-message -p x\\;break-pane", + "set-option -g @x { break-pane }", + "# break-pane", + "display-message -p -- break-pane" + ].each { |line| allowed_line(line, "3.7") } end def test_control_lines_get_the_buffer_and_layout_gates_too @@ -148,8 +165,14 @@ def test_control_lines_get_the_buffer_and_layout_gates_too end def test_clipboard_query_needs_tmux_3_6a - [%w[refresh-client -l], %w[refresh -l], %w[refresh-c -t /dev/pts/1 -l], %w[refresh-client -Sl], - %w[refresh-client -l%1], ["display-message", "-p", "ok", ";", "refresh-client", "-l"]].each do |argv| + [ + %w[refresh-client -l], + %w[refresh -l], + %w[refresh-c -t /dev/pts/1 -l], + %w[refresh-client -Sl], + %w[refresh-client -l%1], + %w[display-message -p ok ; refresh-client -l] + ].each do |argv| %w[3.3a 3.4 3.5 3.5a 3.6].each { |text| refused(argv, text) } %w[3.6a 3.6b 3.7c 3.8 next-3.9].each { |text| allowed(argv, text) } end @@ -158,14 +181,29 @@ def test_clipboard_query_needs_tmux_3_6a end def test_raw_names_with_colon_or_period_are_refused_on_exact_tmux_3_7 - [%w[new-session -d -s a.b], %w[new -s a:b], %w[new-session -d -n a.b], %w[new-window -d -n a.b], %w[neww -n x:y], - %w[rename-window a.b], %w[renamew -t @1 a.b], %w[rename-session a:b], %w[rename -t $1 a.b], - ["new-window", "-d", "-n", "ok", ";", "rename-window", "a.b"]].each do |argv| + [ + %w[new-session -d -s a.b], + %w[new -s a:b], + %w[new-session -d -n a.b], + %w[new-window -d -n a.b], + %w[neww -n x:y], + %w[rename-window a.b], + %w[renamew -t @1 a.b], + %w[rename-session a:b], + %w[rename -t $1 a.b], + %w[new-window -d -n ok ; rename-window a.b] + ].each do |argv| refused(argv, "3.7") allowed(argv, "3.7a") allowed(argv, "3.4") end - [%w[new-session -d -s plain], %w[new-window -n plain-name], %w[rename-window plain], %w[rename-window -t @1.2 plain], - %w[new-window -t sess:1 -n plain], %w[display-message -p a.b]].each { |argv| allowed(argv, "3.7") } + [ + %w[new-session -d -s plain], + %w[new-window -n plain-name], + %w[rename-window plain], + %w[rename-window -t @1.2 plain], + %w[new-window -t sess:1 -n plain], + %w[display-message -p a.b] + ].each { |argv| allowed(argv, "3.7") } end end diff --git a/test/unit/option_catalog_test.rb b/test/unit/option_catalog_test.rb index b6e595a5..3dd7ca8e 100644 --- a/test/unit/option_catalog_test.rb +++ b/test/unit/option_catalog_test.rb @@ -5,7 +5,8 @@ class OptionCatalogTest < Minitest::Test def setup - assert LibTmux.const_defined?(:OptionCatalog, false), "libtmux exposes the tmux option and hook catalog" + assert LibTmux.const_defined?(:OptionCatalog, false), + "libtmux exposes the tmux option and hook catalog" @catalog = LibTmux::OptionCatalog end @@ -21,10 +22,10 @@ def test_options_report_types_scopes_and_allowed_values position = @catalog.options.fetch("status-position") assert_equal :choice, position.type - assert_equal ["top", "bottom"], position.choices + assert_equal %w[top bottom], position.choices assert_nil position.range assert @catalog.options.fetch("command-alias").array? - assert_equal [:window, :pane], @catalog.options.fetch("remain-on-exit").scopes + assert_equal %i[window pane], @catalog.options.fetch("remain-on-exit").scopes assert_equal 1_048_576, @catalog.options.fetch("input-buffer-size").range.begin assert_nil @catalog.options["@custom"] end @@ -33,7 +34,7 @@ def test_hooks_report_the_scope_of_each_upstream_macro scopes_by_name = { "after-new-window" => [:session], "client-created" => [:session], - "pane-created" => [:window, :pane], + "pane-created" => %i[window pane], "window-created" => [:window], "window-zoomed" => [:window] } diff --git a/test/unit/process_test.rb b/test/unit/process_test.rb index c4c8b698..ccd77b61 100644 --- a/test/unit/process_test.rb +++ b/test/unit/process_test.rb @@ -11,7 +11,7 @@ def test_preserves_literal_arguments_and_clears_tmux_environment arguments = ["", ";", "a\nb", "\\", "$(false)", "x y", "\"'", "#{35.chr}{pid}"] source = "Marshal.dump([ARGV, ENV.values_at('TMUX', 'TMUX_PANE')], STDOUT)" argv = ruby(source, *arguments) - result = executor.run(argv, env: {"TMUX" => "borrowed", "TMUX_PANE" => "%42"}) + result = executor.run(argv, env: { "TMUX" => "borrowed", "TMUX_PANE" => "%42" }) assert_equal [arguments, [nil, nil]], Marshal.load(result.stdout) assert result.success? @@ -24,7 +24,10 @@ def test_preserves_literal_arguments_and_clears_tmux_environment end def test_preserves_binary_streams_and_raw_nonzero_status - result = executor.run(ruby("STDOUT.write([255, 10, 10].pack('C*')); STDERR.write([0, 254].pack('C*')); exit 17")) + result = + executor.run( + ruby("STDOUT.write([255, 10, 10].pack('C*')); STDERR.write([0, 254].pack('C*')); exit 17") + ) assert_equal "\xff\n\n".b, result.stdout assert_equal "\x00\xfe".b, result.stderr @@ -63,7 +66,8 @@ def test_rejects_nul_before_spawning end def test_expired_deadline_is_known_not_sent - error = assert_raises(LibTmux::DeadlineExceeded) { executor.run(["must-not-spawn"], timeout: 0) } + error = + assert_raises(LibTmux::DeadlineExceeded) { executor.run(["must-not-spawn"], timeout: 0) } assert_equal :not_sent, error.delivery assert_equal :admission, error.phase @@ -71,9 +75,12 @@ def test_expired_deadline_is_known_not_sent end def test_output_limit_retires_and_reaps_the_child - error = assert_raises(LibTmux::CapacityError) do - executor(stdout_limit: 1024).run(ruby("STDOUT.sync = true; loop { STDOUT.write('x' * 8192) }")) - end + error = + assert_raises(LibTmux::CapacityError) do + executor(stdout_limit: 1024).run( + ruby("STDOUT.sync = true; loop { STDOUT.write('x' * 8192) }") + ) + end assert_equal :possibly_sent, error.delivery assert_equal :read, error.phase @@ -84,7 +91,8 @@ def test_output_limit_retires_and_reaps_the_child def test_cancellation_before_dispatch_never_spawns cancellation = LibTmux::Cancellation.new cancellation.cancel - error = assert_raises(LibTmux::Cancelled) { executor.run(["must-not-spawn"], cancel: cancellation) } + error = + assert_raises(LibTmux::Cancelled) { executor.run(["must-not-spawn"], cancel: cancellation) } assert_equal :not_sent, error.delivery assert_equal :admission, error.phase @@ -96,14 +104,15 @@ def test_cancellation_before_dispatch_never_spawns def test_cancellation_escalates_and_reaps_a_child_ignoring_term cancellation = LibTmux::Cancellation.new with_child_readiness do |ready, environment| - worker = task do - executor(cleanup_timeout: 0.1).run(ruby(<<~RUBY), env: environment, cancel: cancellation) + worker = + task do + executor(cleanup_timeout: 0.1).run(ruby(<<~RUBY), env: environment, cancel: cancellation) trap('TERM') {} File.write(ENV.fetch('READY'), Process.pid.to_s + "\n") input, output = IO.pipe input.read(1) RUBY - end + end pid = Integer(read_event(ready), 10) 20.times { cancellation.cancel } assert worker.join(0.5), "cancellation did not retire the owned client" @@ -124,13 +133,11 @@ def test_cancellation_escalates_and_reaps_a_child_ignoring_term def test_deadline_after_dispatch_reports_possible_effects with_child_readiness do |ready, environment| - worker = task do - executor.run(ruby(<<~RUBY), env: environment, timeout: 0.1) + worker = task { executor.run(ruby(<<~RUBY), env: environment, timeout: 0.1) } File.write(ENV.fetch('READY'), Process.pid.to_s + "\n") input, output = IO.pipe input.read(1) RUBY - end pid = Integer(read_event(ready), 10) assert worker.join(0.5), "deadline did not retire the owned client" error = worker.value @@ -150,14 +157,13 @@ def test_drain_deadline_bounds_a_pipe_retained_after_child_exit Dir.mktmpdir("libtmux-ruby-") do |directory| path = File.join(directory, "transfer") UNIXServer.open(path) do |server| - worker = task do - executor(drain_timeout: 0.04).run(ruby(<<~RUBY), env: {"TRANSFER" => path}) + worker = + task { executor(drain_timeout: 0.04).run(ruby(<<~RUBY), env: { "TRANSFER" => path }) } require 'socket' socket = UNIXSocket.new(ENV.fetch('TRANSFER')) socket.send_io(STDOUT) socket.close RUBY - end assert IO.select([server], nil, nil, 0.5), "child did not connect for pipe transfer" connection = server.accept assert IO.select([connection], nil, nil, 0.5), "child did not transfer its pipe" @@ -184,13 +190,11 @@ def test_drain_deadline_bounds_a_pipe_retained_after_child_exit def test_thread_exception_survives_owned_cleanup failure = RuntimeError.new("caller cancelled") with_child_readiness do |ready, environment| - worker = task do - executor.run(ruby(<<~RUBY), env: environment) + worker = task { executor.run(ruby(<<~RUBY), env: environment) } File.write(ENV.fetch('READY'), Process.pid.to_s + "\n") input, output = IO.pipe input.read(1) RUBY - end pid = Integer(read_event(ready), 10) worker.raise(failure) assert worker.join(0.5), "interrupted caller did not retire its client" @@ -209,22 +213,21 @@ def test_repeated_thread_cancellation_does_not_replace_the_first_failure release = Queue.new observer = nil with_child_readiness do |ready, environment| - trace = TracePoint.new(:c_call) do |event| - next unless event.method_id == :wait2 && !observer + trace = + TracePoint.new(:c_call) do |event| + next unless event.method_id == :wait2 && !observer - observer = Thread.current - ready.syswrite("reaping\n") - release.pop - end + observer = Thread.current + ready.syswrite("reaping\n") + release.pop + end trace.enable - worker = task do - executor(cleanup_timeout: 0.15).run(ruby(<<~RUBY), env: environment) + worker = task { executor(cleanup_timeout: 0.15).run(ruby(<<~RUBY), env: environment) } input, output = IO.pipe trap('TERM') {} File.write(ENV.fetch('READY'), Process.pid.to_s + "\n") input.read(1) RUBY - end pid = Integer(read_event(ready), 10) worker.raise(original) assert_equal "reaping", read_event(ready) @@ -244,9 +247,10 @@ def test_repeated_thread_cancellation_does_not_replace_the_first_failure end def test_caps_request_bytes_before_dispatch - error = assert_raises(LibTmux::CapacityError) do - executor.run(ruby("exit 0"), input: "x" * ((1 << 20) + 1)) - end + error = + assert_raises(LibTmux::CapacityError) do + executor.run(ruby("exit 0"), input: "x" * ((1 << 20) + 1)) + end assert_equal :not_sent, error.delivery assert_equal :admission, error.phase assert_nil error.pid @@ -259,9 +263,10 @@ def test_caps_request_bytes_before_dispatch def test_spawn_failure_closes_descriptors_and_redacts_the_executable before = Dir.children("/dev/fd").length - error = assert_raises(LibTmux::TransportError) do - executor.run(["/unavailable/private-command-argument"]) - end + error = + assert_raises(LibTmux::TransportError) do + executor.run(["/unavailable/private-command-argument"]) + end assert_equal :not_sent, error.delivery assert_equal :spawn, error.phase @@ -281,11 +286,12 @@ def test_exit_observation_leaves_child_waitable_until_owner_reaps assert_equal 1, Process.kill(0, pid) assert_equal 1, Process.kill("TERM", pid) - waited = begin - Process.waitpid2(pid, Process::WNOHANG) - rescue Errno::ECHILD - nil - end + waited = + begin + Process.waitpid2(pid, Process::WNOHANG) + rescue Errno::ECHILD + nil + end assert waited, "exit observer reaped the client before its owner could finish signalling" assert_equal pid, waited.first assert_equal 17, waited.last.exitstatus @@ -330,20 +336,22 @@ def test_observed_exit_wins_cancellation_before_native_status_publication release = Queue.new handed_off = false observer = nil - trace = TracePoint.new(:return, :c_call) do |event| - if event.event == :return && event.defined_class == LibTmux::Internal::OwnedChild && - event.method_id == :finish_signalling && !handed_off - handed_off = true - cancel.cancel - elsif event.event == :c_call && event.method_id == :wait2 && !observer - observer = Thread.current - release.pop - elsif event.event == :c_call && event.method_id == :select && handed_off - release << true + trace = + TracePoint.new(:return, :c_call) do |event| + if event.event == :return && event.defined_class == LibTmux::Internal::OwnedChild && + event.method_id == :finish_signalling && !handed_off + handed_off = true + cancel.cancel + elsif event.event == :c_call && event.method_id == :wait2 && !observer + observer = Thread.current + release.pop + elsif event.event == :c_call && event.method_id == :select && handed_off + release << true + end end - end trace.enable - worker = task { executor(cleanup_timeout: 0.02).run(ruby('STDOUT.write("done")'), cancel: cancel) } + worker = + task { executor(cleanup_timeout: 0.02).run(ruby('STDOUT.write("done")'), cancel: cancel) } assert worker.join(0.5), "observed command did not finish its bounded drain" assert_instance_of LibTmux::CommandResult, worker.value assert_equal "done", worker.value.stdout @@ -361,14 +369,19 @@ def test_incomplete_cleanup_retains_the_obligation_to_reap before = Thread.list cancellation = LibTmux::Cancellation.new with_child_readiness do |ready, environment| - worker = task do - executor(cleanup_timeout: 0.000000001).run(ruby(<<~RUBY), env: environment, cancel: cancellation) + worker = + task do + executor(cleanup_timeout: 0.000000001).run( + ruby(<<~RUBY), trap('TERM') {} File.write(ENV.fetch('READY'), Process.pid.to_s + "\n") input, output = IO.pipe input.read(1) RUBY - end + env: environment, + cancel: cancellation + ) + end pid = Integer(read_event(ready), 10) cancellation.cancel assert worker.join(0.5), "cleanup did not respect its deadline" @@ -392,17 +405,19 @@ def test_incomplete_cleanup_retains_the_obligation_to_reap def test_fork_child_detaches_cancellation_without_waking_parent cancellation = LibTmux::Cancellation.new - child = fork do - cancellation.close - exit!(cancellation.reader.closed? ? 0 : 18) - rescue Exception - exit! 17 - end + child = + fork do + cancellation.close + exit!(cancellation.reader.closed? ? 0 : 18) + rescue Exception + exit! 17 + end _, status = Process.wait2(child) assert status.success?, "fork child could not detach inherited token descriptors" refute cancellation.cancelled? - assert_nil IO.select([cancellation.reader], nil, nil, 0), "child wrote to the parent's cancellation pipe" + assert_nil IO.select([cancellation.reader], nil, nil, 0), + "child wrote to the parent's cancellation pipe" cancellation.cancel assert IO.select([cancellation.reader], nil, nil, 0) ensure @@ -412,22 +427,21 @@ def test_fork_child_detaches_cancellation_without_waking_parent def test_interrupted_exit_observer_does_not_abandon_a_live_owned_child release = Queue.new # Raise in the real observer thread without substituting the child or waiter. - trace = TracePoint.new(:call) do |event| - if event.defined_class == LibTmux::Internal::ProcessWait && event.method_id == :observe - release.pop - raise IOError, "exit observer failed" + trace = + TracePoint.new(:call) do |event| + if event.defined_class == LibTmux::Internal::ProcessWait && event.method_id == :observe + release.pop + raise IOError, "exit observer failed" + end end - end with_child_readiness do |ready, environment| trace.enable - worker = task do - executor(cleanup_timeout: 0.1).run(ruby(<<~RUBY), env: environment) + worker = task { executor(cleanup_timeout: 0.1).run(ruby(<<~RUBY), env: environment) } trap('TERM') {} File.write(ENV.fetch('READY'), Process.pid.to_s + "\n") input, output = IO.pipe input.read(1) RUBY - end pid = Integer(read_event(ready), 10) release << true assert worker.join(0.5), "failed exit observer did not release command ownership" @@ -455,23 +469,26 @@ def test_late_observer_failure_receives_reaping_ownership_after_final_signal release = Queue.new selected = nil cancellation = LibTmux::Cancellation.new - trace = TracePoint.new(:call) do |event| - if event.defined_class == LibTmux::Internal::ProcessWait && event.method_id == :observe && !selected - selected = Thread.current - release.pop - raise IOError, "late exit observer failure" + trace = + TracePoint.new(:call) do |event| + if event.defined_class == LibTmux::Internal::ProcessWait && event.method_id == :observe && + !selected + selected = Thread.current + release.pop + raise IOError, "late exit observer failure" + end end - end with_child_readiness do |ready, environment| trace.enable - worker = task do - executor(cleanup_timeout: 0.1).run(ruby(<<~RUBY), env: environment, cancel: cancellation) + worker = + task do + executor(cleanup_timeout: 0.1).run(ruby(<<~RUBY), env: environment, cancel: cancellation) trap('TERM') {} File.write(ENV.fetch('READY'), Process.pid.to_s + "\n") input, output = IO.pipe input.read(1) RUBY - end + end pid = Integer(read_event(ready), 10) cancellation.cancel witness = task { LibTmux::Internal::ProcessWait.new.observe(pid) } @@ -521,9 +538,7 @@ def with_child_readiness Dir.mktmpdir("libtmux-ruby-") do |directory| path = File.join(directory, "ready") File.mkfifo(path, 0o600) - File.open(path, File::RDWR | File::NONBLOCK) do |ready| - yield ready, {"READY" => path} - end + File.open(path, File::RDWR | File::NONBLOCK) { |ready| yield ready, { "READY" => path } } end end diff --git a/test/unit/readme_blocks_test.rb b/test/unit/readme_blocks_test.rb index 5380e21b..4a4ed1b2 100644 --- a/test/unit/readme_blocks_test.rb +++ b/test/unit/readme_blocks_test.rb @@ -11,14 +11,10 @@ class ReadmeBlocksTest < Minitest::Test TOOLS = LibTmux::MCP.const_get(:Catalog)::NAMES def test_console_blocks_hold_one_command_each - Blocks::DOCUMENTS.each do |path| - assert_empty Blocks.console_problems(Blocks.read(path), path) - end + Blocks::DOCUMENTS.each { |path| assert_empty Blocks.console_problems(Blocks.read(path), path) } two = "```console\n$ one\n$ two\n```\n" output = "```console\n$ one\nprinted\n```\n" - [two, output].each do |markdown| - refute_empty Blocks.console_problems(markdown, "control.md") - end + [two, output].each { |markdown| refute_empty Blocks.console_problems(markdown, "control.md") } continued = Blocks.fences("```console\n$ libtmux-workspace load \\\n --json x\n```\n").first assert_equal "libtmux-workspace load --json x", Blocks.command(continued) end @@ -48,7 +44,8 @@ def test_root_and_core_readmes_link_every_gem_directory_from_a_heading bare_colon = "### [libtmux](#{Blocks::GEM_TREE}/libtmux):\n" refute_empty Blocks.gem_heading_problems(bare_colon, "control.md", gems: %w[libtmux]) Blocks::GEMS.each do |name| - assert File.file?(File.join(Blocks::ROOT, "gems", name, "README.md")), "#{name} has no README to link" + assert File.file?(File.join(Blocks::ROOT, "gems", name, "README.md")), + "#{name} has no README to link" end end @@ -57,76 +54,134 @@ def test_tool_names_in_tables_and_lists_link_to_their_pages assert_empty Blocks.tool_link_problems(Blocks.read(path), path, tools: TOOLS) end page = "#{Blocks::TOOL_PAGES}/tmux_send/" - assert_empty Blocks.tool_link_problems("| [`tmux_send`](#{page}) | x |\n", "control.md", tools: TOOLS) - bare = Blocks.tool_link_problems("| `tmux_send` | x |\n- `tmux_snapshot` reads\n", "control.md", tools: TOOLS) + assert_empty Blocks.tool_link_problems( + "| [`tmux_send`](#{page}) | x |\n", + "control.md", + tools: TOOLS + ) + bare = + Blocks.tool_link_problems( + "| `tmux_send` | x |\n- `tmux_snapshot` reads\n", + "control.md", + tools: TOOLS + ) assert_equal 2, bare.length - wrong = Blocks.tool_link_problems("- [`tmux_send`](#{Blocks::TOOL_PAGES}/tmux_capture/)\n", "control.md", tools: TOOLS) + wrong = + Blocks.tool_link_problems( + "- [`tmux_send`](#{Blocks::TOOL_PAGES}/tmux_capture/)\n", + "control.md", + tools: TOOLS + ) assert_match(/links to/, wrong.first) - assert_empty Blocks.tool_link_problems("Prose may name `tmux_send` once.\n", "control.md", tools: TOOLS) + assert_empty Blocks.tool_link_problems( + "Prose may name `tmux_send` once.\n", + "control.md", + tools: TOOLS + ) end def test_tool_names_may_link_by_reference page = "#{Blocks::TOOL_PAGES}/tmux_send/" referenced = "- [`tmux_send`][tool-tmux_send]\n\n[tool-tmux_send]: #{page}\n" assert_empty Blocks.tool_link_problems(referenced, "control.md", tools: TOOLS) - undefined = Blocks.tool_link_problems("- [`tmux_send`][tool-tmux_send]\n", "control.md", tools: TOOLS) + undefined = + Blocks.tool_link_problems("- [`tmux_send`][tool-tmux_send]\n", "control.md", tools: TOOLS) assert_match(/undefined link label/, undefined.first) other = "- [`tmux_send`][tool]\n\n[tool]: #{Blocks::TOOL_PAGES}/tmux_capture/\n" assert_match(/links to/, Blocks.tool_link_problems(other, "control.md", tools: TOOLS).first) - bare = Blocks.tool_link_problems("- `tmux_send` reads\n\n[tool]: #{page}\n", "control.md", tools: TOOLS) + bare = + Blocks.tool_link_problems( + "- `tmux_send` reads\n\n[tool]: #{page}\n", + "control.md", + tools: TOOLS + ) assert_equal 1, bare.length end def test_names_that_are_not_tools_may_link_elsewhere - template = "[`tmux_screen`][resource]\n\n[resource]: https://libtmux.org/en/ruby/latest/mcp/resources/templates/tmux_screen/\n" + template = + "[`tmux_screen`][resource]\n\n[resource]: https://libtmux.org/en/ruby/latest/mcp/resources/templates/tmux_screen/\n" assert_empty Blocks.tool_link_problems(template, "control.md", tools: TOOLS) misspelled = "[`tmux_sned`](#{Blocks::TOOL_PAGES}/tmux_send/)\n" - assert_match(/links to/, Blocks.tool_link_problems(misspelled, "control.md", tools: TOOLS).first) + assert_match( + /links to/, + Blocks.tool_link_problems(misspelled, "control.md", tools: TOOLS).first + ) end def test_reference_links_name_a_definition_and_every_definition_is_used Blocks::DOCUMENTS.each do |path| assert_empty Blocks.reference_link_problems(Blocks.read(path), path) end - assert_empty Blocks.reference_link_problems("A [`call`][call].\n\n[call]: https://example.test/\n", "control.md") - mistyped = Blocks.reference_link_problems("A [`call`][cal].\n\n[call]: https://example.test/\n", "control.md") - assert_equal ["control.md: the link label [cal] has no definition", - "control.md: the link definition [call] is not used"], mistyped + assert_empty Blocks.reference_link_problems( + "A [`call`][call].\n\n[call]: https://example.test/\n", + "control.md" + ) + mistyped = + Blocks.reference_link_problems( + "A [`call`][cal].\n\n[call]: https://example.test/\n", + "control.md" + ) + assert_equal [ + "control.md: the link label [cal] has no definition", + "control.md: the link definition [call] is not used" + ], + mistyped fenced = "```ruby\nlist[0][1]\n```\n\n[call]: https://example.test/\n" - assert_equal ["control.md: the link definition [call] is not used"], Blocks.reference_link_problems(fenced, "control.md") + assert_equal ["control.md: the link definition [call] is not used"], + Blocks.reference_link_problems(fenced, "control.md") end def test_contents_links_land_on_headings - Blocks::DOCUMENTS.each do |path| - assert_empty Blocks.anchor_problems(Blocks.read(path), path) - end - page = "## Quick start\n\n### [`Server#list_sessions`][list]: what tmux has now\n\n" \ - "### Repeat\n\n### Repeat\n\n[a](#quick-start) [b](#serverlist_sessions-what-tmux-has-now) [c](#repeat-1)\n" + Blocks::DOCUMENTS.each { |path| assert_empty Blocks.anchor_problems(Blocks.read(path), path) } + page = + "## Quick start\n\n### [`Server#list_sessions`][list]: what tmux has now\n\n" \ + "### Repeat\n\n### Repeat\n\n[a](#quick-start) [b](#serverlist_sessions-what-tmux-has-now) [c](#repeat-1)\n" assert_empty Blocks.anchor_problems(page, "control.md") missing = Blocks.anchor_problems("## Quick start\n\n[a](#quick-starts)\n", "control.md") assert_equal ["control.md: no heading has the anchor #quick-starts"], missing - in_fence = Blocks.anchor_problems("```ruby\n## Quick start\n```\n\n[a](#quick-start)\n", "control.md") + in_fence = + Blocks.anchor_problems("```ruby\n## Quick start\n```\n\n[a](#quick-start)\n", "control.md") refute_empty in_fence end def test_the_mcp_readme_lists_every_tool_of_the_catalog_in_its_table - rows = Blocks.read("gems/libtmux-mcp/README.md").lines.grep(/\A\| .*\[`tmux_.* \| (?:Enabled|Disabled) \|/) + rows = + Blocks + .read("gems/libtmux-mcp/README.md") + .lines + .grep(/\A\| .*\[`tmux_.* \| (?:Enabled|Disabled) \|/) names = rows.flat_map { |row| row.split(" | ").first.scan(/\[`(tmux_[a-z_]+)`\]/).flatten } assert_equal TOOLS.sort, names.sort assert_equal 4, rows.length end def test_the_gem_index_keeps_its_rows - {"README.md" => "[%s](gems/%s/README.md)", "gems/libtmux/README.md" => "[%s](#{Blocks::GEM_TREE}/%s)"}.each do |path, link| - assert_empty Blocks.gem_index_problems(Blocks.read(path), path, gems: Blocks::GEMS, link: link) + { + "README.md" => "[%s](gems/%s/README.md)", + "gems/libtmux/README.md" => "[%s](#{Blocks::GEM_TREE}/%s)" + }.each do |path, link| + assert_empty Blocks.gem_index_problems( + Blocks.read(path), + path, + gems: Blocks::GEMS, + link: link + ) end - without = Blocks.read("README.md").lines.reject { |line| line.start_with?("| [libtmux-async]") }.join - refute_empty Blocks.gem_index_problems(without, "control.md", gems: Blocks::GEMS, link: "[%s](gems/%s/README.md)") + without = + Blocks.read("README.md").lines.reject { |line| line.start_with?("| [libtmux-async]") }.join + refute_empty Blocks.gem_index_problems( + without, + "control.md", + gems: Blocks::GEMS, + link: "[%s](gems/%s/README.md)" + ) end def test_contributing_names_the_one_artifact_the_version_bump_rewrites load File.join(Blocks::ROOT, "scripts/version/version.rb") unless defined?(VersionBump) - current = Gem::Specification.load(File.join(Blocks::ROOT, "gems/libtmux/libtmux.gemspec")).version + current = + Gem::Specification.load(File.join(Blocks::ROOT, "gems/libtmux/libtmux.gemspec")).version bump = VersionBump.new(Blocks::ROOT) contributing = Blocks.read(".github/CONTRIBUTING.md") bump.send(:validate_artifact_doc, contributing, current) @@ -152,12 +207,25 @@ def test_documented_flags_belong_to_the_executable help = StringIO.new assert_equal 0, cli.run(["--help"], out: help, err: StringIO.new) Blocks::DOCUMENTS.each do |path| - problems = Blocks.flag_problems(Blocks.read(path), path, program: program, help: help.string, prose: path == own) + problems = + Blocks.flag_problems( + Blocks.read(path), + path, + program: program, + help: help.string, + prose: path == own + ) assert_empty problems end invented = "```console\n$ #{program} --no-such-option\n```\n" refute_empty Blocks.flag_problems(invented, "control.md", program: program, help: help.string) - refute_empty Blocks.flag_problems("Pass `--no-such-option` to it.\n", "control.md", program: program, help: help.string, prose: true) + refute_empty Blocks.flag_problems( + "Pass `--no-such-option` to it.\n", + "control.md", + program: program, + help: help.string, + prose: true + ) end end end diff --git a/test/unit/replay_test.rb b/test/unit/replay_test.rb index 48af4358..87ef73fd 100644 --- a/test/unit/replay_test.rb +++ b/test/unit/replay_test.rb @@ -32,7 +32,7 @@ def test_failure RUBY executable = File.join(directory, "custom tmux") - env = {"SEED" => "321", "LIBTMUX_TEST_TMUX" => executable} + env = { "SEED" => "321", "LIBTMUX_TEST_TMUX" => executable } report, original = Open3.capture2e(env, Gem.ruby, "scripts/check", "unit", fixture) refute original.success? assert_includes report, "4 runs" @@ -43,7 +43,7 @@ def test_failure refute status.success?, repeated assert_includes repeated, "--seed 321" assert_includes repeated, "replay canary" - refute_includes repeated, "replay canary in #{ENV.fetch('TMUX_TMPDIR')}" + refute_includes repeated, "replay canary in #{ENV.fetch("TMUX_TMPDIR")}" assert_includes repeated, "using #{executable}" assert_includes repeated, "1 runs" end diff --git a/test/unit/sandbox_test.rb b/test/unit/sandbox_test.rb index f48cdaf5..363241a7 100644 --- a/test/unit/sandbox_test.rb +++ b/test/unit/sandbox_test.rb @@ -13,8 +13,13 @@ # assertion prints the log and the child inherits the developer's environment. class SandboxTest < Minitest::Test Sandbox = LibTmuxTest::Sandbox - DECOYS = {"TMUX" => "/decoy/server,1,0", "TMUX_PANE" => "%9", "LIBTMUX_SOCKET" => "decoy-name", - "LIBTMUX_SOCKET_PATH" => "/decoy/path", "LIBTMUX_SOCKET_NAME" => "decoy-other"}.freeze + DECOYS = { + "TMUX" => "/decoy/server,1,0", + "TMUX_PANE" => "%9", + "LIBTMUX_SOCKET" => "decoy-name", + "LIBTMUX_SOCKET_PATH" => "/decoy/path", + "LIBTMUX_SOCKET_NAME" => "decoy-other" + }.freeze TESTS = File.expand_path("..", __dir__) RECORDER = <<~'STUB' File.open(ENV.fetch("FAKE_TMUX_LOG"), "a") do |log| @@ -34,7 +39,8 @@ class SandboxTest < Minitest::Test def test_this_process_is_sandboxed assert_empty Sandbox.violations(ENV) - assert ENV.fetch("TMUX_TMPDIR") == ENV.fetch(Sandbox::MARKER), "TMUX_TMPDIR is not the marked sandbox" + assert ENV.fetch("TMUX_TMPDIR") == ENV.fetch(Sandbox::MARKER), + "TMUX_TMPDIR is not the marked sandbox" end def test_every_selector_is_named_without_its_value @@ -47,20 +53,28 @@ def test_every_selector_is_named_without_its_value end def test_unrelated_variables_and_unset_selectors_stay_quiet - env = ENV.to_h.merge("LIBTMUX_TEST_TMUX" => "tmux", "LIBTMUX_RELEASE_DIR" => "pkg", "TMUX_VERSION" => "3.8", - "TMUX" => nil, "LIBTMUX_SOCKET" => nil) + env = + ENV.to_h.merge( + "LIBTMUX_TEST_TMUX" => "tmux", + "LIBTMUX_RELEASE_DIR" => "pkg", + "TMUX_VERSION" => "3.8", + "TMUX" => nil, + "LIBTMUX_SOCKET" => nil + ) assert_empty Sandbox.violations(env) end def test_tmux_tmpdir_must_be_the_sandbox_of_this_run directory = ENV.fetch("TMUX_TMPDIR") marked = ->(path) { ENV.to_h.merge("TMUX_TMPDIR" => path, Sandbox::MARKER => path) } - [["is unset", ENV.to_h.merge("TMUX_TMPDIR" => nil)], - ["is not an absolute path", marked.call("relative/lt-rb-x")], - ["is longer than", marked.call(File.join(directory, "x" * Sandbox::MAX_BYTES))], - ["is not the sandbox directory of this run", ENV.to_h.merge("TMUX_TMPDIR" => "/tmp")], - ["is not the sandbox directory of this run", ENV.to_h.merge(Sandbox::MARKER => nil)], - ["missing", marked.call("#{directory}x")]].each do |expected, env| + [ + ["is unset", ENV.to_h.merge("TMUX_TMPDIR" => nil)], + ["is not an absolute path", marked.call("relative/lt-rb-x")], + ["is longer than", marked.call(File.join(directory, "x" * Sandbox::MAX_BYTES))], + ["is not the sandbox directory of this run", ENV.to_h.merge("TMUX_TMPDIR" => "/tmp")], + ["is not the sandbox directory of this run", ENV.to_h.merge(Sandbox::MARKER => nil)], + ["missing", marked.call("#{directory}x")] + ].each do |expected, env| found = Sandbox.violations(env) assert_equal 1, found.length, expected assert_includes found.first, expected @@ -69,11 +83,13 @@ def test_tmux_tmpdir_must_be_the_sandbox_of_this_run def test_tmux_tmpdir_must_be_owner_only Dir.mktmpdir(Sandbox::PREFIX, "/tmp") do |directory| - env = {"TMUX_TMPDIR" => directory, Sandbox::MARKER => directory} + env = { "TMUX_TMPDIR" => directory, Sandbox::MARKER => directory } assert_empty Sandbox.violations(env) [0o750, 0o705, 0o755].each do |mode| File.chmod(mode, directory) - assert_equal ["the sandbox directory is open to group or others"], Sandbox.violations(env), mode.to_s(8) + assert_equal ["the sandbox directory is open to group or others"], + Sandbox.violations(env), + mode.to_s(8) end end end @@ -83,7 +99,10 @@ def test_prepare_clears_selectors_and_makes_a_short_private_directory directory, created = Sandbox.prepare(env) assert created assert_empty Sandbox.violations(env) - assert_equal({"TMUX_TMPDIR" => directory, Sandbox::MARKER => directory, "LIBTMUX_RELEASE_DIR" => "kept"}, env) + assert_equal( + { "TMUX_TMPDIR" => directory, Sandbox::MARKER => directory, "LIBTMUX_RELEASE_DIR" => "kept" }, + env + ) assert_operator directory.bytesize, :<=, Sandbox::MAX_BYTES assert_equal 0o700, File.stat(directory).mode & 0o777 refute directory == ENV.fetch("TMUX_TMPDIR"), "made no directory of its own" @@ -106,7 +125,8 @@ def test_the_longest_socket_path_the_sandbox_allows_fits_in_a_hundred_bytes worst_uid = "tmux-4294967295" longest_name = "n" * 20 largest = File.join("/" + "x" * (Sandbox::MAX_BYTES - 1), worst_uid, longest_name) - assert largest.bytesize <= 100, "a socket path in the largest sandbox directory is over 100 bytes" + assert largest.bytesize <= 100, + "a socket path in the largest sandbox directory is over 100 bytes" actual = File.join(ENV.fetch("TMUX_TMPDIR"), worst_uid, longest_name) assert actual.bytesize <= 100, "a socket path in this run's sandbox is over 100 bytes" end @@ -128,9 +148,11 @@ def test_prepare_refuses_without_a_directory_short_enough_for_a_socket end def test_a_run_that_cannot_make_its_directory_exits_2_and_says_it_refused - code = 'require "tmpdir"; Dir.define_singleton_method(:mktmpdir) { |*| raise Errno::EACCES }; load ARGV.fetch(0)' + code = + 'require "tmpdir"; Dir.define_singleton_method(:mktmpdir) { |*| raise Errno::EACCES }; load ARGV.fetch(0)' env = DECOYS.merge("TMUX_TMPDIR" => "/decoy/tmpdir", Sandbox::MARKER => nil) - _, error, status = Open3.capture3(env, Gem.ruby, "-e", code, File.join(TESTS, "support", "sandbox.rb")) + _, error, status = + Open3.capture3(env, Gem.ruby, "-e", code, File.join(TESTS, "support", "sandbox.rb")) assert_equal 2, status.exitstatus assert_includes error, "libtmux-ruby tests refused to run" refute_match(/decoy/, error) @@ -164,7 +186,10 @@ def test_a_link_to_a_socket_elsewhere_is_not_a_leak_and_is_not_stopped def test_release_stops_each_server_wherever_it_sits_and_removes_the_directory with_directories do |directory, bin| - sockets = [%w[tmux-1000 default], %w[custom.sock], %w[a b c.sock]].map { |path| listen(directory, *path) } + sockets = + [%w[tmux-1000 default], %w[custom.sock], %w[a b c.sock]].map do |path| + listen(directory, *path) + end log = File.join(bin, "calls") kill = fake_tmux(bin, <<~'STUB', LOG: log) File.write(LOG, "#{ARGV[2]} #{ARGV[1]}\n", mode: "a") @@ -173,7 +198,8 @@ def test_release_stops_each_server_wherever_it_sits_and_removes_the_directory released = Sandbox.release(directory, tmux: kill, wait: 1) assert_equal %w[a/b/c.sock custom.sock tmux-1000/default], released.leaked assert_empty released.answering - assert_equal sockets.sort.map { |socket| "kill-server #{socket}" }, File.read(log).lines.map(&:chomp).sort + assert_equal sockets.sort.map { |socket| "kill-server #{socket}" }, + File.read(log).lines.map(&:chomp).sort refute File.exist?(directory) end end @@ -202,7 +228,8 @@ def test_release_keeps_the_directory_while_a_server_still_answers released = Sandbox.release(directory, tmux: one, wait: 0.2) assert_equal %w[custom.sock gone.sock], released.leaked assert_equal %w[custom.sock], released.answering - assert File.exist?(File.join(directory, "custom.sock")), "removed the directory of a live server" + assert File.exist?(File.join(directory, "custom.sock")), + "removed the directory of a live server" message = released.message(directory) assert_includes message, "custom.sock" assert_includes message, "#{File.basename(directory)} was kept" @@ -239,7 +266,8 @@ def test_release_does_not_wait_on_a_stop_that_never_returns elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started assert_equal %w[custom.sock], released.answering assert elapsed < 5, "the stop held the run for as long as the hung client" - assert File.exist?(File.join(directory, "custom.sock")), "removed the directory of a live server" + assert File.exist?(File.join(directory, "custom.sock")), + "removed the directory of a live server" end end @@ -255,8 +283,10 @@ def test_release_keeps_the_directory_when_there_is_no_tmux_to_stop_the_server def test_the_overlay_unsets_what_a_saved_environment_may_carry overlay = Sandbox.overlay(DECOYS.merge("PATH" => "/bin")) DECOYS.each_key { |name| assert overlay.key?(name) && overlay[name].nil?, name } - assert ENV.fetch("TMUX_TMPDIR") == overlay.fetch("TMUX_TMPDIR"), "overlay names another TMUX_TMPDIR" - assert ENV.fetch(Sandbox::MARKER) == overlay.fetch(Sandbox::MARKER), "overlay names another marker" + assert ENV.fetch("TMUX_TMPDIR") == overlay.fetch("TMUX_TMPDIR"), + "overlay names another TMUX_TMPDIR" + assert ENV.fetch(Sandbox::MARKER) == overlay.fetch(Sandbox::MARKER), + "overlay names another marker" refute overlay.key?("PATH") assert_equal Sandbox::NAMES.sort, Sandbox.overlay({}).select { |_, value| value.nil? }.keys.sort end @@ -281,8 +311,9 @@ def test_the_same_child_without_the_sandbox_hands_tmux_every_selector end def test_a_run_that_leaves_a_socket_in_the_sandbox_fails_and_stops_that_server - code = 'require "socket"; require "fileutils"; socket = File.join(ENV.fetch("TMUX_TMPDIR"), *ARGV); ' \ - 'FileUtils.mkdir_p(File.dirname(socket)); UNIXServer.new(socket); puts ENV.fetch("TMUX_TMPDIR")' + code = + 'require "socket"; require "fileutils"; socket = File.join(ENV.fetch("TMUX_TMPDIR"), *ARGV); ' \ + 'FileUtils.mkdir_p(File.dirname(socket)); UNIXServer.new(socket); puts ENV.fetch("TMUX_TMPDIR")' [["tmux-#{Process.uid}", "default"], ["custom.sock"]].each do |path| with_recorder("FAKE_TMUX_KILLS" => "1") do |recorder, run| output, error, status = run.call(true, code, *path) @@ -290,15 +321,16 @@ def test_a_run_that_leaves_a_socket_in_the_sandbox_fails_and_stops_that_server assert_equal 1, status.exitstatus, path.join("/") assert_includes error, path.join("/") refute_includes error, "answers" - assert_equal ["ARG -S", "ARG #{sandbox}/#{path.join('/')}", "ARG kill-server"], - File.read(recorder).lines.map(&:chomp).grep(/\AARG /) + assert_equal ["ARG -S", "ARG #{sandbox}/#{path.join("/")}", "ARG kill-server"], + File.read(recorder).lines.map(&:chomp).grep(/\AARG /) refute File.exist?(sandbox) end end end def test_a_run_whose_server_survives_kill_server_keeps_the_sandbox_and_says_so - code = 'require "socket"; UNIXServer.new(File.join(ENV.fetch("TMUX_TMPDIR"), "custom.sock")); puts ENV.fetch("TMUX_TMPDIR")' + code = + 'require "socket"; UNIXServer.new(File.join(ENV.fetch("TMUX_TMPDIR"), "custom.sock")); puts ENV.fetch("TMUX_TMPDIR")' with_recorder do |_recorder, run| output, error, status = run.call(true, code) sandbox = output.chomp @@ -321,8 +353,15 @@ def test_the_canary_failure_does_not_echo_what_tmux_printed puts "error connecting to /lt-rb-echo-decoy/socket (No such file or directory)" exit 1 STUB - output, error, status = Open3.capture3({"LIBTMUX_TEST_TMUX" => printer}, Gem.ruby, "-I#{TESTS}", canary, "-n", - "test_a_client_that_names_no_socket_looks_only_in_the_sandbox") + output, error, status = + Open3.capture3( + { "LIBTMUX_TEST_TMUX" => printer }, + Gem.ruby, + "-I#{TESTS}", + canary, + "-n", + "test_a_client_that_names_no_socket_looks_only_in_the_sandbox" + ) refute_predicate status, :success?, "the canary accepted a client that looked elsewhere" assert_includes output, "the client looked outside the sandbox" refute_includes output + error, "lt-rb-echo-decoy" @@ -343,10 +382,25 @@ def test_the_benchmark_enters_the_sandbox_before_it_starts_tmux bench = File.expand_path("../../scripts/bench", __dir__) with_recorder do |recorder, _run, env| directory = File.dirname(recorder) - arguments = ["run", "--output", File.join(directory, "evidence"), "--panes", "1", "--samples", "2", - "--tmux", File.join(directory, "bin", "tmux")] - _, error, status = Open3.capture3(env.merge("TMPDIR" => directory), Gem.ruby, bench, *arguments, - chdir: File.expand_path("../..", __dir__)) + arguments = [ + "run", + "--output", + File.join(directory, "evidence"), + "--panes", + "1", + "--samples", + "2", + "--tmux", + File.join(directory, "bin", "tmux") + ] + _, error, status = + Open3.capture3( + env.merge("TMPDIR" => directory), + Gem.ruby, + bench, + *arguments, + chdir: File.expand_path("../..", __dir__) + ) refute_predicate status, :success?, "the recorder serves no benchmark" calls = File.read(recorder) assert_includes calls, "ARG -V\n", error @@ -370,7 +424,14 @@ def test_selectors_are_gone_and_tmux_tmpdir_is_a_sandbox end RUBY env = DECOYS.merge("TMUX_TMPDIR" => "/decoy/tmpdir", Sandbox::MARKER => nil) - _, error, status = Open3.capture3(env, Gem.ruby, File.expand_path("../../scripts/check", __dir__), "unit", probe) + _, error, status = + Open3.capture3( + env, + Gem.ruby, + File.expand_path("../../scripts/check", __dir__), + "unit", + probe + ) assert_predicate status, :success?, error _, _, status = Open3.capture3(env, Gem.ruby, probe) refute_predicate status, :success? @@ -416,12 +477,19 @@ def with_recorder(extra = {}) Dir.mkdir(bin) LibTmuxTest::StubExecutable.write(File.join(bin, "tmux"), RECORDER) log = File.join(directory, "calls") - env = DECOYS.merge("TMUX_TMPDIR" => "/decoy/tmpdir", Sandbox::MARKER => nil, "FAKE_TMUX_LOG" => log, - "PATH" => "#{bin}#{File::PATH_SEPARATOR}#{ENV.fetch('PATH')}", "LIBTMUX_TEST_TMUX" => "tmux").merge(extra) - run = lambda do |preload, code, *arguments| - preloads = preload ? ["-rsupport/sandbox"] : [] - Open3.capture3(env, Gem.ruby, "-I#{TESTS}", *preloads, "-e", code, *arguments) - end + env = + DECOYS.merge( + "TMUX_TMPDIR" => "/decoy/tmpdir", + Sandbox::MARKER => nil, + "FAKE_TMUX_LOG" => log, + "PATH" => "#{bin}#{File::PATH_SEPARATOR}#{ENV.fetch("PATH")}", + "LIBTMUX_TEST_TMUX" => "tmux" + ).merge(extra) + run = + lambda do |preload, code, *arguments| + preloads = preload ? ["-rsupport/sandbox"] : [] + Open3.capture3(env, Gem.ruby, "-I#{TESTS}", *preloads, "-e", code, *arguments) + end yield log, run, env end end diff --git a/test/unit/schema_test.rb b/test/unit/schema_test.rb index 9d749fc1..f87bfb91 100644 --- a/test/unit/schema_test.rb +++ b/test/unit/schema_test.rb @@ -12,35 +12,58 @@ def test_generated_schema_and_decoder_accept_the_same_wire_grammar assert JSONSchemer.valid_schema?(schema) validator = JSONSchemer.schema(schema) accepted = { - pane: [{}, {active: false}, {currentCommand: {startsWith: "nv"}}, - {deadStatus: nil}, {index: {not: {in: [2, 12]}}}, {or: []}], - window: [{panes: {some: {active: true, currentCommand: "cat"}}}, - {activePane: {isNot: nil}}], - session: [{currentWindow: {is: {panes: {every: {dead: false}}}}}], - window_link: [{index: {gte: 0}}], - client: [{height: nil}, {session: {is: nil}}] + pane: [ + {}, + { active: false }, + { currentCommand: { startsWith: "nv" } }, + { deadStatus: nil }, + { index: { not: { in: [2, 12] } } }, + { or: [] } + ], + window: [ + { panes: { some: { active: true, currentCommand: "cat" } } }, + { activePane: { isNot: nil } } + ], + session: [{ currentWindow: { is: { panes: { every: { dead: false } } } } }], + window_link: [{ index: { gte: 0 } }], + client: [{ height: nil }, { session: { is: nil } }] } accepted.each do |entity, cases| cases.each do |where| - envelope = {profile: LibTmux::FilterExpr::PROFILE, version: 1, entity: entity.to_s, where: where} + envelope = { + profile: LibTmux::FilterExpr::PROFILE, + version: 1, + entity: entity.to_s, + where: where + } input = JSON.parse(JSON.generate(envelope)) assert validator.valid?(input), "schema rejected #{entity} criterion" expression = LibTmux::FilterExpr.from_json(JSON.generate(input)) assert validator.valid?(expression.to_h), "schema rejected normalized #{entity} criterion" end end - rejected = [{active: "0"}, {active: nil}, {index: -1}, {index: 4_294_967_296}, - {index: {contains: "1"}}, {current_command: "cat"}, - {currentCommand: {starts_with: "ca"}}, {currentCommand: {regex: "cat"}}, - {window: {is: nil}}, {unknownField: true}, {or: [{}, {title: 7}]}] + rejected = [ + { active: "0" }, + { active: nil }, + { index: -1 }, + { index: 4_294_967_296 }, + { index: { contains: "1" } }, + { current_command: "cat" }, + { currentCommand: { starts_with: "ca" } }, + { currentCommand: { regex: "cat" } }, + { window: { is: nil } }, + { unknownField: true }, + { or: [{}, { title: 7 }] } + ] rejected.each do |where| - envelope = {profile: LibTmux::FilterExpr::PROFILE, version: 1, entity: "pane", where: where} + envelope = { profile: LibTmux::FilterExpr::PROFILE, version: 1, entity: "pane", where: where } wire = JSON.generate(envelope) refute validator.valid?(JSON.parse(wire)), "schema accepted invalid criterion" assert_raises(LibTmux::InvalidFilterError) { LibTmux::FilterExpr.from_json(wire) } end # JSON Schema integers are mathematical; the Ruby decoder also rejects float tokens. - float_token = '{"profile":"libtmux-ruby.where","version":1,"entity":"pane","where":{"index":1.0}}' + float_token = + '{"profile":"libtmux-ruby.where","version":1,"entity":"pane","where":{"index":1.0}}' assert validator.valid?(JSON.parse(float_token)) assert_raises(LibTmux::InvalidFilterError) { LibTmux::FilterExpr.from_json(float_token) } end diff --git a/test/unit/selection_test.rb b/test/unit/selection_test.rb index c06e23eb..85c8b608 100644 --- a/test/unit/selection_test.rb +++ b/test/unit/selection_test.rb @@ -45,11 +45,12 @@ def test_filter_blocks_keep_truthiness_control_flow_and_original_exceptions error = RuntimeError.new("block failure") assert_same error, assert_raises(RuntimeError) { selection.find_all { raise error } } visited = [] - result = selection.select do |value| - visited << value - next false if value.nil? - true - end + result = + selection.select do |value| + visited << value + next false if value.nil? + true + end assert_equal [false, nil, 0, ""], visited assert_equal [false, 0, ""], result.to_a end diff --git a/test/unit/snapshot_test.rb b/test/unit/snapshot_test.rb index acee4d0f..1ca3d5a4 100644 --- a/test/unit/snapshot_test.rb +++ b/test/unit/snapshot_test.rb @@ -2,7 +2,9 @@ require_relative "../test_helper" require "libtmux" -require "libtmux/snapshot" if File.exist?(File.expand_path("../../gems/libtmux/lib/libtmux/snapshot.rb", __dir__)) +if File.exist?(File.expand_path("../../gems/libtmux/lib/libtmux/snapshot.rb", __dir__)) + require "libtmux/snapshot" +end class SnapshotTest < Minitest::Test def test_graph_owns_values_orders_numeric_ids_and_retains_link_occurrences @@ -13,15 +15,15 @@ def test_graph_owns_values_orders_numeric_ids_and_retains_link_occurrences rows.fetch(:pane).clear assert capture.frozen? - assert_equal ["@2", "@10"], capture.windows.map(&:id) - assert_equal ["%2", "%10"], capture.panes.map(&:id) + assert_equal %w[@2 @10], capture.windows.map(&:id) + assert_equal %w[%2 %10], capture.panes.map(&:id) session = capture.sessions.one assert_equal "session", session.name assert session.name.frozen? assert_equal [2, 5, 10], session.window_links.map(&:index) - assert_equal ["@2", "@2", "@10"], session.windows.map(&:id) + assert_equal %w[@2 @2 @10], session.windows.map(&:id) assert_same session.windows.first, session.windows.to_a.fetch(1) - assert_equal ["%10", "%2"], capture.windows.first.panes.map(&:id) + assert_equal %w[%10 %2], capture.windows.first.panes.map(&:id) assert_equal 2, capture.windows.first.window_links.size assert_same capture.windows.first, capture.panes.first.window assert_same capture.panes.first, capture.windows.first.active_pane @@ -89,19 +91,34 @@ def test_invalid_text_keeps_raw_bytes_without_hiding_unrelated_fields def test_coverage_distinguishes_absent_empty_unloaded_incomplete_and_unsupported full = build(graph_rows) assert_nil full.panes.first.dead_status - empty = build({session: [], window: [], pane: [], window_link: []}) + empty = build({ session: [], window: [], pane: [], window_link: [] }) assert_empty empty.panes - partial = build({pane: [{id: "%1", window_id: "@1", index: "0"}]}) + partial = build({ pane: [{ id: "%1", window_id: "@1", index: "0" }] }) pane = partial.panes.one assert_equal :unloaded, pane.__send__(:field_coverage, :title) assert_equal :unloaded, pane.__send__(:relation_coverage, :window) assert_raises(LibTmux::IncompleteSnapshotError) { pane.window } assert_raises(LibTmux::IncompleteSnapshotError) { pane.title } assert_raises(LibTmux::IncompleteSnapshotError) { partial.windows } - unavailable = build(graph_rows, coverage: {pane: {fields: {title: :unsupported}}, window: {relations: {panes: :incomplete}}}) + unavailable = + build( + graph_rows, + coverage: { + pane: { + fields: { + title: :unsupported + } + }, + window: { + relations: { + panes: :incomplete + } + } + } + ) assert_raises(LibTmux::UnsupportedFeatureError) { unavailable.panes.first.title } assert_raises(LibTmux::IncompleteSnapshotError) { unavailable.windows.first.panes } - no_children = build({window: [{id: "@0"}], pane: []}) + no_children = build({ window: [{ id: "@0" }], pane: [] }) assert_nil no_children.windows.one.active_pane end @@ -125,17 +142,43 @@ def test_catalog_is_explicit_typed_and_deeply_frozen end def test_declared_coverage_cannot_invent_missing_values_or_relations - partial = build({pane: [{id: "%1", window_id: "@1", index: "0"}]}, - coverage: {pane: {fields: {title: :complete}, relations: {window: :complete}}}) + partial = + build( + { pane: [{ id: "%1", window_id: "@1", index: "0" }] }, + coverage: { + pane: { + fields: { + title: :complete + }, + relations: { + window: :complete + } + } + } + ) pane = partial.panes.one assert_equal :unloaded, pane.__send__(:field_coverage, :title) assert_equal :unloaded, pane.__send__(:relation_coverage, :window) assert_raises(LibTmux::IncompleteSnapshotError) { pane.title } assert_raises(LibTmux::IncompleteSnapshotError) { pane.window } - observed = build({client: [{name: "control", pid: "1", created: "2", session_id: ""}]}) + observed = build({ client: [{ name: "control", pid: "1", created: "2", session_id: "" }] }) assert_nil observed.clients.one.session assert_raises(LibTmux::UnsupportedFeatureError) { observed.clients.one.ref } - per_record = build(graph_rows, coverage: {pane: {records: {"%2" => {fields: {title: :unsupported}}}}}) + per_record = + build( + graph_rows, + coverage: { + pane: { + records: { + "%2" => { + fields: { + title: :unsupported + } + } + } + } + } + ) assert_raises(LibTmux::UnsupportedFeatureError) { per_record.panes.first.title } assert_equal "sibling", per_record.panes.to_a.last.title end @@ -144,22 +187,34 @@ def test_declared_coverage_cannot_invent_missing_values_or_relations def build(rows, **options) assert defined?(LibTmux::Snapshot), "captured graph is not implemented" - LibTmux::Snapshot.__send__(:new, rows: rows, binding_key: "binding", started_at: 1.0, - finished_at: 2.0, reads: [], server_info: {}, **options) + LibTmux::Snapshot.__send__( + :new, + rows: rows, + binding_key: "binding", + started_at: 1.0, + finished_at: 2.0, + reads: [], + server_info: { + }, + **options + ) end def graph_rows { - session: [{id: "$2", name: +"session", window_count: "3"}], - window: [{id: "@10", name: "second", pane_count: "0"}, {id: "@2", name: "shared", pane_count: "2"}], + session: [{ id: "$2", name: +"session", window_count: "3" }], + window: [ + { id: "@10", name: "second", pane_count: "0" }, + { id: "@2", name: "shared", pane_count: "2" } + ], pane: [ - {id: "%2", window_id: "@2", index: "4", title: "title", active: "1", dead_status: ""}, - {id: "%10", window_id: "@2", index: "0", title: "sibling", active: "0", dead_status: ""} + { id: "%2", window_id: "@2", index: "4", title: "title", active: "1", dead_status: "" }, + { id: "%10", window_id: "@2", index: "0", title: "sibling", active: "0", dead_status: "" } ], window_link: [ - {session_id: "$2", window_id: "@10", index: "10", active: "0"}, - {session_id: "$2", window_id: "@2", index: "5", active: "0"}, - {session_id: "$2", window_id: "@2", index: "2", active: "1"} + { session_id: "$2", window_id: "@10", index: "10", active: "0" }, + { session_id: "$2", window_id: "@2", index: "5", active: "0" }, + { session_id: "$2", window_id: "@2", index: "2", active: "1" } ] } end diff --git a/test/unit/source_query_test.rb b/test/unit/source_query_test.rb index 017df2ad..bbbd1c3c 100644 --- a/test/unit/source_query_test.rb +++ b/test/unit/source_query_test.rb @@ -20,15 +20,34 @@ def snapshot(**options) end def test_plan_has_no_io_and_local_modes_capture_once_without_restricting_relations - rows = {window: [{id: "@1"}], pane: [ - {id: "%1", window_id: "@1", index: "0", current_command: "cat"}, - {id: "%2", window_id: "@1", index: "1", current_command: "nvim"} - ]} - graph = LibTmux::Snapshot.__send__(:new, rows: rows, binding_key: "binding", - started_at: 1.0, finished_at: 2.0, reads: [], server_info: {}) + rows = { + window: [{ id: "@1" }], + pane: [ + { id: "%1", window_id: "@1", index: "0", current_command: "cat" }, + { id: "%2", window_id: "@1", index: "1", current_command: "nvim" } + ] + } + graph = + LibTmux::Snapshot.__send__( + :new, + rows: rows, + binding_key: "binding", + started_at: 1.0, + finished_at: 2.0, + reads: [], + server_info: { + } + ) source = Source.new(graph) %i[auto never].each do |mode| - plan = LibTmux::Internal::SourceQuery.new(:pane, where: {current_command: "nvim"}, pushdown: mode) + plan = + LibTmux::Internal::SourceQuery.new( + :pane, + where: { + current_command: "nvim" + }, + pushdown: mode + ) before = source.calls.size explanation = plan.explain assert_nil explanation.fetch(:pushed) @@ -38,28 +57,41 @@ def test_plan_has_no_io_and_local_modes_capture_once_without_restricting_relatio result = plan.execute(source, timeout: 0.5) assert_equal before + 1, source.calls.size assert_equal ["%2"], result.map(&:id) - assert_equal ["%1", "%2"], result.one.window.panes.map(&:id) + assert_equal %w[%1 %2], result.one.window.panes.map(&:id) result.to_a result.where(index: 1).one assert_equal before + 1, source.calls.size end - refute_empty LibTmux::Internal::SourceQuery.new(:pane, where: {}, pushdown: :auto).explain.fetch(:rejected_optimization_reasons) + refute_empty LibTmux::Internal::SourceQuery + .new(:pane, where: {}, pushdown: :auto) + .explain + .fetch(:rejected_optimization_reasons) end def test_invalid_criteria_and_required_pushdown_are_rejected_before_acquisition source = Source.new(nil) assert_raises(LibTmux::InvalidFilterError) do - LibTmux::Internal::SourceQuery.new(:pane, where: {active: "0"}, pushdown: :auto).execute(source) + LibTmux::Internal::SourceQuery.new(:pane, where: { active: "0" }, pushdown: :auto).execute( + source + ) end - assert_raises(ArgumentError) { LibTmux::Internal::SourceQuery.new(:pane, where: {}, pushdown: :sometimes) } - plan = LibTmux::Internal::SourceQuery.new(:pane, where: {index: {gt: 2}}, pushdown: :required) + assert_raises(ArgumentError) do + LibTmux::Internal::SourceQuery.new(:pane, where: {}, pushdown: :sometimes) + end + plan = + LibTmux::Internal::SourceQuery.new(:pane, where: { index: { gt: 2 } }, pushdown: :required) refute plan.explain.fetch(:executable) assert_raises(LibTmux::UnsupportedFeatureError) { plan.execute(source) } assert_empty source.calls - private_plan = LibTmux::Internal::SourceQuery.new(:pane, where: {current_path: "private-secret"}) + private_plan = + LibTmux::Internal::SourceQuery.new(:pane, where: { current_path: "private-secret" }) refute_includes private_plan.inspect, "private-secret" assert_raises(LibTmux::InvalidFilterError) do - LibTmux::Internal::SourceQuery.new(:pane, where: LibTmux::WindowWhere.build({}), pushdown: :never) + LibTmux::Internal::SourceQuery.new( + :pane, + where: LibTmux::WindowWhere.build({}), + pushdown: :never + ) end end end diff --git a/test/unit/support_test.rb b/test/unit/support_test.rb index 2e2d1310..705a8d4c 100644 --- a/test/unit/support_test.rb +++ b/test/unit/support_test.rb @@ -11,7 +11,10 @@ def test_the_minimum_is_shared_by_the_version_check def test_require_supported_returns_the_release_text_or_refuses assert_equal "3.8", LibTmux::Support.require_supported("3.8") - error = assert_raises(LibTmux::UnsupportedFeatureError) { LibTmux::Support::Versions.require_supported("3.3") } + error = + assert_raises(LibTmux::UnsupportedFeatureError) do + LibTmux::Support::Versions.require_supported("3.3") + end assert_equal :not_sent, error.delivery assert_match(/3\.3a or newer/, error.message) end diff --git a/test/unit/tmux_version_test.rb b/test/unit/tmux_version_test.rb index 03fe7c15..9ec05eb9 100644 --- a/test/unit/tmux_version_test.rb +++ b/test/unit/tmux_version_test.rb @@ -5,19 +5,20 @@ require "libtmux/tmux_version" class TmuxVersionTest < Minitest::Test - Report = Struct.new(:stdout, :stderr, :ok, keyword_init: true) do - def success? - ok - end + Report = + Struct.new(:stdout, :stderr, :ok, keyword_init: true) do + def success? + ok + end - def pid - nil - end + def pid + nil + end - def delivery - :observed + def delivery + :observed + end end - end def version LibTmux::Internal::TmuxVersion @@ -46,23 +47,54 @@ def test_development_builds_and_candidates_rank_below_their_release GRAMMAR = { accept: %w[3.3a 3.4 3.7d 3.8 3.10 4.0 3.4-rc 3.8-rc 3.8-rc2 3.8-rc999 next-3.4 next-3.9], below_floor: %w[3.3 3.2a 3.3-rc 3.2-rc5 next-3.3], - unparseable: ["master", "openbsd-7.6", "", "3", "garbage", "3.3a garbage", "3.3a-master", "3.3a-dev", "next-3.3a", - "next-3.9-master", "next-3.9a", "3.8a-rc2", "3.8-rcx", "3.8-RC2", "3.8-rc-2", "3.8-rc1000", "3.8-rc2000000"] + unparseable: [ + "master", + "openbsd-7.6", + "", + "3", + "garbage", + "3.3a garbage", + "3.3a-master", + "3.3a-dev", + "next-3.3a", + "next-3.9-master", + "next-3.9a", + "3.8a-rc2", + "3.8-rcx", + "3.8-RC2", + "3.8-rc-2", + "3.8-rc1000", + "3.8-rc2000000" + ] }.freeze - ORDER = [%w[next-3.7 3.7-rc 3.7-rc3 3.7 3.7a], %w[next-3.4 3.4-rc 3.4], %w[3.8-rc 3.8-rc2 3.8-rc999 3.8 3.8a 3.9], %w[3.9 3.10 4.0]].freeze + ORDER = [ + %w[next-3.7 3.7-rc 3.7-rc3 3.7 3.7a], + %w[next-3.4 3.4-rc 3.4], + %w[3.8-rc 3.8-rc2 3.8-rc999 3.8 3.8a 3.9], + %w[3.9 3.10 4.0] + ].freeze def test_version_grammar_vectors - GRAMMAR.fetch(:accept).each { |value| assert_equal value, version.require_supported(value).text, value } - GRAMMAR.fetch(:below_floor).each do |value| - assert_equal value, version.parse(value).text - assert_raises(LibTmux::UnsupportedFeatureError, value) { version.require_supported(value) } - end - GRAMMAR.fetch(:unparseable).each do |value| - error = assert_raises(LibTmux::UnsupportedFeatureError, value.inspect) { version.parse(value) } - assert_match(/unrecognized/, error.message) - end + GRAMMAR + .fetch(:accept) + .each { |value| assert_equal value, version.require_supported(value).text, value } + GRAMMAR + .fetch(:below_floor) + .each do |value| + assert_equal value, version.parse(value).text + assert_raises(LibTmux::UnsupportedFeatureError, value) { version.require_supported(value) } + end + GRAMMAR + .fetch(:unparseable) + .each do |value| + error = + assert_raises(LibTmux::UnsupportedFeatureError, value.inspect) { version.parse(value) } + assert_match(/unrecognized/, error.message) + end ORDER.each do |chain| - chain.each_cons(2) { |lower, higher| assert_operator version.parse(lower), :<, version.parse(higher), "#{lower} < #{higher}" } + chain.each_cons(2) do |lower, higher| + assert_operator version.parse(lower), :<, version.parse(higher), "#{lower} < #{higher}" + end end end @@ -75,7 +107,9 @@ def test_a_candidate_number_cannot_outrank_its_release def test_exactly_matches_only_the_numbered_release assert version.parse("3.7").exactly?(3, 7) - %w[3.7a 3.7-rc 3.7-rc2 next-3.7 3.8].each { |value| refute version.parse(value).exactly?(3, 7), value } + %w[3.7a 3.7-rc 3.7-rc2 next-3.7 3.8].each do |value| + refute version.parse(value).exactly?(3, 7), value + end end def test_control_gate_vectors @@ -83,8 +117,11 @@ def test_control_gate_vectors assert_equal value, version.require_control(version.parse(value)).text end %w[3.3a 3.6b 3.7-rc 3.7-rc2 next-3.7].each do |value| - error = assert_raises(LibTmux::UnsupportedFeatureError, value) { version.require_control(version.parse(value)) } - assert_equal [:not_sent, :admission], [error.delivery, error.phase] + error = + assert_raises(LibTmux::UnsupportedFeatureError, value) do + version.require_control(version.parse(value)) + end + assert_equal %i[not_sent admission], [error.delivery, error.phase] end end @@ -96,8 +133,29 @@ def test_the_floor_itself_is_met_only_by_its_release end def test_unrecognized_reports_fail_closed - ["master", "openbsd-7.5", "openbsd-3.9", "next-master", "3.4garbage", "3.7beta", "3.3a-unknown", "3.3A", "3.3aa", "3", "tmux 3.3a", "3.3a\n", " 3.3a", "3.3a\0", "", nil, 3.4].each do |value| - error = assert_raises(LibTmux::UnsupportedFeatureError, value.inspect) { version.require_supported(value) } + [ + "master", + "openbsd-7.5", + "openbsd-3.9", + "next-master", + "3.4garbage", + "3.7beta", + "3.3a-unknown", + "3.3A", + "3.3aa", + "3", + "tmux 3.3a", + "3.3a\n", + " 3.3a", + "3.3a\0", + "", + nil, + 3.4 + ].each do |value| + error = + assert_raises(LibTmux::UnsupportedFeatureError, value.inspect) do + version.require_supported(value) + end assert_equal :admission, error.phase assert_equal :not_sent, error.delivery end @@ -108,21 +166,29 @@ def test_unrecognized_reports_name_what_was_reported assert_match(/unrecognized \(the daemon reports "master"\)/, error.message) error = assert_raises(LibTmux::UnsupportedFeatureError) { version.parse("x" * 500) } assert_operator error.message.length, :<, 300 - error = assert_raises(LibTmux::UnsupportedFeatureError) do - version.executable("/tmp/tmux") { Report.new(stdout: "openbsd-7.6\n", stderr: "", ok: true) } - end + error = + assert_raises(LibTmux::UnsupportedFeatureError) do + version.executable("/tmp/tmux") do + Report.new(stdout: "openbsd-7.6\n", stderr: "", ok: true) + end + end assert_match(/unrecognized \(the executable reports "openbsd-7\.6"\)/, error.message) - error = assert_raises(LibTmux::UnsupportedFeatureError) do - version.executable("/tmp/tmux") { Report.new(stdout: "tmux 3.3\n", stderr: "", ok: true) } - end + error = + assert_raises(LibTmux::UnsupportedFeatureError) do + version.executable("/tmp/tmux") { Report.new(stdout: "tmux 3.3\n", stderr: "", ok: true) } + end assert_match(/\(the executable reports 3\.3\)/, error.message) refute_match(/connected version/, error.message) end def test_executable_report_accepts_tmux_and_the_executable_name path = "/tmp/selected tmux" - [["tmux 3.3a\n", path], ["selected tmux 3.3a\n", path], ["tmux-3.3a 3.3a\n", "/tmp/tmux-3.3a"], - ["selected-\xFF 3.7d\n".b, "/tmp/selected-\xFF".b]].each do |stdout, selected| + [ + ["tmux 3.3a\n", path], + ["selected tmux 3.3a\n", path], + ["tmux-3.3a 3.3a\n", "/tmp/tmux-3.3a"], + ["selected-\xFF 3.7d\n".b, "/tmp/selected-\xFF".b] + ].each do |stdout, selected| release = version.executable(selected) { Report.new(stdout: stdout, stderr: "", ok: true) } assert_equal stdout.split.last, release.text end @@ -130,34 +196,53 @@ def test_executable_report_accepts_tmux_and_the_executable_name def test_executable_report_refuses_old_malformed_and_failed_reports path = "/tmp/selected" - ["tmux 3.3\n", "tmux 3.2a\n", " tmux 3.3a\n", "other 3.3a\n", "tmux 3.3a\nextra\n", "tmux\n", "", "tmux 3.4garbage\n"].each do |stdout| - error = assert_raises(LibTmux::UnsupportedFeatureError, stdout) do - version.executable(path) { Report.new(stdout: stdout, stderr: "", ok: true) } - end + [ + "tmux 3.3\n", + "tmux 3.2a\n", + " tmux 3.3a\n", + "other 3.3a\n", + "tmux 3.3a\nextra\n", + "tmux\n", + "", + "tmux 3.4garbage\n" + ].each do |stdout| + error = + assert_raises(LibTmux::UnsupportedFeatureError, stdout) do + version.executable(path) { Report.new(stdout: stdout, stderr: "", ok: true) } + end assert_equal :not_sent, error.delivery end - error = assert_raises(LibTmux::CommandError) { version.executable(path) { Report.new(stdout: "", stderr: "x", ok: false) } } + error = + assert_raises(LibTmux::CommandError) do + version.executable(path) { Report.new(stdout: "", stderr: "x", ok: false) } + end assert_equal :not_sent, error.delivery end def test_connected_probe_reads_the_version_from_the_private_marker_error argv = nil - release = version.connected(["tmux", "-N", "-S", "route"]) do |command| - argv = command - marker = command.last.delete_suffix('#{version}') - Report.new(stdout: "", stderr: "unknown command: #{marker}3.7d\n", ok: false) - end + release = + version.connected(%w[tmux -N -S route]) do |command| + argv = command + marker = command.last.delete_suffix('#{version}') + Report.new(stdout: "", stderr: "unknown command: #{marker}3.7d\n", ok: false) + end assert_equal "3.7d", release.text - assert_equal ["tmux", "-N", "-S", "route", "run-shel", "-C"], argv.first(6) + assert_equal %w[tmux -N -S route run-shel -C], argv.first(6) assert_match(/\Alibtmux-version-\h{32}-\#\{version\}\z/, argv.last) end def test_connected_probe_refuses_an_older_daemon_before_effects - error = assert_raises(LibTmux::UnsupportedFeatureError) do - version.connected(["tmux"]) do |command| - Report.new(stdout: "", stderr: "unknown command: #{command.last.delete_suffix('#{version}')}3.3\n", ok: false) + error = + assert_raises(LibTmux::UnsupportedFeatureError) do + version.connected(["tmux"]) do |command| + Report.new( + stdout: "", + stderr: "unknown command: #{command.last.delete_suffix('#{version}')}3.3\n", + ok: false + ) + end end - end assert_match(/3\.3a or newer is required \(connected version 3\.3\)/, error.message) assert_equal :not_sent, error.delivery end @@ -165,16 +250,25 @@ def test_connected_probe_refuses_an_older_daemon_before_effects # tmux 3.1 does not know run-shell -C and prints its usage; a 3.0 daemon # speaks a protocol the client refuses outright. def test_connected_probe_maps_every_pre_3_2_answer_to_the_version_refusal - ["usage: run-shell [-b] [-t target-pane] shell-command\n", "server version is too old for client\n"].each do |stderr| - error = assert_raises(LibTmux::UnsupportedFeatureError, stderr) do - version.connected(["tmux"]) { Report.new(stdout: "", stderr: stderr, ok: false) } - end - assert_equal [:not_sent, :admission], [error.delivery, error.phase] - assert_match(/tmux 3\.3a or newer is required \(the connected daemon is older than 3\.2\); upgrade tmux and restart the server/, - error.message) - end - ["usage: run-shell [-bC] [-d delay] [-t target-pane] [shell-command]\n", "server version is too old for client\nextra\n", - "usage: run-shell [-b] [-t target-pane] shell-command\n\n"].each do |stderr| + [ + "usage: run-shell [-b] [-t target-pane] shell-command\n", + "server version is too old for client\n" + ].each do |stderr| + error = + assert_raises(LibTmux::UnsupportedFeatureError, stderr) do + version.connected(["tmux"]) { Report.new(stdout: "", stderr: stderr, ok: false) } + end + assert_equal %i[not_sent admission], [error.delivery, error.phase] + assert_match( + /tmux 3\.3a or newer is required \(the connected daemon is older than 3\.2\); upgrade tmux and restart the server/, + error.message + ) + end + [ + "usage: run-shell [-bC] [-d delay] [-t target-pane] [shell-command]\n", + "server version is too old for client\nextra\n", + "usage: run-shell [-b] [-t target-pane] shell-command\n\n" + ].each do |stderr| assert_raises(LibTmux::CommandError, stderr) do version.connected(["tmux"]) { Report.new(stdout: "", stderr: stderr, ok: false) } end @@ -184,21 +278,53 @@ def test_connected_probe_maps_every_pre_3_2_answer_to_the_version_refusal # The MCP result carries a fixed hint only for refusals of the daemon's # release; other unsupported features keep the generic text. def test_only_floor_refusals_are_marked_for_the_fixed_hint - refusals = [-> { version.require_supported("3.2a") }, -> { version.parse("master") }, - -> { version.executable("/tmp/tmux") { Report.new(stdout: "tmux 3.3\n", stderr: "", ok: true) } }, - -> { version.connected(["tmux"]) { Report.new(stdout: "", stderr: "server version is too old for client\n", ok: false) } }, - -> { version.check_fence(Report.new(stdout: "", stderr: "unknown command: m\n", ok: false), "m", version.parse("3.7d")) }] - refusals.each { |refusal| assert version.refusal?(assert_raises(LibTmux::UnsupportedFeatureError, &refusal)) } - refute version.refusal?(LibTmux::UnsupportedFeatureError.new("mirrored layouts require tmux 3.5+", phase: :admission)) + refusals = [ + -> { version.require_supported("3.2a") }, + -> { version.parse("master") }, + -> do + version.executable("/tmp/tmux") { Report.new(stdout: "tmux 3.3\n", stderr: "", ok: true) } + end, + -> do + version.connected(["tmux"]) do + Report.new(stdout: "", stderr: "server version is too old for client\n", ok: false) + end + end, + -> do + version.check_fence( + Report.new(stdout: "", stderr: "unknown command: m\n", ok: false), + "m", + version.parse("3.7d") + ) + end + ] + refusals.each do |refusal| + assert version.refusal?(assert_raises(LibTmux::UnsupportedFeatureError, &refusal)) + end + refute version.refusal?( + LibTmux::UnsupportedFeatureError.new( + "mirrored layouts require tmux 3.5+", + phase: :admission + ) + ) refute version.refusal?(LibTmux::CommandError.new("tmux did not report a daemon version")) - assert_match(/\Atmux 3\.3a or newer is required.*upgrade tmux and restart the server\z/, version.hint) + assert_match( + /\Atmux 3\.3a or newer is required.*upgrade tmux and restart the server\z/, + version.hint + ) end def test_every_refusal_names_the_remedy - [-> { version.require_supported("3.2a") }, -> { version.parse("master") }, - -> { version.executable("/tmp/tmux") { Report.new(stdout: "tmux 3.3\n", stderr: "", ok: true) } }].each do |refusal| - assert_match(/upgrade tmux and restart the server, or pin the previous libtmux release/, - assert_raises(LibTmux::UnsupportedFeatureError, &refusal).message) + [ + -> { version.require_supported("3.2a") }, + -> { version.parse("master") }, + -> do + version.executable("/tmp/tmux") { Report.new(stdout: "tmux 3.3\n", stderr: "", ok: true) } + end + ].each do |refusal| + assert_match( + /upgrade tmux and restart the server, or pin the previous libtmux release/, + assert_raises(LibTmux::UnsupportedFeatureError, &refusal).message + ) end end @@ -206,19 +332,32 @@ def test_every_refusal_names_the_remedy # build or candidate of a release stays below the gate that release opens. def test_the_mirrored_layout_gate_ranks_development_builds_below_3_5 ref = Struct.new(:kind, :id).new(:window, "@1") - {"next-3.5" => false, "3.5-rc" => false, "3.4" => false, "3.5" => true, "3.5a" => true, "next-3.9" => true, "3.8" => true}.each do |release, allowed| + { + "next-3.5" => false, + "3.5-rc" => false, + "3.4" => false, + "3.5" => true, + "3.5a" => true, + "next-3.9" => true, + "3.8" => true + }.each do |release, allowed| calls = [] server = Object.new server.define_singleton_method(:operation_budget) { |*| Struct.new(:options).new({}) } - server.define_singleton_method(:tmux_release) { LibTmux::Internal::TmuxVersion.parse(release) } + server.define_singleton_method(:tmux_release) do + LibTmux::Internal::TmuxVersion.parse(release) + end server.define_singleton_method(:target) { |*| "@1" } server.define_singleton_method(:execute_typed) { |argv, **| calls << argv } window = LibTmux::Window.send(:new, server, ref) if allowed window.select_layout(:main_vertical_mirrored) - assert_equal [["select-layout", "-t", "@1", "--", "main-vertical-mirrored"]], calls, release + assert_equal [%w[select-layout -t @1 -- main-vertical-mirrored]], calls, release else - error = assert_raises(LibTmux::UnsupportedFeatureError, release) { window.select_layout(:main_vertical_mirrored) } + error = + assert_raises(LibTmux::UnsupportedFeatureError, release) do + window.select_layout(:main_vertical_mirrored) + end assert_equal :not_sent, error.delivery assert_empty calls end @@ -229,11 +368,18 @@ def test_the_mirrored_layout_gate_ranks_development_builds_below_3_5 def test_the_json_layout_gate_opens_at_3_8 ref = Struct.new(:kind, :id).new(:window, "@1") json = '{"V":2,"L":{}}' - {"3.7c" => false, "3.7d" => false, "3.8" => true, "next-3.9" => true}.each do |release, allowed| + { + "3.7c" => false, + "3.7d" => false, + "3.8" => true, + "next-3.9" => true + }.each do |release, allowed| calls = [] server = Object.new server.define_singleton_method(:operation_budget) { |*| Struct.new(:options).new({}) } - server.define_singleton_method(:tmux_release) { LibTmux::Internal::TmuxVersion.parse(release) } + server.define_singleton_method(:tmux_release) do + LibTmux::Internal::TmuxVersion.parse(release) + end server.define_singleton_method(:target) { |*| "@1" } server.define_singleton_method(:execute_typed) { |argv, **| calls << argv } window = LibTmux::Window.send(:new, server, ref) @@ -241,7 +387,8 @@ def test_the_json_layout_gate_opens_at_3_8 window.select_layout(json) assert_equal [["select-layout", "-t", "@1", "--", json]], calls, release else - error = assert_raises(LibTmux::UnsupportedFeatureError, release) { window.select_layout(json) } + error = + assert_raises(LibTmux::UnsupportedFeatureError, release) { window.select_layout(json) } assert_equal :not_sent, error.delivery assert_empty calls, release end @@ -255,49 +402,72 @@ def test_the_json_layout_floor_is_tmux_3_8_and_the_refusal_names_it server = Object.new server.define_singleton_method(:operation_budget) { |*| Struct.new(:options).new({}) } server.define_singleton_method(:tmux_release) { LibTmux::Internal::TmuxVersion.parse("3.7c") } - error = assert_raises(LibTmux::UnsupportedFeatureError) do - LibTmux::Window.send(:new, server, ref).select_layout('{"V":2,"L":{}}') - end + error = + assert_raises(LibTmux::UnsupportedFeatureError) do + LibTmux::Window.send(:new, server, ref).select_layout('{"V":2,"L":{}}') + end assert_equal "JSON layouts require tmux 3.8 or newer (connected version 3.7c)", error.message end 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", "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 + [ + "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", + "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], ["", "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 + [ + ["", "error connecting to /tmp/route (Permission denied)\n", false], + ["3.3a\n", "", true], + ["", "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 assert_equal :not_sent, error.delivery assert_equal :admission, error.phase 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) + 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 - version.connected(["tmux"]) { raise kind.new("failed", delivery: :possibly_sent, phase: phase, pid: 7) } - end + [ + [LibTmux::DeadlineExceeded, :read], + [LibTmux::TransportError, :spawn], + [LibTmux::TransportError, :transport] + ].each do |kind, phase| + error = + assert_raises(kind, phase.to_s) do + version.connected(["tmux"]) do + raise kind.new("failed", delivery: :possibly_sent, phase: phase, pid: 7) + end + end assert_equal [:not_sent, phase, 7], [error.delivery, error.phase, error.pid] end - error = assert_raises(LibTmux::DeadlineExceeded) do - version.executable("/tmp/tmux") { raise LibTmux::DeadlineExceeded.new("slow", delivery: :possibly_sent, phase: :read) } - end - assert_equal [:not_sent, :read], [error.delivery, error.phase] + error = + assert_raises(LibTmux::DeadlineExceeded) do + version.executable("/tmp/tmux") do + raise LibTmux::DeadlineExceeded.new("slow", delivery: :possibly_sent, phase: :read) + end + end + assert_equal %i[not_sent read], [error.delivery, error.phase] end def test_fence_names_the_exact_release_and_a_private_marker @@ -310,14 +480,18 @@ def test_fence_names_the_exact_release_and_a_private_marker def test_fence_failure_is_recognized_only_as_the_marker_error_line release = version.parse("3.7d") - marker = "libtmux-version-#{'a' * 32}" + marker = "libtmux-version-#{"a" * 32}" refused = Report.new(stdout: "", stderr: "unknown command: #{marker}\n", ok: false) - error = assert_raises(LibTmux::UnsupportedFeatureError) { version.check_fence(refused, marker, release) } - assert_equal [:not_sent, :admission], [error.delivery, error.phase] - [Report.new(stdout: "", stderr: "", ok: true), Report.new(stdout: "", stderr: "unknown command: #{marker}x\n", ok: false), - Report.new(stdout: "unknown command: #{marker}\n", stderr: "", ok: true)].each do |result| - assert_same result, version.check_fence(result, marker, release) - end + error = + assert_raises(LibTmux::UnsupportedFeatureError) do + version.check_fence(refused, marker, release) + end + assert_equal %i[not_sent admission], [error.delivery, error.phase] + [ + Report.new(stdout: "", stderr: "", ok: true), + Report.new(stdout: "", stderr: "unknown command: #{marker}x\n", ok: false), + Report.new(stdout: "unknown command: #{marker}\n", stderr: "", ok: true) + ].each { |result| assert_same result, version.check_fence(result, marker, release) } end def test_fence_self_check_accepts_only_the_marker_error_from_the_real_commands @@ -325,34 +499,54 @@ def test_fence_self_check_accepts_only_the_marker_error_from_the_real_commands assert_equal ["if-shel", "-F", "1", "run-shel -C #{marker}"], argv good = Report.new(stdout: "", stderr: "unknown command: #{marker}\n", ok: false) assert_same good, version.verify_fence(good, marker) - ["", "command display-message: too many arguments (need at most 1)\n", "ambiguous command: if-shel\n", - "unknown command: #{marker}\nextra\n"].each do |stderr| - error = assert_raises(LibTmux::UnsupportedFeatureError, stderr) do - version.verify_fence(Report.new(stdout: "", stderr: stderr, ok: false), marker) - end - assert_equal [:not_sent, :admission], [error.delivery, error.phase] + [ + "", + "command display-message: too many arguments (need at most 1)\n", + "ambiguous command: if-shel\n", + "unknown command: #{marker}\nextra\n" + ].each do |stderr| + error = + assert_raises(LibTmux::UnsupportedFeatureError, stderr) do + version.verify_fence(Report.new(stdout: "", stderr: stderr, ok: false), marker) + end + assert_equal %i[not_sent admission], [error.delivery, error.phase] + end + assert_raises(LibTmux::UnsupportedFeatureError) do + version.verify_fence( + Report.new(stdout: "", stderr: "unknown command: #{marker}\n", ok: true), + marker + ) end - assert_raises(LibTmux::UnsupportedFeatureError) { version.verify_fence(Report.new(stdout: "", stderr: "unknown command: #{marker}\n", ok: true), marker) } end def test_identity_fields_travel_as_one_comma_joined_word argv, marker = version.identity_argv(%w[version pid start_time]) assert_equal ["run-shel", "-C", "#{marker}\#{version},\#{pid},\#{start_time}"], argv - result = Report.new(stdout: "", stderr: "unknown command: #{marker}3.7d,41,1700000000\n", ok: false) + result = + Report.new(stdout: "", stderr: "unknown command: #{marker}3.7d,41,1700000000\n", ok: false) assert_equal %w[3.7d 41 1700000000], version.parse_identity(result, marker, 3) end def test_identity_reports_that_are_not_one_complete_word_are_refused _, marker = version.identity_argv(%w[version pid]) - [["unknown command: #{marker}3.7d,41\nunknown command: x\n", false], ["unknown command: #{marker}3.7d 41\n", false], - ["unknown command: #{marker}3.7d\n", false], ["unknown command: other3.7d,41\n", false], - ["unknown command: #{marker}3.7d,41\n", true], ["", false]].each do |stderr, ok| + [ + ["unknown command: #{marker}3.7d,41\nunknown command: x\n", false], + ["unknown command: #{marker}3.7d 41\n", false], + ["unknown command: #{marker}3.7d\n", false], + ["unknown command: other3.7d,41\n", false], + ["unknown command: #{marker}3.7d,41\n", true], + ["", false] + ].each do |stderr, ok| assert_raises(LibTmux::ProtocolError, stderr) do version.parse_identity(Report.new(stdout: "", stderr: stderr, ok: ok), marker, 2) end end assert_raises(LibTmux::ProtocolError) do - version.parse_identity(Report.new(stdout: "x", stderr: "unknown command: #{marker}3.7d,41\n", ok: false), marker, 2) + version.parse_identity( + Report.new(stdout: "x", stderr: "unknown command: #{marker}3.7d,41\n", ok: false), + marker, + 2 + ) end end end diff --git a/test/unit/types_audit_test.rb b/test/unit/types_audit_test.rb index e5f65e89..0ef9f20b 100644 --- a/test/unit/types_audit_test.rb +++ b/test/unit/types_audit_test.rb @@ -62,9 +62,10 @@ def self.ghost: () -> void end def test_an_export_without_a_declaration_fails - error = assert_raises(PublicAPI::Error) do - planted("module LibTmux; class AuditProbeBare; end; end", "") { |api| api.audit! } - end + error = + assert_raises(PublicAPI::Error) do + planted("module LibTmux; class AuditProbeBare; end; end", "") { |api| api.audit! } + end assert_equal "missing RBS declaration: LibTmux::AuditProbeBare", error.message end @@ -72,7 +73,9 @@ def test_an_export_without_a_declaration_fails # The lines `audit!` raises for the planted classes. def audit_errors(ruby, rbs) - planted(ruby, rbs) { |api| assert_raises(PublicAPI::Error) { api.audit! } }.message.lines(chomp: true) + planted(ruby, rbs) { |api| assert_raises(PublicAPI::Error) { api.audit! } }.message.lines( + chomp: true + ) end # Defines the Ruby source inside LibTmux, declares the RBS beside the diff --git a/test/unit/workflow_apt_test.rb b/test/unit/workflow_apt_test.rb index 446893f1..7f0d0418 100644 --- a/test/unit/workflow_apt_test.rb +++ b/test/unit/workflow_apt_test.rb @@ -19,17 +19,22 @@ class WorkflowAptTest < Minitest::Test # A command word: at the start of a line or after an operator, a control # keyword, sudo, env or a variable assignment. A path such as # ./tools/apt-get.sh and a name such as apt-cache are not one. - RAW_APT = /(?:\A|[;&|(`{!]|\$\(|\b(?:then|do|else)\s)\s*(?:sudo\s+(?:-\S+\s+)*)?(?:env\s+)?(?:\w+=\S*\s+)*(apt-get|apt)(?=\s|\z)/ + RAW_APT = + /(?:\A|[;&|(`{!]|\$\(|\b(?:then|do|else)\s)\s*(?:sudo\s+(?:-\S+\s+)*)?(?:env\s+)?(?:\w+=\S*\s+)*(apt-get|apt)(?=\s|\z)/ def self.raw_calls(script) - script.gsub(/\\\n\s*/, " ").lines.reject { |line| line.lstrip.start_with?("#") }.filter_map do |line| - line[RAW_APT, 1] - end + script + .gsub(/\\\n\s*/, " ") + .lines + .reject { |line| line.lstrip.start_with?("#") } + .filter_map { |line| line[RAW_APT, 1] } end def self.steps_of(document) jobs = document["jobs"] - return (document.dig("runs", "steps") || []).map { |step| ["the action", step] } unless jobs.is_a?(Hash) + unless jobs.is_a?(Hash) + return (document.dig("runs", "steps") || []).map { |step| ["the action", step] } + end jobs.flat_map { |name, job| (job["steps"] || []).map { |step| ["job #{name}", step] } } end @@ -37,82 +42,111 @@ def self.steps_of(document) def self.problems(document, path) steps_of(document).each_with_index.flat_map do |(owner, step), index| label = step["name"] || step["id"] || "step #{index + 1}" - found = raw_calls(step["run"].to_s).map do |command| - "#{path}: #{owner}, step #{label}: calls #{command} directly; use #{ACTION}" - end + found = + raw_calls(step["run"].to_s).map do |command| + "#{path}: #{owner}, step #{label}: calls #{command} directly; use #{ACTION}" + end uses = step["uses"].to_s if uses.start_with?("#{ACTION}@") && !PINNED.match?(uses) - found << "#{path}: #{owner}, step #{label}: pins #{uses.split('@').first} to #{uses.split('@', 2).last}, not a full commit SHA" + found << "#{path}: #{owner}, step #{label}: pins #{uses.split("@").first} to #{uses.split("@", 2).last}, not a full commit SHA" end found end end def self.tree_problems(root) - Dir.glob(File.join(root, FILES)).sort.flat_map do |file| - problems(YAML.safe_load_file(file, aliases: false), file.delete_prefix("#{root}/")) - end + Dir + .glob(File.join(root, FILES)) + .sort + .flat_map do |file| + problems(YAML.safe_load_file(file, aliases: false), file.delete_prefix("#{root}/")) + end end def workflow(run = nil, uses: nil) - step = {"name" => "Install tmux"} + step = { "name" => "Install tmux" } step["run"] = run if run step["uses"] = uses if uses - {"jobs" => {"build" => {"steps" => [step]}}} + { "jobs" => { "build" => { "steps" => [step] } } } end def test_the_workflows_route_apt_through_the_shared_action - refute_empty Dir.glob(File.join(ROOT, FILES)), "the glob finds no workflow, so the rule checks nothing" + refute_empty Dir.glob(File.join(ROOT, FILES)), + "the glob finds no workflow, so the rule checks nothing" assert_equal [], self.class.tree_problems(ROOT) end def test_the_workflows_use_the_shared_action_and_no_vendored_wrapper - refute File.exist?(File.join(ROOT, "scripts/apt-get.sh")), "the shared action replaces the vendored wrapper" - uses = Dir.glob(File.join(ROOT, FILES)).flat_map do |file| - self.class.steps_of(YAML.safe_load_file(file, aliases: false)).map { |_, step| step["uses"].to_s } - end + refute File.exist?(File.join(ROOT, "scripts/apt-get.sh")), + "the shared action replaces the vendored wrapper" + uses = + Dir + .glob(File.join(ROOT, FILES)) + .flat_map do |file| + self + .class + .steps_of(YAML.safe_load_file(file, aliases: false)) + .map { |_, step| step["uses"].to_s } + end assert uses.any? { |use| use.start_with?("#{ACTION}@") }, "no step uses #{ACTION}" end def test_a_raw_call_is_reported_with_its_place_and_the_fix - message = "w.yml: job build, step Install tmux: calls apt-get directly; use libtmux/.github/actions/apt-get" + message = + "w.yml: job build, step Install tmux: calls apt-get directly; use libtmux/.github/actions/apt-get" assert_equal [message], self.class.problems(workflow("sudo apt-get update\n"), "w.yml") end def test_the_pinned_action_passes - assert_equal [], self.class.problems(workflow(uses: "#{ACTION}@#{'a' * 40}"), "w.yml") + assert_equal [], self.class.problems(workflow(uses: "#{ACTION}@#{"a" * 40}"), "w.yml") end def test_an_action_pinned_to_a_tag_or_a_branch_is_reported ["main", "v1", "a" * 39, "A" * 40].each do |ref| problems = self.class.problems(workflow(uses: "#{ACTION}@#{ref}"), "w.yml") - assert_equal ["w.yml: job build, step Install tmux: pins #{ACTION} to #{ref}, not a full commit SHA"], problems, ref + assert_equal [ + "w.yml: job build, step Install tmux: pins #{ACTION} to #{ref}, not a full commit SHA" + ], + problems, + ref end end def test_each_spelling_of_a_raw_call_is_reported [ - "apt-get update", "sudo apt-get install --yes tmux", "sudo -E apt-get update", "sudo apt install tmux", - "sudo DEBIAN_FRONTEND=noninteractive apt-get install tmux", "sudo env DEBIAN_FRONTEND=noninteractive apt-get install tmux", - "set -e\nsudo apt-get update && sudo apt-get install tmux", "if ! sudo apt-get update; then exit 1; fi", - "echo start; sudo apt-get update", "sudo \\\n apt-get update" - ].each do |run| - refute_empty self.class.problems(workflow(run), "w.yml"), run.inspect - end + "apt-get update", + "sudo apt-get install --yes tmux", + "sudo -E apt-get update", + "sudo apt install tmux", + "sudo DEBIAN_FRONTEND=noninteractive apt-get install tmux", + "sudo env DEBIAN_FRONTEND=noninteractive apt-get install tmux", + "set -e\nsudo apt-get update && sudo apt-get install tmux", + "if ! sudo apt-get update; then exit 1; fi", + "echo start; sudo apt-get update", + "sudo \\\n apt-get update" + ].each { |run| refute_empty self.class.problems(workflow(run), "w.yml"), run.inspect } end def test_a_comment_or_a_mention_is_not_a_call [ - "# sudo apt-get update\nmake", " # apt-get is bounded by the shared action", - "echo \"run sudo apt-get update by hand\"", "apt-cache policy tmux", "cat tools/apt-get.sh" - ].each do |run| - assert_equal [], self.class.problems(workflow(run), "w.yml"), run.inspect - end + "# sudo apt-get update\nmake", + " # apt-get is bounded by the shared action", + "echo \"run sudo apt-get update by hand\"", + "apt-cache policy tmux", + "cat tools/apt-get.sh" + ].each { |run| assert_equal [], self.class.problems(workflow(run), "w.yml"), run.inspect } end def test_a_composite_action_is_checked_too - action = {"runs" => {"using" => "composite", "steps" => [{"run" => "sudo apt-get update", "shell" => "bash"}]}} - assert_equal ["a/action.yml: the action, step step 1: calls apt-get directly; use libtmux/.github/actions/apt-get"], - self.class.problems(action, "a/action.yml") + action = { + "runs" => { + "using" => "composite", + "steps" => [{ "run" => "sudo apt-get update", "shell" => "bash" }] + } + } + assert_equal [ + "a/action.yml: the action, step step 1: calls apt-get directly; use libtmux/.github/actions/apt-get" + ], + self.class.problems(action, "a/action.yml") end end diff --git a/test/unit/workspace_cli_test.rb b/test/unit/workspace_cli_test.rb index 64787469..3ced5742 100644 --- a/test/unit/workspace_cli_test.rb +++ b/test/unit/workspace_cli_test.rb @@ -23,7 +23,15 @@ def test_version_does_not_require_configuration_or_a_tmux_endpoint def test_validation_discovery_and_offline_plan_are_inert_and_render_the_same_plan Dir.mktmpdir("libtmux-ruby-cli-") do |directory| file = File.join(directory, ".tmuxp.json") - File.write(file, JSON.generate({session_name: "cli", windows: [{window_name: "one", panes: [{shell_command: "touch must-not-run"}]}]})) + File.write( + file, + JSON.generate( + { + session_name: "cli", + windows: [{ window_name: "one", panes: [{ shell_command: "touch must-not-run" }] }] + } + ) + ) status, output, error = run_cli(%w[validate --json], directory) assert_equal 0, status assert_equal true, JSON.parse(output).fetch("valid") @@ -46,11 +54,15 @@ def test_invalid_arguments_and_configuration_return_two_without_echoing_payloads Dir.mktmpdir("libtmux-ruby-cli-") do |directory| file = File.join(directory, "private-config.json") File.write(file, '{"session_name":"a","session_name":"secret-name"}') - cases = [["validate", "--json", file], ["load", "--json", "--socket", "private-socket", file], + cases = [ + ["validate", "--json", file], + ["load", "--json", "--socket", "private-socket", file], ["load", "--json", "--attach", "--switch", file], ["load", "--json", "--socket", "private-socket", "--switch", file], - ["plan", "--json", "--live", "--socket", "private-socket", file], ["load", "--json", "--timeout", "NaN", file], - ["validate", "--json", "--unknown=private-value", file]] + ["plan", "--json", "--live", "--socket", "private-socket", file], + ["load", "--json", "--timeout", "NaN", file], + ["validate", "--json", "--unknown=private-value", file] + ] cases.each do |arguments| status, output, error = run_cli(arguments, directory) assert_equal 2, status @@ -81,7 +93,11 @@ def test_tmuxp_compatibility_records_cli_refusals end def test_explicit_tmuxp_blank_workspace_validates_and_plans - entry = LibTmuxTest::TmuxpCatalog.syntax.fetch("entries").find { |form| form.fetch("id") == "pane-blank-mapping" } + entry = + LibTmuxTest::TmuxpCatalog + .syntax + .fetch("entries") + .find { |form| form.fetch("id") == "pane-blank-mapping" } Dir.mktmpdir("libtmux-ruby-cli-") do |directory| file = File.join(directory, "blank.yaml") File.write(file, entry.fetch("probe").join("\n") + "\n") @@ -100,9 +116,18 @@ def test_explicit_tmuxp_blank_workspace_validates_and_plans def test_plan_resolves_tilde_with_explicit_home Dir.mktmpdir("libtmux-ruby-cli-") do |directory| file = File.join(directory, "home.json") - File.write(file, JSON.generate({session_name: "cli", start_directory: "~/project", - windows: [{window_name: "one", panes: [{}]}]})) - status, output, = run_cli(["plan", "--json", file], directory, environment: {"HOME" => "/ambient-home"}) + File.write( + file, + JSON.generate( + { + session_name: "cli", + start_directory: "~/project", + windows: [{ window_name: "one", panes: [{}] }] + } + ) + ) + status, output, = + run_cli(["plan", "--json", file], directory, environment: { "HOME" => "/ambient-home" }) assert_equal 2, status assert_match(/\.start_directory/, JSON.parse(output).dig("error", "message")) @@ -116,20 +141,44 @@ def test_plan_resolves_tilde_with_explicit_home def test_only_floor_refusals_get_the_unsupported_code floor = LibTmux::Internal::TmuxVersion below = assert_raises(LibTmux::UnsupportedFeatureError) { floor.require_supported("3.2a") } - changed = LibTmux::UnsupportedFeatureError.new("the tmux daemon no longer reports 3.3a; reopen the server", - phase: :admission, delivery: :not_sent, expected: floor::EXPECTED) - unrelated = LibTmux::UnsupportedFeatureError.new("native waitid is unavailable", phase: :admission, delivery: :not_sent) + changed = + LibTmux::UnsupportedFeatureError.new( + "the tmux daemon no longer reports 3.3a; reopen the server", + phase: :admission, + delivery: :not_sent, + expected: floor::EXPECTED + ) + unrelated = + LibTmux::UnsupportedFeatureError.new( + "native waitid is unavailable", + phase: :admission, + delivery: :not_sent + ) Dir.mktmpdir("libtmux-ruby-cli-") do |directory| file = File.join(directory, "load.json") - File.write(file, JSON.generate({session_name: "refused", windows: [{window_name: "one", panes: [{}]}]})) + File.write( + file, + JSON.generate({ session_name: "refused", windows: [{ window_name: "one", panes: [{}] }] }) + ) socket = File.join(directory, "socket") - [[below, true], [changed, true], [floor.unrecognized("master", "the daemon"), true], [unrelated, false]].each do |error, refusal| - status, output, = with_open_raising(error) { run_cli(["load", file, "--json", "--socket", socket], directory) } + [ + [below, true], + [changed, true], + [floor.unrecognized("master", "the daemon"), true], + [unrelated, false] + ].each do |error, refusal| + status, output, = + with_open_raising(error) do + run_cli(["load", file, "--json", "--socket", socket], directory) + end failure = JSON.parse(output).fetch("error") assert_equal 1, status - assert_equal refusal ? "tmux_unsupported" : "execution", failure.fetch("kind"), error.message + assert_equal refusal ? "tmux_unsupported" : "execution", + failure.fetch("kind"), + error.message assert_equal error.message, failure.fetch("message") - _, plain, shown = with_open_raising(error) { run_cli(["load", file, "--socket", socket], directory) } + _, plain, shown = + with_open_raising(error) { run_cli(["load", file, "--socket", socket], directory) } assert_empty plain assert_equal "#{error.message}\n", shown end @@ -141,17 +190,23 @@ def test_load_and_live_plan_take_the_socket_the_core_picks_when_no_flag_names_on inside = "/inside/socket,1,0" named = "#{directory}/tmux-#{Process.uid}" cases = [ - [{"LIBTMUX_SOCKET_PATH" => "/variable/path.sock", "LIBTMUX_SOCKET" => "variable"}, "/variable/path.sock"], - [{"LIBTMUX_SOCKET" => "variable"}, "#{named}/variable"], - [{"TMUX" => inside}, "/inside/socket"], - [{"LIBTMUX_SOCKET" => "variable", "TMUX" => inside}, "#{named}/variable"], + [ + { "LIBTMUX_SOCKET_PATH" => "/variable/path.sock", "LIBTMUX_SOCKET" => "variable" }, + "/variable/path.sock" + ], + [{ "LIBTMUX_SOCKET" => "variable" }, "#{named}/variable"], + [{ "TMUX" => inside }, "/inside/socket"], + [{ "LIBTMUX_SOCKET" => "variable", "TMUX" => inside }, "#{named}/variable"], [{}, "#{named}/default"] ] Dir.mktmpdir("libtmux-ruby-cli-") do |work| file = write_config(work) - [["load"], ["plan", "--live"]].each do |command| + [["load"], %w[plan --live]].each do |command| cases.each do |variables, socket| - status, endpoints, = capturing_open { |environment| run_cli([*command, "--json", file], work, environment: environment.merge(variables)) } + status, endpoints, = + capturing_open do |environment| + run_cli([*command, "--json", file], work, environment: environment.merge(variables)) + end assert_equal 1, status, "#{command} #{variables.keys}" assert_equal [socket], endpoints.map(&:socket_path), "#{command} #{variables.keys}" end @@ -162,11 +217,20 @@ def test_load_and_live_plan_take_the_socket_the_core_picks_when_no_flag_names_on def test_the_socket_flag_wins_over_every_variable Dir.mktmpdir("libtmux-ruby-cli-") do |work| file = write_config(work) - variables = {"LIBTMUX_SOCKET_PATH" => "/variable/path.sock", "LIBTMUX_SOCKET" => "variable", "TMUX" => "/inside/socket,1,0"} - [["load"], ["plan", "--live"]].each do |command| - _, endpoints, = capturing_open do |environment| - run_cli([*command, "--json", "--socket", "flag.sock", file], work, environment: environment.merge(variables)) - end + variables = { + "LIBTMUX_SOCKET_PATH" => "/variable/path.sock", + "LIBTMUX_SOCKET" => "variable", + "TMUX" => "/inside/socket,1,0" + } + [["load"], %w[plan --live]].each do |command| + _, endpoints, = + capturing_open do |environment| + run_cli( + [*command, "--json", "--socket", "flag.sock", file], + work, + environment: environment.merge(variables) + ) + end assert_equal [File.join(work, "flag.sock")], endpoints.map(&:socket_path), command.inspect end end @@ -175,9 +239,14 @@ def test_the_socket_flag_wins_over_every_variable def test_a_bad_variable_is_refused_by_name_before_any_server_opens Dir.mktmpdir("libtmux-ruby-cli-") do |work| file = write_config(work) - status, endpoints, output = capturing_open do |environment| - run_cli(["load", "--json", file], work, environment: environment.merge("LIBTMUX_SOCKET" => "private-a/b")) - end + status, endpoints, output = + capturing_open do |environment| + run_cli( + ["load", "--json", file], + work, + environment: environment.merge("LIBTMUX_SOCKET" => "private-a/b") + ) + end assert_equal 2, status assert_empty endpoints assert_includes output, "LIBTMUX_SOCKET" @@ -189,10 +258,18 @@ def test_a_socket_that_cannot_expand_is_refused_by_name_before_any_server_opens user = "libtmux-ruby-no-such-user" Dir.mktmpdir("libtmux-ruby-cli-") do |work| file = write_config(work) - [[["--socket", "~#{user}/x"], {}, "--socket"], [[], {"LIBTMUX_SOCKET_PATH" => "~#{user}/x"}, "LIBTMUX_SOCKET_PATH"]].each do |flags, variables, name| - status, endpoints, output = capturing_open do |environment| - run_cli(["load", "--json", *flags, file], work, environment: environment.merge(variables)) - end + [ + [["--socket", "~#{user}/x"], {}, "--socket"], + [[], { "LIBTMUX_SOCKET_PATH" => "~#{user}/x" }, "LIBTMUX_SOCKET_PATH"] + ].each do |flags, variables, name| + status, endpoints, output = + capturing_open do |environment| + run_cli( + ["load", "--json", *flags, file], + work, + environment: environment.merge(variables) + ) + end assert_equal 2, status, name assert_empty endpoints, name assert_includes output, name @@ -204,9 +281,16 @@ def test_a_socket_that_cannot_expand_is_refused_by_name_before_any_server_opens def test_an_empty_socket_flag_and_a_socket_flag_without_a_live_command_are_refused_before_any_server_opens Dir.mktmpdir("libtmux-ruby-cli-") do |work| file = write_config(work) - [["load", "--socket", ""], ["plan", "--live", "--socket", ""], ["plan", "--socket", "flag.sock"], - ["validate", "--socket", "flag.sock"]].each do |arguments| - status, endpoints, = capturing_open { |environment| run_cli([*arguments, "--json", file], work, environment: environment) } + [ + ["load", "--socket", ""], + ["plan", "--live", "--socket", ""], + %w[plan --socket flag.sock], + %w[validate --socket flag.sock] + ].each do |arguments| + status, endpoints, = + capturing_open do |environment| + run_cli([*arguments, "--json", file], work, environment: environment) + end assert_equal 2, status, arguments.inspect assert_empty endpoints, arguments.inspect end @@ -217,7 +301,10 @@ def test_an_empty_socket_flag_and_a_socket_flag_without_a_live_command_are_refus def write_config(directory) file = File.join(directory, "workspace.json") - File.write(file, JSON.generate({session_name: "cli", windows: [{window_name: "one", panes: [{}]}]})) + File.write( + file, + JSON.generate({ session_name: "cli", windows: [{ window_name: "one", panes: [{}] }] }) + ) file end @@ -231,7 +318,7 @@ def capturing_open endpoints << options.fetch(:endpoint) raise LibTmux::TargetNotFoundError.new("stopped by the test", phase: :bind) end - status, output, = yield({"TMUX_TMPDIR" => PRIVATE_TMUX_TMPDIR}) + status, output, = yield({ "TMUX_TMPDIR" => PRIVATE_TMUX_TMPDIR }) [status, endpoints, output] ensure LibTmux::Server.define_singleton_method(:open, original) @@ -247,8 +334,14 @@ def with_open_raising(error) def run_cli(arguments, directory, environment: {}) output, error = StringIO.new, StringIO.new - status = LibTmux::Workspace::CLI.run(arguments, out: output, err: error, directory: directory, - environment: {"TMUX_TMPDIR" => PRIVATE_TMUX_TMPDIR}.merge(environment)) + status = + LibTmux::Workspace::CLI.run( + arguments, + out: output, + err: error, + directory: directory, + environment: { "TMUX_TMPDIR" => PRIVATE_TMUX_TMPDIR }.merge(environment) + ) [status, output.string, error.string] end end diff --git a/test/unit/workspace_test.rb b/test/unit/workspace_test.rb index 9e0e023f..d245c6e3 100644 --- a/test/unit/workspace_test.rb +++ b/test/unit/workspace_test.rb @@ -6,13 +6,21 @@ class WorkspaceTest < Minitest::Test def document - {"session_name" => "work", "windows" => [ - {"window_name" => "editor", "panes" => [{"shell_command" => "printf literal"}, {}]} - ]} + { + "session_name" => "work", + "windows" => [ + { "window_name" => "editor", "panes" => [{ "shell_command" => "printf literal" }, {}] } + ] + } end def parse(value, **options) - LibTmux::Workspace.parse(JSON.generate(value), format: :json, base_directory: "/workspace", **options) + LibTmux::Workspace.parse( + JSON.generate(value), + format: :json, + base_directory: "/workspace", + **options + ) end def test_data_only_yaml_and_json_loads_have_one_immutable_normalized_profile @@ -24,12 +32,24 @@ def test_data_only_yaml_and_json_loads_have_one_immutable_normalized_profile path = File.join(directory, "workspace.yaml") File.write(path, Psych.dump(source)) yaml = LibTmux::Workspace.load(path) - json = LibTmux::Workspace.parse(JSON.generate(source), format: :json, base_directory: directory) + json = + LibTmux::Workspace.parse(JSON.generate(source), format: :json, base_directory: directory) assert_equal yaml.to_h, json.to_h assert_equal "libtmux-ruby.workspace", yaml.to_h.fetch("profile") - assert_equal File.join(directory, "project"), yaml.to_h.fetch("windows").first.fetch("panes").first.fetch("start_directory") + assert_equal File.join(directory, "project"), + yaml.to_h.fetch("windows").first.fetch("panes").first.fetch("start_directory") refute File.exist?(marker) - assert_raises(FrozenError) { yaml.to_h.fetch("windows").first.fetch("panes").first.fetch("shell_command").first.replace("changed") } + assert_raises(FrozenError) do + yaml + .to_h + .fetch("windows") + .first + .fetch("panes") + .first + .fetch("shell_command") + .first + .replace("changed") + end refute_includes yaml.inspect, marker end end @@ -37,10 +57,17 @@ def test_data_only_yaml_and_json_loads_have_one_immutable_normalized_profile # tmuxp's "Blank panes" example: a lone pane or blank is a pane with nothing to # run, and only a lone one. def test_a_lone_pane_or_blank_is_a_pane_with_nothing_to_run - panes = ["pane", "blank", {"shell_command" => "pane"}, {"shell_command" => ["blank"]}, - {"shell_command" => ["cd /tmp", "pane"]}, "panes"] - loaded = parse(document.merge("windows" => [{"window_name" => "w", "panes" => panes}])) - commands = loaded.to_h.fetch("windows").first.fetch("panes").map { |pane| pane.fetch("shell_command") } + panes = [ + "pane", + "blank", + { "shell_command" => "pane" }, + { "shell_command" => ["blank"] }, + { "shell_command" => ["cd /tmp", "pane"] }, + "panes" + ] + loaded = parse(document.merge("windows" => [{ "window_name" => "w", "panes" => panes }])) + commands = + loaded.to_h.fetch("windows").first.fetch("panes").map { |pane| pane.fetch("shell_command") } assert_equal [[], [], [], [], ["cd /tmp", "pane"], ["panes"]], commands end @@ -58,17 +85,29 @@ def test_duplicates_tags_aliases_unknown_fields_and_limits_fail_before_planning end end assert_raises(LibTmux::Workspace::ConfigError) do - LibTmux::Workspace.parse('{"session_name":"a","session_name":"b"}', format: :json, base_directory: "/workspace") + LibTmux::Workspace.parse( + '{"session_name":"a","session_name":"b"}', + format: :json, + base_directory: "/workspace" + ) end - [document.merge("before_script" => "secret-command"), document.merge("private-secret-key" => true), - document.merge("version" => 1), document.merge("profile" => "foreign", "version" => 1), - document.merge("windows" => []), document.merge("session_name" => "bad:name")].each do |value| + [ + document.merge("before_script" => "secret-command"), + document.merge("private-secret-key" => true), + document.merge("version" => 1), + document.merge("profile" => "foreign", "version" => 1), + document.merge("windows" => []), + document.merge("session_name" => "bad:name") + ].each do |value| error = assert_raises(LibTmux::Workspace::ConfigError) { parse(value) } refute_includes error.full_message, "secret" end assert_raises(LibTmux::Workspace::ConfigError) { parse(document, max_bytes: 16) } assert_raises(LibTmux::Workspace::ConfigError) { parse(document, max_panes: 1) } - nonfile = assert_raises(LibTmux::Workspace::ConfigError) { LibTmux::Workspace.load("/dev/null", format: :yaml) } + nonfile = + assert_raises(LibTmux::Workspace::ConfigError) do + LibTmux::Workspace.load("/dev/null", format: :yaml) + end assert_equal "regular configuration file", nonfile.expected nested = "a: [" * 40 + "0" + "]" * 40 assert_raises(LibTmux::Workspace::ConfigError) do @@ -77,24 +116,56 @@ def test_duplicates_tags_aliases_unknown_fields_and_limits_fail_before_planning end def test_inheritance_is_parent_to_child_and_expansion_is_explicit_and_nonshell - source = document.merge("start_directory" => "${PROJECT}", "environment" => {"A" => "root", "B" => "${VALUE}"}, - "shell_command_before" => ["root-before"]) + source = + document.merge( + "start_directory" => "${PROJECT}", + "environment" => { + "A" => "root", + "B" => "${VALUE}" + }, + "shell_command_before" => ["root-before"] + ) window = source.fetch("windows").first - window.merge!("start_directory" => "window", "environment" => {"A" => "window"}, "shell_command_before" => "window-before") + window.merge!( + "start_directory" => "window", + "environment" => { + "A" => "window" + }, + "shell_command_before" => "window-before" + ) pane = window.fetch("panes").first - pane.merge!("start_directory" => "../pane", "environment" => {"A" => "pane"}, - "shell_command_before" => "pane-before", "shell_command" => "echo ${VALUE}; $(touch ignored)") - config = parse(source, expand_environment: true, environment: {"PROJECT" => "root", "VALUE" => "literal"}).to_h + pane.merge!( + "start_directory" => "../pane", + "environment" => { + "A" => "pane" + }, + "shell_command_before" => "pane-before", + "shell_command" => "echo ${VALUE}; $(touch ignored)" + ) + config = + parse( + source, + expand_environment: true, + environment: { + "PROJECT" => "root", + "VALUE" => "literal" + } + ).to_h first, second = config.fetch("windows").first.fetch("panes") assert_equal "/workspace/root/pane", first.fetch("start_directory") assert_equal "/workspace/root/window", second.fetch("start_directory") - assert_equal({"A" => "pane", "B" => "literal"}, first.fetch("environment")) - assert_equal ["root-before", "window-before", "pane-before"], first.fetch("shell_command_before") + assert_equal({ "A" => "pane", "B" => "literal" }, first.fetch("environment")) + assert_equal %w[root-before window-before pane-before], first.fetch("shell_command_before") assert_equal ["echo ${VALUE}; $(touch ignored)"], first.fetch("shell_command") - round_trip = LibTmux::Workspace.parse(JSON.generate(config), format: :json, base_directory: "/elsewhere") + round_trip = + LibTmux::Workspace.parse(JSON.generate(config), format: :json, base_directory: "/elsewhere") assert_equal config, round_trip.to_h assert_equal ["root-before", "window-before", "pane-before", "echo ${VALUE}; $(touch ignored)"], - round_trip.plan.steps.select { |step| step.operation == :send_command && step.target == "pane:0:0" }.map { |step| step.arguments.fetch("command") } + round_trip + .plan + .steps + .select { |step| step.operation == :send_command && step.target == "pane:0:0" } + .map { |step| step.arguments.fetch("command") } assert_equal "${VALUE}", parse(source).to_h.fetch("environment").fetch("B") assert_raises(LibTmux::Workspace::ConfigError) { parse(source, expand_environment: true) } end @@ -104,7 +175,7 @@ def test_tilde_uses_supplied_home_and_overrides_the_parent_directory window = source.fetch("windows").first window["start_directory"] = "project" window.fetch("panes").first["start_directory"] = "~/shared" - config = parse(source, environment: {"HOME" => "/explicit/home"}).to_h + config = parse(source, environment: { "HOME" => "/explicit/home" }).to_h assert_equal "/explicit/home", config.fetch("start_directory") assert_equal "/explicit/home/project", config.dig("windows", 0, "start_directory") @@ -114,8 +185,9 @@ def test_tilde_uses_supplied_home_and_overrides_the_parent_directory def test_tilde_refuses_missing_or_relative_explicit_home source = document.merge("start_directory" => "~/private-path") - [{}, {"HOME" => "relative-home"}, {"HOME" => ""}].each do |environment| - error = assert_raises(LibTmux::Workspace::ConfigError) { parse(source, environment: environment) } + [{}, { "HOME" => "relative-home" }, { "HOME" => "" }].each do |environment| + error = + assert_raises(LibTmux::Workspace::ConfigError) { parse(source, environment: environment) } assert_equal "$.start_directory", error.path refute_includes error.message, "private-path" refute_includes error.message, "relative-home" @@ -124,16 +196,17 @@ def test_tilde_refuses_missing_or_relative_explicit_home def test_named_user_tilde_is_refused_without_echoing_the_username source = document.merge("start_directory" => "~private-user/project") - error = assert_raises(LibTmux::Workspace::ConfigError) do - parse(source, environment: {"HOME" => "/explicit/home"}) - end + error = + assert_raises(LibTmux::Workspace::ConfigError) do + parse(source, environment: { "HOME" => "/explicit/home" }) + end assert_equal "$.start_directory", error.path refute_includes error.message, "private-user" end def test_indexes_focus_layout_and_typed_scope_options_are_validated source = document - source["windows"] << {"window_name" => "logs", "window_index" => 3, "panes" => ["tail logs"]} + source["windows"] << { "window_name" => "logs", "window_index" => 3, "panes" => ["tail logs"] } source["windows"][0].merge!("window_index" => 3) assert_raises(LibTmux::Workspace::ConfigError) { parse(source) } source["windows"][0]["window_index"] = 0 @@ -143,32 +216,41 @@ def test_indexes_focus_layout_and_typed_scope_options_are_validated source["windows"][0]["layout"] = "arbitrary,layout" assert_raises(LibTmux::Workspace::ConfigError) { parse(source) } source["windows"][0]["layout"] = "tiled" - source["options"] = {"mouse" => "on"} + source["options"] = { "mouse" => "on" } assert_raises(LibTmux::Workspace::ConfigError) { parse(source) } - source["options"] = {"mouse" => true, "status" => false} - source["windows"][0]["options"] = {"automatic-rename" => false, "remain-on-exit" => true} + source["options"] = { "mouse" => true, "status" => false } + source["windows"][0]["options"] = { "automatic-rename" => false, "remain-on-exit" => true } assert_equal 3, parse(source).to_h.fetch("windows").last.fetch("window_index") - source["window_options"] = {"pane-base-index" => 65535} - assert_equal 65535, parse(source).to_h.fetch("windows").first.fetch("options").fetch("pane-base-index") - source["window_options"]["pane-base-index"] = 65536 + source["window_options"] = { "pane-base-index" => 65_535 } + assert_equal 65_535, + parse(source).to_h.fetch("windows").first.fetch("options").fetch("pane-base-index") + source["window_options"]["pane-base-index"] = 65_536 error = assert_raises(LibTmux::Workspace::ConfigError) { parse(source) } assert_equal "$.window_options.pane-base-index", error.path end def test_expansion_and_inheritance_obey_normalized_memory_bounds - source = document.merge("environment" => {"EXPANDED" => "${BIG}" * 20}) + source = document.merge("environment" => { "EXPANDED" => "${BIG}" * 20 }) assert_raises(LibTmux::Workspace::ConfigError) do - parse(source, expand_environment: true, environment: {"BIG" => "x" * 100}, max_string_bytes: 1024) + parse( + source, + expand_environment: true, + environment: { + "BIG" => "x" * 100 + }, + max_string_bytes: 1024 + ) end source = document.merge("shell_command_before" => "x" * 200) source["windows"][0]["panes"] = Array.new(8) { {} } assert_raises(LibTmux::Workspace::ConfigError) { parse(source, max_bytes: 1024) } assert_raises(LibTmux::Workspace::ConfigError) do - parse(document, environment: {"BIG1" => "x" * 700, "BIG2" => "x" * 700}, max_bytes: 1024) + parse(document, environment: { "BIG1" => "x" * 700, "BIG2" => "x" * 700 }, max_bytes: 1024) end escaped = document.merge("shell_command_before" => "\u0001" * 50) assert_raises(LibTmux::Workspace::ConfigError) { parse(escaped, max_bytes: 1024) } - yaml = "session_name: work\nenvironment: {NUMBER: 1.5}\nwindows: [{window_name: one, panes: [{}]}]\n" + yaml = + "session_name: work\nenvironment: {NUMBER: 1.5}\nwindows: [{window_name: one, panes: [{}]}]\n" assert_raises(LibTmux::Workspace::ConfigError) do LibTmux::Workspace.parse(yaml, format: :yaml, base_directory: "/workspace") end @@ -177,24 +259,49 @@ def test_expansion_and_inheritance_obey_normalized_memory_bounds def test_plan_reuses_initial_entities_and_keeps_provenance_without_io source = document source["windows"][0]["layout"] = "tiled" - source["windows"] << {"window_name" => "logs", "panes" => [{}]} + source["windows"] << { "window_name" => "logs", "panes" => [{}] } workspace = parse(source) offline = workspace.plan assert_equal :offline_create, offline.mode - assert_equal [:create_session, :split_pane, :create_window], offline.steps.select { |step| step.effect == :creation }.map(&:operation) - assert_equal ["session", "window:0", "pane:0:0"], offline.steps.first.produces + assert_equal %i[create_session split_pane create_window], + offline.steps.select { |step| step.effect == :creation }.map(&:operation) + assert_equal %w[session window:0 pane:0:0], offline.steps.first.produces command = offline.steps.find { |step| step.operation == :send_command } assert_equal :dispatch_only, command.effect assert_equal "pane:0:0", command.target assert offline.frozen? assert offline.steps.all?(&:frozen?) assert_raises(FrozenError) { offline.steps.first.arguments.fetch("name").replace("changed") } - graph = LibTmux::Snapshot.send(:new, rows: {session: []}, binding_key: "binding", started_at: 1, finished_at: 2, reads: [], server_info: {}) + graph = + LibTmux::Snapshot.send( + :new, + rows: { + session: [] + }, + binding_key: "binding", + started_at: 1, + finished_at: 2, + reads: [], + server_info: { + } + ) live = workspace.plan(snapshot: graph) assert_equal :captured_create, live.mode assert_equal graph.capture_id, live.preconditions.fetch("capture_id") assert_equal "binding", live.preconditions.fetch("binding_key") - conflict = LibTmux::Snapshot.send(:new, rows: {session: [{id: "$1", name: "work"}]}, binding_key: "binding", started_at: 1, finished_at: 2, reads: [], server_info: {}) + conflict = + LibTmux::Snapshot.send( + :new, + rows: { + session: [{ id: "$1", name: "work" }] + }, + binding_key: "binding", + started_at: 1, + finished_at: 2, + reads: [], + server_info: { + } + ) assert_raises(LibTmux::Workspace::ConflictError) { workspace.plan(snapshot: conflict) } assert_equal offline.to_h, workspace.plan.to_h end diff --git a/test/unit/workspace_tmuxp_test.rb b/test/unit/workspace_tmuxp_test.rb index 241e7af8..284ba6be 100644 --- a/test/unit/workspace_tmuxp_test.rb +++ b/test/unit/workspace_tmuxp_test.rb @@ -34,37 +34,58 @@ def test_tmuxp_examples_the_loader_refuses_fail_as_recorded def test_each_loaded_example_has_one_expected_structure expected = Dir.children(Catalog::EXPECTED).sort assert_equal Catalog::LOADED.map { |name| name.sub(/\.yaml\z/, ".json") }.sort, expected - Catalog::LOADED.each { |name| assert_equal %w[session source windows].sort, Catalog.expected(name).keys.sort, name } + Catalog::LOADED.each do |name| + assert_equal %w[session source windows].sort, Catalog.expected(name).keys.sort, name + end end def test_each_loaded_example_produces_the_structure_tmuxp_documents_for_it Catalog::LOADED.each do |name| - assert_equal Catalog.port_expected(name), Catalog.structure(Catalog.workspace(name), name), name + assert_equal Catalog.port_expected(name), + Catalog.structure(Catalog.workspace(name), name), + name end end def test_the_comparison_reports_a_wrong_structure loaded = Catalog.structure(Catalog.workspace("3-pane.yaml"), "3-pane.yaml") assert_equal Catalog.port_expected("3-pane.yaml"), loaded - {"another file" => Catalog.port_expected("4-pane.yaml"), - "a layout" => Catalog.port_expected("3-pane.yaml").tap { |tree| tree["windows"][0]["layout"] = "tiled" }, - "a focus" => Catalog.port_expected("3-pane.yaml").tap { |tree| tree["windows"][0]["panes"][1]["focus"] = true }, - "a command" => Catalog.port_expected("3-pane.yaml").tap { |tree| tree["windows"][0]["panes"][2]["commands"] << "x" }, - "a directory" => Catalog.port_expected("3-pane.yaml").tap { |tree| tree["windows"][0]["panes"][0]["start_directory"] = "/tmp" }}.each do |change, wrong| - refute_equal wrong, loaded, change - end + { + "another file" => Catalog.port_expected("4-pane.yaml"), + "a layout" => + Catalog.port_expected("3-pane.yaml").tap { |tree| tree["windows"][0]["layout"] = "tiled" }, + "a focus" => + Catalog + .port_expected("3-pane.yaml") + .tap { |tree| tree["windows"][0]["panes"][1]["focus"] = true }, + "a command" => + Catalog + .port_expected("3-pane.yaml") + .tap { |tree| tree["windows"][0]["panes"][2]["commands"] << "x" }, + "a directory" => + Catalog + .port_expected("3-pane.yaml") + .tap { |tree| tree["windows"][0]["panes"][0]["start_directory"] = "/tmp" } + }.each { |change, wrong| refute_equal wrong, loaded, change } end def parse(entry) options = (entry["options"] || {}).transform_keys(&:to_sym) - LibTmux::Workspace.parse(entry.fetch("probe").join("\n") + "\n", format: :yaml, base_directory: "/workspace", **options) + LibTmux::Workspace.parse( + entry.fetch("probe").join("\n") + "\n", + format: :yaml, + base_directory: "/workspace", + **options + ) end def test_the_syntax_record_matches_what_the_loader_does record = Catalog.syntax entries = record.fetch("entries") - assert_equal record.fetch("statuses").keys.sort, entries.map { |entry| entry.fetch("status") }.uniq.sort - assert_equal entries.map { |entry| entry.fetch("id") }, entries.map { |entry| entry.fetch("id") }.uniq + assert_equal record.fetch("statuses").keys.sort, + entries.map { |entry| entry.fetch("status") }.uniq.sort + assert_equal entries.map { |entry| entry.fetch("id") }, + entries.map { |entry| entry.fetch("id") }.uniq entries.each do |entry| id = entry.fetch("id") case entry.fetch("status") @@ -82,37 +103,80 @@ def test_the_syntax_record_matches_what_the_loader_does when "refused" error = assert_raises(LibTmux::Workspace::ConfigError, id) { parse(entry) } assert_equal entry.fetch("message"), error.message, id - else flunk "#{id}: unknown status" + else + flunk "#{id}: unknown status" end end end def test_the_syntax_record_names_every_tmuxp_key_the_catalog_uses keys = Catalog.syntax.fetch("entries").map { |entry| entry.fetch("key") } - %w[session_name start_directory environment shell_command_before before_script global_options options plugins window_name - layout window_index focus options_after window_shell suppress_history panes shell_command enter sleep_before sleep_after shell].each do |key| - assert_includes keys, key - end - used = Catalog.children.flat_map { |name| File.read(Catalog.path(name)).scan(/^\s*(?:-\s+)?([a-z_]+):/).flatten }.uniq + %w[ + session_name + start_directory + environment + shell_command_before + before_script + global_options + options + plugins + window_name + layout + window_index + focus + options_after + window_shell + suppress_history + panes + shell_command + enter + sleep_before + sleep_after + shell + ].each { |key| assert_includes keys, key } + used = + Catalog + .children + .flat_map { |name| File.read(Catalog.path(name)).scan(/^\s*(?:-\s+)?([a-z_]+):/).flatten } + .uniq assert_empty used - keys - %w[cmd], "keys in the catalog the record does not name" end def test_the_syntax_record_covers_the_tmuxp_shorthand_forms - expected = %w[windows-omitted windows-null window-null-entry - window-no-panes window-panes-null window-panes-empty pane-shell-command-single-mapping - pane-shell-command-before-single-mapping pane-unwrapped-cmd pane-blank-mapping] + expected = %w[ + windows-omitted + windows-null + window-null-entry + window-no-panes + window-panes-null + window-panes-empty + pane-shell-command-single-mapping + pane-shell-command-before-single-mapping + pane-unwrapped-cmd + pane-blank-mapping + ] entries = Catalog.syntax.fetch("entries").map { |entry| entry.fetch("id") } assert_empty expected - entries end def test_a_changed_loader_fails_the_record - entry = Catalog.syntax.fetch("entries").find { |candidate| candidate.fetch("id") == "before-script" } - accepted = entry.merge("probe" => ["session_name: a", "windows:", " - window_name: w", " panes: [{}]"]) + entry = + Catalog.syntax.fetch("entries").find { |candidate| candidate.fetch("id") == "before-script" } + accepted = + entry.merge( + "probe" => ["session_name: a", "windows:", " - window_name: w", " panes: [{}]"] + ) assert_raises(Minitest::Assertion) do assert_raises(LibTmux::Workspace::ConfigError) { parse(accepted) } end - entry = Catalog.syntax.fetch("entries").find { |candidate| candidate.fetch("id") == "start-directory-tilde" } - wrong = entry.merge("observed" => {"path" => ["start_directory"], "value" => "/workspace/~/x"}) - refute_equal wrong.dig("observed", "value"), parse(wrong).to_h.dig(*wrong.dig("observed", "path")) + entry = + Catalog + .syntax + .fetch("entries") + .find { |candidate| candidate.fetch("id") == "start-directory-tilde" } + wrong = + entry.merge("observed" => { "path" => ["start_directory"], "value" => "/workspace/~/x" }) + refute_equal wrong.dig("observed", "value"), + parse(wrong).to_h.dig(*wrong.dig("observed", "path")) end end