@yuriai/web 0.2.27-beta.3 → 0.2.27-beta.6

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.
Files changed (148) hide show
  1. package/README.md +9 -0
  2. package/dist/assets/{AgentAvatar-kIN4sZMz.js → AgentAvatar-Bi1vvWPC.js} +1 -1
  3. package/dist/assets/AssistantContactStatus-CWq-PDz6.js +3 -0
  4. package/dist/assets/AssistantUnreadBadge-DdJyySwn.js +1 -0
  5. package/dist/assets/AssistantView-Br1iETTs.js +1 -0
  6. package/dist/assets/{DiagramView-DK0iXm9b.js → DiagramView-CI4bTtxy.js} +1 -1
  7. package/dist/assets/{FadeInOnReveal-BJA9Za3T.js → FadeInOnReveal-BB4qEnAn.js} +1 -1
  8. package/dist/assets/GuiPluginSurface-CguxFUbM.js +1 -0
  9. package/dist/assets/{GuiPluginWindow-l4FYY6S-.js → GuiPluginWindow-DOJ7wuRH.js} +1 -1
  10. package/dist/assets/Icon-t2xvbAyN.js +1 -0
  11. package/dist/assets/{ImageLoadingPlaceholder-DCWssLJG.js → ImageLoadingPlaceholder-D1L13TK0.js} +1 -1
  12. package/dist/assets/{LoadingImage-C_Hryaqe.js → LoadingImage-5rY_edNm.js} +1 -1
  13. package/dist/assets/{MarkdownRenderer-Y6uQXIFH.js → MarkdownRenderer-BlGxjOei.js} +2 -2
  14. package/dist/assets/{MarkdownRendererImpl-qKp1tQrP.js → MarkdownRendererImpl-cE-0AYRg.js} +1 -1
  15. package/dist/assets/{MarkstreamRendererImpl-B_JTod0h.js → MarkstreamRendererImpl-BZyqDl82.js} +1 -1
  16. package/dist/assets/MobileDetailNavigation-tbfsMfB-.js +1 -0
  17. package/dist/assets/{MobileResizableSheet-F1zSUD1S.js → MobileResizableSheet-BeRmT6_x.js} +1 -1
  18. package/dist/assets/{MobileShareBridge-F70fkIfS.js → MobileShareBridge-C3Equ3P_.js} +2 -2
  19. package/dist/assets/MobileTabPageHeader-DQRqAAEf.js +2 -0
  20. package/dist/assets/{MultiRunWindow-D8m6R_4x.js → MultiRunWindow-CAM2XPII.js} +1 -1
  21. package/dist/assets/{OnboardingScreen-BAsPVV_W.js → OnboardingScreen-4ftRerP5.js} +1 -1
  22. package/dist/assets/{OverlayScrollbar-wiRM4AGj.js → OverlayScrollbar-CF0PCvQz.js} +1 -1
  23. package/dist/assets/{SettingsView-izzjIckv.js → SettingsView-2tk4WH7R.js} +13 -13
  24. package/dist/assets/{SettingsWindow-CSuHDq_c.js → SettingsWindow-B9zbeJaW.js} +1 -1
  25. package/dist/assets/TerminalView-DfxvTHye.js +8 -0
  26. package/dist/assets/{ToolOutputDialog-DJs9w1_J.js → ToolOutputDialog-CrjDIhru.js} +1 -1
  27. package/dist/assets/{YuriLogo-aBS6wlYU.js → YuriLogo-QvS1ZEHi.js} +1 -1
  28. package/dist/assets/{appThemeRegistry-BY5rY9-W.js → appThemeRegistry-Bb_DtiV9.js} +1 -1
  29. package/dist/assets/{button-Dt6Ygbc7.js → button-DinGM3tu.js} +1 -1
  30. package/dist/assets/{capgoAdapter-MQ1qpf60.js → capgoAdapter-DufzjXRs.js} +1 -1
  31. package/dist/assets/{collapsible-Dm7OHk7m.js → collapsible-Bh1GLNYV.js} +1 -1
  32. package/dist/assets/context-menu-DpbkRkk1.js +1 -0
  33. package/dist/assets/{diagram-DWZaG3_v.js → diagram-BmG-7Jb4.js} +1 -1
  34. package/dist/assets/{dialog-CjQeHVOc.js → dialog-BXssfGXA.js} +1 -1
  35. package/dist/assets/es-HP_Ise0X.js +15 -0
  36. package/dist/assets/{fileMentionTouchSelection-D7QtVxjI.js → fileMentionTouchSelection-DSl0tj2r.js} +1 -1
  37. package/dist/assets/{fileReferenceActions-BAoEu4z8.js → fileReferenceActions-CGpBSFq4.js} +1 -1
  38. package/dist/assets/fr-D0kJXJ6U.js +13 -0
  39. package/dist/assets/gitApi-Wo0IZow9.js +370 -0
  40. package/dist/assets/{gitApiHttp-DHrRqnYh.js → gitApiHttp-De9liKnG.js} +4 -4
  41. package/dist/assets/host-FR_grJxM.js +1 -0
  42. package/dist/assets/{input-Dq4usRDa.js → input-v8-rVbo-.js} +1 -1
  43. package/dist/assets/insertionBoundaries-CZz7TWJv.js +1 -0
  44. package/dist/assets/ja-BjHKXazE.js +15 -0
  45. package/dist/assets/ko-Llwnl876.js +15 -0
  46. package/dist/assets/main-Bp9HHqTr.js +2 -0
  47. package/dist/assets/main-DOwAfmxJ.js +169 -0
  48. package/dist/assets/{markdownHeightCache-C1u0bWDL.js → markdownHeightCache-BVV2dktw.js} +1 -1
  49. package/dist/assets/{mcpQueries-D2IxTr4k.js → mcpQueries-BoBrB4a4.js} +1 -1
  50. package/dist/assets/miniChat-BJDgCrfF.js +2 -0
  51. package/dist/assets/mobile-GM9931J_.js +2 -0
  52. package/dist/assets/{mobileBackNavigation-vpCg1S7j.js → mobileBackNavigation-DMSzAvb6.js} +1 -1
  53. package/dist/assets/{multirun-DT-dFXud.js → multirun-BhWttsRQ.js} +1 -1
  54. package/dist/assets/{native-De1DIkLZ.js → native-DSvNnKAm.js} +1 -1
  55. package/dist/assets/{native-config-ncdoz9Wl.js → native-config-DjdrW_9n.js} +1 -1
  56. package/dist/assets/{persistence-JyLTFv27.js → persistence-CfrHIiIS.js} +1 -1
  57. package/dist/assets/pl-BOd_idqn.js +15 -0
  58. package/dist/assets/{projectMeta-CG8NLahh.js → projectMeta-31PobC-M.js} +1 -1
  59. package/dist/assets/pt-BR-B8djxMsl.js +15 -0
  60. package/dist/assets/react-B9v0P7kT.js +1 -0
  61. package/dist/assets/{readiness-DSJs_3v4.js → readiness-CYNnsekT.js} +1 -1
  62. package/dist/assets/renderElectronMiniChatApp-N2r999Bf.js +2 -0
  63. package/dist/assets/renderMobileApp-CU1ec6Ak.js +28 -0
  64. package/dist/assets/{runtimeConfig-CZrflo-r.js → runtimeConfig-Db7yfo6L.js} +1 -1
  65. package/dist/assets/runtimeEndpointReset-DO5WVetV.js +149 -0
  66. package/dist/assets/scheduledTaskNavigation-Bsrhv3Ow.js +1 -0
  67. package/dist/assets/sessionLookup-DRVy7LM1.js +1 -0
  68. package/dist/assets/sortable-tabs-strip-yKyqsqut.js +1 -0
  69. package/dist/assets/speechSettingsQueries-DU25rmGc.js +4 -0
  70. package/dist/assets/src-Bckdo2XS.css +2 -0
  71. package/dist/assets/store-CUBymvAC.js +15 -0
  72. package/dist/assets/{terminalApi-B5o8UqWA.js → terminalApi-BblSkqch.js} +1 -1
  73. package/dist/assets/{textarea-vtIQM2iP.js → textarea-B39OCNPV.js} +1 -1
  74. package/dist/assets/{tooltip-BpG2mxrT.js → tooltip-d8TNN4lx.js} +1 -1
  75. package/dist/assets/{types-CNTgeeM1.js → types-BqFQhQTt.js} +1 -1
  76. package/dist/assets/{uk-B_JwElWz.js → uk-BNd7CjVO.js} +4 -4
  77. package/dist/assets/{useAppFontEffects-BguV1Hfa.js → useAppFontEffects-BVoVpJYO.js} +57 -55
  78. package/dist/assets/{useAssistantUIStore-C9FPlYQz.js → useAssistantUIStore-Bp6TxG5E.js} +1 -1
  79. package/dist/assets/useDesktopWindowControlsLayout-CYx1LNO5.js +1 -0
  80. package/dist/assets/{useEffectiveDirectory-Ci6Z13kj.js → useEffectiveDirectory-D8FFE5Yn.js} +1 -1
  81. package/dist/assets/{useFontPreferences-DMiP_Yy-.js → useFontPreferences-BFyBjtQ6.js} +1 -1
  82. package/dist/assets/useMobileNavigationStore-BHMFeMjo.js +23 -0
  83. package/dist/assets/useUIStore-BbYD420L.js +1 -0
  84. package/dist/assets/{useWorkerHighlightedLines-HKhuYGSj.js → useWorkerHighlightedLines-CPxG8Fya.js} +1 -1
  85. package/dist/assets/{vendor-codemirror-search-ZqtrPLjU.js → vendor-codemirror-search-DiPwvA-6.js} +2 -2
  86. package/dist/assets/{vendor-opencode-plugin-Bw7Q6Nv9.js → vendor-opencode-plugin-CgKz9Hcy.js} +1 -1
  87. package/dist/assets/{vendor-replit-codemirror-vim-DDj0dSVY.js → vendor-replit-codemirror-vim-DCdAdxvE.js} +3 -3
  88. package/dist/assets/zh-CN-BkTAEOZG.js +15 -0
  89. package/dist/assets/zh-TW-x8SfMzfc.js +15 -0
  90. package/dist/index.html +10 -10
  91. package/dist/mini-chat.html +10 -10
  92. package/dist/mobile.html +10 -10
  93. package/package.json +3 -3
  94. package/server/lib/assistants/DOCUMENTATION.md +20 -0
  95. package/server/lib/assistants/contracts.js +1 -0
  96. package/server/lib/assistants/service.js +23 -7
  97. package/server/lib/assistants/service.test.js +151 -0
  98. package/server/lib/assistants/weixin/DOCUMENTATION.md +58 -1
  99. package/server/lib/assistants/weixin/routes.js +4 -3
  100. package/server/lib/assistants/weixin/routes.test.js +30 -0
  101. package/server/lib/assistants/weixin/runtime.js +77 -8
  102. package/server/lib/assistants/weixin/runtime.test.js +216 -2
  103. package/server/lib/assistants/weixin/store.js +13 -0
  104. package/server/lib/opencode/DOCUMENTATION.md +2 -1
  105. package/server/lib/opencode/npm-registry.js +7 -21
  106. package/server/lib/opencode/npm-registry.test.js +36 -5
  107. package/server/lib/opencode/plugin-icon.d.ts +2 -0
  108. package/server/lib/opencode/plugin-icon.js +43 -0
  109. package/server/lib/opencode/plugin-icon.test.js +41 -0
  110. package/server/lib/opencode/plugin-routes.js +3 -1
  111. package/server/lib/opencode/plugin-routes.test.js +13 -0
  112. package/dist/assets/AssistantView-C2KQZ6a4.js +0 -3
  113. package/dist/assets/GuiPluginSurface-Dz2CdSUA.js +0 -1
  114. package/dist/assets/Icon-BP1sfnHn.js +0 -1
  115. package/dist/assets/MobileDetailNavigation-B3rUx5Ve.js +0 -1
  116. package/dist/assets/MobileTabPageHeader-0esgB2TO.js +0 -2
  117. package/dist/assets/TerminalView-BtM5-BVx.js +0 -8
  118. package/dist/assets/dropdown-menu.styles-PdxueXzN.js +0 -1
  119. package/dist/assets/es-BjI1GHJ5.js +0 -15
  120. package/dist/assets/fr-Bs7ndHkb.js +0 -13
  121. package/dist/assets/gitApi-BxQmH8Wg.js +0 -10
  122. package/dist/assets/host-D1EpSUMR.js +0 -1
  123. package/dist/assets/insertionBoundaries-CKQL85zy.js +0 -1
  124. package/dist/assets/ja-DkdV26EW.js +0 -15
  125. package/dist/assets/ko-B0qoC5da.js +0 -15
  126. package/dist/assets/main-CNwFqQQd.js +0 -2
  127. package/dist/assets/main-DPhcXanT.js +0 -169
  128. package/dist/assets/miniChat-CF2vb25D.js +0 -2
  129. package/dist/assets/mobile-C24qSj44.js +0 -2
  130. package/dist/assets/pl-D27Y_GBs.js +0 -15
  131. package/dist/assets/pt-BR-DbocEu4b.js +0 -15
  132. package/dist/assets/react-CURmDhtB.js +0 -1
  133. package/dist/assets/renderElectronMiniChatApp-ChZCxxH6.js +0 -2
  134. package/dist/assets/renderMobileApp-CRv3Il6P.js +0 -28
  135. package/dist/assets/runtimeEndpointReset-Cx3RE97b.js +0 -149
  136. package/dist/assets/scheduledTaskNavigation-rhgnZaaj.js +0 -1
  137. package/dist/assets/sessionChangeSummary-CVUA1AFw.js +0 -1
  138. package/dist/assets/sessionLookup-C3_vQwLe.js +0 -1
  139. package/dist/assets/sortable-tabs-strip-C1QmKFdb.js +0 -1
  140. package/dist/assets/speechSettingsQueries-BSQ-2JTv.js +0 -4
  141. package/dist/assets/src-NKCZI3Lg.css +0 -2
  142. package/dist/assets/store-DvN2L3vf.js +0 -15
  143. package/dist/assets/useDesktopWindowControlsLayout-CwgkVw9f.js +0 -1
  144. package/dist/assets/useMobileNavigationStore-TCj7ZnhV.js +0 -418
  145. package/dist/assets/useUIStore-DI7va1HH.js +0 -1
  146. package/dist/assets/zh-CN-DhFFdHQu.js +0 -15
  147. package/dist/assets/zh-TW-BvehppXO.js +0 -15
  148. /package/dist/assets/{sessionChangeSummary-8C8nv-EP.css → sessionLookup-8C8nv-EP.css} +0 -0
