dsh-mobile-plugin 0.5.123 → 0.5.125

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.
@@ -27,6 +27,28 @@ const { lanInterfaces } = require('../relay/lan-network.cjs');
27
27
  /** 自建渠道写在这个命名空间里;桌面端 `src/custom-channels.js` 的 PI_AI_NS 同值。 */
28
28
  const PI_AI_NS = 'llm-pi-ai';
29
29
 
30
+ /**
31
+ * 宿主自带的官方渠道里,手机「一键导入」能直接用的那几条。
32
+ *
33
+ * 它们不在 `llm-pi-ai` 的 providers 里,没有一份可搬的 profile;但官方 DeepSeek 的 Key
34
+ * 与 OpenAI 兼容地址是确定的。桌面这条走 Anthropic Messages(`api.deepseek.com/anthropic`),
35
+ * 手机本机 Agent 只认 OpenAI 那套,所以导出时换成手机能拨的 OpenAI 兼容地址,模型名与 Key
36
+ * 不变。其它插件 / 宿主渠道没有确定的地址与 Key,不在这里,导出去也用不了。
37
+ */
38
+ const IMPORTABLE_BUILTINS = new Map([
39
+ ['deepseek-official', {
40
+ name: 'DeepSeek',
41
+ protocol: 'openai-completions',
42
+ baseUrl: 'https://api.deepseek.com',
43
+ credentialRef: 'DEEPSEEK_API_KEY',
44
+ }],
45
+ ]);
46
+
47
+ /** 这条内置渠道是否可按上面的方式导入;不是就回 null。 */
48
+ function importableBuiltinOf(id) {
49
+ return typeof id === 'string' && IMPORTABLE_BUILTINS.has(id) ? IMPORTABLE_BUILTINS.get(id) : null;
50
+ }
51
+
30
52
  const PROTOCOLS = ['openai-completions', 'openai-responses', 'anthropic-messages', 'google-generative-ai'];
31
53
  const GEMINI_LEVELS = ['minimal', 'low', 'medium', 'high'];
32
54
 
@@ -278,7 +300,10 @@ async function handleChannels(ctx, req, res) {
278
300
  }
279
301
 
280
302
  const customIds = Object.keys(providers);
281
- const refs = customIds.map(credentialRefOf);
303
+ const refs = [...new Set([
304
+ ...customIds.map(credentialRefOf),
305
+ ...[...IMPORTABLE_BUILTINS.values()].map((spec) => spec.credentialRef),
306
+ ])];
282
307
  let keyState = {};
