peerband 0.1.3 → 0.1.5

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/herdr/README.md CHANGED
@@ -1,18 +1,18 @@
1
- # Herdr plugin sources (contributors)
2
-
3
- Plain `.mjs` files run directly by Herdr; they are not bundled. Every command in `../herdr-plugin.toml` goes through `launch.mjs`, which picks the right Node (from `settings.json` written by `peerband herdr install`: `nodePath`, optional `configHome`), checks Node >= 22.13, applies `configHome` (`PEERBAND_CONFIG_HOME`, unless already set), and imports one allowlisted entry (`pane`, `open-pane`, `lifecycle`).
4
-
5
- - `pane*.mjs` - the persistent "PeerBand Relay" TUI tab. `pane-state.mjs` validates connector events; `pane-ui.mjs` renders.
6
- - `lifecycle.mjs` - supervisor that owns the connector child (`node dist/peerband.mjs connect --managed`, plus `--runtime mock` if `PEERBAND_RUNTIME=mock`, `--config` if `PEERBAND_CONNECTOR_CONFIG` is set). Closing the owning pane stops the child. Never kills a stored PID.
7
- - `control.mjs`, `paths.mjs` - control channel and config paths (`paths.mjs` mirrors `configHome()` in `src/core/config.ts`).
8
- - `relay-tab.mjs` - marker-validated tab open/reuse/rename/close. `openRelayTab()` is also imported by the bundled CLI (`peerband relay`), so it must not depend on files next to it.
9
-
10
- ## Connector child contract
11
-
12
- Spawned with an IPC channel. It sends `{ type: "peerband:pane-event", kind: "connection", state }` and `{ type: "peerband:pane-event", kind: "activity", requestId, tool, target?, outcome, latencyMs }`, and exits on `{ type: "peerband:shutdown" }`.
13
-
14
- ## Environment
15
-
16
- - `PEERBAND_CONFIG_HOME`, `HERDR_BIN_PATH` (Herdr always sets it for plugin processes; `settings.json` no longer records it, and a leftover `herdrBinary` key is ignored), `HERDR_PLUGIN_CONFIG_DIR` (Herdr-provided), `HERDR_PANE_ID`.
17
- - `PEERBAND_RUNTIME=mock`, `PEERBAND_CONNECTOR_CONFIG=<path>` - forwarded to the connector child.
18
- - Test-only: `PEERBAND_CONNECTOR_ENTRY` replaces `dist/peerband.mjs` as the connector child (tests use `test/fixtures/fake-connector.mjs`); `PEERBAND_NODE_MIN` overrides the Node version floor in `launch.mjs`; `PEERBAND_LAUNCH_DEBUG=1` makes `launch.mjs` print the Node it runs under.
1
+ # Herdr plugin sources (contributors)
2
+
3
+ Plain `.mjs` files run directly by Herdr; they are not bundled. Every command in `../herdr-plugin.toml` goes through `launch.mjs`, which picks the right Node (from `settings.json` written by `peerband herdr install`: `nodePath`, optional `configHome`), checks Node >= 22.13, applies `configHome` (`PEERBAND_CONFIG_HOME`, unless already set), and imports one allowlisted entry (`pane`, `open-pane`, `lifecycle`).
4
+
5
+ - `pane*.mjs` - the persistent "PeerBand Relay" TUI tab. `pane-state.mjs` validates connector events; `pane-ui.mjs` renders.
6
+ - `lifecycle.mjs` - supervisor that owns the connector child (`node dist/peerband.mjs connect --managed`, plus `--runtime mock` if `PEERBAND_RUNTIME=mock`, `--config` if `PEERBAND_CONNECTOR_CONFIG` is set). Closing the owning pane stops the child. Never kills a stored PID.
7
+ - `control.mjs`, `paths.mjs` - control channel and config paths (`paths.mjs` mirrors `configHome()` in `src/core/config.ts`).
8
+ - `relay-tab.mjs` - marker-validated tab open/reuse/rename/close. `openRelayTab()` is also imported by the bundled CLI (`peerband relay`), so it must not depend on files next to it.
9
+
10
+ ## Connector child contract
11
+
12
+ Spawned with an IPC channel. It sends `{ type: "peerband:pane-event", kind: "connection", state }` and `{ type: "peerband:pane-event", kind: "activity", requestId, tool, target?, outcome, latencyMs }`, and exits on `{ type: "peerband:shutdown" }`.
13
+
14
+ ## Environment
15
+
16
+ - `PEERBAND_CONFIG_HOME`, `HERDR_BIN_PATH` (Herdr always sets it for plugin processes; `settings.json` no longer records it, and a leftover `herdrBinary` key is ignored), `HERDR_PLUGIN_CONFIG_DIR` (Herdr-provided), `HERDR_PANE_ID`.
17
+ - `PEERBAND_RUNTIME=mock`, `PEERBAND_CONNECTOR_CONFIG=<path>` - forwarded to the connector child.
18
+ - Test-only: `PEERBAND_CONNECTOR_ENTRY` replaces `dist/peerband.mjs` as the connector child (tests use `test/fixtures/fake-connector.mjs`); `PEERBAND_NODE_MIN` overrides the Node version floor in `launch.mjs`; `PEERBAND_LAUNCH_DEBUG=1` makes `launch.mjs` print the Node it runs under.
package/herdr/launch.mjs CHANGED
@@ -1,87 +1,87 @@
1
- // PeerBand Herdr launcher. Every manifest command runs through this file:
2
- // node herdr/launch.mjs <entry> [args...]
3
- // Written in conservative syntax (no top-level await, no optional chaining) so that it still parses on old
4
- // Node versions and can print a friendly "Node too old" message instead of a SyntaxError.
5
- import { spawnSync } from "child_process";
6
- import { existsSync, readFileSync } from "fs";
7
- import { dirname, join } from "path";
8
- import { pathToFileURL } from "url";
9
-
10
- var ENTRIES = ["pane", "open-pane", "lifecycle"];
11
- // PEERBAND_NODE_MIN is for tests only.
12
- var MIN_NODE = (process.env.PEERBAND_NODE_MIN || "22.13.0").split(".").map(Number);
13
-
14
- function fail(message) {
15
- process.stderr.write(message + "\n");
16
- process.exit(1);
17
- }
18
-
19
- function nodeIsRecentEnough() {
20
- var have = process.versions.node.split(".").map(Number);
21
- for (var i = 0; i < 3; i++) {
22
- if (have[i] > MIN_NODE[i]) return true;
23
- if (have[i] < MIN_NODE[i]) return false;
24
- }
25
- return true;
26
- }
27
-
28
- function readSettings() {
29
- var dir = process.env.HERDR_PLUGIN_CONFIG_DIR;
30
- if (!dir) return {};
31
- try {
32
- var value = JSON.parse(readFileSync(join(dir, "settings.json"), "utf8"));
33
- return value && typeof value === "object" ? value : {};
34
- } catch {
35
- return {};
36
- }
37
- }
38
-
39
- function main() {
40
- var entry = process.argv[2];
41
- if (ENTRIES.indexOf(entry) < 0) {
42
- fail("peerband: unknown plugin entry " + JSON.stringify(entry || "") + ". Expected one of: " + ENTRIES.join(", ") + ".");
43
- }
44
- var settings = readSettings();
45
- var args = process.argv.slice(2);
46
-
47
- if (
48
- typeof settings.nodePath === "string" && settings.nodePath &&
49
- settings.nodePath !== process.execPath &&
50
- !process.env.PEERBAND_LAUNCHED &&
51
- existsSync(settings.nodePath)
52
- ) {
53
- var env = {};
54
- for (var key in process.env) env[key] = process.env[key];
55
- env.PEERBAND_LAUNCHED = "1";
56
- // The pane entry is an interactive TUI: on Windows, hiding the console would detach it.
57
- var result = spawnSync(settings.nodePath, [process.argv[1]].concat(args), {
58
- stdio: "inherit",
59
- env: env,
60
- windowsHide: entry !== "pane",
61
- });
62
- if (result.error) fail("peerband: could not start Node.js at " + settings.nodePath + " (" + result.error.message + "). Run `peerband herdr install` to refresh the plugin settings.");
63
- process.exit(result.status === null ? 1 : result.status);
64
- }
65
-
66
- if (!nodeIsRecentEnough()) {
67
- fail(
68
- "PeerBand needs Node.js " + MIN_NODE.join(".") + " or newer (Herdr found " + process.versions.node + " at " + process.execPath + "). " +
69
- "Run `peerband herdr install` from a shell with Node.js " + MIN_NODE.join(".") + "+ so the plugin remembers it."
70
- );
71
- }
72
-
73
- if (typeof settings.configHome === "string" && settings.configHome && !process.env.PEERBAND_CONFIG_HOME) {
74
- process.env.PEERBAND_CONFIG_HOME = settings.configHome;
75
- }
76
- if (process.env.PEERBAND_LAUNCH_DEBUG) process.stderr.write("peerband-launch: node=" + process.execPath + " entry=" + entry + "\n");
77
-
78
- // Entry modules read their own arguments from argv[2..] (lifecycle's argv[2] is its command), so
79
- // present them with the argv they would have had if run directly.
80
- var entryPath = join(dirname(process.argv[1]), entry + ".mjs");
81
- process.argv.splice(1, 2, entryPath);
82
- import(pathToFileURL(entryPath).href).catch(function (error) {
83
- fail("peerband: could not start " + entry + ": " + (error && error.message ? error.message : error));
84
- });
85
- }
86
-
87
- main();
1
+ // PeerBand Herdr launcher. Every manifest command runs through this file:
2
+ // node herdr/launch.mjs <entry> [args...]
3
+ // Written in conservative syntax (no top-level await, no optional chaining) so that it still parses on old
4
+ // Node versions and can print a friendly "Node too old" message instead of a SyntaxError.
5
+ import { spawnSync } from "child_process";
6
+ import { existsSync, readFileSync } from "fs";
7
+ import { dirname, join } from "path";
8
+ import { pathToFileURL } from "url";
9
+
10
+ var ENTRIES = ["pane", "open-pane", "lifecycle"];
11
+ // PEERBAND_NODE_MIN is for tests only.
12
+ var MIN_NODE = (process.env.PEERBAND_NODE_MIN || "22.13.0").split(".").map(Number);
13
+
14
+ function fail(message) {
15
+ process.stderr.write(message + "\n");
16
+ process.exit(1);
17
+ }
18
+
19
+ function nodeIsRecentEnough() {
20
+ var have = process.versions.node.split(".").map(Number);
21
+ for (var i = 0; i < 3; i++) {
22
+ if (have[i] > MIN_NODE[i]) return true;
23
+ if (have[i] < MIN_NODE[i]) return false;
24
+ }
25
+ return true;
26
+ }
27
+
28
+ function readSettings() {
29
+ var dir = process.env.HERDR_PLUGIN_CONFIG_DIR;
30
+ if (!dir) return {};
31
+ try {
32
+ var value = JSON.parse(readFileSync(join(dir, "settings.json"), "utf8"));
33
+ return value && typeof value === "object" ? value : {};
34
+ } catch {
35
+ return {};
36
+ }
37
+ }
38
+
39
+ function main() {
40
+ var entry = process.argv[2];
41
+ if (ENTRIES.indexOf(entry) < 0) {
42
+ fail("peerband: unknown plugin entry " + JSON.stringify(entry || "") + ". Expected one of: " + ENTRIES.join(", ") + ".");
43
+ }
44
+ var settings = readSettings();
45
+ var args = process.argv.slice(2);
46
+
47
+ if (
48
+ typeof settings.nodePath === "string" && settings.nodePath &&
49
+ settings.nodePath !== process.execPath &&
50
+ !process.env.PEERBAND_LAUNCHED &&
51
+ existsSync(settings.nodePath)
52
+ ) {
53
+ var env = {};
54
+ for (var key in process.env) env[key] = process.env[key];
55
+ env.PEERBAND_LAUNCHED = "1";
56
+ // The pane entry is an interactive TUI: on Windows, hiding the console would detach it.
57
+ var result = spawnSync(settings.nodePath, [process.argv[1]].concat(args), {
58
+ stdio: "inherit",
59
+ env: env,
60
+ windowsHide: entry !== "pane",
61
+ });
62
+ if (result.error) fail("peerband: could not start Node.js at " + settings.nodePath + " (" + result.error.message + "). Run `peerband herdr install` to refresh the plugin settings.");
63
+ process.exit(result.status === null ? 1 : result.status);
64
+ }
65
+
66
+ if (!nodeIsRecentEnough()) {
67
+ fail(
68
+ "PeerBand needs Node.js " + MIN_NODE.join(".") + " or newer (Herdr found " + process.versions.node + " at " + process.execPath + "). " +
69
+ "Run `peerband herdr install` from a shell with Node.js " + MIN_NODE.join(".") + "+ so the plugin remembers it."
70
+ );
71
+ }
72
+
73
+ if (typeof settings.configHome === "string" && settings.configHome && !process.env.PEERBAND_CONFIG_HOME) {
74
+ process.env.PEERBAND_CONFIG_HOME = settings.configHome;
75
+ }
76
+ if (process.env.PEERBAND_LAUNCH_DEBUG) process.stderr.write("peerband-launch: node=" + process.execPath + " entry=" + entry + "\n");
77
+
78
+ // Entry modules read their own arguments from argv[2..] (lifecycle's argv[2] is its command), so
79
+ // present them with the argv they would have had if run directly.
80
+ var entryPath = join(dirname(process.argv[1]), entry + ".mjs");
81
+ process.argv.splice(1, 2, entryPath);
82
+ import(pathToFileURL(entryPath).href).catch(function (error) {
83
+ fail("peerband: could not start " + entry + ": " + (error && error.message ? error.message : error));
84
+ });
85
+ }
86
+
87
+ main();
@@ -8,6 +8,7 @@ import { fileURLToPath } from "node:url";
8
8
  import { normalizePaneEvent, createPaneSnapshot, fallbackPaneSnapshot } from "./pane-state.mjs";
