@vibedev-si/dsh-island 0.1.0 → 0.2.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/CHANGELOG.md CHANGED
@@ -4,7 +4,17 @@
4
4
  再用三级标题分组,每组是一个列表。新的写在上面。这里的内容显示在设置页的「关于 → 更新记录」里,
5
5
  所以写给用小岛的人看,不写实现细节。
6
6
 
7
- ## 0.1.0(开发中)
7
+ ## 0.2.0
8
+
9
+ 影视工作台这类插件的生成进度、最近生成和完成通知,现在在小岛上看得到了。
10
+
11
+ ### 插件放到小岛上的东西
12
+
13
+ - 展开小岛时,页头最后多了一个插件页(只有一个插件时就是它的名字,比如「影视工作台」):进行中的任务带阶段文字和真实进度,没有进度时显示流动的条纹,做完打勾、失败标红;下面是「最近生成」的缩略图,点一张回到那个插件里打开它
14
+ - 折叠条上直接写阶段:「视频生成 · 排队中,第 3 位」「视频生成 · 62%」;领着插件任务时展开会先打开插件页
15
+ - 插件发来的完成通知可以带「查看」,点了把 VibeDev 带到前台、交给那个插件打开结果
16
+
17
+ ## 0.1.0
8
18
 
9
19
  第一个版本:把小岛接进 VibeDev,由这个插件启动、管理和设置。
10
20
 
Binary file
package/contributions.js CHANGED
@@ -2,7 +2,8 @@
2
2
  * 别的 VibeDev 插件放到岛上的后台任务(`island` 服务的 `contributor()` 背后的那本账)。
3
3
  *
4
4
  * 规划见 docs/island-plan.md 第 3 节。这一块是**后台任务**:有标题、有一句说明、有真实进度
5
- * (或者没有,那就转圈)、会结束。状态项、页、通知走 `ctx.island` 的直接方法(island-items.js)。
5
+ * (或者没有,那就转圈)、会结束。同一个入口上的「最近生成」在 recent.js,通知上的「查看」在 openers.js;
6
+ * 状态项、页、通知也可以走 `ctx.island` 的直接方法(island-items.js)。
6
7
  *
7
8
  * 几条不变的规则(规划 3.7):
8
9
  * - 只收文字和数字。标题最多 40 个字、说明最多 120 个字,超出的截断;进度夹到 0–1,
