@vibedev-si/dsh-island 0.1.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/island-items.js CHANGED
@@ -68,6 +68,7 @@ export function noticeOf(input) {
68
68
  export function createIslandItems({
69
69
  send,
70
70
  allowed,
71
+ displayOf = (plugin) => ({ title: plugin, icon: 'box' }),
71
72
  setTimer = setTimeout,
72
73
  clearTimer = clearTimeout,
73
74
  now = Date.now,
@@ -85,7 +86,10 @@ export function createIslandItems({
85
86
  return state
86
87
  }
87
88
  const islandId = (plugin, id) => `plugin:${plugin}:${id}`
88
- const message = (plugin, item) => ({ ...item, id: islandId(plugin, item.id), source: plugin })
89
+ const message = (plugin, item) => {
90
+ const display = displayOf(plugin)
91
+ return { ...item, id: islandId(plugin, item.id), owner: plugin, source: display.title, icon: display.icon }
92
+ }
89
93
 
90
94
  const flush = (plugin) => {
91
95
  const state = plugins.get(plugin)
@@ -132,8 +136,13 @@ export function createIslandItems({
132
136
  return true
133
137
  },
134
138
 
135
- /** 一条会自己消失的通知。一分钟超过 3 条的不发。 */
136
- notify(plugin, input) {
139
+ /**
140
+ * 一条会自己消失的通知。一分钟超过 3 条的不发。
141
+ * @param {string} plugin
142
+ * @param {unknown} input `{ title, body?, durationMs? }`
143
+ * @param {string} [openId] 通知上的「查看」被点了时报回来的编号(openers.js);没有就不带按钮
144
+ */
145
+ notify(plugin, input, openId) {
137
146
  if (!allowed(plugin)) return false
138
147
  const notice = noticeOf(input)
139
148
  if (notice === undefined) return false
@@ -143,7 +152,12 @@ export function createIslandItems({
143
152
  if (state.notices.length >= NOTICES_PER_MINUTE) return false
144
153
  state.notices.push(at)
145
154
  state.lastAt = at
146
- send('notify', { ...notice, body: notice.body === undefined ? `来自 ${plugin}` : `${notice.body}(${plugin})` })
155
+ const source = displayOf(plugin).title
156
+ send('notify', {
157
+ ...notice,
158
+ body: notice.body === undefined ? `来自 ${source}` : `${notice.body}(${source})`,
159
+ ...(typeof openId === 'string' ? { openId } : {}),
160
+ })
147
161
  return true
148
162
  },
149
163
 
package/openers.js ADDED
@@ -0,0 +1,77 @@
1
+ /**
2
+ * 通知上的「查看」:插件发通知时给的 `open`。
3
+ *
4
+ * 函数留在宿主这边,岛上的通知只带一个编号(`openId`);用户点了「查看」,岛屿把编号报回来
5
+ * (`contrib/open`),这里调用对应的函数。通知早就消失了,所以编号只记一阵子(默认 10 分钟),
6
+ * 每个插件最多记 20 个;插件停用或被关掉时它的全部作废。
7
+ *
8
+ * 纯逻辑:时钟和日志由调用方给。
9
+ */
10
+
11
+ export const OPEN_TTL_MS = 10 * 60_000
12
+ export const OPENERS_PER_PLUGIN = 20
13
+
14
+ const nothing = () => undefined
15
+
16
+ /**
17
+ * @param {object} [options]
18
+ * @param {() => number} [options.now]
19
+ * @param {(line: string) => void} [options.log]
20
+ */
21
+ export function createOpeners(options = {}) {
22
+ const now = options.now ?? Date.now
23
+ const log = options.log ?? nothing
24
+ /** 编号 → `{ owner, open, until }`,按登记的先后排。 */
25
+ const entries = new Map()
26
+ let sequence = 0
27
+
28
+ const prune = () => {
29
+ const at = now()
30
+ for (const [id, entry] of entries) if (entry.until <= at) entries.delete(id)
31
+ }
32
+
33
+ return {
34
+ /**
35
+ * 记下一个 `open`,返回岛上用的编号。
36
+ * @param {string} owner 插件名
37
+ * @param {() => void} open
38
+ */
39
+ register(owner, open) {
40
+ prune()
41
+ const mine = Array.from(entries).filter(([, entry]) => entry.owner === owner)
42
+ for (const [id] of mine.slice(0, Math.max(0, mine.length - OPENERS_PER_PLUGIN + 1))) entries.delete(id)
43
+ sequence += 1
44
+ const id = `notice:${owner}:${sequence}`
45
+ entries.set(id, { owner, open, until: now() + OPEN_TTL_MS })
46
+ return id
47
+ },
48
+
49
+ /**
50
+ * 用户点了「查看」:调用对应的函数。返回这个编号是不是这里的。
51
+ * @param {string} id
52
+ */
53
+ run(id) {
54
+ prune()
55
+ const entry = entries.get(id)
56
+ if (entry === undefined) return typeof id === 'string' && id.startsWith('notice:')
57
+ try {
58
+ entry.open()
59
+ log(`notice: ${entry.owner} opened`)
60
+ } catch (error) {
61
+ log(`notice: ${entry.owner} failed to open: ${error}`)
62
+ }
63
+ return true
64
+ },
65
+
66
+ /** 这个插件的全部作废。 */
67
+ clear(owner) {
68
+ for (const [id, entry] of entries) if (entry.owner === owner) entries.delete(id)
69
+ },
70
+
71
+ /** 现在记着几个。 */
72
+ size: () => {
73
+ prune()
74
+ return entries.size
75
+ },
76
+ }
77
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vibedev-si/dsh-island",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "VibeDev 岛屿:在屏幕顶部常驻显示 VibeDev 会话进度、等你处理的审批和提问、插件后台任务,以及待办、剪贴板、音乐与截图。岛屿是独立的原生程序,由本插件启动和管理;仅支持 Windows · VibeDev Island: an always-on status surface for VibeDev, started and managed by this plugin (Windows only)",
5
5
  "type": "module",
6
6
  "main": "index.js",
@@ -23,6 +23,9 @@
23
23
  "events.js",
24
24
  "selection.js",
25
25
  "approvals.js",
26
+ "approval-details.js",
27
+ "account-usage.js",
28
+ "usage-host.js",
26
29
  "outbox.js",
27
30
  "island-items.js",
28
31
  "diagnostics.js",
@@ -36,6 +39,12 @@
36
39
  "wechat.js",
37
40
  "contributions.js",
38
41
  "executable.js",
42
+ "platform.js",
43
+ "features.js",
44
+ "contributor-display.js",
45
+ "contributor-entry.js",
46
+ "recent.js",
47
+ "openers.js",
39
48
  "CHANGELOG.md",
40
49
  "LICENSE",
41
50
  "bin",
package/platform.js ADDED
@@ -0,0 +1,57 @@
1
+ /**
2
+ * 插件一半里和操作系统有关的几件事:设置放哪、开发时手动放的岛屿程序在哪、随包的程序在包里哪个目录、
3
+ * 怎么在文件管理器里选中一个文件、诊断信息里怎么写系统。
4
+ *
5
+ * Windows 上的结果和以前完全一样(`%APPDATA%\VibeDev`、`%LOCALAPPDATA%\VibeDev\island`、`explorer /select,`)。
6
+ * macOS 用 `~/Library/Application Support/VibeDev` 和 `open -R`。别的系统给出路径,但没有岛屿程序。
7
+ *
8
+ * 纯函数:系统、环境变量、主目录、CPU 架构都由调用方给,测试里换成假的。
9
+ */
10
+ import { join } from 'node:path'
11
+
12
+ /** 岛屿程序的文件名。 */
13
+ export const ISLAND_PROGRAM = Object.freeze({ win32: 'vibedev-island.exe', darwin: 'vibedev-island' })
14
+
15
+ /** 设置这类小文件放在哪个目录(`VibeDev` 那一层)。 */
16
+ export function appDataDir({ platform, env, home }) {
17
+ if (platform === 'win32') return join(env.APPDATA ?? join(env.USERPROFILE ?? home, 'AppData', 'Roaming'), 'VibeDev')
18
+ if (platform === 'darwin') return join(home, 'Library', 'Application Support', 'VibeDev')
19
+ return join(env.XDG_CONFIG_HOME ?? join(home, '.config'), 'VibeDev')
20
+ }
21
+
22
+ /** 开发时手动放岛屿程序的目录(`VibeDev/island` 那一层)。 */
23
+ export function devProgramDir({ platform, env, home }) {
24
+ if (platform === 'win32')
25
+ return join(env.LOCALAPPDATA ?? join(env.USERPROFILE ?? home, 'AppData', 'Local'), 'VibeDev', 'island')
26
+ if (platform === 'darwin') return join(home, 'Library', 'Application Support', 'VibeDev', 'island')
27
+ return join(env.XDG_DATA_HOME ?? join(home, '.local', 'share'), 'VibeDev', 'island')
28
+ }
29
+
30
+ /**
31
+ * 随包的岛屿程序在包里的位置(`bin/<系统>-<架构>/<文件名>`);这个系统没有岛屿程序时是 undefined。
32
+ * @param {{ platform: string, arch: string }} where
33
+ * @returns {string[] | undefined}
34
+ */
35
+ export function bundledProgram({ platform, arch }) {
36
+ const name = ISLAND_PROGRAM[platform]
37
+ return name === undefined ? undefined : ['bin', `${platform}-${arch}`, name]
38
+ }
39
+
40
+ /**
41
+ * 在文件管理器里选中一个文件要运行的程序和参数。
42
+ * @param {string} platform
43
+ * @param {string} path
44
+ * @returns {{ program: string, args: string[] }}
45
+ */
46
+ export function revealCommand(platform, path) {
47
+ if (platform === 'win32') return { program: 'explorer.exe', args: [`/select,${path}`] }
48
+ if (platform === 'darwin') return { program: 'open', args: ['-R', path] }
49
+ return { program: 'xdg-open', args: [path.replace(/[\\/][^\\/]*$/, '') || path] }
50
+ }
51
+
52
+ /** 诊断信息里的系统一行(macOS 的 `os.release()` 是 Darwin 内核版本,照实写)。 */
53
+ export function systemLabel(platform, release) {
54
+ if (platform === 'darwin') return `macOS (Darwin ${release})`
55
+ const name = { win32: 'Windows', linux: 'Linux' }[platform] ?? platform
56
+ return `${name} ${release}`
57
+ }
package/recent.js ADDED
@@ -0,0 +1,194 @@
1
+ /**
2
+ * 别的插件放到小岛上的「最近生成」(`ctx.island.contributor(名字).recent / forget`)。
3
+ *
4
+ * 一条是一个做好了的结果:标题、一句说明、是图片 / 视频 / 音频、一张小缩略图、完成时间,以及用户在小岛上
5
+ * 点了它时要做的事(`open`)。规则:
6
+ * - 只收文字、数字和 `data:image/(png|jpeg|webp);base64,…` 形式的缩略图,缩略图整串不超过 64 KB,
7
+ * 超了或者格式不对就当没有(这一条照样显示,画成图标)。小岛不去读插件给的文件路径或网址。
8
+ * - 每个插件只留最新的 8 条(按完成时间),旧的自动撤下。
9
+ * - `open` 留在宿主这边:岛上只知道这一条「可以打开」,被点了就把它的编号报回来(`contrib/open`),
10
+ * 由这里调用插件的函数。插件的函数抛错不影响别的。
11
+ * - 谁能放由 `allowed(插件名)` 决定(设置里的开关);不让放的照样记着,放开之后补发。岛屿重启后补发。
12
+ *
13
+ * 不碰宿主也不碰进程:发消息、时钟、名字和图标都由调用方给,测试里换成假的。
14
+ */
15
+
16
+ export const RECENT_LIMIT = 8
17
+ export const THUMBNAIL_MAX = 64 * 1024
18
+ export const RECENT_TITLE_MAX = 40
19
+ export const RECENT_DETAIL_MAX = 120
20
+ export const MEDIA = Object.freeze(['image', 'video', 'audio'])
21
+
22
+ const ID_PATTERN = /^[\w.-]{1,64}$/
23
+ const THUMBNAIL = /^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}$/
24
+
25
+ const nothing = () => undefined
26
+
27
+ /** 截到 `max` 个字(末尾省略号);不是字符串或只有空白时是 undefined。 */
28
+ function cut(value, max) {
29
+ if (typeof value !== 'string') return undefined
30
+ const text = value.replace(/\s+/g, ' ').trim()
31
+ if (text === '') return undefined
32
+ const letters = Array.from(text)
33
+ return letters.length <= max ? text : `${letters.slice(0, max - 1).join('')}…`
34
+ }
35
+
36
+ /** 能用的缩略图;不能用时是 undefined。 */
37
+ export function thumbnailOf(value) {
38
+ return typeof value === 'string' && value.length <= THUMBNAIL_MAX && THUMBNAIL.test(value) ? value : undefined
39
+ }
40
+
41
+ /**
42
+ * 插件给的一条最近生成里能用的部分;标题不像样时是 undefined。
43
+ * @param {unknown} spec `{ title, subtitle?, media?, thumbnail?, at? }`
44
+ * @param {number} fallbackAt 没给完成时间时用它
45
+ */
46
+ export function recentOf(spec, fallbackAt) {
47
+ if (spec === null || typeof spec !== 'object') return undefined
48
+ const title = cut(spec.title, RECENT_TITLE_MAX)
49
+ if (title === undefined) return undefined
50
+ const detail = cut(spec.subtitle, RECENT_DETAIL_MAX)
51
+ const media = MEDIA.includes(spec.media) ? spec.media : undefined
52
+ const thumbnail = thumbnailOf(spec.thumbnail)
53
+ const at = typeof spec.at === 'number' && Number.isFinite(spec.at) && spec.at > 0 ? spec.at : fallbackAt
54
+ return { title, detail: detail ?? null, media: media ?? null, thumbnail: thumbnail ?? null, at }
55
+ }
56
+
57
+ /**
58
+ * @param {object} options
59
+ * @param {(method: string, params: object) => boolean} options.send 交给岛屿;岛屿没在运行时返回 false。
60
+ * @param {(owner: string) => { title: string, icon: string }} options.displayOf 插件在小岛上的名字和图标
61
+ * @param {(owner: string) => boolean} [options.allowed]
62
+ * @param {() => number} [options.now]
63
+ * @param {(line: string) => void} [options.log]
64
+ */
65
+ export function createRecentBook(options) {
66
+ const send = options.send
67
+ const displayOf = options.displayOf
68
+ const allowed = options.allowed ?? (() => true)
69
+ const now = options.now ?? Date.now
70
+ const log = options.log ?? nothing
71
+ /** 插件名 → (id → 条目)。 */
72
+ const owners = new Map()
73
+ /** 岛上的编号 → 条目(点了之后按它找回来)。 */
74
+ const byWire = new Map()
75
+
76
+ const everyEntry = () => Array.from(owners.values()).flatMap((entries) => Array.from(entries.values()))
77
+
78
+ const payloadOf = (entry) => {
79
+ const display = displayOf(entry.owner)
80
+ return {
81
+ id: entry.wireId,
82
+ kind: 'recent',
83
+ owner: entry.owner,
84
+ source: display.title,
85
+ icon: display.icon,
86
+ ...entry.item,
87
+ openable: entry.open !== undefined,
88
+ }
89
+ }
90
+
91
+ const flush = (entry) => {
92
+ if (!allowed(entry.owner)) return
93
+ const payload = payloadOf(entry)
94
+ const serialized = JSON.stringify(payload)
95
+ if (serialized === entry.shown) return
96
+ if (send('contrib/upsert', payload)) entry.shown = serialized
97
+ }
98
+
99
+ const withdraw = (entry) => {
100
+ if (entry.shown !== undefined) send('contrib/remove', { id: entry.wireId })
101
+ entry.shown = undefined
102
+ }
103
+
104
+ const drop = (owner, id) => {
105
+ const entries = owners.get(owner)
106
+ const entry = entries?.get(id)
107
+ if (entry === undefined) return false
108
+ withdraw(entry)
109
+ entries.delete(id)
110
+ byWire.delete(entry.wireId)
111
+ if (entries.size === 0) owners.delete(owner)
112
+ return true
113
+ }
114
+
115
+ return {
116
+ /**
117
+ * 放上或更新一条最近生成。返回收下了没有。
118
+ * @param {string} owner 插件名
119
+ * @param {string} id 插件自己的编号(字母、数字、`.`、`_`、`-`,最多 64 个)
120
+ * @param {object} spec `{ title, subtitle?, media?, thumbnail?, at?, open? }`
121
+ */
122
+ put(owner, id, spec) {
123
+ const item = typeof id === 'string' && ID_PATTERN.test(id) ? recentOf(spec, now()) : undefined
124
+ if (item === undefined) {
125
+ log(`recent: ${owner} sent a result without a usable id or title`)
126
+ return false
127
+ }
128
+ const entries = owners.get(owner) ?? new Map()
129
+ owners.set(owner, entries)
130
+ let entry = entries.get(id)
131
+ if (entry === undefined) {
132
+ entry = { owner, id, wireId: `recent:${owner}:${id}` }
133
+ entries.set(id, entry)
134
+ byWire.set(entry.wireId, entry)
135
+ }
136
+ entry.item = item
137
+ entry.open = typeof spec.open === 'function' ? spec.open : undefined
138
+ // 只留最新的几条:完成得最早的撤下。
139
+ const ordered = Array.from(entries.values()).sort((left, right) => right.item.at - left.item.at)
140
+ for (const old of ordered.slice(RECENT_LIMIT)) drop(owner, old.id)
141
+ if (entries.get(id) === entry) flush(entry)
142
+ return entries.get(id) === entry
143
+ },
144
+
145
+ /** 撤下一条。 */
146
+ forget(owner, id) {
147
+ return drop(owner, id)
148
+ },
149
+
150
+ /** 这个插件的全部撤下。 */
151
+ clear(owner) {
152
+ for (const id of Array.from(owners.get(owner)?.keys() ?? Array.of())) drop(owner, id)
153
+ },
154
+
155
+ /**
156
+ * 用户在小岛上点了这一条:调用插件给的 `open`。返回这个编号是不是这里的(是的话就算处理过了)。
157
+ * @param {string} wireId 岛上的编号
158
+ */
159
+ open(wireId) {
160
+ const entry = byWire.get(wireId)
161
+ if (entry === undefined) return false
162
+ if (entry.open === undefined) {
163
+ log(`recent: ${entry.owner} ${entry.id} has nothing to open`)
164
+ return true
165
+ }
166
+ try {
167
+ entry.open()
168
+ log(`recent: opened ${entry.owner} ${entry.id}`)
169
+ } catch (error) {
170
+ log(`recent: ${entry.owner} failed to open ${entry.id}: ${error}`)
171
+ }
172
+ return true
173
+ },
174
+
175
+ /** 开关变了或者名字、图标变了:不让上岛的撤下,能上的补发现在的样子;没变的不发。 */
176
+ refresh() {
177
+ for (const entry of everyEntry()) {
178
+ if (allowed(entry.owner)) flush(entry)
179
+ else withdraw(entry)
180
+ }
181
+ },
182
+
183
+ /** 岛屿刚起来(或重启):全部补发。 */
184
+ islandStarted() {
185
+ for (const entry of everyEntry()) {
186
+ entry.shown = undefined
187
+ flush(entry)
188
+ }
189
+ },
190
+
191
+ /** 放过最近生成的插件和各自记着几条。 */
192
+ summary: () => Array.from(owners, ([name, entries]) => ({ name, items: entries.size })),
193
+ }
194
+ }
package/routes.js CHANGED
@@ -25,6 +25,7 @@ export const CONTROL_ACTIONS = [
25
25
  'stop',
26
26
  'restart',
27
27
  'suspend',
28
+ 'open-native-settings',
28
29
  'qq-request-access',
29
30
  'qq-open-settings',
30
31
  'reset-settings',
package/settings.js CHANGED
@@ -5,7 +5,9 @@
5
5
  * 读入时按默认值的结构合并、丢掉未知字段、把越界数字夹回范围——用户手改文件也不会把岛搞坏。
6
6
  */
7
7
  import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
8
+ import { homedir } from 'node:os'
8
9
  import { dirname, join } from 'node:path'
10
+ import { appDataDir } from './platform.js'
9
11
 
10
12
  /**
11
13
  * 岛屿真正会读的设置,一项不多。
@@ -88,8 +90,10 @@ export const DEFAULT_SETTINGS = {
88
90
  notifyOnQuestion: true,
89
91
  /** VibeDev 等你批准时在岛上出一张卡片。 */
90
92
  approveOnIsland: true,
91
- /** 不在 VibeDev 里时,先在小岛上问允许还是拒绝;危险操作只能回 VibeDev,60 秒没人管就交回。 */
93
+ /** 不在 VibeDev 里时,先在小岛上问允许还是拒绝;危险操作交回 VibeDev。 */
92
94
  decideOnIsland: true,
95
+ /** 原生岛屿上的交互请求没人处理时,多久交回 VibeDev。 */
96
+ approvalTimeoutSeconds: 60,
93
97
  },
94
98
 
95
99
  todos: {
@@ -162,6 +166,8 @@ const LIMITS = {
162
166
  'clipboard.maxItems': [20, 200],
163
167
  }
164
168
 
169
+ const APPROVAL_TIMEOUT_SECONDS = [15, 30, 60, 120]
170
+
165
171
  /** 枚举值:只接受列出的选项。 */
166
172
  const CHOICES = {
167
173
  'appearance.theme': ['vibedev', 'dark', 'light'],
@@ -172,6 +178,7 @@ const CHOICES = {
172
178
  'sessions.titleMode': ['changes', 'always', 'never'],
173
179
  'sessions.lightStyle': ['dot', 'ring'],
174
180
  'sessions.sound': ['exclamation', 'notify', 'message', 'calendar', 'chimes', 'chord', 'tada'],
181
+ 'sessions.approvalTimeoutSeconds': APPROVAL_TIMEOUT_SECONDS,
175
182
  // 发送到会话、识别文字还没做;旧值 send / ocr 会被夹回默认的 copy。
176
183
  'screenshot.action': ['copy', 'save', 'send'],
177
184
  // line 折叠条上一行 / banner 折叠的小岛下面的一张卡片 / panel 直接展开到消息页。
@@ -199,9 +206,9 @@ export function normalizePages(pages) {
199
206
  return { ...pages, order, hidden: allHidden ? hidden.filter((page) => page !== order[0]) : hidden }
200
207
  }
201
208
 
209
+ /** 设置文件:Windows 是 `%APPDATA%\VibeDev\island-settings.json`,macOS 在 `~/Library/Application Support/VibeDev`(platform.js)。 */
202
210
  export function settingsPath() {
203
- const appData = process.env.APPDATA ?? join(process.env.USERPROFILE ?? '', 'AppData', 'Roaming')
204
- return join(appData, 'VibeDev', 'island-settings.json')
211
+ return join(appDataDir({ platform: process.platform, env: process.env, home: homedir() }), 'island-settings.json')
205
212
  }
206
213
 
207
214
  function merge(defaults, incoming) {
@@ -265,8 +272,10 @@ function isShortcut(value) {
265
272
  )
266
273
  }
267
274
 
275
+ const validTranslationShortcut = (value) => typeof value === 'string' && (value.trim() === '' || isShortcut(value))
276
+
268
277
  /** 快捷键字段的位置,用来在合并后统一校验。 */
269
- const SHORTCUT_FIELDS = ['clipboard.shortcut', 'screenshot.shortcut', 'translation.shortcut']
278
+ const SHORTCUT_FIELDS = ['clipboard.shortcut', 'screenshot.shortcut']
270
279
 
271
280
  /** 可以不设的快捷键:空字符串合法,表示不注册。 */
272
281
  const OPTIONAL_SHORTCUT_FIELDS = ['behavior.toggleShortcut', 'behavior.sessionsShortcut']
@@ -291,6 +300,10 @@ export function normalize(incoming) {
291
300
  for (const path of SHORTCUT_FIELDS) {
292
301
  if (!isShortcut(getAt(merged, path))) setAt(merged, path, getAt(DEFAULT_SETTINGS, path))
293
302
  }
303
+ const translationShortcut = merged.translation.shortcut.trim()
304
+ merged.translation.shortcut = validTranslationShortcut(translationShortcut)
305
+ ? translationShortcut
306
+ : DEFAULT_SETTINGS.translation.shortcut
294
307
  // 可选的快捷键:格式不合法就当没设,而不是塞一个默认组合进去。
295
308
  for (const path of OPTIONAL_SHORTCUT_FIELDS) {
296
309
  const value = getAt(merged, path).trim()
@@ -312,6 +325,47 @@ export function applyPatch(current, patch) {
312
325
  return normalize(merge(normalize(current), patch))
313
326
  }
314
327
 
328
+ const boolean = (value) => typeof value === 'boolean'
329
+ const NATIVE_SETTINGS = {
330
+ sessions: {
331
+ approveOnIsland: boolean,
332
+ decideOnIsland: boolean,
333
+ approvalTimeoutSeconds: (value) => APPROVAL_TIMEOUT_SECONDS.includes(value),
334
+ },
335
+ screenshot: {
336
+ enabled: boolean,
337
+ action: (value) => CHOICES['screenshot.action'].includes(value),
338
+ saveDirectory: (value) => typeof value === 'string',
339
+ shortcut: isShortcut,
340
+ },
341
+ translation: {
342
+ selection: boolean,
343
+ provider: (value) => CHOICES['translation.provider'].includes(value),
344
+ shortcut: validTranslationShortcut,
345
+ readOtherApps: boolean,
346
+ },
347
+ }
348
+
349
+ /** 只允许原生设置窗口修改它真的显示的宿主设置,不把其它字段交给普通补丁合并。 */
350
+ export function nativeSettingsPatch(input) {
351
+ const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value)
352
+ if (!isObject(input)) return undefined
353
+ const sections = Object.entries(input)
354
+ if (sections.length === 0) return undefined
355
+ const patch = {}
356
+ for (const [section, inputFields] of sections) {
357
+ if (!Object.hasOwn(NATIVE_SETTINGS, section) || !isObject(inputFields)) return undefined
358
+ const fields = Object.entries(inputFields)
359
+ const allowed = NATIVE_SETTINGS[section]
360
+ if (fields.length === 0) return undefined
361
+ for (const [key, value] of fields) {
362
+ if (!Object.hasOwn(allowed, key) || !allowed[key](value)) return undefined
363
+ }
364
+ patch[section] = Object.fromEntries(fields)
365
+ }
366
+ return patch
367
+ }
368
+
315
369
  function getAt(target, path) {
316
370
  return path
317
371
  .split('.')