From 645234d3a54e5553d407243862ec9ee6faeb1db9 Mon Sep 17 00:00:00 2001 From: Graeme Foster <80714+GraemeF@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:43:42 +0000 Subject: [PATCH 1/3] feat(berth): resume a seat after the herdr app's core restarts herdr-core brings a kept terminal back as a bare shell and does not resume agents. The app adapter now keeps every berth, keeps its command where only its user can read it, and on the next call types the command back with --resume in place of the prompt, then has sign-on pass the startup gate. --- bin/berth-herdr-app | 113 ++++++++++++++++++++++++++++++--- docs/design.md | 1 + nix/berth/default.nix | 6 +- tests/herdr-app-restore | 135 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 245 insertions(+), 10 deletions(-) create mode 100755 tests/herdr-app-restore diff --git a/bin/berth-herdr-app b/bin/berth-herdr-app index a27e765..51cfdec 100755 --- a/bin/berth-herdr-app +++ b/bin/berth-herdr-app @@ -115,10 +115,95 @@ terminal_agent_state() { # berth_command=("$BASH" -c 'export BERTH_BACKEND=herdr-app BERTH_YARD=$1 BERTH_ID=$HC_TERMINAL_ID shift; "$@"; exec "${SHELL:-sh}"' berth "$yard") +state_dir() { + echo "${XDG_STATE_HOME:-$HOME/.local/state}/berth/herdr-app/$yard" +} + +# A berth's command is kept where only its user can read it, because sign-on +# passes a seat's environment, secrets included, on its command line. +kept_command() { # + echo "$(state_dir)/$1.command" +} + +keep_command() { # ... + local file + file=$(kept_command "$1") + shift + (umask 077 && mkdir -p "${file%/*}" && printf '%s\0' "$@" >"$file") +} + +# herdr-core restarts a kept terminal with the shell alone as its program. The +# berth.restore label names the shell the adapter has already acted on. +restored='(.argv | length) == 1 and ((.labels["berth.restore"] // "") | split(" ")[0]) != (.pid | tostring)' + +# The shell is alone in the foreground for a moment before its start-up runs +# anything, such as a dev shell's hook that would swallow typed text, so it +# has to stay alone for several polls in a row. +shell_settle_polls=4 +shell_poll_seconds=0.25 + +shell_settled() { # + local _ + for _ in $(seq 1 "$shell_settle_polls"); do + terminal_get "$1" | jq -e '.foreground.pid == .pid' >/dev/null || return 1 + sleep "$shell_poll_seconds" + done +} + +# Types a command into a restored berth's shell, under the berth's own +# variables, and says on the terminal what was done with its shell. +type_command() { # ... + local id pid line + id=$(jq -r .address <<<"$1") + pid=$(jq -r .pid <<<"$1") + printf -v line '%q ' env BERTH_BACKEND=herdr-app "BERTH_YARD=$yard" "BERTH_ID=$id" "${@:3}" + hc_call send --force -- "$id" "$line" >/dev/null + hc_call label "$id" "berth.restore=$pid $2" >/dev/null +} + +not_resumed() { # + local id pid + id=$(jq -r .address <<<"$1") + pid=$(jq -r .pid <<<"$1") + echo "berth (herdr-app): the berth $id is not resumed, because $2. Its shell is left bare." >&2 + hc_call label "$id" "berth.restore=$pid not resumed: $2" >/dev/null +} + +# Resumes each seat that herdr-core restored, from the session id the plugin's +# mod left on its terminal. sign-on launches a seat with its prompt last, after +# --, so the resume takes the prompt's place. sign-on then gets the seat past +# its startup gate. +resume_seats() { + local seats terminal id file command at + mapfile -t seats < <(terminals | jq -c ".[] | select(.labels[\"berth.relationship\"] and .labels[\"claude.session\"] and $restored)") + for terminal in "${seats[@]}"; do + id=$(jq -r .address <<<"$terminal") + shell_settled "$id" || continue + file=$(kept_command "$id") + [ -f "$file" ] || { not_resumed "$terminal" "its command was not kept"; continue; } + mapfile -d '' -t command <"$file" + for ((at = 0; at < ${#command[@]}; at++)); do + [ "${command[at]}" != -- ] || break + done + case $((${#command[@]} - at)) in + 0) ;; + 2) command=("${command[@]:0:at}") ;; + *) not_resumed "$terminal" "its command has more after -- than a prompt"; continue ;; + esac + type_command "$terminal" resumed "${command[@]}" --resume "$(jq -r '.labels["claude.session"]' <<<"$terminal")" + if command -v sign-on >/dev/null; then + BERTH_BACKEND=herdr-app BERTH_YARD=$yard sign-on --pass-gate "$id" /dev/null 2>&1 & + else + echo "berth (herdr-app): sign-on is not on the path, so the berth $id waits at its startup gate." >&2 + fi + done +} + open() { - local as=$1 place=$2 cwd=$4 label=$5 opener=$6 id line="" labels=() + local as=$1 place=$2 cwd=$4 label=$5 opener=$6 id line="" labels=() tender shift 6 # Focus belongs to the window, which places no berth yet. + resume_seats if [ "$as" = independent ] && [ "$place" = apart ]; then opener="" @@ -129,24 +214,33 @@ open() { labels+=(--label "berth.line=$line") fi + # A tender that herdr-core restored is adopted with its command started + # again. if [ "$as" = tender ] && [ -n "$label" ]; then - id=$(terminals | jq -r --arg line "$line" --arg label "$label" ' + tender=$(terminals | jq -c --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 + and .labels["berth.label"] == $label)) // empty') + if [ -n "$tender" ]; then + id=$(jq -r .address <<<"$tender") hc_call label "$id" "berth.parent=$opener" >/dev/null + if jq -e "$restored" <<<"$tender" >/dev/null && shell_settled "$id"; then + type_command "$tender" "ran again" "$@" + keep_command "$id" "$@" + fi printf '%s\n' "$id" return fi fi # Closing its opener leaves an independent berth, so its opener is not its - # parent. + # parent. A kept terminal comes back as a bare shell when herdr-core + # restarts, where a terminal not kept would come back finished. [ "$as" = independent ] || labels+=(--label "berth.parent=$opener") - id=$(hc_call run --bg --no-parent --no-notify --cwd "$cwd" \ + id=$(hc_call run --bg --keep --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) + keep_command "$id" "$@" [ -n "$line" ] || hc_call label "$id" "berth.line=$id" >/dev/null printf '%s\n' "$id" } @@ -154,6 +248,7 @@ open() { name() { local id id=$(berth_id "$1") + resume_seats existing_terminal "$id" "it cannot be named" >/dev/null hc_call label "$id" "berth.label=$2" >/dev/null } @@ -184,7 +279,7 @@ yards() { # 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" + echo "$(state_dir)/$1.text" } send_text() { @@ -241,6 +336,7 @@ read_screen() { # left, so a berth with no agent state lists none. list() { # yard=${1:-$yard} + resume_seats terminals | jq --arg scope "$2" "$agent_state_of"' [.[] | agent_state as $agent | (.labels["berth.relationship"] // null) as $relationship @@ -281,6 +377,7 @@ agent_state() { close() { local id child status=0 id=$(berth_id "$1") + resume_seats terminal_get "$id" >/dev/null || status=$? case $status in 0) ;; @@ -292,7 +389,7 @@ close() { done hc_call kill "$id" >/dev/null || [ $? = 3 ] hc_call rm "$id" >/dev/null || [ $? = 3 ] - rm -f "$(held_text "$id")" + rm -f "$(held_text "$id")" "$(kept_command "$id")" } verb=$1 diff --git a/docs/design.md b/docs/design.md index 74bc088..cfef67c 100644 --- a/docs/design.md +++ b/docs/design.md @@ -148,6 +148,7 @@ The herdr desktop app runs its terminals in its own backend, herdr-core, and nev - **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. +- **Restore.** herdr-core brings back only a terminal opened to be kept, and when it restarts, it gives that terminal the same id and labels and a bare shell. herdr-core does not resume an agent, so the adapter resumes its own seats. It opens every berth to be kept, and keeps the berth's command in a file under `berth/herdr-app//` that only its user can read, because sign-on passes a seat's environment on the command line. The next `open`, `name`, `list` or `close` finds each restored berth whose terminal holds a `claude.session` label and whose shell sits alone in the foreground. It types the kept command back into the shell under the berth's own `BERTH_*` variables, with `--resume ` in place of the prompt, and starts `sign-on --pass-gate` for the berth in the background. sign-on puts the prompt last, after `--`. Where the kept command has more than a prompt after `--`, or no command was kept, the adapter leaves the shell bare and says why on standard error. The terminal's `berth.restore` label names the shell the adapter acted on and what it did, so a later call leaves it alone. When `open` adopts a restored tender, it types the tender's command in again. This restore can go once herdr-core resumes agents itself. - **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. diff --git a/nix/berth/default.nix b/nix/berth/default.nix index c07f581..bf4e315 100644 --- a/nix/berth/default.nix +++ b/nix/berth/default.nix @@ -2,6 +2,7 @@ let berth = pkgs.callPackage ./package.nix { }; + sign-on = pkgs.callPackage ../sign-on/package.nix { }; openByHand = pkgs.writeShellScript "herdr-open-by-hand" '' exec bash ${../../tests/herdr-open-by-hand} "$@" @@ -24,7 +25,7 @@ let # 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 ]; } '' + { nativeBuildInputs = [ berth sign-on 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}"} @@ -38,6 +39,7 @@ in berth-contract-herdr = herdrSuite "berth-contract"; berth-contract-herdr-app = herdrAppSuite "berth-contract"; berth-herdr-app-caller = herdrAppSuite "herdr-app-caller"; + berth-herdr-app-restore = herdrAppSuite "herdr-app-restore"; berth-herdr-layout = herdrSuite "herdr-layout"; berth-herdr-lost-agent = herdrSuite "herdr-lost-agent"; berth-herdr-session = herdrSuite "herdr-session"; @@ -66,7 +68,7 @@ in ${../../tests/herdr-shell-start} ${../../tests/herdr-binary} ${../../tests/herdr-session} ${../../tests/herdr-restore} \ ${../../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} + ${../../tests/herdr-app-caller} ${../../tests/herdr-app-restore} touch $out ''; }; diff --git a/tests/herdr-app-restore b/tests/herdr-app-restore new file mode 100755 index 0000000..617d55f --- /dev/null +++ b/tests/herdr-app-restore @@ -0,0 +1,135 @@ +#!/usr/bin/env bash +# The herdr app adapter brings its seats back as agents after herdr-core +# restarts. See docs/design.md, "The herdr app adapter". +# +# The yard's core is stopped and served again, which is when herdr-core gives +# each kept terminal a bare shell. The core this suite serves is stopped by the +# pid it was started with, and by nothing else. +# +# Run it under with-herdr-app-yard. +# +# Needs: bash, coreutils, flock, herdr-core, jq, berth, sign-on. +set -uo pipefail + +: "${BERTH_BACKEND:?}" +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 +} + +eventually() { # ... + local _ + for _ in $(seq 1 300); do + "$@" && return 0 + sleep 0.1 + done + return 1 +} + +# A stand-in for Claude Code shows a startup gate, then records the session +# id on its terminal as the plugin's mod does, and reports itself at rest. Each +# start logs what it was started with. +export SIGN_ON_GATE="Press Enter to go on" +echo "#!$(command -v bash)" >"$work/claude" +cat >>"$work/claude" <<'EOF' +log=$1 +shift +echo "args=$* id=$BERTH_ID yard=$BERTH_YARD backend=$BERTH_BACKEND seat=${SEAT:-none}" >>"$log" +echo "$SIGN_ON_GATE" +read -r +echo passed >>"$log" +hc label "$HC_TERMINAL_ID" claude.session=s-1 >/dev/null +printf '\e]7501;:state=idle:app=claude-code\e\\' +exec sleep 600 +EOF +chmod +x "$work/claude" + +starts() { # + grep -c '^args=' "$1" 2>/dev/null || echo 0 +} + +passed() { # + grep -c '^passed$' "$1" 2>/dev/null || echo 0 +} + +session_of() { # + berth list 2>>"$work/list.err" | jq -r --arg id "$1" '.[] | select(.id == $id) | .agent_session // "none"' +} + +has_session() { # + [ "$(session_of "$1")" = s-1 ] +} + +# sign-on puts the seat's environment before the command, and its prompt last +# after --. +seat=$(berth open --as independent --cwd "$work" --label seat -- \ + env SEAT=one "$work/claude" "$work/seat.log" --model m -- "the first prompt") +eventually test "$(starts "$work/seat.log")" = 1 +berth send-key "$seat" Enter +eventually has_session "$seat" + +# A command whose -- is not just before its last word is not one the adapter +# knows how to resume. +odd=$(berth open --as independent --cwd "$work" --label odd -- \ + "$work/claude" "$work/odd.log" -- "a prompt" --model m) +eventually test "$(starts "$work/odd.log")" = 1 +berth send-key "$odd" Enter +eventually has_session "$odd" + +viewer() { # + BERTH_ID=$1 berth open --as tender --cwd "$work" --label viewer -- \ + bash -c "echo run >>$(printf '%q' "$work/viewer-runs"); exec sleep 600" +} +view=$(viewer "$seat") +eventually test "$(wc -l <"$work/viewer-runs" 2>/dev/null)" = 1 + +echo "# herdr-core restarts" + +yard_down() { + ! berth yards | grep -qx "$BERTH_YARD" +} +berth stop "$BERTH_YARD" +eventually yard_down +berth serve "$BERTH_YARD" >"$work/serve.log" 2>&1 & +serving=$! +trap 'kill "$serving" 2>/dev/null; wait "$serving" 2>/dev/null' EXIT +eventually berth list >/dev/null 2>&1 || { echo "the core did not come back."; cat "$work/serve.log"; exit 1; } + +eventually has_session "$seat" +check "a seat comes back under the same berth with its agent session" s-1 "$(session_of "$seat")" +check "the seat starts once more" 2 "$(starts "$work/seat.log")" +check "it resumes its session in place of its prompt, under its own environment" \ + "args=--model m --resume s-1 id=$seat yard=$BERTH_YARD backend=herdr-app seat=one" \ + "$(tail -n 2 "$work/seat.log" | head -n 1)" +eventually test "$(passed "$work/seat.log")" = 2 +check "sign-on gets it past its startup gate" 2 "$(passed "$work/seat.log")" + +berth list >/dev/null 2>&1 +sleep 1 +check "a later call does not resume it again" 2 "$(starts "$work/seat.log")" + +check "a seat whose command the adapter does not know is left at its shell" 1 "$(starts "$work/odd.log")" +check "and berth says why" true \ + "$(grep -q "berth $odd .*not resumed" "$work/list.err" && echo true || echo false)" + +check "a restored viewer is adopted by its label" "$view" "$(viewer "$seat")" +eventually test "$(wc -l <"$work/viewer-runs")" = 2 +check "and runs its command again" 2 "$(wc -l <"$work/viewer-runs")" + +for id in "$view" "$odd" "$seat"; do + berth close "$id" +done + +echo +if [ "$failures" -gt 0 ]; then + echo "$failures failed." + exit 1 +fi +echo "The herdr app adapter brings its seats back as agents after a restart." From df35490c2df8e1414f4a5a22cb6b7e034c3b0b82 Mon Sep 17 00:00:00 2001 From: Graeme Foster <80714+GraemeF@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:44:17 +0000 Subject: [PATCH 2/3] docs: reword the app adapter's restore opening --- docs/design.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/design.md b/docs/design.md index cfef67c..2310cd8 100644 --- a/docs/design.md +++ b/docs/design.md @@ -148,7 +148,7 @@ The herdr desktop app runs its terminals in its own backend, herdr-core, and nev - **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. -- **Restore.** herdr-core brings back only a terminal opened to be kept, and when it restarts, it gives that terminal the same id and labels and a bare shell. herdr-core does not resume an agent, so the adapter resumes its own seats. It opens every berth to be kept, and keeps the berth's command in a file under `berth/herdr-app//` that only its user can read, because sign-on passes a seat's environment on the command line. The next `open`, `name`, `list` or `close` finds each restored berth whose terminal holds a `claude.session` label and whose shell sits alone in the foreground. It types the kept command back into the shell under the berth's own `BERTH_*` variables, with `--resume ` in place of the prompt, and starts `sign-on --pass-gate` for the berth in the background. sign-on puts the prompt last, after `--`. Where the kept command has more than a prompt after `--`, or no command was kept, the adapter leaves the shell bare and says why on standard error. The terminal's `berth.restore` label names the shell the adapter acted on and what it did, so a later call leaves it alone. When `open` adopts a restored tender, it types the tender's command in again. This restore can go once herdr-core resumes agents itself. +- **Restore.** herdr-core brings back only a terminal opened to be kept. A restart gives that terminal its id and labels back, with a bare shell. herdr-core does not resume an agent, so the adapter resumes its own seats. It opens every berth to be kept, and keeps the berth's command in a file under `berth/herdr-app//` that only its user can read, because sign-on passes a seat's environment on the command line. The next `open`, `name`, `list` or `close` finds each restored berth whose terminal holds a `claude.session` label and whose shell sits alone in the foreground. It types the kept command back into the shell under the berth's own `BERTH_*` variables, with `--resume ` in place of the prompt, and starts `sign-on --pass-gate` for the berth in the background. sign-on puts the prompt last, after `--`. Where the kept command has more than a prompt after `--`, or no command was kept, the adapter leaves the shell bare and says why on standard error. The terminal's `berth.restore` label names the shell the adapter acted on and what it did, so a later call leaves it alone. When `open` adopts a restored tender, it types the tender's command in again. This restore can go once herdr-core resumes agents itself. - **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. From a42b47a02c2ce39f51e85fcc95e37f857ed7b900 Mon Sep 17 00:00:00 2001 From: Graeme Foster <80714+GraemeF@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:18:21 +0000 Subject: [PATCH 3/3] fix(berth): restore a yard's seats one call at a time Two berth calls at once could each type the resume line into the same restored shell, sending the second into the agent the first had started. The restore now holds a per-yard lock, sends nothing to a program that reports itself blocked, and names each kept command for its terminal's creation as well as its id. --- bin/berth-herdr-app | 47 +++++++++++++++++++++++++++++------------ docs/design.md | 2 +- tests/herdr-app-restore | 36 ++++++++++++++++++++++++------- 3 files changed, 63 insertions(+), 22 deletions(-) diff --git a/bin/berth-herdr-app b/bin/berth-herdr-app index 51cfdec..9542592 100755 --- a/bin/berth-herdr-app +++ b/bin/berth-herdr-app @@ -120,14 +120,16 @@ state_dir() { } # A berth's command is kept where only its user can read it, because sign-on -# passes a seat's environment, secrets included, on its command line. -kept_command() { # - echo "$(state_dir)/$1.command" +# passes a seat's environment, secrets included, on its command line. The file +# is named for the terminal's creation as well as its id, so a command never +# reaches a terminal it was not opened in. +kept_command() { # + jq -r --arg dir "$(state_dir)" '"\($dir)/\(.address).\(.created_ms).command"' <<<"$1" } keep_command() { # ... local file - file=$(kept_command "$1") + file=$(kept_command "$(existing_terminal "$1" "its command cannot be kept")") shift (umask 077 && mkdir -p "${file%/*}" && printf '%s\0' "$@" >"$file") } @@ -136,28 +138,42 @@ keep_command() { # ... # berth.restore label names the shell the adapter has already acted on. restored='(.argv | length) == 1 and ((.labels["berth.restore"] // "") | split(" ")[0]) != (.pid | tostring)' +# Two berth calls at once would each type into the same restored shell, and +# the second line would land in the agent the first one started. So one call +# at a time restores a yard, and it reads the terminals once it holds the lock. +restore_lock() { + mkdir -p "$(state_dir)" + exec {restoring}>"$(state_dir)/restore.lock" + flock "$restoring" +} + +restore_unlock() { + exec {restoring}>&- +} + # The shell is alone in the foreground for a moment before its start-up runs # anything, such as a dev shell's hook that would swallow typed text, so it -# has to stay alone for several polls in a row. +# has to stay alone for several polls in a row, the last just before typing. shell_settle_polls=4 shell_poll_seconds=0.25 shell_settled() { # local _ for _ in $(seq 1 "$shell_settle_polls"); do - terminal_get "$1" | jq -e '.foreground.pid == .pid' >/dev/null || return 1 sleep "$shell_poll_seconds" + terminal_get "$1" | jq -e '.foreground.pid == .pid' >/dev/null || return 1 done } # Types a command into a restored berth's shell, under the berth's own -# variables, and says on the terminal what was done with its shell. +# variables, and says on the terminal what was done with its shell. hc types +# nothing into a program that reports itself blocked. type_command() { # ... local id pid line id=$(jq -r .address <<<"$1") pid=$(jq -r .pid <<<"$1") printf -v line '%q ' env BERTH_BACKEND=herdr-app "BERTH_YARD=$yard" "BERTH_ID=$id" "${@:3}" - hc_call send --force -- "$id" "$line" >/dev/null + hc_call send -- "$id" "$line" >/dev/null hc_call label "$id" "berth.restore=$pid $2" >/dev/null } @@ -174,12 +190,13 @@ not_resumed() { # # --, so the resume takes the prompt's place. sign-on then gets the seat past # its startup gate. resume_seats() { - local seats terminal id file command at + local seats terminal id file command at restoring + restore_lock mapfile -t seats < <(terminals | jq -c ".[] | select(.labels[\"berth.relationship\"] and .labels[\"claude.session\"] and $restored)") for terminal in "${seats[@]}"; do id=$(jq -r .address <<<"$terminal") shell_settled "$id" || continue - file=$(kept_command "$id") + file=$(kept_command "$terminal") [ -f "$file" ] || { not_resumed "$terminal" "its command was not kept"; continue; } mapfile -d '' -t command <"$file" for ((at = 0; at < ${#command[@]}; at++)); do @@ -192,15 +209,16 @@ resume_seats() { esac type_command "$terminal" resumed "${command[@]}" --resume "$(jq -r '.labels["claude.session"]' <<<"$terminal")" if command -v sign-on >/dev/null; then - BERTH_BACKEND=herdr-app BERTH_YARD=$yard sign-on --pass-gate "$id" /dev/null 2>&1 & + BERTH_BACKEND=herdr-app BERTH_YARD=$yard sign-on --pass-gate "$id" /dev/null 2>&1 {restoring}>&- & else echo "berth (herdr-app): sign-on is not on the path, so the berth $id waits at its startup gate." >&2 fi done + restore_unlock } open() { - local as=$1 place=$2 cwd=$4 label=$5 opener=$6 id line="" labels=() tender + local as=$1 place=$2 cwd=$4 label=$5 opener=$6 id line="" labels=() tender restoring shift 6 # Focus belongs to the window, which places no berth yet. resume_seats @@ -217,6 +235,7 @@ open() { # A tender that herdr-core restored is adopted with its command started # again. if [ "$as" = tender ] && [ -n "$label" ]; then + restore_lock tender=$(terminals | jq -c --arg line "$line" --arg label "$label" ' first(.[] | select(.labels["berth.relationship"] == "tender" and .labels["berth.line"] == $line and .labels["berth.label"] == $label)) // empty') @@ -227,9 +246,11 @@ open() { type_command "$tender" "ran again" "$@" keep_command "$id" "$@" fi + restore_unlock printf '%s\n' "$id" return fi + restore_unlock fi # Closing its opener leaves an independent berth, so its opener is not its @@ -389,7 +410,7 @@ close() { done hc_call kill "$id" >/dev/null || [ $? = 3 ] hc_call rm "$id" >/dev/null || [ $? = 3 ] - rm -f "$(held_text "$id")" "$(kept_command "$id")" + rm -f "$(held_text "$id")" "$(state_dir)/$id".*.command } verb=$1 diff --git a/docs/design.md b/docs/design.md index 2310cd8..8f21ca8 100644 --- a/docs/design.md +++ b/docs/design.md @@ -148,7 +148,7 @@ The herdr desktop app runs its terminals in its own backend, herdr-core, and nev - **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. -- **Restore.** herdr-core brings back only a terminal opened to be kept. A restart gives that terminal its id and labels back, with a bare shell. herdr-core does not resume an agent, so the adapter resumes its own seats. It opens every berth to be kept, and keeps the berth's command in a file under `berth/herdr-app//` that only its user can read, because sign-on passes a seat's environment on the command line. The next `open`, `name`, `list` or `close` finds each restored berth whose terminal holds a `claude.session` label and whose shell sits alone in the foreground. It types the kept command back into the shell under the berth's own `BERTH_*` variables, with `--resume ` in place of the prompt, and starts `sign-on --pass-gate` for the berth in the background. sign-on puts the prompt last, after `--`. Where the kept command has more than a prompt after `--`, or no command was kept, the adapter leaves the shell bare and says why on standard error. The terminal's `berth.restore` label names the shell the adapter acted on and what it did, so a later call leaves it alone. When `open` adopts a restored tender, it types the tender's command in again. This restore can go once herdr-core resumes agents itself. +- **Restore.** herdr-core brings back only a terminal opened to be kept. A restart gives that terminal its id and labels back, with a bare shell. herdr-core does not resume an agent, so the adapter resumes its own seats. It opens every berth to be kept, and keeps the berth's command in a file under `berth/herdr-app//` that only its user can read, because sign-on passes a seat's environment on the command line. The file is named for the terminal's id and its creation time, so a command never reaches a terminal it was not opened in. One call at a time restores a yard, under a lock in the same folder, so two calls never both type into one shell. The next `open`, `name`, `list` or `close` finds each restored berth whose terminal holds a `claude.session` label and whose shell sits alone in the foreground. It types the kept command back into the shell under the berth's own `BERTH_*` variables, with `--resume ` in place of the prompt, and starts `sign-on --pass-gate` for the berth in the background. sign-on puts the prompt last, after `--`. Where the kept command has more than a prompt after `--`, or no command was kept, the adapter leaves the shell bare and says why on standard error. The terminal's `berth.restore` label names the shell the adapter acted on and what it did, so a later call leaves it alone. When `open` adopts a restored tender, it types the tender's command in again. This restore can go once herdr-core resumes agents itself. - **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. diff --git a/tests/herdr-app-restore b/tests/herdr-app-restore index 617d55f..8a7911c 100755 --- a/tests/herdr-app-restore +++ b/tests/herdr-app-restore @@ -43,8 +43,8 @@ log=$1 shift echo "args=$* id=$BERTH_ID yard=$BERTH_YARD backend=$BERTH_BACKEND seat=${SEAT:-none}" >>"$log" echo "$SIGN_ON_GATE" -read -r -echo passed >>"$log" +read -r reply +echo "passed${reply:+ $reply}" >>"$log" hc label "$HC_TERMINAL_ID" claude.session=s-1 >/dev/null printf '\e]7501;:state=idle:app=claude-code\e\\' exec sleep 600 @@ -56,7 +56,7 @@ starts() { # } passed() { # - grep -c '^passed$' "$1" 2>/dev/null || echo 0 + grep -c '^passed' "$1" 2>/dev/null || echo 0 } session_of() { # @@ -95,12 +95,31 @@ echo "# herdr-core restarts" yard_down() { ! berth yards | grep -qx "$BERTH_YARD" } -berth stop "$BERTH_YARD" -eventually yard_down -berth serve "$BERTH_YARD" >"$work/serve.log" 2>&1 & -serving=$! +yard_up() { + ! yard_down +} +# Serving straight after a stop now and then finds the yard briefly held by +# a core the suite did not start, so the suite serves until its own core +# holds the yard. +serving="" trap 'kill "$serving" 2>/dev/null; wait "$serving" 2>/dev/null' EXIT -eventually berth list >/dev/null 2>&1 || { echo "the core did not come back."; cat "$work/serve.log"; exit 1; } +serve_again() { + eventually yard_down || return 1 + berth serve "$BERTH_YARD" >"$work/serve.log" 2>&1 & + serving=$! + eventually yard_up && sleep 0.5 && kill -0 "$serving" 2>/dev/null +} +berth stop "$BERTH_YARD" +for _ in 1 2 3 4 5; do + ! serve_again || break +done +kill -0 "$serving" 2>/dev/null || { echo "the core did not come back."; cat "$work/serve.log"; exit 1; } + +# The first calls after the restart race each other to resume the seats. +berth list >/dev/null 2>>"$work/list.err" & +first=$! +berth list >/dev/null 2>>"$work/list.err" & +wait "$first" $! eventually has_session "$seat" check "a seat comes back under the same berth with its agent session" s-1 "$(session_of "$seat")" @@ -110,6 +129,7 @@ check "it resumes its session in place of its prompt, under its own environment" "$(tail -n 2 "$work/seat.log" | head -n 1)" eventually test "$(passed "$work/seat.log")" = 2 check "sign-on gets it past its startup gate" 2 "$(passed "$work/seat.log")" +check "and nothing else is typed into it" passed "$(grep '^passed' "$work/seat.log" | tail -n 1)" berth list >/dev/null 2>&1 sleep 1