dsh-mobile-ios 0.2.6 → 0.2.8

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,1193 +1,1294 @@
1
- // lib/client.js — 桌面端 UI 注入模块(X3)
2
- //
3
- // 契约(考古自社区 dsh-mobile 0.8.11 的 lib/client.js):
4
- // 宿主 web app 按包的 `exports["./client"]` 加载本文件,浏览器里执行到
5
- // `window.__ModuleLoader__.load({ id, factory })` 注册模块;
6
- // factory 返回的模块需导出 `apply(ctx)` 与 `inject = ["slots"]`,
7
- // 宿主把 slots 服务注入进来,UI 通过 slots 挂载。
8
- //
9
- // 我们挂两个东西:
10
- // 1. 左下角侧栏 banner(slot: sidebar.footer.action)——手机图标 + 「iOS移动伴侣」
11
- // + 连接状态点;窄栏(rail)只留图标。
12
- // 2. 点击展开的状态面板(原生 DOM overlay,宿主未提供 react-dom)——
13
- // 网关状态 / 适配器 / 已配对设备 / 隧道 / 生成配对码。
14
- //
15
- // 如实边界:网关端口被占会自动顺延(3081–3085 探测);面板数据来自
16
- // /mobile/v1/desktop/summary(回环-only,无敏感字段),拿不到就明确显示
17
- // 「网关不可达」,绝不编造状态。
18
- window.__ModuleLoader__.load({
19
- id: 'dsh-mobile-ios',
20
- factory: (require) => {
21
- var module = { exports: {} };
22
- var exports = module.exports;
23
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
24
-
25
- let react = require('react');
26
-
27
- // ── 状态 ─────────────────────────────────────────────────────
28
- const PORT_CANDIDATES = [3081, 3082, 3083, 3084, 3085];
29
- let gatewayPort = null;
30
- let summary = null; // /desktop/summary 结果或 null
31
- let probing = false;
32
-
33
- function baseUrl() {
34
- return gatewayPort ? `http://127.0.0.1:${gatewayPort}` : null;
35
- }
36
-
37
- async function fetchJson(path, options, timeoutMs = 1500) {
38
- const base = baseUrl();
39
- if (!base) throw new Error('gateway-not-found');
40
- const controller = new AbortController();
41
- const timer = setTimeout(() => controller.abort(), timeoutMs);
42
- try {
43
- const res = await fetch(base + path, { ...options, signal: controller.signal });
44
- const body = await res.json();
45
- if (!res.ok) throw Object.assign(new Error(body?.error?.message || res.statusText), { body });
46
- return body;
47
- } finally {
48
- clearTimeout(timer);
49
- }
50
- }
51
-
52
- /** 探测网关端口(顺延容忍),成功后拉一次摘要 */
53
- async function probe() {
54
- if (probing) return;
55
- probing = true;
56
- try {
57
- let found = null;
58
- for (const port of PORT_CANDIDATES) {
59
- const controller = new AbortController();
60
- const timer = setTimeout(() => controller.abort(), 700);
61
- try {
62
- const res = await fetch(`http://127.0.0.1:${port}/mobile/v1/health`, { signal: controller.signal });
63
- if (res.ok) { found = port; break; }
64
- } catch {} // 端口不是我们/没起,继续探
65
- finally { clearTimeout(timer); }
66
- }
67
- // 必须跟着探到的结果走:只在成功时赋值、失败时清空。
68
- // 以前失败会保留旧端口,网关换端口后一直去敲那个死端口(若被别的服务
69
- // 占用还会解析出非 JSON),面板就一直红着。
70
- gatewayPort = found;
71
- if (gatewayPort) summary = await fetchJson('/mobile/v1/desktop/summary').catch(() => null);
72
- else summary = null;
73
- } finally {
74
- probing = false;
75
- }
76
- }
77
-
78
- /** 面板打开时的轻量刷新:端口已经探到,只拉摘要并重绘,不再重复扫端口。 */
79
- async function refreshSummary() {
80
- if (!gatewayPort || summaryFetching) return;
81
- summaryFetching = true;
82
- try {
83
- const next = await fetchJson('/mobile/v1/desktop/summary').catch(() => null);
84
- if (next?.ok) {
85
- summary = next;
86
- renderSummary();
87
- }
88
- } finally {
89
- summaryFetching = false;
90
- }
91
- }
92
-
93
- /**
94
- * 首屏快速补探。
95
- *
96
- * 宿主重启时插件先于网关绑端口加载,第一次探测必然落空;
97
- * 只靠 15 秒轮询会让面板红着不动,用户看到的就是「插件坏了」。
98
- */
99
- async function probeUntilUp(attempts = 5, delayMs = 1200) {
100
- for (let i = 0; i < attempts; i += 1) {
101
- await probe();
102
- if (summary && summary.ok) return;
103
- if (i < attempts - 1) await new Promise((resolve) => { setTimeout(resolve, delayMs); });
104
- }
105
- }
106
-
107
- /** 生成配对码(本机动作,回环-only 端点)。route 显式选路:'lan' | 'tunnel' | undefined=自动 */
108
- async function issuePairingCode(route) {
109
- return fetchJson('/mobile/v1/pairing/code', {
110
- method: 'POST',
111
- headers: { 'content-type': 'application/json' },
112
- body: JSON.stringify({ deviceName: '待连接设备', ...(route ? { route } : {}) }),
113
- }, 2500);
114
- }
115
-
116
- /** 隧道启停(本机管理面动作,回环-only 端点) */
117
- /** 单台下线:管理面动作,与出码同样的本机约束,绝不走公网域名。 */
118
- async function revokeDevice(deviceId) {
119
- return fetchJson('/mobile/v1/pairing/revoke-device', {
120
- method: 'POST',
121
- headers: { 'content-type': 'application/json' },
122
- body: JSON.stringify({ deviceId }),
123
- }, 2500);
124
- }
125
-
126
- async function tunnelAction(action) {
127
- // start 首次会顺带「开通固定地址 + 等公网注册 + DNS 复查」,实测经常超过 20s;
128
- // 以前 20s 就掐断,用户点第一次报错、点第二次才出码——就是这里太短。
129
- return fetchJson(`/mobile/v1/tunnel/${action}`, { method: 'POST' }, action === 'start' ? 60000 : 25000);
130
- }
131
-
132
- // ── 样式 ─────────────────────────────────────────────────────
133
- const STYLE_ID = 'dsh-mios-style';
134
- function installStyle() {
135
- if (document.getElementById(STYLE_ID)) return;
136
- const style = document.createElement('style');
137
- style.id = STYLE_ID;
138
- // 主题跟随宿主:颜色全部走 CSS 变量,.light 类由 detectHostTheme() 动态切换。
139
- // 以前全硬编码深色,宿主开浅色主题时面板像一块黑补丁(2026-11-18 真机反馈)。
140
- style.textContent = `
141
- .dsh-mios-trigger { display: inline-flex; align-items: center; gap: 7px; background: none;
142
- border: none; color: inherit; cursor: pointer; padding: 6px 8px; border-radius: 8px;
143
- font: inherit; line-height: 1; }
144
- .dsh-mios-trigger:hover { background: rgba(255,255,255,.08); }
145
- .dsh-mios-trigger.is-rail { padding: 8px; }
146
- .dsh-mios-dot { width: 7px; height: 7px; border-radius: 50%; flex: none; }
147
- .dsh-mios-dot.ok { background: #3fb27f; }
148
- .dsh-mios-dot.down { background: #d94f3d; }
149
- .dsh-mios-panel { --bg: #171b24; --fg: #e8eaf0; --muted: #8b93a3; --border: #303a52;
150
- --border-hover: #4a5678; --shadow: rgba(0,0,0,.5); --fg-soft: rgba(232,234,240,.7);
151
- --muted-border: rgba(139,147,163,.45); --muted-bg: rgba(139,147,163,.12);
152
- --muted-bg-hover: rgba(139,147,163,.2); }
153
- .dsh-mios-panel.light { --bg: #ffffff; --fg: #1f2430; --muted: #6b7280; --border: #d9dee8;
154
- --border-hover: #9aa5bd; --shadow: rgba(31,36,48,.18); --fg-soft: rgba(31,36,48,.7);
155
- --muted-border: rgba(107,114,128,.4); --muted-bg: rgba(107,114,128,.1);
156
- --muted-bg-hover: rgba(107,114,128,.18); }
157
- .dsh-mios-panel { position: fixed; left: 14px; bottom: 52px; width: 300px; z-index: 99990;
158
- background: var(--bg); color: var(--fg); border: 1px solid var(--border); border-radius: 14px;
159
- box-shadow: 0 14px 44px var(--shadow); font: 13px/1.6 -apple-system, "PingFang SC", sans-serif;
160
- padding: 14px; }
161
- .dsh-mios-panel h3 { margin: 0 0 10px; font-size: 14px; display: flex; align-items: center; gap: 8px; }
162
- .dsh-mios-upd { margin-left: auto; background: none; border: 1px solid var(--border); border-radius: 7px;
163
- color: var(--muted); font-family: inherit; font-size: 11px; font-weight: 500; line-height: 1.4;
164
- cursor: pointer; padding: 3px 8px; }
165
- .dsh-mios-upd:hover { color: var(--fg); border-color: var(--border-hover); }
166
- .dsh-mios-modal-mask { --modal-bg:#1c2230; --modal-fg:#e8eaf0; --modal-muted:#8b93a3;
167
- --modal-border:#3a4560; --modal-btn:rgba(139,147,163,.12); --modal-accent:#3fb27f; --modal-shadow:rgba(0,0,0,.6);
168
- position:fixed; inset:0; z-index:2147483000; background:var(--modal-shadow);
169
- display:flex; align-items:center; justify-content:center; padding:20px;
170
- font-family:-apple-system, "PingFang SC", sans-serif; font-size:13px; line-height:1.6; }
171
- .dsh-mios-modal-mask.light { --modal-bg:#ffffff; --modal-fg:#1f2430; --modal-muted:#6b7280;
172
- --modal-border:#d9dee8; --modal-btn:rgba(107,114,128,.1); --modal-accent:#2f9d70; --modal-shadow:rgba(31,36,48,.35); }
173
- .dsh-mios-modal { width:100%; max-width:340px; box-sizing:border-box; background:var(--modal-bg);
174
- color:var(--modal-fg); border:1px solid var(--modal-border); border-radius:14px; padding:18px;
175
- box-shadow:0 18px 60px var(--modal-shadow); }
176
- .dsh-mios-modal h4 { margin:0 0 12px; font-size:15px; display:flex; align-items:center; gap:8px; }
177
- .dsh-mios-modal .modal-banner { margin:0 0 12px; padding:9px 11px; border-radius:9px; font-size:12px;
178
- font-weight:600; line-height:1.5; background:rgba(63,178,127,.12); color:var(--modal-accent);
179
- border:1px solid var(--modal-accent); }
180
- .dsh-mios-modal .modal-banner.success { background:rgba(63,178,127,.16); color:#2f9d70; }
181
- .dsh-mios-modal .modal-banner.warn { background:rgba(224,160,60,.14); color:#d18a26; border-color:#d18a26; }
182
- .dsh-mios-modal .modal-banner.error { background:rgba(217,79,61,.14); color:#d94f3d; border-color:#d94f3d; }
183
- .dsh-mios-modal .modal-x { margin-left:auto; background:none; border:none; color:var(--modal-muted);
184
- font-size:16px; cursor:pointer; line-height:1; padding:2px 4px; }
185
- .dsh-mios-modal .modal-line { display:flex; justify-content:space-between; gap:10px;
186
- font-size:12px; color:var(--modal-muted); margin:6px 0; }
187
- .dsh-mios-modal .modal-line b { color:var(--modal-fg); font-weight:600; max-width:200px;
188
- overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
189
- .dsh-mios-modal .modal-line b.new { color:var(--modal-accent); }
190
- .dsh-mios-modal .modal-note { margin:12px 0 4px; font-size:11px; color:var(--modal-muted); line-height:1.6; }
191
- .dsh-mios-modal .modal-actions { display:flex; gap:8px; margin-top:14px; }
192
- .dsh-mios-modal .modal-actions button { flex:1; padding:8px 0; border-radius:8px; cursor:pointer;
193
- font-family:inherit; font-size:12px; font-weight:600; line-height:1.4;
194
- border:1px solid var(--modal-border); background:var(--modal-btn); color:var(--modal-fg); }
195
- .dsh-mios-modal .modal-actions button.primary { border-color:var(--modal-accent);
196
- background:rgba(63,178,127,.16); color:var(--modal-accent); }
197
- .dsh-mios-modal .modal-actions button:disabled { opacity:.6; cursor:default; }
198
- .dsh-mios-panel .row { display: flex; justify-content: space-between; gap: 8px; color: var(--muted); margin: 3px 0; }
199
- .dsh-mios-panel .row b { color: var(--fg); font-weight: 600; text-align: right; max-width: 170px;
200
- overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
201
- .dsh-mios-device-toggle { background: none; border: none; color: var(--muted); cursor: pointer;
202
- font: inherit; padding: 0; display: inline-flex; align-items: center; gap: 5px; }
203
- .dsh-mios-device-toggle:hover { color: var(--fg); }
204
- .dsh-mios-devices { margin: 2px 0 6px; border: 1px solid var(--border); border-radius: 8px; overflow: hidden; }
205
- .dsh-mios-devices[hidden] { display: none; }
206
- .dsh-mios-device-row { display: flex; align-items: center; gap: 8px; padding: 5px 10px;
207
- font-size: 11px; color: var(--muted); border-top: 1px solid var(--border); }
208
- .dsh-mios-device-row:first-child { border-top: none; }
209
- .dsh-mios-device-name { flex: 1; min-width: 0; overflow-wrap: anywhere; white-space: normal;
210
- line-height: 1.35; color: var(--fg); }
211
- .dsh-mios-device-online { color: #3fb27f; flex: none; }
212
- .dsh-mios-device-offline { color: var(--muted); flex: none; }
213
- .dsh-mios-device-kick { margin-left: auto; background: none; border: 1px solid rgba(217,79,61,.4); border-radius: 4px;
214
- color: #c97a6d; cursor: pointer; font-family: inherit; font-size: 9px; font-weight: 500;
215
- line-height: 1.3; padding: 1px 5px; flex: none; }
216
- .dsh-mios-device-kick:hover { color: #d94f3d; border-color: rgba(217,79,61,.7); }
217
- .dsh-mios-devices-empty { padding: 6px 8px; font-size: 11px; color: var(--muted); }
218
- .dsh-mios-panel .pairbtn { width: 100%; margin-top: 10px; padding: 8px 0; border-radius: 9px;
219
- border: 1px solid rgba(63,178,127,.45); background: rgba(63,178,127,.14); color: #3fb27f;
220
- font: 600 13px/1.4 inherit-font, sans-serif; cursor: pointer; }
221
- .dsh-mios-panel .pairbtn:disabled { opacity: .5; cursor: default; }
222
- .dsh-mios-banner { border: 1px solid var(--border); border-radius: 10px; padding: 10px 10px 11px; margin-top: 10px; }
223
- .dsh-mios-banner h4 { margin: 0; font-size: 12px; font-weight: 600; color: var(--fg);
224
- display: flex; justify-content: space-between; align-items: baseline; gap: 8px; }
225
- .dsh-mios-banner .banner-state { font-size: 11px; font-weight: 400; color: var(--muted);
226
- max-width: 190px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
227
- .dsh-mios-banner .banner-guide { margin-top: 4px; font-size: 11px; color: var(--muted); line-height: 1.5; }
228
- .dsh-mios-banner .banner-addr { margin-top: 4px; font-size: 11px; color: var(--muted);
229
- font-family: ui-monospace, "SF Mono", Menlo, monospace; word-break: break-all; line-height: 1.5; }
230
- .dsh-mios-banner .pairbtn { margin-top: 8px; }
231
- .dsh-mios-banner .tunnelbtn { border-color: var(--muted-border); background: var(--muted-bg); color: var(--muted); }
232
- .dsh-mios-banner .tunnelbtn:hover:not(:disabled) { border-color: var(--fg-soft); color: var(--fg); background: var(--muted-bg-hover); }
233
- .dsh-mios-banner .tunnelbtn:disabled { opacity: .5; cursor: default; }
234
- .dsh-mios-banner .stopbtn { margin-top: 6px; padding: 5px 0; font-weight: 500;
235
- border-color: rgba(217,79,61,.4); background: none; color: #c97a6d; }
236
- .dsh-mios-banner .stopbtn:hover:not(:disabled) { border-color: rgba(217,79,61,.7); color: #d94f3d; }
237
- .dsh-mios-panel .code { margin-top: 10px; text-align: center; font-size: 30px; letter-spacing: 8px;
238
- font-weight: 700; color: var(--fg); font-variant-numeric: tabular-nums; }
239
- .dsh-mios-qr { margin-top: 10px; padding: 10px; background: #fff; border-radius: 10px;
240
- display: flex; justify-content: center; }
241
- .dsh-mios-qr svg { width: 180px; height: 180px; display: block; }
242
- .dsh-mios-panel .err { margin-top: 10px; font-size: 12px; color: #d94f3d; text-align: center; }
243
- .dsh-mios-panel footer { margin-top: 10px; font-size: 11px; color: var(--muted); text-align: center; }
244
- .dsh-mios-close { margin-left: auto; background: none; border: none; color: var(--muted);
245
- font-size: 16px; cursor: pointer; padding: 2px 6px; }
246
- `;
247
- document.head.append(style);
248
- }
249
-
250
- // ── 面板(原生 DOM;宿主无 react-dom) ───────────────────────
251
- // 双 banner 布局:上面「局域网连接」,下面「远程通道连接」。
252
- // 远程 banner 是合并后的单一主按钮:没开过→开通;开过没跑→开启并出码;
253
- // 跑着→直接出码。停止远程是旁边的小按钮,只在该停的时候出现。
254
- const PANEL_TITLE = 'DSH iOS移动伴侣';
255
- const BANNER_LABEL = '📱 iOS移动伴侣';
256
- // 插件更新检查:读 npm registry 的 latest(与「添加插件」安装源同源)。
257
- // npm 官方源带 CORS *,桌面端 webview 可直接 fetch;npmmirror 作国内备用。
258
- const PLUGIN_NAME = 'dsh-mobile-ios';
259
- const PLUGIN_REGISTRIES = [
260
- 'https://registry.npmjs.org',
261
- 'https://registry.npmmirror.com',
262
- ];
263
- const stripUrl = (u) => String(u || '').replace(/^https?:\/\//, '');
264
- const stripLocal = (h) => String(h || '').replace(/\.local$/i, '');
265
-
266
- // 宿主插件管理服务(remote.pluginManager)。注入模块经 apply 拿到;
267
- // 非 Desktop 或老宿主拿不到时保持 null,更新入口降级为「复制包名」手动安装。
268
- let pluginManager = null;
269
- let updateInFlight = false; // 一步更新的并发锁:更新中禁止再次触发
270
- let panelEl = null;
271
- let tunnelBusy = false;
272
- const bannerBusy = { lan: false, remote: false };
273
- let outsideCloser = null;
274
- let devicesExpanded = false;
275
- let kickingDeviceId = null;
276
- // 面板打开期间的摘要刷新:probe() 只更新数据不重绘,正是「扫码后要关掉重开才更新」的根因。
277
- let summaryPollTimer = null;
278
- let summaryFetching = false;
279
- let lastDeviceSignature = null;
280
-
281
- /** 探测宿主主题:显式标记(class/data-theme)→ body 亮度启发 → 系统偏好。
282
- * Electron 宿主切换主题只改页面 class,matchMedia 不一定跟着变,所以三级都查。 */
283
- function detectHostTheme() {
284
- const root = document.documentElement;
285
- const body = document.body;
286
- const marked = `${root.className} ${body?.className || ''} ${root.getAttribute('data-theme') || ''} ${body?.getAttribute('data-theme') || ''} ${root.getAttribute('data-color-mode') || ''}`.toLowerCase();
287
- if (/\bdark\b/.test(marked)) return 'dark';
288
- if (/\blight\b/.test(marked)) return 'light';
289
- // 亮度启发:宿主页面底色亮就是浅色主题(面板挂在这个页面上,跟它一致最直观)。
290
- // 全黑或全透明底色不可判,落到系统偏好。
291
- const bgc = body ? getComputedStyle(body).backgroundColor
292
- : getComputedStyle(root).backgroundColor;
293
- const m = bgc.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
294
- if (m && (+m[1] + +m[2] + +m[3]) > 0) {
295
- return (0.2126 * +m[1] + 0.7152 * +m[2] + 0.0722 * +m[3]) > 140 ? 'light' : 'dark';
296
- }
297
- return window.matchMedia?.('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
298
- }
299
-
300
- /** 面板主题实时跟随宿主:每次渲染都重判(用户可能中途切主题)。 */
301
- function applyPanelTheme() {
302
- if (!panelEl) return;
303
- panelEl.classList.toggle('light', detectHostTheme() === 'light');
304
- }
305
-
306
- function removePanel() {
307
- panelEl?.remove();
308
- panelEl = null;
309
- closeUpdateModal();
310
- if (summaryPollTimer) {
311
- clearInterval(summaryPollTimer);
312
- summaryPollTimer = null;
313
- }
314
- lastDeviceSignature = null;
315
- if (outsideCloser) {
316
- document.removeEventListener('pointerdown', outsideCloser);
317
- outsideCloser = null;
318
- }
319
- }
320
-
321
- function row(label, valueId) {
322
- const div = document.createElement('div');
323
- div.className = 'row';
324
- const l = document.createElement('span');
325
- l.textContent = label;
326
- const v = document.createElement('b');
327
- v.id = valueId;
328
- v.textContent = '—';
329
- div.append(l, v);
330
- return div;
331
- }
332
-
333
- /** 「同时在线设备」行:标签可点开展开在线设备清单,右侧显示 在线/上限。 */
334
- function deviceRows() {
335
- const wrap = document.createElement('div');
336
- const head = document.createElement('div');
337
- head.className = 'row';
338
- const toggle = document.createElement('button');
339
- toggle.className = 'dsh-mios-device-toggle';
340
- toggle.id = 'dsh-mios-device-toggle';
341
- toggle.type = 'button';
342
- toggle.textContent = '▸';
343
- toggle.setAttribute('aria-label', '展开或收起当前在线设备清单');
344
- const label = document.createElement('span');
345
- label.textContent = '同时在线设备(最多5台)';
346
- const left = document.createElement('span');
347
- left.append(toggle, label);
348
- const value = document.createElement('b');
349
- value.id = 'dsh-mios-devices';
350
- value.textContent = '—';
351
- head.append(left, value);
352
- toggle.addEventListener('click', () => {
353
- devicesExpanded = !devicesExpanded;
354
- renderDeviceList();
355
- });
356
- const list = document.createElement('div');
357
- list.className = 'dsh-mios-devices';
358
- list.id = 'dsh-mios-devices-list';
359
- list.hidden = true;
360
- wrap.append(head, list);
361
- return wrap;
362
- }
363
-
364
- /** 在线设备清单:默认折叠;只列当前在线设备(同时在线上限 5 台),下线逐台二次确认。 */
365
- function renderDeviceList() {
366
- const box = panelEl?.querySelector('#dsh-mios-devices-list');
367
- if (!box) return;
368
- box.hidden = !devicesExpanded;
369
- const toggle = panelEl.querySelector('#dsh-mios-device-toggle');
370
- if (toggle) toggle.textContent = devicesExpanded ? '▾' : '▸';
371
- box.replaceChildren();
372
- if (!summary?.ok) return;
373
- // 后端已限制活跃设备上限;这里再按在线态筛选并截到 5,保证面板只展示真实并发连接。
374
- const devices = (summary.pairing?.devices || []).filter((d) => d.online).slice(0, 5);
375
- if (!devices.length) {
376
- const empty = document.createElement('div');
377
- empty.className = 'dsh-mios-devices-empty';
378
- empty.textContent = '当前没有在线设备';
379
- box.append(empty);
380
- return;
381
- }
382
- for (const device of devices) {
383
- const line = document.createElement('div');
384
- line.className = 'dsh-mios-device-row';
385
- const name = document.createElement('span');
386
- name.className = 'dsh-mios-device-name';
387
- name.textContent = device.deviceName || '未命名设备';
388
- name.title = name.textContent;
389
- const state = document.createElement('span');
390
- state.className = device.online ? 'dsh-mios-device-online' : 'dsh-mios-device-offline';
391
- state.textContent = device.online ? '在线' : '离线';
392
- const kick = document.createElement('button');
393
- kick.className = 'dsh-mios-device-kick';
394
- kick.textContent = kickingDeviceId === device.deviceId ? '处理中' : '下线';
395
- kick.disabled = kickingDeviceId !== null;
396
- kick.title = `将 ${name.textContent} 从这台电脑移除`;
397
- kick.addEventListener('click', async () => {
398
- // 二次确认:下线会让那台手机立刻失去读任务的能力,不能误点。
399
- if (!window.confirm(`确定让「${name.textContent}」下线?该设备需要重新扫码才能再次连接。`)) return;
400
- kickingDeviceId = device.deviceId;
401
- renderDeviceList();
402
- try {
403
- await revokeDevice(device.deviceId);
404
- await probe();
405
- } catch (err) {
406
- window.alert('下线失败:' + (err?.body?.error?.message || err.message));
407
- } finally {
408
- kickingDeviceId = null;
409
- renderSummary();
410
- }
411
- });
412
- line.append(name, state, kick);
413
- box.append(line);
414
- }
415
- }
416
-
417
- function renderSummary() {
418
- if (!panelEl) return;
419
- applyPanelTheme();
420
- const dot = panelEl.querySelector('#dsh-mios-panel-dot');
421
- const ok = !!(summary && summary.ok);
422
- dot.className = 'dsh-mios-dot ' + (ok ? 'ok' : 'down');
423
- const set = (id, text) => { const el = panelEl.querySelector('#' + id); if (el) el.textContent = text; };
424
- set('dsh-mios-adapter', ok ? `v${summary.version}` : '—');
425
- set('dsh-mios-host', ok ? (stripLocal(summary.hostName) || '未上报') : '—');
426
- if (ok) {
427
- const max = summary.pairing?.maxDevices ?? 5;
428
- const online = summary.pairing?.onlineDevices ?? 0;
429
- set('dsh-mios-devices', `${online}/${max} 台`);
430
- } else {
431
- set('dsh-mios-devices', '—');
432
- }
433
- // 只有设备名/在线态/顺序变化才重建列表:1.2s 刷新不能让 hover 提示和下线按钮闪烁。
434
- const devices = ok ? (summary.pairing?.devices || []) : [];
435
- const signature = devices
436
- .map((d) => `${d.deviceId}\u0000${d.deviceName || ''}\u0000${d.online ? 1 : 0}`)
437
- .join('\u0001');
438
- if (signature !== lastDeviceSignature) {
439
- lastDeviceSignature = signature;
440
- renderDeviceList();
441
- }
442
-
443
- // ── 局域网 banner ──
444
- const lan = ok ? summary.lan : null;
445
- const lanState = panelEl.querySelector('#dsh-mios-lan-state');
446
- if (lanState) lanState.textContent = ok ? (lan ? `电脑地址 ${lan}` : '未获取到局域网地址') : '网关不可达';
447
- const lanCodeBtn = panelEl.querySelector('#dsh-mios-lan-code');
448
- if (lanCodeBtn) {
449
- lanCodeBtn.disabled = !ok || !lan || bannerBusy.lan;
450
- lanCodeBtn.title = ok && lan ? '' : '网关不可达或没有局域网地址';
451
- }
452
-
453
- // ── 远程通道 banner ──
454
- // 四种事实分开说:运行中 / 已开通但没开 / 根本没开通 / 域名没生效。
455
- // 「域名未生效」必须单列:地址开出来了但公网解析不到,显示「已开通」会误导人去扫码。
456
- const tunnel = ok ? summary.tunnel : null;
457
- const dnsBroken = tunnel && tunnel.dnsOk === false;
458
- const running = !!(tunnel && tunnel.state === 'running' && !dnsBroken);
459
- const remoteState = panelEl.querySelector('#dsh-mios-remote-state');
460
- if (remoteState) {
461
- remoteState.textContent = !tunnel
462
- ? '—'
463
- : dnsBroken
464
- ? '解析异常 · 未开启'
465
- : running
466
- ? '已开启'
467
- : tunnel.provisioned && tunnel.fixedUrl
468
- ? '已开通 · 未开启'
469
- : tunnel.mode === 'named' ? '未开通固定地址' : tunnel.state;
470
- }
471
- // 固定地址独占一行完整显示,不再和状态词挤在一起被省略号截断
472
- const remoteAddr = panelEl.querySelector('#dsh-mios-remote-addr');
473
- if (remoteAddr) {
474
- const addr = tunnel && (tunnel.fixedUrl || tunnel.url);
475
- remoteAddr.textContent = tunnel && tunnel.provisioned ? stripUrl(addr) : '—';
476
- // 默认色交给 CSS 变量(跟随主题);只有解析异常时才覆盖成红色
477
- remoteAddr.style.color = dnsBroken ? '#d94f3d' : '';
478
- }
479
- const mainBtn = panelEl.querySelector('#dsh-mios-remote-main');
480
- if (mainBtn) {
481
- // 出码态走绿色主按钮;开启态走灰色次按钮(悬浮变白),视觉上分清两件事
482
- mainBtn.className = 'pairbtn' + (running || dnsBroken ? '' : ' tunnelbtn');
483
- mainBtn.style.display = tunnel && tunnel.state !== 'disabled' ? '' : 'none';
484
- mainBtn.disabled = tunnelBusy || bannerBusy.remote || dnsBroken;
485
- mainBtn.textContent = dnsBroken
486
- ? '域名解析异常,暂不可开启'
487
- : running
488
- ? (bannerBusy.remote ? '生成中…' : '生成配对码(远程)')
489
- : tunnel.mode === 'named'
490
- ? (tunnel.provisioned ? '开启远程并生成配对码' : '开启远程(分配固定地址)')
491
- : '启动隧道(外网连接)';
492
- }
493
- const stopBtn = panelEl.querySelector('#dsh-mios-remote-stop');
494
- if (stopBtn) {
495
- // 停止按钮只在该停的时候出现:没开过/没在跑都没有「停」可言
496
- stopBtn.style.display = running && !tunnelBusy ? '' : 'none';
497
- stopBtn.disabled = tunnelBusy;
498
- }
499
- // 远程码跟着可用性走:不是 running 就收起(与「停止即收码」同一语义,
500
- // 兜住任何没经过停止按钮的路径,比如进程意外退出)。
501
- if (!running && !bannerBusy.remote) {
502
- panelEl.querySelector('#dsh-mios-remote-main')?.closest('.dsh-mios-banner')
503
- ?.querySelectorAll('.dsh-mios-code-slot, .err').forEach((e) => e.remove());
504
- }
505
-
506
- // 提示行只承载告警与错误:没有告警就整行隐藏,不再放固定说明文字
507
- const hint = panelEl.querySelector('#dsh-mios-hint');
508
- if (hint) {
509
- const warn = ok ? summary.tunnel?.warning : null;
510
- hint.textContent = warn ? `⚠️ ${warn}` : '';
511
- hint.style.color = '#e0a03c';
512
- hint.style.display = warn ? '' : 'none';
513
- }
514
- }
515
-
516
- /** 双 banner 里的一块:标题 + 状态行 + 指引一句 + 内容区 */
517
- function bannerBox(title, stateId, guideText) {
518
- const box = document.createElement('div');
519
- box.className = 'dsh-mios-banner';
520
- const head = document.createElement('h4');
521
- head.textContent = title;
522
- const state = document.createElement('span');
523
- state.className = 'banner-state';
524
- state.id = stateId;
525
- state.textContent = '—';
526
- head.append(state);
527
- const guide = document.createElement('div');
528
- guide.className = 'banner-guide';
529
- guide.textContent = guideText;
530
- box.append(head, guide);
531
- return box;
532
- }
533
-
534
- /** 出码结果挂进所属 banner:QR + 码 + 地址说明(同一 banner 只保留最新一码) */
535
- function mountCode(banner, issued) {
536
- banner.querySelectorAll('.dsh-mios-code-slot').forEach((e) => e.remove());
537
- const slot = document.createElement('div');
538
- slot.className = 'dsh-mios-code-slot';
539
- if (issued.qrSvg) {
540
- const qr = document.createElement('div');
541
- qr.className = 'dsh-mios-qr';
542
- qr.innerHTML = issued.qrSvg;
543
- slot.append(qr);
544
- }
545
- const code = document.createElement('div');
546
- code.className = 'code';
547
- code.textContent = issued.code;
548
- const addr = document.createElement('div');
549
- addr.style.cssText = 'margin-top:6px;text-align:center;font-size:12px;color:#3fb27f;';
550
- addr.textContent = issued.route === 'tunnel'
551
- ? `扫码连接 · 公网固定地址 ${stripUrl(issued.address)}`
552
- : issued.address
553
- ? `扫码连接 · 局域网 ${issued.address}`
554
- : '手机填电脑局域网地址 + 此码';
555
- slot.append(code, addr);
556
- banner.append(slot);
557
- }
558
-
559
- /** banner 内的出码按钮统一行为:busy → 出码 → 失败在 banner 内显错 */
560
- function bindCodeBtn(btn, banner, route) {
561
- btn.addEventListener('click', async () => {
562
- if (bannerBusy[route]) return;
563
- bannerBusy[route] = true;
564
- btn.disabled = true;
565
- btn.textContent = '生成中…';
566
- try {
567
- mountCode(banner, await issuePairingCode(route));
568
- } catch (err) {
569
- banner.querySelectorAll('.dsh-mios-code-slot').forEach((e) => e.remove());
570
- const errEl = document.createElement('div');
571
- errEl.className = 'err';
572
- errEl.textContent = '生成失败:' + (err?.body?.error?.message || err.message);
573
- banner.append(errEl);
574
- } finally {
575
- bannerBusy[route] = false;
576
- btn.textContent = '重新生成配对码';
577
- renderSummary();
578
- }
579
- });
580
- }
581
-
582
- function showPanel() {
583
- if (panelEl) return;
584
- // 打开期间持续轻量刷新:扫码上线、改名、下线都能立刻反映,无需关掉重开。
585
- if (summaryPollTimer) clearInterval(summaryPollTimer);
586
- summaryPollTimer = setInterval(refreshSummary, 1200);
587
- installStyle();
588
- panelEl = document.createElement('div');
589
- panelEl.className = 'dsh-mios-panel';
590
-
591
- const header = document.createElement('h3');
592
- const dot = document.createElement('span');
593
- dot.id = 'dsh-mios-panel-dot';
594
- dot.className = 'dsh-mios-dot down';
595
- const title = document.createElement('span');
596
- title.textContent = PANEL_TITLE;
597
- // 插件更新:放在关闭按钮左边,点击弹出更新对话框(版本对比 + 更新与否由用户选)
598
- const updBtn = document.createElement('button');
599
- updBtn.className = 'dsh-mios-upd';
600
- updBtn.textContent = '插件更新';
601
- updBtn.addEventListener('click', () => {
602
- // 点击务必先有可见反馈再联网,避免「无反应」错觉(缓存旧模块时旧逻辑写已移除的内联元素)。
603
- try { checkPluginUpdate(); } catch (e) {
604
- console.error('[dsh-mobile-ios] checkPluginUpdate failed:', e);
605
- showUpdateModal({ title: '插件更新', lines: [], note: `打开更新检查失败:${e?.message || e}`, actions: [{ label: '知道了', primary: true, onClick: closeUpdateModal }] });
606
- }
607
- });
608
- const close = document.createElement('button');
609
- close.className = 'dsh-mios-close';
610
- close.textContent = '✕';
611
- close.setAttribute('aria-label', '关闭面板');
612
- close.addEventListener('click', removePanel);
613
- header.append(dot, title, updBtn, close);
614
-
615
- const body = document.createElement('div');
616
- body.append(
617
- row('插件版本', 'dsh-mios-adapter'),
618
- row('电脑名称', 'dsh-mios-host'),
619
- deviceRows(),
620
- );
621
-
622
- // ── banner 1:局域网连接(在家 · 直连 · 始终可用) ──
623
- const lanBanner = bannerBox('局域网连接', 'dsh-mios-lan-state', '手机与电脑连同一个 Wi-Fi,直连不走外网。适合在家日常用。');
624
- const lanCodeBtn = document.createElement('button');
625
- lanCodeBtn.className = 'pairbtn';
626
- lanCodeBtn.id = 'dsh-mios-lan-code';
627
- lanCodeBtn.textContent = '生成配对码';
628
- bindCodeBtn(lanCodeBtn, lanBanner, 'lan');
629
- lanBanner.append(lanCodeBtn);
630
-
631
- // ── banner 2:远程通道连接(出门 · 固定域名 · 一个主按钮走完) ──
632
- // 「开启远程」与「生成配对码」合并成一个主按钮:没开过→开通;
633
- // 开过没跑→开启并出码;跑着→直接出码。停止是旁边的小按钮。
634
- const remoteBanner = bannerBox('远程通道连接', 'dsh-mios-remote-state', '出门在外扫码连固定域名,电脑和手机不必在同一网络。');
635
- const remoteAddr = document.createElement('div');
636
- remoteAddr.id = 'dsh-mios-remote-addr';
637
- remoteAddr.className = 'banner-addr';
638
- remoteAddr.textContent = '—';
639
- remoteBanner.append(remoteAddr);
640
- const mainBtn = document.createElement('button');
641
- mainBtn.className = 'pairbtn';
642
- mainBtn.id = 'dsh-mios-remote-main';
643
- mainBtn.textContent = '开启远程并生成配对码';
644
- mainBtn.addEventListener('click', () => remoteMainAction(remoteBanner));
645
- const stopBtn = document.createElement('button');
646
- stopBtn.className = 'pairbtn stopbtn';
647
- stopBtn.id = 'dsh-mios-remote-stop';
648
- stopBtn.textContent = '停止远程';
649
- stopBtn.addEventListener('click', stopRemoteAction);
650
- remoteBanner.append(mainBtn, stopBtn);
651
-
652
- const hint = document.createElement('div');
653
- hint.id = 'dsh-mios-hint';
654
- hint.style.cssText = 'margin-top:8px;font-size:11px;color:#e0a03c;line-height:1.5;';
655
- hint.style.display = 'none';
656
-
657
- const footer = document.createElement('footer');
658
- footer.textContent = 'iPhone/iPad App → 连接 → 扫码(约 2 分钟有效)';
659
-
660
- panelEl.append(header, body, lanBanner, remoteBanner, hint, footer);
661
- document.body.append(panelEl);
662
- applyPanelTheme();
663
- placePanelAboveTrigger();
664
- renderSummary();
665
- probe();
666
-
667
- // 点击面板/触发 banner 以外的任意区域即关闭(✕ 之外的第二条路)
668
- outsideCloser = (ev) => {
669
- if (!panelEl) return;
670
- const t = ev.target;
671
- if (panelEl.contains(t) || (t.closest && t.closest('.dsh-mios-trigger'))) return;
672
- removePanel();
673
- };
674
- document.addEventListener('pointerdown', outsideCloser);
675
- }
676
-
677
- /** 面板底边对齐触发 banner 顶边:不遮挡 banner,屏幕放不下就整体上推并内滚。 */
678
- function placePanelAboveTrigger() {
679
- const trigger = document.querySelector('.dsh-mios-trigger');
680
- if (trigger) {
681
- const rect = trigger.getBoundingClientRect();
682
- panelEl.style.left = `${Math.max(10, Math.round(rect.left))}px`;
683
- panelEl.style.bottom = `${Math.max(10, Math.round(window.innerHeight - rect.top + 8))}px`;
684
- }
685
- panelEl.style.maxHeight = 'min(72vh, 640px)';
686
- panelEl.style.overflowY = 'auto';
687
- }
688
-
689
- /** 更新检查:与「添加插件」同源,读 npm registry 的 latest 比对当前版本。
690
- * 404 = 包未发布(本地开发版);网络失败 = 如实报不可达,二者不混为一谈。 */
691
- /** 更新对话框:显示版本对比,更新与否由用户选;随面板销毁清理。 */
692
- let updateModal = null;
693
- function closeUpdateModal() {
694
- updateModal?.remove();
695
- updateModal = null;
696
- }
697
- function showUpdateModal({ title, banner, lines, note, actions }) {
698
- closeUpdateModal();
699
- const mask = document.createElement('div');
700
- mask.className = 'dsh-mios-modal-mask';
701
- if (detectHostTheme() === 'light') mask.classList.add('light');
702
- const box = document.createElement('div');
703
- box.className = 'dsh-mios-modal';
704
-
705
- const h = document.createElement('h4');
706
- h.textContent = title;
707
- const x = document.createElement('button');
708
- x.className = 'modal-x';
709
- x.textContent = '✕';
710
- x.setAttribute('aria-label', '关闭');
711
- x.addEventListener('click', closeUpdateModal);
712
- h.append(x);
713
- box.append(h);
714
-
715
- // banner:一步更新流程的状态横幅(发现新版 / 更新中 / 成功 / 失败)
716
- if (banner) {
717
- const b = document.createElement('div');
718
- b.className = `modal-banner${banner.tone ? ' ' + banner.tone : ''}`;
719
- b.textContent = banner.text;
720
- box.append(b);
721
- }
722
-
723
- for (const line of lines || []) {
724
- const row = document.createElement('div');
725
- row.className = 'modal-line';
726
- const label = document.createElement('span');
727
- label.textContent = line.label;
728
- const value = document.createElement('b');
729
- value.textContent = line.value;
730
- if (line.highlight) value.className = 'new';
731
- row.append(label, value);
732
- box.append(row);
733
- }
734
- if (note) {
735
- const n = document.createElement('div');
736
- n.className = 'modal-note';
737
- n.textContent = note;
738
- box.append(n);
739
- }
740
-
741
- const bar = document.createElement('div');
742
- bar.className = 'modal-actions';
743
- for (const action of actions || []) {
744
- const btn = document.createElement('button');
745
- btn.textContent = action.label;
746
- if (action.primary) btn.className = 'primary';
747
- btn.addEventListener('click', () => action.onClick?.(btn));
748
- bar.append(btn);
749
- }
750
- box.append(bar);
751
- mask.append(box);
752
- mask.addEventListener('click', (e) => { if (e.target === mask) closeUpdateModal(); });
753
- document.body.append(mask);
754
- updateModal = mask;
755
- }
756
-
757
- /** 复制文本:clipboard API 不可用时回退到 textarea + execCommand。 */
758
- async function copyToClipboard(text) {
759
- try {
760
- if (navigator.clipboard?.writeText) {
761
- await navigator.clipboard.writeText(text);
762
- return true;
763
- }
764
- } catch { /* 落到下面的回退 */ }
765
- try {
766
- const ta = document.createElement('textarea');
767
- ta.value = text;
768
- ta.style.position = 'fixed';
769
- ta.style.opacity = '0';
770
- document.body.append(ta);
771
- ta.select();
772
- const ok = document.execCommand('copy');
773
- ta.remove();
774
- return ok;
775
- } catch {
776
- return false;
777
- }
778
- }
779
-
780
- async function checkPluginUpdate() {
781
- showUpdateModal({ title: '插件更新', lines: [], note: '正在检查更新…', actions: [] });
782
- const current = summary?.version || '未知';
783
- let latest = '';
784
- let sawNotFound = false;
785
- let lastError = null;
786
- for (const base of PLUGIN_REGISTRIES) {
787
- try {
788
- const res = await fetch(`${base}/${PLUGIN_NAME}/latest`, { signal: AbortSignal.timeout(6000) });
789
- if (res.status === 404) { sawNotFound = true; continue; }
790
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
791
- const meta = await res.json();
792
- if (meta?.version) { latest = String(meta.version); break; }
793
- } catch (e) {
794
- lastError = e;
795
- }
796
- }
797
- if (!latest) {
798
- showUpdateModal({
799
- title: '插件更新',
800
- lines: [{ label: '当前版本', value: `v${current}` }],
801
- note: sawNotFound
802
- ? '插件尚未发布到 npm,当前为本地开发版。更新方式:拉取仓库最新代码后重启 DSH 桌面端,插件会随源码热重载。'
803
- : `更新源暂不可达${lastError ? `(${lastError.message})` : ''},无法确认是否有新版本。`,
804
- actions: [{ label: '知道了', primary: true, onClick: closeUpdateModal }],
805
- });
806
- return;
807
- }
808
- if (compareVersions(latest, current) > 0) {
809
- // 一步更新:宿主提供 pluginManager 时直接安装,无需复制包名手动添加。
810
- const canAuto = !!(pluginManager && typeof pluginManager.installBundle === 'function');
811
- const actions = [{ label: '稍后再说', onClick: closeUpdateModal }];
812
- if (canAuto) {
813
- actions.push({
814
- label: `立即更新到 v${latest}`, primary: true,
815
- onClick: () => performUpdate(latest),
816
- });
817
- } else {
818
- // 降级:拿不到宿主安装服务(老宿主 / 非 Desktop),保留复制包名手动安装。
819
- actions.push({
820
- label: `复制 ${PLUGIN_NAME}@${latest}`, primary: true,
821
- onClick: async (btn) => {
822
- const ok = await copyToClipboard(`${PLUGIN_NAME}@${latest}`);
823
- btn.textContent = ok ? '已复制,去插件页粘贴安装' : '复制失败,请手动复制包名';
824
- },
825
- });
826
- }
827
- showUpdateModal({
828
- title: '新版本更新',
829
- banner: { text: `⬆️ 发现新版本 v${latest},可一键更新`, tone: 'info' },
830
- lines: [
831
- { label: '当前版本', value: `v${current}` },
832
- { label: '最新版本', value: `v${latest}`, highlight: true },
833
- ],
834
- note: canAuto
835
- ? '点击「立即更新」将由 DSH 安装器一步完成,更新中请勿关闭窗口。是否更新由你决定。'
836
- : '当前宿主未提供一步更新能力,请复制包名到 DSH「插件 → 添加插件」粘贴安装。',
837
- actions,
838
- });
839
- } else {
840
- showUpdateModal({
841
- title: '已是最新版本',
842
- lines: [
843
- { label: '当前版本', value: `v${current}` },
844
- { label: 'npm 最新', value: `v${latest}` },
845
- ],
846
- note: '当前版本已是最新,无需更新。',
847
- actions: [{ label: '知道了', primary: true, onClick: closeUpdateModal }],
848
- });
849
- }
850
- }
851
-
852
- /** 一步更新:经宿主 pluginManager.installBundle 安装 npm spec,
853
- * 状态机覆盖 更新中 / 成功 / 失败 / 超时对账 / 重复点击。 */
854
- let UPDATE_TIMEOUT_MS = 180000; // pnpm 安装 + 可能的重启,给足 3 分钟
855
- function unwrapRemote(result) {
856
- if (result && typeof result === 'object' && Object.hasOwn(result, 'ok')) {
857
- if (!result.ok) throw new Error(result.error?.code || result.error?.message || '宿主返回失败');
858
- return result.value;
859
- }
860
- return result;
861
- }
862
- function withTimeout(promise, ms, label) {
863
- return new Promise((resolve, reject) => {
864
- let settled = false;
865
- const timer = setTimeout(() => {
866
- if (settled) return;
867
- settled = true;
868
- reject(new Error(`${label}超时(${Math.round(ms / 1000)} 秒)`));
869
- }, ms);
870
- Promise.resolve(promise).then(
871
- (v) => { if (!settled) { settled = true; clearTimeout(timer); resolve(v); } },
872
- (e) => { if (!settled) { settled = true; clearTimeout(timer); reject(e); } },
873
- );
874
- });
875
- }
876
-
877
- // ── 跨 HMR 重载的更新状态持久化 ─────────────────────────────
878
- // 更新「自己」会触发宿主卸载本模块并加载新版,当前 JS 上下文连同弹窗一起销毁。
879
- // 因此发起更新前把状态写入 localStorage,新模块 apply 时读取并给出结果反馈,
880
- // 避免出现「点一下弹窗消失、什么都没发生」的体验。
881
- const UPDATE_STATE_KEY = 'dsh-mios-update-state';
882
- function readUpdateState() {
883
- try {
884
- const raw = globalThis.localStorage?.getItem(UPDATE_STATE_KEY);
885
- return raw ? JSON.parse(raw) : null;
886
- } catch { return null; }
887
- }
888
- function writeUpdateState(state) {
889
- try { globalThis.localStorage?.setItem(UPDATE_STATE_KEY, JSON.stringify(state)); }
890
- catch { /* 存储不可用时静默,功能降级但不崩 */ }
891
- }
892
- function clearUpdateState() {
893
- try { globalThis.localStorage?.removeItem(UPDATE_STATE_KEY); }
894
- catch { /* 同上 */ }
895
- }
896
- /** apply 时调用:若上次更新尚未收尾,依据当前版本推断结果并弹窗告知。 */
897
- function restorePendingUpdate() {
898
- const st = readUpdateState();
899
- if (!st || st.status !== 'updating' || !st.target) return;
900
- const current = String(summary?.version || '').trim();
901
- const age = Date.now() - (st.at || 0);
902
- if (current && compareVersions(current, st.target) >= 0) {
903
- clearUpdateState();
904
- // 延迟到面板初次渲染后再弹,避免被 apply 后续的初始化覆盖
905
- setTimeout(() => showUpdateModal({
906
- title: '更新完成',
907
- banner: { text: `✅ 已更新到 v${st.target}`, tone: 'success' },
908
- lines: [{ label: '当前版本', value: `v${current}` }],
909
- note: '插件已更新并重新加载完成。',
910
- actions: [{ label: '知道了', primary: true, onClick: closeUpdateModal }],
911
- }), 600);
912
- } else if (age > 5 * 60 * 1000) {
913
- clearUpdateState();
914
- setTimeout(() => showUpdateModal({
915
- title: '更新结果未知',
916
- banner: { text: '⚠️ 上一步更新未能确认', tone: 'warn' },
917
- lines: [{ label: '目标版本', value: `v${st.target}` }, { label: '当前版本', value: current ? `v${current}` : '未知' }],
918
- note: '更新过程被中断或耗时过长。请到「插件」页确认当前版本,必要时手动更新。',
919
- actions: [{ label: '知道了', primary: true, onClick: closeUpdateModal }],
920
- }), 600);
921
- }
922
- // 未超时且版本未变:保持 updating 状态,等下次 apply(轮询重载)再判断
923
- }
924
- async function performUpdate(latest) {
925
- // 重复点击保护:更新中直接忽略再次触发
926
- if (updateInFlight) return;
927
- if (!pluginManager || typeof pluginManager.installBundle !== 'function') {
928
- showUpdateModal({
929
- title: '更新不可用',
930
- banner: { text: '⚠️ 宿主未提供一步更新能力', tone: 'warn' },
931
- lines: [],
932
- note: '请复制包名,到 DSH「插件 → 添加插件」粘贴安装。',
933
- actions: [
934
- { label: '知道了', onClick: closeUpdateModal },
935
- { label: `复制 ${PLUGIN_NAME}@${latest}`, primary: true, onClick: async (btn) => {
936
- const ok = await copyToClipboard(`${PLUGIN_NAME}@${latest}`);
937
- btn.textContent = ok ? '已复制' : '复制失败';
938
- } },
939
- ],
940
- });
941
- return;
942
- }
943
- updateInFlight = true;
944
- const current = summary?.version || '未知';
945
- const spec = `${PLUGIN_NAME}@${latest}`;
946
- // 先持久化「更新中」,确保 HMR 卸载本模块后新实例能恢复出结果反馈。
947
- writeUpdateState({ status: 'updating', target: String(latest), at: Date.now() });
948
- // 状态:更新中。无取消/关闭动作外的操作按钮,防重复点击。
949
- showUpdateModal({
950
- title: '正在更新',
951
- banner: { text: `⏳ 正在更新到 v${latest},请稍候`, tone: 'info' },
952
- lines: [
953
- { label: '当前版本', value: `v${current}` },
954
- { label: '目标版本', value: `v${latest}`, highlight: true },
955
- ],
956
- note: '正在通过 DSH 安装器更新,可能需要 1–3 分钟。请勿重复点击或关闭窗口。',
957
- actions: [],
958
- });
959
- let requestId;
960
- try {
961
- requestId = globalThis.crypto?.randomUUID?.();
962
- if (typeof requestId !== 'string') throw new Error('无法生成更新请求 ID');
963
- let result;
964
- try {
965
- result = await withTimeout(
966
- pluginManager.installBundle(spec, { enabled: true, requestId }),
967
- UPDATE_TIMEOUT_MS, '安装',
968
- );
969
- } catch (err) {
970
- // 超时/结果未知:用 requestId 对账,绝不重复提交安装
971
- if (typeof pluginManager.waitForInstall === 'function') {
972
- const recovered = await withTimeout(pluginManager.waitForInstall(requestId), 60000, '结果对账');
973
- if (!recovered) throw err;
974
- result = recovered;
975
- } else throw err;
976
- }
977
- const value = unwrapRemote(result);
978
- const restart = !!(value && (value.restartRequired || value.restart));
979
- clearUpdateState(); // 安装器已返回结果,交由本弹窗反馈,无需跨重载恢复
980
- // 状态:成功
981
- showUpdateModal({
982
- title: '更新完成',
983
- banner: { text: `✅ 已安装 v${latest}`, tone: 'success' },
984
- lines: [
985
- { label: '目标版本', value: `v${latest}` },
986
- ],
987
- note: restart
988
- ? '插件已更新,重启 DSH 桌面端后生效。'
989
- : '插件已更新。若面板未刷新,重开面板或重启 DSH 即可。',
990
- actions: [{ label: '知道了', primary: true, onClick: closeUpdateModal }],
991
- });
992
- } catch (err) {
993
- // 状态:失败(保留重试入口;重试会重新走一遍锁与状态机)
994
- clearUpdateState();
995
- showUpdateModal({
996
- title: '更新失败',
997
- banner: { text: '❌ 更新未成功', tone: 'error' },
998
- lines: [{ label: '目标版本', value: `v${latest}` }],
999
- note: `安装失败:${err?.message || String(err)}。可重试,或复制包名到「插件 → 添加插件」手动安装。`,
1000
- actions: [
1001
- { label: '关闭', onClick: closeUpdateModal },
1002
- { label: '重试更新', primary: true, onClick: () => performUpdate(latest) },
1003
- ],
1004
- });
1005
- } finally {
1006
- updateInFlight = false;
1007
- }
1008
- }
1009
-
1010
- function compareVersions(a, b) {
1011
- const parse = (s) => String(s || '').replace(/^v/i, '').split('-')[0].split('.').map((n) => parseInt(n, 10) || 0);
1012
- const [pa, pb] = [parse(a), parse(b)];
1013
- for (let i = 0; i < 3; i += 1) {
1014
- if ((pa[i] || 0) !== (pb[i] || 0)) return (pa[i] || 0) - (pb[i] || 0);
1015
- }
1016
- return 0;
1017
- }
1018
-
1019
- /** 等 summary 反映出「远程已可用」:服务端 start 会等到注册成功才返回,
1020
- * 但客户端超时/轮询窗口内可能还没看到,这里统一补轮询兜底。 */
1021
- async function waitForTunnelUp(attempts = 8, delayMs = 1500) {
1022
- for (let i = 0; i < attempts; i += 1) {
1023
- await probe();
1024
- renderSummary();
1025
- const t = summary?.tunnel;
1026
- if (t && t.state === 'running' && t.dnsOk !== false) return true;
1027
- if (i < attempts - 1) await new Promise((resolve) => { setTimeout(resolve, delayMs); });
1028
- }
1029
- return false;
1030
- }
1031
-
1032
- /** 远程主按钮:一条动作链走完「确保在跑 → 出码」。一次点击出码,绝不让人点两下。 */
1033
- async function remoteMainAction(banner) {
1034
- if (tunnelBusy || bannerBusy.remote) return;
1035
- const mainBtn = panelEl?.querySelector('#dsh-mios-remote-main');
1036
- const running = summary?.tunnel?.state === 'running' && summary?.tunnel?.dnsOk !== false;
1037
- try {
1038
- if (!running) {
1039
- tunnelBusy = true;
1040
- if (mainBtn) mainBtn.textContent = '开启中…';
1041
- let startErr = null;
1042
- try {
1043
- await tunnelAction('start');
1044
- } catch (err) {
1045
- // 客户端超时 ≠ 服务端失败:cloudflared 可能还在注册路上。
1046
- // 不直接报错收场,继续轮询等它真的起来(或确认起不来)。
1047
- startErr = err;
1048
- }
1049
- const up = await waitForTunnelUp();
1050
- if (!up) {
1051
- // 真没起来才报错;错误信息优先用服务端带回来的
1052
- const t = summary?.tunnel;
1053
- const msg = startErr?.body?.error?.message
1054
- || (t?.dnsOk === false ? '固定域名尚未在公网生效,请稍后再试' : null)
1055
- || startErr?.message || '远程通道未能开启';
1056
- throw Object.assign(new Error(msg), { body: startErr?.body });
1057
- }
1058
- }
1059
- bannerBusy.remote = true;
1060
- if (mainBtn) mainBtn.textContent = '生成中…';
1061
- mountCode(banner, await issuePairingCode('tunnel'));
1062
- } catch (err) {
1063
- const hint = panelEl?.querySelector('#dsh-mios-hint');
1064
- if (hint) {
1065
- hint.textContent = `⚠️ ${err?.body?.error?.message || err.message}`;
1066
- hint.style.display = '';
1067
- hint.style.color = '#d94f3d';
1068
- }
1069
- } finally {
1070
- tunnelBusy = false;
1071
- bannerBusy.remote = false;
1072
- renderSummary();
1073
- }
1074
- }
1075
-
1076
- async function stopRemoteAction() {
1077
- if (tunnelBusy) return;
1078
- tunnelBusy = true;
1079
- const stopBtn = panelEl?.querySelector('#dsh-mios-remote-stop');
1080
- if (stopBtn) stopBtn.textContent = '停止中…';
1081
- try {
1082
- await tunnelAction('stop');
1083
- } catch (err) {
1084
- const hint = panelEl?.querySelector('#dsh-mios-hint');
1085
- if (hint) {
1086
- hint.textContent = `⚠️ ${err?.body?.error?.message || err.message}`;
1087
- hint.style.display = '';
1088
- hint.style.color = '#d94f3d';
1089
- }
1090
- }
1091
- // 停止即收码:远程关了,码还挂在屏幕上只会误导人去扫
1092
- panelEl?.querySelectorAll('#dsh-mios-remote-main')
1093
- .forEach((btn) => btn.closest('.dsh-mios-banner')?.querySelectorAll('.dsh-mios-code-slot, .err')
1094
- .forEach((e) => e.remove()));
1095
- await probe();
1096
- renderSummary();
1097
- tunnelBusy = false;
1098
- }
1099
-
1100
- function togglePanel() {
1101
- if (panelEl) removePanel();
1102
- else showPanel();
1103
- }
1104
-
1105
- // ── banner(slot 渲染,React 元素) ──────────────────────────
1106
- // 注意:slot 渲染回调不是 React 组件(宿主按回调取元素),不能用 hooks;
1107
- // 状态点读模块级 summary,新鲜度由 apply 里的轮询保证,
1108
- // 宿主重渲侧栏时自然取到最新值。面板打开时另有主动 probe()。
1109
-
1110
- const STATUS_OK = { stroke: '#3fb27f', fill: 'rgba(63,178,127,.18)' };
1111
- const STATUS_DOWN = { stroke: '#d94f3d', fill: 'rgba(217,79,61,.18)' };
1112
-
1113
- function PhoneIcon() {
1114
- return react.createElement('svg', {
1115
- 'aria-hidden': true, focusable: false, width: 16, height: 16,
1116
- viewBox: '0 0 16 16', fill: 'none', stroke: 'currentColor',
1117
- strokeWidth: 1.5, strokeLinecap: 'round', strokeLinejoin: 'round',
1118
- },
1119
- react.createElement('rect', { x: 4, y: 1, width: 8, height: 14, rx: 2 }),
1120
- react.createElement('path', { d: 'M7 12h2' }));
1121
- }
1122
-
1123
- function apply(ctx) {
1124
- installStyle();
1125
-
1126
- // 注入宿主插件管理器:一步更新能力来源。可选能力——用安全读取而非硬依赖,
1127
- // 拿不到时 pluginManager 保持 null,更新弹窗自动降级为「复制包名」手动安装。
1128
- try {
1129
- const remote = (typeof ctx.get === 'function' && ctx.get('remote'))
1130
- || ctx.remote || null;
1131
- pluginManager = remote?.pluginManager || null;
1132
- } catch { pluginManager = null; }
1133
-
1134
- // 跨 HMR 重载恢复:一步更新触发插件自更新会卸载本模块,弹窗随之消失。
1135
- // 发起前把状态写入 localStorage,重载后据此显示「更新完成/进行中」反馈。
1136
- try { restorePendingUpdate(); } catch { /* 存储不可用时跳过,不影响主流程 */ }
1137
-
1138
- // 轮询保持 summary 新鲜(banner 状态点 + 面板数据共用)
1139
- probeUntilUp();
1140
- const pollTimer = setInterval(probe, 15000);
1141
-
1142
- // 状态面板打开期间保持轮询:banner 的 useGatewayStatus 只在宿主渲染时活跃
1143
- const disposeSlot = ctx.slots.inject('sidebar.footer.action', () =>
1144
- ctx.slots.register(
1145
- { name: 'sidebar.footer.action', id: 'dsh-mobile-ios' },
1146
- ({ wide }) => {
1147
- const ok = !!(summary && summary.ok);
1148
- const tone = ok ? STATUS_OK : STATUS_DOWN;
1149
- return react.createElement('button', {
1150
- className: `dsh-mios-trigger${wide ? '' : ' is-rail'}`,
1151
- type: 'button',
1152
- title: PANEL_TITLE,
1153
- 'aria-label': PANEL_TITLE,
1154
- onClick: togglePanel,
1155
- },
1156
- react.createElement('span', {
1157
- className: 'dsh-mios-dot ' + (ok ? 'ok' : 'down'),
1158
- style: { background: tone.stroke },
1159
- }),
1160
- // 名称左边不再放 SVG 手机图标:wide 模式有「📱」emoji 就够了;
1161
- // 窄栏(rail)没有名字,图标仍是唯一的视觉标识,保留。
1162
- wide ? undefined : react.createElement(PhoneIcon),
1163
- wide ? react.createElement('span', null, BANNER_LABEL) : undefined);
1164
- }
1165
- )
1166
- );
1167
-
1168
- return () => {
1169
- clearInterval(pollTimer);
1170
- disposeSlot();
1171
- removePanel();
1172
- document.getElementById(STYLE_ID)?.remove();
1173
- };
1174
- }
1175
-
1176
- // 注意:宿主 inject 数组是「硬依赖」,缺失会让整个模块挂起(pending)。
1177
- // remote/pluginManager 属可选能力,只声明 slots;安装服务在 apply 内安全获取。
1178
- const inject = ['slots'];
1179
- exports.apply = apply;
1180
- exports.inject = inject;
1181
- exports.__test = {
1182
- PORT_CANDIDATES, STATUS_OK, STATUS_DOWN,
1183
- showUpdateModal, closeUpdateModal, copyToClipboard,
1184
- performUpdate, checkPluginUpdate, compareVersions, unwrapRemote,
1185
- setPluginManager: (m) => { pluginManager = m; },
1186
- setUpdateTimeout: (ms) => { UPDATE_TIMEOUT_MS = ms; },
1187
- isUpdateInFlight: () => updateInFlight,
1188
- restorePendingUpdate, readUpdateState, writeUpdateState, clearUpdateState,
1189
- };
1190
-
1191
- return module.exports;
1192
- },
1193
- });
1
+ // lib/client.js — 桌面端 UI 注入模块(X3)
2
+ //
3
+ // 契约(考古自社区 dsh-mobile 0.8.11 的 lib/client.js):
4
+ // 宿主 web app 按包的 `exports["./client"]` 加载本文件,浏览器里执行到
5
+ // `window.__ModuleLoader__.load({ id, factory })` 注册模块;
6
+ // factory 返回的模块需导出 `apply(ctx)` 与 `inject = ["slots"]`,
7
+ // 宿主把 slots 服务注入进来,UI 通过 slots 挂载。
8
+ //
9
+ // 我们挂两个东西:
10
+ // 1. 左下角侧栏 banner(slot: sidebar.footer.action)——手机图标 + 「iOS移动伴侣」
11
+ // + 连接状态点;窄栏(rail)只留图标。
12
+ // 2. 点击展开的状态面板(原生 DOM overlay,宿主未提供 react-dom)——
13
+ // 网关状态 / 适配器 / 已配对设备 / 隧道 / 生成配对码。
14
+ //
15
+ // 如实边界:网关端口被占会自动顺延(3081–3085 探测);面板数据来自
16
+ // /mobile/v1/desktop/summary(回环-only,无敏感字段),拿不到就明确显示
17
+ // 「网关不可达」,绝不编造状态。
18
+ window.__ModuleLoader__.load({
19
+ id: 'dsh-mobile-ios',
20
+ factory: (require) => {
21
+ var module = { exports: {} };
22
+ var exports = module.exports;
23
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
24
+
25
+ let react = require('react');
26
+
27
+ // ── 状态 ─────────────────────────────────────────────────────
28
+ const PORT_CANDIDATES = [3081, 3082, 3083, 3084, 3085];
29
+ let gatewayPort = null;
30
+ let summary = null; // /desktop/summary 结果或 null
31
+ let probing = false;
32
+
33
+ function baseUrl() {
34
+ return gatewayPort ? `http://127.0.0.1:${gatewayPort}` : null;
35
+ }
36
+
37
+ async function fetchJson(path, options, timeoutMs = 1500) {
38
+ const base = baseUrl();
39
+ if (!base) throw new Error('gateway-not-found');
40
+ const controller = new AbortController();
41
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
42
+ try {
43
+ const res = await fetch(base + path, { ...options, signal: controller.signal });
44
+ const body = await res.json();
45
+ if (!res.ok) throw Object.assign(new Error(body?.error?.message || res.statusText), { body });
46
+ return body;
47
+ } finally {
48
+ clearTimeout(timer);
49
+ }
50
+ }
51
+
52
+ /** 探测网关端口(顺延容忍),成功后拉一次摘要 */
53
+ async function probe() {
54
+ if (probing) return;
55
+ probing = true;
56
+ try {
57
+ let found = null;
58
+ for (const port of PORT_CANDIDATES) {
59
+ const controller = new AbortController();
60
+ const timer = setTimeout(() => controller.abort(), 700);
61
+ try {
62
+ const res = await fetch(`http://127.0.0.1:${port}/mobile/v1/health`, { signal: controller.signal });
63
+ if (res.ok) { found = port; break; }
64
+ } catch {} // 端口不是我们/没起,继续探
65
+ finally { clearTimeout(timer); }
66
+ }
67
+ // 必须跟着探到的结果走:只在成功时赋值、失败时清空。
68
+ // 以前失败会保留旧端口,网关换端口后一直去敲那个死端口(若被别的服务
69
+ // 占用还会解析出非 JSON),面板就一直红着。
70
+ gatewayPort = found;
71
+ if (gatewayPort) summary = await fetchJson('/mobile/v1/desktop/summary').catch(() => null);
72
+ else summary = null;
73
+ } finally {
74
+ probing = false;
75
+ }
76
+ }
77
+
78
+ /** 面板打开时的轻量刷新:端口已经探到,只拉摘要并重绘,不再重复扫端口。 */
79
+ async function refreshSummary() {
80
+ if (!gatewayPort || summaryFetching) return;
81
+ summaryFetching = true;
82
+ try {
83
+ const next = await fetchJson('/mobile/v1/desktop/summary').catch(() => null);
84
+ if (next?.ok) {
85
+ summary = next;
86
+ renderSummary();
87
+ }
88
+ } finally {
89
+ summaryFetching = false;
90
+ }
91
+ }
92
+
93
+ /**
94
+ * 首屏快速补探。
95
+ *
96
+ * 宿主重启时插件先于网关绑端口加载,第一次探测必然落空;
97
+ * 只靠 15 秒轮询会让面板红着不动,用户看到的就是「插件坏了」。
98
+ */
99
+ async function probeUntilUp(attempts = 5, delayMs = 1200) {
100
+ for (let i = 0; i < attempts; i += 1) {
101
+ await probe();
102
+ if (summary && summary.ok) return;
103
+ if (i < attempts - 1) await new Promise((resolve) => { setTimeout(resolve, delayMs); });
104
+ }
105
+ }
106
+
107
+ /** 生成配对码(本机动作,回环-only 端点)。route 显式选路:'lan' | 'tunnel' | undefined=自动 */
108
+ async function issuePairingCode(route) {
109
+ return fetchJson('/mobile/v1/pairing/code', {
110
+ method: 'POST',
111
+ headers: { 'content-type': 'application/json' },
112
+ body: JSON.stringify({ deviceName: '待连接设备', ...(route ? { route } : {}) }),
113
+ }, 2500);
114
+ }
115
+
116
+ /** 隧道启停(本机管理面动作,回环-only 端点) */
117
+ /** 单台下线:管理面动作,与出码同样的本机约束,绝不走公网域名。 */
118
+ async function revokeDevice(deviceId) {
119
+ return fetchJson('/mobile/v1/pairing/revoke-device', {
120
+ method: 'POST',
121
+ headers: { 'content-type': 'application/json' },
122
+ body: JSON.stringify({ deviceId }),
123
+ }, 2500);
124
+ }
125
+
126
+ async function tunnelAction(action) {
127
+ // start 首次会顺带「开通固定地址 + 等公网注册 + DNS 复查」,实测经常超过 20s;
128
+ // 以前 20s 就掐断,用户点第一次报错、点第二次才出码——就是这里太短。
129
+ return fetchJson(`/mobile/v1/tunnel/${action}`, { method: 'POST' }, action === 'start' ? 60000 : 25000);
130
+ }
131
+
132
+ // ── 样式 ─────────────────────────────────────────────────────
133
+ const STYLE_ID = 'dsh-mios-style';
134
+ function installStyle() {
135
+ if (document.getElementById(STYLE_ID)) return;
136
+ const style = document.createElement('style');
137
+ style.id = STYLE_ID;
138
+ // 主题跟随宿主:颜色全部走 CSS 变量,.light 类由 detectHostTheme() 动态切换。
139
+ // 以前全硬编码深色,宿主开浅色主题时面板像一块黑补丁(2026-11-18 真机反馈)。
140
+ style.textContent = `
141
+ .dsh-mios-trigger { display: inline-flex; align-items: center; gap: 7px; background: none;
142
+ border: none; color: inherit; cursor: pointer; padding: 6px 8px; border-radius: 8px;
143
+ font: inherit; line-height: 1; }
144
+ .dsh-mios-trigger:hover { background: rgba(255,255,255,.08); }
145
+ .dsh-mios-trigger.is-rail { padding: 8px; }
146
+ .dsh-mios-dot { width: 7px; height: 7px; border-radius: 50%; flex: none; }
147
+ .dsh-mios-dot.ok { background: #3fb27f; }
148
+ .dsh-mios-dot.down { background: #d94f3d; }
149
+ .dsh-mios-panel { --bg: #171b24; --fg: #e8eaf0; --muted: #8b93a3; --border: #303a52;
150
+ --border-hover: #4a5678; --shadow: rgba(0,0,0,.5); --fg-soft: rgba(232,234,240,.7);
151
+ --muted-border: rgba(139,147,163,.45); --muted-bg: rgba(139,147,163,.12);
152
+ --muted-bg-hover: rgba(139,147,163,.2); }
153
+ .dsh-mios-panel.light { --bg: #ffffff; --fg: #1f2430; --muted: #6b7280; --border: #d9dee8;
154
+ --border-hover: #9aa5bd; --shadow: rgba(31,36,48,.18); --fg-soft: rgba(31,36,48,.7);
155
+ --muted-border: rgba(107,114,128,.4); --muted-bg: rgba(107,114,128,.1);
156
+ --muted-bg-hover: rgba(107,114,128,.18); }
157
+ .dsh-mios-panel { position: fixed; left: 14px; bottom: 52px; width: 300px; z-index: 99990;
158
+ background: var(--bg); color: var(--fg); border: 1px solid var(--border); border-radius: 14px;
159
+ box-shadow: 0 14px 44px var(--shadow); font: 13px/1.6 -apple-system, "PingFang SC", sans-serif;
160
+ padding: 14px; }
161
+ .dsh-mios-panel h3 { margin: 0 0 10px; font-size: 14px; display: flex; align-items: center; gap: 8px; }
162
+ .dsh-mios-upd { margin-left: auto; background: none; border: 1px solid var(--border); border-radius: 7px;
163
+ color: var(--muted); font-family: inherit; font-size: 11px; font-weight: 500; line-height: 1.4;
164
+ cursor: pointer; padding: 3px 8px; }
165
+ .dsh-mios-upd:hover { color: var(--fg); border-color: var(--border-hover); }
166
+ .dsh-mios-modal-mask { --modal-bg:#1c2230; --modal-fg:#e8eaf0; --modal-muted:#8b93a3;
167
+ --modal-border:#3a4560; --modal-btn:rgba(139,147,163,.12); --modal-accent:#3fb27f; --modal-shadow:rgba(0,0,0,.6);
168
+ position:fixed; inset:0; z-index:2147483000; background:var(--modal-shadow);
169
+ display:flex; align-items:center; justify-content:center; padding:20px;
170
+ font-family:-apple-system, "PingFang SC", sans-serif; font-size:13px; line-height:1.6; }
171
+ .dsh-mios-modal-mask.light { --modal-bg:#ffffff; --modal-fg:#1f2430; --modal-muted:#6b7280;
172
+ --modal-border:#d9dee8; --modal-btn:rgba(107,114,128,.1); --modal-accent:#2f9d70; --modal-shadow:rgba(31,36,48,.35); }
173
+ .dsh-mios-modal { width:100%; max-width:340px; box-sizing:border-box; background:var(--modal-bg);
174
+ color:var(--modal-fg); border:1px solid var(--modal-border); border-radius:14px; padding:18px;
175
+ box-shadow:0 18px 60px var(--modal-shadow); }
176
+ .dsh-mios-modal h4 { margin:0 0 12px; font-size:15px; display:flex; align-items:center; gap:8px; }
177
+ .dsh-mios-modal .modal-banner { margin:0 0 12px; padding:9px 11px; border-radius:9px; font-size:12px;
178
+ font-weight:600; line-height:1.5; background:rgba(63,178,127,.12); color:var(--modal-accent);
179
+ border:1px solid var(--modal-accent); }
180
+ .dsh-mios-modal .modal-banner.success { background:rgba(63,178,127,.16); color:#2f9d70; }
181
+ .dsh-mios-modal .modal-banner.warn { background:rgba(224,160,60,.14); color:#d18a26; border-color:#d18a26; }
182
+ .dsh-mios-modal .modal-banner.error { background:rgba(217,79,61,.14); color:#d94f3d; border-color:#d94f3d; }
183
+ .dsh-mios-modal .modal-x { margin-left:auto; background:none; border:none; color:var(--modal-muted);
184
+ font-size:16px; cursor:pointer; line-height:1; padding:2px 4px; }
185
+ .dsh-mios-modal .modal-line { display:flex; justify-content:space-between; gap:10px;
186
+ font-size:12px; color:var(--modal-muted); margin:6px 0; }
187
+ .dsh-mios-modal .modal-line b { color:var(--modal-fg); font-weight:600; max-width:200px;
188
+ overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
189
+ .dsh-mios-modal .modal-line b.new { color:var(--modal-accent); }
190
+ .dsh-mios-modal .modal-note { margin:12px 0 4px; font-size:11px; color:var(--modal-muted); line-height:1.6; }
191
+ .dsh-mios-modal .modal-actions { display:flex; gap:8px; margin-top:14px; }
192
+ .dsh-mios-modal .modal-actions button { flex:1; padding:8px 0; border-radius:8px; cursor:pointer;
193
+ font-family:inherit; font-size:12px; font-weight:600; line-height:1.4;
194
+ border:1px solid var(--modal-border); background:var(--modal-btn); color:var(--modal-fg); }
195
+ .dsh-mios-modal .modal-actions button.primary { border-color:var(--modal-accent);
196
+ background:rgba(63,178,127,.16); color:var(--modal-accent); }
197
+ .dsh-mios-modal .modal-actions button:disabled { opacity:.6; cursor:default; }
198
+ .dsh-mios-panel .row { display: flex; justify-content: space-between; gap: 8px; color: var(--muted); margin: 3px 0; }
199
+ .dsh-mios-panel .row b { color: var(--fg); font-weight: 600; text-align: right; max-width: 170px;
200
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
201
+ .dsh-mios-device-toggle { background: none; border: none; color: var(--muted); cursor: pointer;
202
+ font: inherit; padding: 0; display: inline-flex; align-items: center; gap: 5px; }
203
+ .dsh-mios-device-toggle:hover { color: var(--fg); }
204
+ .dsh-mios-devices { margin: 2px 0 6px; border: 1px solid var(--border); border-radius: 8px; overflow: hidden; }
205
+ .dsh-mios-devices[hidden] { display: none; }
206
+ .dsh-mios-device-row { display: flex; align-items: center; gap: 8px; padding: 5px 10px;
207
+ font-size: 11px; color: var(--muted); border-top: 1px solid var(--border); }
208
+ .dsh-mios-device-row:first-child { border-top: none; }
209
+ .dsh-mios-device-name { flex: 1; min-width: 0; overflow-wrap: anywhere; white-space: normal;
210
+ line-height: 1.35; color: var(--fg); }
211
+ .dsh-mios-device-online { color: #3fb27f; flex: none; }
212
+ .dsh-mios-device-offline { color: var(--muted); flex: none; }
213
+ .dsh-mios-device-kick { margin-left: auto; background: none; border: 1px solid rgba(217,79,61,.4); border-radius: 4px;
214
+ color: #c97a6d; cursor: pointer; font-family: inherit; font-size: 9px; font-weight: 500;
215
+ line-height: 1.3; padding: 1px 5px; flex: none; }
216
+ .dsh-mios-device-kick:hover { color: #d94f3d; border-color: rgba(217,79,61,.7); }
217
+ .dsh-mios-devices-empty { padding: 6px 8px; font-size: 11px; color: var(--muted); }
218
+ .dsh-mios-panel .pairbtn { width: 100%; margin-top: 10px; padding: 8px 0; border-radius: 9px;
219
+ border: 1px solid rgba(63,178,127,.45); background: rgba(63,178,127,.14); color: #3fb27f;
220
+ font: 600 13px/1.4 inherit-font, sans-serif; cursor: pointer; }
221
+ .dsh-mios-panel .pairbtn:disabled { opacity: .5; cursor: default; }
222
+ .dsh-mios-banner { border: 1px solid var(--border); border-radius: 10px; padding: 10px 10px 11px; margin-top: 10px; }
223
+ .dsh-mios-banner h4 { margin: 0; font-size: 12px; font-weight: 600; color: var(--fg);
224
+ display: flex; justify-content: space-between; align-items: baseline; gap: 8px; }
225
+ .dsh-mios-banner .banner-state { font-size: 11px; font-weight: 400; color: var(--muted);
226
+ max-width: 190px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
227
+ .dsh-mios-banner .banner-guide { margin-top: 4px; font-size: 11px; color: var(--muted); line-height: 1.5; }
228
+ .dsh-mios-banner .banner-addr { margin-top: 4px; font-size: 11px; color: var(--muted);
229
+ font-family: ui-monospace, "SF Mono", Menlo, monospace; word-break: break-all; line-height: 1.5; }
230
+ .dsh-mios-banner .pairbtn { margin-top: 8px; }
231
+ .dsh-mios-banner .tunnelbtn { border-color: var(--muted-border); background: var(--muted-bg); color: var(--muted); }
232
+ .dsh-mios-banner .tunnelbtn:hover:not(:disabled) { border-color: var(--fg-soft); color: var(--fg); background: var(--muted-bg-hover); }
233
+ .dsh-mios-banner .tunnelbtn:disabled { opacity: .5; cursor: default; }
234
+ .dsh-mios-banner .stopbtn { margin-top: 6px; padding: 5px 0; font-weight: 500;
235
+ border-color: rgba(217,79,61,.4); background: none; color: #c97a6d; }
236
+ .dsh-mios-banner .stopbtn:hover:not(:disabled) { border-color: rgba(217,79,61,.7); color: #d94f3d; }
237
+ .dsh-mios-panel .code { margin-top: 10px; text-align: center; font-size: 30px; letter-spacing: 8px;
238
+ font-weight: 700; color: var(--fg); font-variant-numeric: tabular-nums; }
239
+ .dsh-mios-qr { margin-top: 10px; padding: 10px; background: #fff; border-radius: 10px;
240
+ display: flex; justify-content: center; }
241
+ .dsh-mios-qr svg { width: 180px; height: 180px; display: block; }
242
+ .dsh-mios-panel .err { margin-top: 10px; font-size: 12px; color: #d94f3d; text-align: center; }
243
+ .dsh-mios-panel footer { margin-top: 10px; font-size: 11px; color: var(--muted); text-align: center; }
244
+ .dsh-mios-close { margin-left: auto; background: none; border: none; color: var(--muted);
245
+ font-size: 16px; cursor: pointer; padding: 2px 6px; }
246
+ `;
247
+ document.head.append(style);
248
+ }
249
+
250
+ // ── 面板(原生 DOM;宿主无 react-dom) ───────────────────────
251
+ // 双 banner 布局:上面「局域网连接」,下面「远程通道连接」。
252
+ // 远程 banner 是合并后的单一主按钮:没开过→开通;开过没跑→开启并出码;
253
+ // 跑着→直接出码。停止远程是旁边的小按钮,只在该停的时候出现。
254
+ const PANEL_TITLE = 'DSH iOS移动伴侣';
255
+ const BANNER_LABEL = '📱 iOS移动伴侣';
256
+ // 插件更新检查:读 npm registry 的 latest(与「添加插件」安装源同源)。
257
+ // npm 官方源带 CORS *,桌面端 webview 可直接 fetch;npmmirror 作国内备用。
258
+ const PLUGIN_NAME = 'dsh-mobile-ios';
259
+ const PLUGIN_REGISTRIES = [
260
+ 'https://registry.npmjs.org',
261
+ 'https://registry.npmmirror.com',
262
+ ];
263
+ const stripUrl = (u) => String(u || '').replace(/^https?:\/\//, '');
264
+ const stripLocal = (h) => String(h || '').replace(/\.local$/i, '');
265
+
266
+ // 宿主插件管理服务(remote.pluginManager)。注入模块经 apply 拿到;
267
+ // 非 Desktop 或老宿主拿不到时保持 null,更新入口降级为「复制包名」手动安装。
268
+ let pluginManager = null;
269
+ let updateInFlight = false; // 一步更新的并发锁:更新中禁止再次触发
270
+ let panelEl = null;
271
+ let tunnelBusy = false;
272
+ const bannerBusy = { lan: false, remote: false };
273
+ let outsideCloser = null;
274
+ let devicesExpanded = false;
275
+ let kickingDeviceId = null;
276
+ // 面板打开期间的摘要刷新:probe() 只更新数据不重绘,正是「扫码后要关掉重开才更新」的根因。
277
+ let summaryPollTimer = null;
278
+ let summaryFetching = false;
279
+ let lastDeviceSignature = null;
280
+
281
+ /** 探测宿主主题:显式标记(class/data-theme)→ body 亮度启发 → 系统偏好。
282
+ * Electron 宿主切换主题只改页面 class,matchMedia 不一定跟着变,所以三级都查。 */
283
+ function detectHostTheme() {
284
+ const root = document.documentElement;
285
+ const body = document.body;
286
+ const marked = `${root.className} ${body?.className || ''} ${root.getAttribute('data-theme') || ''} ${body?.getAttribute('data-theme') || ''} ${root.getAttribute('data-color-mode') || ''}`.toLowerCase();
287
+ if (/\bdark\b/.test(marked)) return 'dark';
288
+ if (/\blight\b/.test(marked)) return 'light';
289
+ // 亮度启发:宿主页面底色亮就是浅色主题(面板挂在这个页面上,跟它一致最直观)。
290
+ // 全黑或全透明底色不可判,落到系统偏好。
291
+ const bgc = body ? getComputedStyle(body).backgroundColor
292
+ : getComputedStyle(root).backgroundColor;
293
+ const m = bgc.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
294
+ if (m && (+m[1] + +m[2] + +m[3]) > 0) {
295
+ return (0.2126 * +m[1] + 0.7152 * +m[2] + 0.0722 * +m[3]) > 140 ? 'light' : 'dark';
296
+ }
297
+ return window.matchMedia?.('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
298
+ }
299
+
300
+ /** 面板主题实时跟随宿主:每次渲染都重判(用户可能中途切主题)。 */
301
+ function applyPanelTheme() {
302
+ if (!panelEl) return;
303
+ panelEl.classList.toggle('light', detectHostTheme() === 'light');
304
+ }
305
+
306
+ function removePanel() {
307
+ panelEl?.remove();
308
+ panelEl = null;
309
+ closeUpdateModal();
310
+ if (summaryPollTimer) {
311
+ clearInterval(summaryPollTimer);
312
+ summaryPollTimer = null;
313
+ }
314
+ lastDeviceSignature = null;
315
+ if (outsideCloser) {
316
+ document.removeEventListener('pointerdown', outsideCloser);
317
+ outsideCloser = null;
318
+ }
319
+ }
320
+
321
+ function row(label, valueId) {
322
+ const div = document.createElement('div');
323
+ div.className = 'row';
324
+ const l = document.createElement('span');
325
+ l.textContent = label;
326
+ const v = document.createElement('b');
327
+ v.id = valueId;
328
+ v.textContent = '—';
329
+ div.append(l, v);
330
+ return div;
331
+ }
332
+
333
+ /** 「同时在线设备」行:标签可点开展开在线设备清单,右侧显示 在线/上限。 */
334
+ function deviceRows() {
335
+ const wrap = document.createElement('div');
336
+ const head = document.createElement('div');
337
+ head.className = 'row';
338
+ const toggle = document.createElement('button');
339
+ toggle.className = 'dsh-mios-device-toggle';
340
+ toggle.id = 'dsh-mios-device-toggle';
341
+ toggle.type = 'button';
342
+ toggle.textContent = '▸';
343
+ toggle.setAttribute('aria-label', '展开或收起当前在线设备清单');
344
+ const label = document.createElement('span');
345
+ label.textContent = '同时在线设备(最多5台)';
346
+ const left = document.createElement('span');
347
+ left.append(toggle, label);
348
+ const value = document.createElement('b');
349
+ value.id = 'dsh-mios-devices';
350
+ value.textContent = '—';
351
+ head.append(left, value);
352
+ toggle.addEventListener('click', () => {
353
+ devicesExpanded = !devicesExpanded;
354
+ renderDeviceList();
355
+ });
356
+ const list = document.createElement('div');
357
+ list.className = 'dsh-mios-devices';
358
+ list.id = 'dsh-mios-devices-list';
359
+ list.hidden = true;
360
+ wrap.append(head, list);
361
+ return wrap;
362
+ }
363
+
364
+ /** 在线设备清单:默认折叠;只列当前在线设备(同时在线上限 5 台),下线逐台二次确认。 */
365
+ function renderDeviceList() {
366
+ const box = panelEl?.querySelector('#dsh-mios-devices-list');
367
+ if (!box) return;
368
+ box.hidden = !devicesExpanded;
369
+ const toggle = panelEl.querySelector('#dsh-mios-device-toggle');
370
+ if (toggle) toggle.textContent = devicesExpanded ? '▾' : '▸';
371
+ box.replaceChildren();
372
+ if (!summary?.ok) return;
373
+ // 后端已限制活跃设备上限;这里再按在线态筛选并截到 5,保证面板只展示真实并发连接。
374
+ const devices = (summary.pairing?.devices || []).filter((d) => d.online).slice(0, 5);
375
+ if (!devices.length) {
376
+ const empty = document.createElement('div');
377
+ empty.className = 'dsh-mios-devices-empty';
378
+ empty.textContent = '当前没有在线设备';
379
+ box.append(empty);
380
+ return;
381
+ }
382
+ for (const device of devices) {
383
+ const line = document.createElement('div');
384
+ line.className = 'dsh-mios-device-row';
385
+ const name = document.createElement('span');
386
+ name.className = 'dsh-mios-device-name';
387
+ name.textContent = device.deviceName || '未命名设备';
388
+ name.title = name.textContent;
389
+ const state = document.createElement('span');
390
+ state.className = device.online ? 'dsh-mios-device-online' : 'dsh-mios-device-offline';
391
+ state.textContent = device.online ? '在线' : '离线';
392
+ const kick = document.createElement('button');
393
+ kick.className = 'dsh-mios-device-kick';
394
+ kick.textContent = kickingDeviceId === device.deviceId ? '处理中' : '下线';
395
+ kick.disabled = kickingDeviceId !== null;
396
+ kick.title = `将 ${name.textContent} 从这台电脑移除`;
397
+ kick.addEventListener('click', async () => {
398
+ // 二次确认:下线会让那台手机立刻失去读任务的能力,不能误点。
399
+ if (!window.confirm(`确定让「${name.textContent}」下线?该设备需要重新扫码才能再次连接。`)) return;
400
+ kickingDeviceId = device.deviceId;
401
+ renderDeviceList();
402
+ try {
403
+ await revokeDevice(device.deviceId);
404
+ await probe();
405
+ } catch (err) {
406
+ window.alert('下线失败:' + (err?.body?.error?.message || err.message));
407
+ } finally {
408
+ kickingDeviceId = null;
409
+ renderSummary();
410
+ }
411
+ });
412
+ line.append(name, state, kick);
413
+ box.append(line);
414
+ }
415
+ }
416
+
417
+ function renderSummary() {
418
+ if (!panelEl) return;
419
+ applyPanelTheme();
420
+ const dot = panelEl.querySelector('#dsh-mios-panel-dot');
421
+ const ok = !!(summary && summary.ok);
422
+ dot.className = 'dsh-mios-dot ' + (ok ? 'ok' : 'down');
423
+ const set = (id, text) => { const el = panelEl.querySelector('#' + id); if (el) el.textContent = text; };
424
+ set('dsh-mios-adapter', ok ? `v${summary.version}` : '—');
425
+ set('dsh-mios-host', ok ? (stripLocal(summary.hostName) || '未上报') : '—');
426
+ if (ok) {
427
+ const max = summary.pairing?.maxDevices ?? 5;
428
+ const online = summary.pairing?.onlineDevices ?? 0;
429
+ set('dsh-mios-devices', `${online}/${max} 台`);
430
+ } else {
431
+ set('dsh-mios-devices', '—');
432
+ }
433
+ // 只有设备名/在线态/顺序变化才重建列表:1.2s 刷新不能让 hover 提示和下线按钮闪烁。
434
+ const devices = ok ? (summary.pairing?.devices || []) : [];
435
+ const signature = devices
436
+ .map((d) => `${d.deviceId}\u0000${d.deviceName || ''}\u0000${d.online ? 1 : 0}`)
437
+ .join('\u0001');
438
+ if (signature !== lastDeviceSignature) {
439
+ lastDeviceSignature = signature;
440
+ renderDeviceList();
441
+ }
442
+
443
+ // ── 局域网 banner ──
444
+ const lan = ok ? summary.lan : null;
445
+ const lanState = panelEl.querySelector('#dsh-mios-lan-state');
446
+ if (lanState) lanState.textContent = ok ? (lan ? `电脑地址 ${lan}` : '未获取到局域网地址') : '网关不可达';
447
+ const lanCodeBtn = panelEl.querySelector('#dsh-mios-lan-code');
448
+ if (lanCodeBtn) {
449
+ lanCodeBtn.disabled = !ok || !lan || bannerBusy.lan;
450
+ lanCodeBtn.title = ok && lan ? '' : '网关不可达或没有局域网地址';
451
+ }
452
+
453
+ // ── 远程通道 banner ──
454
+ // 四种事实分开说:运行中 / 已开通但没开 / 根本没开通 / 域名没生效。
455
+ // 「域名未生效」必须单列:地址开出来了但公网解析不到,显示「已开通」会误导人去扫码。
456
+ const tunnel = ok ? summary.tunnel : null;
457
+ const dnsBroken = tunnel && tunnel.dnsOk === false;
458
+ const running = !!(tunnel && tunnel.state === 'running' && !dnsBroken);
459
+ const remoteState = panelEl.querySelector('#dsh-mios-remote-state');
460
+ if (remoteState) {
461
+ remoteState.textContent = !tunnel
462
+ ? '—'
463
+ : dnsBroken
464
+ ? '解析异常 · 未开启'
465
+ : running
466
+ ? '已开启'
467
+ : tunnel.provisioned && tunnel.fixedUrl
468
+ ? '已开通 · 未开启'
469
+ : tunnel.mode === 'named' ? '未开通固定地址' : tunnel.state;
470
+ }
471
+ // 固定地址独占一行完整显示,不再和状态词挤在一起被省略号截断
472
+ const remoteAddr = panelEl.querySelector('#dsh-mios-remote-addr');
473
+ if (remoteAddr) {
474
+ const addr = tunnel && (tunnel.fixedUrl || tunnel.url);
475
+ remoteAddr.textContent = tunnel && tunnel.provisioned ? stripUrl(addr) : '—';
476
+ // 默认色交给 CSS 变量(跟随主题);只有解析异常时才覆盖成红色
477
+ remoteAddr.style.color = dnsBroken ? '#d94f3d' : '';
478
+ }
479
+ const mainBtn = panelEl.querySelector('#dsh-mios-remote-main');
480
+ if (mainBtn) {
481
+ // 出码态走绿色主按钮;开启态走灰色次按钮(悬浮变白),视觉上分清两件事
482
+ mainBtn.className = 'pairbtn' + (running || dnsBroken ? '' : ' tunnelbtn');
483
+ mainBtn.style.display = tunnel && tunnel.state !== 'disabled' ? '' : 'none';
484
+ mainBtn.disabled = tunnelBusy || bannerBusy.remote || dnsBroken;
485
+ const needsInstall = tunnel.executable === 'missing';
486
+ mainBtn.textContent = needsInstall && tunnel.canAutoInstall
487
+ ? '安装 cloudflared 并开启远程'
488
+ : dnsBroken
489
+ ? '域名解析异常,暂不可开启'
490
+ : running
491
+ ? (bannerBusy.remote ? '生成中…' : '生成配对码(远程)')
492
+ : tunnel.mode === 'named'
493
+ ? (tunnel.provisioned ? '开启远程并生成配对码' : '开启远程(分配固定地址)')
494
+ : '启动隧道(外网连接)';
495
+ }
496
+ const stopBtn = panelEl.querySelector('#dsh-mios-remote-stop');
497
+ if (stopBtn) {
498
+ // 停止按钮只在该停的时候出现:没开过/没在跑都没有「停」可言
499
+ stopBtn.style.display = running && !tunnelBusy ? '' : 'none';
500
+ stopBtn.disabled = tunnelBusy;
501
+ }
502
+ // 远程码跟着可用性走:不是 running 就收起(与「停止即收码」同一语义,
503
+ // 兜住任何没经过停止按钮的路径,比如进程意外退出)。
504
+ if (!running && !bannerBusy.remote) {
505
+ panelEl.querySelector('#dsh-mios-remote-main')?.closest('.dsh-mios-banner')
506
+ ?.querySelectorAll('.dsh-mios-code-slot, .err').forEach((e) => e.remove());
507
+ }
508
+
509
+ // 提示行承载告警与错误:warning 优先,其次是 tunnel.error。
510
+ // 以前只读 warning,服务端明确报的 error(如「主机未安装 cloudflared」)
511
+ // 被 1.2s 一次的刷新瞬间清空,用户点了按钮只看到一闪而过、误以为「无反应」。
512
+ const hint = panelEl.querySelector('#dsh-mios-hint');
513
+ if (hint) {
514
+ const t = ok ? summary.tunnel : null;
515
+ const msg = t?.warning || t?.error || null;
516
+ hint.textContent = msg ? `⚠️ ${msg}` : '';
517
+ hint.style.color = t?.error && !t?.warning ? '#d94f3d' : '#e0a03c';
518
+ hint.style.display = msg ? '' : 'none';
519
+ }
520
+ }
521
+
522
+ /** 双 banner 里的一块:标题 + 状态行 + 指引一句 + 内容区 */
523
+ function bannerBox(title, stateId, guideText) {
524
+ const box = document.createElement('div');
525
+ box.className = 'dsh-mios-banner';
526
+ const head = document.createElement('h4');
527
+ head.textContent = title;
528
+ const state = document.createElement('span');
529
+ state.className = 'banner-state';
530
+ state.id = stateId;
531
+ state.textContent = '—';
532
+ head.append(state);
533
+ const guide = document.createElement('div');
534
+ guide.className = 'banner-guide';
535
+ guide.textContent = guideText;
536
+ box.append(head, guide);
537
+ return box;
538
+ }
539
+
540
+ /** 出码结果挂进所属 banner:QR + 码 + 地址说明(同一 banner 只保留最新一码) */
541
+ function mountCode(banner, issued) {
542
+ banner.querySelectorAll('.dsh-mios-code-slot').forEach((e) => e.remove());
543
+ const slot = document.createElement('div');
544
+ slot.className = 'dsh-mios-code-slot';
545
+ if (issued.qrSvg) {
546
+ const qr = document.createElement('div');
547
+ qr.className = 'dsh-mios-qr';
548
+ qr.innerHTML = issued.qrSvg;
549
+ slot.append(qr);
550
+ }
551
+ const code = document.createElement('div');
552
+ code.className = 'code';
553
+ code.textContent = issued.code;
554
+ const addr = document.createElement('div');
555
+ addr.style.cssText = 'margin-top:6px;text-align:center;font-size:12px;color:#3fb27f;';
556
+ addr.textContent = issued.route === 'tunnel'
557
+ ? `扫码连接 · 公网固定地址 ${stripUrl(issued.address)}`
558
+ : issued.address
559
+ ? `扫码连接 · 局域网 ${issued.address}`
560
+ : '手机填电脑局域网地址 + 此码';
561
+ slot.append(code, addr);
562
+ banner.append(slot);
563
+ }
564
+
565
+ /** banner 内的出码按钮统一行为:busy → 出码 → 失败在 banner 内显错 */
566
+ function bindCodeBtn(btn, banner, route) {
567
+ btn.addEventListener('click', async () => {
568
+ if (bannerBusy[route]) return;
569
+ bannerBusy[route] = true;
570
+ btn.disabled = true;
571
+ btn.textContent = '生成中…';
572
+ try {
573
+ mountCode(banner, await issuePairingCode(route));
574
+ } catch (err) {
575
+ banner.querySelectorAll('.dsh-mios-code-slot').forEach((e) => e.remove());
576
+ const errEl = document.createElement('div');
577
+ errEl.className = 'err';
578
+ errEl.textContent = '生成失败:' + (err?.body?.error?.message || err.message);
579
+ banner.append(errEl);
580
+ } finally {
581
+ bannerBusy[route] = false;
582
+ btn.textContent = '重新生成配对码';
583
+ renderSummary();
584
+ }
585
+ });
586
+ }
587
+
588
+ function showPanel() {
589
+ if (panelEl) return;
590
+ // 打开期间持续轻量刷新:扫码上线、改名、下线都能立刻反映,无需关掉重开。
591
+ if (summaryPollTimer) clearInterval(summaryPollTimer);
592
+ summaryPollTimer = setInterval(refreshSummary, 1200);
593
+ installStyle();
594
+ panelEl = document.createElement('div');
595
+ panelEl.className = 'dsh-mios-panel';
596
+
597
+ const header = document.createElement('h3');
598
+ const dot = document.createElement('span');
599
+ dot.id = 'dsh-mios-panel-dot';
600
+ dot.className = 'dsh-mios-dot down';
601
+ const title = document.createElement('span');
602
+ title.textContent = PANEL_TITLE;
603
+ // 插件更新:放在关闭按钮左边,点击弹出更新对话框(版本对比 + 更新与否由用户选)
604
+ const updBtn = document.createElement('button');
605
+ updBtn.className = 'dsh-mios-upd';
606
+ updBtn.textContent = '插件更新';
607
+ updBtn.addEventListener('click', () => {
608
+ // 点击务必先有可见反馈再联网,避免「无反应」错觉(缓存旧模块时旧逻辑写已移除的内联元素)。
609
+ try { checkPluginUpdate(); } catch (e) {
610
+ console.error('[dsh-mobile-ios] checkPluginUpdate failed:', e);
611
+ showUpdateModal({ title: '插件更新', lines: [], note: `打开更新检查失败:${e?.message || e}`, actions: [{ label: '知道了', primary: true, onClick: closeUpdateModal }] });
612
+ }
613
+ });
614
+ const close = document.createElement('button');
615
+ close.className = 'dsh-mios-close';
616
+ close.textContent = '✕';
617
+ close.setAttribute('aria-label', '关闭面板');
618
+ close.addEventListener('click', removePanel);
619
+ header.append(dot, title, updBtn, close);
620
+
621
+ const body = document.createElement('div');
622
+ body.append(
623
+ row('插件版本', 'dsh-mios-adapter'),
624
+ row('电脑名称', 'dsh-mios-host'),
625
+ deviceRows(),
626
+ );
627
+
628
+ // ── banner 1:局域网连接(在家 · 直连 · 始终可用) ──
629
+ const lanBanner = bannerBox('局域网连接', 'dsh-mios-lan-state', '手机与电脑连同一个 Wi-Fi,直连不走外网。适合在家日常用。');
630
+ const lanCodeBtn = document.createElement('button');
631
+ lanCodeBtn.className = 'pairbtn';
632
+ lanCodeBtn.id = 'dsh-mios-lan-code';
633
+ lanCodeBtn.textContent = '生成配对码';
634
+ bindCodeBtn(lanCodeBtn, lanBanner, 'lan');
635
+ lanBanner.append(lanCodeBtn);
636
+
637
+ // ── banner 2:远程通道连接(出门 · 固定域名 · 一个主按钮走完) ──
638
+ // 「开启远程」与「生成配对码」合并成一个主按钮:没开过→开通;
639
+ // 开过没跑→开启并出码;跑着→直接出码。停止是旁边的小按钮。
640
+ const remoteBanner = bannerBox('远程通道连接', 'dsh-mios-remote-state', '出门在外扫码连固定域名,电脑和手机不必在同一网络。');
641
+ const remoteAddr = document.createElement('div');
642
+ remoteAddr.id = 'dsh-mios-remote-addr';
643
+ remoteAddr.className = 'banner-addr';
644
+ remoteAddr.textContent = '—';
645
+ remoteBanner.append(remoteAddr);
646
+ const mainBtn = document.createElement('button');
647
+ mainBtn.className = 'pairbtn';
648
+ mainBtn.id = 'dsh-mios-remote-main';
649
+ mainBtn.textContent = '开启远程并生成配对码';
650
+ mainBtn.addEventListener('click', () => remoteMainAction(remoteBanner));
651
+ const stopBtn = document.createElement('button');
652
+ stopBtn.className = 'pairbtn stopbtn';
653
+ stopBtn.id = 'dsh-mios-remote-stop';
654
+ stopBtn.textContent = '停止远程';
655
+ stopBtn.addEventListener('click', stopRemoteAction);
656
+ remoteBanner.append(mainBtn, stopBtn);
657
+
658
+ const hint = document.createElement('div');
659
+ hint.id = 'dsh-mios-hint';
660
+ hint.style.cssText = 'margin-top:8px;font-size:11px;color:#e0a03c;line-height:1.5;';
661
+ hint.style.display = 'none';
662
+
663
+ const footer = document.createElement('footer');
664
+ footer.textContent = 'iPhone/iPad App → 连接 → 扫码(约 2 分钟有效)';
665
+
666
+ panelEl.append(header, body, lanBanner, remoteBanner, hint, footer);
667
+ document.body.append(panelEl);
668
+ applyPanelTheme();
669
+ placePanelAboveTrigger();
670
+ renderSummary();
671
+ probe();
672
+
673
+ // 点击面板/触发 banner 以外的任意区域即关闭(✕ 之外的第二条路)
674
+ outsideCloser = (ev) => {
675
+ if (!panelEl) return;
676
+ const t = ev.target;
677
+ if (panelEl.contains(t) || (t.closest && t.closest('.dsh-mios-trigger'))) return;
678
+ removePanel();
679
+ };
680
+ document.addEventListener('pointerdown', outsideCloser);
681
+ }
682
+
683
+ /** 面板底边对齐触发 banner 顶边:不遮挡 banner,屏幕放不下就整体上推并内滚。 */
684
+ function placePanelAboveTrigger() {
685
+ const trigger = document.querySelector('.dsh-mios-trigger');
686
+ if (trigger) {
687
+ const rect = trigger.getBoundingClientRect();
688
+ panelEl.style.left = `${Math.max(10, Math.round(rect.left))}px`;
689
+ panelEl.style.bottom = `${Math.max(10, Math.round(window.innerHeight - rect.top + 8))}px`;
690
+ }
691
+ panelEl.style.maxHeight = 'min(72vh, 640px)';
692
+ panelEl.style.overflowY = 'auto';
693
+ }
694
+
695
+ /** 更新检查:与「添加插件」同源,读 npm registry 的 latest 比对当前版本。
696
+ * 404 = 包未发布(本地开发版);网络失败 = 如实报不可达,二者不混为一谈。 */
697
+ /** 更新对话框:显示版本对比,更新与否由用户选;随面板销毁清理。 */
698
+ let updateModal = null;
699
+ function closeUpdateModal() {
700
+ updateModal?.remove();
701
+ updateModal = null;
702
+ }
703
+ function showUpdateModal({ title, banner, lines, note, actions }) {
704
+ closeUpdateModal();
705
+ const mask = document.createElement('div');
706
+ mask.className = 'dsh-mios-modal-mask';
707
+ if (detectHostTheme() === 'light') mask.classList.add('light');
708
+ const box = document.createElement('div');
709
+ box.className = 'dsh-mios-modal';
710
+
711
+ const h = document.createElement('h4');
712
+ h.textContent = title;
713
+ const x = document.createElement('button');
714
+ x.className = 'modal-x';
715
+ x.textContent = '✕';
716
+ x.setAttribute('aria-label', '关闭');
717
+ x.addEventListener('click', closeUpdateModal);
718
+ h.append(x);
719
+ box.append(h);
720
+
721
+ // banner:一步更新流程的状态横幅(发现新版 / 更新中 / 成功 / 失败)
722
+ if (banner) {
723
+ const b = document.createElement('div');
724
+ b.className = `modal-banner${banner.tone ? ' ' + banner.tone : ''}`;
725
+ b.textContent = banner.text;
726
+ box.append(b);
727
+ }
728
+
729
+ for (const line of lines || []) {
730
+ const row = document.createElement('div');
731
+ row.className = 'modal-line';
732
+ const label = document.createElement('span');
733
+ label.textContent = line.label;
734
+ const value = document.createElement('b');
735
+ value.textContent = line.value;
736
+ if (line.highlight) value.className = 'new';
737
+ row.append(label, value);
738
+ box.append(row);
739
+ }
740
+ if (note) {
741
+ const n = document.createElement('div');
742
+ n.className = 'modal-note';
743
+ n.textContent = note;
744
+ box.append(n);
745
+ }
746
+
747
+ const bar = document.createElement('div');
748
+ bar.className = 'modal-actions';
749
+ for (const action of actions || []) {
750
+ const btn = document.createElement('button');
751
+ btn.textContent = action.label;
752
+ if (action.primary) btn.className = 'primary';
753
+ btn.addEventListener('click', () => action.onClick?.(btn));
754
+ bar.append(btn);
755
+ }
756
+ box.append(bar);
757
+ mask.append(box);
758
+ mask.addEventListener('click', (e) => { if (e.target === mask) closeUpdateModal(); });
759
+ document.body.append(mask);
760
+ updateModal = mask;
761
+ }
762
+
763
+ /** 复制文本:clipboard API 不可用时回退到 textarea + execCommand。 */
764
+ async function copyToClipboard(text) {
765
+ try {
766
+ if (navigator.clipboard?.writeText) {
767
+ await navigator.clipboard.writeText(text);
768
+ return true;
769
+ }
770
+ } catch { /* 落到下面的回退 */ }
771
+ try {
772
+ const ta = document.createElement('textarea');
773
+ ta.value = text;
774
+ ta.style.position = 'fixed';
775
+ ta.style.opacity = '0';
776
+ document.body.append(ta);
777
+ ta.select();
778
+ const ok = document.execCommand('copy');
779
+ ta.remove();
780
+ return ok;
781
+ } catch {
782
+ return false;
783
+ }
784
+ }
785
+
786
+ async function checkPluginUpdate() {
787
+ showUpdateModal({ title: '插件更新', lines: [], note: '正在检查更新…', actions: [] });
788
+ const current = summary?.version || '未知';
789
+ let latest = '';
790
+ let sawNotFound = false;
791
+ let lastError = null;
792
+ for (const base of PLUGIN_REGISTRIES) {
793
+ try {
794
+ const res = await fetch(`${base}/${PLUGIN_NAME}/latest`, { signal: AbortSignal.timeout(6000) });
795
+ if (res.status === 404) { sawNotFound = true; continue; }
796
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
797
+ const meta = await res.json();
798
+ if (meta?.version) { latest = String(meta.version); break; }
799
+ } catch (e) {
800
+ lastError = e;
801
+ }
802
+ }
803
+ if (!latest) {
804
+ showUpdateModal({
805
+ title: '插件更新',
806
+ lines: [{ label: '当前版本', value: `v${current}` }],
807
+ note: sawNotFound
808
+ ? '插件尚未发布到 npm,当前为本地开发版。更新方式:拉取仓库最新代码后重启 DSH 桌面端,插件会随源码热重载。'
809
+ : `更新源暂不可达${lastError ? `(${lastError.message})` : ''},无法确认是否有新版本。`,
810
+ actions: [{ label: '知道了', primary: true, onClick: closeUpdateModal }],
811
+ });
812
+ return;
813
+ }
814
+ if (compareVersions(latest, current) > 0) {
815
+ // 一步更新:宿主提供 pluginManager 时直接安装,无需复制包名手动添加。
816
+ const canAuto = !!(pluginManager && typeof pluginManager.installBundle === 'function');
817
+ const actions = [{ label: '稍后再说', onClick: closeUpdateModal }];
818
+ if (canAuto) {
819
+ actions.push({
820
+ label: `立即更新到 v${latest}`, primary: true,
821
+ onClick: () => performUpdate(latest),
822
+ });
823
+ } else {
824
+ // 降级:拿不到宿主安装服务(老宿主 / 非 Desktop),保留复制包名手动安装。
825
+ actions.push({
826
+ label: `复制 ${PLUGIN_NAME}@${latest}`, primary: true,
827
+ onClick: async (btn) => {
828
+ const ok = await copyToClipboard(`${PLUGIN_NAME}@${latest}`);
829
+ btn.textContent = ok ? '已复制,去插件页粘贴安装' : '复制失败,请手动复制包名';
830
+ },
831
+ });
832
+ }
833
+ showUpdateModal({
834
+ title: '新版本更新',
835
+ banner: { text: `⬆️ 发现新版本 v${latest},可一键更新`, tone: 'info' },
836
+ lines: [
837
+ { label: '当前版本', value: `v${current}` },
838
+ { label: '最新版本', value: `v${latest}`, highlight: true },
839
+ ],
840
+ note: canAuto
841
+ ? '点击「立即更新」将由 DSH 安装器一步完成,更新中请勿关闭窗口。是否更新由你决定。'
842
+ : '当前宿主未提供一步更新能力,请复制包名到 DSH「插件 → 添加插件」粘贴安装。',
843
+ actions,
844
+ });
845
+ } else {
846
+ showUpdateModal({
847
+ title: '已是最新版本',
848
+ lines: [
849
+ { label: '当前版本', value: `v${current}` },
850
+ { label: 'npm 最新', value: `v${latest}` },
851
+ ],
852
+ note: '当前版本已是最新,无需更新。',
853
+ actions: [{ label: '知道了', primary: true, onClick: closeUpdateModal }],
854
+ });
855
+ }
856
+ }
857
+
858
+ /** 一步更新:经宿主 pluginManager.installBundle 安装 npm spec,
859
+ * 状态机覆盖 更新中 / 成功 / 失败 / 超时对账 / 重复点击。 */
860
+ let UPDATE_TIMEOUT_MS = 180000; // pnpm 安装 + 可能的重启,给足 3 分钟
861
+ function unwrapRemote(result) {
862
+ if (result && typeof result === 'object' && Object.hasOwn(result, 'ok')) {
863
+ if (!result.ok) throw new Error(result.error?.code || result.error?.message || '宿主返回失败');
864
+ return result.value;
865
+ }
866
+ return result;
867
+ }
868
+ function withTimeout(promise, ms, label) {
869
+ return new Promise((resolve, reject) => {
870
+ let settled = false;
871
+ const timer = setTimeout(() => {
872
+ if (settled) return;
873
+ settled = true;
874
+ reject(new Error(`${label}超时(${Math.round(ms / 1000)} 秒)`));
875
+ }, ms);
876
+ Promise.resolve(promise).then(
877
+ (v) => { if (!settled) { settled = true; clearTimeout(timer); resolve(v); } },
878
+ (e) => { if (!settled) { settled = true; clearTimeout(timer); reject(e); } },
879
+ );
880
+ });
881
+ }
882
+
883
+ // ── 跨 HMR 重载的更新状态持久化 ─────────────────────────────
884
+ // 更新「自己」会触发宿主卸载本模块并加载新版,当前 JS 上下文连同弹窗一起销毁。
885
+ // 因此发起更新前把状态写入 localStorage,新模块 apply 时读取并给出结果反馈,
886
+ // 避免出现「点一下弹窗消失、什么都没发生」的体验。
887
+ const UPDATE_STATE_KEY = 'dsh-mios-update-state';
888
+ function readUpdateState() {
889
+ try {
890
+ const raw = globalThis.localStorage?.getItem(UPDATE_STATE_KEY);
891
+ return raw ? JSON.parse(raw) : null;
892
+ } catch { return null; }
893
+ }
894
+ function writeUpdateState(state) {
895
+ try { globalThis.localStorage?.setItem(UPDATE_STATE_KEY, JSON.stringify(state)); }
896
+ catch { /* 存储不可用时静默,功能降级但不崩 */ }
897
+ }
898
+ function clearUpdateState() {
899
+ try { globalThis.localStorage?.removeItem(UPDATE_STATE_KEY); }
900
+ catch { /* 同上 */ }
901
+ }
902
+ /** apply 时调用:若上次更新尚未收尾,依据当前版本推断结果并弹窗告知。 */
903
+ function restorePendingUpdate() {
904
+ const st = readUpdateState();
905
+ if (!st || st.status !== 'updating' || !st.target) return;
906
+ const current = String(summary?.version || '').trim();
907
+ const age = Date.now() - (st.at || 0);
908
+ if (current && compareVersions(current, st.target) >= 0) {
909
+ clearUpdateState();
910
+ // 延迟到面板初次渲染后再弹,避免被 apply 后续的初始化覆盖
911
+ setTimeout(() => showUpdateModal({
912
+ title: '更新完成',
913
+ banner: { text: `✅ 已更新到 v${st.target}`, tone: 'success' },
914
+ lines: [{ label: '当前版本', value: `v${current}` }],
915
+ note: '插件已更新并重新加载完成。',
916
+ actions: [{ label: '知道了', primary: true, onClick: closeUpdateModal }],
917
+ }), 600);
918
+ } else if (age > 5 * 60 * 1000) {
919
+ clearUpdateState();
920
+ setTimeout(() => showUpdateModal({
921
+ title: '更新结果未知',
922
+ banner: { text: '⚠️ 上一步更新未能确认', tone: 'warn' },
923
+ lines: [{ label: '目标版本', value: `v${st.target}` }, { label: '当前版本', value: current ? `v${current}` : '未知' }],
924
+ note: '更新过程被中断或耗时过长。请到「插件」页确认当前版本,必要时手动更新。',
925
+ actions: [{ label: '知道了', primary: true, onClick: closeUpdateModal }],
926
+ }), 600);
927
+ }
928
+ // 未超时且版本未变:保持 updating 状态,等下次 apply(轮询重载)再判断
929
+ }
930
+ async function performUpdate(latest) {
931
+ // 重复点击保护:更新中直接忽略再次触发
932
+ if (updateInFlight) return;
933
+ if (!pluginManager || typeof pluginManager.installBundle !== 'function') {
934
+ showUpdateModal({
935
+ title: '更新不可用',
936
+ banner: { text: '⚠️ 宿主未提供一步更新能力', tone: 'warn' },
937
+ lines: [],
938
+ note: '请复制包名,到 DSH「插件 → 添加插件」粘贴安装。',
939
+ actions: [
940
+ { label: '知道了', onClick: closeUpdateModal },
941
+ { label: `复制 ${PLUGIN_NAME}@${latest}`, primary: true, onClick: async (btn) => {
942
+ const ok = await copyToClipboard(`${PLUGIN_NAME}@${latest}`);
943
+ btn.textContent = ok ? '已复制' : '复制失败';
944
+ } },
945
+ ],
946
+ });
947
+ return;
948
+ }
949
+ updateInFlight = true;
950
+ const current = summary?.version || '未知';
951
+ const spec = `${PLUGIN_NAME}@${latest}`;
952
+ // 先持久化「更新中」,确保 HMR 卸载本模块后新实例能恢复出结果反馈。
953
+ writeUpdateState({ status: 'updating', target: String(latest), at: Date.now() });
954
+ // 状态:更新中。无取消/关闭动作外的操作按钮,防重复点击。
955
+ showUpdateModal({
956
+ title: '正在更新',
957
+ banner: { text: `⏳ 正在更新到 v${latest},请稍候`, tone: 'info' },
958
+ lines: [
959
+ { label: '当前版本', value: `v${current}` },
960
+ { label: '目标版本', value: `v${latest}`, highlight: true },
961
+ ],
962
+ note: '正在通过 DSH 安装器更新,可能需要 1–3 分钟。请勿重复点击或关闭窗口。',
963
+ actions: [],
964
+ });
965
+ let requestId;
966
+ try {
967
+ requestId = globalThis.crypto?.randomUUID?.();
968
+ if (typeof requestId !== 'string') throw new Error('无法生成更新请求 ID');
969
+ let result;
970
+ try {
971
+ result = await withTimeout(
972
+ pluginManager.installBundle(spec, { enabled: true, requestId }),
973
+ UPDATE_TIMEOUT_MS, '安装',
974
+ );
975
+ } catch (err) {
976
+ // 超时/结果未知:用 requestId 对账,绝不重复提交安装
977
+ if (typeof pluginManager.waitForInstall === 'function') {
978
+ const recovered = await withTimeout(pluginManager.waitForInstall(requestId), 60000, '结果对账');
979
+ if (!recovered) throw err;
980
+ result = recovered;
981
+ } else throw err;
982
+ }
983
+ const value = unwrapRemote(result);
984
+ const restart = !!(value && (value.restartRequired || value.restart));
985
+ clearUpdateState(); // 安装器已返回结果,交由本弹窗反馈,无需跨重载恢复
986
+ // 状态:成功
987
+ showUpdateModal({
988
+ title: '更新完成',
989
+ banner: { text: `✅ 已安装 v${latest}`, tone: 'success' },
990
+ lines: [
991
+ { label: '目标版本', value: `v${latest}` },
992
+ ],
993
+ note: restart
994
+ ? '插件已更新,重启 DSH 桌面端后生效。'
995
+ : '插件已更新。若面板未刷新,重开面板或重启 DSH 即可。',
996
+ actions: [{ label: '知道了', primary: true, onClick: closeUpdateModal }],
997
+ });
998
+ } catch (err) {
999
+ // 状态:失败(保留重试入口;重试会重新走一遍锁与状态机)
1000
+ clearUpdateState();
1001
+ showUpdateModal({
1002
+ title: '更新失败',
1003
+ banner: { text: '❌ 更新未成功', tone: 'error' },
1004
+ lines: [{ label: '目标版本', value: `v${latest}` }],
1005
+ note: `安装失败:${err?.message || String(err)}。可重试,或复制包名到「插件 → 添加插件」手动安装。`,
1006
+ actions: [
1007
+ { label: '关闭', onClick: closeUpdateModal },
1008
+ { label: '重试更新', primary: true, onClick: () => performUpdate(latest) },
1009
+ ],
1010
+ });
1011
+ } finally {
1012
+ updateInFlight = false;
1013
+ }
1014
+ }
1015
+
1016
+ function compareVersions(a, b) {
1017
+ const parse = (s) => String(s || '').replace(/^v/i, '').split('-')[0].split('.').map((n) => parseInt(n, 10) || 0);
1018
+ const [pa, pb] = [parse(a), parse(b)];
1019
+ for (let i = 0; i < 3; i += 1) {
1020
+ if ((pa[i] || 0) !== (pb[i] || 0)) return (pa[i] || 0) - (pb[i] || 0);
1021
+ }
1022
+ return 0;
1023
+ }
1024
+
1025
+ /** 等 summary 反映出「远程已可用」:服务端 start 会等到注册成功才返回,
1026
+ * 但客户端超时/轮询窗口内可能还没看到,这里统一补轮询兜底。 */
1027
+ async function waitForTunnelUp(attempts = 8, delayMs = 1500) {
1028
+ for (let i = 0; i < attempts; i += 1) {
1029
+ await probe();
1030
+ renderSummary();
1031
+ const t = summary?.tunnel;
1032
+ if (t && t.state === 'running' && t.dnsOk !== false) return true;
1033
+ if (i < attempts - 1) await new Promise((resolve) => { setTimeout(resolve, delayMs); });
1034
+ }
1035
+ return false;
1036
+ }
1037
+
1038
+ /** 自举安装 cloudflared:先弹窗征得同意,确认后经网关从官方源下载到私有目录。
1039
+ * 安装成功即重探状态(发现链已含组件目录),让本次点击继续走开启远程。 */
1040
+ let installBusy = false;
1041
+ let installBanner = null; // 保存触发安装的 banner,供成功后自动继续出码(onClick 只传按钮,不传 banner)
1042
+ let autoContinueTimer = null; // 安装成功后延迟自动出码的定时器,允许手动「立即开启」取消
1043
+ async function installCloudflaredAction(banner) {
1044
+ if (installBusy) return;
1045
+ installBusy = true;
1046
+ installBanner = banner || null;
1047
+ try {
1048
+ showUpdateModal({
1049
+ title: '安装 cloudflared',
1050
+ banner: { text: '⬇️ 远程通道需要 cloudflared', tone: 'info' },
1051
+ lines: [
1052
+ { label: '来源', value: 'Cloudflare 官方发布' },
1053
+ { label: '安装位置', value: '本机私有目录(不改系统设置)' },
1054
+ ],
1055
+ note: '将从 Cloudflare 官方发布地址下载 cloudflared 到本机,仅用于远程通道。下载期间请保持网络畅通,是否继续?',
1056
+ actions: [
1057
+ { label: '取消', onClick: () => { installBanner = null; closeUpdateModal(); } },
1058
+ { label: '确认下载并安装', primary: true, onClick: () => runInstall() },
1059
+ ],
1060
+ });
1061
+ } finally {
1062
+ installBusy = false;
1063
+ }
1064
+ }
1065
+
1066
+ // 安装成功后接着走「确保隧道起来 → 出码」。抽出来供安装链与手动链共用,
1067
+ // 避免「装完只弹提示、还得再点一次」的伪无反应。
1068
+ async function continueRemoteAfterInstall() {
1069
+ const banner = installBanner;
1070
+ installBanner = null;
1071
+ await remoteMainAction(banner);
1072
+ }
1073
+
1074
+ async function runInstall() {
1075
+ if (installBusy) return;
1076
+ installBusy = true;
1077
+ const mainBtn = panelEl?.querySelector('#dsh-mios-remote-main');
1078
+ if (mainBtn) { mainBtn.textContent = '安装中…'; mainBtn.disabled = true; }
1079
+ // 先把确认框换成「正在安装」——用户点确认后立即有可见反馈,不进入静默等待。
1080
+ showUpdateModal({
1081
+ title: '正在安装',
1082
+ banner: { text: '⏳ 正在下载 cloudflared,请稍候', tone: 'info' },
1083
+ lines: [],
1084
+ note: '首次下载约几十 MB,取决于网速,请耐心等待,不要关闭窗口。',
1085
+ actions: [],
1086
+ });
1087
+ let succeeded = false;
1088
+ try {
1089
+ const res = await fetchJson('/mobile/v1/tunnel/install-cloudflared', { method: 'POST' }, 240000);
1090
+ await probe();
1091
+ renderSummary();
1092
+ const nowFound = summary?.tunnel?.executable === 'found';
1093
+ if (!nowFound) throw new Error('安装完成但网关尚未识别到 cloudflared,请重开面板重试');
1094
+ succeeded = true;
1095
+ showUpdateModal({
1096
+ title: '安装完成',
1097
+ banner: { text: '✅ cloudflared 已就绪,正在开启远程…', tone: 'success' },
1098
+ lines: [],
1099
+ note: res?.reused ? '本机已有 cloudflared,无需重复下载。正在为你开启远程并出码。' : 'cloudflared 已安装。正在为你开启远程并出码。',
1100
+ actions: [{ label: '立即开启远程', primary: true, onClick: () => { if (autoContinueTimer) { clearTimeout(autoContinueTimer); autoContinueTimer = null; } closeUpdateModal(); continueRemoteAfterInstall(); } }],
1101
+ });
1102
+ } catch (err) {
1103
+ showUpdateModal({
1104
+ title: '安装失败',
1105
+ banner: { text: '❌ 未能自动安装', tone: 'error' },
1106
+ lines: [],
1107
+ note: `${err?.body?.error?.message || err?.message || String(err)}。可检查网络后重试,或按提示手动安装 cloudflared。`,
1108
+ actions: [
1109
+ { label: '关闭', onClick: closeUpdateModal },
1110
+ { label: '重试安装', primary: true, onClick: () => runInstall() },
1111
+ ],
1112
+ });
1113
+ } finally {
1114
+ installBusy = false;
1115
+ renderSummary();
1116
+ // 关键修复:安装成功后自动继续出码,无需用户再点一次主按钮。
1117
+ if (succeeded) {
1118
+ if (autoContinueTimer) clearTimeout(autoContinueTimer);
1119
+ autoContinueTimer = setTimeout(() => {
1120
+ autoContinueTimer = null;
1121
+ closeUpdateModal();
1122
+ continueRemoteAfterInstall();
1123
+ }, 900);
1124
+ }
1125
+ }
1126
+ }
1127
+
1128
+ /** 远程主按钮:一条动作链走完「确保在跑 → 出码」。一次点击出码,绝不让人点两下。 */
1129
+ async function remoteMainAction(banner) {
1130
+ if (tunnelBusy || bannerBusy.remote || installBusy) return;
1131
+ const mainBtn = panelEl?.querySelector('#dsh-mios-remote-main');
1132
+ // 缺依赖且平台可自动装:先走安装确认,装完再继续开启(避免点了必然失败的 start)
1133
+ if (summary?.tunnel?.executable === 'missing' && summary?.tunnel?.canAutoInstall) {
1134
+ installCloudflaredAction(banner);
1135
+ return;
1136
+ }
1137
+ const running = summary?.tunnel?.state === 'running' && summary?.tunnel?.dnsOk !== false;
1138
+ try {
1139
+ if (!running) {
1140
+ tunnelBusy = true;
1141
+ if (mainBtn) mainBtn.textContent = '开启中…';
1142
+ let startErr = null;
1143
+ try {
1144
+ await tunnelAction('start');
1145
+ } catch (err) {
1146
+ // 客户端超时 ≠ 服务端失败:cloudflared 可能还在注册路上。
1147
+ // 不直接报错收场,继续轮询等它真的起来(或确认起不来)。
1148
+ startErr = err;
1149
+ }
1150
+ const up = await waitForTunnelUp();
1151
+ if (!up) {
1152
+ // 真没起来才报错;错误信息优先用服务端带回来的
1153
+ const t = summary?.tunnel;
1154
+ const msg = startErr?.body?.error?.message
1155
+ || (t?.dnsOk === false ? '固定域名尚未在公网生效,请稍后再试' : null)
1156
+ || startErr?.message || '远程通道未能开启';
1157
+ throw Object.assign(new Error(msg), { body: startErr?.body });
1158
+ }
1159
+ }
1160
+ bannerBusy.remote = true;
1161
+ if (mainBtn) mainBtn.textContent = '生成中…';
1162
+ mountCode(banner, await issuePairingCode('tunnel'));
1163
+ } catch (err) {
1164
+ const hint = panelEl?.querySelector('#dsh-mios-hint');
1165
+ if (hint) {
1166
+ hint.textContent = `⚠️ ${err?.body?.error?.message || err.message}`;
1167
+ hint.style.display = '';
1168
+ hint.style.color = '#d94f3d';
1169
+ }
1170
+ } finally {
1171
+ tunnelBusy = false;
1172
+ bannerBusy.remote = false;
1173
+ renderSummary();
1174
+ }
1175
+ }
1176
+
1177
+ async function stopRemoteAction() {
1178
+ if (tunnelBusy) return;
1179
+ tunnelBusy = true;
1180
+ const stopBtn = panelEl?.querySelector('#dsh-mios-remote-stop');
1181
+ if (stopBtn) stopBtn.textContent = '停止中…';
1182
+ try {
1183
+ await tunnelAction('stop');
1184
+ } catch (err) {
1185
+ const hint = panelEl?.querySelector('#dsh-mios-hint');
1186
+ if (hint) {
1187
+ hint.textContent = `⚠️ ${err?.body?.error?.message || err.message}`;
1188
+ hint.style.display = '';
1189
+ hint.style.color = '#d94f3d';
1190
+ }
1191
+ }
1192
+ // 停止即收码:远程关了,码还挂在屏幕上只会误导人去扫
1193
+ panelEl?.querySelectorAll('#dsh-mios-remote-main')
1194
+ .forEach((btn) => btn.closest('.dsh-mios-banner')?.querySelectorAll('.dsh-mios-code-slot, .err')
1195
+ .forEach((e) => e.remove()));
1196
+ await probe();
1197
+ renderSummary();
1198
+ tunnelBusy = false;
1199
+ }
1200
+
1201
+ function togglePanel() {
1202
+ if (panelEl) removePanel();
1203
+ else showPanel();
1204
+ }
1205
+
1206
+ // ── banner(slot 渲染,React 元素) ──────────────────────────
1207
+ // 注意:slot 渲染回调不是 React 组件(宿主按回调取元素),不能用 hooks;
1208
+ // 状态点读模块级 summary,新鲜度由 apply 里的轮询保证,
1209
+ // 宿主重渲侧栏时自然取到最新值。面板打开时另有主动 probe()。
1210
+
1211
+ const STATUS_OK = { stroke: '#3fb27f', fill: 'rgba(63,178,127,.18)' };
1212
+ const STATUS_DOWN = { stroke: '#d94f3d', fill: 'rgba(217,79,61,.18)' };
1213
+
1214
+ function PhoneIcon() {
1215
+ return react.createElement('svg', {
1216
+ 'aria-hidden': true, focusable: false, width: 16, height: 16,
1217
+ viewBox: '0 0 16 16', fill: 'none', stroke: 'currentColor',
1218
+ strokeWidth: 1.5, strokeLinecap: 'round', strokeLinejoin: 'round',
1219
+ },
1220
+ react.createElement('rect', { x: 4, y: 1, width: 8, height: 14, rx: 2 }),
1221
+ react.createElement('path', { d: 'M7 12h2' }));
1222
+ }
1223
+
1224
+ function apply(ctx) {
1225
+ installStyle();
1226
+
1227
+ // 注入宿主插件管理器:一步更新能力来源。可选能力——用安全读取而非硬依赖,
1228
+ // 拿不到时 pluginManager 保持 null,更新弹窗自动降级为「复制包名」手动安装。
1229
+ try {
1230
+ const remote = (typeof ctx.get === 'function' && ctx.get('remote'))
1231
+ || ctx.remote || null;
1232
+ pluginManager = remote?.pluginManager || null;
1233
+ } catch { pluginManager = null; }
1234
+
1235
+ // 跨 HMR 重载恢复:一步更新触发插件自更新会卸载本模块,弹窗随之消失。
1236
+ // 发起前把状态写入 localStorage,重载后据此显示「更新完成/进行中」反馈。
1237
+ try { restorePendingUpdate(); } catch { /* 存储不可用时跳过,不影响主流程 */ }
1238
+
1239
+ // 轮询保持 summary 新鲜(banner 状态点 + 面板数据共用)
1240
+ probeUntilUp();
1241
+ const pollTimer = setInterval(probe, 15000);
1242
+
1243
+ // 状态面板打开期间保持轮询:banner 的 useGatewayStatus 只在宿主渲染时活跃
1244
+ const disposeSlot = ctx.slots.inject('sidebar.footer.action', () =>
1245
+ ctx.slots.register(
1246
+ { name: 'sidebar.footer.action', id: 'dsh-mobile-ios' },
1247
+ ({ wide }) => {
1248
+ const ok = !!(summary && summary.ok);
1249
+ const tone = ok ? STATUS_OK : STATUS_DOWN;
1250
+ return react.createElement('button', {
1251
+ className: `dsh-mios-trigger${wide ? '' : ' is-rail'}`,
1252
+ type: 'button',
1253
+ title: PANEL_TITLE,
1254
+ 'aria-label': PANEL_TITLE,
1255
+ onClick: togglePanel,
1256
+ },
1257
+ react.createElement('span', {
1258
+ className: 'dsh-mios-dot ' + (ok ? 'ok' : 'down'),
1259
+ style: { background: tone.stroke },
1260
+ }),
1261
+ // 名称左边不再放 SVG 手机图标:wide 模式有「📱」emoji 就够了;
1262
+ // 窄栏(rail)没有名字,图标仍是唯一的视觉标识,保留。
1263
+ wide ? undefined : react.createElement(PhoneIcon),
1264
+ wide ? react.createElement('span', null, BANNER_LABEL) : undefined);
1265
+ }
1266
+ )
1267
+ );
1268
+
1269
+ return () => {
1270
+ clearInterval(pollTimer);
1271
+ disposeSlot();
1272
+ removePanel();
1273
+ document.getElementById(STYLE_ID)?.remove();
1274
+ };
1275
+ }
1276
+
1277
+ // 注意:宿主 inject 数组是「硬依赖」,缺失会让整个模块挂起(pending)。
1278
+ // remote/pluginManager 属可选能力,只声明 slots;安装服务在 apply 内安全获取。
1279
+ const inject = ['slots'];
1280
+ exports.apply = apply;
1281
+ exports.inject = inject;
1282
+ exports.__test = {
1283
+ PORT_CANDIDATES, STATUS_OK, STATUS_DOWN,
1284
+ showUpdateModal, closeUpdateModal, copyToClipboard,
1285
+ performUpdate, checkPluginUpdate, compareVersions, unwrapRemote,
1286
+ setPluginManager: (m) => { pluginManager = m; },
1287
+ setUpdateTimeout: (ms) => { UPDATE_TIMEOUT_MS = ms; },
1288
+ isUpdateInFlight: () => updateInFlight,
1289
+ restorePendingUpdate, readUpdateState, writeUpdateState, clearUpdateState,
1290
+ };
1291
+
1292
+ return module.exports;
1293
+ },
1294
+ });