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.
package/src/bridge.js CHANGED
@@ -4,15 +4,22 @@ import { mkdir, readFile, writeFile, rename } from 'node:fs/promises';
4
4
  import { join } from 'node:path';
5
5
  import { WebSocketServer, WebSocket } from 'ws';
6
6
  import { PORT, MAX_MESSAGE, DEADLINE_MS, PARALLEL_TABS } from '../extension/protocol.js';
7
+ import { classifyPairingCode, generatePairingCode, normalizePairingCode } from '../extension/pairing-code.js';
8
+ import { candidatePorts, portStateDir, preferencePath, probePort, readPreferredPort, writePreferredPort } from './port-selector.js';
7
9
 
8
10
  const equal = (a, b) => typeof a === 'string' && typeof b === 'string' && a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));
9
11
  const extensionOrigin = /^chrome-extension:\/\/[a-p]{32}$/;
10
12
  const CLAIM_WAIT_MS = 10000;
11
13
 
12
14
  export class Bridge {
13
- constructor({ port = PORT, stateDir, deadlineMs = DEADLINE_MS, claimWaitMs = CLAIM_WAIT_MS } = {}) {
14
- this.port = port;
15
+ constructor({ port = PORT, auto = false, portCandidates, baseStateDir, stateDir, probe = probePort, deadlineMs = DEADLINE_MS, claimWaitMs = CLAIM_WAIT_MS } = {}) {
16
+ this.port = auto ? undefined : port;
17
+ this.requestedPort = auto ? undefined : port;
18
+ this.auto = auto;
19
+ this.portCandidates = portCandidates;
20
+ this.baseStateDir = baseStateDir;
15
21
  this.stateDir = stateDir;
22
+ this.probe = probe;
16
23
  this.deadlineMs = deadlineMs;
17
24
  this.claimWaitMs = claimWaitMs;
18
25
  this.claims = new Map();
@@ -30,40 +37,94 @@ export class Bridge {
30
37
  }
31
38
 
32
39
  async start() {
33
- if (this.stateDir) {
34
- await mkdir(this.stateDir, { recursive: true, mode: 0o700 });
40
+ if (!this.auto) {
35
41
  try {
36
- this.identity = JSON.parse(await readFile(join(this.stateDir, 'pairing.json'), 'utf8'));
37
- if (!extensionOrigin.test(this.identity.origin) || !/^[a-f0-9]{64}$/.test(this.identity.token)) throw new Error('Invalid saved pairing');
42
+ await this.listen(this.port);
38
43
  } catch (error) {
39
- if (error.code !== 'ENOENT') throw new Error(`PAIRING_STATE_ERROR: ${error.message}`);
44
+ if (error.message.startsWith('PAIRING_STATE_ERROR')) throw error;
45
+ throw this.startFailure(error, this.port);
40
46
  }
47
+ this.requestedPort = this.port;
48
+ return;
41
49
  }
42
- this.http = createServer((req, res) => {
50
+
51
+ const preferred = this.baseStateDir ? await readPreferredPort(preferencePath(this.baseStateDir)) : undefined;
52
+ const candidates = this.portCandidates ?? candidatePorts(preferred);
53
+ this.requestedPort = candidates[0];
54
+ for (const candidate of candidates) {
55
+ if (!(await this.probe(candidate))) continue;
56
+ try {
57
+ await this.listen(candidate);
58
+ } catch (error) {
59
+ if (error.code === 'EADDRINUSE') continue;
60
+ if (error.message.startsWith('PAIRING_STATE_ERROR')) throw error;
61
+ throw this.startFailure(error, candidate);
62
+ }
63
+ if (this.baseStateDir) {
64
+ await writePreferredPort(preferencePath(this.baseStateDir), this.port).catch(error => { this.lastError = `PORT_PREFERENCE_WRITE_FAILED: ${error.message}`; });
65
+ }
66
+ return;
67
+ }
68
+ throw new Error(`BRIDGE_START_FAILED: no free loopback port among ${candidates.join(', ')}. Set DSH_CHROME_USE_PORT to a free port.`);
69
+ }
70
+
71
+ startFailure(error, port) {
72
+ return new Error(`BRIDGE_START_FAILED: ${error.code ?? error.message}. Port ${port} is unavailable; stop the other process or start this Harness with DSH_CHROME_USE_PORT set to a free port.`);
73
+ }
74
+
75
+ async listen(port) {
76
+ const stateDir = this.baseStateDir ? portStateDir(this.baseStateDir, port) : this.stateDir;
77
+ const http = createServer((req, res) => {
43
78
  res.writeHead(404, { 'Content-Type': 'text/plain', 'Cache-Control': 'no-store' });
44
79
  res.end('dsh-chrome-use accepts only authenticated extension connections.');
45
80
  });
46
- this.http.requestTimeout = 5000;
47
- this.http.headersTimeout = 5000;
48
- this.ws = new WebSocketServer({ noServer: true, maxPayload: MAX_MESSAGE, perMessageDeflate: false });
49
- this.http.on('upgrade', (req, socket, head) => {
50
- if (this.closed || req.url !== '/bridge' || req.headers.host !== `127.0.0.1:${this.port}` || !extensionOrigin.test(req.headers.origin ?? '') || this.ws.clients.size >= 4) {
81
+ http.requestTimeout = 5000;
82
+ http.headersTimeout = 5000;
83
+ const ws = new WebSocketServer({ noServer: true, maxPayload: MAX_MESSAGE, perMessageDeflate: false });
84
+ const boundPort = () => http.address()?.port ?? port;
85
+ http.on('upgrade', (req, socket, head) => {
86
+ if (this.closed || req.url !== '/bridge' || req.headers.host !== `127.0.0.1:${boundPort()}` || !extensionOrigin.test(req.headers.origin ?? '') || ws.clients.size >= 4) {
51
87
  socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n');
52
88
  return;
53
89
  }
54
- this.ws.handleUpgrade(req, socket, head, client => this.accept(client, req.headers.origin));
90
+ ws.handleUpgrade(req, socket, head, client => this.accept(client, req.headers.origin));
55
91
  });
56
92
  await new Promise((resolve, reject) => {
57
- this.http.once('error', reject);
58
- this.http.listen(this.port, '127.0.0.1', () => {
59
- this.http.off('error', reject);
60
- this.port = this.http.address().port;
93
+ http.once('error', reject);
94
+ http.listen(port, '127.0.0.1', () => {
95
+ http.off('error', reject);
61
96
  resolve();
62
97
  });
63
- }).catch(error => { this.ws.close(); throw new Error(`BRIDGE_START_FAILED: ${error.code ?? error.message}. Another Harness profile may already own port ${this.port}.`); });
64
- this.http.on('error', error => { this.lastError = error.message; });
98
+ }).catch(error => {
99
+ ws.close();
100
+ const failure = new Error(error.code ?? error.message);
101
+ failure.code = error.code;
102
+ throw failure;
103
+ });
104
+ let identity;
105
+ if (stateDir) {
106
+ try {
107
+ await mkdir(stateDir, { recursive: true, mode: 0o700 });
108
+ try {
109
+ identity = JSON.parse(await readFile(join(stateDir, 'pairing.json'), 'utf8'));
110
+ if (!extensionOrigin.test(identity.origin) || !/^[a-f0-9]{64}$/.test(identity.token)) throw new Error('Invalid saved pairing');
111
+ } catch (error) {
112
+ if (error.code !== 'ENOENT') throw error;
113
+ }
114
+ } catch (error) {
115
+ ws.close();
116
+ await new Promise(resolve => http.close(resolve));
117
+ throw new Error(`PAIRING_STATE_ERROR: ${error.message}`);
118
+ }
119
+ }
120
+ http.on('error', error => { this.lastError = error.message; });
121
+ this.http = http;
122
+ this.ws = ws;
123
+ this.port = boundPort();
124
+ this.stateDir = stateDir;
125
+ this.identity = identity;
65
126
  this.heartbeat = setInterval(() => {
66
- for (const client of this.ws.clients) {
127
+ for (const client of ws.clients) {
67
128
  if (client.alive === false) client.terminate();
68
129
  else {
69
130
  client.alive = false;
@@ -77,13 +138,28 @@ export class Bridge {
77
138
  }
78
139
 
79
140
  status() {
80
- return { connected: this.peer?.readyState === WebSocket.OPEN, port: this.port, extensionVersion: this.peer?.extensionVersion ?? null, claimedTabs: [...this.claims.keys()], ...(this.lastError ? { lastError: this.lastError } : {}) };
141
+ return {
142
+ connected: this.peer?.readyState === WebSocket.OPEN,
143
+ port: this.port,
144
+ ...(this.requestedPort !== undefined && this.requestedPort !== this.port ? { requestedPort: this.requestedPort } : {}),
145
+ extensionVersion: this.peer?.extensionVersion ?? null,
146
+ claimedTabs: [...this.claims.keys()],
147
+ ...(this.lastError ? { lastError: this.lastError } : {}),
148
+ };
81
149
  }
82
150
 
83
151
  pair() {
84
152
  if (this.peer) throw new Error('ALREADY_CONNECTED: disconnect in the extension before pairing again');
85
- this.pairing = { code: String(randomInt(10000000, 100000000)), expires: Date.now() + 120000, attempts: 0 };
86
- return { code: this.pairing.code, port: this.port, expiresInSeconds: 120, instructions: 'Open dsh-chrome-use in the Chrome toolbar, enter this code and click Connect. Connecting permits access to all normal tabs in this Chrome. Do not enter the code into a website or post it publicly.' };
153
+ const code = String(randomInt(10000000, 100000000));
154
+ const pairingCode = generatePairingCode(this.port, () => randomInt(0, 0x1000000));
155
+ this.pairing = { code, pairingCode, expires: Date.now() + 120000, attempts: 0 };
156
+ return {
157
+ code,
158
+ pairingCode,
159
+ port: this.port,
160
+ expiresInSeconds: 120,
161
+ instructions: `Open dsh-chrome-use in the Chrome toolbar and enter the 8-character pairing code for port ${this.port}. New extensions read the port from the code; older extensions use the 8-digit compatibility code only on port 18791. Connecting permits access to all normal tabs in this Chrome. Do not enter the code into a website or post it publicly.`,
162
+ };
87
163
  }
88
164
 
89
165
  accept(client, origin) {
@@ -118,7 +194,22 @@ export class Bridge {
118
194
  this.authFailures = this.authFailures.filter(time => time > Date.now() - 60000);
119
195
  if (this.authFailures.length >= 10) throw new Error('PAIRING_RATE_LIMIT');
120
196
  let identity;
121
- if (message.type === 'pair' && this.pairing && Date.now() < this.pairing.expires && ++this.pairing.attempts <= 5 && equal(message.code, this.pairing.code)) {
197
+ if (message.type === 'pair') {
198
+ const pairing = this.pairing;
199
+ let matched = false;
200
+ if (pairing && Date.now() < pairing.expires) {
201
+ pairing.attempts += 1;
202
+ if (pairing.attempts <= 5) {
203
+ const submitted = normalizePairingCode(message.code);
204
+ const classified = classifyPairingCode(submitted);
205
+ if (classified?.kind === 'encoded') matched = classified.port === this.port && equal(classified.code, pairing.pairingCode);
206
+ else if (classified?.kind === 'legacy') matched = equal(classified.code, pairing.code);
207
+ }
208
+ }
209
+ if (!matched) {
210
+ this.authFailures.push(Date.now());
211
+ throw new Error('AUTH_FAILED: request a fresh pairing code from Harness');
212
+ }
122
213
  if (this.peer) throw new Error('BROWSER_ALREADY_CONNECTED');
123
214
  // Reserve before file I/O so two pairing requests cannot win.
124
215
  this.pairing = undefined;
package/src/client.js CHANGED
@@ -1,15 +1,25 @@
1
1
  window.__ModuleLoader__.load({ id: 'dsh-chrome-use', factory: (require) => { const module = { exports: {} };
2
2
  function parseStatus(value) {
3
3
  if (!value || typeof value.connected !== 'boolean' || !Number.isSafeInteger(value.tabCount) || value.tabCount < 0 || !(value.extensionVersion === null || typeof value.extensionVersion === 'string')) throw new Error('Invalid Chrome connection status');
4
- return { connected: value.connected, tabCount: value.tabCount, extensionVersion: value.extensionVersion };
4
+ const status = { connected: value.connected, tabCount: value.tabCount, extensionVersion: value.extensionVersion };
5
+ for (const field of ['port', 'requestedPort']) {
6
+ if (value[field] === undefined) continue;
7
+ if (!Number.isSafeInteger(value[field]) || value[field] < 1024 || value[field] > 65535) throw new Error(`Invalid Chrome connection ${field}`);
8
+ status[field] = value[field];
9
+ }
10
+ return status;
5
11
  }
12
+ const PAIRING_CODE_RE = /^[0-9A-HJKMNP-TV-Z]{8}$/;
6
13
  function parsePairing(value) {
7
14
  if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid pairing response');
8
15
  if (typeof value.code !== 'string' || !/^[0-9]{8}$/.test(value.code)) throw new Error('Invalid pairing code');
16
+ if (value.pairingCode !== undefined) {
17
+ if (typeof value.pairingCode !== 'string' || !PAIRING_CODE_RE.test(value.pairingCode) || !/[A-Z]/.test(value.pairingCode)) throw new Error('Invalid pairing code');
18
+ }
9
19
  if (!Number.isSafeInteger(value.port) || value.port < 1 || value.port > 65535) throw new Error('Invalid pairing port');
10
20
  if (!Number.isSafeInteger(value.expiresInSeconds) || value.expiresInSeconds < 1 || value.expiresInSeconds > 600) throw new Error('Invalid pairing lifetime');
11
21
  if (typeof value.instructions !== 'string' || value.instructions.length > 2000) throw new Error('Invalid pairing instructions');
12
- return { code: value.code, port: value.port, expiresInSeconds: value.expiresInSeconds, instructions: value.instructions };
22
+ return { code: value.code, ...(value.pairingCode === undefined ? {} : { pairingCode: value.pairingCode }), port: value.port, expiresInSeconds: value.expiresInSeconds, instructions: value.instructions };
13
23
  }
14
24
  const statusCodec = { mode: 'strict', typeSymbol: 'dsh-chrome-use#ConnectionStatus', schema: { parse: parseStatus }, create: () => ({ parse: parseStatus }) };
15
25
  const pairingCodec = { mode: 'strict', typeSymbol: 'dsh-chrome-use#PairingCode', schema: { parse: parsePairing }, create: () => ({ parse: parsePairing }) };
@@ -58,7 +68,7 @@ async function checkRelease(current, fetcher = fetch) {
58
68
  } finally { clearTimeout(timer); }
59
69
  }
60
70
 
61
- const packageVersion = "0.6.8";
71
+ const packageVersion = "0.7.0";
62
72
  // Wrapped by scripts/build-client.mjs for the Harness browser module loader.
63
73
  const React = require('react');
64
74
  const { createElement: h, useState, useEffect, useRef } = React;
@@ -109,11 +119,11 @@ function StatusPage({ read, pair }) {
109
119
  const stamp = Date.now();
110
120
  if (!alive.current) return;
111
121
  setNow(stamp);
112
- setPairing({ code: value.code, port: value.port, expiresAt: stamp + value.expiresInSeconds * 1000 });
122
+ setPairing({ code: value.pairingCode ?? value.code, pairingCode: value.pairingCode, legacyCode: value.code, port: value.port, expiresAt: stamp + value.expiresInSeconds * 1000 });
113
123
  } catch (error) {
114
124
  if (!alive.current) return;
115
125
  const message = String(error && error.message ? error.message : error);
116
- setPairing({ error: message.includes('ALREADY_CONNECTED') ? 'Chrome 已连接,无需新的配对码。如需重新配对,请先在扩展弹窗中点击“断开连接”。' : message.includes('BRIDGE_STOPPED') ? 'Harness 插件已停止,请重启 Harness 后再试。' : `生成配对码失败:${message}` });
126
+ setPairing({ error: message.includes('ALREADY_CONNECTED') ? 'Chrome 已连接,无需新的配对码。如需重新配对,请先在扩展弹窗中点击“断开全部连接”。' : message.includes('BRIDGE_STOPPED') ? 'Harness 插件已停止,请重启 Harness 后再试。' : `生成配对码失败:${message}` });
117
127
  }
118
128
  }
119
129
  async function copyCode() {
@@ -141,18 +151,22 @@ function StatusPage({ read, pair }) {
141
151
  h('h3', null, '连接状态'),
142
152
  h('p', { role: 'status' }, state.loading && !value ? '正在查询 Chrome 连接…' : state.error && !value ? state.error : connected ? '已连接 Chrome' : '未连接 Chrome'),
143
153
  value && h('p', null, `扩展版本:${value.extensionVersion || '未知'} · 正在调试的标签页:${value.tabCount}`),
144
- value && !connected && h('p', null, '请生成配对码,在 Chrome 工具栏的扩展弹窗中输入并点击“连接”。'),
145
- connected && h('p', null, '如需重新配对,请先在扩展弹窗中点击“断开连接”,再回到这里生成新的配对码。'),
154
+ value?.port && h('p', { role: 'status' }, value.requestedPort && value.requestedPort !== value.port ? `本机端口 ${value.port}(${value.requestedPort} 被占用,已自动改用)` : `本机端口 ${value.port}`),
155
+ value && !connected && h('p', null, '请生成配对码,在 Chrome 工具栏的扩展弹窗中粘贴并点击“连接”。'),
156
+ connected && h('p', null, '如需重新配对,请先在扩展弹窗中点击“断开全部连接”,再回到这里生成新的配对码。'),
146
157
  h('button', { onClick: refresh, disabled: state.loading, style: buttonStyle }, state.loading ? '刷新中…' : '刷新状态'));
147
158
  const pairBlock = h('div', { key: 'pair' },
148
159
  h('h3', null, '配对 Chrome 扩展'),
149
- h('p', null, '点击下面的按钮生成 8 位配对码,然后在 Chrome 工具栏打开 dsh-chrome-use 扩展,输入配对码并点击“连接”。配对码 2 分钟内有效,生成新码会让旧码立即失效。'),
160
+ h('p', null, '点击下面的按钮生成 8 位配对码,然后在 Chrome 工具栏打开 dsh-chrome-use 扩展,粘贴配对码并点击“连接”。新配对码已经包含端口,扩展会自动识别,不需要手填端口。配对码 2 分钟内有效,生成新码会让旧码立即失效。'),
150
161
  h('button', { onClick: requestPairing, disabled: pairing.loading, style: buttonStyle }, pairing.loading ? '正在生成…' : pairing.code || expired ? '重新生成配对码' : '生成配对码'),
151
162
  pairing.error && h('p', { role: 'alert', style: { color: 'var(--dsh-danger, #d9534f)' } }, pairing.error),
152
163
  pairing.code && !expired && h('div', { style: { marginTop: 12 } },
153
164
  h('code', { style: codeStyle, 'aria-label': '配对码' }, pairing.code),
154
165
  h('p', { role: 'status' }, `剩余有效时间:${countdown}(本机端口 ${pairing.port})`),
155
- h('button', { onClick: copyCode, style: buttonStyle }, pairing.copied ? '已复制' : '复制配对码')),
166
+ h('button', { onClick: copyCode, style: buttonStyle }, pairing.copied ? '已复制' : '复制配对码'),
167
+ pairing.pairingCode && pairing.port === 18791 && h('details', null,
168
+ h('summary', null, '旧版扩展(仅 18791)'),
169
+ h('p', null, `旧版扩展只认纯数字兼容码,并且在 18791 上使用:${pairing.legacyCode}`))),
156
170
  expired && h('p', { role: 'status' }, '配对码已过期,请点击“重新生成配对码”。'),
157
171
  h('p', null, '如果按钮不可用,也可以在对话中让 Harness 调用 chrome_pair,拿到的是同一种临时码。'));
158
172
  const installBlock = h('div', { key: 'install' },
@@ -170,7 +184,7 @@ function StatusPage({ read, pair }) {
170
184
  return h('section', { style: { padding: 24 }, 'aria-label': 'dsh-chrome-use' },
171
185
  h('h2', null, 'dsh-chrome-use'),
172
186
  h('p', null, `Harness 插件版本:${packageVersion}`),
173
- h('p', null, link(repositoryUrl, '觉得好用?点个 Star ⭐ 这对我们很重要')),
187
+ h('p', null, link(repositoryUrl, '喜欢这个插件?去 GitHub 点个 Star')),
174
188
  settingsSectionOrder(connected).map(key => blocks[key]));
175
189
  }
176
190
  module.exports.inject = ['slots', 'remote'];
package/src/index.js CHANGED
@@ -6,7 +6,7 @@ import { randomUUID } from 'node:crypto';
6
6
  import { Bridge } from './bridge.js';
7
7
  import { storeUrl } from './links.js';
8
8
  import { registerChromeUseSkill } from './skill.js';
9
- import { TOOLS, validateArgs } from '../extension/protocol.js';
9
+ import { TOOLS, validateArgs, parsePort } from '../extension/protocol.js';
10
10
  import { buildIssueReport } from './report.js';
11
11
  import { createRequire } from 'node:module';
12
12
 
@@ -16,6 +16,11 @@ const pluginVersion = createRequire(import.meta.url)('../package.json').version;
16
16
  export const name = 'dsh-chrome-use';
17
17
  export const inject = ['tools'];
18
18
 
19
+ export function bridgeOptions(env, baseStateDir) {
20
+ const configured = env?.DSH_CHROME_USE_PORT?.trim();
21
+ return configured ? { port: parsePort(configured), baseStateDir } : { auto: true, baseStateDir };
22
+ }
23
+
19
24
  // DSH accepts a JSON Schema subset. Keep full bounds in the shared validator.
20
25
  export function harnessParameters(parameters) {
21
26
  return { ...parameters, properties: Object.fromEntries(Object.entries(parameters.properties).map(([key, value]) => {
@@ -98,7 +103,9 @@ export function renderOutput(name, value) {
98
103
 
99
104
  export async function apply(ctx) {
100
105
  const stateDir = join(homedir(), '.dsh', 'dsh-chrome-use');
101
- const bridge = new Bridge({ stateDir });
106
+ // An explicit port is strict. Without one, the bridge remembers the last
107
+ // successful auto port and falls back through loopback candidates.
108
+ const bridge = new Bridge(bridgeOptions(process.env, stateDir));
102
109
  // Register startup itself with Cordis so shutdown also waits for a pending start.
103
110
  await ctx.effect(async () => {
104
111
  await bridge.start();
@@ -0,0 +1,63 @@
1
+ import { createServer } from 'node:net';
2
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
3
+ import { dirname, join } from 'node:path';
4
+ import { PORT } from '../extension/protocol.js';
5
+
6
+ export const FIXTURE_PORT = 18792;
7
+ export const AUTO_PORTS = [PORT, 18793, 18794, 18795, 18796, 18797, 18798, 18799];
8
+ export const PREFERENCE_FILE = 'port.json';
9
+
10
+ export function isValidAutoPort(value) {
11
+ return Number.isSafeInteger(value) && value >= 1024 && value <= 65535 && value !== FIXTURE_PORT;
12
+ }
13
+
14
+ export function portStateDir(baseDir, port) {
15
+ return port === PORT ? baseDir : join(baseDir, `port-${port}`);
16
+ }
17
+
18
+ export function candidatePorts(preferred) {
19
+ const candidates = [];
20
+ for (const port of [preferred, ...AUTO_PORTS]) {
21
+ if (isValidAutoPort(port) && !candidates.includes(port)) candidates.push(port);
22
+ }
23
+ return candidates;
24
+ }
25
+
26
+ export async function readPreferredPort(file) {
27
+ try {
28
+ const value = JSON.parse(await readFile(file, 'utf8'));
29
+ return isValidAutoPort(value?.port) ? value.port : undefined;
30
+ } catch {
31
+ return undefined;
32
+ }
33
+ }
34
+
35
+ export async function writePreferredPort(file, port) {
36
+ if (!isValidAutoPort(port)) throw new Error(`INVALID_PORT: ${port}`);
37
+ await mkdir(dirname(file), { recursive: true, mode: 0o700 });
38
+ const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;
39
+ await writeFile(temporary, JSON.stringify({ port }), { mode: 0o600 });
40
+ await rename(temporary, file);
41
+ }
42
+
43
+ // A loopback probe is advisory only. The actual bind is still the reservation,
44
+ // so a concurrent process can win between probe and bind.
45
+ export async function probePort(port) {
46
+ const probe = createServer();
47
+ try {
48
+ await new Promise((resolve, reject) => {
49
+ probe.once('error', reject);
50
+ probe.listen(port, '127.0.0.1', resolve);
51
+ });
52
+ return true;
53
+ } catch (error) {
54
+ if (error.code === 'EADDRINUSE') return false;
55
+ throw new Error(`BRIDGE_PORT_PROBE_FAILED: ${error.code ?? error.message}`);
56
+ } finally {
57
+ if (probe.listening) await new Promise(resolve => probe.close(resolve));
58
+ }
59
+ }
60
+
61
+ export function preferencePath(baseDir) {
62
+ return join(baseDir, PREFERENCE_FILE);
63
+ }
@@ -48,11 +48,11 @@ function StatusPage({ read, pair }) {
48
48
  const stamp = Date.now();
49
49
  if (!alive.current) return;
50
50
  setNow(stamp);
51
- setPairing({ code: value.code, port: value.port, expiresAt: stamp + value.expiresInSeconds * 1000 });
51
+ setPairing({ code: value.pairingCode ?? value.code, pairingCode: value.pairingCode, legacyCode: value.code, port: value.port, expiresAt: stamp + value.expiresInSeconds * 1000 });
52
52
  } catch (error) {
53
53
  if (!alive.current) return;
54
54
  const message = String(error && error.message ? error.message : error);
55
- setPairing({ error: message.includes('ALREADY_CONNECTED') ? 'Chrome 已连接,无需新的配对码。如需重新配对,请先在扩展弹窗中点击“断开连接”。' : message.includes('BRIDGE_STOPPED') ? 'Harness 插件已停止,请重启 Harness 后再试。' : `生成配对码失败:${message}` });
55
+ setPairing({ error: message.includes('ALREADY_CONNECTED') ? 'Chrome 已连接,无需新的配对码。如需重新配对,请先在扩展弹窗中点击“断开全部连接”。' : message.includes('BRIDGE_STOPPED') ? 'Harness 插件已停止,请重启 Harness 后再试。' : `生成配对码失败:${message}` });
56
56
  }
57
57
  }
58
58
  async function copyCode() {
@@ -80,18 +80,22 @@ function StatusPage({ read, pair }) {
80
80
  h('h3', null, '连接状态'),
81
81
  h('p', { role: 'status' }, state.loading && !value ? '正在查询 Chrome 连接…' : state.error && !value ? state.error : connected ? '已连接 Chrome' : '未连接 Chrome'),
82
82
  value && h('p', null, `扩展版本:${value.extensionVersion || '未知'} · 正在调试的标签页:${value.tabCount}`),
83
- value && !connected && h('p', null, '请生成配对码,在 Chrome 工具栏的扩展弹窗中输入并点击“连接”。'),
84
- connected && h('p', null, '如需重新配对,请先在扩展弹窗中点击“断开连接”,再回到这里生成新的配对码。'),
83
+ value?.port && h('p', { role: 'status' }, value.requestedPort && value.requestedPort !== value.port ? `本机端口 ${value.port}(${value.requestedPort} 被占用,已自动改用)` : `本机端口 ${value.port}`),
84
+ value && !connected && h('p', null, '请生成配对码,在 Chrome 工具栏的扩展弹窗中粘贴并点击“连接”。'),
85
+ connected && h('p', null, '如需重新配对,请先在扩展弹窗中点击“断开全部连接”,再回到这里生成新的配对码。'),
85
86
  h('button', { onClick: refresh, disabled: state.loading, style: buttonStyle }, state.loading ? '刷新中…' : '刷新状态'));
86
87
  const pairBlock = h('div', { key: 'pair' },
87
88
  h('h3', null, '配对 Chrome 扩展'),
88
- h('p', null, '点击下面的按钮生成 8 位配对码,然后在 Chrome 工具栏打开 dsh-chrome-use 扩展,输入配对码并点击“连接”。配对码 2 分钟内有效,生成新码会让旧码立即失效。'),
89
+ h('p', null, '点击下面的按钮生成 8 位配对码,然后在 Chrome 工具栏打开 dsh-chrome-use 扩展,粘贴配对码并点击“连接”。新配对码已经包含端口,扩展会自动识别,不需要手填端口。配对码 2 分钟内有效,生成新码会让旧码立即失效。'),
89
90
  h('button', { onClick: requestPairing, disabled: pairing.loading, style: buttonStyle }, pairing.loading ? '正在生成…' : pairing.code || expired ? '重新生成配对码' : '生成配对码'),
90
91
  pairing.error && h('p', { role: 'alert', style: { color: 'var(--dsh-danger, #d9534f)' } }, pairing.error),
91
92
  pairing.code && !expired && h('div', { style: { marginTop: 12 } },
92
93
  h('code', { style: codeStyle, 'aria-label': '配对码' }, pairing.code),
93
94
  h('p', { role: 'status' }, `剩余有效时间:${countdown}(本机端口 ${pairing.port})`),
94
- h('button', { onClick: copyCode, style: buttonStyle }, pairing.copied ? '已复制' : '复制配对码')),
95
+ h('button', { onClick: copyCode, style: buttonStyle }, pairing.copied ? '已复制' : '复制配对码'),
96
+ pairing.pairingCode && pairing.port === 18791 && h('details', null,
97
+ h('summary', null, '旧版扩展(仅 18791)'),
98
+ h('p', null, `旧版扩展只认纯数字兼容码,并且在 18791 上使用:${pairing.legacyCode}`))),
95
99
  expired && h('p', { role: 'status' }, '配对码已过期,请点击“重新生成配对码”。'),
96
100
  h('p', null, '如果按钮不可用,也可以在对话中让 Harness 调用 chrome_pair,拿到的是同一种临时码。'));
97
101
  const installBlock = h('div', { key: 'install' },
@@ -109,7 +113,7 @@ function StatusPage({ read, pair }) {
109
113
  return h('section', { style: { padding: 24 }, 'aria-label': 'dsh-chrome-use' },
110
114
  h('h2', null, 'dsh-chrome-use'),
111
115
  h('p', null, `Harness 插件版本:${packageVersion}`),
112
- h('p', null, link(repositoryUrl, '觉得好用?点个 Star ⭐ 这对我们很重要')),
116
+ h('p', null, link(repositoryUrl, '喜欢这个插件?去 GitHub 点个 Star')),
113
117
  settingsSectionOrder(connected).map(key => blocks[key]));
114
118
  }
115
119
  module.exports.inject = ['slots', 'remote'];
@@ -1,14 +1,24 @@
1
1
  export function parseStatus(value) {
2
2
  if (!value || typeof value.connected !== 'boolean' || !Number.isSafeInteger(value.tabCount) || value.tabCount < 0 || !(value.extensionVersion === null || typeof value.extensionVersion === 'string')) throw new Error('Invalid Chrome connection status');
3
- return { connected: value.connected, tabCount: value.tabCount, extensionVersion: value.extensionVersion };
3
+ const status = { connected: value.connected, tabCount: value.tabCount, extensionVersion: value.extensionVersion };
4
+ for (const field of ['port', 'requestedPort']) {
5
+ if (value[field] === undefined) continue;
6
+ if (!Number.isSafeInteger(value[field]) || value[field] < 1024 || value[field] > 65535) throw new Error(`Invalid Chrome connection ${field}`);
7
+ status[field] = value[field];
8
+ }
9
+ return status;
4
10
  }
11
+ const PAIRING_CODE_RE = /^[0-9A-HJKMNP-TV-Z]{8}$/;
5
12
  export function parsePairing(value) {
6
13
  if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid pairing response');
7
14
  if (typeof value.code !== 'string' || !/^[0-9]{8}$/.test(value.code)) throw new Error('Invalid pairing code');
15
+ if (value.pairingCode !== undefined) {
16
+ if (typeof value.pairingCode !== 'string' || !PAIRING_CODE_RE.test(value.pairingCode) || !/[A-Z]/.test(value.pairingCode)) throw new Error('Invalid pairing code');
17
+ }
8
18
  if (!Number.isSafeInteger(value.port) || value.port < 1 || value.port > 65535) throw new Error('Invalid pairing port');
9
19
  if (!Number.isSafeInteger(value.expiresInSeconds) || value.expiresInSeconds < 1 || value.expiresInSeconds > 600) throw new Error('Invalid pairing lifetime');
10
20
  if (typeof value.instructions !== 'string' || value.instructions.length > 2000) throw new Error('Invalid pairing instructions');
11
- return { code: value.code, port: value.port, expiresInSeconds: value.expiresInSeconds, instructions: value.instructions };
21
+ return { code: value.code, ...(value.pairingCode === undefined ? {} : { pairingCode: value.pairingCode }), port: value.port, expiresInSeconds: value.expiresInSeconds, instructions: value.instructions };
12
22
  }
13
23
  const statusCodec = { mode: 'strict', typeSymbol: 'dsh-chrome-use#ConnectionStatus', schema: { parse: parseStatus }, create: () => ({ parse: parseStatus }) };
14
24
  const pairingCodec = { mode: 'strict', typeSymbol: 'dsh-chrome-use#PairingCode', schema: { parse: parsePairing }, create: () => ({ parse: parsePairing }) };
package/src/settings.js CHANGED
@@ -25,7 +25,7 @@ export function registerSettings(ctx, bridge) {
25
25
  async read() {
26
26
  try {
27
27
  const status = bridge.status();
28
- return parseStatus({ connected: status.connected, extensionVersion: status.extensionVersion, tabCount: status.claimedTabs.length });
28
+ return parseStatus({ connected: status.connected, port: status.port, ...(status.requestedPort === undefined ? {} : { requestedPort: status.requestedPort }), extensionVersion: status.extensionVersion, tabCount: status.claimedTabs.length });
29
29
  } catch (error) { report('read', error); throw error; }
30
30
  },
31
31
  async pair() {
package/src/skill.js CHANGED
@@ -16,7 +16,7 @@ export const chromeUseSkill = {
16
16
  ## 连接
17
17
 
18
18
  1. 先调用 chrome_status 检查连接。
19
- 2. 未连接时调用 chrome_pair 生成 8 位配对码(2 分钟内有效),让用户在 Chrome 工具栏打开 dsh-chrome-use 扩展,输入配对码并点击“连接”。扩展还没安装时,让用户到 Harness 设置 → dsh-chrome-use 点商店链接安装。不要要求用户重装或手动加载文件夹。
19
+ 2. 未连接时调用 chrome_pair 生成 8 位配对码(2 分钟内有效)。返回里有 pairingCode 时优先把 pairingCode 给用户;它已经包含端口,新扩展会自动识别,不要要求用户再填端口。没有 pairingCode 时使用纯数字 code(旧桥/旧扩展,只在 18791 可用)。让用户在 Chrome 工具栏打开 dsh-chrome-use 扩展,粘贴配对码并点击“连接”。扩展还没安装时,让用户到 Harness 设置 → dsh-chrome-use 点商店链接安装。不要要求用户重装或手动加载文件夹。
20
20
  3. 配对成功后,重启 Harness、Chrome 或扩展自动更新都会自动重连。用户主动断开后,留空配对码点“连接”即可。
21
21
 
22
22
  ## 操作流程
@@ -36,7 +36,7 @@ export const chromeUseSkill = {
36
36
 
37
37
  ## 出错时
38
38
 
39
- 1. 先按错误码处理能自愈的情况:STALE_ELEMENT 重新 chrome_snapshot;TAB_BUSY 等当前命令结束;TAB_IN_USE 让原会话释放或新开页面;PAGE_HIDDEN 说明窗口被最小化或遮挡,问用户要不要用 chrome_activate 调出来。
39
+ 1. 先按错误码处理能自愈的情况:STALE_ELEMENT 重新 chrome_snapshot;TAB_BUSY 等当前命令结束;TAB_IN_USE 让原会话释放或新开页面;TAB_OWNED_BY_ANOTHER_HARNESS 表示另一个 Harness 占用了该页,换一个标签页或让对方 chrome_release;TAB_LEASE_QUARANTINED 表示 Chrome 清理未完成,让用户重载扩展后再试;TAB_LEASE_CLOSING 表示另一个 Harness 正在清理该标签页,等清理结束后再试,不要循环;PAGE_HIDDEN 说明窗口被最小化或遮挡,问用户要不要用 chrome_activate 调出来。
40
40
  2. 重试后仍失败、或错误码无法解释时,用一两句话告诉用户哪个工具失败、错误原文是什么、你已经试过什么。
41
41
  3. 然后问用户:“需要我帮你给 dsh-chrome-use 提一个 issue 吗?只会带上工具名、错误信息和版本,不会带页面内容、截图或登录信息。”
42
42
  4. 用户同意后再调用 chrome_report(error 填工具返回的错误原文,tool 填工具名,note 写一句你在做什么),把返回的链接用 chrome_open 打开,让用户自己检查并提交;不要替用户点击提交。
@@ -47,6 +47,7 @@ export const chromeUseSkill = {
47
47
 
48
48
  - chrome_claim 遇到其他会话占用时,按先来后到排队,最多等 10 秒。TAB_IN_USE 表示等待超时:让原会话释放,或新开页面。不要循环争抢;完成任务后及时 chrome_release。
49
49
  - TAB_BUSY 表示这个标签页还有命令或取消清理在运行,等它结束再操作。不同标签页的读取、等待可以并行;点击、输入、拖拽、激活等前台操作会自动排队,排队计入命令超时。
50
+ - 多个 Harness 同时连接时,标签页占用由扩展统一管理。TAB_OWNED_BY_ANOTHER_HARNESS 不会跨 Harness 排队,不要循环重试。
50
51
  - 超时或取消会请求停止当前命令,清理确认前保留操作锁,不会自动重放。其他页面通常不受影响;清理超过 8 秒或使用旧版扩展时会断开连接。重新占用并读取页面,确认之前的操作是否已经发生。
51
52
  - 扩展弹窗有「前台模式」开关,默认开着:开着时点击、输入会把浏览器窗口抬到最前,会抢走用户正在用的应用的焦点;关掉后是后台静默模式,只在浏览器窗口内切标签页、不抢焦点。用户抱怨输入被打断时,提示他在扩展弹窗里关掉「前台模式」。chrome_activate 在任何模式都会把窗口抬到最前,除非用户明确要求看到页面,否则不要调用。
52
53
  - 后台静默模式下,窗口最小化或被系统判定完全遮挡时标签页是 hidden,操作会返回 PAGE_HIDDEN。不要为了继续任务自动调用 chrome_activate 把窗口弹出来,先告诉用户发生了什么,由用户决定。