@narumitw/pi-herdr 0.3.1 → 0.3.2

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/README.md CHANGED
@@ -9,7 +9,7 @@ Connect Pi's interactive lifecycle to Herdr and bootstrap the operating guidance
9
9
  - Reports Pi session identity and `working`, `blocked`, and `idle` lifecycle states to the current Herdr pane.
10
10
  - Publishes bounded `model`, `provider`, `thinking`, `session`, and `context_usage` tokens for Herdr sidebar rows.
11
11
  - Shows recognized sibling agents from the current Herdr workspace in a passive widget above Pi's editor, with a saved visibility toggle in `/herdr`.
12
- - Updates the widget from Herdr pane lifecycle and agent-status events without polling the CLI.
12
+ - Refreshes the widget on Herdr pane, workspace-name, and agent-status updates without polling the CLI.
13
13
  - Coalesces rapid state changes and retries short-lived local socket failures without interrupting Pi.
14
14
  - Derives blocked state from Pi's public `ui_prompt_start` and `ui_prompt_end` lifecycle events.
15
15
  - Bundles a thin `herdr` bootstrap skill for explicit Herdr inspection and control requests.
@@ -100,8 +100,13 @@ Agent reports contain the same ownership fields plus the current lifecycle state
100
100
  Blocking extension prompts use their Pi-provided title as the label and fall back to the prompt kind.
101
101
 
102
102
  Local socket delivery is best-effort.
103
- A failed request is retried once with bounded timeouts, and reporting failures never stop Pi.
104
- Session shutdown aborts in-flight reporting and prevents stale session work from publishing later state.
103
+ Connection failures, malformed responses, and timeouts are retried once with bounded timeouts; explicit API rejections are not retried.
104
+ Only a complete success response with the matching request ID acknowledges a report. Herdr can acknowledge but ignore an old sequence, so acknowledgement does not guarantee a state change.
105
+ Reporting failures never stop Pi.
106
+ Session shutdown aborts and drains in-flight reporting and prevents stale session work from publishing later state.
107
+ Replacement aborts pending metadata cleanup.
108
+ Native quit cleanup remains Herdr-owned: the extension does not release native Pi identity or clear reporting authority and restore references.
109
+ Herdr ignores official-source release requests, while authority clearing also removes session restore data; neither operation is used during shutdown.
105
110
 
106
111
  ## 🏷️ Pane metadata
107
112
 
@@ -144,17 +149,19 @@ The widget orders agents by `blocked`, `done`, `working`, `idle`, and `unknown`,
144
149
  A state label published through Herdr metadata can replace the raw state name.
145
150
  Herdr's public pane responses do not expose the blocked prompt message, so the widget cannot show that reason.
146
151
  The widget is read-only and does not focus panes, read terminal output, send prompts, or mark a background `done` state as seen.
147
- The extension discovers the current workspace, pane list, and agent names, opens pane-scoped status subscriptions plus topology subscriptions, and then reloads those identities to reconcile changes made during initialization.
148
- Expected pane creation, movement, or agent detection rebuilds the pane-scoped subscriptions without consuming the bounded failure retry.
149
- Unexpected disconnection clears the widget before one bounded reconnect attempt, and a second failure leaves it hidden until the next Pi session or `/reload`.
150
- Session replacement and shutdown abort the subscription, pending requests, reconnect delay, and stale widget publication.
152
+ The extension discovers the current workspace, pane list, and agent names, opens pane-scoped status subscriptions plus pane-update and workspace-name subscriptions, and then reloads those identities.
153
+ Events trigger serialized, coalesced reads rather than replacing current state with event payloads. If an event arrives during a read, the extension reads again before publishing that result.
154
+ Agent names, workspace labels, and cleared presentation fields update from these authoritative reads.
155
+ Changes to the current pane, workspace, or recognized-agent set rebuild the pane-scoped subscriptions without consuming the bounded failure retry.
156
+ Unexpected disconnection or `events_lost` clears the widget before one bounded reconnect attempt, and a second failure leaves it hidden until the next Pi session or `/reload`.
157
+ Session replacement and shutdown abort the subscription, pending reads, reconnect delay, and stale widget publication.
151
158
 
152
159
  ## 🔒 Security and privacy
153
160
 
154
161
  The extension connects only to the Unix socket or Windows named pipe provided by `HERDR_SOCKET_PATH`.
