replywizard-whatsapp-mcp 0.3.0 → 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
@@ -84,15 +84,36 @@ always an option.
84
84
  Antigravity is a VS Code fork and inherits both `--add-mcp` and the `mcp/install` URL handler,
85
85
  but **it keeps two MCP lists** and they are not the same one:
86
86
 
87
- | List | Path | Key | Written by |
87
+ | List | Path | Key | Reaches the agent? |
88
88
  |---|---|---|---|
89
- | The editor's | `~/.config/Antigravity IDE/User/mcp.json` | `servers` | `antigravity-ide --add-mcp` |
90
- | The agent's | `~/.gemini/config/mcp_config.json` | `mcpServers` | by hand, and it is the config above |
91
-
92
- The **Copy Antigravity command** button hands you the `--add-mcp` line. If the agent panel does
93
- not list Reply Wizard afterwards, put the JSON above into `~/.gemini/config/mcp_config.json`
94
- instead. There is deliberately no deeplink button: the handler ships in the build, but nothing
95
- registers the `antigravity-ide:` scheme on Linux, so the click would do nothing and say nothing.
89
+ | The editor's | `~/.config/Antigravity IDE/User/mcp.json` | `servers` | **No.** Written by `antigravity-ide --add-mcp` |
90
+ | The agent's | `~/.gemini/config/mcp_config.json` | `mcpServers` | **Yes.** Edited by hand, and it is the config above |
91
+
92
+ **Use the agent's file.** That ordering was measured rather than assumed: a traced entry was
93
+ left in the editor's list, whose command appends a line to a log file before starting the real
94
+ server, and it sat there across an IDE restart two and a half hours later without the log ever
95
+ being written. Nothing started it. In that same session the agent answered live WhatsApp
96
+ questions, configured only in the agent's file. So `--add-mcp` reports success and changes
97
+ nothing the agent reads. The **Copy Antigravity config** button gives you the JSON above; the
98
+ `--add-mcp` line is still printed on the tab, labelled for what it does, for anyone who wants
99
+ the entry in the editor's own MCP panel as well.
100
+
101
+ **The bridge names its own version on the handshake** as of 0.3.1, so the extension can tell a
102
+ current host from a stale one and say so on its WhatsApp MCP tab. An absent version is itself
103
+ the signal: a host old enough to matter is exactly one that does not send the field, which is
104
+ why `/healthz` carrying it since 0.3.0 was not enough on its own. The commonest cause of a
105
+ stale host is a **global install shadowing `npx`** -- run
106
+ `npm uninstall -g replywizard-whatsapp-mcp` and the next client start fetches the current one.
107
+
108
+ **Configured is not the same as loaded.** Antigravity caches each loaded server's tool schemas
109
+ under `~/.gemini/antigravity-ide/mcp/<name>/`. On that restart six of the seven configured
110
+ servers had their schemas rewritten within the minute, and Reply Wizard's directory kept a
111
+ two-week-old timestamp, so the agent had no Reply Wizard tools that session. If the agent panel
112
+ does not list Reply Wizard after you edit the file, switch it on there. The connector is not
113
+ the usual cause: five consecutive stdio launches all came up in about 1.7 seconds.
114
+
115
+ There is deliberately no deeplink button: the handler ships in the build, but nothing registers
116
+ the `antigravity-ide:` scheme on Linux, so the click would do nothing and say nothing.
96
117
 
97
118
  ## The command line
98
119
 
@@ -230,12 +251,33 @@ Two things do **not** change on reuse, and each is tested:
230
251
 
231
252
  A code is still destroyed immediately on a successful pairing, on lockout, and on expiry.
232
253
 
