dsh-plugin-weapp-gateway 0.8.61 → 0.8.65

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,1911 +1,1901 @@
1
- // Browser half of dsh-plugin-mobile-gateway. The package manifest makes this
2
- // bundle part of DSH's client-module graph; it contributes one Settings
3
- // section that opens the management dialog, without replacing shipped UI seats.
4
- window.__ModuleLoader__.load({
5
- id: 'dsh-plugin-weapp-gateway',
6
- factory: (require) => {
7
- const React = require('react')
8
- const module = { exports: {} }
9
- const exports = module.exports
10
-
11
- let open = false
12
- const listeners = new Set()
13
- const setOpen = (value) => {
14
- open = value
15
- for (const listener of listeners) listener()
16
- }
17
- const subscribe = (listener) => {
18
- listeners.add(listener)
19
- return () => listeners.delete(listener)
20
- }
21
- const getOpen = () => open
22
-
23
- // 侧边栏入口开关:由管理接口 /mgw/ui 持久化;apply() 时读取一次,
24
- // 面板内切换后立即通知侧边栏按钮显示/隐藏。
25
- let sidebarEntry = true
26
- const sidebarListeners = new Set()
27
- const getSidebarEntry = () => sidebarEntry
28
- const setSidebarEntry = (value) => {
29
- const next = value !== false
30
- if (next === sidebarEntry) return
31
- sidebarEntry = next
32
- for (const listener of sidebarListeners) listener()
33
- }
34
- const subscribeSidebar = (listener) => {
35
- sidebarListeners.add(listener)
36
- return () => sidebarListeners.delete(listener)
37
- }
38
-
39
- // Shared Web UI / Desktop semantic tokens update with the host theme.
40
- const restartNoticeStorageKey = 'mobile-gateway-dismissed-restart-notice'
41
- let dismissedRestartInstance = null
42
- try { dismissedRestartInstance = window.localStorage.getItem(restartNoticeStorageKey) } catch { /* storage unavailable */ }
43
-
44
- const colors = {
45
- panel: 'var(--dsw-alias-bg-layer-2, var(--color-bg, Canvas))',
46
- card: 'var(--dsw-alias-bg-module-platform, var(--color-bg-elevated, Canvas))',
47
- text: 'var(--dsw-alias-label-primary, var(--color-text, CanvasText))',
48
- muted: 'var(--dsw-alias-label-secondary, var(--color-text-muted, GrayText))',
49
- border: 'var(--dsw-alias-border-l3, var(--color-border, rgba(127,127,127,.24)))',
50
- accent: 'var(--dsw-alias-button-primary-fill, var(--color-primary, #4f7cff))',
51
- accentText: 'var(--dsw-alias-label-primary-foreground, #fff)',
52
- danger: 'var(--dsw-alias-state-error-primary, #dc4c64)',
53
- success: 'var(--dsw-alias-state-success-primary, #2fb171)',
54
- }
55
- const styles = {
56
- backdrop: {
57
- position: 'fixed', inset: 0, zIndex: 1200, pointerEvents: 'auto',
58
- background: 'var(--dsw-alias-bg-mask-1, rgba(0,0,0,.32))', display: 'flex',
59
- justifyContent: 'center', alignItems: 'center',
60
- padding: 'max(16px, var(--dsh-frame-overlay-top, 16px)) 16px', boxSizing: 'border-box',
61
- },
62
- panel: {
63
- width: 'clamp(640px, 84vw, 1120px)', maxWidth: '100%', maxHeight: '100%', minHeight: 0, height: 'min(780px, calc(100dvh - 48px))', overflow: 'hidden',
64
- scrollbarWidth: 'none', msOverflowStyle: 'none',
65
- display: 'flex', flexDirection: 'column',
66
- background: colors.panel, color: colors.text, border: `1px solid ${colors.border}`, borderRadius: 'var(--dsw-radius-panel, 16px)',
67
- boxShadow: 'var(--dsw-elevation-prominent, 0 20px 60px rgba(0,0,0,.22))', padding: 24,
68
- fontFamily: 'var(--dsw-font-family, system-ui, sans-serif)', fontSize: 13, boxSizing: 'border-box',
69
- },
70
- header: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18, flexShrink: 0 },
71
- title: { margin: 0, fontSize: 22, fontWeight: 650 },
72
- card: { background: 'transparent', border: 0, borderBottom: `1px solid ${colors.border}`, borderRadius: 0, padding: '16px 0', marginBottom: 0, flexShrink: 0 },
73
- label: { display: 'block', color: colors.muted, fontSize: 12, marginBottom: 6 },
74
- input: { width: '100%', boxSizing: 'border-box', border: `1px solid ${colors.border}`, borderRadius: 10, padding: '8px 12px', marginBottom: 8, background: colors.card, color: 'inherit', outline: 'none' },
75
- pairingText: { width: '100%', minHeight: 86, boxSizing: 'border-box', resize: 'vertical', border: `1px solid ${colors.border}`, borderRadius: 8, padding: '9px 10px', margin: '10px 0', background: 'transparent', color: 'inherit', outline: 'none', fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace', fontSize: 11, lineHeight: 1.45, overflowWrap: 'anywhere' },
76
- button: { cursor: 'pointer', border: `1px solid ${colors.border}`, background: 'transparent', borderRadius: 8, padding: '7px 11px', color: 'inherit', font: 'inherit' },
77
- headerButton: { width: 34, height: 34, boxSizing: 'border-box', border: 0, padding: 0, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 },
78
- primary: { background: colors.accent, color: colors.accentText, borderColor: colors.accent, width: '100%' },
79
- muted: { color: colors.muted, fontSize: 12, lineHeight: 1.45 },
80
- row: { display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) auto', columnGap: 12, alignItems: 'center', padding: '12px 0', borderBottom: `1px solid ${colors.border}` },
81
- badge: { display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11, marginLeft: 8, color: colors.muted },
82
- dot: { width: 7, height: 7, borderRadius: 99, display: 'inline-block' },
83
- error: { color: colors.danger, background: 'rgba(220,76,100,.12)', borderRadius: 8, padding: 10, marginBottom: 12 },
84
- qr: { display: 'block', width: 220, height: 220, margin: '12px auto', background: '#fff', borderRadius: 10, padding: 8 },
85
- helpButton: { width: 20, height: 20, boxSizing: 'border-box', padding: 0, borderRadius: '50%', border: 0, background: 'var(--dsw-alias-interactive-bg-hover, rgba(127,127,127,.1))', color: 'var(--dsw-alias-label-tertiary, #888)', cursor: 'help', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, fontSize: 12, fontWeight: 600, lineHeight: 1 },
86
- helpBubble: { position: 'absolute', top: '100%', left: 0, zIndex: 20, width: 'min(300px, calc(100vw - 88px))', maxHeight: 'min(440px, calc(100vh - 160px))', overflowY: 'auto', boxSizing: 'border-box', padding: 12, borderRadius: 10, border: `1px solid ${colors.border}`, background: colors.panel, color: colors.text, boxShadow: '0 12px 28px rgba(0,0,0,.35)', fontSize: 12, lineHeight: 1.5 },
87
- toolsMenu: { position: 'absolute', top: 'calc(100% + 6px)', right: 0, zIndex: 30, width: 250, maxWidth: 'calc(100vw - 48px)', border: `1px solid ${colors.border}`, borderRadius: 10, padding: 5, background: colors.panel, boxShadow: '0 12px 28px rgba(0,0,0,.35)' },
88
- toolsItem: { display: 'block', width: '100%', padding: '9px 10px', textAlign: 'left', border: 0, borderRadius: 7, background: 'transparent', color: colors.text, font: 'inherit', cursor: 'pointer' },
89
- switch: { position: 'relative', display: 'inline-flex', width: 42, height: 24, flexShrink: 0 },
90
- switchInput: { position: 'absolute', opacity: 0, width: 1, height: 1 },
91
- switchTrack: { position: 'absolute', inset: 0, borderRadius: 99, transition: 'background .18s ease', cursor: 'pointer' },
92
- switchKnob: { position: 'absolute', top: 3, width: 18, height: 18, borderRadius: 99, background: '#fff', boxShadow: '0 1px 3px rgba(0,0,0,.35)', transition: 'left .18s ease', pointerEvents: 'none' },
93
- version: { flexShrink: 0, marginTop: 'auto', padding: '18px 2px 0', color: colors.muted, fontSize: 11, lineHeight: 1.4, textAlign: 'right', letterSpacing: '.02em' },
94
- }
95
-
96
- const panelCss = `
97
- @keyframes mgw-pairing-enter {
98
- from { opacity: 0; transform: scale(.82); }
99
- to { opacity: 1; transform: scale(1); }
100
- }
101
- .mgw-pairing-dialog {
102
- transform-origin: center;
103
- animation: mgw-pairing-enter 240ms cubic-bezier(.2, .8, .2, 1);
104
- }
105
- @keyframes mgw-pairing-exit {
106
- from { opacity: 1; transform: scale(1); }
107
- to { opacity: 0; transform: scale(.82); }
108
- }
109
- .mgw-pairing-dialog[data-closing="true"] {
110
- animation: mgw-pairing-exit 180ms ease-in forwards;
111
- pointer-events: none;
112
- }
113
- @media (prefers-reduced-motion: reduce) {
114
- .mgw-pairing-dialog { animation: none; }
115
- }
116
- .mobile-gateway-panel, .mobile-gateway-panel *, .mgw-pairing-dialog, .mgw-pairing-dialog *, .mgw-select-menu {
117
- scrollbar-width: none !important;
118
- -ms-overflow-style: none;
119
- }
120
- .mobile-gateway-panel::-webkit-scrollbar, .mobile-gateway-panel *::-webkit-scrollbar,
121
- .mgw-pairing-dialog::-webkit-scrollbar, .mgw-pairing-dialog *::-webkit-scrollbar, .mgw-select-menu::-webkit-scrollbar {
122
- display: none !important;
123
- width: 0;
124
- height: 0;
125
- }
126
- .mobile-gateway-panel .mgw-body { display: grid; grid-template-columns: 180px minmax(0, 1fr); gap: 28px; flex: 1; min-height: 0; }
127
- .mobile-gateway-panel .mgw-nav { display: flex; flex-direction: column; gap: 4px; }
128
- .mobile-gateway-panel .mgw-nav button { text-align: left; border: 0; padding: 12px 14px; border-radius: 10px; background: transparent; color: inherit; font: inherit; cursor: pointer; }
129
- .mobile-gateway-panel .mgw-nav button[aria-current="page"] { background: var(--dsw-alias-bg-overlay, rgba(127,127,127,.12)); font-weight: 500; }
130
- .mobile-gateway-panel .mgw-nav button:hover { background: var(--dsw-alias-interactive-bg-hover, rgba(127,127,127,.08)); }
131
- .mobile-gateway-panel .mgw-content { min-width: 0; overflow-y: auto; scrollbar-width: none; padding-right: 4px; }
132
- .mobile-gateway-panel .mgw-content::-webkit-scrollbar { display: none; }
133
- .mobile-gateway-panel .mgw-content p { margin: 6px 0 10px; }
134
- .mobile-gateway-panel strong { font-weight: 550; }
135
- .mobile-gateway-panel .mgw-device-permissions > summary::-webkit-details-marker { display: none; }
136
- .mobile-gateway-panel .mgw-device-permissions[open] > summary .mgw-permissions-chevron { transform: rotate(90deg); }
137
- .mobile-gateway-panel .mgw-section-title { margin: 0 0 10px; font-size: 17px; line-height: 1.4; font-weight: 650; color: inherit; }
138
- .mobile-gateway-panel .mgw-setting-row { display: flex; flex-direction: column; align-items: flex-start; gap: 8px; margin-bottom: 12px; }
139
- .mobile-gateway-panel .mgw-setting-row select { width: auto !important; max-width: 100%; min-width: 150px; margin-bottom: 0 !important; flex-shrink: 1; }
140
- .mobile-gateway-panel .mgw-cloudflare-block input, .mobile-gateway-panel .mgw-cloudflare-block .mgw-select-trigger { background: var(--dsw-alias-bg-layer-2, Canvas) !important; }
141
- .mobile-gateway-panel .mgw-setting-label { font-size: 14px; font-weight: 550; color: inherit; }
142
-
143
- .mobile-gateway-panel input:focus-visible, .mobile-gateway-panel select:focus-visible, .mobile-gateway-panel button:focus-visible { outline: 2px solid var(--dsw-alias-label-primary, currentColor); outline-offset: 2px; }
144
- @media (max-width: 640px) {
145
- .mobile-gateway-panel .mgw-body { grid-template-columns: minmax(0, 1fr); gap: 8px; }
146
- /* Fork: the dialog nav is not the settings rail — keep it a tab strip.
147
- dsh-settings-mobile-nav collapses the first <nav> of any settings
148
- dialog, which used to swallow ours and leave a lone expand button.
149
- A stable height plus the marker below opts out. */
150
- .mobile-gateway-panel .mgw-nav { flex-direction: row; flex-wrap: nowrap; }
151
- .mobile-gateway-panel .mgw-nav button {
152
- flex: 1 1 0; min-width: 0; min-height: 40px; height: 40px;
153
- padding: 8px 6px; text-align: center; white-space: nowrap;
154
- overflow: hidden; text-overflow: ellipsis;
155
- }
156
- }
157
- `
158
-
159
- function GatewaySelect({ style, children, value, onChange, disabled, ...props }) {
160
- const options = React.Children.toArray(children).filter((child) => React.isValidElement(child))
161
- const [menu, setMenu] = React.useState(null)
162
- const [active, setActive] = React.useState(0)
163
- const buttonRef = React.useRef(null)
164
- const menuRef = React.useRef(null)
165
- const menuId = React.useId()
166
- const selected = options.find((option) => option.props.value === value)
167
- const enabled = options.map((option, index) => option.props.disabled ? -1 : index).filter((index) => index >= 0)
168
- const close = (restoreFocus = false) => {
169
- setMenu(null)
170
- if (restoreFocus) buttonRef.current?.focus()
171
- }
172
- const openMenu = () => {
173
- if (disabled) return
174
- const rect = buttonRef.current.getBoundingClientRect()
175
- const computed = window.getComputedStyle(buttonRef.current)
176
- const fontSize = parseFloat(computed.fontSize) || 14
177
- const lineHeight = parseFloat(computed.lineHeight) || fontSize * 1.5
178
- const measure = document.createElement('canvas').getContext('2d')
179
- if (measure) measure.font = computed.font || `${fontSize}px sans-serif`
180
- const longest = Math.max(...options.map((option) => measure
181
- ? measure.measureText(String(option.props.children)).width : String(option.props.children).length * fontSize))
182
- const height = Math.min(options.length * Math.max(40, lineHeight + 16) + 14, window.innerHeight - 24)
183
- const width = Math.min(Math.max(rect.width, longest + 72, 200), window.innerWidth - 24)
184
- setActive(Math.max(0, options.findIndex((option) => option.props.value === value && !option.props.disabled)))
185
- setMenu({ left: Math.max(12, Math.min(rect.left, window.innerWidth - width - 12)),
186
- top: Math.max(12, rect.bottom + height + 6 <= window.innerHeight - 12 ? rect.bottom + 6 : rect.top - height - 6), width, maxHeight: window.innerHeight - 24 })
187
- }
188
- const choose = (index) => {
189
- const option = options[index]
190
- if (!option || option.props.disabled) return
191
- onChange?.({ target: { value: option.props.value } })
192
- close(true)
193
- }
194
- React.useEffect(() => {
195
- if (!menu) return
196
- menuRef.current?.focus()
197
- const outside = (event) => {
198
- if (!buttonRef.current?.contains(event.target) && !menuRef.current?.contains(event.target)) close()
199
- }
200
- const scrolled = (event) => { if (!menuRef.current?.contains(event.target)) close() }
201
- const resized = () => close()
202
- document.addEventListener('pointerdown', outside)
203
- document.addEventListener('scroll', scrolled, true)
204
- window.addEventListener('resize', resized)
205
- return () => {
206
- document.removeEventListener('pointerdown', outside)
207
- document.removeEventListener('scroll', scrolled, true)
208
- window.removeEventListener('resize', resized)
209
- }
210
- }, [menu])
211
- React.useEffect(() => {
212
- if (menu) document.getElementById(`${menuId}-${active}`)?.scrollIntoView({ block: 'nearest' })
213
- }, [active, menu])
214
- return React.createElement('span', { style: { display: 'inline-flex', maxWidth: '100%', minWidth: 0 } },
215
- React.createElement('button', { ...props, className: 'mgw-select-trigger', ref: buttonRef, type: 'button', disabled,
216
- 'aria-haspopup': 'listbox', 'aria-expanded': !!menu, 'aria-controls': menu ? menuId : undefined,
217
- onClick: () => menu ? close() : openMenu(),
218
- onKeyDown: (event) => {
219
- if (['ArrowDown', 'ArrowUp'].includes(event.key)) { event.preventDefault(); openMenu() }
220
- },
221
- style: { ...style, width: 'auto', maxWidth: '100%', marginBottom: 0, border: 0, borderRadius: 12,
222
- padding: '10px 16px', background: colors.card, color: colors.text, font: 'inherit', cursor: disabled ? 'default' : 'pointer',
223
- display: 'inline-flex', alignItems: 'center', gap: 18, opacity: disabled ? .5 : 1 } },
224
- React.createElement('span', { style: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, selected?.props.children || value),
225
- React.createElement('svg', { width: 14, height: 14, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor',
226
- strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true, style: { flexShrink: 0 } },
227
- React.createElement('path', { d: 'M6 9l6 6 6-6' }))),
228
- menu ? React.createElement('div', { className: 'mgw-select-menu', ref: menuRef, id: menuId, role: 'listbox', tabIndex: -1,
229
- 'aria-label': props['aria-label'], 'aria-activedescendant': `${menuId}-${active}`,
230
- style: { ...menu, position: 'fixed', zIndex: 1250, boxSizing: 'border-box', overflowY: 'auto', padding: 6,
231
- background: colors.panel, color: colors.text, border: `1px solid ${colors.border}`, borderRadius: 14,
232
- boxShadow: 'var(--dsw-elevation-prominent, 0 8px 28px rgba(0,0,0,.12))', outline: 'none' },
233
- onKeyDown: (event) => {
234
- if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); close(true) }
235
- else if (event.key === 'Tab') close()
236
- else if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); choose(active) }
237
- else if (['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) {
238
- event.preventDefault()
239
- const index = enabled.indexOf(active)
240
- setActive(event.key === 'Home' ? enabled[0] : event.key === 'End' ? enabled[enabled.length - 1]
241
- : enabled[(index + (event.key === 'ArrowDown' ? 1 : -1) + enabled.length) % enabled.length])
242
- }
243
- } }, options.map((option, index) => React.createElement('div', { key: option.props.value,
244
- id: `${menuId}-${index}`, role: 'option', 'aria-selected': option.props.value === value, 'aria-disabled': !!option.props.disabled,
245
- onPointerMove: () => { if (!option.props.disabled) setActive(index) }, onClick: () => choose(index),
246
- style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, minHeight: 40, whiteSpace: 'nowrap',
247
- boxSizing: 'border-box', padding: '8px 12px', borderRadius: 8, cursor: option.props.disabled ? 'default' : 'pointer',
248
- opacity: option.props.disabled ? .4 : 1, background: active === index ? 'var(--dsw-alias-interactive-bg-hover, rgba(127,127,127,.08))' : 'transparent' } },
249
- React.createElement('span', { style: { minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis' }, title: String(option.props.children) }, option.props.children), option.props.value === value ? React.createElement('svg', { width: 16, height: 16, viewBox: '0 0 24 24',
250
- fill: 'none', stroke: 'currentColor', strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true, style: { flexShrink: 0 } },
251
- React.createElement('path', { d: 'M5 12l4 4L19 6' })) : null))) : null)
252
- }
253
-
254
- // --------------------------------------------------------------------------
255
- // Settings-nav glyph, pinned by the plugin itself.
256
- //
257
- // The `settings.section` contract carries no icon field — the core reads
258
- // only id/label/order and `navIcon(id)` falls back to the gear for every
259
- // unknown id. Patching that core bundle is not durable: a DSH runtime
260
- // re-extract, or any other plugin installing/removing its own patch, wipes
261
- // it. So this plugin pins its own glyph at runtime instead.
262
- //
263
- // It finds its nav cell by label text and rewrites the existing <svg> in
264
- // place, keeping the shell's element, class and box — nothing here depends
265
- // on the shell's hashed class names, so a DSH upgrade cannot break it. A
266
- // MutationObserver re-applies the glyph whenever the shell re-renders the
267
- // nav and restores the gear.
268
- //
269
- // `glyph()` is pure and returns the markup: it runs BEFORE any DOM mutation,
270
- // so a throwing glyph leaves the shell's own icon in place rather than
271
- // blanking the cell.
272
- // --------------------------------------------------------------------------
273
- const NAV_LABEL = '鲸尾网关助手'
274
- const NAV_ICON_MARK = 'data-mgw-nav-icon'
275
-
276
- function navGlyph() {
277
- return {
278
- viewBox: '0 0 24 24',
279
- stroke: 'currentColor',
280
- markup: '<rect x="6" y="2" width="12" height="20" rx="2.5"></rect><path d="M10 18h4"></path>',
281
- }
282
- }
283
-
284
- function pinNavGlyph(labels, mark, glyph) {
285
- if (typeof document === 'undefined' || typeof MutationObserver === 'undefined') return
286
- const apply = () => {
287
- // Cheap guard: the nav only exists while the settings panel is open.
288
- if (document.querySelector('[role="dialog"]') === null) return
289
- const cells = document.querySelectorAll('[role="dialog"] nav button')
290
- for (const cell of cells) {
291
- // An <svg> contributes no text, so this is exactly the nav label.
292
- if (labels.indexOf(cell.textContent.trim()) < 0) continue
293
- const svg = cell.querySelector('svg')
294
- if (svg === null || svg.getAttribute(mark) === '1') continue
295
- let spec
296
- try {
297
- spec = glyph()
298
- } catch (error) {
299
- console.warn('[dsh-plugin-weapp-gateway] nav glyph failed; keeping the shell icon', error)
300
- continue
301
- }
302
- svg.setAttribute('viewBox', spec.viewBox)
303
- svg.setAttribute('fill', 'none')
304
- if (spec.stroke) {
305
- svg.setAttribute('stroke', spec.stroke)
306
- svg.setAttribute('stroke-width', spec.strokeWidth || '1.8')
307
- svg.setAttribute('stroke-linecap', 'round')
308
- svg.setAttribute('stroke-linejoin', 'round')
309
- }
310
- svg.innerHTML = spec.markup
311
- svg.setAttribute('aria-hidden', 'true')
312
- svg.setAttribute(mark, '1')
313
- }
314
- }
315
- apply()
316
- // The shell re-renders the nav on ledger/locale changes; without this the
317
- // gear would come back on the next re-render.
318
- new MutationObserver(apply).observe(document.body, { childList: true, subtree: true })
319
- }
320
-
321
- // Fork: management RPC must resolve against the document base, not the
322
- // origin root. Behind the fnOS gateway the whole WebUI is served under
323
- // /app/deepseek-harness/fngateway/, where an absolute /mgw/... request
324
- // hits the gateway's own router and 404s. DSH serves its own assets
325
- // document-relative for exactly this reason.
326
- function apiPath(path) {
327
- let base = '/'
328
- try { base = new URL('.', document.baseURI).pathname } catch { base = '/' }
329
- if (!base.endsWith('/')) base += '/'
330
- return base + String(path).replace(/^\/+/, '')
331
- }
332
-
333
- async function request(path, options) {
334
- const response = await fetch(apiPath(path), { credentials: 'same-origin', ...options })
335
- const body = await response.json().catch(() => ({}))
336
- if (!response.ok) throw new Error(body.message || body.error || `HTTP ${response.status}`)
337
- return body
338
- }
339
-
340
- function inferredUrl(wsPath) {
341
- const scheme = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
342
- return `${scheme}//${window.location.host}${wsPath || '/ws/mobile'}`
343
- }
344
-
345
- function lanPairingUrl(status) {
346
- const urls = status?.lan?.listening && Array.isArray(status.lan.urls) ? status.lan.urls : []
347
- return urls.find((url) => !/^ws:\/\/169\.254\./.test(url)) || urls[0] || ''
348
- }
349
-
350
- function pairingUrlFor(route, status) {
351
- const lanUrl = lanPairingUrl(status)
352
- const tunnelUrl = status.cloudflare?.enabled && status.cloudflare.publicReady === true
353
- ? status.cloudflare.publicUrl || '' : ''
354
- if (route === 'lan') return lanUrl
355
- if (route === 'relay') return status.relay?.relay || ''
356
- if (route === 'cloudflare') return tunnelUrl
357
- if (route === 'tailscale') return status.tailscale?.serveUrl || status.tailscale?.urls?.[0] || ''
358
- const statusUrl = status.cloudflare?.enabled && status.cloudflare.publicReady !== true &&
359
- status.publicUrl === status.cloudflare.publicUrl ? '' : status.publicUrl
360
- return tunnelUrl || statusUrl || lanUrl || inferredUrl(status.wsPath)
361
- }
362
-
363
- // 从手动输入里取主机:支持 `100.x.x.x`、`ws://100.x.x.x:3081/ws/mobile`、
364
- // 以及带方括号的 IPv6。用于 Tailscale 路线的手动填写校验与补全。
365
- function tailscaleHostOf(value) {
366
- let raw = String(value || '').trim()
367
- if (!raw) return ''
368
- raw = raw.replace(/^(?:wss?|https?):\/\//i, '')
369
- raw = raw.split(/[/?#]/)[0]
370
- raw = raw.replace(/^\[|\]$/g, '')
371
- return raw.replace(/:\d+$/, '')
372
- }
373
-
374
- function isTailscaleInput(value) {
375
- const host = tailscaleHostOf(value)
376
- if (!host) return false
377
- if (/\.ts\.net$/i.test(host)) return true
378
- const octets = host.split('.').map(Number)
379
- if (octets.length === 4 && octets.every((part) => Number.isInteger(part) && part >= 0 && part <= 255)) {
380
- return octets[0] === 100 && octets[1] >= 64 && octets[1] <= 127
381
- }
382
- return /^fd7a:115c:a1e0:/i.test(host)
383
- }
384
-
385
- // 与上游一致的连接方案摘要:按所选入口给出「配对入口 + 提示」。
386
- function appConnectionPlan(route, status, rawUrl) {
387
- const lanUrl = lanPairingUrl(status)
388
- if (route === 'auto') {
389
- return {
390
- valid: !!lanUrl,
391
- entry: '自动选择(公网优先,局域网兜底)',
392
- note: lanUrl ? '手机会按实际连通情况在公网与局域网之间自动切换。' : '局域网入口不可用;自动选择需要一个手机可访问的局域网或公网入口。',
393
- }
394
- }
395
- if (route === 'lan') {
396
- return {
397
- valid: !!lanUrl,
398
- entry: '局域网直连',
399
- note: lanUrl ? '同一局域网可直接访问;离开该网络就无法直连。' : '局域网入口不可用,请先开启基本设置中的局域网入口。',
400
- }
401
- }
402
- if (route === 'cloudflare') {
403
- const ready = !!(status?.cloudflare?.enabled && status.cloudflare.publicReady === true && status.cloudflare.publicUrl)
404
- return {
405
- valid: ready,
406
- entry: 'Cloudflare Tunnel',
407
- note: ready ? '公网入口已验证可达;手机在任何网络都可尝试。' : '公网入口尚未验证通过,请先完成下方配置和检测。',
408
- }
409
- }
410
- if (route === 'tailscale') {
411
- const serveUrl = status?.tailscale?.serveUrl || ''
412
- const valid = !!((serveUrl && String(rawUrl || '').trim() === serveUrl) || (status?.lan?.listening && isTailscaleInput(rawUrl)))
413
- return {
414
- valid,
415
- entry: 'Tailscale 内嵌隧道',
416
- note: valid
417
- ? '手机经 App 内嵌隧道连接网关节点(不占用系统 VPN,局域网不可用时仍可用)。'
418
- : '可一键使用网关内置隧道地址;也可填写主机 Tailscale 100.x 地址。',
419
- }
420
- }
421
- // custom:按地址特征给提示(与上游 pairingConnectionPlan 同一判定思路)。
422
- const raw = String(rawUrl || '').trim()
423
- let endpoint
424
- try { endpoint = new URL(raw) } catch {
425
- return { valid: false, entry: '等待填写有效的配对地址', note: '请输入手机能够访问的 ws:// 或 wss:// 地址。' }
426
- }
427
- const scheme = endpoint.protocol === 'http:' ? 'ws:' : endpoint.protocol === 'https:' ? 'wss:' : endpoint.protocol
428
- const host = endpoint.hostname.replace(/^\[|\]$/g, '').toLowerCase()
429
- const parts = host.split('.').map(Number)
430
- const ipv4 = parts.length === 4 && parts.every((n) => Number.isInteger(n) && n >= 0 && n <= 255)
431
- const loopback = host === 'localhost' || host === '::1' || (ipv4 && parts[0] === 127)
432
- const privateHost = loopback || host.endsWith('.local') ||
433
- (ipv4 && (parts[0] === 10 || (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) ||
434
- (parts[0] === 192 && parts[1] === 168) || (parts[0] === 169 && parts[1] === 254))) ||
435
- (host.includes(':') && /^(fc|fd|fe80:)/.test(host))
436
- if (!['ws:', 'wss:'].includes(scheme) || endpoint.username || endpoint.password || endpoint.search || endpoint.hash ||
437
- raw.length > 2048 || ['0.0.0.0', '::'].includes(host) || (scheme === 'ws:' && !privateHost)) {
438
- return { valid: false, entry: '配对地址需要修改', note: '公网地址必须使用 wss://;地址不能包含账号、查询参数或片段。' }
439
- }
440
- const entry = loopback ? '本机回环地址' : privateHost ? '局域网或子网路由' : '加密 WebSocket 入口'
441
- let note = '配对地址已填写,手机是否可达仍需实际连接确认。'
442
- if (loopback) note = '回环地址仅适用于本机模拟器;真机请填写电脑的局域网、Tailscale 或公网地址。'
443
- else if (privateHost) note = '同一局域网可直接访问;异地访问此地址需要手机已有可用的子网路由。'
444
- return { valid: true, entry, note }
445
- }
446
-
447
- // 手动输入的裸 IP 补成 ws://<ip>:<lanPort><wsPath>;已是 URL 的原样返回。
448
- function tailscaleEndpointOf(value, status) {
449
- const raw = String(value || '').trim()
450
- if (!raw) return ''
451
- if (/^(?:wss?|https?):\/\//i.test(raw)) return raw
452
- const port = status?.lan?.port || 3081
453
- const wsPath = status?.wsPath || '/ws/mobile'
454
- const host = raw.includes(':') ? `[${raw.replace(/^\[|\]$/g, '')}]` : raw
455
- return `ws://${host}:${port}${wsPath}`
456
- }
457
-
458
- // Tailscale 内嵌隧道:地址自动填入,无需用户手填。
459
- function tailscaleServeUrl(status) {
460
- return status?.tailscale?.serveUrl || ''
461
- }
462
-
463
- function connectionAdvice(status, publicSetup) {
464
- if (!status) return { detected: '正在读取网关环境…', local: '', remote: '' }
465
- const system = status.platform === 'darwin' ? 'macOS 电脑' : status.platform === 'win32' ? 'Windows 电脑' : status.platform === 'linux' ? 'Linux 服务器' : '当前设备'
466
- const lanReady = !!lanPairingUrl(status)
467
- const tunnel = status.cloudflare
468
- const tunnelReady = !!(tunnel?.enabled && tunnel.publicReady === true && tunnel.publicUrl)
469
- const statusUrlIsUnreadyTunnel = !!(tunnel?.enabled && tunnel.publicReady !== true &&
470
- status.publicUrl === tunnel.publicUrl)
471
- const serverReady = status.platform === 'linux' && !!(
472
- (publicSetup?.configured && publicSetup.publicUrl) || (!statusUrlIsUnreadyTunnel && /^wss:\/\//.test(status.publicUrl || '')))
473
- const detected = `当前检测:${system};局域网入口${lanReady ? '已就绪' : '未就绪'};Tailscale 地址${status.tailscale?.urls?.length ? '可用' : '未检测到'};${serverReady ? '公网服务器入口已配置' : tunnelReady ? `${tunnel.mode === 'quick' ? 'Quick' : '命名'} Tunnel 已连接` : tunnel?.enabled ? (tunnel.state === 'online' ? '隧道已连接,公网入口未验证或检测失败' : 'Cloudflare Tunnel 连接中') : '外网入口未连接'}。`
474
- const local = lanReady
475
- ? 'DSH App 和小程序都可以通过局域网或 VPN 连接;手机与 DSH 同网时可使用局域网地址。'
476
- : '两种客户端都可使用局域网连接;先确认局域网入口已开启并监听成功。'
477
- let remote
478
- if (serverReady) remote = '两种客户端在外网时都可使用已配置的公网 WSS;自动选择会同时保留局域网候选地址。'
479
- else if (tunnelReady && tunnel.mode === 'named') remote = '两种客户端在外网时都可使用固定域名的 Cloudflare Tunnel;自动选择也会保留局域网候选地址。'
480
- else if (tunnelReady) remote = '两种客户端在外网时都可使用 Cloudflare Quick Tunnel;地址变化后需重新配对。'
481
- else if (status.platform === 'darwin' || status.platform === 'win32') remote = '外网使用可开启 Quick Tunnel;需要固定地址时可配置命名 Tunnel。'
482
- else if (status.platform === 'linux') remote = '外网使用可配置 Linux 公网入口或 Cloudflare Tunnel。'
483
- else remote = '外网连接需要可访问的 wss:// 公网地址;两种客户端都支持公网或局域网。'
484
- return { detected, local, remote }
485
- }
486
-
487
- // 可信设备徽标:按手机当前连接入口标注 局域网 / 公网 / Cloudflare 外网。
488
- // routes 来自 /mgw/devices 的实时连接统计,面板每 3 秒轮询,手机切网后
489
- // 重连即换徽标;离线设备没有连接,不显示线路徽标。
490
- const ROUTE_BADGES = {
491
- lan: { label: '局域网', color: colors.success, title: '手机当前通过局域网直连(同一 Wi-Fi 或 VPN)' },
492
- public: { label: '公网', color: 'var(--dsw-alias-link, #4176e6)', title: '手机当前通过公网入口连接(公网服务器或鲸尾中继)' },
493
- cloudflare: { label: 'Cloudflare 外网', color: 'var(--dsw-alias-state-warning-primary, #d98324)', title: '手机当前通过 Cloudflare Tunnel 外网连接' },
494
- }
495
- function routeBadges(device) {
496
- if (!device || !device.online || !Array.isArray(device.routes)) return []
497
- return device.routes.map((route) => ROUTE_BADGES[route]).filter(Boolean)
498
- }
499
-
500
- // 服务端网络检测:向每条已鉴权移动连接发一次 WebSocket ping,展示协议 RTT。
501
- // 数据来自管理接口 POST /mgw/network-test(loopback);页面可见时每两秒刷新,
502
- // 进入后台或关闭面板即停止。RTT 只反映网关到手机的协议往返,不是业务处理耗时。
503
- function ServerNetworkDiagnostics() {
504
- const [snapshot, setSnapshot] = React.useState(null)
505
- const [failure, setFailure] = React.useState('')
506
- const [running, setRunning] = React.useState(typeof document === 'undefined' ? false : !document.hidden)
507
- React.useEffect(() => {
508
- if (typeof document === 'undefined') return undefined
509
- let mounted = true, timer, controller, generation = 0
510
- const stop = () => { generation++; window.clearTimeout(timer); controller?.abort() }
511
- const sample = async (lease) => {
512
- if (!mounted || document.hidden || generation !== lease) return
513
- controller = new AbortController()
514
- try {
515
- const data = await request('/mgw/network-test', { method: 'POST', signal: controller.signal })
516
- if (mounted && generation === lease) { setSnapshot(data); setFailure('') }
517
- } catch (cause) {
518
- if (mounted && generation === lease && cause.name !== 'AbortError') setFailure(cause.message)
519
- } finally {
520
- if (mounted && generation === lease && !document.hidden) timer = window.setTimeout(() => sample(lease), 2000)
521
- }
522
- }
523
- const visibility = () => {
524
- stop()
525
- setRunning(!document.hidden)
526
- if (!document.hidden) { setSnapshot(null); void sample(generation) }
527
- }
528
- document.addEventListener('visibilitychange', visibility)
529
- if (!document.hidden) void sample(generation)
530
- return () => { mounted = false; stop(); document.removeEventListener('visibilitychange', visibility) }
531
- }, [])
532
- const number = (value) => Number.isFinite(value) ? `${value.toFixed(1)} ms` : '—'
533
- const statusLabel = (value) => ({ ok: '正常', timeout: '探测超时', disconnected: '已断开', error: '检测失败', unavailable: '暂无有效样本', cancelled: '已停止' })[value] || '暂无有效样本'
534
- const channelLabel = (value) => ({ control: '控制通道', conversation: '会话通道', legacy: '兼容通道' })[value] || '兼容通道'
535
- const chart = (channel) => {
536
- const points = channel.samples || []
537
- const end = snapshot.at
538
- const maximum = Math.max(1, ...points.map((point) => point.rttMs || 0)) * 1.15
539
- const paths = []; let segment = []
540
- const flush = () => { if (segment.length) paths.push(segment.join(' ')); segment = [] }
541
- for (const point of points) {
542
- if (!Number.isFinite(point.rttMs)) { flush(); continue }
543
- segment.push(`${Math.max(0, (point.at - end + 60000) / 60000 * 300)},${70 - point.rttMs / maximum * 65}`)
544
- }
545
- flush()
546
- return React.createElement('svg', { viewBox: '0 0 300 78', preserveAspectRatio: 'none', role: 'img', 'aria-label': '服务端最近一分钟 RTT', style: { width: '100%', height: 86, display: 'block' } },
547
- [5, 38, 70].map((y) => React.createElement('line', { key: y, x1: 0, x2: 300, y1: y, y2: y, stroke: colors.border, strokeWidth: .6 })),
548
- paths.map((points, index) => React.createElement('polyline', { key: index, points, fill: 'none', stroke: 'var(--dsw-alias-link, #4176e6)', strokeWidth: 1.5 })),
549
- (points.filter((point) => Number.isFinite(point.rttMs)).slice(-1)).map((point) => React.createElement('circle', { key: point.at,
550
- cx: Math.max(0, (point.at - end + 60000) / 60000 * 300), cy: 70 - point.rttMs / maximum * 65, r: 2, fill: 'var(--dsw-alias-link, #4176e6)' })))
551
- }
552
- return React.createElement('section', { style: styles.card, 'aria-label': '服务端网络检测' },
553
- React.createElement('h3', { className: 'mgw-section-title' }, '服务端网络检测'),
554
- React.createElement('p', { style: styles.muted }, running ? '自动检测已连接设备,每两秒刷新;离开此页或进入后台后停止。' : '后台已暂停检测'),
555
- React.createElement('p', { style: styles.muted }, '使用 WebSocket 协议 Ping/Pong 测量往返时延;经过 Tunnel 或代理时,RTT 可能只反映代理链路。'),
556
- failure ? React.createElement('p', { role: 'alert', style: styles.error }, failure) : null,
557
- !snapshot ? React.createElement('p', { style: styles.muted }, '正在检测…') : snapshot.devices.length === 0
558
- ? React.createElement('p', { style: styles.muted }, '当前没有已连接设备。')
559
- : snapshot.devices.map((device) => React.createElement('section', { key: device.deviceId, style: { marginTop: 18, paddingTop: 14, borderTop: `1px solid ${colors.border}` } },
560
- React.createElement('strong', null, device.name || '未命名设备'),
561
- device.channels.map((channel) => React.createElement('div', { key: channel.connectionId, style: { marginTop: 12 } },
562
- React.createElement('div', { style: { display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between', gap: 8 } },
563
- React.createElement('span', null, channelLabel(channel.channel), ' · WebSocket'),
564
- React.createElement('strong', null, 'RTT ', number(channel.rttMs))),
565
- React.createElement('p', { style: { ...styles.muted, margin: '6px 0' } }, statusLabel(channel.status), ' · 协议 Ping/Pong · 最近一分钟平均 ', number(channel.averageRttMs), ' · P95 ', number(channel.p95RttMs)),
566
- chart(channel))))),
567
- snapshot ? React.createElement('p', { style: styles.muted }, '服务端读取时间 ', new Date(snapshot.at).toLocaleTimeString(), ' · 曲线范围:最近一分钟') : null,
568
- snapshot?.truncated ? React.createElement('p', { style: styles.muted }, '连接数量过多,仅检测前 256 条连接。') : null)
569
- }
570
- function DeviceRow({ device, onRevoke, revoking }) {
571
- const triggerRevoke = (event) => {
572
- event.preventDefault()
573
- event.stopPropagation()
574
- if (!revoking) onRevoke(device)
575
- }
576
- return React.createElement('div', { style: styles.row },
577
- React.createElement('div', { style: { minWidth: 0, overflow: 'hidden' } },
578
- React.createElement('div', { style: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } },
579
- device.displayName || device.name,
580
- React.createElement('span', { style: styles.badge },
581
- React.createElement('span', { style: { ...styles.dot, background: device.online ? colors.success : colors.muted } }),
582
- device.online ? '在线' : '离线'),
583
- routeBadges(device).map((badge) => React.createElement('span', { key: badge.label, style: styles.badge, title: badge.title },
584
- React.createElement('span', { style: { ...styles.dot, background: badge.color } }),
585
- badge.label))),
586
- React.createElement('div', { style: { ...styles.muted, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', marginTop: 3 } },
587
- device.lastSeenAt ? `最近连接:${new Date(device.lastSeenAt).toLocaleString()}` : '尚未连接')),
588
- React.createElement('button', {
589
- type: 'button',
590
- disabled: revoking,
591
- style: {
592
- ...styles.button,
593
- color: colors.danger,
594
- background: 'transparent',
595
- borderColor: 'rgba(220,76,100,.55)',
596
- flexShrink: 0,
597
- minWidth: 54,
598
- opacity: revoking ? .6 : 1,
599
- },
600
- title: `吊销 ${device.displayName || device.name}`,
601
- // Pointer-up is more reliable than click inside the management dialog on
602
- // touch devices. The click handler remains for keyboard activation.
603
- onPointerUp: triggerRevoke,
604
- onClick: (event) => {
605
- if (event.detail === 0) triggerRevoke(event)
606
- },
607
- }, revoking ? '吊销中…' : '吊销'))
608
- }
609
-
610
- function DevicePanel() {
611
- // 侧边栏入口开关:与侧边栏按钮共享同一状态(切换后立即生效)。
612
- const sidebarOn = React.useSyncExternalStore(subscribeSidebar, getSidebarEntry, () => true)
613
- const [activeSection, setActiveSection] = React.useState('general')
614
- const [devices, setDevices] = React.useState(null)
615
- const [deviceLoadError, setDeviceLoadError] = React.useState(null)
616
- const [statusLoadError, setStatusLoadError] = React.useState(null)
617
- const refreshRequests = React.useRef(new Map())
618
- const manualRefreshRef = React.useRef(false)
619
- // fork:离线设备折叠开关(上游整合时该状态丢失)。
620
- const [showAllDevices, setShowAllDevices] = React.useState(false)
621
- const [permissionSaving, setPermissionSaving] = React.useState(null)
622
- const permissionLock = React.useRef(false)
623
- const deviceRevision = React.useRef(0)
624
- const [selectedDeviceIds, setSelectedDeviceIds] = React.useState(() => new Set())
625
- React.useEffect(() => {
626
- const existing = new Set((devices || []).map(device => device.id))
627
- setSelectedDeviceIds(current => {
628
- const next = new Set([...current].filter(id => existing.has(id)))
629
- return next.size === current.size ? current : next
630
- })
631
- }, [devices])
632
- const [status, setStatus] = React.useState(null)
633
- const [dismissedNotice, setDismissedNotice] = React.useState(() => dismissedRestartInstance)
634
- // 两个配对模块各自维护方案:鲸尾公网小程序(主用)与兼容 App(折叠备用)。
635
- const [appUrl, setAppUrl] = React.useState('')
636
- const [appRoute, setAppRoute] = React.useState('auto')
637
- const [connectionHelpOpen, setConnectionHelpOpen] = React.useState(false)
638
- const [toolsOpen, setToolsOpen] = React.useState(false)
639
- const [toolBusy, setToolBusy] = React.useState(false)
640
- const [backgroundBusy, setBackgroundBusy] = React.useState(false)
641
- const [toolNotice, setToolNotice] = React.useState('')
642
- const stoppedRef = React.useRef(false)
643
- const [publicIp, setPublicIp] = React.useState('')
644
- const [publicSetup, setPublicSetup] = React.useState(null)
645
- const [publicSetupBusy, setPublicSetupBusy] = React.useState(false)
646
- const [cloudflareHost, setCloudflareHost] = React.useState('')
647
- const [cloudflareToken, setCloudflareToken] = React.useState('')
648
- const [cloudflareMode, setCloudflareMode] = React.useState('quick')
649
- const [cloudflareBusy, setCloudflareBusy] = React.useState(false)
650
- const [qr, setQr] = React.useState(null)
651
- const pairingDialogRef = React.useRef(null)
652
- const navRef = React.useRef(null)
653
- // Fork: id of the pairing code currently shown as a QR. The panel polls
654
- // the server's pending list and closes the dialog as soon as this id is
655
- // gone — a successful scan consumes the code immediately.
656
- const pairingIdRef = React.useRef(null)
657
- const [pairingClosing, setPairingClosing] = React.useState(false)
658
- const pairingCloseTimer = React.useRef(null)
659
- const closePairingDialog = () => {
660
- pairingIdRef.current = null
661
- setCopyNotice(null)
662
- if (pairingCloseTimer.current !== null) return
663
- if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
664
- setQr(null)
665
- return
666
- }
667
- setPairingClosing(true)
668
- pairingCloseTimer.current = window.setTimeout(() => {
669
- pairingCloseTimer.current = null
670
- setQr(null)
671
- setPairingClosing(false)
672
- }, 180)
673
- }
674
- React.useEffect(() => {
675
- setPairingClosing(false)
676
- return () => {
677
- if (pairingCloseTimer.current !== null) {
678
- window.clearTimeout(pairingCloseTimer.current)
679
- pairingCloseTimer.current = null
680
- }
681
- }
682
- }, [qr])
683
- const [error, setError] = React.useState(null)
684
- const [busy, setBusy] = React.useState(false)
685
- const [updateInfo, setUpdateInfo] = React.useState(null)
686
- const [updateChecking, setUpdateChecking] = React.useState(true)
687
- const [updateBusy, setUpdateBusy] = React.useState(false)
688
- const [updateNotice, setUpdateNotice] = React.useState('')
689
- const [updateError, setUpdateError] = React.useState('')
690
- const [refreshing, setRefreshing] = React.useState(false)
691
- const [refreshNotice, setRefreshNotice] = React.useState(null)
692
- const [pairingTokenCopied, setPairingTokenCopied] = React.useState(false)
693
- // Copy feedback that must live inside the QR dialog: the panel's error
694
- // banner is behind the modal, so a clipboard failure looked like "the
695
- // button does nothing".
696
- const [copyNotice, setCopyNotice] = React.useState(null)
697
- const [deviceNotice, setDeviceNotice] = React.useState(null)
698
- const [deviceNoticeError, setDeviceNoticeError] = React.useState(false)
699
- const [revokingIds, setRevokingIds] = React.useState(() => new Set())
700
- const [sidebarBusy, setSidebarBusy] = React.useState(false)
701
- const [offlineClearing, setOfflineClearing] = React.useState(false)
702
- const [appLayerOpen, setAppLayerOpen] = React.useState(true)
703
-
704
- const revokingIdsRef = React.useRef(new Set())
705
- const manualAppUrlRef = React.useRef(false)
706
- const appUrlRef = React.useRef('')
707
- const appRouteRef = React.useRef('auto')
708
- const appRouteChosenRef = React.useRef(false)
709
- const cloudflareModeLoadedRef = React.useRef(false)
710
-
711
- // 同类读取去重:轮询与手动刷新并发时复用同一个 in-flight 请求(上游 0.12.x)。
712
- const refreshRead = async (kind, options) => {
713
- const inflight = refreshRequests.current.get(kind)
714
- if (inflight && !(options && options.force)) return inflight
715
- const task = request(kind === 'devices' ? '/mgw/devices' : '/mgw/status', options)
716
- refreshRequests.current.set(kind, task)
717
- try { return await task } finally { refreshRequests.current.delete(kind) }
718
- }
719
- const refresh = React.useCallback(async () => {
720
- try {
721
- const [deviceData, statusData] = await Promise.all([
722
- request('/mgw/devices'),
723
- request('/mgw/status'),
724
- ])
725
- const nextDevices = deviceData.devices || []
726
- // Keep existing DOM rows alive when polling returns identical data.
727
- // Replacing them every three seconds can swallow a pointer/click that
728
- // started on the old button and ended after React replaced the row.
729
- if (revokingIdsRef.current.size === 0) {
730
- setDevices((current) => JSON.stringify(current) === JSON.stringify(nextDevices) ? current : nextDevices)
731
- }
732
- setStatus((current) => JSON.stringify(current) === JSON.stringify(statusData) ? current : statusData)
733
- // Fork: the QR dialog closes itself once the code is consumed. The
734
- // server drops a redeemed code from its pending list, so the poll
735
- // sees our id disappear and dismisses the dialog (with animation).
736
- if (pairingIdRef.current !== null && Array.isArray(statusData.pendingPairings)
737
- && !statusData.pendingPairings.includes(pairingIdRef.current)) {
738
- pairingIdRef.current = null
739
- setQr(null)
740
- }
741
- if (statusData.cloudflare && statusData.cloudflare.hostname) {
742
- setCloudflareHost((current) => current || statusData.cloudflare.hostname)
743
- }
744
- if (statusData.cloudflare && !cloudflareModeLoadedRef.current) {
745
- cloudflareModeLoadedRef.current = true
746
- setCloudflareMode(statusData.cloudflare.mode || 'quick')
747
- }
748
- // 小程序模块固定为鲸尾公网(中继优先、局域网兜底),不再需要方案状态。
749
- // App 模块地址跟随环境刷新;自定义地址与手动填写的 Tailscale 地址不被覆盖。
750
- if (appRouteRef.current !== 'custom'
751
- && !(appRouteRef.current === 'tailscale' && manualAppUrlRef.current)) {
752
- const preferredUrl = pairingUrlFor(appRouteRef.current, statusData)
753
- if (appUrlRef.current && preferredUrl !== appUrlRef.current) setQr(null)
754
- appUrlRef.current = preferredUrl
755
- setAppUrl(preferredUrl)
756
- }
757
- return true
758
- } catch (cause) {
759
- setError(cause.message)
760
- return false
761
- }
762
- }, [])
763
-
764
-
765
- const manualRefresh = async () => {
766
- if (manualRefreshRef.current) return
767
- manualRefreshRef.current = true
768
- setRefreshing(true)
769
- setRefreshNotice(null)
770
- const succeeded = await refresh()
771
- setRefreshing(false)
772
- if (succeeded) {
773
- setError(null)
774
- setRefreshNotice(`已刷新 · ${new Date().toLocaleTimeString()}`)
775
- window.setTimeout(() => setRefreshNotice(null), 2200)
776
- }
777
- }
778
-
779
- const checkForPluginUpdate = async () => {
780
- setUpdateChecking(true)
781
- setUpdateError('')
782
- try {
783
- setUpdateInfo(await request('/mgw/update-check'))
784
- } catch (cause) {
785
- setUpdateError(cause.message)
786
- } finally {
787
- setUpdateChecking(false)
788
- }
789
- }
790
-
791
- const upgradePlugin = async () => {
792
- if (updateBusy || !updateInfo?.updateAvailable) return
793
- setUpdateBusy(true)
794
- setUpdateNotice('')
795
- setUpdateError('')
796
- try {
797
- const result = await request('/mgw/update', { method: 'POST' })
798
- if (result.reason === 'plugin-manager-unavailable') {
799
- setUpdateNotice(`当前 DSH 不支持面板内更新。请在 Terminal 执行:${result.command}`)
800
- } else if (result.reason === 'already-current') {
801
- setUpdateInfo(result)
802
- setUpdateNotice('插件已是最新版本。')
803
- } else if (result.installed) {
804
- const application = result.installation?.application
805
- const pendingBuilds = result.installation?.pendingBuilds
806
- if (Array.isArray(pendingBuilds) && pendingBuilds.length > 0) {
807
- setUpdateNotice(`更新等待构建脚本审核(${pendingBuilds.join('、')});未自动批准。请到 DSH 插件管理中审核。`)
808
- } else if (application === 'restart-required') {
809
- setUpdateInfo({ ...result, currentVersion: result.latestVersion, updateAvailable: false })
810
- setUpdateNotice(`已安装 v${result.latestVersion},需要重启 DSH 后生效。`)
811
- } else if (application === 'failed' || application === 'cancelled' || application === 'refused') {
812
- const installError = result.installation?.error
813
- const detail = result.installation?.errorMessage
814
- || (typeof installError === 'string' ? installError : '')
815
- || (typeof installError?.message === 'string' ? installError.message : '')
816
- || (typeof installError?.code === 'string' ? installError.code : '')
817
- || '请在 DSH 插件管理中查看安装详情。'
818
- setUpdateNotice(`安装未完成:${application}(${detail})`)
819
- } else {
820
- setUpdateInfo({ ...result, currentVersion: result.latestVersion, updateAvailable: false })
821
- setUpdateNotice(`已安装 v${result.latestVersion}。如界面尚未更新,请重启 DSH。`)
822
- }
823
- }
824
- } catch (cause) {
825
- setUpdateError(cause.message)
826
- } finally {
827
- setUpdateBusy(false)
828
- }
829
- }
830
-
831
- // Linux 持久化后台运行:交给 systemd 用户服务托管整个 DSH Web。
832
- const toggleBackgroundService = async (event) => {
833
- const enabled = event.target.checked
834
- if (backgroundBusy || toolBusy) return
835
- setBackgroundBusy(true)
836
- setError(null)
837
- try {
838
- const oldPid = status?.webPid
839
- const data = await request('/mgw/background-service', {
840
- method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ enabled }),
841
- })
842
- setStatus((current) => ({ ...current, backgroundService: data }))
843
- if (data.handoff) {
844
- setToolNotice('正在切换到后台服务,连接会短暂中断,请等待自动重连…')
845
- const deadline = Date.now() + 60_000
846
- while (Date.now() < deadline) {
847
- await new Promise((resolve) => window.setTimeout(resolve, 700))
848
- try {
849
- const next = await request('/mgw/status')
850
- if (next.webPid !== oldPid && next.backgroundService?.managed) { window.location.reload(); return }
851
- } catch { /* 前台进程正在退出,忽略 */ }
852
- }
853
- throw new Error('后台接管超时,请在服务器使用 journalctl --user -u <服务名> 查看服务日志。')
854
- }
855
- setToolNotice(enabled
856
- ? '持久化后台运行已开启。'
857
- : '已关闭自动启动;当前进程继续运行,可通过右上角工具停止 DSH Web。')
858
- } catch (cause) { setError(cause.message) }
859
- finally { setBackgroundBusy(false) }
860
- }
861
-
862
- const runTool = async (tool) => {
863
- if (toolBusy || backgroundBusy) return
864
- setToolsOpen(false)
865
- setToolBusy(true)
866
- setToolNotice('')
867
- setError(null)
868
- try {
869
- const oldPid = status?.webPid
870
- await request(`/mgw/tools/${tool}`, { method: 'POST' })
871
- if (tool === 'stop-web') {
872
- stoppedRef.current = true
873
- setToolNotice('DSH Web 已收到停止指令。需要时可在 Terminal 运行 dsh web 重新启动。')
874
- return
875
- }
876
- if (tool === 'restart-web') {
877
- setToolNotice('正在重启 DSH Web,当前连接会短暂中断…')
878
- const deadline = Date.now() + 60_000
879
- while (Date.now() < deadline) {
880
- await new Promise((resolve) => window.setTimeout(resolve, 700))
881
- try {
882
- const next = await request('/mgw/status')
883
- if (next.webPid && next.webPid !== oldPid) {
884
- window.location.reload()
885
- return
886
- }
887
- } catch { /* old process is shutting down */ }
888
- }
889
- throw new Error('DSH Web 重启超时,请检查 /tmp/mobile-gateway.log')
890
- }
891
- } catch (cause) {
892
- setError(cause.message)
893
- setToolNotice('')
894
- } finally {
895
- setToolBusy(false)
896
- }
897
- }
898
-
899
- // Fork: dsh-settings-mobile-nav collapses the first <nav> of any settings
900
- // dialog on narrow viewports (it assumes the settings rail). Our dialog nav
901
- // is that first nav, so tapping a section used to hide the whole strip and
902
- // leave a lone ☰ button. Never intercept the click itself — React delegates
903
- // onClick at the document root, so stopPropagation in the capture phase
904
- // would kill our own handler. Instead, make the nav un-collapsible: a
905
- // MutationObserver reverts the display/aria-hidden edits (and drops the
906
- // stray expand button) the moment they land.
907
- React.useEffect(() => {
908
- const nav = navRef.current
909
- if (nav === null || typeof MutationObserver === 'undefined') return undefined
910
- const restore = () => {
911
- if (nav.style.display === 'none') nav.style.display = ''
912
- if (nav.getAttribute('aria-hidden') === 'true') nav.removeAttribute('aria-hidden')
913
- const stray = nav.closest('[role="dialog"]')?.querySelector('[data-dsh-settings-nav-expand]')
914
- if (stray !== null && stray !== undefined) stray.remove()
915
- }
916
- const observer = new MutationObserver(restore)
917
- observer.observe(nav, { attributes: true, attributeFilter: ['style', 'aria-hidden'] })
918
- const dialog = nav.closest('[role="dialog"]')
919
- if (dialog !== null) observer.observe(dialog, { childList: true })
920
- return () => observer.disconnect()
921
- }, [])
922
-
923
- React.useEffect(() => {
924
- let active = true
925
- refresh()
926
- request('/mgw/update-check').then((data) => {
927
- if (active) setUpdateInfo(data)
928
- }).catch((cause) => {
929
- if (active) setUpdateError(cause.message)
930
- }).finally(() => {
931
- if (active) setUpdateChecking(false)
932
- })
933
- request('/mgw/public-setup').then((data) => {
934
- if (!active) return
935
- setPublicSetup(data)
936
- if (data.publicUrl) {
937
- const match = /^wss:\/\/([^/]+)\/ws\/mobile$/.exec(data.publicUrl)
938
- if (match) setPublicIp(match[1])
939
- }
940
- }).catch((cause) => active && setPublicSetup({ installed: false, configured: false, error: cause.message }))
941
- const timer = window.setInterval(() => { if (!stoppedRef.current) refresh() }, 3000)
942
- return () => { active = false; window.clearInterval(timer) }
943
- }, [refresh])
944
-
945
-
946
- React.useEffect(() => {
947
- if (!qr) return
948
- const previousFocus = document.activeElement
949
- pairingDialogRef.current?.querySelector('button')?.focus()
950
- return () => previousFocus?.focus()
951
- }, [qr])
952
-
953
-
954
-
955
- // App 模块方案:自定义地址与手动 Tailscale 地址不随轮询覆盖。
956
- const chooseAppRoute = (route) => {
957
- setQr(null)
958
- appRouteChosenRef.current = true
959
- appRouteRef.current = route
960
- setAppRoute(route)
961
- manualAppUrlRef.current = false
962
- const nextUrl = route === 'custom'
963
- ? (publicSetup && publicSetup.publicUrl) || ''
964
- : (status ? pairingUrlFor(route, status) : '')
965
- appUrlRef.current = nextUrl
966
- setAppUrl(nextUrl)
967
- }
968
-
969
- const configurePublicAccess = async () => {
970
- if (publicSetupBusy) return
971
- setPublicSetupBusy(true)
972
- setError(null)
973
- try {
974
- const data = await request('/mgw/public-setup', {
975
- method: 'POST',
976
- headers: { 'Content-Type': 'application/json' },
977
- body: JSON.stringify({ publicIp }),
978
- })
979
- setPublicSetup(data)
980
- // 手动地址模块尚未编辑时,把刚配置好的公网入口预填进去。
981
- if (data.publicUrl && appRouteRef.current === 'custom' && !manualAppUrlRef.current) {
982
- appUrlRef.current = data.publicUrl
983
- setAppUrl(data.publicUrl)
984
- }
985
- } catch (cause) {
986
- setError(cause.message)
987
- } finally {
988
- setPublicSetupBusy(false)
989
- }
990
- }
991
-
992
- const configureCloudflare = async (enabled, mode = cloudflareMode) => {
993
- if (cloudflareBusy) return
994
- setCloudflareBusy(true)
995
- setError(null)
996
- try {
997
- const data = await request('/mgw/cloudflare', {
998
- method: 'POST',
999
- headers: { 'Content-Type': 'application/json' },
1000
- body: JSON.stringify({ enabled, ...(enabled ? {
1001
- mode,
1002
- ...(mode === 'named' ? { hostname: cloudflareHost, token: cloudflareToken } : {}),
1003
- } : {}) }),
1004
- })
1005
- setCloudflareToken('')
1006
- setStatus((current) => ({ ...(current || {}), cloudflare: data, gatewayEnabled: data.gatewayEnabled, gatewayMode: data.gatewayMode, publicUrl: data.publicUrl || null }))
1007
- await refresh()
1008
- } catch (cause) {
1009
- setError(cause.message)
1010
- } finally {
1011
- setCloudflareBusy(false)
1012
- }
1013
- }
1014
-
1015
- const checkCloudflare = async () => {
1016
- if (cloudflareBusy) return
1017
- setCloudflareBusy(true)
1018
- setError(null)
1019
- try {
1020
- const data = await request('/mgw/cloudflare/check', { method: 'POST' })
1021
- setStatus((current) => ({ ...(current || {}), cloudflare: data }))
1022
- } catch (cause) { setError(cause.message) }
1023
- finally { setCloudflareBusy(false) }
1024
- }
1025
-
1026
- const restartCloudflare = async () => {
1027
- if (cloudflareBusy) return
1028
- setCloudflareBusy(true)
1029
- setError(null)
1030
- try {
1031
- const data = await request('/mgw/cloudflare/restart', { method: 'POST' })
1032
- if (data.mode === 'quick') setQr(null)
1033
- setStatus((current) => ({ ...(current || {}), cloudflare: data }))
1034
- await refresh()
1035
- } catch (cause) {
1036
- setError(cause.message)
1037
- } finally {
1038
- setCloudflareBusy(false)
1039
- }
1040
- }
1041
-
1042
- const requestPairing = async (body) => request('/mgw/pair', {
1043
- method: 'POST',
1044
- headers: { 'Content-Type': 'application/json' },
1045
- body: JSON.stringify({ lanUrl: lanPairingUrl(status), ...body }),
1046
- })
1047
-
1048
- // 两个模块各自生成二维码:
1049
- // 小程序:自动选择(多路载荷,小程序优先中继)或鲸尾公网中继专用码;
1050
- // App:局域网 / Cloudflare / Tailscale / 手动地址(上游插件的直连方式)。
1051
- const pairFor = async (module) => {
1052
- setBusy(true)
1053
- setError(null)
1054
- setPairingTokenCopied(false)
1055
- try {
1056
- let data
1057
- if (module === 'mini') {
1058
- // 小程序专用路线:中继优先、局域网兜底(路线由小程序端按路由表选择)。
1059
- data = await requestPairing({ route: 'mini' })
1060
- } else {
1061
- data = await requestPairing({
1062
- publicUrl: appRoute === 'tailscale' ? tailscaleEndpointOf(appUrl, status) : appUrl,
1063
- route: appRoute,
1064
- })
1065
- }
1066
- pairingIdRef.current = data.pairing?.id || null
1067
- setQr(data)
1068
- } catch (cause) {
1069
- setError(cause.message)
1070
- } finally {
1071
- setBusy(false)
1072
- }
1073
- }
1074
-
1075
- // Fork: the pairing payload must be copyable wherever the WebUI is
1076
- // opened. navigator.clipboard only exists in a secure context, and the
1077
- // fnOS gateway embedding is plain http — there the async API is simply
1078
- // missing. Fall back to the deprecated-but-universal execCommand path
1079
- // before giving up, and report failures inside the QR dialog (the
1080
- // panel's error banner sits behind the modal and is invisible).
1081
- const writeClipboard = (text) => {
1082
- if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
1083
- return navigator.clipboard.writeText(text)
1084
- }
1085
- return new Promise((resolve, reject) => {
1086
- const holder = document.createElement('textarea')
1087
- holder.value = text
1088
- holder.setAttribute('readonly', '')
1089
- holder.style.position = 'fixed'
1090
- holder.style.top = '-1000px'
1091
- holder.style.opacity = '0'
1092
- document.body.appendChild(holder)
1093
- holder.select()
1094
- holder.setSelectionRange(0, text.length)
1095
- let copied = false
1096
- try {
1097
- copied = document.execCommand('copy')
1098
- } catch (error) {
1099
- copied = false
1100
- }
1101
- document.body.removeChild(holder)
1102
- if (copied) resolve()
1103
- else reject(new Error('浏览器拒绝写入剪贴板'))
1104
- })
1105
- }
1106
-
1107
- const copyPairingText = async () => {
1108
- if (!qr || !qr.qrPayload) return
1109
- try {
1110
- await writeClipboard(qr.qrPayload)
1111
- setError(null)
1112
- setCopyNotice(null)
1113
- setPairingTokenCopied(true)
1114
- window.setTimeout(() => setPairingTokenCopied(false), 2200)
1115
- } catch (cause) {
1116
- setPairingTokenCopied(false)
1117
- setCopyNotice(`${cause.message || '复制失败'},请选中上面文本后按 Ctrl/Cmd+C`)
1118
- window.setTimeout(() => setCopyNotice(null), 6000)
1119
- // Leave the payload selected so the manual copy is one keystroke away.
1120
- const area = pairingDialogRef.current && pairingDialogRef.current.querySelector('textarea')
1121
- if (area) { area.focus(); area.select() }
1122
- }
1123
- }
1124
-
1125
- const changeGatewayMode = async (mode) => {
1126
- setBusy(true)
1127
- setError(null)
1128
- try {
1129
- const data = await request('/mgw/gateway', {
1130
- method: 'POST',
1131
- headers: { 'Content-Type': 'application/json' },
1132
- body: JSON.stringify({ mode }),
1133
- })
1134
- setStatus((current) => ({ ...(current || {}), ...data }))
1135
- if (mode === 'disabled') setQr(null)
1136
- } catch (cause) {
1137
- setError(cause.message)
1138
- } finally {
1139
- setBusy(false)
1140
- }
1141
- }
1142
-
1143
- const toggleAuth = async () => {
1144
- const enabled = !(status && status.requireAuth)
1145
- if (!enabled && !window.confirm('关闭设备鉴权后,任何能访问移动网关的人都可以控制 DSH。此选项仅限 Debug 阶段使用,确定继续吗?')) return
1146
- setBusy(true)
1147
- setError(null)
1148
- try {
1149
- const data = await request('/mgw/auth', {
1150
- method: 'POST',
1151
- headers: { 'Content-Type': 'application/json' },
1152
- body: JSON.stringify({ enabled }),
1153
- })
1154
- setStatus((current) => ({ ...(current || {}), requireAuth: data.requireAuth }))
1155
- } catch (cause) {
1156
- setError(cause.message)
1157
- } finally {
1158
- setBusy(false)
1159
- }
1160
- }
1161
-
1162
- // 左侧栏入口开关:持久化到 /mgw/ui,并立即通知侧边栏按钮。
1163
- const toggleSidebarEntry = async () => {
1164
- if (sidebarBusy) return
1165
- setSidebarBusy(true)
1166
- setError(null)
1167
- try {
1168
- const data = await request('/mgw/ui', {
1169
- method: 'POST',
1170
- headers: { 'Content-Type': 'application/json' },
1171
- body: JSON.stringify({ sidebarEntry: !sidebarOn }),
1172
- })
1173
- setSidebarEntry(data.sidebarEntry !== false)
1174
- } catch (cause) {
1175
- setError(cause.message)
1176
- } finally {
1177
- setSidebarBusy(false)
1178
- }
1179
- }
1180
-
1181
- // 一键清除离线设备:吊销所有当前离线的已配对设备,在线设备不受影响。
1182
- const clearOfflineDevices = async () => {
1183
- const targets = Array.isArray(devices) ? devices.filter((device) => !device.online) : []
1184
- if (targets.length === 0 || offlineClearing) return
1185
- if (!window.confirm(`清除 ${targets.length} 台离线设备?清除后需要重新配对才能连接。`)) return
1186
- setOfflineClearing(true)
1187
- setDeviceNotice(null)
1188
- setDeviceNoticeError(false)
1189
- setError(null)
1190
- try {
1191
- const data = await request('/mgw/devices/revoke-offline', { method: 'POST' })
1192
- const removedIds = new Set(Array.isArray(data.removed) ? data.removed : [])
1193
- setDevices((current) => Array.isArray(current) ? current.filter((item) => !removedIds.has(item.id)) : current)
1194
- setDeviceNotice(`已清除 ${data.count ?? removedIds.size} 台离线设备`)
1195
- window.setTimeout(() => setDeviceNotice(null), 2200)
1196
- } catch (cause) {
1197
- setDeviceNoticeError(true)
1198
- setDeviceNotice(`清除失败:${cause.message}`)
1199
- setError(cause.message)
1200
- } finally {
1201
- setOfflineClearing(false)
1202
- }
1203
- }
1204
-
1205
- // 批量吊销:逐个调用单设备吊销接口(/mgw/devices/<id>/revoke)。
1206
- const removeDevices = async (list) => {
1207
- const targets = Array.isArray(list) ? list : [list]
1208
- const removed = []
1209
- for (const device of targets) {
1210
- if (revokingIdsRef.current.has(device.id)) continue
1211
- setDeviceNotice(null)
1212
- setDeviceNoticeError(false)
1213
- setError(null)
1214
- deviceRevision.current += 1
1215
- revokingIdsRef.current.add(device.id)
1216
- setRevokingIds((current) => new Set(current).add(device.id))
1217
- try {
1218
- await request(`/mgw/devices/${encodeURIComponent(device.id)}/revoke`, { method: 'POST' })
1219
- removed.push(device.id)
1220
- setDevices((current) => Array.isArray(current) ? current.filter((item) => item.id !== device.id) : current)
1221
- setDeviceNotice(`已吊销 ${device.displayName || device.name}`)
1222
- window.setTimeout(() => setDeviceNotice(null), 2200)
1223
- } catch (cause) {
1224
- setDeviceNoticeError(true)
1225
- setDeviceNotice(`吊销失败:${cause.message}`)
1226
- setError(cause.message)
1227
- } finally {
1228
- deviceRevision.current += 1
1229
- revokingIdsRef.current.delete(device.id)
1230
- setRevokingIds((current) => { const next = new Set(current); next.delete(device.id); return next })
1231
- }
1232
- }
1233
- await refreshRead('devices')
1234
- return removed
1235
- }
1236
- const revoke = (device) => removeDevices([device])
1237
- const selectDevice = (id, selected) => setSelectedDeviceIds(current => {
1238
- const next = new Set(current)
1239
- selected ? next.add(id) : next.delete(id)
1240
- return next
1241
- })
1242
-
1243
- const savePermission = async (device, module, value) => {
1244
- if (permissionLock.current || revokingIdsRef.current.size) return
1245
- permissionLock.current = true
1246
- deviceRevision.current += 1
1247
- setPermissionSaving(`${device.id}:${module}`)
1248
- setError(null)
1249
- try {
1250
- const result = await request(`/mgw/devices/${encodeURIComponent(device.id)}/permissions`, {
1251
- method: 'POST', headers: { 'Content-Type': 'application/json' },
1252
- body: JSON.stringify({ permissions: { [module]: value } }),
1253
- })
1254
- setDevices(current => current?.map(row => row.id === device.id ? { ...row, permissions: result.permissions } : row))
1255
- } catch (cause) { setError(cause.message) }
1256
- finally { deviceRevision.current += 1; permissionLock.current = false; setPermissionSaving(null) }
1257
- }
1258
- const restartNoticeInstance = status?.gatewayInstanceId || (status?.webPid ? String(status.webPid) : null)
1259
- const dismissRestartNotice = () => {
1260
- dismissedRestartInstance = restartNoticeInstance
1261
- setDismissedNotice(restartNoticeInstance)
1262
- try { window.localStorage.setItem(restartNoticeStorageKey, restartNoticeInstance) } catch { /* keep in-memory dismissal */ }
1263
- }
1264
-
1265
- const onlineDevices = (devices || []).filter((device) => device.online)
1266
- const offlineDevices = (devices || []).filter((device) => !device.online)
1267
- const orderedDevices = [...onlineDevices, ...offlineDevices]
1268
- // fork:默认只列在线设备,展开后列全部(上游整合时该派生值丢失)。
1269
- const visibleDevices = showAllDevices ? orderedDevices : onlineDevices
1270
- const selectedCount = orderedDevices.filter(device => selectedDeviceIds.has(device.id)).length
1271
- const deletingDevices = revokingIds.size > 0
1272
- const deviceActionsDisabled = deletingDevices || permissionSaving !== null
1273
-
1274
- // The same v2 QR is native-app compatible; mini-program-only public
1275
- // routing is carried in an optional field that older apps ignore.
1276
- const relayInfo = status && status.relay ? status.relay : null
1277
- const relayConnector = status && status.relayConnector ? status.relayConnector : null
1278
- const cloudflareReady = !!(status?.cloudflare?.enabled && status.cloudflare.publicReady === true && status.cloudflare.publicUrl)
1279
- // App 模块的生成按钮:入口就绪才可点,避免生成无法连接的二维码。
1280
- const appPairingDisabled = busy || !(status && status.gatewayEnabled) ||
1281
- (appRoute === 'custom' && !appUrl.trim()) ||
1282
- (appRoute === 'cloudflare' && !cloudflareReady) ||
1283
- (appRoute === 'auto' && !lanPairingUrl(status)) ||
1284
- (appRoute === 'lan' && !lanPairingUrl(status)) ||
1285
- (appRoute === 'tailscale' && !(status?.lan?.listening && isTailscaleInput(appUrl)))
1286
- const appPlan = appConnectionPlan(appRoute, status, appUrl)
1287
-
1288
- const advice = connectionAdvice(status, publicSetup)
1289
- const helpLine = (name, description) => React.createElement('div', { style: { marginTop: 7 } },
1290
- React.createElement('strong', null, name), ':', description)
1291
-
1292
- return React.createElement('div', { style: styles.backdrop, onMouseDown: () => setOpen(false) },
1293
- qr ? React.createElement('div', { style: { ...styles.backdrop, zIndex: 1201 },
1294
- onMouseDown: (event) => { event.stopPropagation(); closePairingDialog() } },
1295
- React.createElement('div', { className: 'mgw-pairing-dialog', 'data-closing': pairingClosing, ref: pairingDialogRef, role: 'dialog', 'aria-modal': true, 'aria-label': '设备配对二维码', tabIndex: -1,
1296
- style: { ...styles.panel, width: 'min(520px, 100%)', height: 'auto', overflowY: 'auto', scrollbarWidth: 'none' },
1297
- onMouseDown: (event) => event.stopPropagation(),
1298
- onKeyDown: (event) => {
1299
- if (event.key === 'Escape') { event.stopPropagation(); closePairingDialog() }
1300
- if (event.key === 'Tab') {
1301
- const items = [...event.currentTarget.querySelectorAll('button, textarea')]
1302
- const first = items[0], last = items[items.length - 1]
1303
- if (event.shiftKey && (document.activeElement === first || document.activeElement === event.currentTarget)) { event.preventDefault(); last?.focus() }
1304
- else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first?.focus() }
1305
- }
1306
- } },
1307
- React.createElement('div', { style: { display: 'flex', justifyContent: 'flex-end' } },
1308
- React.createElement('button', { type: 'button', style: { ...styles.button, ...styles.headerButton }, 'aria-label': '关闭配对窗口', onClick: closePairingDialog }, '✕')),
1309
- React.createElement('section', { style: { textAlign: 'center' } },
1310
- React.createElement('strong', null, qr.payload?.version === 3 && qr.payload?.mode === 'relay'
1311
- ? '使用鲸尾小程序扫码(此二维码仅适用于小程序)'
1312
- : '使用 DSH App 或鲸尾小程序扫码'),
1313
- React.createElement('img', { style: styles.qr, src: `data:image/svg+xml;charset=utf-8,${encodeURIComponent(qr.svg)}`, alt: '一次性设备配对二维码' }),
1314
- qr.payload?.version === 3 && qr.payload?.mode === 'relay'
1315
- ? React.createElement('p', { style: { ...styles.muted, textAlign: 'left' } }, '这是小程序专用的鲸尾公网中继二维码,DSH App 不能使用。需要同时配对 DSH App 和小程序时,请改选“自动选择”。')
1316
- : qr.payload?.miniProgramRoute?.mode === 'direct'
1317
- ? React.createElement('p', { style: { ...styles.muted, textAlign: 'left' } }, '此二维码为 DSH App 和小程序提供公网与局域网候选地址;客户端会自动尝试可达线路。')
1318
- : qr.payload?.miniProgramRoute?.mode === 'relay'
1319
- ? React.createElement('p', { style: { ...styles.muted, textAlign: 'left' } }, '当前没有可用公网 WSS:DSH App 使用局域网,小程序使用鲸尾公网中继。选择“局域网直连”时,两端都直接使用局域网。')
1320
- : React.createElement('p', { style: { ...styles.muted, textAlign: 'left' } }, '此二维码含当前可用的连接地址;DSH App 和小程序均可通过公网或局域网连接。'),
1321
- React.createElement('label', { style: { ...styles.label, textAlign: 'left' } }, 'Base64URL 配对字符串'),
1322
- React.createElement('textarea', { style: styles.pairingText, value: qr.qrPayload, readOnly: true, spellCheck: false, onFocus: (event) => event.target.select() }),
1323
- React.createElement('button', { type: 'button', style: { ...styles.button, width: '100%', marginBottom: 8, borderColor: pairingTokenCopied ? colors.success : colors.border, color: pairingTokenCopied ? colors.success : colors.text }, onClick: copyPairingText }, pairingTokenCopied ? '✓ 已复制' : '复制配对 Token'),
1324
- pairingTokenCopied ? React.createElement('div', { style: { ...styles.muted, color: colors.success, marginBottom: 8 } }, '已复制到剪贴板') : null,
1325
- copyNotice ? React.createElement('div', { role: 'alert', style: { ...styles.muted, color: colors.danger, marginBottom: 8 } }, copyNotice) : null,
1326
- React.createElement('div', { style: styles.muted }, `有效期至 ${new Date(qr.pairing.expiresAt).toLocaleTimeString()};扫码成功后此二维码立即失效。`)))) : null,
1327
- React.createElement('aside', { className: 'mobile-gateway-panel', inert: qr ? true : undefined, 'aria-hidden': qr ? true : undefined, style: styles.panel, onMouseDown: (event) => { event.stopPropagation(); setToolsOpen(false) }, role: 'dialog', 'aria-modal': true, 'aria-label': '鲸尾网关助手管理' },
1328
- React.createElement('div', { style: styles.header },
1329
- React.createElement('div', null,
1330
- React.createElement('h2', { style: styles.title }, '鲸尾网关助手'),
1331
- React.createElement('div', { style: styles.muted }, !status ? '正在加载网关状态…' : status.gatewayEnabled ? `移动网关已开启 · ${status.requireAuth ? '设备鉴权已开启' : '本机设备鉴权已关闭'}` : '移动网关已关闭 · 普通 WebUI 模式')),
1332
- React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 6 } },
1333
- React.createElement('div', { style: { position: 'relative' }, onMouseDown: (event) => event.stopPropagation() },
1334
- React.createElement('button', {
1335
- type: 'button', style: { ...styles.button, ...styles.headerButton, borderRadius: '50%' }, title: '工具', 'aria-label': '工具',
1336
- 'aria-haspopup': 'menu', 'aria-expanded': toolsOpen,
1337
- onClick: () => setToolsOpen((value) => !value),
1338
- }, React.createElement('svg', { width: 20, height: 20, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true },
1339
- React.createElement('path', { d: 'M10.3 2.8h3.4l.5 2.2a7.6 7.6 0 0 1 1.7.7l1.9-1.2 2.4 2.4L19 8.8c.3.5.5 1.1.7 1.7l2.2.5v3.4l-2.2.5a7.6 7.6 0 0 1-.7 1.7l1.2 1.9-2.4 2.4-1.9-1.2a7.6 7.6 0 0 1-1.7.7l-.5 2.2h-3.4l-.5-2.2a7.6 7.6 0 0 1-1.7-.7l-1.9 1.2-2.4-2.4L5 16.6a7.6 7.6 0 0 1-.7-1.7l-2.2-.5V11l2.2-.5A7.6 7.6 0 0 1 5 8.8L3.8 6.9l2.4-2.4 1.9 1.2a7.6 7.6 0 0 1 1.7-.7l.5-2.2Z' }),
1340
- React.createElement('circle', { cx: 12, cy: 12.7, r: 3.1 }))),
1341
- toolsOpen ? React.createElement('div', { style: styles.toolsMenu, role: 'menu', 'aria-label': '网关工具' },
1342
- React.createElement('button', {
1343
- type: 'button', role: 'menuitem', disabled: toolBusy || stoppedRef.current || !status?.tools?.restartWeb,
1344
- style: { ...styles.toolsItem, opacity: status?.tools?.restartWeb ? 1 : .5 },
1345
- onClick: () => runTool('restart-web'),
1346
- }, '重启当前网关',
1347
- React.createElement('span', { style: { ...styles.muted, display: 'block', marginTop: 2 } }, '结束当前进程并重新启动 DSH Web')),
1348
- React.createElement('button', {
1349
- type: 'button', role: 'menuitem', disabled: toolBusy || stoppedRef.current || !status?.tools?.stopWeb,
1350
- style: { ...styles.toolsItem, color: colors.danger, opacity: status?.tools?.stopWeb ? 1 : .5 },
1351
- onClick: () => runTool('stop-web'),
1352
- }, '停止 DSH Web',
1353
- React.createElement('span', { style: { ...styles.muted, display: 'block', marginTop: 2 } }, '结束后台进程,所有连接将断开')))
1354
- : null),
1355
- React.createElement('button', { style: { ...styles.button, ...styles.headerButton }, onClick: () => setOpen(false), 'aria-label': '关闭' },
1356
- React.createElement('svg', { width: 20, height: 20, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 2.2, strokeLinecap: 'round', 'aria-hidden': true },
1357
- React.createElement('path', { d: 'M6 6l12 12M18 6L6 18' }))))),
1358
- React.createElement('div', { className: 'mgw-body' },
1359
- React.createElement('nav', { ref: navRef, className: 'mgw-nav', 'aria-label': '鲸尾网关助手设置分组' },
1360
- [['general', '通用设置'], ['pairing', '连接与配对'], ['devices', '可信设备'], ['network', '网络检测']].map(([id, label]) =>
1361
- React.createElement('button', { key: id, type: 'button', 'aria-current': activeSection === id ? 'page' : undefined,
1362
- onClick: () => { setActiveSection(id); setConnectionHelpOpen(false); setToolsOpen(false) } }, label))),
1363
- React.createElement('div', { className: 'mgw-content', key: activeSection },
1364
- restartNoticeInstance && dismissedNotice !== restartNoticeInstance ? React.createElement('section', { style: { ...styles.card, position: 'relative', padding: '10px 40px 10px 12px', border: '1px solid', borderRadius: 10, marginBottom: 8, background: 'var(--dsw-alias-state-warn-tertiary, #fff7df)', borderColor: 'color-mix(in srgb, #d99a16 35%, transparent)', fontSize: 12, lineHeight: 1.6 }, role: 'note' },
1365
- React.createElement('button', { type: 'button', 'aria-label': '关闭重启提醒', title: '关闭提醒',
1366
- style: { ...styles.button, position: 'absolute', right: 8, top: 8, border: 0, width: 24, height: 24, padding: 0, color: colors.muted },
1367
- onClick: dismissRestartNotice }, '✕'),
1368
- React.createElement('strong', null, '若安装或更新后连接异常,请重启应用'),
1369
- React.createElement('div', { style: { color: colors.muted, marginTop: 4 } },
1370
- '完全退出并重启 APP/Desktop;Web UI 请重启 DSH Web 服务。'),
1371
- React.createElement('div', { style: { color: colors.muted, marginTop: 4 } },
1372
- '端口仍被占用时,请关闭其他 Harness 实例。')) : null,
1373
- toolNotice ? React.createElement('div', { style: { ...styles.muted, marginBottom: 10 } }, toolNotice) : null,
1374
- (error || deviceLoadError || statusLoadError) ? React.createElement('div', { style: styles.error, role: 'alert' }, error || deviceLoadError || statusLoadError) : null,
1375
- React.createElement('div', { hidden: activeSection !== 'general' },
1376
- // Linux 专属:持久化后台运行(systemd 用户服务)。其他平台不渲染。
1377
- status?.platform === 'linux' ? React.createElement('section', { style: styles.card },
1378
- React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 14, alignItems: 'center' } },
1379
- React.createElement('div', null,
1380
- React.createElement('strong', null, '持久化后台运行'),
1381
- React.createElement('p', { style: styles.muted }, '由 systemd 托管整个 DSH Web,SSH 断开后继续运行,服务器重启后自动启动。开启时会短暂重连。'),
1382
- status.backgroundService?.reason ? React.createElement('p', { style: styles.muted }, status.backgroundService.reason) : null,
1383
- status.backgroundService?.unit ? React.createElement('p', { style: { ...styles.muted, opacity: .75 } }, `服务名:${status.backgroundService.unit}`) : null),
1384
- React.createElement('label', { style: { ...styles.switch, opacity: status.backgroundService?.available || status.backgroundService?.managed ? (backgroundBusy ? .55 : 1) : .55 },
1385
- title: status.backgroundService?.available ? '切换持久化后台运行' : (status.backgroundService?.reason || '当前环境不支持') },
1386
- React.createElement('input', {
1387
- type: 'checkbox',
1388
- role: 'switch',
1389
- 'aria-label': '持久化后台运行',
1390
- 'aria-checked': !!status.backgroundService?.managed,
1391
- checked: !!status.backgroundService?.managed,
1392
- disabled: backgroundBusy || !(status.backgroundService?.available || status.backgroundService?.managed),
1393
- onChange: toggleBackgroundService,
1394
- style: styles.switchInput,
1395
- }),
1396
- React.createElement('span', { style: { ...styles.switchTrack, background: status.backgroundService?.managed ? colors.success : colors.muted } }),
1397
- React.createElement('span', { style: { ...styles.switchKnob, left: status.backgroundService?.managed ? 21 : 3 } }))),
1398
- ) : null,
1399
- React.createElement('section', { style: styles.card },
1400
- React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 14, alignItems: 'center' } },
1401
- React.createElement('div', null,
1402
- React.createElement('strong', null, '网关运行模式'),
1403
- React.createElement('div', { style: { ...styles.muted, marginTop: 4 } }, status && status.gatewayEnabled
1404
- ? status.gatewayMode === 'persistent'
1405
- ? '重启后保持开启'
1406
- : status.waitExpiresAt
1407
- ? `等待可信设备连接,约 ${Math.max(1, Math.ceil((status.waitExpiresAt - Date.now()) / 60000))} 分钟后自动关闭`
1408
- : '设备已连接过,本次运行保持开启;重启后重新计时'
1409
- : '不接受移动设备连接')),
1410
- React.createElement('span', { style: { position: 'relative', display: 'inline-flex', flexShrink: 0 } },
1411
- React.createElement(GatewaySelect, {
1412
- style: { ...styles.input, width: 'auto', marginBottom: 0, padding: '8px 40px 8px 12px', appearance: 'none', WebkitAppearance: 'none' },
1413
- 'aria-label': '网关运行模式',
1414
- value: status ? status.gatewayMode || (status.gatewayEnabled ? 'temporary' : 'disabled') : 'disabled',
1415
- disabled: busy || !status,
1416
- onChange: (event) => changeGatewayMode(event.target.value),
1417
- },
1418
- React.createElement('option', { value: 'disabled' }, '关闭'),
1419
- React.createElement('option', { value: 'temporary' }, '临时开启'),
1420
- React.createElement('option', { value: 'persistent' }, '常驻开启')),
1421
- )),
1422
- status && status.gatewayId ? React.createElement('div', { style: { ...styles.muted, marginTop: 12, overflowWrap: 'anywhere' } },
1423
- status.gatewayName) : null),
1424
- React.createElement('section', { style: styles.card },
1425
- React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 14, alignItems: 'center' } },
1426
- React.createElement('div', null,
1427
- React.createElement('strong', null, '设备鉴权'),
1428
- React.createElement('div', { style: { ...styles.muted, marginTop: 4 } }, status && status.requireAuth ? '已开启,仅允许可信设备连接' : '已关闭,仅影响本机 Debug 入口')),
1429
- React.createElement('label', { style: { ...styles.switch, opacity: busy || !status ? .55 : 1 }, title: status && status.requireAuth ? '关闭设备鉴权' : '开启设备鉴权' },
1430
- React.createElement('input', {
1431
- type: 'checkbox',
1432
- role: 'switch',
1433
- 'aria-label': '设备鉴权',
1434
- 'aria-checked': !!(status && status.requireAuth),
1435
- checked: !!(status && status.requireAuth),
1436
- disabled: busy || !status,
1437
- onChange: toggleAuth,
1438
- style: styles.switchInput,
1439
- }),
1440
- React.createElement('span', { style: { ...styles.switchTrack, background: status && status.requireAuth ? colors.success : colors.danger } }),
1441
- React.createElement('span', { style: { ...styles.switchKnob, left: status && status.requireAuth ? 21 : 3 } }))),
1442
- status && !status.requireAuth
1443
- ? React.createElement('p', { style: { ...styles.error, margin: '12px 0 0' } }, 'Debug 模式:本机 DSH 入口将跳过设备凭证校验;独立局域网入口仍强制鉴权。')
1444
- : null),
1445
- React.createElement('section', { style: styles.card },
1446
- React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 14, alignItems: 'center' } },
1447
- React.createElement('div', null,
1448
- React.createElement('strong', null, '在左侧栏显示入口'),
1449
- React.createElement('div', { style: { ...styles.muted, marginTop: 4 } }, sidebarOn
1450
- ? 'Harness 侧边栏底部显示「鲸尾移动设备」按钮;关闭后仅从设置页打开。'
1451
- : '已隐藏侧边栏入口;可在这里重新开启。')),
1452
- React.createElement('label', { style: { ...styles.switch, opacity: sidebarBusy ? .55 : 1 }, title: sidebarOn ? '隐藏左侧栏入口' : '在左侧栏显示入口' },
1453
- React.createElement('input', {
1454
- type: 'checkbox',
1455
- role: 'switch',
1456
- 'aria-label': '在左侧栏显示入口',
1457
- 'aria-checked': sidebarOn,
1458
- checked: sidebarOn,
1459
- disabled: sidebarBusy,
1460
- onChange: toggleSidebarEntry,
1461
- style: styles.switchInput,
1462
- }),
1463
- React.createElement('span', { style: { ...styles.switchTrack, background: sidebarOn ? colors.success : colors.muted } }),
1464
- React.createElement('span', { style: { ...styles.switchKnob, left: sidebarOn ? 21 : 3 } })))),
1465
- React.createElement('section', { style: styles.card },
1466
- React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 14, alignItems: 'flex-start' } },
1467
- React.createElement('div', null,
1468
- React.createElement('strong', null, '插件在线更新'),
1469
- React.createElement('div', { style: { ...styles.muted, marginTop: 4 } }, updateChecking
1470
- ? '正在检查 npm 最新版本…'
1471
- : updateInfo
1472
- ? `当前版本 v${updateInfo.currentVersion} · npm 最新 v${updateInfo.latestVersion}`
1473
- : '暂时无法获取版本信息'),
1474
- updateInfo?.updateAvailable
1475
- ? React.createElement('div', { style: { marginTop: 6, color: colors.success, fontWeight: 600 } }, '发现新版本,可直接升级安装。')
1476
- : null,
1477
- updateInfo && !updateInfo.updateAvailable
1478
- ? React.createElement('div', { style: { marginTop: 6, color: colors.success } }, '当前已是最新版本。')
1479
- : null,
1480
- updateNotice
1481
- ? React.createElement('div', { style: { ...styles.muted, marginTop: 6, overflowWrap: 'anywhere' }, role: 'status' }, updateNotice)
1482
- : null,
1483
- updateError
1484
- ? React.createElement('div', { style: { ...styles.muted, marginTop: 6, color: colors.danger, overflowWrap: 'anywhere' }, role: 'status' }, `检查失败:${updateError}`)
1485
- : null),
1486
- React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 8, minWidth: 100 } },
1487
- React.createElement('button', {
1488
- type: 'button',
1489
- style: { ...styles.button, ...styles.primary, opacity: updateBusy || !updateInfo?.updateAvailable ? .55 : 1 },
1490
- disabled: updateBusy || updateChecking || !updateInfo?.updateAvailable,
1491
- onClick: upgradePlugin,
1492
- }, updateBusy ? '正在升级…' : '立即升级'),
1493
- React.createElement('button', {
1494
- type: 'button',
1495
- style: styles.button,
1496
- disabled: updateChecking || updateBusy,
1497
- onClick: checkForPluginUpdate,
1498
- }, updateChecking ? '检查中…' : '重新检查')))),
1499
- ),
1500
- React.createElement('div', { hidden: activeSection !== 'network' },
1501
- React.createElement(ServerNetworkDiagnostics, null)),
1502
- React.createElement('div', { hidden: activeSection !== 'pairing' },
1503
- // ── 模块一:DSH App(推荐)────────────────────────────────
1504
- React.createElement('section', { style: { ...styles.card, marginTop: 16 } },
1505
- React.createElement('button', {
1506
- type: 'button',
1507
- style: { ...styles.button, width: '100%', textAlign: 'left', display: 'flex', justifyContent: 'space-between', alignItems: 'center', background: 'transparent', border: 0, padding: 0 },
1508
- 'aria-expanded': appLayerOpen,
1509
- onClick: () => setAppLayerOpen((value) => !value),
1510
- },
1511
- React.createElement('span', null,
1512
- React.createElement('strong', null, 'DSH App(推荐)'),
1513
- React.createElement('span', { style: { ...styles.muted, marginLeft: 8, fontWeight: 400 } },
1514
- appLayerOpen ? '收起 DSH App 方式' : '推荐:手机安装 DSH App 时使用')),
1515
- React.createElement('svg', { width: 16, height: 16, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor',
1516
- strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true,
1517
- style: { flexShrink: 0, color: colors.muted, transform: appLayerOpen ? 'rotate(180deg)' : 'none', transition: 'transform .18s ease' } },
1518
- React.createElement('path', { d: 'M6 9l6 6 6-6' }))),
1519
- appLayerOpen
1520
- ? React.createElement(React.Fragment, null,
1521
- React.createElement('p', { style: styles.muted }, 'DSH App 直连入口(推荐手机端使用),与下方的鲸尾公网互不影响。'),
1522
- React.createElement('div', { style: { display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: '8px 14px', maxWidth: '100%', marginBottom: 16 } },
1523
- React.createElement(GatewaySelect, { style: styles.input, value: appRoute, onChange: (event) => chooseAppRoute(event.target.value), disabled: !status, 'aria-label': 'App 连接方式' },
1524
- React.createElement('option', { value: 'auto' }, '自动选择'),
1525
- React.createElement('option', { value: 'lan', disabled: !lanPairingUrl(status) }, lanPairingUrl(status)
1526
- ? '局域网直连'
1527
- : '局域网直连 · 当前不可用'),
1528
- status?.cloudflare?.supported
1529
- ? React.createElement('option', { value: 'cloudflare' }, 'Cloudflare 外网') : null,
1530
- React.createElement('option', { value: 'tailscale', disabled: !(status && ((status.tailscale && status.tailscale.serveUrl) || (status.lan && status.lan.listening))) },
1531
- (status && ((status.tailscale && status.tailscale.serveUrl) || (status.lan && status.lan.listening)))
1532
- ? 'Tailscale 内嵌隧道'
1533
- : 'Tailscale 内嵌隧道 · 未就绪'),
1534
- React.createElement('option', { value: 'custom' }, '公网或其他手动地址'))),
1535
- // 与上游一致的连接方案摘要:配对入口 + 提示。
1536
- React.createElement('div', { 'aria-label': '当前连接方案', style: { margin: '0 0 10px', padding: '9px 11px', borderRadius: 10, border: `1px solid ${colors.border}`, background: colors.card, fontSize: 12, lineHeight: 1.7 } },
1537
- React.createElement('div', null, React.createElement('strong', null, '配对入口'), ':', appPlan.entry),
1538
- React.createElement('div', { style: { color: appPlan.valid ? colors.muted : colors.danger } }, appPlan.note)),
1539
- appRoute === 'tailscale'
1540
- ? React.createElement('div', { style: { margin: '0 0 10px', padding: '9px 11px', borderRadius: 10, border: `1px solid ${colors.border}`, background: colors.card, fontSize: 12, lineHeight: 1.7 } },
1541
- React.createElement('div', { style: { fontWeight: 600 } }, (() => {
1542
- const ts = status?.tailscale || {}
1543
- const serve = ts.serve || {}
1544
- if (ts.serveUrl) return '内嵌隧道已连接'
1545
- if (serve.loginUrl) return '内嵌隧道需要授权'
1546
- return '内嵌隧道未启动'
1547
- })()),
1548
- React.createElement('div', { style: { color: colors.muted, marginTop: 2, wordBreak: 'break-all' } }, (() => {
1549
- const ts = status?.tailscale || {}
1550
- const serve = ts.serve || {}
1551
- if (ts.serveUrl) return ts.serveUrl
1552
- if (serve.loginUrl) return '点「去授权」在浏览器完成一次登录,之后地址会自动填入下方。'
1553
- if (serve.backendState && serve.backendState !== 'disabled') return '状态:' + serve.backendState + (serve.error ? '(' + serve.error + ')' : '')
1554
- return '网关内置 Tailscale 节点(userspace,不占系统 VPN)。启动后可自动生成固定地址。'
1555
- })()),
1556
- React.createElement('div', { style: { display: 'flex', gap: 8, marginTop: 8, flexWrap: 'wrap' } },
1557
- (status?.tailscale?.serve?.loginUrl || '') !== ''
1558
- ? React.createElement('button', {
1559
- type: 'button',
1560
- style: { ...styles.button, ...styles.primary },
1561
- onClick: () => window.open('/mgw/tailscale/login', '_blank', 'noopener'),
1562
- }, '去授权')
1563
- : null,
1564
- React.createElement('button', {
1565
- type: 'button',
1566
- style: styles.button,
1567
- onClick: async () => {
1568
- try {
1569
- setBusy(true)
1570
- await request('/mgw/tailscale', {
1571
- method: 'POST',
1572
- headers: { 'Content-Type': 'application/json' },
1573
- body: JSON.stringify({ action: 'start' }),
1574
- })
1575
- const next = await request('/mgw/status')
1576
- setStatus(next)
1577
- } catch (cause) {
1578
- setError(cause.message)
1579
- } finally {
1580
- setBusy(false)
1581
- }
1582
- },
1583
- }, status?.tailscale?.serveUrl ? '重新连接' : '启动隧道')))
1584
- : null,
1585
- React.createElement('label', { style: styles.label, htmlFor: 'mgw-pair-address' }, appRoute === 'tailscale'
1586
- ? '主机 Tailscale 地址(运行网关的电脑,不是手机)'
1587
- : '配对入口地址(手机需能访问)'),
1588
- React.createElement('input', {
1589
- id: 'mgw-pair-address',
1590
- style: styles.input,
1591
- value: appUrl,
1592
- onChange: (event) => {
1593
- const value = event.target.value
1594
- if (appRoute === 'tailscale') { manualAppUrlRef.current = true; setAppUrl(value); return }
1595
- if (appRoute !== 'custom') { chooseAppRoute('custom'); setAppUrl(value); return }
1596
- setAppUrl(value)
1597
- },
1598
- placeholder: appRoute === 'tailscale'
1599
- ? '100.x.x.x 或 ws://100.x.x.x:3081/ws/mobile(IPv6 用 [fd7a:…])'
1600
- : 'ws://192.168.1.10:3081/ws/mobile 或 wss://gateway.example.com/ws/mobile',
1601
- spellCheck: false,
1602
- }),
1603
- appRoute === 'tailscale' && appUrl.trim() && !isTailscaleInput(appUrl)
1604
- ? React.createElement('div', { style: { ...styles.error, margin: '-4px 0 8px' } }, '这里要填 100.64.0.0/10(或 fd7a:115c:a1e0::/48)的 Tailscale 私有地址。')
1605
- : null,
1606
- // Tailscale 手动地址指引:检测到本机地址时提示可直接使用。
1607
- appRoute === 'tailscale'
1608
- ? React.createElement('div', { style: { ...styles.muted, margin: '-4px 0 10px', fontWeight: 500 } }, (() => {
1609
- const detected = Array.isArray(status?.tailscale?.urls) ? status.tailscale.urls : []
1610
- return detected.length
1611
- ? `已检测到本机 Tailscale 地址:${detected.join('、')}(可直接生成二维码)。手机需登录同一 tailnet。`
1612
- : '未检测到本机 Tailscale 地址:请填写运行网关这台主机的 Tailscale IP(不是手机 IP),例如 100.x.x.x。手机与电脑需登录同一 tailnet。'
1613
- })())
1614
- : null,
1615
- appRoute !== 'tailscale' && status && status.lan && status.lan.enabled
1616
- ? React.createElement('div', { style: { ...styles.muted, margin: '-7px 0 10px', fontWeight: 500, color: status.lan.error ? colors.danger : status.lan.listening ? colors.success : 'var(--dsw-alias-link, #4176e6)' } },
1617
- status.lan.error
1618
- ? `局域网监听失败:${status.lan.error}`
1619
- : status.lan.listening
1620
- ? `局域网入口已开启${status.lan.urls && status.lan.urls.length ? `:${status.lan.urls.join('、')}` : `,端口 ${status.lan.port}`}`
1621
- : '局域网入口启动中…')
1622
- : null,
1623
- appRoute === 'cloudflare' && !cloudflareReady
1624
- ? React.createElement('div', { style: { ...styles.muted, margin: '-4px 0 10px', fontWeight: 500 } }, status?.cloudflare?.enabled
1625
- ? 'Cloudflare 外网尚未就绪,请稍候或查看下方 Cloudflare 设置。'
1626
- : '尚未开启 Cloudflare Tunnel,可在下方设置中一键开启。')
1627
- : null,
1628
- React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' } },
1629
- React.createElement('button', {
1630
- style: { ...styles.button, ...styles.primary, opacity: appPairingDisabled ? .65 : 1 },
1631
- disabled: appPairingDisabled,
1632
- onClick: () => pairFor('app'),
1633
- }, busy ? '正在生成…' : !(status && status.gatewayEnabled) ? '请先开启移动网关'
1634
- : appRoute === 'cloudflare' && !cloudflareReady
1635
- ? status?.cloudflare?.enabled ? '等待 Cloudflare 外网就绪' : '先开启 Cloudflare Tunnel'
1636
- : appRoute === 'tailscale' && !status?.lan?.listening ? '请先开启局域网入口'
1637
- : appRoute === 'tailscale' && !isTailscaleInput(appUrl) ? '填写主机 Tailscale 地址'
1638
- : appRoute === 'lan' && !lanPairingUrl(status) ? '当前不可用'
1639
- : appRoute === 'custom' && !appUrl.trim() ? '等待连接地址' : '生成 App 二维码'),
1640
- React.createElement('span', { style: styles.muted }, '二维码只发给 App;小程序请用下方模块。')))
1641
- : React.createElement('p', { style: { ...styles.muted, margin: '8px 0 0' } }, '局域网直连 / Cloudflare 外网 / Tailscale 私有网络 / 公网或其他手动地址;与鲸尾公网互不影响。')),
1642
- appLayerOpen && appRoute === 'cloudflare' && status?.cloudflare?.supported
1643
- ? React.createElement('section', { className: 'mgw-cloudflare-block', style: { ...styles.card, background: colors.card, border: 0, borderRadius: 16, padding: 18, marginTop: 16 } },
1644
- React.createElement('h3', { className: 'mgw-section-title' }, 'Cloudflare Tunnel · 外网接入'),
1645
- React.createElement('p', { style: styles.muted }, status.platform === 'linux'
1646
- ? 'Linux 服务器不自动下载:请先安装 cloudflared(Cloudflare 官方源 pkg.cloudflare.com 的 cloudflared 包),或将插件配置 cloudflaredPath 指向已有可执行文件。DSH App 和小程序均可使用已配置的公网入口,并且仍要求设备鉴权。'
1647
- : '首次开启自动准备 Tunnel 组件。'),
1648
- React.createElement('div', { className: 'mgw-setting-row' },
1649
- React.createElement('span', { className: 'mgw-setting-label' }, '接入方式'),
1650
- React.createElement(GatewaySelect, { style: styles.input, value: cloudflareMode, 'aria-label': 'Cloudflare 接入方式', onChange: (event) => {
1651
- const mode = event.target.value
1652
- setCloudflareMode(mode)
1653
- if (status.cloudflare.enabled && mode !== status.cloudflare.mode &&
1654
- (mode === 'quick' || (status.cloudflare.configured && cloudflareHost === status.cloudflare.hostname && !cloudflareToken))) {
1655
- void configureCloudflare(true, mode)
1656
- }
1657
- }, disabled: cloudflareBusy },
1658
- React.createElement('option', { value: 'quick' }, 'Quick Tunnel · 无需域名'),
1659
- React.createElement('option', { value: 'named' }, '命名 Tunnel · 固定域名'))),
1660
- cloudflareMode === 'quick'
1661
- ? React.createElement('p', { style: styles.muted }, '临时地址可能变化,变化后需重新扫码。')
1662
- : React.createElement(React.Fragment, null,
1663
- React.createElement('p', { style: styles.muted }, '先在 Cloudflare 创建命名 Tunnel,把公开域名的 Service URL 设为 ', React.createElement('code', null, `http://127.0.0.1:${status.cloudflare.port}`), '。Tunnel Token 仅授权连接,不能自动创建公开主机名或 DNS;还需确认域名存在指向 Tunnel UUID.cfargotunnel.com 的已代理 CNAME 记录。'),
1664
- React.createElement('div', { style: { display: 'flex', gap: 14, flexWrap: 'wrap', margin: '2px 0 4px' } },
1665
- React.createElement('a', { href: 'https://dash.cloudflare.com/?to=/:account/tunnels', target: '_blank', rel: 'noreferrer', style: { color: 'var(--dsw-alias-link, #4176e6)', fontSize: 12, fontWeight: 500, textDecoration: 'none' } }, 'Cloudflare 控制台 → 隧道 ↗'),
1666
- React.createElement('a', { href: 'https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/get-started/create-remote-tunnel/', target: '_blank', rel: 'noreferrer', style: { color: 'var(--dsw-alias-link, #4176e6)', fontSize: 12, fontWeight: 500, textDecoration: 'none' } }, '官方创建教程 ↗')),
1667
- React.createElement('p', { style: styles.muted }, 'Token 在控制台建好 Tunnel 后选择操作系统给出的安装命令里,是 eyJ… 开头的一段(只用它,不需要在 NAS 上执行该命令)。'),
1668
- React.createElement('label', { style: styles.label }, '公开域名'),
1669
- React.createElement('input', { style: styles.input, value: cloudflareHost, onChange: (event) => setCloudflareHost(event.target.value.trim()), placeholder: 'gateway.example.com', spellCheck: false }),
1670
- React.createElement('label', { style: styles.label }, 'Tunnel Token'),
1671
- React.createElement('input', { style: styles.input, type: 'password', value: cloudflareToken, onChange: (event) => setCloudflareToken(event.target.value.trim()), placeholder: status.cloudflare.configured ? '已保存;留空则保持原 Token' : '粘贴 eyJ… Token', autoComplete: 'off', spellCheck: false })),
1672
- (!status.cloudflare.enabled || (cloudflareMode === 'named' &&
1673
- (status.cloudflare.mode !== 'named' || cloudflareHost !== status.cloudflare.hostname || !!cloudflareToken)))
1674
- ? React.createElement('button', {
1675
- style: { ...styles.button, ...styles.primary, opacity: cloudflareBusy || (cloudflareMode === 'named' && (!cloudflareHost || (!cloudflareToken && !status.cloudflare.configured))) ? .65 : 1 },
1676
- disabled: cloudflareBusy || (cloudflareMode === 'named' && (!cloudflareHost || (!cloudflareToken && !status.cloudflare.configured))),
1677
- onClick: () => configureCloudflare(true),
1678
- }, cloudflareBusy ? '正在处理…' : status.cloudflare.enabled ? '保存并连接' : cloudflareMode === 'quick' ? '一键开启 Quick Tunnel' : '开启命名 Tunnel') : null,
1679
- status.cloudflare.enabled
1680
- ? React.createElement(React.Fragment, null,
1681
- React.createElement('button', { style: { ...styles.button, width: '100%', marginTop: 8 }, disabled: cloudflareBusy || status.cloudflare.state !== 'online', onClick: checkCloudflare }, '检测公网 DNS / TLS / WebSocket'),
1682
- React.createElement('button', { style: { ...styles.button, width: '100%', marginTop: 8 }, disabled: cloudflareBusy || !status.gatewayEnabled, onClick: restartCloudflare }, '重启 Tunnel'),
1683
- React.createElement('button', { style: { ...styles.button, width: '100%', marginTop: 8 }, disabled: cloudflareBusy, onClick: () => configureCloudflare(false) }, '关闭 Cloudflare Tunnel'),
1684
- React.createElement('p', { style: styles.muted }, '重启会短暂断开连接。'))
1685
- : null,
1686
- React.createElement('div', { style: { ...styles.muted, marginTop: 9, overflowWrap: 'anywhere', fontWeight: 500, color: status.cloudflare.error ? colors.danger : status.cloudflare.state === 'online' ? colors.success : ['starting', 'preparing', 'connecting'].includes(status.cloudflare.state) ? 'var(--dsw-alias-link, #4176e6)' : colors.muted } },
1687
- status.cloudflare.error || ({ disabled: '未开启', starting: '正在启动本机入口…', preparing: '正在准备 cloudflared(首次需下载)…', connecting: '正在连接 Cloudflare…', online: '隧道传输已连接(不等于公网入口可达)', 'waiting-for-gateway': '等待移动网关开启' }[status.cloudflare.state] || status.cloudflare.state),
1688
- status.cloudflare.publicUrl ? ` · ${status.cloudflare.publicUrl}` : ''),
1689
- status.cloudflare.enabled && status.cloudflare.endpointHealth
1690
- ? React.createElement('p', { style: { ...styles.muted, overflowWrap: 'anywhere', fontWeight: 500, color: status.cloudflare.endpointHealth.state === 'reachable' ? colors.success : status.cloudflare.endpointHealth.state === 'checking' ? 'var(--dsw-alias-link, #4176e6)' : status.cloudflare.endpointHealth.state === 'unchecked' ? colors.muted : colors.danger } },
1691
- status.cloudflare.endpointHealth.message,
1692
- status.cloudflare.endpointHealth.checkedAt ? `(检测时间:${status.cloudflare.endpointHealth.checkedAt})` : '')
1693
- : null)
1694
- : null,
1695
- status && status.platform === 'linux' ? React.createElement('section', { style: styles.card },
1696
- React.createElement('h3', { className: 'mgw-section-title' }, '公网接入'),
1697
- publicSetup === null
1698
- ? React.createElement('p', { style: styles.muted }, '正在检查系统组件…')
1699
- : publicSetup.installed
1700
- ? React.createElement(React.Fragment, null,
1701
- React.createElement('div', { style: { ...styles.muted, margin: '5px 0 12px' } }, publicSetup.configured
1702
- ? publicSetup.backendPort && status && status.webPort && publicSetup.backendPort !== status.webPort
1703
- ? `端口需要更新:Nginx 当前为 ${publicSetup.backendPort},DSH 当前为 ${status.webPort}`
1704
- : `已配置${publicSetup.backendPort ? `,Nginx 转发至 DSH 端口 ${publicSetup.backendPort}` : ''}`
1705
- : `Helper 已就绪,将自动使用当前 DSH 端口${status && status.webPort ? ` ${status.webPort}` : ''}`),
1706
- React.createElement('label', { style: styles.label }, '服务器公网 IPv4'),
1707
- React.createElement('input', {
1708
- style: styles.input,
1709
- value: publicIp,
1710
- onChange: (event) => setPublicIp(event.target.value.trim()),
1711
- placeholder: '203.0.113.10',
1712
- inputMode: 'decimal',
1713
- spellCheck: false,
1714
- }),
1715
- React.createElement('button', {
1716
- style: { ...styles.button, ...styles.primary, opacity: publicSetupBusy || !publicIp ? .65 : 1 },
1717
- disabled: publicSetupBusy || !publicIp,
1718
- onClick: configurePublicAccess,
1719
- }, publicSetupBusy ? '正在配置 Nginx 与证书…' : publicSetup.configured ? '更新公网配置' : '配置公网接入'),
1720
- publicSetup.publicUrl
1721
- ? React.createElement('div', { style: { ...styles.muted, marginTop: 9, overflowWrap: 'anywhere' } }, publicSetup.publicUrl)
1722
- : null)
1723
- : React.createElement(React.Fragment, null,
1724
- React.createElement('p', { style: { ...styles.muted, marginBottom: 8 } }, '尚未安装系统 Helper。请在服务器执行一次初始化:'),
1725
- React.createElement('code', { style: { display: 'block', fontSize: 10, lineHeight: 1.5, overflowWrap: 'anywhere', userSelect: 'all' } }, 'npx --yes dsh-plugin-mobile-gateway@latest init'))) : null,
1726
-
1727
- // ── 模块二:小程序连接(备用)────────────────────────────────────
1728
- React.createElement('section', { style: styles.card },
1729
- React.createElement('div', { style: { position: 'relative', display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }, onMouseLeave: () => setConnectionHelpOpen(false) },
1730
- React.createElement('h3', { className: 'mgw-section-title', style: { marginBottom: 0 } }, '小程序连接(备用)'),
1731
- React.createElement('button', {
1732
- type: 'button',
1733
- style: styles.helpButton,
1734
- 'aria-label': '连接方式说明与场景建议',
1735
- 'aria-expanded': connectionHelpOpen,
1736
- 'aria-describedby': connectionHelpOpen ? 'mgw-route-help' : undefined,
1737
- onMouseEnter: () => setConnectionHelpOpen(true),
1738
- onFocus: () => setConnectionHelpOpen(true),
1739
- onBlur: () => setConnectionHelpOpen(false),
1740
- onClick: () => setConnectionHelpOpen(true),
1741
- onKeyDown: (event) => { if (event.key === 'Escape') setConnectionHelpOpen(false) },
1742
- }, '?'),
1743
- connectionHelpOpen ? React.createElement('div', { id: 'mgw-route-help', role: 'tooltip', style: styles.helpBubble },
1744
- React.createElement('strong', null, '怎么选连接方式'),
1745
- helpLine('小程序连接(备用)', '鲸尾小程序在微信里通过鲸尾公网中继连接,不受 wss 域名限制;手机与网关在同一局域网时自动兜底直连。'),
1746
- helpLine('鲸尾公网 · 小程序', '小程序专用二维码:中继优先、局域网兜底;无需公网域名。'),
1747
- helpLine('DSH App(推荐)', 'DSH App 使用直连入口:自动选择、局域网直连、Cloudflare 外网、Tailscale 私有网络或公网/手动地址。'),
1748
- helpLine('自动选择(App)', '优先已就绪的公网入口,同时保留局域网与 Tailscale 地址;没有公网入口时使用局域网。'),
1749
- helpLine('局域网直连', '手机与 DSH 在同一个可互访的局域网,使用 ws:// 私有地址;离开该网络就无法直连。'),
1750
- helpLine('Cloudflare 外网', 'PC 主动连接 Cloudflare,外网用固定域名的 wss://;需要 Cloudflare 账户和域名。'),
1751
- helpLine('Tailscale 私有网络', '可检测本机地址,或填写主机的 100.x 私有地址;手机与电脑需登录同一 tailnet。'),
1752
- helpLine('公网或其他手动地址', '已配置公网 WSS 反代或只想指定一个固定地址时使用;编辑下方地址即可。'),
1753
- React.createElement('div', { style: { borderTop: `1px solid ${colors.border}`, marginTop: 10, paddingTop: 8 } },
1754
- React.createElement('strong', null, '结合当前环境'),
1755
- React.createElement('div', { style: { color: colors.muted, marginTop: 4 } }, advice.detected),
1756
- React.createElement('div', { style: { marginTop: 6 } }, advice.local),
1757
- React.createElement('div', { style: { marginTop: 6 } }, advice.remote),
1758
- React.createElement('div', { style: { color: colors.muted, marginTop: 6 } }, '面板无法判断手机当前网络;请按手机所在位置选择,提示不会替你修改选择。')))
1759
- : null),
1760
- React.createElement('p', { style: styles.muted }, '小程序默认通过鲸尾公网中继连接,不需要公网域名;手机与网关在同一局域网时自动兜底直连。'),
1761
-
1762
- // 中继信息块属于小程序模块(自动选择 / 鲸尾公网中继)。
1763
- (relayInfo || relayConnector?.running || relayConnector?.delegatedTo || relayConnector?.lastError)
1764
- ? (relayInfo
1765
- ? React.createElement('div', { style: { ...styles.muted, margin: '2px 0 0', fontWeight: 500 } },
1766
- '鲸尾公网服务 · 已注册', ' · ',
1767
- React.createElement('span', { style: { opacity: .8 } }, `设备 ID ${relayInfo.nodeId.slice(0, 8)}… · ${relayInfo.gatewayName}`),
1768
- React.createElement('div', { style: { marginTop: 4, color: relayConnector?.lastError ? colors.danger : relayConnector?.running || relayConnector?.delegatedTo ? colors.success : 'var(--dsw-alias-link, #4176e6)' } },
1769
- relayConnector?.running || relayConnector?.delegatedTo
1770
- ? '中继连接保持运行'
1771
- : relayConnector?.lastError ? `中继连接器异常:${relayConnector.lastError}`
1772
- : '中继连接器正在恢复…'))
1773
- : relayConnector && relayConnector.running
1774
- ? React.createElement('div', { style: { ...styles.muted, margin: '2px 0 0', fontWeight: 500,
1775
- color: 'var(--dsw-alias-link, #4176e6)' } }, '内置连接器已自动启动,正在连接中继并上报身份…')
1776
- : relayConnector && relayConnector.lastError
1777
- ? React.createElement('div', { style: { ...styles.muted, margin: '2px 0 0', fontWeight: 500, color: colors.danger } },
1778
- '公网连接器暂时不可用,请检查网络或重新开启公网连接。', ' ',
1779
- React.createElement('span', { style: { opacity: .8 } }, '如已自行部署连接器,请执行 systemctl restart dsh-connector。'))
1780
- : React.createElement('div', { style: { ...styles.muted, margin: '2px 0 0' } }, '正在启动内置连接器…(中继模式需要一个本地连接器把小程序流量桥接进来,插件会自动准备)'))
1781
- : null,
1782
- React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap', marginTop: 10 } },
1783
- React.createElement('button', {
1784
- style: { ...styles.button, ...styles.primary, opacity: busy || !(status && status.gatewayEnabled) || !status?.relay || !lanPairingUrl(status) ? .65 : 1 },
1785
- disabled: busy || !(status && status.gatewayEnabled) || !status?.relay || !lanPairingUrl(status),
1786
- onClick: () => pairFor('mini'),
1787
- }, busy ? '正在生成…' : !(status && status.gatewayEnabled) ? '请先开启移动网关'
1788
- : !status?.relay ? '请先注册鲸尾公网中继'
1789
- : !lanPairingUrl(status) ? '请先开启局域网入口' : '生成小程序二维码'),
1790
- React.createElement('span', { style: styles.muted }, '配对码仅可使用一次,5 分钟内有效。'))),
1791
- ),
1792
- React.createElement('div', { hidden: activeSection !== 'devices' },
1793
- React.createElement('section', { style: styles.card },
1794
- React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center' } },
1795
- React.createElement('h3', { className: 'mgw-section-title', style: { marginBottom: 0 } }, '可信设备'),
1796
- React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 10 } },
1797
- deviceNotice || refreshNotice ? React.createElement('span', {
1798
- style: { ...styles.muted, color: deviceNoticeError ? colors.danger : colors.success },
1799
- }, deviceNotice || refreshNotice) : null,
1800
- React.createElement('button', {
1801
- style: { ...styles.button, opacity: offlineDevices.length === 0 ? .55 : 1, color: colors.danger },
1802
- disabled: offlineDevices.length === 0 || offlineClearing,
1803
- title: '吊销所有当前离线的已配对设备',
1804
- onClick: clearOfflineDevices,
1805
- }, offlineClearing ? '清除中…' : `一键清除离线设备(${offlineDevices.length})`),
1806
- React.createElement('button', {
1807
- style: { ...styles.button, opacity: refreshing ? .6 : 1 },
1808
- disabled: refreshing,
1809
- onClick: manualRefresh,
1810
- }, refreshing ? '刷新中…' : '刷新'))),
1811
- devices === null
1812
- ? React.createElement('p', { style: styles.muted }, '加载中…')
1813
- : devices.length === 0
1814
- ? React.createElement('p', { style: styles.muted }, '暂无已配对设备。')
1815
- : React.createElement(React.Fragment, null,
1816
- visibleDevices.length === 0 ? React.createElement('p', { style: styles.muted }, '当前没有在线设备。') : null,
1817
- visibleDevices.map((device) => React.createElement(DeviceRow, {
1818
- key: device.id,
1819
- device,
1820
- onRevoke: revoke,
1821
- revoking: revokingIds.has(device.id),
1822
- })),
1823
- offlineDevices.length > 0 ? React.createElement('button', {
1824
- type: 'button',
1825
- style: { ...styles.button, marginTop: 10, color: colors.muted },
1826
- 'aria-expanded': showAllDevices,
1827
- onClick: () => setShowAllDevices((value) => !value),
1828
- }, showAllDevices ? '收起离线设备' : `展开其他已配对设备(${offlineDevices.length})`) : null)),
1829
- )),
1830
- ),
1831
- status && status.version
1832
- ? React.createElement('div', { style: styles.version, 'aria-label': `插件版本 ${status.version}` }, `v${status.version}`)
1833
- : null))
1834
- }
1835
-
1836
- // Fork: the entry is a Settings section instead of a sidebar footer button.
1837
- // Tapping the Settings nav item opens the management dialog directly — the
1838
- // dialog itself is upstream's unchanged shell.
1839
- function SettingsEntry() {
1840
- const isOpen = React.useSyncExternalStore(subscribe, getOpen, () => false)
1841
- React.useEffect(() => { setOpen(true) }, [])
1842
- return isOpen ? React.createElement(DevicePanel) : null
1843
- }
1844
-
1845
- // 侧边栏入口:与上游一致,在 Harness WebUI 侧边栏底部放一个「鲸尾移动设备」
1846
- // 按钮,点击打开同一个管理弹窗;设置页入口保留,两个入口共享同一 open 状态。
1847
- function FooterButton(props) {
1848
- const isOpen = React.useSyncExternalStore(subscribe, getOpen, () => false)
1849
- const visible = React.useSyncExternalStore(subscribeSidebar, getSidebarEntry, () => true)
1850
- if (!visible) return null
1851
- const wide = !!props.wide
1852
- const iconSize = wide ? 20 : 22
1853
- const icon = React.createElement('svg', { width: iconSize, height: iconSize, viewBox: '0 0 24 24', fill: 'none',
1854
- stroke: 'currentColor', strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true, style: { flexShrink: 0 } },
1855
- React.createElement('rect', { x: 6, y: 2, width: 12, height: 20, rx: 2.5 }),
1856
- React.createElement('path', { d: 'M10 18h4' }))
1857
- return React.createElement('button', {
1858
- type: 'button', title: '鲸尾移动设备', 'aria-label': '鲸尾移动设备', 'aria-pressed': isOpen,
1859
- onClick: () => setOpen(!isOpen),
1860
- style: { cursor: 'pointer', background: 'transparent', border: 'none', color: 'inherit', font: 'inherit',
1861
- display: 'flex', alignItems: 'center', justifyContent: wide ? 'flex-start' : 'center', gap: wide ? 8 : 0,
1862
- boxSizing: 'border-box', width: wide ? 'calc(100% + 4px)' : 36, height: wide ? 42 : 36,
1863
- margin: wide ? '4px -2px' : '3px 0', padding: wide ? '0 10px 0 8px' : 0, lineHeight: wide ? '22px' : 'normal' },
1864
- }, icon, wide ? React.createElement('span', null, '鲸尾移动设备') : null)
1865
- }
1866
-
1867
- function OverlayEntry() {
1868
- const isOpen = React.useSyncExternalStore(subscribe, getOpen, () => false)
1869
- return isOpen ? React.createElement(DevicePanel, null) : null
1870
- }
1871
- const inject = ['slots']
1872
- function apply(ctx) {
1873
- // Upstream 0.10.1: the panel stylesheet is injected once through an
1874
- // effect instead of being re-rendered inside the component tree.
1875
- ctx.effect(() => {
1876
- const style = document.createElement('style')
1877
- style.textContent = panelCss
1878
- document.head.appendChild(style)
1879
- return () => style.remove()
1880
- }, 'mobile-gateway: panel styles')
1881
- pinNavGlyph([NAV_LABEL], NAV_ICON_MARK, navGlyph)
1882
- // Fork: the entry is a Settings section, not the upstream sidebar footer
1883
- // button. The id deliberately stays 'mobile-gateway' (not the package
1884
- // name): it is a slot key that pinned-section state and the settings
1885
- // plugin-hub map against, so renaming it would drop existing pins.
1886
- ctx.slots.inject('settings.section', () => ctx.slots.register(
1887
- { name: 'settings.section', id: 'mobile-gateway', order: 35, label: () => NAV_LABEL },
1888
- () => React.createElement(SettingsEntry, null),
1889
- ))
1890
- // 侧边栏入口的显示开关来自管理接口;读取失败时保持默认显示。
1891
- void request('/mgw/ui').then((data) => setSidebarEntry(data.sidebarEntry !== false)).catch(() => {})
1892
- // 与上游一致:侧边栏底部入口 + shell overlay,共享同一个 open 状态。
1893
- ctx.slots.inject('sidebar.footer.action', () => ctx.slots.register(
1894
- { name: 'sidebar.footer.action', id: 'mobile-gateway-devices', order: 80, label: '鲸尾移动设备' },
1895
- (props) => React.createElement(FooterButton, props),
1896
- ))
1897
- ctx.slots.inject('shell.overlay', () => ctx.slots.register(
1898
- { name: 'shell.overlay', id: 'mobile-gateway-devices-panel', order: 100, label: '移动设备' },
1899
- () => React.createElement(OverlayEntry, null),
1900
- ))
1901
- }
1902
-
1903
- exports.apply = apply
1904
- exports.inject = inject
1905
- exports.pinNavGlyph = pinNavGlyph
1906
- // Exposed for tests: the Settings entry and the dialog body render separately.
1907
- exports.SettingsEntry = SettingsEntry
1908
- exports.DevicePanel = DevicePanel
1909
- return module.exports
1910
- },
1911
- })
1
+ // Browser half of dsh-plugin-mobile-gateway. The package manifest makes this
2
+ // bundle part of DSH's client-module graph; it contributes one Settings
3
+ // section that opens the management dialog, without replacing shipped UI seats.
4
+ window.__ModuleLoader__.load({
5
+ id: 'dsh-plugin-weapp-gateway',
6
+ factory: (require) => {
7
+ const React = require('react')
8
+ const module = { exports: {} }
9
+ const exports = module.exports
10
+
11
+ let open = false
12
+ const listeners = new Set()
13
+ const setOpen = (value) => {
14
+ open = value
15
+ for (const listener of listeners) listener()
16
+ }
17
+ const subscribe = (listener) => {
18
+ listeners.add(listener)
19
+ return () => listeners.delete(listener)
20
+ }
21
+ const getOpen = () => open
22
+
23
+ // 侧边栏入口开关:由管理接口 /mgw/ui 持久化;apply() 时读取一次,
24
+ // 面板内切换后立即通知侧边栏按钮显示/隐藏。
25
+ let sidebarEntry = true
26
+ const sidebarListeners = new Set()
27
+ const getSidebarEntry = () => sidebarEntry
28
+ const setSidebarEntry = (value) => {
29
+ const next = value !== false
30
+ if (next === sidebarEntry) return
31
+ sidebarEntry = next
32
+ for (const listener of sidebarListeners) listener()
33
+ }
34
+ const subscribeSidebar = (listener) => {
35
+ sidebarListeners.add(listener)
36
+ return () => sidebarListeners.delete(listener)
37
+ }
38
+
39
+ // Shared Web UI / Desktop semantic tokens update with the host theme.
40
+ const restartNoticeStorageKey = 'mobile-gateway-dismissed-restart-notice'
41
+ let dismissedRestartInstance = null
42
+ try { dismissedRestartInstance = window.localStorage.getItem(restartNoticeStorageKey) } catch { /* storage unavailable */ }
43
+
44
+ const colors = {
45
+ panel: 'var(--dsw-alias-bg-layer-2, var(--color-bg, Canvas))',
46
+ card: 'var(--dsw-alias-bg-module-platform, var(--color-bg-elevated, Canvas))',
47
+ text: 'var(--dsw-alias-label-primary, var(--color-text, CanvasText))',
48
+ muted: 'var(--dsw-alias-label-secondary, var(--color-text-muted, GrayText))',
49
+ border: 'var(--dsw-alias-border-l3, var(--color-border, rgba(127,127,127,.24)))',
50
+ accent: 'var(--dsw-alias-button-primary-fill, var(--color-primary, #4f7cff))',
51
+ accentText: 'var(--dsw-alias-label-primary-foreground, #fff)',
52
+ danger: 'var(--dsw-alias-state-error-primary, #dc4c64)',
53
+ success: 'var(--dsw-alias-state-success-primary, #2fb171)',
54
+ }
55
+ const styles = {
56
+ backdrop: {
57
+ position: 'fixed', inset: 0, zIndex: 1200, pointerEvents: 'auto',
58
+ background: 'var(--dsw-alias-bg-mask-1, rgba(0,0,0,.32))', display: 'flex',
59
+ justifyContent: 'center', alignItems: 'center',
60
+ padding: 'max(16px, var(--dsh-frame-overlay-top, 16px)) 16px', boxSizing: 'border-box',
61
+ },
62
+ panel: {
63
+ width: 'clamp(640px, 84vw, 1120px)', maxWidth: '100%', maxHeight: '100%', minHeight: 0, height: 'min(780px, calc(100dvh - 48px))', overflow: 'hidden',
64
+ scrollbarWidth: 'none', msOverflowStyle: 'none',
65
+ display: 'flex', flexDirection: 'column',
66
+ background: colors.panel, color: colors.text, border: `1px solid ${colors.border}`, borderRadius: 'var(--dsw-radius-panel, 16px)',
67
+ boxShadow: 'var(--dsw-elevation-prominent, 0 20px 60px rgba(0,0,0,.22))', padding: 24,
68
+ fontFamily: 'var(--dsw-font-family, system-ui, sans-serif)', fontSize: 13, boxSizing: 'border-box',
69
+ },
70
+ header: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18, flexShrink: 0 },
71
+ title: { margin: 0, fontSize: 22, fontWeight: 650 },
72
+ card: { background: 'transparent', border: 0, borderBottom: `1px solid ${colors.border}`, borderRadius: 0, padding: '16px 0', marginBottom: 0, flexShrink: 0 },
73
+ label: { display: 'block', color: colors.muted, fontSize: 12, marginBottom: 6 },
74
+ input: { width: '100%', boxSizing: 'border-box', border: `1px solid ${colors.border}`, borderRadius: 10, padding: '8px 12px', marginBottom: 8, background: colors.card, color: 'inherit', outline: 'none' },
75
+ pairingText: { width: '100%', minHeight: 86, boxSizing: 'border-box', resize: 'vertical', border: `1px solid ${colors.border}`, borderRadius: 8, padding: '9px 10px', margin: '10px 0', background: 'transparent', color: 'inherit', outline: 'none', fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace', fontSize: 11, lineHeight: 1.45, overflowWrap: 'anywhere' },
76
+ button: { cursor: 'pointer', border: `1px solid ${colors.border}`, background: 'transparent', borderRadius: 8, padding: '7px 11px', color: 'inherit', font: 'inherit' },
77
+ headerButton: { width: 34, height: 34, boxSizing: 'border-box', border: 0, padding: 0, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 },
78
+ primary: { background: colors.accent, color: colors.accentText, borderColor: colors.accent, width: '100%' },
79
+ muted: { color: colors.muted, fontSize: 12, lineHeight: 1.45 },
80
+ row: { display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) auto', columnGap: 12, alignItems: 'center', padding: '12px 0', borderBottom: `1px solid ${colors.border}` },
81
+ badge: { display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11, marginLeft: 8, color: colors.muted },
82
+ dot: { width: 7, height: 7, borderRadius: 99, display: 'inline-block' },
83
+ error: { color: colors.danger, background: 'rgba(220,76,100,.12)', borderRadius: 8, padding: 10, marginBottom: 12 },
84
+ qr: { display: 'block', width: 220, height: 220, margin: '12px auto', background: '#fff', borderRadius: 10, padding: 8 },
85
+ helpButton: { width: 20, height: 20, boxSizing: 'border-box', padding: 0, borderRadius: '50%', border: 0, background: 'var(--dsw-alias-interactive-bg-hover, rgba(127,127,127,.1))', color: 'var(--dsw-alias-label-tertiary, #888)', cursor: 'help', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, fontSize: 12, fontWeight: 600, lineHeight: 1 },
86
+ helpBubble: { position: 'absolute', top: '100%', left: 0, zIndex: 20, width: 'min(300px, calc(100vw - 88px))', maxHeight: 'min(440px, calc(100vh - 160px))', overflowY: 'auto', boxSizing: 'border-box', padding: 12, borderRadius: 10, border: `1px solid ${colors.border}`, background: colors.panel, color: colors.text, boxShadow: '0 12px 28px rgba(0,0,0,.35)', fontSize: 12, lineHeight: 1.5 },
87
+ toolsMenu: { position: 'absolute', top: 'calc(100% + 6px)', right: 0, zIndex: 30, width: 250, maxWidth: 'calc(100vw - 48px)', border: `1px solid ${colors.border}`, borderRadius: 10, padding: 5, background: colors.panel, boxShadow: '0 12px 28px rgba(0,0,0,.35)' },
88
+ toolsItem: { display: 'block', width: '100%', padding: '9px 10px', textAlign: 'left', border: 0, borderRadius: 7, background: 'transparent', color: colors.text, font: 'inherit', cursor: 'pointer' },
89
+ switch: { position: 'relative', display: 'inline-flex', width: 42, height: 24, flexShrink: 0 },
90
+ switchInput: { position: 'absolute', opacity: 0, width: 1, height: 1 },
91
+ switchTrack: { position: 'absolute', inset: 0, borderRadius: 99, transition: 'background .18s ease', cursor: 'pointer' },
92
+ switchKnob: { position: 'absolute', top: 3, width: 18, height: 18, borderRadius: 99, background: '#fff', boxShadow: '0 1px 3px rgba(0,0,0,.35)', transition: 'left .18s ease', pointerEvents: 'none' },
93
+ version: { flexShrink: 0, marginTop: 'auto', padding: '18px 2px 0', color: colors.muted, fontSize: 11, lineHeight: 1.4, textAlign: 'right', letterSpacing: '.02em' },
94
+ }
95
+
96
+ const panelCss = `
97
+ @keyframes mgw-pairing-enter {
98
+ from { opacity: 0; transform: scale(.82); }
99
+ to { opacity: 1; transform: scale(1); }
100
+ }
101
+ .mgw-pairing-dialog {
102
+ transform-origin: center;
103
+ animation: mgw-pairing-enter 240ms cubic-bezier(.2, .8, .2, 1);
104
+ }
105
+ @keyframes mgw-pairing-exit {
106
+ from { opacity: 1; transform: scale(1); }
107
+ to { opacity: 0; transform: scale(.82); }
108
+ }
109
+ .mgw-pairing-dialog[data-closing="true"] {
110
+ animation: mgw-pairing-exit 180ms ease-in forwards;
111
+ pointer-events: none;
112
+ }
113
+ @media (prefers-reduced-motion: reduce) {
114
+ .mgw-pairing-dialog { animation: none; }
115
+ }
116
+ .mobile-gateway-panel, .mobile-gateway-panel *, .mgw-pairing-dialog, .mgw-pairing-dialog *, .mgw-select-menu {
117
+ scrollbar-width: none !important;
118
+ -ms-overflow-style: none;
119
+ }
120
+ .mobile-gateway-panel::-webkit-scrollbar, .mobile-gateway-panel *::-webkit-scrollbar,
121
+ .mgw-pairing-dialog::-webkit-scrollbar, .mgw-pairing-dialog *::-webkit-scrollbar, .mgw-select-menu::-webkit-scrollbar {
122
+ display: none !important;
123
+ width: 0;
124
+ height: 0;
125
+ }
126
+ .mobile-gateway-panel .mgw-body { display: grid; grid-template-columns: 180px minmax(0, 1fr); gap: 28px; flex: 1; min-height: 0; }
127
+ .mobile-gateway-panel .mgw-nav { display: flex; flex-direction: column; gap: 4px; }
128
+ .mobile-gateway-panel .mgw-nav button { text-align: left; border: 0; padding: 12px 14px; border-radius: 10px; background: transparent; color: inherit; font: inherit; cursor: pointer; }
129
+ .mobile-gateway-panel .mgw-nav button[aria-current="page"] { background: var(--dsw-alias-bg-overlay, rgba(127,127,127,.12)); font-weight: 500; }
130
+ .mobile-gateway-panel .mgw-nav button:hover { background: var(--dsw-alias-interactive-bg-hover, rgba(127,127,127,.08)); }
131
+ .mobile-gateway-panel .mgw-content { min-width: 0; overflow-y: auto; scrollbar-width: none; padding-right: 4px; }
132
+ .mobile-gateway-panel .mgw-content::-webkit-scrollbar { display: none; }
133
+ .mobile-gateway-panel .mgw-content p { margin: 6px 0 10px; }
134
+ .mobile-gateway-panel strong { font-weight: 550; }
135
+ .mobile-gateway-panel .mgw-device-permissions > summary::-webkit-details-marker { display: none; }
136
+ .mobile-gateway-panel .mgw-device-permissions[open] > summary .mgw-permissions-chevron { transform: rotate(90deg); }
137
+ .mobile-gateway-panel .mgw-section-title { margin: 0 0 10px; font-size: 17px; line-height: 1.4; font-weight: 650; color: inherit; }
138
+ .mobile-gateway-panel .mgw-setting-row { display: flex; flex-direction: column; align-items: flex-start; gap: 8px; margin-bottom: 12px; }
139
+ .mobile-gateway-panel .mgw-setting-row select { width: auto !important; max-width: 100%; min-width: 150px; margin-bottom: 0 !important; flex-shrink: 1; }
140
+ .mobile-gateway-panel .mgw-cloudflare-block input, .mobile-gateway-panel .mgw-cloudflare-block .mgw-select-trigger { background: var(--dsw-alias-bg-layer-2, Canvas) !important; }
141
+ .mobile-gateway-panel .mgw-setting-label { font-size: 14px; font-weight: 550; color: inherit; }
142
+
143
+ .mobile-gateway-panel input:focus-visible, .mobile-gateway-panel select:focus-visible, .mobile-gateway-panel button:focus-visible { outline: 2px solid var(--dsw-alias-label-primary, currentColor); outline-offset: 2px; }
144
+ @media (max-width: 640px) {
145
+ .mobile-gateway-panel .mgw-body { grid-template-columns: minmax(0, 1fr); gap: 8px; }
146
+ /* Fork: the dialog nav is not the settings rail — keep it a tab strip.
147
+ dsh-settings-mobile-nav collapses the first <nav> of any settings
148
+ dialog, which used to swallow ours and leave a lone expand button.
149
+ A stable height plus the marker below opts out. */
150
+ .mobile-gateway-panel .mgw-nav { flex-direction: row; flex-wrap: nowrap; }
151
+ .mobile-gateway-panel .mgw-nav button {
152
+ flex: 1 1 0; min-width: 0; min-height: 40px; height: 40px;
153
+ padding: 8px 6px; text-align: center; white-space: nowrap;
154
+ overflow: hidden; text-overflow: ellipsis;
155
+ }
156
+ }
157
+ `
158
+
159
+ function GatewaySelect({ style, children, value, onChange, disabled, ...props }) {
160
+ const options = React.Children.toArray(children).filter((child) => React.isValidElement(child))
161
+ const [menu, setMenu] = React.useState(null)
162
+ const [active, setActive] = React.useState(0)
163
+ const buttonRef = React.useRef(null)
164
+ const menuRef = React.useRef(null)
165
+ const menuId = React.useId()
166
+ const selected = options.find((option) => option.props.value === value)
167
+ const enabled = options.map((option, index) => option.props.disabled ? -1 : index).filter((index) => index >= 0)
168
+ const close = (restoreFocus = false) => {
169
+ setMenu(null)
170
+ if (restoreFocus) buttonRef.current?.focus()
171
+ }
172
+ const openMenu = () => {
173
+ if (disabled) return
174
+ const rect = buttonRef.current.getBoundingClientRect()
175
+ const computed = window.getComputedStyle(buttonRef.current)
176
+ const fontSize = parseFloat(computed.fontSize) || 14
177
+ const lineHeight = parseFloat(computed.lineHeight) || fontSize * 1.5
178
+ const measure = document.createElement('canvas').getContext('2d')
179
+ if (measure) measure.font = computed.font || `${fontSize}px sans-serif`
180
+ const longest = Math.max(...options.map((option) => measure
181
+ ? measure.measureText(String(option.props.children)).width : String(option.props.children).length * fontSize))
182
+ const height = Math.min(options.length * Math.max(40, lineHeight + 16) + 14, window.innerHeight - 24)
183
+ const width = Math.min(Math.max(rect.width, longest + 72, 200), window.innerWidth - 24)
184
+ setActive(Math.max(0, options.findIndex((option) => option.props.value === value && !option.props.disabled)))
185
+ setMenu({ left: Math.max(12, Math.min(rect.left, window.innerWidth - width - 12)),
186
+ top: Math.max(12, rect.bottom + height + 6 <= window.innerHeight - 12 ? rect.bottom + 6 : rect.top - height - 6), width, maxHeight: window.innerHeight - 24 })
187
+ }
188
+ const choose = (index) => {
189
+ const option = options[index]
190
+ if (!option || option.props.disabled) return
191
+ onChange?.({ target: { value: option.props.value } })
192
+ close(true)
193
+ }
194
+ React.useEffect(() => {
195
+ if (!menu) return
196
+ menuRef.current?.focus()
197
+ const outside = (event) => {
198
+ if (!buttonRef.current?.contains(event.target) && !menuRef.current?.contains(event.target)) close()
199
+ }
200
+ const scrolled = (event) => { if (!menuRef.current?.contains(event.target)) close() }
201
+ const resized = () => close()
202
+ document.addEventListener('pointerdown', outside)
203
+ document.addEventListener('scroll', scrolled, true)
204
+ window.addEventListener('resize', resized)
205
+ return () => {
206
+ document.removeEventListener('pointerdown', outside)
207
+ document.removeEventListener('scroll', scrolled, true)
208
+ window.removeEventListener('resize', resized)
209
+ }
210
+ }, [menu])
211
+ React.useEffect(() => {
212
+ if (menu) document.getElementById(`${menuId}-${active}`)?.scrollIntoView({ block: 'nearest' })
213
+ }, [active, menu])
214
+ return React.createElement('span', { style: { display: 'inline-flex', maxWidth: '100%', minWidth: 0 } },
215
+ React.createElement('button', { ...props, className: 'mgw-select-trigger', ref: buttonRef, type: 'button', disabled,
216
+ 'aria-haspopup': 'listbox', 'aria-expanded': !!menu, 'aria-controls': menu ? menuId : undefined,
217
+ onClick: () => menu ? close() : openMenu(),
218
+ onKeyDown: (event) => {
219
+ if (['ArrowDown', 'ArrowUp'].includes(event.key)) { event.preventDefault(); openMenu() }
220
+ },
221
+ style: { ...style, width: 'auto', maxWidth: '100%', marginBottom: 0, border: 0, borderRadius: 12,
222
+ padding: '10px 16px', background: colors.card, color: colors.text, font: 'inherit', cursor: disabled ? 'default' : 'pointer',
223
+ display: 'inline-flex', alignItems: 'center', gap: 18, opacity: disabled ? .5 : 1 } },
224
+ React.createElement('span', { style: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, selected?.props.children || value),
225
+ React.createElement('svg', { width: 14, height: 14, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor',
226
+ strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true, style: { flexShrink: 0 } },
227
+ React.createElement('path', { d: 'M6 9l6 6 6-6' }))),
228
+ menu ? React.createElement('div', { className: 'mgw-select-menu', ref: menuRef, id: menuId, role: 'listbox', tabIndex: -1,
229
+ 'aria-label': props['aria-label'], 'aria-activedescendant': `${menuId}-${active}`,
230
+ style: { ...menu, position: 'fixed', zIndex: 1250, boxSizing: 'border-box', overflowY: 'auto', padding: 6,
231
+ background: colors.panel, color: colors.text, border: `1px solid ${colors.border}`, borderRadius: 14,
232
+ boxShadow: 'var(--dsw-elevation-prominent, 0 8px 28px rgba(0,0,0,.12))', outline: 'none' },
233
+ onKeyDown: (event) => {
234
+ if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); close(true) }
235
+ else if (event.key === 'Tab') close()
236
+ else if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); choose(active) }
237
+ else if (['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) {
238
+ event.preventDefault()
239
+ const index = enabled.indexOf(active)
240
+ setActive(event.key === 'Home' ? enabled[0] : event.key === 'End' ? enabled[enabled.length - 1]
241
+ : enabled[(index + (event.key === 'ArrowDown' ? 1 : -1) + enabled.length) % enabled.length])
242
+ }
243
+ } }, options.map((option, index) => React.createElement('div', { key: option.props.value,
244
+ id: `${menuId}-${index}`, role: 'option', 'aria-selected': option.props.value === value, 'aria-disabled': !!option.props.disabled,
245
+ onPointerMove: () => { if (!option.props.disabled) setActive(index) }, onClick: () => choose(index),
246
+ style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, minHeight: 40, whiteSpace: 'nowrap',
247
+ boxSizing: 'border-box', padding: '8px 12px', borderRadius: 8, cursor: option.props.disabled ? 'default' : 'pointer',
248
+ opacity: option.props.disabled ? .4 : 1, background: active === index ? 'var(--dsw-alias-interactive-bg-hover, rgba(127,127,127,.08))' : 'transparent' } },
249
+ React.createElement('span', { style: { minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis' }, title: String(option.props.children) }, option.props.children), option.props.value === value ? React.createElement('svg', { width: 16, height: 16, viewBox: '0 0 24 24',
250
+ fill: 'none', stroke: 'currentColor', strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true, style: { flexShrink: 0 } },
251
+ React.createElement('path', { d: 'M5 12l4 4L19 6' })) : null))) : null)
252
+ }
253
+
254
+ // --------------------------------------------------------------------------
255
+ // Settings-nav glyph, pinned by the plugin itself.
256
+ //
257
+ // The `settings.section` contract carries no icon field — the core reads
258
+ // only id/label/order and `navIcon(id)` falls back to the gear for every
259
+ // unknown id. Patching that core bundle is not durable: a DSH runtime
260
+ // re-extract, or any other plugin installing/removing its own patch, wipes
261
+ // it. So this plugin pins its own glyph at runtime instead.
262
+ //
263
+ // It finds its nav cell by label text and rewrites the existing <svg> in
264
+ // place, keeping the shell's element, class and box — nothing here depends
265
+ // on the shell's hashed class names, so a DSH upgrade cannot break it. A
266
+ // MutationObserver re-applies the glyph whenever the shell re-renders the
267
+ // nav and restores the gear.
268
+ //
269
+ // `glyph()` is pure and returns the markup: it runs BEFORE any DOM mutation,
270
+ // so a throwing glyph leaves the shell's own icon in place rather than
271
+ // blanking the cell.
272
+ // --------------------------------------------------------------------------
273
+ const NAV_LABEL = '鲸尾网关助手'
274
+ const NAV_ICON_MARK = 'data-mgw-nav-icon'
275
+
276
+ function navGlyph() {
277
+ return {
278
+ viewBox: '0 0 24 24',
279
+ stroke: 'currentColor',
280
+ markup: '<rect x="6" y="2" width="12" height="20" rx="2.5"></rect><path d="M10 18h4"></path>',
281
+ }
282
+ }
283
+
284
+ function pinNavGlyph(labels, mark, glyph) {
285
+ if (typeof document === 'undefined' || typeof MutationObserver === 'undefined') return
286
+ const apply = () => {
287
+ // Cheap guard: the nav only exists while the settings panel is open.
288
+ if (document.querySelector('[role="dialog"]') === null) return
289
+ const cells = document.querySelectorAll('[role="dialog"] nav button')
290
+ for (const cell of cells) {
291
+ // An <svg> contributes no text, so this is exactly the nav label.
292
+ if (labels.indexOf(cell.textContent.trim()) < 0) continue
293
+ const svg = cell.querySelector('svg')
294
+ if (svg === null || svg.getAttribute(mark) === '1') continue
295
+ let spec
296
+ try {
297
+ spec = glyph()
298
+ } catch (error) {
299
+ console.warn('[dsh-plugin-weapp-gateway] nav glyph failed; keeping the shell icon', error)
300
+ continue
301
+ }
302
+ svg.setAttribute('viewBox', spec.viewBox)
303
+ svg.setAttribute('fill', 'none')
304
+ if (spec.stroke) {
305
+ svg.setAttribute('stroke', spec.stroke)
306
+ svg.setAttribute('stroke-width', spec.strokeWidth || '1.8')
307
+ svg.setAttribute('stroke-linecap', 'round')
308
+ svg.setAttribute('stroke-linejoin', 'round')
309
+ }
310
+ svg.innerHTML = spec.markup
311
+ svg.setAttribute('aria-hidden', 'true')
312
+ svg.setAttribute(mark, '1')
313
+ }
314
+ }
315
+ apply()
316
+ // The shell re-renders the nav on ledger/locale changes; without this the
317
+ // gear would come back on the next re-render.
318
+ new MutationObserver(apply).observe(document.body, { childList: true, subtree: true })
319
+ }
320
+
321
+ // Fork: management RPC must resolve against the document base, not the
322
+ // origin root. Behind the fnOS gateway the whole WebUI is served under
323
+ // /app/deepseek-harness/fngateway/, where an absolute /mgw/... request
324
+ // hits the gateway's own router and 404s. DSH serves its own assets
325
+ // document-relative for exactly this reason.
326
+ function apiPath(path) {
327
+ let base = '/'
328
+ try { base = new URL('.', document.baseURI).pathname } catch { base = '/' }
329
+ if (!base.endsWith('/')) base += '/'
330
+ return base + String(path).replace(/^\/+/, '')
331
+ }
332
+
333
+ async function request(path, options) {
334
+ const response = await fetch(apiPath(path), { credentials: 'same-origin', ...options })
335
+ const body = await response.json().catch(() => ({}))
336
+ if (!response.ok) throw new Error(body.message || body.error || `HTTP ${response.status}`)
337
+ return body
338
+ }
339
+
340
+ function inferredUrl(wsPath) {
341
+ const scheme = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
342
+ return `${scheme}//${window.location.host}${wsPath || '/ws/mobile'}`
343
+ }
344
+
345
+ function lanPairingUrl(status) {
346
+ const urls = status?.lan?.listening && Array.isArray(status.lan.urls) ? status.lan.urls : []
347
+ return urls.find((url) => !/^ws:\/\/169\.254\./.test(url)) || urls[0] || ''
348
+ }
349
+
350
+ function pairingUrlFor(route, status) {
351
+ const lanUrl = lanPairingUrl(status)
352
+ const tunnelUrl = status.cloudflare?.enabled && status.cloudflare.publicReady === true
353
+ ? status.cloudflare.publicUrl || '' : ''
354
+ if (route === 'lan') return lanUrl
355
+ if (route === 'relay') return status.relay?.relay || ''
356
+ if (route === 'cloudflare') return tunnelUrl
357
+ if (route === 'tailscale') return status.tailscale?.serveUrl || status.tailscale?.urls?.[0] || ''
358
+ const statusUrl = status.cloudflare?.enabled && status.cloudflare.publicReady !== true &&
359
+ status.publicUrl === status.cloudflare.publicUrl ? '' : status.publicUrl
360
+ return tunnelUrl || statusUrl || lanUrl || inferredUrl(status.wsPath)
361
+ }
362
+
363
+ // 从手动输入里取主机:支持 `100.x.x.x`、`ws://100.x.x.x:3081/ws/mobile`、
364
+ // 以及带方括号的 IPv6。用于 Tailscale 路线的手动填写校验与补全。
365
+ function tailscaleHostOf(value) {
366
+ let raw = String(value || '').trim()
367
+ if (!raw) return ''
368
+ raw = raw.replace(/^(?:wss?|https?):\/\//i, '')
369
+ raw = raw.split(/[/?#]/)[0]
370
+ raw = raw.replace(/^\[|\]$/g, '')
371
+ return raw.replace(/:\d+$/, '')
372
+ }
373
+
374
+ function isTailscaleInput(value) {
375
+ const host = tailscaleHostOf(value)
376
+ if (!host) return false
377
+ if (/\.ts\.net$/i.test(host)) return true
378
+ const octets = host.split('.').map(Number)
379
+ if (octets.length === 4 && octets.every((part) => Number.isInteger(part) && part >= 0 && part <= 255)) {
380
+ return octets[0] === 100 && octets[1] >= 64 && octets[1] <= 127
381
+ }
382
+ return /^fd7a:115c:a1e0:/i.test(host)
383
+ }
384
+
385
+ // 与上游一致的连接方案摘要:按所选入口给出「配对入口 + 提示」。
386
+ function appConnectionPlan(route, status, rawUrl) {
387
+ const lanUrl = lanPairingUrl(status)
388
+ if (route === 'auto') {
389
+ return {
390
+ valid: !!lanUrl,
391
+ entry: '自动选择(公网优先,局域网兜底)',
392
+ note: lanUrl ? '手机会按实际连通情况在公网与局域网之间自动切换。' : '局域网入口不可用;自动选择需要一个手机可访问的局域网或公网入口。',
393
+ }
394
+ }
395
+ if (route === 'lan') {
396
+ return {
397
+ valid: !!lanUrl,
398
+ entry: '局域网直连',
399
+ note: lanUrl ? '同一局域网可直接访问;离开该网络就无法直连。' : '局域网入口不可用,请先开启基本设置中的局域网入口。',
400
+ }
401
+ }
402
+ if (route === 'cloudflare') {
403
+ const ready = !!(status?.cloudflare?.enabled && status.cloudflare.publicReady === true && status.cloudflare.publicUrl)
404
+ return {
405
+ valid: ready,
406
+ entry: 'Cloudflare Tunnel',
407
+ note: ready ? '公网入口已验证可达;手机在任何网络都可尝试。' : '公网入口尚未验证通过,请先完成下方配置和检测。',
408
+ }
409
+ }
410
+ if (route === 'tailscale') {
411
+ const serveUrl = status?.tailscale?.serveUrl || ''
412
+ const valid = !!((serveUrl && String(rawUrl || '').trim() === serveUrl) || (status?.lan?.listening && isTailscaleInput(rawUrl)))
413
+ return {
414
+ valid,
415
+ entry: 'Tailscale 内嵌隧道',
416
+ note: valid
417
+ ? '手机经 App 内嵌隧道连接网关节点(不占用系统 VPN,局域网不可用时仍可用)。'
418
+ : '可一键使用网关内置隧道地址;也可填写主机 Tailscale 100.x 地址。',
419
+ }
420
+ }
421
+ // custom:按地址特征给提示(与上游 pairingConnectionPlan 同一判定思路)。
422
+ const raw = String(rawUrl || '').trim()
423
+ let endpoint
424
+ try { endpoint = new URL(raw) } catch {
425
+ return { valid: false, entry: '等待填写有效的配对地址', note: '请输入手机能够访问的 ws:// 或 wss:// 地址。' }
426
+ }
427
+ const scheme = endpoint.protocol === 'http:' ? 'ws:' : endpoint.protocol === 'https:' ? 'wss:' : endpoint.protocol
428
+ const host = endpoint.hostname.replace(/^\[|\]$/g, '').toLowerCase()
429
+ const parts = host.split('.').map(Number)
430
+ const ipv4 = parts.length === 4 && parts.every((n) => Number.isInteger(n) && n >= 0 && n <= 255)
431
+ const loopback = host === 'localhost' || host === '::1' || (ipv4 && parts[0] === 127)
432
+ const privateHost = loopback || host.endsWith('.local') ||
433
+ (ipv4 && (parts[0] === 10 || (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) ||
434
+ (parts[0] === 192 && parts[1] === 168) || (parts[0] === 169 && parts[1] === 254))) ||
435
+ (host.includes(':') && /^(fc|fd|fe80:)/.test(host))
436
+ if (!['ws:', 'wss:'].includes(scheme) || endpoint.username || endpoint.password || endpoint.search || endpoint.hash ||
437
+ raw.length > 2048 || ['0.0.0.0', '::'].includes(host) || (scheme === 'ws:' && !privateHost)) {
438
+ return { valid: false, entry: '配对地址需要修改', note: '公网地址必须使用 wss://;地址不能包含账号、查询参数或片段。' }
439
+ }
440
+ const entry = loopback ? '本机回环地址' : privateHost ? '局域网或子网路由' : '加密 WebSocket 入口'
441
+ let note = '配对地址已填写,手机是否可达仍需实际连接确认。'
442
+ if (loopback) note = '回环地址仅适用于本机模拟器;真机请填写电脑的局域网、Tailscale 或公网地址。'
443
+ else if (privateHost) note = '同一局域网可直接访问;异地访问此地址需要手机已有可用的子网路由。'
444
+ return { valid: true, entry, note }
445
+ }
446
+
447
+ // 手动输入的裸 IP 补成 ws://<ip>:<lanPort><wsPath>;已是 URL 的原样返回。
448
+ function tailscaleEndpointOf(value, status) {
449
+ const raw = String(value || '').trim()
450
+ if (!raw) return ''
451
+ if (/^(?:wss?|https?):\/\//i.test(raw)) return raw
452
+ const port = status?.lan?.port || 3081
453
+ const wsPath = status?.wsPath || '/ws/mobile'
454
+ const host = raw.includes(':') ? `[${raw.replace(/^\[|\]$/g, '')}]` : raw
455
+ return `ws://${host}:${port}${wsPath}`
456
+ }
457
+
458
+ // Tailscale 内嵌隧道:地址自动填入,无需用户手填。
459
+ function tailscaleServeUrl(status) {
460
+ return status?.tailscale?.serveUrl || ''
461
+ }
462
+
463
+ function connectionAdvice(status, publicSetup) {
464
+ if (!status) return { detected: '正在读取网关环境…', local: '', remote: '' }
465
+ const system = status.platform === 'darwin' ? 'macOS 电脑' : status.platform === 'win32' ? 'Windows 电脑' : status.platform === 'linux' ? 'Linux 服务器' : '当前设备'
466
+ const lanReady = !!lanPairingUrl(status)
467
+ const tunnel = status.cloudflare
468
+ const tunnelReady = !!(tunnel?.enabled && tunnel.publicReady === true && tunnel.publicUrl)
469
+ const statusUrlIsUnreadyTunnel = !!(tunnel?.enabled && tunnel.publicReady !== true &&
470
+ status.publicUrl === tunnel.publicUrl)
471
+ const serverReady = status.platform === 'linux' && !!(
472
+ (publicSetup?.configured && publicSetup.publicUrl) || (!statusUrlIsUnreadyTunnel && /^wss:\/\//.test(status.publicUrl || '')))
473
+ const detected = `当前检测:${system};局域网入口${lanReady ? '已就绪' : '未就绪'};Tailscale 地址${status.tailscale?.urls?.length ? '可用' : '未检测到'};${serverReady ? '公网服务器入口已配置' : tunnelReady ? `${tunnel.mode === 'quick' ? 'Quick' : '命名'} Tunnel 已连接` : tunnel?.enabled ? (tunnel.state === 'online' ? '隧道已连接,公网入口未验证或检测失败' : 'Cloudflare Tunnel 连接中') : '外网入口未连接'}。`
474
+ const local = lanReady
475
+ ? 'DSH App 和小程序都可以通过局域网或 VPN 连接;手机与 DSH 同网时可使用局域网地址。'
476
+ : '两种客户端都可使用局域网连接;先确认局域网入口已开启并监听成功。'
477
+ let remote
478
+ if (serverReady) remote = '两种客户端在外网时都可使用已配置的公网 WSS;自动选择会同时保留局域网候选地址。'
479
+ else if (tunnelReady && tunnel.mode === 'named') remote = '两种客户端在外网时都可使用固定域名的 Cloudflare Tunnel;自动选择也会保留局域网候选地址。'
480
+ else if (tunnelReady) remote = '两种客户端在外网时都可使用 Cloudflare Quick Tunnel;地址变化后需重新配对。'
481
+ else if (status.platform === 'darwin' || status.platform === 'win32') remote = '外网使用可开启 Quick Tunnel;需要固定地址时可配置命名 Tunnel。'
482
+ else if (status.platform === 'linux') remote = '外网使用可配置 Linux 公网入口或 Cloudflare Tunnel。'
483
+ else remote = '外网连接需要可访问的 wss:// 公网地址;两种客户端都支持公网或局域网。'
484
+ return { detected, local, remote }
485
+ }
486
+
487
+ // 可信设备徽标:按手机当前连接入口标注 局域网 / 公网 / Cloudflare 外网。
488
+ // routes 来自 /mgw/devices 的实时连接统计,面板每 3 秒轮询,手机切网后
489
+ // 重连即换徽标;离线设备没有连接,不显示线路徽标。
490
+ const ROUTE_BADGES = {
491
+ lan: { label: '局域网', color: colors.success, title: '手机当前通过局域网直连(同一 Wi-Fi 或 VPN)' },
492
+ public: { label: '公网', color: 'var(--dsw-alias-link, #4176e6)', title: '手机当前通过公网入口连接(公网服务器或鲸尾中继)' },
493
+ cloudflare: { label: 'Cloudflare 外网', color: 'var(--dsw-alias-state-warning-primary, #d98324)', title: '手机当前通过 Cloudflare Tunnel 外网连接' },
494
+ }
495
+ function routeBadges(device) {
496
+ if (!device || !device.online || !Array.isArray(device.routes)) return []
497
+ return device.routes.map((route) => ROUTE_BADGES[route]).filter(Boolean)
498
+ }
499
+
500
+ // 服务端网络检测:向每条已鉴权移动连接发一次 WebSocket ping,展示协议 RTT。
501
+ // 数据来自管理接口 POST /mgw/network-test(loopback);页面可见时每两秒刷新,
502
+ // 进入后台或关闭面板即停止。RTT 只反映网关到手机的协议往返,不是业务处理耗时。
503
+ function ServerNetworkDiagnostics() {
504
+ const [snapshot, setSnapshot] = React.useState(null)
505
+ const [failure, setFailure] = React.useState('')
506
+ const [running, setRunning] = React.useState(typeof document === 'undefined' ? false : !document.hidden)
507
+ React.useEffect(() => {
508
+ if (typeof document === 'undefined') return undefined
509
+ let mounted = true, timer, controller, generation = 0
510
+ const stop = () => { generation++; window.clearTimeout(timer); controller?.abort() }
511
+ const sample = async (lease) => {
512
+ if (!mounted || document.hidden || generation !== lease) return
513
+ controller = new AbortController()
514
+ try {
515
+ const data = await request('/mgw/network-test', { method: 'POST', signal: controller.signal })
516
+ if (mounted && generation === lease) { setSnapshot(data); setFailure('') }
517
+ } catch (cause) {
518
+ if (mounted && generation === lease && cause.name !== 'AbortError') setFailure(cause.message)
519
+ } finally {
520
+ if (mounted && generation === lease && !document.hidden) timer = window.setTimeout(() => sample(lease), 2000)
521
+ }
522
+ }
523
+ const visibility = () => {
524
+ stop()
525
+ setRunning(!document.hidden)
526
+ if (!document.hidden) { setSnapshot(null); void sample(generation) }
527
+ }
528
+ document.addEventListener('visibilitychange', visibility)
529
+ if (!document.hidden) void sample(generation)
530
+ return () => { mounted = false; stop(); document.removeEventListener('visibilitychange', visibility) }
531
+ }, [])
532
+ const number = (value) => Number.isFinite(value) ? `${value.toFixed(1)} ms` : '—'
533
+ const statusLabel = (value) => ({ ok: '正常', timeout: '探测超时', disconnected: '已断开', error: '检测失败', unavailable: '暂无有效样本', cancelled: '已停止' })[value] || '暂无有效样本'
534
+ const channelLabel = (value) => ({ control: '控制通道', conversation: '会话通道', legacy: '兼容通道' })[value] || '兼容通道'
535
+ const chart = (channel) => {
536
+ const points = channel.samples || []
537
+ const end = snapshot.at
538
+ const maximum = Math.max(1, ...points.map((point) => point.rttMs || 0)) * 1.15
539
+ const paths = []; let segment = []
540
+ const flush = () => { if (segment.length) paths.push(segment.join(' ')); segment = [] }
541
+ for (const point of points) {
542
+ if (!Number.isFinite(point.rttMs)) { flush(); continue }
543
+ segment.push(`${Math.max(0, (point.at - end + 60000) / 60000 * 300)},${70 - point.rttMs / maximum * 65}`)
544
+ }
545
+ flush()
546
+ return React.createElement('svg', { viewBox: '0 0 300 78', preserveAspectRatio: 'none', role: 'img', 'aria-label': '服务端最近一分钟 RTT', style: { width: '100%', height: 86, display: 'block' } },
547
+ [5, 38, 70].map((y) => React.createElement('line', { key: y, x1: 0, x2: 300, y1: y, y2: y, stroke: colors.border, strokeWidth: .6 })),
548
+ paths.map((points, index) => React.createElement('polyline', { key: index, points, fill: 'none', stroke: 'var(--dsw-alias-link, #4176e6)', strokeWidth: 1.5 })),
549
+ (points.filter((point) => Number.isFinite(point.rttMs)).slice(-1)).map((point) => React.createElement('circle', { key: point.at,
550
+ cx: Math.max(0, (point.at - end + 60000) / 60000 * 300), cy: 70 - point.rttMs / maximum * 65, r: 2, fill: 'var(--dsw-alias-link, #4176e6)' })))
551
+ }
552
+ return React.createElement('section', { style: styles.card, 'aria-label': '服务端网络检测' },
553
+ React.createElement('h3', { className: 'mgw-section-title' }, '服务端网络检测'),
554
+ React.createElement('p', { style: styles.muted }, running ? '自动检测已连接设备,每两秒刷新;离开此页或进入后台后停止。' : '后台已暂停检测'),
555
+ React.createElement('p', { style: styles.muted }, '使用 WebSocket 协议 Ping/Pong 测量往返时延;经过 Tunnel 或代理时,RTT 可能只反映代理链路。'),
556
+ failure ? React.createElement('p', { role: 'alert', style: styles.error }, failure) : null,
557
+ !snapshot ? React.createElement('p', { style: styles.muted }, '正在检测…') : snapshot.devices.length === 0
558
+ ? React.createElement('p', { style: styles.muted }, '当前没有已连接设备。')
559
+ : snapshot.devices.map((device) => React.createElement('section', { key: device.deviceId, style: { marginTop: 18, paddingTop: 14, borderTop: `1px solid ${colors.border}` } },
560
+ React.createElement('strong', null, device.name || '未命名设备'),
561
+ device.channels.map((channel) => React.createElement('div', { key: channel.connectionId, style: { marginTop: 12 } },
562
+ React.createElement('div', { style: { display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between', gap: 8 } },
563
+ React.createElement('span', null, channelLabel(channel.channel), ' · WebSocket'),
564
+ React.createElement('strong', null, 'RTT ', number(channel.rttMs))),
565
+ React.createElement('p', { style: { ...styles.muted, margin: '6px 0' } }, statusLabel(channel.status), ' · 协议 Ping/Pong · 最近一分钟平均 ', number(channel.averageRttMs), ' · P95 ', number(channel.p95RttMs)),
566
+ chart(channel))))),
567
+ snapshot ? React.createElement('p', { style: styles.muted }, '服务端读取时间 ', new Date(snapshot.at).toLocaleTimeString(), ' · 曲线范围:最近一分钟') : null,
568
+ snapshot?.truncated ? React.createElement('p', { style: styles.muted }, '连接数量过多,仅检测前 256 条连接。') : null)
569
+ }
570
+ function DeviceRow({ device, onRevoke, revoking }) {
571
+ const triggerRevoke = (event) => {
572
+ event.preventDefault()
573
+ event.stopPropagation()
574
+ if (!revoking) onRevoke(device)
575
+ }
576
+ return React.createElement('div', { style: styles.row },
577
+ React.createElement('div', { style: { minWidth: 0, overflow: 'hidden' } },
578
+ React.createElement('div', { style: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } },
579
+ device.displayName || device.name,
580
+ React.createElement('span', { style: styles.badge },
581
+ React.createElement('span', { style: { ...styles.dot, background: device.online ? colors.success : colors.muted } }),
582
+ device.online ? '在线' : '离线'),
583
+ routeBadges(device).map((badge) => React.createElement('span', { key: badge.label, style: styles.badge, title: badge.title },
584
+ React.createElement('span', { style: { ...styles.dot, background: badge.color } }),
585
+ badge.label))),
586
+ React.createElement('div', { style: { ...styles.muted, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', marginTop: 3 } },
587
+ device.lastSeenAt ? `最近连接:${new Date(device.lastSeenAt).toLocaleString()}` : '尚未连接')),
588
+ React.createElement('button', {
589
+ type: 'button',
590
+ disabled: revoking,
591
+ style: {
592
+ ...styles.button,
593
+ color: colors.danger,
594
+ background: 'transparent',
595
+ borderColor: 'rgba(220,76,100,.55)',
596
+ flexShrink: 0,
597
+ minWidth: 54,
598
+ opacity: revoking ? .6 : 1,
599
+ },
600
+ title: `吊销 ${device.displayName || device.name}`,
601
+ // Pointer-up is more reliable than click inside the management dialog on
602
+ // touch devices. The click handler remains for keyboard activation.
603
+ onPointerUp: triggerRevoke,
604
+ onClick: (event) => {
605
+ if (event.detail === 0) triggerRevoke(event)
606
+ },
607
+ }, revoking ? '吊销中…' : '吊销'))
608
+ }
609
+
610
+ function DevicePanel() {
611
+ // 侧边栏入口开关:与侧边栏按钮共享同一状态(切换后立即生效)。
612
+ const sidebarOn = React.useSyncExternalStore(subscribeSidebar, getSidebarEntry, () => true)
613
+ const [activeSection, setActiveSection] = React.useState('general')
614
+ const [devices, setDevices] = React.useState(null)
615
+ const [deviceLoadError, setDeviceLoadError] = React.useState(null)
616
+ const [statusLoadError, setStatusLoadError] = React.useState(null)
617
+ const refreshRequests = React.useRef(new Map())
618
+ const manualRefreshRef = React.useRef(false)
619
+ // fork:离线设备折叠开关(上游整合时该状态丢失)。
620
+ const [showAllDevices, setShowAllDevices] = React.useState(false)
621
+ const [permissionSaving, setPermissionSaving] = React.useState(null)
622
+ const permissionLock = React.useRef(false)
623
+ const deviceRevision = React.useRef(0)
624
+ const [selectedDeviceIds, setSelectedDeviceIds] = React.useState(() => new Set())
625
+ React.useEffect(() => {
626
+ const existing = new Set((devices || []).map(device => device.id))
627
+ setSelectedDeviceIds(current => {
628
+ const next = new Set([...current].filter(id => existing.has(id)))
629
+ return next.size === current.size ? current : next
630
+ })
631
+ }, [devices])
632
+ const [status, setStatus] = React.useState(null)
633
+ const [dismissedNotice, setDismissedNotice] = React.useState(() => dismissedRestartInstance)
634
+ // 两个配对模块各自维护方案:鲸尾公网小程序(主用)与兼容 App(折叠备用)。
635
+ const [appUrl, setAppUrl] = React.useState('')
636
+ const [appRoute, setAppRoute] = React.useState('auto')
637
+ const [connectionHelpOpen, setConnectionHelpOpen] = React.useState(false)
638
+ const [toolsOpen, setToolsOpen] = React.useState(false)
639
+ const [toolBusy, setToolBusy] = React.useState(false)
640
+ const [backgroundBusy, setBackgroundBusy] = React.useState(false)
641
+ const [toolNotice, setToolNotice] = React.useState('')
642
+ const stoppedRef = React.useRef(false)
643
+ const [publicIp, setPublicIp] = React.useState('')
644
+ const [publicSetup, setPublicSetup] = React.useState(null)
645
+ const [publicSetupBusy, setPublicSetupBusy] = React.useState(false)
646
+ const [cloudflareHost, setCloudflareHost] = React.useState('')
647
+ const [cloudflareToken, setCloudflareToken] = React.useState('')
648
+ const [cloudflareMode, setCloudflareMode] = React.useState('quick')
649
+ const [cloudflareBusy, setCloudflareBusy] = React.useState(false)
650
+ const [qr, setQr] = React.useState(null)
651
+ const pairingDialogRef = React.useRef(null)
652
+ const navRef = React.useRef(null)
653
+ // Fork: id of the pairing code currently shown as a QR. The panel polls
654
+ // the server's pending list and closes the dialog as soon as this id is
655
+ // gone — a successful scan consumes the code immediately.
656
+ const pairingIdRef = React.useRef(null)
657
+ const [pairingClosing, setPairingClosing] = React.useState(false)
658
+ const pairingCloseTimer = React.useRef(null)
659
+ const closePairingDialog = () => {
660
+ pairingIdRef.current = null
661
+ setCopyNotice(null)
662
+ if (pairingCloseTimer.current !== null) return
663
+ if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
664
+ setQr(null)
665
+ return
666
+ }
667
+ setPairingClosing(true)
668
+ pairingCloseTimer.current = window.setTimeout(() => {
669
+ pairingCloseTimer.current = null
670
+ setQr(null)
671
+ setPairingClosing(false)
672
+ }, 180)
673
+ }
674
+ React.useEffect(() => {
675
+ setPairingClosing(false)
676
+ return () => {
677
+ if (pairingCloseTimer.current !== null) {
678
+ window.clearTimeout(pairingCloseTimer.current)
679
+ pairingCloseTimer.current = null
680
+ }
681
+ }
682
+ }, [qr])
683
+ const [error, setError] = React.useState(null)
684
+ const [busy, setBusy] = React.useState(false)
685
+ const [updateInfo, setUpdateInfo] = React.useState(null)
686
+ const [updateChecking, setUpdateChecking] = React.useState(true)
687
+ const [updateBusy, setUpdateBusy] = React.useState(false)
688
+ const [updateNotice, setUpdateNotice] = React.useState('')
689
+ const [updateError, setUpdateError] = React.useState('')
690
+ const [refreshing, setRefreshing] = React.useState(false)
691
+ const [refreshNotice, setRefreshNotice] = React.useState(null)
692
+ const [pairingTokenCopied, setPairingTokenCopied] = React.useState(false)
693
+ // Copy feedback that must live inside the QR dialog: the panel's error
694
+ // banner is behind the modal, so a clipboard failure looked like "the
695
+ // button does nothing".
696
+ const [copyNotice, setCopyNotice] = React.useState(null)
697
+ const [deviceNotice, setDeviceNotice] = React.useState(null)
698
+ const [deviceNoticeError, setDeviceNoticeError] = React.useState(false)
699
+ const [revokingIds, setRevokingIds] = React.useState(() => new Set())
700
+ const [sidebarBusy, setSidebarBusy] = React.useState(false)
701
+ const [offlineClearing, setOfflineClearing] = React.useState(false)
702
+ const [appLayerOpen, setAppLayerOpen] = React.useState(true)
703
+
704
+ const revokingIdsRef = React.useRef(new Set())
705
+ const manualAppUrlRef = React.useRef(false)
706
+ const appUrlRef = React.useRef('')
707
+ const appRouteRef = React.useRef('auto')
708
+ const appRouteChosenRef = React.useRef(false)
709
+ const cloudflareModeLoadedRef = React.useRef(false)
710
+
711
+ // 同类读取去重:轮询与手动刷新并发时复用同一个 in-flight 请求(上游 0.12.x)。
712
+ const refreshRead = async (kind, options) => {
713
+ const inflight = refreshRequests.current.get(kind)
714
+ if (inflight && !(options && options.force)) return inflight
715
+ const task = request(kind === 'devices' ? '/mgw/devices' : '/mgw/status', options)
716
+ refreshRequests.current.set(kind, task)
717
+ try { return await task } finally { refreshRequests.current.delete(kind) }
718
+ }
719
+ const refresh = React.useCallback(async () => {
720
+ try {
721
+ const [deviceData, statusData] = await Promise.all([
722
+ request('/mgw/devices'),
723
+ request('/mgw/status'),
724
+ ])
725
+ const nextDevices = deviceData.devices || []
726
+ // Keep existing DOM rows alive when polling returns identical data.
727
+ // Replacing them every three seconds can swallow a pointer/click that
728
+ // started on the old button and ended after React replaced the row.
729
+ if (revokingIdsRef.current.size === 0) {
730
+ setDevices((current) => JSON.stringify(current) === JSON.stringify(nextDevices) ? current : nextDevices)
731
+ }
732
+ setStatus((current) => JSON.stringify(current) === JSON.stringify(statusData) ? current : statusData)
733
+ // Fork: the QR dialog closes itself once the code is consumed. The
734
+ // server drops a redeemed code from its pending list, so the poll
735
+ // sees our id disappear and dismisses the dialog (with animation).
736
+ if (pairingIdRef.current !== null && Array.isArray(statusData.pendingPairings)
737
+ && !statusData.pendingPairings.includes(pairingIdRef.current)) {
738
+ pairingIdRef.current = null
739
+ setQr(null)
740
+ }
741
+ if (statusData.cloudflare && statusData.cloudflare.hostname) {
742
+ setCloudflareHost((current) => current || statusData.cloudflare.hostname)
743
+ }
744
+ if (statusData.cloudflare && !cloudflareModeLoadedRef.current) {
745
+ cloudflareModeLoadedRef.current = true
746
+ setCloudflareMode(statusData.cloudflare.mode || 'quick')
747
+ }
748
+ // 小程序模块固定为鲸尾公网(中继优先、局域网兜底),不再需要方案状态。
749
+ // App 模块地址跟随环境刷新;自定义地址与手动填写的 Tailscale 地址不被覆盖。
750
+ if (appRouteRef.current !== 'custom'
751
+ && !(appRouteRef.current === 'tailscale' && manualAppUrlRef.current)) {
752
+ const preferredUrl = pairingUrlFor(appRouteRef.current, statusData)
753
+ if (appUrlRef.current && preferredUrl !== appUrlRef.current) setQr(null)
754
+ appUrlRef.current = preferredUrl
755
+ setAppUrl(preferredUrl)
756
+ }
757
+ return true
758
+ } catch (cause) {
759
+ setError(cause.message)
760
+ return false
761
+ }
762
+ }, [])
763
+
764
+
765
+ const manualRefresh = async () => {
766
+ if (manualRefreshRef.current) return
767
+ manualRefreshRef.current = true
768
+ setRefreshing(true)
769
+ setRefreshNotice(null)
770
+ const succeeded = await refresh()
771
+ setRefreshing(false)
772
+ if (succeeded) {
773
+ setError(null)
774
+ setRefreshNotice(`已刷新 · ${new Date().toLocaleTimeString()}`)
775
+ window.setTimeout(() => setRefreshNotice(null), 2200)
776
+ }
777
+ }
778
+
779
+ const checkForPluginUpdate = async () => {
780
+ setUpdateChecking(true)
781
+ setUpdateError('')
782
+ try {
783
+ setUpdateInfo(await request('/mgw/update-check'))
784
+ } catch (cause) {
785
+ setUpdateError(cause.message)
786
+ } finally {
787
+ setUpdateChecking(false)
788
+ }
789
+ }
790
+
791
+ const upgradePlugin = async () => {
792
+ if (updateBusy || !updateInfo?.updateAvailable) return
793
+ setUpdateBusy(true)
794
+ setUpdateNotice('')
795
+ setUpdateError('')
796
+ try {
797
+ const result = await request('/mgw/update', { method: 'POST' })
798
+ if (result.reason === 'plugin-manager-unavailable') {
799
+ setUpdateNotice(`当前 DSH 不支持面板内更新。请在 Terminal 执行:${result.command}`)
800
+ } else if (result.reason === 'already-current') {
801
+ setUpdateInfo(result)
802
+ setUpdateNotice('插件已是最新版本。')
803
+ } else if (result.installed) {
804
+ const application = result.installation?.application
805
+ const pendingBuilds = result.installation?.pendingBuilds
806
+ if (Array.isArray(pendingBuilds) && pendingBuilds.length > 0) {
807
+ setUpdateNotice(`更新等待构建脚本审核(${pendingBuilds.join('、')});未自动批准。请到 DSH 插件管理中审核。`)
808
+ } else if (application === 'restart-required') {
809
+ setUpdateInfo({ ...result, currentVersion: result.latestVersion, updateAvailable: false })
810
+ setUpdateNotice(`已安装 v${result.latestVersion},需要重启 DSH 后生效。`)
811
+ } else if (application === 'failed' || application === 'cancelled' || application === 'refused') {
812
+ const installError = result.installation?.error
813
+ const detail = result.installation?.errorMessage
814
+ || (typeof installError === 'string' ? installError : '')
815
+ || (typeof installError?.message === 'string' ? installError.message : '')
816
+ || (typeof installError?.code === 'string' ? installError.code : '')
817
+ || '请在 DSH 插件管理中查看安装详情。'
818
+ setUpdateNotice(`安装未完成:${application}(${detail})`)
819
+ } else {
820
+ setUpdateInfo({ ...result, currentVersion: result.latestVersion, updateAvailable: false })
821
+ setUpdateNotice(`已安装 v${result.latestVersion}。如界面尚未更新,请重启 DSH。`)
822
+ }
823
+ }
824
+ } catch (cause) {
825
+ setUpdateError(cause.message)
826
+ } finally {
827
+ setUpdateBusy(false)
828
+ }
829
+ }
830
+
831
+ // Linux 持久化后台运行:交给 systemd 用户服务托管整个 DSH Web。
832
+ const toggleBackgroundService = async (event) => {
833
+ const enabled = event.target.checked
834
+ if (backgroundBusy || toolBusy) return
835
+ setBackgroundBusy(true)
836
+ setError(null)
837
+ try {
838
+ const oldPid = status?.webPid
839
+ const data = await request('/mgw/background-service', {
840
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ enabled }),
841
+ })
842
+ setStatus((current) => ({ ...current, backgroundService: data }))
843
+ if (data.handoff) {
844
+ setToolNotice('正在切换到后台服务,连接会短暂中断,请等待自动重连…')
845
+ const deadline = Date.now() + 60_000
846
+ while (Date.now() < deadline) {
847
+ await new Promise((resolve) => window.setTimeout(resolve, 700))
848
+ try {
849
+ const next = await request('/mgw/status')
850
+ if (next.webPid !== oldPid && next.backgroundService?.managed) { window.location.reload(); return }
851
+ } catch { /* 前台进程正在退出,忽略 */ }
852
+ }
853
+ throw new Error('后台接管超时,请在服务器使用 journalctl --user -u <服务名> 查看服务日志。')
854
+ }
855
+ setToolNotice(enabled
856
+ ? '持久化后台运行已开启。'
857
+ : '已关闭自动启动;当前进程继续运行,可通过右上角工具停止 DSH Web。')
858
+ } catch (cause) { setError(cause.message) }
859
+ finally { setBackgroundBusy(false) }
860
+ }
861
+
862
+ const runTool = async (tool) => {
863
+ if (toolBusy || backgroundBusy) return
864
+ setToolsOpen(false)
865
+ setToolBusy(true)
866
+ setToolNotice('')
867
+ setError(null)
868
+ try {
869
+ const oldPid = status?.webPid
870
+ await request(`/mgw/tools/${tool}`, { method: 'POST' })
871
+ if (tool === 'stop-web') {
872
+ stoppedRef.current = true
873
+ setToolNotice('DSH Web 已收到停止指令。需要时可在 Terminal 运行 dsh web 重新启动。')
874
+ return
875
+ }
876
+ if (tool === 'restart-web') {
877
+ setToolNotice('正在重启 DSH Web,当前连接会短暂中断…')
878
+ const deadline = Date.now() + 60_000
879
+ while (Date.now() < deadline) {
880
+ await new Promise((resolve) => window.setTimeout(resolve, 700))
881
+ try {
882
+ const next = await request('/mgw/status')
883
+ if (next.webPid && next.webPid !== oldPid) {
884
+ window.location.reload()
885
+ return
886
+ }
887
+ } catch { /* old process is shutting down */ }
888
+ }
889
+ throw new Error('DSH Web 重启超时,请检查 /tmp/mobile-gateway.log')
890
+ }
891
+ } catch (cause) {
892
+ setError(cause.message)
893
+ setToolNotice('')
894
+ } finally {
895
+ setToolBusy(false)
896
+ }
897
+ }
898
+
899
+ // Fork: dsh-settings-mobile-nav collapses the first <nav> of any settings
900
+ // dialog on narrow viewports (it assumes the settings rail). Our dialog nav
901
+ // is that first nav, so tapping a section used to hide the whole strip and
902
+ // leave a lone ☰ button. Never intercept the click itself — React delegates
903
+ // onClick at the document root, so stopPropagation in the capture phase
904
+ // would kill our own handler. Instead, make the nav un-collapsible: a
905
+ // MutationObserver reverts the display/aria-hidden edits (and drops the
906
+ // stray expand button) the moment they land.
907
+ React.useEffect(() => {
908
+ const nav = navRef.current
909
+ if (nav === null || typeof MutationObserver === 'undefined') return undefined
910
+ const restore = () => {
911
+ if (nav.style.display === 'none') nav.style.display = ''
912
+ if (nav.getAttribute('aria-hidden') === 'true') nav.removeAttribute('aria-hidden')
913
+ const stray = nav.closest('[role="dialog"]')?.querySelector('[data-dsh-settings-nav-expand]')
914
+ if (stray !== null && stray !== undefined) stray.remove()
915
+ }
916
+ const observer = new MutationObserver(restore)
917
+ observer.observe(nav, { attributes: true, attributeFilter: ['style', 'aria-hidden'] })
918
+ const dialog = nav.closest('[role="dialog"]')
919
+ if (dialog !== null) observer.observe(dialog, { childList: true })
920
+ return () => observer.disconnect()
921
+ }, [])
922
+
923
+ React.useEffect(() => {
924
+ let active = true
925
+ refresh()
926
+ request('/mgw/update-check').then((data) => {
927
+ if (active) setUpdateInfo(data)
928
+ }).catch((cause) => {
929
+ if (active) setUpdateError(cause.message)
930
+ }).finally(() => {
931
+ if (active) setUpdateChecking(false)
932
+ })
933
+ request('/mgw/public-setup').then((data) => {
934
+ if (!active) return
935
+ setPublicSetup(data)
936
+ if (data.publicUrl) {
937
+ const match = /^wss:\/\/([^/]+)\/ws\/mobile$/.exec(data.publicUrl)
938
+ if (match) setPublicIp(match[1])
939
+ }
940
+ }).catch((cause) => active && setPublicSetup({ installed: false, configured: false, error: cause.message }))
941
+ const timer = window.setInterval(() => { if (!stoppedRef.current) refresh() }, 3000)
942
+ return () => { active = false; window.clearInterval(timer) }
943
+ }, [refresh])
944
+
945
+
946
+ React.useEffect(() => {
947
+ if (!qr) return
948
+ const previousFocus = document.activeElement
949
+ pairingDialogRef.current?.querySelector('button')?.focus()
950
+ return () => previousFocus?.focus()
951
+ }, [qr])
952
+
953
+
954
+
955
+ // App 模块方案:自定义地址与手动 Tailscale 地址不随轮询覆盖。
956
+ const chooseAppRoute = (route) => {
957
+ setQr(null)
958
+ appRouteChosenRef.current = true
959
+ appRouteRef.current = route
960
+ setAppRoute(route)
961
+ manualAppUrlRef.current = false
962
+ const nextUrl = route === 'custom'
963
+ ? (publicSetup && publicSetup.publicUrl) || ''
964
+ : (status ? pairingUrlFor(route, status) : '')
965
+ appUrlRef.current = nextUrl
966
+ setAppUrl(nextUrl)
967
+ }
968
+
969
+ const configurePublicAccess = async () => {
970
+ if (publicSetupBusy) return
971
+ setPublicSetupBusy(true)
972
+ setError(null)
973
+ try {
974
+ const data = await request('/mgw/public-setup', {
975
+ method: 'POST',
976
+ headers: { 'Content-Type': 'application/json' },
977
+ body: JSON.stringify({ publicIp }),
978
+ })
979
+ setPublicSetup(data)
980
+ // 手动地址模块尚未编辑时,把刚配置好的公网入口预填进去。
981
+ if (data.publicUrl && appRouteRef.current === 'custom' && !manualAppUrlRef.current) {
982
+ appUrlRef.current = data.publicUrl
983
+ setAppUrl(data.publicUrl)
984
+ }
985
+ } catch (cause) {
986
+ setError(cause.message)
987
+ } finally {
988
+ setPublicSetupBusy(false)
989
+ }
990
+ }
991
+
992
+ const configureCloudflare = async (enabled, mode = cloudflareMode) => {
993
+ if (cloudflareBusy) return
994
+ setCloudflareBusy(true)
995
+ setError(null)
996
+ try {
997
+ const data = await request('/mgw/cloudflare', {
998
+ method: 'POST',
999
+ headers: { 'Content-Type': 'application/json' },
1000
+ body: JSON.stringify({ enabled, ...(enabled ? {
1001
+ mode,
1002
+ ...(mode === 'named' ? { hostname: cloudflareHost, token: cloudflareToken } : {}),
1003
+ } : {}) }),
1004
+ })
1005
+ setCloudflareToken('')
1006
+ setStatus((current) => ({ ...(current || {}), cloudflare: data, gatewayEnabled: data.gatewayEnabled, gatewayMode: data.gatewayMode, publicUrl: data.publicUrl || null }))
1007
+ await refresh()
1008
+ } catch (cause) {
1009
+ setError(cause.message)
1010
+ } finally {
1011
+ setCloudflareBusy(false)
1012
+ }
1013
+ }
1014
+
1015
+ const checkCloudflare = async () => {
1016
+ if (cloudflareBusy) return
1017
+ setCloudflareBusy(true)
1018
+ setError(null)
1019
+ try {
1020
+ const data = await request('/mgw/cloudflare/check', { method: 'POST' })
1021
+ setStatus((current) => ({ ...(current || {}), cloudflare: data }))
1022
+ } catch (cause) { setError(cause.message) }
1023
+ finally { setCloudflareBusy(false) }
1024
+ }
1025
+
1026
+ const restartCloudflare = async () => {
1027
+ if (cloudflareBusy) return
1028
+ setCloudflareBusy(true)
1029
+ setError(null)
1030
+ try {
1031
+ const data = await request('/mgw/cloudflare/restart', { method: 'POST' })
1032
+ if (data.mode === 'quick') setQr(null)
1033
+ setStatus((current) => ({ ...(current || {}), cloudflare: data }))
1034
+ await refresh()
1035
+ } catch (cause) {
1036
+ setError(cause.message)
1037
+ } finally {
1038
+ setCloudflareBusy(false)
1039
+ }
1040
+ }
1041
+
1042
+ const requestPairing = async (body) => request('/mgw/pair', {
1043
+ method: 'POST',
1044
+ headers: { 'Content-Type': 'application/json' },
1045
+ body: JSON.stringify({ lanUrl: lanPairingUrl(status), ...body }),
1046
+ })
1047
+
1048
+ // 两个模块各自生成二维码:
1049
+ // 小程序:自动选择(多路载荷,小程序优先中继)或鲸尾公网中继专用码;
1050
+ // App:局域网 / Cloudflare / Tailscale / 手动地址(上游插件的直连方式)。
1051
+ const pairFor = async (module) => {
1052
+ setBusy(true)
1053
+ setError(null)
1054
+ setPairingTokenCopied(false)
1055
+ try {
1056
+ let data
1057
+ if (module === 'mini') {
1058
+ // 小程序专用路线:中继优先、局域网兜底(路线由小程序端按路由表选择)。
1059
+ data = await requestPairing({ route: 'mini' })
1060
+ } else {
1061
+ data = await requestPairing({
1062
+ publicUrl: appRoute === 'tailscale' ? tailscaleEndpointOf(appUrl, status) : appUrl,
1063
+ route: appRoute,
1064
+ })
1065
+ }
1066
+ pairingIdRef.current = data.pairing?.id || null
1067
+ setQr(data)
1068
+ } catch (cause) {
1069
+ setError(cause.message)
1070
+ } finally {
1071
+ setBusy(false)
1072
+ }
1073
+ }
1074
+
1075
+ // Fork: the pairing payload must be copyable wherever the WebUI is
1076
+ // opened. navigator.clipboard only exists in a secure context, and the
1077
+ // fnOS gateway embedding is plain http — there the async API is simply
1078
+ // missing. Fall back to the deprecated-but-universal execCommand path
1079
+ // before giving up, and report failures inside the QR dialog (the
1080
+ // panel's error banner sits behind the modal and is invisible).
1081
+ const writeClipboard = (text) => {
1082
+ if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
1083
+ return navigator.clipboard.writeText(text)
1084
+ }
1085
+ return new Promise((resolve, reject) => {
1086
+ const holder = document.createElement('textarea')
1087
+ holder.value = text
1088
+ holder.setAttribute('readonly', '')
1089
+ holder.style.position = 'fixed'
1090
+ holder.style.top = '-1000px'
1091
+ holder.style.opacity = '0'
1092
+ document.body.appendChild(holder)
1093
+ holder.select()
1094
+ holder.setSelectionRange(0, text.length)
1095
+ let copied = false
1096
+ try {
1097
+ copied = document.execCommand('copy')
1098
+ } catch (error) {
1099
+ copied = false
1100
+ }
1101
+ document.body.removeChild(holder)
1102
+ if (copied) resolve()
1103
+ else reject(new Error('浏览器拒绝写入剪贴板'))
1104
+ })
1105
+ }
1106
+
1107
+ const copyPairingText = async () => {
1108
+ if (!qr || !qr.qrPayload) return
1109
+ try {
1110
+ await writeClipboard(qr.qrPayload)
1111
+ setError(null)
1112
+ setCopyNotice(null)
1113
+ setPairingTokenCopied(true)
1114
+ window.setTimeout(() => setPairingTokenCopied(false), 2200)
1115
+ } catch (cause) {
1116
+ setPairingTokenCopied(false)
1117
+ setCopyNotice(`${cause.message || '复制失败'},请选中上面文本后按 Ctrl/Cmd+C`)
1118
+ window.setTimeout(() => setCopyNotice(null), 6000)
1119
+ // Leave the payload selected so the manual copy is one keystroke away.
1120
+ const area = pairingDialogRef.current && pairingDialogRef.current.querySelector('textarea')
1121
+ if (area) { area.focus(); area.select() }
1122
+ }
1123
+ }
1124
+
1125
+ const changeGatewayMode = async (mode) => {
1126
+ setBusy(true)
1127
+ setError(null)
1128
+ try {
1129
+ const data = await request('/mgw/gateway', {
1130
+ method: 'POST',
1131
+ headers: { 'Content-Type': 'application/json' },
1132
+ body: JSON.stringify({ mode }),
1133
+ })
1134
+ setStatus((current) => ({ ...(current || {}), ...data }))
1135
+ if (mode === 'disabled') setQr(null)
1136
+ } catch (cause) {
1137
+ setError(cause.message)
1138
+ } finally {
1139
+ setBusy(false)
1140
+ }
1141
+ }
1142
+
1143
+ const toggleAuth = async () => {
1144
+ const enabled = !(status && status.requireAuth)
1145
+ if (!enabled && !window.confirm('关闭设备鉴权后,任何能访问移动网关的人都可以控制 DSH。此选项仅限 Debug 阶段使用,确定继续吗?')) return
1146
+ setBusy(true)
1147
+ setError(null)
1148
+ try {
1149
+ const data = await request('/mgw/auth', {
1150
+ method: 'POST',
1151
+ headers: { 'Content-Type': 'application/json' },
1152
+ body: JSON.stringify({ enabled }),
1153
+ })
1154
+ setStatus((current) => ({ ...(current || {}), requireAuth: data.requireAuth }))
1155
+ } catch (cause) {
1156
+ setError(cause.message)
1157
+ } finally {
1158
+ setBusy(false)
1159
+ }
1160
+ }
1161
+
1162
+ // 左侧栏入口开关:持久化到 /mgw/ui,并立即通知侧边栏按钮。
1163
+ const toggleSidebarEntry = async () => {
1164
+ if (sidebarBusy) return
1165
+ setSidebarBusy(true)
1166
+ setError(null)
1167
+ try {
1168
+ const data = await request('/mgw/ui', {
1169
+ method: 'POST',
1170
+ headers: { 'Content-Type': 'application/json' },
1171
+ body: JSON.stringify({ sidebarEntry: !sidebarOn }),
1172
+ })
1173
+ setSidebarEntry(data.sidebarEntry !== false)
1174
+ } catch (cause) {
1175
+ setError(cause.message)
1176
+ } finally {
1177
+ setSidebarBusy(false)
1178
+ }
1179
+ }
1180
+
1181
+ // 一键清除离线设备:吊销所有当前离线的已配对设备,在线设备不受影响。
1182
+ const clearOfflineDevices = async () => {
1183
+ const targets = Array.isArray(devices) ? devices.filter((device) => !device.online) : []
1184
+ if (targets.length === 0 || offlineClearing) return
1185
+ if (!window.confirm(`清除 ${targets.length} 台离线设备?清除后需要重新配对才能连接。`)) return
1186
+ setOfflineClearing(true)
1187
+ setDeviceNotice(null)
1188
+ setDeviceNoticeError(false)
1189
+ setError(null)
1190
+ try {
1191
+ const data = await request('/mgw/devices/revoke-offline', { method: 'POST' })
1192
+ const removedIds = new Set(Array.isArray(data.removed) ? data.removed : [])
1193
+ setDevices((current) => Array.isArray(current) ? current.filter((item) => !removedIds.has(item.id)) : current)
1194
+ setDeviceNotice(`已清除 ${data.count ?? removedIds.size} 台离线设备`)
1195
+ window.setTimeout(() => setDeviceNotice(null), 2200)
1196
+ } catch (cause) {
1197
+ setDeviceNoticeError(true)
1198
+ setDeviceNotice(`清除失败:${cause.message}`)
1199
+ setError(cause.message)
1200
+ } finally {
1201
+ setOfflineClearing(false)
1202
+ }
1203
+ }
1204
+
1205
+ // 批量吊销:逐个调用单设备吊销接口(/mgw/devices/<id>/revoke)。
1206
+ const removeDevices = async (list) => {
1207
+ const targets = Array.isArray(list) ? list : [list]
1208
+ const removed = []
1209
+ for (const device of targets) {
1210
+ if (revokingIdsRef.current.has(device.id)) continue
1211
+ setDeviceNotice(null)
1212
+ setDeviceNoticeError(false)
1213
+ setError(null)
1214
+ deviceRevision.current += 1
1215
+ revokingIdsRef.current.add(device.id)
1216
+ setRevokingIds((current) => new Set(current).add(device.id))
1217
+ try {
1218
+ await request(`/mgw/devices/${encodeURIComponent(device.id)}/revoke`, { method: 'POST' })
1219
+ removed.push(device.id)
1220
+ setDevices((current) => Array.isArray(current) ? current.filter((item) => item.id !== device.id) : current)
1221
+ setDeviceNotice(`已吊销 ${device.displayName || device.name}`)
1222
+ window.setTimeout(() => setDeviceNotice(null), 2200)
1223
+ } catch (cause) {
1224
+ setDeviceNoticeError(true)
1225
+ setDeviceNotice(`吊销失败:${cause.message}`)
1226
+ setError(cause.message)
1227
+ } finally {
1228
+ deviceRevision.current += 1
1229
+ revokingIdsRef.current.delete(device.id)
1230
+ setRevokingIds((current) => { const next = new Set(current); next.delete(device.id); return next })
1231
+ }
1232
+ }
1233
+ await refreshRead('devices')
1234
+ return removed
1235
+ }
1236
+ const revoke = (device) => removeDevices([device])
1237
+ const selectDevice = (id, selected) => setSelectedDeviceIds(current => {
1238
+ const next = new Set(current)
1239
+ selected ? next.add(id) : next.delete(id)
1240
+ return next
1241
+ })
1242
+
1243
+ const savePermission = async (device, module, value) => {
1244
+ if (permissionLock.current || revokingIdsRef.current.size) return
1245
+ permissionLock.current = true
1246
+ deviceRevision.current += 1
1247
+ setPermissionSaving(`${device.id}:${module}`)
1248
+ setError(null)
1249
+ try {
1250
+ const result = await request(`/mgw/devices/${encodeURIComponent(device.id)}/permissions`, {
1251
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
1252
+ body: JSON.stringify({ permissions: { [module]: value } }),
1253
+ })
1254
+ setDevices(current => current?.map(row => row.id === device.id ? { ...row, permissions: result.permissions } : row))
1255
+ } catch (cause) { setError(cause.message) }
1256
+ finally { deviceRevision.current += 1; permissionLock.current = false; setPermissionSaving(null) }
1257
+ }
1258
+ const restartNoticeInstance = status?.gatewayInstanceId || (status?.webPid ? String(status.webPid) : null)
1259
+ const dismissRestartNotice = () => {
1260
+ dismissedRestartInstance = restartNoticeInstance
1261
+ setDismissedNotice(restartNoticeInstance)
1262
+ try { window.localStorage.setItem(restartNoticeStorageKey, restartNoticeInstance) } catch { /* keep in-memory dismissal */ }
1263
+ }
1264
+
1265
+ const onlineDevices = (devices || []).filter((device) => device.online)
1266
+ const offlineDevices = (devices || []).filter((device) => !device.online)
1267
+ const orderedDevices = [...onlineDevices, ...offlineDevices]
1268
+ // fork:默认只列在线设备,展开后列全部(上游整合时该派生值丢失)。
1269
+ const visibleDevices = showAllDevices ? orderedDevices : onlineDevices
1270
+ const selectedCount = orderedDevices.filter(device => selectedDeviceIds.has(device.id)).length
1271
+ const deletingDevices = revokingIds.size > 0
1272
+ const deviceActionsDisabled = deletingDevices || permissionSaving !== null
1273
+
1274
+ // The same v2 QR is native-app compatible; mini-program-only public
1275
+ // routing is carried in an optional field that older apps ignore.
1276
+ const relayInfo = status && status.relay ? status.relay : null
1277
+ const relayConnector = status && status.relayConnector ? status.relayConnector : null
1278
+ const cloudflareReady = !!(status?.cloudflare?.enabled && status.cloudflare.publicReady === true && status.cloudflare.publicUrl)
1279
+ // App 模块的生成按钮:入口就绪才可点,避免生成无法连接的二维码。
1280
+ const appPairingDisabled = busy || !(status && status.gatewayEnabled) ||
1281
+ (appRoute === 'custom' && !appUrl.trim()) ||
1282
+ (appRoute === 'cloudflare' && !cloudflareReady) ||
1283
+ (appRoute === 'auto' && !lanPairingUrl(status)) ||
1284
+ (appRoute === 'lan' && !lanPairingUrl(status)) ||
1285
+ (appRoute === 'tailscale' && !(status?.lan?.listening && isTailscaleInput(appUrl)))
1286
+ const appPlan = appConnectionPlan(appRoute, status, appUrl)
1287
+
1288
+ const advice = connectionAdvice(status, publicSetup)
1289
+ const helpLine = (name, description) => React.createElement('div', { style: { marginTop: 7 } },
1290
+ React.createElement('strong', null, name), ':', description)
1291
+
1292
+ return React.createElement('div', { style: styles.backdrop, onMouseDown: () => setOpen(false) },
1293
+ qr ? React.createElement('div', { style: { ...styles.backdrop, zIndex: 1201 },
1294
+ onMouseDown: (event) => { event.stopPropagation(); closePairingDialog() } },
1295
+ React.createElement('div', { className: 'mgw-pairing-dialog', 'data-closing': pairingClosing, ref: pairingDialogRef, role: 'dialog', 'aria-modal': true, 'aria-label': '设备配对二维码', tabIndex: -1,
1296
+ style: { ...styles.panel, width: 'min(520px, 100%)', height: 'auto', overflowY: 'auto', scrollbarWidth: 'none' },
1297
+ onMouseDown: (event) => event.stopPropagation(),
1298
+ onKeyDown: (event) => {
1299
+ if (event.key === 'Escape') { event.stopPropagation(); closePairingDialog() }
1300
+ if (event.key === 'Tab') {
1301
+ const items = [...event.currentTarget.querySelectorAll('button, textarea')]
1302
+ const first = items[0], last = items[items.length - 1]
1303
+ if (event.shiftKey && (document.activeElement === first || document.activeElement === event.currentTarget)) { event.preventDefault(); last?.focus() }
1304
+ else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first?.focus() }
1305
+ }
1306
+ } },
1307
+ React.createElement('div', { style: { display: 'flex', justifyContent: 'flex-end' } },
1308
+ React.createElement('button', { type: 'button', style: { ...styles.button, ...styles.headerButton }, 'aria-label': '关闭配对窗口', onClick: closePairingDialog }, '✕')),
1309
+ React.createElement('section', { style: { textAlign: 'center' } },
1310
+ React.createElement('strong', null, qr.payload?.version === 3 && qr.payload?.mode === 'relay'
1311
+ ? '使用鲸尾小程序扫码(此二维码仅适用于小程序)'
1312
+ : '使用 DSH App 或鲸尾小程序扫码'),
1313
+ React.createElement('img', { style: styles.qr, src: `data:image/svg+xml;charset=utf-8,${encodeURIComponent(qr.svg)}`, alt: '一次性设备配对二维码' }),
1314
+ qr.payload?.version === 3 && qr.payload?.mode === 'relay'
1315
+ ? React.createElement('p', { style: { ...styles.muted, textAlign: 'left' } }, '这是小程序专用的鲸尾公网中继二维码,DSH App 不能使用。需要同时配对 DSH App 和小程序时,请改选“自动选择”。')
1316
+ : qr.payload?.miniProgramRoute?.mode === 'direct'
1317
+ ? React.createElement('p', { style: { ...styles.muted, textAlign: 'left' } }, '此二维码为 DSH App 和小程序提供公网与局域网候选地址;客户端会自动尝试可达线路。')
1318
+ : qr.payload?.miniProgramRoute?.mode === 'relay'
1319
+ ? React.createElement('p', { style: { ...styles.muted, textAlign: 'left' } }, '当前没有可用公网 WSS:DSH App 使用局域网,小程序使用鲸尾公网中继。选择“局域网直连”时,两端都直接使用局域网。')
1320
+ : React.createElement('p', { style: { ...styles.muted, textAlign: 'left' } }, '此二维码含当前可用的连接地址;DSH App 和小程序均可通过公网或局域网连接。'),
1321
+ React.createElement('label', { style: { ...styles.label, textAlign: 'left' } }, 'Base64URL 配对字符串'),
1322
+ React.createElement('textarea', { style: styles.pairingText, value: qr.qrPayload, readOnly: true, spellCheck: false, onFocus: (event) => event.target.select() }),
1323
+ React.createElement('button', { type: 'button', style: { ...styles.button, width: '100%', marginBottom: 8, borderColor: pairingTokenCopied ? colors.success : colors.border, color: pairingTokenCopied ? colors.success : colors.text }, onClick: copyPairingText }, pairingTokenCopied ? '✓ 已复制' : '复制配对 Token'),
1324
+ pairingTokenCopied ? React.createElement('div', { style: { ...styles.muted, color: colors.success, marginBottom: 8 } }, '已复制到剪贴板') : null,
1325
+ copyNotice ? React.createElement('div', { role: 'alert', style: { ...styles.muted, color: colors.danger, marginBottom: 8 } }, copyNotice) : null,
1326
+ React.createElement('div', { style: styles.muted }, `有效期至 ${new Date(qr.pairing.expiresAt).toLocaleTimeString()};扫码成功后此二维码立即失效。`)))) : null,
1327
+ React.createElement('aside', { className: 'mobile-gateway-panel', inert: qr ? true : undefined, 'aria-hidden': qr ? true : undefined, style: styles.panel, onMouseDown: (event) => { event.stopPropagation(); setToolsOpen(false) }, role: 'dialog', 'aria-modal': true, 'aria-label': '鲸尾网关助手管理' },
1328
+ React.createElement('div', { style: styles.header },
1329
+ React.createElement('div', null,
1330
+ React.createElement('h2', { style: styles.title }, '鲸尾网关助手'),
1331
+ React.createElement('div', { style: styles.muted }, !status ? '正在加载网关状态…' : status.gatewayEnabled ? `移动网关已开启 · ${status.requireAuth ? '设备鉴权已开启' : '本机设备鉴权已关闭'}` : '移动网关已关闭 · 普通 WebUI 模式')),
1332
+ React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 6 } },
1333
+ React.createElement('div', { style: { position: 'relative' }, onMouseDown: (event) => event.stopPropagation() },
1334
+ React.createElement('button', {
1335
+ type: 'button', style: { ...styles.button, ...styles.headerButton, borderRadius: '50%' }, title: '工具', 'aria-label': '工具',
1336
+ 'aria-haspopup': 'menu', 'aria-expanded': toolsOpen,
1337
+ onClick: () => setToolsOpen((value) => !value),
1338
+ }, React.createElement('svg', { width: 20, height: 20, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true },
1339
+ React.createElement('path', { d: 'M10.3 2.8h3.4l.5 2.2a7.6 7.6 0 0 1 1.7.7l1.9-1.2 2.4 2.4L19 8.8c.3.5.5 1.1.7 1.7l2.2.5v3.4l-2.2.5a7.6 7.6 0 0 1-.7 1.7l1.2 1.9-2.4 2.4-1.9-1.2a7.6 7.6 0 0 1-1.7.7l-.5 2.2h-3.4l-.5-2.2a7.6 7.6 0 0 1-1.7-.7l-1.9 1.2-2.4-2.4L5 16.6a7.6 7.6 0 0 1-.7-1.7l-2.2-.5V11l2.2-.5A7.6 7.6 0 0 1 5 8.8L3.8 6.9l2.4-2.4 1.9 1.2a7.6 7.6 0 0 1 1.7-.7l.5-2.2Z' }),
1340
+ React.createElement('circle', { cx: 12, cy: 12.7, r: 3.1 }))),
1341
+ toolsOpen ? React.createElement('div', { style: styles.toolsMenu, role: 'menu', 'aria-label': '网关工具' },
1342
+ React.createElement('button', {
1343
+ type: 'button', role: 'menuitem', disabled: toolBusy || stoppedRef.current || !status?.tools?.restartWeb,
1344
+ style: { ...styles.toolsItem, opacity: status?.tools?.restartWeb ? 1 : .5 },
1345
+ onClick: () => runTool('restart-web'),
1346
+ }, '重启当前网关',
1347
+ React.createElement('span', { style: { ...styles.muted, display: 'block', marginTop: 2 } }, '结束当前进程并重新启动 DSH Web')),
1348
+ React.createElement('button', {
1349
+ type: 'button', role: 'menuitem', disabled: toolBusy || stoppedRef.current || !status?.tools?.stopWeb,
1350
+ style: { ...styles.toolsItem, color: colors.danger, opacity: status?.tools?.stopWeb ? 1 : .5 },
1351
+ onClick: () => runTool('stop-web'),
1352
+ }, '停止 DSH Web',
1353
+ React.createElement('span', { style: { ...styles.muted, display: 'block', marginTop: 2 } }, '结束后台进程,所有连接将断开')))
1354
+ : null),
1355
+ React.createElement('button', { style: { ...styles.button, ...styles.headerButton }, onClick: () => setOpen(false), 'aria-label': '关闭' },
1356
+ React.createElement('svg', { width: 20, height: 20, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 2.2, strokeLinecap: 'round', 'aria-hidden': true },
1357
+ React.createElement('path', { d: 'M6 6l12 12M18 6L6 18' }))))),
1358
+ React.createElement('div', { className: 'mgw-body' },
1359
+ React.createElement('nav', { ref: navRef, className: 'mgw-nav', 'aria-label': '鲸尾网关助手设置分组' },
1360
+ [['general', '通用设置'], ['pairing', '连接与配对'], ['devices', '可信设备'], ['network', '网络检测']].map(([id, label]) =>
1361
+ React.createElement('button', { key: id, type: 'button', 'aria-current': activeSection === id ? 'page' : undefined,
1362
+ onClick: () => { setActiveSection(id); setConnectionHelpOpen(false); setToolsOpen(false) } }, label))),
1363
+ React.createElement('div', { className: 'mgw-content', key: activeSection },
1364
+ restartNoticeInstance && dismissedNotice !== restartNoticeInstance ? React.createElement('section', { style: { ...styles.card, position: 'relative', padding: '10px 40px 10px 12px', border: '1px solid', borderRadius: 10, marginBottom: 8, background: 'var(--dsw-alias-state-warn-tertiary, #fff7df)', borderColor: 'color-mix(in srgb, #d99a16 35%, transparent)', fontSize: 12, lineHeight: 1.6 }, role: 'note' },
1365
+ React.createElement('button', { type: 'button', 'aria-label': '关闭重启提醒', title: '关闭提醒',
1366
+ style: { ...styles.button, position: 'absolute', right: 8, top: 8, border: 0, width: 24, height: 24, padding: 0, color: colors.muted },
1367
+ onClick: dismissRestartNotice }, '✕'),
1368
+ React.createElement('strong', null, '若安装或更新后连接异常,请重启应用'),
1369
+ React.createElement('div', { style: { color: colors.muted, marginTop: 4 } },
1370
+ '完全退出并重启 APP/Desktop;Web UI 请重启 DSH Web 服务。'),
1371
+ React.createElement('div', { style: { color: colors.muted, marginTop: 4 } },
1372
+ '端口仍被占用时,请关闭其他 Harness 实例。')) : null,
1373
+ toolNotice ? React.createElement('div', { style: { ...styles.muted, marginBottom: 10 } }, toolNotice) : null,
1374
+ (error || deviceLoadError || statusLoadError) ? React.createElement('div', { style: styles.error, role: 'alert' }, error || deviceLoadError || statusLoadError) : null,
1375
+ React.createElement('div', { hidden: activeSection !== 'general' },
1376
+ // Linux 专属:持久化后台运行(systemd 用户服务)。其他平台不渲染。
1377
+ status?.platform === 'linux' ? React.createElement('section', { style: styles.card },
1378
+ React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 14, alignItems: 'center' } },
1379
+ React.createElement('div', null,
1380
+ React.createElement('strong', null, '持久化后台运行'),
1381
+ React.createElement('p', { style: styles.muted }, '由 systemd 托管整个 DSH Web,SSH 断开后继续运行,服务器重启后自动启动。开启时会短暂重连。'),
1382
+ status.backgroundService?.reason ? React.createElement('p', { style: styles.muted }, status.backgroundService.reason) : null,
1383
+ status.backgroundService?.unit ? React.createElement('p', { style: { ...styles.muted, opacity: .75 } }, `服务名:${status.backgroundService.unit}`) : null),
1384
+ React.createElement('label', { style: { ...styles.switch, opacity: status.backgroundService?.available || status.backgroundService?.managed ? (backgroundBusy ? .55 : 1) : .55 },
1385
+ title: status.backgroundService?.available ? '切换持久化后台运行' : (status.backgroundService?.reason || '当前环境不支持') },
1386
+ React.createElement('input', {
1387
+ type: 'checkbox',
1388
+ role: 'switch',
1389
+ 'aria-label': '持久化后台运行',
1390
+ 'aria-checked': !!status.backgroundService?.managed,
1391
+ checked: !!status.backgroundService?.managed,
1392
+ disabled: backgroundBusy || !(status.backgroundService?.available || status.backgroundService?.managed),
1393
+ onChange: toggleBackgroundService,
1394
+ style: styles.switchInput,
1395
+ }),
1396
+ React.createElement('span', { style: { ...styles.switchTrack, background: status.backgroundService?.managed ? colors.success : colors.muted } }),
1397
+ React.createElement('span', { style: { ...styles.switchKnob, left: status.backgroundService?.managed ? 21 : 3 } }))),
1398
+ ) : null,
1399
+ React.createElement('section', { style: styles.card },
1400
+ React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 14, alignItems: 'center' } },
1401
+ React.createElement('div', null,
1402
+ React.createElement('strong', null, '网关运行模式'),
1403
+ React.createElement('div', { style: { ...styles.muted, marginTop: 4 } }, status && status.gatewayEnabled
1404
+ ? status.gatewayMode === 'persistent'
1405
+ ? '重启后保持开启'
1406
+ : status.waitExpiresAt
1407
+ ? `等待可信设备连接,约 ${Math.max(1, Math.ceil((status.waitExpiresAt - Date.now()) / 60000))} 分钟后自动关闭`
1408
+ : '设备已连接过,本次运行保持开启;重启后重新计时'
1409
+ : '不接受移动设备连接')),
1410
+ React.createElement('span', { style: { position: 'relative', display: 'inline-flex', flexShrink: 0 } },
1411
+ React.createElement(GatewaySelect, {
1412
+ style: { ...styles.input, width: 'auto', marginBottom: 0, padding: '8px 40px 8px 12px', appearance: 'none', WebkitAppearance: 'none' },
1413
+ 'aria-label': '网关运行模式',
1414
+ value: status ? status.gatewayMode || (status.gatewayEnabled ? 'temporary' : 'disabled') : 'disabled',
1415
+ disabled: busy || !status,
1416
+ onChange: (event) => changeGatewayMode(event.target.value),
1417
+ },
1418
+ React.createElement('option', { value: 'disabled' }, '关闭'),
1419
+ React.createElement('option', { value: 'temporary' }, '临时开启'),
1420
+ React.createElement('option', { value: 'persistent' }, '常驻开启')),
1421
+ )),
1422
+ status && status.gatewayId ? React.createElement('div', { style: { ...styles.muted, marginTop: 12, overflowWrap: 'anywhere' } },
1423
+ status.gatewayName) : null),
1424
+ React.createElement('section', { style: styles.card },
1425
+ React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 14, alignItems: 'center' } },
1426
+ React.createElement('div', null,
1427
+ React.createElement('strong', null, '设备鉴权'),
1428
+ React.createElement('div', { style: { ...styles.muted, marginTop: 4 } }, status && status.requireAuth ? '已开启,仅允许可信设备连接' : '已关闭,仅影响本机 Debug 入口')),
1429
+ React.createElement('label', { style: { ...styles.switch, opacity: busy || !status ? .55 : 1 }, title: status && status.requireAuth ? '关闭设备鉴权' : '开启设备鉴权' },
1430
+ React.createElement('input', {
1431
+ type: 'checkbox',
1432
+ role: 'switch',
1433
+ 'aria-label': '设备鉴权',
1434
+ 'aria-checked': !!(status && status.requireAuth),
1435
+ checked: !!(status && status.requireAuth),
1436
+ disabled: busy || !status,
1437
+ onChange: toggleAuth,
1438
+ style: styles.switchInput,
1439
+ }),
1440
+ React.createElement('span', { style: { ...styles.switchTrack, background: status && status.requireAuth ? colors.success : colors.danger } }),
1441
+ React.createElement('span', { style: { ...styles.switchKnob, left: status && status.requireAuth ? 21 : 3 } }))),
1442
+ status && !status.requireAuth
1443
+ ? React.createElement('p', { style: { ...styles.error, margin: '12px 0 0' } }, 'Debug 模式:本机 DSH 入口将跳过设备凭证校验;独立局域网入口仍强制鉴权。')
1444
+ : null),
1445
+ React.createElement('section', { style: styles.card },
1446
+ React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 14, alignItems: 'center' } },
1447
+ React.createElement('div', null,
1448
+ React.createElement('strong', null, '在左侧栏显示入口'),
1449
+ React.createElement('div', { style: { ...styles.muted, marginTop: 4 } }, sidebarOn
1450
+ ? 'Harness 侧边栏底部显示「鲸尾移动设备」按钮;关闭后仅从设置页打开。'
1451
+ : '已隐藏侧边栏入口;可在这里重新开启。')),
1452
+ React.createElement('label', { style: { ...styles.switch, opacity: sidebarBusy ? .55 : 1 }, title: sidebarOn ? '隐藏左侧栏入口' : '在左侧栏显示入口' },
1453
+ React.createElement('input', {
1454
+ type: 'checkbox',
1455
+ role: 'switch',
1456
+ 'aria-label': '在左侧栏显示入口',
1457
+ 'aria-checked': sidebarOn,
1458
+ checked: sidebarOn,
1459
+ disabled: sidebarBusy,
1460
+ onChange: toggleSidebarEntry,
1461
+ style: styles.switchInput,
1462
+ }),
1463
+ React.createElement('span', { style: { ...styles.switchTrack, background: sidebarOn ? colors.success : colors.muted } }),
1464
+ React.createElement('span', { style: { ...styles.switchKnob, left: sidebarOn ? 21 : 3 } })))),
1465
+ React.createElement('section', { style: styles.card },
1466
+ React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 14, alignItems: 'flex-start' } },
1467
+ React.createElement('div', null,
1468
+ React.createElement('strong', null, '插件在线更新'),
1469
+ React.createElement('div', { style: { ...styles.muted, marginTop: 4 } }, updateChecking
1470
+ ? '正在检查 npm 最新版本…'
1471
+ : updateInfo
1472
+ ? `当前版本 v${updateInfo.currentVersion} · npm 最新 v${updateInfo.latestVersion}`
1473
+ : '暂时无法获取版本信息'),
1474
+ updateInfo?.updateAvailable
1475
+ ? React.createElement('div', { style: { marginTop: 6, color: colors.success, fontWeight: 600 } }, '发现新版本,可直接升级安装。')
1476
+ : null,
1477
+ updateInfo && !updateInfo.updateAvailable
1478
+ ? React.createElement('div', { style: { marginTop: 6, color: colors.success } }, '当前已是最新版本。')
1479
+ : null,
1480
+ updateNotice
1481
+ ? React.createElement('div', { style: { ...styles.muted, marginTop: 6, overflowWrap: 'anywhere' }, role: 'status' }, updateNotice)
1482
+ : null,
1483
+ updateError
1484
+ ? React.createElement('div', { style: { ...styles.muted, marginTop: 6, color: colors.danger, overflowWrap: 'anywhere' }, role: 'status' }, `检查失败:${updateError}`)
1485
+ : null),
1486
+ React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 8, minWidth: 100 } },
1487
+ React.createElement('button', {
1488
+ type: 'button',
1489
+ style: { ...styles.button, ...styles.primary, opacity: updateBusy || !updateInfo?.updateAvailable ? .55 : 1 },
1490
+ disabled: updateBusy || updateChecking || !updateInfo?.updateAvailable,
1491
+ onClick: upgradePlugin,
1492
+ }, updateBusy ? '正在升级…' : '立即升级'),
1493
+ React.createElement('button', {
1494
+ type: 'button',
1495
+ style: styles.button,
1496
+ disabled: updateChecking || updateBusy,
1497
+ onClick: checkForPluginUpdate,
1498
+ }, updateChecking ? '检查中…' : '重新检查')))),
1499
+ ),
1500
+ React.createElement('div', { hidden: activeSection !== 'network' },
1501
+ React.createElement(ServerNetworkDiagnostics, null)),
1502
+ React.createElement('div', { hidden: activeSection !== 'pairing' },
1503
+ // ── 模块一:DSH App(推荐)────────────────────────────────
1504
+ React.createElement('section', { style: { ...styles.card, marginTop: 16 } },
1505
+ React.createElement('button', {
1506
+ type: 'button',
1507
+ style: { ...styles.button, width: '100%', textAlign: 'left', display: 'flex', justifyContent: 'space-between', alignItems: 'center', background: 'transparent', border: 0, padding: 0 },
1508
+ 'aria-expanded': appLayerOpen,
1509
+ onClick: () => setAppLayerOpen((value) => !value),
1510
+ },
1511
+ React.createElement('span', null,
1512
+ React.createElement('strong', null, 'DSH App(推荐)'),
1513
+ React.createElement('span', { style: { ...styles.muted, marginLeft: 8, fontWeight: 400 } },
1514
+ appLayerOpen ? '收起 DSH App 方式' : '推荐:手机安装 DSH App 时使用')),
1515
+ React.createElement('svg', { width: 16, height: 16, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor',
1516
+ strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true,
1517
+ style: { flexShrink: 0, color: colors.muted, transform: appLayerOpen ? 'rotate(180deg)' : 'none', transition: 'transform .18s ease' } },
1518
+ React.createElement('path', { d: 'M6 9l6 6 6-6' }))),
1519
+ appLayerOpen
1520
+ ? React.createElement(React.Fragment, null,
1521
+ React.createElement('p', { style: styles.muted }, 'DSH App 直连入口(推荐手机端使用),与下方的鲸尾公网互不影响。'),
1522
+ React.createElement('div', { style: { display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: '8px 14px', maxWidth: '100%', marginBottom: 16 } },
1523
+ React.createElement(GatewaySelect, { style: styles.input, value: appRoute, onChange: (event) => chooseAppRoute(event.target.value), disabled: !status, 'aria-label': 'App 连接方式' },
1524
+ React.createElement('option', { value: 'auto' }, '自动选择'),
1525
+ React.createElement('option', { value: 'lan', disabled: !lanPairingUrl(status) }, lanPairingUrl(status)
1526
+ ? '局域网直连'
1527
+ : '局域网直连 · 当前不可用'),
1528
+ status?.cloudflare?.supported
1529
+ ? React.createElement('option', { value: 'cloudflare' }, 'Cloudflare 外网') : null,
1530
+ React.createElement('option', { value: 'tailscale' },
1531
+ (() => {
1532
+ const ts = status?.tailscale || {}
1533
+ const serve = ts.serve || {}
1534
+ if (ts.serveUrl) return 'Tailscale 内嵌隧道 · 已连接'
1535
+ if (serve.loginUrl) return 'Tailscale · 等待授权'
1536
+ if (serve.state === 'starting') return 'Tailscale · 启动中'
1537
+ return 'Tailscale 内嵌隧道'
1538
+ })()),
1539
+ React.createElement('option', { value: 'custom' }, '公网或其他手动地址'))),
1540
+ // 与上游一致的连接方案摘要:配对入口 + 提示。
1541
+ React.createElement('div', { 'aria-label': '当前连接方案', style: { margin: '0 0 10px', padding: '9px 11px', borderRadius: 10, border: `1px solid ${colors.border}`, background: colors.card, fontSize: 12, lineHeight: 1.7 } },
1542
+ React.createElement('div', null, React.createElement('strong', null, '配对入口'), ':', appPlan.entry),
1543
+ React.createElement('div', { style: { color: appPlan.valid ? colors.muted : colors.danger } }, appPlan.note)),
1544
+ appRoute === 'tailscale'
1545
+ ? (() => {
1546
+ const ts = status?.tailscale || {}
1547
+ const node = ts.node || ts.serve || {}
1548
+ const backend = String(node.backendState || 'disabled')
1549
+ const running = backend === 'Running'
1550
+ const needAuth = !running && !!node.loginUrl
1551
+ const host = node.hostname || 'dsh-gateway'
1552
+ const dot = running ? '#22c55e' : (needAuth ? '#f59e0b' : '#9ca3af')
1553
+ const title = running ? '已连接' : (needAuth ? '等待授权' : (backend === 'Starting' ? '启动中' : '未启动'))
1554
+ return React.createElement('div', { style: { margin: '0 0 12px', padding: 12, borderRadius: 12, border: '1px solid ' + colors.border, background: colors.card, display: 'flex', flexDirection: 'column', gap: 10 } },
1555
+ React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8 } },
1556
+ React.createElement('span', { style: { width: 8, height: 8, borderRadius: 4, background: dot, display: 'inline-block' } }),
1557
+ React.createElement('strong', { style: { fontSize: 13 } }, 'Tailscale 内嵌隧道'),
1558
+ React.createElement('span', { style: { marginLeft: 'auto', fontSize: 12, color: colors.muted } }, title)),
1559
+ React.createElement('div', { style: { fontSize: 12, color: colors.muted, wordBreak: 'break-all', lineHeight: 1.6 } },
1560
+ running ? (ts.serveUrl || node.dnsName || '已连接') : (needAuth ? '需要一次浏览器授权,或直接填写 Auth Key 免登录。' : (node.error || '点击「启动隧道」创建内嵌节点。'))),
1561
+ React.createElement('div', { style: { display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' } },
1562
+ needAuth ? React.createElement('button', { type: 'button', style: { ...styles.button, ...styles.primary, width: 'auto', flex: '0 0 auto', minWidth: 96 }, onClick: () => window.open(node.loginUrl || '/mgw/tailscale/login', '_blank', 'noopener') }, '去授权') : null,
1563
+ React.createElement('button', { type: 'button', style: { ...styles.button, ...styles.primary, width: 'auto', flex: '0 0 auto', minWidth: 96 }, onClick: async () => { try { setBusy(true); await request('/mgw/tailscale', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'start' }) }); setStatus(await request('/mgw/status')) } catch (cause) { setError(cause.message) } finally { setBusy(false) } } }, running ? '重新连接' : '启动隧道'),
1564
+ React.createElement('button', { type: 'button', style: { ...styles.button, width: 'auto', flex: '0 0 auto', minWidth: 96 }, onClick: async () => { try { setBusy(true); await request('/mgw/tailscale', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'stop' }) }); setStatus(await request('/mgw/status')) } catch (cause) { setError(cause.message) } finally { setBusy(false) } } }, '停止')),
1565
+ React.createElement('div', { style: { display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' } },
1566
+ React.createElement('span', { style: { fontSize: 12, color: colors.muted, minWidth: 52 } }, '节点名'),
1567
+ React.createElement('input', { id: 'mgw-ts-hostname', style: { ...styles.input, flex: '1 1 0%', minWidth: 0, height: 34, margin: 0, marginBottom: 0, boxSizing: 'border-box', padding: '0 10px' }, defaultValue: host, placeholder: 'dsh-gateway-win' }),
1568
+ React.createElement('button', { type: 'button', style: { ...styles.button, width: 110, flex: '0 0 110px', minWidth: 0, height: 34, padding: 0, lineHeight: '34px', textAlign: 'center', boxSizing: 'border-box', margin: 0 }, onClick: async () => { try { setBusy(true); const el = document.getElementById('mgw-ts-hostname'); const value = el && typeof el.value === 'string' ? el.value.trim() : ''; await request('/mgw/tailscale/hostname', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ hostname: value }) }); setStatus(await request('/mgw/status')) } catch (cause) { setError(cause.message) } finally { setBusy(false) } } }, '保存节点名')),
1569
+ React.createElement('div', { style: { display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' } },
1570
+ React.createElement('span', { style: { fontSize: 12, color: colors.muted, minWidth: 52 } }, 'Auth Key'),
1571
+ React.createElement('input', { id: 'mgw-ts-authkey', style: { ...styles.input, flex: '1 1 0%', minWidth: 0, height: 34, margin: 0, marginBottom: 0, boxSizing: 'border-box', padding: '0 10px' }, placeholder: 'tskey-auth-…(可选)' }),
1572
+ React.createElement('button', { type: 'button', style: { ...styles.button, width: 110, flex: '0 0 110px', minWidth: 0, height: 34, padding: 0, lineHeight: '34px', textAlign: 'center', boxSizing: 'border-box', margin: 0 }, onClick: async () => { try { setBusy(true); const el = document.getElementById('mgw-ts-authkey'); const authKey = el && typeof el.value === 'string' ? el.value.trim() : ''; if (!authKey) { setError('请先填写 Auth Key'); return } await request('/mgw/tailscale', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'start', authKey }) }); setStatus(await request('/mgw/status')) } catch (cause) { setError(cause.message) } finally { setBusy(false) } } }, '用 Key 连接')))
1573
+ })()
1574
+ : null,
1575
+ React.createElement('label', { style: styles.label, htmlFor: 'mgw-pair-address' }, appRoute === 'tailscale'
1576
+ ? '主机 Tailscale 地址(运行网关的电脑,不是手机)'
1577
+ : '配对入口地址(手机需能访问)'),
1578
+ React.createElement('input', {
1579
+ id: 'mgw-pair-address',
1580
+ style: styles.input,
1581
+ value: appUrl,
1582
+ onChange: (event) => {
1583
+ const value = event.target.value
1584
+ if (appRoute === 'tailscale') { manualAppUrlRef.current = true; setAppUrl(value); return }
1585
+ if (appRoute !== 'custom') { chooseAppRoute('custom'); setAppUrl(value); return }
1586
+ setAppUrl(value)
1587
+ },
1588
+ placeholder: appRoute === 'tailscale'
1589
+ ? '100.x.x.x 或 ws://100.x.x.x:3081/ws/mobile(IPv6 用 [fd7a:…])'
1590
+ : 'ws://192.168.1.10:3081/ws/mobile 或 wss://gateway.example.com/ws/mobile',
1591
+ spellCheck: false,
1592
+ }),
1593
+ appRoute === 'tailscale' && appUrl.trim() && !isTailscaleInput(appUrl)
1594
+ ? React.createElement('div', { style: { ...styles.error, margin: '-4px 0 8px' } }, '这里要填 100.64.0.0/10(或 fd7a:115c:a1e0::/48)的 Tailscale 私有地址。')
1595
+ : null,
1596
+ // Tailscale 手动地址指引:检测到本机地址时提示可直接使用。
1597
+ appRoute === 'tailscale'
1598
+ ? React.createElement('div', { style: { ...styles.muted, margin: '-4px 0 10px', fontWeight: 500 } }, (() => {
1599
+ const detected = Array.isArray(status?.tailscale?.urls) ? status.tailscale.urls : []
1600
+ return detected.length
1601
+ ? `已检测到本机 Tailscale 地址:${detected.join('、')}(可直接生成二维码)。手机需登录同一 tailnet。`
1602
+ : '未检测到本机 Tailscale 地址:请填写运行网关这台主机的 Tailscale IP(不是手机 IP),例如 100.x.x.x。手机与电脑需登录同一 tailnet。'
1603
+ })())
1604
+ : null,
1605
+ appRoute !== 'tailscale' && status && status.lan && status.lan.enabled
1606
+ ? React.createElement('div', { style: { ...styles.muted, margin: '-7px 0 10px', fontWeight: 500, color: status.lan.error ? colors.danger : status.lan.listening ? colors.success : 'var(--dsw-alias-link, #4176e6)' } },
1607
+ status.lan.error
1608
+ ? `局域网监听失败:${status.lan.error}`
1609
+ : status.lan.listening
1610
+ ? `局域网入口已开启${status.lan.urls && status.lan.urls.length ? `:${status.lan.urls.join('、')}` : `,端口 ${status.lan.port}`}`
1611
+ : '局域网入口启动中…')
1612
+ : null,
1613
+ appRoute === 'cloudflare' && !cloudflareReady
1614
+ ? React.createElement('div', { style: { ...styles.muted, margin: '-4px 0 10px', fontWeight: 500 } }, status?.cloudflare?.enabled
1615
+ ? 'Cloudflare 外网尚未就绪,请稍候或查看下方 Cloudflare 设置。'
1616
+ : '尚未开启 Cloudflare Tunnel,可在下方设置中一键开启。')
1617
+ : null,
1618
+ React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' } },
1619
+ React.createElement('button', {
1620
+ style: { ...styles.button, ...styles.primary, opacity: appPairingDisabled ? .65 : 1 },
1621
+ disabled: appPairingDisabled,
1622
+ onClick: () => pairFor('app'),
1623
+ }, busy ? '正在生成…' : !(status && status.gatewayEnabled) ? '请先开启移动网关'
1624
+ : appRoute === 'cloudflare' && !cloudflareReady
1625
+ ? status?.cloudflare?.enabled ? '等待 Cloudflare 外网就绪' : '先开启 Cloudflare Tunnel'
1626
+ : appRoute === 'tailscale' && !status?.lan?.listening ? '请先开启局域网入口'
1627
+ : appRoute === 'tailscale' && !isTailscaleInput(appUrl) ? '填写主机 Tailscale 地址'
1628
+ : appRoute === 'lan' && !lanPairingUrl(status) ? '当前不可用'
1629
+ : appRoute === 'custom' && !appUrl.trim() ? '等待连接地址' : '生成 App 二维码'),
1630
+ React.createElement('span', { style: styles.muted }, '二维码只发给 App;小程序请用下方模块。')))
1631
+ : React.createElement('p', { style: { ...styles.muted, margin: '8px 0 0' } }, '局域网直连 / Cloudflare 外网 / Tailscale 私有网络 / 公网或其他手动地址;与鲸尾公网互不影响。')),
1632
+ appLayerOpen && appRoute === 'cloudflare' && status?.cloudflare?.supported
1633
+ ? React.createElement('section', { className: 'mgw-cloudflare-block', style: { ...styles.card, background: colors.card, border: 0, borderRadius: 16, padding: 18, marginTop: 16 } },
1634
+ React.createElement('h3', { className: 'mgw-section-title' }, 'Cloudflare Tunnel · 外网接入'),
1635
+ React.createElement('p', { style: styles.muted }, status.platform === 'linux'
1636
+ ? 'Linux 服务器不自动下载:请先安装 cloudflared(Cloudflare 官方源 pkg.cloudflare.com 的 cloudflared 包),或将插件配置 cloudflaredPath 指向已有可执行文件。DSH App 和小程序均可使用已配置的公网入口,并且仍要求设备鉴权。'
1637
+ : '首次开启自动准备 Tunnel 组件。'),
1638
+ React.createElement('div', { className: 'mgw-setting-row' },
1639
+ React.createElement('span', { className: 'mgw-setting-label' }, '接入方式'),
1640
+ React.createElement(GatewaySelect, { style: styles.input, value: cloudflareMode, 'aria-label': 'Cloudflare 接入方式', onChange: (event) => {
1641
+ const mode = event.target.value
1642
+ setCloudflareMode(mode)
1643
+ if (status.cloudflare.enabled && mode !== status.cloudflare.mode &&
1644
+ (mode === 'quick' || (status.cloudflare.configured && cloudflareHost === status.cloudflare.hostname && !cloudflareToken))) {
1645
+ void configureCloudflare(true, mode)
1646
+ }
1647
+ }, disabled: cloudflareBusy },
1648
+ React.createElement('option', { value: 'quick' }, 'Quick Tunnel · 无需域名'),
1649
+ React.createElement('option', { value: 'named' }, '命名 Tunnel · 固定域名'))),
1650
+ cloudflareMode === 'quick'
1651
+ ? React.createElement('p', { style: styles.muted }, '临时地址可能变化,变化后需重新扫码。')
1652
+ : React.createElement(React.Fragment, null,
1653
+ React.createElement('p', { style: styles.muted }, '先在 Cloudflare 创建命名 Tunnel,把公开域名的 Service URL 设为 ', React.createElement('code', null, `http://127.0.0.1:${status.cloudflare.port}`), '。Tunnel Token 仅授权连接,不能自动创建公开主机名或 DNS;还需确认域名存在指向 Tunnel UUID.cfargotunnel.com 的已代理 CNAME 记录。'),
1654
+ React.createElement('div', { style: { display: 'flex', gap: 14, flexWrap: 'wrap', margin: '2px 0 4px' } },
1655
+ React.createElement('a', { href: 'https://dash.cloudflare.com/?to=/:account/tunnels', target: '_blank', rel: 'noreferrer', style: { color: 'var(--dsw-alias-link, #4176e6)', fontSize: 12, fontWeight: 500, textDecoration: 'none' } }, 'Cloudflare 控制台 → 隧道 ↗'),
1656
+ React.createElement('a', { href: 'https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/get-started/create-remote-tunnel/', target: '_blank', rel: 'noreferrer', style: { color: 'var(--dsw-alias-link, #4176e6)', fontSize: 12, fontWeight: 500, textDecoration: 'none' } }, '官方创建教程 ↗')),
1657
+ React.createElement('p', { style: styles.muted }, 'Token 在控制台建好 Tunnel 后选择操作系统给出的安装命令里,是 eyJ… 开头的一段(只用它,不需要在 NAS 上执行该命令)。'),
1658
+ React.createElement('label', { style: styles.label }, '公开域名'),
1659
+ React.createElement('input', { style: styles.input, value: cloudflareHost, onChange: (event) => setCloudflareHost(event.target.value.trim()), placeholder: 'gateway.example.com', spellCheck: false }),
1660
+ React.createElement('label', { style: styles.label }, 'Tunnel Token'),
1661
+ React.createElement('input', { style: styles.input, type: 'password', value: cloudflareToken, onChange: (event) => setCloudflareToken(event.target.value.trim()), placeholder: status.cloudflare.configured ? '已保存;留空则保持原 Token' : '粘贴 eyJ… Token', autoComplete: 'off', spellCheck: false })),
1662
+ (!status.cloudflare.enabled || (cloudflareMode === 'named' &&
1663
+ (status.cloudflare.mode !== 'named' || cloudflareHost !== status.cloudflare.hostname || !!cloudflareToken)))
1664
+ ? React.createElement('button', {
1665
+ style: { ...styles.button, ...styles.primary, opacity: cloudflareBusy || (cloudflareMode === 'named' && (!cloudflareHost || (!cloudflareToken && !status.cloudflare.configured))) ? .65 : 1 },
1666
+ disabled: cloudflareBusy || (cloudflareMode === 'named' && (!cloudflareHost || (!cloudflareToken && !status.cloudflare.configured))),
1667
+ onClick: () => configureCloudflare(true),
1668
+ }, cloudflareBusy ? '正在处理…' : status.cloudflare.enabled ? '保存并连接' : cloudflareMode === 'quick' ? '一键开启 Quick Tunnel' : '开启命名 Tunnel') : null,
1669
+ status.cloudflare.enabled
1670
+ ? React.createElement(React.Fragment, null,
1671
+ React.createElement('button', { style: { ...styles.button, width: '100%', marginTop: 8 }, disabled: cloudflareBusy || status.cloudflare.state !== 'online', onClick: checkCloudflare }, '检测公网 DNS / TLS / WebSocket'),
1672
+ React.createElement('button', { style: { ...styles.button, width: '100%', marginTop: 8 }, disabled: cloudflareBusy || !status.gatewayEnabled, onClick: restartCloudflare }, '重启 Tunnel'),
1673
+ React.createElement('button', { style: { ...styles.button, width: '100%', marginTop: 8 }, disabled: cloudflareBusy, onClick: () => configureCloudflare(false) }, '关闭 Cloudflare Tunnel'),
1674
+ React.createElement('p', { style: styles.muted }, '重启会短暂断开连接。'))
1675
+ : null,
1676
+ React.createElement('div', { style: { ...styles.muted, marginTop: 9, overflowWrap: 'anywhere', fontWeight: 500, color: status.cloudflare.error ? colors.danger : status.cloudflare.state === 'online' ? colors.success : ['starting', 'preparing', 'connecting'].includes(status.cloudflare.state) ? 'var(--dsw-alias-link, #4176e6)' : colors.muted } },
1677
+ status.cloudflare.error || ({ disabled: '未开启', starting: '正在启动本机入口…', preparing: '正在准备 cloudflared(首次需下载)…', connecting: '正在连接 Cloudflare…', online: '隧道传输已连接(不等于公网入口可达)', 'waiting-for-gateway': '等待移动网关开启' }[status.cloudflare.state] || status.cloudflare.state),
1678
+ status.cloudflare.publicUrl ? ` · ${status.cloudflare.publicUrl}` : ''),
1679
+ status.cloudflare.enabled && status.cloudflare.endpointHealth
1680
+ ? React.createElement('p', { style: { ...styles.muted, overflowWrap: 'anywhere', fontWeight: 500, color: status.cloudflare.endpointHealth.state === 'reachable' ? colors.success : status.cloudflare.endpointHealth.state === 'checking' ? 'var(--dsw-alias-link, #4176e6)' : status.cloudflare.endpointHealth.state === 'unchecked' ? colors.muted : colors.danger } },
1681
+ status.cloudflare.endpointHealth.message,
1682
+ status.cloudflare.endpointHealth.checkedAt ? `(检测时间:${status.cloudflare.endpointHealth.checkedAt})` : '')
1683
+ : null)
1684
+ : null,
1685
+ status && status.platform === 'linux' ? React.createElement('section', { style: styles.card },
1686
+ React.createElement('h3', { className: 'mgw-section-title' }, '公网接入'),
1687
+ publicSetup === null
1688
+ ? React.createElement('p', { style: styles.muted }, '正在检查系统组件…')
1689
+ : publicSetup.installed
1690
+ ? React.createElement(React.Fragment, null,
1691
+ React.createElement('div', { style: { ...styles.muted, margin: '5px 0 12px' } }, publicSetup.configured
1692
+ ? publicSetup.backendPort && status && status.webPort && publicSetup.backendPort !== status.webPort
1693
+ ? `端口需要更新:Nginx 当前为 ${publicSetup.backendPort},DSH 当前为 ${status.webPort}`
1694
+ : `已配置${publicSetup.backendPort ? `,Nginx 转发至 DSH 端口 ${publicSetup.backendPort}` : ''}`
1695
+ : `Helper 已就绪,将自动使用当前 DSH 端口${status && status.webPort ? ` ${status.webPort}` : ''}`),
1696
+ React.createElement('label', { style: styles.label }, '服务器公网 IPv4'),
1697
+ React.createElement('input', {
1698
+ style: styles.input,
1699
+ value: publicIp,
1700
+ onChange: (event) => setPublicIp(event.target.value.trim()),
1701
+ placeholder: '203.0.113.10',
1702
+ inputMode: 'decimal',
1703
+ spellCheck: false,
1704
+ }),
1705
+ React.createElement('button', {
1706
+ style: { ...styles.button, ...styles.primary, opacity: publicSetupBusy || !publicIp ? .65 : 1 },
1707
+ disabled: publicSetupBusy || !publicIp,
1708
+ onClick: configurePublicAccess,
1709
+ }, publicSetupBusy ? '正在配置 Nginx 与证书…' : publicSetup.configured ? '更新公网配置' : '配置公网接入'),
1710
+ publicSetup.publicUrl
1711
+ ? React.createElement('div', { style: { ...styles.muted, marginTop: 9, overflowWrap: 'anywhere' } }, publicSetup.publicUrl)
1712
+ : null)
1713
+ : React.createElement(React.Fragment, null,
1714
+ React.createElement('p', { style: { ...styles.muted, marginBottom: 8 } }, '尚未安装系统 Helper。请在服务器执行一次初始化:'),
1715
+ React.createElement('code', { style: { display: 'block', fontSize: 10, lineHeight: 1.5, overflowWrap: 'anywhere', userSelect: 'all' } }, 'npx --yes dsh-plugin-mobile-gateway@latest init'))) : null,
1716
+
1717
+ // ── 模块二:小程序连接(备用)────────────────────────────────────
1718
+ React.createElement('section', { style: styles.card },
1719
+ React.createElement('div', { style: { position: 'relative', display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }, onMouseLeave: () => setConnectionHelpOpen(false) },
1720
+ React.createElement('h3', { className: 'mgw-section-title', style: { marginBottom: 0 } }, '小程序连接(备用)'),
1721
+ React.createElement('button', {
1722
+ type: 'button',
1723
+ style: styles.helpButton,
1724
+ 'aria-label': '连接方式说明与场景建议',
1725
+ 'aria-expanded': connectionHelpOpen,
1726
+ 'aria-describedby': connectionHelpOpen ? 'mgw-route-help' : undefined,
1727
+ onMouseEnter: () => setConnectionHelpOpen(true),
1728
+ onFocus: () => setConnectionHelpOpen(true),
1729
+ onBlur: () => setConnectionHelpOpen(false),
1730
+ onClick: () => setConnectionHelpOpen(true),
1731
+ onKeyDown: (event) => { if (event.key === 'Escape') setConnectionHelpOpen(false) },
1732
+ }, '?'),
1733
+ connectionHelpOpen ? React.createElement('div', { id: 'mgw-route-help', role: 'tooltip', style: styles.helpBubble },
1734
+ React.createElement('strong', null, '怎么选连接方式'),
1735
+ helpLine('小程序连接(备用)', '鲸尾小程序在微信里通过鲸尾公网中继连接,不受 wss 域名限制;手机与网关在同一局域网时自动兜底直连。'),
1736
+ helpLine('鲸尾公网 · 小程序', '小程序专用二维码:中继优先、局域网兜底;无需公网域名。'),
1737
+ helpLine('DSH App(推荐)', 'DSH App 使用直连入口:自动选择、局域网直连、Cloudflare 外网、Tailscale 私有网络或公网/手动地址。'),
1738
+ helpLine('自动选择(App)', '优先已就绪的公网入口,同时保留局域网与 Tailscale 地址;没有公网入口时使用局域网。'),
1739
+ helpLine('局域网直连', '手机与 DSH 在同一个可互访的局域网,使用 ws:// 私有地址;离开该网络就无法直连。'),
1740
+ helpLine('Cloudflare 外网', 'PC 主动连接 Cloudflare,外网用固定域名的 wss://;需要 Cloudflare 账户和域名。'),
1741
+ helpLine('Tailscale 私有网络', '可检测本机地址,或填写主机的 100.x 私有地址;手机与电脑需登录同一 tailnet。'),
1742
+ helpLine('公网或其他手动地址', '已配置公网 WSS 反代或只想指定一个固定地址时使用;编辑下方地址即可。'),
1743
+ React.createElement('div', { style: { borderTop: `1px solid ${colors.border}`, marginTop: 10, paddingTop: 8 } },
1744
+ React.createElement('strong', null, '结合当前环境'),
1745
+ React.createElement('div', { style: { color: colors.muted, marginTop: 4 } }, advice.detected),
1746
+ React.createElement('div', { style: { marginTop: 6 } }, advice.local),
1747
+ React.createElement('div', { style: { marginTop: 6 } }, advice.remote),
1748
+ React.createElement('div', { style: { color: colors.muted, marginTop: 6 } }, '面板无法判断手机当前网络;请按手机所在位置选择,提示不会替你修改选择。')))
1749
+ : null),
1750
+ React.createElement('p', { style: styles.muted }, '小程序默认通过鲸尾公网中继连接,不需要公网域名;手机与网关在同一局域网时自动兜底直连。'),
1751
+
1752
+ // 中继信息块属于小程序模块(自动选择 / 鲸尾公网中继)。
1753
+ (relayInfo || relayConnector?.running || relayConnector?.delegatedTo || relayConnector?.lastError)
1754
+ ? (relayInfo
1755
+ ? React.createElement('div', { style: { ...styles.muted, margin: '2px 0 0', fontWeight: 500 } },
1756
+ '鲸尾公网服务 · 已注册', ' · ',
1757
+ React.createElement('span', { style: { opacity: .8 } }, `设备 ID ${relayInfo.nodeId.slice(0, 8)}… · ${relayInfo.gatewayName}`),
1758
+ React.createElement('div', { style: { marginTop: 4, color: relayConnector?.lastError ? colors.danger : relayConnector?.running || relayConnector?.delegatedTo ? colors.success : 'var(--dsw-alias-link, #4176e6)' } },
1759
+ relayConnector?.running || relayConnector?.delegatedTo
1760
+ ? '中继连接保持运行'
1761
+ : relayConnector?.lastError ? `中继连接器异常:${relayConnector.lastError}`
1762
+ : '中继连接器正在恢复…'))
1763
+ : relayConnector && relayConnector.running
1764
+ ? React.createElement('div', { style: { ...styles.muted, margin: '2px 0 0', fontWeight: 500,
1765
+ color: 'var(--dsw-alias-link, #4176e6)' } }, '内置连接器已自动启动,正在连接中继并上报身份…')
1766
+ : relayConnector && relayConnector.lastError
1767
+ ? React.createElement('div', { style: { ...styles.muted, margin: '2px 0 0', fontWeight: 500, color: colors.danger } },
1768
+ '公网连接器暂时不可用,请检查网络或重新开启公网连接。', ' ',
1769
+ React.createElement('span', { style: { opacity: .8 } }, '如已自行部署连接器,请执行 systemctl restart dsh-connector。'))
1770
+ : React.createElement('div', { style: { ...styles.muted, margin: '2px 0 0' } }, '正在启动内置连接器…(中继模式需要一个本地连接器把小程序流量桥接进来,插件会自动准备)'))
1771
+ : null,
1772
+ React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap', marginTop: 10 } },
1773
+ React.createElement('button', {
1774
+ style: { ...styles.button, ...styles.primary, opacity: busy || !(status && status.gatewayEnabled) || !status?.relay || !lanPairingUrl(status) ? .65 : 1 },
1775
+ disabled: busy || !(status && status.gatewayEnabled) || !status?.relay || !lanPairingUrl(status),
1776
+ onClick: () => pairFor('mini'),
1777
+ }, busy ? '正在生成…' : !(status && status.gatewayEnabled) ? '请先开启移动网关'
1778
+ : !status?.relay ? '请先注册鲸尾公网中继'
1779
+ : !lanPairingUrl(status) ? '请先开启局域网入口' : '生成小程序二维码'),
1780
+ React.createElement('span', { style: styles.muted }, '配对码仅可使用一次,5 分钟内有效。'))),
1781
+ ),
1782
+ React.createElement('div', { hidden: activeSection !== 'devices' },
1783
+ React.createElement('section', { style: styles.card },
1784
+ React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center' } },
1785
+ React.createElement('h3', { className: 'mgw-section-title', style: { marginBottom: 0 } }, '可信设备'),
1786
+ React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 10 } },
1787
+ deviceNotice || refreshNotice ? React.createElement('span', {
1788
+ style: { ...styles.muted, color: deviceNoticeError ? colors.danger : colors.success },
1789
+ }, deviceNotice || refreshNotice) : null,
1790
+ React.createElement('button', {
1791
+ style: { ...styles.button, opacity: offlineDevices.length === 0 ? .55 : 1, color: colors.danger },
1792
+ disabled: offlineDevices.length === 0 || offlineClearing,
1793
+ title: '吊销所有当前离线的已配对设备',
1794
+ onClick: clearOfflineDevices,
1795
+ }, offlineClearing ? '清除中…' : `一键清除离线设备(${offlineDevices.length})`),
1796
+ React.createElement('button', {
1797
+ style: { ...styles.button, opacity: refreshing ? .6 : 1 },
1798
+ disabled: refreshing,
1799
+ onClick: manualRefresh,
1800
+ }, refreshing ? '刷新中…' : '刷新'))),
1801
+ devices === null
1802
+ ? React.createElement('p', { style: styles.muted }, '加载中…')
1803
+ : devices.length === 0
1804
+ ? React.createElement('p', { style: styles.muted }, '暂无已配对设备。')
1805
+ : React.createElement(React.Fragment, null,
1806
+ visibleDevices.length === 0 ? React.createElement('p', { style: styles.muted }, '当前没有在线设备。') : null,
1807
+ visibleDevices.map((device) => React.createElement(DeviceRow, {
1808
+ key: device.id,
1809
+ device,
1810
+ onRevoke: revoke,
1811
+ revoking: revokingIds.has(device.id),
1812
+ })),
1813
+ offlineDevices.length > 0 ? React.createElement('button', {
1814
+ type: 'button',
1815
+ style: { ...styles.button, marginTop: 10, color: colors.muted },
1816
+ 'aria-expanded': showAllDevices,
1817
+ onClick: () => setShowAllDevices((value) => !value),
1818
+ }, showAllDevices ? '收起离线设备' : `展开其他已配对设备(${offlineDevices.length})`) : null)),
1819
+ )),
1820
+ ),
1821
+ status && status.version
1822
+ ? React.createElement('div', { style: styles.version, 'aria-label': `插件版本 ${status.version}` }, `v${status.version}`)
1823
+ : null))
1824
+ }
1825
+
1826
+ // Fork: the entry is a Settings section instead of a sidebar footer button.
1827
+ // Tapping the Settings nav item opens the management dialog directly — the
1828
+ // dialog itself is upstream's unchanged shell.
1829
+ function SettingsEntry() {
1830
+ const isOpen = React.useSyncExternalStore(subscribe, getOpen, () => false)
1831
+ React.useEffect(() => { setOpen(true) }, [])
1832
+ return isOpen ? React.createElement(DevicePanel) : null
1833
+ }
1834
+
1835
+ // 侧边栏入口:与上游一致,在 Harness WebUI 侧边栏底部放一个「鲸尾移动设备」
1836
+ // 按钮,点击打开同一个管理弹窗;设置页入口保留,两个入口共享同一 open 状态。
1837
+ function FooterButton(props) {
1838
+ const isOpen = React.useSyncExternalStore(subscribe, getOpen, () => false)
1839
+ const visible = React.useSyncExternalStore(subscribeSidebar, getSidebarEntry, () => true)
1840
+ if (!visible) return null
1841
+ const wide = !!props.wide
1842
+ const iconSize = wide ? 20 : 22
1843
+ const icon = React.createElement('svg', { width: iconSize, height: iconSize, viewBox: '0 0 24 24', fill: 'none',
1844
+ stroke: 'currentColor', strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true, style: { flexShrink: 0 } },
1845
+ React.createElement('rect', { x: 6, y: 2, width: 12, height: 20, rx: 2.5 }),
1846
+ React.createElement('path', { d: 'M10 18h4' }))
1847
+ return React.createElement('button', {
1848
+ type: 'button', title: '鲸尾移动设备', 'aria-label': '鲸尾移动设备', 'aria-pressed': isOpen,
1849
+ onClick: () => setOpen(!isOpen),
1850
+ style: { cursor: 'pointer', background: 'transparent', border: 'none', color: 'inherit', font: 'inherit',
1851
+ display: 'flex', alignItems: 'center', justifyContent: wide ? 'flex-start' : 'center', gap: wide ? 8 : 0,
1852
+ boxSizing: 'border-box', width: wide ? 'calc(100% + 4px)' : 36, height: wide ? 42 : 36,
1853
+ margin: wide ? '4px -2px' : '3px 0', padding: wide ? '0 10px 0 8px' : 0, lineHeight: wide ? '22px' : 'normal' },
1854
+ }, icon, wide ? React.createElement('span', null, '鲸尾移动设备') : null)
1855
+ }
1856
+
1857
+ function OverlayEntry() {
1858
+ const isOpen = React.useSyncExternalStore(subscribe, getOpen, () => false)
1859
+ return isOpen ? React.createElement(DevicePanel, null) : null
1860
+ }
1861
+ const inject = ['slots']
1862
+ function apply(ctx) {
1863
+ // Upstream 0.10.1: the panel stylesheet is injected once through an
1864
+ // effect instead of being re-rendered inside the component tree.
1865
+ ctx.effect(() => {
1866
+ const style = document.createElement('style')
1867
+ style.textContent = panelCss
1868
+ document.head.appendChild(style)
1869
+ return () => style.remove()
1870
+ }, 'mobile-gateway: panel styles')
1871
+ pinNavGlyph([NAV_LABEL], NAV_ICON_MARK, navGlyph)
1872
+ // Fork: the entry is a Settings section, not the upstream sidebar footer
1873
+ // button. The id deliberately stays 'mobile-gateway' (not the package
1874
+ // name): it is a slot key that pinned-section state and the settings
1875
+ // plugin-hub map against, so renaming it would drop existing pins.
1876
+ ctx.slots.inject('settings.section', () => ctx.slots.register(
1877
+ { name: 'settings.section', id: 'mobile-gateway', order: 35, label: () => NAV_LABEL },
1878
+ () => React.createElement(SettingsEntry, null),
1879
+ ))
1880
+ // 侧边栏入口的显示开关来自管理接口;读取失败时保持默认显示。
1881
+ void request('/mgw/ui').then((data) => setSidebarEntry(data.sidebarEntry !== false)).catch(() => {})
1882
+ // 与上游一致:侧边栏底部入口 + shell overlay,共享同一个 open 状态。
1883
+ ctx.slots.inject('sidebar.footer.action', () => ctx.slots.register(
1884
+ { name: 'sidebar.footer.action', id: 'mobile-gateway-devices', order: 80, label: '鲸尾移动设备' },
1885
+ (props) => React.createElement(FooterButton, props),
1886
+ ))
1887
+ ctx.slots.inject('shell.overlay', () => ctx.slots.register(
1888
+ { name: 'shell.overlay', id: 'mobile-gateway-devices-panel', order: 100, label: '移动设备' },
1889
+ () => React.createElement(OverlayEntry, null),
1890
+ ))
1891
+ }
1892
+
1893
+ exports.apply = apply
1894
+ exports.inject = inject
1895
+ exports.pinNavGlyph = pinNavGlyph
1896
+ // Exposed for tests: the Settings entry and the dialog body render separately.
1897
+ exports.SettingsEntry = SettingsEntry
1898
+ exports.DevicePanel = DevicePanel
1899
+ return module.exports
1900
+ },
1901
+ })