155
162
  Lifecycle reporting sends the current Herdr pane ID, Pi session path or ID, lifecycle state, session start reason, and blocked label to that endpoint.
156
163
  Metadata reporting sends the current Herdr pane ID plus only the selected model ID, provider ID, effective Thinking level, explicit Pi session name, and rounded context-usage percentage.
157
- For the widget, it reads the canonical current pane, current workspace metadata, current workspace pane list, and session agent list, then subscribes to pane creation, closure, movement, exit, agent detection, and agent-status events.
164
+ For the widget, it reads the canonical current pane, current workspace metadata, current workspace pane list, and session agent list, then subscribes to pane creation, updates, closure, movement, exit, agent detection, agent-status changes, and workspace renames.
158
165
  The session agent list can contain agent metadata from other workspaces, but the extension retains names only for panes in the current workspace list.
159
166
  Widget fields can include workspace, tab, pane, terminal, agent, display, name, title, label, state-label, and lifecycle identifiers supplied by Herdr.
160
167
  The subscription can deliver matching pane events from other workspaces in the same Herdr session, and the extension ignores them after resolving the current workspace.
@@ -172,7 +179,8 @@ Command recipes, approval handling, and other operating safety rules come from t
172
179
  - Lifecycle reporting, metadata reporting, and the agent widget are disabled in RPC, JSON, and print modes.
173
180
  - The widget has no settings for placement, workspace scope, or row count.
174
181
  - The widget cannot show blocked prompt text because Herdr does not expose it through public pane responses.
175
- - Herdr exposes no rename event, so agent and pane renames appear after the next topology refresh, reconnect, Pi `/reload`, or session start rather than immediately.
182
+ - The widget requires compatible pane-update and workspace-name subscriptions; unsupported subscriptions hide the widget without disabling lifecycle or metadata reporting.
183
+ - A pane-label change appears on its next update event or authoritative refresh; an agent rename emits a pane-update event.
176
184
  - Integration requires a running compatible Herdr session and valid injected environment variables.
177
185
  - Model control requires an installed Herdr CLI that supports `herdr --skill`.
178
186
  - Socket failures are intentionally silent after the bounded retry.
package/dist/index.ts CHANGED
@@ -31,6 +31,9 @@ var NdjsonFrames = class {
31
31
  throw new Error("Herdr returned invalid JSON");
32
32
  }
33
33
  }
34
+ if (this.buffer.length > MAX_HERDR_FRAME_BYTES) {
35
+ throw new Error("Herdr response frame exceeded the size limit");
36
+ }
34
37
  return frames;
35
38
  }
36
39
  };
