universal-plugin-hub 1.0.35 → 1.0.50

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/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "title": "Universal Plugin Hub",
4
4
  "displayName": "Universal Plugin Hub",
5
5
  "description": "在 DSH 中使用 Claude Code、Codex 等软件生态的插件,一站式管理插件、Skills 与 MCP。支持添加 Git 插件源和 marketplace、上传插件和 Skills、添加 MCP 服务器,自动扫描并开关本地 Skills,接入插件提供的子代理、MCP、Hooks 与 LSP。",
6
- "version": "1.0.35",
6
+ "version": "1.0.50",
7
7
  "engines": {
8
8
  "dsh": ">=0.1.5-rc.1"
9
9
  },
@@ -34,7 +34,8 @@
34
34
  ],
35
35
  "dependencies": {
36
36
  "@modelcontextprotocol/sdk": "1.32.1",
37
- "js-yaml": "^5.3.0"
37
+ "js-yaml": "^5.3.0",
38
+ "pngjs": "7.0.0"
38
39
  },
39
40
  "peerDependencies": {
40
41
  "@deepseek-ai/cordis": ">=4.0.1 <5.0.0"
package/src/icons.js CHANGED
@@ -1,7 +1,8 @@
1
- import { statSync, realpathSync, readFileSync } from 'node:fs'
1
+ import { statSync, realpathSync, readFileSync, readdirSync, openSync, readSync, closeSync, mkdirSync, writeFileSync, rmSync } from 'node:fs'
2
2
  import { mkdir, readFile, writeFile, stat } from 'node:fs/promises'
3
3
  import { join, relative, isAbsolute, posix } from 'node:path'
4
4
  import { createHash } from 'node:crypto'
5
+ import { PNG } from 'pngjs'
5
6
  import { marketRoot } from './store.js'
6
7
  import { pluginPath } from './market.js'
7
8
 
@@ -38,10 +39,259 @@ export function readLocalIcon(root, path) {
38
39
  return { buffer, contentType }
39
40
  }
40
41
 
41
- /** Carry manifest assets through marketplace rows without exposing filesystem paths. */
42
+ // Claude's plugin manifest has no icon field and marketplace entries do not
43
+ // carry one either, so a plugin's artwork can only be found on disk. Matching a
44
+ // fixed list of nine filenames missed most of it, which sent those rows to the
45
+ // network for the author's GitHub avatar: the wrong picture, and a round trip
46
+ // on every cold start.
47
+ const ICON_FILE = /\.(?:svg|png|webp|jpe?g|ico)$/i
48
+ // Names that promise artwork, names that promise a different kind of picture.
49
+ const ICON_STRONG = /(?:^|[-_. ])(?:app[-_]?icon|icon|glyph|favicon|emblem)(?:[-_. ]|$)/i
50
+ const ICON_WEAK = /(?:^|[-_. ])(?:logo|brand|avatar|mark)(?:[-_. ]|$)/i
51
+ // Anchored like the two patterns above: an unanchored substring test rejected
52
+ // `heroku-icon.png` on "hero" and `photon-logo.png` on "photo", which is the
53
+ // very failure this discovery is meant to remove.
54
+ const ICON_NOISE = /(?:^|[-_. ])(?:screenshots?|screen[-_]?shots?|examples?|previews?|banners?|covers?|thumbs?|thumbnails?|hero|demo|readme|illustrations?|diagrams?|charts?|backgrounds?|wallpapers?|social|samples?|fixtures?|mocks?|placeholders?|spinners?|loaders?|sprites?|swatches?|captures?|photos?)(?:[-_. ]|$)/i
55
+ const ICON_SKIP_DIRS = new Set([
56
+ 'node_modules', '.git', '.github', 'skills', 'skill', 'commands', 'command', 'agents', 'hooks',
57
+ 'docs', 'doc', 'tests', 'test', '__tests__', 'scripts', 'src', 'lib', 'dist', 'build',
58
+ 'examples', 'templates', 'locales', 'i18n',
59
+ ])
60
+
61
+ /**
62
+ * Pixel size read from a file header.
63
+ *
64
+ * Cheap enough to run on every candidate, and it is the only signal that
65
+ * separates an icon from a banner or a screenshot regardless of its name.
66
+ *
67
+ * The format is decided by `imageContentType` so there is one answer to "what
68
+ * is this file" — the PNG branch below only reads fields, it does not re-sniff
69
+ * magic numbers. Note the PNG branch needs a full 24-byte IHDR, which is
70
+ * checked before reading.
71
+ */
72
+ function imageSize(file) {
73
+ let handle
74
+ try {
75
+ handle = openSync(file, 'r')
76
+ const head = Buffer.alloc(4096)
77
+ const read = readSync(handle, head, 0, head.length, 0)
78
+ const bytes = head.subarray(0, read)
79
+ const kind = imageContentType(bytes)
80
+ if (kind === 'image/png') {
81
+ if (bytes.length < 24) return null
82
+ return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) }
83
+ }
84
+ if (kind !== 'image/svg+xml') return null
85
+ const svg = bytes.toString('utf8').match(/<svg\b[^>]*>/i)
86
+ if (!svg) return null
87
+ const attribute = (name) => {
88
+ const found = svg[0].match(new RegExp(`\\b${name}\\s*=\\s*["']\\s*([0-9.]+)`, 'i'))
89
+ return found ? Number(found[1]) : null
90
+ }
91
+ const width = attribute('width')
92
+ const height = attribute('height')
93
+ if (width > 0 && height > 0) return { width, height }
94
+ const box = svg[0].match(/\bviewBox\s*=\s*["']\s*([-\d.]+)[ ,]+([-\d.]+)[ ,]+([\d.]+)[ ,]+([\d.]+)/i)
95
+ if (box && Number(box[3]) > 0 && Number(box[4]) > 0) return { width: Number(box[3]), height: Number(box[4]) }
96
+ } catch {
97
+ } finally {
98
+ if (handle !== undefined) try { closeSync(handle) } catch {}
99
+ }
100
+ return null
101
+ }
102
+
103
+ /**
104
+ * Icon files a plugin ships without declaring, best candidate first.
105
+ *
106
+ * Ranked the way a desktop picks an application icon: artwork by name first,
107
+ * then squareness and size, then how close the file sits to the plugin root.
108
+ * A file needs at least one naming signal, so a passing diagram cannot win.
109
+ */
110
+ function discoverIconFiles(dir, pluginName) {
111
+ if (!dir) return []
112
+ const key = String(pluginName || '').replace(/[^a-z0-9]/gi, '').toLowerCase()
113
+ const found = []
114
+ let visited = 0
115
+
116
+ const walk = (relative, depth) => {
117
+ if (depth > 2 || visited > 400) return
118
+ let entries
119
+ try { entries = readdirSync(relative ? join(dir, relative) : dir, { withFileTypes: true }) } catch { return }
120
+ for (const entry of entries) {
121
+ const path = relative ? `${relative}/${entry.name}` : entry.name
122
+ if (entry.isDirectory()) {
123
+ if (!ICON_SKIP_DIRS.has(entry.name.toLowerCase())) walk(path, depth + 1)
124
+ continue
125
+ }
126
+ visited++
127
+ if (!ICON_FILE.test(entry.name) || ICON_NOISE.test(entry.name)) continue
128
+
129
+ const base = entry.name.replace(/\.[^.]+$/, '').toLowerCase()
130
+ const flat = base.replace(/[^a-z0-9]/g, '')
131
+ let score = 0
132
+ if (ICON_STRONG.test(base)) score += 12
133
+ else if (ICON_WEAK.test(base)) score += 8
134
+ if (key && (flat === key || (flat.length >= 3 && key.startsWith(flat)) || (key.length >= 3 && flat.startsWith(key)))) score += 9
135
+ if (score === 0) continue
136
+
137
+ const size = imageSize(join(dir, path))
138
+ // A portrait mark is a logotype, not an app tile: it is authored to sit on
139
+ // the publisher's own background, so drawing it into our rounded container
140
+ // shows a bare glyph over whatever our well is. Exa's 151x182 blue line
141
+ // art looked like a blank blue tile this way. It is kept — dropping it
142
+ // only moved the problem to a GitHub avatar — but flagged so it is tried
143
+ // after the brand artwork the client already knows.
144
+ const portrait = !!size && Math.abs(size.width - size.height) / Math.max(size.width, size.height) > 0.15
145
+ if (size && !portrait) {
146
+ // An icon is square, and a 4:1 file is a banner however it is named.
147
+ score += 6
148
+ const edge = Math.min(size.width, size.height)
149
+ if (edge >= 96) score += 3
150
+ else if (edge < 32) score -= 14
151
+ // A file too small to read is not artwork at any shape.
152
+ if (edge < 24) score -= 20
153
+ }
154
+ score += Math.max(0, 3 - depth)
155
+ if (/\.svg$/i.test(entry.name)) score += 1
156
+ found.push({ path, score, dark: /dark/i.test(base), portrait })
157
+ }
158
+ }
159
+
160
+ walk('', 0)
161
+ return found.sort((a, b) => b.score - a.score || a.path.localeCompare(b.path))
162
+ }
163
+
164
+ // Small local artwork can travel in the row directly. Larger PNGs use a
165
+ // bounded 96px preview, cached separately from the original. Remote images
166
+ // only contribute a preview when bytes already exist in the proxy cache;
167
+ // parsing a catalog never waits on an upstream image request.
168
+
169
+ const INLINE_LIMIT = 12 * 1024
170
+ // A preview is carried once per URL rather than duplicated in both theme arrays.
171
+ // This covers ordinary raster logos while keeping large artwork out of list JSON.
172
+ const PREVIEW_LIMIT = 64 * 1024
173
+ // Decoding runs synchronously inside catalog parsing, once per row, so the
174
+ // bound has to cover the decode itself and not just the file size.
175
+ const PREVIEW_MAX_PIXELS = 262144
176
+ const PREVIEWS_DIR = 'previews'
177
+ const PREVIEW_CACHE_KEEP = 200
178
+ const previewMemory = new Map()
179
+ let lastPreviewPrune = 0
180
+
181
+ /** A local file's bytes as a data URL, or null when it is too big or unreadable. */
182
+ function inlineFile(file) {
183
+ try {
184
+ const info = statSync(file)
185
+ if (!info.isFile() || info.size > INLINE_LIMIT) return null
186
+ const buffer = readFileSync(file)
187
+ const contentType = imageContentType(buffer)
188
+ return contentType ? `data:${contentType};base64,${buffer.toString('base64')}` : null
189
+ } catch { return null }
190
+ }
191
+
192
+ function inlinePreview(buffer) {
193
+ const contentType = imageContentType(buffer)
194
+ if (!contentType) return null
195
+ if (contentType === 'image/png' && buffer.length > INLINE_LIMIT) {
196
+ if (buffer.length < 24) return null
197
+ const w = buffer.readUInt32BE(16), h = buffer.readUInt32BE(20)
198
+ // Reject before decoding: the decode is the expensive part.
199
+ if (!w || !h || w * h > PREVIEW_MAX_PIXELS) return null
200
+ // Version the derived cache by content and algorithm, so replacing artwork
201
+ // cannot leave an old thumbnail behind. Originals are never overwritten.
202
+ const key = createHash('sha256').update(buffer).digest('hex')
203
+ const directory = join(marketRoot(), 'icons', PREVIEWS_DIR)
204
+ const file = join(directory, `96-v1-${key}.png`)
205
+ try {
206
+ const saved = readFileSync(file)
207
+ if (saved.length <= INLINE_LIMIT && imageContentType(saved) === 'image/png') return `data:image/png;base64,${saved.toString('base64')}`
208
+ } catch {}
209
+ let image
210
+ try { image = PNG.sync.read(buffer) } catch { return null }
211
+ const ratio = Math.min(1, 96 / Math.max(w, h))
212
+ const width = Math.max(1, Math.round(w * ratio)), height = Math.max(1, Math.round(h * ratio))
213
+ const data = Buffer.alloc(width * height * 4)
214
+ // Area sampling with premultiplied alpha preserves fine edges on both
215
+ // themes; simply averaging transparent RGB creates dark logo fringes.
216
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
217
+ const left = x * w / width, right = (x + 1) * w / width
218
+ const top = y * h / height, bottom = (y + 1) * h / height
219
+ let red = 0, green = 0, blue = 0, alpha = 0
220
+ for (let sy = Math.floor(top); sy < Math.ceil(bottom); sy++) for (let sx = Math.floor(left); sx < Math.ceil(right); sx++) {
221
+ const weight = (Math.min(right, sx + 1) - Math.max(left, sx)) * (Math.min(bottom, sy + 1) - Math.max(top, sy))
222
+ const i = (sy * w + sx) * 4, a = image.data[i + 3] / 255 * weight
223
+ alpha += a; red += image.data[i] * a; green += image.data[i + 1] * a; blue += image.data[i + 2] * a
224
+ }
225
+ const i = (y * width + x) * 4
226
+ if (alpha) { data[i] = Math.round(red / alpha); data[i + 1] = Math.round(green / alpha); data[i + 2] = Math.round(blue / alpha) }
227
+ data[i + 3] = Math.round(255 * alpha / ((right - left) * (bottom - top)))
228
+ }
229
+ const thumbnail = PNG.sync.write({ width, height, data }, { deflateLevel: 9, deflateStrategy: 0 })
230
+ if (thumbnail.length > INLINE_LIMIT) return null
231
+ try {
232
+ mkdirSync(directory, { recursive: true })
233
+ writeFileSync(file, thumbnail)
234
+ prunePreviewCache(directory)
235
+ } catch {}
236
+ return `data:image/png;base64,${thumbnail.toString('base64')}`
237
+ }
238
+ return buffer.length <= PREVIEW_LIMIT ? `data:${contentType};base64,${buffer.toString('base64')}` : null
239
+ }
240
+
241
+ /** Content-addressed thumbnails are never overwritten, so they need pruning. */
242
+ function prunePreviewCache(directory) {
243
+ const now = Date.now()
244
+ if (now - lastPreviewPrune < 60 * 60 * 1000) return
245
+ lastPreviewPrune = now
246
+ try {
247
+ const files = readdirSync(directory)
248
+ .map((entry) => {
249
+ try { const info = statSync(join(directory, entry)); return info.isFile() ? { entry, at: info.mtimeMs } : null } catch { return null }
250
+ })
251
+ .filter(Boolean)
252
+ .sort((a, b) => b.at - a.at)
253
+ for (const stale of files.slice(PREVIEW_CACHE_KEEP)) {
254
+ try { rmSync(join(directory, stale.entry), { force: true }) } catch {}
255
+ }
256
+ } catch {}
257
+ }
258
+
259
+ function previewFile(file) {
260
+ try {
261
+ const info = statSync(file)
262
+ if (!info.isFile() || info.size > MAX_BYTES) return null
263
+ const key = `${file}:${info.mtimeMs}:${info.size}`
264
+ if (previewMemory.has(key)) return previewMemory.get(key)
265
+ const preview = inlinePreview(readFileSync(file))
266
+ if (previewMemory.size >= 256) previewMemory.delete(previewMemory.keys().next().value)
267
+ previewMemory.set(key, preview)
268
+ return preview
269
+ } catch { return null }
270
+ }
271
+
272
+ function cachedIconPreview(url) {
273
+ const cached = memory.get(url)
274
+ if (cached) {
275
+ try { return inlinePreview(cached.buffer) } catch { return null }
276
+ }
277
+ return previewFile(iconCacheFile(url))
278
+ }
279
+
280
+ /**
281
+ * Carry manifest assets through marketplace rows without exposing filesystem paths.
282
+ *
283
+ * Local artwork is inlined as a data URL so a cold start paints it in the same
284
+ * frame as the row itself. Rows still carry a `/api/plugin-icon` URL for the
285
+ * full-size copy and for the installed-plugin route, but the first candidate is
286
+ * always something the client can draw without a round trip.
287
+ */
42
288
  export function buildPluginIcons(meta, { sourceId, name, dir, source } = {}) {
43
289
  const ui = meta?.interface || {}
44
290
  const proxy = (url) => `/universal-plugin-hub/api/icon?v=2&u=${encodeURIComponent(url)}`
291
+ // Local files are stat'd once here and the same File is reused for the inline
292
+ // copy, so discovering artwork and inlining it is one pass over the disk.
293
+ const files = new Map()
294
+ const previews = {}
45
295
  const toUrl = (value) => {
46
296
  if (typeof value !== 'string' || !value.trim()) return null
47
297
  if (/^https?:\/\//i.test(value)) return proxy(value)
@@ -51,7 +301,9 @@ export function buildPluginIcons(meta, { sourceId, name, dir, source } = {}) {
51
301
  const file = pluginPath(dir, value)
52
302
  const info = statSync(file)
53
303
  if (!info.isFile() || info.size > MAX_BYTES) return null
54
- return `/universal-plugin-hub/api/plugin-icon?sourceId=${encodeURIComponent(sourceId)}&name=${encodeURIComponent(name)}&path=${encodeURIComponent(value)}&v=${info.mtimeMs}-${info.size}`
304
+ const url = `/universal-plugin-hub/api/plugin-icon?sourceId=${encodeURIComponent(sourceId)}&name=${encodeURIComponent(name)}&path=${encodeURIComponent(value)}&v=${info.mtimeMs}-${info.size}`
305
+ files.set(url, file)
306
+ return url
55
307
  } catch { return null }
56
308
  }
57
309
  const repo = source?.url?.match(/^https:\/\/github\.com\/([^/]+)\/([^/#?]+?)(?:\.git)?\/?$/i)
@@ -65,10 +317,58 @@ export function buildPluginIcons(meta, { sourceId, name, dir, source } = {}) {
65
317
  }
66
318
  const common = [ui.composerIcon, ui.icon, ui.iconSmall, ui.iconLarge, ui.logo, meta?.icon, meta?.iconUrl, meta?.logo]
67
319
  const values = (theme) => common.flatMap((v) => typeof v === 'object' && v ? [v[theme], v.default, v.url, v.src, v[theme === 'dark' ? 'light' : 'dark']] : [v])
68
- const defaults = dir ? ['assets/icon.svg', 'assets/logo.svg', 'assets/icon.png', 'assets/codex-icon.png', 'assets/logo.png', 'icon.svg', 'logo.svg', 'icon.png', 'logo.png'] : []
69
- const light = [...new Set([ui.iconLight, ui.logoLight, meta?.iconLight, ...values('light'), ...defaults].map(toUrl).filter(Boolean))]
70
- const dark = [...new Set([ui.iconDark, ui.logoDark, meta?.iconDark, ...values('dark'), ...defaults].map(toUrl).filter(Boolean))]
71
- return { light, dark }
320
+ const found = discoverIconFiles(dir, name)
321
+ // Portrait artwork is not a tile candidate: it leaves the normal ranking
322
+ // entirely and is reported separately, so nothing can arrange it back into
323
+ // the lead position.
324
+ const tiles = found.filter((f) => !f.portrait)
325
+ const plain = tiles.filter((f) => !f.dark).map((f) => f.path)
326
+ // A dark-mode variant is a bonus, not a requirement: a plugin that ships only
327
+ // one dark-named logo still needs a light-mode picture.
328
+ const shade = tiles.filter((f) => f.dark).map((f) => f.path)
329
+ const portrait = found.filter((f) => f.portrait).map((f) => f.path)
330
+ const build = (theme) => {
331
+ const declared = theme === 'dark'
332
+ ? [ui.iconDark, ui.logoDark, meta?.iconDark, ...values('dark'), ...shade, ...plain]
333
+ : [ui.iconLight, ui.logoLight, meta?.iconLight, ...values('light'), ...plain, ...shade]
334
+ const urls = [...new Set(declared.map(toUrl).filter(Boolean))]
335
+ // The inline copy leads, so the first candidate needs no request at all.
336
+ // Only local files lead with their bytes. The separately carried preview
337
+ // never changes candidate priority or replaces the normal refresh request.
338
+ const inline = urls.map((url) => files.get(url) && inlineFile(files.get(url))).find(Boolean)
339
+ if (!inline && urls[0]) {
340
+ const first = urls[0]
341
+ const remote = first.startsWith('/universal-plugin-hub/api/icon?') ? new URL(first, 'http://localhost').searchParams.get('u') : null
342
+ const preview = files.has(first) ? previewFile(files.get(first)) : remote && cachedIconPreview(remote)
343
+ if (preview) previews[first] = preview
344
+ }
345
+ return inline ? [inline, ...urls.filter((url) => url !== inline)] : urls
346
+ }
347
+ const served = (paths) => [...new Set(paths.map(toUrl).filter(Boolean))]
348
+ // Reported apart from the tile candidates so the client can try them after
349
+ // the brand artwork it knows about, instead of leading every row with them.
350
+ const light = build('light')
351
+ const dark = build('dark')
352
+ // Avatar-only rows already have reusable bytes in the proxy's disk cache.
353
+ // Expose those as a preview without starting network work during parsing;
354
+ // the normal image request still refreshes expired cache entries.
355
+ if (!light.length || !dark.length) {
356
+ const githubOwner = (url) => typeof url === 'string' ? url.match(/github\.com\/([^/]+)/i)?.[1] : null
357
+ let owner = [source?.url || meta?.source?.url, meta?.homepage].map(githubOwner).find((value) => value && !value.toLowerCase().includes('anthropics'))
358
+ const author = (typeof meta?.author === 'string' ? meta.author : meta?.author?.name || '').trim().toLowerCase()
359
+ if (!owner && /^[a-z0-9_-]+$/i.test(author) && author !== 'anthropic') owner = author
360
+ if (owner) {
361
+ const url = `https://github.com/${encodeURIComponent(owner)}.png?size=80`
362
+ const preview = cachedIconPreview(url)
363
+ if (preview) previews[proxy(url)] = preview
364
+ }
365
+ }
366
+ return {
367
+ light,
368
+ dark,
369
+ portrait: { light: served(portrait), dark: served(portrait) },
370
+ ...(Object.keys(previews).length ? { previews } : {}),
371
+ }
72
372
  }
73
373
 
74
374
  function remember(key, value) {
@@ -77,6 +377,29 @@ function remember(key, value) {
77
377
  return value
78
378
  }
79
379
 
380
+ function iconCacheFile(url) {
381
+ return join(marketRoot(), 'icons', `icon_${createHash('md5').update(url).digest('hex')}.bin`)
382
+ }
383
+
384
+ /** Fetch one icon from upstream and store it. Throws so callers can decide. */
385
+ async function downloadIcon(url, file) {
386
+ const response = await fetch(url, { signal: AbortSignal.timeout(4000), headers: { Accept: 'image/avif,image/webp,image/svg+xml,image/*;q=0.8' } })
387
+ if (!response.ok) throw new Error(`Icon request failed: ${response.status}`)
388
+ if (Number(response.headers.get('content-length')) > MAX_BYTES) { await response.body?.cancel(); throw new Error('Icon too large') }
389
+ const chunks = []
390
+ let size = 0
391
+ for await (const chunk of response.body) {
392
+ size += chunk.length
393
+ if (size > MAX_BYTES) throw new Error('Icon too large')
394
+ chunks.push(chunk)
395
+ }
396
+ const buffer = Buffer.concat(chunks)
397
+ const contentType = imageContentType(buffer)
398
+ if (!contentType) throw new Error('Unsupported icon content')
399
+ try { await mkdir(join(marketRoot(), 'icons'), { recursive: true }); await writeFile(file, buffer) } catch {}
400
+ return { buffer, contentType }
401
+ }
402
+
80
403
  /** Share concurrent loads, cache successful images, and briefly suppress failed URLs. */
81
404
  export async function getOrFetchIcon(url) {
82
405
  if (typeof url !== 'string' || !/^https?:\/\//i.test(url)) throw new Error('Invalid icon URL')
@@ -93,30 +416,34 @@ export async function getOrFetchIcon(url) {
93
416
  if (failures.get(url) > Date.now()) throw new Error('Icon temporarily unavailable')
94
417
  if (pending.has(url)) return pending.get(url)
95
418
  const task = (async () => {
96
- const file = join(marketRoot(), 'icons', `icon_${createHash('md5').update(url).digest('hex')}.bin`)
419
+ const file = iconCacheFile(url)
420
+ let expired = null
97
421
  try {
98
422
  const info = await stat(file)
99
- if (info.size <= MAX_BYTES && Date.now() - info.mtimeMs < CACHE_TTL) {
423
+ if (info.size <= MAX_BYTES) {
100
424
  const buffer = await readFile(file)
101
425
  const contentType = imageContentType(buffer)
102
- if (contentType) return remember(url, { buffer, contentType })
426
+ if (contentType) {
427
+ if (Date.now() - info.mtimeMs < CACHE_TTL) return remember(url, { buffer, contentType })
428
+ expired = { buffer, contentType }
429
+ }
103
430
  }
104
431
  } catch {}
105
- const response = await fetch(url, { signal: AbortSignal.timeout(4000), headers: { Accept: 'image/avif,image/webp,image/svg+xml,image/*;q=0.8' } })
106
- if (!response.ok) throw new Error(`Icon request failed: ${response.status}`)
107
- if (Number(response.headers.get('content-length')) > MAX_BYTES) { await response.body?.cancel(); throw new Error('Icon too large') }
108
- const chunks = []
109
- let size = 0
110
- for await (const chunk of response.body) {
111
- size += chunk.length
112
- if (size > MAX_BYTES) throw new Error('Icon too large')
113
- chunks.push(chunk)
432
+ // Stale-while-revalidate: an expired copy is still the right picture, so
433
+ // hand it back immediately and refresh behind the scenes. Waiting on the
434
+ // network here is what made those icons appear to reload on every restart —
435
+ // and a failed refresh must never turn a usable icon into a 502.
436
+ if (expired) {
437
+ // Record the failure in the same cooldown the foreground path uses, or a
438
+ // permanently dead URL launches a fresh 4s fetch on every request while
439
+ // continuing to serve the stale bytes.
440
+ downloadIcon(url, file).catch(() => {
441
+ if (failures.size >= 256) failures.delete(failures.keys().next().value)
442
+ failures.set(url, Date.now() + 60_000)
443
+ })
444
+ return remember(url, expired)
114
445
  }
115
- const buffer = Buffer.concat(chunks)
116
- const contentType = imageContentType(buffer)
117
- if (!contentType) throw new Error('Unsupported icon content')
118
- try { await mkdir(join(marketRoot(), 'icons'), { recursive: true }); await writeFile(file, buffer) } catch {}
119
- return remember(url, { buffer, contentType })
446
+ return remember(url, await downloadIcon(url, file))
120
447
  })()
121
448
  pending.set(url, task)
122
449
  try { return await task } catch (error) {
package/src/index.js CHANGED
@@ -10,6 +10,7 @@ import { mountRoutes } from './routes.js'
10
10
  import { cancelAllOAuthVerifications } from './oauth.js'
11
11
  import { syncAllInstalledSkillsToDsh, installProfilePackages, findDshMainNodeModules, LSP_HOST_PACKAGES, HOOK_HOST_PACKAGES } from './install.js'
12
12
  import { createSkillsManager } from './skills.js'
13
+ import { restoreUploadedSkills } from './skill-uploads.js'
13
14
  import { createProfileApplicator } from './runtime.js'
14
15
  import { createRequire } from 'node:module'
15
16
  import { join } from 'node:path'
@@ -31,6 +32,8 @@ export function apply(ctx) {
31
32
 
32
33
  // Ensure all installed plugin skills are immediately synced to $DSH_HOME/skills
33
34
  try {
35
+ restoreUploadedSkills()
36
+
34
37
  syncAllInstalledSkillsToDsh()
35
38
  } catch (err) {
36
39
  ctx.logger?.warn?.(`[universal-plugin-hub] skill sync error: ${err.message}`)