dsh-chrome-use 0.6.8 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,28 @@
1
1
  import { BrowserController } from './controller.js';
2
- import { PORT, MAX_MESSAGE, PARALLEL_TABS } from './protocol.js';
2
+ import { TabLeases } from './leases.js';
3
+ import { PORT, MAX_MESSAGE, PARALLEL_TABS, validateArgs } from './protocol.js';
4
+ import { classifyPairingCode } from './pairing-code.js';
5
+
6
+ // One Chrome extension can drive several harnesses at once. Each connection
7
+ // keeps its own socket, pairing token, command map and cleanup generation. The
8
+ // only shared authority is the lease table below: it decides which connection
9
+ // may touch a tab. Bridge-local chat claims stay unchanged.
10
+ const MAX_CONNECTIONS = 4;
11
+ const clients = new Map();
12
+ const portErrors = new Map();
13
+ const leases = new TabLeases();
14
+ const busyTabs = new Map();
15
+ // New pairings reserve a slot before the token is persisted. This counts both
16
+ // stored connections and handshakes still in flight.
17
+ const pairingInFlight = new Set();
18
+ let lastError = '';
19
+ let epochSeq = 0;
20
+ let lifecycleEpoch = 0;
21
+ let intentSeq = 0;
22
+ const portIntents = new Map();
23
+ const forgottenPorts = new Set();
24
+ let restoring;
3
25
 
4
- let socket;
5
- let connected = false;
6
- let connecting;
7
- let connectionGeneration = 0;
8
- const running = new Map();
9
26
  // These actions make their tab the current tab of its window, and Chrome only
10
27
  // delivers synthesized input to the current tab. Queue them across tabs so two
11
28
  // commands cannot switch the same window underneath each other. They do not
