dsh-mobile-plugin 0.5.111 → 0.5.113

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,4 +1,4 @@
1
- // 节点小宝设备端的安装与启动:下载官方二进制、按平台装成系统服务、确保它在跑。
1
+ // 节点小宝设备端的安装与启动:下载官方设备端 / 安装脚本、按平台装成系统服务、确保它在跑。
2
2
  'use strict';
3
3
 
4
4
  /**
@@ -6,12 +6,12 @@
6
6
  * 装成**系统服务**——它的设备身份写在系统目录里,只有以 root 跑才存得住,否则每次重启都当新
7
7
  * 设备(实测:普通用户跑,重启后 peerid 变空、线路全掉)。
8
8
  *
9
- * 所以这里绕不开一次管理员授权。插件能做的是把整件事自动化:自己下载、自己装、自己拉起,
10
- * 用户只在系统弹出的授权框里确认一次(Touch ID / 输密码)。这是操作系统对「装系统服务」的
11
- * 规矩,不是我们多要一步。
9
+ * 所以这里绕不开一次管理员授权。插件能做的是把整件事自动化:macOS 自己下载二进制、写服务定义;
10
+ * Windows 与 Linux 跑官方的一键安装脚本;用户只在系统弹出的授权框里确认一次(Touch ID / 密码、
11
+ * UAC、polkit)。这是操作系统对「装系统服务」的规矩,不是我们多要一步。
12
12
  *
13
- * 只做 macOS:它的 launchd 服务定义简单、我们也在这套上实测过。Linux 的 systemd 与 Windows
14
- * 的服务注册各自还有一套没验过的细节,先如实报「这一版没接」,不猜着写。
13
+ * 三个平台的本地管理口与绑定链接都由 probe.cjs 只读探测;面板的「装没装」以探测为准,不靠
14
+ * 各平台的文件标记。无图形授权的 Linux 服务器弹不出 polkit 框,会如实报错,不猜着装成功。
15
15
  */
16
16
 
17
17
  const { execFile } = require('node:child_process');
@@ -25,6 +25,8 @@ const BINARY = path.join(INSTALL_DIR, 'NodeBabyLinkService');
25
25
  const PLIST = '/Library/LaunchDaemons/com.iepose.NodeBabyLinkService.plist';
26
26
  const LOG_DIR = path.join(INSTALL_DIR, 'logs');
27
27
  const CDN = 'https://cdn.ionewu.com/upgrade/jdxb';
28
+ const WINDOWS_INSTALLER = 'https://iepose.com/install.ps1';
29
+ const LINUX_INSTALLER = 'https://iepose.com/install.sh';
28
30
  const DOWNLOAD_TIMEOUT_MS = 120_000;
29
31
  /** 授权框等人点:给足三分钟,但别无限挂着。 */
30
32
  const ELEVATE_TIMEOUT_MS = 180_000;
@@ -34,13 +36,20 @@ const START_WAIT_MS = 15_000;
34
36
  function platformKey(platform, arch) {
35
37
  const p = String(platform || process.platform);
36
38
  const a = String(arch || process.arch);
37
- if (p !== 'darwin') return '';
38
- if (a === 'arm64') return 'darwin-arm64';
39
- if (a === 'x64') return 'darwin-x64';
39
+ if (p === 'darwin') {
40
+ if (a === 'arm64') return 'darwin-arm64';
41
+ if (a === 'x64') return 'darwin-x64';
42
+ return '';
43
+ }
44
+ // 官方 Windows 精简版明确不支持 32 位;Linux 的安装脚本按架构自己下载。
45
+ if (p === 'win32') return a === 'x64' ? 'win32-x64' : '';
46
+ if (p === 'linux') return a === 'x64' || a === 'arm64' ? `linux-${a}` : '';
40
47
  return '';
41
48
  }
42
49
 
43
50
  function downloadUrl(key) {
51
+ if (key === 'win32-x64') return WINDOWS_INSTALLER;
52
+ if (key === 'linux-x64' || key === 'linux-arm64') return LINUX_INSTALLER;
44
53
  const arch = key === 'darwin-arm64' ? 'arm64' : 'amd64';
45
54
  return `${CDN}/NodeBabyLinkService.darwin.${arch}.${VERSION}`;
46
55
  }
@@ -56,6 +65,13 @@ function looksLikeMachO(buffer) {
56
65
  return MACHO_MAGICS.has(buffer.readUInt32BE(0));
57
66
  }
58
67
 
