diff --git a/bin/berth b/bin/berth index 1825e81..45815e1 100755 --- a/bin/berth +++ b/bin/berth @@ -1,8 +1,8 @@ #!/usr/bin/env bash # berth: the backend-neutral port. See docs/design.md, "The port: berth". # -# This front end reads the arguments and hands each verb to the adapter that -# BERTH_BACKEND names, `berth-` beside this script. An adapter takes +# This front end reads the arguments and hands each verb to the adapter for +# the backend, `berth-` beside this script. An adapter takes # the verbs already parsed: # # serve @@ -74,10 +74,20 @@ verb=$1 shift case "${1:-}" in -h | --help) print_usage; exit 0 ;; esac -[ -n "${BERTH_BACKEND:-}" ] || - die "no backend named. Set BERTH_BACKEND, for example to herdr." -adapter="$(dirname "$(readlink -f "$0")")/berth-$BERTH_BACKEND" -[ -x "$adapter" ] || die "there is no adapter for the backend '$BERTH_BACKEND'." +# Without BERTH_BACKEND, the calling pane's own variables name the backend. +# herdr's panes inherit an app terminal's variables when herdr runs inside +# one, so a caller that has both cannot be told apart. +backend=${BERTH_BACKEND:-} +if [ -z "$backend" ]; then + case "${HC_TERMINAL_ID:+app}${HERDR_PANE_ID:+herdr}" in + app) backend=herdr-app ;; + herdr) backend=herdr ;; + appherdr) die "no backend named, and the caller is in both a herdr pane and a herdr app terminal. Set BERTH_BACKEND." ;; + *) die "no backend named, and the caller is in no herdr pane or herdr app terminal. Set BERTH_BACKEND, for example to herdr." ;; + esac +fi +adapter="$(dirname "$(readlink -f "$0")")/berth-$backend" +[ -x "$adapter" ] || die "there is no adapter for the backend '$backend'." case "$verb" in serve | stop) diff --git a/bin/berth-herdr-app b/bin/berth-herdr-app new file mode 100755 index 0000000..a27e765 --- /dev/null +++ b/bin/berth-herdr-app @@ -0,0 +1,310 @@ +#!/usr/bin/env bash +# berth-herdr-app: berth's adapter for the herdr desktop app, which `berth` +# runs with the verbs already parsed. See docs/design.md, "The herdr app +# adapter". +# +# The app runs its terminals in herdr-core, and the adapter drives herdr-core +# through hc. A berth is an hc terminal, and its id is the terminal's id. A +# yard is an hc session. The relationship, the opener, the line of work and +# the label live on the terminal as hc labels. +# +# Needs: bash, coreutils, flock, herdr-core, jq. +set -euo pipefail + +yard=${BERTH_YARD:-${HC_SESSION:-default}} + +die() { + echo "berth (herdr-app): $1" >&2 + exit 1 +} + +# Every hc command starts its session's core when none is running, so the +# adapter looks for a running core itself before it asks hc anything. A +# running core holds a lock on core.lock in its session's state folder. +core_lock() { # + echo "${XDG_STATE_HOME:-$HOME/.local/state}/herdr-core/$1/core.lock" +} + +yard_running() { # + local lock + lock=$(core_lock "$1") + [ -f "$lock" ] && ! flock -n "$lock" true +} + +# Inside a terminal, hc reaches the terminal's own core and takes the terminal +# as its caller, so neither may override the yard. +hc_env() { + env -u HC_TERMINAL_SOCKET -u HC_SOCKET -u HC_TERMINAL_ID HC_SESSION="$yard" "$@" +} + +# Prints what hc prints. Returns 3 for a terminal hc does not have, so a caller +# can answer gone. Anything else that fails ends berth. +hc_call() { + local out status=0 message + yard_running "$yard" || die "the yard $yard is not up." + out=$(hc_env hc "$1" --json "${@:2}" 2>&1) || status=$? + [ "$status" = 0 ] && { printf '%s\n' "$out"; return; } + [ "$status" = 3 ] && return 3 + message=$(jq -r '.error.message? // empty' <<<"$out" 2>/dev/null) || message="" + die "hc $1 failed in yard $yard: ${message:-$out}" +} + +# Runs a call on a berth that has to exist for the verb to go on. +on_berth() { # ... + local id=$1 what=$2 status=0 + shift 2 + "$@" || status=$? + case $status in + 0) ;; + 3) die "the berth $id is gone, so $what." ;; + *) exit "$status" ;; + esac +} + +# A finished terminal is gone, as one that hc has removed is. +terminal_get() { # + local terminal + terminal=$(hc_call get "$1") || return + jq -e '.state == "live"' <<<"$terminal" >/dev/null || return 3 + printf '%s\n' "$terminal" +} + +existing_terminal() { # + on_berth "$1" "$2" terminal_get "$1" +} + +# Every live terminal of the yard, in one call. +terminals() { + local out + yard_running "$yard" || die "the yard $yard is not up." + out=$(hc_env hc connect <<<'{"jsonrpc":"2.0","id":1,"method":"terminal.list","params":{}}' 2>&1) || + die "hc connect failed in yard $yard: $out" + jq -ce '.result.terminals' <<<"$out" 2>/dev/null || + die "hc's terminal list failed in yard $yard: $out" +} + +# The given berth, or the calling terminal. A terminal id is unique only within +# its session, so the calling terminal stands for the caller only in its own +# yard. +berth_id() { # [] + local id=$1 what=${2:-there is no berth to act on} own + if [ -z "$id" ]; then + [ -n "${HC_TERMINAL_ID:-}" ] || die "the caller is neither a berth nor in a herdr app terminal, so $what." + own=${HC_SESSION:-default} + [ "$own" = "$yard" ] || die "the caller's herdr app terminal is in the yard $own, not in $yard, so $what." + id=$HC_TERMINAL_ID + fi + printf '%s\n' "$id" +} + +# herdr-core takes a terminal's status only from what its program reports +# over OSC 7501. +agent_state_of='def agent_state: {working: "active", blocked: "blocked", idle: "at-rest", + done: "at-rest", error: "at-rest"}[.status.state? // "none"];' + +terminal_agent_state() { # + jq -r "$agent_state_of"' agent_state // "none"' <<<"$1" +} + +# The command runs under the shell, so a berth whose command has exited, such +# as an agent that left, stays open at a prompt. hc gives a terminal its id +# only once it exists, so the command reads its BERTH_ID from the terminal. +# The terminal runs in herdr-core's environment, not the caller's, so the +# shell is named by its path. +# shellcheck disable=SC2016 # the berth's own shell expands it +berth_command=("$BASH" -c 'export BERTH_BACKEND=herdr-app BERTH_YARD=$1 BERTH_ID=$HC_TERMINAL_ID + shift; "$@"; exec "${SHELL:-sh}"' berth "$yard") + +open() { + local as=$1 place=$2 cwd=$4 label=$5 opener=$6 id line="" labels=() + shift 6 + # Focus belongs to the window, which places no berth yet. + + if [ "$as" = independent ] && [ "$place" = apart ]; then + opener="" + else + opener=$(berth_id "$opener" "there is nothing to open a berth beside") + line=$(existing_terminal "$opener" "there is nothing to open a berth beside" | + jq -r --arg id "$opener" '.labels["berth.line"] // $id') + labels+=(--label "berth.line=$line") + fi + + if [ "$as" = tender ] && [ -n "$label" ]; then + id=$(terminals | jq -r --arg line "$line" --arg label "$label" ' + first(.[] | select(.labels["berth.relationship"] == "tender" and .labels["berth.line"] == $line + and .labels["berth.label"] == $label) | .address) // empty') + if [ -n "$id" ]; then + hc_call label "$id" "berth.parent=$opener" >/dev/null + printf '%s\n' "$id" + return + fi + fi + + # Closing its opener leaves an independent berth, so its opener is not its + # parent. + [ "$as" = independent ] || labels+=(--label "berth.parent=$opener") + id=$(hc_call run --bg --no-parent --no-notify --cwd "$cwd" \ + --label "berth.relationship=$as" --label "berth.place=$place" \ + ${label:+--label "berth.label=$label"} "${labels[@]}" \ + -- "${berth_command[@]}" "$@" | jq -r .address) + [ -n "$line" ] || hc_call label "$id" "berth.line=$id" >/dev/null + printf '%s\n' "$id" +} + +name() { + local id + id=$(berth_id "$1") + existing_terminal "$id" "it cannot be named" >/dev/null + hc_call label "$id" "berth.label=$2" >/dev/null +} + +serve() { + yard=$1 + ! yard_running "$yard" || die "the yard $yard is already being served." + exec env -u HC_TERMINAL_SOCKET -u HC_SOCKET -u HC_TERMINAL_ID HC_SESSION="$yard" herdr-core serve +} + +stop() { + yard=$1 + yard_running "$yard" || return 0 + hc_call server stop >/dev/null +} + +# Each session's core keeps a state folder of its own. +yards() { + local dir up=() + for dir in "${XDG_STATE_HOME:-$HOME/.local/state}"/herdr-core/*/; do + [ -d "$dir" ] || continue + dir=${dir%/} + ! yard_running "${dir##*/}" || up+=("${dir##*/}") + done + [ ${#up[@]} = 0 ] || printf '%s\n' "${up[@]}" +} + +# hc can only type text and press Enter in one go, so text sent without a key +# waits in the adapter's state until Enter submits it. +held_text() { # + echo "${XDG_STATE_HOME:-$HOME/.local/state}/berth/herdr-app/$yard/$1.text" +} + +send_text() { + local id held + id=$(berth_id "$1") + existing_terminal "$id" "it cannot take text" >/dev/null + held=$(held_text "$id") + mkdir -p "${held%/*}" + printf '%s' "$2" >>"$held" +} + +# berth names keys as herdr does, and hc names them in lower case. +send_key() { + local id key held + id=$(berth_id "$1") + key=$(tr '[:upper:]' '[:lower:]' <<<"$2") + [ "$key" != escape ] || key=esc + existing_terminal "$id" "it cannot take a key" >/dev/null + held=$(held_text "$id") + if [ -f "$held" ]; then + [ "$key" = enter ] || + die "berth $id holds text that only Enter can submit, because hc cannot type text without pressing Enter." + on_berth "$id" "it cannot take text" hc_call send --force -- "$id" "$(cat "$held")" >/dev/null + rm -f "$held" + else + on_berth "$id" "it cannot take a key" hc_call keys "$id" "$key" >/dev/null + fi +} + +# hc reads lines whole, however wide the terminal, so a line taller than the +# terminal still matches. +recent_lines=1000 + +wait_text() { + local id deadline text + id=$(berth_id "$1") + deadline=$(($(date +%s%N) + $3 * 1000000000)) + while :; do + text=$(on_berth "$id" "there is nothing to wait on" hc_call read "$id" --lines "$recent_lines" | jq -r .text) + ! grep -qF -- "$2" <<<"$text" || return 0 + [ "$(date +%s%N)" -lt "$deadline" ] || return 1 + sleep 0.2 + done +} + +read_screen() { + local id + id=$(berth_id "$1") + on_berth "$id" "it cannot be read" hc_call read "$id" --lines 0 | jq -r .text +} + +# With all, a terminal that berth did not open is listed while it runs an +# agent. Like herdr, the app keeps a terminal's session once its agent has +# left, so a berth with no agent state lists none. +list() { # + yard=${1:-$yard} + terminals | jq --arg scope "$2" "$agent_state_of"' + [.[] | agent_state as $agent + | (.labels["berth.relationship"] // null) as $relationship + | select($relationship != null or ($scope == "all" and $agent != null)) | { + id: .address, + label: (.labels["berth.label"] // null), + relationship: $relationship, + parent: (.labels["berth.parent"] // null), + state: "open", + agent_state: $agent, + agent_session: (if $agent == null then null else .labels["claude.session"] // null end) + }]' +} + +state() { + local id status=0 + id=$(berth_id "$1") + terminal_get "$id" >/dev/null || status=$? + case $status in + 0) echo open ;; + 3) echo gone ;; + *) exit "$status" ;; + esac +} + +agent_state() { + local id terminal status=0 + id=$(berth_id "$1") + terminal=$(terminal_get "$id") || status=$? + case $status in + 0) terminal_agent_state "$terminal" ;; + 3) echo none ;; + *) exit "$status" ;; + esac +} + +# Closing a berth closes the berths it opened first. +close() { + local id child status=0 + id=$(berth_id "$1") + terminal_get "$id" >/dev/null || status=$? + case $status in + 0) ;; + 3) return 0 ;; + *) exit "$status" ;; + esac + for child in $(terminals | jq -r --arg id "$id" '.[] | select(.labels["berth.parent"] == $id) | .address'); do + close "$child" + done + hc_call kill "$id" >/dev/null || [ $? = 3 ] + hc_call rm "$id" >/dev/null || [ $? = 3 ] + rm -f "$(held_text "$id")" +} + +verb=$1 +shift +case "$verb" in + serve | stop | open | name | list | state | close | yards) "$verb" "$@" ;; + yard) echo "$yard" ;; + id) berth_id "$1" ;; + send-text) send_text "$@" ;; + send-key) send_key "$@" ;; + wait-text) wait_text "$@" ;; + read) read_screen "$@" ;; + agent-state) agent_state "$@" ;; + *) die "berth passed an unknown verb, $verb." ;; +esac diff --git a/docs/design.md b/docs/design.md index 1907a7b..74bc088 100644 --- a/docs/design.md +++ b/docs/design.md @@ -2,7 +2,7 @@ ## Purpose -Boatyard runs coding agents in terminal multiplexer panes and coordinates them. It hides the multiplexer behind a port, so that moving to another multiplexer means writing an adapter rather than editing skills. herdr is the first backend. tuios, Orca and tmux are candidates. +Boatyard runs coding agents in terminal multiplexer panes and coordinates them. It hides the multiplexer behind a port, so that moving to another multiplexer means writing an adapter rather than editing skills. herdr is the first backend, and the herdr desktop app is the second. tuios, Orca and tmux are candidates. ## Scope @@ -39,7 +39,7 @@ The port knows only terminal mechanics. It knows nothing about Claude Code. The ### Concepts -- **Yard.** One backend session that holds berths, such as a herdr server session. +- **Yard.** One backend session that holds berths, such as a herdr server session or a herdr-core session. - **Berth.** One terminal in which a process runs, usually an agent. A berth id is opaque to consumers. An adapter may use its backend's native id, and the herdr adapter does, returning herdr's pane id verbatim. - **Relationship.** Every berth is opened in a relationship to its opener: - **independent**: it starts its own line of work, as a steward or a long-lived agent does. @@ -102,7 +102,9 @@ Every berth carries three variables: A berth opened from inside another inherits `BERTH_BACKEND` and `BERTH_YARD`. An adapter may set variables of its own, but consumers read only these three. -A caller that is not itself a berth has none of the three: a service manager's unit, or a pane a person opened by hand. The host's environment then names the backend, and the adapter resolves the yard and the calling pane from its backend's own variables. With no backend named, `berth` exits non-zero. +A caller that is not itself a berth has none of the three: a service manager's unit, or a pane a person opened by hand. The host's environment then names the backend, and the adapter resolves the yard and the calling pane from its backend's own variables. + +`BERTH_BACKEND` wins wherever it is set, and every berth sets it. Without it, `berth` takes the backend from the calling pane, so a pane a person opened by hand works on a host that runs herdr and the herdr app side by side. herdr-core's terminal variable `HC_TERMINAL_ID` selects the herdr app, and herdr's pane variable `HERDR_PANE_ID` selects herdr. A caller that has both is refused. This happens where herdr runs inside an app terminal, because herdr's panes inherit the app terminal's variables. A caller that has neither is refused too. Each refusal says which case it is. Where a verb needs the caller, such as a worker's opener or the opener a berth opens beside, the calling pane stands in for a caller that is not a berth. It stands in only within its own yard. A caller in no pane, or whose pane is in another yard than the one named, is refused with a message that says which. @@ -138,6 +140,17 @@ It is written first. Its obligations beyond straight mapping: - **Package parameter.** herdr's package is a parameter, so a host can supply a platform-specific build. - **The host's herdr.** A host can name the herdr binary the adapter runs, with `BERTH_HERDR` set to its path. Without it, the adapter runs the packaged herdr. A macOS host that re-signs herdr needs this, because macOS ties its Local-Network grant to the binary's path. The adapter takes the binary from a variable and not from the caller's `PATH`, because a herdr host usually has some herdr on its `PATH`, and the packaged one would quietly give way to it. +### The herdr app adapter + +The herdr desktop app runs its terminals in its own backend, herdr-core, and never attaches to a herdr server. The adapter drives herdr-core through its command, `hc`. A yard is an hc session, named by `HC_SESSION` and `default` without it. A berth is an hc terminal, and its id is herdr-core's terminal id, verbatim. The relationship, parent, label and line of work live on the terminal as hc labels under `berth.`. Its obligations beyond straight mapping: + +- **A yard that is down stays down.** Every hc command starts its session's core when none is running. So the adapter checks for a running core before it asks hc anything. It looks for the lock that a running core holds on `core.lock` in the session's folder under `herdr-core/` in `$XDG_STATE_HOME`. `berth serve` runs `herdr-core serve` in the foreground. +- **Agent state.** herdr-core takes a terminal's agent state only from what its program reports over OSC 7501. `working` is `active`, `blocked` is `blocked`, and `idle`, `done` and `error` are `at-rest`. A terminal with no report has no agent state. A berth's agent session is the terminal's `claude.session` label, which the plugin's mod sets, as *Agent state under the herdr app* says. The adapter lists none for a berth with no agent state. +- **The shell after the command.** hc runs a berth's command as the terminal's program, and the terminal finishes when the command exits. So the adapter runs the command under a shell, which becomes the shell that `SHELL` names in herdr-core's environment once the command exits. An agent that leaves for its shell then leaves its berth open, and herdr-core clears its agent state once the shell is back in the foreground. The command takes its `BERTH_ID` from herdr-core's own `HC_TERMINAL_ID`, because hc gives a terminal its id only once it exists. +- **Text waits for Enter.** hc can paste text and press Enter in one call, but it cannot type text without submitting it. So `send-text` holds the text in the adapter's state, under `berth/herdr-app//` in `$XDG_STATE_HOME`, and the next `send-key Enter` submits it with one paste. Text held this way does not show on screen until then. A key other than Enter is refused while text is held, because hc could not type the text in front of it. A later hc that types without submitting closes the gap. +- **Lines of work.** The app window places no berth yet, so every berth stays hidden from the window. A line of work is a label: an independent berth that opens apart starts one, and every other berth joins its opener's. `open` looks within it for a labelled tender, and closing a berth closes what it opened. +- **Package parameter.** herdr-core's package is a parameter, as herdr's is for its adapter. + ## `sign-on` `sign-on` launches Claude Code in a berth: @@ -234,15 +247,17 @@ Pull requests are GitHub's. The skills read, wait on and merge them with `gh` an ## Testing -- **Port contract suite.** One suite states what every adapter must do: open in each relationship, list, list with `--all`, yards, name, send-text, send-key, wait-text, read, state, agent state across all three agent states and none, close, and the cascade when an independent berth closes. It runs against every adapter. Each adapter's run supplies a command that opens a pane as a person would, outside berth, for the `--all` cases. +- **Port contract suite.** One suite states what every adapter must do: open in each relationship, list, list with `--all`, yards, name, send-text, send-key, wait-text, read, state, agent state across all three agent states and none, close, and the cascade when an independent berth closes. It runs against every adapter. Each adapter's run supplies a command that opens a pane as a person would, outside berth, for the `--all` cases. A run may also name the cases that its backend cannot meet yet. The suite reports such a case rather than failing it, and fails it once it holds, so the gap is dropped as soon as the backend closes it. The herdr app's run names the case where text sent without a key shows on screen. - For herdr, it runs a throwaway server with `HOME` redirected and every `HERDR_*` variable unset. An inherited `HERDR_SOCKET_PATH` would otherwise drive the live session. The server runs inside the nix build sandbox, so the suite is a flake check. - - herdr treats a process named `claude` as an agent and reads its state from the screen. The suite drives the states with a stand-in process of that name, not with Claude Code. + - For the herdr app, it runs a throwaway herdr-core in the same way, with `HOME` and the XDG folders redirected and every `HC_*` and `HERDR_*` variable unset. + - herdr treats a process named `claude` as an agent and reads its state from the screen. herdr-core takes the state Claude Code reports over OSC 7501. The suite drives the states with a stand-in process of that name, not with Claude Code, and the stand-in both draws Claude's screens and makes its reports. +- **Choosing a backend.** The front end's usage test covers a host that runs both backends. A caller in an app terminal reaches the app's adapter, one in a herdr pane reaches herdr's, and one in both or in neither is refused. - **Unit tests.** The mod's compaction rule, its rule for a resumed steward and its reports to the herdr app have their own tests, run by `claude plugin test` against a stand-in engine. So does each adapter's mapping from backend states to the port's agent states, including the herdr parked-on-background-work and lost-agent corrections. - **End to end.** One real effort runs on `steward` and `worker`. ## Open decisions -- **The second adapter.** tmux would bring `berth` to the most users. tuios fits the port model most closely. Orca was the original request for a second backend. +- **The next adapter.** tmux would bring `berth` to the most users. tuios fits the port model most closely. Orca was the original request for a second backend. ## Rejected alternatives diff --git a/nix/berth/default.nix b/nix/berth/default.nix index fe5a9f7..c07f581 100644 --- a/nix/berth/default.nix +++ b/nix/berth/default.nix @@ -15,12 +15,29 @@ let bash ${../../tests/with-herdr-yard} bash ${../../tests + "/${suite}"} touch $out ''; + + openByHandInApp = pkgs.writeShellScript "herdr-app-open-by-hand" '' + exec bash ${../../tests/herdr-app-open-by-hand} "$@" + ''; + + # Each suite runs against a herdr-core of its own inside the build sandbox. + # hc cannot type text without pressing Enter, so text that berth holds for + # the next Enter does not show on screen until then. + herdrAppSuite = suite: pkgs.runCommand "berth-${suite}-herdr-app" + { nativeBuildInputs = [ berth pkgs.bash pkgs.coreutils pkgs.flock pkgs.herdr-core pkgs.jq ]; } '' + export BERTH_OPEN_BY_HAND=${openByHandInApp} + export BERTH_CONTRACT_GAPS=unsent-text-shows + bash ${../../tests/with-herdr-app-yard} bash ${../../tests + "/${suite}"} + touch $out + ''; in { packages.berth = berth; checks = { berth-contract-herdr = herdrSuite "berth-contract"; + berth-contract-herdr-app = herdrAppSuite "berth-contract"; + berth-herdr-app-caller = herdrAppSuite "herdr-app-caller"; berth-herdr-layout = herdrSuite "herdr-layout"; berth-herdr-lost-agent = herdrSuite "herdr-lost-agent"; berth-herdr-session = herdrSuite "herdr-session"; @@ -47,7 +64,9 @@ in ${../../tests/with-herdr-yard} ${../../tests/berth-contract} ${../../tests/herdr-layout} \ ${../../tests/herdr-state} ${../../tests/herdr-lost-agent} ${../../tests/herdr-caller} \ ${../../tests/herdr-shell-start} ${../../tests/herdr-binary} ${../../tests/herdr-session} ${../../tests/herdr-restore} \ - ${../../tests/berth-usage} ${../../tests/herdr-open-by-hand} + ${../../tests/berth-usage} ${../../tests/herdr-open-by-hand} \ + ${../../bin/berth-herdr-app} ${../../tests/with-herdr-app-yard} ${../../tests/herdr-app-open-by-hand} \ + ${../../tests/herdr-app-caller} touch $out ''; }; diff --git a/nix/berth/package.nix b/nix/berth/package.nix index f9c1f43..8b59def 100644 --- a/nix/berth/package.nix +++ b/nix/berth/package.nix @@ -1,24 +1,31 @@ -# herdr is an argument so that a host can supply its own build of it. A host -# can instead name a herdr binary at run time with BERTH_HERDR. -{ lib, stdenvNoCC, makeWrapper, bash, coreutils, jq, herdr }: +# herdr and herdr-core are arguments so that a host can supply its own builds +# of them. A host can instead name a herdr binary at run time with +# BERTH_HERDR. +{ lib, stdenvNoCC, makeWrapper, bash, coreutils, flock, jq, herdr, herdr-core }: stdenvNoCC.mkDerivation { name = "berth"; src = lib.fileset.toSource { root = ../../bin; - fileset = lib.fileset.unions [ ../../bin/berth ../../bin/berth-herdr ../../bin/berth-herdr-state ]; + fileset = lib.fileset.unions [ + ../../bin/berth + ../../bin/berth-herdr + ../../bin/berth-herdr-state + ../../bin/berth-herdr-app + ]; }; nativeBuildInputs = [ makeWrapper ]; buildInputs = [ bash ]; installPhase = '' - install -Dm755 -t $out/bin berth berth-herdr berth-herdr-state + install -Dm755 -t $out/bin berth berth-herdr berth-herdr-state berth-herdr-app wrapProgram $out/bin/berth --prefix PATH : ${lib.makeBinPath [ coreutils ]} wrapProgram $out/bin/berth-herdr --prefix PATH : ${lib.makeBinPath [ coreutils jq ]} \ --set-default BERTH_HERDR ${herdr}/bin/herdr wrapProgram $out/bin/berth-herdr-state --prefix PATH : ${lib.makeBinPath [ jq ]} + wrapProgram $out/bin/berth-herdr-app --prefix PATH : ${lib.makeBinPath [ coreutils flock jq herdr-core ]} ''; meta.mainProgram = "berth"; diff --git a/tests/berth-contract b/tests/berth-contract index 8437978..56027fa 100755 --- a/tests/berth-contract +++ b/tests/berth-contract @@ -7,7 +7,8 @@ # that opens a pane in that yard as a person would, outside berth, runs the # rest of its arguments there, and prints the pane's id. The suite reads # nothing of any backend, so a second adapter runs it unchanged, given a -# BERTH_OPEN_BY_HAND of its own. +# BERTH_OPEN_BY_HAND of its own. BERTH_CONTRACT_GAPS may name the cases its +# backend cannot meet yet, as known_gap says. # # Needs: bash, coreutils, jq, berth. set -uo pipefail @@ -27,6 +28,23 @@ check() { # fi } +# A case that BERTH_CONTRACT_GAPS names is one the adapter's backend cannot +# meet yet. It is reported rather than failed, and fails once it holds, so the +# gap is dropped as soon as the backend closes it. +known_gap() { # + case " ${BERTH_CONTRACT_GAPS:-} " in + *" $1 "*) + if [ "$3" = "$4" ]; then + echo "FAIL: $2: it holds, so drop $1 from BERTH_CONTRACT_GAPS" + failures=$((failures + 1)) + else + echo "known gap: $2" + fi + ;; + *) check "$2" "$3" "$4" ;; + esac +} + refused() { # ... local what=$1 err shift @@ -131,6 +149,8 @@ berth wait-text "$typist" "heard HELLO" --timeout 1 2>/dev/null check "text sent without a key is not submitted, so wait-text fails at its timeout" 1 "$?" check "wait-text waits out its timeout before it fails" true \ "$([ $(($(date +%s%N) - started)) -ge 1000000000 ] && echo true || echo false)" +known_gap unsent-text-shows "text sent without a key shows on screen" true \ + "$(berth read "$typist" | grep -q hello && echo true || echo false)" berth send-key "$typist" Enter BERTH_ID=$typist berth wait-text "heard HELLO" --timeout 10 @@ -163,19 +183,21 @@ berth close "$tall" echo "# state" # A backend knows Claude Code by its process name and reads its state from -# the screen, so a copy of bash named claude stands in for it and draws -# Claude's screens on cue. +# the screen, or takes the state Claude Code reports over OSC 7501. So a copy +# of bash named claude stands in for it, and draws Claude's screens and makes +# Claude's reports on cue. cp "$(command -v bash)" "$work/claude" cat >"$work/stand-in" <<'EOF' prompt_box() { printf '\n────────\n❯ \n────────\n'; } +reports() { printf '\e]7501;:state=%s:app=claude-code\e\\' "$1"; } screen=rest while :; do printf '\e[H\e[2J\e[3J' case $screen in - rest) printf '\e]0;✳ Claude\a'; prompt_box ;; - turn) printf '\e]0;⠂ Claude\a✻ Thinking… (esc to interrupt)\n' ;; - parked) printf '\e]0;⠂ Claude\a✻ Waiting for 2 background agents to finish\n'; prompt_box ;; - permission) printf '\e]0;✳ Claude\aDo you want to proceed?\n❯ 1. Yes\n 2. No\n\nEsc to cancel\n' ;; + rest) reports idle; printf '\e]0;✳ Claude\a'; prompt_box ;; + turn) reports working; printf '\e]0;⠂ Claude\a✻ Thinking… (esc to interrupt)\n' ;; + parked) reports done; printf '\e]0;⠂ Claude\a✻ Waiting for 2 background agents to finish\n'; prompt_box ;; + permission) reports 'blocked:kind=permission'; printf '\e]0;✳ Claude\aDo you want to proceed?\n❯ 1. Yes\n 2. No\n\nEsc to cancel\n' ;; leave) exit ;; esac read -r screen diff --git a/tests/berth-usage b/tests/berth-usage index 356fca1..b2243d2 100755 --- a/tests/berth-usage +++ b/tests/berth-usage @@ -90,5 +90,33 @@ refuses "name refuses a dashed label for a named berth" "${berth[@]}" name some- "${berth[@]}" name some-berth "a plain label" check "name still sets a plain label" "name some-berth a plain label" "$(cat "$calls")" +# A host such as one running herdr and the herdr app side by side names no +# backend, and the calling pane's variables choose it. +for backend in herdr herdr-app; do + { + echo "#!$BASH" + echo "echo \"$backend \$*\" >>'$calls'" + } >"$work/berth-$backend" + chmod +x "$work/berth-$backend" +done +unset BERTH_BACKEND HC_TERMINAL_ID HERDR_PANE_ID + +passes "BERTH_BACKEND wins over the calling pane" "yard" \ + env BERTH_BACKEND=recorder HC_TERMINAL_ID=t1 HERDR_PANE_ID=p1 "${berth[@]}" yard +passes "a caller in a herdr app terminal reaches the app's adapter" "herdr-app yard" \ + env HC_TERMINAL_ID=t1 "${berth[@]}" yard +passes "a caller in a herdr pane reaches herdr's adapter" "herdr yard" \ + env HERDR_PANE_ID=p1 "${berth[@]}" yard +refuses "a caller in both a herdr pane and an app terminal is refused" \ + env HC_TERMINAL_ID=t1 HERDR_PANE_ID=p1 "${berth[@]}" yard +refuses "a caller in neither is refused" "${berth[@]}" yard + +err=$(env HC_TERMINAL_ID=t1 HERDR_PANE_ID=p1 "${berth[@]}" yard 2>&1) +check "the refusal of a caller in both says so" true \ + "$(case $err in *both*) echo true ;; *) echo false ;; esac)" +err=$("${berth[@]}" yard 2>&1) +check "the refusal of a caller in neither says so" true \ + "$(case $err in *" no herdr pane or herdr app terminal"*) echo true ;; *) echo false ;; esac)" + rm -rf "$work" exit $((failures > 0)) diff --git a/tests/herdr-app-caller b/tests/herdr-app-caller new file mode 100755 index 0000000..4dc2d90 --- /dev/null +++ b/tests/herdr-app-caller @@ -0,0 +1,105 @@ +#!/usr/bin/env bash +# A caller that is not a berth, run from a herdr app terminal, acts on that +# terminal's own yard, and names no backend. See docs/design.md, "The port: +# berth". +# +# Run it under with-herdr-app-yard. It serves a second yard of its own, so +# that the default yard and a named one each hold a terminal with the same +# id, and a caller sent to the wrong yard renames the wrong terminal. +# +# Needs: bash, coreutils, herdr-core, jq, berth. +set -uo pipefail + +: "${BERTH_BACKEND:?}" +yard=named +work=$(mktemp -d) +failures=0 + +check() { # + if [ "$2" = "$3" ]; then + echo "ok: $1" + else + echo "FAIL: $1: wanted '$2', got '$3'" + failures=$((failures + 1)) + fi +} + +unset BERTH_YARD BERTH_ID +berth serve "$yard" >"$work/serve.log" 2>&1 & +serving=$! +trap 'kill "$serving" 2>/dev/null' EXIT +for _ in $(seq 1 100); do + berth list "$yard" >/dev/null 2>&1 && break + sleep 0.1 +done + +hand() { # ... + env -u HC_TERMINAL_SOCKET -u HC_TERMINAL_ID HC_SESSION="$1" hc "$2" --json "${@:3}" +} + +new_terminal() { # + hand "$1" run --bg --no-parent --no-notify --cwd "$work" | jq -r .address +} + +label() { # + hand "$1" get "$2" | jq -r '.labels["berth.label"] // "none"' +} + +# Runs a command in the terminal's own shell, with no backend named and +# nothing else but what herdr-core gave it, and waits for it to finish. Its +# output, errors and exit status land in .out, .err and +# .status. +runs() { # + local _ + hand "$1" send -- "$2" \ + "env -u BERTH_BACKEND $4 >'$work/$3.out' 2>'$work/$3.err'; echo \$? >'$work/$3.status'" >/dev/null + for _ in $(seq 1 100); do + [ -s "$work/$3.status" ] && break + sleep 0.1 + done +} + +renames() { #