254
+ **More than one browser can stay paired, since 0.3.2.** The session file held a single token
255
+ until then, and the hub accepts one extension socket at a time, so somebody running two Chrome
256
+ profiles (or Chrome and Edge) had each pairing invalidate the other's: whichever browser took
257
+ the socket next was asked for a fresh six-digit code, and neither was doing anything wrong. Up
258
+ to **five** browsers now stay paired at once. The least recently used is dropped when a sixth
259
+ pairs, and a successful reconnect moves that browser to the front, so the ones actually in use
260
+ are the ones that survive. Each token is still 256 bits, still minted only by a completed
261
+ pairing, and still only ever compared.
262
+
263
+ **If the hub cannot SAVE the pairing, it now says so.** Before 0.3.2 a failed write was a line
264
+ on a stderr the daemon does not have (the connector spawns it detached), so an unwritable or
265
+ full home directory produced a pairing that worked until the daemon restarted and was then
266
+ demanded again, for ever, with nothing said anywhere. Writes are atomic and read back before
267
+ they count, the extension is told on the handshake (`session_persisted: false`) and puts a
268
+ sentence on the MCP tab, and `replywizard status` prints both the reason and the directory it
269
+ is using. That directory matters on its own: the daemon inherits the environment of whichever
270
+ client started it, so a sandboxed editor (flatpak, snap) gives its daemon a different `HOME`
271
+ and therefore a different session file, and the pairing it makes is invisible to every other
272
+ client. Printed, the two tell themselves apart.
273
+
233
274
  ## Security
234
275
 
235
276
  - Binds to `127.0.0.1` only.
236
277
  - No tool runs until the pairing code is confirmed in the extension.
237
278
  - **Read + value tools only**: v1 has no send/modify capability.
238
- - The session token is stored at `~/.replywizard-mcp/session.json` (mode 600).
279
+ - Session tokens are stored at `~/.replywizard-mcp/session.json` (mode 600), at most five,
280
+ newest first. Override the directory with `RW_MCP_STATE_DIR`.
239
281
 
240
282
  ## Troubleshooting
241
283
 
@@ -243,6 +285,7 @@ A code is still destroyed immediately on a successful pairing, on lockout, and o
243
285
  |---------|-----|
244
286
  | `Reply Wizard extension is not connected` | Open WhatsApp Web and enable AI access in the popup. |
