herdr-gentle-shell 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/DESIGN.md CHANGED
@@ -19,7 +19,8 @@ explicitly in §10 and are not decided here.
19
19
  - The human operator watching Pi + Gentle Shell agents: needs to distinguish
20
20
  generic activity (`gentle`, machine key `working`) vs the active TaskStore role (`explorer`,
21
21
  `worker`, `verify`, `rdd`), `ask` (blocked on user input), `blocked`
22
- (error), `done`, and `idle` at a glance. No visible text ever carries
22
+ (the row word for the `error` key), `done`, and `idle` at a glance. No
23
+ visible text ever carries
23
24
  a subagent count, and generic activity never reads `working`.
24
25
 
25
26
  ### Current boundary and interaction
@@ -130,7 +131,8 @@ an explicit writer-ownership decision. Rationale follows each choice.
130
131
  `error:`) plus the native `pane.report_agent` state; desktop attention is
131
132
  native Herdr exclusively (E9 unchanged): `Blocked` fires the `NeedsAttention`
132
133
  toast and background `Working|Blocked → Idle` fires `Finished`, both
133
- Herdr-owned. The consumer emits `herdr notification` for nothing — its
134
+ Herdr-owned. Native `blocked` is emitted for an actual human-wait
135
+ intervention only: an error is sidebar-only, so no attention fires for it. The consumer emits `herdr notification` for nothing — its
134
136
  former ask toast fired on the poll after the native one for the same
135
137
  question, a systematic duplication, so the toast path, its copy, the
136
138
  notification ledger and the send machinery were removed in v0.3.1. The ask
@@ -203,7 +205,8 @@ Sidecar only: ships beside `herdr-agent-state.ts`, never modifies it.
203
205
  | TaskStore `running` non-empty (G3; queued/waiting never execute) | `gentle_work_v1=<hash>:<count>:<exp>` (running total of delegates — never a principal-working signal) + `gentle_roles_v1=<csv>` (roles from `TaskRecord.agent`, authoritative, oldest-first) + `gentle_names_v1=<csv>` (compat transport only, never rendered) + `gentle_orchestrating_v1=<hash>:<exp>` (root-only marker, §4.3) | the oldest running role word (known short word or unknown sanitized name) whenever the principal itself is not working; a working principal reads `gentle` instead; role labels show the total when two or more delegates run |
204
206
  | `ASK_USER_CHOICE_BLOCKED_EVENT` / `gentle-pi:ask-user-choice:blocked` (G4), incl. questionnaire + tool-gated `ui_prompt` dialog spans (`kind` other than `custom` — a panel or overlay such as the agents view, ODD viewer, changes view or design canvas never counts, because opening a panel is navigation, not a question), plus direct Pi in-process `tool_execution_start` opens / `tool_execution_end` / `tool_result` closes for the exact tools `ask_user_question` and `ask_user_choice`, tracked by `toolCallId` in a call-id set (a `tool_call` proposal alone never opens; an abort/error end with no result still closes; overlapping calls correct; cleared on result/end/reset/shutdown; event legs and error > ask > review precedence unchanged; boundary: only what Pi emits as execution events is observable — a host ask UI that never emits one stays covered by the event legs only). `gentle_review` starts (any operation) never enter ask: the former consent-eligible pending signal fired before any outcome/UI and falsely blocked pre-granted sessions | `herdr:blocked` label `ask:<intentId>` + durable `gentle_ask_v1=<hash>:<intentId>:<exp>` on every beat while ask is active (null/clear when inactive — repairs a missed label edge; §4.3) | `ask` (existing machine key, user-facing `ask`, amber/orange, native `?`) |
205
207
  | Pi in-process `tool_execution_start` opens / `tool_execution_end` / `tool_result` closes (by `toolCallId`; a `tool_call` proposal alone never opens) for the exact tools `gentle_review_capture`, `gentle_review_capture_group` with `reviewerRunAcknowledged: true` in the runtime args; `correctionLines` (native planning, never a reviewer), forecast-only calls, `gentle_review` (any operation), `gentle_review_scope`, and all sidebar/hook signals never enter — unknown legacy shapes stay dark (conservative) | `herdr:blocked` label `review:<reviewId>` | `review` (machine key `review`) — during a capture-group run the single parent capture-group call stays in flight across the whole multi-reviewer span, so that one call alone holds the label. Bounded approximation: the acknowledged capture interval contains preparation and admission; no exact reviewer internal events exist today |
206
- | agent error / task failed / transport failure | `herdr:blocked` label `error:<code>` | `blocked` (machine key `error`) |
208
+ | the agent run itself stops on an error (an assistant message whose `stopReason` is `error` — the same signal Pi derives `turn_end.outcome === "error"` from) | durable `gentle_error_v1=<hash>:run-failed:<exp>` on every beat while the leg stands (null/clear the beat it releases, §4.3) + `herdr:blocked` label `error:run-failed`; no native state is derived from it (the pane stays on its lifecycle state — `working` — while the leg stands, so the host raises no NeedsAttention toast or sound) | `error` (row word `blocked`) — never a native `blocked` |
209
+ | a tool call fails, a delegate record ends `failed`, or a beat transport fails | nothing — detection only (a counter and a debug line under `GENTLE_HERDR_DEBUG=1`) | nothing: no label, no native state, no finish hold, no notification |
207
210
  | `agent_settled` + 0 active subs | `gentle_work_v1=<hash>:0:<exp>`; clear `blocked` labels | `done` |
208
211
  | `SESSION_CHANGE_ENTRY` `gentle-pi.session-change/v1` tool outcome (G1/G2) | `gentle_changes_v2=<hash>:<files>:<added>:<deleted>:<exp>` (+ legacy `gentle_changes_v1` dual-emit, §4.3) | change segments only (orthogonal to state) |
209
212
 
@@ -354,6 +357,17 @@ gentle_review_v1 = sessionHash ":" reviewId ":" expiry
354
357
  ; execution is in flight, null (clear) otherwise; silent
355
358
  ; working natively, never a notification (full def:
356
359
  ; extensions/gentle-herdr-state.ts, herdr-plugin/lib/gentle-tokens.js)
360
+ gentle_error_v1 = sessionHash ":" code ":" expiry
361
+ ; durable run-error signal, session-bound + TTL-fresh —
362
+ ; emitted on every beat while the run-error leg stands
363
+ ; (the agent run itself stopped on an error), null
364
+ ; (clear) the beat it releases; the sidebar's ONLY error
365
+ ; carrier (the native report never claims `blocked`, so
366
+ ; no toast, no sound, no phone envelope). Tool-level
367
+ ; failures never reach it (they are telemetry only).
368
+ ; Consumer: fresh token => `error` display (row word
369
+ ; `blocked`, silent) with the same
370
+ ; error > ask > review priority as the label leg.
357
371
  herdr:blocked = "ask:" intentId / "review:" reviewId / "error:" code
358
372
  ```
359
373
 
@@ -380,7 +394,8 @@ pane.report_metadata --source gentle:v1 --token gentle_orchestrating_v1=Ab3_xK9q
380
394
  pane.report_metadata --source gentle:v1 --token gentle_principal_v1=Ab3_xK9q2mZ7QwErTyUiOpAsDfGhJkL012345678:1789000000000
381
395
  pane.report_metadata --source gentle:v1 --token gentle_names_v1=planner,code-writer
382
396
  pane.report_metadata --source gentle:v1 --token gentle_changes_v2=Ab3_xK9q2mZ7QwErTyUiOpAsDfGhJkL012345678:5:110:22:1789000000000
383
- herdr:blocked labels: ["ask:q-7f3a"] | ["review:r-42"] | ["error:transport-timeout"]
397
+ pane.report_metadata --source gentle:v1 --token gentle_error_v1=Ab3_xK9q2mZ7QwErTyUiOpAsDfGhJkL012345678:run-failed:1789000000000
398
+ herdr:blocked labels: ["ask:q-7f3a"] | ["review:r-42"] | ["error:run-failed"]
384
399
  ```
385
400
 
386
401
  Example reads: worker oldest + explorer active with count 2 → sidebar
@@ -450,6 +465,8 @@ count), `gentle_principal_v1` (principal-only activity marker + freshness
450
465
  gate for the working-vs-idle decision — never rendered as a count),
451
466
  `gentle_done_v1` (synthesized finish signal + its own hold freshness gate
452
467
  for the reachable `done` display — the host never reports `done`, §4.3),
