From c422dd2c8ecc106615e57c3ffaa9c4249ac4bf7a Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Mon, 30 Nov 2026 20:18:32 -0600 Subject: [PATCH] Core(feat): Scope a terminal application why: Interactive application clients need one owner for their terminal without acquiring ownership of a borrowed daemon. what: Expose the terminal program lifecycle and its typed outcomes, and exercise scoped use from the JVM language facades. --- CHANGELOG.md | 7 + README.md | 4 + docs/guide/clojure-api.md | 73 ++++ .../clojure/libtmux/private_server_test.clj | 63 ++- .../libtmux/scaladsl/ox/OxProgramSuite.scala | 67 ++++ libtmux-clojure/CHANGELOG.md | 3 + libtmux-clojure/README.md | 33 ++ .../src/main/clojure/libtmux/core.clj | 118 +++++- libtmux-kotlin/CHANGELOG.md | 4 + libtmux-kotlin/README.md | 41 ++ libtmux-kotlin/api/libtmux-kotlin.api | 13 + .../github/libtmux/kotlin/ExecutionPolicy.kt | 5 +- .../io/github/libtmux/kotlin/Program.kt | 91 +++++ .../libtmux/kotlin/PrivateServerTest.kt | 76 ++++ libtmux-scala-cats/CHANGELOG.md | 3 + libtmux-scala-cats/README.md | 43 +++ .../libtmux/scaladsl/cats/Execution.scala | 4 + .../libtmux/scaladsl/cats/Program.scala | 46 +++ .../github/libtmux/scaladsl/cats/Server.scala | 9 + .../scaladsl/cats/PrivateServerSuite.scala | 61 ++- libtmux-scala-ox/README.md | 39 ++ libtmux-scala/CHANGELOG.md | 3 + libtmux-scala/README.md | 41 ++ .../io/github/libtmux/scaladsl/Program.scala | 81 ++++ .../libtmux/scaladsl/PrivateServerSuite.scala | 36 ++ libtmux/CHANGELOG.md | 5 + libtmux/README.md | 51 +++ .../main/java/io/github/libtmux/Program.java | 358 ++++++++++++++++++ .../java/io/github/libtmux/ProgramExit.java | 42 ++ .../java/io/github/libtmux/ProgramResult.java | 21 + .../java/io/github/libtmux/ProgramSpec.java | 141 +++++++ .../java/io/github/libtmux/ProgramTest.java | 243 ++++++++++++ 32 files changed, 1809 insertions(+), 16 deletions(-) create mode 100644 integration-tests/src/test/scala/io/github/libtmux/scaladsl/ox/OxProgramSuite.scala create mode 100644 libtmux-kotlin/src/main/kotlin/io/github/libtmux/kotlin/Program.kt create mode 100644 libtmux-scala-cats/src/main/scala/io/github/libtmux/scaladsl/cats/Program.scala create mode 100644 libtmux-scala/src/main/scala/io/github/libtmux/scaladsl/Program.scala create mode 100644 libtmux/src/main/java/io/github/libtmux/Program.java create mode 100644 libtmux/src/main/java/io/github/libtmux/ProgramExit.java create mode 100644 libtmux/src/main/java/io/github/libtmux/ProgramResult.java create mode 100644 libtmux/src/main/java/io/github/libtmux/ProgramSpec.java create mode 100644 libtmux/src/test/java/io/github/libtmux/ProgramTest.java diff --git a/CHANGELOG.md b/CHANGELOG.md index df95979db..57d22fdbb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,13 @@ release that first shipped the module. ## Unreleased +### Added + +- **JVM callers can own an interactive terminal program.** Java, Kotlin, + Clojure and the direct, Cats Effect and Ox Scala APIs let a caller send + input, inspect the visible screen and wait for the exit reported by tmux. + Closing the owner cleans up the application's session. (#172) + ### Changed - **The API examples start their own tmux server.** The Java, Kotlin, Scala diff --git a/README.md b/README.md index 97615e16d..ed91a7bb5 100644 --- a/README.md +++ b/README.md @@ -300,6 +300,10 @@ ran.exitStatus().getAsInt(); // → 3 ran.output(); // → [built] ``` +To send input while an application is running, [start an interactive +program](libtmux/README.md#run-an-interactive-application). Its scope owns +the pane. You can read its final screen and the exit that tmux reports. + ### [`Pane.resize`][pane-resize]: change a size [`Pane.resize`][pane-resize] grows a pane by a number of cells toward a diff --git a/docs/guide/clojure-api.md b/docs/guide/clojure-api.md index 9430207ae..804cdc869 100644 --- a/docs/guide/clojure-api.md +++ b/docs/guide/clojure-api.md @@ -748,6 +748,21 @@ channel until [`signal-channel!`][api:libtmux.core/signal-channel!] releases it. - Channels: [`await-channel!`][api:libtmux.core/await-channel!], [`signal-channel!`][api:libtmux.core/signal-channel!] +**Terminal applications.** [`start-program!`][api:libtmux.core/start-program!] +acquires an owner for a +literal executable and its arguments. +[`program-pane`][api:libtmux.core/program-pane] exposes its pane. +[`wait-program!`][api:libtmux.core/wait-program!] observes exit without stopping +it, [`terminate-program!`][api:libtmux.core/terminate-program!] +closes the session, and [`run-program!`][api:libtmux.core/run-program!] starts, +observes and closes it. + +- Acquire: [`start-program!`][api:libtmux.core/start-program!], +[`program-pane`][api:libtmux.core/program-pane] +- Observe and close: [`wait-program!`][api:libtmux.core/wait-program!], +[`terminate-program!`][api:libtmux.core/terminate-program!], +[`run-program!`][api:libtmux.core/run-program!] + **Running a command.** Anything tmux can do that is not above is reachable by running a command directly. [`raw!`][api:libtmux.core/raw!] runs one tmux argv with no shell and @@ -794,6 +809,13 @@ Pastes an explicit buffer into a pane. [`set-buffer!`][api:libtmux.core/set-buffer!] supplies contents; [`await-text!`][api:libtmux.core/await-text!] observes pane output. +### [`libtmux.core/program-pane`][libtmux.core] + +`(program-pane program)` + +Returns the original pane for input and [`capture!`][api:libtmux.core/capture!] +while the owner is open. + ### [`libtmux.core/raw!`][libtmux.core] `(raw! server argv)` @@ -834,6 +856,17 @@ Resizes a window or pane to positive cell dimensions. [`apply-layout!`][api:libtmux.core/apply-layout!] arranges all panes in a window. +### [`libtmux.core/run-program!`][libtmux.core] + +`(run-program! options timeout)` + +Starts a private program, observes exit, and closes the owner before returning. +Accepts the options from [`start-program!`][api:libtmux.core/start-program!] and +a positive observation timeout. +Returns `:program/exit` data and `:program/screen` as visible lines. +In [`libtmux.async/submit!`][api:libtmux.async/submit!], use `:kind :wait`. +Cancelling the task waits for cleanup. + ### [`libtmux.core/run-shell!`][libtmux.core] `(run-shell! server command)` @@ -963,6 +996,21 @@ and throws if the server still answers or a program left another one in it. Unlike [`open!`][api:libtmux.core/open!], which owns only a client. +### [`libtmux.core/start-program!`][libtmux.core] + +`(start-program! options)` + +`(start-program! server options)` + +Starts an application and returns its owner for `with-open`. +Supply `:executable` and optional `:args` vector, `:directory`, `:environment` +string map and `:size` pair of columns and rows. Arguments pass literally. +`:launch` takes the options from [`start!`][api:libtmux.core/start!] for a +private server. With a server +argument, the program borrows it and closes only its own session. +[`program-pane`][api:libtmux.core/program-pane] gives access to the pane inside +the scope. + ### [`libtmux.core/switch-client!`][libtmux.core] `(switch-client! client session)` @@ -971,6 +1019,13 @@ Switches an explicit client to a session. [`detach-client!`][api:libtmux.core/detach-client!] disconnects a client instead of switching its session. +### [`libtmux.core/terminate-program!`][libtmux.core] + +`(terminate-program! program)` + +Closes the owner and its session. As with `with-open`, a borrowed server stays +open. + ### [`libtmux.core/unlink-window!`][libtmux.core] `(unlink-window! window)` @@ -1001,6 +1056,14 @@ Removes an explicit hook. Removes a local option override. [`options!`][api:libtmux.core/options!] can read the resulting effective value. +### [`libtmux.core/wait-program!`][libtmux.core] + +`(wait-program! program timeout)` + +Observes the original program within a positive Duration. +Timeout and interruption leave the program under its owner. For a bounded +[`libtmux.async/submit!`][api:libtmux.async/submit!] task, use `:kind :wait`. + ### [`libtmux.core/windows!`][libtmux.core] `(windows! server)` @@ -1431,6 +1494,8 @@ deliveries have drained. #libtmuxcorepanes [api:libtmux.core/paste-buffer!]: #libtmuxcorepaste-buffer +[api:libtmux.core/program-pane]: + #libtmuxcoreprogram-pane [api:libtmux.core/raw!]: #libtmuxcoreraw [api:libtmux.core/refresh!]: @@ -1441,6 +1506,8 @@ deliveries have drained. #libtmuxcorerename [api:libtmux.core/resize!]: #libtmuxcoreresize +[api:libtmux.core/run-program!]: + #libtmuxcorerun-program [api:libtmux.core/run-shell!]: #libtmuxcorerun-shell [api:libtmux.core/select!]: @@ -1469,8 +1536,12 @@ deliveries have drained. #libtmuxcoresplit-pane [api:libtmux.core/start!]: #libtmuxcorestart +[api:libtmux.core/start-program!]: + #libtmuxcorestart-program [api:libtmux.core/switch-client!]: #libtmuxcoreswitch-client +[api:libtmux.core/terminate-program!]: + #libtmuxcoreterminate-program [api:libtmux.core/unlink-window!]: #libtmuxcoreunlink-window [api:libtmux.core/unset-environment!]: @@ -1479,6 +1550,8 @@ deliveries have drained. #libtmuxcoreunset-hook [api:libtmux.core/unset-option!]: #libtmuxcoreunset-option +[api:libtmux.core/wait-program!]: + #libtmuxcorewait-program [api:libtmux.core/windows!]: #libtmuxcorewindows [api:libtmux.data]: diff --git a/integration-tests/src/test/clojure/libtmux/private_server_test.clj b/integration-tests/src/test/clojure/libtmux/private_server_test.clj index 035648a91..2662464dc 100644 --- a/integration-tests/src/test/clojure/libtmux/private_server_test.clj +++ b/integration-tests/src/test/clojure/libtmux/private_server_test.clj @@ -1,8 +1,10 @@ (ns libtmux.private-server-test (:require [clojure.test :refer [deftest is]] + [libtmux.async :as async] [libtmux.core :as tm]) (:import [java.nio.file Files Path] - [java.nio.file.attribute FileAttribute])) + [java.nio.file.attribute FileAttribute] + [java.time Duration])) (defn- ^Path test-root [] (let [base (Path/of "/tmp/libtmux-java-test" (make-array String 0))] @@ -13,6 +15,11 @@ (cond-> {:root root} (System/getProperty "libtmux.tmux") (assoc :binary (System/getProperty "libtmux.tmux")))) +(defn- expected-exit? [status exit] + (contains? #{{:program/outcome :exited :program/status status} + {:program/outcome :unavailable :program/reason :status-missing}} + exit)) + (deftest a-started-server-answers-and-close-removes-its-directory (let [root (test-root) server (tm/start! (options root)) @@ -33,3 +40,57 @@ (is (= :tmux/validation (:tmux/error (ex-data error)))) (is (= 0 (count (iterator-seq (.iterator (Files/list root)))))) (Files/delete root))) + +(deftest a-program-observation-timeout-keeps-the-program-open + (let [root (test-root)] + (try + (with-open [program (tm/start-program! + {:executable "/bin/sh" + :args ["-c" "read answer; printf 'answer: %s\\n' \"$answer\"; exit 7"] + :launch (options root)})] + (is (= {:program/outcome :timed-out} + (tm/wait-program! program (Duration/ofMillis 150)))) + (let [pane (tm/program-pane program)] + (tm/send-literal! pane "computed") + (tm/send-keys! pane ["Enter"]) + (is (expected-exit? 7 (tm/wait-program! program (Duration/ofSeconds 5)))) + (is (some #{"answer: computed"} (tm/capture! pane))))) + (finally (Files/delete root))))) + +(deftest an-owned-run-returns-the-exit-observation-and-screen + (let [root (test-root)] + (try + (let [result (tm/run-program! + {:executable "/bin/sh" :args ["-c" "printf 'built\\n'; exit 7"] + :launch (options root)} + (Duration/ofSeconds 5))] + (is (expected-exit? 7 (:program/exit result))) + (is (some #{"built"} (:program/screen result)))) + (finally (Files/delete root))))) + +(deftest cancelling-an-owned-task-settles-after-application-cleanup + (let [root (test-root) + marker (.resolve root "started") + links (make-array java.nio.file.LinkOption 0)] + (try + (with-open [^libtmux.async.AsyncRuntime runtime (async/runtime! {:max-running 2})] + (let [run (async/submit! + runtime {:kind :wait} + #(tm/run-program! + {:executable "/bin/sh" + :args ["-c" "touch \"$1\"; exec sleep 30" "worker" (str marker)] + :launch (options root)} + (Duration/ofSeconds 20)))] + (is (loop [attempts 200] + (cond + (Files/exists marker links) true + (zero? attempts) false + :else (do (Thread/sleep 15) (recur (dec attempts)))))) + (is (true? (async/cancel! run))) + (let [failure (try (deref run 5000 ::timeout) (catch Exception e e))] + (is (= :cancelled (:tmux/error (ex-data failure))))) + (with-open [children (Files/list root)] + (is (= [marker] (vec (.toList children))))))) + (finally + (Files/deleteIfExists marker) + (Files/delete root))))) diff --git a/integration-tests/src/test/scala/io/github/libtmux/scaladsl/ox/OxProgramSuite.scala b/integration-tests/src/test/scala/io/github/libtmux/scaladsl/ox/OxProgramSuite.scala new file mode 100644 index 000000000..e63080770 --- /dev/null +++ b/integration-tests/src/test/scala/io/github/libtmux/scaladsl/ox/OxProgramSuite.scala @@ -0,0 +1,67 @@ +package io.github.libtmux.scaladsl.ox + +import _root_.ox.{fork, forkCancellable, supervised, useCloseableInScope} +import io.github.libtmux.ProgramExit.{Exited, Unavailable} +import io.github.libtmux.ProgramExit.Unavailable.Reason.STATUS_MISSING +import io.github.libtmux.scaladsl.* +import io.github.libtmux.scaladsl.fixture.OwnedTmux +import java.util.concurrent.{CountDownLatch, TimeUnit} +import munit.FunSuite +import scala.concurrent.duration.* +import scala.util.Using + +final class OxProgramSuite extends FunSuite { + + test( + "a supervised program outlives its waiter and leaves a borrowed server alive" + ) { + OwnedTmux.use { fixture => + Using.resource(Server.open(fixture.config)) { server => + val neighbors = server.sessions().map(_.id) + val spec = Program.Spec( + "/bin/sh", + Seq( + "-c", + "IFS= read -r answer; printf 'ANSWER=%s\\n' \"$answer\"; exit 7" + ) + ) + supervised { + val program = useCloseableInScope(Program.start(server, spec)) + val started = new CountDownLatch(1) + val wait = forkCancellable { + started.countDown() + program.awaitExit(30.seconds) + } + assert( + started.await(5, TimeUnit.SECONDS), + "the observer did not start" + ) + wait.cancel() + val exit = fork { program.awaitExit(5.seconds) } + program.pane.sendLine("42") + val observed = exit.join() + val version = server.version() + assert( + observed.equals(new Exited(7)) || + (version.toString == "3.4" && observed.equals( + new Unavailable(STATUS_MISSING) + )), + s"tmux $version reported $observed" + ) + assert(program.pane.capture().contains("ANSWER=42")) + } + assertEquals(server.sessions().map(_.id), neighbors) + + val failure = new IllegalStateException("application scope failed") + val reported = intercept[IllegalStateException] { + supervised { + useCloseableInScope(Program.start(server, spec)) + throw failure + } + } + assert(reported eq failure) + assertEquals(server.sessions().map(_.id), neighbors) + } + } + } +} diff --git a/libtmux-clojure/CHANGELOG.md b/libtmux-clojure/CHANGELOG.md index b42b3e787..217e22a68 100644 --- a/libtmux-clojure/CHANGELOG.md +++ b/libtmux-clojure/CHANGELOG.md @@ -25,3 +25,6 @@ CI, and release tooling, are in the [main changelog](../CHANGELOG.md). possible partial effects. (#20) - **`libtmux.core/start!` starts a private tmux server for `with-open`.** Closing it stops tmux and removes its directory. (#142) +- **`start-program!` owns an application for `with-open`.** Observe its exit + as data with `wait-program!`, or use `run-program!` to return the exit and + screen after cleanup. (#172) diff --git a/libtmux-clojure/README.md b/libtmux-clojure/README.md index 77182b553..0b8789daf 100644 --- a/libtmux-clojure/README.md +++ b/libtmux-clojure/README.md @@ -84,6 +84,39 @@ also stops the tmux server it started and removes that server's directory. - [`libtmux.control`][control-api] — explicit control replies and owned output subscriptions. +## Run an interactive terminal application + +`start-program!` starts a literal executable and argument vector. Keep the +owner in `with-open` and use `program-pane` to send input and read the screen. +An observation timeout leaves that owner available for another wait. +When tmux omits the exit status, the wait reports `:status-missing`. + + +```clojure +(require '[libtmux.core :as tm]) +(import '[java.time Duration]) + +(with-open [server (tm/start!) + program (tm/start-program! + server {:executable "/bin/sh" + :args ["-c" "read answer; printf 'built\\n'; exit 7"]})] + (let [first-look (tm/wait-program! program (Duration/ofMillis 150)) + pane (tm/program-pane program)] + (tm/send-literal! pane "continue") + (tm/send-keys! pane ["Enter"]) + (let [exit (tm/wait-program! program (Duration/ofSeconds 5))] + [(:program/outcome first-look) + (or (= 7 (:program/status exit)) + (= :status-missing (:program/reason exit))) + (boolean (some #{"built"} (tm/capture! pane)))]))) +;; => [:timed-out true true] +``` + +Pass just the options map to start on a private server. `run-program!` +returns `:program/exit` and `:program/screen` after closing that private scope. +For asynchronous observation or owning runs, submit to the bounded +[`libtmux.async` runtime][async-api] with `{:kind :wait}`. + ## Run complete programs The [Clojure API programs][programs] include their imports, entry points, diff --git a/libtmux-clojure/src/main/clojure/libtmux/core.clj b/libtmux-clojure/src/main/clojure/libtmux/core.clj index 553c1e454..f274afd56 100644 --- a/libtmux-clojure/src/main/clojure/libtmux/core.clj +++ b/libtmux-clojure/src/main/clojure/libtmux/core.clj @@ -215,7 +215,9 @@ (:require [libtmux.data :as data]) (:import [io.github.libtmux Server ServerEndpoint Session Window Pane Client ServerLaunch SessionSpec SessionSpec$Builder WindowSpec WindowSpec$Builder - SplitSpec SplitSpec$Builder CaptureSpec Dimensions Options Environment Hooks BufferInfo] + SplitSpec SplitSpec$Builder CaptureSpec Dimensions Options Environment Hooks BufferInfo + Program ProgramSpec ProgramExit$Exited ProgramExit$Signalled ProgramExit$TimedOut + ProgramExit$Unavailable] [io.github.libtmux.exception LibTmuxException TargetGoneException ServerUnavailableException UnsupportedFeatureException ServerClosedException] [io.github.libtmux.exception DispatchException$TimedOut DispatchException] @@ -296,11 +298,11 @@ (defn- execute! [operation kind f] (io! - (when (and *execution-check* (not= :close operation)) + (when (and *execution-check* (not (#{:close :terminate-program} operation))) (*execution-check* {:operation operation :kind kind})) (try (f) (catch LibTmuxException failure - (throw (translate operation (= kind :mutation) failure))) + (throw (translate operation (or (= kind :mutation) (= operation :run-program)) failure))) (catch IllegalArgumentException failure (if (and (#{:link-window :move-window :join-pane :switch-client} operation) (#{"handles belong to different tmux servers" @@ -312,7 +314,7 @@ :tmux/effects :none} failure)) (throw failure))) (catch ServerClosedException failure - (throw (translate operation (= kind :mutation) failure)))))) + (throw (translate operation (or (= kind :mutation) (= operation :run-program)) failure)))))) (defn error-summary "Returns fixed error metadata without arguments or cause messages. @@ -435,6 +437,14 @@ [[delete-buffer!]], [[paste-buffer!]] - Channels: [[await-channel!]], [[signal-channel!]] + **Terminal applications.** [[start-program!]] acquires an owner for a + literal executable and its arguments. [[program-pane]] exposes its pane. + [[wait-program!]] observes exit without stopping it, [[terminate-program!]] + closes the session, and [[run-program!]] starts, observes and closes it. + + - Acquire: [[start-program!]], [[program-pane]] + - Observe and close: [[wait-program!]], [[terminate-program!]], [[run-program!]] + **Running a command.** Anything tmux can do that is not above is reachable by running a command directly. [[raw!]] runs one tmux argv with no shell and returns its exit status and streams, and [[run-shell!]] runs a shell command @@ -464,6 +474,15 @@ (when-let [x (:timeout options)] (.defaultTimeout builder x)) (.build builder))))) +(defn- ^ServerLaunch server-launch [operation options] + (closed! operation options {:binary string? :config-file path? :root path? :timeout duration?}) + (let [builder (ServerLaunch/builder)] + (when-let [x (:binary options)] (.binary builder x)) + (when-let [x (:config-file options)] (.configFile builder (path x))) + (when-let [x (:root options)] (.root builder (path x))) + (when-let [x (:timeout options)] (.timeout builder x)) + (.build builder))) + (defn ^Server start! "Starts a private tmux server that the returned Server owns. The server has a directory of its own, an empty config unless `:config-file` names one, @@ -475,14 +494,89 @@ Unlike [[open!]], which owns only a client." ([] (start! {})) ([options] - (closed! :start options {:binary string? :config-file path? :root path? :timeout duration?}) - (execute! :start :mutation - #(let [builder (ServerLaunch/builder)] - (when-let [x (:binary options)] (.binary builder x)) - (when-let [x (:config-file options)] (.configFile builder (path x))) - (when-let [x (:root options)] (.root builder (path x))) - (when-let [x (:timeout options)] (.timeout builder x)) - (Server/start (.build builder)))))) + (let [launch (server-launch :start options)] + (execute! :start :mutation #(Server/start launch))))) + +(defn- ^ProgramSpec program-spec [operation options] + (closed! operation options + {:executable string? :args #(and (vector? %) (every? string? %)) + :directory path? :environment environment? :launch map? + :size #(and (vector? %) (= 2 (count %)) (every? positive-int? %))}) + (require! operation (string? (:executable options))) + (try + (let [builder (ProgramSpec/builder (:executable options))] + (when-let [args (:args options)] (.args builder args)) + (when-let [directory (:directory options)] (.in builder (path directory))) + (when-let [environment (:environment options)] (.environment builder environment)) + (when-let [[width height] (:size options)] (.sized builder (Dimensions. (int width) (int height)))) + (.build builder)) + (catch IllegalArgumentException _ (invalid! operation)))) + +(defn- program-exit [exit] + (cond + (instance? ProgramExit$Exited exit) + {:program/outcome :exited :program/status (.status ^ProgramExit$Exited exit)} + (instance? ProgramExit$Signalled exit) + {:program/outcome :signalled :program/signal (.signal ^ProgramExit$Signalled exit)} + (instance? ProgramExit$TimedOut exit) {:program/outcome :timed-out} + (instance? ProgramExit$Unavailable exit) + {:program/outcome :unavailable + :program/reason (case (.name (.reason ^ProgramExit$Unavailable exit)) + "SERVER_GONE" :server-gone + "PANE_GONE" :pane-gone + "PROCESS_REPLACED" :process-replaced + "STATUS_MISSING" :status-missing)})) + +(defn ^Program start-program! + "Starts an application and returns its owner for `with-open`. + Supply `:executable` and optional `:args` vector, `:directory`, `:environment` + string map and `:size` pair of columns and rows. Arguments pass literally. + `:launch` takes the options from [[start!]] for a private server. With a server + argument, the program borrows it and closes only its own session. + [[program-pane]] gives access to the pane inside the scope." + ([options] + (let [spec (program-spec :start-program options) + launch (server-launch :start-program (get options :launch {}))] + (execute! :start-program :mutation #(Program/start launch spec)))) + ([server options] + (let [^Server server (ref! :start-program server [Server]) + spec (program-spec :start-program options)] + (require! :start-program (not (contains? options :launch))) + (execute! :start-program :mutation #(Program/start server spec))))) + +(defn ^Pane program-pane + "Returns the original pane for input and [[capture!]] while the owner is open." + [program] + (.pane ^Program (ref! :program-pane program [Program]))) + +(defn wait-program! + "Observes the original program within a positive Duration. + Timeout and interruption leave the program under its owner. For a bounded + [[libtmux.async/submit!]] task, use `:kind :wait`." + [program timeout] + (require! :wait-program (duration? timeout)) + (let [^Program program (ref! :wait-program program [Program])] + (execute! :wait-program :wait #(program-exit (.awaitExit program timeout))))) + +(defn run-program! + "Starts a private program, observes exit, and closes the owner before returning. + Accepts the options from [[start-program!]] and a positive observation timeout. + Returns `:program/exit` data and `:program/screen` as visible lines. + In [[libtmux.async/submit!]], use `:kind :wait`. Cancelling the task waits for cleanup." + [options timeout] + (require! :run-program (duration? timeout)) + (let [spec (program-spec :run-program options) + launch (server-launch :run-program (get options :launch {}))] + (execute! :run-program :wait + #(let [result (Program/run launch spec timeout)] + {:program/exit (program-exit (.exit result)) + :program/screen (vec (.screen result))})))) + +(defn terminate-program! + "Closes the owner and its session. As with `with-open`, a borrowed server stays open." + [program] + (let [^Program program (ref! :terminate-program program [Program])] + (execute! :terminate-program :mutation #(.close program)))) (defn snapshot! "Acquires an eager captured graph from an explicit server. Traverse one observation with [[libtmux.data/windows]] and [[libtmux.data/panes]]." diff --git a/libtmux-kotlin/CHANGELOG.md b/libtmux-kotlin/CHANGELOG.md index dfbfe164e..9426f0fec 100644 --- a/libtmux-kotlin/CHANGELOG.md +++ b/libtmux-kotlin/CHANGELOG.md @@ -16,6 +16,10 @@ changelog](../CHANGELOG.md). ### Added +- **`withProgram` scopes a terminal application to a coroutine.** Await exit + without stopping the application, or use `runProgram` for an owning run + that returns its exit and screen after cleanup. (#172) + - **`Server.start` and `withPrivateServer` scope a private tmux server.** The block's server is stopped and its directory removed however the block ends. (#142) diff --git a/libtmux-kotlin/README.md b/libtmux-kotlin/README.md index 25accc6ea..c9f57d128 100644 --- a/libtmux-kotlin/README.md +++ b/libtmux-kotlin/README.md @@ -211,6 +211,47 @@ withServer(config) { server -> } ``` +## Run an interactive terminal application + +`withProgram` owns the application session for the block. An exit +observation can time out or be cancelled while the application keeps running. +Closing the scope ends the application and releases its session. +When tmux omits the exit status, the wait reports `STATUS_MISSING`. + + +```kotlin +import io.github.libtmux.ProgramExit +import io.github.libtmux.ProgramSpec +import io.github.libtmux.kotlin.capture +import io.github.libtmux.kotlin.sendLine +import io.github.libtmux.kotlin.withProgram +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.seconds +import kotlinx.coroutines.runBlocking + +fun main() = runBlocking { + val spec = ProgramSpec.builder("/bin/sh") + .args(listOf("-c", "read answer; printf 'built\\n'; exit 7")) + .build() + withProgram(spec) { program -> + check(program.awaitExit(150.milliseconds) is ProgramExit.TimedOut) + program.pane.sendLine("continue") + val exit = program.awaitExit(5.seconds) + check(when (exit) { + is ProgramExit.Exited -> exit.status() == 7 + is ProgramExit.Unavailable -> + exit.reason() == ProgramExit.Unavailable.Reason.STATUS_MISSING + else -> false + }) + println(program.pane.capture().first { it == "built" }) + } +} +``` + +The program prints `built`. Use `server.withProgram(spec)` inside an existing +server scope to keep that server alive. `runProgram(spec, timeout)` returns +the exit and screen after closing its private scope. + ## Query with typed fields ### [`Pane.command`][text-field]: fields live on the companion diff --git a/libtmux-kotlin/api/libtmux-kotlin.api b/libtmux-kotlin/api/libtmux-kotlin.api index 830b88d78..534a534cc 100644 --- a/libtmux-kotlin/api/libtmux-kotlin.api +++ b/libtmux-kotlin/api/libtmux-kotlin.api @@ -308,6 +308,19 @@ public final class io/github/libtmux/kotlin/PaneOperationsKt { public static final fun variables (Lio/github/libtmux/kotlin/Pane;Ljava/util/List;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; } +public final class io/github/libtmux/kotlin/Program { + public final fun awaitExit-VtjQ1oo (JLkotlin/coroutines/Continuation;)Ljava/lang/Object; + public final fun getPane ()Lio/github/libtmux/kotlin/Pane; +} + +public final class io/github/libtmux/kotlin/ProgramKt { + public static final fun runProgram-WPwdCS8 (Lio/github/libtmux/ProgramSpec;JLio/github/libtmux/ServerLaunch;Lio/github/libtmux/kotlin/ExecutionPolicy;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public static synthetic fun runProgram-WPwdCS8$default (Lio/github/libtmux/ProgramSpec;JLio/github/libtmux/ServerLaunch;Lio/github/libtmux/kotlin/ExecutionPolicy;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; + public static final fun withProgram (Lio/github/libtmux/ProgramSpec;Lio/github/libtmux/ServerLaunch;Lio/github/libtmux/kotlin/ExecutionPolicy;Lkotlin/jvm/functions/Function2;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public static final fun withProgram (Lio/github/libtmux/kotlin/Server;Lio/github/libtmux/ProgramSpec;Lkotlin/jvm/functions/Function2;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public static synthetic fun withProgram$default (Lio/github/libtmux/ProgramSpec;Lio/github/libtmux/ServerLaunch;Lio/github/libtmux/kotlin/ExecutionPolicy;Lkotlin/jvm/functions/Function2;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; +} + public final class io/github/libtmux/kotlin/Prompt { public fun equals (Ljava/lang/Object;)Z public final fun getAsJava ()Lio/github/libtmux/Prompt; diff --git a/libtmux-kotlin/src/main/kotlin/io/github/libtmux/kotlin/ExecutionPolicy.kt b/libtmux-kotlin/src/main/kotlin/io/github/libtmux/kotlin/ExecutionPolicy.kt index 688e2c8ac..a41493006 100644 --- a/libtmux-kotlin/src/main/kotlin/io/github/libtmux/kotlin/ExecutionPolicy.kt +++ b/libtmux-kotlin/src/main/kotlin/io/github/libtmux/kotlin/ExecutionPolicy.kt @@ -10,8 +10,9 @@ import kotlinx.coroutines.Dispatchers * * Two independently sized pools, not one: [commands] backs every `suspend` operation this module * generates or hand-writes, sized from the transport's own admission bound rather than a guess. - * [streamReads] backs only what still genuinely blocks a thread — [Server.liveState]'s background - * pump. [ControlClient.output] and [ControlClient.events] hold no thread from either pool; they are + * [streamReads] backs the [Server.liveState] pump and [Program.awaitExit] so application + * observations leave capacity for input. [ControlClient.output] and [ControlClient.events] hold + * no thread from either pool. They are * built on [io.github.libtmux.control.EventSubscription.poll] and `onReady`, not on a blocking read. */ public class ExecutionPolicy( diff --git a/libtmux-kotlin/src/main/kotlin/io/github/libtmux/kotlin/Program.kt b/libtmux-kotlin/src/main/kotlin/io/github/libtmux/kotlin/Program.kt new file mode 100644 index 000000000..8cd8a931f --- /dev/null +++ b/libtmux-kotlin/src/main/kotlin/io/github/libtmux/kotlin/Program.kt @@ -0,0 +1,91 @@ +package io.github.libtmux.kotlin + +import io.github.libtmux.Program as JavaProgram +import io.github.libtmux.ProgramExit +import io.github.libtmux.ProgramResult +import io.github.libtmux.ProgramSpec +import io.github.libtmux.ServerConfig +import io.github.libtmux.ServerLaunch +import kotlin.time.Duration +import kotlin.time.toJavaDuration +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.runInterruptible +import kotlinx.coroutines.withContext + +/** Uses the application pane while its [withProgram] block owns it. */ +public class Program internal constructor( + private val java: JavaProgram, + private val policy: ExecutionPolicy, + server: Server? = null, +) { + public val pane: Pane = Pane(java.pane(), server ?: Server.fromJava(java.pane().server(), policy)) + + /** Cancels only the observation when the deadline passes or its coroutine is cancelled. */ + public suspend fun awaitExit(timeout: Duration): ProgramExit = + runInterruptible(policy.streamReads) { java.awaitExit(timeout.toJavaDuration()) } +} + +/** Runs [block] with a program and its private server, then closes them even on cancellation. */ +public suspend fun withProgram( + spec: ProgramSpec, + launch: ServerLaunch = ServerLaunch.builder().build(), + policy: ExecutionPolicy = ExecutionPolicy.default(ServerConfig.builder().build()), + block: suspend (Program) -> R, +): R = programScope(policy, null, { JavaProgram.start(launch, spec) }, block) + +/** Runs [block] on this server and closes the new session when the block ends. */ +public suspend fun Server.withProgram( + spec: ProgramSpec, + block: suspend (Program) -> R, +): R = programScope(policy, this, { JavaProgram.start(java, spec) }, block) + +/** Runs a private program, then closes it before resuming the caller. */ +public suspend fun runProgram( + spec: ProgramSpec, + timeout: Duration, + launch: ServerLaunch = ServerLaunch.builder().build(), + policy: ExecutionPolicy = ExecutionPolicy.default(ServerConfig.builder().build()), +): ProgramResult = try { + runInterruptible(policy.commands) { JavaProgram.run(launch, spec, timeout.toJavaDuration()) } +} catch (failure: RuntimeException) { + try { + currentCoroutineContext().ensureActive() + } catch (cancelled: CancellationException) { + if (cancelled !== failure) cancelled.addSuppressed(failure) + throw cancelled + } + throw failure +} + +private suspend fun programScope( + policy: ExecutionPolicy, + server: Server?, + acquire: () -> JavaProgram, + block: suspend (Program) -> R, +): R { + var owned: JavaProgram? = null + var primary: Throwable? = null + try { + currentCoroutineContext().ensureActive() + // Keep the owner before returning to a context that can discard a cancelled result. + withContext(NonCancellable + policy.commands) { owned = acquire() } + currentCoroutineContext().ensureActive() + return block(Program(checkNotNull(owned), policy, server)) + } catch (failure: Throwable) { + primary = failure + throw failure + } finally { + val program = owned + if (program != null) { + try { + withContext(NonCancellable + policy.commands) { program.close() } + } catch (failure: Throwable) { + if (primary == null) throw failure + primary.addSuppressed(failure) + } + } + } +} diff --git a/libtmux-kotlin/src/test/kotlin/io/github/libtmux/kotlin/PrivateServerTest.kt b/libtmux-kotlin/src/test/kotlin/io/github/libtmux/kotlin/PrivateServerTest.kt index 223d17fe2..235de9e86 100644 --- a/libtmux-kotlin/src/test/kotlin/io/github/libtmux/kotlin/PrivateServerTest.kt +++ b/libtmux-kotlin/src/test/kotlin/io/github/libtmux/kotlin/PrivateServerTest.kt @@ -5,13 +5,31 @@ import java.nio.file.Path import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue +import kotlin.test.fail import kotlinx.coroutines.runBlocking import org.junit.jupiter.api.Test import io.github.libtmux.ServerEndpoint import io.github.libtmux.ServerLaunch +import io.github.libtmux.ProgramExit +import io.github.libtmux.ProgramSpec +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.seconds +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.launch class PrivateServerTest { + private fun assertExit(expected: Int, exit: ProgramExit) { + when (exit) { + is ProgramExit.Exited -> assertEquals(expected, exit.status()) + is ProgramExit.Unavailable -> assertEquals(ProgramExit.Unavailable.Reason.STATUS_MISSING, exit.reason()) + else -> fail("expected process completion, got $exit") + } + } + private fun launch(): ServerLaunch { val root = Path.of("/tmp/libtmux-java-test") Files.createDirectories(root) @@ -46,4 +64,62 @@ class PrivateServerTest { assertEquals("deliberate", failure?.message) assertFalse(Files.exists(directory!!), "a throwing block left its server directory behind") } + + @Test + fun `cancelling observation leaves an interactive program running`() = runBlocking { + val spec = ProgramSpec.builder("/bin/sh") + .args(listOf("-c", "read answer; printf 'answer: %s\\n' \"\$answer\"; exit 7")) + .build() + val owned = launch() + try { + withProgram(spec, owned) { program -> + assertEquals(ProgramExit.TimedOut(), program.awaitExit(150.milliseconds)) + val observer = launch(start = CoroutineStart.UNDISPATCHED) { program.awaitExit(20.seconds) } + observer.cancelAndJoin() + program.pane.sendLine("computed") + assertExit(7, program.awaitExit(5.seconds)) + assertTrue("answer: computed" in program.pane.capture()) + } + } finally { + Files.delete(owned.root()) + } + } + + @Test + fun `cancelling the owner returns after the private socket is removed`() = runBlocking { + val owned = launch() + val started = CompletableDeferred() + val spec = ProgramSpec.builder("/bin/sleep").args(listOf("30")).build() + try { + val scope = launch { + withProgram(spec, owned) { program -> + val endpoint = program.pane.server.config.endpoint() as ServerEndpoint.SocketPath + started.complete(endpoint.path()) + awaitCancellation() + } + } + val socket = started.await() + assertTrue(Files.exists(socket)) + scope.cancelAndJoin() + assertFalse(Files.exists(socket)) + } finally { + Files.delete(owned.root()) + } + } + + @Test + fun `an owning run returns the exit observation and screen after closing`() = runBlocking { + val owned = launch() + val spec = ProgramSpec.builder("/bin/sh") + .args(listOf("-c", "printf 'built\\n'; exit 7")) + .build() + try { + val result = runProgram(spec, 5.seconds, owned) + assertExit(7, result.exit()) + assertTrue("built" in result.screen()) + Files.list(owned.root()).use { assertFalse(it.findAny().isPresent) } + } finally { + Files.delete(owned.root()) + } + } } diff --git a/libtmux-scala-cats/CHANGELOG.md b/libtmux-scala-cats/CHANGELOG.md index fcb787048..946f77b95 100644 --- a/libtmux-scala-cats/CHANGELOG.md +++ b/libtmux-scala-cats/CHANGELOG.md @@ -16,6 +16,9 @@ changelog](../CHANGELOG.md). ### Added +- **`Program.start` and `Server.program` own application resources.** Cancel + an exit wait independently of the application owner. (#172) + - **`Server.start[F]` is a `Resource` over a private tmux server.** Releasing it stops tmux and removes its directory. (#142) diff --git a/libtmux-scala-cats/README.md b/libtmux-scala-cats/README.md index 0ba337179..a0273988a 100644 --- a/libtmux-scala-cats/README.md +++ b/libtmux-scala-cats/README.md @@ -65,6 +65,47 @@ Server.resource[IO](config).use { server => It prints the current command of each active pane. +## Run a terminal application + +### [`Program.start`][program]: own the application in a `Resource` + +Cancelling an exit wait leaves the application available for more input. +Cancelling the owner’s `use` releases the application before returning. +Use [`server.program(spec)`][server] to own a session on an existing server. + + +```scala +import _root_.cats.effect.IO +import io.github.libtmux.ProgramExit.{Exited, Unavailable} +import io.github.libtmux.ProgramExit.Unavailable.Reason.STATUS_MISSING +import io.github.libtmux.scaladsl as direct +import io.github.libtmux.scaladsl.cats.* +import scala.concurrent.duration.* + +val spec = direct.Program.Spec( + "/bin/sh", + Seq("-c", """IFS= read -r n; printf 'ANSWER=%s\n' "$n"; exit 7""") +) +Program.start[IO](spec).use { program => + for { + _ <- program.pane.sendLine("42") + exit <- program.awaitExit(5.seconds) + screen <- program.pane.capture() + _ <- IO { + assert(exit.equals(new Exited(7)) || + exit.equals(new Unavailable(STATUS_MISSING))) + assert(screen.contains("ANSWER=42")) + } + } yield () +} +``` + +Run this example against the artifacts built from this checkout. + +```console +$ ./gradlew :docs:test --tests '*DocumentationSuite.*cats-program' +``` + ## Observe tmux change ### [`Control.attach`][control]: observe a session rename @@ -180,3 +221,5 @@ block. [reference]: https://libtmux.org/en/scala/latest/reference/ [server]: https://libtmux.org/en/scala/latest/reference/io-github-libtmux-scaladsl-cats-server/ [shell]: https://libtmux.org/en/scala/latest/reference/io-github-libtmux-scaladsl-cats-shell/ + +[program]: src/main/scala/io/github/libtmux/scaladsl/cats/Program.scala diff --git a/libtmux-scala-cats/src/main/scala/io/github/libtmux/scaladsl/cats/Execution.scala b/libtmux-scala-cats/src/main/scala/io/github/libtmux/scaladsl/cats/Execution.scala index eead50901..63e4babea 100644 --- a/libtmux-scala-cats/src/main/scala/io/github/libtmux/scaladsl/cats/Execution.scala +++ b/libtmux-scala-cats/src/main/scala/io/github/libtmux/scaladsl/cats/Execution.scala @@ -21,6 +21,10 @@ private[cats] final class Execution[F[_]] private[cats] ( def apply[A](operation: => A): F[A] = supervise(total.permit.use(_ => F.interruptible(operation))) + // A finalizer shares the admission bound and can run as its supervisor closes. + def release(operation: => Unit): F[Unit] = + total.permit.use(_ => F.blocking(operation)) + def waiting[A](operation: => A): F[A] = waiters match { case None => F.raiseError( diff --git a/libtmux-scala-cats/src/main/scala/io/github/libtmux/scaladsl/cats/Program.scala b/libtmux-scala-cats/src/main/scala/io/github/libtmux/scaladsl/cats/Program.scala new file mode 100644 index 000000000..3a321ef5c --- /dev/null +++ b/libtmux-scala-cats/src/main/scala/io/github/libtmux/scaladsl/cats/Program.scala @@ -0,0 +1,46 @@ +package io.github.libtmux.scaladsl.cats + +import _root_.cats.effect.{Async, Resource} +import io.github.libtmux.{Program as JavaProgram, ProgramExit, ServerLaunch} +import io.github.libtmux.scaladsl as direct +import io.github.libtmux.scaladsl.server +import scala.concurrent.duration.FiniteDuration + +/** Owns an application for the lifetime of its `Resource`. */ +final class Program[F[_]] private[cats] ( + underlying: direct.Program, + server: Server[F] +) { + + /** The existing pane handle, with operations running in `F`. */ + val pane: Pane[F] = server.pane(underlying.pane) + + /** Observes exit through the server's bounded wait policy. Cancelling this + * effect leaves the application and its scope alive. + */ + def awaitExit(timeout: FiniteDuration): F[ProgramExit] = + server.execution.waiting(underlying.awaitExit(timeout)) + + /** The underlying Java owner. Its lifetime belongs to the resource. */ + def asJava: JavaProgram = underlying.asJava +} + +object Program { + + /** Runs a program on a private tmux server. Cancellation of `use` awaits + * release of the program and server. + */ + def start[F[_]: Async]( + spec: direct.Program.Spec, + launch: ServerLaunch = ServerLaunch.builder().build() + ): Resource[F, Program[F]] = + for { + execution <- Execution.resource[F](4) + owner <- owned(execution)(direct.Program.start(spec, launch)) + } yield new Program(owner, new Server(owner.pane.server, execution)) + + private[cats] def owned[F[_]: Async](execution: Execution[F])( + acquire: => direct.Program + ): Resource[F, direct.Program] = + Resource.make(execution(acquire))(owner => execution.release(owner.close())) +} diff --git a/libtmux-scala-cats/src/main/scala/io/github/libtmux/scaladsl/cats/Server.scala b/libtmux-scala-cats/src/main/scala/io/github/libtmux/scaladsl/cats/Server.scala index c7783b911..fc7dd638c 100644 --- a/libtmux-scala-cats/src/main/scala/io/github/libtmux/scaladsl/cats/Server.scala +++ b/libtmux-scala-cats/src/main/scala/io/github/libtmux/scaladsl/cats/Server.scala @@ -20,6 +20,15 @@ final class Server[F[_]] private[cats] ( /** The Java client this wraps: the one escape hatch, as on every handle. */ val asJava: JavaServer = underlying.asJava + /** Starts an application in a session this resource owns. Release removes the + * application and leaves this server and its other sessions available. + */ + def program(spec: direct.Program.Spec): Resource[F, Program[F]] = + Program.owned(execution)(direct.Program.start(underlying, spec)).map { + owner => + new Program(owner, this) + } + private[cats] def session(value: direct.Session): Session[F] = new Session(value, this) private[cats] def window(value: direct.Window): Window[F] = diff --git a/libtmux-scala-cats/src/test/scala/io/github/libtmux/scaladsl/cats/PrivateServerSuite.scala b/libtmux-scala-cats/src/test/scala/io/github/libtmux/scaladsl/cats/PrivateServerSuite.scala index 6059e9578..a1a0c7e01 100644 --- a/libtmux-scala-cats/src/test/scala/io/github/libtmux/scaladsl/cats/PrivateServerSuite.scala +++ b/libtmux-scala-cats/src/test/scala/io/github/libtmux/scaladsl/cats/PrivateServerSuite.scala @@ -1,10 +1,14 @@ package io.github.libtmux.scaladsl.cats -import _root_.cats.effect.IO +import _root_.cats.effect.{Deferred, IO} import _root_.cats.effect.unsafe.implicits.global +import io.github.libtmux.ProgramExit.{Exited, Unavailable} +import io.github.libtmux.ProgramExit.Unavailable.Reason.STATUS_MISSING import io.github.libtmux.{ServerEndpoint, ServerLaunch} +import io.github.libtmux.scaladsl as direct import java.nio.file.{Files, Path} import munit.FunSuite +import scala.concurrent.duration.* final class PrivateServerSuite extends FunSuite { private def launch(): ServerLaunch = { @@ -17,6 +21,61 @@ final class PrivateServerSuite extends FunSuite { .build() } + test( + "cancel an exit wait without ending the application, then cancel an owner" + ) { + val spec = direct.Program.Spec( + "/bin/sh", + Seq( + "-c", + "IFS= read -r answer; printf 'ANSWER=%s\\n' \"$answer\"; exit 7" + ) + ) + Server + .start[IO](launch()) + .use { server => + for { + _ <- server.newSession("anchor") + _ <- server.program(spec).use { program => + for { + wait <- program.awaitExit(30.seconds).start + _ <- IO.sleep(100.millis) + _ <- wait.cancel + outcome <- wait.join + _ <- IO(assert(outcome.isCanceled)) + _ <- program.pane.sendLine("42") + exit <- program.awaitExit(5.seconds) + screen <- program.pane.capture() + version <- server.version() + _ <- IO { + assert( + exit.equals(new Exited(7)) || + (version.toString == "3.4" && exit + .equals(new Unavailable(STATUS_MISSING))), + s"tmux $version reported $exit" + ) + assert(screen.contains("ANSWER=42")) + } + } yield () + } + started <- Deferred[IO, Unit] + owner <- server + .program(spec) + .use(_ => started.complete(()) *> IO.never[Unit]) + .start + _ <- started.get.timeout(5.seconds) + _ <- owner.cancel + outcome <- owner.join + sessions <- server.sessions() + _ <- IO { + assert(outcome.isCanceled) + assertEquals(sessions.map(_.name), Vector("anchor")) + } + } yield () + } + .unsafeRunSync() + } + test("the Resource ends the server and removes its directory on release") { val directory = Server .start[IO](launch()) diff --git a/libtmux-scala-ox/README.md b/libtmux-scala-ox/README.md index 6bf59977d..5eaa546d8 100644 --- a/libtmux-scala-ox/README.md +++ b/libtmux-scala-ox/README.md @@ -87,6 +87,43 @@ event it kept, or a gap naming how many were lost. split one sequence, gaps included, or the second would close the subscription under the first. +## Run a terminal application + +### [`Program.start`][program]: own the application in a supervised scope + +Ox scopes the direct Scala owner with `useCloseableInScope`. A fork can wait +for exit while the scope sends input through the application’s pane. Starting +on an existing server keeps that server and its other sessions available. + + +```scala +import _root_.ox.{fork, supervised, useCloseableInScope} +import io.github.libtmux.ProgramExit.{Exited, Unavailable} +import io.github.libtmux.ProgramExit.Unavailable.Reason.STATUS_MISSING +import io.github.libtmux.scaladsl.* +import scala.concurrent.duration.* + +val spec = Program.Spec( + "/bin/sh", + Seq("-c", """IFS= read -r n; printf 'ANSWER=%s\n' "$n"; exit 7""") +) +supervised { + val program = useCloseableInScope(Program.start(spec)) + val exit = fork { program.awaitExit(5.seconds) } + program.pane.sendLine("42") + val observed = exit.join() + assert(observed.equals(new Exited(7)) || + observed.equals(new Unavailable(STATUS_MISSING))) + assert(program.pane.capture().contains("ANSWER=42")) +} +``` + +Run this example against the artifacts built from this checkout. + +```console +$ ./gradlew :docs:test --tests '*DocumentationSuite.*ox-program' +``` + ## What it leaves out - **A handle type.** The facade's opaque handles work unchanged here. @@ -118,3 +155,5 @@ event it kept, or a gap naming how many were lost. src/main/scala/io/github/libtmux/scaladsl/ox/Flows.scala [javadoc]: https://javadoc.io/doc/io.github.libtmux/libtmux-scala-ox_3 [subscription]: https://libtmux.org/en/java/latest/reference/io-github-libtmux-control-eventsubscription-eventsubscription/ + +[program]: ../libtmux-scala/src/main/scala/io/github/libtmux/scaladsl/Program.scala diff --git a/libtmux-scala/CHANGELOG.md b/libtmux-scala/CHANGELOG.md index f23387a84..b301e533b 100644 --- a/libtmux-scala/CHANGELOG.md +++ b/libtmux-scala/CHANGELOG.md @@ -16,6 +16,9 @@ changelog](../CHANGELOG.md). ### Added +- **`Program.start` scopes a terminal application.** Send input through its + pane and observe the original process's typed exit. (#172) + - **`Server.start` starts a private tmux server for `Using.resource`.** Closing it stops tmux and removes its directory. (#142) diff --git a/libtmux-scala/README.md b/libtmux-scala/README.md index 761f06208..7b5447673 100644 --- a/libtmux-scala/README.md +++ b/libtmux-scala/README.md @@ -80,6 +80,45 @@ The operation closes its client and leaves tmux running. - A failed acquisition raises the original Java error. It does not become an empty vector. +## Run a terminal application + +### [`Program.start`][program]: own a process and its pane + +`Using.resource` closes the application session. Starting with a +[`Server`][server] argument borrows that server and keeps its other sessions +alive. The exit wait observes the process within a deadline. + + +```scala +import io.github.libtmux.ProgramExit.{Exited, Unavailable} +import io.github.libtmux.ProgramExit.Unavailable.Reason.STATUS_MISSING +import io.github.libtmux.scaladsl.* +import scala.concurrent.duration.* +import scala.util.Using + +val spec = Program.Spec( + "/bin/sh", + Seq("-c", """IFS= read -r n; printf 'ANSWER=%s\n' "$n"; exit 7""") +) +Using.resource(Program.start(spec)) { program => + program.pane.sendLine("42") + val exit = program.awaitExit(5.seconds) + assert(exit.equals(new Exited(7)) || + exit.equals(new Unavailable(STATUS_MISSING))) + assert(program.pane.capture().contains("ANSWER=42")) +} +``` + +Run this example against the artifacts built from this checkout. + +```console +$ ./gradlew :docs:test --tests '*DocumentationSuite.*direct-program' +``` + +When tmux omits the exit status, `STATUS_MISSING` records that outcome. +Change the expected row to `ANSWER=43` to check that the program rejects an +incorrect answer and still releases the owner. + ## What it leaves out - **A Scala 2.13 build.** There is none. @@ -132,3 +171,5 @@ repository's [migration notes](../MIGRATION.md). [source-server]: src/main/scala/io/github/libtmux/scaladsl/Server.scala [window]: https://libtmux.org/en/scala/latest/reference/io-github-libtmux-scaladsl-window/ + +[program]: src/main/scala/io/github/libtmux/scaladsl/Program.scala diff --git a/libtmux-scala/src/main/scala/io/github/libtmux/scaladsl/Program.scala b/libtmux-scala/src/main/scala/io/github/libtmux/scaladsl/Program.scala new file mode 100644 index 000000000..20cf76227 --- /dev/null +++ b/libtmux-scala/src/main/scala/io/github/libtmux/scaladsl/Program.scala @@ -0,0 +1,81 @@ +package io.github.libtmux.scaladsl + +import io.github.libtmux.{ + Dimensions, + Program as JavaProgram, + ProgramExit, + ProgramSpec as JavaSpec, + ServerLaunch +} +import java.nio.file.Path +import scala.concurrent.duration.FiniteDuration +import scala.jdk.CollectionConverters.* +import scala.jdk.DurationConverters.* + +/** An application owner suitable for `Using.resource`. Closing it ends its + * session and any private server it owns. + */ +opaque type Program <: AutoCloseable = JavaProgram + +object Program { + + /** A literal executable and its arguments, with optional launch overrides. */ + final case class Spec( + executable: String, + arguments: Seq[String] = Seq.empty, + directory: Option[Path] = None, + environment: Map[String, String] = Map.empty, + size: Option[Dimensions] = None + ) { + private[Program] def asJava: JavaSpec = { + val builder = JavaSpec + .builder(executable) + .args(arguments.asJava) + .environment(environment.asJava) + directory.foreach(builder.in) + size.foreach(builder.sized) + builder.build() + } + } + + /** The exit observation and visible screen left by an owning run. */ + final case class Result(exit: ProgramExit, screen: Vector[String]) + + /** Starts a program and owns its private tmux server. */ + def start( + spec: Spec, + launch: ServerLaunch = ServerLaunch.builder().build() + ): Program = + JavaProgram.start(launch, spec.asJava) + + /** Starts a program in its own session on the borrowed server. */ + def start(server: Server, spec: Spec): Program = + JavaProgram.start(server.asJava, spec.asJava) + + /** Runs a program, reads its visible screen and closes the owner before + * returning. Timeout bounds exit observation. + */ + def run( + spec: Spec, + timeout: FiniteDuration, + launch: ServerLaunch = ServerLaunch.builder().build() + ): Result = { + val result = JavaProgram.run(launch, spec.asJava, timeout.toJava) + Result(result.exit(), result.screen().asScala.toVector) + } + + extension (self: Program) { + + /** The existing pane handle for literal input and rendered screen reads. */ + def pane: Pane = Pane.wrap(self.pane()) + + /** Blocks the caller while observing exit. Interruption and timeout leave + * the application under its owner. + */ + def awaitExit(timeout: FiniteDuration): ProgramExit = + self.awaitExit(timeout.toJava) + + /** The underlying Java owner. */ + def asJava: JavaProgram = self + } +} diff --git a/libtmux-scala/src/test/scala/io/github/libtmux/scaladsl/PrivateServerSuite.scala b/libtmux-scala/src/test/scala/io/github/libtmux/scaladsl/PrivateServerSuite.scala index 328d1bce3..1557fa412 100644 --- a/libtmux-scala/src/test/scala/io/github/libtmux/scaladsl/PrivateServerSuite.scala +++ b/libtmux-scala/src/test/scala/io/github/libtmux/scaladsl/PrivateServerSuite.scala @@ -1,8 +1,11 @@ package io.github.libtmux.scaladsl +import io.github.libtmux.ProgramExit.{Exited, Unavailable} +import io.github.libtmux.ProgramExit.Unavailable.Reason.STATUS_MISSING import io.github.libtmux.{ServerEndpoint, ServerLaunch} import java.nio.file.{Files, Path} import munit.FunSuite +import scala.concurrent.duration.* import scala.util.Using final class PrivateServerSuite extends FunSuite { @@ -16,6 +19,39 @@ final class PrivateServerSuite extends FunSuite { .build() } + test( + "a private application accepts a line and retains its exit and screen until release" + ) { + val spec = Program.Spec( + "/bin/sh", + Seq( + "-c", + "IFS= read -r answer; printf 'ANSWER=%s\\n' \"$answer\"; exit 7" + ) + ) + val directory = Using.resource(Program.start(spec, launch())) { program => + program.pane.sendLine("42") + val exit = program.awaitExit(5.seconds) + val version = program.pane.server.version() + assert( + exit.equals(new Exited(7)) || + (version.toString == "3.4" && exit.equals( + new Unavailable(STATUS_MISSING) + )), + s"tmux $version reported $exit" + ) + assert(program.pane.capture().contains("ANSWER=42")) + program.pane.server.config.endpoint + .asInstanceOf[ServerEndpoint.SocketPath] + .path + .getParent + } + assert( + !Files.exists(directory), + "the application left its server directory behind" + ) + } + test("Using.resource ends the server and removes its directory") { var directory: Path = null val name = Using.resource(Server.start(launch())) { server => diff --git a/libtmux/CHANGELOG.md b/libtmux/CHANGELOG.md index e72b9684a..f891b4dd3 100644 --- a/libtmux/CHANGELOG.md +++ b/libtmux/CHANGELOG.md @@ -16,6 +16,11 @@ changelog](../CHANGELOG.md). ### Added +- **`Program.start` starts an owned terminal application.** Pass a literal + executable and arguments, observe exit separately from cleanup, and read the + rendered screen through the owned pane. Pass an existing server to keep it + and its other sessions after the application closes. (#172) + - **`Server.captureServer()` exposes one captured tmux graph.** Sessions, window links, pane occurrences and clients share the same observations and remain local to traverse. (#20) diff --git a/libtmux/README.md b/libtmux/README.md index 1562c8a27..e5f6e93ce 100644 --- a/libtmux/README.md +++ b/libtmux/README.md @@ -118,6 +118,56 @@ window.name(); // → build window.refresh().panes().size(); // → 2 ``` +## Run an interactive application + +Start an [application][program] with an executable path and its arguments. +It owns a terminal and a tmux session. Wait for a prompt, then send a reply. + +```java +import io.github.libtmux.Program; +import io.github.libtmux.ProgramSpec; +import io.github.libtmux.WakeReason; +import java.time.Duration; +import java.util.List; + +var spec = ProgramSpec.builder("/bin/sh") + .args(List.of("-c", """ + printf 'Name?\\n' + IFS= read -r name + printf 'Hello, %s\\n' "$name" + """)) + .build(); +var wait = Duration.ofSeconds(5); +boolean greeted; +try (var app = Program.start(spec)) { + var pane = app.pane(); + if (pane.await(p -> p.capture().contains("Name?"), wait) + != WakeReason.SIGNALLED) { + throw new IllegalStateException("the application did not ask for a name"); + } + pane.sendLine("tmux"); + app.awaitExit(wait); + greeted = pane.capture().contains("Hello, tmux"); +} +greeted; // → true +``` + +An exit wait leaves the application available after a deadline or +interruption. Closing the owner releases its private session and server. +Pass a running [server][server] to keep that server and its other sessions. + +For a single bounded run, the [owning call][program] returns the exit +observation and visible screen after it closes the application. + +tmux reports signal termination as a name or decimal number, such as +`TERM` or `15`. A launch shell can report its own exit status when it +cannot start the executable. The screen is still available when tmux reports +that the pane died without an exit status or signal. + +Standard output and standard error written to the terminal share the visible +rows. Wrapping, cursor updates, and scrolling affect the captured rows. +Detached helpers need their own shutdown request. + ## Read what tmux has ### [`server.sessions()`][server]: one read, then handles @@ -565,6 +615,7 @@ rename.getAnnotation(io.github.libtmux.catalog.Operation.class).value(); // [pane]: https://libtmux.org/en/java/latest/reference/io-github-libtmux-pane-pane/ [pane-run]: https://libtmux.org/en/java/latest/reference/io-github-libtmux-pane-pane-run/ [pane_]: https://libtmux.org/en/java/latest/reference/io-github-libtmux-pane_-pane_/ +[program]: src/main/java/io/github/libtmux/Program.java [reference]: https://libtmux.org/en/java/latest/reference/ [rowformat]: https://libtmux.org/en/java/latest/reference/io-github-libtmux-format-rowformat-rowformat/ [selections]: https://libtmux.org/en/java/latest/reference/io-github-libtmux-query-selections-selections/ diff --git a/libtmux/src/main/java/io/github/libtmux/Program.java b/libtmux/src/main/java/io/github/libtmux/Program.java new file mode 100644 index 000000000..ddd378579 --- /dev/null +++ b/libtmux/src/main/java/io/github/libtmux/Program.java @@ -0,0 +1,358 @@ +package io.github.libtmux; + +import io.github.libtmux.ProgramExit.Unavailable; +import io.github.libtmux.ProgramExit.Unavailable.Reason; +import io.github.libtmux.exception.CommandRejectedException; +import io.github.libtmux.exception.DispatchException; +import io.github.libtmux.exception.MalformedResponseException; +import io.github.libtmux.exception.ServerUnavailableException; +import io.github.libtmux.exception.TargetGoneException; +import io.github.libtmux.snapshot.ServerSnapshot; +import io.github.libtmux.transport.CommandResult; +import java.nio.file.Path; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +/** + * Owns one terminal application, its session, and optionally a private tmux server. + * + *