@@ -57,6 +58,8 @@ function progressOf(value) {
57
58
  * @param {() => number} [options.now]
58
59
  * @param {(line: string) => void} [options.log]
59
60
  * @param {(owner: string) => boolean} [options.allowed] 这个插件现在能不能上岛;不给就都能。
61
+ * @param {(owner: string) => { title: string, icon: string }} [options.displayOf] 插件在小岛上的名字和图标;
62
+ * 不给就用插件名和通用图标。
60
63
  */
61
64
  export function createContributions(options) {
62
65
  const send = options.send
@@ -65,6 +68,7 @@ export function createContributions(options) {
65
68
  const now = options.now ?? Date.now
66
69
  const log = options.log ?? nothing
67
70
  const allowed = options.allowed ?? (() => true)
71
+ const displayOf = options.displayOf ?? ((owner) => ({ title: owner, icon: 'box' }))
68
72
  /** 插件名 → (任务 id → 任务)。 */
69
73
  const owners = new Map()
70
74
  /** 已经说过一次「不收」的插件名,免得日志被刷满。 */
@@ -88,12 +92,18 @@ export function createContributions(options) {
88
92
  /** 把这条任务现在的样子送到岛上;和上一次送的一样就不送,太密就等一会儿只送最后一份。 */
89
93
  const flush = (task) => {
90
94
  if (task.gone || !allowed(task.owner)) return
95
+ const display = displayOf(task.owner)
91
96
  const payload = {
92
97
  id: task.wireId,
93
98
  kind: 'task',
99
+ owner: task.owner,
100
+ source: display.title,
101
+ icon: display.icon,
94
102
  title: task.title,
95
103
  detail: task.detail ?? null,
96
104
  progress: task.progress,
105
+ // 结束了的任务说明是走完了还是失败了(小岛据此画成「已完成」或「失败」);还在进行的不带。
106
+ ...(task.state === undefined ? {} : { state: task.state }),
97
107
  }
98
108
  const serialized = JSON.stringify(payload)
99
109
  if (serialized === task.shown) return
@@ -149,6 +159,7 @@ export function createContributions(options) {
149
159
  applyPatch(task, patch)
150
160
  const failed = isRecord(patch) && patch.state === 'failed'
151
161
  const stated = isRecord(patch) && 'progress' in patch
162
+ task.state = failed ? 'failed' : 'done'
152
163
  // 结束了的任务不再转圈:走完的画满;没走完的停在原来的进度上,本来就不知道进度的画成空的。
153
164
  if (!stated) task.progress = failed ? (task.progress ?? 0) : 1
154
165
  flush(task)
@@ -205,6 +216,7 @@ export function createContributions(options) {
205
216
  // 结束后还留着的那几秒里又开始了:按新任务算。
206
217
  stopTimer(task, 'linger')
207
218
  task.finished = false
219
+ task.state = undefined
208
220
  }
209
221
  applyPatch(task, { subtitle: undefined, progress: null, ...spec })
210
222
  flush(task)
@@ -0,0 +1,68 @@
1
+ /**
2
+ * 小岛上怎么称呼一个放东西的插件:名字和图标。
3
+ *
4
+ * 插件拿入口时可以自己报:`ctx.island.contributor('dsh-film', { title: '影视工作台', icon: 'film' })`。
5
+ * 没报的时候,认得的 VibeDev 插件用这里的默认值(老版本的影视工作台还不会报),其余的用包名和一个通用图标。
6
+ * 图标只能从下面几种里挑:小岛不画插件给的图,也不放插件的 HTML。
7
+ */
8
+
9
+ /** 小岛认得的图标。 */
10
+ export const ICONS = Object.freeze(['film', 'image', 'music', 'sparkles', 'box'])
11
+ /** 名字最多这么多个字。 */
12
+ export const DISPLAY_TITLE_MAX = 20
13
+
14
+ /** VibeDev 自己的插件:还没报名字的版本也显示得像样。 */
15
+ export const KNOWN_CONTRIBUTORS = Object.freeze({
16
+ 'dsh-film': Object.freeze({ title: '影视工作台', icon: 'film' }),
17
+ })
18
+
19
+ /** 去掉多余空白,截到 `max` 个字(截过的末尾是省略号);不是字符串或只有空白时是 undefined。 */
20
+ function cut(value, max) {
21
+ if (typeof value !== 'string') return undefined
22
+ const text = value.replace(/\s+/g, ' ').trim()
23
+ if (text === '') return undefined
24
+ const letters = Array.from(text)
25
+ return letters.length <= max ? text : `${letters.slice(0, max - 1).join('')}…`
26
+ }
27
+
28
+ /**
29
+ * 插件报上来的名字和图标里能用的部分。
30
+ * @param {unknown} input `{ title?, icon? }`
31
+ * @returns {{ title?: string, icon?: string }}
32
+ */
33
+ export function displayInput(input) {
34
+ if (input === null || typeof input !== 'object') return {}
35
+ const title = cut(input.title, DISPLAY_TITLE_MAX)
36
+ const icon = ICONS.includes(input.icon) ? input.icon : undefined
37
+ return { ...(title === undefined ? {} : { title }), ...(icon === undefined ? {} : { icon }) }
38
+ }
39
+
40
+ /** 每个插件在小岛上的名字和图标。 */
41
+ export function createDisplays() {
42
+ /** 插件名 → 它自己报的。 */
43
+ const declared = new Map()
44
+ return {
45
+ /**
46
+ * 插件报上名字和图标。返回和之前比有没有变(变了的话,已经在岛上的东西要重发一遍)。
47
+ * @param {string} owner
48
+ * @param {unknown} input
49
+ */
50
+ declare(owner, input) {
51
+ const next = displayInput(input)
52
+ if (Object.keys(next).length === 0) return false
53
+ const before = JSON.stringify(declared.get(owner) ?? {})
54
+ declared.set(owner, next)
55
+ return JSON.stringify(next) !== before
56
+ },
57
+ /**
58
+ * 这个插件在小岛上的名字和图标。
59
+ * @param {string} owner
60
+ * @returns {{ title: string, icon: string }}
61
+ */
62
+ of(owner) {
63
+ const own = declared.get(owner) ?? {}
64
+ const known = KNOWN_CONTRIBUTORS[owner] ?? {}
65
+ return { title: own.title ?? known.title ?? owner, icon: own.icon ?? known.icon ?? 'box' }
66
+ },
67
+ }
68
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * `ctx.island.contributor(名字)` 交给插件的那个对象:后台任务、最近生成、通知,合在一个入口上。
3
+ *
4
+ * 各自的规则在各自的模块里:任务在 contributions.js,最近生成在 recent.js,通知在 island-items.js,
5
+ * 通知上的「查看」在 openers.js。这里只是把它们按插件名接起来。
6
+ */
7
+
8
+ const refuse = () => false
9
+ const idleJob = Object.freeze({ update: () => undefined, finish: () => undefined, remove: () => undefined })
10
+
11
+ /** 名字不能用时给的入口:什么都不做。 */
12
+ export const IDLE_ENTRY = Object.freeze({
13
+ task: () => idleJob,
14
+ recent: refuse,
15
+ forget: refuse,
16
+ notify: refuse,
17
+ clear: () => undefined,
18
+ })
19
+
20
+ /**
21
+ * @param {string} name 插件名
22
+ * @param {object} books
23
+ * @param {{ contributor(name: string): { task: Function, clear(): void } }} books.tasks contributions.js
24
+ * @param {{ put: Function, forget: Function, clear(name: string): void }} books.recent recent.js
25
+ * @param {{ notify(name: string, input: unknown, openId?: string): boolean }} books.items island-items.js
26
+ * @param {{ register(name: string, open: () => void): string, clear(name: string): void }} books.openers openers.js
27
+ */
28
+ export function contributorEntry(name, { tasks, recent, items, openers }) {
29
+ if (typeof name !== 'string' || name.trim() === '') return IDLE_ENTRY
30
+ const own = tasks.contributor(name)
31
+ return Object.freeze({
32
+ /** 一条后台任务:`task(id, { title, subtitle?, progress? })`,返回 `update` / `finish` / `remove`。 */
33
+ task: (id, spec) => own.task(id, spec),
34
+ /** 一条最近生成:`recent(id, { title, subtitle?, media?, thumbnail?, at?, open? })`。返回收下了没有。 */
35
+ recent: (id, spec) => recent.put(name, id, spec),
36
+ /** 撤下一条最近生成。 */
37
+ forget: (id) => recent.forget(name, id),
38
+ /** 一条会自己消失的通知:`notify({ title, body?, open? })`;有 `open` 时带「查看」。一分钟最多 3 条。 */
39
+ notify(spec) {
40
+ const open = typeof spec?.open === 'function' ? spec.open : undefined
41
+ return items.notify(name, spec, open === undefined ? undefined : openers.register(name, open))
42
+ },
43
+ /** 这个插件的任务和最近生成全部撤下。 */
44
+ clear() {
45
+ own.clear()
46
+ recent.clear(name)
47
+ },
48
+ })
49
+ }
package/index.js CHANGED
@@ -34,6 +34,10 @@ import { diagnosticsFileName, diagnosticsReport } from './diagnostics.js'
34
34
  import { wechatSummary } from './wechat.js'
35
35
  import { executableCandidates, missingExecutableMessage } from './executable.js'
36
36
  import { createContributions } from './contributions.js'
37
+ import { createDisplays } from './contributor-display.js'
38
+ import { createRecentBook } from './recent.js'
39
+ import { createOpeners } from './openers.js'
40
+ import { contributorEntry } from './contributor-entry.js'
37
41
 
38
42
  const PROTOCOL_VERSION = 1
39
43
  const APP_DIR_NAME = 'VibeDev'
@@ -224,11 +228,17 @@ export function apply(ctx, config) {
224
228
  */
225
229
  const contributionAllowed = (plugin) =>
226
230
  settings.contrib?.enabled !== false && !(settings.contrib?.blocked ?? []).includes(plugin)
231
+ /** 每个插件在小岛上的名字和图标(插件自己报的,或者认得的 VibeDev 插件的默认值)。 */
232
+ const displays = createDisplays()
233
+ const displayOf = (plugin) => displays.of(plugin)
234
+ /** 通知上的「查看」:岛上点了之后调回插件。 */
235
+ const openers = createOpeners({ log })
227
236
  const islandItems = createIslandItems({
228
237
  send: (method, params) => {
229
238
  if (ready) notify(method, params)
230
239
  },
231
240
  allowed: contributionAllowed,
241
+ displayOf,
232
242
  setTimer: later,
233
243
  clearTimer: cancel,
234
244
  log,
@@ -243,11 +253,23 @@ export function apply(ctx, config) {
243
253
  cancel,
244
254
  log,
245
255
  allowed: contributionAllowed,
256
+ displayOf,
246
257
  })
247
- /** 放过东西的插件(两本账合起来),设置页上每个一行开关。 */
258
+ /** 别的插件的「最近生成」(`contributor(名字).recent`)。 */
259
+ const recentBook = createRecentBook({
260
+ send: (method, params) => {
261
+ if (!ready) return false
262
+ notify(method, params)
263
+ return true
264
+ },
265
+ displayOf,
266
+ allowed: contributionAllowed,
267
+ log,
268
+ })
269
+ /** 放过东西的插件(几本账合起来),设置页上每个一行开关。 */
248
270
  const contributorSummary = () => {
249
271
  const merged = new Map()
250
- for (const item of [...islandItems.summary(), ...pluginTasks.summary()]) {
272
+ for (const item of [...islandItems.summary(), ...pluginTasks.summary(), ...recentBook.summary()]) {
251
273
  const known = merged.get(item.name)
252
274
  merged.set(item.name, { name: item.name, items: (known?.items ?? 0) + item.items })
253
275
  }
@@ -469,6 +491,7 @@ export function apply(ctx, config) {
469
491
  // 刚被关掉的插件(或者整个入口关了):它们放在岛上的东西撤下来。
470
492
  for (const { name } of islandItems.summary()) if (!contributionAllowed(name)) islandItems.clear(name)
471
493
  pluginTasks.refresh()
494
+ recentBook.refresh()
472
495
  // 深浅的设置可能刚改了。
473
496
  pushTheme()
474
497
  log('settings saved')
@@ -576,6 +599,7 @@ export function apply(ctx, config) {
576
599
  // 别的插件放的东西:新起来的岛屿上还没有。
577
600
  islandItems.replay()
578
601
  pluginTasks.islandStarted()
602
+ recentBook.islandStarted()
579
603
  sentScheme = undefined
580
604
  pushTheme()
581
605
  // 岛屿刚连上:页面里还选着的文字再给它一次,不用等用户重新选。
@@ -666,6 +690,12 @@ export function apply(ctx, config) {
666
690
  )
667
691
  break
668
692
  }
693
+ // 岛上点了一条最近生成,或者通知上的「查看」:把 VibeDev 带到前台由岛屿自己做,这里调回放它的插件。
694
+ case 'contrib/open': {
695
+ const id = typeof params?.id === 'string' ? params.id : ''
696
+ if (!recentBook.open(id) && !openers.run(id)) log(`contrib/open: nothing to open for ${JSON.stringify(id)}`)
697
+ break
698
+ }
669
699
  case 'state/error':
670
700
  lastError = JSON.stringify(params)
671
701
  log(`island reported an error: ${lastError}`)
@@ -1008,6 +1038,8 @@ export function apply(ctx, config) {
1008
1038
  followed.delete(plugin)
1009
1039
  islandItems.clear(plugin)
1010
1040
  pluginTasks.contributor(plugin).clear()
1041
+ recentBook.clear(plugin)
1042
+ openers.clear(plugin)
1011
1043
  })
1012
1044
  followed.add(plugin)
1013
1045
  } catch (error) {
@@ -1026,11 +1058,13 @@ export function apply(ctx, config) {
1026
1058
  ctx,
1027
1059
  [Symbol.for('cordis.tracker')]: { associate: 'island', property: 'ctx' },
1028
1060
  /**
1029
- * 后台任务的入口:报上名字,拿到 `task(id, { title, subtitle?, progress? })`,返回的句柄有
1030
- * `update` / `finish` / `remove`;`clear()` 撤下自己的全部(规则见 contributions.js)。
1061
+ * 一个插件的入口:报上名字(和可选的 `{ title, icon }`:小岛上怎么称呼它),拿到后台任务
1062
+ * `task(id, { title, subtitle?, progress? })`(返回 `update` / `finish` / `remove`)、最近生成
1063
+ * `recent(id, { title, subtitle?, media?, thumbnail?, at?, open? })` / `forget(id)`、通知
1064
+ * `notify({ title, body?, open? })`,以及撤下自己全部任务和最近生成的 `clear()`(规则见 contributor-entry.js)。
1031
1065
  * 认得出调用方时用它的包名,报的名字只在认不出时用:一个插件不能冒用别人的名字绕过开关。
1032
1066
  */
1033
- contributor(owner) {
1067
+ contributor(owner, display) {
1034
1068
  const tracked = trackedCaller(this?.ctx)
1035
1069
  const name = tracked === 'unknown' ? owner : tracked
1036
1070
  if (tracked !== 'unknown') follow(this.ctx, name)
@@ -1038,7 +1072,12 @@ export function apply(ctx, config) {
1038
1072
  contributorsSeen.add(name)
1039
1073
  log(`contrib: ${String(name)} can now put background tasks on the island (it called itself "${String(owner)}")`)
1040
1074
  }
1041
- return pluginTasks.contributor(name)
1075
+ if (typeof name === 'string' && displays.declare(name, display)) {
1076
+ log(`contrib: ${name} is shown as ${JSON.stringify(displays.of(name))}`)
1077
+ pluginTasks.refresh()
1078
+ recentBook.refresh()
1079
+ }
1080
+ return contributorEntry(name, { tasks: pluginTasks, recent: recentBook, items: islandItems, openers })
1042
1081
  },
1043
1082
  /** 一条状态:`{ id, title, detail? }`。返回收下了没有。 */
1044
1083
  status(input) {
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.2.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",
@@ -36,6 +36,10 @@
36
36
  "wechat.js",
37
37
  "contributions.js",
38
38
  "executable.js",
39
+ "contributor-display.js",
40
+ "contributor-entry.js",
41
+ "recent.js",
42
+ "openers.js",
39
43
  "CHANGELOG.md",
40
44
  "LICENSE",
41
45
  "bin",
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
+ }