dsh-plugin-dingtalk-bridge 0.3.5 → 0.3.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -26,6 +26,7 @@
26
26
  - **Star / Issue 入口**:面板右上角「使用说明」旁边有 **★ Star** 与 **提交 Issue**,说明卡底部也有同样的链接与 npm 入口,方便反馈问题。
27
27
  - **彩色插件图标**:侧边栏与面板标题使用 3D 机器人图标,宿主提供 `GET /icon` 路由,加载失败时回退单色 SVG。
28
28
  - **授权与去重**:默认 `loginMode=loopback`(浏览器授权,**不需要授权码**);`loginReset=true` 时重新授权会先 `dws auth logout --yes` 退出旧组织,只保留本次登录的组织;也支持手动「退出」。
29
+ - **dws 自动检测 / 安装 / 更新**:插件启动时只做检测,不会偷偷装东西。如果这台机器没有 `dws`,面板顶部会出现一条提示,点 **安装 dws** 即自动执行 `npm install -g dingtalk-workspace-cli`(含 npm 12 会拦掉的 `install.js` 准备步骤),装完自动重新检测并开始接收;已装的话点 **检查更新** 能看到 npm 上的最新版本,再点 **更新到 vX** 升级。npm 源可用 `dwsRegistry` 换成国内镜像。
29
30
  - **演练模式**:`dryRun=true` 时只预览将发送的内容(`dws --dry-run`),不真正发到钉钉,适合先试跑。
30
31
  - **持久化与自愈**:状态存在 `<DSH_HOME>/integrations/dingtalk-bridge/state.json`(tmp + rename 原子写,mode 0600),图片在 `.../media/`;早于 2020 年或超前一天的时间戳重置为当前时间,旧版 `confirmation_required` 失败记录自动清掉。
31
32
 
@@ -41,9 +42,9 @@
41
42
  | --- | --- |
42
43
  | ![确认弹框](docs/images/confirm-modal.png) | ![授权](docs/images/auth-loopback.png) |
43
44
 
44
- | Star / Issue 入口(右上角) |
45
- | --- |
46
- | ![Star 与 Issue 入口](docs/images/star-issue.png) |
45
+ | Star / Issue 入口(右上角) | dws 未安装时的自动安装提示 |
46
+ | --- | --- |
47
+ | ![Star 与 Issue 入口](docs/images/star-issue.png) | ![dws 安装提示](docs/images/dws-install.png) |
47
48
 
48
49
  来源条展开、群 @ 回复气泡、连续多条编号、上下文窗口下拉框:
49
50
 
@@ -85,12 +86,13 @@
85
86
 
86
87
  ## 配置项
87
88
 
88
- 共 28 项,可在「设置 → 插件 → 钉钉消息自动化」里可视化编辑(也可直接改 `cordis.patch.yml` 的 `config`)。
89
+ 共 29 项,可在「设置 → 插件 → 钉钉消息自动化」里可视化编辑(也可直接改 `cordis.patch.yml` 的 `config`)。
89
90
 
90
91
  | 配置 | 类型 / 默认 | 说明 |
91
92
  | --- | --- | --- |
92
93
  | `enabled` | bool / `true` | 总开关,关闭后不启动事件监听、不注册路由。 |
93
- | `dwsPath` | string / `dws` | dws 可执行文件路径;已在 PATH 里就留 `dws`。 |
94
+ | `dwsPath` | string / `dws` | dws 可执行文件路径;已在 PATH 里就留 `dws`。安装成功后插件会自动指向 npm 全局包里的 `vendor/dws.exe`。 |
95
+ | `dwsRegistry` | string / `https://registry.npmjs.org/` | 自动安装 / 更新 dws 时用的 npm 源,只在点「安装 dws」「更新 dws」时生效,可换国内镜像。 |
94
96
  | `profiles` | string[] / `[]` | 只监听这些组织(profile 标识);留空表示跟随 dws 当前登录账号。 |
95
97
  | `listenDirect` | bool / `true` | 是否接收私信。 |
96
98
  | `listenGroupAt` | bool / `true` | 是否接收群 @ 我的消息。 |
@@ -147,6 +149,8 @@
147
149
 
148
150
  | 现象 | 处理 |
149
151
  | --- | --- |
152
+ | 点授权报错 `'dws' 不是内部或外部命令` / `spawn dws ENOENT` | 这台机器没装 dws。面板顶部会自动出现提示卡,点 **安装 dws** 即执行 `npm install -g dingtalk-workspace-cli`(含被 npm 12 拦掉的 `install.js` 步骤),装完自动重新检测并开始接收;没有 npm 就先装 Node.js,或把 `dwsPath` 指到已有的 dws 可执行文件。 |
153
+ | 想升级 dws | 点提示卡或设置页的 **检查更新**(只查 npm 上的版本),发现新版后点 **更新到 vX**;npm 源慢就改 `dwsRegistry`(如 `https://registry.npmmirror.com/`)。 |
150
154
  | 点「钉钉授权」后没有二维码 | **默认 loopback 模式本来就没有二维码**——弹框里是授权说明 + **打开钉钉授权页面** 按钮,浏览器会自动弹出授权页;没弹出就点 **复制链接**。只有 `loginMode=device` 才显示二维码。 |
151
155
  | 授权页要求输入授权码 | 说明 `loginMode` 是 `device`(设备流)。改回 `loopback` 并重启 DSH,即浏览器授权、无需授权码。 |