468
+ `gentle_error_v1` (durable run-error signal + freshness gate for the `error`
469
+ display — repairs a missed `error:` label edge, §4.3),
453
470
  `gentle_roles_v1` (authoritative activity roles,
454
471
  oldest-first by immutable firstSeen), `gentle_names_v1` (compat transport only — never
455
472
  rendered), `gentle_changes_v2` (normative; a
@@ -461,7 +478,9 @@ ignore them under O1 (never parsed for state, never deleted).
461
478
  ### 5.2 Reducer (priority order, first match wins)
462
479
 
463
480
  ```text
464
- error := herdr:blocked has error:* (fresh, §5.4)
481
+ error := fresh `gentle_error_v1` (durable per-beat token, §4.3)
482
+ OR herdr:blocked has error:* (fresh, §5.4) — one shared
483
+ priority: error > ask > review
465
484
  ask := fresh `gentle_ask_v1` (durable per-beat token, §4.3)
466
485
  OR herdr:blocked has ask:* (fresh)
467
486
  review := herdr:blocked has review:* (fresh)
@@ -566,8 +585,9 @@ marker, and only after the minted finish hold lapses does it recede to
566
585
  delegates run) | `ask` | `rdd` (user-facing word for the `review`
567
586
  machine key; a delegated rdd and a tool-only review both render `rdd` —
568
587
  review execution is silent, never a notification; only
569
- a waiting `ask` intent notifies once) | `blocked` (user-facing word for the `error`
570
- machine key) | `done` (settled-plus-empty only: principal settled with no
588
+ a waiting `ask` intent notifies once) | `blocked` (user-facing row word for the `error`
589
+ machine key; carried by the durable `gentle_error_v1` token or the `error:`
590
+ label, and the pane's native state never claims `blocked` for it) | `done` (settled-plus-empty only: principal settled with no
571
591
  running delegates and no pending launches; a settled principal with
572
592
  running delegates keeps the role word) | `idle`. Role labels append the
573
593
  total count when at least two delegates run.
@@ -705,10 +725,17 @@ gentle-ai concern and explicitly out of scope for this plugin.
705
725
  id is a new sidebar ask episode (and a new native toast edge). The
706
726
  `intentId` doubles as the Moshi `approval_required` action id when the
707
727
  phone channel is enabled (§7).
708
- - Error containment: transport failure surfaces as `herdr:blocked`
709
- `error:<code>` (itself a token, subject to the same TTL), never as an
710
- exception path that stops the producer beat. `error` state clears only on a
711
- fresh non-error snapshot, not on silence.
728
+ - Error containment: a failed beat transport is telemetry (a counter and a
729
+ debug line), never state: it is our own report mechanism failing, not the
730
+ agent, so it neither paints `error:` nor raises native `blocked`, and the
731
+ next landed beat resets the counter. The one real error leg — the run
732
+ itself stopping on an error — is released by the next non-error beat
733
+ (`agent_start`, any tool activity, or a non-error assistant message), never
734
+ latched; no exception path ever stops the producer beat. While the leg
735
+ stands it publishes the durable `gentle_error_v1` token on every beat, so
736
+ an error the sidebar missed on one beat is repaired by the next, and the
737
+ release beat clears it (the missed-beat discipline of the ask/review
738
+ tokens).
712
739
  - No exactly-once end-to-end claim: at-least-once beats + TTL expiry is the
713
740
  engineered scope (consistent with the async/events guidance: never claim
714
741
  exactly-once without a deliberate mechanism). Desktop toast dedup is
@@ -727,9 +754,12 @@ gentle-ai concern and explicitly out of scope for this plugin.
727
754
  duplication. The ask token still drives the sidebar ask display; sounds,
728
755
  suppression, and delay stay Herdr's.
729
756
  - `review` and `error` never emit a plugin notification: `review` attention
730
- stays in-flow/native; `error` is visible as sidebar state (native `blocked`
731
- attention on `herdr:blocked` already fires per E9 — the plugin adds no
732
- toast path).
757
+ stays in-flow/native; `error` is sidebar state only — our own `error:` label
758
+ with the pane left on native `working`, so neither the `NeedsAttention`
759
+ toast nor its sound fires and no phone envelope is sent. Tool-level failures
760
+ (a failed tool call, a delegate record ending `failed`, a failed beat
761
+ transport) never touch state at all: they are detected and logged, nothing
762
+ more.
733
763
  - Optional Moshi replacement (off by default): one flag file,
734
764
  `gentle-moshi.json` in the plugin state root, holding
735
765
  `{"enabled":true}` and re-read per event by the producer extension. While
@@ -751,7 +781,12 @@ gentle-ai concern and explicitly out of scope for this plugin.
751
781
  running/queued plus zero pending plus zero live background jobs plus no
752
782
  human wait — never a raw native `working → idle` transition, which fires
753
783
  with work still left and skipped `done` entirely),
754
- never per prompt and never per turn. A `session.closed` (`session_ended`)
784
+ never per prompt and never per turn. Every envelope path requires the flag at
785
+ send time: a context captured for Chat View while the channel was on is
786
+ prefill only and never authorizes a notification after it is turned off, and
787
+ `task_complete` is announced at the minted `done` edge itself rather than
788
+ after a successful Herdr publish, so a failed token beat cannot drop it. A
789
+ `session.closed` (`session_ended`)
755
790
  envelope closes the row on shutdown, and the host-awaited handler flushes
756
791
  in-flight sends. `task_complete` carries title `Gentle finished: <project>`
757
792
  and names the last finished task: `<project> finished — <label>. Return to
@@ -773,7 +808,8 @@ gentle-ai concern and explicitly out of scope for this plugin.
773
808
  publishes to Moshi (single emitter). Moshi owns pairing and credentials
774
809
  (host secret in its own store); the plugin never reads or stores a token,
775
810
  and an absent daemon or unpaired host is a silent no-op that never
776
- interrupts Pi. `review` and `error` never notify. Limits (host-owned,
811
+ interrupts Pi. `review` and `error` never notify; a failed tool never even
812
+ changes state. Limits (host-owned,
777
813
  unverified): the phone-side approval round-trip through Moshi's TUI bridge,
778
814
  the Live Activity lifecycle, and whether a `task_complete` renders as a
779
815
  separate banner or only updates a running Live Activity are Moshi's.
@@ -790,7 +826,7 @@ report after a Pi restart or `/new` (both recreate the extension runtime)
790
826
  lose, freezing the pane's `agent_session` binding at the old session while
791
827
  the producer keeps beating for the new one — the consumer then rejects those
792
828
  fresh tokens as a session-hash mismatch and the pane stays on `idle` until a
793
- report with a higher seq lands. Parity contract: `working` carries the specific working role in the message (oldest running role word from the same roles resolution — known short word, unknown sanitized name, or `gentle` with no delegation; never bare generic `working`; machine keys unchanged); terminal `idle` only on a truly empty settle (principal settled plus zero running/queued plus zero pending plus zero live background jobs plus no human-wait prompt; settle-with-delegates/pending/jobs stays `working`, emitted once with no re-emit on repeat settles). Live background jobs come from Gentle Shell's own bus event `gentle-ai:jobs-sidebar` (`bash_background` / `monitor`), session-scoped and emitted on job edges only, so a snapshot counts only while it is fresh — a stale or foreign snapshot is zero jobs; an absent Gentle Shell simply reports none (today's behavior). While such a job waits with the principal settled and no delegate running or launching, the producer keeps the root marker live so the row stays on the pink generic `gentle` (§5.2) and the finish is held back; the wait ends on the beat the principal resumes, a delegate starts, the last job ends, or the snapshot ages past its staleness bound. `blocked` only for a real principal-stopped error or an actual human-wait intervention leg with its label (review/RDD execution stays `working`, silent). The native status keeps its aggregate meaning (it reads `working` while any delegate runs, which is what Herdr's own pane state means): the sidebar row's working-vs-idle decision reads the principal-only `gentle_principal_v1` instead (§5.2), so an idle principal with a running delegate shows the delegate role word rather than `gentle`. Single publisher by design: the managed native extension file is excluded
829
+ report with a higher seq lands. Parity contract: `working` carries the specific working role in the message (oldest running role word from the same roles resolution — known short word, unknown sanitized name, or `gentle` with no delegation; never bare generic `working`; machine keys unchanged); terminal `idle` only on a truly empty settle (principal settled plus zero running/queued plus zero pending plus zero live background jobs plus no human-wait prompt; settle-with-delegates/pending/jobs stays `working`, emitted once with no re-emit on repeat settles). Live background jobs come from Gentle Shell's own bus event `gentle-ai:jobs-sidebar` (`bash_background` / `monitor`), session-scoped and emitted on job edges only, so a snapshot counts only while it is fresh — a stale or foreign snapshot is zero jobs; an absent Gentle Shell simply reports none (today's behavior). Only an entry with no `status` is pending work: Gentle Shell keeps a finished job in the array as a result tail (`status: exited|stopped|failed`), and counting that tail is what pinned the row on the pink generic `gentle` — and blocked `done` — while the panel read no running job. One `unref()`-ed timer per live snapshot publishes a single beat at the instant the snapshot goes stale, so a missed exit event cannot leave the settle without a beat. While such a job waits with the principal settled and no delegate running or launching, the producer keeps the root marker live so the row stays on the pink generic `gentle` (§5.2) and the finish is held back; the wait ends on the beat the principal resumes, a delegate starts, the last job ends, or the snapshot ages past its staleness bound. `blocked` only for an actual human-wait intervention leg with its label (review/RDD execution stays `working`, silent); an error never claims native `blocked` — while our `error:` label stands the pane reports `working`, the only native state that raises no host attention, and returns to the lifecycle state on the next non-error beat. The native status keeps its aggregate meaning (it reads `working` while any delegate runs, which is what Herdr's own pane state means): the sidebar row's working-vs-idle decision reads the principal-only `gentle_principal_v1` instead (§5.2), so an idle principal with a running delegate shows the delegate role word rather than `gentle`. Single publisher by design: the managed native extension file is excluded
794
830
  reversibly (`-extensions/herdr-agent-state.ts` in Pi settings, bytes
795
831
  preserved on disk, never auto-loaded next to ours). `node
796
832
  bin/gentle-sidebar.js (enable|disable|status|toggle)` selects the
@@ -831,11 +867,15 @@ argument, Esc, or a cancelled menu writes nothing. With no argument the
831
867
  command opens the floating panel (`lib/customize-panel.js`, painted through its
832
868
  own palette) over `ctx.ui.custom` in Gentle Shell's own layout: one left
833
869
  `CATEGORIES` list, one right pane headed `<Category> · n/m` with its setting
834
- rows, each row painting the stored value with `●` and the other with `○`, and
835
- the footer
836
- `Click · ←/→ or Tab panes · ↑/↓ move · Enter apply · Esc close`. There is no
870
+ rows, each row painting the stored value with `●` and the other with `○`; one
871
+ line above the footer describes the focused setting
872
+ (`<setting> — <what it changes>`), and the footer
873
+ `←/→ or Tab panes · ↑/↓ move · Enter apply · Esc close`. There is no
874
+ `Click` token and no
837
875
  `Preview · …` band and no `p profiles` key: this plugin owns no profiles
838
- concept, so the footer advertises nothing it cannot do. `←/→` or `Tab` moves
876
+ concept, so the footer advertises nothing it cannot do — every token in it is a
877
+ key the panel answers to, and a narrow card compacts the legend instead of
878
+ wrapping it. `←/→` or `Tab` moves
839
879
  between the category and value panes, `↑/↓` or `j/k` moves the cursor, `Enter`
840
880
  applies the focused row and `Esc` closes without a write; a click on a category
841
881
  selects it, a click on a row applies it, and a click outside the panes is
@@ -859,11 +899,12 @@ exactly one mechanism writes each piece of state.
859
899
  ## 8. Limits
860
900
 
861
901
  - Token budget: ≤ 16 tokens per report per pane (E8 discipline); the
862
- producer emits at most 11 tokens per beat (including the retired
902
+ producer emits at most 12 tokens per beat (including the retired
863
903
  `gentle_subs_v1` clear) (`gentle_work_v1`,
864
904
  `gentle_roles_v1`, `gentle_names_v1`,
865
905
  `gentle_orchestrating_v1`, `gentle_principal_v1`, `gentle_done_v1`,
866
- `gentle_ask_v1`, `gentle_review_v1`, `gentle_changes_v2`,
906
+ `gentle_ask_v1`, `gentle_review_v1`, `gentle_error_v1`,
907
+ `gentle_changes_v2`,
867
908
  `gentle_changes_v1`) and the daemon publishes its 72-token owned family
868
909
  chunked ≤ 16 per report (row 1 is the 3 native tokens
869
910
  `state_icon`/`workspace`/`agent`; the legacy 11 `gentle_heading_*` compat
package/README.md CHANGED
@@ -201,7 +201,12 @@ and token names stay `review` — review execution is silent, never a
201
201
  notification; only an actual waiting prompt renders `ask` (desktop attention
202
202
  is Herdr's native `blocked` toast); the judge delegate role renders `judge` in
203
203
  purple `#cba6f7` (distinct from explorer blue, verify teal, and
204
- orchestrating pink); the error value renders `blocked`; the orchestrating
204
+ orchestrating pink); the error value renders `blocked` as the row word for
205
+ the `error` machine key (never the pane's native state — an error is
206
+ sidebar-only, DESIGN §7; it rides the durable session-bound
207
+ `gentle_error_v1` token, republished on every beat while the run-error leg
208
+ stands and cleared the beat it releases, so a beat the sidebar missed is
209
+ repaired by the next one); the orchestrating
205
210
  leg renders the user-facing word `gentle` (machine key stays
206
211
  `orchestrating`, pink `#f5c2e7`). Remaining state colors:
207
212
  working/worker amber `#f9e2af`, explorer blue `#89b4fa`, verify teal
@@ -303,7 +308,7 @@ the principal session actively works — even with zero subagents — and keeps
303
308
  `gentle` while its delegates run (a role word such as `worker`, `explorer`,
304
309
  `verify`, `judge` shows once the principal itself is idle), row 1 shows
305
310
  the single heading cell (`● <project>` plus ` +N`/` -N`/` ↑N` inline, zero `·`) after edits / when behind upstream; then `ask` on an open
306
- question (choice / native-questionnaire / legacy event legs, executed `ask_user_question`/`ask_user_choice`, tool-gated `ui_prompt` dialog spans (a `custom` panel — agents view, ODD viewer, changes view, design canvas — never counts, because opening a panel is navigation, not a question), or permission waiting; `gentle_review` starts never speculate ask) and `blocked` on error. `rdd` (machine key `review`) applies during acknowledged native capture/group execution only (`reviewerRunAcknowledged: true` at execution start — never proposal, never forecast-only, never `correctionLines` planning, never `gentle_review`/`gentle_review_scope` in any operation; no hook/sidebar signal observed; unknown legacy shapes stay dark; call-id tracked so thrown/cancelled calls still clear, read-only `assess` excluded). Bounded approximation: the acknowledged interval contains preparation and admission; no exact reviewer internal events exist today. The orchestrator-host `ask_user_choice` prompt emits no Pi tool/event observable by this extension and stays covered only by the event legs above. Never point the fixture commands at the live config: keep
311
+ question (choice / native-questionnaire / legacy event legs, executed `ask_user_question`/`ask_user_choice`, tool-gated `ui_prompt` dialog spans (a `custom` panel — agents view, ODD viewer, changes view, design canvas — never counts, because opening a panel is navigation, not a question), or permission waiting; `gentle_review` starts never speculate ask, and no failed tool ever does either: a tool error changes nothing, see the error rule below). `rdd` (machine key `review`) applies during acknowledged native capture/group execution only (`reviewerRunAcknowledged: true` at execution start — never proposal, never forecast-only, never `correctionLines` planning, never `gentle_review`/`gentle_review_scope` in any operation; no hook/sidebar signal observed; unknown legacy shapes stay dark; call-id tracked so thrown/cancelled calls still clear, read-only `assess` excluded). Bounded approximation: the acknowledged interval contains preparation and admission; no exact reviewer internal events exist today. The orchestrator-host `ask_user_choice` prompt emits no Pi tool/event observable by this extension and stays covered only by the event legs above. Never point the fixture commands at the live config: keep
307
312
  `HERDR_CONFIG_PATH` on a temp file for apply/uninstall checks.
308
313
 
309
314
  ## Core Workflow
@@ -358,7 +363,11 @@ See [DESIGN.md](DESIGN.md) §4 (producer) and §5 (consumer), and
358
363
  `rdd` during native review execution (machine key stays `review`; execution
359
364
  is silent — desktop attention fires only for a waiting `ask` intent, as
360
365
  Herdr's native toast), and
361
- user-facing `blocked` for errors.
366
+ user-facing `blocked` as the row word for the `error` machine key (an
367
+ error never claims the native `blocked` state — that is the host's
368
+ NeedsAttention toast and sound, so the sidebar carries the error on the
369
+ durable `gentle_error_v1` token while the pane stays quiet on `working`,
370
+ and no phone envelope is sent).
362
371
  - Single-cell row-1 heading (`<icon> <project>` plus ` +N`/` -N`/` ↑N`
363
372
  inline, exactly one nonempty cell so zero `·` separators; white base with
364
373
  `contains` rules keeping ` +` green (added), ` -` red (deleted,
@@ -395,7 +404,7 @@ See [DESIGN.md](DESIGN.md) §4 (producer) and §5 (consumer), and
395
404
  nothing and logs one line per reason. The gs pane's own live state stays
396
405
  unobservable until the isolated install forwards `HERDR_ENV` to its agent (a
397
406
  gentle-ai concern, out of scope here).
398
- - Gentle mode is enabled by default: while selected, this extension is the single publisher of native `pane.report_agent` (`working`/`blocked`/`idle`) alongside its metadata beats, with session path-or-id binding, monotonic seq, and a serial latest-wins coalesced queue. Parity contract: `working` carries the specific working role in the message (oldest running role word — known short word, unknown sanitized name, or `gentle` with no delegation; never bare generic `working`; machine keys unchanged); terminal `idle` fires only on a truly empty settle (principal settled plus zero running/queued plus zero pending plus zero live background jobs plus no human-wait prompt; settle-with-delegates/pending/jobs stays `working`, emitted once). Live background jobs (`bash_background` / `monitor`) are read from Gentle Shell's session-scoped `gentle-ai:jobs-sidebar` bus event, so waiting on a CI run or a long command keeps the row on `gentle` and never reaches `done`; `blocked` fires only for a real error or an actual human-wait intervention leg with its label (review/RDD execution stays `working`, silent). The native status keeps its aggregate meaning — it reads `working` while any delegate runs — while the sidebar row's working-vs-idle decision reads the principal-only `gentle_principal_v1` marker, so an idle principal with a running delegate shows the delegate role word instead of `gentle`. Our code never emits `done`/`finished` native states or a Herdr notification (the opt-in Moshi replacement below is a separate, off-by-default channel): the host owns finished text on `done`, `blocked`/unknown presentation, sound, and all desktop attention toasts (ask + finish) — there is no consumer toast path left to dedup. Single publisher by design: the managed native extension file stays on disk and is excluded through an ownership-bound Pi settings entry while Gentle mode is selected. `node bin/gentle-sidebar.js disable` removes only our owned exclusion and managed rows, gates our producer/daemon, and hands the sidebar back to the native publisher (running Pi sessions need `/reload`); never run both publishers on the same pane. Limits (unverified, host-owned): the host `idle`→`done`→`finished` mapping and unknown-state handling are owned by Herdr.
407
+ - Gentle mode is enabled by default: while selected, this extension is the single publisher of native `pane.report_agent` (`working`/`blocked`/`idle`) alongside its metadata beats, with session path-or-id binding, monotonic seq, and a serial latest-wins coalesced queue. Parity contract: `working` carries the specific working role in the message (oldest running role word — known short word, unknown sanitized name, or `gentle` with no delegation; never bare generic `working`; machine keys unchanged); terminal `idle` fires only on a truly empty settle (principal settled plus zero running/queued plus zero pending plus zero live background jobs plus no human-wait prompt; settle-with-delegates/pending/jobs stays `working`, emitted once). Live background jobs (`bash_background` / `monitor`) are read from Gentle Shell's session-scoped `gentle-ai:jobs-sidebar` bus event, so waiting on a CI run or a long command keeps the row on `gentle` and never reaches `done`; `blocked` fires only for an actual human-wait intervention leg with its label (review/RDD execution stays `working`, silent). `blocked` is never derived from an error: native `blocked` is what fires the host's NeedsAttention toast and sound, so a failed run shows our own `error` state — the durable, session-bound `gentle_error_v1` token (republished every beat while the leg stands, cleared when it releases) that the sidebar reduces to the `error` row word — while the pane stays on `working`, and a failed tool call (or a delegate that ended `failed`, or a failed beat transport) changes nothing at all: it is detected and logged, never published, and never reaches the error token. The native status keeps its aggregate meaning — it reads `working` while any delegate runs — while the sidebar row's working-vs-idle decision reads the principal-only `gentle_principal_v1` marker, so an idle principal with a running delegate shows the delegate role word instead of `gentle`. Our code never emits `done`/`finished` native states or a Herdr notification (the opt-in Moshi replacement below is a separate, off-by-default channel): the host owns finished text on `done`, `blocked`/unknown presentation, sound, and all desktop attention toasts (ask + finish) — there is no consumer toast path left to dedup. Single publisher by design: the managed native extension file stays on disk and is excluded through an ownership-bound Pi settings entry while Gentle mode is selected. `node bin/gentle-sidebar.js disable` removes only our owned exclusion and managed rows, gates our producer/daemon, and hands the sidebar back to the native publisher (running Pi sessions need `/reload`); never run both publishers on the same pane. Limits (unverified, host-owned): the host `idle`→`done`→`finished` mapping and unknown-state handling are owned by Herdr.
399
408
  - Sidebar switch (`enable` / `disable` / `status` / `toggle`):
400
409
  `node bin/gentle-sidebar.js <verb>` picks between this plugin's sidebar rows
401
410
  and the native Herdr sidebar. `status` is read-only; `enable` converges the
@@ -407,12 +416,17 @@ See [DESIGN.md](DESIGN.md) §4 (producer) and §5 (consumer), and
407
416
  no argument the command opens the floating panel in Gentle Shell's own
408
417
  layout: one left `CATEGORIES` list (`Herdr Sidebar`, `Moshi notifications`)
409
418
  and one right pane headed `<Category> · n/m` with its setting rows, each row
410
- painting the stored value with `●` and the other with `○`; the footer reads
411
- `Click · ←/→ or Tab panes · ↑/↓ move · Enter apply · Esc close`, and `←/→` or
419
+ painting the stored value with `●` and the other with `○`; one line above the
420
+ footer describes the focused setting (`<setting> — <what it changes>`), and
421
+ the footer reads
422
+ `←/→ or Tab panes · ↑/↓ move · Enter apply · Esc close`, while `←/→` or
412
423
  `Tab` moves between the category and value panes, `↑/↓` or `j/k` moves the
413
- cursor while `Esc` closes. A click on a category selects it and a click on a
414
- row applies it, exactly like `Enter` on the focused row; clicks outside the
415
- panes are ignored. The notifications switch appears twice — as its own
424
+ cursor, `Enter` applies the focused row and `Esc` closes without a write. The
425
+ legend names only keys: it never advertises `Click`, because every token in
426
+ it is a key the panel answers to, and a narrow card compacts it instead of
427
+ wrapping. Pointer input still works without being advertised — a click on a
428
+ category selects it, a click on a row applies it, and a click outside the
429
+ panes is ignored. The notifications switch appears twice — as its own
416
430
  `Moshi notifications` category and as a `Notifications` row inside
417
431
  `Herdr Sidebar` — and both rows read the one flag below, so the state they
418
432
  show can never disagree. The plain two-step menu stays as the fallback
@@ -451,7 +465,10 @@ See [DESIGN.md](DESIGN.md) §4 (producer) and §5 (consumer), and
451
465
  session row, terminal context, phone-side approvals) keeps working, but
452
466
  notifications follow this plugin's policy — one when Pi really needs your
453
467
  input (`ask`) and one when Pi really finishes. Nothing per prompt, nothing per
454
- turn. If `extensions/moshi-hooks.ts` is installed, add
468
+ turn, and nothing at all while the flag is off: every envelope path requires
469
+ the flag at send time, so a context captured for Chat View while the channel
470
+ was on can never authorize a notification after it is turned off. If
471
+ `extensions/moshi-hooks.ts` is installed, add
455
472
  `-extensions/moshi-hooks.ts` to the `extensions` list in your Pi
456
473
  `settings.json` so the Moshi-managed hook cannot notify in parallel; that edit
457
474
  leaves every other settings key and entry untouched. Removal of the flag (or
@@ -468,7 +485,9 @@ See [DESIGN.md](DESIGN.md) §4 (producer) and §5 (consumer), and
468
485
  heartbeat tick). Ambiguous, stale, or oversize snapshots never clear
469
486
  tasks. Known limits: delegates that launch and finish between presence
470
487
  publications never appear and still depend on chat delivery, and
471
- absence-driven completion records `completed` without latching an error.
488
+ absence-driven completion records `completed` without touching the error
489
+ leg; a delegate that ended `failed` is detected and logged, never published
490
+ as state.
472
491
  - TTL-bounded tokens: stale panes fall back to native `idle`.
473
492
  - Herdr session opener (`herdr_session_open`): opens a Herdr panel running a
474
493
  Pi session at a path. A linked Git worktree opens as a **worktree panel**
@@ -90,6 +90,17 @@
90
90
  // (single effective label, priority error > ask >
91
91
  // review, edge-triggered so the native counter in
92
92
  // herdr-agent-state.ts stays balanced)
93
+ // gentle_error_v1 = <hash>:<code>:<expiry>
94
+ // (durable run-error signal, session-bound + TTL-fresh
95
+ // like gentle_ask_v1: emitted on every beat while the
96
+ // run-error leg stands, null / clear the beat it
97
+ // releases. It is the sidebar's ONLY error carrier —
98
+ // the native pane report never claims `blocked`, so an
99
+ // error raises no host NeedsAttention toast or sound
100
+ // and sends no phone envelope. The consumer reduces a
101
+ // fresh token to `error` (row word `blocked`) with the
102
+ // same error > ask > review priority the label leg
103
+ // uses, independently of work token presence.)
93
104
  //
94
105
  // Event seams (all in-process; this extension imports nothing from
95
106
  // gentle-shell — DESIGN §10 U6 source pin is unresolved, so the producer is
@@ -178,9 +189,17 @@
178
189
  // as user-facing `rdd` (machine key stays `review`).
179
190
  // Fail-safe: no provider verdicts are
180
191
  // invented; the id is a sanitized correlation id only.
181
- // error : subagent task failed status / subagent tool error /
182
- // repeated own-transport failure. Latched until the next
183
- // agent_start (fresh snapshot), TTL-bounded display.
192
+ // error : the agent run itself stopped on an error (an assistant
193
+ // message whose `stopReason` is `error` — the same
194
+ // signal Pi derives `turn_end.outcome === "error"`
195
+ // from). Never a tool-level failure, never a failed
196
+ // delegate record, never our own transport: those are
197
+ // detected and logged, and change no state. Sidebar-only:
198
+ // the pane keeps reporting native `working` while the
199
+ // label stands, so an error never fires the host's
200
+ // NeedsAttention toast or sound. Released by the next
201
+ // non-error beat (agent_start, any tool activity, or a
202
+ // non-error assistant message), never latched.
184
203
  // changes : SESSION_CHANGE_ENTRY facts mirroring the Gentle Shell
185
204
  // SessionChanges model semantics from the session
186
205
  // transcript (write|edit tool outcomes only, never git
@@ -719,6 +738,21 @@ const DONE_HOLD_ENV = "GENTLE_HERDR_DONE_HOLD_MS";
719
738
  // minutes is the generous end of the [30 s, 5 min] band: a job longer than this
720
739
  // fails open early, and a missed exit event delays `done` by at most this long.
721
740
  export const JOBS_SNAPSHOT_TTL_MS = 300000;
741
+ const JOBS_TTL_ENV = "GENTLE_HERDR_JOBS_TTL_MS";
742
+ const JOBS_TTL_MIN_MS = 100;
743
+ const JOBS_TTL_MAX_MS = 3600000;
744
+
745
+ // Same discipline as doneHoldMs: an absent or unparseable value keeps the
746
+ // default and anything outside the band is clamped, so a debugging session (or
747
+ // a test that cannot wait five minutes) can shorten the bound without ever
748
+ // making every snapshot instantly stale.
749
+ export function jobsSnapshotTtlMs(raw = process.env[JOBS_TTL_ENV]) {
750
+ const text = typeof raw === "string" ? raw.trim() : "";
751
+ if (text.length === 0) return JOBS_SNAPSHOT_TTL_MS;
752
+ const parsed = Number(text);
753
+ if (!Number.isFinite(parsed)) return JOBS_SNAPSHOT_TTL_MS;
754
+ return Math.min(JOBS_TTL_MAX_MS, Math.max(JOBS_TTL_MIN_MS, Math.round(parsed)));
755
+ }
722
756
  const MAX_TOKENS_PER_REPORT = 16;
723
757
  const MAX_LABEL_CHARS = 64;
724
758
  // Herdr's wire ceiling for a single pane-metadata token value, measured in
@@ -734,7 +768,6 @@ const MAX_LABEL_CHARS = 64;
734
768
  const MAX_TOKEN_BYTES = 512;
735
769
  const MAX_TRACKED_TASKS = 128;
736
770
  const MAX_CHANGE_PATHS = 256;
737
- const TRANSPORT_FAIL_LATCH = 3;
738
771
  const CLI_FALLBACK_TIMEOUT_MS = 2500;
739
772
 
740
773
  const ASK_EVENT = "gentle-pi:ask-user-choice:blocked";
@@ -793,6 +826,13 @@ const ASK_TOKEN = "gentle_ask_v1";
793
826
  // review is active (acknowledged capture/group execution only). Null /
794
827
  // clear the beat the last execution resolves — NO GRACE, no timers.
795
828
  const REVIEW_TOKEN = "gentle_review_v1";
829
+ // Durable run-error token name (DESIGN §4.3): session-bound + TTL-fresh
830
+ // `<hash>:<code>:<expiry>`, emitted on every beat while the run-error leg
831
+ // stands and cleared to null the beat it releases. This is the sidebar's only
832
+ // error carrier: the native report stays `working` while the leg stands, so an
833
+ // error never raises the host's NeedsAttention toast, its sound, or a phone
834
+ // envelope (DESIGN §7).
835
+ const ERROR_TOKEN = "gentle_error_v1";
796
836
  // Principal-only activity marker (DESIGN §4.3): session-bound + TTL-fresh
797
837
  // `<hash>:<expiry>`, emitted while this session's own agent is active and
798
838
  // cleared when it settles. It carries the principal input of
@@ -1079,14 +1119,17 @@ function cliFallback(patch) {
1079
1119
  export const NATIVE_STATES = ["working", "blocked", "idle"];
1080
1120
  const NATIVE_MAX_ATTEMPTS = 2;
1081
1121
 
1082
- // Principal-gated native state (pure, testable): blocked on a real
1083
- // principal-stopped error OR an actual human-wait intervention leg
1122
+ // Principal-gated native state (pure, testable): blocked on the `hasError`
1123
+ // input OR an actual human-wait intervention leg
1084
1124
  // (ask/choice/question/questionnaire/permission — never
1085
1125
  // review/RDD execution, which stays working and silent); working while the
1086
1126
  // principal is active OR running/queued delegates exist OR pending launches
1087
1127
  // exist OR review execution holds; idle ONLY on authoritative principal
1088
1128
  // settled plus zero running+queued plus zero pending plus no human-wait
1089
- // prompt and no review execution. Never infer terminal from child
1129
+ // prompt and no review execution. The producer never sets `hasError`: native
1130
+ // `blocked` is what fires the host's NeedsAttention toast and sound, so an
1131
+ // `error:` label stays sidebar-only and the pane reports `working` while it
1132
+ // stands. Never infer terminal from child
1090
1133
  // completion, timeout, or count0 alone (settled required). Never
1091
1134
  // done/finished (only working|blocked|idle) and never a notification
1092
1135
  // method — the host owns finished text plus toast/sound, and desktop ask
@@ -1814,16 +1857,20 @@ function moshiSessionIsChild(file) {
1814
1857
  return child;
1815
1858
  }
1816
1859
 
1817
- let moshiFlagCache = { mtimeMs: -1, enabled: false };
1860
+ let moshiFlagCache = { key: "", enabled: false };
1818
1861
 
1819
1862
  function moshiEnabled() {
1820
1863
  const path = moshiFlagPath();
1821
1864
  try {
1822
1865
  const stat = fs.statSync(path);
1823
- if (stat.mtimeMs === moshiFlagCache.mtimeMs) return moshiFlagCache.enabled;
1824
- moshiFlagCache = { mtimeMs: stat.mtimeMs, enabled: moshiFlagEnabled(path) };
1866
+ // Identity, not just mtime: a rewrite that lands inside the same timestamp
1867
+ // tick (or on a coarse or network filesystem) must still flip the gate. A
1868
+ // stale "enabled" is exactly the notification the user asked not to get.
1869
+ const key = `${stat.mtimeMs}:${stat.size}:${stat.ino}`;
1870
+ if (key === moshiFlagCache.key) return moshiFlagCache.enabled;
1871
+ moshiFlagCache = { key, enabled: moshiFlagEnabled(path) };
1825
1872
  } catch {
1826
- moshiFlagCache = { mtimeMs: -1, enabled: false };
1873
+ moshiFlagCache = { key: "", enabled: false };
1827
1874
  }
1828
1875
  return moshiFlagCache.enabled;
1829
1876
  }
@@ -1932,6 +1979,11 @@ const CUSTOMIZE_OVERLAY_OPTIONS = {
1932
1979
  overlay: true,
1933
1980
  overlayOptions: { anchor: "center", width: "70%", minWidth: 60, maxHeight: "85%" },
1934
1981
  };
1982
+ // The overlay caps its own box at `maxHeight` of the terminal, so the panel's
1983
+ // row budget is that box and never the whole terminal: a card taller than the
1984
+ // box is clipped by the host, and the pointer would then hit-test rows the user
1985
+ // cannot see (the reported "the switch never changes" bug).
1986
+ const CUSTOMIZE_OVERLAY_MAX_HEIGHT = 0.85;
1935
1987
  let customizeTuiLoader = () => import("@earendil-works/pi-tui");
1936
1988
 
1937
1989
  export function setCustomizeTuiLoader(loader) {
@@ -2449,7 +2501,10 @@ async function executeCustomize(rawArgs, ctx) {
2449
2501
  theme,
2450
2502
  rowsAvailable: () => {
2451
2503
  try {
2452
- return hostTui && hostTui.terminal ? hostTui.terminal.rows : undefined;
2504
+ const rows = hostTui && hostTui.terminal ? hostTui.terminal.rows : undefined;
2505
+ return Number.isFinite(rows)
2506
+ ? Math.floor(rows * CUSTOMIZE_OVERLAY_MAX_HEIGHT)
2507
+ : undefined;
2453
2508
  } catch {
2454
2509
  return undefined;
2455
2510
  }
@@ -2560,10 +2615,37 @@ export default function (pi) {
2560
2615
  // it is never a display state of its own: no job count is published and no
2561
2616
  // `job` token exists to render (odd/tasks/restore-done-idle.md).
2562
2617
  let jobsSnapshot;
2618
+ // One timer per live snapshot, armed for the instant that snapshot goes
2619
+ // stale. The bus is edge-emitted, so a job whose exit snapshot never arrives
2620
+ // would otherwise leave `freshRunningJobCount()` frozen at its last value
2621
+ // with nothing left to publish the settle that follows: no beat, no `done`,
2622
+ // and the row stays on the pink generic `gentle` for good. One beat at the
2623
+ // expiry is enough — from that instant the hint is zero jobs, so the beat
2624
+ // either mints `done` or reports the real activity that still holds it.
2625
+ // Never a poll: a new snapshot replaces the timer, the session reset and
2626
+ // shutdown drop it, and an empty snapshot drops it immediately.
2627
+ let jobsExpiryTimer;
2628
+
2629
+ function clearJobsExpiry() {
2630
+ if (jobsExpiryTimer === undefined) return;
2631
+ clearTimeout(jobsExpiryTimer);
2632
+ jobsExpiryTimer = undefined;
2633
+ }
2634
+
2635
+ function armJobsExpiry(at) {
2636
+ clearJobsExpiry();
2637
+ const delay = Math.max(0, at + jobsSnapshotTtlMs() - Date.now());
2638
+ jobsExpiryTimer = setTimeout(() => {
2639
+ jobsExpiryTimer = undefined;
2640
+ if (!rootSession) return;
2641
+ schedulePublish();
2642
+ }, delay);
2643
+ if (jobsExpiryTimer.unref) jobsExpiryTimer.unref();
2644
+ }
2563
2645
 
2564
2646
  function freshRunningJobCount() {
2565
2647
  if (!jobsSnapshot) return 0;
2566
- if (Date.now() - jobsSnapshot.at > JOBS_SNAPSHOT_TTL_MS) return 0;
2648
+ if (Date.now() - jobsSnapshot.at > jobsSnapshotTtlMs()) return 0;
2567
2649
  const owner = jobsSnapshot.sessionId;
2568
2650
  const mine = sessionId;
2569
2651
  if (
@@ -2586,11 +2668,23 @@ export default function (pi) {
2586
2668
  const jobs = value.snapshot.jobs.filter(
2587
2669
  (entry) => isRecord(entry) && typeof entry.id === "string" && entry.id.length > 0,
2588
2670
  );
2671
+ // Gentle Shell publishes a FINISHED TAIL: a job that already ended stays in
2672
+ // the array carrying `status: "exited" | "stopped" | "failed"` (its
2673
+ // `RunningJobDisplay`, optional so older publishers that list running jobs
2674
+ // only keep validating). Only an entry with NO status is still running.
2675
+ // Counting a tail entry made `activity` true forever: the row stayed on the
2676
+ // pink generic `gentle` and the `done` mint — hence the finish token, the
2677
+ // host `idle` edge and the Finished toast — never happened, on a panel that
2678
+ // read `none running`. Any status, known or not, therefore stops counting.
2679
+ // `jobs` is only read by freshRunningJobCount, so the filter lives here.
2680
+ const live = jobs.filter((entry) => entry.status === undefined);
2589
2681
  jobsSnapshot = {
2590
2682
  sessionId: typeof value.sessionId === "string" ? value.sessionId : undefined,
2591
- jobs,
2683
+ jobs: live,
2592
2684
  at: Date.now(),
2593
2685
  };
2686
+ if (live.length > 0) armJobsExpiry(jobsSnapshot.at);
2687
+ else clearJobsExpiry();
2594
2688
  schedulePublish();
2595
2689
  }
2596
2690
 
@@ -2619,6 +2713,10 @@ export default function (pi) {
2619
2713
 
2620
2714
  function moshiEmit(eventName, extra = {}) {
2621
2715
  if (!rootSession) return;
2716
+ // THE gate for every envelope path: the opt-in flag is required here, on
2717
+ // every path, with no per-event exception. A context captured while the
2718
+ // channel was on is Chat View prefill only — it never authorizes a send.
2719
+ if (!moshiEnabled()) return;
2622
2720
  if (!moshiContext && !moshiEnsureContext()) return;
2623
2721
  const context = moshiContext;
2624
2722
  if (!context) return;
@@ -2641,6 +2739,15 @@ export default function (pi) {
2641
2739
  moshiSendEnvelope(envelope);
2642
2740
  }
2643
2741
 
2742
+ // The notifications name the project, so they must resolve it the way a send
2743
+ // resolves its context — capturing on demand, which also keeps a channel
2744
+ // enabled mid-session from announcing itself as a bare "Gentle".
2745
+ function moshiNotifyProject() {
2746
+ if (!moshiEnabled()) return "Gentle";
2747
+ moshiEnsureContext();
2748
+ return moshiContext?.project ?? "Gentle";
2749
+ }
2750
+
2644
2751
  // Captures on demand and sends the silent carrier once per session, so
2645
2752
  // enabling Moshi mid-session still opens the Chat View row instead of
2646
2753
  // waiting for the next Pi session.
@@ -2671,8 +2778,14 @@ export default function (pi) {
2671
2778
  function syncReviewActive() {
2672
2779
  reviewActive = reviewCalls.size > 0;
2673
2780
  }
2674
- // Error latch: cleared on the next agent_start (fresh snapshot).
2781
+ // Run-error leg: set ONLY when the agent run itself stops on an error, and
2782
+ // released by the next non-error beat (see setRunError/clearRunError). Tool
2783
+ // failures never touch it, so a failed tool can no longer repaint the row.
2675
2784
  let errorCode;
2785
+ const RUN_ERROR = "run-failed";
2786
+ // Tool-level failures are still detected (the reported defect asked for
2787
+ // detection) but are telemetry: a counter plus a debug line, never state.
2788
+ let toolErrors = 0;
2676
2789
  let emittedLabel;
2677
2790
 
2678
2791
  let changes = { files: 0, added: 0, deleted: 0 };
@@ -2774,6 +2887,26 @@ export default function (pi) {
2774
2887
  return undefined;
2775
2888
  }
2776
2889
 
2890
+ // Detection surface for tool-level failures: recorded, never published. The
2891
+ // state they reach (label, native state, finish hold) is untouched by design
2892
+ // — only a run that stops on an error may show `error:`.
2893
+ function recordToolFailure(site) {
2894
+ toolErrors += 1;
2895
+ debug("tool-error", `${site} count=${toolErrors}`);
2896
+ }
2897
+
2898
+ function setRunError() {
2899
+ if (errorCode) return;
2900
+ errorCode = RUN_ERROR;
2901
+ updateBlocker();
2902
+ }
2903
+
2904
+ function clearRunError() {
2905
+ if (!errorCode) return;
2906
+ errorCode = undefined;
2907
+ updateBlocker();
2908
+ }
2909
+
2777
2910
  function ensureAskIntent() {
2778
2911
  if (askActiveNow() && !askIntentId) {
2779
2912
  askCounter += 1;
@@ -2781,14 +2914,16 @@ export default function (pi) {
2781
2914
  // Moshi replacement (DESIGN §7): a real ask episode is the only
2782
2915
  // intervention that reaches the phone — one approval_required per
2783
2916
  // intentId, exactly like the Herdr toast, and never a speculative ask.
2784
- if (moshiContext || moshiEnabled()) {
2917
+ // `moshiContext` alone never authorizes it: the flag gates every send.
2918
+ if (moshiEnabled()) {
2919
+ const project = moshiNotifyProject();
2785
2920
  moshiEmit("PermissionRequest", {
2786
2921
  category: "approval_required",
2787
2922
  phase: "waitingForApproval",
2788
2923
  actionId: askIntentId,
2789
- title: `Gentle ask: ${moshiContext?.project ?? "Gentle"}`,
2924
+ title: `Gentle ask: ${project}`,
2790
2925
  subtitle: "Answer in terminal",
2791
- message: `${moshiContext?.project ?? "Gentle"} has a question and is waiting for your answer. Return to Pi to respond.`,
2926
+ message: `${project} has a question and is waiting for your answer. Return to Pi to respond.`,
2792
2927
  ...(lastAskToolName ? { toolName: lastAskToolName } : {}),
2793
2928
  });
2794
2929
  }
@@ -3041,6 +3176,16 @@ export default function (pi) {
3041
3176
  if (!reviewActive) reviewId = undefined;
3042
3177
  if (reviewActive && reviewId) tokens[REVIEW_TOKEN] = `${sessionHash}:${reviewId}:${expiry}`;
3043
3178
  else tokens[REVIEW_TOKEN] = null;
3179
+ // Durable run-error signal: session-bound + TTL-fresh
3180
+ // `<hash>:<code>:<expiry>`, republished on every beat while the run-error
3181
+ // leg stands (durable, never edge-only, so a missed beat cannot strand the
3182
+ // row) and cleared to null on the beat the leg releases. It is the only
3183
+ // carrier of the error to the sidebar: the native report stays `working`
3184
+ // while it stands, which is what keeps the host from firing a
3185
+ // NeedsAttention toast or sound for it (DESIGN §7). Tool-level failures
3186
+ // never reach this leg (recordToolFailure is telemetry only).
3187
+ if (errorCode) tokens[ERROR_TOKEN] = `${sessionHash}:${errorCode}:${expiry}`;
3188
+ else tokens[ERROR_TOKEN] = null;
3044
3189
  // Root-only orchestrating marker (DESIGN §4.3): session-bound freshness
3045
3190
  // (<hash>:<expiry>, same binding/TTL style as gentle_work_v1, no count)
3046
3191
  // emitted by the root Pi session while the main session is actively
@@ -3148,6 +3293,10 @@ export default function (pi) {
3148
3293
  askToolCalls.size > 0 ||
3149
3294
  uiPromptActive ||
3150
3295
  reviewActive ||
3296
+ // The standing run error keeps a beat alive so its durable token stays
3297
+ // republished (and TTL-fresh) until the leg releases, even after the
3298
+ // session settles.
3299
+ errorCode !== undefined ||
3151
3300
  emittedLabel !== undefined ||
3152
3301
  doneExpiry !== undefined
3153
3302
  );
@@ -3181,15 +3330,22 @@ export default function (pi) {
3181
3330
  // stays consumer-side per DESIGN §7).
3182
3331
  function desiredNativeReport() {
3183
3332
  if (!rootSession) return undefined;
3184
- const state = computeNativeState({
3185
- agentActive,
3186
- settled,
3187
- activeCount: activeSubs().length,
3188
- pendingCount: pendingCalls.size + (nativeSettledPending ? 1 : 0),
3189
- askActive: askActiveNow(),
3190
- reviewActive,
3191
- hasError: !!errorCode,
3192
- });
3333
+ // `error:` is sidebar-only: native `blocked` is exactly what fires the
3334
+ // host's NeedsAttention toast and sound (DESIGN §7), so an error label
3335
+ // never claims it. While the label stands the pane reports `working` —
3336
+ // the only native state that raises no attention — and returns to the
3337
+ // lifecycle state on the next non-error beat. `hasError` stays out of
3338
+ // computeNativeState for this reason.
3339
+ const state = errorCode
3340
+ ? "working"
3341
+ : computeNativeState({
3342
+ agentActive,
3343
+ settled,
3344
+ activeCount: activeSubs().length,
3345
+ pendingCount: pendingCalls.size + (nativeSettledPending ? 1 : 0),
3346
+ askActive: askActiveNow(),
3347
+ reviewActive,
3348
+ });
3193
3349
  if (!state) return undefined;
3194
3350
  if (state === "blocked") {
3195
3351
  ensureAskIntent();
@@ -3306,7 +3462,7 @@ export default function (pi) {
3306
3462
  // live jobs — never off a raw native working->idle transition, which fires
3307
3463
  // with work still left and used to skip `done` entirely.
3308
3464
  function emitFinish() {
3309
- const project = moshiContext?.project ?? "Gentle";
3465
+ const project = moshiNotifyProject();
3310
3466
  const lastLabel = lastFinishedLabel(tasks);
3311
3467
  moshiEmit("AgentEnd", {
3312
3468
  category: "task_complete",
@@ -3408,6 +3564,15 @@ export default function (pi) {
3408
3564
  maybeStopBeat();
3409
3565
  return;
3410
3566
  }
3567
+ // The finish notification is a Moshi envelope, not a Herdr token: it hangs
3568
+ // off the minted done edge above, and announcing it here — before, and
3569
+ // regardless of, the token publish — keeps a transport failure from
3570
+ // swallowing it. Cleared with the announcement, so a retried beat can
3571
+ // never duplicate it.
3572
+ if (donePending) {
3573
+ donePending = false;
3574
+ emitFinish();
3575
+ }
3411
3576
  publishInFlight = true;
3412
3577
  try {
3413
3578
  const ok = await sendTokens(tokens);
@@ -3415,21 +3580,15 @@ export default function (pi) {
3415
3580
  // One coalesced wake per landed beat, after the tokens are in Herdr
3416
3581
  // (a request written first could render a frame over stale tokens).
3417
3582
  requestStatusRefresh();
3418
- if (donePending) {
3419
- donePending = false;
3420
- emitFinish();
3421
- }
3422
- if (transportFails >= TRANSPORT_FAIL_LATCH && errorCode === "transport") {
3423
- errorCode = undefined;
3424
- updateBlocker();
3425
- }
3583
+ if (transportFails > 0) debug("transport-ok", `after ${transportFails} failed beat(s)`);
3426
3584
  transportFails = 0;
3427
3585
  } else {
3586
+ // Our own report transport failing is not the agent failing: it is a
3587
+ // telemetry line, never an `error:` label and never native `blocked`
3588
+ // (that latched a stuck red row on a socket hiccup and fired the
3589
+ // host's toast for it). The next landed beat resets the counter.
3428
3590
  transportFails += 1;
3429
- if (transportFails >= TRANSPORT_FAIL_LATCH && !errorCode) {
3430
- errorCode = "transport";
3431
- updateBlocker();
3432
- }
3591
+ debug("transport-failed", `${transportFails} beat(s) in a row`);
3433
3592
  }
3434
3593
  } finally {
3435
3594
  publishInFlight = false;
@@ -3466,12 +3625,10 @@ export default function (pi) {
3466
3625
  return;
3467
3626
  }
3468
3627
  if (!Array.isArray(applied) || applied.length === 0) return;
3469
- // An explicitly failed delegate latches the error leg exactly like a
3470
- // failed tool_result/message_end; absence-driven completion carries no
3471
- // known terminal state and never latches.
3472
- if (!errorCode && applied.some((entry) => entry && entry.status === "failed")) {
3473
- errorCode = "task-failed";
3474
- updateBlocker();
3628
+ // A delegate that ended failed is a tool-level outcome, not the run
3629
+ // stopping: detected and counted, and no state changes.
3630
+ if (applied.some((entry) => entry && entry.status === "failed")) {
3631
+ recordToolFailure("presence:failed");
3475
3632
  }
3476
3633
  }
3477
3634
 
@@ -3556,7 +3713,9 @@ export default function (pi) {
3556
3713
  donePending = false;
3557
3714
  sawActivity = false;
3558
3715
  jobsSnapshot = undefined;
3716
+ clearJobsExpiry();
3559
3717
  errorCode = undefined;
3718
+ toolErrors = 0;
3560
3719
  liveGen += 1;
3561
3720
  liveInFlight = false;
3562
3721
  liveQueued = false;
@@ -3730,6 +3889,9 @@ export default function (pi) {
3730
3889
 
3731
3890
  pi.on("tool_call", (event) => {
3732
3891
  if (!rootSession || !isRecord(event) || typeof event.toolName !== "string") return;
3892
+ // A tool starting proves a run is alive: an error left over from a run that
3893
+ // already died is released here rather than sticking until the next turn.
3894
+ clearRunError();
3733
3895
  // Structured ask proposals never open ask (execution does); subagent
3734
3896
  // launch correlation below is unchanged.
3735
3897
  if (event.toolName === "subagent_run" || event.toolName === "subagent_continue") {
@@ -3758,6 +3920,7 @@ export default function (pi) {
3758
3920
 
3759
3921
  pi.on("tool_result", (event) => {
3760
3922
  if (!rootSession || !isRecord(event) || typeof event.toolName !== "string") return;
3923
+ clearRunError();
3761
3924
  if (typeof event.toolCallId === "string" && askToolCalls.delete(event.toolCallId)) {
3762
3925
  updateBlocker();
3763
3926
  }
@@ -3788,10 +3951,9 @@ export default function (pi) {
3788
3951
  }
3789
3952
  const details = isRecord(event.details) ? event.details.gentleAgents : undefined;
3790
3953
  if (!isRecord(details) || typeof details.taskId !== "string") {
3791
- if (event.toolName === "subagent_run" && event.isError === true && !errorCode) {
3792
- errorCode = "task-failed";
3793
- updateBlocker();
3794
- }
3954
+ // A tool that failed is detected and counted, and that is all: no label,
3955
+ // no native state, no finish hold, no notification.
3956
+ if (event.isError === true) recordToolFailure(`tool:${event.toolName}`);
3795
3957
  return;
3796
3958
  }
3797
3959
  const previous = tasks.get(details.taskId);
@@ -3858,10 +4020,7 @@ export default function (pi) {
3858
4020
  const oldest = tasks.keys().next().value;
3859
4021
  tasks.delete(oldest);
3860
4022
  }
3861
- if (status === "failed" && !errorCode) {
3862
- errorCode = "task-failed";
3863
- updateBlocker();
3864
- }
4023
+ if (status === "failed") recordToolFailure(`task:${details.taskId}`);
3865
4024
  schedulePublish();
3866
4025
  });
3867
4026
 
@@ -3880,7 +4039,18 @@ export default function (pi) {
3880
4039
  pi.on("message_end", (event) => {
3881
4040
  if (!rootSession || !isRecord(event)) return;
3882
4041
  const message = event.message;
3883
- if (!isRecord(message) || message.role !== "custom") return;
4042
+ if (!isRecord(message)) return;
4043
+ if (message.role === "assistant") {
4044
+ // The one real error state. Pi derives `turn_end.outcome === "error"`
4045
+ // from exactly this stopReason, so a run that stopped on an error is
4046
+ // visible here without a second handler; any other assistant message
4047
+ // proves the run is alive again (a retry that succeeded) and releases
4048
+ // the label.
4049
+ if (message.stopReason === "error") setRunError();
4050
+ else clearRunError();
4051
+ return;
4052
+ }
4053
+ if (message.role !== "custom") return;
3884
4054
  if (message.customType !== AGENTS_RESULT_TYPE) return;
3885
4055
  const details = isRecord(message.details) ? message.details.gentleAgents : undefined;
3886
4056
  if (!isRecord(details) || typeof details.taskId !== "string") return;
@@ -3908,10 +4078,7 @@ export default function (pi) {
3908
4078
  const oldest = tasks.keys().next().value;
3909
4079
  tasks.delete(oldest);
3910
4080
  }
3911
- if (details.status === "failed" && !errorCode) {
3912
- errorCode = "task-failed";
3913
- updateBlocker();
3914
- }
4081
+ if (details.status === "failed") recordToolFailure(`background:${details.taskId}`);
3915
4082
  schedulePublish();
3916
4083
  });
3917
4084
 
@@ -3956,10 +4123,7 @@ export default function (pi) {
3956
4123
  agentActive = true;
3957
4124
  settled = false;
3958
4125
  nativeSettledPending = false;
3959
- if (errorCode) {
3960
- errorCode = undefined;
3961
- updateBlocker();
3962
- }
4126
+ clearRunError();
3963
4127
  refreshChanges();
3964
4128
  schedulePublish();
3965
4129
  });
@@ -3976,7 +4140,7 @@ export default function (pi) {
3976
4140
  // S62 turn-end: the working tree may have changed without transcript
3977
4141
  // evidence (external/untracked edits), so re-scan before publishing.
3978
4142
  refreshChanges();
3979
- if (activeSubs().length === 0 && !askActiveNow() && !reviewActive) {
4143
+ if (activeSubs().length === 0 && !askActiveNow() && !reviewActive && !errorCode) {
3980
4144
  clearEmittedLabel();
3981
4145
  void publishNow();
3982
4146
  } else {
@@ -5,11 +5,12 @@
5
5
  // Shell's own customize card (odd/tasks/customize-parity-done-idle.md T1, S1).
6
6
  //
7
7
  // One left `CATEGORIES` list, one right pane headed `<Category> · n/m` holding
8
- // the setting rows, and the Shell's footer keys. Each switch is ONE row that
9
- // paints the stored value with `●` and the other with `○`, so Enter (or a click
10
- // on the row) is still the whole toggle. The removed worktree / ODD / Issues /
11
- // Reset sections are gone, and the panel reads the current state handed in by
12
- // the extension instead of a cross-extension provider slot.
8
+ // the setting rows, one line describing what the focused setting does, and the
9
+ // Shell's footer keys. Each switch is ONE row that paints the stored value with
10
+ // `●` and the other with `○`, so Enter (or a click on the row) is still the
11
+ // whole toggle. The removed worktree / ODD / Issues / Reset sections are gone,
12
+ // and the panel reads the current state handed in by the extension instead of a
13
+ // cross-extension provider slot.
13
14
  //
14
15
  // The host component contract (pi-coding-agent `custom`): the factory receives
15
16
  // (hostTui, theme, keybindings, done) and returns
@@ -156,10 +157,21 @@ const CUSTOMIZE_PILL_OTHER = "○";
156
157
  // The switches this package owns. `id` is the apply target the extension knows
157
158
  // (the sidebar rows go through the Herdr plugin's own configure step,
158
159
  // notifications through the `gentle-moshi.json` flag and its Pi settings
159
- // exclusion) and `setting` is the row name the panel paints.
160
+ // exclusion) and `setting` is the row name the panel paints. `description` is
161
+ // the one line the card shows for the focused setting: it says what the switch
162
+ // changes, and the notification switch is the Moshi channel, never the agent
163
+ // notifications the host owns.
160
164
  const CUSTOMIZE_SWITCHES = [
161
- { id: "sidebar", setting: "Sidebar agent rows" },
162
- { id: "moshi", setting: "Notifications" },
165
+ {
166
+ id: "sidebar",
167
+ setting: "Sidebar agent rows",
168
+ description: "Hands the Herdr sidebar to this plugin's managed agent rows.",
169
+ },
170
+ {
171
+ id: "moshi",
172
+ setting: "Notifications",
173
+ description: "Replaces the Moshi hook with this plugin's own notification channel.",
174
+ },
163
175
  ];
164
176
 
165
177
  // Categories only group rows for display. Notifications appears under both
@@ -167,8 +179,18 @@ const CUSTOMIZE_SWITCHES = [
167
179
  // looked for, and `Moshi notifications` keeps the switch the user already
168
180
  // knows. Both rows read the one flag, so they can never disagree.
169
181
  const CUSTOMIZE_CATEGORIES = [
170
- { id: "sidebar", title: "Herdr Sidebar", switches: ["sidebar", "moshi"] },
171
- { id: "moshi", title: "Moshi notifications", switches: ["moshi"] },
182
+ {
183
+ id: "sidebar",
184
+ title: "Herdr Sidebar",
185
+ description: "Sidebar agent rows plus the Moshi notification channel.",
186
+ switches: ["sidebar", "moshi"],
187
+ },
188
+ {
189
+ id: "moshi",
190
+ title: "Moshi notifications",
191
+ description: "The Moshi notification channel this plugin owns.",
192
+ switches: ["moshi"],
193
+ },
172
194
  ];
173
195
 
174
196
  // One row per switch: it paints the stored value and carries the value Enter
@@ -181,6 +203,7 @@ function toggleRow(definition, active) {
181
203
  id: current === "on" ? "off" : "on",
182
204
  switchId: definition.id,
183
205
  setting: definition.setting,
206
+ description: definition.description,
184
207
  current,
185
208
  currentLabel: current === "on" ? "On" : current === "off" ? "Off" : "Unknown",
186
209
  otherLabel: current === "on" ? "Off" : "On",
@@ -199,6 +222,7 @@ function customizePanelModel({ sidebar, moshi } = {}) {
199
222
  return CUSTOMIZE_CATEGORIES.map((category) => ({
200
223
  id: category.id,
201
224
  title: category.title,
225
+ description: category.description,
202
226
  rows: category.switches.map((switchId) => toggleRow(
203
227
  CUSTOMIZE_SWITCHES.find((entry) => entry.id === switchId),
204
228
  current[switchId],
@@ -210,9 +234,9 @@ function customizePanelModel({ sidebar, moshi } = {}) {
210
234
  // role and the rest as its description. `short` is the compact form, and
211
235
  // `priority` is the drop order, so the close key outlives every other hint.
212
236
  // There is no `p profiles` entry: this plugin owns no profiles concept, and a
213
- // dead key in the footer would be a lie.
237
+ // dead key in the footer would be a lie. The pointer needs no entry either:
238
+ // every legend token names a key the panel answers to.
214
239
  const CUSTOMIZE_FOOTER_KEYS = [
215
- { text: "Click", short: "Click", priority: 10 },
216
240
  { key: "←/→", text: "←/→ or Tab panes", short: "←/→ panes", priority: 60 },
217
241
  { key: "↑/↓", text: "↑/↓ move", short: "↑/↓ move", priority: 70 },
218
242
  { key: "Enter", text: "Enter apply", short: "Enter apply", priority: 80 },
@@ -358,7 +382,10 @@ function customizeIsKeyRelease(helpers, data) {
358
382
  // One setting line: the name column, then the Shell's pill pair — `●` on the
359
383
  // stored value and `○` on the other. A pair wider than the pane falls back to
360
384
  // the stored pill alone, so the narrow width keeps showing the real state.
361
- function customizeSettingLine(helpers, theme, row, nameWidth, size, focused) {
385
+ // `focused` marks the row Enter would apply (visible in either pane, so the
386
+ // keyboard always shows its target) and `active` adds the band, which only the
387
+ // pane that owns the focus paints.
388
+ function customizeSettingLine(helpers, theme, row, nameWidth, size, focused, active) {
362
389
  const name = String(row.setting);
363
390
  const namePad = " ".repeat(Math.max(0, nameWidth - customizeMeasure(helpers, name)));
364
391
  const prefix = focused ? "▸ " : " ";
@@ -368,7 +395,7 @@ function customizeSettingLine(helpers, theme, row, nameWidth, size, focused) {
368
395
  const pair = `${stored} ${other}`;
369
396
  const showPair = customizeMeasure(helpers, `${lead}${pair}`) <= size;
370
397
  const body = showPair ? pair : stored;
371
- if (focused && theme && typeof theme.bg === "function") {
398
+ if (active && theme && typeof theme.bg === "function") {
372
399
  try {
373
400
  const plain = customizeFit(helpers, `${lead}${body}`, Math.max(0, size));
374
401
  const band = theme.bg("selectedBg", plain + " ".repeat(Math.max(0, size - customizeMeasure(helpers, plain))));
@@ -408,6 +435,15 @@ function createCustomizePanel({ helpers, hostTui, theme, rowsAvailable, model, d
408
435
  const category = model[state.cat];
409
436
  return { category, row: category.rows[state.row[state.cat]] || null };
410
437
  }
438
+ // What the card describes on its own row: the setting the values pane holds
439
+ // the focus on, or the category while the left list owns it.
440
+ function focusedDescription() {
441
+ const category = model[state.cat];
442
+ const row = state.pane === "values" ? focused().row : null;
443
+ return row
444
+ ? { title: row.setting, description: row.description }
445
+ : { title: category.title, description: category.description };
446
+ }
411
447
  function render(width) {
412
448
  const w = typeof width === "number" && Number.isFinite(width) ? Math.floor(width) : 0;
413
449
  state.frame = null;
@@ -435,11 +471,17 @@ function createCustomizePanel({ helpers, hostTui, theme, rowsAvailable, model, d
435
471
  const category = model[state.cat];
436
472
  const rows = category.rows;
437
473
  const showHeading = height >= 6;
474
+ // The description rides directly above the legend, so it needs one more row
475
+ // than the heading and the legend alone; a 6-row card keeps the keys and
476
+ // drops the prose instead of the other way round.
477
+ const showDescription = height >= 7;
438
478
  // Right pane: one line per setting (name column plus the pill pair) and,
439
479
  // when the stored state is unreadable, one muted note under it.
440
480
  const rightLines = rows.map((row, index) => ({ kind: "row", index, row }));
441
481
  for (const row of rows) if (row.note) rightLines.push({ kind: "note", text: row.note });
442
- const contentHeight = Math.max(1, height - 2 - 1 - (showHeading ? 2 : 0));
482
+ // Title, then heading + description + legend when they fit, above two borders.
483
+ const chrome = 1 + (showHeading ? 2 : 0) + (showDescription ? 1 : 0);
484
+ const contentHeight = Math.max(1, height - 2 - chrome);
443
485
  const position = navOnly ? state.cat : state.row[state.cat];
444
486
  const listLength = navOnly ? model.length : rightLines.length;
445
487
  const start = Math.min(Math.max(0, position - contentHeight + 1), Math.max(0, listLength - contentHeight));
@@ -497,6 +539,7 @@ function createCustomizePanel({ helpers, hostTui, theme, rowsAvailable, model, d
497
539
  item.row,
498
540
  nameWidth,
499
541
  rightWidth,
542
+ at === state.row[state.cat],
500
543
  at === state.row[state.cat] && state.pane === "values",
501
544
  );
502
545
  } else if (item && item.kind === "note") {
@@ -512,6 +555,13 @@ function createCustomizePanel({ helpers, hostTui, theme, rowsAvailable, model, d
512
555
  if (navOnly && item) hits.push({ kind: "category", index: at, y, x: rightStart + 2, end: rightStart + rightWidth });
513
556
  else if (item && item.kind === "row") hits.push({ kind: "row", index: item.index, y, x: rightStart + 2, end: rightStart + rightWidth });
514
557
  }
558
+ if (showDescription) {
559
+ const described = focusedDescription();
560
+ lines.push(compose([
561
+ { kind: "value", text: `${described.title} — ` },
562
+ { kind: "description", text: described.description },
563
+ ], inner));
564
+ }
515
565
  if (showHeading) {
516
566
  lines.push(customizePad(helpers, customizeFooter(helpers, theme, CUSTOMIZE_FOOTER_KEYS, inner), inner));
517
567
  }
@@ -566,33 +616,53 @@ function createCustomizePanel({ helpers, hostTui, theme, rowsAvailable, model, d
566
616
  }
567
617
  // Pointer contract: x/y are local to this component's rendered frame, the
568
618
  // card border included. A press only captures the gesture; the click that
569
- // follows activates the hit, so a drag never applies a row by accident.
570
- // Anything outside a pane's text is ignored, which is also the answer for a
571
- // click on a border, the title, the heading or the footer.
619
+ // follows activates the hit, so a drag never applies a row by accident, and
620
+ // a move only carries the focus. Anything outside a pane's text is ignored,
621
+ // which is also the answer for a click on a border, the title, the heading
622
+ // or the footer.
623
+ //
624
+ // The reported `width`/`height` are the box the host rendered, which the
625
+ // overlay may have clipped shorter than the rows this panel budgeted. The hit
626
+ // test therefore reads the frame it rendered and only clamps the row into it:
627
+ // a geometry comparison the user cannot see must never swallow a real click.
628
+ function focusHit(hit) {
629
+ if (hit.kind === "category") {
630
+ if (state.pane === "categories" && state.cat === hit.index) return false;
631
+ state.cat = hit.index;
632
+ state.pane = "categories";
633
+ return true;
634
+ }
635
+ const target = model[state.cat];
636
+ if (!target || !target.rows[hit.index]) return false;
637
+ if (state.pane === "values" && state.row[state.cat] === hit.index) return false;
638
+ state.pane = "values";
639
+ state.row[state.cat] = hit.index;
640
+ return true;
641
+ }
572
642
  function handleMouse(event) {
573
- if (!event || event.button !== "left") return undefined;
574
- if (event.type !== "press" && event.type !== "click") return undefined;
643
+ if (!event) return undefined;
644
+ const moving = event.type === "move";
645
+ if (!moving && (event.button !== "left" || (event.type !== "press" && event.type !== "click"))) return undefined;
575
646
  const frame = state.frame;
576
647
  if (!frame) return undefined;
577
648
  if (!Number.isFinite(event.x) || !Number.isFinite(event.y)) return undefined;
578
- const sized = (!Number.isFinite(event.width) || event.width === frame.width)
579
- && (!Number.isFinite(event.height) || event.height === frame.height);
580
- if (!sized) return undefined;
581
- const hit = frame.hits.find((entry) => entry.y === event.y && event.x >= entry.x && event.x < entry.end);
649
+ const y = Math.min(Math.max(0, Math.floor(event.y)), Math.max(0, frame.height - 1));
650
+ const hit = frame.hits.find((entry) => entry.y === y && event.x >= entry.x && event.x < entry.end);
582
651
  if (!hit) return undefined;
652
+ if (moving) return { handled: true, render: focusHit(hit) };
583
653
  if (event.type === "press") return { handled: true, capture: true, render: false };
584
654
  const target = model[state.cat];
585
655
  if (hit.kind === "category") {
586
656
  state.cat = hit.index;
587
657
  state.pane = "categories";
588
- return { handled: true, render: true };
658
+ return { handled: true, render: true, focus: true };
589
659
  }
590
660
  const row = target ? target.rows[hit.index] : null;
591
661
  if (!row) return undefined;
592
662
  state.pane = "values";
593
663
  state.row[state.cat] = hit.index;
594
664
  done({ categoryId: target.id, switchId: row.switchId, valueId: row.id });
595
- return { handled: true, render: true };
665
+ return { handled: true, render: true, focus: true };
596
666
  }
597
667
  function invalidate() {}
598
668
  return { render, handleInput, handleMouse, invalidate, state };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "herdr-gentle-shell",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "description": "Pi package for Herdr sidebar states: the Pi extension sidecar that publishes session facts as Herdr pane-metadata tokens, the optional Moshi notification channel, and the Pi-side helpers the Herdr Gentle Shell plugin drives.",
5
5
  "keywords": [
6
6
  "pi-package",