dsh-chrome-bridge 1.15.2 → 1.16.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/README.md CHANGED
@@ -4,6 +4,9 @@ A DeepSeek Harness (DSH) plugin that drives the Chrome you already use: real cli
4
4
 
5
5
  让 DSH 直接操作你正在用的 Chrome:真点击、真输入,页面里看得到光标,登录状态都在。提供 12 个 `browser_*` 工具,走 native messaging 和 Chrome 调试接口,不开监听端口。
6
6
 
7
+ Pages the agent opens go into a separate background window of your Chrome, so your own window keeps its tabs and focus.
8
+ agent 新开的页放进你 Chrome 里一个单独的后台窗口,你自己的窗口不多标签页、焦点不动。
9
+
7
10
  ## Install / 安装
8
11
 
9
12
  1. In DSH, open **Plugins**, click **Add plugin**, enter `dsh-chrome-bridge`, then restart DSH.
package/client.js CHANGED
@@ -2,7 +2,7 @@
2
2
  * dsh-chrome-bridge 的网页端:DSH「插件」页里我们这张卡的设置页。
3
3
  *
4
4
  * 连接状态(扩展 / 本地宿主、版本、正在控制哪些标签页)+ 全部松手
5
- * 两个开关:允许 DSH 控制浏览器(这里只能关)、页面里显示 DSH 光标
5
+ * 三个开关:允许 DSH 控制浏览器(这里只能关)、页面里显示 DSH 光标、新页开在单独窗口
6
6
  * 没连上时:差哪一步、一键帮你打开安装页
7
7
  *
8
8
  * 数据全走插件自己挂在 DSH webServer 上的路由(plugin/panel.js),每 2.5 秒刷一次。