245
287
  | `Not paired yet` | Enter the 6-digit code (printed to the hub's stderr) in the popup. |
288
+ | It asks for a code again and again | Run `replywizard status`. A `WARNING: this daemon cannot save its state` line means the state directory is unwritable or full. Otherwise compare the `state:` line across your AI clients: a sandboxed editor gives its daemon a different `HOME`, so it keeps its own session file. |
246
289
  | `No WhatsApp Web tab is open` | A read/value tool needs an open, logged-in WhatsApp Web tab. |
247
290
  | Transcription error about a cloud provider | `transcribe_voice_note` needs a **cloud** STT key in Options → Speech-to-Text (on-device STT is not used over MCP). |
248
291
  | Port in use | The default is `7869`. Changing it is advanced (set `RW_MCP_PORT` on the hub **and** the `rw_mcp_port` value in the extension's storage to match). |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "replywizard-whatsapp-mcp",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "description": "Local MCP server and command line that expose WhatsApp Web (read + value tools) to AI clients via the Reply Wizard Chrome extension.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/cli.js CHANGED
@@ -336,6 +336,8 @@ export async function status(deps = {}) {
336
336
  paired: !!body.paired,
337
337
  sessions: body.sessions || 0,
338
338
  tokenPresent: !!(deps.token !== undefined ? deps.token : readToken()),
339
+ stateDir: body.stateDir || null,
340
+ persistError: body.persistError || null,
339
341
  };
340
342
  } catch {
341
343
  return { running: false, reason: 'nothing is listening; start any AI client, or run a command and it will start itself' };
@@ -361,6 +363,21 @@ export function statusLines(s) {
361
363
  `paired: ${s.paired ? 'yes' : 'no (enter the 6-digit code in the extension, see `replywizard pair`)'}`,
362
364
  `sessions: ${s.sessions}`,
363
365
  `token: ${s.tokenPresent ? 'present' : 'missing (~/.replywizard-mcp/daemon-token.json)'}`,
366
+ /*
367
+ * WHICH directory, always, and not only when something is wrong.
368
+ *
369
+ * The daemon is spawned by whichever AI client started first, with that client's
370
+ * environment, so an editor that runs sandboxed (flatpak, snap) gives its daemon a
371
+ * different HOME and therefore a different session file: it knows nothing of the pairing
372
+ * every other client shares, and asks for a six-digit code that the other daemon then
373
+ * does not recognise either. Printed here, the two daemons tell themselves apart at a
374
+ * glance; before this there was nothing to compare.
375
+ */
376
+ `state: ${s.stateDir || 'unknown (this host is older than 0.3.2)'}`,
377
+ ...(s.persistError
378
+ ? [`WARNING: this daemon cannot save its state: ${s.persistError}`,
379
+ ' Pairing will work until the daemon restarts, and then be asked for again.']
380
+ : []),
364
381
  ];
365
382
  }
366
383
 
package/src/daemon.js CHANGED
@@ -20,14 +20,15 @@
20
20
 
21
21
  import http from 'node:http';
22
22
  import { randomUUID } from 'node:crypto';
23
- import { readFileSync, realpathSync } from 'node:fs';
23
+ import { realpathSync } from 'node:fs';
24
24
  import { fileURLToPath } from 'node:url';
25
25
  import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
26
26
  import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
27
- import { ExtensionBridge } from './wsServer.js';
27
+ import { ExtensionBridge, stateDir as stateDirPath } from './wsServer.js';
28
28
  import { createMcpServer } from './mcpServer.js';
29
29
  import { DEFAULT_PORT } from './protocol.js';
30
- import { loadOrCreateToken, tokenMatches, bearerFrom } from './daemonAuth.js';
30
+ import { loadOrCreateToken, tokenMatches, bearerFrom, tokenWriteError } from './daemonAuth.js';
31
+ import { hostVersion } from './hostVersion.js';
31
32
 
32
33
  // Daemon-only (not part of the extension wire contract, so it lives here rather than
33
34
  // in protocol.js). Overridable via env for users who run more than one profile.
@@ -46,16 +47,11 @@ const HOST = '127.0.0.1';
46
47
  * first question in a support thread has an answer the user can read off their own machine.
47
48
  *
48
49
  * Read once, and a failure is `null` rather than a throw: a missing package.json must not
49
- * take the health endpoint down with it.
50
+ * take the health endpoint down with it. The read itself lives in `hostVersion.js` since
51
+ * ledger row 48, because the WebSocket handshake needs the same answer and two readers would
52
+ * be two things to keep true.
50
53
  */
51
- export const HOST_VERSION = (() => {
52
- try {
53
- const here = fileURLToPath(new URL('../package.json', import.meta.url));
54
- return JSON.parse(readFileSync(here, 'utf8')).version || null;
55
- } catch {
56
- return null;
57
- }
58
- })();
54
+ export const HOST_VERSION = hostVersion();
59
55
 
60
56
  const log = (...args) => console.error('[replywizard-mcp]', ...args);
61
57
 
@@ -177,6 +173,13 @@ export function createDaemon({
177
173
  extensionConnected: connected,
178
174
  paired: !!(bridge && bridge.paired),
179
175
  sessions: sessions.size,
176
+ // WHERE state is kept, and WHETHER it could be written. Two different ways a customer
177
+ // ends up typing a pairing code again and again, and from the outside they look the
178
+ // same: a daemon started from a sandboxed editor resolves a different HOME and reads
179
+ // a different session file, and a daemon whose $HOME is unwritable cannot keep the
180
+ // pairing it just made. Neither was visible from anywhere before 0.3.2.
181
+ stateDir: stateDirPath(),
182
+ persistError: (bridge && bridge.persistError) || tokenWriteError() || null,
180
183
  });
181
184
  return;
182
185
  }
package/src/daemonAuth.js CHANGED
@@ -12,15 +12,18 @@
12
12
  // the real ~/.replywizard-mcp).
13
13
 
14
14
  import { randomBytes, timingSafeEqual } from 'node:crypto';
