herdr-remote 0.2.12 → 0.2.14

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-plugin.toml CHANGED
@@ -1,7 +1,7 @@
1
1
  id = "herdr.remote.web"
2
2
  name = "Herdr Remote Web"
3
- version = "0.2.12"
4
- min_herdr_version = "0.9.0"
3
+ version = "0.2.14"
4
+ min_herdr_version = "0.9.1"
5
5
  description = "Browser access to Herdr workspaces via local or self-hosted relay"
6
6
  platforms = ["linux", "macos"]
7
7
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "herdr-remote",
3
- "version": "0.2.12",
3
+ "version": "0.2.14",
4
4
  "description": "Browser access to Herdr workspaces: plugin, host connector, and configuration TUI",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -0,0 +1,131 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * What the agents on this workstation are doing, small enough to put in a
5
+ * status bar.
6
+ *
7
+ * The question a phone actually has is "does anything need me?", and the
8
+ * terminal is a poor way to ask it: finding a blocked agent means navigating
9
+ * Herdr's sidebar through a viewport the width of a hand. Herdr already knows
10
+ * the answer — it classifies every pane as idle, working, blocked, done or
11
+ * unknown — so this turns a session snapshot into the two-line version.
12
+ *
13
+ * Deliberately a pure function over a snapshot. The socket, the debounce and
14
+ * the retry live in the host connector; what counts as "needs me" lives here,
15
+ * where it can be tested without either.
16
+ */
17
+
18
+ /** Herdr's own vocabulary, in the order a person cares about them. */
19
+ const AGENT_STATUSES = ['blocked', 'done', 'working', 'idle', 'unknown'];
20
+
21
+ /**
22
+ * How many agents travel with the summary.
23
+ *
24
+ * The counts are always exact; this caps only the named list, which exists so a
25
+ * future screen can say *which* agent is blocked. A workstation with more than
26
+ * this many live agents is not going to be read off a phone anyway.
27
+ */
28
+ const MAX_LISTED_AGENTS = 16;
29
+
30
+ /** Titles come from a remote program; keep them short and printable. */
31
+ const MAX_TITLE_LENGTH = 48;
32
+
33
+ function cleanText(value, limit = MAX_TITLE_LENGTH) {
34
+ if (typeof value !== 'string') return null;
35
+ // eslint-disable-next-line no-control-regex
36
+ const collapsed = value.replace(/[\u0000-\u001F\u007F-\u009F]/g, ' ').replace(/\s+/g, ' ').trim();
37
+ if (!collapsed) return null;
38
+ return collapsed.length > limit ? collapsed.slice(0, limit) : collapsed;
39
+ }
40
+
41
+ function normalizeStatus(value) {
42
+ return AGENT_STATUSES.includes(value) ? value : 'unknown';
43
+ }
44
+
45
+ function emptyCounts() {
46
+ return Object.fromEntries(AGENT_STATUSES.map((status) => [status, 0]));
47
+ }
48
+
49
+ /**
50
+ * Turn `session.snapshot` into the summary the browser receives.
51
+ *
52
+ * Sorted by how much each status wants attention, so the capped list keeps the
53
+ * agents worth naming rather than the first ones Herdr happened to report.
54
+ * `focusedPaneId` and `focusedAgent` also track the live pane selection,
55
+ * including shells and panes Herdr has not added to its agent summary.
56
+ */
57
+ function summarizeAgents(snapshot) {
58
+ const entries = Array.isArray(snapshot?.agents) ? snapshot.agents : [];
59
+ const focusedPaneId = typeof snapshot?.focused_pane_id === 'string' ? snapshot.focused_pane_id : null;
60
+ const focusedPane = focusedPaneId && Array.isArray(snapshot?.panes)
61
+ ? snapshot.panes.find((pane) => pane?.pane_id === focusedPaneId)
62
+ : null;
63
+ const focusedAgentEntry = focusedPaneId
64
+ ? entries.find((entry) => entry?.pane_id === focusedPaneId)
65
+ : null;
66
+ const focusedAgent = typeof focusedPane?.agent === 'string'
67
+ ? focusedPane.agent
68
+ : typeof focusedAgentEntry?.agent === 'string'
69
+ ? focusedAgentEntry.agent
70
+ : null;
71
+ const counts = emptyCounts();
72
+ const ranked = [];
73
+
74
+ for (const entry of entries) {
75
+ if (!entry || typeof entry.pane_id !== 'string') continue;
76
+ const status = normalizeStatus(entry.agent_status);
77
+ counts[status] += 1;
78
+ ranked.push({
79
+ paneId: entry.pane_id,
80
+ workspaceId: typeof entry.workspace_id === 'string' ? entry.workspace_id : null,
81
+ agent: cleanText(entry.display_agent || entry.agent, 24),
82
+ title: cleanText(entry.terminal_title_stripped || entry.terminal_title),
83
+ status,
84
+ focused: entry.focused === true,
85
+ });
86
+ }
87
+
88
+ ranked.sort((left, right) => AGENT_STATUSES.indexOf(left.status) - AGENT_STATUSES.indexOf(right.status));
89
+
90
+ return {
91
+ focusedPaneId,
92
+ focusedAgent,
93
+ counts,
94
+ // Total rather than a sum the browser has to compute, and the one number a
95
+ // collapsed chip can show on its own.
96
+ total: ranked.length,
97
+ agents: ranked.slice(0, MAX_LISTED_AGENTS),
98
+ };
99
+ }
100
+
101
+ /** Whether two summaries say the same thing, so an unchanged one is not sent. */
102
+ function sameSummary(left, right) {
103
+ if (!left || !right) return left === right;
104
+ if (left.focusedPaneId !== right.focusedPaneId || left.focusedAgent !== right.focusedAgent) return false;
105
+ if (left.total !== right.total) return false;
106
+ for (const status of AGENT_STATUSES) {
107
+ if ((left.counts?.[status] || 0) !== (right.counts?.[status] || 0)) return false;
108
+ }
109
+ if (left.agents.length !== right.agents.length) return false;
110
+ return left.agents.every((agent, index) => {
111
+ const other = right.agents[index];
112
+ return other
113
+ && agent.paneId === other.paneId
114
+ && agent.status === other.status
115
+ && agent.agent === other.agent
116
+ && agent.title === other.title;
117
+ });
118
+ }
119
+
120
+ /** The summary of a workstation with nothing to report, or nothing to ask. */
121
+ function emptySummary() {
122
+ return { focusedPaneId: null, focusedAgent: null, counts: emptyCounts(), total: 0, agents: [] };
123
+ }
124
+
125
+ module.exports = {
126
+ AGENT_STATUSES,
127
+ MAX_LISTED_AGENTS,
128
+ emptySummary,
129
+ sameSummary,
130
+ summarizeAgents,
131
+ };
@@ -0,0 +1,244 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * One question for Herdr's local socket API.
5
+ *
6
+ * Everything else in this package talks to Herdr by spawning a client into a
7
+ * PTY and shipping the bytes. That is the terminal. This is the side channel:
8
+ * the one place that asks Herdr *about* itself rather than drawing it, so a
9
+ * phone can answer "does anything need me?" without navigating a TUI through a
10
+ * 40-column viewport.
11
+ *
12
+ * The wire format is newline-delimited JSON over the Unix socket:
13
+ *
14
+ * request {"id":"…","method":"session.snapshot","params":{}}
15
+ * response {"id":"…","result":{…}} or {"id":"…","error":{"code","message"}}
16
+ *
17
+ * One request per connection, which is why this is a function and not a client.
18
+ * Herdr closes the socket once it has answered: against 0.9.1 a second request
19
+ * written to the same connection meets `EPIPE`. A long-lived client that
20
+ * reconnects on close therefore turns into a connect-answer-close loop about
21
+ * once a second, busy regardless of how rarely it actually asks anything. The
22
+ * `herdr` CLI connects per command for the same reason, and so does this.
23
+ *
24
+ * Subscriptions are the exception Herdr does keep open — `events.subscribe`
25
+ * holds the connection. Focus and agent-detection events let the caller refresh
26
+ * the focused pane immediately, with a slow poll retained as a fallback.
27
+ *
28
+ * Nothing here may affect a terminal session. Herdr's server is an ordinary
29
+ * process that can be restarted under a running herdr-remote, and when it is,
30
+ * the PTYs keep streaming while this quietly fails and is asked again later.
31
+ */
32
+
33
+ const net = require('node:net');
34
+
35
+ /** How long one question waits, connection included. */
36
+ const REQUEST_TIMEOUT_MS = 10_000;
37
+
38
+ /** An answer this long is not an answer. Guards a socket that never newlines. */
39
+ const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
40
+
41
+ /** A subscription that disappears should recover without keeping a dead socket busy. */
42
+ const SUBSCRIBE_RETRY_BASE_MS = 1_000;
43
+ const SUBSCRIBE_RETRY_MAX_MS = 10_000;
44
+
45
+ let requestCounter = 0;
46
+
47
+ /**
48
+ * Ask Herdr one thing.
49
+ *
50
+ * Resolves with the `result` object, rejects for a refused connection, a
51
+ * timeout, an unparseable answer, or an `error` response — in which case
52
+ * `error.code` is Herdr's own code.
53
+ */
54
+ function requestHerdr(socketPath, method, params = {}, options = {}) {
55
+ const { timeout = REQUEST_TIMEOUT_MS, connect = net.connect } = options;
56
+ requestCounter += 1;
57
+ const id = `herdr-remote:${requestCounter}`;
58
+
59
+ return new Promise((resolve, reject) => {
60
+ let socket;
61
+ let buffer = '';
62
+ let settled = false;
63
+
64
+ const finish = (error, result) => {
65
+ if (settled) return;
66
+ settled = true;
67
+ clearTimeout(timer);
68
+ if (socket) {
69
+ socket.removeAllListeners();
70
+ socket.destroy();
71
+ }
72
+ if (error) reject(error);
73
+ else resolve(result);
74
+ };
75
+
76
+ const timer = setTimeout(
77
+ () => finish(new Error(`Herdr API did not answer ${method} in time`)),
78
+ timeout,
79
+ );
80
+ if (typeof timer.unref === 'function') timer.unref();
81
+
82
+ try {
83
+ socket = connect(socketPath);
84
+ } catch (error) {
85
+ finish(error);
86
+ return;
87
+ }
88
+
89
+ socket.setEncoding('utf8');
90
+ socket.on('connect', () => {
91
+ socket.write(`${JSON.stringify({ id, method, params })}\n`);
92
+ });
93
+ socket.on('data', (chunk) => {
94
+ buffer += chunk;
95
+ if (buffer.length > MAX_RESPONSE_BYTES) {
96
+ finish(new Error('Herdr API sent an oversized response'));
97
+ return;
98
+ }
99
+ const newline = buffer.indexOf('\n');
100
+ if (newline === -1) return;
101
+ let message;
102
+ try {
103
+ message = JSON.parse(buffer.slice(0, newline));
104
+ } catch {
105
+ finish(new Error('Herdr API sent a line that is not JSON'));
106
+ return;
107
+ }
108
+ if (message.error) {
109
+ const error = new Error(message.error.message || 'Herdr API request failed');
110
+ error.code = message.error.code || 'herdr_api_error';
111
+ finish(error);
112
+ return;
113
+ }
114
+ finish(null, message.result);
115
+ });
116
+ socket.on('error', (error) => finish(error));
117
+ // Herdr hanging up before it answered is the ordinary shape of "the server
118
+ // is not running", not something that needs its own diagnosis.
119
+ socket.on('close', () => finish(new Error(`Herdr API closed before answering ${method}`)));
120
+ });
121
+ }
122
+
123
+ /**
124
+ * Subscribe to Herdr's event stream and reconnect if its local server restarts.
125
+ *
126
+ * The initial response is an acknowledgement (`result.type` is
127
+ * `subscription_started`); later lines are envelopes with `event` and `data`.
128
+ * They share a socket, but are separate NDJSON messages. A subscription never
129
+ * starts or writes to a terminal, so an unavailable socket is only a reason to
130
+ * retry this side channel.
131
+ */
132
+ function subscribeHerdr(socketPath, subscriptions, onEvent, options = {}) {
133
+ const {
134
+ connect = net.connect,
135
+ retryBaseMs = SUBSCRIBE_RETRY_BASE_MS,
136
+ retryMaxMs = SUBSCRIBE_RETRY_MAX_MS,
137
+ } = options;
138
+ let socket = null;
139
+ let reconnectTimer = null;
140
+ let handshakeTimer = null;
141
+ let retryCount = 0;
142
+ let closed = false;
143
+
144
+ const scheduleReconnect = () => {
145
+ if (closed || reconnectTimer) return;
146
+ const delay = Math.min(retryBaseMs * (2 ** retryCount), retryMaxMs);
147
+ retryCount += 1;
148
+ reconnectTimer = setTimeout(() => {
149
+ reconnectTimer = null;
150
+ open();
151
+ }, delay);
152
+ if (typeof reconnectTimer.unref === 'function') reconnectTimer.unref();
153
+ };
154
+
155
+ const open = () => {
156
+ if (closed) return;
157
+ let current;
158
+ try {
159
+ current = connect(socketPath);
160
+ } catch {
161
+ scheduleReconnect();
162
+ return;
163
+ }
164
+ socket = current;
165
+ let buffer = '';
166
+ let requestId = null;
167
+ let acknowledged = false;
168
+ const clearHandshake = () => {
169
+ if (handshakeTimer) clearTimeout(handshakeTimer);
170
+ handshakeTimer = null;
171
+ };
172
+
173
+ current.setEncoding('utf8');
174
+ current.on('connect', () => {
175
+ requestCounter += 1;
176
+ requestId = `herdr-remote:subscription:${requestCounter}`;
177
+ current.write(`${JSON.stringify({
178
+ id: requestId,
179
+ method: 'events.subscribe',
180
+ params: { subscriptions },
181
+ })}\n`);
182
+ handshakeTimer = setTimeout(() => current.destroy(), REQUEST_TIMEOUT_MS);
183
+ if (typeof handshakeTimer.unref === 'function') handshakeTimer.unref();
184
+ });
185
+ current.on('data', (chunk) => {
186
+ buffer += chunk;
187
+ if (Buffer.byteLength(buffer, 'utf8') > MAX_RESPONSE_BYTES) {
188
+ current.destroy();
189
+ return;
190
+ }
191
+ let newline;
192
+ while ((newline = buffer.indexOf('\n')) !== -1) {
193
+ const line = buffer.slice(0, newline);
194
+ buffer = buffer.slice(newline + 1);
195
+ if (!line) continue;
196
+ let message;
197
+ try {
198
+ message = JSON.parse(line);
199
+ } catch {
200
+ current.destroy();
201
+ return;
202
+ }
203
+ if (message?.id === requestId) {
204
+ clearHandshake();
205
+ if (message.error) {
206
+ current.destroy();
207
+ return;
208
+ }
209
+ acknowledged = true;
210
+ retryCount = 0;
211
+ } else if (acknowledged && typeof message?.event === 'string' && message.data && typeof message.data === 'object') {
212
+ try { onEvent(message); } catch {}
213
+ }
214
+ }
215
+ });
216
+ current.on('error', () => {});
217
+ current.on('close', () => {
218
+ clearHandshake();
219
+ if (socket === current) socket = null;
220
+ scheduleReconnect();
221
+ });
222
+ };
223
+
224
+ open();
225
+ return {
226
+ close() {
227
+ if (closed) return;
228
+ closed = true;
229
+ if (reconnectTimer) clearTimeout(reconnectTimer);
230
+ if (handshakeTimer) clearTimeout(handshakeTimer);
231
+ reconnectTimer = null;
232
+ handshakeTimer = null;
233
+ const active = socket;
234
+ socket = null;
235
+ if (active) active.destroy();
236
+ },
237
+ };
238
+ }
239
+
240
+ module.exports = {
241
+ REQUEST_TIMEOUT_MS,
242
+ requestHerdr,
243
+ subscribeHerdr,
244
+ };
@@ -18,9 +18,25 @@
18
18
  const fs = require('node:fs');
