From cb947835e0f3204f480fd8484e560e2a04f3067d Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Fri, 4 Dec 2026 19:35:46 -0600 Subject: [PATCH 1/3] =?UTF-8?q?Examples(feat):=20Keep=20a=20pane=20job?= =?UTF-8?q?=E2=80=99s=20exit=20result?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit why: A build can exit before Lua reads its last line. Two builds can leave the same screen and still return different exit codes. what: - Send the direct child’s exit result back to a standalone Lua caller. - Run the commands in real panes and test early exits and replacement. - Show how to use a retained screen sample when one is available. --- README.md | 3 + docs/creation.md | 4 +- examples/concepts/program_exit/README.md | 105 +++++++ examples/concepts/program_exit/adapter.lua | 250 +++++++++++++++++ examples/concepts/program_exit/check.lua | 4 + examples/concepts/program_exit/run.lua | 152 +++++++++++ examples/concepts/program_exit/supervisor.lua | 93 +++++++ tests/integration/program_exit_concept.lua | 257 ++++++++++++++++++ .../integration/test_program_exit_concept.lua | 140 ++++++++++ 9 files changed, 1007 insertions(+), 1 deletion(-) create mode 100644 examples/concepts/program_exit/README.md create mode 100644 examples/concepts/program_exit/adapter.lua create mode 100644 examples/concepts/program_exit/check.lua create mode 100644 examples/concepts/program_exit/run.lua create mode 100644 examples/concepts/program_exit/supervisor.lua create mode 100644 tests/integration/program_exit_concept.lua create mode 100644 tests/integration/test_program_exit_concept.lua diff --git a/README.md b/README.md index e00839a3..7a3a7c33 100644 --- a/README.md +++ b/README.md @@ -348,6 +348,9 @@ editor build ## Create sessions, windows and panes +The [pane job example](examples/concepts/program_exit/README.md) reads a +command's exit status after its pane closes. + ### [`Session:new_window`][ref-session-new-window]: add a window [`Session:new_window`][ref-session-new-window] adds a window to a session, diff --git a/docs/creation.md b/docs/creation.md index 89851fd9..8203e24a 100644 --- a/docs/creation.md +++ b/docs/creation.md @@ -13,7 +13,9 @@ from tmux's returned IDs. Its `created` list names what the call created: - A split: the pane only. The other handles describe the containing context. A created pane proves -neither that its program started nor that it succeeded. +neither that its program started nor that it succeeded. See the +[pane job completion experiment](../examples/concepts/program_exit/README.md) +for a result from the specific command a Lua caller launched. ## Commands and literal values diff --git a/examples/concepts/program_exit/README.md b/examples/concepts/program_exit/README.md new file mode 100644 index 00000000..eec8d0da --- /dev/null +++ b/examples/concepts/program_exit/README.md @@ -0,0 +1,105 @@ +# Ask how a pane job ended + +A build runner can use the exit of the command it launched to decide whether +to publish an artifact. This checkout experiment gets that exit even after +tmux removes the pane. + +## Run a syntax check + +Run from this checkout with standalone Lua, `luv` on its module path, and +tmux on `PATH`. Set `TMUX_BIN` to an absolute path to select a different build. +The launcher starts and cleans up a private server. + +```console +$ export LUA_PATH='./lua/?.lua;./lua/?/init.lua;;' +``` + +```console +$ lua examples/concepts/program_exit/run.lua -- \ + lua examples/concepts/program_exit/check.lua lua/libtmux/init.lua +``` + +```console +$ lua examples/concepts/program_exit/run.lua -- \ + lua examples/concepts/program_exit/check.lua README.md +``` + +Both checks print `done` in their pane. The first file parses as Lua and +the second fails to parse. After the pane closes, the runner reports +`job exited 0` or `job exited 23`, with `screen unavailable` in both runs. + +The runner treats arguments after `--` as literal executable and arguments. +The shell receives the job's numeric exit, 128 plus the signal number, +or 125 when the runner has no exit. The printed outcome distinguishes +collisions. For example, `exit 143` and SIGTERM both return 143 to the +shell and give different reports. + +## Send a line and sample the screen + +```console +$ lua examples/concepts/program_exit/run.lua --screen --input 'build next' \ + -- /bin/sh -c 'test -t 0 && test -t 1 && test -t 2 && read -r line && + test "$line" = "build next" && printf "%s\n" "$line"' +``` + +`--input` types one line and Enter. If the pane closes during the send, the +runner reports the input error on stderr and still returns the job's exit. +All three standard descriptors use the pane's terminal. + +`--screen` retains exited panes in the private server long enough +to request the first four visible rows, at most 1,024 bytes. The sample may +omit a last write that tmux had yet to render. PTY output and screen cells +cannot separate stdout from stderr. + +## What the receipt means + +The app prepares a private Unix socket for each launch. It grants permission +only to the supervisor that presents the identity passed in the initial +pane's environment. tmux can replay the argv on respawn. The environment +identity belongs to the initial launch and is removed before the child runs. + +The [Lua caller](run.lua) gets its job handle after the supervisor spawns the +child and acknowledges startup. The adapter closes the channel and attempts +to remove the unpublished pane after a failed launch. Startup without an +acknowledgement within 750 ms returns an unknown result. + +The supervisor reports the direct child's exit or signal from its process +exit callback. Losing the connection before a complete receipt gives an +unknown outcome. A received receipt stays available to this Lua process +even after the pane or daemon is gone. + +The runner waits up to 30 seconds for a receipt after launch and input. +Use `--timeout-ms N` to change this budget. Checking the closed pane or +sampling the screen has a separate 750 ms budget. + +A timed-out or cancelled wait detaches that wait. Completing a job retires +its socket and lease. A long-lived caller can call `job:close():await()` +to join channel cleanup before starting another job. The saved receipt stays +readable. A still-running child can outlive channel cleanup. + +When the app leaves its scope, it closes the connection and stops its +server. On connection close or terminal hangup, the supervisor sends +SIGKILL to a direct child that still runs and tries to reap it. + +## Check the experiment + +```console +$ luajit scripts/check/check.lua integration program_exit_concept +``` + +The checks cover immediate exit, identical rendered lines with different +results after pane removal, stdin on a tty, literal argv, lookup after +daemon shutdown, cancellation and a supervisor lost before or after +startup acknowledgement. The replacement cannot fill the original result. +A cooked-terminal Ctrl-C reached the child and the supervisor reported +signal 2 in these checks. + +The checkout-only adapter uses standalone Lua for the launcher and its +supervisor. It uses the same executable for both. Neovim would need a way +to select a separate Lua executable and use its own host loop. + +The receipt stays in memory for the lifetime of this app. Recovery after +app restart, portable PTY and job control behavior, complete terminal +output and descendant cleanup need separate ownership rules. An abruptly +killed supervisor can leave children outside its control. Run trusted +commands under the same user as the private server. diff --git a/examples/concepts/program_exit/adapter.lua b/examples/concepts/program_exit/adapter.lua new file mode 100644 index 00000000..ffd5f7ba --- /dev/null +++ b/examples/concepts/program_exit/adapter.lua @@ -0,0 +1,250 @@ +local adapter = require("libtmux.runtime.luv") +local errors = require("libtmux._internal.error") +---@type any +---@diagnostic disable-next-line: different-requires +local uv = require("luv") + +local M = { run = adapter.run } +local IDENTITY = "LIBTMUX_LUA_CONCEPT_LAUNCH" +local FRAME_LIMIT = 64 + +local function must(value, err) + if not value then + error(tostring(err), 0) + end + return value +end + +local function now() + return tonumber(uv.hrtime()) / 1e6 +end + +local source = debug.getinfo(1, "S").source:sub(2) +local supervisor = must(uv.fs_realpath(source)):gsub("adapter%.lua$", "supervisor.lua") + +local function decode(frame) + local kind, number = frame:match("^(%a+) (%d+)$") + number = tonumber(number) + if kind == "exit" and number <= 255 or kind == "signal" and number > 0 and number <= 127 then + return { kind = kind, number = number } + end + return { kind = "unknown" } +end + +local function mailbox(runtime) + local saved, waiters = nil, {} + local function publish(result) + if not saved then + saved = result + for wake in pairs(waiters) do + wake(result) + end + end + end + local function wait(deadline) + return runtime:_logical_request({ + deadline = deadline, + bytes = FRAME_LIMIT, + start = function(settle, retire) + local function wake(result) + waiters[wake] = nil + settle({ kind = result.kind, number = result.number, cause = result.cause }) + retire() + end + if saved then + wake(saved) + else + waiters[wake] = true + end + return function() + waiters[wake] = nil + retire() + end + end, + }) + end + return publish, wait +end + +function M.launch(runtime, session, argv) + local deadline = now() + 750 + local identity = must(uv.random(16)):gsub(".", function(byte) + return ("%02x"):format(byte:byte()) + end) + local directory = must(uv.fs_mkdtemp("/tmp/libtmux-lua-job-XXXXXX")) + local socket = directory .. "/job.sock" + local listener, peer + local cleanup, closing = nil, 0 + + local function remove_directory() + if cleanup and closing == 0 then + local done = cleanup + cleanup = nil + local _, err = uv.fs_rmdir(directory) + done(err) + end + end + + local function close(handle) + if handle and not handle:is_closing() then + closing = closing + 1 + handle:close(function() + closing = closing - 1 + remove_directory() + end) + end + end + + local lease, err = runtime:_resource(function(done) + cleanup = done + close(listener) + close(peer) + remove_directory() + end) + if not lease then + must(uv.fs_rmdir(directory)) + return nil, err + end + + local publish_start, wait_start = mailbox(runtime) + local publish_exit, wait_exit = mailbox(runtime) + local phase = "identity" + local function finish(result) + if phase ~= "finished" then + phase = "finished" + lease:close() + publish_start(result) + publish_exit(result) + end + end + local function lost() + finish({ kind = "unknown" }) + end + + local creation + local function grant() + if not creation or phase ~= "permission" then + return + end + if now() >= deadline then + lost() + return + end + phase = "startup" + if + not peer:write("S", function(write_error) + if write_error then + lost() + end + end) + then + lost() + end + end + + local function receive(line) + if phase == "startup" and now() >= deadline then + lost() + elseif phase == "identity" and line == identity then + phase = "permission" + grant() + elseif phase == "startup" and line == "started" then + phase = "exit" + publish_start({ kind = "started" }) + elseif phase == "startup" and line:match("^spawn_failed [A-Z0-9_]+$") then + finish({ kind = "spawn_failed", cause = line:sub(14) }) + elseif phase == "exit" then + finish(decode(line)) + else + lost() + end + end + + listener = must(uv.new_pipe(false)) + must(listener:bind(socket)) + must(listener:listen(1, function(accept_error) + if accept_error then + lost() + return + end + peer = uv.new_pipe(false) + if not peer or not listener:accept(peer) then + lost() + return + end + close(listener) + local pending = "" + if + not peer:read_start(function(read_error, bytes) + if read_error or bytes == nil or #pending + #bytes > FRAME_LIMIT then + lost() + return + end + pending = pending .. bytes + while phase ~= "finished" do + local newline = pending:find("\n", 1, true) + if not newline then + break + end + local line = pending:sub(1, newline - 1) + pending = pending:sub(newline + 1) + receive(line) + end + end) + then + lost() + end + end)) + + local command = { must(uv.exepath()), supervisor, socket } + for _, value in ipairs(argv) do + command[#command + 1] = value + end + -- tmux reuses argv on respawn. This value belongs to the initial spawn. + creation, err = session + :new_window({ + argv = command, + cwd = uv.cwd(), + process = { deadline = deadline }, + environment = { [IDENTITY] = identity }, + }) + :await() + if not creation then + lost() + local _, cleanup_error = lease:close():await() + return nil, cleanup_error or err + end + grant() + + local pane = creation.pane + local startup, reason = wait_start(deadline):await() + if not startup or startup.kind ~= "started" then + lost() + local _, channel_error = lease:close():await() + local _, kill_error = pane:kill({ process = { timeout = 250 } }):await() + local cleanup_error = channel_error or kill_error + if startup and startup.kind == "spawn_failed" then + return nil, errors.new("spawn_failed", startup.cause, { cleanup_error = cleanup_error }) + end + return nil, + errors.new("launch_unknown", "supervisor did not acknowledge command startup", { + effect = "unknown", + cause = reason, + cleanup_error = cleanup_error, + }) + end + + return { + pane = pane, + directory = directory, + close = function(_) + lost() + return lease:close() + end, + wait = function(_, limit) + return wait_exit(limit) + end, + } +end + +return M diff --git a/examples/concepts/program_exit/check.lua b/examples/concepts/program_exit/check.lua new file mode 100644 index 00000000..29bbeee2 --- /dev/null +++ b/examples/concepts/program_exit/check.lua @@ -0,0 +1,4 @@ +local source = assert((...), "give the checker one Lua source file") +local chunk = loadfile(source) +print("done") +os.exit(chunk and 0 or 23) diff --git a/examples/concepts/program_exit/run.lua b/examples/concepts/program_exit/run.lua new file mode 100644 index 00000000..9c775007 --- /dev/null +++ b/examples/concepts/program_exit/run.lua @@ -0,0 +1,152 @@ +---@type any +---@diagnostic disable-next-line: different-requires +local uv = require("luv") + +local function must(value, err) + if value == nil then + error(tostring(err), 0) + end + return value +end + +local here = debug.getinfo(1, "S").source:match("^@(.*[/])") +local adapter = dofile(assert(here) .. "adapter.lua") +local argv = { ... } +local screen, line, timeout = false, nil, 30000 +local usage = "usage: run.lua [--screen] [--input LINE] [--timeout-ms N] -- COMMAND [ARG ...]" +while argv[1] and argv[1] ~= "--" do + local flag = table.remove(argv, 1) + if flag == "--screen" then + screen = true + elseif flag == "--input" then + line = assert(table.remove(argv, 1), usage) + assert(not line:find("[\r\n]"), usage) + elseif flag == "--timeout-ms" then + local value = tonumber(table.remove(argv, 1)) + assert(value and value >= 1 and value <= 2147483647 and value % 1 == 0, usage) + timeout = math.floor(value) + else + error(usage, 0) + end +end +assert(table.remove(argv, 1) == "--" and #argv > 0, usage) + +local function deadline(ms) + return tonumber(uv.hrtime()) / 1e6 + ms +end + +local report, problem = adapter.run(function(runtime) + local server = must(runtime + :start_server({ + binary = os.getenv("TMUX_BIN"), + }) + :await()).server + if screen then + local configured = must(server + :command({ + "set-option", + "-gw", + "remain-on-exit", + "on", + }) + :await()) + assert(configured.exit_code == 0, configured.stderr) + end + local session = must(server + :new_session({ + name = "build", + width = 80, + height = 24, + argv = { "/bin/cat" }, + }) + :await()).session + local job, launch_error = adapter.launch(runtime, session, argv) + if not job then + return nil, launch_error + end + local pane = job.pane + if line then + local sent, input_error = pane:send_text(line):await() + if sent then + local _, key_error = pane:send_keys({ "Enter" }):await() + input_error = key_error + end + if input_error then + io.stderr:write("tmux could not confirm input delivery: ", tostring(input_error), "\n") + end + end + + local result, err = job:wait(deadline(timeout)):await() + must(job:close():await()) + if not result then + return nil, err + end + if result.kind == "unknown" then + return result + end + + local id = pane:reference().id + local screen_deadline = deadline(750) + repeat + local state = server + :command({ + "display-message", + "-pt", + id, + "#{pane_id} #{pane_dead}", + }, { deadline = screen_deadline }) + :await() + if not state or state.exit_code ~= 0 then + break + end + local present, dead = state.stdout:match("^(%%%d+) (%d)\n$") + if present ~= id then + result.pane = "closed" + elseif screen and dead == "1" then + result.pane = "retained" + local sample = pane:capture({ + start_line = 0, + end_line = 3, + process = { deadline = screen_deadline, max_output_bytes = 1024 }, + }):await() + result.screen = sample and sample.bytes + end + until result.pane or deadline(0) >= screen_deadline + return result +end) + +if not report then + if problem and problem.code == "spawn_failed" then + print("job could not start (" .. tostring(problem) .. ")") + os.exit(125) + end + local message = "job runner failed" + if problem and problem.code == "deadline_exceeded" then + message = "completion wait timed out" + elseif problem and problem.code == "launch_unknown" then + message = "job startup unknown" + end + io.stderr:write(message, ": ", tostring(problem), "\n") + os.exit(125) +end +if report.pane then + print("pane " .. report.pane) +end +if report.kind == "exit" then + print("job exited " .. report.number) +elseif report.kind == "signal" then + print("job killed by signal " .. report.number) +else + print("job exit unknown") +end +if report.screen then + io.write("screen sample\n", report.screen) +else + print("screen unavailable") +end +if report.kind == "exit" then + os.exit(report.number) +elseif report.kind == "signal" then + os.exit(128 + report.number) +end +os.exit(125) diff --git a/examples/concepts/program_exit/supervisor.lua b/examples/concepts/program_exit/supervisor.lua new file mode 100644 index 00000000..438fe91a --- /dev/null +++ b/examples/concepts/program_exit/supervisor.lua @@ -0,0 +1,93 @@ +---@type any +---@diagnostic disable-next-line: different-requires +local uv = require("luv") + +local variable = "LIBTMUX_LUA_CONCEPT_LAUNCH" +local identity = os.getenv(variable) +if not identity then + return +end +assert(uv.os_unsetenv(variable)) +local socket, executable = ... +local argv = { select(3, ...) } +local pipe = assert(uv.new_pipe(false)) +local hangup = assert(uv.new_signal()) +local interrupt = assert(uv.new_signal()) +local child + +local function close_signals() + if not hangup:is_closing() then + hangup:close() + interrupt:close() + end +end + +local function disconnect() + if not pipe:is_closing() then + pipe:close() + end + if child then + child:kill("sigkill") + else + close_signals() + end +end + +local function send(frame, final) + if pipe:is_closing() then + close_signals() + return + end + if + not pipe:write(frame, function(err) + if err or final then + disconnect() + end + end) + then + disconnect() + end +end + +assert(hangup:start("sighup", disconnect)) +-- Ctrl-C reaches the child in the same foreground process group. Stay to reap it. +assert(interrupt:start("sigint", function() end)) +pipe:connect(socket, function(err) + if err then + disconnect() + return + end + local started = false + if + not pipe:read_start(function(read_error, bytes) + if read_error or bytes ~= "S" or started then + disconnect() + return + end + started = true + local _, cause + child, _, cause = uv.spawn( + executable, + { args = argv, stdio = { 0, 1, 2 } }, + function(code, signal) + child:close() + child = nil + local status = signal == 0 and ("exit %d\n"):format(code) + or ("signal %d\n"):format(signal) + send(status, true) + end + ) + if child then + send("started\n") + else + send(("spawn_failed %s\n"):format(cause or "UNKNOWN"), true) + end + end) + then + disconnect() + return + end + send(identity .. "\n") +end) + +uv.run("default") diff --git a/tests/integration/program_exit_concept.lua b/tests/integration/program_exit_concept.lua new file mode 100644 index 00000000..4398d4d3 --- /dev/null +++ b/tests/integration/program_exit_concept.lua @@ -0,0 +1,257 @@ +---@type any +---@diagnostic disable-next-line: different-requires +local uv = require("luv") +local adapter = dofile("examples/concepts/program_exit/adapter.lua") + +local function must(value, err) + if value == nil then + error(tostring(err), 0) + end + return value +end + +local function deadline(ms) + return tonumber(uv.hrtime()) / 1e6 + ms +end + +local function retained(server, pane, expected) + local limit = deadline(750) + repeat + local id = pane:reference().id + local current = must(server + :command({ + "display-message", + "-pt", + id, + "#{pane_id} #{pane_dead} #{pane_dead_status}", + }, { deadline = limit }) + :await()) + if current.stdout == ("%s 1 %d\n"):format(id, expected) then + return + end + until deadline(0) >= limit + error("pane did not retain exit " .. expected) +end + +local startup_probe = os.getenv("LIBTMUX_JOB_STARTUP_TEST") +if startup_probe then + local gate = startup_probe .. "/initial" + local marker = startup_probe .. "/child" + local init = ([=[ + local uv = require("luv") + local gate = uv.fs_open(%q, "wx", 384) + if gate then + uv.fs_write(gate, tostring(uv.os_getpid()), -1) + uv.fs_close(gate) + local hold = uv.new_timer() + hold:start(5000, 0, function() hold:close() end) + uv.run("default") + end + ]=]):format(gate) + must(adapter.run(function(runtime) + local owned = must(runtime + :start_server({ + binary = assert(os.getenv("TMUX_BIN")), + environment = { + LUA_INIT = init, + ["LUA_INIT_" .. _VERSION:sub(5):gsub("%.", "_")] = init, + }, + }) + :await()) + local server = owned.server + local session = + must(server:new_session({ name = "build", argv = { "/bin/cat" } }):await()).session + local resources = runtime:stats().resources + local start_time = deadline(0) + local active = runtime:spawn(function() + local job, err = adapter.launch(runtime, session, { + "/bin/sh", + "-c", + 'printf "%s\n" "$PPID" > "$1"; exit 71', + "sh", + marker, + }) + return { job = job, err = err } + end) + + local pane + local limit = deadline(650) + repeat + local fd = uv.fs_open(gate, "r", 0) + local pid + if fd then + pid = tonumber(uv.fs_read(fd, 32, 0)) + uv.fs_close(fd) + end + local snapshot = must(server:snapshot():await()) + for _, candidate in ipairs(snapshot.panes) do + if pid and candidate.pid == pid then + pane = must(server:handle(snapshot, candidate)) + break + end + end + until pane or deadline(0) >= limit + assert(pane, "initial supervisor never reached the test gate") + assert(not uv.fs_lstat(marker), "command started before the gate") + if os.getenv("LIBTMUX_JOB_STARTUP_RESPAWN") == "yes" then + must(pane:respawn({ kill = true }):await()) + end + + local launch = must(active:await()) + if launch.job then + local result = must(launch.job:wait(deadline(750)):await()) + error( + "unacknowledged supervisor escaped launch as " + .. result.kind + .. " " + .. tostring(result.number) + ) + end + assert(launch.err and launch.err.code == "launch_unknown", tostring(launch.err)) + assert(launch.err.cause and launch.err.cause.code == "deadline_exceeded") + local elapsed = deadline(0) - start_time + assert( + elapsed >= 700 and elapsed < 1500, + ("unacknowledged startup took %.0f ms"):format(elapsed) + ) + assert(not uv.fs_lstat(marker), "respawn replayed the command") + local _, pane_error = pane:snapshot():await() + assert(pane_error and pane_error.code == "target_missing", tostring(pane_error)) + assert(runtime:stats().resources == resources, "startup left a channel lease") + return true + end)) + return +end + +local dirs = {} +local socket +must(adapter.run(function(runtime) + local owned = must(runtime:start_server({ binary = assert(os.getenv("TMUX_BIN")) }):await()) + local server = owned.server + socket = owned.socket_path + local settings = must(server + :command({ + "set-option", + "-gw", + "remain-on-exit", + "on", + }) + :await()) + assert(settings.exit_code == 0, settings.stderr) + local session = must(server + :new_session({ + name = "build", + argv = { "/bin/cat" }, + }) + :await()).session + + local resources = runtime:stats().resources + local function retired(job) + must(job:close():await()) + assert(not uv.fs_lstat(job.directory)) + assert(runtime:stats().resources == resources, "the job lease survived") + end + + local before = must(server:command({ "list-panes", "-a", "-F", "#{pane_id}" }):await()) + local failed, spawn_error = adapter.launch(runtime, session, { "/no-libtmux-executable" }) + assert(not failed and spawn_error and spawn_error.code == "spawn_failed", tostring(spawn_error)) + local after = must(server:command({ "list-panes", "-a", "-F", "#{pane_id}" }):await()) + assert(after.stdout == before.stdout, "spawn failure left an unpublished pane") + assert(runtime:stats().resources == resources, "spawn failure left a channel lease") + + local function launch(body) + local job = must(adapter.launch(runtime, session, { "/bin/sh", "-c", body })) + dirs[#dirs + 1] = job.directory + must(job.pane:wait_for_text("ready", { timeout = 750, interval = 10 }):await()) + return job + end + + local typed = launch("printf 'ready\\n'; IFS= read -r line; test \"$line\" = passed || exit 21") + local _, expired = typed:wait(deadline(25)):await() + assert(expired and expired.code == "deadline_exceeded") + local canceled = typed:wait(deadline(750)) + must(server:command({ "list-panes" }):await()) + assert(canceled:cancel()) + local _, stopped = canceled:await() + assert(stopped and stopped.code == "cancelled") + must(typed.pane:send_text("passed"):await()) + must(typed.pane:send_keys({ "Enter" }):await()) + local completed = must(typed:wait(deadline(750)):await()) + assert(completed.kind == "exit" and completed.number == 0) + retired(typed) + must(typed.pane:respawn({ kill = true, argv = { "/bin/sh", "-c", "exit 57" } }):await()) + retained(server, typed.pane, 57) + assert(must(typed:wait(deadline(750)):await()).number == 0) + + local lost = launch([[printf 'ready\n'; IFS= read -r line; kill -KILL 0]]) + local id = lost.pane:reference().id + must(lost.pane:send_keys({ "Enter" }):await()) + assert(must(lost:wait(deadline(750)):await()).kind == "unknown") + must(lost.pane:respawn({ kill = true, argv = { "/bin/sh", "-c", "exit 41" } }):await()) + assert(lost.pane:reference().id == id) + retained(server, lost.pane, 41) + assert(must(lost:wait(deadline(750)):await()).kind == "unknown") + retired(lost) + + local replay = must(adapter.launch(runtime, session, { + "/bin/sh", + "-c", + "IFS= read -r line; exit 31", + })) + dirs[#dirs + 1] = replay.directory + must(replay.pane:respawn({ kill = true }):await()) + assert(must(replay:wait(deadline(750)):await()).kind == "unknown") + retained(server, replay.pane, 0) + retired(replay) + + local interrupted = launch("printf 'ready\\n'; IFS= read -r line; exit 29") + must(interrupted.pane:send_keys({ "C-c" }):await()) + local signal = must(interrupted:wait(deadline(750)):await()) + assert(signal.kind == "signal" and signal.number == 2, signal.kind) + retired(interrupted) + + must(server:command({ "set-option", "-gw", "remain-on-exit", "off" }):await()) + for _, case in ipairs({ { "lua/libtmux/init.lua", 0 }, { "README.md", 23 } }) do + local visible = must(adapter.launch(runtime, session, { + "/bin/sh", + "-c", + '"$1" "$2" "$3"; status=$?; IFS= read -r line; exit "$status"', + "sh", + uv.exepath(), + "examples/concepts/program_exit/check.lua", + case[1], + })) + dirs[#dirs + 1] = visible.directory + must(visible.pane:wait_for_text("done", { timeout = 750, interval = 10 }):await()) + local capture = must(visible.pane:capture({ start_line = 0, end_line = 0 }):await()) + assert(capture.bytes == "done\n", capture.bytes) + local visible_id = visible.pane:reference().id + must(visible.pane:send_keys({ "Enter" }):await()) + local gone + local limit = deadline(750) + repeat + local state = must(server + :command({ + "display-message", + "-pt", + visible_id, + "#{pane_id}", + }, { deadline = limit }) + :await()) + gone = state.stdout == "\n" + until gone or deadline(0) >= limit + assert(gone, "pane still exists") + local result = must(visible:wait(deadline(750)):await()) + assert(result.kind == "exit" and result.number == case[2]) + retired(visible) + end + + must(owned:stop():await()) + local later = must(typed:wait(deadline(750)):await()) + assert(later.kind == "exit" and later.number == 0) + return true +end, { max_resources = 3 })) +assert(not uv.fs_lstat(socket)) +for _, directory in ipairs(dirs) do + assert(not uv.fs_lstat(directory), "job directory survived: " .. directory) +end diff --git a/tests/integration/test_program_exit_concept.lua b/tests/integration/test_program_exit_concept.lua new file mode 100644 index 00000000..3e00d5cd --- /dev/null +++ b/tests/integration/test_program_exit_concept.lua @@ -0,0 +1,140 @@ +local child = require("tests.support.child") +local fixture = require("tests.support.fixture") +local repo = require("support.repo") +local fs = require("support.fs") +local test = require("luaunit") + +local M = {} +local concept = "examples/concepts/program_exit/" + +local function run(argv) + local env = fixture.environment({ TMUX_BIN = fixture.tmux() }) + return child.run(argv, { env = env, cwd = repo.root, timeout = 3 }) +end + +local function demo(...) + return run({ fixture.lua(), concept .. "run.lua", "--", ... }) +end + +function M.test_the_same_visible_done_leads_to_two_different_build_results() + local command = { fixture.lua(), concept .. "check.lua" } + for _, case in ipairs({ + { source = "lua/libtmux/init.lua", status = 0 }, + { source = "README.md", status = 23 }, + }) do + local direct = run({ command[1], command[2], case.source }) + test.assertEquals(direct.code, case.status) + test.assertEquals(direct.stdout, "done\n") + + local result = demo(command[1], command[2], case.source) + test.assertEquals(result.stderr, "") + test.assertEquals(result.code, case.status) + test.assertEquals( + result.stdout, + ("pane closed\njob exited %d\nscreen unavailable\n"):format(case.status) + ) + end +end + +function M.test_exit_143_and_sigterm_are_distinct() + local exited = demo("/bin/sh", "-c", "exit 143") + local signaled = demo("/bin/sh", "-c", "kill -TERM $$") + test.assertEquals(exited.code, 143, exited.stderr) + test.assertEquals(signaled.code, 143, signaled.stderr) + test.assertStrContains(exited.stdout, "job exited 143") + test.assertStrContains(signaled.stdout, "job killed by signal 15") +end + +function M.test_literal_argv_and_input_reach_a_real_pty() + local input = "one line from the Lua app" + local expected = [[$(printf altered); #{pane_id}]] + local result = run({ + fixture.lua(), + concept .. "run.lua", + "--screen", + "--input", + input, + "--", + "/bin/sh", + "-c", + [=[ + test -t 0 && test -t 1 && test -t 2 || exit 31 + test "$1" = '$(printf altered); #{pane_id}' || exit 32 + test -z "$LIBTMUX_LUA_CONCEPT_LAUNCH" || exit 35 + IFS= read -r line && test "$line" = "$2" || exit 33 + for i in 1 2 3 4 5 6 7 8 9; do printf '%s\n' "$line"; done + ]=], + "sh", + expected, + input, + }) + test.assertEquals(result.stderr, "") + test.assertEquals(result.code, 0, result.stdout) + local screen = result.stdout:match("screen sample\n(.*)$") + test.assertNotNil(screen, result.stdout) + local _, lines = screen:gsub("\n", "") + test.assertEquals(lines, 4) + test.assertTrue(#screen <= 1024) +end + +function M.test_a_missing_executable_has_no_exit_status() + local result = demo("/this-directory-does-not-exist-libtmux/command") + test.assertEquals(result.code, 125, result.stderr) + test.assertStrContains(result.stdout, "job could not start (ENOENT)") +end + +function M.test_early_exit_keeps_its_status_when_the_runner_sends_input() + local result = run({ + fixture.lua(), + concept .. "run.lua", + "--input", + "build next", + "--", + "/bin/sh", + "-c", + "exit 23", + }) + test.assertEquals(result.code, 23, result.stdout .. result.stderr) + test.assertStrContains(result.stdout, "job exited 23") +end + +function M.test_cli_timeout_has_no_exit_status() + local result = run({ + fixture.lua(), + concept .. "run.lua", + "--timeout-ms", + "25", + "--", + "/bin/sh", + "-c", + "IFS= read -r line; exit 91", + }) + test.assertEquals(result.code, 125, result.stderr) + test.assertStrContains(result.stderr, "completion wait timed out") + test.assertEquals(result.stdout, "") +end + +function M.test_waiting_and_replacing_the_pane() + fixture.program("luv", "program_exit_concept", { TMUX_BIN = fixture.tmux() }, { timeout = 4 }) +end + +local function startup(respawn) + local root = fs.mkdtemp("libtmux-lua-job-startup-") + local ok, err = pcall(fixture.program, "luv", "program_exit_concept", { + TMUX_BIN = fixture.tmux(), + LIBTMUX_JOB_STARTUP_TEST = root, + LIBTMUX_JOB_STARTUP_RESPAWN = respawn, + }, { timeout = 3 }) + fs.remove_tree(root) + assert(ok, err) +end + +function M.test_respawn_before_connect_cannot_start_the_original_job() + startup("yes") +end + +function M.test_startup_deadline_cleans_up_a_stalled_supervisor_and_lease() + startup("no") +end + +return M From e88eca59f16ff3c9870d75ca0ded44f1d579088f Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 12:00:14 -0600 Subject: [PATCH 2/3] Program(feat): Own terminal application runs why: An application exit result and final terminal output must survive the pane lifecycle. Standalone Lua and Neovim need the same ownership contract. what: - Start an interactive Program or run it to completion with a Request. - Retain the application exit, terminal bytes, final screen and cleanup. - Test input, deadlines, explicit stop and externally closed sessions. --- README.md | 4 +- capabilities.json | 10 + docs/creation.md | 7 +- docs/programs.md | 139 +++ examples/api/README.md | 1 + examples/api/manifest.json | 16 + examples/api/owned_program.lua | 94 ++ examples/concepts/program_exit/README.md | 20 +- examples/concepts/program_exit/adapter.lua | 7 +- lua/libtmux/_internal/domain.lua | 9 +- lua/libtmux/_internal/pane.lua | 4 +- lua/libtmux/_internal/program.lua | 1080 +++++++++++++++++ lua/libtmux/_internal/program_channel.lua | 382 ++++++ lua/libtmux/_internal/program_supervisor.lua | 467 +++++++ lua/libtmux/_internal/server.lua | 40 +- .../_internal/support/capabilities.lua | 15 + lua/libtmux/runtime/luv.lua | 18 + rockspecs/libtmux-scm-1.rockspec | 3 + scripts/docs/tests/test_api_examples.lua | 15 +- tests/integration/program_contract.lua | 504 ++++++++ tests/integration/program_exit_concept.lua | 14 + tests/integration/test_program_contract.lua | 66 + .../integration/test_program_exit_concept.lua | 5 +- tests/integration/test_runtime.lua | 51 +- tests/unit/server.lua | 64 +- 25 files changed, 2984 insertions(+), 51 deletions(-) create mode 100644 docs/programs.md create mode 100644 examples/api/owned_program.lua create mode 100644 lua/libtmux/_internal/program.lua create mode 100644 lua/libtmux/_internal/program_channel.lua create mode 100644 lua/libtmux/_internal/program_supervisor.lua create mode 100644 tests/integration/program_contract.lua create mode 100644 tests/integration/test_program_contract.lua diff --git a/README.md b/README.md index 7a3a7c33..06082b92 100644 --- a/README.md +++ b/README.md @@ -348,8 +348,8 @@ editor build ## Create sessions, windows and panes -The [pane job example](examples/concepts/program_exit/README.md) reads a -command's exit status after its pane closes. +The [terminal program guide](docs/programs.md) shows how to run a job, send +input and collect its exit status and final screen after its pane closes. ### [`Session:new_window`][ref-session-new-window]: add a window diff --git a/capabilities.json b/capabilities.json index 585cd11c..1dd93d56 100644 --- a/capabilities.json +++ b/capabilities.json @@ -3,6 +3,16 @@ "port": "lua", "floor": {"minimum": "3.3a"}, "capabilities": [ + { + "id": "owned-program", + "name": "Owned terminal programs", + "summary": "Start a terminal program and collect its output, status and cleanup.", + "since": "3.3a", + "handling": "refuse", + "error": "libtmux.Error", + "apis": ["libtmux.Server:start_program", "libtmux.Server:run_program"], + "commands": [{"command": "new-session", "flags": ["-e", "-F", "-P"]}, {"command": "if-shell", "flags": ["-F", "-t"]}, {"command": "pipe-pane", "flags": ["-O", "-t"]}] + }, { "id": "control-mode", "name": "Control mode observation", diff --git a/docs/creation.md b/docs/creation.md index 8203e24a..95459326 100644 --- a/docs/creation.md +++ b/docs/creation.md @@ -12,10 +12,9 @@ from tmux's returned IDs. Its `created` list names what the call created: - A window: the window, pane and link. - A split: the pane only. -The other handles describe the containing context. A created pane proves -neither that its program started nor that it succeeded. See the -[pane job completion experiment](../examples/concepts/program_exit/README.md) -for a result from the specific command a Lua caller launched. +The other handles describe the containing context. Use +[`Server:run_program`](programs.md) to obtain the exit status and final screen +of the application you launched. ## Commands and literal values diff --git a/docs/programs.md b/docs/programs.md new file mode 100644 index 00000000..bac48c02 --- /dev/null +++ b/docs/programs.md @@ -0,0 +1,139 @@ +# Run a terminal program + +Use `Server:run_program(argv, options)` when you want the application's exit +status and final terminal output. Use `Server:start_program(argv, options)` +when you also need to send input or sample the screen while the program runs. +Both calls return Requests. The start Request resolves to a Program after +the executable launches in its own tmux session. + +The [complete Program example](../examples/api/owned_program.lua) reads a +calculator's answer and exit status, stops a second interactive program, +and checks cleanup after a run deadline. + +Install the source build of the library and `luv` using the +[API examples setup](../examples/api/README.md). The published `0.1.1-1` rock +predates this API. + +```console +$ lua examples/api/owned_program.lua +``` + +The same example uses the +[`libtmux.runtime.nvim` adapter](runtime.md) in Neovim. + +```console +$ nvim --headless -u NONE -i NONE -l examples/api/owned_program.lua +``` + +The example waits for the application's reply, then awaits `program:stop()` +for its signal, terminal output and cleanup result. It prints +`received: [draft] (signal 15, pane closed)` and reads the saved final screen +with `program:screen()`. + +## Launch and input + +- Pass a literal argv array. The executable may be a single item, and empty + later arguments and shell metacharacters are preserved. To interpret + shell source, pass that shell and its source explicitly as argv. +- `cwd` must be an absolute directory. `environment` adds literal strings + to the launched application's inherited terminal environment. + The launcher receives its own configuration. The internal names + `LIBTMUX_LUA_PROGRAM_TOKEN` and `LIBTMUX_LUA_PROGRAM_CPATH` are reserved. +- `width` and `height` default to 80 by 24. The requested area may contain + up to 1,048,576 terminal cells. The argv and environment limits are the + same as for [session creation](creation.md#errors-and-limits). +- `startup_timeout` defaults to 1,000 ms. With `start_program`, `timeout` + also selects the startup limit when `startup_timeout` is omitted. With + `run_program`, `timeout` bounds the entire run, including startup. +- `program:send_text(text)` sends literal text and + `program:send_keys({ "Enter" })` sends named keys. Both take optional timing + as the last argument. `program:reference()` copies the three tmux IDs and + exposes the launch's `cleanup_scope` while it runs. + +The launch is pinned to the connected tmux generation. The +[`owned-program` capability](../capabilities.json) describes the minimum +daemon release and native commands. Below tmux 3.3a or with an unsupported +daemon version, connection or launch refuses before the application starts. + +The tmux server and Lua host must run as the same user and see the same +installation and local socket directory. Standalone Lua launches the +supervisor with its own Lua executable and `luv`. Neovim launches a dedicated +headless Neovim using its embedded libuv. If needed, pass `lua` with an +absolute path to a standalone Lua executable that can load `luv`. +The supervisor path stays tied to the loaded library. Standalone Lua +resolves relative native-module templates from the runtime's starting +directory, including when the application uses a different `cwd`. + +## Wait, stop and recover + +`program:wait({ timeout = 25 })` can return `deadline_exceeded` with the +program still running. Cancelling that Request detaches that wait. Another +wait can collect the result. Use `deadline` for an absolute monotonic time +in milliseconds. When both bounds are present, the earlier one applies. +Requests follow the [runtime's settlement and retirement +rules](runtime.md#cancellation-and-limits). + +`program:stop()` requests termination and returns the same ProgramResult as +`wait()`. Its default wait is 3,200 ms. Cancelling an owning `run_program` +Request also requests termination. The Request can settle with +`cancelled` while cleanup proceeds. After it retires, the error can carry +`partial.result`, `cleanup_error` and a recoverable `program` handle or +`program_name`. A run that reaches its timeout joins the bounded cleanup +before returning `deadline_exceeded`. + +If the runtime closes while `start_program` or `run_program` is starting +an application, check the Request's error after it retires. +`cleanup_error` and `program_name` identify a tmux session whose removal +the runtime could not confirm. The session may already have closed. + +Closing a Server handle stops its Programs. The runtime also owns the +native supervisor connection and closes it at scope exit. The supervisor +then terminates and reaps the directly spawned application. A verified +Linux subreaper with pidfds also terminates and reaps adopted descendants. +`cleanup.scope` reports `direct` or `tree` for the launch. Descendants on a +`direct` host can outlive the application. Loss of the supervisor can leave +status or process cleanup unconfirmed. + +Pass `require_tree = true` to either launch call when you depend on orphan +cleanup. The application starts only after the supervisor verifies that +scope. Otherwise the call returns `unsupported` and closes any temporary +pane it used for qualification. + +On Linux, a PUC Lua application can request tree cleanup by passing +`{ lua = "/path/to/luajit", require_tree = true }`. Use the absolute path to +a LuaJIT executable that can load its own `luv`. + +`cleanup.pane_closed` confirms that the original pane disappeared from the +pinned daemon. On external replacement, input is refused and the +replacement pane stays available. A cleanup failure can include a +`program_name` to inspect on the same daemon. Confirm the ownership of a +remaining session before removing it. + +## Read the status and output + +The result's `kind` is `exit`, `signal` or `unknown`. An exit has +`exit_code`, a signal has a numeric `signal`, and an unconfirmed status can +carry an `error`. A nonzero exit code still returns a ProgramResult. + +If someone closes the program's session or stops its server while it is +running, a confirmed status can arrive with `output.complete = false` and +a `screen_error`. When the server stops, `cleanup.pane_closed` can be +`false` with `cleanup_error.code = "stale_generation"`. The saved exit +status or signal is still valid. The cleanup error describes pane +verification against the old daemon. + +- `output.bytes` is the retained PTY byte prefix from `tmux_pipe_pane`. + It preserves CR, NUL and escape sequences. It includes merged stdout, + stderr and terminal input echo. `output.complete` requires the supervisor's + end marker and zero dropped bytes. `dropped_bytes` counts discarded bytes + received before the marker. An interrupted stream can report `output.error` + with no count for the bytes it never received. +- `screen.bytes` is the rendered viewport from `tmux_capture_pane` with + `rows` and `columns`. It excludes scrollback and uses newline-separated + visible rows. `screen.final` records capture after the end marker. + `program:screen()` uses that saved sample after completion. Capture failure + is reported in `screen_error`. +- Both representations use the `max_output_bytes` cap, which defaults to + 1 MiB and accepts integers through 16 MiB. Each has a `truncated` flag. + A byte prefix can end in the middle of UTF-8 text. Runtime byte limits + also apply to buffered output and delivery. diff --git a/examples/api/README.md b/examples/api/README.md index c28dda0d..5520fd51 100644 --- a/examples/api/README.md +++ b/examples/api/README.md @@ -44,6 +44,7 @@ to select a different build. | [read_pane_line.lua](read_pane_line.lua) | Wait for a complete `result=` line (tmux 3.7 or newer) | `result=42` | | [send_keys.lua](send_keys.lua) | Send text and press Enter | `lua input ready` | | [capture.lua](capture.lua) | Read a completed command's output | `lua capture ready` | +| [owned_program.lua](owned_program.lua) | Read an exit status, stop an interactive program, and inspect its final screen | `answer=42 (exit 7)`, `received: [draft] (signal 15, pane closed)`, `deadline_exceeded, pane closed` | | [wait_for_text.lua](wait_for_text.lua) | Wait for text on the visible screen | `lua wait ready` | | [watch_pane.lua](watch_pane.lua) | Send a sum to `awk` and read its reply over control mode (tmux 3.7 or newer) | `19 + 23 = 42` | | [vote_counter.lua](vote_counter.lua) | Send votes and read each tally over control mode (tmux 3.7 or newer) | Three tallies ending at `yes=2 no=1` | diff --git a/examples/api/manifest.json b/examples/api/manifest.json index 2533fcfb..2f2a30ae 100644 --- a/examples/api/manifest.json +++ b/examples/api/manifest.json @@ -153,6 +153,22 @@ "description": "Capture a completed command's output from a pane.", "stdout": "lua capture ready\n" }, + { + "id": "owned_program", + "symbols": [ + "libtmux.Server:start_program", + "libtmux.Server:run_program", + "libtmux.Program:send_text", + "libtmux.Program:send_keys", + "libtmux.Program:wait", + "libtmux.Program:reference", + "libtmux.Program:stop", + "libtmux.Program:screen" + ], + "file": "examples/api/owned_program.lua", + "description": "Read a calculator result, stop an interactive program, and inspect its final terminal output.", + "stdout": "answer=42 (exit 7)\nreceived: [draft] (signal 15, pane closed)\ndeadline_exceeded, pane closed\n" + }, { "id": "wait_for_text", "symbols": [ diff --git a/examples/api/owned_program.lua b/examples/api/owned_program.lua new file mode 100644 index 00000000..be4d0054 --- /dev/null +++ b/examples/api/owned_program.lua @@ -0,0 +1,94 @@ +local adapter = require("libtmux.runtime.luv") + +local function must(value, err) + if err then + error(tostring(err), 0) + end + return assert(value) +end + +local binary = os.getenv("TMUX_BIN") + +---@param server libtmux.Server +local function run_programs(server) + local batch_argv = { "/bin/sh", "-c", [[printf 'batch\n'; exit 3]] } + local batch = must(server:run_program(batch_argv):await()) + assert(batch.exit_code == 3 and batch.output.bytes == "batch\r\n") + + local program = must(server + :start_program({ + "/usr/bin/awk", + [[NF == 3 && $2 == "+" { printf "answer=%d\n", $1 + $3; exit 7 }]], + }) + :await()) + local ready, expired = program:wait({ timeout = 0 }):await() + assert(not ready and expired and expired.code == "deadline_exceeded") + must(program:send_text("19 + 23"):await()) + must(program:send_keys({ "Enter" }):await()) + local result = must(program:wait({ timeout = 2000 }):await()) + assert(result.kind == "exit" and result.output.complete) + local answer = assert(result.output.bytes:match("(answer=%d+)\r\n")) + local final = must(result.screen, result.screen_error) + assert(final.bytes:find(answer, 1, true) and result.cleanup.pane_closed) + io.write(("%s (exit %d)\n"):format(answer, result.exit_code)) + + local draft = must(server + :start_program({ + "/usr/bin/awk", + [[{ print "received: [" $0 "]"; fflush() }]], + }) + :await()) + must(draft:send_text("draft"):await()) + must(draft:send_keys({ "Enter" }):await()) + + local snapshot = must(server:snapshot():await()) + local pane_id = draft:reference().pane_id + local row = must(snapshot.panes:where({ id = pane_id }):one()) + local pane = must(server:handle(snapshot, row)) + local reply = "received: [draft]" + must(pane:wait_for_text(reply, { timeout = 2000 }):await()) + + local cancelled = must(draft:stop():await()) + assert(cancelled.kind == "signal" and cancelled.signal == 15) + local output = cancelled.output + assert(output.complete and output.bytes == "draft\r\n" .. reply .. "\r\n") + local screen = must(draft:screen():await()) + assert(screen.final and screen.bytes:find(reply .. "\n", 1, true)) + assert(not cancelled.cleanup_error, tostring(cancelled.cleanup_error)) + assert(cancelled.cleanup.pane_closed) + io.write(("%s (signal %d, pane closed)\n"):format(reply, cancelled.signal)) + + local bounded = server:run_program({ "/bin/cat" }, { timeout = 1000 }) + local idle, timeout = bounded:await() + assert(not idle and timeout and timeout.code == "deadline_exceeded") + local stopped = assert(timeout.partial.result) + assert(stopped.kind == "signal" and stopped.cleanup.pane_closed) + io.write("deadline_exceeded, pane closed\n") + return true +end + +---@param runtime libtmux.Runtime +local function run(runtime) + return runtime:with_server({ binary = binary }, run_programs):await() +end + +local host = rawget(_G, "vim") +if not host then + must(adapter.run(run)) + return +end + +local done, value, failure +local nvim = require("libtmux.runtime.nvim") +local runtime, start_error = nvim.start(run, function(result, err) + done, value, failure = true, result, err +end) +assert(runtime, tostring(start_error)) +local function finished() + return done == true +end +if not host.wait(15000, finished) then + runtime:close("example timed out") + assert(host.wait(6000, finished), "example cleanup timed out") +end +must(value, failure) diff --git a/examples/concepts/program_exit/README.md b/examples/concepts/program_exit/README.md index eec8d0da..10ec977b 100644 --- a/examples/concepts/program_exit/README.md +++ b/examples/concepts/program_exit/README.md @@ -1,5 +1,8 @@ # Ask how a pane job ended +Use the [owned Program API](../../../docs/programs.md) in an application. +This checkout experiment shows the earlier status receipt on its own. + A build runner can use the exit of the command it launched to decide whether to publish an artifact. This checkout experiment gets that exit even after tmux removes the pane. @@ -39,7 +42,7 @@ shell and give different reports. ```console $ lua examples/concepts/program_exit/run.lua --screen --input 'build next' \ -- /bin/sh -c 'test -t 0 && test -t 1 && test -t 2 && read -r line && - test "$line" = "build next" && printf "%s\n" "$line"' + test "$line" = "build next" && printf "reply: [%s]\n" "$line"' ``` `--input` types one line and Enter. If the pane closes during the send, the @@ -58,10 +61,17 @@ only to the supervisor that presents the identity passed in the initial pane's environment. tmux can replay the argv on respawn. The environment identity belongs to the initial launch and is removed before the child runs. -The [Lua caller](run.lua) gets its job handle after the supervisor spawns the -child and acknowledges startup. The adapter closes the channel and attempts -to remove the unpublished pane after a failed launch. Startup without an -acknowledgement within 750 ms returns an unknown result. +Inside [`adapter.run`](run.lua), call `adapter.launch(runtime, session, argv)` +with a dense list of strings. It checks the list before opening a channel +and returns a job after the supervisor acknowledges that the child started. + +Call `job:wait(deadline):await()` to read the receipt. A build runner can +publish when `receipt.kind == "exit"` and `receipt.number == 0`. +The deadline is in absolute monotonic milliseconds. + +The adapter closes the channel and attempts to remove the unpublished pane +after a failed launch. Startup without an acknowledgement within 750 ms +returns an unknown result. The supervisor reports the direct child's exit or signal from its process exit callback. Losing the connection before a complete receipt gives an diff --git a/examples/concepts/program_exit/adapter.lua b/examples/concepts/program_exit/adapter.lua index ffd5f7ba..59862892 100644 --- a/examples/concepts/program_exit/adapter.lua +++ b/examples/concepts/program_exit/adapter.lua @@ -1,5 +1,6 @@ local adapter = require("libtmux.runtime.luv") local errors = require("libtmux._internal.error") +local process = require("libtmux._internal.process") ---@type any ---@diagnostic disable-next-line: different-requires local uv = require("luv") @@ -67,6 +68,10 @@ local function mailbox(runtime) end function M.launch(runtime, session, argv) + local launch, invalid = process.prepare(argv) + if not launch then + return nil, invalid + end local deadline = now() + 750 local identity = must(uv.random(16)):gsub(".", function(byte) return ("%02x"):format(byte:byte()) @@ -197,7 +202,7 @@ function M.launch(runtime, session, argv) end)) local command = { must(uv.exepath()), supervisor, socket } - for _, value in ipairs(argv) do + for _, value in ipairs(launch.argv) do command[#command + 1] = value end -- tmux reuses argv on respawn. This value belongs to the initial spawn. diff --git a/lua/libtmux/_internal/domain.lua b/lua/libtmux/_internal/domain.lua index b75b34f7..a5cba7d3 100644 --- a/lua/libtmux/_internal/domain.lua +++ b/lua/libtmux/_internal/domain.lua @@ -135,7 +135,7 @@ local function current(state, parent) return generation, ref end -local function prepare(runtime, kind, ref, options) +function M.prepare(runtime, kind, ref, options, format) if not commands[kind] then invalid("unknown creation kind") end @@ -185,7 +185,7 @@ local function prepare(runtime, kind, ref, options) flag("-d") end flag("-P") - flag("-F", creation_format) + flag("-F", format or creation_format) if options.name ~= nil then if not bytes(options.name, false, 1024) then invalid("name must be a bounded NUL-free string") @@ -282,10 +282,11 @@ local function prepare(runtime, kind, ref, options) return plan end -function M.directory(state, path, operation) +function M.directory(state, path, operation, deadline) operation = operation or "create.cwd" return state.runtime:_request({ bytes = #path, + deadline = deadline, operation = operation, effect = "not_sent", start = function(settle, retire) @@ -391,7 +392,7 @@ function M.create(state, parent, kind, options, wrap) if not generation then validation_error = ref else - local ok, value = pcall(prepare, state.runtime, kind, ref, options) + local ok, value = pcall(M.prepare, state.runtime, kind, ref, options) if ok then plan = value else diff --git a/lua/libtmux/_internal/pane.lua b/lua/libtmux/_internal/pane.lua index 01caf4a4..f7e6b537 100644 --- a/lua/libtmux/_internal/pane.lua +++ b/lua/libtmux/_internal/pane.lua @@ -211,7 +211,7 @@ local function current(state, owned, kind) return ref end -local function prepare(state, ref, kind, data, options, inspect) +function M.prepare(state, ref, kind, data, options, inspect) local function invalid(message, code) error(failure(code or "invalid_options", message, kind), 0) end @@ -525,7 +525,7 @@ function M.run(state, owned, kind, data, options, inspect) local ref, validation_error = current(state, owned, kind) local plan if ref then - local ok, value = pcall(prepare, state, ref, kind, data, options, inspect) + local ok, value = pcall(M.prepare, state, ref, kind, data, options, inspect) if ok then plan = value else diff --git a/lua/libtmux/_internal/program.lua b/lua/libtmux/_internal/program.lua new file mode 100644 index 00000000..57a87b21 --- /dev/null +++ b/lua/libtmux/_internal/program.lua @@ -0,0 +1,1080 @@ +local capabilities = require("libtmux._internal.support.capabilities") +local channel = require("libtmux._internal.program_channel") +local codec = require("libtmux._internal.codec") +local command = require("libtmux._internal.command") +local domain = require("libtmux._internal.domain") +local errors = require("libtmux._internal.error") +local fields = require("libtmux._internal.fields") +local pane = require("libtmux._internal.pane") +local process = require("libtmux._internal.process") +local M, Program = {}, {} +local programs = setmetatable({}, { __mode = "kv" }) + +local TOKEN = "LIBTMUX_LUA_PROGRAM_TOKEN" +local CPATH = "LIBTMUX_LUA_PROGRAM_CPATH" +local CLEANUP_MS = 750 +local STOP_MS = 3200 +local MAX_OUTPUT = 16 * 1024 * 1024 +local CAPTURE_READ_SIZE = 64 * 1024 +local MAX_SCREEN_CELLS = 1024 * 1024 +local format = assert(codec.format({ "session_id", "window_id", "pane_id", "pane_pid" })) +local source = debug.getinfo(1, "S").source:sub(2) +local supervisor = (source:gsub("program%.lua$", "program_supervisor.lua")) + +function M.bind(runtime) + local uv = runtime._driver.uv + if supervisor:sub(1, 1) == "/" or not uv or type(uv.cwd) ~= "function" then + return + end + local cwd = uv.cwd() + if cwd then + supervisor = cwd:gsub("/$", "") .. "/" .. supervisor + end +end + +local function failure(code, message, operation, details) + details = details or {} + details.operation = "program." .. operation + details.effect = details.effect or "not_sent" + return errors.new(code, message, details) +end + +local function plain(value) + return type(value) == "table" and getmetatable(value) == nil +end + +local function finite(value) + return type(value) == "number" and math.abs(value) < math.huge +end + +local function default(value, fallback) + if value == nil then + return fallback + end + return value +end + +local function copy(value) + local result = {} + for key, item in pairs(value) do + result[key] = item + end + return result +end + +local function copy_result(value) + local result = copy(value) + for _, key in ipairs({ "output", "screen", "cleanup" }) do + if value[key] then + result[key] = copy(value[key]) + end + end + return result +end + +local function reject(state, err, operation) + return state.runtime:_operation(function() + return nil, err + end, { operation = "program." .. operation, effect = "not_sent" }) +end + +local function deadline(owner, options, operation, fallback) + options = default(options, {}) + if not plain(options) then + return nil, failure("invalid_options", "program timing must be a plain table", operation) + end + for key in next, options do + if key ~= "timeout" and key ~= "deadline" then + return nil, failure("invalid_options", "unknown program timing option", operation) + end + end + local timeout = options.timeout + if timeout == nil and options.deadline == nil then + timeout = fallback + end + local limit, reason = owner.server.runtime:_deadline(timeout, options.deadline) + if reason then + return nil, failure("invalid_options", reason, operation) + end + return limit +end + +local function absolute(value) + return type(value) == "string" + and value:sub(1, 1) == "/" + and #value <= 4096 + and not value:find("\000", 1, true) +end + +local function launch_argv(plan, mode, ...) + local argv = { plan.executable } + if plan.nvim then + for _, flag in ipairs({ "--headless", "-u", "NONE", "-i", "NONE", "-l" }) do + argv[#argv + 1] = flag + end + end + argv[#argv + 1] = plan.script + argv[#argv + 1] = mode + for i = 1, select("#", ...) do + argv[#argv + 1] = select(i, ...) + end + return argv +end + +local option_names = { + cwd = true, + environment = true, + width = true, + height = true, + lua = true, + startup_timeout = true, + timeout = true, + max_output_bytes = true, + require_tree = true, +} + +local function unavailable_tree(operation) + return failure("unsupported", "the program host does not provide tree cleanup", operation, { + cleanup_scope = "direct", + required = "tree", + }) +end + +local function resolve_supervisor(runtime, path, limit) + local uv = runtime._driver.uv + return runtime:_request({ + bytes = #path, + deadline = limit, + operation = "program.supervisor", + effect = "not_sent", + start = function(settle, retire) + local function done(err, script) + if script then + settle(script) + else + settle( + nil, + failure( + "invalid_options", + "program supervisor could not be found in the installation", + "start", + { cause = err } + ) + ) + end + retire() + end + local work, err = uv.fs_realpath(path, done) + if not work then + done(err) + return + end + return function() + uv.cancel(work) + end + end, + }) +end + +local function prepare(state, argv, options, operation) + local function invalid(message) + error(failure("invalid_options", message, "start"), 0) + end + options = default(options, {}) + if not plain(options) then + invalid("program options must be a plain table") + end + for name in next, options do + if not option_names[name] then + invalid("unknown program option") + end + end + if options.require_tree ~= nil and type(options.require_tree) ~= "boolean" then + invalid("require_tree must be boolean") + end + local arguments, err = process.prepare(argv) + if not arguments then + error(err, 0) + end + local driver = state.runtime._driver + local uv = driver.uv + if + not uv + or type(uv.random) ~= "function" + or type(uv.new_pipe) ~= "function" + or type(uv.fs_realpath) ~= "function" + then + error( + failure("unsupported", "runtime does not expose the program host operations", "start"), + 0 + ) + end + local executable = default(options.lua, uv.exepath()) + if not absolute(executable) then + invalid("lua must name an absolute executable") + end + if supervisor:sub(1, 1) ~= "/" then + invalid("program supervisor could not be found in the installation") + end + local startup = + default(options.startup_timeout, operation == "start" and options.timeout or 1000) + local timeout = options.timeout + local limit = default(options.max_output_bytes, 1048576) + local width, height = default(options.width, 80), default(options.height, 24) + local _, startup_error = state.runtime:_deadline(startup) + local _, timeout_error = state.runtime:_deadline(timeout) + if startup_error or timeout_error then + invalid(startup_error or timeout_error) + end + if type(limit) ~= "number" or limit % 1 ~= 0 or limit < 1 or limit > MAX_OUTPUT then + invalid("max_output_bytes must be an integer from 1 through 16777216") + end + if + not finite(width) + or not finite(height) + or width < 1 + or height < 1 + or width * height > MAX_SCREEN_CELLS + then + invalid("program dimensions cannot exceed 1048576 cells") + end + local environment = default(options.environment, {}) + if not plain(environment) or environment[TOKEN] ~= nil or environment[CPATH] ~= nil then + invalid("program environment uses a reserved name or is not a plain table") + end + local embedded = rawget(_G, "vim") ~= nil + if options.require_tree and options.lua == nil and not rawget(_G, "jit") then + error(unavailable_tree(operation), 0) + end + local plan = { + executable = executable, + script = supervisor, + nvim = embedded and options.lua == nil, + explicit_lua = options.lua ~= nil, + cpath = not embedded and options.lua == nil and driver.module_cpath or nil, + startup = startup, + timeout = timeout, + limit = limit, + require_tree = options.require_tree == true, + launch = { + cwd = options.cwd, + width = width, + height = height, + }, + argv = arguments.argv, + } + local proxy = launch_argv(plan, "status", "/" .. ("x"):rep(106), ("x"):rep(32)) + for _, value in ipairs(plan.argv) do + proxy[#proxy + 1] = value + end + local validation = copy(plan.launch) + validation.argv = proxy + validation.environment = copy(environment) + validation.environment[TOKEN] = ("x"):rep(32) + validation.environment[CPATH] = plan.cpath + -- Keep the original environment and argv admission limits. + local prepared = domain.prepare(state.runtime, "session", nil, validation, format) + local entries = {} + for name, value in pairs(environment) do + entries[#entries + 1] = name .. "=" .. value .. "\000" + end + plan.environment = table.concat(entries) + plan.bytes = prepared.bytes + return plan +end + +-- pipe-pane expands tmux formats and strftime before its shell sees the command. +local function shell_word(value) + value = value:gsub("#", "##"):gsub("%%", "%%%%") + return "'" .. value:gsub("'", "'\\''") .. "'" +end + +local function output_command(owner) + local channel_state, plan = owner.channel, owner.plan + local argv = launch_argv(plan, "output", channel_state.output_path, channel_state.output_token) + local words = {} + if plan.cpath then + words[#words + 1] = CPATH .. "=" .. shell_word(plan.cpath) + end + words[#words + 1] = "exec" + for _, value in ipairs(argv) do + words[#words + 1] = shell_word(value) + end + return table.concat(words, " ") +end + +local function guarded(owner, commands, limit, operation, maximum) + local source_text, err = command.prepare_program({ commands = commands }, true) + if not source_text then + return nil, err + end + local condition = "#{&&:#{==:#{pane_pid}," + .. owner.pid + .. "},#{m:*" + .. owner.channel.fence_token + .. "*,#{pane_start_command}}}" + local missing = "libtmux-program-missing-" .. owner.channel.token + local result + result, err = owner.server.bound + :group({ + { + "if-shell", + "-F", + "-t", + owner.pane_id, + condition, + source_text, + "display-message -p " .. missing, + }, + }, { deadline = limit, max_output_bytes = maximum }) + :await() + if not result then + return nil, err + end + if result.stdout == missing .. "\n" or result.stderr:find("can't find pane", 1, true) then + return nil, failure("program_replaced", "the program's pane changed or closed", operation) + elseif result.exit_code ~= 0 then + return nil, + failure("exit_failed", "tmux could not " .. operation, operation, { + effect = "unknown", + partial = result, + }) + end + return result +end + +local function screen(owner, limit) + local pane_id = owner.pane_id + local result, err = guarded(owner, { + { "display-message", "-pt", pane_id, "#{pane_height}:#{pane_width}" }, + { "capture-pane", "-pt", pane_id }, + }, limit, "capture", owner.plan.limit + CAPTURE_READ_SIZE) + local truncated = false + if not result and err and err.code == "output_limit" then + result, truncated = err.partial, true + end + if not result or type(result.stdout) ~= "string" then + return nil, err + end + local rows, columns, content = result.stdout:match("^(%d+):(%d+)\n(.*)$") + if not content then + return nil, failure("invalid_result", "tmux returned no screen dimensions", "capture") + end + local bytes = content:sub(1, owner.plan.limit) + return { + bytes = bytes, + rows = tonumber(rows), + columns = tonumber(columns), + source = "tmux_capture_pane", + truncated = truncated or #bytes < #content, + } +end + +local function pause(runtime, milliseconds) + return runtime:_logical_request({ + start = function(settle, retire) + local cancel = runtime._driver.timer(milliseconds, function() + settle(true) + retire() + end) + return function() + cancel() + retire() + end + end, + }) +end + +local function pane_closed(owner, limit) + local state = owner.server + local runtime = state.runtime + while runtime._driver.now() < limit do + local probe, err = state.bound + :execute({ "display-message", "-pt", owner.pane_id, "#{pane_id} #{pane_pid}" }, { + deadline = limit, + max_output_bytes = 128, + }) + :await() + if not probe then + return nil, err + end + if probe.stdout == " \n" then + return true + end + local pane_id, pid = probe.stdout:match("^(%%%d+) (%d*)\n$") + if pane_id ~= owner.pane_id or (pid ~= "" and pid ~= owner.pid) then + return nil, failure("program_replaced", "the program's pane identity changed", "close") + end + local waited + waited, err = pause(runtime, 15):await() + if not waited then + return nil, err + end + end + return nil, failure("cleanup_failed", "tmux did not remove the program pane", "close") +end + +local function final_result(owner) + local state, peer = owner.server, owner.channel + local runtime = state.runtime + local raw_deadline = runtime._driver.now() + CLEANUP_MS + if not peer.fenced and not peer.output_ended then + peer:wait_until(function() + return peer.fenced or peer.output_ended + end, raw_deadline):await() + end + if not peer.fenced then + peer:_end_output("the output deadline passed or the peer closed") + end + local result = peer.result and copy(peer.result) + or { kind = "unknown", error = peer.start_error } + result.output = peer:output_result() + result.cleanup = { scope = peer.scope } + result.cleanup_error = peer.cleanup_error or (not peer.result and peer.start_error) or nil + peer.terminal_error_observed = not peer.result + + local native_deadline = runtime._driver.now() + CLEANUP_MS + if peer.result then + result.screen, result.screen_error = screen(owner, native_deadline) + if result.screen then + result.screen.final = peer.fenced + end + -- The receipt carries cleanup status. Channel closure also releases a + -- supervisor waiting for acknowledgment. + peer:send("A") + end + local removed, removal_error = pane_closed(owner, runtime._driver.now() + CLEANUP_MS) + result.cleanup.pane_closed = removed == true + result.cleanup_error = result.cleanup_error or removal_error + local _, close_error = peer.lease:close():await() + result.cleanup_error = result.cleanup_error or close_error + owner.result = result + peer.updated = nil + state.programs[owner] = nil + peer:_notify() +end + +local function schedule_finish(owner) + local peer, runtime = owner.channel, owner.server.runtime + if + owner.published + and not owner.finishing + and (peer.result or peer.status_ended) + and not runtime._closing + then + owner.finishing = runtime:_root_operation(function() + final_result(owner) + return true + end, { operation = "program.finish" }) + owner.finishing:_on_retire(function() + local _, err = owner.finishing:result() + if err and not owner.result then + local result = peer.result and copy(peer.result) + or { kind = "unknown", error = peer.start_error } + if not peer.fenced then + peer:_end_output(err) + end + result.output, result.screen_error, result.cleanup_error = + peer:output_result(), err, err + result.cleanup = { scope = peer.scope, pane_closed = false } + owner.result = result + owner.server.programs[owner] = nil + peer.lease:close() + peer:_notify() + end + end) + end +end + +local function wait_result(owner, limit, launch) + if launch and launch.cancelled then + return nil, launch.cancelled + end + if limit and owner.server.runtime._driver.now() >= limit then + return nil, failure("deadline_exceeded", "request deadline expired", "wait") + end + if not owner.result then + local ok, err = owner.channel + :wait_until(function() + return owner.result ~= nil or (launch and launch.cancelled) + end, limit) + :await() + if not ok then + return nil, (launch and launch.cancelled) or err + end + end + if launch and launch.cancelled then + return nil, launch.cancelled + end + return copy_result(owner.result) +end + +local function start(state, operation, plan, store, limit) + local runtime = state.runtime + local environment = plan.environment + plan.environment = nil + if runtime._driver.now() >= limit then + return nil, failure("deadline_exceeded", "request deadline expired", "start") + end + local script, path_error = resolve_supervisor(runtime, plan.script, limit):await() + if not script then + return nil, path_error + end + plan.script = script + if plan.launch.cwd then + local valid, cause = domain.directory(state, plan.launch.cwd, "program.cwd", limit):await() + if not valid then + return nil, cause + end + end + if plan.explicit_lua then + local capable, cause = process + .execute(runtime, { + plan.executable, + "-e", + 'assert(require("luv"))', + }, { deadline = limit, max_output_bytes = 4096 }) + :await() + if not capable and cause and cause.code == "deadline_exceeded" then + return nil, cause + elseif not capable then + return nil, + failure("unsupported", "the selected Lua interpreter could not load luv", "start", { + cause = cause, + }) + end + end + if store.cancelled then + return nil, store.cancelled + end + if runtime._driver.now() >= limit then + return nil, failure("deadline_exceeded", "request deadline expired", "start") + end + local peer, err = channel.open(runtime, plan.limit) + if not peer then + return nil, err + end + local owner = { + channel = peer, + server = state, + plan = plan, + } + store.owner = owner + state.programs = state.programs or {} + state.programs[owner] = true + local options = plan.launch + options.name = "libtmux-program-" .. peer.token + owner.session_name = options.name + options.argv = launch_argv(plan, "status", peer.status_path, peer.fence_token) + for _, value in ipairs(plan.argv) do + options.argv[#options.argv + 1] = value + end + options.environment = { [TOKEN] = peer.token, [CPATH] = plan.cpath } + options.process = { deadline = limit } + local prepared = domain.prepare(runtime, "session", nil, options, format) + operation:_set_effect("unknown") + local launch + launch, err = state.bound:execute(prepared.argv, prepared.options):await() + if not launch then + return nil, err + end + local rows = codec.decode(launch.stdout, 4, { max_rows = 1, max_bytes = 4096 }) + local ids = rows and rows[1] + if + not ids + or not ids[1]:match("^%$%d+$") + or not ids[2]:match("^@%d+$") + or not ids[3]:match("^%%%d+$") + or not ids[4]:match("^[1-9]%d*$") + then + return nil, + failure("invalid_result", "tmux did not return the new program identity", "start", { + effect = "unknown", + }) + end + owner.session_id, owner.window_id, owner.pane_id, owner.pid = ids[1], ids[2], ids[3], ids[4] + local prepared_program + prepared_program, err = guarded(owner, { + { "set-option", "-p", "-t", owner.pane_id, "remain-on-exit", "off" }, + { "pipe-pane", "-O", "-t", owner.pane_id, output_command(owner) }, + { "set-environment", "-u", "-t", owner.session_id, TOKEN }, + { "set-environment", "-u", "-t", owner.session_id, CPATH }, + }, limit, "prepare") + if not prepared_program then + return nil, err + end + local ready + ready, err = peer:wait_until(function() + return state.closed + or store.cancelled + or (peer.pid and peer.output_ready) + or peer.status_ended + or peer.output_ended + end, limit):await() + if store.cancelled then + return nil, store.cancelled + end + if runtime._driver.now() >= limit then + return nil, + failure("deadline_exceeded", "request deadline expired", "start", { + effect = "unknown", + }) + end + if + not ready + or state.closed + or peer.pid ~= owner.pid + or not peer.output_ready + or peer.status_ended + then + return nil, + peer.start_error or failure( + "program_start_failed", + "program launch identity or output stream was unavailable", + "start", + { + cause = err or peer.output_cause, + effect = "unknown", + } + ) + end + if plan.require_tree and peer.scope ~= "tree" then + return nil, unavailable_tree("start") + end + peer.granted = true + local sent + sent, err = peer:send(("S%07d"):format(#environment) .. environment) + if not sent then + return nil, err + end + ready, err = peer:wait_until(function() + return peer.started or peer.status_ended + end, limit):await() + if not ready or not peer.started then + return nil, peer.start_error or err + end + if state.closed or runtime._driver.now() >= limit then + local code = state.closed and "closed" or "deadline_exceeded" + local message = state.closed and "server handle is closed" or "request deadline expired" + return nil, failure(code, message, "start", { effect = "unknown" }) + end + local object = setmetatable({}, { + __metatable = "libtmux.Program", + __index = function(_, key) + return owner.methods[key] + end, + }) + owner.methods = Program + programs[object] = owner + owner.object = object + owner.published = true + peer.updated = function() + schedule_finish(owner) + end + schedule_finish(owner) + operation:_set_effect("completed") + return object +end + +local function plan_for(state, argv, options, operation) + if state.closed then + return nil, failure("closed", "server handle is closed", "start") + end + local required = capabilities.since("owned-program") + if not fields.at_least(state.version, required) then + return nil, + failure("unsupported", "owned programs require tmux " .. required, "start", { + required = required, + version = state.version, + }) + end + local valid, plan = pcall(prepare, state, argv, options, operation) + if not valid then + return nil, errors.wrap(plan, "invalid_options") + end + return plan +end + +local function retain_request(request, bytes) + if not request:is_settled() then + local retained, err = request:_retain(bytes) + if not retained then + request:cancel(err) + end + end +end + +local function ask_stop(owner) + if owner.result or owner.channel.result or owner.stop_requested then + return true + end + owner.stop_requested = true + return owner.channel:send("X") +end + +local function recoverable(err, owner) + if err.cleanup_error then + err.program = owner.object + err.program_name = owner.session_name + end + return err +end + +local function failed_start(owner, err) + local runtime = owner.server.runtime + local _, transport_error = owner.channel.lease:close():await() + local removal_error + if owner.pane_id then + local _ + _, removal_error = pane_closed(owner, runtime._driver.now() + CLEANUP_MS) + elseif owner.session_name and err.effect ~= "not_sent" then + removal_error = + failure("cleanup_failed", "tmux returned no program pane to verify", "close") + end + owner.server.programs[owner] = nil + err.cleanup_error = transport_error or removal_error + return recoverable(err, owner) +end + +local function stop_and_collect(owner, reason) + ask_stop(owner) + local result, err = wait_result(owner, owner.server.runtime._driver.now() + STOP_MS) + reason.partial = { result = result } + reason.cleanup_error = err or (result and result.cleanup_error) + return recoverable(reason, owner) +end + +local function retain_result(request, result, operation) + local bytes = (result.output and #result.output.bytes or 0) + + (result.screen and #result.screen.bytes or 0) + local kept, err = request:_retain(bytes) + if not kept then + return nil, + failure("queue_full", "runtime cannot retain the program result", operation, { + cause = err, + effect = "completed", + }) + end + return result +end + +local function submit(state, argv, options, kind) + local plan, err = plan_for(state, argv, options, kind) + if not plan then + return reject(state, err, kind) + end + local runtime = state.runtime + local now = runtime._driver.now() + local limit = kind == "run" and plan.timeout and now + plan.timeout or nil + local startup_limit = math.min(limit or math.huge, now + plan.startup) + local operation = "program." .. kind + return runtime:_logical_request({ + bytes = plan.bytes, + operation = operation, + effect = "not_sent", + start = function(settle, retire, request) + local launch = {} + local worker = runtime:_root_operation(function() + if launch.cancelled then + return nil, launch.cancelled + elseif state.closed then + return nil, failure("closed", "server handle is closed", kind) + end + local object, cause = start(state, request, plan, launch, startup_limit) + local owner = launch.owner + if not object then + cause = launch.cancelled + or cause + or failure("program_start_failed", "startup ended without a receipt", kind) + if owner then + cause = failed_start(owner, cause) + end + return nil, cause + end + if kind == "start" and not launch.cancelled then + return object + end + request:_set_effect("unknown") + local value, wait_error = wait_result(owner, limit, launch) + if not value then + return nil, stop_and_collect(owner, wait_error) + end + request:_set_effect("completed") + return retain_result(request, value, kind) + end, { operation = operation }) + worker:_on_retire(function() + local value, cause = worker:result() + local owner = launch.owner + local function finish() + settle(value, cause) + retire() + end + if not value and owner and state.programs[owner] then + local close = owner.channel.lease:close() + close:_on_retire(function() + local _, cleanup_error = close:result() + state.programs[owner] = nil + local primary = launch.cancelled or cause + if primary then + primary.cleanup_error = primary.cleanup_error or cleanup_error + if not primary.cleanup_error and primary.effect ~= "not_sent" then + primary.cleanup_error = failure( + "cleanup_failed", + "program pane removal was not confirmed", + "close" + ) + end + recoverable(primary, owner) + end + finish() + end) + else + finish() + end + end) + return function(reason) + launch.cancelled = reason + local owner = launch.owner + if owner then + if owner.channel.granted then + ask_stop(owner) + end + owner.channel:_notify() + end + end + end, + }) +end + +function M.start(state, argv, options) + return submit(state, argv, options, "start") +end + +function M.run(state, argv, options) + return submit(state, argv, options, "run") +end + +function Program:wait(options) + local owner = assert(programs[self], "invalid program") + local limit, err = deadline(owner, options, "wait") + if err then + return reject(owner.server, err, "wait") + end + return owner.server.runtime:_operation(function(_, operation) + local result, cause = wait_result(owner, limit) + if not result then + return nil, cause + end + return retain_result(operation, result, "wait") + end, { operation = "program.wait", effect = "not_sent" }) +end + +function Program:stop(options) + local owner = assert(programs[self], "invalid program") + local limit, err = deadline(owner, options, "stop", STOP_MS) + if err then + return reject(owner.server, err, "stop") + end + return owner.server.runtime:_operation(function(_, operation) + if limit and owner.server.runtime._driver.now() >= limit then + return nil, failure("deadline_exceeded", "request deadline expired", "stop") + end + local sent, cause = ask_stop(owner) + if not sent and not owner.channel.status_ended then + return nil, cause + end + operation:_set_effect("unknown") + local result, wait_error = wait_result(owner, limit) + if not result then + return nil, wait_error + end + operation:_set_effect("completed") + return retain_result(operation, result, "stop") + end, { operation = "program.stop", effect = "not_sent" }) +end + +local function send(owner, kind, data, options) + local state = owner.server + local limit, err = deadline(owner, options, kind, CLEANUP_MS) + if err then + return reject(state, err, kind) + end + local valid, prepared = pcall(pane.prepare, state, { id = owner.pane_id }, kind, data, {}) + if not valid then + return reject(state, errors.wrap(prepared, "invalid_input"), kind) + end + local request = state.runtime:_operation(function(_, operation) + if limit and state.runtime._driver.now() >= limit then + return nil, failure("deadline_exceeded", "request deadline expired", kind) + end + if owner.channel.result or owner.channel.status_ended or owner.stop_requested then + return nil, failure("program_closed", "the program has ended or is stopping", kind) + end + operation:_set_effect("unknown") + local result, cause = guarded(owner, { prepared.argv }, limit, kind) + if not result then + return nil, cause + end + operation:_set_effect("completed") + return true + end, { operation = "program." .. kind, effect = "not_sent" }) + retain_request(request, prepared.bytes) + return request +end + +function Program:send_text(text, options) + return send(assert(programs[self], "invalid program"), "send_text", text, options) +end + +function Program:send_keys(keys, options) + return send(assert(programs[self], "invalid program"), "send_keys", keys, options) +end + +function Program:screen(options) + local owner = assert(programs[self], "invalid program") + local limit, err = deadline(owner, options, "screen", CLEANUP_MS) + if err then + return reject(owner.server, err, "screen") + end + return owner.server.runtime:_operation(function(_, operation) + if limit and owner.server.runtime._driver.now() >= limit then + return nil, failure("deadline_exceeded", "request deadline expired", "screen") + end + local value, cause + if owner.result then + if owner.result.screen then + value = copy(owner.result.screen) + else + cause = owner.result.screen_error + or failure("program_closed", "no final screen is available", "screen") + end + else + value, cause = screen(owner, limit) + end + if not value then + return nil, cause + end + local kept + kept, cause = operation:_retain(#value.bytes) + if not kept then + return nil, cause + end + return value + end, { operation = "program.screen", effect = "not_sent" }) +end + +function Program:reference() + local owner = assert(programs[self], "invalid program") + return { + pane_id = owner.pane_id, + window_id = owner.window_id, + session_id = owner.session_id, + cleanup_scope = owner.channel.scope, + } +end + +function M.close_server(state) + if state.program_close then + return state.program_close + end + if not state.programs or not next(state.programs) then + return state.bound:close() + end + state.program_close = state.runtime:_operation(function() + local limit = state.runtime._driver.now() + STOP_MS + local owners = {} + for owner in pairs(state.programs) do + owners[#owners + 1] = owner + if owner.published then + ask_stop(owner) + else + owner.channel:_notify() + end + end + local cleanup_error + for _, owner in ipairs(owners) do + if owner.published then + local result, err = wait_result(owner, limit) + cleanup_error = cleanup_error or err or (result and result.cleanup_error) + end + if state.programs[owner] then + local _, err = owner.channel.lease:close():await() + cleanup_error = cleanup_error or err + state.programs[owner] = nil + end + end + local closed, err = state.bound:close():await() + if cleanup_error then + return nil, cleanup_error + end + return closed, err + end, { operation = "close" }) + return state.program_close +end + +---@class libtmux.ProgramOptions +---@field cwd? string Absolute working directory. +---@field environment? table Initial program environment overlay. +---@field width? integer Terminal width, default 80. +---@field height? integer Terminal height, default 24. +---@field lua? string Absolute alternate standalone Lua executable with luv. +---@field startup_timeout? number Time to acknowledge launch, in milliseconds. +---@field timeout? number Startup limit for start_program, or whole-run limit for run_program. +---@field max_output_bytes? integer Per-representation cap for PTY and screen bytes. +---@field require_tree? boolean Refuse before running argv unless tree cleanup has been verified. + +---@class libtmux.ProgramTiming +---@field timeout? number Milliseconds from submission. +---@field deadline? number Absolute monotonic milliseconds. The earlier bound applies. + +---@class libtmux.ProgramOutput +---@field source "tmux_pipe_pane" +---@field bytes string Merged terminal byte prefix, including terminal echo. +---@field complete boolean The supervisor fence arrived and all preceding bytes fit. +---@field truncated boolean Some bytes read from the pipe did not fit. +---@field dropped_bytes integer Number of bytes the pipe delivered beyond the retained prefix. +---@field error? libtmux.Error The stream ended without the supervisor fence. + +---@class libtmux.ProgramScreen +---@field source "tmux_capture_pane" +---@field bytes string Rendered visible rows. +---@field rows integer +---@field columns integer +---@field truncated boolean Some captured bytes did not fit. +---@field final? boolean Capture followed the supervisor output fence. + +---@class libtmux.ProgramCleanup +---@field scope "direct"|"tree" +---@field pane_closed boolean + +---@class libtmux.ProgramResult +---@field kind "exit"|"signal"|"unknown" +---@field exit_code? integer +---@field signal? integer +---@field output? libtmux.ProgramOutput +---@field screen? libtmux.ProgramScreen +---@field cleanup? libtmux.ProgramCleanup +---@field error? libtmux.Error Cause of an unknown outcome. +---@field screen_error? libtmux.Error +---@field cleanup_error? libtmux.Error + +---@class libtmux.ProgramReference +---@field session_id string +---@field window_id string +---@field pane_id string +---@field cleanup_scope "direct"|"tree" + +---@class libtmux.Program +---@field wait fun(self:libtmux.Program, +--- options?:libtmux.ProgramTiming):libtmux.Request +---@field stop fun(self:libtmux.Program, +--- options?:libtmux.ProgramTiming):libtmux.Request +---@field send_text fun(self:libtmux.Program,text:string, +--- options?:libtmux.ProgramTiming):libtmux.Request +---@field send_keys fun(self:libtmux.Program,keys:string[], +--- options?:libtmux.ProgramTiming):libtmux.Request +---@field screen fun(self:libtmux.Program, +--- options?:libtmux.ProgramTiming):libtmux.Request +---@field reference fun(self:libtmux.Program):libtmux.ProgramReference + +return M diff --git a/lua/libtmux/_internal/program_channel.lua b/lua/libtmux/_internal/program_channel.lua new file mode 100644 index 00000000..ccfab1a8 --- /dev/null +++ b/lua/libtmux/_internal/program_channel.lua @@ -0,0 +1,382 @@ +local errors = require("libtmux._internal.error") +local M, Channel = {}, {} +Channel.__index = Channel + +local FRAME_LIMIT = 128 + +local function failure(code, message, cause) + return errors.new(code, message, { operation = "program.channel", cause = cause }) +end + +local function hex(bytes) + return (bytes:gsub(".", function(byte) + return ("%02x"):format(byte:byte()) + end)) +end + +function Channel:_notify() + for wake in pairs(self.waiters) do + wake() + end + if self.updated then + self.updated() + end + if self.close_done and (self.result or self.status_ended) then + if + self.granted + and not self.result + and not self.spawn_failed + and not self.terminal_error_observed + then + self.close_error = self.start_error + end + self:_shutdown() + end +end + +function Channel:wait_until(predicate, deadline) + return self.runtime:_logical_request({ + deadline = deadline, + operation = "program.channel", + start = function(settle, retire) + local function wake() + if deadline and self.runtime._driver.now() >= deadline then + self.waiters[wake] = nil + settle(nil, failure("deadline_exceeded", "request deadline expired")) + retire() + elseif predicate() then + self.waiters[wake] = nil + settle(true) + retire() + end + end + self.waiters[wake] = true + wake() + return function() + self.waiters[wake] = nil + retire() + end + end, + }) +end + +function Channel:_close_handle(handle) + if handle and not handle:is_closing() then + self.closing_handles = self.closing_handles + 1 + handle:close(function() + self.closing_handles = self.closing_handles - 1 + self:_retire() + end) + end +end + +function Channel:_remove_directory() + if not self.directory then + return + end + local removed, err = self.uv.fs_rmdir(self.directory) + if removed then + self.directory = nil + end + return err +end + +function Channel:_retire() + if not self.shutdown or self.closing_handles ~= 0 or not self.close_done then + return + end + local done = self.close_done + self.close_done = nil + self.budget:release(self.charged) + self.charged, self.chunks = 0, {} + done(self:_remove_directory() or self.close_error) +end + +function Channel:_shutdown() + if self.shutdown then + return + end + self.shutdown = true + if self.cancel_close then + self.cancel_close() + self.cancel_close = nil + end + self:_close_handle(self.status_listener) + self:_close_handle(self.output_listener) + self:_close_handle(self.status) + self:_close_handle(self.output) + self:_retire() +end + +function Channel:_end_status(cause) + if self.status_ended then + return + end + self.status_ended = true + self:_close_handle(self.status) + if not self.result and not self.start_error then + self.start_error = failure("program_unknown", "program supervisor connection ended", cause) + end + self:_notify() +end + +function Channel:send(message) + if not self.status or self.status_ended or self.status:is_closing() then + return nil, self.start_error or failure("program_unknown", "program supervisor is gone") + end + local written, err = self.status:write(message, function(cause) + if cause then + self:_end_status(cause) + end + end) + if not written then + self:_end_status(err) + return nil, self.start_error + end + return true +end + +function Channel:_status_line(line) + if not self.pid then + local token, pid, scope = line:match("^hello (%x+) (%d+) (%a+)$") + if token ~= self.token or (scope ~= "tree" and scope ~= "direct") then + self:_end_status("program supervisor identity differs") + return + end + self.pid, self.scope = pid, scope + elseif not self.started and self.granted then + if line == "started" then + self.started = true + else + local errno = line:match("^spawn_failed ([A-Z0-9_]+)$") + if errno then + self.spawn_failed = true + self.start_error = failure("spawn_failed", errno) + end + self:_end_status("program did not acknowledge startup") + end + elseif not self.result and self.started then + local errno = line:match("^cleanup_failed ([A-Z0-9_]+)$") + if errno then + self.cleanup_error = + failure("cleanup_failed", "program supervisor cleanup failed", errno) + else + local kind, number = line:match("^(%a+) (%d+)$") + number = tonumber(number) + if kind == "exit" and number <= 255 then + self.result = { kind = "exit", exit_code = number } + elseif kind == "signal" and number > 0 and number <= 127 then + self.result = { kind = "signal", signal = number } + else + self:_end_status("program supervisor sent an invalid status") + end + end + else + self:_end_status("program supervisor sent an unexpected status") + end + self:_notify() +end + +function Channel:_retain(data) + self.output_total = self.output_total + #data + if self.output_lost or #data == 0 then + return + end + local size = math.min(#data, self.limit - self.output_bytes) + if size > 0 then + local charge = size + 32 + if self.budget:retain(charge) then + self.charged = self.charged + charge + self.output_bytes = self.output_bytes + size + self.chunks[#self.chunks + 1] = data:sub(1, size) + else + self.output_lost = true + end + end + if size < #data then + self.output_lost = true + end +end + +function Channel:_raw(data) + if self.fenced or self.output_ended then + return + end + local bytes = self.tail .. data + local start = bytes:find(self.fence, 1, true) + if start then + self:_retain(bytes:sub(1, start - 1)) + self.fenced, self.tail = true, "" + self:_notify() + return + end + local through = #bytes - #self.fence + 1 + if through > 0 then + self:_retain(bytes:sub(1, through)) + self.tail = bytes:sub(through + 1) + else + self.tail = bytes + end +end + +function Channel:_end_output(cause) + if not self.output_ended then + self:_retain(self.tail) + self.tail, self.output_ended, self.output_cause = "", true, cause + self:_close_handle(self.output) + self:_notify() + end +end + +function Channel:output_result() + local dropped = self.output_total - self.output_bytes + return { + bytes = table.concat(self.chunks), + source = "tmux_pipe_pane", + complete = self.fenced == true and dropped == 0, + truncated = dropped > 0, + dropped_bytes = dropped, + error = not self.fenced and failure( + "output_gap", + "terminal stream ended without the program fence", + self.output_cause + ) or nil, + } +end + +function Channel:_listen(name, path) + local listener = assert(self.uv.new_pipe(false)) + self[name .. "_listener"] = listener + assert(listener:bind(path)) + local end_peer = name == "status" and self._end_status or self._end_output + assert(listener:listen(1, function(accept_error) + if accept_error or self.shutdown then + return end_peer(self, accept_error) + end + local peer, cause = self.uv.new_pipe(false) + if not peer then + return end_peer(self, cause) + end + self[name] = peer + local accepted, accept_cause = listener:accept(peer) + self:_close_handle(listener) + if not accepted then + return end_peer(self, accept_cause) + end + self.accepted_listeners = self.accepted_listeners + 1 + if self.accepted_listeners == 2 then + -- Listener close unlinks its socket name synchronously. + -- Retirement retries if the directory cannot be removed here. + self:_remove_directory() + end + local partial = "" + local reading, read_cause = peer:read_start(function(err, data) + if err or not data then + return end_peer(self, err) + end + if name == "output" and self.output_ready then + return self:_raw(data) + end + local bytes = partial .. data + while true do + local newline = bytes:find("\n", 1, true) + if (newline or #bytes) > FRAME_LIMIT then + return end_peer(self, "program frame exceeds its byte limit") + elseif not newline then + partial = bytes + return + end + local line = bytes:sub(1, newline - 1) + bytes = bytes:sub(newline + 1) + if name == "output" then + if line ~= "output " .. self.output_token then + return end_peer(self, "program output identity differs") + end + self.output_ready = true + self:_notify() + return self:_raw(bytes) + end + self:_status_line(line) + if self.status_ended then + return + end + end + end) + if not reading then + end_peer(self, read_cause) + end + end)) +end + +function M.open(runtime, limit) + local uv = runtime._driver.uv + local random, random_error = uv.random(48) + if not random then + return nil, + failure("host_error", "cannot generate program channel identities", random_error) + end + local directory, directory_error = uv.fs_mkdtemp("/tmp/libtmux-lua-program-XXXXXX") + if not directory then + return nil, + failure("host_error", "cannot create a private program directory", directory_error) + end + local fence_token = hex(random:sub(33)) + local channel = setmetatable({ + runtime = runtime, + uv = uv, + directory = directory, + token = hex(random:sub(1, 16)), + output_token = hex(random:sub(17, 32)), + fence_token = fence_token, + fence = "\027]697;libtmux-program=" .. fence_token .. "\007", + status_path = directory .. "/status", + output_path = directory .. "/output", + limit = limit, + chunks = {}, + output_total = 0, + output_bytes = 0, + charged = 0, + tail = "", + accepted_listeners = 0, + closing_handles = 0, + waiters = {}, + }, Channel) + local lease, err = runtime:_resource(function(done) + channel.close_done = done + if + channel.granted + and not channel.result + and not channel.spawn_failed + and not channel.terminal_error_observed + then + if channel.status_ended then + channel.close_error = channel.start_error + elseif channel:send("X") then + channel.cancel_close = runtime._driver.timer(1200, function() + channel.close_error = + failure("cleanup_failed", "program supervisor did not acknowledge stop") + channel:_shutdown() + end) + return + end + end + channel:_shutdown() + end) + if not lease then + uv.fs_rmdir(directory) + return nil, err + end + channel.lease = lease + channel.budget = assert(lease:_budget(limit + 1048576)) + local ok, cause = pcall(function() + channel:_listen("status", channel.status_path) + channel:_listen("output", channel.output_path) + end) + if not ok then + lease:close():await() + return nil, failure("host_error", "cannot listen on a private program socket", cause) + end + return channel +end + +return M diff --git a/lua/libtmux/_internal/program_supervisor.lua b/lua/libtmux/_internal/program_supervisor.lua new file mode 100644 index 00000000..d5206e8c --- /dev/null +++ b/lua/libtmux/_internal/program_supervisor.lua @@ -0,0 +1,467 @@ +-- This file runs in a dedicated tmux pane or as its pipe-pane reader. +local host = rawget(_G, "vim") +local cpath_env = "LIBTMUX_LUA_PROGRAM_CPATH" +local cpath = os.getenv(cpath_env) +if cpath and not host then + package.cpath = cpath .. ";" .. package.cpath +end +---@type any +---@diagnostic disable-next-line: different-requires +local uv = host and (host.uv or host.loop) or require("luv") +if cpath then + assert(uv.os_unsetenv(cpath_env)) +end +local identity_env = "LIBTMUX_LUA_PROGRAM_TOKEN" +local grant_header_bytes = 8 +local max_environment_bytes = 1024 * 1024 +local start_budget = 2000 +local grace = 100 +local reap_budget = 750 +local receipt_budget = 2000 + +local function close(handle) + if handle and not handle:is_closing() then + handle:close() + end +end + +local function token(value) + return type(value) == "string" and #value == 32 and value:match("^[0-9a-f]+$") +end + +local function ignore_script_host_interrupt() + if not host then + return + end + local ok, ffi = pcall(require, "ffi") + if ok then + ffi.cdef([[ + typedef void (*libtmux_signal_handler)(int); + libtmux_signal_handler signal(int, libtmux_signal_handler); + ]]) + -- Neovim's own SIGINT watcher can terminate a -l script. This is a + -- dedicated peer process. libuv resets signals in the spawned child. + assert(ffi.cast("intptr_t", ffi.C.signal(2, ffi.cast("libtmux_signal_handler", 1))) ~= -1) + end +end + +local function now() + return tonumber(uv.hrtime()) / 1e6 +end + +local function read_proc(path) + local fd = uv.fs_open(path, "r", 0) + if not fd then + return nil + end + local data = uv.fs_read(fd, 8192, 0) + uv.fs_close(fd) + return data +end + +local function child_identity(pid) + local stat = read_proc(("/proc/%d/stat"):format(pid)) + local tail = stat and stat:match("^%d+ .+%) (.+)$") + if tail then + local fields = {} + for field in tail:gmatch("%S+") do + fields[#fields + 1] = field + end + -- The tail starts with the state in field 3 of /proc//stat. + return tonumber(fields[2]), fields[20] + end +end + +-- Linux can give this dedicated process its orphaned descendants. A pidfd +-- holds the identity across the ownership recheck and subsequent signal. +local function linux_tree(pid) + local lua_jit = rawget(_G, "jit") + local arch = lua_jit and lua_jit.arch + if not (arch == "x64" or arch == "arm64") or uv.os_uname().sysname ~= "Linux" then + return nil + end + local ok, ffi = pcall(require, "ffi") + if not ok then + return nil + end + ffi.cdef([[ + long syscall(long number, ...); + int prctl(int option, ...); + int getpgrp(void); + int getsid(int pid); + int waitpid(int pid, int *status, int options); + int close(int fd); + ]]) + local libc, long = ffi.C, ffi.typeof("long") + local pidfd_open, pidfd_send_signal = 434, 424 + local set_child_subreaper, nohang, no_children = 36, 1, 10 + local children = ("/proc/self/task/%d/children"):format(pid) + if libc.getpgrp() ~= pid or libc.getsid(0) ~= pid or read_proc(children) == nil then + return nil + end + local function open_pidfd(id) + return libc.syscall(pidfd_open, long(id), long(0)) + end + local probe = open_pidfd(pid) + if probe < 0 then + return nil + end + libc.close(probe) + if libc.prctl(set_child_subreaper, long(1), long(0), long(0), long(0)) ~= 0 then + return nil + end + local function signal_children(signal) + for text in (read_proc(children) or ""):gmatch("%d+") do + local id = assert(tonumber(text)) + local owner, birth = child_identity(id) + if owner == pid and birth then + local fd = open_pidfd(id) + if fd >= 0 then + local current_owner, current_birth = child_identity(id) + if current_owner == pid and current_birth == birth then + libc.syscall(pidfd_send_signal, long(fd), long(signal), long(0), long(0)) + end + libc.close(fd) + end + end + end + end + return function(signal) + local result = 0 + for _ = 1, 64 do + result = libc.waitpid(-1, nil, nohang) + if result <= 0 then + break + end + end + if result == -1 and ffi.errno() == no_children then + return true + end + if signal and result >= 0 then + signal_children(signal) + end + return false + end +end + +local function relay(socket, output_token, finish) + local input, peer = assert(uv.new_pipe(false)), assert(uv.new_pipe(false)) + local function done() + close(input) + close(peer) + finish() + end + local function read() + if + not input:read_start(function(err, bytes) + input:read_stop() + if err or not bytes then + done() + return + end + -- Stop reading while one chunk is outstanding. + if + not peer:write(bytes, function(write_error) + if write_error then + done() + elseif not input:is_closing() then + read() + end + end) + then + done() + end + end) + then + done() + end + end + assert(input:open(0)) + assert(peer:connect(socket, function(err) + if err or not peer:read_start(done) then + done() + elseif + not peer:write("output " .. output_token .. "\n", function(write_error) + if write_error then + done() + elseif not input:is_closing() then + read() + end + end) + then + done() + end + end)) +end + +local function spawn_environment(payload) + if payload == "" then + return true + end + local overlay = uv.os_environ() + local cursor, count = 1, 0 + while cursor <= #payload do + local separator = payload:find("\000", cursor, true) + if not separator then + return false + end + local entry = payload:sub(cursor, separator - 1) + local name, value = entry:match("^([A-Za-z_][A-Za-z0-9_]*)=(.*)$") + count = count + 1 + if not name or #name > 256 or count > 128 or name == identity_env or name == cpath_env then + return false + end + overlay[name] = value + cursor = separator + 1 + end + local environment = {} + for name, value in pairs(overlay) do + environment[#environment + 1] = name .. "=" .. value + end + return true, environment +end + +local function supervise(socket, fence, executable, args, finish) + local identity = os.getenv(identity_env) + if not token(identity) then + finish() + return + end + assert(uv.os_unsetenv(identity_env)) + local pid = uv.os_getpid() + local reap = linux_tree(pid) + local peer = assert(uv.new_pipe(false)) + local clock = assert(uv.new_timer()) + local signals = {} + local child, terminal + local phase, lost, stopping = "permission", false, false + + local function done() + phase = "closed" + close(peer) + close(clock) + close(terminal) + for _, signal in ipairs(signals) do + close(signal) + end + finish() + end + + local function stop() + if phase == "permission" or phase == "receipt" then + done() + elseif child and not stopping then + stopping = true + child:kill("sigterm") + clock:start(grace, 0, function() + if child then + child:kill("sigkill") + end + end) + end + end + + local function disconnected() + lost = true + close(peer) + stop() + end + + local function send(frame, after) + if + not peer:write(frame, function(err) + if err then + disconnected() + elseif after and phase ~= "closed" then + after() + end + end) + then + disconnected() + end + end + + local function report(status, clean) + if lost then + done() + return + end + phase = "receipt" + clock:start(receipt_budget, 0, done) + if not clean then + send("cleanup_failed ETIMEDOUT\n" .. status, done) + return + end + send(status, function() + terminal = uv.new_tty(1, false) + if not terminal then + done() + return + end + local marker = "\027]697;libtmux-program=" .. fence .. "\007" + if + not terminal:write(marker, function(err) + if err then + done() + end + end) + then + done() + end + end) + end + + local function exited(code, signal) + close(child) + child = nil + clock:stop() + phase = "reaping" + local status = signal == 0 and ("exit %d\n"):format(code) or ("signal %d\n"):format(signal) + if not reap or reap(15) then + report(status, true) + return + end + local started = now() + clock:start(10, 10, function() + local elapsed = now() - started + if reap(elapsed >= grace and 9 or nil) then + report(status, true) + elseif elapsed >= reap_budget then + report(status, false) + end + end) + end + + local function start(payload) + local valid, environment = spawn_environment(payload) + if not valid then + return false + end + phase = "running" + clock:stop() + local _, cause + child, _, cause = uv.spawn(executable, { + args = args, + env = environment, + stdio = { 0, 1, 2 }, + }, exited) + if child then + send("started\n") + else + local name = type(cause) == "string" and cause:match("^[A-Z0-9_]+$") or "UNKNOWN" + phase = "receipt" + send("spawn_failed " .. name .. "\n", done) + end + return true + end + + -- The authenticated grant carries a fixed-size length and NUL-delimited entries. + local header, remaining, pieces = "", nil, {} + local function grant(bytes) + if not remaining then + local needed = grant_header_bytes - #header + header = header .. bytes:sub(1, needed) + if header:sub(1, 1) ~= "S" then + return nil + end + if #header < grant_header_bytes then + return "" + end + remaining = tonumber(header:match("^S(%d+)$")) + if not remaining or remaining > max_environment_bytes then + return nil + end + bytes = bytes:sub(needed + 1) + end + local size = math.min(#bytes, remaining) + if size > 0 then + pieces[#pieces + 1] = bytes:sub(1, size) + remaining = remaining - size + end + if remaining > 0 then + return "" + end + local payload = table.concat(pieces) + pieces = nil + if not start(payload) then + return nil + end + return bytes:sub(size + 1) + end + + local function command(err, bytes) + if err or not bytes then + disconnected() + return + end + if phase == "permission" then + if header == "" and bytes == "X" then + stop() + return + end + bytes = grant(bytes) + end + if not bytes or #bytes > 8 then + disconnected() + return + end + for byte in bytes:gmatch(".") do + if byte == "X" then + stop() + elseif byte == "A" and phase == "receipt" then + done() + else + disconnected() + end + if phase == "closed" or lost then + return + end + end + end + + for name, callback in pairs({ + sigint = function() end, + sigpipe = function() end, + sighup = stop, + sigterm = stop, + }) do + local signal = assert(uv.new_signal()) + signals[#signals + 1] = signal + assert(signal:start(name, callback)) + end + ignore_script_host_interrupt() + clock:start(start_budget, 0, done) + assert(peer:connect(socket, function(err) + if err or not peer:read_start(command) then + disconnected() + else + send(("hello %s %d %s\n"):format(identity, pid, reap and "tree" or "direct")) + end + end)) +end + +local mode, socket, id = arg[1], arg[2], arg[3] +assert(socket and token(id), "invalid program supervisor endpoint") +local finished = false +local function finish() + finished = true +end +if mode == "output" then + relay(socket, id, finish) +else + assert(mode == "status" and arg[4], "invalid program supervisor command") + local args = {} + for index = 5, #arg do + args[#args + 1] = arg[index] + end + supervise(socket, id, arg[4], args, finish) +end +if host then + while not finished do + host.wait(1000, function() + return finished + end, 10, true) + end +else + uv.run("default") +end diff --git a/lua/libtmux/_internal/server.lua b/lua/libtmux/_internal/server.lua index a39fd484..04dd0a60 100644 --- a/lua/libtmux/_internal/server.lua +++ b/lua/libtmux/_internal/server.lua @@ -14,6 +14,7 @@ local process = require("libtmux._internal.process") local domain = require("libtmux._internal.domain") local live_query = require("libtmux._internal.live_query") local observation = require("libtmux._internal.observation") +local program = require("libtmux._internal.program") local M, Server = {}, {} -- Live objects own state; the registry must not root returned-request cycles on Lua 5.1. local servers = setmetatable({}, { __mode = "kv" }) @@ -512,14 +513,23 @@ function Server:batch(commands, options) return execute(self, "batch", commands, options) end +function Server:start_program(argv, options) + return program.start(servers[self], argv, options) +end + +function Server:run_program(argv, options) + return program.run(servers[self], argv, options) +end + --- Close owned connections; the selected tmux daemon remains running. function Server:close() local state = servers[self] state.closed = true - return state.bound:close() + return program.close_server(state) end function M.connect(runtime, options) + program.bind(runtime) local copied, validation_error = connection_options(options) local context = { operation = "connect" } if copied and copied.binary == nil then @@ -1073,6 +1083,7 @@ local function scope_guard(state) end local function prepare_start(runtime, options, operation) + program.bind(runtime) local copied, err = start_options(options) if copied then if copied.binary == nil then @@ -1270,7 +1281,8 @@ end --- the runtime ran for you that finds a `leaked_server` or `stop_failed` fails --- the run with `cleanup_failed`. --- ---- `libtmux.Server:close` on `server` still only releases the handle. +--- `libtmux.Server:close` stops programs owned by `server` and releases +--- the handle. The private daemon keeps running until `stop`. ---@class libtmux.OwnedServer ---@field server libtmux.Server ---@field socket_path string The private socket. @@ -1417,6 +1429,15 @@ end --- --- `Server:new_session`, `Server:switch_client` and `Server:detach_client` --- +--- **Running terminal programs.** `Server:start_program` launches literal +--- argv in a dedicated pane and resolves to a `libtmux.Program` for input, +--- screen capture and waiting. `Server:run_program` owns the run and +--- resolves to a `libtmux.ProgramResult` with the termination outcome, +--- bounded output and pane cleanup status. +--- +--- `Server:start_program`, `Server:run_program`, `libtmux.Program:wait` and +--- `libtmux.Program:stop` +--- --- **Options and hooks.** `Server:get_option`, `Server:list_options`, --- `Server:set_option` and `Server:unset_option` address the server's own --- options; pass `scope = "global_session"` or `"global_window"` for tmux's @@ -1435,14 +1456,14 @@ end --- **Everything else tmux keeps.** Paste buffers, always by explicit name: --- `Server:set_buffer` stores bytes, `Server:show_buffer` reads them back and --- `Server:delete_buffer` removes the buffer. None infers the most recent ---- buffer. Key bindings, configuration files, shell jobs and wait-for channels ---- have no method here; reach them through `Server:command`. +--- buffer. Key bindings, configuration files, `run-shell` jobs and wait-for +--- channels use `Server:command`. --- --- `Server:set_buffer`, `Server:show_buffer`, `Server:delete_buffer` and --- `Server:command` --- ---- **Things that need a terminal.** None. The luv and Neovim adapters do not ---- own an interactive terminal, so `libtmux.Session:attach` returns +--- **Attaching a client.** `libtmux.Session:attach` requires a host terminal. +--- With the luv and Neovim adapters, this request returns --- `unsupported_tty`. --- --- `libtmux.Session:attach` @@ -1531,6 +1552,13 @@ end --- options?:libtmux.CommandOptions):libtmux.Request ---@field batch fun(self:libtmux.Server, commands:string[][], --- options?:libtmux.CommandBatchOptions):libtmux.Request +--- Resolves to a Program after the executable has started in its tmux pane. +---@field start_program fun(self:libtmux.Server,argv:string[], +--- options?:libtmux.ProgramOptions):libtmux.Request +--- Resolves to the application's result after cleanup. A nonzero exit +--- is reported in that result. +---@field run_program fun(self:libtmux.Server,argv:string[], +--- options?:libtmux.ProgramOptions):libtmux.Request ---@field snapshot fun(self:libtmux.Server, --- options?:libtmux.SnapshotOptions):libtmux.Request ---@field close fun(self:libtmux.Server):libtmux.Request diff --git a/lua/libtmux/_internal/support/capabilities.lua b/lua/libtmux/_internal/support/capabilities.lua index 79ccf44f..8fbe0376 100644 --- a/lua/libtmux/_internal/support/capabilities.lua +++ b/lua/libtmux/_internal/support/capabilities.lua @@ -37,6 +37,21 @@ end ---@type libtmux.Capability[] M.capabilities = { + { + id = "owned-program", + name = "Owned terminal programs", + summary = "Start a terminal program and collect its output, status and cleanup.", + since = "3.3a", + except = {}, + handling = "refuse", + error = REFUSAL, + apis = { "libtmux.Server:start_program", "libtmux.Server:run_program" }, + commands = { + { command = "new-session", flags = { "-e", "-F", "-P" } }, + { command = "if-shell", flags = { "-F", "-t" } }, + { command = "pipe-pane", flags = { "-O", "-t" } }, + }, + }, { id = "control-mode", name = "Control mode observation", diff --git a/lua/libtmux/runtime/luv.lua b/lua/libtmux/runtime/luv.lua index f7e177dd..68e5721c 100644 --- a/lua/libtmux/runtime/luv.lua +++ b/lua/libtmux/runtime/luv.lua @@ -106,6 +106,23 @@ function M._result(root, rt) return value, err end +local function module_cpath(uv) + local cwd = uv.cwd() + local templates = package.cpath + if not cwd or type(templates) ~= "string" then + return templates + end + local prefix = cwd:gsub("/$", "") .. "/" + return ( + templates:gsub("[^;]+", function(template) + if template:sub(1, 1) == "/" then + return template + end + return prefix .. template + end) + ) +end + ---@generic T ---@param fn fun(runtime:libtmux.Runtime):T?, libtmux.Error? ---@param options? libtmux.RuntimeOptions @@ -139,6 +156,7 @@ function M.run(fn, options) return nil, errors.new("invalid_run_context", "run needs a quiescent standalone loop") end local driver = M._driver(uv) + driver.module_cpath = module_cpath(uv) local rt = runtime.new(driver, options) local root = rt:start(fn) local failure, guard, expired, guard_failed diff --git a/rockspecs/libtmux-scm-1.rockspec b/rockspecs/libtmux-scm-1.rockspec index 37b545ab..9d74448d 100644 --- a/rockspecs/libtmux-scm-1.rockspec +++ b/rockspecs/libtmux-scm-1.rockspec @@ -19,6 +19,9 @@ build = { ["libtmux._internal.runtime"] = "lua/libtmux/_internal/runtime.lua", ["libtmux._internal.error"] = "lua/libtmux/_internal/error.lua", ["libtmux._internal.process"] = "lua/libtmux/_internal/process.lua", + ["libtmux._internal.program"] = "lua/libtmux/_internal/program.lua", + ["libtmux._internal.program_channel"] = "lua/libtmux/_internal/program_channel.lua", + ["libtmux._internal.program_supervisor"] = "lua/libtmux/_internal/program_supervisor.lua", ["libtmux._internal.codec"] = "lua/libtmux/_internal/codec.lua", ["libtmux._internal.scope"] = "lua/libtmux/_internal/scope.lua", ["libtmux._internal.options_catalog"] = "lua/libtmux/_internal/options_catalog.lua", diff --git a/scripts/docs/tests/test_api_examples.lua b/scripts/docs/tests/test_api_examples.lua index 681ef834..a8de0004 100644 --- a/scripts/docs/tests/test_api_examples.lua +++ b/scripts/docs/tests/test_api_examples.lua @@ -20,7 +20,10 @@ for symbol in libtmux.Runtime:with_server libtmux.OwnedServer.server libtmux.OwnedServer.socket_path libtmux.OwnedServer:stop libtmux.SnapshotSession.window_links libtmux.SnapshotWindowLink.window libtmux.SnapshotWindow.panes - libtmux.WindowLink:move libtmux.Window:layout]]):gmatch("%S+") + libtmux.WindowLink:move libtmux.Window:layout + libtmux.Server:start_program libtmux.Server:run_program + libtmux.Program:send_text libtmux.Program:send_keys libtmux.Program:wait + libtmux.Program:reference libtmux.Program:stop libtmux.Program:screen]]):gmatch("%S+") do TARGETS[symbol] = true end @@ -69,7 +72,7 @@ end function M.test_complete_programs_cover_their_existing_targets() local loaded = api.load_examples(repo.root, TARGETS) - test.assertEquals(#loaded.examples, 21) + test.assertEquals(#loaded.examples, 22) local seen = {} for _, example in ipairs(loaded.examples) do for _, symbol in ipairs(example.symbols) do @@ -78,11 +81,9 @@ function M.test_complete_programs_cover_their_existing_targets() local source = files.read(repo.root .. "/" .. example.file) test.assertStrContains(source, 'require("libtmux.runtime.luv")') -- Each program starts its own server and ends it, or hands it to the scoped form. - test.assertStrContains( - source, - example.id == "with_server" and "with_server" or "start_server" - ) - if example.id ~= "with_server" then + local scoped = example.id == "with_server" or example.id == "owned_program" + test.assertStrContains(source, scoped and ":with_server(" or ":start_server(") + if not scoped then test.assertStrContains(source, "owned:stop():await()") end test.assertNil(source:find('require("tests.', 1, true)) diff --git a/tests/integration/program_contract.lua b/tests/integration/program_contract.lua new file mode 100644 index 00000000..4c03f32a --- /dev/null +++ b/tests/integration/program_contract.lua @@ -0,0 +1,504 @@ +local test_case = assert(os.getenv("LIBTMUX_PROGRAM_CASE")) +if test_case == "client_directory" then + package.path = "./lua/?.lua;./lua/?/init.lua;" .. package.path +end +local host = rawget(_G, "vim") +local adapter = require(host and "libtmux.runtime.nvim" or "libtmux.runtime.luv") +---@diagnostic disable-next-line: different-requires +local uv = host and (host.uv or host.loop) or require("luv") + +if test_case == "application_directory" and not host then + local checkout = assert(os.getenv("LIBTMUX_PROGRAM_TEST_CWD")) + local loader_dir = assert(os.getenv("LIBTMUX_PROGRAM_TEST_DIR")) + package.path = checkout .. "/lua/?.lua;" .. checkout .. "/lua/?/init.lua;" .. package.path + local native_module + for template in package.cpath:gmatch("[^;]+") do + native_module = uv.fs_realpath((template:gsub("%?", "luv"))) + if native_module then + break + end + end + assert(uv.fs_symlink(assert(native_module), loader_dir .. "/luv.so")) + assert(uv.chdir(loader_dir)) + package.cpath = "./?.so" +end + +local function must(value, err) + if err then + error(tostring(err), 0) + end + return assert(value) +end + +local function interactive(server) + local program = must(server + :start_program({ + "/bin/sh", + "-c", + [[test -t 0 && test -t 1 && test -t 2 || exit 97 +IFS= read -r line +printf 'reply=[%s]\n' "$line" +exit 23]], + }) + :await()) + local reference = program:reference() + local launch = must( + server + :command({ "display-message", "-p", "-t", reference.pane_id, "#{pane_start_command}" }) + :await() + ) + local directory = assert(launch.stdout:match("(/tmp/libtmux%-lua%-program%-%w+)/status")) + local stat, _, stat_code = uv.fs_lstat(directory) + assert( + not stat and stat_code == "ENOENT", + "started program retained its private socket directory" + ) + + local early, timeout = program:wait({ timeout = 10 }):await() + assert(not early and timeout and timeout.code == "deadline_exceeded") + local detached = program:wait() + must(server:command({ "display-message", "-p", "active wait" }):await()) + assert(detached:cancel()) + local absent, cancelled = detached:await() + assert(not absent and cancelled and cancelled.code == "cancelled") + local scope = reference.cleanup_scope + assert(scope == "tree" or scope == "direct") + must(program:send_text("interactive"):await()) + must(program:send_keys({ "Enter" }):await()) + local finished = must(program:wait({ timeout = 2000 }):await()) + assert(finished.kind == "exit" and finished.exit_code == 23) + assert(finished.output.complete, tostring(finished.output.error)) + assert(finished.output.bytes:find("reply=[interactive]\r\n", 1, true)) + local screen = must(finished.screen, finished.screen_error) + assert(screen.bytes:find("reply=[interactive]\n", 1, true), ("%q"):format(screen.bytes)) + local saved = must(program:screen():await()) + assert(saved.bytes == finished.screen.bytes) + assert(finished.cleanup.scope == scope) + local result, past = program:wait({ deadline = 0, timeout = 500 }):await() + assert(not result and past and past.code == "deadline_exceeded", "ignored earlier deadline") + local valid, nan = program:wait({ deadline = 0 / 0, timeout = 500 }):await() + assert(not valid and nan and nan.code == "invalid_options", "accepted non-finite deadline") + local remaining, zero = + program:wait({ deadline = uv.hrtime() / 1e6 + 500, timeout = 0 }):await() + assert(not remaining and zero and zero.code == "deadline_exceeded", "ignored earlier timeout") + assert( + finished.cleanup.pane_closed and not finished.cleanup_error, + tostring(finished.cleanup_error) + ) +end + +local function noninteractive(server) + local completed = must(server + :run_program({ + "/bin/sh", + "-c", + "printf 'done\\n'; printf 'diagnostic\\n' >&2; exit 42", + }) + :await()) + assert(completed.kind == "exit" and completed.exit_code == 42) + assert(completed.output.bytes == "done\r\ndiagnostic\r\n", completed.output.bytes) + assert(completed.output.complete, tostring(completed.output.error)) + assert(completed.cleanup.pane_closed, tostring(completed.cleanup_error)) + local explicit = must(server:run_program({ "/bin/sh", "-c", "exit 143" }):await()) + local signal = must(server:run_program({ "/bin/sh", "-c", "kill -TERM $$" }):await()) + assert(explicit.kind == "exit" and explicit.exit_code == 143) + assert(signal.kind == "signal" and signal.signal == 15) + local bounded = must( + server + :run_program({ "/bin/sh", "-c", "printf '%080d\\n' 0" }, { max_output_bytes = 10 }) + :await() + ) + assert(bounded.output.bytes == ("0"):rep(10)) + assert(bounded.output.dropped_bytes == 72 and bounded.output.truncated) + local screen = must(bounded.screen, bounded.screen_error) + assert(not bounded.output.complete and screen.truncated) +end + +local function client_directory(server) + local previous = assert(uv.cwd()) + local directory = assert(os.getenv("LIBTMUX_PROGRAM_TEST_DIR")) + assert(uv.chdir(directory)) + local result, err = server:run_program({ "/bin/true" }):await() + assert(uv.chdir(previous)) + assert(result and result.exit_code == 0, tostring(err)) +end + +local function application_directory(server) + local directory = assert(os.getenv("LIBTMUX_PROGRAM_TEST_DIR")) .. "/application" + assert(uv.fs_mkdir(directory, 448)) + local result = must(server:run_program({ "/bin/pwd" }, { cwd = directory }):await()) + assert(result.exit_code == 0 and result.output.complete) + assert(result.output.bytes == directory .. "\r\n", result.output.bytes) +end + +local function admission(server) + local _, malformed = server:start_program({ [1] = "/bin/false", [3] = "hole" }):await() + assert(malformed and malformed.code == "invalid_argv" and malformed.effect == "not_sent") + local none, expired = server:run_program({ "/bin/false" }, { timeout = 0 }):await() + assert(not none and expired and expired.code == "deadline_exceeded") + local base = assert(os.getenv("LIBTMUX_PROGRAM_TEST_CWD")) + local literal = [=[# % "'; $(printf changed)]=] .. "\nfirst=second\n" + local environment = { + PROGRAM_LITERAL = literal, + PROGRAM_EMPTY = "", + PROGRAM_LARGE = ("L"):rep(65536), + PROGRAM_AUX = ("A"):rep(16384), + LUA_INIT = "@/guest-config/unused-by-sh.lua", + } + local guest = server:run_program({ + "/bin/sh", + "-c", + [[test "$PWD" = "$1" && test "$2" = "$PROGRAM_LITERAL" && +test -z "$3" && test "$#" -eq 3 && +test -z "${LIBTMUX_LUA_PROGRAM_TOKEN+x}" && test -z "${LIBTMUX_LUA_PROGRAM_CPATH+x}" && +test -n "$TMUX" && test -n "$TMUX_PANE" && test -n "$TERM" && +test "${PROGRAM_EMPTY+x}" = x && test -z "$PROGRAM_EMPTY" && +test "${#PROGRAM_LARGE}" -eq 65536 && test "${#PROGRAM_AUX}" -eq 16384 && +test "$LUA_INIT" = "@/guest-config/unused-by-sh.lua" +]], + "sh", + base, + literal, + "", + }, { cwd = base, environment = environment }) + environment.LUA_INIT, environment.PROGRAM_LITERAL, environment.PROGRAM_EMPTY = + nil, "changed", "changed" + local result = must(guest:await()) + assert(result.kind == "exit" and result.exit_code == 0) + local directory = assert(os.getenv("LIBTMUX_PROGRAM_TEST_DIR")) + local executable = directory .. "/program-guest-path" + local output = assert(io.open(executable, "w")) + assert(output:write("#!/bin/sh\nprintf 'guest-path\\n'\n")) + assert(output:close()) + assert(uv.fs_chmod(executable, 448)) + local lookup = must(server + :run_program({ "program-guest-path" }, { + environment = { PATH = directory }, + }) + :await()) + assert(lookup.kind == "exit" and lookup.exit_code == 0) + assert(lookup.output.bytes == "guest-path\r\n") + local invalid, oversized = server + :run_program({ "/bin/false" }, { + environment = { PROGRAM_LARGE = ("L"):rep(65537) }, + }) + :await() + assert(not invalid and oversized and oversized.code == "invalid_options") + local bad, spawn = server:start_program({ "/missing-libtmux-program-executable" }):await() + assert(not bad and spawn and spawn.code == "spawn_failed") +end + +local function stopping(server) + local action = + must(server:start_program({ "/bin/sh", "-c", "IFS= read -r line; exit 91" }):await()) + local stopped = must(action:stop():await()) + assert(stopped.kind == "signal" and (stopped.signal == 15 or stopped.signal == 9)) + assert(stopped.cleanup.pane_closed, tostring(stopped.cleanup_error)) + assert(must(action:wait():await()).signal == stopped.signal) +end + +local function poll(check) + local deadline = uv.hrtime() + 2e9 + repeat + local value = check() + if value then + return value + end + until uv.hrtime() >= deadline + error("program state did not become ready", 0) +end + +local function operator_stop(server) + local mode = assert(os.getenv("LIBTMUX_PROGRAM_OPERATOR_MODE")) + local receipt = assert(os.getenv("LIBTMUX_PROGRAM_TEST_DIR")) .. "/operator-exit" + local program = must(server + :start_program({ + "/bin/sh", + "-c", + [[trap 'printf "31\n" > "$1"; exit 31' HUP +trap 'printf "29\n" > "$1"; exit 29' TERM +printf 'before operator stop\n' +IFS= read -r input +printf '37\n' > "$1" +exit 37]], + "sh", + receipt, + }) + :await()) + poll(function() + local screen = must(program:screen():await()) + return screen.bytes:find("before operator stop\n", 1, true) + end) + + local waiting = program:wait({ timeout = 3000 }) + must(server:command({ "display-message", "-p", "wait active" }):await()) + assert(not waiting:is_settled()) + io.stdout:write("operator-wait: ", program:reference().session_id, "\n") + io.stdout:flush() + + local result = must(waiting:await()) + assert(waiting:is_retired()) + local output = must(result.output) + local cleanup = must(result.cleanup) + local cleanup_error = result.cleanup_error and result.cleanup_error.code + local expected_cleanup_error + if result.kind == "unknown" then + expected_cleanup_error = "program_unknown" + elseif mode == "server" then + expected_cleanup_error = "stale_generation" + end + assert( + output.complete == false and cleanup_error == expected_cleanup_error, + ("output.complete=%s, cleanup_error=%s"):format( + tostring(output.complete), + tostring(result.cleanup_error) + ) + ) + assert(output.bytes == "before operator stop\r\n") + assert(output.error and output.error.code == "output_gap") + assert(not result.screen) + assert(cleanup.pane_closed == (mode == "session")) + if result.kind == "exit" then + local file = assert(io.open(receipt, "r")) + local exit = tonumber(file:read("*l")) + file:close() + assert(exit == 29 or exit == 31 or exit == 37) + assert(result.exit_code == exit and not result.signal and not result.error) + elseif result.kind == "signal" then + assert(result.signal == 1 or result.signal == 9 or result.signal == 15) + assert(not result.exit_code and not result.error) + else + assert(result.kind == "unknown" and result.error and result.error.code == "program_unknown") + assert(not result.exit_code and not result.signal) + end + local saved = must(program:wait():await()) + assert( + saved.kind == result.kind + and saved.exit_code == result.exit_code + and saved.signal == result.signal + ) +end + +local function running_pane(server) + local listed = must(server + :command({ + "list-panes", + "-a", + "-F", + "#{pane_id} #{session_name}", + }) + :await()) + return listed.stdout:match("(%%%d+) libtmux%-program%-%x+\n") +end + +local function shell_word(value) + return "'" .. value:gsub("'", "'\\''") .. "'" +end + +local function setup_cancel(server) + local path = assert(os.getenv("LIBTMUX_PROGRAM_TEST_DIR")) + local lua = assert(os.getenv("LIBTMUX_TEST_LUA")) + local cpath = os.getenv("LIBTMUX_TEST_LUA_CPATH") or package.cpath + local wrapper, accepted, ran = path .. "/delayed-lua", path .. "/accepted", path .. "/ran" + local out = assert(io.open(wrapper, "w")) + assert( + out:write( + "#!/bin/sh\n", + "export LUA_CPATH=", + shell_word(cpath), + "\n", + 'if [ "$2" = status ]; then\n', + " : > ", + shell_word(accepted), + "\n", + " /bin/sleep 0.4\n", + "fi\n", + "exec ", + shell_word(lua), + ' "$@"\n' + ) + ) + assert(out:close()) + assert(uv.fs_chmod(wrapper, 448)) + local start = server:start_program({ + "/bin/sh", + "-c", + 'printf "launched" > "$1"', + "sh", + ran, + }, { lua = wrapper, startup_timeout = 2000 }) + poll(function() + return running_pane(server) and uv.fs_stat(accepted) + end) + assert(start:cancel()) + local value, cancelled = start:await() + assert(not value and cancelled and cancelled.code == "cancelled") + poll(function() + running_pane(server) + return start:is_retired() + end) + assert(not uv.fs_stat(ran), "the program received a launch grant after cancellation") + assert(not running_pane(server), "startup retired before clearing the accepted pane") + assert(not cancelled.cleanup_error, tostring(cancelled.cleanup_error)) +end + +local function cancellation(server) + local run = server:run_program({ + "/bin/sh", + "-c", + [[trap '' TERM +printf 'actual-start:%s\n' "$$" +IFS= read -r hold]], + }) + local child = poll(function() + local pane_id = running_pane(server) + if pane_id then + local capture = must(server:command({ "capture-pane", "-pt", pane_id }):await()) + return tonumber(capture.stdout:match("actual%-start:(%d+)")) + end + end) + assert(run:cancel()) + local value, cancelled = run:await() + assert(not value and cancelled and cancelled.code == "cancelled") + assert(not run:is_retired() or not uv.kill(child, 0), "run retired before the program left") + poll(function() + must(server:command({ "display-message", "-p", "joining" }):await()) + return run:is_retired() + end) + assert(not uv.kill(child, 0), "run retired without reaping its program") + assert(not running_pane(server), "run retired before closing its owned pane") + assert(not cancelled.cleanup_error, tostring(cancelled.cleanup_error)) +end + +local function replacement(server) + local program = must(server + :start_program({ + "/bin/sh", + "-c", + "IFS= read -r input; exit 91", + }) + :await()) + local pane_id = program:reference().pane_id + must(server + :command({ + "respawn-pane", + "-k", + "-t", + pane_id, + "--", + "/bin/sh", + "-c", + [[printf 'replacement-ready\n' +IFS= read -r line +printf 'replacement-got:[%s]\n' "$line" +IFS= read -r hold]], + }) + :await()) + local _, refused = program:send_text("old-owner-input"):await() + assert(refused and (refused.code == "program_replaced" or refused.code == "program_closed")) + local finished = must(program:stop({ timeout = 2400 }):await()) + assert(finished.kind ~= "exit" or finished.exit_code == 91) + assert(not finished.cleanup.pane_closed) + assert(finished.cleanup_error) + local capture = must(server:command({ "capture-pane", "-pt", pane_id }):await()) + assert(capture.stdout:find("replacement-ready", 1, true)) + assert(not capture.stdout:find("old-owner-input", 1, true)) + must(server:command({ "kill-pane", "-t", pane_id }):await()) +end + +local function pressure(server) + local program = must(server + :start_program({ + "/bin/sh", + "-c", + [[IFS= read -r key +/usr/bin/head -c 524288 /dev/zero +printf 'app-end\n' +exit 17]], + }, { max_output_bytes = 32768 }) + :await()) + local wait = program:wait({ timeout = 2000 }) + must(program:send_keys({ "Enter" }):await()) + local other = must(server:command({ "display-message", "-p", "other work" }):await()) + assert(other.stdout == "other work\n") + local result = must(wait:await()) + assert(result.exit_code == 17) + assert(result.output.bytes == "\r\n" .. ("\000"):rep(32766)) + assert(result.output.truncated and not result.output.complete and not result.output.error) + assert(result.output.dropped_bytes == 524288 + 2 + #"app-end\r\n" - 32768) + local sample = must(result.screen, result.screen_error) + assert(sample.bytes:find("app-end", 1, true)) + assert(result.cleanup.pane_closed) +end + +local function closing(server) + local argv = { "/bin/sh", "-c", "IFS= read -r input" } + local one = must(server:start_program(argv):await()) + local two = must(server:start_program(argv):await()) + must(server:close():await()) + assert(must(one:wait():await()).cleanup.pane_closed) + assert(must(two:wait():await()).cleanup.pane_closed) +end + +local function tree_requirement(server) + local path = assert(os.getenv("LIBTMUX_PROGRAM_TEST_DIR")) .. "/tree-launched" + local run, refusal = server + :run_program({ + "/bin/sh", + "-c", + 'printf "tree-run" > "$1"; exit 37', + "sh", + path, + }, { require_tree = true }) + :await() + if refusal then + assert(refusal.code == "unsupported" and refusal.cleanup_scope == "direct") + assert(not uv.fs_stat(path), "the program ran before tree cleanup was verified") + assert(not refusal.cleanup_error, tostring(refusal.cleanup_error)) + else + assert(run and run.exit_code == 37 and run.cleanup.scope == "tree") + assert(uv.fs_stat(path)) + end +end + +local cases = { + client_directory = client_directory, + application_directory = application_directory, + interactive = interactive, + noninteractive = noninteractive, + admission = admission, + stopping = stopping, + operator_stop = operator_stop, + cancellation = cancellation, + replacement = replacement, + setup_cancel = setup_cancel, + pressure = pressure, + closing = closing, + tree_requirement = tree_requirement, +} + +local function work(runtime) + local server = must(runtime + :connect({ + binary = assert(os.getenv("TMUX_BIN")), + socket_path = assert(os.getenv("TMUX_SOCKET")), + }) + :await()) + assert(cases[test_case])(server) + must(server:close():await()) + return "public owned program passed" +end + +if host then + adapter.start(work, function(value, err) + if err then + io.stderr:write(tostring(err), "\n") + host.cmd("cquit 1") + else + print(value) + host.cmd("qall!") + end + end) +else + print(must(adapter.run(work))) +end diff --git a/tests/integration/program_exit_concept.lua b/tests/integration/program_exit_concept.lua index 4398d4d3..be5089cb 100644 --- a/tests/integration/program_exit_concept.lua +++ b/tests/integration/program_exit_concept.lua @@ -153,6 +153,20 @@ must(adapter.run(function(runtime) end local before = must(server:command({ "list-panes", "-a", "-F", "#{pane_id}" }):await()) + local truncated, argv_error = adapter.launch(runtime, session, { + "/bin/sh", + "-c", + "exit 89", + [5] = "missing argument before this", + }) + if truncated then + local receipt = must(truncated:wait(deadline(750)):await()) + error("invalid argv launched the command with exit " .. tostring(receipt.number)) + end + assert(argv_error and argv_error.code == "invalid_argv", tostring(argv_error)) + assert(argv_error.effect == "not_sent") + assert(runtime:stats().resources == resources, "invalid argv created a channel lease") + local failed, spawn_error = adapter.launch(runtime, session, { "/no-libtmux-executable" }) assert(not failed and spawn_error and spawn_error.code == "spawn_failed", tostring(spawn_error)) local after = must(server:command({ "list-panes", "-a", "-F", "#{pane_id}" }):await()) diff --git a/tests/integration/test_program_contract.lua b/tests/integration/test_program_contract.lua new file mode 100644 index 00000000..dd4d1eae --- /dev/null +++ b/tests/integration/test_program_contract.lua @@ -0,0 +1,66 @@ +local test = require("luaunit") +local fixture = require("tests.support.fixture") +local repo = require("support.repo") +local M = {} + +for _, case in ipairs({ + "interactive", + "noninteractive", + "client_directory", + "application_directory", + "admission", + "stopping", + "cancellation", + "replacement", + "setup_cancel", + "pressure", + "closing", + "tree_requirement", +}) do + fixture.each_host(M, "public_program_" .. case, function(host) + fixture.with(function(f) + if case == "application_directory" then + f:run("set-environment", "-g", "LUA_CPATH", "") + end + local result = f:program(host, "program_contract", { + LIBTMUX_PROGRAM_CASE = case, + LIBTMUX_PROGRAM_TEST_CWD = repo.root, + LIBTMUX_PROGRAM_TEST_DIR = assert(f.path), + }, { timeout = 8 }) + test.assertStrContains(result.stdout .. result.stderr, "public owned program passed") + test.assertEquals(f:out("list-sessions", "-F", "#{session_name}"), "fixture\n") + end) + end) +end + +for _, mode in ipairs({ "session", "server" }) do + fixture.each_host(M, "public_program_operator_stop_" .. mode, function(host) + fixture.with(function(f) + local client = f:start_program(host, "program_contract", { + LIBTMUX_PROGRAM_CASE = "operator_stop", + LIBTMUX_PROGRAM_OPERATOR_MODE = mode, + LIBTMUX_PROGRAM_TEST_DIR = assert(f.path), + }) + local session + test.assertTrue( + client:expect(function() + session = client:output():match("operator%-wait: (%$%d+)\n") + return session ~= nil + end, fixture.DEADLINE), + client:errors() + ) + if mode == "session" then + f:run("kill-session", "-t", assert(session)) + test.assertEquals(f:out("list-sessions", "-F", "#{session_name}"), "fixture\n") + else + f:run("kill-server") + f:wait_exits() + end + local result = client:finish(fixture.DEADLINE) + test.assertEquals(result.code, 0, result.stderr) + test.assertStrContains(result.stdout .. result.stderr, "public owned program passed") + end) + end) +end + +return M diff --git a/tests/integration/test_program_exit_concept.lua b/tests/integration/test_program_exit_concept.lua index 3e00d5cd..0a3da18c 100644 --- a/tests/integration/test_program_exit_concept.lua +++ b/tests/integration/test_program_exit_concept.lua @@ -60,18 +60,21 @@ function M.test_literal_argv_and_input_reach_a_real_pty() [=[ test -t 0 && test -t 1 && test -t 2 || exit 31 test "$1" = '$(printf altered); #{pane_id}' || exit 32 + test "$#" -eq 3 && test -z "$3" || exit 36 test -z "$LIBTMUX_LUA_CONCEPT_LAUNCH" || exit 35 IFS= read -r line && test "$line" = "$2" || exit 33 - for i in 1 2 3 4 5 6 7 8 9; do printf '%s\n' "$line"; done + for i in 1 2 3 4 5 6 7 8 9; do printf 'reply: [%s]\n' "$line"; done ]=], "sh", expected, input, + "", }) test.assertEquals(result.stderr, "") test.assertEquals(result.code, 0, result.stdout) local screen = result.stdout:match("screen sample\n(.*)$") test.assertNotNil(screen, result.stdout) + test.assertStrContains(screen, "reply: [" .. input .. "]\n") local _, lines = screen:gsub("\n", "") test.assertEquals(lines, 4) test.assertTrue(#screen <= 1024) diff --git a/tests/integration/test_runtime.lua b/tests/integration/test_runtime.lua index 17ff15e0..cf51bacf 100644 --- a/tests/integration/test_runtime.lua +++ b/tests/integration/test_runtime.lua @@ -2,11 +2,11 @@ local test = require("luaunit") local child = require("tests.support.child") local fixture = require("tests.support.fixture") +local sandbox = require("tests.support.sandbox") +local sandbox_host = require("tests.support.sandbox_host") local files = require("support.files") local fs = require("support.fs") local repo = require("support.repo") -local sandbox = require("tests.support.sandbox") -local sandbox_host = require("tests.support.sandbox_host") local uv = require("support.uv") local M = {} @@ -37,7 +37,7 @@ local function snapshot_example() return nvim("--cmd", "set runtimepath+=.", "-c", "luafile tests/support/nvim_example.lua") end -local function release_snapshot(root, binary, ok, failure) +local function release_example(root, binary, ok, failure) local released = sandbox_host.release(root, binary) fixture.settle(ok, failure, #released.leaked == 0, sandbox_host.describe(released, root)) end @@ -55,23 +55,29 @@ function M.test_nvim_borrows_loop_and_preserves_unrelated_handle() test.assertStrContains(result.stdout .. result.stderr, "Neovim runtime smoke PASS") end -function M.test_neovim_example_starts_its_own_server_and_reports_the_pane_count() - -- Short and under /tmp: the example's private directory must fit a socket path. +local function check_nvim_example(argv, stdout, timeout) + local tmux = fixture.tmux() local root = fs.mkdtemp(sandbox.PREFIX) - local bin = fs.mkdtemp("libtmux-lua-") - local binary = fixture.tmux() + local sockets, bin = root .. "/sockets", root .. "/bin" local ok, failure = pcall(function() - -- Put the selected build on the PATH the example inherits. - assert(uv.fs_symlink(binary, bin .. "/tmux")) - local env = - nvim_environment({ TMPDIR = root, PATH = bin .. ":" .. (os.getenv("PATH") or "") }) - local result = run(snapshot_example(), env, 3) + fs.mkdir_p(sockets) + fs.mkdir_p(bin) + assert(uv.fs_symlink(tmux, bin .. "/tmux")) + local env = nvim_environment({ + TMPDIR = sockets, + TMUX_BIN = tmux, + PATH = bin .. ":" .. (os.getenv("PATH") or ""), + }) + local result = run(argv, env, timeout) test.assertEquals(result.code, 0, result.stdout .. result.stderr) - test.assertEquals(result.stdout, "Panes: 1\n") - test.assertEquals(fs.list(root), {}, "the example left its server directory") + test.assertEquals(result.stdout, stdout) + test.assertEquals(fs.list(sockets), {}, "the example left its server directory") end) - fs.remove_tree(bin) - release_snapshot(root, binary, ok, failure) + release_example(root, tmux, ok, failure) +end + +function M.test_neovim_example_starts_its_own_server_and_reports_the_pane_count() + check_nvim_example(snapshot_example(), "Panes: 1\n", 3) end -- A snapshot command records the owned processes, then waits indefinitely on the FIFO. @@ -168,10 +174,21 @@ function M.test_neovim_example_watchdog_retires_the_daemon_and_pane() test.assertNil(fs.stat(socket), "the watchdog left its socket") end) local retired, retire_error = pcall(retire_snapshot_program, program, fifo, writer, receipt) - local released, release_error = pcall(release_snapshot, root, binary, retired, retire_error) + local released, release_error = pcall(release_example, root, binary, retired, retire_error) fixture.settle(ok, failure, released, release_error) end +function M.test_neovim_program_example() + local manifest = require("docs.api_examples").load_examples(repo.root) + for _, example in ipairs(manifest.examples) do + if example.id == "owned_program" then + check_nvim_example(nvim("-l", example.file), example.stdout, 30) + return + end + end + error("the Program example is missing from the manifest", 0) +end + function M.test_neovim_quick_start_calculates_the_requested_sum() local binary = fixture.tmux() local version = run({ binary, "-V" }) diff --git a/tests/unit/server.lua b/tests/unit/server.lua index 92beb106..ced29cfa 100644 --- a/tests/unit/server.lua +++ b/tests/unit/server.lua @@ -6,7 +6,7 @@ local identity = require("libtmux._internal.identity") local fields = require("libtmux._internal.fields") local M = {} -local function fixture(body, limits) +local function fixture(body, limits, expected_root_error) local driver = drivers.new() local rt = runtimes.new(driver, limits or { max_active = 1 }) local state = { calls = {}, binds = 0 } @@ -116,7 +116,11 @@ local function fixture(body, limits) driver:drain() t.assertTrue(root:is_retired()) local _, failure = root:result() - t.assertNil(failure) + if expected_root_error then + t.assertEquals(failure and failure.code, expected_root_error) + else + t.assertNil(failure) + end end) rawset(endpoints, "bind", original) if not ok then @@ -129,6 +133,62 @@ local function connect(rt) return assert(rt:connect({ binary = "/bin/tmux", socket_path = "/owned/socket" }):await()) end +function M.test_runtime_close_reports_which_program_session_may_still_exist() + local channel = require("libtmux._internal.program_channel") + local original = channel.open + for _, method in ipairs({ "start_program", "run_program" }) do + for _, connected in ipairs({ false, true }) do + local request + local dispatched = false + rawset(channel, "open", function(rt) + return { + token = "example", + fence_token = "fence", + status_path = "/test/status", + pid = connected and 123 or nil, + _notify = function() end, + lease = assert(rt:_resource(function(done) + done() + end)), + } + end) + local ok, cause = pcall(fixture, function(rt, state) + rt._driver.uv = { + cwd = function() + return assert(os.getenv("PWD")) + end, + exepath = function() + return "/test/lua" + end, + new_pipe = error, + random = error, + fs_realpath = function(path, done) + done(nil, path) + return true + end, + } + local server = connect(rt) + state.before = function(_, argv) + t.assertEquals(argv[1], "new-session") + dispatched = true + rt:close() + end + request = server[method](server, { "fixture" }) + request:await() + end, nil, "cancelled") + rawset(channel, "open", original) + assert(ok, cause) + t.assertTrue(dispatched) + t.assertTrue(request:is_retired()) + local _, err = request:result() + t.assertEquals(err.code, "cancelled") + t.assertEquals(err.effect, "unknown") + t.assertEquals(err.cleanup_error and err.cleanup_error.code, "cleanup_failed") + t.assertEquals(err.program_name, "libtmux-program-example") + end + end +end + function M.test_public_batch_can_register_its_only_completion_slot() local returned, observed local calls = 0 From f0681c897283a0017b365caad3d6621182cf98b7 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 12:00:32 -0600 Subject: [PATCH 3/3] Docs(changelog): Mention owned terminal programs why: Readers need the entry points for running and interacting with an owned application in tmux. what: - Summarize run_program and start_program under Unreleased. --- CHANGES.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 7982dde9..4b87a57b 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -63,6 +63,9 @@ Notable changes to `libtmux`. callers to open a fresh watch on the live observation. (#148) - `Observation:watch_pane_lines` reads complete lines with an optional reply prefix and a single deadline across intervening output. +- Await `Server:run_program(argv)` for a program’s exit code or signal, terminal + output and final tmux screen. Await `Server:start_program(argv)` to send text + or keys to its pane before waiting for it to finish. (#107) ## 0.1.1-1 (2026-11-01)