@vibedev-si/dsh-island 0.2.0 → 0.3.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/executable.js CHANGED
@@ -1,28 +1,28 @@
1
1
  /**
2
2
  * 岛屿程序在哪。
3
3
  *
4
- * 顺序:设置里指定的路径 › 随插件一起装上的(从 npm 装的包自带,见 native/scripts/pack-plugin.mjs)
5
- * › `%LOCALAPPDATA%\VibeDev\island`(开发时手动拷过去的那一份)。随包的排在前面:从 npm 装过之后,
6
- * 机器上旧的手动拷贝不会顶替新版本。开发用的插件目录里没有随包的程序,所以开发时照旧用手动拷的那份。
4
+ * 顺序:设置里指定的路径 › 随插件一起装上的(从 npm 装的包自带,`bin/<系统>-<架构>/`,见 native/scripts/pack-plugin.mjs)
5
+ * › 开发时手动放的那一份(Windows 是 `%LOCALAPPDATA%\VibeDev\island`,macOS 是
6
+ * `~/Library/Application Support/VibeDev/island`,见 platform.js)。随包的排在前面:从 npm 装过之后,
7
+ * 机器上旧的手动拷贝不会顶替新版本。开发用的插件目录里没有随包的程序,所以开发时照旧用手动放的那份。
7
8
  *
8
- * 岛屿只有 Windows 版:别的系统上没有候选,宿主据此说明「只支持 Windows」。
9
+ * 岛屿有 Windows 版;macOS 版在做(docs/macos-port.md)。别的系统上没有候选,宿主据此说明不支持。
9
10
  */
10
11
  import { join } from 'node:path'
11
-
12
- /** 随包的岛屿程序相对插件目录的位置。打包脚本把编译好的程序放到这里。 */
13
- export const BUNDLED_EXECUTABLE = Object.freeze(['bin', 'win32-x64', 'vibedev-island.exe'])
12
+ import { bundledProgram } from './platform.js'
14
13
 
15
14
  /**
16
15
  * 按顺序该去哪几个地方找岛屿程序。
17
16
  *
18
- * @param {{ configured?: unknown, platform: string, pluginDir: string, localAppData: string, appDirName: string }} where
19
- * @returns {string[]} 候选路径;设置里指定了就只有那一个,不是 Windows 时是空的
17
+ * @param {{ configured?: unknown, platform: string, arch: string, pluginDir: string, devDir: string }} where
18
+ * @returns {string[]} 候选路径;设置里指定了就只有那一个,这个系统没有岛屿程序时是空的
20
19
  */
