diff --git a/bin/berth-herdr-app b/bin/berth-herdr-app index a27e765..6bf1d79 100755 --- a/bin/berth-herdr-app +++ b/bin/berth-herdr-app @@ -115,19 +115,90 @@ 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") +# 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() { # + printf '%s%s\n' "$1" "$(od -An -N16 -tx1 /dev/urandom | tr -d ' \n')" +} + +# Nothing can measure the window's panes while it may be closed, so a count +# stands in for the size floors that herdr's adapter measures. +workers_per_tab=4 + +# The tab in the opener's space where its next worker goes: the oldest of its +# workers' tabs that has room. +worker_tab() { # + local tab + tab=$(terminals | jq -r --arg opener "$1" --arg space "$2" --argjson most "$workers_per_tab" ' + [.[] | select(.labels["berth.parent"] == $opener and .labels["berth.relationship"] == "worker" + and .labels["herdr.space"] == $space)] | sort_by(.created_ms) | map(.labels["herdr.tab"]) as $tabs + | first($tabs[] as $tab | select([$tabs[] | select(. == $tab)] | length < $most) | $tab) // empty') + [ -n "$tab" ] || tab=$(new_place_id tb) + printf '%s\n' "$tab" +} + +# Names and focus belong to the window, so they wait on no window. A closed +# one leaves Herdr's own names. The window may not have seen a new terminal's +# labels yet, so a refusal is tried again for a while. +window_wait_seconds=5 + +window() { # ... + local out deadline=$((SECONDS + window_wait_seconds)) + command -v herdr-app >/dev/null && herdr-app status >/dev/null 2>&1 || return 0 + until out=$(herdr-app "do" "$@" 2>&1); do + if [ "$SECONDS" -ge "$deadline" ]; then + echo "berth (herdr-app): the window refused $1: $out" >&2 + return 0 + fi + sleep 0.2 + done +} + +# Names whatever an independent berth's place gives it: the space and its +# first tab for one opened apart, and the tab for one opened in a tab. The +# window takes a command with no id to mean what it shows, so a berth that +# the window does not show names nothing. +name_place() { #