68
+ /** 官方安装脚本是纯文本;被强制门户换成网页时当场认出来,别把 HTML 拿去提权执行。 */
69
+ function looksLikeScript(buffer) {
70
+ const text = Buffer.isBuffer(buffer) ? buffer.toString('utf8', 0, Math.min(buffer.length, 4096)) : String(buffer || '');
71
+ if (!text.trim()) return false;
72
+ return !/^\s*<(?:!doctype|html|script|title)\b/i.test(text);
73
+ }
74
+
59
75
  /** `launchctl list <label>`:加载了就有输出,没加载退出码非 0。 */
60
76
  function serviceLoaded(options = {}) {
61
77
  const run = typeof options.run === 'function' ? options.run : defaultRun;
@@ -66,13 +82,14 @@ function serviceLoaded(options = {}) {
66
82
 
67
83
  function defaultRun(file, args, opts = {}) {
68
84
  return new Promise((resolve) => {
69
- execFile(file, args, { timeout: opts.timeoutMs || 10_000, maxBuffer: 1 << 20 }, (err, stdout, stderr) => {
85
+ execFile(file, args, { timeout: opts.timeoutMs || 10_000, maxBuffer: 1 << 20, windowsHide: true }, (err, stdout, stderr) => {
70
86
  resolve({ code: err ? (typeof err.code === 'number' ? err.code : 1) : 0, stdout: String(stdout || ''), stderr: String(stderr || '') });
71
87
  });
72
88
  });
73
89
  }
74
90
 
75
- /** 本机装没装:服务定义与二进制都在,才算装过(只装了一半的照实报没装)。 */
91
+ /** macOS 的文件标记:服务定义与二进制都在,才算装过(只装了一半的照实报没装)。
92
+ * 其它平台的真实状态由本地管理口探测给出,不用这份文件标记。 */
76
93
  function installedSync() {
77
94
  try {
78
95
  return fs.existsSync(PLIST) && fs.existsSync(BINARY);
@@ -106,8 +123,8 @@ function plistBody() {
106
123
  }
107
124
 
108
125
  /**
109
- * 以管理员权限跑一段 shell。macOS 上就是系统自带的授权框(`do shell script ... with
110
- * administrator privileges`);它会弹出 Touch ID / 密码,用户点一下确认,脚本才以 root 跑。
126
+ * 以管理员权限跑一段 shell(macOS)。系统自带的授权框(do shell script ... with
127
+ * administrator privileges)会弹 Touch ID / 密码,用户点一下确认,脚本才以 root 跑。
111
128
  *
112
129
  * 脚本先写到用户自己的临时目录(0700):同一个人能改的只有这一份,跨不过权限边界;写死命令
113
130
  * 串反而要跟一堆引号打架,出错时也看不出哪一步断的。
@@ -126,6 +143,24 @@ function runElevated(script, options = {}) {
126
143
  });
127
144
  }
128
145
 
146
+ /** Windows:Start-Process -Verb RunAs 弹 UAC,等官方安装脚本跑完把退出码透传回来。 */
147
+ function runWindowsScript(file, options = {}) {
148
+ const run = typeof options.run === 'function' ? options.run : defaultRun;
149
+ const args = `-NoProfile -ExecutionPolicy Bypass -File '${String(file).replace(/'/g, "''")}'`;
150
+ const quotedArgs = `'${args.replace(/'/g, "''")}'`;
151
+ const script = `$p = Start-Process -FilePath 'powershell.exe' -ArgumentList ${quotedArgs} -Verb RunAs -Wait -PassThru; exit $p.ExitCode`;
152
+ return run('powershell.exe', ['-NoProfile', '-Command', script], {
153
+ timeoutMs: options.timeoutMs || ELEVATE_TIMEOUT_MS,
154
+ windowsHide: true,
155
+ });
156
+ }
157
+
158
+ /** Linux:pkexec 弹 polkit 授权框,脚本路径作为独立参数传,不经 shell。 */
159
+ function runLinuxScript(file, options = {}) {
160
+ const run = typeof options.run === 'function' ? options.run : defaultRun;
161
+ return run('pkexec', ['bash', file], { timeoutMs: options.timeoutMs || ELEVATE_TIMEOUT_MS });
162
+ }
163
+
129
164
  /**
130
165
  * 装好并拉起来。
131
166
  *
@@ -134,70 +169,121 @@ function runElevated(script, options = {}) {
134
169
  */
135
170
  async function install(options = {}) {
136
171
  const key = options.platformKey || platformKey(options.platform, options.arch);
137
- if (!key) return { ok: false, installed: installedSync(), started: false, error: '这一版只接了 macOS 的自动安装' };
138
- if (installedSync() && await serviceLoaded(options)) {
139
- return { ok: true, installed: true, started: true, error: '' };
172
+ const isMac = key.startsWith('darwin');
173
+ if (!key) {
174
+ return {
175
+ ok: false, installed: installedSync(), started: false,
176
+ error: '这一版只接了 macOS、Windows x64 与 Linux x64/arm64 的自动安装',
177
+ };
140
178
  }
179
+
180
+ let alreadyInstalled = false;
181
+ if (isMac) {
182
+ if (installedSync() && await serviceLoaded(options)) {
183
+ return { ok: true, installed: true, started: true, error: '' };
184
+ }
185
+ } else {
186
+ // Windows / Linux 以本地管理口为准:装过就不再跑官方脚本(它会进入卸载 / 升级菜单)。
187
+ try {
188
+ const probeStatus = typeof options.probeStatus === 'function'
189
+ ? options.probeStatus
190
+ : () => require('./probe.cjs').readStatus(options);
191
+ const snapshot = await probeStatus();
192
+ alreadyInstalled = Boolean(snapshot && snapshot.installed);
193
+ if (alreadyInstalled) return { ok: true, installed: true, started: true, error: '' };
194
+ } catch {
195
+ // 探测失败当作没装,继续走安装;装完还要再探一次才算成功。
196
+ }
197
+ }
198
+
141
199
  const fetchImpl = typeof options.fetchImpl === 'function' ? options.fetchImpl : globalThis.fetch;
142
- if (typeof fetchImpl !== 'function') return { ok: false, installed: installedSync(), started: false, error: '当前环境没有可用的 fetch' };
200
+ if (typeof fetchImpl !== 'function') {
201
+ return { ok: false, installed: alreadyInstalled, started: false, error: '当前环境没有可用的 fetch' };
202
+ }
143
203
 
144
204
  let temp = '';
145
205
  try {
146
206
  const response = await fetchImpl(downloadUrl(key), { redirect: 'follow' });
147
207
  if (!response || response.ok !== true) {
148
- return { ok: false, installed: installedSync(), started: false, error: `下载设备端失败(HTTP ${response && response.status ? response.status : '?'})` };
208
+ return {
209
+ ok: false, installed: alreadyInstalled, started: false,
210
+ error: `下载设备端失败(HTTP ${response && response.status ? response.status : '?'})`,
211
+ };
149
212
  }
150
213
  const buffer = Buffer.from(await response.arrayBuffer());
151
- if (!looksLikeMachO(buffer)) {
152
- return { ok: false, installed: installedSync(), started: false, error: '下载到的不是可执行文件,可能被网络拦截了' };
214
+ if (!(isMac ? looksLikeMachO(buffer) : looksLikeScript(buffer))) {
215
+ return {
216
+ ok: false, installed: alreadyInstalled, started: false,
217
+ error: isMac ? '下载到的不是可执行文件,可能被网络拦截了' : '下载到的不是安装脚本,可能被网络拦截了',
218
+ };
153
219
  }
154
- temp = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-jdxb-bin-')), 'NodeBabyLinkService');
220
+ const name = isMac ? 'NodeBabyLinkService' : (key.startsWith('win32') ? 'install.ps1' : 'install.sh');
221
+ temp = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-jdxb-')), name);
155
222
  fs.writeFileSync(temp, buffer, { mode: 0o700 });
156
223
  } catch (error) {
157
- return { ok: false, installed: installedSync(), started: false, error: `下载设备端失败:${error && error.message ? error.message : String(error)}` };
224
+ return {
225
+ ok: false, installed: alreadyInstalled, started: false,
226
+ error: `下载设备端失败:${error && error.message ? error.message : String(error)}`,
227
+ };
158
228
  }
159
229
 
160
- const script = [
161
- 'set -e',
162
- `mkdir -p '${INSTALL_DIR}' '${LOG_DIR}'`,
163
- `cp '${temp}' '${BINARY}'`,
164
- `chmod 755 '${BINARY}'`,
165
- `cat > '${PLIST}' <<'PLIST_EOF'`,
166
- plistBody(),
167
- 'PLIST_EOF',
168
- `chmod 644 '${PLIST}'`,
169
- `launchctl unload '${PLIST}' 2>/dev/null || true`,
170
- `launchctl load -w '${PLIST}'`,
171
- ].join('\n');
172
-
173
- const elevated = await runElevated(script, options);
230
+ let elevated;
231
+ try {
232
+ if (isMac) {
233
+ const script = [
234
+ 'set -e',
235
+ `mkdir -p '${INSTALL_DIR}' '${LOG_DIR}'`,
236
+ `cp '${temp}' '${BINARY}'`,
237
+ `chmod 755 '${BINARY}'`,
238
+ `cat > '${PLIST}' <<'PLIST_EOF'`,
239
+ plistBody(),
240
+ 'PLIST_EOF',
241
+ `chmod 644 '${PLIST}'`,
242
+ `launchctl unload '${PLIST}' 2>/dev/null || true`,
243
+ `launchctl load -w '${PLIST}'`,
244
+ ].join('\n');
245
+ elevated = await runElevated(script, options);
246
+ } else if (key.startsWith('win32')) {
247
+ elevated = await runWindowsScript(temp, options);
248
+ } else {
249
+ elevated = await runLinuxScript(temp, options);
250
+ }
251
+ } catch (error) {
252
+ elevated = { code: 1, stdout: '', stderr: String(error && error.message ? error.message : error) };
253
+ }
174
254
  try { fs.rmSync(path.dirname(temp), { recursive: true, force: true }); } catch {}
255
+
175
256
  if (elevated.code !== 0) {
176
257
  const detail = String(elevated.stderr || '').trim().split('\n').filter(Boolean).slice(-1)[0] || '';
177
- // 用户点了取消时 osascript 会回 -128;这时别报「安装失败」,说清是他取消了。
178
- const cancelled = /-128|User canceled/i.test(`${elevated.stderr || ''}${elevated.stdout || ''}`);
258
+ // 取消 / 拒绝授权各平台措辞不同:osascript 回 -128,UAC 是 "canceled by the user",
259
+ // polkit 是 "Not authorized" / "dismissed"。统一说清是没通过授权,不是安装本身坏了。
260
+ const cancelled = /-128|user cancel|canceled by the user|not authorized|dismissed/i.test(`${elevated.stderr || ''}${elevated.stdout || ''}`);
179
261
  return {
180
262
  ok: false,
181
- installed: installedSync(),
263
+ installed: alreadyInstalled || installedSync(),
182
264
  started: false,
183
265
  error: cancelled ? '授权被取消,设备端没有安装' : `安装没成功${detail ? `:${detail}` : ''}`,
184
266
  };
185
267
  }
186
268
 
187
- // 脚本以 root 跑完了就当装上了:文件在不在不该由这个进程猜二遍(它也无权读 root 区)。
188
- // 真要用得起来看的是下面这条端口应答。
269
+ // 脚本以管理员权限跑完了就当装上了:真要用得起来看的是下面这条管理口应答。
189
270
  const started = await waitForPort(options);
190
271
  return { ok: started, installed: true, started, error: started ? '' : '设备端装好了,但本地管理口没起来,请查看系统服务状态' };
191
272
  }
192
273
 
193
- /** 装完等管理口应答:`launchctl load` 返回不代表进程已经监听,别装完立刻报没起来。 */
274
+ /** 装完等管理口应答:`launchctl load` / 安装脚本返回不代表进程已经监听。 */
194
275
  async function waitForPort(options = {}) {
195
- const probe = typeof options.probePort === 'function' ? options.probePort : require('./probe.cjs').probePort;
196
- const port = Number(options.port) > 0 ? Number(options.port) : 2080;
276
+ const probeModule = require('./probe.cjs');
277
+ const probe = typeof options.probePort === 'function' ? options.probePort : probeModule.probePort;
278
+ const platform = String(options.platform || process.platform);
279
+ const endpoints = Array.isArray(options.endpoints) ? options.endpoints : probeModule.endpointsFor(platform);
280
+ const candidates = endpoints.length ? endpoints : [{ host: '127.0.0.1', port: Number(options.port) > 0 ? Number(options.port) : 2080 }];
197
281
  const deadline = Date.now() + (Number(options.waitMs) > 0 ? Number(options.waitMs) : START_WAIT_MS);
198
282
  while (Date.now() < deadline) {
199
- const result = await probe(port, { timeoutMs: 1500 });
200
- if (result && result.ok) return true;
283
+ for (const { host, port } of candidates) {
284
+ const result = await probe(port, { host, timeoutMs: 1500 });
285
+ if (result && result.ok) return true;
286
+ }
201
287
  if (typeof options.sleep === 'function') await options.sleep(500);
202
288
  else await new Promise((resolve) => setTimeout(resolve, 500));
203
289
  }
@@ -211,8 +297,13 @@ module.exports = {
211
297
  PLIST,
212
298
  platformKey,
213
299
  downloadUrl,
300
+ looksLikeMachO,
301
+ looksLikeScript,
214
302
  installedSync,
215
303
  serviceLoaded,
304
+ runElevated,
305
+ runWindowsScript,
306
+ runLinuxScript,
216
307
  install,
217
308
  waitForPort,
218
- };
309
+ };
@@ -1,3 +1,4 @@
1
+ // 整包按平台选打包命令:Windows 没有系统 zip,改用自带 tar(见 pack-directory)。
1
2
  // 目录返回真实来源与声明元数据;未知年龄与未公开链接保持空值。
2
3
  'use strict';
3
4
 
@@ -27,6 +28,7 @@ const { sendJson } = require('../shared/http-util');
27
28
  const thirdParty = require('./third-party-extensions');
28
29
  const { metadataOf } = require('./extension-metadata.cjs');
29
30
  const registry = require('../../extension-registry/index.json');
31
+ const { packDirectory } = require('./pack-directory');
30
32
 
31
33
  /** 只有登记了实际扩展 slug 的条目才有官网详情;私装包不凭空获得公开记录。 */
32
34
  function registryMetadata(slug, packageName) {
@@ -354,17 +356,14 @@ async function handleCatalogArchive(_ctx, req, res, root = catalogRoot(), plugin
354
356
  /**
355
357
  * 把一个目录打成 zip 字节(与 `extension-dev.js` 的整包同一条命令)。
356
358
  *
357
- * 用系统的 `zip`:宿主不引第三方压缩库,而 `zip` 三个桌面系统都有。`-X` 去掉多余的扩展属性、
358
- * `-q` 安静、`-r` 递归;从目录里执行、打包 `.`,所以包内路径是相对路径,手机解出来的键与文件
359
- * 清单里的 `path` 对得上。
359
+ * 用系统命令打包,宿主不引第三方压缩库:mac/Linux 用 `zip`,Windows 没有系统 zip,
360
+ * 改用自带的 `tar -a`(按 `.zip` 扩展名选格式)。两条命令都从目录里执行、打包 `.`,
361
+ * 所以包内路径是相对路径,手机解出来的键与文件清单里的 `path` 对得上。
360
362
  */
361
363
  function zipDirectory(directory) {
362
364
  const outFile = path.join(require('node:os').tmpdir(), `dshm-catalog-${process.pid}-${Date.now()}.zip`);
363
365
  try {
364
- require('node:child_process').execFileSync('zip', ['-r', '-q', '-X', outFile, '.'], {
365
- cwd: directory,
366
- stdio: 'pipe',
367
- });
366
+ packDirectory(directory, outFile);
368
367
  return fs.readFileSync(outFile);
369
368
  } finally {
370
369
  try { fs.rmSync(outFile, { force: true }); } catch { /* 临时文件删不掉不影响结果 */ }
@@ -1,3 +1,4 @@
1
+ // 整包按平台选打包命令:Windows 没有系统 zip,改用自带 tar(见 pack-directory)。
1
2
  // 开发包也返回实际声明的用途、来源、年龄与能力,供手动安装前确认。
2
3
  'use strict';
3
4
 
@@ -23,6 +24,7 @@ const path = require('node:path');
23
24
  const { sendJson } = require('../shared/http-util');
24
25
  const { dshHome } = require('../shared/paths');
25
26
  const { metadataOf } = require('./extension-metadata.cjs');
27
+ const { packDirectory } = require('./pack-directory');
26
28
 
27
29
  /** 开发包根目录名。目录不存在时按需建出来 —— 作者要往里放东西。 */
28
30
  const DEV_ROOT_NAME = 'extension-dev';
@@ -267,17 +269,14 @@ async function handleDevArchive(_ctx, req, res) {
267
269
  /**
268
270
  * 把一个目录打成 zip 字节。
269
271
  *
270
- * 用系统的 `zip`(与产包脚本同一条命令):宿主不引第三方压缩库,而 `zip` 三个桌面系统都有。
271
- * `-X` 去掉多余的扩展属性、`-q` 安静、`-r` 递归;从目录里执行、打包 `.`,所以包内路径是
272
- * 相对路径,手机解出来的键与文件清单里的 `path` 对得上。
272
+ * 用系统命令打包,宿主不引第三方压缩库:mac/Linux 用 `zip`,Windows 没有系统 zip,
273
+ * 改用自带的 `tar -a`(按 `.zip` 扩展名选格式)。两条命令都从目录里执行、打包 `.`,
274
+ * 所以包内路径是相对路径,手机解出来的键与文件清单里的 `path` 对得上。
273
275
  */
274
276
  function zipDirectory(directory) {
275
277
  const outFile = path.join(require('node:os').tmpdir(), `dshm-dev-${process.pid}-${Date.now()}.zip`);
276
278
  try {
277
- require('node:child_process').execFileSync('zip', ['-r', '-q', '-X', outFile, '.'], {
278
- cwd: directory,
279
- stdio: 'pipe',
280
- });
279
+ packDirectory(directory, outFile);
281
280
  return fs.readFileSync(outFile);
282
281
  } finally {
283
282
  try { fs.rmSync(outFile, { force: true }); } catch { /* 临时文件删不掉不影响结果 */ }
@@ -0,0 +1,106 @@
1
+ // 用途:订阅固定分发平台的公开反馈 SSE,实时等第一条官方回复,工具与本机控制面共用同一份线程契约。
2
+ 'use strict';
3
+
4
+ const PLATFORM_ORIGIN = 'https://app.wnluo.com';
5
+ const FEEDBACK_EVENTS_PATH = '/api/sdk/feedback/events';
6
+ const DEFAULT_TIMEOUT_MS = 5 * 60_000;
7
+
8
+ /** 与 feedback-read.cjs 同一口径:错误自带 status,调用方照原样带出去。 */
9
+ function feedbackError(message, status) {
10
+ return Object.assign(new Error(message), { status });
11
+ }
12
+
13
+ /** 只认 id 大于水位、作者是官方的 reply;其余帧都不算回复。 */
14
+ function staffReplyOf(event, data, afterMessageId) {
15
+ if (event !== 'reply' || !data) return null;
16
+ let payload = null;
17
+ try { payload = JSON.parse(data); } catch { return null; }
18
+ if (!payload || typeof payload.id !== 'number' || payload.id <= afterMessageId || payload.author !== 'staff') return null;
19
+ return {
20
+ id: payload.id,
21
+ author: 'staff',
22
+ content: typeof payload.content === 'string' ? payload.content : '',
23
+ created_at: typeof payload.created_at === 'string' ? payload.created_at : '',
24
+ };
25
+ }
26
+
27
+ /**
28
+ * 挂 SSE 长连接等官方回复。只读公开事件流,不读凭据、不碰会话内容。
29
+ * 选项:afterMessageId(已见过的最大 id,默认 0)、timeoutMs(默认 5 分钟)。
30
+ * afterMessageId 原样作为 after 查询参数带上(默认 0 也带),让平台从这条之后回放已有回复,
31
+ * 覆盖 submit 后立刻回复、watch 稍后才连上的情况。
32
+ * 超时或服务端提前断流且没有回复时返回 { timedOut: true };HTTP 错误与网络错误抛出。
33
+ */
34
+ async function watchFeedback(threadKey, options = {}) {
35
+ const key = typeof threadKey === 'string' ? threadKey.trim() : '';
36
+ if (!key) throw feedbackError('watch 需要 threadKey', 400);
37
+ const opts = options && typeof options === 'object' ? options : {};
38
+ const afterMessageId = Number.isFinite(opts.afterMessageId) ? opts.afterMessageId : 0;
39
+ const timeoutMs = Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0 ? opts.timeoutMs : DEFAULT_TIMEOUT_MS;
40
+ const controller = new AbortController();
41
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
42
+ let reader = null;
43
+ try {
44
+ const response = await fetch(`${PLATFORM_ORIGIN}${FEEDBACK_EVENTS_PATH}?thread_key=${encodeURIComponent(key)}&after=${afterMessageId}`, {
45
+ method: 'GET',
46
+ headers: { accept: 'text/event-stream' },
47
+ signal: controller.signal,
48
+ });
49
+ if (response.status < 200 || response.status >= 300) {
50
+ let message = '';
51
+ if (typeof response.json === 'function') {
52
+ try {
53
+ const body = await response.json();
54
+ if (body && typeof body.error === 'string') message = body.error.trim();
55
+ } catch { /* 非 JSON 错误体按状态码报 */ }
56
+ }
57
+ throw feedbackError(message || `反馈订阅失败(HTTP ${response.status})`, response.status);
58
+ }
59
+ if (!response.body || typeof response.body.getReader !== 'function') {
60
+ throw feedbackError('反馈订阅没有返回事件流', 502);
61
+ }
62
+ reader = response.body.getReader();
63
+ const decoder = new TextDecoder();
64
+ let buffer = '';
65
+ let event = '';
66
+ let data = '';
67
+ for (;;) {
68
+ const { done, value } = await reader.read();
69
+ if (done) break;
70
+ buffer += decoder.decode(value, { stream: true });
71
+ let index;
72
+ while ((index = buffer.indexOf('\n')) >= 0) {
73
+ let line = buffer.slice(0, index);
74
+ buffer = buffer.slice(index + 1);
75
+ if (line.endsWith('\r')) line = line.slice(0, -1);
76
+ if (line === '') {
77
+ const reply = staffReplyOf(event, data, afterMessageId);
78
+ if (reply) return reply;
79
+ event = '';
80
+ data = '';
81
+ continue;
82
+ }
83
+ if (line.startsWith(':')) continue; // 心跳注释
84
+ const colon = line.indexOf(':');
85
+ const field = colon === -1 ? line : line.slice(0, colon);
86
+ let valueText = colon === -1 ? '' : line.slice(colon + 1);
87
+ if (valueText.startsWith(' ')) valueText = valueText.slice(1);
88
+ if (field === 'event') event = valueText;
89
+ else if (field === 'data') data = data ? `${data}\n${valueText}` : valueText;
90
+ }
91
+ }
92
+ const pending = staffReplyOf(event, data, afterMessageId);
93
+ if (pending) return pending;
94
+ return { timedOut: true };
95
+ } catch (error) {
96
+ if (error && (error.name === 'AbortError' || controller.signal.aborted)) return { timedOut: true };
97
+ throw error;
98
+ } finally {
99
+ clearTimeout(timer);
100
+ if (reader) {
101
+ try { await reader.cancel(); } catch { /* 流已被服务端收掉 */ }
102
+ }
103
+ }
104
+ }
105
+
106
+ module.exports = { watchFeedback };
@@ -1,4 +1,4 @@
1
- // 用途:插件反馈统一提交与读取口;工具和本机面板按线程查看官方回复、继续跟进。
1
+ // 用途:插件反馈统一提交、读取与实时等回复口;工具和本机面板按线程查看官方回复、继续跟进。
2
2
  'use strict';
3
3
 
4
4
  /**
@@ -10,7 +10,8 @@
10
10
  * - **分发平台**:公开反馈接口(`/api/sdk/feedback`)。明确指定设备号时带上那台手机的
11
11
  * 身份;没指定时用这台电脑上的插件安装身份;没配手机时依然能交,受影响手机那几格留空。
12
12
  * 诊断文本作为 text/plain 附件一起发。线程 key 当场回显,可在本机面板或工具里读取
13
- * 官方回复,再带同一个 key 继续补充;线程历史由提交端保留,不写进 App 的反馈列表。
13
+ * 官方回复,再带同一个 key 继续补充;submit 后也可以用 watch 挂长连接实时等官方回复,
14
+ * 不要靠反复 read 轮询。线程历史由提交端保留,不写进 App 的反馈列表。
14
15
  * - **GitHub**:插件代码本身的 bug 可以直接提 PR。这条路依赖用户自己登录 GitHub,
15
16
  * 插件无法代提,所以只把仓库与前提写进说明,由 AI 自己判断走不走。
16
17
  *
@@ -24,6 +25,7 @@
24
25
  const { randomUUID } = require('node:crypto');
25
26
  const { version: COMPONENT_VERSION } = require('../../package.json');
26
27
  const { readFeedback } = require('./feedback-read.cjs');
28
+ const { watchFeedback } = require('./feedback-watch.cjs');
27
29
 
28
30
  const PLATFORM_ORIGIN = 'https://app.wnluo.com';
29
31
  const FEEDBACK_PATH = '/api/sdk/feedback';
@@ -66,7 +68,7 @@ function feedbackChannels() {
66
68
  {
67
69
  kind: 'distribution',
68
70
  name: 'APP 分发系统反馈',
69
- description: '提交到分发平台的公开反馈接口(与 App 里的反馈页同一个)。没配手机也能提交:指定设备号才带那台手机的身份,否则用这台电脑的插件安装身份;诊断文本作 text/plain 附件。提交后给出可复制的线程 key,可在本机面板或工具 read 动作查看官方回复,再用 submit 带 threadKey 继续补充;不会写进 App 的反馈列表。',
71
+ description: '提交到分发平台的公开反馈接口(与 App 里的反馈页同一个)。没配手机也能提交:指定设备号才带那台手机的身份,否则用这台电脑的插件安装身份;诊断文本作 text/plain 附件。提交后给出可复制的线程 key,可在本机面板或工具 watch 动作实时等官方回复,不要反复 read 轮询;需要看历史再 read,用 submit 带 threadKey 继续补充;不会写进 App 的反馈列表。',
70
72
  endpoint: `${PLATFORM_ORIGIN}${FEEDBACK_PATH}`,
71
73
  requiresLogin: false,
72
74
  },
@@ -240,15 +242,15 @@ function registerFeedbackTool(ctx, deps) {
240
242
  ctx.tools.register(defineTool({
241
243
  name: 'dsh_feedback',
242
244
  description: 'Report a real problem with this mobile plugin or the AI-HUB app. '
243
- + 'Feedback routes: (1) the APP distribution platform — `submit` sends the content to it. You do NOT need to find the root cause: describe what you observed, what you already checked, and what is still uncertain. No paired phone is required either; without an explicitly chosen device the plugin submits under its local installation identity, with a text/plain diagnostics attachment and a thread key you can show to the user. Use `read` with the thread key to view the conversation and official replies, then `submit` with the same threadKey to follow up. The local feedback dialog can show these threads; they are not written into the in-app feedback list. '
245
+ + 'Feedback routes: (1) the APP distribution platform — `submit` sends the content to it. You do NOT need to find the root cause: describe what you observed, what you already checked, and what is still uncertain. No paired phone is required either; without an explicitly chosen device the plugin submits under its local installation identity, with a text/plain diagnostics attachment and a thread key you can show to the user. After `submit`, call `watch` with the returned threadKey to wait in real time for the official reply; do NOT repeatedly poll `read` while waiting. Use `read` with the thread key only when you need to review the conversation history, and `submit` with the same threadKey to follow up. The local feedback dialog can show these threads; they are not written into the in-app feedback list. '
244
246
  + '(2) GitHub — code-level bugs can go to https://github.com/WNLUO/dsh-mobile-plugin as a pull request or issue, but that needs the user to be logged into GitHub and is not submitted by this tool. '
245
247
  + 'Use `channels` to list both routes.',
246
248
  parameters: {
247
249
  action: {
248
250
  type: 'string',
249
251
  required: true,
250
- enum: ['channels', 'read', 'submit'],
251
- description: 'channels: list the feedback routes. read: view a thread and replies. submit: open a feedback thread or follow up using threadKey.',
252
+ enum: ['channels', 'read', 'submit', 'watch'],
253
+ description: 'channels: list the feedback routes. read: view a thread and replies. submit: open a feedback thread or follow up using threadKey. watch: after submit, wait on the public event stream for the first official staff reply on that threadKey; do not poll read.',
252
254
  },
253
255
  content: {
254
256
  type: 'string',
@@ -256,7 +258,11 @@ function registerFeedbackTool(ctx, deps) {
256
258
  },
257
259
  threadKey: {
258
260
  type: 'string',
259
- description: 'Required for read. Optional for submit: append to this existing feedback thread instead of opening a new one.',
261
+ description: 'Required for read and watch. Optional for submit: append to this existing feedback thread instead of opening a new one.',
262
+ },
263
+ afterMessageId: {
264
+ type: 'number',
265
+ description: 'Optional for watch: only return a staff reply whose id is greater than this value. Defaults to 0; pass the highest id already seen so an old reply is not returned again.',
260
266
  },
261
267
  deviceId: {
262
268
  type: 'string',
@@ -287,6 +293,8 @@ function registerFeedbackTool(ctx, deps) {
287
293
  submitted: { type: 'boolean' },
288
294
  thread: { type: 'object', additionalProperties: true },
289
295
  threadKey: { type: 'string' },
296
+ reply: { type: 'object', additionalProperties: true },
297
+ timedOut: { type: 'boolean' },
290
298
  message: { type: 'string' },
291
299
  },
292
300
  },
@@ -304,6 +312,12 @@ function registerFeedbackTool(ctx, deps) {
304
312
  const submitted = await submitFeedback(deps, args.content, args.threadKey, args.deviceId);
305
313
  return { action: 'submit', submitted: true, threadKey: submitted.threadKey, message: submitted.message };
306
314
  }
315
+ case 'watch': {
316
+ const reply = await watchFeedback(args.threadKey, { afterMessageId: args.afterMessageId });
317
+ return reply && reply.timedOut
318
+ ? { action: 'watch', threadKey: args.threadKey, timedOut: true }
319
+ : { action: 'watch', threadKey: args.threadKey, reply };
320
+ }
307
321
  default:
308
322
  throw new Error(`未知的 action:${args.action}`);
309
323
  }
@@ -321,6 +335,10 @@ function renderSummary(value) {
321
335
  return `反馈 ${value.threadKey}(${value.thread.status})\n${value.thread.messages.map(message => `[${message.author === 'staff' ? '官方' : '用户'} ${message.created_at}] ${message.content}`).join('\n')}`;
322
336
  case 'submit':
323
337
  return value.message || '已提交反馈。';
338
+ case 'watch':
339
+ return value.reply
340
+ ? `反馈 ${value.threadKey} 收到官方回复(${value.reply.created_at}):${value.reply.content}`
341
+ : `反馈 ${value.threadKey} 还没有官方回复,等官方答复后再继续。`;
324
342
  default:
325
343
  return '完成。';
326
344
  }
@@ -356,4 +374,5 @@ module.exports = {
356
374
  registerFeedbackTool,
357
375
  submissionIdFor,
358
376
  submitFeedback,
377
+ watchFeedback,
359
378
  };