dsh-mobile-plugin 0.5.84 → 0.5.85

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/lib/client.js CHANGED
@@ -1,3 +1,4 @@
1
+ // 用途:桌面端入口;诊断窗就地提交插件反馈并回显线程 key,不依赖 AI 工具。
1
2
  /**
2
3
  * 移动端插件提供电脑插件页面目录;标准页面保留宿主上下文并支持直接导航。
3
4
  * 聊天嵌入服务合并顶部栏显示声明,随提供方与消费方生命周期释放。
@@ -171,6 +172,101 @@ window.__ModuleLoader__.load({
171
172
  body: JSON.stringify(payload || {}),
172
173
  });
173
174
 
175
+ /* ── 就地反馈:不经过 AI 工具,直接 POST 公开接口 ──────────────────────────
176
+ * 诊断窗里点一颗按钮就能交。只带插件自己拿得到的诊断文本;不读任意本地文件、
177
+ * 不读密钥、不读会话内容。没配对手机也能交:device_id 用本机持久随机 id,
178
+ * 受影响手机的字段留空,source 固定 plugin,绝不伪造安卓 / iOS / extension。
179
+ */
180
+ const FEEDBACK_URL = 'https://app.wnluo.com/api/sdk/feedback';
181
+ const FEEDBACK_DEVICE_ID_KEY = 'dsh-mobile-plugin.feedback.deviceId';
182
+ const FEEDBACK_TIMEOUT_MS = 30000;
183
+ const feedbackSubmissionIds = new Map();
184
+
185
+ function feedbackRandomId() {
186
+ const webCrypto = typeof globalThis !== 'undefined' ? globalThis.crypto : null;
187
+ if (webCrypto && typeof webCrypto.randomUUID === 'function') return webCrypto.randomUUID();
188
+ return `${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`;
189
+ }
190
+
191
+ function feedbackDeviceId() {
192
+ try {
193
+ const saved = localStorage.getItem(FEEDBACK_DEVICE_ID_KEY);
194
+ if (saved) return saved;
195
+ const id = feedbackRandomId();
196
+ localStorage.setItem(FEEDBACK_DEVICE_ID_KEY, id);
197
+ return id;
198
+ } catch {
199
+ return feedbackRandomId();
200
+ }
201
+ }
202
+
203
+ /** 同一条反馈重试复用同一个 submission_id。 */
204
+ function feedbackSubmissionIdOf(text) {
205
+ if (!feedbackSubmissionIds.has(text)) feedbackSubmissionIds.set(text, feedbackRandomId());
206
+ return feedbackSubmissionIds.get(text);
207
+ }
208
+
209
+ /**
210
+ * 就地反馈附件的诊断文本:只放插件自己认得的固定字段。原始错误串、面板地址与 UA
211
+ * 只留在「复制诊断信息」那份给人看的全文里,不随附件出门。
212
+ */
213
+ function feedbackDiagnosisText({ version, stage, code, scope }) {
214
+ return [
215
+ 'dsh-mobile-plugin feedback',
216
+ `source=plugin`,
217
+ `component_id=dsh-mobile-plugin`,
218
+ `component_version=${version || ''}`,
219
+ `stage=${stage || ''}`,
220
+ `code=${code === undefined || code === null ? '' : String(code)}`,
221
+ `scope=${scope || ''}`,
222
+ ].join('\n');
223
+ }
224
+
225
+ async function submitIssueFeedback({ summary, diagnosis, version, context }) {
226
+ const submissionId = feedbackSubmissionIdOf(summary);
227
+ const form = new FormData();
228
+ for (const key of ['package_id', 'platform', 'version_name', 'build_number', 'model', 'system_version', 'channel']) {
229
+ form.append(key, '');
230
+ }
231
+ form.append('device_id', feedbackDeviceId());
232
+ form.append('content', summary);
233
+ form.append('product_slug', 'dsh-mobile');
234
+ form.append('source', 'plugin');
235
+ form.append('component_id', 'dsh-mobile-plugin');
236
+ form.append('component_version', version || '');
237
+ form.append('submission_id', submissionId);
238
+ form.append('context', JSON.stringify({
239
+ source: 'plugin',
240
+ product_slug: 'dsh-mobile',
241
+ component_id: 'dsh-mobile-plugin',
242
+ component_version: version || '',
243
+ device_source: 'install',
244
+ files: { name: 'diagnosis.txt', type: 'text/plain' },
245
+ ...(context || {}),
246
+ }));
247
+ form.append('files', new Blob([diagnosis || ''], { type: 'text/plain' }), 'diagnosis.txt');
248
+
249
+ const controller = new AbortController();
250
+ const timer = setTimeout(() => controller.abort(), FEEDBACK_TIMEOUT_MS);
251
+ try {
252
+ const response = await fetch(FEEDBACK_URL, { method: 'POST', body: form, signal: controller.signal });
253
+ let body = null;
254
+ try { body = await response.json(); } catch { body = null; }
255
+ if (!response.ok) throw new Error((body && body.error) || `HTTP ${response.status}`);
256
+ const threadKey = body && body.data && body.data.thread_key;
257
+ if (!threadKey) throw new Error('反馈接口没有返回线程编号');
258
+ // 成功后清掉这条的 id:下一次同文案提交是新反馈,不能被服务端当成重试返回旧回执。
259
+ // 失败时保留,重试仍沿用同一个 id;在途的重复点击此前已取到同一个号,不受影响。
260
+ feedbackSubmissionIds.delete(summary);
261
+ return { threadKey, submissionId };
262
+ } catch (error) {
263
+ if (error && error.name === 'AbortError') throw new Error('反馈提交超时,网络可能不通');
264
+ throw error;
265
+ } finally {
266
+ clearTimeout(timer);
267
+ }
268
+ }
269
+
174
270
  /**
175
271
  * 打开那两小时网页管理窗口。
176
272
  *
@@ -632,6 +728,32 @@ window.__ModuleLoader__.load({
632
728
  },
633
729
  };
634
730
 
731
+ /**
732
+ * 就地反馈另挂一份小字典:原 `DICT` 的键集被守卫逐条钉死,新增动作不再往里挤。
733
+ * 中英各一份,与原字典同口径(locale 服务按命名空间注册 / 取词)。
734
+ */
735
+ const FEEDBACK_NS = 'settings.mobileRelay.feedback';
736
+ const FEEDBACK_DICT = {
737
+ zh: {
738
+ send: '发送此问题',
739
+ sending: '正在提交…',
740
+ receipt: '已提交,反馈编号 {key}。请复制编号留档;这条先留在本机,不会写进 App 的反馈列表。',
741
+ failed: '发送失败:{error}',
742
+ copyKey: '复制编号',
743
+ copied: '编号已复制。',
744
+ copyFailed: '复制失败,请手动选中编号复制。',
745
+ },
746
+ en: {
747
+ send: 'Send this issue',
748
+ sending: 'Submitting…',
749
+ receipt: 'Submitted. Feedback key {key}. Copy it for your records; this stays local first and is not written into the in-app feedback list.',
750
+ failed: 'Could not send: {error}',
751
+ copyKey: 'Copy key',
752
+ copied: 'Key copied.',
753
+ copyFailed: 'Copy failed; select the key and copy it manually.',
754
+ },
755
+ };
756
+
635
757
  /* ── 侧边栏图标选择(同一页共享) ────────────────────────────────────────
636
758
  * 设置卡和两颗图标各自物化,谁先谁后不定;选择放在这一份闭包里,开关一拨当场生效,
637
759
  * 不必等下一轮 20 秒的 /status。状态先到者写入;用户拨过之后,在途的旧状态不再覆盖
@@ -1545,7 +1667,7 @@ window.__ModuleLoader__.load({
1545
1667
  doc.body.appendChild(overlay);
1546
1668
  }
1547
1669
 
1548
- function MobileWebEntry({ wide, t }) {
1670
+ function MobileWebEntry({ wide, t, tf }) {
1549
1671
  /** null = 还没问到;'' = 问到了但宿主没给地址(老版本或还没起来)。 */