@@ -40,47 +43,36 @@ function isRecord(value) {
40
43
  function abortReason(signal) {
41
44
  return signal.reason instanceof Error ? signal.reason : new DOMException("Herdr request aborted", "AbortError");
42
45
  }
46
+ var HerdrApiError = class extends Error {
47
+ code;
48
+ constructor(error) {
49
+ super(`Herdr ${typeof error.message === "string" ? error.message : "request failed"}`);
50
+ this.code = typeof error.code === "string" ? error.code : void 0;
51
+ }
52
+ };
43
53
  function responseError(frame) {
44
- if (!isRecord(frame.error)) return void 0;
45
- const message = typeof frame.error.message === "string" ? frame.error.message : "request failed";
46
- return new Error(`Herdr ${message}`);
47
- }
48
- function sendRequestAttempt(socketEndpoint, request, timeoutMs, signal) {
49
- if (signal.aborted) return Promise.resolve(false);
50
- return new Promise((resolve) => {
51
- let finished = false;
52
- let timeout;
53
- const socket = net.createConnection(socketEndpoint);
54
- const finish = (delivered) => {
55
- if (finished) return;
56
- finished = true;
57
- if (timeout) clearTimeout(timeout);
58
- signal.removeEventListener("abort", abort);
59
- socket.destroy();
60
- resolve(delivered);
61
- };
62
- const abort = () => finish(false);
63
- signal.addEventListener("abort", abort, { once: true });
64
- socket.on("error", () => finish(false));
65
- socket.on("connect", () => socket.write(`${JSON.stringify(request)}
66
- `));
67
- socket.on("data", () => finish(true));
68
- socket.on("end", () => finish(false));
69
- socket.on("close", () => finish(false));
70
- timeout = setTimeout(() => finish(false), timeoutMs);
71
- timeout.unref?.();
72
- });
54
+ if (!("error" in frame)) return void 0;
55
+ if (!isRecord(frame.error)) return new Error("Herdr returned an invalid error response");
56
+ return new HerdrApiError(frame.error);
73
57
  }
74
58
  function createBestEffortSender(socketEndpoint) {
75
59
  return async (request, signal) => {
76
- if (await sendRequestAttempt(socketEndpoint, request, 500, signal)) return;
77
- if (signal.aborted) return;
78
- await sendRequestAttempt(socketEndpoint, request, 1500, signal);
60
+ for (const timeoutMs of [500, 1500]) {
61
+ if (signal.aborted) return;
62
+ try {
63
+ const result = await requestHerdr(socketEndpoint, request, signal, timeoutMs);
64
+ if (isRecord(result) && result.type === "ok") return;
65
+ } catch (error) {
66
+ if (signal.aborted || error instanceof HerdrApiError) return;
67
+ }
68
+ }
79
69
  };
80
70
  }
81
71
  function requestHerdr(socketEndpoint, request, signal, timeoutMs = 1500) {
82
72
  if (signal.aborted) return Promise.reject(abortReason(signal));
83
73
  return new Promise((resolve, reject) => {
74
+ const payload = `${JSON.stringify(request)}
75
+ `;
84
76
  const socket = net.createConnection(socketEndpoint);
85
77
  const parser = new NdjsonFrames();
86
78
  let finished = false;
@@ -100,12 +92,14 @@ function requestHerdr(socketEndpoint, request, signal, timeoutMs = 1500) {
100
92
  };
101
93
  const abort = () => finish(abortReason(signal));
102
94
  signal.addEventListener("abort", abort, { once: true });
103
- socket.on("connect", () => socket.write(`${JSON.stringify(request)}
104
- `));
95
+ socket.on("connect", () => {
96
+ if (!finished) socket.write(payload);
97
+ });
105
98
  socket.on("error", (error) => finish(error));
106
99
  socket.on("end", () => finish(new Error("Herdr closed the request before responding")));
107
100
  socket.on("close", () => finish(new Error("Herdr request socket closed")));
108
101
  socket.on("data", (chunk) => {
102
+ if (finished) return;
109
103
  try {
110
104
  for (const value of parser.push(chunk)) {
111
105
  if (!isRecord(value)) continue;
@@ -135,6 +129,8 @@ function requestHerdr(socketEndpoint, request, signal, timeoutMs = 1500) {
135
129
  }
136
130
  async function openHerdrSubscription(socketEndpoint, request, signal, onEvent, timeoutMs = 1500) {
137
131
  if (signal.aborted) throw abortReason(signal);
132
+ const payload = `${JSON.stringify(request)}
133
+ `;
138
134
  const socket = net.createConnection(socketEndpoint);
139
135
  const parser = new NdjsonFrames();
140
136
  const pendingEvents = [];
@@ -175,6 +171,7 @@ async function openHerdrSubscription(socketEndpoint, request, signal, onEvent, t
175
171
  else resolveClosed();
176
172
  };
177
173
  const deliver = (frame) => {
174
+ if (finished) return;
178
175
  try {
179
176
  onEvent(frame);
180
177
  } catch (error) {
@@ -186,28 +183,27 @@ async function openHerdrSubscription(socketEndpoint, request, signal, onEvent, t
186
183
  finish();
187
184
  };
188
185
  signal.addEventListener("abort", abort, { once: true });
189
- socket.on("connect", () => socket.write(`${JSON.stringify(request)}
190
- `));
186
+ socket.on("connect", () => {
187
+ if (!finished) socket.write(payload);
188
+ });
191
189
  socket.on("error", (error) => finish(error));
192
190
  socket.on("end", () => finish(new Error("Herdr subscription closed")));
193
191
  socket.on("close", () => finish(new Error("Herdr subscription socket closed")));
194
192
  socket.on("data", (chunk) => {
193
+ if (finished) return;
195
194
  try {
196
195
  for (const value of parser.push(chunk)) {
197
- if (!ready) {
198
- if (isRecord(value)) {
199
- const uncorrelatedError = responseError(value);
200
- if (uncorrelatedError && (value.id === "" || value.id === void 0)) {
201
- finish(uncorrelatedError);
202
- return;
203
- }
196
+ if (finished) return;
197
+ if (isRecord(value)) {
198
+ const error = responseError(value);
199
+ if (error && (value.id === request.id || value.id === "" || value.id === void 0)) {
200
+ finish(error);
201
+ return;
204
202
  }
203
+ if ("id" in value && value.id !== request.id) continue;
204
+ }
205
+ if (!ready) {
205
206
  if (isRecord(value) && value.id === request.id) {
206
- const error = responseError(value);
207
- if (error) {
208
- finish(error);
209
- return;
210
- }
211
207
  if (!isRecord(value.result) || value.result.type !== "subscription_started") {
212
208
  finish(new Error("Herdr returned an invalid subscription acknowledgement"));
213
209
  return;
@@ -301,6 +297,8 @@ function createHerdrMetadataRequest(options) {
301
297
  var HERDR_AGENT_STATUSES = ["idle", "working", "blocked", "done", "unknown"];
302
298
  var HERDR_WIDGET_TOPOLOGY_SUBSCRIPTIONS = [
303
299
  { type: "pane.created" },
300
+ { type: "pane.updated" },
301
+ { type: "workspace.renamed" },
304
302
  { type: "pane.closed" },
305
303
  { type: "pane.moved" },
306
304
  { type: "pane.exited" },
@@ -398,7 +396,12 @@ function parseHerdrPaneEvent(value) {
398
396
  return void 0;
399
397
  }
400
398
  const data = value.data;
401
- if (value.event === "pane.agent_status_changed") {
399
+ if (value.event === "workspace_renamed") {
400
+ const workspaceId = requiredString(data.workspace_id);
401
+ if (!workspaceId || typeof data.label !== "string") return void 0;
402
+ return { type: "workspace_renamed", workspaceId };
403
+ }
404
+ if (value.event === "pane.agent_status_changed" || value.event === "pane_agent_status_changed") {
402
405
  const paneId = requiredString(data.pane_id);
403
406
  const workspaceId = requiredString(data.workspace_id);
404
407
  const status = agentStatus(data.agent_status);
@@ -406,17 +409,12 @@ function parseHerdrPaneEvent(value) {
406
409
  return {
407
410
  type: "agent_status_changed",
408
411
  paneId,
409
- workspaceId,
410
- agent: optionalString(data.agent),
411
- agentStatus: status,
412
- displayAgent: optionalString(data.display_agent),
413
- stateLabels: stringRecord(data.state_labels),
414
- title: optionalString(data.title)
412
+ workspaceId
415
413
  };
416
414
  }
417
- if (value.event === "pane_created") {
415
+ if (value.event === "pane_created" || value.event === "pane_updated") {
418
416
  const pane = parseHerdrPane(data.pane);
419
- return pane ? { type: "created", pane } : void 0;
417
+ return pane ? { type: value.event === "pane_created" ? "created" : "updated", pane } : void 0;
420
418
  }
421
419
  if (value.event === "pane_closed" || value.event === "pane_exited") {
422
420
  const paneId = requiredString(data.pane_id);
@@ -438,16 +436,15 @@ function parseHerdrPaneEvent(value) {
438
436
  if (value.event === "pane_agent_detected") {
439
437
  const paneId = requiredString(data.pane_id);
440
438
  const workspaceId = requiredString(data.workspace_id);
441
- if (!paneId || !workspaceId || typeof data.released !== "boolean") return void 0;
439
+ if (!paneId || !workspaceId || data.released !== void 0 && typeof data.released !== "boolean") {
440
+ return void 0;
441
+ }
442
442
  const finalStatus = data.final_status === null ? void 0 : agentStatus(data.final_status);
443
443
  if (data.final_status !== void 0 && data.final_status !== null && !finalStatus) return void 0;
444
444
  return {
445
445
  type: "agent_detected",
446
446
  paneId,
447
- workspaceId,
448
- agent: optionalString(data.agent),
449
- finalStatus,
450
- released: data.released
447
+ workspaceId
451
448
  };
452
449
  }
453
450
  return void 0;
@@ -543,57 +540,6 @@ var HerdrWidgetModel = class {
543
540
  isCurrentWorkspace(workspaceId) {
544
541
  return this.currentWorkspaceId === workspaceId;
545
542
  }
546
- apply(event) {
547
- if (event.type === "created") {
548
- this.panes.set(event.pane.paneId, observedPane(event.pane));
549
- return;
550
- }
551
- if (event.type === "closed" || event.type === "exited") {
552
- this.panes.delete(event.paneId);
553
- return;
554
- }
555
- if (event.type === "moved") {
556
- this.panes.delete(event.previousPaneId);
557
- this.panes.set(event.pane.paneId, observedPane(event.pane));
558
- if (this.currentPaneId === event.previousPaneId) {
559
- this.currentPaneId = event.pane.paneId;
560
- this.currentWorkspaceId = event.pane.workspaceId;
561
- this.workspace = { workspaceId: event.pane.workspaceId };
562
- }
563
- return;
564
- }
565
- const existing = this.panes.get(event.paneId);
566
- if (event.type === "agent_detected") {
567
- if (event.released || !event.agent) {
568
- if (existing) this.panes.set(event.paneId, { ...existing, agent: void 0 });
569
- return;
570
- }
571
- this.panes.set(event.paneId, {
572
- ...existing ?? {
573
- paneId: event.paneId,
574
- workspaceId: event.workspaceId,
575
- agentStatus: event.finalStatus ?? "unknown",
576
- stateLabels: {}
577
- },
578
- agent: event.agent,
579
- agentStatus: event.finalStatus ?? existing?.agentStatus ?? "unknown"
580
- });
581
- return;
582
- }
583
- if (event.type !== "agent_status_changed") return;
584
- this.panes.set(event.paneId, {
585
- ...existing ?? {
586
- paneId: event.paneId,
587
- workspaceId: event.workspaceId,
588
- stateLabels: {}
589
- },
590
- agent: event.agent ?? existing?.agent,
591
- agentStatus: event.agentStatus,
592
- displayAgent: event.displayAgent ?? existing?.displayAgent,
593
- stateLabels: event.stateLabels ?? existing?.stateLabels ?? {},
594
- title: event.title ?? existing?.title
595
- });
596
- }
597
543
  snapshot() {
598
544
  if (!this.currentPaneId || !this.currentWorkspaceId || !this.workspace) return void 0;
599
545
  const rows = [...this.panes.values()].filter(
@@ -659,18 +605,16 @@ function herdrWidgetFingerprint(snapshot) {
659
605
  }
660
606
 
661
607
  // src/herdr-observer.ts
662
- var MAX_PENDING_EVENTS = 1024;
663
608
  var HerdrTopologyChangedError = class extends Error {
664
609
  };
665
- function requiresResubscribe(event) {
666
- return event.type === "created" || event.type === "moved" || event.type === "agent_detected";
667
- }
668
610
  function isRelevantEvent(model, event) {
669
- if (event.type === "created") return model.isCurrentWorkspace(event.pane.workspaceId);
611
+ if (event.type === "created" || event.type === "updated") {
612
+ return model.isCurrentWorkspace(event.pane.workspaceId);
613
+ }
670
614
  if (event.type === "moved") {
671
615
  return model.isCurrentPane(event.previousPaneId) || model.isCurrentWorkspace(event.previousWorkspaceId) || model.isCurrentWorkspace(event.pane.workspaceId);
672
616
  }
673
- return model.isCurrentWorkspace(event.workspaceId);
617
+ return "workspaceId" in event && model.isCurrentWorkspace(event.workspaceId);
674
618
  }
675
619
  function subscriptionFingerprint(currentPane, panes) {
676
620
  const agentPaneIds = panes.filter((pane) => pane.agent !== void 0).map((pane) => pane.paneId).sort();
@@ -765,7 +709,11 @@ function createHerdrWidgetObserver(options) {
765
709
  )
766
710
  ]);
767
711
  if (!owns(ctx, expectedGeneration) || signal.aborted) return void 0;
768
- const namesByPane = new Map(parseAgentListResult(agentResult).map((pane) => [pane.paneId, pane.agentName]));
712
+ const panes = parsePaneListResult(listResult);
713
+ const paneIds = new Set(panes.map((pane) => pane.paneId));
714
+ const namesByPane = new Map(
715
+ parseAgentListResult(agentResult).filter((pane) => pane.workspaceId === currentPane.workspaceId && paneIds.has(pane.paneId)).map((pane) => [pane.paneId, pane.agentName])
716
+ );
769
717
  const withAgentName = (pane) => ({
770
718
  ...pane,
771
719
  agentName: namesByPane.get(pane.paneId) ?? pane.agentName
@@ -776,7 +724,7 @@ function createHerdrWidgetObserver(options) {
776
724
  }
777
725
  return {
778
726
  currentPane: withAgentName(currentPane),
779
- panes: parsePaneListResult(listResult).map(withAgentName),
727
+ panes: panes.map(withAgentName),
780
728
  workspace
781
729
  };
782
730
  };
@@ -788,60 +736,27 @@ function createHerdrWidgetObserver(options) {
788
736
  const signal = attemptController.signal;
789
737
  let attemptActive = true;
790
738
  let subscription;
791
- let refreshTask;
739
+ let failure;
740
+ let wake;
741
+ const wakeRefresh = () => {
742
+ const resolve = wake;
743
+ wake = void 0;
744
+ resolve?.();
745
+ };
746
+ signal.addEventListener("abort", wakeRefresh);
747
+ const failAttempt = (error) => {
748
+ if (!attemptActive || signal.aborted) return;
749
+ failure = error;
750
+ if (owns(ctx, expectedGeneration)) clearWidget(ctx);
751
+ attemptController.abort(error);
752
+ };
792
753
  try {
793
754
  const discovered = await loadPaneSet(ctx, expectedGeneration, signal);
794
755
  if (!discovered) return;
795
756
  const subscribedFingerprint = subscriptionFingerprint(discovered.currentPane, discovered.panes);
796
757
  const model = new HerdrWidgetModel();
797
758
  model.reset(discovered.currentPane, discovered.panes, discovered.workspace);
798
- const pendingEvents = [];
799
- const pendingStatusEvents = [];
800
- let initialized = false;
801
- let topologyPending = false;
802
- let refreshingTopology = false;
803
- let refreshAgain = false;
804
- let rejectReconfigure;
805
- let reconfigureSettled = false;
806
- const reconfigure = new Promise((_resolve, reject) => {
807
- rejectReconfigure = reject;
808
- });
809
- void reconfigure.catch(() => void 0);
810
- const failAttempt = (error) => {
811
- if (reconfigureSettled) return;
812
- reconfigureSettled = true;
813
- rejectReconfigure(error);
814
- };
815
- const scheduleTopologyRefresh = () => {
816
- if (!initialized || !attemptActive || signal.aborted) return;
817
- if (refreshTask) {
818
- refreshAgain = true;
819
- return;
820
- }
821
- refreshTask = (async () => {
822
- do {
823
- refreshAgain = false;
824
- refreshingTopology = true;
825
- const refreshed = await loadPaneSet(ctx, expectedGeneration, signal);
826
- if (!refreshed || !attemptActive || signal.aborted) return;
827
- model.reset(refreshed.currentPane, refreshed.panes, refreshed.workspace);
828
- for (const event of pendingStatusEvents.splice(0)) {
829
- if (isRelevantEvent(model, event)) model.apply(event);
830
- }
831
- refreshingTopology = false;
832
- publish(ctx, model, expectedGeneration);
833
- if (subscriptionFingerprint(refreshed.currentPane, refreshed.panes) !== subscribedFingerprint) {
834
- failAttempt(new HerdrTopologyChangedError());
835
- return;
836
- }
837
- } while (refreshAgain && attemptActive && !signal.aborted);
838
- })().catch((error) => {
839
- failAttempt(error instanceof Error ? error : new Error(String(error)));
840
- }).finally(() => {
841
- refreshingTopology = false;
842
- refreshTask = void 0;
843
- });
844
- };
759
+ let dirty = true;
845
760
  subscription = await subscribe(
846
761
  options.environment.socketEndpoint,
847
762
  {
@@ -851,62 +766,46 @@ function createHerdrWidgetObserver(options) {
851
766
  },
852
767
  signal,
853
768
  (frame) => {
769
+ if (!attemptActive || !owns(ctx, expectedGeneration) || signal.aborted) return;
854
770
  const event = parseHerdrPaneEvent(frame);
855
- if (!initialized) {
856
- if (!event || !isRelevantEvent(model, event)) return;
857
- if (requiresResubscribe(event)) {
858
- topologyPending = true;
859
- return;
860
- }
861
- if (pendingEvents.length >= MAX_PENDING_EVENTS) {
862
- throw new Error("Too many Herdr events arrived during initialization");
863
- }
864
- pendingEvents.push(event);
865
- return;
866
- }
867
- if (!event || !owns(ctx, expectedGeneration) || signal.aborted || !isRelevantEvent(model, event)) {
868
- return;
869
- }
870
- if (requiresResubscribe(event)) {
871
- scheduleTopologyRefresh();
872
- return;
873
- }
874
- if (refreshingTopology) {
875
- if (pendingStatusEvents.length >= MAX_PENDING_EVENTS) {
876
- throw new Error("Too many Herdr status events arrived during refresh");
877
- }
878
- pendingStatusEvents.push(event);
879
- return;
880
- }
881
- model.apply(event);
882
- publish(ctx, model, expectedGeneration);
771
+ if (!event || !isRelevantEvent(model, event)) return;
772
+ dirty = true;
773
+ wakeRefresh();
774
+ }
775
+ ).catch(async (error) => {
776
+ if (!owns(ctx, expectedGeneration) || signal.aborted) throw error;
777
+ const latest = await loadPaneSet(ctx, expectedGeneration, signal);
778
+ if (latest && subscriptionFingerprint(latest.currentPane, latest.panes) !== subscribedFingerprint) {
779
+ throw new HerdrTopologyChangedError();
883
780
  }
781
+ throw error;
782
+ });
783
+ void subscription.closed.then(
784
+ () => failAttempt(new Error("Herdr subscription ended")),
785
+ (error) => failAttempt(error instanceof Error ? error : new Error(String(error)))
884
786
  );
885
- if (!owns(ctx, expectedGeneration) || signal.aborted) return;
886
- const reconciled = await loadPaneSet(ctx, expectedGeneration, signal);
887
- if (!reconciled) return;
888
- model.reset(reconciled.currentPane, reconciled.panes, reconciled.workspace);
889
- for (const event of pendingEvents.splice(0)) {
890
- if (isRelevantEvent(model, event)) model.apply(event);
891
- }
892
- if (subscriptionFingerprint(reconciled.currentPane, reconciled.panes) !== subscribedFingerprint) {
893
- throw new HerdrTopologyChangedError();
787
+ while (owns(ctx, expectedGeneration) && !signal.aborted) {
788
+ dirty = false;
789
+ const refreshed = await loadPaneSet(ctx, expectedGeneration, signal);
790
+ if (!refreshed || signal.aborted) break;
791
+ if (dirty) continue;
792
+ if (subscriptionFingerprint(refreshed.currentPane, refreshed.panes) !== subscribedFingerprint) {
793
+ throw new HerdrTopologyChangedError();
794
+ }
795
+ model.reset(refreshed.currentPane, refreshed.panes, refreshed.workspace);
796
+ publish(ctx, model, expectedGeneration);
797
+ await new Promise((resolve) => {
798
+ wake = resolve;
799
+ if (dirty || signal.aborted) wakeRefresh();
800
+ });
894
801
  }
895
- initialized = true;
896
- publish(ctx, model, expectedGeneration);
897
- if (topologyPending) scheduleTopologyRefresh();
898
- await Promise.race([
899
- subscription.closed.then(() => {
900
- if (!signal.aborted) throw new Error("Herdr subscription ended");
901
- }),
902
- reconfigure
903
- ]);
802
+ if (failure) throw failure;
904
803
  } finally {
905
804
  attemptActive = false;
906
805
  attemptController.abort(new DOMException("Herdr widget attempt ended", "AbortError"));
806
+ signal.removeEventListener("abort", wakeRefresh);
907
807
  sessionSignal.removeEventListener("abort", abortAttempt);
908
808
  subscription?.close();
909
- await Promise.allSettled(refreshTask ? [refreshTask] : []);
910
809
  }
911
810
  };
912
811
  const run = async (ctx, expectedGeneration, signal) => {
@@ -1285,7 +1184,8 @@ function createHerdrAgentStateExtension(options = {}) {
1285
1184
  let metadataDrainTask;
1286
1185
  let lastMetadataSnapshot;
1287
1186
  let metadataRefreshTimer;
1288
- let shutdownClearController;
1187
+ const sessionReportTasks = /* @__PURE__ */ new Set();
1188
+ let shutdownController;
1289
1189
  let shutdownSession;
1290
1190
  let shutdownTask;
1291
1191
  function requestId(kind) {
@@ -1323,7 +1223,7 @@ function createHerdrAgentStateExtension(options = {}) {
1323
1223
  function reportSession(sessionStartSource) {
1324
1224
  const sessionRef = currentSessionRef();
1325
1225
  if (!sessionRef) return Promise.resolve();
1326
- return safeSend(
1226
+ const task = safeSend(
1327
1227
  {
1328
1228
  id: requestId("session"),
1329
1229
  method: "pane.report_agent_session",
@@ -1338,6 +1238,9 @@ function createHerdrAgentStateExtension(options = {}) {
1338
1238
  },
1339
1239
  sessionController.signal
1340
1240
  );
1241
+ sessionReportTasks.add(task);
1242
+ void task.finally(() => sessionReportTasks.delete(task));
1243
+ return task;
1341
1244
  }
1342
1245
  function stateRequest(state) {
1343
1246
  return {
@@ -1477,8 +1380,10 @@ function createHerdrAgentStateExtension(options = {}) {
1477
1380
  const generation = ++sessionGeneration;
1478
1381
  const replaced = new DOMException("Herdr session replaced", "AbortError");
1479
1382
  sessionController.abort(replaced);
1480
- shutdownClearController?.abort(replaced);
1481
- shutdownClearController = void 0;
1383
+ shutdownController?.abort(replaced);
1384
+ shutdownController = void 0;
1385
+ shutdownTask = void 0;
1386
+ shutdownSession = void 0;
1482
1387
  if (metadataRefreshTimer) clearTimeout(metadataRefreshTimer);
1483
1388
  metadataRefreshTimer = void 0;
1484
1389
  queuedMetadata = void 0;
@@ -1500,7 +1405,7 @@ function createHerdrAgentStateExtension(options = {}) {
1500
1405
  const sessionReport = reportSession(event.reason);
1501
1406
  publishMetadata(ctx);
1502
1407
  await Promise.all([sessionReport, widgetStart]);
1503
- if (generation !== sessionGeneration || sessionController.signal.aborted || !rootSession) {
1408
+ if (generation !== sessionGeneration || activeSession !== ctx.sessionManager || sessionController.signal.aborted || !rootSession) {
1504
1409
  return;
1505
1410
  }
1506
1411
  agentActive = !ctx.isIdle();
@@ -1543,24 +1448,27 @@ function createHerdrAgentStateExtension(options = {}) {
1543
1448
  sessionController.abort(new DOMException("Herdr session shut down", "AbortError"));
1544
1449
  queuedState = void 0;
1545
1450
  queuedMetadata = void 0;
1546
- await Promise.allSettled([drainTask, metadataDrainTask, widget.shutdown(ctx)]);
1547
- const stillOwnsShutdown = shutdownGeneration === sessionGeneration && activeSession === session && !rootSession;
1548
- if (shouldClearMetadata && stillOwnsShutdown) {
1451
+ await Promise.allSettled([...sessionReportTasks, drainTask, metadataDrainTask, widget.shutdown(ctx)]);
1452
+ const stillOwnsShutdown = () => shutdownGeneration === sessionGeneration && activeSession === session && !rootSession;
1453
+ if (shouldClearMetadata && stillOwnsShutdown()) {
1549
1454
  const controller = new AbortController();
1550
- shutdownClearController = controller;
1551
- await safeSend(
1552
- createHerdrMetadataRequest({
1553
- id: requestId(),
1554
- paneId: environment.paneId,
1555
- source: SOURCE,
1556
- seq: nextReportSeq(),
1557
- snapshot: createHerdrMetadataClearSnapshot()
1558
- }),
1559
- controller.signal
1560
- );
1561
- if (shutdownClearController === controller) shutdownClearController = void 0;
1455
+ shutdownController = controller;
1456
+ try {
1457
+ await safeSend(
1458
+ createHerdrMetadataRequest({
1459
+ id: requestId(),
1460
+ paneId: environment.paneId,
1461
+ source: SOURCE,
1462
+ seq: nextReportSeq(),
1463
+ snapshot: createHerdrMetadataClearSnapshot()
1464
+ }),
1465
+ controller.signal
1466
+ );
1467
+ } finally {
1468
+ if (shutdownController === controller) shutdownController = void 0;
1469
+ }
1562
1470
  }
1563
- if (shutdownGeneration !== sessionGeneration || activeSession !== session || rootSession) {
1471
+ if (!stillOwnsShutdown()) {
1564
1472
  return;
1565
1473
  }
1566
1474
  lastMetadataSnapshot = void 0;