21
- export function executableCandidates({ configured, platform, pluginDir, localAppData, appDirName }) {
20
+ export function executableCandidates({ configured, platform, arch, pluginDir, devDir }) {
22
21
  const chosen = typeof configured === 'string' ? configured.trim() : ''
23
22
  if (chosen !== '') return [chosen]
24
- if (platform !== 'win32') return []
25
- return [join(pluginDir, ...BUNDLED_EXECUTABLE), join(localAppData, appDirName, 'island', 'vibedev-island.exe')]
23
+ const bundled = bundledProgram({ platform, arch })
24
+ if (bundled === undefined) return []
25
+ return [join(pluginDir, ...bundled), join(devDir, bundled[bundled.length - 1])]
26
26
  }
27
27
 
28
28
  /**
@@ -32,6 +32,8 @@ export function executableCandidates({ configured, platform, pluginDir, localApp
32
32
  * @param {string[]} candidates 找过的地方
33
33
  */
34
34
  export function missingExecutableMessage(platform, candidates) {
35
- if (platform !== 'win32' && candidates.length === 0) return 'VibeDev 岛屿只支持 Windows。'
36
- return `没有找到岛屿程序(找过:${candidates.join(';')})。重新安装插件试试。`
35
+ if (candidates.length === 0) return 'VibeDev 岛屿不支持这个系统。'
36
+ const where = candidates.join(';')
37
+ if (platform === 'darwin') return `这个版本的插件里没有 macOS 的岛屿程序(找过:${where})。`
38
+ return `没有找到岛屿程序(找过:${where})。重新安装插件试试。`
37
39
  }
package/features.js ADDED
@@ -0,0 +1,33 @@
1
+ /**
2
+ * 这台机器上的小岛有哪些要靠系统接口的功能(岛屿程序的 `src-tauri/src/features.rs`,握手时报上来)。
3
+ * 插件页据此不显示没有的设置:没有的功能不放开关。
4
+ *
5
+ * 岛屿没在运行、或者是不报这一项的旧版时,按系统猜:旧版岛屿只有 Windows 版,Windows 上全有;
6
+ * 别的系统上只有不靠系统接口的 QQ 邮箱。
7
+ */
8
+
9
+ /** Windows 版岛屿的全部功能,和 features.rs 的 Windows 列表一致。 */
10
+ export const WINDOWS_FEATURES = Object.freeze([
11
+ 'shortcuts',
12
+ 'clipboard',
13
+ 'screenshot',
14
+ 'media',
15
+ 'sound',
16
+ 'fullscreen',
17
+ 'readOtherApps',
18
+ 'wechat',
19
+ 'qqNotifications',
20
+ 'qqMail',
21
+ ])
22
+
23
+ /** 别的系统上没有握手结果时的猜测,和 features.rs 的非 Windows 列表一致。 */
24
+ export const OTHER_FEATURES = Object.freeze(['qqMail'])
25
+
26
+ /**
27
+ * @param {{ reported: unknown, platform: string }} input `reported` 是握手结果里的 `features`
28
+ * @returns {string[]}
29
+ */
30
+ export function featuresOf({ reported, platform }) {
31
+ if (Array.isArray(reported)) return reported.filter((feature) => typeof feature === 'string')
32
+ return [...(platform === 'win32' ? WINDOWS_FEATURES : OTHER_FEATURES)]
33
+ }
package/index.js CHANGED
@@ -5,7 +5,7 @@
5
5
  * 持有设置并下发给岛屿,把 VibeDev 的会话、审批和提问转给岛屿,以及给插件页提供同源路由。
6
6
  * 协议见仓库的 protocol/README.md。
7
7
  *
8
- * 岛屿只能由这里拉起:它没有托盘、没有自己的设置窗口,单独启动会直接退出。
8
+ * 岛屿只能由这里拉起:它没有托盘,单独启动会直接退出。
9
9
  *
10
10
  * 这里只做接线。能脱离宿主算出来的东西各在自己的模块里,并有单测:
11
11
  * sessions.js(会话列表与通知)、requests.js(审批与提问的文案)、translate.js、
@@ -13,12 +13,20 @@
13
13
  */
14
14
  import { existsSync, readFileSync } from 'node:fs'
15
15
  import { readFile, writeFile } from 'node:fs/promises'
16
- import { arch as osArch, release as osRelease } from 'node:os'
16
+ import { arch as osArch, homedir, release as osRelease } from 'node:os'
17
17
  import { createInterface } from 'node:readline'
18
18
  import { basename, dirname, join } from 'node:path'
19
19
  import { fileURLToPath } from 'node:url'
20
20
  import { LOG_FILE, createLog } from './log.js'
21
- import { defaultsKeepingPresets, loadSettings, normalize, saveSettings, settingsPath } from './settings.js'
21
+ import {
22
+ applyPatch,
23
+ defaultsKeepingPresets,
24
+ loadSettings,
25
+ nativeSettingsPatch,
26
+ normalize,
27
+ saveSettings,
28
+ settingsPath,
29
+ } from './settings.js'
22
30
  import { islandRoutes } from './routes.js'
23
31
  import { loadChangelog } from './changelog.js'
24
32
  import { createSessionBook, doneNotice, errorItem, islandSurface, sessionsForIsland } from './sessions.js'
@@ -27,20 +35,23 @@ import { closeMessage, createAttention, showMessage, withWaiting } from './atten
27
35
  import { ANONYMOUS_PROVIDERS, translateWith } from './translate.js'
28
36
  import { createPageEvents } from './events.js'
29
37
  import { createSelectionRelay } from './selection.js'
30
- import { createApprovalHolds, HAND_BACK_MS, isDangerous, isFullAccess } from './approvals.js'
38
+ import { createApprovalHolds, createForegroundRecheck, HAND_BACK_MS, isDangerous, isFullAccess } from './approvals.js'
39
+ import { createToolCallBook, structuredQuestions, validatedAnswers } from './approval-details.js'
31
40
  import { createOutbox, mediaTypeOf, promptText, sendRequest } from './outbox.js'
32
41
  import { createIslandItems } from './island-items.js'
33
42
  import { diagnosticsFileName, diagnosticsReport } from './diagnostics.js'
34
43
  import { wechatSummary } from './wechat.js'
35
44
  import { executableCandidates, missingExecutableMessage } from './executable.js'
45
+ import { devProgramDir, revealCommand, systemLabel } from './platform.js'
46
+ import { featuresOf } from './features.js'
36
47
  import { createContributions } from './contributions.js'
37
48
  import { createDisplays } from './contributor-display.js'
38
49
  import { createRecentBook } from './recent.js'
39
50
  import { createOpeners } from './openers.js'
40
51
  import { contributorEntry } from './contributor-entry.js'
52
+ import { createAccountUsagePoll, readAccountUsageRoute } from './usage-host.js'
41
53
 
42
54
  const PROTOCOL_VERSION = 1
43
- const APP_DIR_NAME = 'VibeDev'
44
55
  /** 崩溃后最多重启几次,以及这些重启要在多久之内。 */
45
56
  const MAX_RESTARTS = 3
46
57
  const RESTART_WINDOW_MS = 5 * 60_000
@@ -113,9 +124,9 @@ function islandExecutableCandidates(config) {
113
124
  return executableCandidates({
114
125
  configured: config?.executable,
115
126
  platform: process.platform,
127
+ arch: process.arch,
116
128
  pluginDir: PLUGIN_DIRECTORY,
117
- localAppData: process.env.LOCALAPPDATA ?? join(process.env.USERPROFILE ?? '', 'AppData', 'Local'),
118
- appDirName: APP_DIR_NAME,
129
+ devDir: devProgramDir({ platform: process.platform, env: process.env, home: homedir() }),
119
130
  })
120
131
  }
121
132
 
@@ -195,6 +206,20 @@ export function apply(ctx, config) {
195
206
  let selectionSeen = false
196
207
  /** 岛上正在等用户决定的审批(在小岛上直接批准)。 */
197
208
  const holds = createApprovalHolds({ setTimer: later, clearTimer: cancel })
209
+ const toolCalls = createToolCallBook()
210
+ let managedRevision = 0
211
+ let nextManagedCard = 1
212
+ let managedTransportClosed = false
213
+ const managedHolds = createApprovalHolds({
214
+ setTimer: later,
215
+ clearTimer: cancel,
216
+ onPendingChange: createForegroundRecheck({
217
+ setTimer: later,
218
+ clearTimer: cancel,
219
+ check: managedForegroundSafe,
220
+ onUnsafe: () => handBackManaged(),
221
+ }),
222
+ })
198
223
  /** 发送到会话:等页面来取的内容,以及每个页面动作是发给哪条会话的。 */
199
224
  const outbox = createOutbox()
200
225
  const sendsBySeq = new Map()
@@ -276,8 +301,12 @@ export function apply(ctx, config) {
276
301
  return Array.from(merged.values()).map((item) => ({ ...item, blocked: !contributionAllowed(item.name) }))
277
302
  }
278
303
 
304
+ const nativeSettingsAvailable = () => handle !== undefined && ready && islandCapabilities.includes('native-settings')
305
+
279
306
  const status = () => ({
280
307
  running: handle !== undefined && ready,
308
+ nativeSettings: nativeSettingsAvailable(),
309
+ nativeSettingsExpected: process.platform === 'win32' && process.arch === 'x64',
281
310
  configured: executable !== undefined,
282
311
  executable,
283
312
  version: islandVersion,
@@ -288,6 +317,9 @@ export function apply(ctx, config) {
288
317
  lastExit,
289
318
  lastError,
290
319
  settingsPath: settingsPath(),
320
+ // 这个系统上的小岛有哪些要靠系统接口的功能:插件页不显示没有的设置。
321
+ platform: process.platform,
322
+ features: featuresOf({ reported: islandFeatures, platform: process.platform }),
291
323
  shortcuts: shortcutStatus,
292
324
  qq: qqStatus,
293
325
  // 微信:原始状态之外附上给页面直接显示的几句话。
@@ -326,6 +358,20 @@ export function apply(ctx, config) {
326
358
  const replyTo = (id, result) => send({ id, result })
327
359
  const failRequest = (id, code, message) => send({ id, error: { code, message } })
328
360
 
361
+ let usageConnection
362
+ const usagePoll = createAccountUsagePoll({
363
+ read: (...args) => (usageConnection === undefined ? undefined : readAccountUsageRoute(usageConnection, ...args)),
364
+ publish: (snapshot) => {
365
+ if (ready && !managedTransportClosed) notify('usage/snapshot', snapshot)
366
+ },
367
+ later,
368
+ cancel,
369
+ })
370
+ const reconcileUsagePoll = () =>
371
+ usagePoll.setEnabled(
372
+ usageConnection !== undefined && ready && !managedTransportClosed && islandCapabilities.includes('account-usage'),
373
+ )
374
+
329
375
  /** 向岛屿发一条请求。成功时得到它的结果;失败或超时得到 `{ error: { message } }`。 */
330
376
  const request = (method, params, timeoutMs = REQUEST_TIMEOUT_MS) =>
331
377
  new Promise((resolve) => {
@@ -357,6 +403,8 @@ export function apply(ctx, config) {
357
403
  const attention = createAttention()
358
404
  /** 岛屿握手时报的能力。旧版岛屿没有 `attention`,只认审批卡片。 */
359
405
  let islandCapabilities = Array.of()
406
+ /** 握手时岛屿报的「这个系统上有的功能」(features.js);旧版岛屿不报,是 undefined。 */
407
+ let islandFeatures
360
408
  /** 已经异步查过标题的会话,每个只查一次。 */
361
409
  const titleLookups = new Set()
362
410
  /** 已经放到岛上的任务行:id -> 上次发出去的内容。 */
@@ -425,6 +473,8 @@ export function apply(ctx, config) {
425
473
 
426
474
  /** 岛屿认不认识「等你处理」的列表;旧版只认审批卡片。 */
427
475
  const attentionCapable = () => islandCapabilities.includes('attention')
476
+ const managedApprovalEngine = () => islandCapabilities.includes('approval-details')
477
+ const managedQuestionEngine = () => islandCapabilities.includes('question-answers')
428
478
  const selectionCapable = () => islandCapabilities.includes('selection')
429
479
 
430
480
  /** 在岛上挂一条「等你处理」,并让会话页把那条会话归到「等你处理」里。 */
@@ -482,8 +532,21 @@ export function apply(ctx, config) {
482
532
  }
483
533
 
484
534
  const save = async (next) => {
485
- settings = normalize(next)
486
- saveSettings(settings)
535
+ const previous = settings
536
+ const saved = normalize(next)
537
+ saveSettings(saved)
538
+ settings = saved
539
+ if (
540
+ (previous.sessions.approveOnIsland && !settings.sessions.approveOnIsland) ||
541
+ (previous.sessions.decideOnIsland && !settings.sessions.decideOnIsland) ||
542
+ (previous.sessions.notifyOnQuestion && !settings.sessions.notifyOnQuestion)
543
+ ) {
544
+ managedRevision += 1
545
+ managedHolds.releaseWhere(({ kind }) => !managedActionEnabled(kind), 'timeout')
546
+ for (const item of attention.list()) {
547
+ if (item.id.startsWith('managed-') && !managedReminderEnabled(item.kind)) closeAttention(item.id)
548
+ }
549
+ }
487
550
  pushSettings()
488
551
 
489
552
  // 「显示会话状态」「显示运行中的任务」可能刚被打开或关掉:马上按新的设置重发。
@@ -554,6 +617,29 @@ export function apply(ctx, config) {
554
617
 
555
618
  /** 岛屿发来的请求(要回复的)。 */
556
619
  const handleRequest = (id, method, params) => {
620
+ if (
621
+ method === 'settings/change' &&
622
+ ready &&
623
+ !managedTransportClosed &&
624
+ (nativeSettingsAvailable() || managedApprovalEngine() || managedQuestionEngine())
625
+ ) {
626
+ const patch = nativeSettingsPatch(params)
627
+ if (patch === undefined) {
628
+ failRequest(id, -32602, 'Invalid native settings patch')
629
+ return
630
+ }
631
+ const current = handle
632
+ void save(applyPatch(settings, patch)).then(
633
+ (saved) => {
634
+ if (handle === current) replyTo(id, saved)
635
+ },
636
+ () => {
637
+ log('saving native approval settings failed')
638
+ if (handle === current) failRequest(id, -32603, 'Could not save native approval settings')
639
+ },
640
+ )
641
+ return
642
+ }
557
643
  // 岛屿要用 VibeDev 的翻译通道。失败时明确报错,让岛屿退回本地密钥。
558
644
  if (method === 'translate') {
559
645
  // 不把用户的文字写进日志,只记长度。
@@ -573,6 +659,8 @@ export function apply(ctx, config) {
573
659
  }
574
660
 
575
661
  const onReady = (params) => {
662
+ const current = handle
663
+ if (current === undefined) return
576
664
  ready = true
577
665
  startedAt = new Date().toISOString()
578
666
  islandVersion = params?.version
@@ -581,6 +669,7 @@ export function apply(ctx, config) {
581
669
  // hostExecutable:岛屿据此认出 VibeDev 的窗口,点「去处理」时把它带到前台。
582
670
  void request('initialize', { protocol: PROTOCOL_VERSION, settings, hostExecutable: process.execPath }).then(
583
671
  (result) => {
672
+ if (handle !== current) return
584
673
  log(`initialize answered: ${JSON.stringify(result)}`)
585
674
  if (result?.error !== undefined) {
586
675
  lastError = String(result.error?.message ?? result.error)
@@ -594,6 +683,8 @@ export function apply(ctx, config) {
594
683
  return
595
684
  }
596
685
  islandCapabilities = Array.isArray(result?.capabilities) ? result.capabilities : Array.of()
686
+ islandFeatures = Array.isArray(result?.features) ? result.features : undefined
687
+ reconcileUsagePoll()
597
688
  // 岛屿是新起来的,它那边什么都没有:把还在等的事重新挂上去。
598
689
  for (const item of attention.visible()) notify(...showMessage(item, attentionCapable()))
599
690
  // 别的插件放的东西:新起来的岛屿上还没有。
@@ -632,7 +723,8 @@ export function apply(ctx, config) {
632
723
  break
633
724
  }
634
725
  closeAttentionFor(sessionId, ['error'])
635
- // 这条会话在岛上等着的审批:用户要去 VibeDev 处理了,交给 VibeDev 的界面。
726
+ handBackManaged('open')
727
+ // 这条会话在旧岛屿上等着的审批也交给 VibeDev 的界面。
636
728
  const handed = holds.decideForSession(sessionId, 'open')
637
729
  if (handed > 0) log(`handed ${handed} approval(s) of ${sessionId} back to VibeDev`)
638
730
  const seq = pageEvents.publish('open-session', { sessionId })
@@ -641,16 +733,19 @@ export function apply(ctx, config) {
641
733
  }
642
734
  // 岛屿页头的齿轮:让开着的页面切到插件页,小岛的设置都在那里。
643
735
  case 'settings/open': {
736
+ handBackManaged('open')
644
737
  const seq = pageEvents.publish('open-settings', Object.freeze({ panel: 'plugins' }))
645
738
  log(`settings open requested (event ${seq}, ${pageEvents.waiting} page(s) were listening)`)
646
739
  break
647
740
  }
648
- // 岛上的一条「等你处理」被点了。是否放行、怎么回答仍在 VibeDev 里决定。
649
741
  case 'attention/decide':
650
742
  case 'approval/decide': {
651
- log(`island attention: ${JSON.stringify(params)}`)
652
743
  const item = attention.get(params?.id)
653
744
  if (item === undefined) break
745
+ if (managedHolds.has(item.id)) {
746
+ if (method === 'attention/decide') void decideManaged(item, params)
747
+ break
748
+ }
654
749
  const decision = params?.decision
655
750
  // 岛上扣着的审批:用户在岛上允许或拒绝了,或者要回 VibeDev 处理。
656
751
  if ((decision === 'allow' || decision === 'deny' || decision === 'open') && holds.decide(item.id, decision))
@@ -713,10 +808,11 @@ export function apply(ctx, config) {
713
808
  let message
714
809
  try {
715
810
  message = JSON.parse(line)
716
- } catch (error) {
717
- log(`dropped a malformed line: ${error}`)
811
+ } catch {
812
+ log('dropped a malformed protocol line')
718
813
  return
719
814
  }
815
+ if (message === null || typeof message !== 'object' || Array.isArray(message)) return
720
816
  if (message.id !== undefined && message.method === undefined) {
721
817
  const resolve = pendingReplies.get(message.id)
722
818
  if (resolve === undefined) return
@@ -733,12 +829,16 @@ export function apply(ctx, config) {
733
829
 
734
830
  const onExit = (outcome) => {
735
831
  ready = false
832
+ reconcileUsagePoll()
736
833
  handle = undefined
737
834
  lastExit = outcome
738
835
  // 下一个岛屿可能是另一个版本:握手之前按最保守的方式发。
739
836
  islandCapabilities = Array.of()
837
+ islandFeatures = undefined
740
838
  for (const resolve of pendingReplies.values()) resolve({ error: { message: 'island exited' } })
741
839
  pendingReplies.clear()
840
+ managedTransportClosed = true
841
+ handBackManaged()
742
842
  // 岛上扣着的审批没人能在岛上答了:马上交回 VibeDev,别让它等满 60 秒。
743
843
  holds.releaseAll('timeout')
744
844
  log(`island exited: ${JSON.stringify(outcome)}`)
@@ -790,7 +890,20 @@ export function apply(ctx, config) {
790
890
  lastError = undefined
791
891
  log(`island spawned: ${executable}`)
792
892
 
793
- if (handle.stdout) createInterface({ input: handle.stdout, crlfDelay: Infinity }).on('line', handleLine)
893
+ if (handle.stdout) {
894
+ const current = handle
895
+ managedTransportClosed = false
896
+ createInterface({ input: current.stdout, crlfDelay: Infinity })
897
+ .on('line', (line) => {
898
+ if (handle === current) handleLine(line)
899
+ })
900
+ .once('close', () => {
901
+ if (handle !== current) return
902
+ managedTransportClosed = true
903
+ reconcileUsagePoll()
904
+ handBackManaged()
905
+ })
906
+ }
794
907
  // 标准错误也按行读:按块记的话,一行会被拆开,几行又会粘在一起。
795
908
  if (handle.stderr) {
796
909
  createInterface({ input: handle.stderr, crlfDelay: Infinity }).on('line', (line) => log(`island stderr: ${line}`))
@@ -801,6 +914,8 @@ export function apply(ctx, config) {
801
914
  /** 先请岛屿自己退出,宽限期到了才强制结束。返回时它已经不在了(或已经下了强制结束的命令)。 */
802
915
  const stopIsland = async () => {
803
916
  desiredRunning = false
917
+ usagePoll.setEnabled(false)
918
+ handBackManaged()
804
919
  if (restartTimer !== undefined) cancel(restartTimer)
805
920
  restartTimer = undefined
806
921
  const current = handle
@@ -823,6 +938,18 @@ export function apply(ctx, config) {
823
938
  }
824
939
  }
825
940
 
941
+ /** 在文件管理器里选中一个文件(Windows 资源管理器 / macOS 访达)。 */
942
+ const reveal = async (path) => {
943
+ const { program, args } = revealCommand(process.platform, path)
944
+ const resolved = await ctx.subprocess.resolveExecutable(program, undefined, disposal.signal)
945
+ ctx.subprocess.spawn({
946
+ argv: [resolved, ...args],
947
+ cwd: dirname(path),
948
+ stdio: { stdin: 'ignore', stdout: { maxBytes: 1024 }, stderr: { maxBytes: 1024 } },
949
+ graceMs: 1000,
950
+ })
951
+ }
952
+
826
953
  const control = async (action, payload) => {
827
954
  log(`control: ${action}`)
828
955
  // 录制快捷键期间挂起截图热键:否则按下新组合就真的去截图了。
@@ -830,6 +957,12 @@ export function apply(ctx, config) {
830
957
  notify('shortcuts/suspend', { suspended: payload?.suspended === true })
831
958
  return
832
959
  }
960
+ if (action === 'open-native-settings') {
961
+ if (!nativeSettingsAvailable()) throw new Error('原生设置窗口当前不可用')
962
+ const result = await request('island/open-settings', null)
963
+ if (result !== null) throw new Error(String(result?.error?.message ?? '岛屿未确认打开设置窗口'))
964
+ return
965
+ }
833
966
  // QQ 通知权限:申请(弹 Windows 授权)或打开系统设置;稍后刷新状态。
834
967
  if (action === 'qq-request-access' || action === 'qq-open-settings') {
835
968
  if (!ready) throw new Error('岛屿没有运行')
@@ -848,24 +981,18 @@ export function apply(ctx, config) {
848
981
  log('settings reset to defaults')
849
982
  return
850
983
  }
851
- // 在资源管理器里选中日志文件。
852
984
  // 设置页上的「试听」:按现在选的提示音和音量响一下。
853
985
  if (action === 'sound-test') {
854
986
  if (!ready) throw new Error('岛屿没有运行')
855
987
  notify('sound/test', { sound: settings.sessions?.sound, volume: settings.sessions?.soundVolume })
856
988
  return
857
989
  }
990
+ // 在文件管理器里选中日志文件。
858
991
  if (action === 'open-logs') {
859
- const explorer = await ctx.subprocess.resolveExecutable('explorer.exe', undefined, disposal.signal)
860
- ctx.subprocess.spawn({
861
- argv: [explorer, `/select,${LOG_FILE}`],
862
- cwd: dirname(LOG_FILE),
863
- stdio: { stdin: 'ignore', stdout: { maxBytes: 1024 }, stderr: { maxBytes: 1024 } },
864
- graceMs: 1000,
865
- })
992
+ await reveal(LOG_FILE)
866
993
  return
867
994
  }
868
- // 导出诊断信息:写一份文本放在日志旁边,在资源管理器里选中它。
995
+ // 导出诊断信息:写一份文本放在日志旁边,在文件管理器里选中它。
869
996
  if (action === 'export-diagnostics') {
870
997
  await refreshDiagnostics().catch(() => undefined)
871
998
  const logText = await readFile(LOG_FILE, 'utf8').catch(() => '')
@@ -873,19 +1000,13 @@ export function apply(ctx, config) {
873
1000
  status: status(),
874
1001
  settings,
875
1002
  logText,
876
- system: { os: `Windows ${osRelease()}`, arch: osArch(), node: process.version },
1003
+ system: { os: systemLabel(process.platform, osRelease()), arch: osArch(), node: process.version },
877
1004
  })
878
1005
  const path = join(dirname(LOG_FILE), diagnosticsFileName())
879
1006
  await writeFile(path, report, 'utf8')
880
1007
  diagnosticsPath = path
881
1008
  log(`diagnostics exported: ${path}`)
882
- const explorer = await ctx.subprocess.resolveExecutable('explorer.exe', undefined, disposal.signal)
883
- ctx.subprocess.spawn({
884
- argv: [explorer, `/select,${path}`],
885
- cwd: dirname(path),
886
- stdio: { stdin: 'ignore', stdout: { maxBytes: 1024 }, stderr: { maxBytes: 1024 } },
887
- graceMs: 1000,
888
- })
1009
+ await reveal(path)
889
1010
  return { path }
890
1011
  }
891
1012
  // 打开翻译窗口:和按翻译快捷键一样,只是不会把已经开着的窗口关掉。
@@ -1109,6 +1230,15 @@ export function apply(ctx, config) {
1109
1230
  }
1110
1231
  // 插件页的同源路由;连接层已做认证,路由不需要自己校验令牌。
1111
1232
  ctx.inject(['connection'], (scoped) => {
1233
+ scoped.effect(() => {
1234
+ const connection = scoped.connection
1235
+ usageConnection = connection
1236
+ reconcileUsagePoll()
1237
+ return () => {
1238
+ if (usageConnection === connection) usageConnection = undefined
1239
+ reconcileUsagePoll()
1240
+ }
1241
+ }, 'dsh-island: VibeDev account poll')
1112
1242
  const pageRoutes = islandRoutes({
1113
1243
  status: statusForPage,
1114
1244
  settings: () => settings,
@@ -1180,6 +1310,9 @@ export function apply(ctx, config) {
1180
1310
 
1181
1311
  ctx.on('api-session/removed', (sessionId) => {
1182
1312
  titleLookups.delete(sessionId)
1313
+ toolCalls.forget(sessionId)
1314
+ managedRevision += 1
1315
+ managedHolds.decideForSession(sessionId, 'timeout')
1183
1316
  closeAttentionFor(sessionId)
1184
1317
  if (book.remove(sessionId)) schedulePush()
1185
1318
  })
@@ -1205,7 +1338,140 @@ export function apply(ctx, config) {
1205
1338
  return !where.front && !(where.quiet && settings.behavior?.quietInFullscreen !== false)
1206
1339
  }
1207
1340
 
1341
+ function handBackManaged(decision = 'timeout') {
1342
+ managedRevision += 1
1343
+ managedHolds.releaseAll(decision)
1344
+ }
1345
+
1346
+ function managedReminderEnabled(kind) {
1347
+ return kind === 'approval'
1348
+ ? settings.sessions?.approveOnIsland !== false
1349
+ : settings.sessions?.notifyOnQuestion !== false
1350
+ }
1351
+
1352
+ function managedActionEnabled(kind) {
1353
+ if (!ready || !desiredRunning || managedTransportClosed || disposal.signal.aborted || !attentionCapable())
1354
+ return false
1355
+ if (
1356
+ !managedReminderEnabled(kind) ||
1357
+ settings.sessions?.approveOnIsland === false ||
1358
+ settings.sessions?.decideOnIsland === false
1359
+ )
1360
+ return false
1361
+ return kind === 'approval'
1362
+ ? managedApprovalEngine() && islandCapabilities.includes('approve')
1363
+ : managedQuestionEngine()
1364
+ }
1365
+
1366
+ async function managedForegroundSafe() {
1367
+ if (handle === undefined || managedTransportClosed) return false
1368
+ const current = handle
1369
+ // Do not let one outstanding probe overlap the next 500 ms recheck.
1370
+ const where = await request('host/foreground', null, 400)
1371
+ return (
1372
+ handle === current &&
1373
+ !managedTransportClosed &&
1374
+ where?.front === false &&
1375
+ where?.quiet === false &&
1376
+ where.error === undefined
1377
+ )
1378
+ }
1379
+
1380
+ async function decideManaged(item, params) {
1381
+ const { decision } = params
1382
+ if (decision === 'open' || decision === 'dismiss') {
1383
+ managedHolds.decide(item.id, decision)
1384
+ return
1385
+ }
1386
+ const result =
1387
+ item.kind === 'approval'
1388
+ ? decision === 'allow' || decision === 'deny'
1389
+ ? decision
1390
+ : undefined
1391
+ : decision === 'answer'
1392
+ ? validatedAnswers(item.questions, params.answers)
1393
+ : undefined
1394
+ if (result === undefined) return
1395
+ if (Date.now() >= item.expiresAt || !managedActionEnabled(item.kind) || !(await managedForegroundSafe())) {
1396
+ managedHolds.decide(item.id, 'timeout')
1397
+ return
1398
+ }
1399
+ if (Date.now() >= item.expiresAt || !managedActionEnabled(item.kind)) {
1400
+ managedHolds.decide(item.id, 'timeout')
1401
+ return
1402
+ }
1403
+ managedHolds.decide(item.id, result)
1404
+ }
1405
+
1406
+ async function holdManaged(item, payload, signal) {
1407
+ if (!managedActionEnabled(item.kind) || signal?.aborted === true) return undefined
1408
+ const revision = managedRevision
1409
+ if (
1410
+ !(await managedForegroundSafe()) ||
1411
+ revision !== managedRevision ||
1412
+ signal?.aborted === true ||
1413
+ !managedActionEnabled(item.kind)
1414
+ )
1415
+ return undefined
1416
+ const timeoutMs = (settings.sessions?.approvalTimeoutSeconds ?? HAND_BACK_MS / 1000) * 1000
1417
+ const response = managedHolds.wait(item.id, { sessionId: item.sessionId, kind: item.kind, signal, timeoutMs })
1418
+ showAttention({ ...item, ...payload, decidable: true, expiresAt: Date.now() + timeoutMs })
1419
+ try {
1420
+ return await response
1421
+ } finally {
1422
+ closeAttention(item.id)
1423
+ }
1424
+ }
1425
+
1426
+ async function managedInteraction(shown, payload, signal, next) {
1427
+ const item = { ...shown, id: `managed-${nextManagedCard++}` }
1428
+ let outcome
1429
+ try {
1430
+ if (payload !== undefined) outcome = await holdManaged(item, payload, signal)
1431
+ } catch {
1432
+ log('could not hold the interaction on the island')
1433
+ }
1434
+ if (signal?.aborted === true) return next()
1435
+ if (outcome === 'allow') return 'allowed-once'
1436
+ if (outcome === 'deny') return 'rejected'
1437
+ if (outcome?.answers !== undefined) return outcome
1438
+
1439
+ if (managedReminderEnabled(item.kind)) {
1440
+ if (outcome === 'dismiss') {
1441
+ attention.add({ ...item, dismissed: true })
1442
+ schedulePush()
1443
+ } else {
1444
+ showAttention(item)
1445
+ }
1446
+ }
1447
+ try {
1448
+ return await next()
1449
+ } finally {
1450
+ closeAttention(item.id)
1451
+ }
1452
+ }
1453
+
1454
+ const workingDirectoryOf = (session) => {
1455
+ const workingDirectory = ctx.get('workingDirectory')
1456
+ return typeof workingDirectory?.get === 'function' ? workingDirectory.get(session) : session.header?.cwd
1457
+ }
1458
+
1459
+ ctx.on('session/event', (session, event) => toolCalls.observe(session, event), { global: true })
1460
+
1461
+ // 审批与提问是瀑布事件。没有确认过的岛上答复时,继续由 VibeDev 的答复者决定。
1208
1462
  ctx.on('approval/request', async (event, next) => {
1463
+ log(`approval request: ${event?.toolName ?? '?'}`)
1464
+ if (managedApprovalEngine()) {
1465
+ if (!managedReminderEnabled('approval') || event?.signal?.aborted === true) return next()
1466
+ const shown = describeApproval(event)
1467
+ let payload
1468
+ try {
1469
+ payload = toolCalls.details(event, workingDirectoryOf)
1470
+ } catch {
1471
+ // 工作目录服务不可用:仍由 VibeDev 完成审批。
1472
+ }
1473
+ return managedInteraction(shown, payload, event?.signal, next)
1474
+ }
1209
1475
  let shown
1210
1476
  try {
1211
1477
  if (settings.sessions?.approveOnIsland !== false) shown = describeApproval(event)
@@ -1249,9 +1515,17 @@ export function apply(ctx, config) {
1249
1515
  // 不管在哪里处理掉的,岛上的那一条都该撤下:留着一条过期的会误导人。
1250
1516
  closeAttention(shown.id)
1251
1517
  }
1252
- })
1518
+ }, { prepend: true })
1253
1519
 
1254
1520
  ctx.on('user-questions/request', async (event, next) => {
1521
+ if (managedQuestionEngine()) {
1522
+ if (event?.signal?.aborted === true || settings.sessions?.notifyOnQuestion === false) return next()
1523
+ if (isApprovalQuestion(event) && attention.waitingOf(event?.agent?.id) === 'approval') return next()
1524
+ const shown = describeQuestion(event)
1525
+ if (!managedReminderEnabled(shown.kind)) return next()
1526
+ const questions = structuredQuestions(event)
1527
+ return managedInteraction(shown, questions === undefined ? undefined : { questions }, event?.signal, next)
1528
+ }
1255
1529
  let shown
1256
1530
  try {
1257
1531
  // 审批有时也走提问通道。岛上已经有这条会话的审批时,不再为同一件事另挂一条。
@@ -1281,6 +1555,8 @@ export function apply(ctx, config) {
1281
1555
  log('plugin disposing; stopping the island')
1282
1556
  // 岛上扣着的审批交回 VibeDev,插件停了它们也不会卡住。
1283
1557
  holds.releaseAll('timeout')
1558
+ handBackManaged()
1559
+ toolCalls.clear()
1284
1560
  islandItems.dispose()
1285
1561
  await stopIsland().catch((error) => log(`stopping the island failed: ${error}`))
1286
1562
  disposal.abort()