9
9
  import { config, lock, recordPath, channel, connectControl, matches } from "./control.mjs";
10
10
  import { relayStatePath } from "./paths.mjs";
11
+ import { ownerIdentity, reclaimIfStale, resetRelayState, SUPERVISOR_PATTERN } from "./stale-lock.mjs";
11
12
 
12
13
  const script = fileURLToPath(import.meta.url);
13
14
  const pluginRoot = resolve(dirname(script), "..");
@@ -78,6 +79,8 @@ async function supervise() {
78
79
  let owner = null;
79
80
  let connectionState = "disabled";
80
81
  let activity = [];
82
+ // `peerband notify` requests waiting for the connector child's answer, by id.
83
+ const pendingNotes = new Map();
81
84
  try {
82
85
  const previous = JSON.parse(await readFile(paneStatePath, "utf8"));
83
86
  activity = createPaneSnapshot(previous).activity;
@@ -116,7 +119,8 @@ async function supervise() {
116
119
  uiOwned = true;
117
120
  if (!child) startChild();
118
121
  reply(currentSnapshot());
119
- } else if (input.command === "status") reply(currentSnapshot(), true);
122
+ } else if (input.command === "notify") forwardNote(input, reply);
123
+ else if (input.command === "status") reply(currentSnapshot(), true);
120
124
  else if (input.command === "stop") {
121
125
  reply({ state: "stopping" }, true);
122
126
  stopSupervisor();
@@ -135,7 +139,8 @@ async function supervise() {
135
139
  };
136
140
  socket.on("data", (chunk) => {
137
141
  buffer += chunk.toString();
138
- if (buffer.length > 4096) { socket.destroy(); return; }
142
+ // Room for a `notify` line (a note of up to 1024 characters, JSON-escaped); other commands are tiny.
143
+ if (buffer.length > 16384) { socket.destroy(); return; }
139
144
  let newline;
140
145
  while ((newline = buffer.indexOf("\n")) >= 0) {
141
146
  const line = buffer.slice(0, newline);
@@ -145,6 +150,49 @@ async function supervise() {
145
150
  }
146
151
  });
147
152
  });
153
+ // Hands a note to the connector child, which sends it to PeerBand as an `agent.notified` event.
154
+ function forwardNote(input, reply) {
155
+ const text = input.text;
156
+ const paneId = input.paneId;
157
+ if (typeof text !== "string" || text.length > 4096 || (paneId !== undefined && (typeof paneId !== "string" || paneId.length > 128))) {
158
+ reply({ error: "invalid", message: "The note must be text of at most 1024 characters." }, true);
159
+ return;
160
+ }
161
+ const current = child;
162
+ if (!current || stopping || finalStop || !current.connected) {
163
+ reply({ error: "not-running", message: "The relay is turned off." }, true);
164
+ return;
165
+ }
166
+ const id = randomBytes(12).toString("hex");
167
+ const timer = setTimeout(() => {
168
+ if (!pendingNotes.delete(id)) return;
169
+ reply({ error: "timeout", message: "The connector did not answer in time." }, true);
170
+ }, 5000);
171
+ timer.unref();
172
+ pendingNotes.set(id, { reply, timer });
173
+ current.send({ type: "peerband:notify", id, text, ...(paneId ? { paneId } : {}) }, (error) => {
174
+ if (!error || !pendingNotes.delete(id)) return;
175
+ clearTimeout(timer);
176
+ reply({ error: "not-running", message: "The connector is not reachable." }, true);
177
+ });
178
+ }
179
+ function settleNote(message) {
180
+ const pending = pendingNotes.get(message.id);
181
+ if (!pending) return;
182
+ pendingNotes.delete(message.id);
183
+ clearTimeout(pending.timer);
184
+ const text = (value, max) => (typeof value === "string" ? value.slice(0, max) : undefined);
185
+ pending.reply(message.ok === true
186
+ ? { ok: true, sent: message.sent === true, agentId: text(message.agentId, 256) ?? null, ...(text(message.eventId, 64) ? { eventId: text(message.eventId, 64) } : {}) }
187
+ : { error: text(message.code, 64) ?? "error", message: text(message.message, 512) ?? "The note could not be sent.", ...(text(message.nextStep, 512) ? { nextStep: text(message.nextStep, 512) } : {}) }, true);
188
+ }
189
+ const failNotes = () => {
190
+ for (const [id, pending] of pendingNotes) {
191
+ pendingNotes.delete(id);
192
+ clearTimeout(pending.timer);
193
+ pending.reply({ error: "not-running", message: "The connector stopped before sending the note." }, true);
194
+ }
195
+ };
148
196
  const cleanup = async () => {
149
197
  if (owner) { const previous = owner; owner = null; previous.destroy(); }
150
198
  server.close();
@@ -186,6 +234,7 @@ async function supervise() {
186
234
  save();
187
235
  current.on("message", (message) => {
188
236
  if (child !== current) return;
237
+ if (message && typeof message === "object" && message.type === "peerband:notify-result" && typeof message.id === "string") { settleNote(message); return; }
189
238
  const event = normalizePaneEvent(message);
190
239
  if (!event) return;
191
240
  if (event.kind === "connection") connectionState = stopping && event.state !== "revoked" ? "disabled" : event.state;
@@ -201,6 +250,7 @@ async function supervise() {
201
250
  current.once("exit", () => {
202
251
  if (child !== current) return;
203
252
  child = null;
253
+ failNotes();
204
254
  if (stopping) connectionState = "disabled";
205
255
  else if (connectionState !== "revoked") connectionState = "unavailable";
206
256
  save();
@@ -218,7 +268,7 @@ async function supervise() {
218
268
  server.once("error", reject);
219
269
  server.listen(channel, resolve);
220
270
  });
221
- await writeFile(recordPath, JSON.stringify({ token }), {
271
+ await writeFile(recordPath, JSON.stringify({ token, ...ownerIdentity() }), {
222
272
  mode: 0o600,
223
273
  flag: "wx",
224
274
  });
@@ -234,6 +284,61 @@ async function assertConnectorEntry() {
234
284
  catch { throw new Error(`PeerBand connector not found at ${connectorEntry}. Reinstall the plugin with \`peerband herdr install\` (a source checkout needs \`npm run build\` first).`); }
235
285
  }
236
286
 
287
+ function lockError(verdict) {
288
+ return new Error(
289
+ `Another PeerBand helper still holds the relay lock (${verdict.reason}). ` +
290
+ "Stop it with `peerband herdr install` (restarts the relay cleanly) or end that process, then try again.",
291
+ );
292
+ }
293
+
294
+ // Removes the helper lock when its owner is provably gone (dead pid, or a legacy lock nobody answers for).
295
+ async function reclaimStaleHelperLock() {
296
+ const result = await reclaimIfStale({
297
+ lockDir: lock,
298
+ ownerFile: recordPath,
299
+ channel,
300
+ processPattern: SUPERVISOR_PATTERN,
301
+ log: (message) => console.error(`peerband: ${message}`),
302
+ });
303
+ if (result.reclaimed) await resetRelayState(paneStatePath).catch(() => {});
304
+ return result;
305
+ }
306
+
307
+ // Takes the helper lock for `start`. Returns false when a running helper already answered (its status is printed).
308
+ async function acquireForStart() {
309
+ for (let round = 0; round < 3; round++) {
310
+ try {
311
+ await mkdir(lock, { mode: 0o700 });
312
+ return true;
313
+ } catch (error) {
314
+ if (error.code !== "EEXIST") throw error;
315
+ }
316
+ let existing = null;
317
+ try { existing = await request("status"); } catch { /* not answering */ }
318
+ if (existing && existing.state === "running") {
319
+ console.log(JSON.stringify(existing));
320
+ return false;
321
+ }
322
+ if (existing && existing.state === "stopping") {
323
+ for (let attempt = 0; attempt < 50; attempt++) {
324
+ await new Promise((resolve) => setTimeout(resolve, 100));
325
+ try {
326
+ const current = await request("status");
327
+ if (current.state === "running") {
328
+ console.log(JSON.stringify(current));
329
+ return false;
330
+ }
331
+ } catch { break; }
332
+ }
333
+ continue;
334
+ }
335
+ if (existing) throw new Error("Existing helper is still changing state.");
336
+ const { reclaimed, verdict } = await reclaimStaleHelperLock();
337
+ if (!reclaimed && verdict.state !== "absent") throw lockError(verdict);
338
+ }
339
+ throw new Error("Existing helper could not be safely restarted.");
340
+ }
341
+
237
342
  async function main() {
238
343
  const command = process.argv[2];
239
344
  if (command === "supervise") {
@@ -248,12 +353,8 @@ async function main() {
248
353
  console.log(JSON.stringify(existing));
249
354
  return;
250
355
  } catch {
251
- try {
252
- await access(lock);
253
- throw new Error("Existing helper lock could not be verified. Inspect the helper before manually clearing a stale lock.");
254
- } catch (error) {
255
- if (error.code !== "ENOENT") throw error;
256
- }
356
+ const { reclaimed, verdict } = await reclaimStaleHelperLock();
357
+ if (!reclaimed && verdict.state !== "absent") throw lockError(verdict);
257
358
  }
258
359
  await mkdir(lock, { mode: 0o700 });
259
360
  const supervisor = spawn(process.execPath, [script, "supervise", "--await-ui"], {
@@ -269,34 +370,7 @@ async function main() {
269
370
  if (command === "start" || command === "enable") {
270
371
  await assertConnectorEntry();
271
372
  await mkdir(config, { recursive: true, mode: 0o700 });
272
- try {
273
- await mkdir(lock, { mode: 0o700 });
274
- } catch (error) {
275
- if (error.code !== "EEXIST") throw error;
276
- try {
277
- const existing = await request("status");
278
- if (existing.state === "running") {
279
- console.log(JSON.stringify(existing));
280
- return;
281
- }
282
- if (existing.state === "stopping") {
283
- for (let attempt = 0; attempt < 50; attempt++) {
284
- await new Promise((resolve) => setTimeout(resolve, 100));
285
- try {
286
- const current = await request("status");
287
- if (current.state === "running") {
288
- console.log(JSON.stringify(current));
289
- return;
290
- }
291
- } catch { break; }
292
- }
293
- await mkdir(lock, { mode: 0o700 });
294
- } else throw new Error("Existing helper is still changing state.");
295
- } catch {
296
- try { await access(lock); } catch { throw new Error("Existing helper could not be safely restarted."); }
297
- throw new Error("Existing helper lock could not be verified. Inspect the helper before manually clearing a stale lock.");
298
- }
299
- }
373
+ if (!(await acquireForStart())) return;
300
374
  const supervisor = spawn(process.execPath, [script, "supervise"], {
301
375
  cwd: config,
302
376
  detached: true,
package/herdr/pane.mjs CHANGED
@@ -33,12 +33,18 @@ let busyError = false;
33
33
  let snapshot = { state: "stopping", connectionState: "disabled", activity: [] };
34
34
  let errorText = "";
35
35
  let timer;
36
+ let reconnectTimer;
36
37
  let control;
37
38
  let controlBuffer = "";
38
39
  const replies = [];
39
40
  let ownsUi = false;
40
- let controlClosed;
41
- const closed = new Promise((resolve) => { controlClosed = resolve; });
41
+ // Resolves when the current control socket has closed (replaced for every new socket).
42
+ let closed = Promise.resolve();
43
+ // While the helper is gone, the pane keeps trying to re-attach (without starting a helper itself), so a relay started
44
+ // another way (the plugin's Start action, `peerband relay`) is picked up and the tab label follows the real state.
45
+ const RECONNECT_MS = 2000;
46
+ const UNAVAILABLE = "Relay helper is not running. Press Space to start it, or run `peerband relay`.";
47
+
42
48
  function draw() {
43
49
  if (closing || !stdout.isTTY) return;
44
50
  stdout.write("\x1b[2J\x1b[H" + renderPane({ snapshot, identity, email, messages, error: errorText, columns: stdout.columns, rows: stdout.rows }));
@@ -47,8 +53,15 @@ async function runLifecycle(command) {
47
53
  const { stdout: result } = await exec(process.execPath, [lifecycle, command], { timeout: 5000, windowsHide: true, maxBuffer: 65_536 });
48
54
  return JSON.parse(result.trim());
49
55
  }
56
+ const controlAlive = () => Boolean(control && !control.destroyed);
57
+ function showUnavailable(message = UNAVAILABLE) {
58
+ snapshot = { state: "stopping", connectionState: "helper-unavailable", activity: snapshot?.activity ?? [] };
59
+ errorText = message;
60
+ void syncRelayTab(false).catch(() => {});
61
+ }
50
62
  async function refresh() {
51
63
  if (closing || pending || refreshInFlight) return;
64
+ if (!controlAlive()) { scheduleReconnect(); return; }
52
65
  refreshInFlight = true;
53
66
  const generation = refreshGeneration;
54
67
  try {
@@ -56,8 +69,7 @@ async function refresh() {
56
69
  if (generation === refreshGeneration) { snapshot = next; if (!busyError) errorText = ""; void syncRelayTab(next.state === "running").catch(() => {}); }
57
70
  } catch {
58
71
  if (generation !== refreshGeneration) return;
59
- snapshot = { state: "stopping", connectionState: "helper-unavailable", activity: [] };
60
- errorText = "Helper control channel unavailable. Reopen peerband relay to reconnect.";
72
+ showUnavailable();
61
73
  } finally { refreshInFlight = false; }
62
74
  draw();
63
75
  }
@@ -70,6 +82,11 @@ async function toggle() {
70
82
  closeArmed = false;
71
83
  draw();
72
84
  try {
85
+ if (!controlAlive()) {
86
+ // No helper: Space starts one, like opening the tab does.
87
+ await attach({ start: true });
88
+ return;
89
+ }
73
90
  const next = await sendUi(snapshot?.state === "running" ? "ui-disable" : "ui-enable");
74
91
  if (next.error === "busy") throw new Error("The relay is still stopping. Try On again in a moment.");
75
92
  snapshot = next;
@@ -86,6 +103,7 @@ async function close() {
86
103
  if (closing) return;
87
104
  closing = true;
88
105
  clearInterval(timer);
106
+ clearTimeout(reconnectTimer);
89
107
  stopInput();
90
108
  process.stdin.off("end", onInputEnd);
91
109
  process.stdin.off("close", onInputEnd);
@@ -93,7 +111,7 @@ async function close() {
93
111
  process.off("SIGTERM", onSignal);
94
112
  process.off("SIGHUP", onSignal);
95
113
  stdout.write("\x1b[2J\x1b[HDisconnecting PeerBand relay…\n");
96
- if (ownsUi) {
114
+ if (ownsUi && controlAlive()) {
97
115
  try { await sendUi("ui-close"); } catch { /* socket closure also owns final cleanup */ }
98
116
  control?.end();
99
117
  } else control?.destroy();
@@ -113,6 +131,83 @@ const stopInput = startPaneInput({ boxRows: controlBoxRows(email), onToggle: tog
113
131
  errorText = "Closing disconnects the relay. Press q again to close; reopen with `peerband relay`.";
114
132
  draw();
115
133
  } });
134
+
135
+ function wireControl(socket) {
136
+ let resolveClosed;
137
+ closed = new Promise((resolve) => { resolveClosed = resolve; });
138
+ controlBuffer = "";
139
+ socket.on("data", (chunk) => {
140
+ if (control !== socket) return;
141
+ controlBuffer += chunk.toString();
142
+ if (controlBuffer.length > 65_536) { failControl(new Error("Invalid relay control response")); return; }
143
+ let newline;
144
+ while ((newline = controlBuffer.indexOf("\n")) >= 0) {
145
+ const line = controlBuffer.slice(0, newline);
146
+ controlBuffer = controlBuffer.slice(newline + 1);
147
+ let value;
148
+ try { value = JSON.parse(line); } catch { failControl(new Error("Invalid relay control response")); return; }
149
+ const request = replies.shift();
150
+ if (request) { clearTimeout(request.timer); request.resolve(value); }
151
+ }
152
+ });
153
+ let lost = false;
154
+ const onLost = (message) => {
155
+ if (lost) return;
156
+ lost = true;
157
+ resolveClosed();
158
+ if (control !== socket) return;
159
+ rejectReplies(new Error(message));
160
+ if (closing) return;
161
+ ownsUi = false;
162
+ showUnavailable(errorText || UNAVAILABLE);
163
+ draw();
164
+ scheduleReconnect();
165
+ };
166
+ socket.on("close", () => onLost("Relay owner channel closed"));
167
+ socket.on("error", () => onLost("Relay owner channel failed"));
168
+ }
169
+
170
+ // Connects to the helper and takes UI ownership. `start`: start a helper if none answers and turn the relay on.
171
+ async function attach({ start }) {
172
+ let socket;
173
+ try { socket = await connectControl(); }
174
+ catch (error) {
175
+ if (!start) throw error;
176
+ await runLifecycle("start-ui");
177
+ socket = await connectControl();
178
+ }
179
+ if (closing) { socket.destroy(); return; }
180
+ control = socket;
181
+ wireControl(socket);
182
+ const attached = await sendUi("attach-ui");
183
+ if (attached.error === "ui-owned") throw new Error("Another relay pane already owns this installation. Close it before reopening.");
184
+ ownsUi = true;
185
+ snapshot = start ? await sendUi("ui-enable") : attached;
186
+ errorText = "";
187
+ void syncRelayTab(snapshot.state === "running").catch(() => {});
188
+ draw();
189
+ if (!timer) {
190
+ timer = setInterval(refresh, 1000);
191
+ timer.unref();
192
+ }
193
+ }
194
+
195
+ // `start` (used once, after the first attempt failed, e.g. a slow first start right after an update) may start a
196
+ // helper; later retries only re-attach to one that something else started.
197
+ function scheduleReconnect(start = false) {
198
+ if (closing || reconnectTimer || controlAlive()) return;
199
+ reconnectTimer = setTimeout(async () => {
200
+ reconnectTimer = undefined;
201
+ if (closing || controlAlive() || pending) { if (!controlAlive()) scheduleReconnect(); return; }
202
+ try { await attach({ start }); }
203
+ catch (error) {
204
+ if (control && !control.destroyed) control.destroy();
205
+ if (/already owns/.test(error.message || "")) { errorText = error.message; draw(); }
206
+ scheduleReconnect();
207
+ }
208
+ }, RECONNECT_MS);
209
+ }
210
+
116
211
  if (stdinIsInteractive()) {
117
212
  process.stdin.once("end", onInputEnd);
118
213
  process.stdin.once("close", onInputEnd);
@@ -124,46 +219,14 @@ if (!stdinIsInteractive()) {
124
219
  console.log(renderPane({ snapshot, identity, email, messages, error: "Interactive terminal controls are required in this pane." }));
125
220
  } else {
126
221
  try {
127
- try { control = await connectControl(); }
128
- catch {
129
- await runLifecycle("start-ui");
130
- control = await connectControl();
131
- }
132
- if (closing) { control.destroy(); }
133
- else {
134
- control.on("data", (chunk) => {
135
- controlBuffer += chunk.toString();
136
- if (controlBuffer.length > 65_536) { failControl(new Error("Invalid relay control response")); return; }
137
- let newline;
138
- while ((newline = controlBuffer.indexOf("\n")) >= 0) {
139
- const line = controlBuffer.slice(0, newline);
140
- controlBuffer = controlBuffer.slice(newline + 1);
141
- let value;
142
- try { value = JSON.parse(line); } catch { failControl(new Error("Invalid relay control response")); return; }
143
- const request = replies.shift();
144
- if (request) { clearTimeout(request.timer); request.resolve(value); }
145
- }
146
- });
147
- control.on("close", () => { controlClosed(); rejectReplies(new Error("Relay owner channel closed")); });
148
- control.on("error", () => { controlClosed(); rejectReplies(new Error("Relay owner channel failed")); });
149
- const attached = await sendUi("attach-ui");
150
- if (attached.error === "ui-owned") throw new Error("Another relay pane already owns this installation. Close it before reopening.");
151
- ownsUi = true;
152
- snapshot = attached;
153
- const enabled = await sendUi("ui-enable");
154
- snapshot = enabled;
155
- void syncRelayTab(enabled.state === "running").catch(() => {});
156
- draw();
157
- await refresh();
158
- timer = setInterval(refresh, 1000);
159
- timer.unref();
160
- }
222
+ await attach({ start: true });
223
+ await refresh();
161
224
  } catch (error) {
162
225
  if (!closing) {
163
- errorText = error.message;
164
- snapshot = { state: "stopping", connectionState: "helper-unavailable", activity: [] };
226
+ if (control && !control.destroyed) control.destroy();
227
+ showUnavailable(error.message);
165
228
  draw();
166
- if (control) control.destroy();
229
+ scheduleReconnect(!/already owns/.test(error.message || ""));
167
230
  }
168
231
  }
169
232
  }