@@ -56,6 +56,9 @@ window.__ModuleLoader__.load({
56
56
  resumeInChrome: '要恢复,请点 Chrome 工具栏上的 DSH Bridge 图标,打开「允许 DSH 控制浏览器」。',
57
57
  showCursor: '页面里显示 DSH 光标',
58
58
  showCursorHint: '关掉只是不画光标,点击、输入照做。',
59
+ ownWindow: '新页开在单独窗口',
60
+ ownWindowHint: 'DSH 新开的页放进一个单独的 Chrome 窗口(登录状态照样在),不往你正在用的窗口里塞标签页、不抢焦点。关掉就开在你当前窗口的后台。',
61
+ ownWindowOld: 'Chrome 里的扩展更新到 1.13 后才有这个开关;现在新页开在你当前窗口的后台。',
59
62
  outdated: 'Chrome 里的扩展版本较旧,更新后才能在这里切换开关。',
60
63
  setupTitle: '还差一步:把扩展装进 Chrome',
61
64
  setupStoreTitle: '扩展装了,但没连上',
@@ -98,6 +101,9 @@ window.__ModuleLoader__.load({
98
101
  resumeInChrome: 'To resume, click the DSH Bridge icon in Chrome\'s toolbar and turn on "Allow DSH to control the browser".',
99
102
  showCursor: 'Show the DSH cursor on pages',
100
103
  showCursorHint: 'Off only hides the cursor; clicks and typing still happen.',
104
+ ownWindow: 'Open new pages in a separate window',
105
+ ownWindowHint: 'Pages DSH opens go into their own Chrome window (same profile, so your logins work) instead of piling tabs into the window you are using, and never take focus. Off: they open as background tabs in your current window.',
106
+ ownWindowOld: 'This switch needs extension 1.13 or newer in Chrome; for now new pages open as background tabs in your current window.',
101
107
  outdated: 'The extension in Chrome is outdated; update it to change these switches here.',
102
108
  setupTitle: 'One step left: add the extension to Chrome',
103
109
  setupStoreTitle: 'The extension is installed but not connected',
@@ -294,7 +300,13 @@ window.__ModuleLoader__.load({
294
300
  h('div', { className: 'dcb-main' },
295
301
  h('div', { className: 'dcb-title' }, t('showCursor')),
296
302
  h('p', { className: 'dcb-hint' }, t('showCursorHint'))),
297
- h(Toggle, { label: t('showCursor'), checked: state.showCursor !== false, disabled: !can, onChange: (on) => run({ action: 'cursor', on }) }))) : null
303
+ h(Toggle, { label: t('showCursor'), checked: state.showCursor !== false, disabled: !can, onChange: (on) => run({ action: 'cursor', on }) })),
304
+ // 商店里还没更新的老扩展没有这个设置(state 里没有 ownWindow):照实说,开关不给点
305
+ state.outdated ? null : h('div', { className: 'dcb-row' },
306
+ h('div', { className: 'dcb-main' },
307
+ h('div', { className: 'dcb-title' }, t('ownWindow')),
308
+ h('p', { className: 'dcb-hint' }, 'ownWindow' in state ? t('ownWindowHint') : t('ownWindowOld'))),
309
+ h(Toggle, { label: t('ownWindow'), checked: state.ownWindow !== false && 'ownWindow' in state, disabled: !can || !('ownWindow' in state), onChange: (on) => run({ action: 'window', on }) }))) : null
298
310
 
299
311
  const notes = [
300
312
  error && !state ? { tone: 'err', text: t('unreachable') } : null,
package/index.js CHANGED
@@ -263,10 +263,20 @@ function forgetTab(id) {
263
263
  for (const [k, v] of currentTab) if (v === Number(id)) currentTab.delete(k)
264
264
  }
265
265
 
266
+ /**
267
+ * 用户正在看的那一页。窗口不止一个时每个窗口都有一个 active:先挑用户最后在用的窗口里的,
268
+ * 再挑不在 DSH 干活窗口里的。老扩展不给 focused / agentWindow,就退回第一个 active(以前的做法)。
269
+ */
270
+ function userTab(tabs) {
271
+ return tabs.find((t) => t.active && t.focused) ||
272
+ tabs.find((t) => t.active && !t.agentWindow) ||
273
+ tabs.find((t) => t.active)
274
+ }
275
+
266
276
  async function resolveTab(tab) {
267
277
  if (tab !== undefined && tab !== null && tab !== '') {
268
278
  if (String(tab) === 'active') {
269
- const active = (await call('tabs')).find((t) => t.active)
279
+ const active = userTab(await call('tabs'))
270
280
  if (!active) throw new Error('没有活动标签页')
271
281
  rememberTab(active.id)
272
282
  return active.id
@@ -491,11 +501,12 @@ export function apply(ctx, config) {
491
501
  name: 'browser_tabs',
492
502
  description:
493
503
  '列出 / 查找 / 打开 / 关闭 / 切换 Chrome 标签页。其它 browser_* 工具都要 tab 参数,先用它拿 id。' +
494
- '只对用户真实浏览器里已存在的页面生效,不会新开一个干净的浏览器。',
504
+ '用的是用户真实的 Chrome(登录状态都在),不会新开一个干净的浏览器。' +
505
+ 'open 新开的页默认放进一个单独的「DSH 干活窗口」,在后台、不抢用户焦点,用户正在看的页面不受影响。',
495
506
  parameters: {
496
507
  action: {
497
508
  type: 'string', required: true, enum: ['list', 'find', 'open', 'close', 'activate'],
498
- description: 'list 全部;find 按关键词过滤标题/URL;open 新开;close 关掉;activate 切到前台',
509
+ description: 'list 全部;find 按关键词过滤标题/URL;open 新开(默认进单独的干活窗口);close 关掉;activate 切到前台(会把那个窗口带到用户眼前,没被要求就别用)',
499
510
  },
500
511
  query: { type: 'string', description: 'action=find 时的关键词(匹配标题或 URL)' },
501
512
  url: { type: 'string', description: 'action=open 时要打开的网址' },
@@ -507,9 +518,11 @@ export function apply(ctx, config) {
507
518
  switch (args.action) {
508
519
  case 'list': {
509
520
  const tabs = await call('tabs')
521
+ const mine = userTab(tabs)
510
522
  const lines = tabs.map((t) =>
511
- `${t.active ? '*' : ' '} ${String(t.id).padStart(5)} ${(t.title || '').slice(0, 50)} — ${t.url.slice(0, 80)}`)
512
- return { text: lines.join('\n') || '(没有标签页)' }
523
+ `${t === mine ? '*' : ' '} ${String(t.id).padStart(5)} ${(t.title || '').slice(0, 50)} — ${t.url.slice(0, 80)}${t.agentWindow ? '(DSH 干活窗口)' : ''}`)
524
+ const text = lines.join('\n') || '(没有标签页)'
525
+ return { text: lines.length ? `${text}\n(* = 用户正在看的页)` : text }
513
526
  }
514
527
  case 'find': {
515
528
  const q = String(args.query || '').toLowerCase()
@@ -523,7 +536,8 @@ export function apply(ctx, config) {
523
536
  if (!args.url) throw new Error('action=open 需要 url')
524
537
  const r = await call('open', { url: args.url })
525
538
  rememberTab(r.tabId)
526
- return { text: `已打开标签页 ${r.tabId}:${r.url}` }
539
+ const where = r.window === 'agent' ? '(在单独的 DSH 干活窗口里,后台打开,没打扰用户正在看的页)' : '(后台标签页)'
540
+ return { text: `已打开标签页 ${r.tabId}${where}:${r.url}` }
527
541
  }
528
542
  case 'close': {
529
543
  const tabId = await resolveTab(args.tab)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-chrome-bridge",
3
- "version": "1.15.2",
3
+ "version": "1.16.0",
4
4
  "description": "DSH plugin: native browser_* tools that drive the Chrome you are already using, over native messaging + CDP. No WebSocket, no port, no Connect button. The native host and the MV3 extension ship inside this package and are installed automatically on first load; the one step left is adding the DSH Bridge extension to Chrome, from the Chrome Web Store or as the bundled unpacked copy. Until then browser_* tools fail loudly with those exact steps.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/panel.js CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * DSH 插件页里那张设置卡的后端:一条 HTTP 路由,挂在 DSH 自己的 webServer 上。
3
3
  *
4
- * GET /dsh-chrome-bridge/panel → 状态(连没连上、扩展版本、正在控制几个标签页、两个开关)
5
- * POST /dsh-chrome-bridge/panel {action} → pause(只能暂停)/ cursor / releaseAll / install,回新状态
4
+ * GET /dsh-chrome-bridge/panel → 状态(连没连上、扩展版本、正在控制几个标签页、三个开关)
5
+ * POST /dsh-chrome-bridge/panel {action} → pause(只能暂停)/ cursor / window / releaseAll / install,回新状态
6
6
  *
7
7
  * 页面(client.js)跑在 DSH 的网页端,只能走 HTTP;这里再转成 socket 上的 `panel` 操作。
8
8
  * webServer 本身不做鉴权,而用户的 Chrome 里随便哪个网页都摸得到 127.0.0.1,所以自己把门:
@@ -115,6 +115,9 @@ export function panelHandler({ call, sock, origin, trace = () => {} }) {
115
115
  case 'cursor':
116
116
  await call('panel', { action: 'cursor', on: !!body.on }, 8000)
117
117
  break
118
+ case 'window':
119
+ await call('panel', { action: 'window', on: !!body.on }, 8000)
120
+ break
118
121
  case 'releaseAll':
119
122
  await call('panel', { action: 'releaseAll' }, 15000)
120
123
  break
package/vendor/cb CHANGED
@@ -16,7 +16,8 @@
16
16
  * cb network [tab] [--limit 40] [--filter 关键词] [--reload 先刷新再看] [--clear]
17
17
  * cb record [tab] [--ms 5000] [--out 目录] [--width 900] # 录一段 screencast 帧(做演示 GIF 用)
18
18
  * cb cursor <tab> move|click|hide [x] [y]
19
- * cb open <url> [--front] 默认**后台**开页(不抢你当前标签页)
19
+ * cb open <url> [--front] 默认开进单独的干活窗口、**后台**(不抢你当前标签页)
20
+ * cb window [on|off] 新页开在单独窗口(on,默认)还是当前窗口后台(off);不给参数就看现在是哪种
20
21
  * cb close <tab> / cb attach|detach <tab>
21
22
  * cb cdp <tab> <方法> [json参数]
22
23
  * cb text <tab> [选择器] 页面可见文字(默认整页)
@@ -208,6 +209,17 @@ async function main() {
208
209
  out(`扩展 v${r.version} id ${r.id}`, r)
209
210
  return
210
211
  }
212
+ case 'window': {
213
+ // 和弹窗、DSH 设置页里的「新页开在单独窗口」是同一个开关
214
+ const on = rest[0]
215
+ if (on && on !== 'on' && on !== 'off') die('用法: cb window [on|off]')
216
+ // 先看扩展认不认这个开关:老扩展收到 window 动作只会报「不认识的 action」
217
+ let r = await call('panel', {})
218
+ if (!('ownWindow' in r)) die(`扩展版本较旧(v${r.version}),没有这个开关(要 1.13 以上)`)
219
+ if (on) r = await call('panel', { action: 'window', on: on === 'on' })
220
+ out(`新页开在:${r.ownWindow ? '单独的干活窗口' : '当前窗口(后台标签页)'}`, r)
221
+ return
222
+ }
211
223
  case 'reload': {
212
224
  const r = await call('reload')
213
225
  out('扩展已触发重载(1 秒后再跑 cb status 确认)', r)
@@ -215,7 +227,7 @@ async function main() {
215
227
  }
216
228
  case 'tabs': {
217
229
  const tabs = await call('tabs')
218
- const lines = tabs.map(t => `${t.active ? '*' : ' '} ${String(t.id).padStart(5)} ${t.attached ? '🔗' : ' '} ${(t.title || '').slice(0, 48)} — ${t.url.slice(0, 70)}`)
230
+ const lines = tabs.map(t => `${t.active ? '*' : ' '} ${String(t.id).padStart(5)} ${t.attached ? '🔗' : ' '} ${(t.title || '').slice(0, 48)} — ${t.url.slice(0, 70)}${t.agentWindow ? '(DSH 干活窗口)' : ''}`)
219
231
  out(lines.join('\n'), tabs)
220
232
  return
221
233
  }
@@ -429,10 +441,10 @@ async function main() {
429
441
  return
430
442
  }
431
443
  case 'open': {
432
- // 默认后台开页 —— 不抢用户当前标签页。想看它跳出来就加 --front
444
+ // 默认开进 DSH 的干活窗口(后台)—— 不抢用户当前标签页。想看它跳出来就加 --front(开在当前窗口前台)
433
445
  const active = !!flags.front
434
446
  const r = await call('open', { url: rest[0], active })
435
- out(`开了新标签 ${r.tabId}(${active ? '前台' : '后台,不抢焦点'}):${r.url}`, r)
447
+ out(`开了新标签 ${r.tabId}(${active ? '前台' : r.window === 'agent' ? '单独的干活窗口,后台' : '后台,不抢焦点'}):${r.url}`, r)
436
448
  return
437
449
  }
438
450
  case 'close': {
@@ -197,9 +197,12 @@ async function touchesOwnPage(op, args) {
197
197
  }
198
198
  /** 用户在弹窗里关了「页面里显示光标」:真实点击照做,只是不画那只蓝色光标 */
199
199
  let showCursor = true
200
- const prefsReady = chrome.storage.local.get(['paused', 'showCursor']).then((v) => {
200
+ /** 用户关了「在单独窗口里干活」:新开的页回到用户当前窗口(后台标签页,不抢焦点) */
201
+ let ownWindow = true
202
+ const prefsReady = chrome.storage.local.get(['paused', 'showCursor', 'ownWindow']).then((v) => {
201
203
  paused = !!(v && v.paused)
202
204
  showCursor = !(v && v.showCursor === false)
205
+ ownWindow = !(v && v.ownWindow === false)
203
206
  updateBadge()
204
207
  }).catch(() => {})
205
208
 
@@ -408,7 +411,8 @@ async function ensureGroup(tabId) {
408
411
  } catch {}
409
412
  }
410
413
  try {
411
- const gid = await chrome.tabs.group({ tabIds: [id] })
414
+ // 新建的组一定要指明在它自己的窗口:不写的话 Chrome 建在「当前窗口」,会把别的窗口里的标签页(比如干活窗口里的)拽过来
415
+ const gid = await chrome.tabs.group({ tabIds: [id], createProperties: { windowId: wid } })
412
416
  groupedTabs.set(id, gid)
413
417
  ourGroup.set(wid, gid)
414
418
  await chrome.tabGroups.update(gid, { title: GROUP_TITLE, color: 'blue' })
@@ -467,6 +471,97 @@ async function reconcileGroups() {
467
471
  }
468
472
  }
469
473
 
474
+ // ── DSH 自己的干活窗口 ──────────────────────────────────────────────────────
475
+
476
+ /**
477
+ * 新开的页默认放进一个单独的 Chrome 窗口:同一个用户资料,登录状态都在,但不往用户正在用的窗口里塞标签页。
478
+ * 窗口在后台开(不抢焦点),之后新开的页都进它;用户把它关了,下次再开一个。
479
+ * 普通和隐身各用各的:用户正在隐身窗口里,新页就开进隐身的干活窗口,不把隐身的事带进普通的 Cookie 和历史记录(反过来也一样)。
480
+ * 窗口 id 记在 storage.session:worker 被挂起再起来还认得;浏览器重启就清空(id 也变了)。
481
+ */
482
+ const agentWindows = { normal: null, incognito: null }
483
+ /** DSH 在干活窗口里开的标签页:用户自己拖进来的页不算,不能把它切走 */
484
+ const agentTabs = new Set()
485
+ const agentWindowReady = chrome.storage.session.get(['agentWindows', 'agentTabs']).then((v) => {
486
+ Object.assign(agentWindows, (v && v.agentWindows) || {})
487
+ for (const id of (v && v.agentTabs) || []) agentTabs.add(id)
488
+ }).catch(() => {})
489
+
490
+ function saveAgentWindows() {
491
+ chrome.storage.session.set({ agentWindows: { ...agentWindows }, agentTabs: [...agentTabs] }).catch(() => {})
492
+ }
493
+
494
+ function forgetAgentWindow(id) {
495
+ let changed = false
496
+ for (const k of Object.keys(agentWindows)) if (agentWindows[k] === id) { agentWindows[k] = null; changed = true }
497
+ if (changed) saveAgentWindows()
498
+ }
499
+
500
+ /** 这一种(normal / incognito)的干活窗口还在就回它的 id,没了(被关掉、浏览器重启过)回 null */
501
+ async function agentWindow(mode) {
502
+ await agentWindowReady
503
+ const id = agentWindows[mode]
504
+ if (id == null) return null
505
+ try {
506
+ const w = await chrome.windows.get(id)
507
+ if (w && w.type === 'normal' && !!w.incognito === (mode === 'incognito')) return w.id
508
+ } catch {}
509
+ forgetAgentWindow(id)
510
+ return null
511
+ }
512
+
513
+ /** 现在还在的干活窗口(两种都算),列标签页时标出来用 */
514
+ async function agentWindowIds() {
515
+ return new Set((await Promise.all(['normal', 'incognito'].map(agentWindow))).filter((id) => id != null))
516
+ }
517
+
518
+ /** 开页排队:两个会话同时开页时,后来的等前一个开完(窗口建好了)再往里加,不另开第二个窗口 */
519
+ let agentWindowQueue = Promise.resolve()
520
+
521
+ function openInAgentWindow(url) {
522
+ const run = agentWindowQueue.then(() => openInAgentWindowNow(url))
523
+ agentWindowQueue = run.catch(() => {})
524
+ return run
525
+ }
526
+
527
+ function rememberAgentTab(t) {
528
+ agentTabs.add(t.id)
529
+ saveAgentWindows()
530
+ return t
531
+ }
532
+
533
+ async function openInAgentWindowNow(url) {
534
+ // 用户最后在用的普通窗口:隐身与否跟它走,新窗口的大小也照它
535
+ let cur = null
536
+ try { cur = await chrome.windows.getLastFocused({ windowTypes: ['normal'] }) } catch {}
537
+ const incognito = !!(cur && cur.incognito)
538
+ const mode = incognito ? 'incognito' : 'normal'
539
+ const wid = await agentWindow(mode)
540
+ if (wid != null) {
541
+ try {
542
+ // 窗口里正显示的是 DSH 开的页就切到新页(偷看一眼就是最新的);不动窗口焦点。
543
+ // 正显示的是用户自己拖进来的页:别把它切走,新页在后台开
544
+ const [shown] = await chrome.tabs.query({ windowId: wid, active: true })
545
+ return rememberAgentTab(await chrome.tabs.create({ windowId: wid, url, active: !shown || agentTabs.has(shown.id) }))
546
+ } catch (e) {
547
+ // 刚好在这一下被关掉了:下面重开一个。窗口还在就是别的错(比如网址不让开),照实报
548
+ if (await chrome.windows.get(wid).then(() => true, () => false)) throw e
549
+ forgetAgentWindow(wid)
550
+ }
551
+ }
552
+ // 跟用户当前窗口一样大、错开一点;最大化 / 全屏的不照抄,交给 Chrome 默认
553
+ const props = { url, focused: false, type: 'normal', incognito }
554
+ let w
555
+ if (cur && cur.state === 'normal' && cur.width && cur.height) {
556
+ try {
557
+ w = await chrome.windows.create({ ...props, left: cur.left + 40, top: cur.top + 40, width: cur.width, height: cur.height })
558
+ } catch {} // 窗口贴着屏幕边,错开以后一半到了屏幕外,Chrome 不让开:交给它自己摆
559
+ }
560
+ if (!w) w = await chrome.windows.create(props)
561
+ agentWindows[mode] = w.id
562
+ return rememberAgentTab(w.tabs[0])
563
+ }
564
+
470
565
  async function ensure(tabId) {
471
566
  if (paused) throw new Error(PAUSED_MSG) // 暂停中不再接管任何标签页(进行中的操作也不会重新 attach)
472
567
  lastUsed.set(Number(tabId), Date.now())
@@ -902,6 +997,8 @@ const OPS = {
902
997
  await setPaused(true, 'DSH 设置页')
903
998
  } else if (action === 'cursor') {
904
999
  await setShowCursor(!!on, 'DSH 设置页')
1000
+ } else if (action === 'window') {
1001
+ await setOwnWindow(!!on, 'DSH 设置页')
905
1002
  } else if (action === 'releaseAll') {
906
1003
  await releaseAllTabs()
907
1004
  } else if (action !== 'state') {
@@ -910,7 +1007,7 @@ const OPS = {
910
1007
  const st = await buildState()
911
1008
  return {
912
1009
  version: st.version, id: chrome.runtime.id, paused: st.paused, showCursor: st.showCursor,
913
- attachedCount: st.attachedCount,
1010
+ ownWindow: st.ownWindow, attachedCount: st.attachedCount,
914
1011
  sessions: st.sessions.filter((x) => x.tabs.some((t) => t.attached)).length,
915
1012
  tabs: [...st.sessions.flatMap((x) => x.tabs), ...st.orphans]
916
1013
  .filter((t) => t.attached).slice(0, 8).map((t) => ({ title: t.title, url: t.url })),
@@ -940,10 +1037,15 @@ const OPS = {
940
1037
 
941
1038
  async tabs() {
942
1039
  const tabs = await chrome.tabs.query({})
1040
+ // 窗口不止一个时每个窗口都有一个 active:focused 标出用户最后在用的那个窗口,agentWindow 标出 DSH 的干活窗口
1041
+ let focusedWin = null
1042
+ try { focusedWin = (await chrome.windows.getLastFocused()).id } catch {}
1043
+ const agentWins = await agentWindowIds()
943
1044
  return tabs
944
1045
  .filter(t => t.url && !t.url.startsWith('chrome-extension://'))
945
1046
  .map(t => ({
946
1047
  id: t.id, windowId: t.windowId, active: t.active, pinned: t.pinned,
1048
+ focused: t.windowId === focusedWin, agentWindow: agentWins.has(t.windowId),
947
1049
  title: t.title, url: t.url, attached: attached.has(t.id),
948
1050
  // 这个标签页是不是被我们自动分进「🖱 DSH agent」组(面板和自检都用得上)
949
1051
  grouped: groupedTabs.has(t.id), groupId: t.groupId >= 0 ? t.groupId : null,
@@ -974,7 +1076,12 @@ const OPS = {
974
1076
  async open({ url, active = false }) {
975
1077
  // 相对地址会被 tabs.create 按扩展自己的地址补全(example.com → chrome-extension://…/example.com),只收完整网址
976
1078
  if (url) { try { new URL(url) } catch { throw new Error(`要给完整网址(带 https://):${url}`) } }
977
- // 默认后台开页:DSH 干活不该顶掉用户正在看的标签页
1079
+ // 默认开进 DSH 自己的窗口(后台,不抢焦点);用户关了「单独窗口」就在当前窗口后台开页。
1080
+ // 两种都不顶掉用户正在看的标签页。active=true(cb open --front)是有意要它跳到眼前,照旧开在当前窗口
1081
+ if (ownWindow && !active) {
1082
+ const t = await openInAgentWindow(url)
1083
+ return { tabId: t.id, url: t.pendingUrl || t.url || url || '', window: 'agent' }
1084
+ }
978
1085
  const t = await chrome.tabs.create({ url, active: !!active })
979
1086
  return { tabId: t.id, url: t.url }
980
1087
  },
@@ -1412,6 +1519,7 @@ async function buildState() {
1412
1519
  idleMs: DETACH_IDLE_MS,
1413
1520
  attachedCount: controlledCount(),
1414
1521
  showCursor,
1522
+ ownWindow,
1415
1523
  sessions,
1416
1524
  orphans,
1417
1525
  activity: ACTIVITY.slice(-30).reverse().map((a) => ({
@@ -1434,7 +1542,7 @@ async function diagnostics() {
1434
1542
  `DSH Bridge ${st.version}(${chrome.runtime.id})`,
1435
1543
  `浏览器:${navigator.userAgent}`,
1436
1544
  `宿主:${st.connected ? '已连接' : '没连上'}${h ? `,pid ${h.pid},socket ${h.socketOk ? '在听' : '没在听'}(${h.socket}),已处理 ${h.served} 次请求` : ''}`,
1437
- `暂停:${st.paused ? '是' : '否'};页内光标:${st.showCursor ? '显示' : '关闭'};受控标签页:${st.attachedCount}`,
1545
+ `暂停:${st.paused ? '是' : '否'};页内光标:${st.showCursor ? '显示' : '关闭'};新页开在:${st.ownWindow ? '单独窗口' : '当前窗口'};受控标签页:${st.attachedCount}`,
1438
1546
  `会话:${st.sessions.map((s) => `${s.key}(${s.ops} 次操作,${s.errors} 次失败,${s.tabs.length} 个标签页)`).join(';') || '无'}`,
1439
1547
  '',
1440
1548
  '最近失败:',
@@ -1476,6 +1584,12 @@ async function setShowCursor(on, where) {
1476
1584
  }
1477
1585
  }
1478
1586
 
1587
+ async function setOwnWindow(on, where) {
1588
+ ownWindow = !!on
1589
+ await chrome.storage.local.set({ ownWindow })
1590
+ log(`新开的页改成开在${ownWindow ? '单独窗口' : '当前窗口'}(${where})`)
1591
+ }
1592
+
1479
1593
  chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
1480
1594
  if (!msg || !msg.popup || sender.id !== chrome.runtime.id) return
1481
1595
  const run = async () => {
@@ -1504,6 +1618,9 @@ chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
1504
1618
  case 'cursor':
1505
1619
  await setShowCursor(!!msg.on, '弹窗')
1506
1620
  return buildState()
1621
+ case 'window':
1622
+ await setOwnWindow(!!msg.on, '弹窗')
1623
+ return buildState()
1507
1624
  case 'diagnostics':
1508
1625
  return { text: await diagnostics() }
1509
1626
  default:
@@ -1540,5 +1657,9 @@ chrome.tabs.onRemoved.addListener((tabId) => {
1540
1657
  tabEpoch.delete(tabId)
1541
1658
  dialogs.delete(tabId)
1542
1659
  failLoadWaiter(tabId, '标签页在加载中被关掉了')
1660
+ if (agentTabs.delete(tabId)) saveAgentWindows()
1661
+ })
1662
+ chrome.windows.onRemoved.addListener((windowId) => {
1663
+ forgetAgentWindow(windowId) // 干活窗口被关了:下次新开页再开一个
1543
1664
  })
1544
1665
  connect()
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "DSH Bridge",
4
- "version": "1.12.0",
4
+ "version": "1.13.0",
5
5
  "description": "DSH 原生浏览器控制桥:装一次永久可用,不需要点 Connect",
6
6
  "minimum_chrome_version": "116",
7
7
  "icons": {
@@ -62,8 +62,14 @@
62
62
  <input type="checkbox" role="switch" data-act="cursor" checked>
63
63
  <span class="switch" aria-hidden="true"></span>
64
64
  </label>
65
+ <label class="row toggle">
66
+ <span class="tile orange" aria-hidden="true"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linejoin="round"><rect x="1.8" y="4.6" width="9.6" height="8.6" rx="1.6"/><path d="M4.6 4.6V3.4c0-.9.7-1.6 1.6-1.6h6.4c.9 0 1.6.7 1.6 1.6v5.6c0 .9-.7 1.6-1.6 1.6h-1.2"/></svg></span>
67
+ <span class="row-main"><span class="row-title">新页开在单独窗口</span></span>
68
+ <input type="checkbox" role="switch" data-act="window" checked>
69
+ <span class="switch" aria-hidden="true"></span>
70
+ </label>
65
71
  </div>
66
- <p class="note">关掉「控制」后,DSH 的浏览器调用会被直接拒绝。关掉「光标」只是不画,操作照做。</p>
72
+ <p class="note">关掉「控制」后,DSH 的浏览器调用会被直接拒绝。关掉「光标」只是不画,操作照做。关掉「单独窗口」,新页就开在你当前窗口的后台。</p>
67
73
  </section>
68
74
 
69
75
  <section class="block">
@@ -137,6 +137,9 @@ function renderSettings(st) {
137
137
  if (pause.checked !== !st.paused) pause.checked = !st.paused
138
138
  const showCursor = st.showCursor !== false
139
139
  if (cursor.checked !== showCursor) cursor.checked = showCursor
140
+ const win = document.querySelector('input[data-act="window"]')
141
+ const ownWindow = st.ownWindow !== false
142
+ if (win.checked !== ownWindow) win.checked = ownWindow
140
143
  }
141
144
 
142
145
  // ── 会话 ────────────────────────────────────────────────────────────────────
@@ -355,6 +358,9 @@ document.addEventListener('change', async (ev) => {
355
358
  } else if (input.dataset.act === 'cursor') {
356
359
  render(await ask('cursor', { on: input.checked }))
357
360
  toast(input.checked ? '页面里会显示 DSH 的光标' : '光标藏起来了,DSH 照常干活')
361
+ } else if (input.dataset.act === 'window') {
362
+ render(await ask('window', { on: input.checked }))
363
+ toast(input.checked ? 'DSH 新开的页会放进一个单独窗口' : 'DSH 新开的页会放在你当前窗口的后台')
358
364
  }
359
365
  })
360
366
 
@@ -22,9 +22,8 @@ import crypto from 'node:crypto'
22
22
  // Windows 上 %TEMP% 本来就是每个用户自己的目录
23
23
  const WIN = process.platform === 'win32'
24
24
  const DIR = process.env.DSH_BRIDGE_DIR || (WIN ? path.join(os.tmpdir(), 'dsh-bridge') : `/tmp/dsh-bridge-${process.getuid()}`)
25
- const SOCK = process.env.DSH_BRIDGE_SOCK ||
26
- (WIN ? `\\\\.\\pipe\\dsh-bridge-${crypto.randomBytes(12).toString('hex')}` : path.join(DIR, 'dsh-bridge.sock'))
27
25
  const TOKEN_FILE = process.env.DSH_BRIDGE_TOKEN || path.join(DIR, 'dsh-bridge.token')
26
+ const UNIX_SOCK = process.env.DSH_BRIDGE_SOCK || path.join(DIR, 'dsh-bridge.sock')
28
27
  const LOG_FILE = process.env.DSH_BRIDGE_LOG || path.join(DIR, 'dsh-bridge.log')
29
28
  const TIMEOUT_MS = Number(process.env.DSH_BRIDGE_TIMEOUT_MS || 45000)
30
29
  const MAX_TIMEOUT_MS = 10 * 60_000
@@ -42,12 +41,25 @@ function privateDir(dir) {
42
41
  }
43
42
 
44
43
  try {
45
- for (const d of new Set([...(WIN ? [] : [SOCK]), TOKEN_FILE, LOG_FILE].map((f) => path.dirname(f)))) privateDir(d)
44
+ for (const d of new Set([...(WIN ? [] : [UNIX_SOCK]), TOKEN_FILE, LOG_FILE].map((f) => path.dirname(f)))) privateDir(d)
46
45
  } catch (e) {
47
46
  process.stderr.write(`dsh-bridge: ${e.message}\n`) // Chrome 会把宿主的 stderr 记进它自己的日志
48
47
  process.exit(1)
49
48
  }
50
49
 
50
+ // Windows 管道名:dsh-bridge-<哪个 token 文件>-<启动时刻,微秒>-<随机>。管道在全机共用的命名空间里,
51
+ // 带上 token 文件真实路径的指纹(目录建好后取 realpath:短文件名 / 链接这些别名都归到一处),同一个 token 文件的宿主才互相比先后(见 isCurrentHost)
52
+ let realToken = TOKEN_FILE
53
+ try { realToken = path.join(fs.realpathSync.native(path.dirname(TOKEN_FILE)), path.basename(TOKEN_FILE)) } catch {}
54
+ const PIPE_SCOPE = crypto.createHash('sha256').update(path.resolve(realToken).toLowerCase()).digest('hex').slice(0, 10)
55
+ const PIPE_RE = new RegExp(`^dsh-bridge-${PIPE_SCOPE}-\\d{17}-[0-9a-f]+$`)
56
+ const SOCK = WIN
57
+ ? process.env.DSH_BRIDGE_SOCK || `\\\\.\\pipe\\dsh-bridge-${PIPE_SCOPE}-${String(Math.round((performance.timeOrigin + performance.now()) * 1000)).padStart(17, '0')}-${crypto.randomBytes(12).toString('hex')}`
58
+ : UNIX_SOCK
59
+ // Unix:先在同目录一个只属于自己的临时名字上监听、记下 inode,再原子改名成公开路径。
60
+ // 直接在公开路径上监听的话,监听完、记 inode 之前要是另一个宿主刚好接管,就会把人家的 inode 记成自己的
61
+ const BIND_PATH = WIN ? SOCK : path.join(path.dirname(SOCK), `.s${process.pid}`)
62
+
51
63
  // 日志:开一次、不跟软链接(O_NOFOLLOW),之后一直往这个 fd 写
52
64
  let logFd = null
53
65
  try { logFd = fs.openSync(LOG_FILE, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0o600); fs.fchmodSync(logFd, 0o600) } catch {}
@@ -116,7 +128,7 @@ function onExtensionMessage(raw) {
116
128
  if (!pending) return
117
129
  waiting.delete(msg.id)
118
130
  clearTimeout(pending.timer)
119
- reply(pending.sock, { id: msg.id, ok: msg.ok !== false, result: msg.result, error: msg.error })
131
+ reply(pending.sock, { id: pending.cid, ok: msg.ok !== false, result: msg.result, error: msg.error })
120
132
  }
121
133
 
122
134
  if (!STANDALONE) {
@@ -141,16 +153,26 @@ if (!STANDALONE) {
141
153
  /** 请求 id → {sock, timer} */
142
154
  const waiting = new Map()
143
155
 
156
+ /** 还没送到客户端手里的回话(连接还没关):宿主要退出时等它们,免得大截图只送出去一截 */
157
+ let writing = 0
158
+
144
159
  function reply(sock, obj) {
160
+ if (sock.destroyed) return // 客户端早走了(close 已经发生过,不会再来)
161
+ writing++
162
+ let done = false
163
+ const fin = () => { if (!done) { done = true; writing-- } }
164
+ sock.once('close', fin)
145
165
  try {
146
- sock.write(JSON.stringify(obj) + '\n', () => { try { sock.end() } catch {} })
147
- } catch (e) { log('回写 CLI 失败:', String(e)) }
166
+ sock.write(JSON.stringify(obj) + '\n', (err) => { if (err) fin(); try { sock.end() } catch {} })
167
+ } catch (e) { fin(); log('回写 CLI 失败:', String(e)) }
148
168
  }
149
169
 
150
170
  function forwardToExtension(sock, req) {
151
- const id = req.id || crypto.randomUUID()
171
+ // 和扩展之间用宿主自己生成的 id:两个客户端碰巧用了同一个 id 也不会拿错对方的结果;回给客户端时换回它自己的
172
+ const id = crypto.randomUUID()
173
+ const cid = req.id ?? id
152
174
  if (!extReady) {
153
- reply(sock, { id, ok: false, error: 'Chrome 扩展未连接:Chrome 没开,或 DSH Bridge 扩展没装/被停用' })
175
+ reply(sock, { id: cid, ok: false, error: 'Chrome 扩展未连接:Chrome 没开,或 DSH Bridge 扩展没装/被停用' })
154
176
  return
155
177
  }
156
178
  // 客户端带了自己的超时(等元素、截图这类慢操作)就按它来,比它早一点点回话,免得客户端先放弃、只看到「超时」
@@ -158,27 +180,31 @@ function forwardToExtension(sock, req) {
158
180
  const ms = asked > 0 ? Math.min(Math.max(asked - 1500, 1000), MAX_TIMEOUT_MS) : TIMEOUT_MS
159
181
  const timer = setTimeout(() => {
160
182
  waiting.delete(id)
161
- reply(sock, { id, ok: false, error: `扩展 ${ms}ms 没回(操作太慢,或者标签页已关闭)` })
183
+ reply(sock, { id: cid, ok: false, error: `扩展 ${ms}ms 没回(操作太慢,或者标签页已关闭;做没做成不确定)` })
162
184
  }, ms)
163
- waiting.set(id, { sock, timer })
185
+ waiting.set(id, { sock, timer, cid })
164
186
  try {
165
187
  toExtension({ id, op: req.op, args: req.args || {}, ...(req.client ? { client: req.client } : {}) })
166
188
  } catch (e) {
167
189
  clearTimeout(timer)
168
190
  waiting.delete(id)
169
- reply(sock, { id, ok: false, error: String(e && e.message || e) })
191
+ reply(sock, { id: cid, ok: false, error: String(e && e.message || e) })
170
192
  }
171
193
  }
172
194
 
173
195
  function handleLine(sock, line) {
174
196
  let req
175
197
  try { req = JSON.parse(line) } catch { return reply(sock, { ok: false, error: '不是合法 JSON' }) }
198
+ if (!req || typeof req !== 'object' || Array.isArray(req)) return reply(sock, { ok: false, error: '请求要是一个 JSON 对象' })
176
199
  if (req.token !== TOKEN) {
177
200
  log('token 不匹配,拒绝')
178
201
  return reply(sock, { id: req.id, ok: false, error: 'token 不匹配' })
179
202
  }
180
203
  served++
181
204
  lastClientAt = Date.now()
205
+ if (draining && req.op !== 'status') {
206
+ return reply(sock, { id: req.id, ok: false, error: '宿主正要重启(临时目录被系统清理了),这次操作没执行:过几秒再试' })
207
+ }
182
208
  if (req.op === 'status') {
183
209
  return reply(sock, {
184
210
  id: req.id, ok: true,
@@ -190,17 +216,7 @@ function handleLine(sock, line) {
190
216
  }
191
217
 
192
218
  function startServer() {
193
- try {
194
- if (!WIN && fs.existsSync(SOCK)) {
195
- // 探测一下是不是活着的旧实例;活着也让路(接管),否则清掉陈旧文件
196
- try {
197
- const probe = net.connect(SOCK)
198
- probe.on('connect', () => probe.end())
199
- probe.on('error', () => {})
200
- } catch {}
201
- fs.unlinkSync(SOCK)
202
- }
203
- } catch (e) { log('清理旧 socket 失败:', String(e)) }
219
+ if (!WIN) { try { fs.unlinkSync(BIND_PATH) } catch {} } // 同 pid 的上一个进程留下的
204
220
 
205
221
  const server = net.createServer((sock) => {
206
222
  sock.setEncoding('utf8')
@@ -218,22 +234,123 @@ function startServer() {
218
234
  })
219
235
 
220
236
  server.on('error', (e) => { log('socket 服务出错:', String(e)); shutdown(1) })
221
- server.listen(SOCK, () => {
222
- listening = true
237
+ server.listen(BIND_PATH, () => {
223
238
  if (!WIN) {
224
- fs.chmodSync(SOCK, 0o600)
225
- try { const st = fs.lstatSync(SOCK); ownSock = { dev: st.dev, ino: st.ino } } catch {}
239
+ try {
240
+ fs.chmodSync(BIND_PATH, 0o600)
241
+ const st = fs.lstatSync(BIND_PATH)
242
+ ownSock = { dev: st.dev, ino: st.ino }
243
+ fs.renameSync(BIND_PATH, SOCK) // 原子换上:旧宿主的 socket 文件(活的死的都一样)被顶掉,旧宿主自己会发现
244
+ published = true
245
+ } catch (e) { log('放 socket 失败:', String(e)); return shutdown(1) }
226
246
  }
247
+ listening = true
227
248
  try { writeToken() } catch (e) { log('写 token 失败:', String(e)); shutdown(1) }
228
249
  log(`监听 ${SOCK}(pid ${process.pid}, standalone=${STANDALONE})`)
250
+ setInterval(healFiles, HEAL_MS).unref()
229
251
  })
230
252
 
231
253
  return server
232
254
  }
233
255
 
256
+ /**
257
+ * 系统会清临时目录:macOS 每天 0 点的 tmp_cleaner 删掉 /tmp 里 3 天没读过的文件,Windows 的存储感知也会清 %TEMP%。
258
+ * token 文件没了宿主还活着,插件和 cb 只会报「token 不匹配」,一直到 Chrome 重启才好(实测:Chrome 开了 5 天,第 4 天 0 点起就连不上)。
259
+ * 所以定时看一眼:客户端正连着的宿主(见 isCurrentHost)发现 token 文件没了、或者不是自己的,就写成自己的;
260
+ * 别的宿主一概不动它,所以几个宿主同时在(两个 Chrome 资料、Chrome + Edge)也不会互相抢,最多一轮就对上。
261
+ * 连 socket 文件都没了(整个目录被清掉)就等手上的调用回完再退出 —— 扩展会马上重新拉起一个宿主,socket 和 token 都是新的。
262
+ */
263
+ const HEAL_MS = Number(process.env.DSH_BRIDGE_HEAL_MS || 60_000)
264
+ const DRAIN_MS = Number(process.env.DSH_BRIDGE_DRAIN_MS || 120_000)
265
+ let ownsToken = true // 上次看到的 token 文件是不是自己写的
266
+ let draining = false
267
+
268
+ /**
269
+ * 客户端现在连的是不是自己(同一时刻只有一个宿主是)。Unix:socket 文件还是自己建的那个(后来的宿主会删掉它换成自己的)。
270
+ * Windows:每个宿主有自己的管道,客户端按 token 文件里写的管道去连;约定同一个 token 文件的宿主里最晚起来的那个算数,
271
+ * 管道名里带着启动时刻,列一下 \\.\pipe\ 就知道。
272
+ */
273
+ function isCurrentHost() {
274
+ if (!WIN) {
275
+ try {
276
+ const st = fs.lstatSync(SOCK)
277
+ return !!ownSock && st.dev === ownSock.dev && st.ino === ownSock.ino
278
+ } catch { return false }
279
+ }
280
+ const me = path.win32.basename(SOCK)
281
+ if (!PIPE_RE.test(me)) return ownsToken // 自己指定的管道名,比不了先后:只在上次见到的 token 是自己的时候补
282
+ try {
283
+ return !fs.readdirSync('\\\\.\\pipe\\').some((n) => PIPE_RE.test(n) && n > me)
284
+ } catch (e) {
285
+ if (!pipeListFailed) log('列不出命名管道,退回看上次见到的 token 是不是自己的:', String(e))
286
+ pipeListFailed = true
287
+ return ownsToken
288
+ }
289
+ }
290
+ let pipeListFailed = false
291
+
292
+ let sockGone = false
293
+ function healFiles() {
294
+ if (draining || sockGone) return
295
+ if (!WIN && !fs.existsSync(SOCK)) {
296
+ // 隔一秒再看一眼:别的宿主退出时会把 socket 挪开一瞬间(见 shutdown),别被这一下骗了
297
+ sockGone = true
298
+ setTimeout(() => {
299
+ sockGone = false
300
+ if (fs.existsSync(SOCK)) return
301
+ log('socket 文件被删了(系统清理临时目录?)')
302
+ if (!STANDALONE) drainThenExit() // 扩展那边断开就会重连、拉起新宿主
303
+ }, 1000).unref()
304
+ return
305
+ }
306
+ let cur = null
307
+ try {
308
+ cur = fs.readFileSync(TOKEN_FILE, 'utf8')
309
+ } catch (e) {
310
+ if (e.code !== 'ENOENT') return
311
+ }
312
+ if (cur !== null) ownsToken = cur.split('\n')[0] === TOKEN
313
+ if (cur !== null && ownsToken) {
314
+ // 顺手刷一下时间:清理程序按「多久没用」删,一直是新的就不会被删
315
+ try { const now = new Date(); fs.utimesSync(TOKEN_FILE, now, now) } catch {}
316
+ return
317
+ }
318
+ if (!isCurrentHost()) return
319
+ try {
320
+ privateDir(path.dirname(TOKEN_FILE))
321
+ writeToken()
322
+ ownsToken = true
323
+ log(cur === null ? 'token 文件被删了(系统清理临时目录?),已写回' : 'token 文件不是自己的(几个宿主同时起来?),已改回')
324
+ } catch (err) {
325
+ log('写回 token 失败:', String(err))
326
+ }
327
+ }
328
+
329
+ /**
330
+ * 等已经转给扩展、还没回话的调用回完、回话也送到客户端了再退(最多 DRAIN_MS):直接退的话客户端只看到连接断了,
331
+ * 操作其实可能已经做了,模型一重试就做两遍。等不到的明确告诉它「结果未知」。这期间新来的操作不转,回「没执行」。
332
+ */
333
+ function drainThenExit() {
334
+ draining = true
335
+ const until = Date.now() + DRAIN_MS
336
+ const tick = () => {
337
+ if ((waiting.size || writing) && Date.now() < until) return setTimeout(tick, 200)
338
+ for (const w of waiting.values()) {
339
+ clearTimeout(w.timer)
340
+ reply(w.sock, { id: w.cid, ok: false, error: '宿主要重启(临时目录被系统清理了),这次操作做没做成不确定:先看看页面现在的样子,再决定要不要重做' })
341
+ }
342
+ waiting.clear()
343
+ const flushBy = Date.now() + 5000
344
+ const flush = () => (writing && Date.now() < flushBy ? setTimeout(flush, 100) : shutdown(0))
345
+ flush()
346
+ }
347
+ tick()
348
+ }
349
+
234
350
  let server = null
235
351
  /** 自己建的那个 socket 文件(dev+inode):退出时只删它,别把后来接管的新宿主的 socket 删了 */
236
352
  let ownSock = null
353
+ let published = false // 已经改名成公开路径了(没成功的话公开路径上的东西跟自己无关,退出时别碰)
237
354
  function shutdown(code) {
238
355
  // 不调 server.close():Node 关 Unix socket 服务时会按路径无条件 unlink(实测),
239
356
  // 正好会删掉后来接管的新宿主的 socket。反正马上退出,fd 由系统回收。
@@ -242,8 +359,22 @@ function shutdown(code) {
242
359
  // 命名管道随进程消失;token 文件还指着自己的管道就删掉,免得客户端连一个不存在的管道
243
360
  if (fs.readFileSync(TOKEN_FILE, 'utf8').split('\n')[1] === SOCK) fs.unlinkSync(TOKEN_FILE)
244
361
  } else {
245
- const st = fs.lstatSync(SOCK)
246
- if (ownSock && st.dev === ownSock.dev && st.ino === ownSock.ino) fs.unlinkSync(SOCK)
362
+ try { fs.unlinkSync(BIND_PATH) } catch {} // 还没来得及改名就退了
363
+ // 只删自己的 socket 文件:先原子挪到自己的临时名再看是谁的(先看再删的话,中间新宿主刚好换上来就会删错)。
364
+ // 挪下来的是新宿主的就放回去(link 不覆盖:放回之前又来了更新的,就不用放了)
365
+ if (published) {
366
+ fs.renameSync(SOCK, BIND_PATH)
367
+ const st = fs.lstatSync(BIND_PATH)
368
+ if (st.dev !== ownSock.dev || st.ino !== ownSock.ino) {
369
+ try {
370
+ fs.linkSync(BIND_PATH, SOCK)
371
+ } catch (e) {
372
+ // 放不回去(不是因为已经有更新的了):改名挪回去,挪不回也别删,那是别人的
373
+ if (e.code !== 'EEXIST') { try { fs.renameSync(BIND_PATH, SOCK) } catch {} ; process.exit(code) }
374
+ }
375
+ }
376
+ fs.unlinkSync(BIND_PATH)
377
+ }
247
378
  }
248
379
  } catch {}
249
380
  process.exit(code)