15
- import { homedir } from 'node:os';
16
15
  import { join } from 'node:path';
17
- import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
16
+ import { readJson, stateDir, writeJsonVerified } from './stateStore.js';
18
17
 
19
18
  const log = (...args) => console.error('[replywizard-mcp]', ...args);
20
19
 
21
- function stateDir(dir) {
22
- return dir || process.env.RW_MCP_STATE_DIR || join(homedir(), '.replywizard-mcp');
23
- }
20
+ // The last persistence failure, or null. `loadOrCreateToken` hands a working token back
21
+ // either way -- the daemon runs, and clients that read the token from THIS process work --
22
+ // but the next daemon mints a different one and every configured client is refused, which is
23
+ // why the daemon reports this on /healthz rather than leaving it in a log nobody sees.
24
+ let lastWriteError = null;
25
+ export function tokenWriteError() { return lastWriteError; }
26
+
24
27
  function tokenFile(dir) {
25
28
  return join(stateDir(dir), 'daemon-token.json');
26
29
  }
@@ -34,18 +37,17 @@ function tokenFile(dir) {
34
37
  // (`rotateToken`), which is what keeps the difference tolerable rather than a hole.
35
38
  // Surfaced by the cross-platform CI matrix, 2026-08-20.
36
39
  function writeToken(token, dir) {
37
- try {
38
- mkdirSync(stateDir(dir), { recursive: true });
39
- writeFileSync(tokenFile(dir), JSON.stringify({ token }), { mode: 0o600 });
40
- } catch (e) {
41
- log('Could not persist daemon auth token:', e && e.message);
42
- }
40
+ // Atomic (temp file then rename) and READ BACK, via stateStore.js: a write that failed used
41
+ // to be a line on a stderr the daemon does not have, and a write that half-landed read back
42
+ // as "no token at all", which is the same thing to every caller here.
43
+ lastWriteError = writeJsonVerified(tokenFile(dir), { token }, (back) => back && back.token === token);
44
+ if (lastWriteError) log('Could not persist daemon auth token:', lastWriteError);
43
45
  }
44
46
 
45
47
  /** Read the persisted token, or null if none / unreadable. */
46
48
  export function readToken(dir) {
47
- try { return JSON.parse(readFileSync(tokenFile(dir), 'utf8')).token || null; }
48
- catch { return null; }
49
+ const raw = readJson(tokenFile(dir));
50
+ return (raw && raw.token) || null;
49
51
  }
50
52
 
51
53
  /** Return the persisted token, creating + persisting a fresh one if absent. */
@@ -0,0 +1,37 @@
1
+ // hostVersion.js: this package's own version, read once, for anything that reports it.
2
+ //
3
+ // WHY IT IS ITS OWN MODULE
4
+ // Three places want it and each had a different answer: `/healthz` read it at daemon start,
5
+ // the CLI printed what `/healthz` gave it, and the WebSocket handshake said nothing at all.
6
+ // That last gap is the one that cost something. Measured on the owner's laptop 2026-09-10: a
7
+ // globally installed 0.2.7 was shadowing `npx`, so every client on that machine ran a bridge
8
+ // two versions behind a published 0.3.0, and the extension's MCP tab said "paired" with no
9
+ // hint. `/healthz` carries the version since 0.3.0, which does not help here at all, because
10
+ // the host too old to report it is exactly the host you need to detect.
11
+ //
12
+ // So the version travels on the handshake as well, where the EXTENSION sees it, and an
13
+ // ABSENT value is itself the signal: any host that does not send one predates this field.
14
+ //
15
+ // Read with a try/catch and cached: a packaging accident that moves package.json must degrade
16
+ // to `null` rather than stop the daemon from starting.
17
+
18
+ import { readFileSync } from 'node:fs';
19
+ import { fileURLToPath } from 'node:url';
20
+
21
+ let cached;
22
+
23
+ /** @returns {string|null} e.g. '0.3.1', or null if it cannot be read. */
24
+ export function hostVersion() {
25
+ if (cached !== undefined) return cached;
26
+ try {
27
+ const path = fileURLToPath(new URL('../package.json', import.meta.url));
28
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
29
+ cached = typeof parsed.version === 'string' ? parsed.version : null;
30
+ } catch {
31
+ cached = null;
32
+ }
33
+ return cached;
34
+ }
35
+
36
+ /** Test seam: forget the cached read. */
37
+ export function resetHostVersionCache() { cached = undefined; }
package/src/protocol.js CHANGED
@@ -36,8 +36,32 @@ export const STATUS = Object.freeze({
36
36
  CONNECTING: 'connecting',
37
37
  AUTH_REQUIRED: 'auth_required',
38
38
  CONNECTED: 'connected',
39
+ // Another browser holds the one extension socket. See CLOSE_BUSY.
40
+ BUSY: 'busy',
39
41
  });
40
42
 
43
+ /*
44
+ * The hub's refusal code, and the single most confusing state this subsystem has.
45
+ *
46
+ * `wsServer._onConnection` accepts ONE extension socket and closes any other with
47
+ * `1013` and the reason `busy`. That is correct and deliberate: the singleton is the
48
+ * BROWSER, because two browsers are two different WhatsApp accounts as far as an
49
+ * assistant is concerned, and silently swapping which one answers is a data problem
50
+ * rather than a cosmetic one.
51
+ *
52
+ * What was missing is that nobody read the code. `mcpBridge.js`'s `onclose` ignored it,
53
+ * so a second browser reported plain `disconnected` and retried on the fast backoff.
54
+ * Diagnosed live 2026-09-10 on a machine running two Chrome profiles: the two took
55
+ * turns holding the socket, each presented its own session token, each mismatched the
56
+ * other's, and every reconnect minted a fresh pairing code. `session.json` was rewritten
57
+ * three times in nine minutes -- and it is only written on a SUCCESSFUL pairing -- with
58
+ * `/healthz` reporting `paired: false` in between. It reads as "pairing is broken" when
59
+ * the truth is "you have two browsers and only one can have it".
60
+ *
61
+ * 1013 is `Try Again Later` in RFC 6455, which is exactly the situation.
62
+ */
63
+ export const CLOSE_BUSY = 1013;
64
+
41
65
  export const CONTROL = Object.freeze({
42
66
  HANDSHAKE: 'handshake',
43
67
  PAIRING_REQUEST: 'pairing_request',
@@ -0,0 +1,66 @@
1
+ // stateStore.js: where this package keeps state, and the only way it writes it.
2
+ //
3
+ // Two files live in `~/.replywizard-mcp` and both are load-bearing: `session.json` holds the
4
+ // tokens that keep a paired browser paired, and `daemon-token.json` holds the bearer token
5
+ // every AI client must present. Until 2026-09-17 each was written with a bare `writeFileSync`
6
+ // inside a `try` whose `catch` called `log()`, and `log()` writes to stderr, which is
7
+ // `/dev/null` for the daemon the connector spawns (`stdio: 'ignore'`). So a write that failed
8
+ // -- an unwritable or full `$HOME`, a container mount, a profile on a read-only volume --
9
+ // produced a pairing that worked until the daemon restarted and then never again, with
10
+ // nothing said anywhere. Worse, `writeFileSync` is not atomic: a crash or a full disk
11
+ // mid-write leaves a truncated file, and the reader's `catch` turns that into "no token",
12
+ // which is indistinguishable from "never paired".
13
+ //
14
+ // So every write here is write-temp-then-rename (atomic within a directory) and is READ BACK
15
+ // before it is called a success. The caller gets a reason string rather than an exception,
16
+ // because none of these callers can do anything about the failure except REPORT it, and
17
+ // reporting it is the whole point: `wsServer.js` puts it on the wire so the extension can say
18
+ // so, and the daemon puts it in `/healthz` so `replywizard status` can print it.
19
+
20
+ import { homedir } from 'node:os';
21
+ import { dirname, join } from 'node:path';
22
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
23
+
24
+ /**
25
+ * The state directory. Overridable via `RW_MCP_STATE_DIR`, which is how the test suite keeps
26
+ * off the real one, and resolved on every call so the environment can change after import.
27
+ *
28
+ * @param {string} [dir] an explicit directory, which wins over everything (daemonAuth's API)
29
+ */
30
+ export function stateDir(dir) {
31
+ return dir || process.env.RW_MCP_STATE_DIR || join(homedir(), '.replywizard-mcp');
32
+ }
33
+
34
+ /** Parse a JSON file, or null if it is missing, unreadable or not JSON. */
35
+ export function readJson(file) {
36
+ try { return JSON.parse(readFileSync(file, 'utf8')); } catch { return null; }
37
+ }
38
+
39
+ /**
40
+ * Write JSON atomically and prove it landed.
41
+ *
42
+ * @param {string} file
43
+ * @param {object} obj
44
+ * @param {(back: any) => boolean} [verify] what "it landed" means for this caller, given the
45
+ * re-read object. Defaults to a deep-enough comparison of the serialized form.
46
+ * @returns {string|null} null on success, else a reason short enough to put on a wire
47
+ */
48
+ export function writeJsonVerified(file, obj, verify) {
49
+ const body = JSON.stringify(obj);
50
+ const tmp = `${file}.tmp`;
51
+ try {
52
+ mkdirSync(dirname(file), { recursive: true });
53
+ // The temp file is a SIBLING, not in the system temp dir: rename is only atomic within one
54
+ // filesystem, and `$HOME` and `/tmp` are routinely two.
55
+ writeFileSync(tmp, body, { mode: 0o600 });
56
+ renameSync(tmp, file);
57
+ } catch (e) {
58
+ try { rmSync(tmp, { force: true }); } catch { /* the write is already the failure */ }
59
+ return (e && e.message) || 'write failed';
60
+ }
61
+
62
+ const back = readJson(file);
63
+ if (back === null) return 'written, but the file could not be read back';
64
+ const ok = verify ? verify(back) : JSON.stringify(back) === body;
65
+ return ok ? null : 'written, but the file does not hold what was just written';
66
+ }
package/src/wsServer.js CHANGED
@@ -23,26 +23,65 @@
23
23
 
24
24
  import { WebSocketServer } from 'ws';
25
25
  import { randomBytes, randomUUID } from 'node:crypto';
26
- import { homedir, platform } from 'node:os';
26
+ import { platform } from 'node:os';
27
27
  import { join } from 'node:path';
28
- import { mkdirSync, readFileSync, writeFileSync, rmSync } from 'node:fs';
28
+ import { mkdirSync, writeFileSync, rmSync } from 'node:fs';
29
29
  import { spawn } from 'node:child_process';
30
30
  import { CONTROL, DEFAULT_PORT, PROTOCOL_VERSION, VALUE_ACTIONS } from './protocol.js';
31
+ import { hostVersion } from './hostVersion.js';
32
+ import { readJson, stateDir, writeJsonVerified } from './stateStore.js';
31
33
 
32
34
  const log = (...args) => console.error('[replywizard-mcp]', ...args);
33
35
 
34
- // State dir is overridable via RW_MCP_STATE_DIR (consistent with daemonAuth.js); used
35
- // by tests for isolation. Resolved lazily (at call time) so the env can be set before
36
- // a bridge is constructed. Defaults to ~/.replywizard-mcp in production.
37
- function stateDir() { return process.env.RW_MCP_STATE_DIR || join(homedir(), '.replywizard-mcp'); }
36
+ // The state dir is `stateStore.js`'s (overridable via RW_MCP_STATE_DIR, resolved on every call
37
+ // so the environment can change after import). Exported because the daemon reports it on
38
+ // /healthz and `replywizard status` prints it: a client whose editor runs sandboxed resolves a
39
+ // different HOME, so its daemon reads a different session file and asks to pair again, and
40
+ // until this was printed that was indistinguishable from a failed write.
41
+ export { stateDir };
38
42
  function stateFile() { return join(stateDir(), 'session.json'); }
39
43
 
40
- function loadToken() {
41
- try { return JSON.parse(readFileSync(stateFile(), 'utf8')).token || null; } catch { return null; }
44
+ /**
45
+ * HOW MANY BROWSERS MAY STAY PAIRED AT ONCE.
46
+ *
47
+ * The file held ONE token until 2026-09-17, and `_onConnection` refuses a second extension
48
+ * socket, so a user with two Chrome profiles (or Chrome and Edge) had each pairing invalidate
49
+ * the other's: whichever browser took the socket next was asked for a fresh six-digit code,
50
+ * for ever, and neither was doing anything wrong. A small SET fixes that without weakening
51
+ * anything -- each token is still 256 bits, still minted only by a completed pairing, and
52
+ * still only ever compared -- and a cap keeps the file from becoming a list of every browser
53
+ * that ever touched this machine. Five is the number of profiles a person plausibly runs; the
54
+ * least recently used is dropped, so the browsers actually in use are the ones that survive.
55
+ */
56
+ const MAX_SESSION_TOKENS = 5;
57
+
58
+ /**
59
+ * Read the persisted tokens, newest first.
60
+ *
61
+ * Accepts the pre-2026-09-17 `{ "token": "..." }` shape as well, because an upgrade must not
62
+ * unpair the browser it finds already paired -- which is the exact failure this whole change
63
+ * is about.
64
+ */
65
+ function loadTokens() {
66
+ const raw = readJson(stateFile());
67
+ const list = Array.isArray(raw && raw.tokens) ? raw.tokens : (raw && typeof raw.token === 'string' ? [raw.token] : []);
68
+ return list.filter((t) => typeof t === 'string' && t).slice(0, MAX_SESSION_TOKENS);
42
69
  }
43
- function saveToken(token) {
44
- try { mkdirSync(stateDir(), { recursive: true }); writeFileSync(stateFile(), JSON.stringify({ token }), { mode: 0o600 }); }
45
- catch (e) { log('Could not persist session token:', e && e.message); }
70
+
71
+ /**
72
+ * Persist the tokens, atomically, and prove it landed. Returns null, or a reason to report.
73
+ *
74
+ * `token` is written beside `tokens` on purpose: an OLDER host reading this file still finds
75
+ * the newest token where it expects one, so downgrading the package does not unpair anybody.
76
+ */
77
+ function saveTokens(tokens) {
78
+ const reason = writeJsonVerified(
79
+ stateFile(),
80
+ { version: 2, tokens, token: tokens[0] || null },
81
+ (back) => Array.isArray(back.tokens) && back.tokens.length === tokens.length && back.tokens[0] === tokens[0],
82
+ );
83
+ if (reason) log('Could not persist the session token:', reason);
84
+ return reason;
46
85
  }
47
86
 
48
87
  // When the daemon runs detached (spawned by the connector, stderr → /dev/null), the
@@ -169,7 +208,10 @@ export class ExtensionBridge {
169
208
  this._pairingTimer = null; // TTL timer that expires the current code
170
209
  this.maxPairingAttempts = opts.maxPairingAttempts ?? MAX_PAIRING_ATTEMPTS;
171
210
  this.pairingCodeTtlMs = opts.pairingCodeTtlMs ?? PAIRING_CODE_TTL_MS;
172
- this.sessionToken = loadToken();
211
+ this.sessionTokens = loadTokens(); // newest first; `sessionToken` below is the head
212
+ // The last persistence failure, or null. Reported on the wire and on /healthz rather than
213
+ // only logged, because the log goes nowhere for a daemon the connector spawned detached.
214
+ this.persistError = null;
173
215
  this.pending = new Map(); // requestId → { entry, lane }
174
216
  this.requestTimeoutMs = opts.requestTimeoutMs ?? 25_000;
175
217
  this.listening = false;
@@ -271,6 +313,32 @@ export class ExtensionBridge {
271
313
  this._pairingTimer = null;
272
314
  }
273
315
 
316
+ /**
317
+ * The newest token, which is what a single-token caller means by "the" session token.
318
+ * Kept as an accessor so `bridge.sessionToken = x` still means what it always did, in the
319
+ * daemon, in the tests, and in any client of this class.
320
+ */
321
+ get sessionToken() { return this.sessionTokens[0] || null; }
322
+ set sessionToken(token) { this.sessionTokens = token ? [token] : []; }
323
+
324
+ /**
325
+ * Is this one of the tokens we issued? If so, move it to the head.
326
+ *
327
+ * The promotion is what makes the cap safe: with two browsers taking turns, the one that
328
+ * has not connected for longest is the one dropped when a sixth pairing arrives, rather
329
+ * than whichever happens to sit at the end of the array. It writes only when the order
330
+ * actually changes, so an ordinary reconnect (already the head) costs no disk at all.
331
+ */
332
+ _acceptToken(token) {
333
+ const at = this.sessionTokens.indexOf(token);
334
+ if (at === -1) return false;
335
+ if (at > 0) {
336
+ this.sessionTokens = [token, ...this.sessionTokens.filter((t) => t !== token)];
337
+ this.persistError = saveTokens(this.sessionTokens);
338
+ }
339
+ return true;
340
+ }
341
+
274
342
  _onConnection(ws) {
275
343
  if (this.socket && this.socket.readyState === this.socket.OPEN) {
276
344
  log('Rejecting extra connection; one extension is already connected.');
@@ -317,9 +385,9 @@ export class ExtensionBridge {
317
385
 
318
386
  if (msg.method === CONTROL.HANDSHAKE) {
319
387
  const token = msg.params && msg.params.session_token;
320
- if (token && this.sessionToken && token === this.sessionToken) {
388
+ if (token && this._acceptToken(token)) {
321
389
  this.paired = true;
322
- this._send({ method: CONTROL.AUTH_SUCCESS, params: { protocol: PROTOCOL_VERSION } });
390
+ this._send({ method: CONTROL.AUTH_SUCCESS, params: { protocol: PROTOCOL_VERSION, host_version: hostVersion(), session_persisted: !this.persistError } });
323
391
  this._sendClients(); // sync current assistants to a freshly reconnected extension
324
392
  log('Reconnected with a valid session token (no pairing needed).');
325
393
  } else if (this._pairingCodeIsLive()) {
@@ -359,12 +427,17 @@ export class ExtensionBridge {
359
427
  this.paired = true;
360
428
  // 256-bit token (hex): matches the daemon's HTTP token strength, rather
361
429
  // than randomUUID's ~122 bits of entropy (L1).
362
- this.sessionToken = randomBytes(32).toString('hex');
363
- saveToken(this.sessionToken);
430
+ const token = randomBytes(32).toString('hex');
431
+ this.sessionTokens = [token, ...this.sessionTokens.filter((t) => t !== token)].slice(0, MAX_SESSION_TOKENS);
432
+ this.persistError = saveTokens(this.sessionTokens);
364
433
  clearPairingCode();
365
434
  this._resetPairing();
366
- this._send({ method: CONTROL.PAIRING_COMPLETE, params: { session_id: randomUUID(), session_token: this.sessionToken } });
367
- this._send({ method: CONTROL.AUTH_SUCCESS, params: {} });
435
+ // `session_persisted: false` says "you are paired now, and this will not survive a
436
+ // restart". The extension shows it; without it the only trace is a log nobody reads
437
+ // and a code that comes back tomorrow for no visible reason.
438
+ this._send({ method: CONTROL.PAIRING_COMPLETE, params: { session_id: randomUUID(), session_token: token, session_persisted: !this.persistError } });
439
+ // Row 48: the extension cannot otherwise tell a current bridge from a stale one.
440
+ this._send({ method: CONTROL.AUTH_SUCCESS, params: { protocol: PROTOCOL_VERSION, host_version: hostVersion(), session_persisted: !this.persistError } });
368
441
  this._sendClients(); // sync current assistants right after pairing
369
442
  log('Pairing approved.');
370
443
  } else {