Keep the handle in a try-with-resources statement. Use {@link #pane()} to send input and + * capture the screen, and {@link #awaitExit(Duration)} to observe the process without stopping it. + * Closing the owner ends the session without waiting for an application-specific shutdown. + * + *

Waits can run on other threads. Keep the pane in its original session and let the owner + * control its lifetime. A pane manually moved to another session is outside that scope. + */ +public final class Program implements AutoCloseable { + private final Server server; + private final boolean ownsServer; + private final Session session; + private final Pane pane; + private final String process; + private final String launchName; + private volatile boolean closed; + + private Program(Server server, boolean ownsServer, Session session, Pane pane, String process, String launchName) { + this.server = server; + this.ownsServer = ownsServer; + this.session = session; + this.pane = pane; + this.process = process; + this.launchName = launchName; + } + + /** + * Starts an application on a new private tmux server with the default server launch options. + * + * @param spec the application to start + * @return the owner of the new application and server + */ + public static Program start(ProgramSpec spec) { + return start(ServerLaunch.builder().build(), spec); + } + + /** + * Starts an application on a new private tmux server. + * + * @param launch how to start tmux + * @param spec the application to start + * @return the owner of the new application and server + */ + public static Program start(ServerLaunch launch, ProgramSpec spec) { + Objects.requireNonNull(spec, "spec"); + Server server = Server.start(launch); + try { + return startOn(server, true, spec); + } catch (RuntimeException failure) { + afterFailure(failure, server::close); + throw failure; + } + } + + /** + * Starts an application in a new session on a running server. + * + *

Closing the returned owner removes the new session and leaves the server, its client + * handles, and its other sessions available. + * + * @param server the running server to borrow + * @param spec the application to start + * @return the owner of the new application and session + * @throws ServerUnavailableException if the server is not running + */ + public static Program start(Server server, ProgramSpec spec) { + return startOn(Objects.requireNonNull(server, "server"), false, Objects.requireNonNull(spec, "spec")); + } + + private static Program startOn(Server server, boolean ownsServer, ProgramSpec spec) { + ServerSnapshot daemon = server.snapshot(); + String name = "libtmux-program-" + UUID.randomUUID(); + String target = "=" + name + ":"; + SessionSpec anchor = SessionSpec.builder() + .named(name) + .sized(spec.size()) + .environment(spec.environment()) + .running("/bin/sleep", "86400") + .build(); + + List spawn = new ArrayList<>(List.of( + "respawn-pane", + "-k", + "-t", + target, + "--", + "/bin/sh", + "-c", + "if [ -n \"$1\" ]; then cd -- \"$1\" || exit 125; fi; shift; exec \"$@\"", + name)); + Path directory = spec.directory(); + spawn.add(directory == null ? "" : directory.toString()); + spawn.add(spec.executable()); + spawn.addAll(spec.arguments()); + + try { + // The option belongs to the pane. Install it before launch even when the process + // may exit before the caller can take its first snapshot. + List receipt = server.runTogether( + daemon, + List.of( + anchor.argv("#{session_id}"), + List.of("set-option", "-p", "-t", target, "remain-on-exit", "on"), + List.of("set-option", "-p", "-t", target, "remain-on-exit-format", ""), + spawn, + List.of("display-message", "-p", "-t", target, "#{pane_id},#{pane_pid}"))) + .stdout(); + if (receipt.size() != 2) { + throw new MalformedResponseException("tmux did not report the program's session and process"); + } + String[] started = receipt.getLast().split(",", -1); + if (started.length != 2 || started[1].isBlank()) { + throw new MalformedResponseException("tmux did not report the program's pane and process"); + } + PaneId paneId = new PaneId(started[0]); + ServerSnapshot fresh = server.refresh(daemon); + Session session = fresh.session(new SessionId(receipt.getFirst())) + .map(state -> new Session(server, fresh, state)) + .orElseThrow(() -> new TargetGoneException("the application session has already ended")); + Pane pane = fresh.panes().stream() + .filter(state -> state.id().equals(paneId) + && state.context().session().equals(session.id())) + .findFirst() + .map(state -> new Pane(server, fresh, state)) + .orElseThrow(() -> new TargetGoneException("the application pane has already ended")); + return new Program(server, ownsServer, session, pane, started[1], name); + } catch (RuntimeException failure) { + if (!ownsServer) { + afterFailure(failure, () -> removeSession(server, daemon, "=" + name)); + } + throw failure; + } + } + + /** + * Returns the application pane for input and rendered screen capture. + * + *

The pane belongs to this scope. Keep it open until observations and input are finished. + * External pane respawn or session mutation can invalidate the association with the original + * process. + * + * @return the original application pane + */ + public Pane pane() { + return pane; + } + + /** + * Observes the original process for at most the given duration. + * + *

Timeout and thread interruption affect only this wait. The application keeps running + * until it exits or its owner closes. A numeric exit status can come from the launch shell + * if it failed to change directory or start the executable. + * + * @param timeout how long to wait, including tmux reads + * @return the process's exit, the elapsed deadline, or the reason an exit cannot be read + * @throws IllegalArgumentException if the timeout is zero or negative + * @throws InterruptedException if the waiting thread is interrupted + */ + public ProgramExit awaitExit(Duration timeout) throws InterruptedException { + requireTimeout(timeout); + Duration longest = Duration.ofNanos(Long.MAX_VALUE); + long nanos = timeout.compareTo(longest) > 0 ? Long.MAX_VALUE : timeout.toNanos(); + long deadline = System.nanoTime() + nanos; + while (true) { + if (Thread.interrupted()) throw new InterruptedException("interrupted while observing the application"); + if (closed) return new Unavailable(Reason.PANE_GONE); + + long left = deadline - System.nanoTime(); + if (left <= 0) return new ProgramExit.TimedOut(); + Server bounded = server.within(Duration.ofNanos(left)); + String state; + try { + state = pane.through(bounded) + .expand("#{pane_id},#{pane_dead},#{pane_pid},#{pane_dead_status}," + "#{pane_dead_signal},#{m:*" + + launchName + "*,#{pane_start_command}}"); + } catch (DispatchException.TimedOut expired) { + return new ProgramExit.TimedOut(); + } catch (DispatchException.Failed failure) { + if (Thread.interrupted()) { + var interrupted = new InterruptedException("interrupted while reading the application process"); + interrupted.initCause(failure); + throw interrupted; + } + throw failure; + } catch (TargetGoneException | ServerUnavailableException lost) { + return new Unavailable(Reason.SERVER_GONE); + } catch (CommandRejectedException failed) { + return afterRejectedRead(pane, deadline, failed); + } + if (Thread.interrupted()) throw new InterruptedException("interrupted while observing the application"); + if (deadline - System.nanoTime() <= 0) return new ProgramExit.TimedOut(); + + String[] fields = state.split(",", -1); + if (fields.length != 6) { + throw new MalformedResponseException("tmux did not report the application's process status"); + } + // Some releases expand the format against an empty context after the pane is removed. + if (!fields[0].equals(pane.id().value())) return new Unavailable(Reason.PANE_GONE); + if (!fields[5].equals("1") || (!fields[2].isEmpty() && !fields[2].equals(process))) { + return new Unavailable(Reason.PROCESS_REPLACED); + } + if (fields[1].equals("1")) return deadExit(fields[3], fields[4]); + left = deadline - System.nanoTime(); + if (left > 0) TimeUnit.NANOSECONDS.sleep(Math.min(left, PaneWait.POLL.toNanos())); + } + } + + static ProgramExit deadExit(String status, String signal) { + if (!status.isEmpty()) { + try { + return new ProgramExit.Exited(Integer.parseInt(status)); + } catch (NumberFormatException invalid) { + throw new MalformedResponseException("tmux reported an invalid application exit", invalid); + } + } + if (!signal.isEmpty()) return new ProgramExit.Signalled(signal); + return new Unavailable(Reason.STATUS_MISSING); + } + + private static ProgramExit afterRejectedRead(Pane pane, long deadline, CommandRejectedException failed) + throws InterruptedException { + long left = deadline - System.nanoTime(); + if (left <= 0) throw failed; + try { + Server bounded = pane.server().within(Duration.ofNanos(left)); + CommandResult listing = bounded.run(pane.snapshot(), List.of("list-panes", "-a", "-F", "#{pane_id}")); + if (Thread.interrupted()) throw new InterruptedException("interrupted while checking the pane"); + if (!listing.stdout().contains(pane.id().value())) return new Unavailable(Reason.PANE_GONE); + } catch (TargetGoneException | ServerUnavailableException lost) { + return new Unavailable(Reason.SERVER_GONE); + } catch (RuntimeException probeFailure) { + if (Thread.interrupted()) { + var interrupted = new InterruptedException("interrupted while checking the pane"); + interrupted.initCause(probeFailure); + throw interrupted; + } + failed.addSuppressed(probeFailure); + } + throw failed; + } + + /** + * Starts, observes and closes a program on a private tmux server with default launch options. + * + * @param spec the application to run + * @param timeout how long to observe exit + * @return the exit observation and last visible screen, after closing the program + * @throws IllegalArgumentException if the timeout is zero or negative + * @throws InterruptedException if the waiting thread is interrupted + */ + public static ProgramResult run(ProgramSpec spec, Duration timeout) throws InterruptedException { + return run(ServerLaunch.builder().build(), spec, timeout); + } + + /** + * Starts, observes and closes a program on a private tmux server. + * + *

The timeout bounds exit observation. Startup, the last screen read, and cleanup have + * their own server deadlines. An observation timeout closes the owner and ends the session, as + * does interruption. The screen is captured before cleanup. + * + * @param launch how to start tmux + * @param spec the application to run + * @param timeout how long to observe exit + * @return the exit observation and last visible screen, after closing the program + * @throws IllegalArgumentException if the timeout is zero or negative + * @throws InterruptedException if the waiting thread is interrupted + */ + public static ProgramResult run(ServerLaunch launch, ProgramSpec spec, Duration timeout) + throws InterruptedException { + requireTimeout(timeout); + try (Program program = start(launch, spec)) { + ProgramExit exit = program.awaitExit(timeout); + List screen = exit instanceof Unavailable lost && lost.reason() != Reason.STATUS_MISSING + ? List.of() + : program.pane.capture(); + return new ProgramResult(exit, screen); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw interrupted; + } + } + + /** + * Ends the application's session and any privately owned server. + * + *

Blocks for cleanup, even on a thread already marked interrupted, and restores the flag + * before returning. A process that detached from the terminal needs its own shutdown. + */ + @Override + public synchronized void close() { + if (closed) return; + boolean interrupted = Thread.interrupted(); + try { + if (ownsServer) { + server.close(); + } else { + removeSession(server, session.snapshot(), session.id().value()); + } + closed = true; + } finally { + if (interrupted) Thread.currentThread().interrupt(); + } + } + + private static void removeSession(Server server, ServerSnapshot daemon, String target) { + try { + CommandResult result = server.cmd(daemon, List.of("kill-session", "-t", target)); + if (!result.succeeded()) { + if (server.failed("kill-session", result) instanceof ServerUnavailableException) return; + ServerSnapshot fresh = server.refresh(daemon); + boolean present = fresh.sessions().stream() + .anyMatch(session -> + session.id().value().equals(target) || ("=" + session.name()).equals(target)); + if (present) throw server.failed("kill-session", result); + } + } catch (TargetGoneException | ServerUnavailableException alreadyGone) { + // This scope no longer has anything on the endpoint. + } + } + + private static void requireTimeout(Duration timeout) { + if (timeout.isZero() || timeout.isNegative()) throw new IllegalArgumentException("timeout is not positive"); + } + + private static void afterFailure(RuntimeException failure, Runnable cleanup) { + boolean interrupted = Thread.interrupted(); + try { + cleanup.run(); + } catch (RuntimeException closeFailure) { + failure.addSuppressed(closeFailure); + } finally { + if (interrupted) Thread.currentThread().interrupt(); + } + } +} diff --git a/libtmux/src/main/java/io/github/libtmux/ProgramExit.java b/libtmux/src/main/java/io/github/libtmux/ProgramExit.java new file mode 100644 index 000000000..9225e0639 --- /dev/null +++ b/libtmux/src/main/java/io/github/libtmux/ProgramExit.java @@ -0,0 +1,42 @@ +package io.github.libtmux; + +/** Tells what tmux reported about the original process in a terminal application. */ +public sealed interface ProgramExit + permits ProgramExit.Exited, ProgramExit.Signalled, ProgramExit.TimedOut, ProgramExit.Unavailable { + + /** + * Carries a normal shell or application exit observed by tmux. + * + * @param status the numeric exit status + */ + record Exited(int status) implements ProgramExit {} + + /** + * Carries the signal that ended the process, when tmux reported it. + * + * @param signal the name or decimal number reported by tmux, such as {@code TERM} or {@code 15} + */ + record Signalled(String signal) implements ProgramExit {} + + /** Indicates that the application did not report an exit within the observation deadline. */ + record TimedOut() implements ProgramExit {} + + /** + * Indicates that tmux could no longer report the original process's outcome. + * + * @param reason why the original process's outcome could not be recovered + */ + record Unavailable(Reason reason) implements ProgramExit { + /** Describes why an exit is unavailable. */ + public enum Reason { + /** The server ended or was replaced. */ + SERVER_GONE, + /** The private pane ended before its status could be read. */ + PANE_GONE, + /** Another process was started in the pane. */ + PROCESS_REPLACED, + /** The pane was dead and tmux supplied neither an exit status nor a signal. */ + STATUS_MISSING + } + } +} diff --git a/libtmux/src/main/java/io/github/libtmux/ProgramResult.java b/libtmux/src/main/java/io/github/libtmux/ProgramResult.java new file mode 100644 index 000000000..5165cd379 --- /dev/null +++ b/libtmux/src/main/java/io/github/libtmux/ProgramResult.java @@ -0,0 +1,21 @@ +package io.github.libtmux; + +import java.util.List; +import java.util.Objects; +import kotlin.annotations.jvm.ReadOnly; + +/** + * Reports an owning run's exit observation and last visible screen. + * + *

Standard output and standard error written to the terminal share the same rows. + * Terminal wrapping, cursor updates, and scrolling affect those rows. + * + * @param exit the outcome of the exit observation + * @param screen immutable rows of the last visible screen, in terminal order, or empty when lost + */ +public record ProgramResult(ProgramExit exit, @ReadOnly List screen) { + public ProgramResult { + Objects.requireNonNull(exit, "exit"); + screen = List.copyOf(screen); + } +} diff --git a/libtmux/src/main/java/io/github/libtmux/ProgramSpec.java b/libtmux/src/main/java/io/github/libtmux/ProgramSpec.java new file mode 100644 index 000000000..f9af1b290 --- /dev/null +++ b/libtmux/src/main/java/io/github/libtmux/ProgramSpec.java @@ -0,0 +1,141 @@ +package io.github.libtmux; + +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import org.jspecify.annotations.Nullable; + +/** Describes a terminal application using a literal executable and argument list. */ +public final class ProgramSpec { + private final String executable; + private final List arguments; + private final @Nullable Path directory; + private final Map environment; + private final Dimensions size; + + private ProgramSpec(Builder builder) { + executable = builder.executable; + arguments = builder.arguments; + directory = builder.directory; + environment = builder.environment; + size = builder.size; + } + + /** + * Describes a program to start, with no arguments and an 80-column, 24-row terminal. + * + * @param executable an executable path, or a name looked up in the pane's {@code PATH} + * @return a builder for the program + * @throws IllegalArgumentException if the executable is empty, contains NUL, or begins with + * {@code -}; use a path such as {@code ./-worker} for a name beginning with {@code -} + */ + public static Builder builder(String executable) { + Objects.requireNonNull(executable, "executable"); + if (executable.isEmpty() || executable.startsWith("-")) { + throw new IllegalArgumentException("expected an executable name or path"); + } + return new Builder(noNul(executable)); + } + + String executable() { + return executable; + } + + List arguments() { + return arguments; + } + + @Nullable + Path directory() { + return directory; + } + + Map environment() { + return environment; + } + + Dimensions size() { + return size; + } + + private static String noNul(String value) { + if (value.indexOf('\0') >= 0) { + throw new IllegalArgumentException("program arguments and environment cannot contain NUL"); + } + return value; + } + + /** Collects the program's arguments and terminal settings. */ + public static final class Builder { + private final String executable; + private List arguments = List.of(); + private @Nullable Path directory; + private Map environment = Map.of(); + private Dimensions size = new Dimensions(80, 24); + + private Builder(String executable) { + this.executable = executable; + } + + /** + * Replaces the arguments with an immutable copy in the caller's order. + * + * @param arguments arguments passed unchanged, including empty strings + * @return this builder + * @throws IllegalArgumentException if an argument contains NUL + */ + public Builder args(List arguments) { + this.arguments = arguments.stream().map(ProgramSpec::noNul).toList(); + return this; + } + + /** + * Selects the application's working directory. + * + * @param directory a directory accessible to tmux, resolved against the JVM working directory + * if relative + * @return this builder + */ + public Builder in(Path directory) { + this.directory = Objects.requireNonNull(directory, "directory").toAbsolutePath(); + return this; + } + + /** + * Sets the environment overrides, copied from the caller's map. + * + * @param environment name-value pairs to set in the pane + * @return this builder + * @throws IllegalArgumentException if a name is empty or contains {@code =}, or a name or value + * contains NUL + */ + public Builder environment(Map environment) { + environment.forEach((name, value) -> { + if (name.isEmpty() || name.contains("=")) { + throw new IllegalArgumentException("expected an environment variable name"); + } + noNul(name); + noNul(value); + }); + this.environment = Map.copyOf(environment); + return this; + } + + /** + * Sets the initial terminal dimensions. + * + * @param size the terminal's columns and rows + * @return this builder + */ + public Builder sized(Dimensions size) { + this.size = Objects.requireNonNull(size, "size"); + return this; + } + + /** Returns an immutable specification that may be reused. */ + public ProgramSpec build() { + return new ProgramSpec(this); + } + } +} diff --git a/libtmux/src/test/java/io/github/libtmux/ProgramTest.java b/libtmux/src/test/java/io/github/libtmux/ProgramTest.java new file mode 100644 index 000000000..c8d446bc4 --- /dev/null +++ b/libtmux/src/test/java/io/github/libtmux/ProgramTest.java @@ -0,0 +1,243 @@ +package io.github.libtmux; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +final class ProgramTest { + private static final Duration WAIT = Duration.ofSeconds(6); + + @TempDir + Path directory; + + @Test + void runsAZeroArgumentExecutableWithSpacesAndKeepsItsLastScreen() throws Exception { + Path executable = directory.resolve("-a worker"); + Files.writeString(executable, """ + #!/bin/sh + printf '%s\\n' "$#" > argument-count + printf '%s\\n' "$RECEIPT" + exit 31 + """); + assertTrue(executable.toFile().setExecutable(true)); + + var spec = ProgramSpec.builder("./-a worker") + .in(directory) + .environment(Map.of("RECEIPT", "final burst")) + .build(); + Path socket; + try (Program app = Program.start(launch(), spec)) { + socket = socket(app); + assertExit(app, 31); + assertTrue(app.pane().capture().contains("final burst")); + assertEquals("0\n", Files.readString(directory.resolve("argument-count"))); + } + assertFalse(Files.exists(socket.getParent())); + } + + @Test + void forwardsMetacharactersAndPreservesEmptyArguments() throws Exception { + List values = List.of("", ";", "quote'\";", "-x", "#{pane_id}", "é雪"); + var arguments = new ArrayList<>(List.of("-c", "printf '<%s>\\n' \"$@\"; exit 12", "argv")); + arguments.addAll(values); + var spec = ProgramSpec.builder("/bin/sh").args(arguments).build(); + try (Program app = Program.start(launch(), spec)) { + assertExit(app, 12); + assertTrue(app.pane() + .capture() + .containsAll(values.stream().map(value -> "<" + value + ">").toList())); + } + } + + @Test + void preservesTheNativeSignalAndKeepsItDistinctFromAnExitCode() throws Exception { + var killed = ProgramSpec.builder("/bin/sh") + .args(List.of("-c", "kill -TERM $$")) + .build(); + try (Program app = Program.start(launch(), killed)) { + var exit = app.awaitExit(WAIT); + if (!statusMissingOn34(app, exit)) { + var signalled = assertInstanceOf(ProgramExit.Signalled.class, exit); + assertEquals(app.pane().expand("#{pane_dead_signal}"), signalled.signal()); + } + } + + var returned = + ProgramSpec.builder("/bin/sh").args(List.of("-c", "exit 143")).build(); + try (Program app = Program.start(launch(), returned)) { + assertExit(app, 143); + } + } + + @Test + void readsNamedAndNumericSignalsFromDeadPaneFormats() { + assertEquals(new ProgramExit.Signalled("TERM"), Program.deadExit("", "TERM")); + assertEquals(new ProgramExit.Signalled("15"), Program.deadExit("", "15")); + assertEquals(new ProgramExit.Exited(143), Program.deadExit("143", "")); + assertEquals( + new ProgramExit.Unavailable(ProgramExit.Unavailable.Reason.STATUS_MISSING), Program.deadExit("", "")); + } + + @Test + void observerTimeoutAndInterruptLeaveAnInteractiveProgramAndItsBorrowedServerRunning() throws Exception { + try (Server server = Server.start(launch())) { + var neighbor = server.newSession("neighbor"); + var spec = ProgramSpec.builder("/bin/sh").args(List.of("-c", """ + printf 'ready\\n' + IFS= read -r answer + printf 'received: %s\\n' "$answer" + exit 37 + """)).build(); + try (Program app = Program.start(server, spec)) { + assertEquals( + WakeReason.SIGNALLED, + app.pane().await(pane -> pane.capture().contains("ready"), WAIT)); + assertInstanceOf(ProgramExit.TimedOut.class, app.awaitExit(Duration.ofMillis(150))); + + var started = new CompletableFuture(); + var outcome = new CompletableFuture(); + Thread waiting = Thread.ofVirtual().start(() -> { + started.complete(null); + try { + app.awaitExit(WAIT); + outcome.completeExceptionally(new AssertionError("observation should be interrupted")); + } catch (Throwable failure) { + outcome.complete(failure); + } + }); + started.get(WAIT.toSeconds(), TimeUnit.SECONDS); + waiting.interrupt(); + assertInstanceOf(InterruptedException.class, outcome.get(WAIT.toSeconds(), TimeUnit.SECONDS)); + + app.pane().sendLine("forty-two"); + assertExit(app, 37); + assertTrue(app.pane().capture().contains("received: forty-two")); + } + assertEquals( + List.of(neighbor.id()), + server.sessions().stream().map(Session::id).toList()); + } + } + + @Test + void doesNotAttributeAReplacementExitToTheOriginalApplication() throws Exception { + try (Program app = + Program.start(launch(), ProgramSpec.builder("/bin/cat").build())) { + app.pane().respawn("/bin/sh", "-c", "exit 93"); + assertEquals( + new ProgramExit.Unavailable(ProgramExit.Unavailable.Reason.PROCESS_REPLACED), app.awaitExit(WAIT)); + } + } + + @Test + void aGoneApplicationPaneLeavesOtherSessionsUntouched() throws Exception { + try (Server server = Server.start(launch())) { + var neighbor = server.newSession("neighbor"); + try (Program app = + Program.start(server, ProgramSpec.builder("/bin/cat").build())) { + app.pane().kill(); + assertEquals( + new ProgramExit.Unavailable(ProgramExit.Unavailable.Reason.PANE_GONE), app.awaitExit(WAIT)); + } + assertTrue(server.hasSession(neighbor.name())); + } + } + + @Test + void closeRefusesToTouchAReplacementDaemon() throws Exception { + Path socketRoot = Files.createTempDirectory(Path.of("/tmp/libtmux-java-test"), "program-replacement-"); + Path socket = socketRoot.resolve("s"); + try (Server server = Server.builder() + .endpoint(ServerEndpoint.socketPath(socket)) + .configFile(Path.of("/dev/null")) + .binary(launch().binary()) + .build()) { + try { + server.newSession("original"); + var spec = ProgramSpec.builder("/bin/cat").build(); + try (Program app = Program.start(server, spec)) { + server.killServer(); + server.newSession("replacement"); + assertEquals( + new ProgramExit.Unavailable(ProgramExit.Unavailable.Reason.SERVER_GONE), + app.awaitExit(WAIT)); + } + assertEquals( + List.of("replacement"), + server.sessions().stream().map(Session::name).toList()); + } finally { + server.killServer(); + } + } finally { + Files.deleteIfExists(socket); + Files.delete(socketRoot); + } + } + + @Test + void anOwningTimeoutReturnsTheScreenAndEndsItsSession() throws Exception { + Path endpoint = directory.resolve("endpoint"); + var spec = ProgramSpec.builder("/bin/sh") + .in(directory) + .args(List.of("-c", """ + printf '%s\\n' "$TMUX" > endpoint + printf 'still running\\n' + IFS= read -r hold + """)) + .build(); + var result = Program.run(launch(), spec, Duration.ofMillis(500)); + assertInstanceOf(ProgramExit.TimedOut.class, result.exit()); + assertTrue(result.screen().contains("still running")); + Path socket = TmuxEnvironment.of( + Map.of("TMUX", Files.readString(endpoint).strip())) + .orElseThrow() + .socket(); + assertFalse(Files.exists(socket.getParent())); + } + + @Test + void refusesInputThatCannotBeAnArgumentBeforeOpeningTmux() { + assertThrows(IllegalArgumentException.class, () -> ProgramSpec.builder("-worker")); + assertThrows(IllegalArgumentException.class, () -> ProgramSpec.builder("worker\0")); + assertThrows( + IllegalArgumentException.class, + () -> ProgramSpec.builder("worker").args(List.of("bad\0arg"))); + } + + private static void assertExit(Program app, int expected) throws InterruptedException { + ProgramExit exit = app.awaitExit(WAIT); + if (!statusMissingOn34(app, exit)) { + assertEquals(new ProgramExit.Exited(expected), exit); + } + } + + private static boolean statusMissingOn34(Program app, ProgramExit exit) { + // tmux 3.4 can show a dead pane without a wait status. + return exit.equals(new ProgramExit.Unavailable(ProgramExit.Unavailable.Reason.STATUS_MISSING)) + && app.pane().server().version().sameRelease(TmuxVersion.parse("3.4")); + } + + private static ServerLaunch launch() { + return ServerLaunch.builder() + .root(Path.of("/tmp/libtmux-java-test")) + .binary(System.getProperty("libtmux.tmux", "tmux")) + .build(); + } + + private static Path socket(Program app) { + return Path.of(app.pane().expand("#{socket_path}")); + } +}