1550
1672
  const [url, setUrl] = useState(null);
1551
1673
  const [webAccess, setWebAccess] = useState(null);
@@ -1835,6 +1957,8 @@ window.__ModuleLoader__.load({
1835
1957
  };
1836
1958
  let current = failure || problem || null;
1837
1959
  let half = null;
1960
+ let submittedKey = '';
1961
+ let sendingFeedback = false;
1838
1962
 
1839
1963
  const title = kind === 'open' ? t('diagTitleOpen') : t('diagTitleLoad');
1840
1964
  const closeAction = { label: t('diagClose'), onClick: () => view.hide() };
@@ -1937,6 +2061,18 @@ window.__ModuleLoader__.load({
1937
2061
  }
1938
2062
  actions.push({ label: t('diagRetry'), onClick: () => void retry() });
1939
2063
  actions.push({ label: t('diagCopy'), onClick: () => void copy() });
2064
+ actions.push({
2065
+ label: submittedKey ? tf('copyKey') : (sendingFeedback ? tf('sending') : tf('send')),
2066
+ onClick: () => {
2067
+ if (submittedKey) {
2068
+ void copyDiagnosisText(document, submittedKey).then((ok) => render(ok
2069
+ ? `${tf('receipt', { key: submittedKey })} ${tf('copied')}`
2070
+ : tf('copyFailed')));
2071
+ } else {
2072
+ void sendFeedback();
2073
+ }
2074
+ },
2075
+ });
1940
2076
  actions.push(closeAction);
1941
2077
  view.open({
1942
2078
  title,
@@ -1955,6 +2091,34 @@ window.__ModuleLoader__.load({
1955
2091
  render(ok ? t('diagCopied') : t('diagCopyFailed'));
1956
2092
  }
1957
2093
 
2094
+ /** 把诊断读数作 text/plain 附件直接提交,回来就地给出线程 key。 */
2095
+ async function sendFeedback() {
2096
+ if (sendingFeedback) return;
2097
+ sendingFeedback = true;
2098
+ let note = tf('sending');
2099
+ try {
2100
+ const safeFacts = {
2101
+ version: half && half.version ? String(half.version) : '',
2102
+ stage: kind,
2103
+ code: current && current.status ? String(current.status) : '',
2104
+ scope: snapshot.scope,
2105
+ };
2106
+ const result = await submitIssueFeedback({
2107
+ summary: `${title}\n${summaryOf()}`,
2108
+ diagnosis: feedbackDiagnosisText(safeFacts),
2109
+ version: safeFacts.version,
2110
+ context: { title, ...safeFacts },
2111
+ });
2112
+ submittedKey = result.threadKey;
2113
+ note = tf('receipt', { key: submittedKey });
2114
+ } catch (error) {
2115
+ note = tf('failed', { error: String((error && error.message) || error) });
2116
+ } finally {
2117
+ sendingFeedback = false;
2118
+ }
2119
+ render(note);
2120
+ }
2121
+
1958
2122
  /** 重读一遍状态;读到就把这一屏的现场换成新的(心跳式的即时自愈)。 */
1959
2123
  async function retry() {
1960
2124
  render(t('diagBusy'));
@@ -2159,7 +2323,7 @@ window.__ModuleLoader__.load({
2159
2323
  * 点下去和手机图标一样弹一扇内嵌窗(不是跳走):公网地址先按 `panelScope` 开好两小时
2160
2324
  * 窗口,本机与局域网直接进。打不开时落到诊断窗,不许「点了没反应」。
2161
2325
  */
2162
- function RemoteWebEntry({ wide, t }) {
2326
+ function RemoteWebEntry({ wide, t, tf }) {
2163
2327
  const [url, setUrl] = useState(null);
2164
2328
  const [webAccess, setWebAccess] = useState(null);
2165
2329
  const [panelScope, setPanelScope] = useState('');
@@ -2212,6 +2376,8 @@ window.__ModuleLoader__.load({
2212
2376
  const view = diagnosisDialog();
2213
2377
  let current = failure || problem || null;
2214
2378
  let half = null;
2379
+ let submittedKey = '';
2380
+ let sendingFeedback = false;
2215
2381
  const snapshot = {
2216
2382
  url: typeof url === 'string' ? url : '',
2217
2383
  scope: panelScope || 'unknown',
@@ -2237,13 +2403,51 @@ window.__ModuleLoader__.load({
2237
2403
  if (half && half.lastError) rows.push({ key: 'host_last_error', label: t('diagFactReason'), value: half.lastError });
2238
2404
  return rows;
2239
2405
  };
2406
+ async function sendFeedback() {
2407
+ if (sendingFeedback) return;
2408
+ sendingFeedback = true;
2409
+ let note = tf('sending');
2410
+ try {
2411
+ const safeFacts = {
2412
+ version: half && half.version ? String(half.version) : '',
2413
+ stage: 'open',
2414
+ code: current && current.status ? String(current.status) : '',
2415
+ scope: snapshot.scope,
2416
+ };
2417
+ const result = await submitIssueFeedback({
2418
+ summary: `${t('diagTitleOpen')}\n${current ? t('diagSummaryOpenFailed') : ''}`,
2419
+ diagnosis: feedbackDiagnosisText(safeFacts),
2420
+ version: safeFacts.version,
2421
+ context: { title: t('diagTitleOpen'), ...safeFacts },
2422
+ });
2423
+ submittedKey = result.threadKey;
2424
+ note = tf('receipt', { key: submittedKey });
2425
+ } catch (error) {
2426
+ note = tf('failed', { error: String((error && error.message) || error) });
2427
+ } finally {
2428
+ sendingFeedback = false;
2429
+ }
2430
+ render(note);
2431
+ }
2432
+ const feedbackAction = () => ({
2433
+ label: submittedKey ? tf('copyKey') : (sendingFeedback ? tf('sending') : tf('send')),
2434
+ onClick: () => {
2435
+ if (submittedKey) {
2436
+ void copyDiagnosisText(document, submittedKey).then((ok) => render(ok
2437
+ ? `${tf('receipt', { key: submittedKey })} ${tf('copied')}`
2438
+ : tf('copyFailed')));
2439
+ } else {
2440
+ void sendFeedback();
2441
+ }
2442
+ },
2443
+ });
2240
2444
  const render = (note) => {
2241
2445
  view.open({
2242
2446
  title: t('diagTitleOpen'),
2243
2447
  summary: current ? t('diagSummaryOpenFailed') : t('diagChecking'),
2244
2448
  factsHeading: t('diagHeadingFacts'),
2245
2449
  facts: facts(),
2246
- actions: [closeAction],
2450
+ actions: [feedbackAction(), closeAction],
2247
2451
  note,
2248
2452
  });
2249
2453
  };
@@ -2980,8 +3184,16 @@ window.__ModuleLoader__.load({
2980
3184
  inject: ['slots', 'locale'],
2981
3185
  apply(ctx) {
2982
3186
  provideMobileChatEmbed(ctx);
2983
- ctx.effect(() => ctx.locale.register(NS, DICT), 'mobile-plugin: settings dictionaries');
3187
+ ctx.effect(() => {
3188
+ const offDictionary = ctx.locale.register(NS, DICT);
3189
+ const offFeedbackDictionary = ctx.locale.register(FEEDBACK_NS, FEEDBACK_DICT);
3190
+ return () => {
3191
+ if (typeof offDictionary === 'function') offDictionary();
3192
+ if (typeof offFeedbackDictionary === 'function') offFeedbackDictionary();
3193
+ };
3194
+ }, 'mobile-plugin: settings dictionaries');
2984
3195
  const t = ctx.locale.bind(NS);
3196
+ const tf = ctx.locale.bind(FEEDBACK_NS);
2985
3197
  installPluginPages(ctx, t);
2986
3198
  captureSessions(ctx);
2987
3199
  openEmbeddedSession(ctx);
@@ -3007,7 +3219,7 @@ window.__ModuleLoader__.load({
3007
3219
  order: 10,
3008
3220
  label: () => t('footerOpen'),
3009
3221
  locale: NS,
3010
- inject: () => ({ t }),
3222
+ inject: () => ({ t, tf }),
3011
3223
  }, MobileWebEntry));
3012
3224
  // 手机图标右边那颗电脑图标:远程电脑独立页的入口。展开态由组件自己插到手机图标
3013
3225
  // 后面(两个组件分别物化、谁先谁后不定,认手机图标的记号定位),窄条态各占一行。
@@ -3017,7 +3229,7 @@ window.__ModuleLoader__.load({
3017
3229
  order: 11,
3018
3230
  label: () => t('footerRemoteOpen'),
3019
3231
  locale: NS,
3020
- inject: () => ({ t }),
3232
+ inject: () => ({ t, tf }),
3021
3233
  }, RemoteWebEntry));
3022
3234
  },
3023
3235
  };
package/lib/impl.js CHANGED
@@ -741,6 +741,11 @@ function apply(ctx) {
741
741
  activeGuard,
742
742
  dropDeviceStreams,
743
743
  dropAllDeviceStreams,
744
+ // 「立即同步」(POST /relay/control-sync):催一发上报、读它的快照、以及它此刻会报上去的
745
+ // 那份明文清单。三样都取自同一个 control 客户端,不另算一套(见 lib/relay/control.js)。
746
+ getControl: () => control.snapshot(),
747
+ syncControl: () => control.sync(),
748
+ controlAddresses: () => control.addresses(),
744
749
  },
745
750
  }))
746
751
  mount('服务同步', () => ctx.effect(() => {
@@ -1,4 +1,4 @@
1
- // 新模型按公开资料补齐能力,已有模型保留原配置。
1
+ // Gemini 原生发现与协议档位保留端点容量,已有模型配置原样沿用。
2
2
  'use strict';
3
3
 
4
4
  /**
@@ -24,7 +24,8 @@ const { lookupModelMeta } = require('./model-meta.js');
24
24
  /** 自建渠道写在这个命名空间里;桌面端 `src/custom-channels.js` 的 PI_AI_NS 同值。 */
25
25
  const PI_AI_NS = 'llm-pi-ai';
26
26
 
27
- const PROTOCOLS = ['openai-completions', 'openai-responses', 'anthropic-messages'];
27
+ const PROTOCOLS = ['openai-completions', 'openai-responses', 'anthropic-messages', 'google-generative-ai'];
28
+ const GEMINI_LEVELS = ['minimal', 'low', 'medium', 'high'];
28
29
 
29
30
  /** 与 pi-ai 的缺省值同值:上游没报的时候,落到这里就是协议层本来会给的那个数。 */
30
31
  const DEFAULT_CONTEXT_WINDOW = 262144;
@@ -166,7 +167,9 @@ function profileOf(channel, existing) {
166
167
  // false 表示明确不思考;资料没有档位时才沿用通用缺省。
167
168
  reasoningEfforts: meta?.reasoning?.length === 0
168
169
  ? false
169
- : Object.fromEntries((meta?.reasoning ?? DEFAULT_REASONING).map((level) => [level, meta?.reasoningWires?.[level] ?? level])),
170
+ : channel.protocol === 'google-generative-ai'
171
+ ? Object.fromEntries(GEMINI_LEVELS.map((level) => [level, level]))
172
+ : Object.fromEntries((meta?.reasoning ?? DEFAULT_REASONING).map((level) => [level, meta?.reasoningWires?.[level] ?? level])),
170
173
  };
171
174
  }),
172
175
  };
@@ -290,7 +293,7 @@ async function handleChannels(ctx, req, res) {
290
293
  * 与桌面端 `discoverCandidates` 同一份规则。
291
294
  */
292
295
  function discoverCandidates(baseUrl, protocol) {
293
- if (protocol === 'anthropic-messages') return [baseUrl];
296
+ if (protocol === 'anthropic-messages' || protocol === 'google-generative-ai') return [baseUrl];
294
297
  let pathname = '/';
295
298
  try {
296
299
  pathname = new URL(baseUrl).pathname;
@@ -317,6 +320,39 @@ function lookupService(ctx, name) {
317
320
  * 「连不上地址」与「Key 不对」在手机上就分不出来。所以在这一层按已经见到的几种形状换成中文:
318
321
  * App 拿到的原话是中文就照原样显示,用户读得到下一步该干什么。
319
322
  */
323
+ function discoveredModelOf(row, protocol) {
324
+ if (!row || typeof row !== 'object') return null;
325
+ if (protocol === 'google-generative-ai' && Array.isArray(row.supportedGenerationMethods) && !row.supportedGenerationMethods.includes('generateContent')) return null;
326
+ if (protocol === 'google-generative-ai' && typeof row.id !== 'string') {
327
+ const rawName = typeof row.name === 'string' ? row.name.trim() : '';
328
+ const methods = Array.isArray(row.supportedGenerationMethods) ? row.supportedGenerationMethods : [];
329
+ if (!rawName || !methods.includes('generateContent')) return null;
330
+ const id = rawName.replace(/^models\//, '');
331
+ if (!id) return null;
332
+ const contextWindow = Number(row.inputTokenLimit);
333
+ const maxTokens = Number(row.outputTokenLimit);
334
+ return {
335
+ id,
336
+ name: typeof row.displayName === 'string' && row.displayName.trim() ? row.displayName.trim() : id,
337
+ ...(Number.isFinite(contextWindow) && contextWindow > 0 ? { contextWindow: Math.trunc(contextWindow) } : {}),
338
+ ...(Number.isFinite(maxTokens) && maxTokens > 0 ? { maxTokens: Math.trunc(maxTokens) } : {}),
339
+ protocol,
340
+ };
341
+ }
342
+ const rawId = typeof row.id === 'string' ? row.id.trim() : '';
343
+ const id = protocol === 'google-generative-ai' ? rawId.replace(/^models\//, '') : rawId;
344
+ if (!id) return null;
345
+ const contextWindow = Number(row.contextWindow ?? row.inputTokenLimit);
346
+ const maxTokens = Number(row.maxTokens ?? row.outputTokenLimit);
347
+ return {
348
+ id,
349
+ name: typeof row.name === 'string' && row.name.trim() ? row.name.trim() : id,
350
+ ...(Number.isFinite(contextWindow) && contextWindow > 0 ? { contextWindow: Math.trunc(contextWindow) } : {}),
351
+ ...(Number.isFinite(maxTokens) && maxTokens > 0 ? { maxTokens: Math.trunc(maxTokens) } : {}),
352
+ ...(row.vision === true || (Array.isArray(row.inputModalities) && row.inputModalities.includes('image')) ? { vision: true } : {}),
353
+ };
354
+ }
355
+
320
356
  function discoverFailureMessage(caught) {
321
357
  const raw = caught && typeof caught.message === 'string' ? caught.message : String(caught == null ? '' : caught);
322
358
  const code = caught && typeof caught.code === 'string' ? caught.code : '';
@@ -381,20 +417,7 @@ async function handleChannelDiscover(ctx, req, res) {
381
417
  ...(apiKey === '' ? {} : { apiKey }),
382
418
  });
383
419
  const models = (Array.isArray(found) ? found : [])
384
- .map((row) => {
385
- if (!row || typeof row !== 'object') return null;
386
- const id = typeof row.id === 'string' ? row.id.trim() : '';
387
- if (!id) return null;
388
- const contextWindow = Number(row.contextWindow);
389
- const maxTokens = Number(row.maxTokens);
390
- return {
391
- id,
392
- name: typeof row.name === 'string' && row.name.trim() ? row.name.trim() : id,
393
- ...(Number.isFinite(contextWindow) && contextWindow > 0 ? { contextWindow: Math.trunc(contextWindow) } : {}),
394
- ...(Number.isFinite(maxTokens) && maxTokens > 0 ? { maxTokens: Math.trunc(maxTokens) } : {}),
395
- ...(row.vision === true ? { vision: true } : {}),
396
- };
397
- })
420
+ .map((row) => discoveredModelOf(row, protocol))
398
421
  .filter(Boolean)
399
422
  .slice(0, MAX_MODELS);
400
423
  return sendJson(res, 200, { ok: true, baseUrl: baseURL, models });