dsh-mobile-plugin 0.5.117 → 0.5.119

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.
@@ -1,3 +1,5 @@
1
+ // 2026-11-25:CLI status 的 connected 也认作在跑,兼容新版客户端字段,别把活线路抖成掉线重连。
2
+ // 2026-11-25:端口失配带上可识别的 reason,让接线层清掉旧地址(配对码不再带失效线路)。
1
3
  // 2026-11-25:running 认守护进程而非早退出的启动进程;连上后可由接线层定时体检判活。
2
4
  // 2026-11-25:复用隧道前比对 local_port,旧端口隧道不再静默复用。
3
5
  // ZeroNews 客户端运行器:ensure→login→start→建隧道→读域名,进程生命周期与状态。
@@ -117,16 +119,17 @@ function parseStatusPayload(raw) {
117
119
  login: truthy(obj.login),
118
120
  loginPending: truthy(obj.login_pending),
119
121
  loginError: typeof obj.login_error === 'string' ? obj.login_error.trim() : '',
120
- running: truthy(obj.running),
122
+ running: truthy(obj.running) || truthy(obj.connected),
121
123
  configured: truthy(obj.configured),
122
124
  clientEnabled: obj.client_enabled !== false,
123
125
  };
124
126
  }
125
127
 
126
- /** 确定性错误:重试也没用,标成 terminal,让接线层别再无限退避重连。 */
127
- function terminalError(message) {
128
+ /** 确定性错误:重试也没用,标成 terminal,让接线层别再无限退避重连。reason 让接线层认出「端口失配」这种要清旧地址的场景。 */
129
+ function terminalError(message, reason) {
128
130
  const error = new Error(message);
129
131
  error.code = 'terminal';
132
+ error.reason = reason || '';
130
133
  return error;
131
134
  }
132
135
 
@@ -163,6 +166,7 @@ function createZeroNewsRunner(options = {}) {
163
166
  let startPromise = null;
164
167
  let binary = '';
165
168
  let error = '';
169
+ let errorReason = '';
166
170
  let url = '';
167
171
  let phase = 'off'; // off | installing | login | starting | connecting | connected | error
168
172
  let retryable = true;
@@ -173,6 +177,9 @@ function createZeroNewsRunner(options = {}) {
173
177
  */
174
178
  let daemonRunning = false;
175
179
  let aliveCheckPromise = null;
180
+ // 已有隧道正指向的本机端口(0 = 还没有隧道)。下次启动原样复用它,别把已经在用
181
+ // 的隧道改到新端口 —— 那会判成端口失配,而官方 CLI 的删除参数没公开,重建有风险。
182
+ let tunnelLocalPort = 0;
176
183
 
177
184
  function status() {
178
185
  return {
@@ -181,11 +188,15 @@ function createZeroNewsRunner(options = {}) {
181
188
  phase,
182
189
  url: phase === 'connected' ? url : '',
183
190
  error,
191
+ // 错误的可识别子类:端口失配时接线层据此清掉状态里那条已经连不上的旧域名。
192
+ errorReason,
184
193
  // 这个错还值不值得自动重试:配额满 / 被拒 / token 冲突这类确定性错误重试也没用,
185
194
  // 交给接线层别再无限退避重连,直接把原因留给用户处理。
186
195
  retryable,
187
196
  // 只反映这一进程里见过的身份;落盘的那份由接线层并进来(见 wiring.cjs 的 statusOf)。
188
197
  configured,
198
+ // 已有隧道指向的本机端口:接线层据此沿用同一端口,避免把在用的隧道判成失配。
199
+ tunnelLocalPort,
189
200
  };
190
201
  }
191
202
 
@@ -276,10 +287,11 @@ function createZeroNewsRunner(options = {}) {
276
287
  const found = pickEndpointDetail(await api('/api/v1/endpoints'));
277
288
  const current = Number.isInteger(port) && port > 0 ? port : 0;
278
289
  if (found) {
290
+ tunnelLocalPort = Number.isInteger(found.localPort) && found.localPort > 0 ? found.localPort : 0;
279
291
  // 只有字段明确在、且指向另一个端口才算失配:老接口的 endpoints 没有 local_port,
280
292
  // 那种照旧复用。失配不自动删云端隧道(仓里没有删除入口),标红并让用户自己删旧的。
281
293
  if (current > 0 && found.localPort > 0 && found.localPort !== current) {
282
- throw terminalError(`旧隧道指向旧端口,请删除后重试(旧端口 ${found.localPort},当前本机端口 ${current})`);
294
+ throw terminalError(`旧隧道指向旧端口,请删除后重试(旧端口 ${found.localPort},当前本机端口 ${current})`, 'port-mismatch');
283
295
  }
284
296
  return found.url;
285
297
  }
@@ -303,9 +315,10 @@ function createZeroNewsRunner(options = {}) {
303
315
  } catch (error) {
304
316
  addError = error && error.message ? error.message : String(error);
305
317
  }
306
- if (added) return added;
318
+ // 新建成功:记住它落在哪个端口上,下次启动沿用,不再判成「旧隧道指向旧端口」。
319
+ if (added) { tunnelLocalPort = port; return added; }
307
320
  const waited = await waitEndpoint(START_TIMEOUT_MS, port);
308
- if (waited) return waited;
321
+ if (waited) { tunnelLocalPort = port; return waited; }
309
322
  // 免费档只有 1 条 1Mbps 隧道;额度被旧隧道占住、或账号侧拒绝时,原文要透出来,
310
323
  // 别让用户只看到「连上了但拿不到地址」这种猜不出原因的提示。
311
324
  if (addError) {
@@ -317,6 +330,7 @@ function createZeroNewsRunner(options = {}) {
317
330
  async function runStart() {
318
331
  const gen = ++generation;
319
332
  error = '';
333
+ errorReason = '';
320
334
  url = '';
321
335
  retryable = true;
322
336
  try {
@@ -423,6 +437,7 @@ function createZeroNewsRunner(options = {}) {
423
437
  }
424
438
  phase = 'error';
425
439
  error = err && err.message ? err.message : String(err);
440
+ errorReason = err && err.reason ? err.reason : '';
426
441
  // 配额 / 被拒 / token 冲突 / 无可用带宽这类重试也白搭,别让接线层无限退避重连。
427
442
  retryable = !(err && err.code === 'terminal') && !/quota|bandwidth|额度|带宽|名额|already exists|token update ignored/i.test(error);
428
443
  }
@@ -458,6 +473,7 @@ function createZeroNewsRunner(options = {}) {
458
473
  phase = 'error';
459
474
  error = 'ZeroNews 客户端意外退出';
460
475
  retryable = true;
476
+ errorReason = '';
461
477
  if (onUnexpectedExit) { try { onUnexpectedExit(error); } catch { /* 回调失败不影响状态 */ } }
462
478
  })();
463
479
  try { await aliveCheckPromise; } finally { aliveCheckPromise = null; }
@@ -472,6 +488,7 @@ function createZeroNewsRunner(options = {}) {
472
488
  daemonRunning = false;
473
489
  url = '';
474
490
  error = '';
491
+ errorReason = '';
475
492
  phase = 'off';
476
493
  return status();
477
494
  }
@@ -1,3 +1,4 @@
1
+ // 2026-11-25:端口失配时清掉状态里的旧地址,配对码 / 心跳 / 总控都不再带失效线路。
1
2
  // 2026-11-25:连上后定时体检守护进程,发现进程没了自动走自愈重连。
2
3
  // 2026-11-24:首次接入先开代理商邀请链接埋归属 cookie,让新注册用户无感归到代理商名下。
3
4
  // ZeroNews 线路挂载:把运行器接进装配层,隧道地址写回独立字段,随 effect 启停。
@@ -181,9 +182,19 @@ function mountZeroNews(options) {
181
182
  return { ...current, configured: current.configured === true || getState().zeroNewsBound === true };
182
183
  };
183
184
 
184
- const runner = makeRunner({
185
+ // 落点端口:已经有隧道在用时沿用它自己的端口(老用户可能仍指向 18787),只在没有隧道时
186
+ // 才用判据给的首选值。反过来做会把在用的隧道判成端口失配 —— 官方 CLI 没公开删除参数,
187
+ // 重建有风险,不如原地复用。
188
+ const preferredPort = () => Number(options.portOf && options.portOf()) || 0;
189
+ let runner = null;
190
+ const tunnelPort = () => {
191
+ const current = runner && typeof runner.status === 'function' ? runner.status() : null;
192
+ const known = current ? Number(current.tunnelLocalPort) : 0;
193
+ return Number.isInteger(known) && known > 0 ? known : preferredPort();
194
+ };
195
+ runner = makeRunner({
185
196
  ensure: provision,
186
- portOf: () => Number(options.portOf && options.portOf()) || 0,
197
+ portOf: tunnelPort,
187
198
  // 客户端在我们「以为还连着」的时候退出(插件重载 / 自动更新 / 偶发崩溃):安排一次自愈重连。
188
199
  onUnexpectedExit: () => scheduleRetry(),
189
200
  });
@@ -202,6 +213,14 @@ function mountZeroNews(options) {
202
213
  try { await settings.update({ zeroNewsUrl: result.url, zeroNewsEnabled: true }); }
203
214
  catch (error) { warn('把 ZeroNews 地址写回状态失败:%s', error && error.message ? error.message : error); }
204
215
  }
216
+ // 端口失配:旧隧道指向的是旧端口,状态里那条域名虽然还在,手机拨过去却连不上。
217
+ // 清掉它,让配对码 / 心跳 / 总控同源的 providerLinesOf 都不再带这条失效线路。
218
+ // notify:false:只落盘并改内存状态,不走 watch → applyServices → control.sync(),
219
+ // 免得「configured 就自动重连」那条 mount effect 被同一份状态变更反复叫醒。
220
+ if (result && result.phase === 'error' && result.errorReason === 'port-mismatch' && getState().zeroNewsUrl) {
221
+ try { await settings.update({ zeroNewsUrl: '' }, { notify: false }); }
222
+ catch (error) { warn('清掉失配的 ZeroNews 旧地址失败:%s', error && error.message ? error.message : error); }
223
+ }
205
224
  // 一旦确认这台机器有身份就落盘标记,面板下次不必再让人粘一遍 token(token 本身不存)。
206
225
  if (result && result.configured === true && getState().zeroNewsBound !== true) {
207
226
  try { await settings.update({ zeroNewsBound: true }); }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-mobile-plugin",
3
- "version": "0.5.117",
3
+ "version": "0.5.119",
4
4
  "description": "Mobile API (/api/mobile/v1) and relay client for the DSH mobile app — desktop profile build (dsh 0.2.x, peers resolved by the host)",
5
5
  "license": "MIT",
6
6
  "icon": "./icon.png",
@@ -117,23 +117,23 @@
117
117
  "yaml": "2.9.1"
118
118
  },
119
119
  "dshMobileReleaseNotes": {
120
- "version": "0.5.117",
120
+ "version": "0.5.119",
121
121
  "kinds": [
122
- "fix",
123
- "feature"
122
+ "feature",
123
+ "fix"
124
124
  ],
125
125
  "notes": {
126
- "zh-Hans": "- 修复零讯线路的问题:客户端意外退出后不再一直显示「已连接」,会定期检查客户端状态,掉线后自动恢复。\n- 从引导页或失败页提交问题时,会自动带上问题来源、场景和版本信息,反馈更容易被定位。",
127
- "zh-Hant": "- 修復零訊線路的問題:用戶端意外結束後不再一直顯示「已連線」,會定期檢查用戶端狀態,掉線後自動恢復。\n- 從引導頁或失敗頁提交問題時,會自動帶上問題來源、場景與版本資訊,讓回報更容易被定位。",
128
- "en": "- Fixed an issue where the ZeroNews route kept showing \"Connected\" after the client exited unexpectedly and never reconnected. The client is now checked periodically and the route is restored automatically after a drop.\n- Feedback sent from the guide or an error page now includes its source, scenario and version details, making reports easier to trace.",
129
- "ja": "- クライアントが予期せず終了しても ZeroNews 回線が「接続済み」のまま自動再接続しない問題を修正しました。定期的にクライアントの状態を確認し、切断後は自動で復旧します。\n- ガイド画面やエラー画面から問題を送信すると、発生元・場面・バージョン情報が自動で付き、報告を追いやすくなりました。",
130
- "ko": "- 클라이언트가 예기치 않게 종료된 뒤에도 ZeroNews 회선이 '연결됨'으로만 표시되고 자동 재연결되지 않던 문제를 수정했습니다. 이제 클라이언트 상태를 주기적으로 확인하고, 연결이 끊기면 자동으로 복구합니다.\n- 안내 화면이나 오류 화면에서 문제를 제출할 때 출처, 상황, 버전 정보가 함께 전송되어 보고 내용을 더 쉽게 추적할 수 있습니다.",
131
- "de": "- Behoben: Die ZeroNews-Verbindung zeigte nach einem unerwarteten Client-Absturz weiterhin „Verbunden\" und stellte die Verbindung nicht wieder her. Der Client wird jetzt regelmäßig geprüft und nach einem Abbruch automatisch wiederhergestellt.\n- Feedback aus dem Einrichtungs- oder Fehlerbildschirm enthält jetzt automatisch Quelle, Szene und Versionsangaben, sodass Meldungen leichter nachvollziehbar sind.",
132
- "es": "- Se corrigió un problema por el cual la línea ZeroNews seguía mostrando «Conectado» después de que el cliente saliera de forma inesperada y nunca se reconectaba. Ahora se comprueba periódicamente el cliente y la línea se restaura automáticamente tras una caída.\n- Los informes enviados desde la guía o una pantalla de error incluyen automáticamente el origen, la situación y la versión, lo que facilita su seguimiento.",
133
- "fr": "- Correction d'un problème où la ligne ZeroNews affichait toujours « Connecté » après la fermeture inattendue du client et ne se reconnectait jamais. Le client est désormais vérifié régulièrement et la ligne est restaurée automatiquement après une coupure.\n- Les signalements envoyés depuis le guide ou un écran d'erreur incluent désormais automatiquement la source, le contexte et la version, ce qui facilite leur suivi.",
134
- "pt": "- Corrigido um problema em que a linha ZeroNews continuava mostrando \"Conectado\" depois que o cliente saía inesperadamente e nunca se reconectava. Agora o cliente é verificado periodicamente e a linha é restaurada automaticamente após uma queda.\n- Os relatórios enviados pelo guia ou por uma tela de erro agora incluem automaticamente a origem, o cenário e a versão, facilitando o acompanhamento.",
135
- "ru": "- Исправлена проблема, при которой линия ZeroNews продолжала показывать «Подключено» после непредвиденного завершения клиента и не восстанавливала соединение. Теперь состояние клиента проверяется периодически, и после обрыва линия восстанавливается автоматически.\n- Отзывы, отправленные из руководства или экрана ошибки, теперь автоматически содержат источник, сценарий и версию, что упрощает их отслеживание.",
136
- "tr": "- İstemci beklenmedik şekilde kapandıktan sonra ZeroNews hattının \"Bağlı\" görünmeye devam edip hiç yeniden bağlanmaması sorunu düzeltildi. Artık istemci düzenli olarak kontrol ediliyor ve kopma sonrası hat otomatik olarak geri yükleniyor.\n- Kılavuz veya hata ekranından gönderilen geri bildirimler artık kaynak, senaryo ve sürüm bilgilerini otomatik olarak içeriyor; böylece takip kolaylaşıyor."
126
+ "zh-Hans": "- 网络:电脑上端口被占用时自动改用专属回环入口继续工作,实在绕不开才弹窗给指引。\n- 修复面板侧栏内容改动后手机端要等一会儿才同步的问题。\n- 修复新版电脑端只报告「已连接」时插件误判为掉线、反复重连的问题。\n- 手机通知默认档改为五类提醒都响铃,完成类提醒不再默认静默。",
127
+ "zh-Hant": "- 網路:電腦上連接埠被佔用時自動改用專屬回環入口繼續運作,真的繞不開才彈窗給指引。\n- 修正面板側欄內容變更後手機端要等一下才同步的問題。\n- 修正新版電腦端只回報「已連線」時外掛誤判為離線、反覆重連的問題。\n- 手機通知預設改為五類提醒都會響鈴,完成類提醒不再預設靜音。",
128
+ "en": "- Network: when a port is already taken on the computer, the plugin now falls back to a dedicated loopback entry automatically and only shows guidance when it really cannot get around the conflict.\n- Fixed phone-side sidebar content lagging behind panel edits.\n- Fixed the plugin treating the newer desktop's \"connected\"-only status as a dropped connection and reconnecting repeatedly.\n- Phone notifications now ring for all five reminder types by default; completion alerts are no longer silent by default.",
129
+ "ja": "- ネットワーク:パソコン側のポートが使用中のときは専用のループバック入口へ自動的に切り替えて動作を続け、どうしても回避できない場合だけ案内を表示します。\n- パネルのサイドバー内容を変更してからスマホ側に同期されるまで待たされる問題を修正しました。\n- 新しいデスクトップ版が「接続済み」だけを報告する場合に、プラグインが切断と誤判定して繰り返し再接続する問題を修正しました。\n- スマホ通知の既定を、5種類のリマインダーすべてが鳴るように変更しました。完了通知は既定で無音になりません。",
130
+ "ko": "- 네트워크: 컴퓨터에서 포트가 사용 중이면 전용 루프백 진입점으로 자동 전환해 계속 동작하고, 정말 우회할 수 없을 때만 안내 창을 띄웁니다.\n- 패널 사이드바 내용을 바꾼 뒤 휴대폰에서 동기화까지 기다려야 하던 문제를 수정했습니다.\n- 최신 데스크톱이 '연결됨'만 보고할 때 플러그인이 끊김으로 잘못 판단해 반복 재연결하던 문제를 수정했습니다.\n- 휴대폰 알림 기본값을 다섯 가지 알림 모두 울리도록 바꿨습니다. 완료 알림은 더 이상 기본으로 무음이 아닙니다.",
131
+ "de": "- Netzwerk: Ist ein Port auf dem Computer belegt, weicht das Plugin jetzt automatisch auf einen eigenen Loopback-Einstieg aus und zeigt nur dann einen Hinweis, wenn das wirklich nicht geht.\n- Behoben: Änderungen in der Seitenleiste des Panels kamen auf dem Handy erst mit Verzögerung an.\n- Behoben: Meldete der neuere Desktop nur „verbunden“, hielt das Plugin die Verbindung für verloren und verband sich wiederholt neu.\n- Benachrichtigungen am Handy klingeln in der Standardeinstellung jetzt bei allen fünf Erinnerungsarten; Abschluss-Hinweise sind nicht mehr standardmäßig stumm.",
132
+ "es": "- Red: si un puerto ya está ocupado en el ordenador, el plugin pasa automáticamente a una entrada de bucle dedicada y solo muestra una guía cuando de verdad no puede evitarlo.\n- Corregido: los cambios en la barra lateral del panel tardaban en llegar al teléfono.\n- Corregido: cuando el escritorio nuevo solo informa \"conectado\", el plugin lo tomaba como desconexión y se reconectaba en bucle.\n- Las notificaciones del teléfono suenan ahora para los cinco tipos de aviso por defecto; los avisos de finalización ya no quedan en silencio.",
133
+ "fr": "- Réseau : si un port est déjà occupé sur l'ordinateur, le plugin bascule automatiquement sur une entrée de boucle dédiée et n'affiche une aide que s'il ne peut vraiment pas l'éviter.\n- Correction : les modifications de la barre latérale du panneau mettaient du temps à arriver sur le téléphone.\n- Correction : quand le nouveau bureau ne signale que « connecté », le plugin croyait à une déconnexion et se reconnectait en boucle.\n- Les notifications du téléphone sonnent désormais pour les cinq types de rappel par défaut ; les alertes de fin ne sont plus muettes par défaut.",
134
+ "pt": "- Rede: se uma porta já estiver em uso no computador, o plugin passa automaticamente para uma entrada de loopback dedicada e só mostra orientação quando realmente não consegue contornar.\n- Corrigido: as alterações na barra lateral do painel demoravam a chegar ao telemóvel.\n- Corrigido: quando o ambiente de trabalho novo só informa \"ligado\", o plugin interpretava como queda e reconectava repetidamente.\n- As notificações do telemóvel passam a tocar para os cinco tipos de aviso por predefinição; os avisos de conclusão já não ficam em silêncio.",
135
+ "ru": "- Сеть: если порт на компьютере уже занят, плагин автоматически переходит на отдельный loopback-вход и показывает подсказку только тогда, когда обойти конфликт действительно нельзя.\n- Исправлено: изменения в боковой панели стали появляться на телефоне с задержкой.\n- Исправлено: когда новая настольная версия сообщает только «подключено», плагин считал соединение потерянным и переподключался по кругу.\n- Уведомления на телефоне теперь по умолчанию звонят для всех пяти типов напоминаний; уведомления о завершении больше не беззвучны.",
136
+ "tr": "- Ağ: bilgisayarda bağlantı noktası doluysa eklenti artık otomatik olarak kendine ait bir loopback girişine geçiyor; gerçekten kaçınamıyorsa yönlendirme gösteriyor.\n- Düzeltildi: panel kenar çubuğundaki değişikliklerin telefona geç ulaşması.\n- Düzeltildi: yeni masaüstü yalnızca \"bağlı\" bildirdiğinde eklentinin bağlantıyı kopmuş sayıp sürekli yeniden bağlanması.\n- Telefon bildirimleri artık varsayılan olarak beş hatırlatma türünün hepsinde çalıyor; tamamlanma bildirimleri varsayılan olarak sessiz değil."
137
137
  }
138
138
  }
139
139
  }