Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
134 changes: 126 additions & 8 deletions bin/berth-herdr-app
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,108 @@ terminal_agent_state() { # <terminal>
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. 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() { # <terminal>
jq -r --arg dir "$(state_dir)" '"\($dir)/\(.address).\(.created_ms).command"' <<<"$1"
}

keep_command() { # <id> <command>...
local file
file=$(kept_command "$(existing_terminal "$1" "its command cannot be kept")")
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)'

# 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, the last just before typing.
shell_settle_polls=4
shell_poll_seconds=0.25

shell_settled() { # <id>
local _
for _ in $(seq 1 "$shell_settle_polls"); do
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. hc types
# nothing into a program that reports itself blocked.
type_command() { # <terminal> <outcome> <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 -- "$id" "$line" >/dev/null
hc_call label "$id" "berth.restore=$pid $2" >/dev/null
}

not_resumed() { # <terminal> <why>
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 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 "$terminal")
[ -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 >/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
}

# The window shows a terminal labelled with herdr.space and herdr.tab in that
# space and tab, and makes a new one for an id it does not know.
new_place_id() { # <sp|tb>
Expand Down Expand Up @@ -193,8 +295,9 @@ name_place() { # <terminal> <label>

open() {
local as=$1 place=$2 focus=$3 cwd=$4 label=$5 opener=$6 id line="" opener_terminal space="" tab=""
local workers_tab="" labels=()
local workers_tab="" labels=() tender restoring
shift 6
resume_seats

if [ "$as" = independent ] && [ "$place" = apart ]; then
opener=""
Expand All @@ -221,24 +324,36 @@ open() {
fi
labels+=(${space:+--label "herdr.space=$space"} ${tab:+--label "herdr.tab=$tab"})

# 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" '
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) | .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
restore_unlock
printf '%s\n' "$id"
return
fi
restore_unlock
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
if [ -n "$space" ]; then
[ -z "$label" ] || name_place "$(hc_call get "$id")" "$label"
Expand All @@ -251,6 +366,7 @@ open() {
name() {
local id terminal
id=$(berth_id "$1")
resume_seats
terminal=$(existing_terminal "$id" "it cannot be named")
hc_call label "$id" "berth.label=$2" >/dev/null
name_place "$terminal" "$2"
Expand Down Expand Up @@ -282,7 +398,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() { # <id>
echo "${XDG_STATE_HOME:-$HOME/.local/state}/berth/herdr-app/$yard/$1.text"
echo "$(state_dir)/$1.text"
}

send_text() {
Expand Down Expand Up @@ -339,6 +455,7 @@ read_screen() {
# left, so a berth with no agent state lists none.
list() { # <yard> <berths|all>
yard=${1:-$yard}
resume_seats
terminals | jq --arg scope "$2" "$agent_state_of"'
[.[] | agent_state as $agent
| (.labels["berth.relationship"] // null) as $relationship
Expand Down Expand Up @@ -379,6 +496,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) ;;
Expand All @@ -390,7 +508,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")" "$(state_dir)/$id".*.command
}

verb=$1
Expand Down
1 change: 1 addition & 0 deletions docs/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ The herdr desktop app runs its terminals in its own backend, herdr-core, and nev
- **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/<yard>/` 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.
- **Layout.** The window shows a terminal in the space and tab that its `herdr.space` and `herdr.tab` labels name, and makes a new space or tab for an id it does not know. So the adapter places a berth through those labels alone, and placement works while the window is closed. An independent berth that opens apart gets a new space. One opened in a tab gets a new tab in its opener's space. One opened beside its opener, and a tender, join the opener's tab, and the window chooses the split. Workers share a tab in their opener's space, four to a tab, and then open another. The window may be closed, so nothing can measure its panes, and the count stands in for herdr's size floors. A berth whose opener the window does not show stays hidden too.
- **Names and focus.** Only the window can name a pane, a space or a tab, or move focus, so the adapter asks it through `herdr-app` when one is open. A berth's label names its pane, and its space and tab, as it does under herdr, and a new workers' tab is called `workers`. The window names a pane by the pane's id, so the adapter finds the pane that shows a berth's terminal in `herdr-app ls`. With the window closed, Herdr's own names stand, and `--focus` does nothing. Naming a pane needs the app at 0.1.17 or later.
- **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/<yard>/` 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 <session>` 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.** 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.

Expand Down
6 changes: 4 additions & 2 deletions nix/berth/default.nix
Original file line number Diff line number Diff line change
Expand Up @@ -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} "$@"
Expand All @@ -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}"}
Expand All @@ -39,6 +40,7 @@ in
berth-contract-herdr-app = herdrAppSuite "berth-contract";
berth-herdr-app-caller = herdrAppSuite "herdr-app-caller";
berth-herdr-app-layout = herdrAppSuite "herdr-app-layout";
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";
Expand Down Expand Up @@ -67,7 +69,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-layout}
${../../tests/herdr-app-caller} ${../../tests/herdr-app-layout} ${../../tests/herdr-app-restore}
touch $out
'';
};
Expand Down
Loading