@@ -14,8 +31,6 @@ const inputActions = new Set(['activate', 'close', 'click', 'fill', 'key', 'hove
14
31
  const inputQueue = [];
15
32
  let inputBusy = false;
16
33
  function acquireInput(signal) {
17
- // A command can now be canceled while the mode is read, so keep one stable
18
- // error code instead of the DOMException throwIfAborted would use.
19
34
  if (signal.aborted) throw new Error('COMMAND_CANCELED');
20
35
  return new Promise((resolve, reject) => {
21
36
  const start = () => {
@@ -37,174 +52,546 @@ function acquireInput(signal) {
37
52
  } else start();
38
53
  });
39
54
  }
40
- // Foreground mode is the default, matching the popup and the extension before
41
- // 0.6.3. Reading it per command keeps a popup change effective immediately.
55
+
56
+ // Foreground mode is shared by every connection because it is a browser
57
+ // behavior, not a per-harness preference.
42
58
  async function applyMode() {
43
59
  const { foregroundMode } = await chrome.storage.local.get('foregroundMode');
44
60
  controller.foregroundMode = foregroundMode !== false;
45
61
  }
46
- let lastError = '';
62
+
47
63
  const controller = new BrowserController(chrome, (tabId, reason) => {
48
- // Carry Chrome's detach reason so the host can explain a dropped tab instead
49
- // of only reporting that the claim disappeared.
50
- if (connected && socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ type: 'detached', tabId, ...(reason ? { reason: String(reason).slice(0, 40) } : {}) }));
64
+ const owner = leases.get(tabId)?.client;
65
+ leases.release(tabId);
66
+ if (owner?.connected && owner.socket?.readyState === WebSocket.OPEN) {
67
+ owner.socket.send(JSON.stringify({ type: 'detached', tabId, ...(reason ? { reason: String(reason).slice(0, 40) } : {}) }));
68
+ }
51
69
  });
52
70
  const badge = text => { chrome.action.setBadgeText({ text }); chrome.action.setBadgeBackgroundColor({ color: '#185adb' }); };
71
+ const updateBadge = () => badge([...clients.values()].some(client => client.connected) ? 'ON' : '');
72
+ const isToken = value => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
73
+ const isPort = value => Number.isSafeInteger(value) && value >= 1024 && value <= 65535;
74
+ const popupPort = value => {
75
+ const port = typeof value === 'string' && /^\d{2,5}$/.test(value.trim()) ? Number(value.trim()) : value;
76
+ if (!isPort(port)) throw new Error('Enter a port between 1024 and 65535.');
77
+ return port;
78
+ };
53
79
 
54
- let resetting = Promise.resolve();
55
- function drainController() {
56
- const tasks = [...running.values()];
57
- for (const task of tasks) task.cancellation.abort();
58
- resetting = resetting.then(async () => {
59
- await Promise.all(tasks.map(task => task.done));
60
- await controller.reset();
80
+ // Storage writes are serialized. A pairing handshake and a disconnect can
81
+ // otherwise read the same old list and let the later write resurrect state.
82
+ let storageQueue = Promise.resolve();
83
+ function mutateStorage(operation) {
84
+ const run = storageQueue.then(operation, operation);
85
+ storageQueue = run.then(() => {}, () => {});
86
+ return run;
87
+ }
88
+ function validConnections(value) {
89
+ const list = Array.isArray(value) ? value : [];
90
+ const seen = new Set();
91
+ const connections = [];
92
+ for (const item of list) {
93
+ if (!item || !isPort(item.port) || !isToken(item.token) || seen.has(item.port)) continue;
94
+ seen.add(item.port);
95
+ connections.push({ port: item.port, token: item.token });
96
+ }
97
+ return connections.sort((a, b) => a.port - b.port);
98
+ }
99
+ async function readStored() {
100
+ return chrome.storage.local.get(['connections', 'token', 'enabled']);
101
+ }
102
+
103
+ // Before multi-port support the extension kept one `token` for port 18791.
104
+ // Migrate it exactly once and remove the legacy key so forget cannot revive it.
105
+ let migration;
106
+ async function migrateLegacy() {
107
+ await mutateStorage(async () => {
108
+ const stored = await readStored();
109
+ const connections = validConnections(stored.connections);
110
+ if (!connections.length && isToken(stored.token)) connections.push({ port: PORT, token: stored.token });
111
+ if (connections.length) await chrome.storage.local.set({ connections });
112
+ await chrome.storage.local.remove('token');
61
113
  });
62
- return resetting;
63
- }
64
-
65
- async function disconnect(forget = false) {
66
- connectionGeneration++;
67
- connected = false;
68
- const client = socket;
69
- socket = undefined;
70
- client?.close();
71
- await drainController();
72
- if (forget) await chrome.storage.local.remove('token');
73
- await chrome.storage.local.set({ enabled: false });
74
- await chrome.alarms.clear('reconnect');
75
- badge('');
76
- }
77
-
78
- async function connect(code) {
79
- if (connected) return;
80
- if (connecting) return connecting;
81
- const generation = connectionGeneration;
82
- connecting = (async () => {
83
- const { token } = await chrome.storage.local.get('token');
84
- if (!code && !token) throw new Error('Ask Harness for a pairing code first.');
85
- await resetting;
86
- await controller.reset();
87
- if (generation !== connectionGeneration) throw new Error('COMMAND_CANCELED: connection was canceled');
88
- const client = new WebSocket(`ws://127.0.0.1:${PORT}/bridge`);
89
- socket = client;
90
- await new Promise((resolve, reject) => {
91
- const timer = setTimeout(() => { client.close(); reject(new Error('Connection timed out. Check that the Harness plugin is running.')); }, 6000);
92
- client.onopen = () => client.send(JSON.stringify({ ...(code ? { type: 'pair', code } : { type: 'auth', token }), version: chrome.runtime.getManifest().version, features: [PARALLEL_TABS] }));
93
- client.onmessage = async event => {
94
- if (socket !== client) return;
114
+ }
115
+ migration = migrateLegacy().catch(error => { lastError = String(error.message); });
116
+
117
+ async function savedConnections() {
118
+ await migration;
119
+ const stored = await readStored();
120
+ return { connections: validConnections(stored.connections), enabled: stored.enabled === true };
121
+ }
122
+
123
+ function isCurrent(client, socket = client.socket) {
124
+ return !client.revoked && clients.get(client.port) === client && client.socket === socket;
125
+ }
126
+ function createClient(port) {
127
+ return {
128
+ port,
129
+ epoch: ++epochSeq,
130
+ socket: undefined,
131
+ connected: false,
132
+ ready: undefined,
133
+ version: null,
134
+ lastError: '',
135
+ tasks: new Map(),
136
+ drain: undefined,
137
+ revoked: false,
138
+ abortStart: undefined,
139
+ pairingReserved: false,
140
+ persist: { wrote: false, wasSaved: false, committed: false },
141
+ };
142
+ }
143
+
144
+ async function saveToken(client, port, token) {
145
+ return mutateStorage(async () => {
146
+ if (!isCurrent(client)) return false;
147
+ const stored = await readStored();
148
+ const connections = validConnections(stored.connections);
149
+ const existing = connections.find(item => item.port === port);
150
+ if (!existing && connections.length >= MAX_CONNECTIONS) throw new Error(`TOO_MANY_CONNECTIONS: forget a saved Harness before pairing a fifth (maximum ${MAX_CONNECTIONS})`);
151
+ client.persist.wasSaved = Boolean(existing);
152
+ if (!isCurrent(client)) return false;
153
+ const next = connections.filter(item => item.port !== port).concat({ port, token }).sort((a, b) => a.port - b.port);
154
+ await chrome.storage.local.set({ connections: next, enabled: true });
155
+ await chrome.storage.local.remove('token');
156
+ client.persist.wrote = true;
157
+ return true;
158
+ });
159
+ }
160
+
161
+ async function drainClient(client) {
162
+ if (client.drain) return client.drain;
163
+ client.drain = (async () => {
164
+ // Block commands as soon as cleanup starts, before the first await.
165
+ for (const tabId of leases.ownedBy(client)) leases.beginClose(tabId, client);
166
+ const tasks = [...client.tasks.values()];
167
+ for (const task of tasks) task.cancellation.abort();
168
+ await Promise.allSettled(tasks.map(task => task.done));
169
+ // Tasks may have released a lease, or a canceled open may have reserved a
170
+ // new one. Re-enumerate; never trust the pre-abort snapshot.
171
+ for (let pass = 0; pass < 2; pass++) {
172
+ const tabs = leases.ownedBy(client);
173
+ if (!tabs.length) return;
174
+ for (const tabId of tabs) leases.beginClose(tabId, client);
175
+ for (const tabId of tabs) {
176
+ if (leases.owner(tabId) !== client) continue;
177
+ if (leases.get(tabId)?.state === 'quarantined') continue;
178
+ try {
179
+ await controller.detachTab(tabId);
180
+ } catch (error) {
181
+ if (leases.owner(tabId) === client) {
182
+ leases.quarantine(tabId, client);
183
+ client.lastError = String(error.message).slice(0, 2000);
184
+ lastError = client.lastError;
185
+ portErrors.set(client.port, client.lastError);
186
+ }
187
+ continue;
188
+ }
189
+ // A task or a late callback may have released/reassigned the lease while
190
+ // native detach was running; do not clean up someone else's tab.
191
+ if (leases.owner(tabId) !== client) continue;
192
+ if (controller.attached.has(tabId) || controller.pendingCleanup.has(tabId)) leases.quarantine(tabId, client);
193
+ else leases.release(tabId, client);
194
+ }
195
+ }
196
+ })();
197
+ return client.drain;
198
+ }
199
+
200
+ function retireClient(client) {
201
+ client.revoked = true;
202
+ if (clients.get(client.port) === client) clients.delete(client.port);
203
+ client.abortStart?.();
204
+ try { client.socket?.close(); } catch {}
205
+ return drainClient(client);
206
+ }
207
+
208
+ async function startClient(client, { code, restoreEpoch } = {}) {
209
+ const port = client.port;
210
+ const staleRestore = () => restoreEpoch !== undefined && restoreEpoch !== lifecycleEpoch;
211
+ if (staleRestore()) throw new Error(`COMMAND_CANCELED: restore for port ${port} was canceled`);
212
+ if (!code && forgottenPorts.has(port)) throw new Error(`COMMAND_CANCELED: port ${port} was forgotten`);
213
+ const { connections } = await savedConnections();
214
+ if (staleRestore() || client.revoked) throw new Error(`COMMAND_CANCELED: connection to port ${port} was canceled`);
215
+ if (!code && forgottenPorts.has(port)) throw new Error(`COMMAND_CANCELED: port ${port} was forgotten`);
216
+ const saved = connections.find(item => item.port === port);
217
+ if (!code && !saved) throw new Error(`No saved pairing for port ${port}. Enter the 8-digit code from Harness.`);
218
+ if (!saved) {
219
+ if (connections.length + pairingInFlight.size >= MAX_CONNECTIONS) throw new Error(`TOO_MANY_CONNECTIONS: forget a saved Harness before pairing a fifth (maximum ${MAX_CONNECTIONS})`);
220
+ pairingInFlight.add(port);
221
+ client.pairingReserved = true;
222
+ }
223
+ if (staleRestore() || client.revoked) throw new Error(`COMMAND_CANCELED: connection to port ${port} was canceled`);
224
+
225
+ let socket;
226
+ try {
227
+ socket = new WebSocket(`ws://127.0.0.1:${port}/bridge`);
228
+ client.socket = socket;
229
+ return await new Promise((resolve, reject) => {
230
+ let done = false;
231
+ let timer;
232
+ const finish = (settle, value) => {
233
+ if (done) return;
234
+ done = true;
235
+ clearTimeout(timer);
236
+ settle(value);
237
+ };
238
+ const fail = error => {
239
+ finish(reject, error instanceof Error ? error : new Error(String(error)));
240
+ try { socket.close(); } catch {}
241
+ };
242
+ timer = setTimeout(() => fail(new Error(`Connection to port ${port} timed out. Check that a Harness bridge is listening there.`)), 6000);
243
+ client.abortStart = () => fail(new Error(`COMMAND_CANCELED: connection to port ${port} was canceled`));
244
+ socket.onopen = () => {
245
+ if (!isCurrent(client, socket)) return;
246
+ socket.send(JSON.stringify({ ...(code ? { type: 'pair', code } : { type: 'auth', token: saved.token }), version: chrome.runtime.getManifest().version, features: [PARALLEL_TABS] }));
247
+ };
248
+ socket.onmessage = async event => {
249
+ if (!isCurrent(client, socket)) return;
95
250
  try {
96
251
  if (typeof event.data !== 'string' || event.data.length > MAX_MESSAGE) throw new Error('Invalid bridge message');
97
252
  const message = JSON.parse(event.data);
98
253
  if (message.type === 'ready') {
99
- if (message.protocol !== 1 || !/^[a-f0-9]{64}$/.test(message.token)) throw new Error('Unsupported bridge protocol');
100
- await chrome.storage.local.set({ token: message.token, enabled: true });
101
- if (socket !== client || client.readyState !== WebSocket.OPEN) return;
102
- connected = true;
103
- lastError = '';
104
- clearTimeout(timer);
105
- await chrome.alarms.create('reconnect', { periodInMinutes: 0.5 });
106
- badge('ON');
107
- resolve();
108
- } else if (message.type === 'error') {
109
- lastError = String(message.error).slice(0, 2000);
110
- reject(new Error(lastError));
111
- } else if (message.type === 'command' && connected) {
112
- if (typeof message.id !== 'string' || !Number.isFinite(message.deadline) || message.deadline <= Date.now() || message.deadline > Date.now() + 20000) throw new Error('Invalid command deadline');
113
- const tabId = Number.isSafeInteger(message.args?.tabId) ? message.args.tabId : undefined;
114
- if (running.has(message.id)) {
115
- if (client.readyState === WebSocket.OPEN) client.send(JSON.stringify({ type: 'result', id: message.id, error: 'DUPLICATE_COMMAND_ID' }));
254
+ if (message.protocol !== 1 || !isToken(message.token)) throw new Error('Unsupported bridge protocol');
255
+ const persisted = await saveToken(client, port, message.token);
256
+ if (!persisted || !isCurrent(client, socket)) {
257
+ fail(new Error(`COMMAND_CANCELED: connection to port ${port} was canceled`));
116
258
  return;
117
259
  }
118
- if (tabId !== undefined && [...running.values()].some(task => task.tabId === tabId)) {
119
- if (client.readyState === WebSocket.OPEN) client.send(JSON.stringify({ type: 'result', id: message.id, error: 'TAB_BUSY: another command is already running on this tab' }));
120
- return;
121
- }
122
- const cancellation = new AbortController();
123
- let finish;
124
- const done = new Promise(resolve => { finish = resolve; });
125
- running.set(message.id, { cancellation, tabId, done });
126
- const deadline = setTimeout(() => cancellation.abort(), message.deadline - Date.now());
127
- let response;
128
- let releaseInput;
129
- try {
130
- if (inputActions.has(message.action)) {
131
- // A settings read failure keeps the last known mode rather than
132
- // failing the action; lastError still surfaces it in the popup.
133
- try { await applyMode(); }
134
- catch (error) { lastError = error.message; }
135
- releaseInput = await acquireInput(cancellation.signal);
136
- }
137
- response = { result: await controller.execute(message.action, message.args, cancellation.signal) };
138
- }
139
- catch (error) { response = { error: String(error.message).slice(0, 2000) }; }
140
- finally {
141
- clearTimeout(deadline);
142
- // Keep both locks through cleanup. The result acknowledges that it
143
- // is safe for the bridge to hand this tab to the next command.
144
- try {
145
- if (tabId !== undefined && (cancellation.signal.aborted || controller.pendingCleanup.has(tabId))) await controller.detachTab(tabId);
146
- } finally {
147
- running.delete(message.id);
148
- releaseInput?.();
149
- finish();
150
- }
151
- }
152
- if (socket === client && client.readyState === WebSocket.OPEN) {
153
- const body = JSON.stringify({ type: 'result', id: message.id, ...response });
154
- client.send(body.length <= MAX_MESSAGE ? body : JSON.stringify({ type: 'result', id: message.id, error: 'RESULT_TOO_LARGE' }));
155
- }
260
+ client.connected = true;
261
+ client.persist.committed = true;
262
+ client.version = chrome.runtime.getManifest().version;
263
+ client.lastError = '';
264
+ portErrors.delete(port);
265
+ lastError = '';
266
+ finish(resolve, client);
267
+ chrome.alarms.create('reconnect', { periodInMinutes: 0.5 }).catch(() => {});
268
+ updateBadge();
269
+ } else if (message.type === 'error') {
270
+ client.lastError = String(message.error).slice(0, 2000);
271
+ lastError = client.lastError;
272
+ fail(new Error(client.lastError));
273
+ } else if (message.type === 'command' && client.connected) {
274
+ await handleCommand(client, message);
156
275
  } else if (message.type === 'cancel') {
157
- const task = typeof message.id === 'string' ? running.get(message.id) : undefined;
158
- task?.cancellation.abort();
276
+ if (typeof message.id === 'string') client.tasks.get(message.id)?.cancellation.abort();
159
277
  }
160
278
  } catch (error) {
161
- lastError = String(error.message);
162
- client.close();
163
- reject(error);
279
+ client.lastError = String(error.message).slice(0, 2000);
280
+ lastError = client.lastError;
281
+ fail(error);
164
282
  }
165
283
  };
166
- client.onerror = () => { lastError = 'Cannot reach Harness on this computer. Start Harness with dsh-chrome-use installed.'; };
167
- client.onclose = () => {
168
- clearTimeout(timer);
169
- if (socket === client) {
170
- connected = false;
171
- socket = undefined;
172
- drainController().catch(error => { lastError = error.message; });
173
- badge('');
284
+ socket.onerror = () => { client.lastError = `Cannot reach a Harness bridge on port ${port}.`; };
285
+ socket.onclose = () => {
286
+ if (clients.get(port) !== client || client.socket !== socket) {
287
+ finish(reject, new Error(client.lastError || `Connection to port ${port} closed. Reconnect to continue.`));
288
+ return;
174
289
  }
175
- reject(new Error(lastError || 'Connection closed. Reconnect to continue.'));
290
+ client.connected = false;
291
+ clients.delete(port);
292
+ updateBadge();
293
+ drainClient(client).catch(error => { lastError = String(error.message); });
294
+ finish(reject, new Error(client.lastError || `Connection to port ${port} closed. Reconnect to continue.`));
176
295
  };
177
296
  });
297
+ } catch (error) {
298
+ throw error instanceof Error ? error : new Error(String(error));
299
+ } finally {
300
+ client.abortStart = undefined;
301
+ if (client.pairingReserved) {
302
+ pairingInFlight.delete(port);
303
+ client.pairingReserved = false;
304
+ }
305
+ }
306
+ }
307
+
308
+ function beginIntent(port) {
309
+ const intent = ++intentSeq;
310
+ portIntents.set(port, intent);
311
+ return intent;
312
+ }
313
+
314
+ function connectPort(port, options = {}) {
315
+ if (options.code) {
316
+ forgottenPorts.delete(port);
317
+ beginIntent(port);
318
+ }
319
+ const existing = clients.get(port);
320
+ if (existing?.connected) return Promise.resolve(existing);
321
+ if (existing?.ready) return existing.ready;
322
+ if (existing) retireClient(existing).catch(() => {});
323
+ const client = createClient(port);
324
+ clients.set(port, client);
325
+ const start = startClient(client, options);
326
+ const ready = start.finally(() => {
327
+ if (client.ready === ready) client.ready = undefined;
328
+ if (!client.connected && !client.revoked && clients.get(port) === client) clients.delete(port);
329
+ });
330
+ client.ready = ready;
331
+ ready.catch(error => { if (!/^COMMAND_CANCELED/.test(error.message)) portErrors.set(port, String(error.message).slice(0, 2000)); });
332
+ return ready;
333
+ }
334
+
335
+ function sendResult(client, message, response) {
336
+ if (!isCurrent(client) || !client.connected || client.socket?.readyState !== WebSocket.OPEN) return;
337
+ const body = JSON.stringify({ type: 'result', id: message.id, ...response });
338
+ client.socket.send(body.length <= MAX_MESSAGE ? body : JSON.stringify({ type: 'result', id: message.id, error: 'RESULT_TOO_LARGE' }));
339
+ }
340
+
341
+ async function settleFailedLease(client, tabId, action) {
342
+ if (tabId === undefined || leases.owner(tabId) !== client) return;
343
+ // A failed command must never clear a tab that is waiting for native cleanup.
344
+ if (leases.get(tabId)?.state === 'quarantined') return;
345
+ if (action === 'close') { leases.quarantine(tabId, client); return; }
346
+ if (controller.attached.has(tabId)) return;
347
+ if (controller.pendingCleanup.has(tabId)) { leases.quarantine(tabId, client); return; }
348
+ leases.release(tabId, client);
349
+ }
350
+
351
+ async function handleCommand(client, message) {
352
+ const id = message.id;
353
+ if (typeof id !== 'string' || id.length > 200 || !Number.isFinite(message.deadline) || message.deadline <= Date.now() || message.deadline > Date.now() + 20000) {
354
+ throw new Error('Invalid command deadline');
355
+ }
356
+ if (client.tasks.has(id)) {
357
+ sendResult(client, message, { error: 'DUPLICATE_COMMAND_ID' });
358
+ return;
359
+ }
360
+ const action = message.action;
361
+ let args;
362
+ try {
363
+ args = validateArgs(`chrome_${action}`, message.args);
364
+ } catch (error) {
365
+ sendResult(client, message, { error: String(error.message).slice(0, 2000) });
366
+ return;
367
+ }
368
+ const tabId = Number.isSafeInteger(args.tabId) ? args.tabId : undefined;
369
+ const lease = tabId === undefined ? undefined : leases.get(tabId);
370
+ if (lease?.state === 'quarantined') {
371
+ sendResult(client, message, { error: 'TAB_LEASE_QUARANTINED: this tab did not finish native cleanup; reload the extension to clear it' });
372
+ return;
373
+ }
374
+ if (lease?.state === 'closing') {
375
+ sendResult(client, message, { error: 'TAB_LEASE_CLOSING: this tab is being cleaned up; retry after cleanup settles' });
376
+ return;
377
+ }
378
+ if (tabId !== undefined && busyTabs.has(tabId)) {
379
+ sendResult(client, message, { error: 'TAB_BUSY: another command is already running on this tab' });
380
+ return;
381
+ }
382
+ if (action === 'claim' && tabId !== undefined) {
383
+ try { leases.acquire(tabId, client); }
384
+ catch (error) { sendResult(client, message, { error: String(error.message).slice(0, 2000) }); return; }
385
+ } else if (action === 'release' || action === 'close') {
386
+ const owner = tabId === undefined ? undefined : leases.owner(tabId);
387
+ if (!owner) { sendResult(client, message, { error: 'TAB_NOT_LEASED: claim the tab first' }); return; }
388
+ if (owner !== client) { sendResult(client, message, { error: 'TAB_OWNED_BY_ANOTHER_HARNESS: another Harness has claimed this tab; use another tab or release it there' }); return; }
389
+ } else if (tabId !== undefined) {
390
+ const owner = leases.owner(tabId);
391
+ if (!owner) { sendResult(client, message, { error: 'TAB_NOT_LEASED: claim the tab first' }); return; }
392
+ if (owner !== client) { sendResult(client, message, { error: 'TAB_OWNED_BY_ANOTHER_HARNESS: another Harness has claimed this tab; use another tab or release it there' }); return; }
393
+ }
394
+
395
+ const cancellation = new AbortController();
396
+ let finish;
397
+ const done = new Promise(resolve => { finish = resolve; });
398
+ const task = { id, client, tabId, cancellation, done };
399
+ client.tasks.set(id, task);
400
+ if (tabId !== undefined) busyTabs.set(tabId, task);
401
+ const deadline = setTimeout(() => cancellation.abort(), message.deadline - Date.now());
402
+ let response;
403
+ let releaseInput;
404
+ let openedTabId;
405
+ let cleanupFailed = false;
406
+ try {
407
+ if (inputActions.has(action)) {
408
+ try { await applyMode(); }
409
+ catch (error) { lastError = error.message; }
410
+ releaseInput = await acquireInput(cancellation.signal);
411
+ }
412
+ const options = action === 'open'
413
+ ? { onTabCreated: tabId => { openedTabId = tabId; return leases.reserve(tabId, client); } }
414
+ : undefined;
415
+ response = { result: await controller.execute(action, args, cancellation.signal, options) };
416
+ } catch (error) {
417
+ response = { error: String(error.message).slice(0, 2000) };
418
+ } finally {
419
+ clearTimeout(deadline);
420
+ try {
421
+ if (tabId !== undefined && leases.owner(tabId) === client && (cancellation.signal.aborted || controller.pendingCleanup.has(tabId))) {
422
+ try { await controller.detachTab(tabId); }
423
+ catch (error) {
424
+ cleanupFailed = true;
425
+ leases.quarantine(tabId, client);
426
+ client.lastError = String(error.message).slice(0, 2000);
427
+ portErrors.set(client.port, client.lastError);
428
+ }
429
+ if (controller.attached.has(tabId) || controller.pendingCleanup.has(tabId)) {
430
+ cleanupFailed = true;
431
+ leases.quarantine(tabId, client);
432
+ client.lastError = 'BROWSER_CLEANUP_PENDING: native cleanup did not settle; reload the extension before touching this tab';
433
+ portErrors.set(client.port, client.lastError);
434
+ } else if (action === 'close') leases.quarantine(tabId, client);
435
+ else leases.release(tabId, client);
436
+ }
437
+ } finally {
438
+ client.tasks.delete(id);
439
+ if (tabId !== undefined && busyTabs.get(tabId) === task) busyTabs.delete(tabId);
440
+ releaseInput?.();
441
+ finish();
442
+ }
443
+ }
444
+ if (!response.error) {
445
+ if ((action === 'release' || action === 'close') && tabId !== undefined) leases.release(tabId, client);
446
+ } else {
447
+ await settleFailedLease(client, openedTabId ?? tabId, action);
448
+ }
449
+ // An unresolved native cleanup must not acknowledge the command: the bridge
450
+ // would release its lock while Chrome may still dispatch the old work.
451
+ if (cleanupFailed) {
452
+ try { client.socket?.close(); } catch {}
453
+ return;
454
+ }
455
+ sendResult(client, message, response);
456
+ }
457
+
458
+ async function disconnectAll() {
459
+ lifecycleEpoch++;
460
+ portErrors.clear();
461
+ const current = [...clients.values()];
462
+ const oldClients = new Set(current);
463
+ for (const client of current) {
464
+ client.revoked = true;
465
+ if (clients.get(client.port) === client) clients.delete(client.port);
466
+ client.abortStart?.();
467
+ try { client.socket?.close(); } catch {}
468
+ }
469
+ await mutateStorage(async () => {
470
+ const stored = await readStored();
471
+ const connections = validConnections(stored.connections);
472
+ // A completed pairing is user state and survives disconnect. Only a token
473
+ // written by a handshake that never reached ready is rolled back.
474
+ const keep = connections.filter(item => {
475
+ const client = current.find(candidate => candidate.port === item.port);
476
+ if (!client?.persist.wrote) return true;
477
+ return Boolean(client.persist.wasSaved || client.persist.committed);
478
+ });
479
+ await chrome.storage.local.set({ connections: keep, enabled: false });
480
+ await chrome.storage.local.remove('token');
481
+ });
482
+ await chrome.alarms.clear('reconnect');
483
+ await Promise.all(current.map(client => drainClient(client)));
484
+ // Never reset the whole controller here: a new connection may already own
485
+ // tabs while the old cleanup is still settling.
486
+ for (const [tabId, entry] of leases.entries) {
487
+ if (!oldClients.has(entry.client)) continue;
488
+ if (entry.state === 'quarantined' || entry.state === 'closing' || controller.attached.has(tabId) || controller.pendingCleanup.has(tabId)) leases.quarantine(tabId, entry.client);
489
+ else leases.release(tabId, entry.client);
490
+ }
491
+ updateBadge();
492
+ }
493
+
494
+ async function forgetConnection(port) {
495
+ // Revoke the current connection and cancel pending restores synchronously,
496
+ // before the first await. A concurrent explicit pairing must not receive the
497
+ // soon-to-retire client.
498
+ lifecycleEpoch++;
499
+ forgottenPorts.add(port);
500
+ const intent = beginIntent(port);
501
+ portErrors.delete(port);
502
+ const client = clients.get(port);
503
+ const retiring = client ? retireClient(client) : undefined;
504
+ const remove = () => mutateStorage(async () => {
505
+ const stored = await readStored();
506
+ const connections = validConnections(stored.connections).filter(item => item.port !== port);
507
+ await chrome.storage.local.set({ connections, ...(connections.length ? {} : { enabled: false }) });
508
+ await chrome.storage.local.remove('token');
509
+ return connections.length;
510
+ });
511
+ let remaining = await remove();
512
+ if (retiring) await retiring;
513
+ // A newer explicit pairing on the same port wins. Do not erase its token.
514
+ if (portIntents.get(port) !== intent) { updateBadge(); return; }
515
+ // A handshake that was already past the admission fence may have written a
516
+ // token while cleanup ran. Remove it once more.
517
+ remaining = await remove();
518
+ if (!remaining) await chrome.alarms.clear('reconnect');
519
+ updateBadge();
520
+ }
521
+
522
+ async function restoreConnections() {
523
+ if (restoring) return restoring;
524
+ restoring = (async () => {
525
+ const epoch = lifecycleEpoch;
526
+ await migration;
527
+ if (epoch !== lifecycleEpoch) return;
528
+ const { connections, enabled: auto } = await savedConnections();
529
+ if (epoch !== lifecycleEpoch) return;
530
+ if (!auto || !connections.length) { await chrome.alarms.clear('reconnect'); updateBadge(); return; }
531
+ if (connections.length > MAX_CONNECTIONS) lastError = `TOO_MANY_CONNECTIONS: only the first ${MAX_CONNECTIONS} saved Harness connections are restored`;
532
+ // Each missing port is attempted independently; one healthy peer must not
533
+ // suppress recovery of another. The captured epoch cancels a stale restore
534
+ // after disconnect or forget.
535
+ await Promise.allSettled(connections.slice(0, MAX_CONNECTIONS).map(({ port }) => {
536
+ if (epoch !== lifecycleEpoch) return null;
537
+ if (clients.get(port)?.connected) return null;
538
+ return connectPort(port, { restoreEpoch: epoch }).catch(error => { lastError = String(error.message).slice(0, 2000); });
539
+ }));
540
+ if (epoch !== lifecycleEpoch) { updateBadge(); return; }
541
+ // Create the retry alarm only after the admission-fenced attempts. A delayed
542
+ // create can no longer race with disconnect/forget and revive a peer.
543
+ await chrome.alarms.create('reconnect', { periodInMinutes: 0.5 });
544
+ updateBadge();
178
545
  })();
179
- try { await connecting; } finally { connecting = undefined; }
546
+ try { await restoring; } finally { restoring = undefined; }
180
547
  }
181
548
 
182
549
  chrome.runtime.onMessage.addListener((message, sender, respond) => {
183
550
  if (sender.id !== chrome.runtime.id || sender.url !== chrome.runtime.getURL('popup.html')) return false;
184
551
  (async () => {
185
552
  if (message.action === 'connect') {
186
- const code = String(message.code ?? '').trim();
187
- if (code && !/^\d{8}$/.test(code)) throw new Error('Enter the 8-digit code from Harness.');
188
- await connect(code || undefined);
189
- } else if (message.action === 'disconnect') await disconnect();
553
+ const raw = String(message.code ?? '').trim();
554
+ const suppliedPort = message.port === undefined || String(message.port).trim() === '' ? undefined : popupPort(message.port);
555
+ let port;
556
+ let code;
557
+ if (raw) {
558
+ const parsed = classifyPairingCode(raw);
559
+ if (!parsed) throw new Error('Enter the 8-character pairing code from Harness.');
560
+ if (parsed.kind === 'encoded') {
561
+ if (suppliedPort !== undefined && suppliedPort !== parsed.port) throw new Error(`PAIRING_CODE_PORT_MISMATCH: this code belongs to port ${parsed.port}; clear or update the port field`);
562
+ port = parsed.port;
563
+ } else {
564
+ port = suppliedPort ?? PORT;
565
+ }
566
+ code = parsed.code;
567
+ } else {
568
+ port = suppliedPort ?? PORT;
569
+ }
570
+ await connectPort(port, code ? { code } : undefined);
571
+ } else if (message.action === 'disconnect') await disconnectAll();
572
+ else if (message.action === 'forget') await forgetConnection(popupPort(message.port));
190
573
  else if (message.action !== 'status') throw new Error('Unknown action');
191
- const { token, enabled } = await chrome.storage.local.get(['token', 'enabled']);
192
- return { connected, paired: Boolean(token), reconnecting: Boolean(enabled) && !connected, error: lastError, tabs: (await chrome.tabs.query({})).filter(tab => controller.attached.has(tab.id)).map(tab => ({ id: tab.id, title: tab.title, attached: true })) };
574
+ const { connections, enabled: auto } = await savedConnections();
575
+ const connected = [...clients.values()].some(client => client.connected);
576
+ return {
577
+ // Old single-connection fields stay for the first-generation popup.
578
+ connected,
579
+ paired: connections.length > 0,
580
+ reconnecting: auto && !connected,
581
+ connections: connections.map(item => {
582
+ const client = clients.get(item.port);
583
+ return { port: item.port, connected: Boolean(client?.connected), version: client?.version ?? null, error: client?.lastError || portErrors.get(item.port) || '' };
584
+ }),
585
+ enabled: auto,
586
+ error: lastError,
587
+ tabs: (await chrome.tabs.query({})).filter(tab => controller.attached.has(tab.id)).map(tab => ({ id: tab.id, title: tab.title, attached: true })),
588
+ };
193
589
  })().then(result => respond({ ok: true, ...result }), error => respond({ ok: false, error: error.message }));
194
590
  return true;
195
591
  });
196
592
 
197
- async function restoreConnection() {
198
- if (connected || connecting) return;
199
- const { enabled } = await chrome.storage.local.get('enabled');
200
- if (enabled) {
201
- // Keep retrying if Harness is started after Chrome or the extension is reloaded.
202
- await chrome.alarms.create('reconnect', { periodInMinutes: 0.5 });
203
- await connect().catch(error => { lastError = error.message; });
204
- }
205
- }
206
593
  chrome.alarms.onAlarm.addListener(alarm => {
207
- if (alarm.name === 'reconnect') restoreConnection().catch(error => { lastError = error.message; });
594
+ if (alarm.name === 'reconnect') restoreConnections().catch(error => { lastError = error.message; });
208
595
  });
209
- chrome.runtime.onStartup.addListener(() => restoreConnection().catch(error => { lastError = error.message; }));
210
- restoreConnection().catch(error => { lastError = error.message; });
596
+ chrome.runtime.onStartup.addListener(() => restoreConnections().catch(error => { lastError = error.message; }));
597
+ restoreConnections().catch(error => { lastError = error.message; });