152
156
  | 每授权一次「实时监听中 · N 个组织」就多一个 | 钉钉登录态按组织累积。`loginReset: true`(默认)会在重新授权前先 `dws auth logout --yes` 退出全部旧组织,只保留本次登录的组织;想把现有组织清干净就点面板右上 **退出** 再重新授权。 |
package/client.js CHANGED
@@ -24,7 +24,7 @@ window.__ModuleLoader__.load({
24
24
  const POLL_MS = 5000
25
25
  const SOFT_POLL_MS = 30000
26
26
  // 与 package.json 的 version 保持一致:宿主上报的 build 前缀对不上,说明 DSH 还在跑旧宿主代码。
27
- const CLIENT_BUILD = '0.3.5'
27
+ const CLIENT_BUILD = '0.3.7'
28
28
  // 源码仓库(GitHub):Star 与 Issue 入口都指向这里
29
29
  const REPO_URL = 'https://github.com/gcggcg/dsh-plugin-dingtalk-bridge'
30
30
  const ISSUES_URL = `${REPO_URL}/issues`
@@ -159,6 +159,18 @@ window.__ModuleLoader__.load({
159
159
  .dsh-dt-srcsearch:focus{border-color:${C.brand}}
160
160
  .dsh-dt-notice{margin:0 20px 8px;padding:8px 12px;border-radius:10px;border:1px dashed ${C.border2};
161
161
  background:${C.layer2};color:${C.sub};font-size:12px;display:flex;align-items:center;gap:6px}
162
+ .dsh-dt-install{margin:0 20px 12px;padding:12px 14px;border-radius:12px;display:flex;align-items:flex-start;gap:11px;
163
+ border:1px solid rgba(217,119,6,.32);background:rgba(217,119,6,.07)}
164
+ .dsh-dt-install[data-tone="error"]{border-color:rgba(220,38,38,.32);background:rgba(220,38,38,.07)}
165
+ .dsh-dt-install[data-tone="busy"]{border-color:rgba(31,111,235,.3);background:rgba(31,111,235,.06)}
166
+ .dsh-dt-install-icon{font-size:16px;line-height:22px;flex:none}
167
+ .dsh-dt-install-title{font-size:13px;font-weight:600;color:${C.text};letter-spacing:.2px}
168
+ .dsh-dt-install-body{margin-top:4px;font-size:12.3px;line-height:1.6;color:${C.sub};word-break:break-word}
169
+ .dsh-dt-install-actions{display:flex;align-items:center;gap:8px;flex:none;flex-wrap:wrap;justify-content:flex-end}
170
+ .dsh-dt-install-log{margin-top:6px;font-size:12px;color:${C.sub}}
171
+ .dsh-dt-install-log summary{cursor:pointer;color:${C.brand}}
172
+ .dsh-dt-install-log pre{margin:6px 0 0;padding:8px 10px;border-radius:8px;background:${C.layer2};
173
+ border:1px solid ${C.border1};font-size:11.5px;line-height:1.5;max-height:180px;overflow:auto;white-space:pre-wrap}
162
174
  .dsh-dt-listbox{margin:0 20px 16px;border:1px solid ${C.border1};border-radius:14px;background:${C.layer1};
163
175
  box-shadow:0 1px 2px rgba(16,24,40,.04);display:flex;flex-direction:column;
164
176
  height:calc(100vh - 330px);min-height:340px;max-height:900px;overflow:hidden}
@@ -1033,6 +1045,10 @@ window.__ModuleLoader__.load({
1033
1045
  '已登录时按钮变成「重新授权」:默认会先退出已登录的组织再登录新的组织(配置 loginReset),所以始终只监听你本次授权的组织,不会越授权越多;想彻底断开就点旁边的「退出」。',
1034
1046
  ],
1035
1047
  ['接收', '插件自动登录 dws 后订阅「私信」与「群 @我」两类事件,消息到达即刻推送到本页,无需刷新。'],
1048
+ [
1049
+ 'dws 环境',
1050
+ '插件依赖 dws CLI 收发钉钉消息。如果这台机器没装 dws,顶部会出现一条提示,点「安装 dws」会自动执行 npm install -g dingtalk-workspace-cli(需要本机有 Node.js),装完自动重新检测并开始接收;已装的话点「检查更新」可以看 npm 上有没有新版本,再点「更新到 vX」升级。npm 源可用配置项 dwsRegistry 换成国内镜像。',
1051
+ ],
1036
1052
  ['消息源', '每条消息记录发送人、来源类型(私信 / 群 @)、群名称与时间;顶部「来源」筛选条按发送人与群聚合统计。'],
1037
1053
  [
1038
1054
  '来源筛选',
@@ -1295,6 +1311,96 @@ window.__ModuleLoader__.load({
1295
1311
  )
1296
1312
  }
1297
1313
 
1314
+ /**
1315
+ * dws 检测 / 安装 / 更新卡片。
1316
+ * 只有用户点按钮才会真的执行 npm install(插件启动时只做「检测」和「查最新版本」)。
1317
+ */
1318
+ function DwsInstallCard(props) {
1319
+ const install = props.install || {}
1320
+ const tool = props.tool || {}
1321
+ const status = String(install.status || 'unknown')
1322
+ const current = String(install.currentVersion || tool.version || '')
1323
+ const latest = String(install.latestVersion || '')
1324
+ const updateAvailable = Boolean(status === 'ready' && latest && current && latest !== current)
1325
+ const ready = Boolean(tool.ok)
1326
+ if (ready && !updateAvailable) return null
1327
+
1328
+ const source = String(install.source || '配置的 npm 源')
1329
+ const busy = props.busy || ''
1330
+ const installing = status === 'installing' || busy === 'install-dws' || busy === 'update-dws'
1331
+ const failed = status === 'error'
1332
+ const tone = failed ? C.error : installing ? C.brand : C.warn
1333
+
1334
+ const headline = installing
1335
+ ? `正在安装 dws${install.targetVersion ? ` v${install.targetVersion}` : ''}…`
1336
+ : failed
1337
+ ? 'dws 安装 / 更新失败'
1338
+ : ready
1339
+ ? `发现新版本 dws v${latest}(当前 v${current})`
1340
+ : '未检测到 dws 命令'
1341
+
1342
+ const body = installing
1343
+ ? '安装过程通常需要 10~60 秒,完成后会自动重新检测并开始接收消息。'
1344
+ : failed
1345
+ ? String(install.log || tool.error || '安装失败,请查看下面的日志。').slice(0, 600)
1346
+ : ready
1347
+ ? `更新后会重启监听,登录状态不受影响。安装来源:${source}`
1348
+ : `这个插件通过 dws CLI 收发钉钉消息。点「安装 dws」会自动执行 npm install -g dingtalk-workspace-cli(来源:${source}),需要本机已安装 Node.js。`
1349
+
1350
+ return h(
1351
+ 'div',
1352
+ { className: 'dsh-dt-install', 'data-tone': failed ? 'error' : installing ? 'busy' : 'warn' },
1353
+ h('div', { className: 'dsh-dt-install-icon', style: { color: tone } }, installing ? '⏳' : failed ? '⚠' : '📦'),
1354
+ h(
1355
+ 'div',
1356
+ { style: { minWidth: 0, flex: 1 } },
1357
+ h('div', { className: 'dsh-dt-install-title' }, headline),
1358
+ h('div', { className: 'dsh-dt-install-body' }, body),
1359
+ failed && install.log && install.log.length > 600
1360
+ ? h('details', { className: 'dsh-dt-install-log' }, h('summary', null, '查看完整日志'), h('pre', null, install.log))
1361
+ : null,
1362
+ install.latestError
1363
+ ? h('div', { className: 'dsh-dt-install-body', style: { opacity: 0.75 } }, `查询最新版本失败:${install.latestError}`)
1364
+ : null,
1365
+ ),
1366
+ h(
1367
+ 'div',
1368
+ { className: 'dsh-dt-install-actions' },
1369
+ ready && updateAvailable
1370
+ ? h(
1371
+ Button,
1372
+ {
1373
+ size: 'sm',
1374
+ variant: 'primary',
1375
+ disabled: installing,
1376
+ onClick: props.onUpdate,
1377
+ title: `更新到 v${latest}`,
1378
+ },
1379
+ installing ? '更新中…' : `更新到 v${latest}`,
1380
+ )
1381
+ : null,
1382
+ !ready
1383
+ ? h(
1384
+ Button,
1385
+ {
1386
+ size: 'sm',
1387
+ variant: 'primary',
1388
+ disabled: installing,
1389
+ onClick: props.onInstall,
1390
+ title: '执行 npm install -g dingtalk-workspace-cli',
1391
+ },
1392
+ installing ? '安装中…' : '安装 dws',
1393
+ )
1394
+ : null,
1395
+ h(
1396
+ Button,
1397
+ { size: 'sm', variant: 'ghost', disabled: installing || busy === 'check-dws-update', onClick: props.onCheck },
1398
+ busy === 'check-dws-update' ? '检查中…' : '检查更新',
1399
+ ),
1400
+ ),
1401
+ )
1402
+ }
1403
+
1298
1404
  function InboxPanel() {
1299
1405
  const { state, error } = useBridge()
1300
1406
  const [tab, setTab] = useState('all')
@@ -1305,6 +1411,7 @@ window.__ModuleLoader__.load({
1305
1411
  const [thresholdDraft, setThresholdDraft] = useState(null)
1306
1412
  const [pendingThreshold, setPendingThreshold] = useState(null)
1307
1413
  const [thresholdError, setThresholdError] = useState('')
1414
+ const [installBusy, setInstallBusy] = useState('')
1308
1415
 
1309
1416
  const messages = useMemo(() => (state && Array.isArray(state.messages) ? state.messages : []), [state])
1310
1417
  const autoReply = Boolean(state && state.autoReply)
@@ -1576,6 +1683,27 @@ window.__ModuleLoader__.load({
1576
1683
  h('span', { className: 'dsh-dt-footnote' }, '欢迎点赞或反馈问题'),
1577
1684
  ),
1578
1685
 
1686
+ h(DwsInstallCard, {
1687
+ install: state && state.install,
1688
+ tool: state && state.tool,
1689
+ busy: installBusy,
1690
+ onInstall: () => {
1691
+ setInstallBusy('install-dws')
1692
+ postAction({ type: 'install-dws' }).finally(() => setInstallBusy(''))
1693
+ },
1694
+ onUpdate: () => {
1695
+ const target = String((state && state.install && state.install.latestVersion) || '')
1696
+ const source = String((state && state.install && state.install.source) || '配置的 npm 源')
1697
+ if (!window.confirm(`将更新 dingtalk-workspace-cli 到 v${target}(来源:${source}),是否继续?`)) return
1698
+ setInstallBusy('update-dws')
1699
+ postAction({ type: 'update-dws' }).finally(() => setInstallBusy(''))
1700
+ },
1701
+ onCheck: () => {
1702
+ setInstallBusy('check-dws-update')
1703
+ postAction({ type: 'check-dws-update' }).finally(() => setInstallBusy(''))
1704
+ },
1705
+ }),
1706
+
1579
1707
  helpOpen ? null : h(
1580
1708
  'div',
1581
1709
  { className: 'dsh-dt-toolbar' },
@@ -2331,6 +2459,28 @@ window.__ModuleLoader__.load({
2331
2459
  : '—',
2332
2460
  ],
2333
2461
  ['dws 版本', state && state.tool && state.tool.version ? state.tool.version : '未检测到'],
2462
+ [
2463
+ 'dws 安装状态',
2464
+ state && state.install
2465
+ ? state.install.status === 'ready'
2466
+ ? `已就绪(v${state.install.currentVersion || state.tool?.version || '?'})${
2467
+ state.install.latestVersion && state.install.latestVersion !== state.install.currentVersion
2468
+ ? `,npm 上最新 v${state.install.latestVersion}`
2469
+ : ''
2470
+ }`
2471
+ : state.install.status === 'installing'
2472
+ ? `安装中(${state.install.targetVersion ? `v${state.install.targetVersion},` : ''}${state.install.source || '...'})`
2473
+ : state.install.status === 'missing'
2474
+ ? '未安装(可点上方「安装 dws」自动安装)'
2475
+ : state.install.status === 'error'
2476
+ ? '安装 / 更新失败(可查看日志后重试)'
2477
+ : '检测中'
2478
+ : '—',
2479
+ ],
2480
+ [
2481
+ 'npm 安装源',
2482
+ state && state.install && state.install.source ? state.install.source : 'https://registry.npmjs.org/',
2483
+ ],
2334
2484
  [
2335
2485
  '宿主版本',
2336
2486
  state && state.build
package/cordis.patch.yml CHANGED
@@ -3,6 +3,7 @@
3
3
  name: dsh-plugin-dingtalk-bridge
4
4
  config:
5
5
  enabled: true
6
+ dwsRegistry: https://registry.npmjs.org/
6
7
  listenDirect: true
7
8
  listenGroupAt: true
8
9
  autoReply: false
Binary file
@@ -1257,7 +1257,7 @@ dws 版本 1.0.68
1257
1257
 
1258
1258
  ### 9.2 可修改的配置项
1259
1259
 
1260
- 以下 28 项定义在 `src/host/config.js`,是配置项与默认值的唯一权威来源。
1260
+ 以下 29 项定义在 `src/host/config.js`,是配置项与默认值的唯一权威来源。
1261
1261
 
1262
1262
  | 配置键 | 类型 | 默认值 | 取值范围 | 改它能解决什么 |
1263
1263
  | --- | --- | --- | --- | --- |
@@ -1289,6 +1289,7 @@ dws 版本 1.0.68
1289
1289
  | `dryRun` | boolean | `false` | — | 演练模式:只 `--dry-run` 预览发送内容,不真正发到钉钉 |
1290
1290
  | `loginMode` | string | `"loopback"` | `loopback` / `device` | 授权方式。`loopback` 用本机浏览器授权(`dws auth login --no-browser --yes`,不需要授权码、不显示二维码);`device` 用设备流(`dws auth login --device --no-browser`,显示二维码 + 授权码,适合无浏览器的远程环境)。见[第 8 章](#8-钉钉授权登录) |
1291
1291
  | `loginReset` | boolean | `true` | `true` / `false` | 重新授权前先退出已登录的组织(`dws auth logout --yes`),只保留本次新授权的组织。关闭后新组织会追加,组织数量只增不减。见 [8.2.3](#823-重新授权与退出登录) |
1292
+ | `dwsRegistry` | string | `"https://registry.npmjs.org/"` | — | 自动安装 / 更新 dws 时使用的 npm 源,只在点「安装 dws」「更新 dws」时生效;国内可换 `https://registry.npmmirror.com/`。见 [10.0](#100-dws-没安装--想升级036) |
1292
1293
 
1293
1294
  模型选择优先级:
1294
1295
 
@@ -1327,6 +1328,29 @@ dws 版本 1.0.68
1327
1328
 
1328
1329
  ## 10. FAQ / 排障
1329
1330
 
1331
+ ### 10.0 dws 没安装 / 想升级(0.3.6)
1332
+
1333
+ 插件通过 `dws` CLI 收发钉钉消息。**换一台没装 dws 的机器时,面板顶部会出现一条提示卡**,不用去命令行折腾:
1334
+
1335
+ | 情形 | 面板表现 | 点哪里 |
1336
+ | --- | --- | --- |
1337
+ | 本机没有 `dws` 命令 | 提示卡「未检测到 dws 命令」,附当前 `dwsPath` 与 npm 源 | **安装 dws** → 自动执行 `npm install -g dingtalk-workspace-cli` |
1338
+ | 正在安装 | 提示卡变蓝色「正在安装 dws vX…」 | 等 10~60 秒,装完自动重新检测并开始接收 |
1339
+ | 装完仍不可用 | 提示卡变红色「dws 安装 / 更新失败」+ 折叠日志 | 展开 **查看完整日志**,多数是网络 / 权限 / 没有 npm |
1340
+ | 已安装,npm 上有新版 | 提示卡「发现新版本 dws vY(当前 vX)」 | **更新到 vY**(会先弹确认框,更新后重启监听,登录态不受影响) |
1341
+ | 已是最新 | 提示卡不显示 | 想手动再查一次就去设置页点 **检查更新** |
1342
+
1343
+ ![dws 未安装时的提示卡](images/dws-install.png)
1344
+
1345
+ 实现要点(便于排障时对照):
1346
+
1347
+ - 插件**启动时只检测、不安装**;`dws --version` 能读出 `x.y.z` 才算就绪,报错文本命中「不是内部或外部命令 / ENOENT / command not found」才判定为「未安装」。
1348
+ - 安装命令固定为 `npm install -g dingtalk-workspace-cli[@版本] --no-fund --no-audit --registry=<dwsRegistry>`;npm 依次尝试 `npm_execpath` → Node 同目录的 `npm.cmd` → PATH 里的 `npm`。
1349
+ - npm 12 默认会拦掉依赖的 `postinstall`,插件会在装完后手动跑一次包内的 `install.js`(`DWS_NO_SKILLS=1`),再用 `npm root -g` 找到 `vendor/dws.exe` 并自动把 `dwsPath` 指过去。
1350
+ - 「检查更新」只发一次 `GET <registry>/dingtalk-workspace-cli/latest`(10 秒超时),不下载任何东西。
1351
+ - 想换国内镜像:配置项 `dwsRegistry` 改成 `https://registry.npmmirror.com/`。
1352
+ - 安装成功后插件会把 `vendor/dws.exe` 的绝对路径写进 `state.json`,**重启后自动沿用**(前提是你没有在配置里显式指定 `dwsPath`),所以即使 npm 全局目录不在 PATH 里也能一直用。
1353
+
1330
1354
  ### 10.1 顶部显示「dws 未就绪」
1331
1355
 
1332
1356
  面板状态行会附带具体错误。按顺序执行:
@@ -1767,6 +1791,9 @@ dws chat +messages-send --as user --group cidAbCdEf123456= --text "收到,下
1767
1791
  | `remove` | `id` | 删除单条消息 |
1768
1792
  | `restart-listeners` | — | 重新检测 dws 并重建全部监听 |
1769
1793
  | `refresh` | — | 重新读取账号与 profile 列表 |
1794
+ | `install-dws` | `version`(可选,空则装 latest) | 执行 `npm install -g dingtalk-workspace-cli[@版本]`,补跑包内 `install.js`,成功后自动重新检测、刷新组织并重启监听。见 [10.0](#100-dws-没安装--想升级036) |
1795
+ | `check-dws-update` | — | 只查 npm 上的最新版本(`GET <dwsRegistry>/dingtalk-workspace-cli/latest`,10 秒超时),不下载任何东西 |
1796
+ | `update-dws` | — | 先查最新版本,再按该版本执行安装(等价 `install-dws` + 版本号) |
1770
1797
 
1771
1798
  响应统一为 `{ ok, ...结果, state }`,客户端用返回的 `state` 直接刷新界面。
1772
1799
 
@@ -1801,6 +1828,7 @@ dws chat +messages-send --as user --group cidAbCdEf123456= --text "收到,下
1801
1828
  | `build` | string | 宿主代码编译标记(如 `0.2.9-20261117T0940`),设置页「宿主版本」显示它;与界面版本不一致时面板头部会多一个 **宿主待重启** 徽标 |
1802
1829
  | `requests` | `Array<{ at, method, path, status, detail }>` | 最近 8 条 API 请求,便于排查写操作被拦、阈值没保存之类的问题 |
1803
1830
  | `lastError` | string | 最近一次失败请求的摘要,如 `POST /api/dingtalk-bridge/action → 403` |
1831
+ | `install` | `{ status, currentVersion, latestVersion, updateAvailable, targetVersion, source, log, latestError, checkedAt }` | dws 安装/更新状态:`status` 为 `unknown` / `ready` / `missing` / `installing` / `error`;`currentVersion` 当前版本、`latestVersion` npm 上最新版本、`updateAvailable` 是否可升级、`targetVersion` 本次安装目标、`source` 使用的 npm 源、`log` 安装日志(失败时界面可展开查看)、`latestError` 查询最新版本失败的原因。见 [10.0](#100-dws-没安装--想升级036) |
1804
1832
 
1805
1833
  ### 12.3 关键常量
1806
1834
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-dingtalk-bridge",
3
- "version": "0.3.5",
3
+ "version": "0.3.7",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "钉钉私信 / 群 @ 消息实时接收、按发送人记录来源、AI 建议回复与自动回复插件",
@@ -13,6 +13,10 @@ export const Config = Schema.object({
13
13
  .default('dws')
14
14
  .description('dws CLI 路径。默认使用 PATH 中的 dws,也可填绝对路径(如 E:\\app\\node\\dws.cmd)。'),
15
15
 
16
+ dwsRegistry: Schema.string()
17
+ .default('https://registry.npmjs.org/')
18
+ .description('自动安装 / 更新 dws 时使用的 npm 源(只在点击「安装 dws」「更新 dws」时生效,可用国内镜像加速)。'),
19
+
16
20
  profiles: Schema.array(Schema.string())
17
21
  .default([])
18
22
  .description('要监听的组织 profile(形如 corpId:userId)。留空表示自动监听当前登录的组织。'),
@@ -1,4 +1,5 @@
1
1
  import { readFile, writeFile, rename, mkdir, unlink, appendFile } from 'node:fs/promises'
2
+ import { existsSync } from 'node:fs'
2
3
  import { homedir } from 'node:os'
3
4
  import { join, dirname } from 'node:path'
4
5
  import { randomUUID } from 'node:crypto'
@@ -19,7 +20,7 @@ import { buildSuggestPrompt, generateSuggestion, formatClock } from './suggest.j
19
20
 
20
21
  export const ROUTE_PREFIX = '/api/dingtalk-bridge'
21
22
  /** 每次改动宿主行为就换个标记:界面与 http-debug.log 都会带上,用来确认「跑的是新代码」。 */
22
- export const HOST_BUILD = '0.3.5-20261117T1335'
23
+ export const HOST_BUILD = '0.3.7-20261117T1445'
23
24
 
24
25
  /** 私信(单聊)全部消息。 */
25
26
  const O2O_KEY = 'user_im_message_receive_o2o_all'
@@ -33,6 +34,27 @@ const MIN_STABLE_MS = 30 * 1000
33
34
  const SUGGEST_CONCURRENCY = 2
34
35
  const BODY_LIMIT = 64 * 1024
35
36
 
37
+ /** dws 的 npm 包名:`npm install -g dingtalk-workspace-cli` 之后就有 `dws` 命令。 */
38
+ const DWS_PACKAGE = 'dingtalk-workspace-cli'
39
+ const DWS_REGISTRY_DEFAULT = 'https://registry.npmjs.org/'
40
+ const INSTALL_TIMEOUT = 300 * 1000
41
+ const INSTALL_LOG_LIMIT = 4000
42
+
43
+ /** 拼 `npm install -g` 的参数:只在用户点「安装 dws」时才会真正执行。 */
44
+ export function buildInstallArgs({ target = '', registry = DWS_REGISTRY_DEFAULT } = {}) {
45
+ const version = String(target ?? '').trim().replace(/^v/, '')
46
+ const spec = version === '' ? DWS_PACKAGE : `${DWS_PACKAGE}@${version}`
47
+ const source = String(registry ?? '').trim() || DWS_REGISTRY_DEFAULT
48
+ return ['install', '-g', spec, '--no-fund', '--no-audit', `--registry=${source}`]
49
+ }
50
+
51
+ /** 判断命令失败是不是「根本没有这个命令」(而不是参数错、未登录之类的业务错误)。 */
52
+ export function looksLikeMissingCommand(text) {
53
+ return /ENOENT|not recognized|不是内部或外部命令|command not found|无法将.{0,20}识别|No such file/i.test(
54
+ String(text ?? ''),
55
+ )
56
+ }
57
+
36
58
  function asBool(value, fallback) {
37
59
  return typeof value === 'boolean' ? value : fallback
38
60
  }
@@ -301,6 +323,7 @@ export class DingTalkBridgeService {
301
323
  this.config = {
302
324
  enabled: asBool(config.enabled, true),
303
325
  dwsPath: asString(config.dwsPath, 'dws').trim() || 'dws',
326
+ dwsRegistry: asString(config.dwsRegistry, DWS_REGISTRY_DEFAULT).trim() || DWS_REGISTRY_DEFAULT,
304
327
  profiles: asStringArray(config.profiles),
305
328
  listenDirect: asBool(config.listenDirect, true),
306
329
  listenGroupAt: asBool(config.listenGroupAt, true),
@@ -353,6 +376,19 @@ export class DingTalkBridgeService {
353
376
  }
354
377
 
355
378
  this.tool = { ok: false, version: '', error: '', checkedAt: 0 }
379
+ // dws 的安装/更新状态:只有用户点「安装 dws」「更新 dws」才会真的执行 npm 命令。
380
+ this.install = {
381
+ status: 'unknown',
382
+ currentVersion: '',
383
+ latestVersion: '',
384
+ updateAvailable: false,
385
+ targetVersion: '',
386
+ source: '',
387
+ log: '',
388
+ latestError: '',
389
+ checkedAt: 0,
390
+ }
391
+ this.installPromise = null
356
392
  this.login = { status: 'idle', code: '', url: '', qr: '', startedAt: 0, error: '', message: '' }
357
393
  this.loginChild = null
358
394
  this.listeners = new Map()
@@ -448,6 +484,8 @@ export class DingTalkBridgeService {
448
484
  }
449
485
  this.startAllListeners()
450
486
  this.refreshVision().catch(() => {})
487
+ // 顺手查一下 npm 上的最新版本(只查不装),让「更新 dws」按钮能显示目标版本。
488
+ this.checkLatestDws().catch(() => {})
451
489
  this.broadcast()
452
490
  }
453
491
 
@@ -477,6 +515,168 @@ export class DingTalkBridgeService {
477
515
 
478
516
  // ------------------------------------------------------------------- 外部命令
479
517
 
518
+ /** 安装/更新 dws 时使用的 npm 源。 */
519
+ registry() {
520
+ return String(this.config.dwsRegistry ?? '').trim() || DWS_REGISTRY_DEFAULT
521
+ }
522
+
523
+ setInstall(patch) {
524
+ this.install = { ...this.install, ...patch, checkedAt: Date.now() }
525
+ this.broadcast()
526
+ return this.install
527
+ }
528
+
529
+ /**
530
+ * 查 npm 上 dingtalk-workspace-cli 的最新版本(只查不装)。
531
+ * 换源时也走这里,所以界面上「检查更新」按钮可以随时点。
532
+ */
533
+ async checkLatestDws() {
534
+ const base = this.registry().replace(/\/+$/, '')
535
+ const url = `${base}/${DWS_PACKAGE}/latest`
536
+ try {
537
+ const res = await fetch(url, {
538
+ headers: { accept: 'application/json' },
539
+ signal: AbortSignal.timeout(10_000),
540
+ })
541
+ if (!res.ok) throw new Error(`HTTP ${res.status}`)
542
+ const data = await res.json()
543
+ const version = String(data?.version ?? '').trim()
544
+ if (!/^\d+\.\d+\.\d+/.test(version)) throw new Error('返回里没有版本号')
545
+ const current = this.install.currentVersion || this.tool.version || ''
546
+ return this.setInstall({
547
+ latestVersion: version,
548
+ latestError: '',
549
+ updateAvailable: Boolean(current && version !== current && this.tool.ok),
550
+ })
551
+ } catch (error) {
552
+ this.setInstall({ latestError: String(error?.message || error) })
553
+ return this.install
554
+ }
555
+ }
556
+
557
+ /** 依次尝试 npm_execpath、node 同目录的 npm、PATH 里的 npm。 */
558
+ async findNpm() {
559
+ const candidates = []
560
+ const execPath = String(process.env.npm_execpath ?? '').trim()
561
+ if (execPath !== '' && !/\.(?:c|m)?js$/i.test(execPath)) candidates.push(execPath)
562
+ const nodeDir = dirname(process.execPath)
563
+ if (process.platform === 'win32') {
564
+ candidates.push(join(nodeDir, 'npm.cmd'))
565
+ } else {
566
+ candidates.push(join(nodeDir, 'bin', 'npm'), join(nodeDir, 'npm'))
567
+ }
568
+ candidates.push('npm')
569
+ for (const candidate of candidates) {
570
+ const probe = await runDws(candidate, ['--version'], { timeoutMs: 15_000 })
571
+ if (probe.code === 0 && /\d+\.\d+\.\d+/.test(`${probe.stdout}${probe.stderr}`)) {
572
+ return candidate
573
+ }
574
+ }
575
+ return ''
576
+ }
577
+
578
+ /** `npm root -g`:全局 node_modules,用来找安装后的包目录。 */
579
+ async npmGlobalRoot(npm) {
580
+ const result = await runDws(npm, ['root', '-g'], { timeoutMs: 20_000 })
581
+ const text = `${result.stdout}`.trim().split(/\r?\n/).filter((line) => line.trim() !== '')
582
+ return result.code === 0 ? String(text.at(-1) ?? '').trim() : ''
583
+ }
584
+
585
+ /** 用户点「安装 dws」/「更新 dws」才会走到这里。 */
586
+ async installDws(target = '') {
587
+ if (this.installPromise) return this.installPromise
588
+ this.installPromise = this.runInstallDws(String(target ?? '').trim()).finally(() => {
589
+ this.installPromise = null
590
+ })
591
+ return this.installPromise
592
+ }
593
+
594
+ async runInstallDws(target) {
595
+ const registry = this.registry()
596
+ const npm = await this.findNpm()
597
+ if (npm === '') {
598
+ this.setInstall({
599
+ status: 'error',
600
+ source: registry,
601
+ targetVersion: target,
602
+ log: '没有找到 npm,无法自动安装 dws。请先安装 Node.js(自带 npm),或在配置项 dwsPath 里填一个已存在的 dws 路径。',
603
+ })
604
+ return { ok: false, error: 'npm not found' }
605
+ }
606
+
607
+ this.setInstall({
608
+ status: 'installing',
609
+ source: registry,
610
+ targetVersion: target,
611
+ log: `正在执行:${npm} ${buildInstallArgs({ target, registry }).join(' ')}`,
612
+ })
613
+
614
+ const args = buildInstallArgs({ target, registry })
615
+ const result = await runDws(npm, args, { timeoutMs: INSTALL_TIMEOUT })
616
+ const output = `${result.stdout}\n${result.stderr}`.trim()
617
+ if (result.code !== 0) {
618
+ this.setInstall({
619
+ status: 'error',
620
+ log: output.slice(-INSTALL_LOG_LIMIT) || describeFailure(result),
621
+ })
622
+ return { ok: false, error: describeFailure(result) }
623
+ }
624
+
625
+ const root = await this.npmGlobalRoot(npm)
626
+ const pkgDir = join(root || join(dirname(process.execPath), 'node_modules'), DWS_PACKAGE)
627
+ // npm 12 默认会拦掉依赖的 postinstall(钉钉包靠 install.js 准备可执行文件),
628
+ // 所以这里手动补跑一次 install.js,否则装完可能仍然找不到可用的 dws。
629
+ let postinstallLog = ''
630
+ const postinstall = join(pkgDir, 'install.js')
631
+ try {
632
+ await readFile(postinstall)
633
+ const prepared = await runDws(process.execPath, [postinstall], {
634
+ cwd: pkgDir,
635
+ timeoutMs: 180_000,
636
+ env: { ...process.env, DWS_NO_SKILLS: '1' },
637
+ })
638
+ postinstallLog = `${prepared.stdout}\n${prepared.stderr}`.trim().slice(-1200)
639
+ if (prepared.code !== 0) postinstallLog = `install.js 退出码 ${prepared.code}\n${postinstallLog}`
640
+ } catch {
641
+ // 没有 install.js 说明这个版本不需要准备步骤。
642
+ }
643
+
644
+ // 有的版本把真正的可执行文件放在 vendor/ 下,优先用它(避免 cmd 垫片再绕一层)。
645
+ const vendor = join(pkgDir, 'vendor', process.platform === 'win32' ? 'dws.exe' : 'dws')
646
+ const installed = await runDws(vendor, ['--version'], { timeoutMs: 20_000 })
647
+ if (installed.code === 0) this.config.dwsPath = vendor
648
+
649
+ await this.checkTool()
650
+ if (!this.tool.ok) {
651
+ this.setInstall({
652
+ status: 'error',
653
+ log: `${output.slice(-INSTALL_LOG_LIMIT)}\n\n${postinstallLog}\n\n安装完成但 dws 仍不可用:${this.tool.error}`.trim(),
654
+ })
655
+ return { ok: false, error: this.tool.error }
656
+ }
657
+
658
+ this.setInstall({
659
+ status: 'ready',
660
+ currentVersion: this.tool.version,
661
+ latestVersion: target.replace(/^v/, '') || this.install.latestVersion,
662
+ updateAvailable: false,
663
+ log: `已安装 dws v${this.tool.version}(来源:${registry})`,
664
+ })
665
+ await this.refreshProfiles()
666
+ this.startAllListeners()
667
+ return { ok: true, version: this.tool.version }
668
+ }
669
+
670
+ /** 「更新 dws」:先查最新版,再按版本号安装。 */
671
+ async updateDws() {
672
+ const latest = await this.checkLatestDws()
673
+ const target = String(latest?.latestVersion ?? '').trim()
674
+ if (target === '') {
675
+ return { ok: false, error: latest?.latestError || '查询最新版本失败,请检查网络或 npm 源' }
676
+ }
677
+ return this.installDws(target)
678
+ }
679
+
480
680
  async checkTool() {
481
681
  const result = await runDws(this.config.dwsPath, ['--version'], { timeoutMs: 15000 })
482
682
  const output = `${result.stdout}\n${result.stderr}`.trim()
@@ -487,6 +687,22 @@ export class DingTalkBridgeService {
487
687
  error: result.code === 0 ? '' : describeFailure(result),
488
688
  checkedAt: Date.now(),
489
689
  }
690
+ const missing = !this.tool.ok && looksLikeMissingCommand(output)
691
+ const current = version || this.install.currentVersion || ''
692
+ this.install = {
693
+ ...this.install,
694
+ status: this.tool.ok ? 'ready' : missing ? 'missing' : 'error',
695
+ currentVersion: current,
696
+ updateAvailable: Boolean(
697
+ this.tool.ok && current && this.install.latestVersion && this.install.latestVersion !== current,
698
+ ),
699
+ log: this.tool.ok
700
+ ? this.install.log
701
+ : missing
702
+ ? `未检测到 dws 命令(当前配置:${this.config.dwsPath})。点击「安装 dws」会自动执行 npm install -g ${DWS_PACKAGE}(来源:${this.registry()})。`
703
+ : this.tool.error,
704
+ checkedAt: Date.now(),
705
+ }
490
706
  return this.tool
491
707
  }
492
708
 
@@ -2135,6 +2351,25 @@ export class DingTalkBridgeService {
2135
2351
  return { ok: true }
2136
2352
  }
2137
2353
 
2354
+ case 'install-dws': {
2355
+ const result = await this.installDws(String(payload.version ?? ''))
2356
+ return { ...result, state: this.snapshot() }
2357
+ }
2358
+
2359
+ case 'check-dws-update': {
2360
+ const install = await this.checkLatestDws()
2361
+ return {
2362
+ ok: install.latestError === '',
2363
+ error: install.latestError,
2364
+ state: this.snapshot(),
2365
+ }
2366
+ }
2367
+
2368
+ case 'update-dws': {
2369
+ const result = await this.updateDws()
2370
+ return { ...result, state: this.snapshot() }
2371
+ }
2372
+
2138
2373
  default:
2139
2374
  return { ok: false, error: `unknown action: ${type}` }
2140
2375
  }
@@ -2171,6 +2406,7 @@ export class DingTalkBridgeService {
2171
2406
  build: HOST_BUILD,
2172
2407
  started: this.started,
2173
2408
  tool: this.tool,
2409
+ install: this.install,
2174
2410
  selfName: this.state.selfName,
2175
2411
  currentProfile: this.state.currentProfile,
2176
2412
  profiles: this.state.profiles,
@@ -2307,6 +2543,13 @@ export class DingTalkBridgeService {
2307
2543
  if (typeof payload.windowMessages === 'number' && payload.windowMessages >= 2 && payload.windowMessages <= 20) {
2308
2544
  this.config.windowMessages = Math.round(payload.windowMessages)
2309
2545
  }
2546
+ // 上次自动安装记下的 dws 路径:只在用户没显式配置(仍为默认 'dws')时采用,
2547
+ // 并且必须真的存在,否则继续用 PATH 里的 dws。
2548
+ if (typeof payload.dwsPath === 'string' && payload.dwsPath.trim() !== '') {
2549
+ const saved = payload.dwsPath.trim()
2550
+ const configured = this.config.dwsPath
2551
+ if ((configured === 'dws' || configured === '') && existsSync(saved)) this.config.dwsPath = saved
2552
+ }
2310
2553
  // 恢复每个来源的滑动窗口;老存档没有这一段,就等新消息进来再重建。
2311
2554
  this.restoreWindows(payload.windows)
2312
2555
  }
@@ -2323,6 +2566,9 @@ export class DingTalkBridgeService {
2323
2566
  autoReplyAt: Number(this.state.autoReplyAt) || 0,
2324
2567
  minConfidence: this.config.minConfidence,
2325
2568
  windowMessages: this.config.windowMessages,
2569
+ // 自动安装后 dwsPath 会指向 npm 全局包里的 vendor 可执行文件;记下来,
2570
+ // 否则重启后 PATH 里没有 dws 又会退回「未安装」。
2571
+ dwsPath: this.config.dwsPath,
2326
2572
  selfName: this.state.selfName,
2327
2573
  titles: Object.fromEntries([...this.titleCache.entries()].filter(([, value]) => value !== '')),
2328
2574
  messages: this.state.messages.slice(0, this.config.maxInbox),