19
19
  const os = require('node:os');
20
20
  const path = require('node:path');
21
+ const { spawnSync } = require('node:child_process');
22
+ // The same MAJOR.MINOR.PATCH comparison the self-updater uses. A second copy
23
+ // would be a second place for 0.9.10 to sort below 0.9.9.
24
+ const { compareVersions } = require('./updater');
21
25
 
22
26
  const COMMAND_NAME = 'herdr';
23
27
 
28
+ /**
29
+ * The oldest Herdr this release is written against.
30
+ *
31
+ * 0.9.0 gave every client its own view, which is what one PTY per browser
32
+ * window rests on. 0.9.1 is what makes that model behave: window titles follow
33
+ * each client's own view instead of another client's selection, activating a
34
+ * machine in the background stops resizing somebody else's focused pane, and a
35
+ * large paste no longer disconnects the client — and pasting is how an image
36
+ * reaches an agent from a phone.
37
+ */
38
+ const MIN_HERDR_VERSION = '0.9.1';
39
+
24
40
  /** Where a user-level install lands, in the order we trust it. */
25
41
  const FALLBACK_DIRECTORIES = [
26
42
  '~/.local/bin',
@@ -138,6 +154,57 @@ function verifyHerdrCommand(command, options = {}) {
138
154
  return findHerdrCommand(options);
139
155
  }
140
156
 
157
+ /** `herdr 0.9.1`, `herdr 0.10.0-preview.2` — the three numbers are all we compare. */
158
+ function parseHerdrVersion(output) {
159
+ const match = /(\d+)\.(\d+)\.(\d+)/.exec(String(output || ''));
160
+ return match ? `${match[1]}.${match[2]}.${match[3]}` : null;
161
+ }
162
+
163
+ /**
164
+ * Whether an install is new enough.
165
+ *
166
+ * An unreadable version counts as new enough. Not knowing is not evidence of an
167
+ * old Herdr, and a warning nobody can act on is worse than no warning.
168
+ */
169
+ function meetsMinimum(version, minimum = MIN_HERDR_VERSION) {
170
+ if (!version) return true;
171
+ return compareVersions(version, minimum) >= 0;
172
+ }
173
+
174
+ /**
175
+ * Ask an install what it is.
176
+ *
177
+ * Deliberately the binary and not the socket: `--version` answers before the
178
+ * server is up, which is when the TUI and the plugin registration ask.
179
+ *
180
+ * `ok` is whether the command ran at all — the presence check registration has
181
+ * always used. `version` is null whenever the output could not be read, and
182
+ * `supported` is true in that case for the reason `meetsMinimum` explains.
183
+ */
184
+ function herdrVersion({ command, timeout = 10_000, ...lookup } = {}) {
185
+ const resolved = command || resolveHerdrCommand(lookup);
186
+ const unknown = { command: resolved, version: null, raw: null, supported: true, ok: false };
187
+ let result;
188
+ try {
189
+ result = spawnSync(resolved, ['--version'], { encoding: 'utf8', timeout });
190
+ } catch {
191
+ return unknown;
192
+ }
193
+ // Status 1 has always counted as present: a binary that answers at all is
194
+ // installed, whatever it thinks of the flag.
195
+ if (result.error || (result.status !== 0 && result.status !== 1)) return unknown;
196
+ const raw = `${result.stdout || ''}${result.stderr || ''}`.trim();
197
+ const version = parseHerdrVersion(raw);
198
+ return { command: resolved, version, raw: raw || null, supported: meetsMinimum(version), ok: true };
199
+ }
200
+
201
+ /** The one line that tells a user why an older Herdr is a problem here. */
202
+ function herdrOutdatedMessage(version) {
203
+ return `Herdr ${version} is older than ${MIN_HERDR_VERSION}, which herdr-remote is written against. `
204
+ + 'Run "herdr update" — window titles, background machine activation and large pastes all '
205
+ + 'misbehave in browser windows before that release.';
206
+ }
207
+
141
208
  /** The one message a user needs to fix a missing install themselves. */
142
209
  function herdrNotFoundMessage({ env = process.env, home = os.homedir(), directories = fallbackDirectories(home) } = {}) {
143
210
  const override = String(env.HERDR_BIN_PATH || '').trim();
@@ -151,9 +218,14 @@ function herdrNotFoundMessage({ env = process.env, home = os.homedir(), director
151
218
  module.exports = {
152
219
  COMMAND_NAME,
153
220
  FALLBACK_DIRECTORIES,
221
+ MIN_HERDR_VERSION,
154
222
  fallbackDirectories,
155
223
  findHerdrCommand,
156
224
  herdrNotFoundMessage,
225
+ herdrOutdatedMessage,
226
+ herdrVersion,
227
+ meetsMinimum,
228
+ parseHerdrVersion,
157
229
  resolveHerdrCommand,
158
230
  verifyHerdrCommand,
159
231
  };
@@ -10,7 +10,7 @@ const fs = require('node:fs');
10
10
  const path = require('node:path');
11
11
  const { spawnSync } = require('node:child_process');
12
12
  const { PACKAGE_ROOT } = require('./config');
13
- const { resolveHerdrCommand } = require('./herdr-command');
13
+ const { herdrVersion, resolveHerdrCommand } = require('./herdr-command');
14
14
 
15
15
  const PLUGIN_ID = 'herdr.remote.web';
16
16
  const MANIFEST_NAME = 'herdr-plugin.toml';
@@ -23,8 +23,7 @@ function manifestPath() {
23
23
  // manager, neither of which is guaranteed the PATH the user installed with, so
24
24
  // the command is resolved rather than named.
25
25
  function herdrAvailable() {
26
- const result = spawnSync(resolveHerdrCommand(), ['--version'], { stdio: 'ignore' });
27
- return result.status === 0 || result.status === 1;
26
+ return herdrVersion().ok;
28
27
  }
29
28
 
30
29
  function runHerdr(args, { timeout = 15_000 } = {}) {
@@ -68,6 +67,10 @@ function registrationStatus() {
68
67
  if (!fs.existsSync(manifestPath())) {
69
68
  return { available: false, registered: false, reason: 'manifest missing' };
70
69
  }
70
+ // Carried on every answer: the screen that shows registration is also the one
71
+ // that has to say the installed Herdr is too old for this plugin.
72
+ const { version, supported } = herdrVersion();
73
+ const installed = { version, versionSupported: supported };
71
74
  let result;
72
75
  try {
73
76
  result = runHerdr(['plugin', 'list']);
@@ -76,11 +79,11 @@ function registrationStatus() {
76
79
  throw error;
77
80
  }
78
81
  if (result.status !== 0) {
79
- return { available: true, registered: false, reason: String(result.stderr || '').trim() };
82
+ return { available: true, registered: false, reason: String(result.stderr || '').trim(), ...installed };
80
83
  }
81
84
  const plugins = parsePluginList(result.stdout);
82
85
  const entry = plugins.find((plugin) => plugin.id === PLUGIN_ID);
83
- if (!entry) return { available: true, registered: false, packageRoot: PACKAGE_ROOT };
86
+ if (!entry) return { available: true, registered: false, packageRoot: PACKAGE_ROOT, ...installed };
84
87
  return {
85
88
  available: true,
86
89
  registered: true,
@@ -90,6 +93,7 @@ function registrationStatus() {
90
93
  // switching from a source install to npm.
91
94
  stale: Boolean(entry.localPath) && path.resolve(entry.localPath) !== path.resolve(PACKAGE_ROOT),
92
95
  packageRoot: PACKAGE_ROOT,
96
+ ...installed,
93
97
  };
94
98
  }
95
99