283
308
  if (refs.length > 0) {
284
309
  const described = unwrap(await ctx.apiProxy.credentials.describe({
@@ -294,12 +319,21 @@ async function handleChannels(ctx, req, res) {
294
319
  if (!item || typeof item.provider !== 'string' || item.provider === '') continue;
295
320
  // 自建路由同样会出现在 llm.providers 里,跳过——下面会以「自建」身份列一次。
296
321
  if (Object.prototype.hasOwnProperty.call(providers, item.provider)) continue;
322
+ const builtin = importableBuiltinOf(item.provider);
323
+ const view = builtin ? keyState[builtin.credentialRef] : null;
297
324
  channels.push({
298
325
  id: item.provider,
299
326
  source: 'external',
300
327
  name: typeof item.displayName === 'string' && item.displayName.trim() ? item.displayName.trim() : item.provider,
301
328
  active: item.active === true,
302
329
  models: modelsOf.get(item.provider) || [],
330
+ // 官方内置渠道额外给手机导入页要的三格;其余插件渠道维持只读、不出现导入入口。
331
+ ...(builtin ? {
332
+ importable: true,
333
+ protocol: builtin.protocol,
334
+ baseUrl: builtin.baseUrl,
335
+ ...(view ? { keySet: view.configured === true } : {}),
336
+ } : {}),
303
337
  });
304
338
  }
305
339
  for (const id of customIds) {
@@ -671,15 +705,76 @@ async function customChannelWithKey(ctx, id) {
671
705
  return { channel, apiKey, keySet: apiKey !== '' };
672
706
  }
673
707
 
708
+ /**
709
+ * 按 provider id 取它的模型清单(`llm.models` 的 groups)。
710
+ *
711
+ * 只给内置官方渠道的导出用:自建那批的模型在它自己的 profile 里,不走这里。
712
+ */
713
+ async function modelsOfProvider(ctx, id) {
714
+ const catalog = unwrap(await ctx.apiProxy.llm.models({
715
+ rpcId: 'mobile',
716
+ method: 'llm.models',
717
+ payload: {},
718
+ }));
719
+ if (catalog.error) return [];
720
+ const groups = Array.isArray(catalog.value && catalog.value.groups) ? catalog.value.groups : [];
721
+ const group = groups.find((entry) => entry && entry.id === id);
722
+ return (Array.isArray(group && group.models) ? group.models : [])
723
+ .map((model) => {
724
+ if (!model || typeof model !== 'object') return null;
725
+ const modelId = typeof model.id === 'string' ? model.id.trim() : '';
726
+ if (!modelId) return null;
727
+ return { id: modelId, name: typeof model.name === 'string' && model.name.trim() ? model.name.trim() : modelId };
728
+ })
729
+ .filter(Boolean);
730
+ }
731
+
732
+ /**
733
+ * 内置官方渠道 → 可导出的那一条;不是这类 id 回 `null`,是这类但宿主上没注册回 `{ error }`。
734
+ *
735
+ * Key 取不到不算失败,与自建那条同一个口径:`keySet:false`,让用户自己填一次。
736
+ */
737
+ async function builtinImportableChannel(ctx, id) {
738
+ const spec = importableBuiltinOf(id);
739
+ if (!spec) return null;
740
+ const listed = unwrap(await ctx.apiProxy.llm.providers({
741
+ rpcId: 'mobile',
742
+ method: 'llm.providers',
743
+ payload: {},
744
+ }));
745
+ if (listed.error) return { error: listed.error };
746
+ const registered = Array.isArray(listed.value && listed.value.providers) ? listed.value.providers : [];
747
+ if (!registered.some((item) => item && item.provider === id)) {
748
+ return { error: { code: 'channel-not-found', message: '这台电脑上没有这条渠道' }, status: 404 };
749
+ }
750
+ const models = await modelsOfProvider(ctx, id);
751
+ let apiKey = '';
752
+ try {
753
+ const resolved = unwrap(await ctx.apiProxy.credentials.resolve({
754
+ rpcId: 'mobile',
755
+ method: 'credentials.resolve',
756
+ payload: { ref: spec.credentialRef },
757
+ }));
758
+ if (!resolved.error && resolved.value && typeof resolved.value.value === 'string') apiKey = resolved.value.value;
759
+ } catch { /* 宿主没注册 resolve:按「没带 Key」处理 */ }
760
+ return {
761
+ channel: { id, name: spec.name, protocol: spec.protocol, baseUrl: spec.baseUrl, models },
762
+ apiKey,
763
+ keySet: apiKey !== '',
764
+ };
765
+ }
766
+
674
767
  /**
675
768
  * POST /api/mobile/v1/channels/export(token){ id }
676
769
  * → { ok, channel, keySet, candidates }
677
770
  *
678
- * 把电脑上这条自建渠道整条交给手机,给「本机 Agent 新增渠道」页的一键导入用:名字、协议、
771
+ * 把电脑上这条渠道整条交给手机,给「本机 Agent 新增渠道」页的一键导入用:名字、协议、
679
772
  * 地址、模型,以及**它的 Key**。手机本来就为手动添加的渠道在本地存着同一把 Key,这里只是
680
773
  * 把「用户再敲一遍」换成「电脑交过来」,不是新开一类暴露。
681
774
  *
682
- * 只认自建那一类:插件 / 宿主注册的提供方没有可搬的地址,也没有一把属于这条路由的 Key。
775
+ * 两类可导:`llm-pi-ai` 里的自建渠道,以及宿主自带的官方 DeepSeek(映射成 OpenAI 兼容
776
+ * 地址,见 `IMPORTABLE_BUILTINS`)。其它插件 / 宿主注册的提供方没有可搬的地址与 Key,
777
+ * 一律 404。
683
778
  * Key 只在用户点名这一条时取一次,取不到(宿主没注册 resolve、凭据是环境变量提供的)就
684
779
  * 如实回 keySet:false,由手机让用户自己填,不把失败报成整条导入失败。
685
780
  *
@@ -692,7 +787,7 @@ async function handleChannelExport(ctx, req, res) {
692
787
  if (!CHANNEL_ID_PATTERN.test(id)) {
693
788
  return sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: '需要渠道 id' } });
694
789
  }
695
- const found = await customChannelWithKey(ctx, id);
790
+ const found = (await builtinImportableChannel(ctx, id)) || await customChannelWithKey(ctx, id);
696
791
  if (found.error) return sendJson(res, found.status || 400, { ok: false, error: found.error });
697
792
  sendJson(res, 200, {
698
793
  ok: true,
@@ -1,4 +1,7 @@
1
1
  // 用途:插件反馈统一提交、读取与轮询等回复口;工具和本机面板按线程查看官方回复、继续跟进。
2
+ // 自检 / 探针文案不进真人反馈队列:submit 只收真实问题的现象描述。
3
+ // 2026-11-26:工具注册改为显式取 tools 服务,没声明注入的宿主也挂得上;真缺服务才跳过。
4
+ // 注册走调用方的注入作用域(`ctx.tools`),记在那一代 fiber 名下,热重载换代时随旧代卸掉。
2
5
  'use strict';
3
6
 
4
7
  /**
@@ -41,6 +44,17 @@ const ATTACHMENT_NAME = 'diagnosis.txt';
41
44
  const CONTENT_MAX = 4000;
42
45
  /** 带一份小文本附件,30 秒足够。 */
43
46
  const SUBMIT_TIMEOUT_MS = 30_000;
47
+ /** 带这些自报标记的正文是连通性自检,不是用户或 AI 观察到的现象。 */
48
+ const SELF_TEST_MARKERS = [
49
+ /勿人工处理/i,
50
+ /自动化测试用/i,
51
+ /连接诊断探针/i,
52
+ /probe from desktop/i,
53
+ ];
54
+ function isSelfTestContent(content) {
55
+ return SELF_TEST_MARKERS.some((pattern) => pattern.test(content));
56
+ }
57
+
44
58
  /** 明确指定设备、但包名读不到时的兜底;没有设备时这一格留空。 */
45
59
  const DEFAULT_PACKAGE_ID = 'com.dsh.mobile';
46
60
 
@@ -227,6 +241,9 @@ async function submitFeedback(deps, content, threadKey, deviceId, options = {})
227
241
  content = typeof content === 'string' ? content.trim() : '';
228
242
  if (!content) throw Object.assign(new Error('submit 需要 content'), { status: 400 });
229
243
  if (content.length > CONTENT_MAX) throw Object.assign(new Error(`content 超长(上限 ${CONTENT_MAX} 字)`), { status: 400 });
244
+ if (isSelfTestContent(content)) {
245
+ throw Object.assign(new Error('自检 / 探针内容不要提交到真人反馈队列;用 channels 查看反馈通道'), { status: 400 });
246
+ }
230
247
  const id = typeof deps && typeof deps.instanceId === 'function' ? deps.instanceId() : '';
231
248
  const devices = deps && deps.credentials && typeof deps.credentials.listDevices === 'function'
232
249
  ? deps.credentials.listDevices(id)
@@ -273,9 +290,22 @@ function registerFeedbackTool(ctx, deps) {
273
290
  throw new Error('反馈工具缺少凭据库或实例号取值器');
274
291
  }
275
292
  const channels = feedbackChannels();
276
- ctx.tools.register(defineTool({
293
+ // 2026-11-26:显式取服务,不靠 inject。缺一个注入就整行 pending 的代价太大,
294
+ // 而 ctx.get('tools') 在有这个服务时(哪怕当前 fiber 没注入)照样取得到了。
295
+ // 但优先用 `ctx.tools`:它把注册记在当前 fiber 名下,换代时随旧代一起卸;直接拿服务对象
296
+ // 注册只记在服务上,热重载时旧代那份还在,会判「已经注册过」把整代装载打回去。
297
+ let tools = null;
298
+ try {
299
+ tools = ctx.tools ?? null;
300
+ } catch (error) {
301
+ if (!String(error?.message || error).includes('without inject')) throw error;
302
+ }
303
+ if (!tools && typeof ctx.get === 'function') tools = ctx.get('tools') || null;
304
+ if (!tools || typeof tools.register !== 'function') return false;
305
+ return tools.register(defineTool({
277
306
  name: 'dsh_feedback',
278
307
  description: 'Report a real problem with this mobile plugin or the AI-HUB app. '
308
+ + 'Do not use `submit` for connectivity tests or automated probes: those are not real problems and must not enter the human feedback queue; use `channels` to inspect the route instead. '
279
309
  + 'Feedback routes: (1) the APP distribution platform — `submit` sends the content to it. You do NOT need to find the root cause: describe what you observed, what you already checked, and what is still uncertain. No paired phone is required either; without an explicitly chosen device the plugin submits under its local installation identity, with a text/plain diagnostics attachment and a thread key you can show to the user. After `submit`, call `watch` with the returned threadKey: it checks the existing feedback endpoint every two seconds for the first official reply, for at most two minutes, then stops with a hint to use `read`. It is polling, not a live stream. Use `read` with the thread key only when you need to review the conversation history, and `submit` with the same threadKey to follow up. The local feedback dialog can show these threads; they are not written into the in-app feedback list. '
280
310
  + '(2) GitHub — code-level bugs can go to https://github.com/WNLUO/dsh-mobile-plugin as a pull request or issue, but that needs the user to be logged into GitHub and is not submitted by this tool. '
281
311
  + 'Use `channels` to list both routes.',
@@ -378,14 +408,9 @@ function renderSummary(value) {
378
408
  }
379
409
  }
380
410
 
381
- /** 装配层入口:挂 `dsh_feedback` 工具;没有 tools 注入时只少这个工具。 */
411
+ /** 装配层入口:挂 `dsh_feedback` 工具;宿主没有 tools 服务时只少这个工具。 */
382
412
  function installFeedback(ctx, deps) {
383
- try {
384
- registerFeedbackTool(ctx, deps);
385
- } catch (error) {
386
- const message = error && error.message ? error.message : String(error);
387
- if (!message.includes('without inject')) throw error;
388
- }
413
+ return registerFeedbackTool(ctx, deps);
389
414
  }
390
415
 
391
416
  module.exports = {
@@ -23,11 +23,19 @@
23
23
  * - 只认 png/jpg/jpeg/webp/gif,并核对魔术字节,不按扩展名撒谎;
24
24
  * - 宽高只读文件头(最多 64KB);读不出来就不带宽高,App 那边照旧现量;
25
25
  * - 围栏代码块与行内代码里的图片语法不碰,那是写法示例。
26
+ *
27
+ * 字节要落在持久目录(2026-11-26 修):原图常在临时目录,第一台手机正看着的时候还在,另一台
28
+ * 重新投影会话时已经被清掉 —— 那时连编号都换不出来,正文就露 `![...](路径)` 源码。登记时把
29
+ * 字节复制到 `~/.dsh/storages/mobile-plugin/local-images/`,并记住「原路径 → 编号」;插件重启后
30
+ * 按编号从副本重建登记项,老会话里的编号也不会失效。取图口仍只认编号,不认请求里的路径。
31
+ * 副本按总量上限回收最旧的那几张;复制不成功就不发编号,宁可留字面 markdown 也不留死链。
26
32
  */
27
33
  const fs = require('node:fs/promises');
34
+ const fsSync = require('node:fs');
28
35
  const os = require('node:os');
29
36
  const path = require('node:path');
30
37
  const crypto = require('node:crypto');
38
+ const { dshHome } = require('../shared/paths.js');
31
39
 
32
40
  /**
33
41
  * `![alt](dest)`。dest 两种写法都认:裸路径(不含空白与右括号)与 `<>` 包裹(里面可以有空格,
@@ -52,15 +60,78 @@ const MAX_IMAGE_BYTES = 2.5 * 1024 * 1024;
52
60
  const HEAD_BYTES = 64 * 1024;
53
61
  /** 登记表上限:翻历史时同一张图反复出现也只登记一次,512 条够一两百个会话轮着用。 */
54
62
  const MAX_REGISTRY_ENTRIES = 512;
63
+ /** 持久副本总量上限:老会话要留,但也不能让这台电脑的缓存无限涨。 */
64
+ const MAX_STORED_BYTES = 128 * 1024 * 1024;
55
65
  /** 一张响应(一页历史 / 一帧 SSE / 一次镜像快照)里最多换几张:防一段文字里几十上百个图片语法。 */
56
66
  const MAX_TEXT_IMAGES = 64;
57
67
 
68
+ /** 编号 → { filePath, mediaType, width?, height? }。 */
69
+ const registry = new Map();
58
70
  /**
59
- * 编号 → { filePath, mediaType, width?, height? }。
60
- *
61
- * 只由本模块登记,取图口只认这里面的编号 —— 这是「不扩能力面」的全部依据(见文件头)。
71
+ * 原图目的地 → 编号。原图被清掉之后,同一段 markdown 重新投影仍要拿回同一个编号,
72
+ * 否则手机只能收到 `![...](原路径)` 并把源码铺在正文里。
62
73
  */
63
- const registry = new Map();
74
+ const pathIndex = new Map();
75
+
76
+ /** 持久副本目录(与收件箱、技能同在 DSH_HOME 下的插件存储里)。 */
77
+ function imageStoreDir() {
78
+ return path.join(dshHome(), 'storages', 'mobile-plugin', 'local-images');
79
+ }
80
+
81
+ const INDEX_FILE = 'index.json';
82
+ /** 编号只可能是我们自己生成的 16 位十六进制;取图口按这个形状挡住目录穿越。 */
83
+ const ID_RE = /^[a-f0-9]{16}$/i;
84
+
85
+ /** 从持久索引恢复登记表(插件重启后内存表是空的)。读不到就按空表起手。 */
86
+ function loadIndex() {
87
+ try {
88
+ const data = JSON.parse(fsSync.readFileSync(path.join(imageStoreDir(), INDEX_FILE), 'utf8'));
89
+ if (!data || data.version !== 1 || !data.entries || !data.paths) return;
90
+ for (const [id, entry] of Object.entries(data.entries)) {
91
+ if (ID_RE.test(id) && entry && typeof entry.mediaType === 'string') registry.set(id, entry);
92
+ }
93
+ for (const [destination, id] of Object.entries(data.paths)) {
94
+ if (ID_RE.test(id) && registry.has(id)) pathIndex.set(destination, id);
95
+ }
96
+ } catch { /* 没有索引 / 索引坏了:这一轮按空表走,老图退回字面 markdown。 */ }
97
+ }
98
+ loadIndex();
99
+
100
+ let saveSequence = 0;
101
+ let indexWriting = Promise.resolve();
102
+ /** 索引很小(上限 512 条),整体重写;排队写避免同一页并发内联时互相覆盖。 */
103
+ function saveIndex() {
104
+ const payload = JSON.stringify({
105
+ version: 1,
106
+ entries: Object.fromEntries(registry),
107
+ paths: Object.fromEntries(pathIndex),
108
+ });
109
+ const file = path.join(imageStoreDir(), INDEX_FILE);
110
+ const tmp = `${file}.${process.pid}.${++saveSequence}.tmp`;
111
+ indexWriting = indexWriting
112
+ .then(() => fs.mkdir(imageStoreDir(), { recursive: true }))
113
+ .then(() => fs.writeFile(tmp, payload, 'utf8'))
114
+ .then(() => fs.rename(tmp, file))
115
+ .catch(() => { /* 索引写不进去只影响重启后的恢复,本轮投影照常。 */ });
116
+ return indexWriting;
117
+ }
118
+
119
+ /** 同步读文件头:给 `localImageOf` 在重启后重建登记项用。 */
120
+ function headSyncOf(file) {
121
+ let fd;
122
+ try {
123
+ fd = fsSync.openSync(file, 'r');
124
+ const size = fsSync.fstatSync(fd).size;
125
+ if (!size) return null;
126
+ const buf = Buffer.alloc(Math.min(size, HEAD_BYTES));
127
+ fsSync.readSync(fd, buf, 0, buf.length, 0);
128
+ return buf;
129
+ } catch {
130
+ return null;
131
+ } finally {
132
+ if (fd !== undefined) fsSync.closeSync(fd);
133
+ }
134
+ }
64
135
 
65
136
  function mediaTypeFor(filePath) {
66
137
  return MEDIA_TYPES[path.extname(filePath).toLowerCase()] || null;
@@ -249,6 +320,42 @@ async function readHead(filePath, size) {
249
320
  }
250
321
  }
251
322
 
323
+ /** 持久副本的扩展名:与 App 侧按编号找缓存文件的那四种一致。 */
324
+ function extensionOf(mediaType) {
325
+ return mediaType === 'image/jpeg' ? '.jpg'
326
+ : mediaType === 'image/gif' ? '.gif'
327
+ : mediaType === 'image/webp' ? '.webp' : '.png';
328
+ }
329
+
330
+ /**
331
+ * 副本超过总量上限时回收最旧的那几张。新登记的那张(keepId)一定留着,
332
+ * 被回收的编号同时撤掉登记与路径映射 —— 下次投影会照常重新登记,不会发死编号。
333
+ */
334
+ async function trimStoredFiles(keepId) {
335
+ const dir = imageStoreDir();
336
+ let names;
337
+ try { names = await fs.readdir(dir); } catch { return; }
338
+ let bytes = 0;
339
+ const files = [];
340
+ for (const name of names) {
341
+ const id = path.parse(name).name;
342
+ if (!ID_RE.test(id) || id === keepId) continue;
343
+ try {
344
+ const stat = await fs.stat(path.join(dir, name));
345
+ bytes += stat.size;
346
+ files.push({ id, name, at: stat.mtimeMs, size: stat.size });
347
+ } catch { /* 半截文件 / 正在写的索引不算 */ }
348
+ }
349
+ files.sort((a, b) => a.at - b.at);
350
+ for (const file of files) {
351
+ if (bytes <= MAX_STORED_BYTES) break;
352
+ await fs.unlink(path.join(dir, file.name)).catch(() => {});
353
+ registry.delete(file.id);
354
+ for (const [destination, id] of pathIndex) if (id === file.id) pathIndex.delete(destination);
355
+ bytes -= file.size;
356
+ }
357
+ }
358
+
252
359
  /**
253
360
  * 登记一张本机图片,返回它的编号与宽高。
254
361
  *
@@ -259,17 +366,31 @@ async function readHead(filePath, size) {
259
366
  * markdown,用户在手机上看到的是一串 `![](路径)` 源码 —— 既不知道发生过什么,也没有任何
260
367
  * 入口。标了之后取图口如实回 413,App 画成「图片太大」的占位块,这才是用户能读懂的一句话。
261
368
  */
262
- async function registerLocalImage(filePath) {
369
+ async function registerLocalImage(filePath, destination = '') {
263
370
  let stat;
264
371
  try {
265
372
  stat = await fs.stat(filePath);
266
373
  } catch {
267
- return null;
374
+ // 原图已经不在(临时目录被清):同一路径以前登记过就继续用那个编号,
375
+ // 字节取的是我们自己的持久副本 —— 另一台设备重新打开会话时走的就是这条路。
376
+ const knownId = pathIndex.get(filePath) || (destination && pathIndex.get(destination));
377
+ const known = knownId ? registry.get(knownId) : null;
378
+ if (known && destination) {
379
+ pathIndex.set(destination, knownId);
380
+ await saveIndex();
381
+ }
382
+ return known ? { id: knownId, ...known } : null;
268
383
  }
269
384
  if (!stat.isFile() || stat.size <= 0) return null;
270
385
  const id = crypto.createHash('sha1').update(`${filePath}:${stat.size}:${stat.mtimeMs}`).digest('hex').slice(0, 16);
271
386
  const known = registry.get(id);
272
- if (known) return { id, ...known };
387
+ if (known) {
388
+ if (destination) {
389
+ pathIndex.set(destination, id);
390
+ await saveIndex();
391
+ }
392
+ return { id, ...known };
393
+ }
273
394
  const head = await readHead(filePath, stat.size);
274
395
  if (!head) return null;
275
396
  const mediaType = sniffMediaType(head);
@@ -280,34 +401,78 @@ async function registerLocalImage(filePath) {
280
401
  && parsed.width <= 30000 && parsed.height <= 30000;
281
402
  const size = sane ? parsed : {};
282
403
  const entry = { filePath, mediaType, ...size, ...(over ? { tooLarge: true } : {}) };
404
+ if (!over) {
405
+ // 副本必须落稳才发编号:留一个指向临时路径的编号,文件被清后那一格会永远失败。
406
+ const dest = path.join(imageStoreDir(), `${id}${extensionOf(mediaType)}`);
407
+ try {
408
+ await fs.mkdir(imageStoreDir(), { recursive: true });
409
+ await fs.copyFile(filePath, dest);
410
+ entry.filePath = dest;
411
+ await trimStoredFiles(id);
412
+ } catch {
413
+ return null;
414
+ }
415
+ }
283
416
  registry.set(id, entry);
417
+ pathIndex.set(filePath, id);
418
+ if (destination) pathIndex.set(destination, id);
284
419
  trimRegistry();
420
+ await saveIndex();
285
421
  return { id, ...entry };
286
422
  }
287
423
 
288
- /** 登记表满了就淘汰最老的一条;取回来的临时文件一并删掉,别在地上留垃圾。 */
424
+ /**
425
+ * 登记表满了就淘汰最老的一条。**持久副本不删**:老会话里的编号还要靠它取回字节
426
+ * (另一台手机上没有缓存,删了就真的取不到了)。
427
+ */
289
428
  function trimRegistry() {
429
+ let dropped = false;
290
430
  while (registry.size > MAX_REGISTRY_ENTRIES) {
291
431
  const oldestId = registry.keys().next().value;
292
- const entry = registry.get(oldestId);
293
432
  registry.delete(oldestId);
294
- if (entry && entry.fetched && entry.filePath) fs.unlink(entry.filePath).catch(() => {});
433
+ for (const [destination, id] of pathIndex) if (id === oldestId) pathIndex.delete(destination);
434
+ dropped = true;
295
435
  }
436
+ if (dropped) void saveIndex();
437
+ }
438
+
439
+ /** 目的地字符串归一:尖括号与首尾空白不参与「原路径 → 编号」的查找。 */
440
+ function destinationKey(raw) {
441
+ if (typeof raw !== 'string') return '';
442
+ let value = raw.trim();
443
+ if (value.startsWith('<') && value.endsWith('>')) value = value.slice(1, -1).trim();
444
+ return value;
296
445
  }
297
446
 
298
447
  /** 取图口用:只认登记表里的编号(构造不出来的编号一律 null → 404)。 */
299
448
  function localImageOf(id) {
300
- if (typeof id !== 'string' || !id) return null;
301
- return registry.get(id) || null;
449
+ if (typeof id !== 'string' || !ID_RE.test(id)) return null;
450
+ const hit = registry.get(id);
451
+ if (hit) return hit;
452
+ // 插件重启:内存表空了,但字节和索引都在持久目录里。按编号找回自己写过的那份。
453
+ for (const ext of ['png', 'jpg', 'webp', 'gif']) {
454
+ const file = path.join(imageStoreDir(), `${id}.${ext}`);
455
+ const head = headSyncOf(file);
456
+ if (!head) continue;
457
+ const mediaType = sniffMediaType(head);
458
+ if (!mediaType) continue;
459
+ const parsed = imageSizeOf(head);
460
+ const sane = parsed && parsed.width > 0 && parsed.height > 0
461
+ && parsed.width <= 30000 && parsed.height <= 30000;
462
+ const entry = { filePath: file, mediaType, ...(sane ? parsed : {}) };
463
+ registry.set(id, entry);
464
+ void saveIndex();
465
+ return entry;
466
+ }
467
+ return null;
302
468
  }
303
469
 
304
- /** 清空登记表(测试用)。取回来的临时文件一并删掉。 */
470
+ /** 清空登记表与持久副本(只在测试里调用,用例之间不串味)。 */
305
471
  function clearLocalImages() {
306
- for (const entry of registry.values()) {
307
- if (entry && entry.fetched && entry.filePath) fs.unlink(entry.filePath).catch(() => {});
308
- }
309
472
  registry.clear();
473
+ pathIndex.clear();
310
474
  loopbackUrlCache.clear();
475
+ fsSync.rmSync(imageStoreDir(), { recursive: true, force: true });
311
476
  }
312
477
 
313
478
  /**
@@ -347,16 +512,22 @@ function loopbackImageUrlOf(url) {
347
512
  }
348
513
 
349
514
  /**
350
- * 取回的图片字节落成临时文件再登记:取图口按编号读 `filePath`,与磁盘上的图同一条路。
515
+ * 取回的图片字节落成持久副本再登记:取图口按编号读 `filePath`,与磁盘上的图同一条路。
351
516
  *
352
517
  * 编号取内容哈希:同一张图反复出现只落一份。超过单张上限的照样登记、但标 `tooLarge`
353
518
  * (取图口回 413,App 画「图片太大」占位),与磁盘图片那条口径一致。
354
519
  */
355
- async function registerLocalImageBytes(buffer, mediaType) {
520
+ async function registerLocalImageBytes(buffer, mediaType, source = '') {
356
521
  if (!buffer || buffer.length === 0) return null;
357
522
  const id = crypto.createHash('sha1').update(buffer).digest('hex').slice(0, 16);
358
523
  const known = registry.get(id);
359
- if (known) return { id, ...known };
524
+ if (known) {
525
+ if (source) {
526
+ pathIndex.set(source, id);
527
+ await saveIndex();
528
+ }
529
+ return { id, ...known };
530
+ }
360
531
  const over = buffer.length > MAX_IMAGE_BYTES;
361
532
  const parsed = over ? null : imageSizeOf(buffer);
362
533
  const sane = parsed && parsed.width > 0 && parsed.height > 0
@@ -365,24 +536,27 @@ async function registerLocalImageBytes(buffer, mediaType) {
365
536
  if (over) {
366
537
  const entry = { filePath: '', mediaType, ...size, tooLarge: true, fetched: true };
367
538
  registry.set(id, entry);
539
+ if (source) pathIndex.set(source, id);
368
540
  trimRegistry();
541
+ await saveIndex();
369
542
  return { id, ...entry };
370
543
  }
371
- const ext = mediaType === 'image/jpeg' ? '.jpg'
372
- : mediaType === 'image/gif' ? '.gif'
373
- : mediaType === 'image/webp' ? '.webp' : '.png';
544
+ const ext = extensionOf(mediaType);
374
545
  let filePath;
375
546
  try {
376
- const dir = path.join(os.tmpdir(), 'dsh-local-images');
547
+ const dir = imageStoreDir();
377
548
  await fs.mkdir(dir, { recursive: true });
378
549
  filePath = path.join(dir, `${id}${ext}`);
379
550
  await fs.writeFile(filePath, buffer);
551
+ await trimStoredFiles(id);
380
552
  } catch {
381
553
  return null;
382
554
  }
383
555
  const entry = { filePath, mediaType, ...size, fetched: true };
384
556
  registry.set(id, entry);
557
+ if (source) pathIndex.set(source, id);
385
558
  trimRegistry();
559
+ await saveIndex();
386
560
  return { id, ...entry };
387
561
  }
388
562
 
@@ -422,7 +596,7 @@ async function fetchLoopbackImage(url) {
422
596
  loopbackUrlCache.set(url, { failedAt: Date.now() });
423
597
  return null;
424
598
  }
425
- const entry = await registerLocalImageBytes(buffer, mediaType);
599
+ const entry = await registerLocalImageBytes(buffer, mediaType, url);
426
600
  if (!entry) {
427
601
  loopbackUrlCache.set(url, { failedAt: Date.now() });
428
602
  return null;
@@ -528,13 +702,22 @@ async function inlineTextImages(text, budget) {
528
702
  let entry = null;
529
703
  const filePath = localImagePathOf(m[2], pool.cwd);
530
704
  if (filePath) {
531
- entry = await registerLocalImage(filePath);
705
+ // 一并记住正文里原本的写法:相对地址按工作区解开后是绝对路径,但另一台设备
706
+ // 可能查不到工作区目录,那时只能靠这个原始写法找回同一编号。
707
+ entry = await registerLocalImage(filePath, destinationKey(m[2]));
532
708
  } else {
533
- // 第二种「本机图片」:生图插件把成品图挂在自己电脑的一个回环小服务上,回的是
534
- // `http://127.0.0.1:<端口>/…`。手机拿着它只会指回手机自己,所以由电脑去取回来、
535
- // 按编号给手机(与磁盘图片同一条路,宽高/缓存/重试全现成)。
536
- const loopbackUrl = loopbackImageUrlOf(m[2]);
537
- if (loopbackUrl) entry = await fetchLoopbackImage(loopbackUrl);
709
+ // 回环地址以前取回过的图:插件重启、那台小服务也关了,仍按同一编号给手机。
710
+ const knownId = pathIndex.get(destinationKey(m[2]));
711
+ const known = knownId ? registry.get(knownId) : null;
712
+ if (known) {
713
+ entry = { id: knownId, ...known };
714
+ } else {
715
+ // 第二种「本机图片」:生图插件把成品图挂在自己电脑的一个回环小服务上,回的是
716
+ // `http://127.0.0.1:<端口>/…`。手机拿着它只会指回手机自己,所以由电脑去取回来、
717
+ // 按编号给手机(与磁盘图片同一条路,宽高/缓存/重试全现成)。
718
+ const loopbackUrl = loopbackImageUrlOf(m[2]);
719
+ if (loopbackUrl) entry = await fetchLoopbackImage(loopbackUrl);
720
+ }
538
721
  }
539
722
  if (!entry) continue;
540
723
  count -= 1;
@@ -1,3 +1,4 @@
1
+ // 2026-11-27:「立即同步」的上报半段只认「自动上报网络地址」开关,中转 / 远程控制关着也能催报一次(与 control.js 解耦口径一致)。
1
2
  // 手机主动重连在回执发出后调用独立隧道动作,普通配置同步保持幂等。
2
3
  // 既有中转配置复用有界健康判据与出网诊断,保留本实例吊销回执收尾。
3
4
  // 2026-11-21:「立即同步」只上报不等查询 —— 查询归手机,宿主没有比自己更新的上游可查。
@@ -654,8 +655,8 @@ function createRelayControlHandlers(deps) {
654
655
  */
655
656
  async function handleControlSync(_ctx, _req, res) {
656
657
  if (typeof syncControl !== 'function' || typeof getControl !== 'function') return unavailable(res);
657
- // 没开远端或用户关了自动上报:连都不会连,催也催不动,等也等不出回执,当场给结论。
658
- const reporting = Boolean(state && state.enabled && state.controlReportEnabled !== false);
658
+ // 用户关了自动上报:连都不会连,催也催不动,等也等不出回执,当场给结论。中转关不关不影响这一条。
659
+ const reporting = Boolean(state && state.controlReportEnabled !== false);
659
660
  if (reporting) {
660
661
  try { syncControl(); } catch { /* 拨号失败会在下面的快照里如实反映 */ }
661
662
  }