@@ -27,11 +27,24 @@ const feedback = (language, kind) => {
27
27
  const safeError = (error) => error instanceof WeixinError ? error.code
28
28
  : ['account_in_use', 'not_found', 'no_provider'].includes(error?.code) ? error.code : 'channel_error';
29
29
 
30
- export function createWeixinRuntime({ directory, service, refreshAllowedRoots = async () => {}, api = createWeixinAPI(), clock = Date.now, intervalMs = 2000 } = {}) {
30
+ export function createWeixinRuntime({ directory, service, refreshAllowedRoots = async () => {}, api = createWeixinAPI(), clock = Date.now, intervalMs = 2000, env = process.env } = {}) {
31
+ const configured = String(env.YURI_WEIXIN_ENABLED ?? '').trim().toLowerCase();
32
+ const development = env.NODE_ENV === 'development' || ['1', 'true'].includes(String(env.YURI_ELECTRON_DEV ?? '').trim().toLowerCase());
33
+ const enabled = configured ? ['1', 'true'].includes(configured) : !development;
34
+ if (!enabled) {
35
+ // Do not open the shared store, acquire a lease, or remove production bindings.
36
+ const disabled = () => { throw new WeixinError('channel_disabled'); };
37
+ return {
38
+ status: () => ({ status: 'disabled', error: null }),
39
+ startLogin: disabled, verify: disabled, retry: disabled, disconnect: disabled, transfer: disabled,
40
+ forget: async () => {}, onTurnEvent: () => {}, close: async () => {},
41
+ };
42
+ }
31
43
  const store = createWeixinStore(directory);
32
44
  const owner = randomUUID();
33
45
  const logins = new Map();
34
46
  const receivers = new Map();
47
+ const bindingWork = new Map();
35
48
  const operations = new Set();
36
49
  const recovered = new Set();
37
50
  const retiring = new Set();
@@ -54,8 +67,10 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
54
67
  const typing = createWeixinTyping({ api, clock, getBinding: store.get, isCurrent, canCancel: canControl });
55
68
  const pause = (ms, signal) => delay(ms, undefined, { signal }).catch(() => {});
56
69
  const stopReceiver = (assistantID) => {
57
- receivers.get(assistantID)?.controller.abort();
70
+ const entry = receivers.get(assistantID);
71
+ entry?.controller.abort();
58
72
  receivers.delete(assistantID);
73
+ return entry?.done;
59
74
  };
60
75
  const setError = (binding, error) => {
61
76
  if (!isCurrent(binding)) return;
@@ -164,11 +179,20 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
164
179
  try {
165
180
  const receiverSignal = receivers.get(binding.assistant_id)?.controller.signal;
166
181
  await api.sendText(current, delivery, receiverSignal ? AbortSignal.any([lifetime.signal, receiverSignal]) : lifetime.signal);
167
- if (!isCurrent(binding)) return;
182
+ if (!isCurrent(binding) && !(retiring.has(binding.assistant_id) && canControl(binding))) return;
168
183
  store.sent(delivery.id);
169
184
  store.patch(binding.epoch, { error: null, updated_at: clock() });
170
185
  } catch (error) {
171
- if (!isCurrent(binding)) return;
186
+ if (!isCurrent(binding)) {
187
+ if (retiring.has(binding.assistant_id) && canControl(binding)) {
188
+ // A failed move may resume this binding. Never strand an aborted send
189
+ // in 'sending', or automatically replay a request already on the wire.
190
+ store.markDelivery(delivery.id, 'unknown');
191
+ store.patch(binding.epoch, error?.code === 'auth_expired'
192
+ ? { status: 'expired', error: 'auth_expired' } : { error: 'delivery_unknown' });
193
+ }
194
+ return;
195
+ }
172
196
  // Network ambiguity is user-retryable, not an automatic duplicate reply.
173
197
  store.markDelivery(delivery.id, error?.ambiguous ? 'unknown' : 'blocked');
174
198
  setError(binding, error?.ambiguous ? new WeixinError('delivery_unknown') : error);
@@ -201,22 +225,34 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
201
225
  const controller = new AbortController();
202
226
  const entry = { controller };
203
227
  receivers.set(binding.assistant_id, entry);
204
- track(receive(binding, controller.signal)).finally(() => {
228
+ entry.done = track(receive(binding, controller.signal)).finally(() => {
205
229
  if (receivers.get(binding.assistant_id) === entry) receivers.delete(binding.assistant_id);
206
230
  }).catch(() => {});
207
231
  }
208
232
  }
209
233
  // One slow Bot cannot prevent another account receiving or replying.
210
- await Promise.allSettled(bindings.map((binding) => processBinding(binding).catch((error) => setError(binding, error))));
234
+ await Promise.allSettled(bindings.map((binding) => {
235
+ const work = processBinding(binding).catch((error) => setError(binding, error));
236
+ bindingWork.set(binding.assistant_id, work);
237
+ return work.finally(() => {
238
+ if (bindingWork.get(binding.assistant_id) === work) bindingWork.delete(binding.assistant_id);
239
+ });
240
+ }));
211
241
  } finally { ticking = false; }
212
242
  };
213
243
 
214
244
  const status = (assistantID) => {
215
245
  service.channelPage(assistantID, { tipOnly: true });
216
246
  const login = logins.get(assistantID);
217
- if (login) return { status: login.status, qrCode: login.qrCode, expiresAt: login.expiresAt, error: login.error ?? null };
218
247
  const binding = store.get(assistantID);
219
- if (!binding) return { status: 'disconnected', error: null };
248
+ const sources = !binding ? store.list().filter((row) => row.assistant_id !== assistantID && row.status !== 'expired') : [];
249
+ const names = sources.length ? new Map(service.snapshot().assistants.map((row) => [row.id, row.name])) : new Map();
250
+ const transferSources = sources.filter((row) => names.has(row.assistant_id)).map((row) => ({
251
+ assistantID: row.assistant_id, name: names.get(row.assistant_id), revision: row.epoch,
252
+ }));
253
+ const available = transferSources.length ? { transferSources } : {};
254
+ if (login) return { status: login.status, qrCode: login.qrCode, expiresAt: login.expiresAt, error: login.error ?? null, ...available };
255
+ if (!binding) return { status: 'disconnected', error: null, ...available };
220
256
  return {
221
257
  status: ownsLease ? binding.status : 'reconnecting',
222
258
  error: ownsLease ? (store.hasUnknown(binding.epoch) ? 'delivery_unknown' : binding.error) : 'channel_in_use',
@@ -301,6 +337,7 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
301
337
  }
302
338
  };
303
339
  const forget = async (assistantID) => {
340
+ if (retiring.has(assistantID)) throw new WeixinError('channel_in_use');
304
341
  retiring.add(assistantID);
305
342
  logins.get(assistantID)?.controller.abort();
306
343
  logins.delete(assistantID);
@@ -316,11 +353,42 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
316
353
  await forget(assistantID);
317
354
  return status(assistantID);
318
355
  };
356
+ const transfer = async (assistantID, input) => {
357
+ assertOwner();
358
+ const { sourceAssistantID, revision, language = 'en' } = input ?? {};
359
+ if (typeof sourceAssistantID !== 'string' || typeof revision !== 'string' || sourceAssistantID === assistantID) {
360
+ throw new WeixinError('validation_error');
361
+ }
362
+ service.channelPage(assistantID, { tipOnly: true });
363
+ service.channelPage(sourceAssistantID, { tipOnly: true });
364
+ if (retiring.has(assistantID) || retiring.has(sourceAssistantID)) throw new WeixinError('channel_in_use');
365
+ const source = store.get(sourceAssistantID);
366
+ if (!source || source.epoch !== revision || source.status === 'expired' || store.get(assistantID)) throw new WeixinError('binding_changed');
367
+ retiring.add(sourceAssistantID);
368
+ retiring.add(assistantID);
369
+ logins.get(assistantID)?.controller.abort();
370
+ logins.delete(assistantID);
371
+ try {
372
+ await Promise.allSettled([stopReceiver(sourceAssistantID), bindingWork.get(sourceAssistantID), typing.forget(sourceAssistantID)]);
373
+ assertOwner();
374
+ // Revalidate after draining: deletion or a stale confirmation must not move credentials.
375
+ service.channelPage(sourceAssistantID, { tipOnly: true });
376
+ const page = service.channelPage(assistantID, { tipOnly: true });
377
+ store.transfer({ sourceAssistantID, expectedEpoch: revision, assistantID,
378
+ generation: page.generation, ordinal: page.tipOrdinal, language: String(language).slice(0, 32), updatedAt: clock() });
379
+ } finally {
380
+ retiring.delete(sourceAssistantID);
381
+ retiring.delete(assistantID);
382
+ if (!closed) void track(tick());
383
+ }
384
+ return status(assistantID);
385
+ };
319
386
  const timer = setInterval(() => { void track(tick()); }, intervalMs);
320
387
  timer.unref?.();
321
388
  void track(tick());
322
389
  return {
323
390
  status, startLogin, disconnect, forget,
391
+ transfer: (assistantID, input) => track(transfer(assistantID, input)),
324
392
  verify: (assistantID, code) => {
325
393
  assertOwner();
326
394
  const login = logins.get(assistantID);
@@ -330,6 +398,7 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
330
398
  },
331
399
  retry: (assistantID) => {
332
400
  assertOwner();
401
+ if (retiring.has(assistantID)) throw new WeixinError('channel_in_use');
333
402
  const binding = store.get(assistantID);
334
403
  if (!binding) throw new WeixinError('not_found');
335
404
  if (binding.status === 'expired') throw new WeixinError('auth_expired');
@@ -23,9 +23,10 @@ const inbound = (id = '1', peer = 'owner', text = 'hello') => ({
23
23
  item_list: [{ type: 1, text_item: { text } }],
24
24
  });
25
25
 
26
- function fixture({ directory = root(), configureAPI, service: externalService, clock } = {}) {
26
+ function fixture({ directory = root(), configureAPI, service: externalService, clock, env = {} } = {}) {
27
27
  const pages = new Map();
28
28
  const service = externalService ?? {
29
+ snapshot: () => ({ assistants: ['bot', 'other-bot', 'third-bot'].map((id) => ({ id, name: `Name ${id}` })) }),
29
30
  channelPage: vi.fn((id, { afterOrdinal = 0, generation = null } = {}) => {
30
31
  if (id === 'missing') throw Object.assign(new Error('not_found'), { code: 'not_found' });
31
32
  const page = pages.get(id) ?? { generation: 0, messages: [] };
@@ -45,7 +46,7 @@ function fixture({ directory = root(), configureAPI, service: externalService, c
45
46
  sendTyping: vi.fn(async () => ({})),
46
47
  };
47
48
  configureAPI?.(api);
48
- const runtime = createWeixinRuntime({ directory, service, api, intervalMs: 15, ...(clock ? { clock } : {}) });
49
+ const runtime = createWeixinRuntime({ directory, service, api, env, intervalMs: 15, ...(clock ? { clock } : {}) });
49
50
  closers.push(() => runtime.close());
50
51
  const bind = async (id = 'bot') => {
51
52
  await runtime.startLogin(id, 'zh-CN');
@@ -56,6 +57,52 @@ function fixture({ directory = root(), configureAPI, service: externalService, c
56
57
  }
57
58
 
58
59
  describe('Weixin Host runtime', () => {
60
+ it.each([
61
+ { NODE_ENV: 'development' },
62
+ { YURI_ELECTRON_DEV: '1' },
63
+ { YURI_ELECTRON_DEV: 'true' },
64
+ { NODE_ENV: 'production', YURI_WEIXIN_ENABLED: '0' },
65
+ { YURI_WEIXIN_ENABLED: 'false' },
66
+ { YURI_WEIXIN_ENABLED: 'invalid' },
67
+ ])('disables channel startup and all mutations without opening storage for %j', async (env) => {
68
+ const directory = path.join(root(), 'must-not-open');
69
+ const api = { getQRCode: vi.fn(), getUpdates: vi.fn(), sendText: vi.fn(), getConfig: vi.fn(), sendTyping: vi.fn() };
70
+ const service = { channelPage: vi.fn(), send: vi.fn() };
71
+ const runtime = createWeixinRuntime({ directory, api, service, env });
72
+ closers.push(() => runtime.close());
73
+ expect(runtime.status('bot')).toEqual({ status: 'disabled', error: null });
74
+ for (const method of ['startLogin', 'verify', 'retry', 'disconnect', 'transfer']) {
75
+ expect(() => runtime[method]('bot', {})).toThrow('channel_disabled');
76
+ }
77
+ runtime.onTurnEvent({ type: 'yuri:contact-turn-start', properties: { assistantID: 'bot', turnID: 'turn' } });
78
+ await runtime.forget('bot');
79
+ await runtime.close();
80
+ expect(fs.existsSync(directory)).toBe(false);
81
+ for (const call of Object.values(api)) expect(call).not.toHaveBeenCalled();
82
+ expect(service.send).not.toHaveBeenCalled();
83
+ expect(service.channelPage).not.toHaveBeenCalled();
84
+ });
85
+
86
+ it('a disabled dev runtime cannot acquire the production lease or delete its binding', async () => {
87
+ const production = fixture();
88
+ await production.bind();
89
+ const dev = fixture({ directory: production.directory, env: { NODE_ENV: 'development' } });
90
+ expect(dev.runtime.status('bot')).toEqual({ status: 'disabled', error: null });
91
+ await dev.runtime.forget('bot');
92
+ await dev.runtime.close();
93
+ production.updates.push([inbound()]);
94
+ await vi.waitFor(() => expect(production.service.send).toHaveBeenCalledTimes(1));
95
+ expect(production.runtime.status('bot')).toEqual({ status: 'connected', error: null });
96
+ expect(dev.api.getUpdates).not.toHaveBeenCalled();
97
+ });
98
+
99
+ it.each(['1', 'true'])('requires an explicit %s override to enable WeChat in development', async (enabled) => {
100
+ const f = fixture({ env: { NODE_ENV: 'development', YURI_ELECTRON_DEV: '1', YURI_WEIXIN_ENABLED: enabled } });
101
+ await f.bind();
102
+ expect(f.runtime.status('bot').status).toBe('connected');
103
+ expect(f.api.getUpdates).toHaveBeenCalled();
104
+ });
105
+
59
106
  it('QR binds one Bot, admits only the owner once, and sends persisted text with the latest context', async () => {
60
107
  const f = fixture();
61
108
  f.updates.push([inbound('1'), inbound('1'), inbound('2', 'stranger'), { ...inbound('3'), group_id: 'group' }]);
@@ -171,6 +218,144 @@ describe('Weixin Host runtime', () => {
171
218
  expect(f.runtime.status('bot').status).toBe('connected');
172
219
  });
173
220
 
221
+ it('offers an explicit local move without scanning and preserves cursor/dedup across restart', async () => {
222
+ const f = fixture();
223
+ f.updates.push([inbound('1')]);
224
+ await f.bind();
225
+ await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledTimes(1));
226
+ f.reply('other-bot', 'old target history', 50);
227
+ const state = f.runtime.status('other-bot');
228
+ expect(state).toMatchObject({ status: 'disconnected', transferSources: [{ assistantID: 'bot', name: 'Name bot' }] });
229
+ expect(JSON.stringify(state)).not.toMatch(/test-token|context-1|peer_id|account_id/);
230
+ const revision = state.transferSources[0].revision;
231
+ const result = await f.runtime.transfer('other-bot', { sourceAssistantID: 'bot', revision, language: 'zh-CN' });
232
+ expect(result).toEqual({ status: 'connected', error: null });
233
+ expect(f.runtime.status('bot').status).toBe('disconnected');
234
+ expect(f.api.getQRCode).toHaveBeenCalledTimes(1);
235
+ f.updates.push([inbound('1'), inbound('2')]);
236
+ f.reply('bot', 'late old bot reply');
237
+ f.reply('other-bot', 'new target reply', 51);
238
+ await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledTimes(2));
239
+ expect(f.service.send.mock.calls[1][0]).toBe('other-bot');
240
+ await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalledTimes(1));
241
+ expect(f.api.sendText.mock.calls[0][1].text).toBe('new target reply');
242
+ expect(f.api.getUpdates.mock.calls.find(([binding]) => binding.assistant_id === 'other-bot')[0].cursor).toBe('next-cursor');
243
+ await f.runtime.close();
244
+ const restarted = fixture({ directory: f.directory });
245
+ restarted.updates.push([inbound('1'), inbound('2')]);
246
+ await vi.waitFor(() => expect(restarted.api.getUpdates).toHaveBeenCalled());
247
+ expect(restarted.api.getUpdates.mock.calls[0][0].assistant_id).toBe('other-bot');
248
+ await new Promise((resolve) => setTimeout(resolve, 60));
249
+ expect(restarted.service.send).not.toHaveBeenCalled();
250
+ });
251
+
252
+ it('rejects stale/occupied/missing/expired transfers without changing the original connection', async () => {
253
+ const f = fixture();
254
+ await f.bind();
255
+ const revision = f.runtime.status('other-bot').transferSources[0].revision;
256
+ await expect(f.runtime.transfer('other-bot', { sourceAssistantID: 'bot', revision: 'stale' })).rejects.toMatchObject({ code: 'binding_changed' });
257
+ await expect(f.runtime.transfer('missing', { sourceAssistantID: 'bot', revision })).rejects.toMatchObject({ code: 'not_found' });
258
+ await expect(f.runtime.transfer('bot', { sourceAssistantID: 'bot', revision })).rejects.toMatchObject({ code: 'validation_error' });
259
+ const second = fixture({ directory: f.directory });
260
+ await expect(second.runtime.transfer('other-bot', { sourceAssistantID: 'bot', revision })).rejects.toMatchObject({ code: 'channel_in_use' });
261
+ await second.runtime.close();
262
+ await f.runtime.transfer('other-bot', { sourceAssistantID: 'bot', revision });
263
+ await expect(f.runtime.transfer('third-bot', { sourceAssistantID: 'bot', revision })).rejects.toMatchObject({ code: 'binding_changed' });
264
+ expect(f.runtime.status('other-bot').status).toBe('connected');
265
+ f.api.getQRStatus.mockResolvedValue({ status: 'confirmed', bot_token: 'second-token', ilink_bot_id: 'second-account', ilink_user_id: 'second-owner' });
266
+ await f.bind('bot');
267
+ const source = f.runtime.status('third-bot').transferSources.find((entry) => entry.assistantID === 'bot');
268
+ await expect(f.runtime.transfer('other-bot', { sourceAssistantID: 'bot', revision: source.revision })).rejects.toMatchObject({ code: 'binding_changed' });
269
+ f.api.getUpdates.mockRejectedValue(new WeixinError('auth_expired'));
270
+ await vi.waitFor(() => expect(f.runtime.status('bot').status).toBe('expired'));
271
+ await expect(f.runtime.transfer('third-bot', { sourceAssistantID: 'bot', revision: source.revision })).rejects.toMatchObject({ code: 'binding_changed' });
272
+ });
273
+
274
+ it('drains old sending/typing, blocks concurrent mutations and fences a cancelled QR confirmation', async () => {
275
+ const f = fixture();
276
+ f.updates.push([inbound()]);
277
+ await f.bind();
278
+ await vi.waitFor(() => expect(f.service.send).toHaveBeenCalled());
279
+ let finishRead;
280
+ let oldSignal;
281
+ f.api.getUpdates.mockImplementationOnce((_binding, signal) => {
282
+ oldSignal = signal;
283
+ return new Promise((resolve) => { finishRead = resolve; });
284
+ });
285
+ let confirm;
286
+ f.api.getQRStatus.mockImplementation(() => new Promise((resolve) => { confirm = resolve; }));
287
+ await f.runtime.startLogin('other-bot');
288
+ await vi.waitFor(() => expect(finishRead).toBeTypeOf('function'));
289
+ f.runtime.onTurnEvent({ type: 'yuri:contact-turn-start', properties: { assistantID: 'bot', turnID: 'live' } });
290
+ await vi.waitFor(() => expect(f.api.sendTyping).toHaveBeenCalled());
291
+ let finishSend;
292
+ f.api.sendText.mockImplementationOnce((_binding, _delivery, signal) => {
293
+ expect(signal.aborted).toBe(false);
294
+ return new Promise((resolve) => { finishSend = resolve; });
295
+ });
296
+ f.reply('bot', 'in flight');
297
+ await vi.waitFor(() => expect(finishSend).toBeTypeOf('function'));
298
+ const revision = f.runtime.status('other-bot').transferSources[0].revision;
299
+ const moving = f.runtime.transfer('other-bot', { sourceAssistantID: 'bot', revision });
300
+ expect(oldSignal.aborted).toBe(true);
301
+ await expect(f.runtime.transfer('third-bot', { sourceAssistantID: 'bot', revision })).rejects.toMatchObject({ code: 'channel_in_use' });
302
+ await expect(f.runtime.disconnect('bot')).rejects.toMatchObject({ code: 'channel_in_use' });
303
+ expect(() => f.runtime.retry('bot')).toThrow('channel_in_use');
304
+ await expect(f.runtime.startLogin('other-bot')).rejects.toMatchObject({ code: 'channel_in_use' });
305
+ confirm({ status: 'confirmed', bot_token: 'stale-token', ilink_bot_id: 'stale-account', ilink_user_id: 'owner' });
306
+ finishRead({ msgs: [inbound('stale')], get_updates_buf: 'stale-cursor' });
307
+ finishSend({ ret: 0 });
308
+ await moving;
309
+ expect(f.api.sendTyping.mock.calls.map((call) => call[2])).toEqual([1, 2]);
310
+ expect(f.service.send).toHaveBeenCalledTimes(1);
311
+ expect(f.runtime.status('bot').status).toBe('disconnected');
312
+ expect(f.runtime.status('other-bot').status).toBe('connected');
313
+ await expect(f.runtime.transfer('third-bot', { sourceAssistantID: 'bot', revision })).rejects.toMatchObject({ code: 'binding_changed' });
314
+ });
315
+
316
+ it('preserves and resumes the source if the target disappears while draining', async () => {
317
+ const f = fixture();
318
+ await f.bind();
319
+ f.runtime.onTurnEvent({ type: 'yuri:contact-turn-start', properties: { assistantID: 'bot', turnID: 'live' } });
320
+ await vi.waitFor(() => expect(f.api.sendTyping).toHaveBeenCalled());
321
+ let finishCancel;
322
+ f.api.sendTyping.mockImplementationOnce(() => new Promise((resolve) => { finishCancel = resolve; }));
323
+ const revision = f.runtime.status('other-bot').transferSources[0].revision;
324
+ const moving = f.runtime.transfer('other-bot', { sourceAssistantID: 'bot', revision }).catch((error) => error);
325
+ await vi.waitFor(() => expect(finishCancel).toBeTypeOf('function'));
326
+ f.service.channelPage.mockImplementationOnce(() => { throw Object.assign(new Error('not_found'), { code: 'not_found' }); });
327
+ finishCancel({});
328
+ expect(await moving).toMatchObject({ code: 'not_found' });
329
+ expect(f.runtime.status('bot').status).toBe('connected');
330
+ f.updates.push([inbound('after-failure')]);
331
+ await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledWith('bot', expect.anything()));
332
+ });
333
+
334
+ it('a failed move leaves an aborted in-flight reply explicitly retryable, never stuck or automatically resent', async () => {
335
+ const f = fixture();
336
+ f.updates.push([inbound()]);
337
+ await f.bind();
338
+ await vi.waitFor(() => expect(f.service.send).toHaveBeenCalled());
339
+ f.runtime.onTurnEvent({ type: 'yuri:contact-turn-start', properties: { assistantID: 'bot', turnID: 'live' } });
340
+ await vi.waitFor(() => expect(f.api.sendTyping).toHaveBeenCalled());
341
+ let finishCancel;
342
+ f.api.sendTyping.mockImplementationOnce(() => new Promise((resolve) => { finishCancel = resolve; }));
343
+ f.api.sendText.mockImplementationOnce((_binding, _delivery, signal) => abortable(signal));
344
+ f.reply('bot', 'possibly delivered');
345
+ await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalledTimes(1));
346
+ const revision = f.runtime.status('other-bot').transferSources[0].revision;
347
+ const moving = f.runtime.transfer('other-bot', { sourceAssistantID: 'bot', revision }).catch((error) => error);
348
+ await vi.waitFor(() => expect(finishCancel).toBeTypeOf('function'));
349
+ f.service.channelPage.mockImplementationOnce(() => { throw Object.assign(new Error('not_found'), { code: 'not_found' }); });
350
+ finishCancel({});
351
+ expect(await moving).toMatchObject({ code: 'not_found' });
352
+ expect(f.runtime.status('bot')).toEqual({ status: 'connected', error: 'delivery_unknown' });
353
+ await new Promise((resolve) => setTimeout(resolve, 60));
354
+ expect(f.api.sendText).toHaveBeenCalledTimes(1);
355
+ f.runtime.retry('bot');
356
+ await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalledTimes(2));
357
+ });
358
+
174
359
  it('non-text input gives a text-only reply without invoking bot tools', async () => {
175
360
  const f = fixture();
176
361
  f.updates.push([{ ...inbound(), item_list: [null, { type: 2, image_item: { media: {} } }] }]);
@@ -266,6 +451,35 @@ describe('Weixin Host runtime', () => {
266
451
  });
267
452
 
268
453
  describe('Weixin durable store', () => {
454
+ it('moves atomically, preserves credentials/cursor/receipt IDs, drops old work, and rolls back failed writes', () => {
455
+ const store = createWeixinStore(root());
456
+ closers.push(() => store.close());
457
+ const initial = { token: 'test-token', peer_id: 'owner', base_url: 'https://ilinkai.weixin.qq.com', language: 'en', generation: 0, ordinal: 0, updated_at: 1 };
458
+ const a = store.bind({ ...initial, assistant_id: 'a', account_id: 'account-a' });
459
+ store.accept(a, 'cursor', [{ id: 'done', text: 'old', context: 'ctx' }, { id: 'pending', text: 'pending' }]);
460
+ store.markInbox('done', 'admitted');
461
+ store.enqueue(a.epoch, 'old-delivery', 'old reply');
462
+ const move = { sourceAssistantID: 'a', expectedEpoch: a.epoch, assistantID: 'b', generation: 5, ordinal: 42, language: 'zh-CN', updatedAt: 2 };
463
+ expect(() => store.transfer({ ...move, ordinal: null })).toThrow();
464
+ expect(store.get('a').epoch).toBe(a.epoch);
465
+ expect(store.pending(a.epoch)).toHaveLength(1);
466
+ expect(store.nextDelivery(a.epoch).text).toBe('old reply');
467
+ const b = store.transfer(move);
468
+ expect(store.get('a')).toBeNull();
469
+ expect(b).toMatchObject({ ...initial, assistant_id: 'b', language: 'zh-CN', generation: 5, ordinal: 42, updated_at: 2, cursor: 'cursor', context_token: 'ctx' });
470
+ expect(b.epoch).not.toBe(a.epoch);
471
+ expect(store.nextDelivery(b.epoch)).toBeUndefined();
472
+ store.accept(b, 'next', [{ id: 'done', text: 'replay' }, { id: 'pending', text: 'replay' }, { id: 'fresh', text: 'new' }]);
473
+ expect(store.pending(b.epoch).map((row) => row.id)).toEqual(['fresh']);
474
+ store.accept(a, 'stale', [{ id: 'stale', text: 'stale' }]);
475
+ expect(store.get('b').cursor).toBe('next');
476
+ expect(() => store.transfer(move)).toThrow('binding_changed');
477
+ store.bind({ ...initial, assistant_id: 'c', account_id: 'account-c' });
478
+ expect(() => store.transfer({ ...move, sourceAssistantID: 'b', expectedEpoch: b.epoch, assistantID: 'c' })).toThrow('binding_changed');
479
+ expect(store.get('b').epoch).toBe(b.epoch);
480
+ expect(store.get('c').account_id).toBe('account-c');
481
+ });
482
+
269
483
  it('rolls back a conflicting rebind, persists cursor/receipt together, and fences old epochs', () => {
270
484
  const store = createWeixinStore(root());
271
485
  closers.push(() => store.close());
@@ -61,6 +61,19 @@ export function createWeixinStore(directory) {
61
61
  .run({ ...value, epoch: randomUUID() });
62
62
  return get(value.assistant_id);
63
63
  }),
64
+ transfer: db.transaction(({ sourceAssistantID, expectedEpoch, assistantID, generation, ordinal, language, updatedAt }) => {
65
+ const source = get(sourceAssistantID);
66
+ if (!source || source.epoch !== expectedEpoch || source.status === 'expired' || get(assistantID)) {
67
+ const error = new Error('binding_changed'); error.code = 'binding_changed'; throw error;
68
+ }
69
+ const epoch = randomUUID();
70
+ // Keep receipt IDs across moves so a replay cannot execute tools in the new Bot.
71
+ db.prepare("UPDATE inbox SET epoch=?,state='done',text='' WHERE epoch=?").run(epoch, source.epoch);
72
+ db.prepare('DELETE FROM outbox WHERE epoch=?').run(source.epoch);
73
+ db.prepare(`UPDATE binding SET assistant_id=?,epoch=?,generation=?,ordinal=?,language=?,updated_at=?,status='connected',error=NULL WHERE epoch=?`)
74
+ .run(assistantID, epoch, generation, ordinal, language, updatedAt, source.epoch);
75
+ return get(assistantID);
76
+ }),
64
77
  accept: db.transaction((binding, cursor, messages) => {
65
78
  if (get(binding.assistant_id)?.epoch !== binding.epoch) return;
66
79
  for (const message of messages) {
@@ -76,7 +76,8 @@ encoding, not removed V1 endpoints.
76
76
  - `packages/web/server/lib/opencode/settings-normalization-runtime.js`: path/settings normalization and sanitization helpers runtime used by settings/routes/config wiring.
77
77
  - `packages/web/server/lib/opencode/theme-runtime.js`: custom theme JSON validation and theme directory loading runtime for settings utility routes.
78
78
  - `packages/web/server/lib/opencode/proxy.js`: OpenCode API/SSE forwarding and readiness-gate route registration.
79
- - `npm-registry.js`: plugin package lookup used by `GET /api/config/plugins/registry`. It asks the user's own `npm view` first (run in the project directory, so scope registries, auth tokens and mirrors from `.npmrc` apply as they do for `npm install`) and falls back to a direct request to the public registry only when the CLI is unavailable; a CLI 404 is final. Results are cached per name and directory. The latest release's `magpie.icon` is returned as `icon` only when it is an `https://` URL or `data:image/` URI of at most ~1.5 MB (`sanitizePluginIcon`); nothing is fetched server-side and clients render it as an image.
79
+ - `npm-registry.js`: plugin package lookup used by `GET /api/config/plugins/registry`. It asks the user's own `npm view` first (run in the project directory, so scope registries, auth tokens and mirrors from `.npmrc` apply as they do for `npm install`) and falls back to a direct request to the public registry only when the CLI is unavailable; a CLI 404 is final. Results are cached per name and directory. The latest release's top-level package.json `icon` is returned as `icon` only when it is an `https://` URL or `data:image/` URI of at most ~1.5 MB; nested icon fields are not read or used as fallbacks.
80
+ - `plugin-icon.js` owns the shared icon sanitizer and optional local package metadata read for Web/Electron/mobile and VS Code. Registry `path-ok` includes the nearest package manifest's top-level `icon` for directories or built entry files. Search stops at the first manifest, root or 32 parents; malformed, unreadable or >2 MiB manifests omit artwork without changing path status. No server-side image fetch occurs. Settings displays package images normally; GUI titlebar/sidebar entries use alpha masks in their current text color.
80
81
  - `plugin-gui-response.js`: shared Web/Electron/VS Code code-only revision response owner for exact `GET /api/plugin/gui?id=…` (one nonempty id). The installed GUI client alias is official `@opencode/client@2.2.0`: HTTP returns `{ location, data: { code, revision, options } }`. Every call still reads the complete current upstream response through the existing auth/readiness/abort boundary; there is no Host bundle cache.
81
82
  - Request `X-Yuri-Gui-Revision: <lowercase SHA-256 hex of UTF-8 revision>` opts into code reuse. This header and HTTP condition/range headers are stripped before upstream so Yuri always requests a complete representation. Other query and request headers retain proxy semantics.
82
83
  - A valid upstream 200 JSON bundle (`code` string, nonempty `revision` string, `options` object) receives `X-Yuri-Gui-Revision` and `Cache-Control: private, no-store`. Matching tokens additionally receive `X-Yuri-Gui-Code: cached` and only `data.code` becomes `''`; current `options`, `revision`, location and other fields remain. Unmatched/ordinary calls preserve original body bytes. No 304 or Yuri ETag is generated. Upstream failure statuses/bodies remain failures; malformed successful bodies remain unchanged without a revision receipt.
@@ -2,6 +2,9 @@ import { execFile } from 'child_process';
2
2
  import fs from 'fs';
3
3
  import path from 'path';
4
4
  import { fileURLToPath } from 'url';
5
+ import { sanitizePluginIcon } from './plugin-icon.js';
6
+
7
+ export { sanitizePluginIcon } from './plugin-icon.js';
5
8
 
6
9
  const NPM_CACHE_TTL_MS = 3_600_000;
7
10
  const NPM_FETCH_TIMEOUT_MS = 5_000;
@@ -13,7 +16,7 @@ const NPM_REGISTRY_BASE = 'https://registry.npmjs.org';
13
16
  * @property {string|null} latest
14
17
  * @property {string[]} versions
15
18
  * @property {Record<string, string>} distTags
16
- * @property {string} [icon] sanitized `magpie.icon` of the latest release
19
+ * @property {string} [icon] sanitized top-level package.json `icon` of the latest release
17
20
  *
18
21
  * @typedef {Object} NpmLookupError
19
22
  * @property {false} ok
@@ -81,23 +84,6 @@ function cacheResult(name, payload) {
81
84
  }
82
85
  }
83
86
 
84
- const NPM_ICON_MAX_LENGTH = 3 << 19;
85
-
86
- /**
87
- * A package's own picture, as magpie reads `magpie.icon` from package.json:
88
- * an https URL or a data:image URI, at most ~1.5 MB. Anything else is dropped.
89
- * Nothing is fetched here; the client renders it as an image.
90
- *
91
- * @param {unknown} value
92
- * @returns {string | undefined}
93
- */
94
- export function sanitizePluginIcon(value) {
95
- const icon = typeof value === 'string' ? value.trim() : '';
96
- return icon.length > 0 && icon.length <= NPM_ICON_MAX_LENGTH && /^(https:\/\/|data:image\/)/i.test(icon)
97
- ? icon
98
- : undefined;
99
- }
100
-
101
87
  const VALID_NPM_NAME = /^(?:@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/;
102
88
  const NPM_CLI_TIMEOUT_MS = 15_000;
103
89
 
@@ -118,7 +104,7 @@ function lookupViaNpmCli(name, cwd) {
118
104
  return new Promise((resolve) => {
119
105
  execFile(
120
106
  process.platform === 'win32' ? 'npm.cmd' : 'npm',
121
- ['view', name, 'dist-tags', 'versions', 'magpie.icon', '--json'],
107
+ ['view', name, 'dist-tags', 'versions', 'icon', '--json'],
122
108
  {
123
109
  cwd: cwd || undefined,
124
110
  timeout: NPM_CLI_TIMEOUT_MS,
@@ -142,7 +128,7 @@ function lookupViaNpmCli(name, cwd) {
142
128
  const versions = Array.isArray(data?.versions)
143
129
  ? data.versions.filter((version) => typeof version === 'string')
144
130
  : typeof data?.versions === 'string' ? [data.versions] : [];
145
- const icon = sanitizePluginIcon(data?.['magpie.icon'] ?? data?.magpie?.icon);
131
+ const icon = sanitizePluginIcon(data?.icon);
146
132
  resolve({ ok: true, latest: distTags.latest ?? null, versions, distTags, ...(icon ? { icon } : {}) });
147
133
  } catch {
148
134
  resolve(null);
@@ -189,7 +175,7 @@ async function lookupNpmPackageOverHttp(name) {
189
175
  const data = await response.json();
190
176
  const distTags = parseDistTags(data?.['dist-tags']);
191
177
  const latest = distTags.latest ?? null;
192
- const icon = sanitizePluginIcon(latest ? data?.versions?.[latest]?.magpie?.icon : undefined);
178
+ const icon = sanitizePluginIcon(latest ? data?.versions?.[latest]?.icon : undefined);
193
179
  return {
194
180
  ok: true,
195
181
  latest,
@@ -1,6 +1,10 @@
1
- import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
1
+ import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
2
2
  import * as npm from './npm-registry.js';
3
3
 
4
+ const mock = vi.fn;
5
+ const execFileMock = vi.hoisted(() => vi.fn());
6
+ vi.mock('child_process', () => ({ execFile: execFileMock }));
7
+
4
8
  const originalFetch = globalThis.fetch;
5
9
  const originalDateNow = Date.now;
6
10
 
@@ -18,6 +22,7 @@ const originalCliLookup = npm.npmCli.lookup;
18
22
  describe('npm registry client', () => {
19
23
  beforeEach(() => {
20
24
  npm.clearCache();
25
+ execFileMock.mockReset();
21
26
  Date.now = originalDateNow;
22
27
  fetchMock = mock(() => jsonResponse({}));
23
28
  globalThis.fetch = fetchMock;
@@ -212,18 +217,30 @@ describe('npm registry client', () => {
212
217
 
213
218
  expect(fetchMock.mock.calls[0][1].headers['User-Agent']).toMatch(/^yuri-server\//);
214
219
  });
215
- test('npm CLI answer carries a vetted magpie.icon', async () => {
216
- npm.npmCli.lookup = async () => ({ ok: true, latest: '1.0.0', versions: ['1.0.0'], distTags: { latest: '1.0.0' }, icon: 'https://cdn.example/a.png' });
220
+ test('npm CLI queries and sanitizes the top-level package icon', async () => {
221
+ npm.npmCli.lookup = originalCliLookup;
222
+ execFileMock.mockImplementation((_command, _args, _options, callback) => callback(null, JSON.stringify({
223
+ 'dist-tags': { latest: '1.0.0' }, versions: ['1.0.0'],
224
+ icon: ' https://cdn.example/a.png ',
225
+ magpie: { icon: 'https://cdn.example/legacy.png' },
226
+ }), ''));
217
227
 
218
228
  const result = await npm.getNpmInfo('@scope/pkg', { cwd: '/proj' });
219
229
 
220
230
  expect(result.icon).toBe('https://cdn.example/a.png');
231
+ expect(execFileMock).toHaveBeenCalledWith(expect.any(String), ['view', '@scope/pkg', 'dist-tags', 'versions', 'icon', '--json'],
232
+ expect.objectContaining({ cwd: '/proj' }), expect.any(Function));
233
+ expect(fetchMock).not.toHaveBeenCalled();
221
234
  });
222
235
 
223
- test('registry fallback reads magpie.icon from the latest release', async () => {
236
+ test('registry fallback reads the top-level icon from the latest release', async () => {
224
237
  fetchMock.mockImplementation(() => jsonResponse({
225
238
  'dist-tags': { latest: '1.0.0' },
226
- versions: { '1.0.0': { magpie: { icon: 'data:image/svg+xml;base64,AAAA' } } },
239
+ icon: 'https://cdn.example/packument.png',
240
+ versions: {
241
+ '0.9.0': { icon: 'https://cdn.example/old.png' },
242
+ '1.0.0': { icon: 'data:image/svg+xml;base64,AAAA', magpie: { icon: 'https://cdn.example/legacy.png' } },
243
+ },
227
244
  }));
228
245
 
229
246
  const result = await npm.lookupNpmPackage('foo');
@@ -231,6 +248,20 @@ describe('npm registry client', () => {
231
248
  expect(result.icon).toBe('data:image/svg+xml;base64,AAAA');
232
249
  });
233
250
 
251
+ test.each(['cli', 'http'])('%s never falls back to magpie.icon when icon is missing or invalid', async (source) => {
252
+ for (const icon of [undefined, 'http://cdn.example/insecure.png', { url: 'https://cdn.example/a.png' }]) {
253
+ const manifest = { icon, magpie: { icon: 'https://cdn.example/legacy.png' }, 'magpie.icon': 'https://cdn.example/legacy-flat.png' };
254
+ if (source === 'cli') {
255
+ npm.npmCli.lookup = originalCliLookup;
256
+ execFileMock.mockImplementation((_command, _args, _options, callback) => callback(null,
257
+ JSON.stringify({ 'dist-tags': { latest: '1.0.0' }, versions: ['1.0.0'], ...manifest }), ''));
258
+ } else fetchMock.mockImplementation(() => jsonResponse({ 'dist-tags': { latest: '1.0.0' }, versions: { '1.0.0': manifest } }));
259
+ const result = await npm.lookupNpmPackage('foo');
260
+ expect(result.ok).toBe(true);
261
+ expect(result).not.toHaveProperty('icon');
262
+ }
263
+ });
264
+
234
265
  test('sanitizePluginIcon keeps only https and data:image, within the size cap', () => {
235
266
  expect(npm.sanitizePluginIcon('https://x/y.png')).toBe('https://x/y.png');
236
267
  expect(npm.sanitizePluginIcon(' data:image/png;base64,AA ')).toBe('data:image/png;base64,AA');
@@ -0,0 +1,2 @@
1
+ export function sanitizePluginIcon(value: unknown): string | undefined;
2
+ export function readLocalPluginIcon(absolutePath: string): Promise<string | undefined>;
@@ -0,0 +1,43 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+
4
+ const ICON_MAX_LENGTH = 3 << 19;
5
+
6
+ /**
7
+ * A package's own picture from the top-level package.json `icon`:
8
+ * an https URL or a data:image URI, at most ~1.5 MB. Anything else is dropped.
9
+ * Nothing is fetched here; the client renders it as an image.
10
+ *
11
+ * @param {unknown} value
12
+ * @returns {string | undefined}
13
+ */
14
+ export function sanitizePluginIcon(value) {
15
+ const icon = typeof value === 'string' ? value.trim() : '';
16
+ return icon.length > 0 && icon.length <= ICON_MAX_LENGTH && /^(https:\/\/|data:image\/)/i.test(icon)
17
+ ? icon
18
+ : undefined;
19
+ }
20
+
21
+ /** Read the nearest package manifest for a local package directory or entry file. */
22
+ export async function readLocalPluginIcon(absolutePath) {
23
+ try {
24
+ const stat = await fs.stat(absolutePath);
25
+ let directory = stat.isDirectory() ? absolutePath : path.dirname(absolutePath);
26
+ for (let depth = 0; depth < 32; depth++) {
27
+ const manifest = path.join(directory, 'package.json');
28
+ try {
29
+ const metadata = await fs.stat(manifest);
30
+ if (!metadata.isFile() || metadata.size > 2 * 1024 * 1024) return undefined;
31
+ return sanitizePluginIcon(JSON.parse(await fs.readFile(manifest, 'utf8')).icon);
32
+ } catch (error) {
33
+ if (error?.code !== 'ENOENT') return undefined;
34
+ }
35
+ const parent = path.dirname(directory);
36
+ if (parent === directory) break;
37
+ directory = parent;
38
+ }
39
+ } catch {
40
+ // Optional artwork must not change the plugin path's load status.
41
+ }
42
+ return undefined;
43
+ }