dsh-plugin-weapp-gateway 0.8.23 → 0.8.34

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.
Files changed (71) hide show
  1. package/LICENSE +21 -21
  2. package/PROTOCOL.md +1545 -1486
  3. package/README.md +503 -464
  4. package/THIRD-PARTY-NOTICES/dsh-cost-meter.txt +31 -31
  5. package/bin/setup-ip.mjs +474 -474
  6. package/cordis.patch.yml +50 -50
  7. package/docs/agent-team-app-integration.md +945 -0
  8. package/docs/blog-mobile-gateway.md +542 -542
  9. package/docs/dsh-0.1.5-rc.2-compatibility-audit.md +255 -255
  10. package/docs/dsh-0.1.6-alpha.1-compatibility-audit.md +122 -122
  11. package/docs/dsh-0.1.7-rc.1-compatibility-audit.md +52 -52
  12. package/docs/dsh-0.2.0-rc.2-plugin-management-mobile-integration.md +109 -109
  13. package/docs/dsh-rc2-mobile-integration.md +155 -155
  14. package/docs/file-upload-app-integration.md +250 -0
  15. package/docs/multi-gateway-app-integration.md +141 -125
  16. package/docs/multi-gateway-phase1-acceptance.md +179 -179
  17. package/docs/multi-gateway-todo.md +137 -137
  18. package/docs/remote-gateway-refactor-plan.md +52 -52
  19. package/docs/runtime-architecture.architecture.json +264 -264
  20. package/docs/runtime-architecture.html +15001 -15001
  21. package/docs/runtime-architecture.visual-check.html +32 -32
  22. package/docs/runtime-architecture.visual-check.json +548 -548
  23. package/docs/session-agent-preset-app-integration.md +93 -93
  24. package/docs/turn-outline-app-integration.md +196 -0
  25. package/docs/typert-remote-gateway-feature-checklist.md +294 -294
  26. package/docs/voice-input-implementation.md +219 -219
  27. package/docs/workspace-changes-mobile-integration.md +32 -32
  28. package/helper/dsh_mobile_gateway_helper.py +227 -227
  29. package/lib/account-bridge.mjs +57 -57
  30. package/lib/client.js +1409 -1361
  31. package/lib/cloudflare-tunnel.mjs +314 -314
  32. package/lib/cloudflared-binary.mjs +135 -135
  33. package/lib/context-bridge.mjs +3338 -1715
  34. package/lib/cost-meter-bridge.mjs +794 -794
  35. package/lib/cost-meter-dashboard-bridge.mjs +1655 -1449
  36. package/lib/devices.js +273 -245
  37. package/lib/dsh-host-adapter.mjs +508 -426
  38. package/lib/file-upload.mjs +205 -0
  39. package/lib/gateway-probe.mjs +6 -6
  40. package/lib/gateway-state.mjs +57 -57
  41. package/lib/gateway-tools.mjs +36 -36
  42. package/lib/history-cache.mjs +66 -0
  43. package/lib/index.mjs +4390 -3803
  44. package/lib/plugin-management.mjs +251 -233
  45. package/lib/public-endpoint-check.mjs +61 -61
  46. package/lib/relay-connector.mjs +213 -181
  47. package/lib/relay-state.mjs +83 -76
  48. package/lib/session-follower.mjs +140 -136
  49. package/lib/session-resume-bridge.mjs +86 -0
  50. package/lib/session-target.mjs +29 -0
  51. package/lib/speech-input.mjs +192 -192
  52. package/lib/vendor/cost-meter/aliyun-balance.mjs +123 -123
  53. package/lib/vendor/cost-meter/coding-plans.mjs +1668 -1668
  54. package/lib/vendor/cost-meter/credentials-shim.mjs +8 -8
  55. package/lib/vendor/cost-meter/custom-balance.mjs +281 -281
  56. package/lib/vendor/cost-meter/factory-quota.mjs +69 -69
  57. package/lib/vendor/cost-meter/gateway-quota-adapters.mjs +1006 -1006
  58. package/lib/vendor/cost-meter/gateway-quotas.mjs +664 -664
  59. package/lib/vendor/cost-meter/home-paths-shim.mjs +13 -13
  60. package/lib/vendor/cost-meter/net.mjs +183 -183
  61. package/lib/vendor/cost-meter/opendesign.mjs +204 -204
  62. package/lib/vendor/cost-meter/tokenrhythm-balance.mjs +95 -95
  63. package/lib/vendor/cost-meter/workbuddy-accounts.mjs +44 -44
  64. package/lib/vendor/cost-meter/workbuddy-transport.mjs +38 -38
  65. package/lib/vendor/cost-meter/workbuddy.mjs +356 -356
  66. package/lib/web-restart.mjs +47 -47
  67. package/lib/wire-json.mjs +7 -7
  68. package/lib/workspace-changes-bridge.mjs +32 -32
  69. package/package.json +54 -54
  70. package/relay/agent-connector.js +588 -569
  71. package/relay/vendor/tweetnacl.js +2391 -2391
package/lib/client.js CHANGED
@@ -1,1361 +1,1409 @@
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
- // Shared Web UI / Desktop semantic tokens update with the host theme.
24
- const restartNoticeStorageKey = 'mobile-gateway-dismissed-restart-notice'
25
- let dismissedRestartInstance = null
26
- try { dismissedRestartInstance = window.localStorage.getItem(restartNoticeStorageKey) } catch { /* storage unavailable */ }
27
-
28
- const colors = {
29
- panel: 'var(--dsw-alias-bg-layer-2, var(--color-bg, Canvas))',
30
- card: 'var(--dsw-alias-bg-module-platform, var(--color-bg-elevated, Canvas))',
31
- text: 'var(--dsw-alias-label-primary, var(--color-text, CanvasText))',
32
- muted: 'var(--dsw-alias-label-secondary, var(--color-text-muted, GrayText))',
33
- border: 'var(--dsw-alias-border-l3, var(--color-border, rgba(127,127,127,.24)))',
34
- accent: 'var(--dsw-alias-button-primary-fill, var(--color-primary, #4f7cff))',
35
- accentText: 'var(--dsw-alias-label-primary-foreground, #fff)',
36
- danger: 'var(--dsw-alias-state-error-primary, #dc4c64)',
37
- success: 'var(--dsw-alias-state-success-primary, #2fb171)',
38
- }
39
- const styles = {
40
- backdrop: {
41
- position: 'fixed', inset: 0, zIndex: 1200, pointerEvents: 'auto',
42
- background: 'var(--dsw-alias-bg-mask-1, rgba(0,0,0,.32))', display: 'flex',
43
- justifyContent: 'center', alignItems: 'center',
44
- padding: 'max(16px, var(--dsh-frame-overlay-top, 16px)) 16px', boxSizing: 'border-box',
45
- },
46
- panel: {
47
- width: 'clamp(640px, 84vw, 1120px)', maxWidth: '100%', maxHeight: '100%', minHeight: 0, height: 'min(780px, calc(100dvh - 48px))', overflow: 'hidden',
48
- scrollbarWidth: 'none', msOverflowStyle: 'none',
49
- display: 'flex', flexDirection: 'column',
50
- background: colors.panel, color: colors.text, border: `1px solid ${colors.border}`, borderRadius: 'var(--dsw-radius-panel, 16px)',
51
- boxShadow: 'var(--dsw-elevation-prominent, 0 20px 60px rgba(0,0,0,.22))', padding: 24,
52
- fontFamily: 'var(--dsw-font-family, system-ui, sans-serif)', fontSize: 13, boxSizing: 'border-box',
53
- },
54
- header: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18, flexShrink: 0 },
55
- title: { margin: 0, fontSize: 22, fontWeight: 650 },
56
- card: { background: 'transparent', border: 0, borderBottom: `1px solid ${colors.border}`, borderRadius: 0, padding: '16px 0', marginBottom: 0, flexShrink: 0 },
57
- label: { display: 'block', color: colors.muted, fontSize: 12, marginBottom: 6 },
58
- 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' },
59
- 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' },
60
- button: { cursor: 'pointer', border: `1px solid ${colors.border}`, background: 'transparent', borderRadius: 8, padding: '7px 11px', color: 'inherit', font: 'inherit' },
61
- headerButton: { width: 34, height: 34, boxSizing: 'border-box', border: 0, padding: 0, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 },
62
- primary: { background: colors.accent, color: colors.accentText, borderColor: colors.accent, width: '100%' },
63
- muted: { color: colors.muted, fontSize: 12, lineHeight: 1.45 },
64
- row: { display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) auto', columnGap: 12, alignItems: 'center', padding: '12px 0', borderBottom: `1px solid ${colors.border}` },
65
- badge: { display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11, marginLeft: 8, color: colors.muted },
66
- dot: { width: 7, height: 7, borderRadius: 99, display: 'inline-block' },
67
- error: { color: colors.danger, background: 'rgba(220,76,100,.12)', borderRadius: 8, padding: 10, marginBottom: 12 },
68
- qr: { display: 'block', width: 220, height: 220, margin: '12px auto', background: '#fff', borderRadius: 10, padding: 8 },
69
- 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 },
70
- 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 },
71
- 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)' },
72
- toolsItem: { display: 'block', width: '100%', padding: '9px 10px', textAlign: 'left', border: 0, borderRadius: 7, background: 'transparent', color: colors.text, font: 'inherit', cursor: 'pointer' },
73
- switch: { position: 'relative', display: 'inline-flex', width: 42, height: 24, flexShrink: 0 },
74
- switchInput: { position: 'absolute', opacity: 0, width: 1, height: 1 },
75
- switchTrack: { position: 'absolute', inset: 0, borderRadius: 99, transition: 'background .18s ease', cursor: 'pointer' },
76
- 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' },
77
- version: { flexShrink: 0, marginTop: 'auto', padding: '18px 2px 0', color: colors.muted, fontSize: 11, lineHeight: 1.4, textAlign: 'right', letterSpacing: '.02em' },
78
- }
79
-
80
- const panelCss = `
81
- @keyframes mgw-pairing-enter {
82
- from { opacity: 0; transform: scale(.82); }
83
- to { opacity: 1; transform: scale(1); }
84
- }
85
- .mgw-pairing-dialog {
86
- transform-origin: center;
87
- animation: mgw-pairing-enter 240ms cubic-bezier(.2, .8, .2, 1);
88
- }
89
- @keyframes mgw-pairing-exit {
90
- from { opacity: 1; transform: scale(1); }
91
- to { opacity: 0; transform: scale(.82); }
92
- }
93
- .mgw-pairing-dialog[data-closing="true"] {
94
- animation: mgw-pairing-exit 180ms ease-in forwards;
95
- pointer-events: none;
96
- }
97
- @media (prefers-reduced-motion: reduce) {
98
- .mgw-pairing-dialog { animation: none; }
99
- }
100
- .mobile-gateway-panel, .mobile-gateway-panel *, .mgw-pairing-dialog, .mgw-pairing-dialog *, .mgw-select-menu {
101
- scrollbar-width: none !important;
102
- -ms-overflow-style: none;
103
- }
104
- .mobile-gateway-panel::-webkit-scrollbar, .mobile-gateway-panel *::-webkit-scrollbar,
105
- .mgw-pairing-dialog::-webkit-scrollbar, .mgw-pairing-dialog *::-webkit-scrollbar, .mgw-select-menu::-webkit-scrollbar {
106
- display: none !important;
107
- width: 0;
108
- height: 0;
109
- }
110
- .mobile-gateway-panel .mgw-body { display: grid; grid-template-columns: 180px minmax(0, 1fr); gap: 28px; flex: 1; min-height: 0; }
111
- .mobile-gateway-panel .mgw-nav { display: flex; flex-direction: column; gap: 4px; }
112
- .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; }
113
- .mobile-gateway-panel .mgw-nav button[aria-current="page"] { background: var(--dsw-alias-bg-overlay, rgba(127,127,127,.12)); font-weight: 500; }
114
- .mobile-gateway-panel .mgw-nav button:hover { background: var(--dsw-alias-interactive-bg-hover, rgba(127,127,127,.08)); }
115
- .mobile-gateway-panel .mgw-content { min-width: 0; overflow-y: auto; scrollbar-width: none; padding-right: 4px; }
116
- .mobile-gateway-panel .mgw-content::-webkit-scrollbar { display: none; }
117
- .mobile-gateway-panel .mgw-content p { margin: 6px 0 10px; }
118
- .mobile-gateway-panel strong { font-weight: 550; }
119
- .mobile-gateway-panel .mgw-section-title { margin: 0 0 10px; font-size: 17px; line-height: 1.4; font-weight: 650; color: inherit; }
120
- .mobile-gateway-panel .mgw-setting-row { display: flex; flex-direction: column; align-items: flex-start; gap: 8px; margin-bottom: 12px; }
121
- .mobile-gateway-panel .mgw-setting-row select { width: auto !important; max-width: 100%; min-width: 150px; margin-bottom: 0 !important; flex-shrink: 1; }
122
- .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; }
123
- .mobile-gateway-panel .mgw-setting-label { font-size: 14px; font-weight: 550; color: inherit; }
124
-
125
- .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; }
126
- @media (max-width: 640px) {
127
- .mobile-gateway-panel .mgw-body { grid-template-columns: minmax(0, 1fr); gap: 8px; }
128
- /* Fork: the dialog nav is not the settings rail — keep it a tab strip.
129
- dsh-settings-mobile-nav collapses the first <nav> of any settings
130
- dialog, which used to swallow ours and leave a lone expand button.
131
- A stable height plus the marker below opts out. */
132
- .mobile-gateway-panel .mgw-nav { flex-direction: row; flex-wrap: nowrap; }
133
- .mobile-gateway-panel .mgw-nav button {
134
- flex: 1 1 0; min-width: 0; min-height: 40px; height: 40px;
135
- padding: 8px 6px; text-align: center; white-space: nowrap;
136
- overflow: hidden; text-overflow: ellipsis;
137
- }
138
- }
139
- `
140
-
141
- function GatewaySelect({ style, children, value, onChange, disabled, ...props }) {
142
- const options = React.Children.toArray(children).filter((child) => React.isValidElement(child))
143
- const [menu, setMenu] = React.useState(null)
144
- const [active, setActive] = React.useState(0)
145
- const buttonRef = React.useRef(null)
146
- const menuRef = React.useRef(null)
147
- const menuId = React.useId()
148
- const selected = options.find((option) => option.props.value === value)
149
- const enabled = options.map((option, index) => option.props.disabled ? -1 : index).filter((index) => index >= 0)
150
- const close = (restoreFocus = false) => {
151
- setMenu(null)
152
- if (restoreFocus) buttonRef.current?.focus()
153
- }
154
- const openMenu = () => {
155
- if (disabled) return
156
- const rect = buttonRef.current.getBoundingClientRect()
157
- const computed = window.getComputedStyle(buttonRef.current)
158
- const fontSize = parseFloat(computed.fontSize) || 14
159
- const lineHeight = parseFloat(computed.lineHeight) || fontSize * 1.5
160
- const measure = document.createElement('canvas').getContext('2d')
161
- if (measure) measure.font = computed.font || `${fontSize}px sans-serif`
162
- const longest = Math.max(...options.map((option) => measure
163
- ? measure.measureText(String(option.props.children)).width : String(option.props.children).length * fontSize))
164
- const height = Math.min(options.length * Math.max(40, lineHeight + 16) + 14, window.innerHeight - 24)
165
- const width = Math.min(Math.max(rect.width, longest + 72, 200), window.innerWidth - 24)
166
- setActive(Math.max(0, options.findIndex((option) => option.props.value === value && !option.props.disabled)))
167
- setMenu({ left: Math.max(12, Math.min(rect.left, window.innerWidth - width - 12)),
168
- top: Math.max(12, rect.bottom + height + 6 <= window.innerHeight - 12 ? rect.bottom + 6 : rect.top - height - 6), width, maxHeight: window.innerHeight - 24 })
169
- }
170
- const choose = (index) => {
171
- const option = options[index]
172
- if (!option || option.props.disabled) return
173
- onChange?.({ target: { value: option.props.value } })
174
- close(true)
175
- }
176
- React.useEffect(() => {
177
- if (!menu) return
178
- menuRef.current?.focus()
179
- const outside = (event) => {
180
- if (!buttonRef.current?.contains(event.target) && !menuRef.current?.contains(event.target)) close()
181
- }
182
- const scrolled = (event) => { if (!menuRef.current?.contains(event.target)) close() }
183
- const resized = () => close()
184
- document.addEventListener('pointerdown', outside)
185
- document.addEventListener('scroll', scrolled, true)
186
- window.addEventListener('resize', resized)
187
- return () => {
188
- document.removeEventListener('pointerdown', outside)
189
- document.removeEventListener('scroll', scrolled, true)
190
- window.removeEventListener('resize', resized)
191
- }
192
- }, [menu])
193
- React.useEffect(() => {
194
- if (menu) document.getElementById(`${menuId}-${active}`)?.scrollIntoView({ block: 'nearest' })
195
- }, [active, menu])
196
- return React.createElement('span', { style: { display: 'inline-flex', maxWidth: '100%', minWidth: 0 } },
197
- React.createElement('button', { ...props, className: 'mgw-select-trigger', ref: buttonRef, type: 'button', disabled,
198
- 'aria-haspopup': 'listbox', 'aria-expanded': !!menu, 'aria-controls': menu ? menuId : undefined,
199
- onClick: () => menu ? close() : openMenu(),
200
- onKeyDown: (event) => {
201
- if (['ArrowDown', 'ArrowUp'].includes(event.key)) { event.preventDefault(); openMenu() }
202
- },
203
- style: { ...style, width: 'auto', maxWidth: '100%', marginBottom: 0, border: 0, borderRadius: 12,
204
- padding: '10px 16px', background: colors.card, color: colors.text, font: 'inherit', cursor: disabled ? 'default' : 'pointer',
205
- display: 'inline-flex', alignItems: 'center', gap: 18, opacity: disabled ? .5 : 1 } },
206
- React.createElement('span', { style: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, selected?.props.children || value),
207
- React.createElement('svg', { width: 14, height: 14, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor',
208
- strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true, style: { flexShrink: 0 } },
209
- React.createElement('path', { d: 'M6 9l6 6 6-6' }))),
210
- menu ? React.createElement('div', { className: 'mgw-select-menu', ref: menuRef, id: menuId, role: 'listbox', tabIndex: -1,
211
- 'aria-label': props['aria-label'], 'aria-activedescendant': `${menuId}-${active}`,
212
- style: { ...menu, position: 'fixed', zIndex: 1250, boxSizing: 'border-box', overflowY: 'auto', padding: 6,
213
- background: colors.panel, color: colors.text, border: `1px solid ${colors.border}`, borderRadius: 14,
214
- boxShadow: 'var(--dsw-elevation-prominent, 0 8px 28px rgba(0,0,0,.12))', outline: 'none' },
215
- onKeyDown: (event) => {
216
- if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); close(true) }
217
- else if (event.key === 'Tab') close()
218
- else if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); choose(active) }
219
- else if (['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) {
220
- event.preventDefault()
221
- const index = enabled.indexOf(active)
222
- setActive(event.key === 'Home' ? enabled[0] : event.key === 'End' ? enabled[enabled.length - 1]
223
- : enabled[(index + (event.key === 'ArrowDown' ? 1 : -1) + enabled.length) % enabled.length])
224
- }
225
- } }, options.map((option, index) => React.createElement('div', { key: option.props.value,
226
- id: `${menuId}-${index}`, role: 'option', 'aria-selected': option.props.value === value, 'aria-disabled': !!option.props.disabled,
227
- onPointerMove: () => { if (!option.props.disabled) setActive(index) }, onClick: () => choose(index),
228
- style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, minHeight: 40, whiteSpace: 'nowrap',
229
- boxSizing: 'border-box', padding: '8px 12px', borderRadius: 8, cursor: option.props.disabled ? 'default' : 'pointer',
230
- opacity: option.props.disabled ? .4 : 1, background: active === index ? 'var(--dsw-alias-interactive-bg-hover, rgba(127,127,127,.08))' : 'transparent' } },
231
- 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',
232
- fill: 'none', stroke: 'currentColor', strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true, style: { flexShrink: 0 } },
233
- React.createElement('path', { d: 'M5 12l4 4L19 6' })) : null))) : null)
234
- }
235
-
236
- // --------------------------------------------------------------------------
237
- // Settings-nav glyph, pinned by the plugin itself.
238
- //
239
- // The `settings.section` contract carries no icon field — the core reads
240
- // only id/label/order and `navIcon(id)` falls back to the gear for every
241
- // unknown id. Patching that core bundle is not durable: a DSH runtime
242
- // re-extract, or any other plugin installing/removing its own patch, wipes
243
- // it. So this plugin pins its own glyph at runtime instead.
244
- //
245
- // It finds its nav cell by label text and rewrites the existing <svg> in
246
- // place, keeping the shell's element, class and box — nothing here depends
247
- // on the shell's hashed class names, so a DSH upgrade cannot break it. A
248
- // MutationObserver re-applies the glyph whenever the shell re-renders the
249
- // nav and restores the gear.
250
- //
251
- // `glyph()` is pure and returns the markup: it runs BEFORE any DOM mutation,
252
- // so a throwing glyph leaves the shell's own icon in place rather than
253
- // blanking the cell.
254
- // --------------------------------------------------------------------------
255
- const NAV_LABEL = '鲸尾移动网关'
256
- const NAV_ICON_MARK = 'data-mgw-nav-icon'
257
-
258
- function navGlyph() {
259
- return {
260
- viewBox: '0 0 24 24',
261
- stroke: 'currentColor',
262
- markup: '<rect x="6" y="2" width="12" height="20" rx="2.5"></rect><path d="M10 18h4"></path>',
263
- }
264
- }
265
-
266
- function pinNavGlyph(labels, mark, glyph) {
267
- if (typeof document === 'undefined' || typeof MutationObserver === 'undefined') return
268
- const apply = () => {
269
- // Cheap guard: the nav only exists while the settings panel is open.
270
- if (document.querySelector('[role="dialog"]') === null) return
271
- const cells = document.querySelectorAll('[role="dialog"] nav button')
272
- for (const cell of cells) {
273
- // An <svg> contributes no text, so this is exactly the nav label.
274
- if (labels.indexOf(cell.textContent.trim()) < 0) continue
275
- const svg = cell.querySelector('svg')
276
- if (svg === null || svg.getAttribute(mark) === '1') continue
277
- let spec
278
- try {
279
- spec = glyph()
280
- } catch (error) {
281
- console.warn('[dsh-plugin-weapp-gateway] nav glyph failed; keeping the shell icon', error)
282
- continue
283
- }
284
- svg.setAttribute('viewBox', spec.viewBox)
285
- svg.setAttribute('fill', 'none')
286
- if (spec.stroke) {
287
- svg.setAttribute('stroke', spec.stroke)
288
- svg.setAttribute('stroke-width', spec.strokeWidth || '1.8')
289
- svg.setAttribute('stroke-linecap', 'round')
290
- svg.setAttribute('stroke-linejoin', 'round')
291
- }
292
- svg.innerHTML = spec.markup
293
- svg.setAttribute('aria-hidden', 'true')
294
- svg.setAttribute(mark, '1')
295
- }
296
- }
297
- apply()
298
- // The shell re-renders the nav on ledger/locale changes; without this the
299
- // gear would come back on the next re-render.
300
- new MutationObserver(apply).observe(document.body, { childList: true, subtree: true })
301
- }
302
-
303
- // Fork: management RPC must resolve against the document base, not the
304
- // origin root. Behind the fnOS gateway the whole WebUI is served under
305
- // /app/deepseek-harness/fngateway/, where an absolute /mgw/... request
306
- // hits the gateway's own router and 404s. DSH serves its own assets
307
- // document-relative for exactly this reason.
308
- function apiPath(path) {
309
- let base = '/'
310
- try { base = new URL('.', document.baseURI).pathname } catch { base = '/' }
311
- if (!base.endsWith('/')) base += '/'
312
- return base + String(path).replace(/^\/+/, '')
313
- }
314
-
315
- async function request(path, options) {
316
- const response = await fetch(apiPath(path), { credentials: 'same-origin', ...options })
317
- const body = await response.json().catch(() => ({}))
318
- if (!response.ok) throw new Error(body.message || body.error || `HTTP ${response.status}`)
319
- return body
320
- }
321
-
322
- function inferredUrl(wsPath) {
323
- const scheme = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
324
- return `${scheme}//${window.location.host}${wsPath || '/ws/mobile'}`
325
- }
326
-
327
- function lanPairingUrl(status) {
328
- const urls = status?.lan?.listening && Array.isArray(status.lan.urls) ? status.lan.urls : []
329
- return urls.find((url) => !/^ws:\/\/169\.254\./.test(url)) || urls[0] || ''
330
- }
331
-
332
- function pairingUrlFor(route, status) {
333
- const lanUrl = lanPairingUrl(status)
334
- const tunnelUrl = status.cloudflare?.enabled ? status.cloudflare.publicUrl || '' : ''
335
- const relayUrl = status.relay?.relay || ''
336
- if (route === 'lan') return lanUrl
337
- if (route === 'relay') return relayUrl
338
- if (route === 'cloudflare') return tunnelUrl
339
- if (status.cloudflare?.enabled && status.cloudflare.mode === 'quick') return tunnelUrl
340
- return tunnelUrl || status.publicUrl || lanUrl || inferredUrl(status.wsPath)
341
- }
342
-
343
- function connectionAdvice(status, publicSetup) {
344
- if (!status) return { detected: '正在读取网关环境…', local: '', remote: '' }
345
- const system = status.platform === 'darwin' ? 'macOS 电脑' : status.platform === 'win32' ? 'Windows 电脑' : status.platform === 'linux' ? 'Linux 服务器' : '当前设备'
346
- const lanReady = !!lanPairingUrl(status)
347
- const tunnel = status.cloudflare
348
- const tunnelReady = !!(tunnel?.enabled && tunnel.publicReady === true && tunnel.publicUrl)
349
- const serverReady = status.platform === 'linux' && !!(
350
- (publicSetup?.configured && publicSetup.publicUrl) || /^wss:\/\//.test(status.publicUrl || ''))
351
- const detected = `当前检测:${system};局域网入口${lanReady ? '已就绪' : '未就绪'};${serverReady ? '公网服务器入口已配置' : tunnelReady ? `${tunnel.mode === 'quick' ? 'Quick' : '命名'} Tunnel 已连接` : tunnel?.enabled ? (tunnel.state === 'online' ? '隧道已连接,公网入口未验证或检测失败' : 'Cloudflare Tunnel 连接中') : '外网入口未连接'}。`
352
- const local = lanReady
353
- ? '手机与 DSH 处于可互访的同一局域网时,建议选“局域网直连”。'
354
- : '如果手机和 DSH 在同一局域网,先确认局域网入口已开启并监听成功。'
355
- let remote
356
- if (serverReady) remote = '手机在外网时,建议使用已配置的公网服务器地址(“自动选择”)。'
357
- else if (tunnelReady && tunnel.mode === 'named') remote = '手机在外网时,建议选“Cloudflare 外网”;当前命名 Tunnel 有固定域名。'
358
- else if (tunnelReady) remote = '手机在外网临时使用时,建议选“Cloudflare 外网”;Quick 地址变化后需要重新确认。'
359
- else if (status.platform === 'darwin' || status.platform === 'win32') remote = '手机在外网时,无自有域名可开启 Quick Tunnel;有域名且需要固定地址可配置命名 Tunnel。'
360
- else if (status.platform === 'linux') remote = '手机在外网时,若使用受支持的 Ubuntu/Debian 服务器且有固定公网 IPv4,可先配置“公网接入”,再选“自动选择”。'
361
- else remote = '手机在外网时,需要一个可访问的 wss:// 地址;可在“手动输入地址”中填写。'
362
- return { detected, local, remote }
363
- }
364
-
365
- function DeviceRow({ device, onRevoke, revoking }) {
366
- const triggerRevoke = (event) => {
367
- event.preventDefault()
368
- event.stopPropagation()
369
- if (!revoking) onRevoke(device)
370
- }
371
- return React.createElement('div', { style: styles.row },
372
- React.createElement('div', { style: { minWidth: 0, overflow: 'hidden' } },
373
- React.createElement('div', { style: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } },
374
- device.displayName || device.name,
375
- React.createElement('span', { style: styles.badge },
376
- React.createElement('span', { style: { ...styles.dot, background: device.online ? colors.success : colors.muted } }),
377
- device.online ? '在线' : '离线')),
378
- React.createElement('div', { style: { ...styles.muted, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', marginTop: 3 } },
379
- device.lastSeenAt ? `最近连接:${new Date(device.lastSeenAt).toLocaleString()}` : '尚未连接')),
380
- React.createElement('button', {
381
- type: 'button',
382
- disabled: revoking,
383
- style: {
384
- ...styles.button,
385
- color: colors.danger,
386
- background: 'transparent',
387
- borderColor: 'rgba(220,76,100,.55)',
388
- flexShrink: 0,
389
- minWidth: 54,
390
- opacity: revoking ? .6 : 1,
391
- },
392
- title: `吊销 ${device.displayName || device.name}`,
393
- // Pointer-up is more reliable than click inside the management dialog on
394
- // touch devices. The click handler remains for keyboard activation.
395
- onPointerUp: triggerRevoke,
396
- onClick: (event) => {
397
- if (event.detail === 0) triggerRevoke(event)
398
- },
399
- }, revoking ? '吊销中…' : '吊销'))
400
- }
401
-
402
- function DevicePanel() {
403
- const [activeSection, setActiveSection] = React.useState('general')
404
- const [devices, setDevices] = React.useState(null)
405
- const [showAllDevices, setShowAllDevices] = React.useState(false)
406
- const [status, setStatus] = React.useState(null)
407
- const [dismissedNotice, setDismissedNotice] = React.useState(() => dismissedRestartInstance)
408
- const [publicUrl, setPublicUrl] = React.useState('')
409
- const [pairingRoute, setPairingRoute] = React.useState('auto')
410
- const [connectionHelpOpen, setConnectionHelpOpen] = React.useState(false)
411
- const [toolsOpen, setToolsOpen] = React.useState(false)
412
- const [toolBusy, setToolBusy] = React.useState(false)
413
- const [toolNotice, setToolNotice] = React.useState('')
414
- const stoppedRef = React.useRef(false)
415
- const [publicIp, setPublicIp] = React.useState('')
416
- const [publicSetup, setPublicSetup] = React.useState(null)
417
- const [publicSetupBusy, setPublicSetupBusy] = React.useState(false)
418
- const [cloudflareHost, setCloudflareHost] = React.useState('')
419
- const [cloudflareToken, setCloudflareToken] = React.useState('')
420
- const [cloudflareMode, setCloudflareMode] = React.useState('quick')
421
- const [cloudflareBusy, setCloudflareBusy] = React.useState(false)
422
- const [qr, setQr] = React.useState(null)
423
- const pairingDialogRef = React.useRef(null)
424
- const navRef = React.useRef(null)
425
- // Fork: id of the pairing code currently shown as a QR. The panel polls
426
- // the server's pending list and closes the dialog as soon as this id is
427
- // gone — a successful scan consumes the code immediately.
428
- const pairingIdRef = React.useRef(null)
429
- const [pairingClosing, setPairingClosing] = React.useState(false)
430
- const pairingCloseTimer = React.useRef(null)
431
- const closePairingDialog = () => {
432
- pairingIdRef.current = null
433
- setCopyNotice(null)
434
- if (pairingCloseTimer.current !== null) return
435
- if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
436
- setQr(null)
437
- return
438
- }
439
- setPairingClosing(true)
440
- pairingCloseTimer.current = window.setTimeout(() => {
441
- pairingCloseTimer.current = null
442
- setQr(null)
443
- setPairingClosing(false)
444
- }, 180)
445
- }
446
- React.useEffect(() => {
447
- setPairingClosing(false)
448
- return () => {
449
- if (pairingCloseTimer.current !== null) {
450
- window.clearTimeout(pairingCloseTimer.current)
451
- pairingCloseTimer.current = null
452
- }
453
- }
454
- }, [qr])
455
- const [error, setError] = React.useState(null)
456
- const [busy, setBusy] = React.useState(false)
457
- const [updateInfo, setUpdateInfo] = React.useState(null)
458
- const [updateChecking, setUpdateChecking] = React.useState(true)
459
- const [updateBusy, setUpdateBusy] = React.useState(false)
460
- const [updateNotice, setUpdateNotice] = React.useState('')
461
- const [updateError, setUpdateError] = React.useState('')
462
- const [refreshing, setRefreshing] = React.useState(false)
463
- const [refreshNotice, setRefreshNotice] = React.useState(null)
464
- const [pairingTokenCopied, setPairingTokenCopied] = React.useState(false)
465
- // Copy feedback that must live inside the QR dialog: the panel's error
466
- // banner is behind the modal, so a clipboard failure looked like "the
467
- // button does nothing".
468
- const [copyNotice, setCopyNotice] = React.useState(null)
469
- const [deviceNotice, setDeviceNotice] = React.useState(null)
470
- const [deviceNoticeError, setDeviceNoticeError] = React.useState(false)
471
- const [revokingIds, setRevokingIds] = React.useState(() => new Set())
472
- const revokingIdsRef = React.useRef(new Set())
473
- const automaticUrlRef = React.useRef('')
474
- const pairingRouteRef = React.useRef('auto')
475
- const cloudflareModeLoadedRef = React.useRef(false)
476
-
477
- const refresh = React.useCallback(async () => {
478
- try {
479
- const [deviceData, statusData] = await Promise.all([
480
- request('/mgw/devices'),
481
- request('/mgw/status'),
482
- ])
483
- const nextDevices = deviceData.devices || []
484
- // Keep existing DOM rows alive when polling returns identical data.
485
- // Replacing them every three seconds can swallow a pointer/click that
486
- // started on the old button and ended after React replaced the row.
487
- if (revokingIdsRef.current.size === 0) {
488
- setDevices((current) => JSON.stringify(current) === JSON.stringify(nextDevices) ? current : nextDevices)
489
- }
490
- setStatus((current) => JSON.stringify(current) === JSON.stringify(statusData) ? current : statusData)
491
- // Fork: the QR dialog closes itself once the code is consumed. The
492
- // server drops a redeemed code from its pending list, so the poll
493
- // sees our id disappear and dismisses the dialog (with animation).
494
- if (pairingIdRef.current !== null && Array.isArray(statusData.pendingPairings)
495
- && !statusData.pendingPairings.includes(pairingIdRef.current)) {
496
- pairingIdRef.current = null
497
- setQr(null)
498
- }
499
- if (statusData.cloudflare && statusData.cloudflare.hostname) {
500
- setCloudflareHost((current) => current || statusData.cloudflare.hostname)
501
- }
502
- if (statusData.cloudflare && !cloudflareModeLoadedRef.current) {
503
- cloudflareModeLoadedRef.current = true
504
- setCloudflareMode(statusData.cloudflare.mode || 'quick')
505
- }
506
- if (pairingRouteRef.current === 'cloudflare' && !statusData.cloudflare?.enabled) {
507
- pairingRouteRef.current = 'auto'
508
- setPairingRoute('auto')
509
- }
510
- // Fork: the server's pairing mode is the source of truth. On open the
511
- // local ref is still 'auto', so the address field would show the
512
- // Cloudflare URL until the operator re-picks the route. Adopt the
513
- // server mode first (without touching an explicit custom entry), then
514
- // derive the address from it.
515
- if (statusData.pairingMode === 'relay' && pairingRouteRef.current !== 'custom') {
516
- pairingRouteRef.current = 'relay'
517
- setPairingRoute('relay')
518
- } else if (statusData.pairingMode === 'direct' && pairingRouteRef.current === 'relay') {
519
- pairingRouteRef.current = 'auto'
520
- setPairingRoute('auto')
521
- }
522
- if (pairingRouteRef.current !== 'custom') {
523
- const preferredUrl = pairingUrlFor(pairingRouteRef.current, statusData)
524
- if (automaticUrlRef.current && preferredUrl !== automaticUrlRef.current) setQr(null)
525
- automaticUrlRef.current = preferredUrl
526
- setPublicUrl(preferredUrl)
527
- }
528
- return true
529
- } catch (cause) {
530
- setError(cause.message)
531
- return false
532
- }
533
- }, [])
534
-
535
- const manualRefresh = async () => {
536
- if (refreshing) return
537
- setRefreshing(true)
538
- setRefreshNotice(null)
539
- const succeeded = await refresh()
540
- setRefreshing(false)
541
- if (succeeded) {
542
- setError(null)
543
- setRefreshNotice(`已刷新 · ${new Date().toLocaleTimeString()}`)
544
- window.setTimeout(() => setRefreshNotice(null), 2200)
545
- }
546
- }
547
-
548
- const checkForPluginUpdate = async () => {
549
- setUpdateChecking(true)
550
- setUpdateError('')
551
- try {
552
- setUpdateInfo(await request('/mgw/update-check'))
553
- } catch (cause) {
554
- setUpdateError(cause.message)
555
- } finally {
556
- setUpdateChecking(false)
557
- }
558
- }
559
-
560
- const upgradePlugin = async () => {
561
- if (updateBusy || !updateInfo?.updateAvailable) return
562
- setUpdateBusy(true)
563
- setUpdateNotice('')
564
- setUpdateError('')
565
- try {
566
- const result = await request('/mgw/update', { method: 'POST' })
567
- if (result.reason === 'plugin-manager-unavailable') {
568
- setUpdateNotice(`当前 DSH 不支持面板内更新。请在 Terminal 执行:${result.command}`)
569
- } else if (result.reason === 'already-current') {
570
- setUpdateInfo(result)
571
- setUpdateNotice('插件已是最新版本。')
572
- } else if (result.installed) {
573
- const application = result.installation?.application
574
- const pendingBuilds = result.installation?.pendingBuilds
575
- if (Array.isArray(pendingBuilds) && pendingBuilds.length > 0) {
576
- setUpdateNotice(`更新等待构建脚本审核(${pendingBuilds.join('、')});未自动批准。请到 DSH 插件管理中审核。`)
577
- } else if (application === 'restart-required') {
578
- setUpdateInfo({ ...result, currentVersion: result.latestVersion, updateAvailable: false })
579
- setUpdateNotice(`已安装 v${result.latestVersion},需要重启 DSH 后生效。`)
580
- } else if (application === 'failed' || application === 'cancelled' || application === 'refused') {
581
- const installError = result.installation?.error
582
- const detail = result.installation?.errorMessage
583
- || (typeof installError === 'string' ? installError : '')
584
- || (typeof installError?.message === 'string' ? installError.message : '')
585
- || (typeof installError?.code === 'string' ? installError.code : '')
586
- || '请在 DSH 插件管理中查看安装详情。'
587
- setUpdateNotice(`安装未完成:${application}(${detail})`)
588
- } else {
589
- setUpdateInfo({ ...result, currentVersion: result.latestVersion, updateAvailable: false })
590
- setUpdateNotice(`已安装 v${result.latestVersion}。如界面尚未更新,请重启 DSH。`)
591
- }
592
- }
593
- } catch (cause) {
594
- setUpdateError(cause.message)
595
- } finally {
596
- setUpdateBusy(false)
597
- }
598
- }
599
-
600
- const runTool = async (tool) => {
601
- if (toolBusy) return
602
- setToolsOpen(false)
603
- setToolBusy(true)
604
- setToolNotice('')
605
- setError(null)
606
- try {
607
- const oldPid = status?.webPid
608
- await request(`/mgw/tools/${tool}`, { method: 'POST' })
609
- if (tool === 'stop-web') {
610
- stoppedRef.current = true
611
- setToolNotice('DSH Web 已收到停止指令。需要时可在 Terminal 运行 dsh web 重新启动。')
612
- return
613
- }
614
- if (tool === 'restart-web') {
615
- setToolNotice('正在重启 DSH Web,当前连接会短暂中断…')
616
- const deadline = Date.now() + 60_000
617
- while (Date.now() < deadline) {
618
- await new Promise((resolve) => window.setTimeout(resolve, 700))
619
- try {
620
- const next = await request('/mgw/status')
621
- if (next.webPid && next.webPid !== oldPid) {
622
- window.location.reload()
623
- return
624
- }
625
- } catch { /* old process is shutting down */ }
626
- }
627
- throw new Error('DSH Web 重启超时,请检查 /tmp/mobile-gateway.log')
628
- }
629
- } catch (cause) {
630
- setError(cause.message)
631
- setToolNotice('')
632
- } finally {
633
- setToolBusy(false)
634
- }
635
- }
636
-
637
- // Fork: dsh-settings-mobile-nav collapses the first <nav> of any settings
638
- // dialog on narrow viewports (it assumes the settings rail). Our dialog nav
639
- // is that first nav, so tapping a section used to hide the whole strip and
640
- // leave a lone ☰ button. Never intercept the click itself — React delegates
641
- // onClick at the document root, so stopPropagation in the capture phase
642
- // would kill our own handler. Instead, make the nav un-collapsible: a
643
- // MutationObserver reverts the display/aria-hidden edits (and drops the
644
- // stray expand button) the moment they land.
645
- React.useEffect(() => {
646
- const nav = navRef.current
647
- if (nav === null || typeof MutationObserver === 'undefined') return undefined
648
- const restore = () => {
649
- if (nav.style.display === 'none') nav.style.display = ''
650
- if (nav.getAttribute('aria-hidden') === 'true') nav.removeAttribute('aria-hidden')
651
- const stray = nav.closest('[role="dialog"]')?.querySelector('[data-dsh-settings-nav-expand]')
652
- if (stray !== null && stray !== undefined) stray.remove()
653
- }
654
- const observer = new MutationObserver(restore)
655
- observer.observe(nav, { attributes: true, attributeFilter: ['style', 'aria-hidden'] })
656
- const dialog = nav.closest('[role="dialog"]')
657
- if (dialog !== null) observer.observe(dialog, { childList: true })
658
- return () => observer.disconnect()
659
- }, [])
660
-
661
- React.useEffect(() => {
662
- let active = true
663
- refresh()
664
- request('/mgw/update-check').then((data) => {
665
- if (active) setUpdateInfo(data)
666
- }).catch((cause) => {
667
- if (active) setUpdateError(cause.message)
668
- }).finally(() => {
669
- if (active) setUpdateChecking(false)
670
- })
671
- request('/mgw/public-setup').then((data) => {
672
- if (!active) return
673
- setPublicSetup(data)
674
- if (data.publicUrl) {
675
- const match = /^wss:\/\/([^/]+)\/ws\/mobile$/.exec(data.publicUrl)
676
- if (match) setPublicIp(match[1])
677
- }
678
- }).catch((cause) => active && setPublicSetup({ installed: false, configured: false, error: cause.message }))
679
- const timer = window.setInterval(() => { if (!stoppedRef.current) refresh() }, 3000)
680
- return () => { active = false; window.clearInterval(timer) }
681
- }, [refresh])
682
-
683
- React.useEffect(() => {
684
- if (!qr) return
685
- const previousFocus = document.activeElement
686
- pairingDialogRef.current?.querySelector('button')?.focus()
687
- return () => previousFocus?.focus()
688
- }, [qr])
689
-
690
- // Fork: the route dropdown is the single place that picks the client.
691
- // 中继 · 小程序 switches the server-side pairing mode; every other route
692
- // is a direct-mode address choice.
693
- const changePairingMode = async (mode) => {
694
- setBusy(true)
695
- setError(null)
696
- try {
697
- const data = await request('/mgw/mode', {
698
- method: 'POST',
699
- headers: { 'Content-Type': 'application/json' },
700
- body: JSON.stringify({ mode }),
701
- })
702
- setStatus((current) => ({ ...(current || {}), pairingMode: data.pairingMode, relay: data.relay }))
703
- } catch (cause) {
704
- setError(cause.message)
705
- } finally {
706
- setBusy(false)
707
- }
708
- }
709
-
710
- const choosePairingRoute = (route) => {
711
- setQr(null)
712
- if (route === 'relay') {
713
- pairingRouteRef.current = 'relay'
714
- setPairingRoute('relay')
715
- if (pairingMode !== 'relay') void changePairingMode('relay')
716
- return
717
- }
718
- if (pairingMode === 'relay') void changePairingMode('direct')
719
- pairingRouteRef.current = route
720
- setPairingRoute(route)
721
- if (route === 'custom') {
722
- automaticUrlRef.current = ''
723
- return
724
- }
725
- if (status) {
726
- const nextUrl = pairingUrlFor(route, status)
727
- automaticUrlRef.current = nextUrl
728
- setPublicUrl(nextUrl)
729
- }
730
- }
731
-
732
- const configurePublicAccess = async () => {
733
- if (publicSetupBusy) return
734
- setPublicSetupBusy(true)
735
- setError(null)
736
- try {
737
- const data = await request('/mgw/public-setup', {
738
- method: 'POST',
739
- headers: { 'Content-Type': 'application/json' },
740
- body: JSON.stringify({ publicIp }),
741
- })
742
- setPublicSetup(data)
743
- if (data.publicUrl && pairingRouteRef.current === 'auto') {
744
- automaticUrlRef.current = data.publicUrl
745
- setPublicUrl(data.publicUrl)
746
- }
747
- } catch (cause) {
748
- setError(cause.message)
749
- } finally {
750
- setPublicSetupBusy(false)
751
- }
752
- }
753
-
754
- const configureCloudflare = async (enabled, mode = cloudflareMode) => {
755
- if (cloudflareBusy) return
756
- setCloudflareBusy(true)
757
- setError(null)
758
- try {
759
- const data = await request('/mgw/cloudflare', {
760
- method: 'POST',
761
- headers: { 'Content-Type': 'application/json' },
762
- body: JSON.stringify({ enabled, ...(enabled ? {
763
- mode,
764
- ...(mode === 'named' ? { hostname: cloudflareHost, token: cloudflareToken } : {}),
765
- } : {}) }),
766
- })
767
- setCloudflareToken('')
768
- setStatus((current) => ({ ...(current || {}), cloudflare: data, gatewayEnabled: data.gatewayEnabled, gatewayMode: data.gatewayMode, publicUrl: data.publicUrl || null }))
769
- if (!enabled && pairingRouteRef.current === 'cloudflare') {
770
- pairingRouteRef.current = 'auto'
771
- setPairingRoute('auto')
772
- }
773
- await refresh()
774
- } catch (cause) {
775
- setError(cause.message)
776
- } finally {
777
- setCloudflareBusy(false)
778
- }
779
- }
780
-
781
- const checkCloudflare = async () => {
782
- if (cloudflareBusy) return
783
- setCloudflareBusy(true)
784
- setError(null)
785
- try {
786
- const data = await request('/mgw/cloudflare/check', { method: 'POST' })
787
- setStatus((current) => ({ ...(current || {}), cloudflare: data }))
788
- } catch (cause) { setError(cause.message) }
789
- finally { setCloudflareBusy(false) }
790
- }
791
-
792
- const restartCloudflare = async () => {
793
- if (cloudflareBusy) return
794
- setCloudflareBusy(true)
795
- setError(null)
796
- try {
797
- const data = await request('/mgw/cloudflare/restart', { method: 'POST' })
798
- if (data.mode === 'quick') setQr(null)
799
- setStatus((current) => ({ ...(current || {}), cloudflare: data }))
800
- await refresh()
801
- } catch (cause) {
802
- setError(cause.message)
803
- } finally {
804
- setCloudflareBusy(false)
805
- }
806
- }
807
-
808
- const createPairing = async (endpoint) => request('/mgw/pair', {
809
- method: 'POST',
810
- headers: { 'Content-Type': 'application/json' },
811
- body: JSON.stringify({ publicUrl: endpoint }),
812
- })
813
-
814
- const pair = async () => {
815
- setBusy(true)
816
- setError(null)
817
- setPairingTokenCopied(false)
818
- try {
819
- const data = await createPairing(publicUrl)
820
- pairingIdRef.current = data.pairing?.id || null
821
- setQr(data)
822
- } catch (cause) {
823
- setError(cause.message)
824
- } finally {
825
- setBusy(false)
826
- }
827
- }
828
-
829
- // Fork: the pairing payload must be copyable wherever the WebUI is
830
- // opened. navigator.clipboard only exists in a secure context, and the
831
- // fnOS gateway embedding is plain http — there the async API is simply
832
- // missing. Fall back to the deprecated-but-universal execCommand path
833
- // before giving up, and report failures inside the QR dialog (the
834
- // panel's error banner sits behind the modal and is invisible).
835
- const writeClipboard = (text) => {
836
- if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
837
- return navigator.clipboard.writeText(text)
838
- }
839
- return new Promise((resolve, reject) => {
840
- const holder = document.createElement('textarea')
841
- holder.value = text
842
- holder.setAttribute('readonly', '')
843
- holder.style.position = 'fixed'
844
- holder.style.top = '-1000px'
845
- holder.style.opacity = '0'
846
- document.body.appendChild(holder)
847
- holder.select()
848
- holder.setSelectionRange(0, text.length)
849
- let copied = false
850
- try {
851
- copied = document.execCommand('copy')
852
- } catch (error) {
853
- copied = false
854
- }
855
- document.body.removeChild(holder)
856
- if (copied) resolve()
857
- else reject(new Error('浏览器拒绝写入剪贴板'))
858
- })
859
- }
860
-
861
- const copyPairingText = async () => {
862
- if (!qr || !qr.qrPayload) return
863
- try {
864
- await writeClipboard(qr.qrPayload)
865
- setError(null)
866
- setCopyNotice(null)
867
- setPairingTokenCopied(true)
868
- window.setTimeout(() => setPairingTokenCopied(false), 2200)
869
- } catch (cause) {
870
- setPairingTokenCopied(false)
871
- setCopyNotice(`${cause.message || '复制失败'},请选中上面文本后按 Ctrl/Cmd+C`)
872
- window.setTimeout(() => setCopyNotice(null), 6000)
873
- // Leave the payload selected so the manual copy is one keystroke away.
874
- const area = pairingDialogRef.current && pairingDialogRef.current.querySelector('textarea')
875
- if (area) { area.focus(); area.select() }
876
- }
877
- }
878
-
879
- const changeGatewayMode = async (mode) => {
880
- setBusy(true)
881
- setError(null)
882
- try {
883
- const data = await request('/mgw/gateway', {
884
- method: 'POST',
885
- headers: { 'Content-Type': 'application/json' },
886
- body: JSON.stringify({ mode }),
887
- })
888
- setStatus((current) => ({ ...(current || {}), ...data }))
889
- if (mode === 'disabled') setQr(null)
890
- } catch (cause) {
891
- setError(cause.message)
892
- } finally {
893
- setBusy(false)
894
- }
895
- }
896
-
897
- const toggleAuth = async () => {
898
- const enabled = !(status && status.requireAuth)
899
- if (!enabled && !window.confirm('关闭设备鉴权后,任何能访问移动网关的人都可以控制 DSH。此选项仅限 Debug 阶段使用,确定继续吗?')) return
900
- setBusy(true)
901
- setError(null)
902
- try {
903
- const data = await request('/mgw/auth', {
904
- method: 'POST',
905
- headers: { 'Content-Type': 'application/json' },
906
- body: JSON.stringify({ enabled }),
907
- })
908
- setStatus((current) => ({ ...(current || {}), requireAuth: data.requireAuth }))
909
- } catch (cause) {
910
- setError(cause.message)
911
- } finally {
912
- setBusy(false)
913
- }
914
- }
915
-
916
- const revoke = async (device) => {
917
- if (revokingIdsRef.current.has(device.id)) return
918
- setDeviceNotice(null)
919
- setDeviceNoticeError(false)
920
- setError(null)
921
- revokingIdsRef.current.add(device.id)
922
- setRevokingIds((current) => new Set(current).add(device.id))
923
- try {
924
- await request(`/mgw/devices/${encodeURIComponent(device.id)}/revoke`, { method: 'POST' })
925
- setDevices((current) => Array.isArray(current) ? current.filter((item) => item.id !== device.id) : current)
926
- setDeviceNotice(`已吊销 ${device.displayName || device.name}`)
927
- window.setTimeout(() => setDeviceNotice(null), 2200)
928
- } catch (cause) {
929
- setDeviceNoticeError(true)
930
- setDeviceNotice(`吊销失败:${cause.message}`)
931
- setError(cause.message)
932
- } finally {
933
- revokingIdsRef.current.delete(device.id)
934
- setRevokingIds((current) => {
935
- const next = new Set(current)
936
- next.delete(device.id)
937
- return next
938
- })
939
- await refresh()
940
- }
941
- }
942
-
943
- const restartNoticeInstance = status?.gatewayInstanceId || (status?.webPid ? String(status.webPid) : null)
944
- const dismissRestartNotice = () => {
945
- dismissedRestartInstance = restartNoticeInstance
946
- setDismissedNotice(restartNoticeInstance)
947
- try { window.localStorage.setItem(restartNoticeStorageKey, restartNoticeInstance) } catch { /* keep in-memory dismissal */ }
948
- }
949
-
950
- const onlineDevices = (devices || []).filter((device) => device.online)
951
- const offlineDevices = (devices || []).filter((device) => !device.online)
952
- const visibleDevices = showAllDevices ? [...onlineDevices, ...offlineDevices] : onlineDevices
953
-
954
- // Fork: relay (mini-program) state. The server's pairing mode is the
955
- // source of truth, so the route dropdown reflects it directly.
956
- const pairingMode = status && status.pairingMode ? status.pairingMode : 'direct'
957
- const relayInfo = status && status.relay ? status.relay : null
958
- const relayConnector = status && status.relayConnector ? status.relayConnector : null
959
- const effectiveRoute = pairingMode === 'relay' ? 'relay' : pairingRoute
960
-
961
- const advice = connectionAdvice(status, publicSetup)
962
- const helpLine = (name, description) => React.createElement('div', { style: { marginTop: 7 } },
963
- React.createElement('strong', null, name), ':', description)
964
-
965
- return React.createElement('div', { style: styles.backdrop, onMouseDown: () => setOpen(false) },
966
- qr ? React.createElement('div', { style: { ...styles.backdrop, zIndex: 1201 },
967
- onMouseDown: (event) => { event.stopPropagation(); closePairingDialog() } },
968
- React.createElement('div', { className: 'mgw-pairing-dialog', 'data-closing': pairingClosing, ref: pairingDialogRef, role: 'dialog', 'aria-modal': true, 'aria-label': '设备配对二维码', tabIndex: -1,
969
- style: { ...styles.panel, width: 'min(520px, 100%)', height: 'auto', overflowY: 'auto', scrollbarWidth: 'none' },
970
- onMouseDown: (event) => event.stopPropagation(),
971
- onKeyDown: (event) => {
972
- if (event.key === 'Escape') { event.stopPropagation(); closePairingDialog() }
973
- if (event.key === 'Tab') {
974
- const items = [...event.currentTarget.querySelectorAll('button, textarea')]
975
- const first = items[0], last = items[items.length - 1]
976
- if (event.shiftKey && (document.activeElement === first || document.activeElement === event.currentTarget)) { event.preventDefault(); last?.focus() }
977
- else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first?.focus() }
978
- }
979
- } },
980
- React.createElement('div', { style: { display: 'flex', justifyContent: 'flex-end' } },
981
- React.createElement('button', { type: 'button', style: { ...styles.button, ...styles.headerButton }, 'aria-label': '关闭配对窗口', onClick: closePairingDialog }, '✕')),
982
- React.createElement('section', { style: { textAlign: 'center' } },
983
- React.createElement('strong', null, '使用移动客户端扫码'),
984
- React.createElement('img', { style: styles.qr, src: `data:image/svg+xml;charset=utf-8,${encodeURIComponent(qr.svg)}`, alt: '一次性设备配对二维码' }),
985
- React.createElement('label', { style: { ...styles.label, textAlign: 'left' } }, 'Base64URL 配对字符串'),
986
- React.createElement('textarea', { style: styles.pairingText, value: qr.qrPayload, readOnly: true, spellCheck: false, onFocus: (event) => event.target.select() }),
987
- 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'),
988
- pairingTokenCopied ? React.createElement('div', { style: { ...styles.muted, color: colors.success, marginBottom: 8 } }, '已复制到剪贴板') : null,
989
- copyNotice ? React.createElement('div', { role: 'alert', style: { ...styles.muted, color: colors.danger, marginBottom: 8 } }, copyNotice) : null,
990
- React.createElement('div', { style: styles.muted }, `有效期至 ${new Date(qr.pairing.expiresAt).toLocaleTimeString()};扫码成功后此二维码立即失效。`)))) : null,
991
- 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': '鲸尾移动网关管理' },
992
- React.createElement('div', { style: styles.header },
993
- React.createElement('div', null,
994
- React.createElement('h2', { style: styles.title }, '鲸尾移动网关'),
995
- React.createElement('div', { style: styles.muted }, !status ? '正在加载网关状态…' : status.gatewayEnabled ? `移动网关已开启 · ${status.requireAuth ? '设备鉴权已开启' : '本机设备鉴权已关闭'}` : '移动网关已关闭 · 普通 WebUI 模式')),
996
- React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 6 } },
997
- React.createElement('div', { style: { position: 'relative' }, onMouseDown: (event) => event.stopPropagation() },
998
- React.createElement('button', {
999
- type: 'button', style: { ...styles.button, ...styles.headerButton, borderRadius: '50%' }, title: '工具', 'aria-label': '工具',
1000
- 'aria-haspopup': 'menu', 'aria-expanded': toolsOpen,
1001
- onClick: () => setToolsOpen((value) => !value),
1002
- }, 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 },
1003
- 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' }),
1004
- React.createElement('circle', { cx: 12, cy: 12.7, r: 3.1 }))),
1005
- toolsOpen ? React.createElement('div', { style: styles.toolsMenu, role: 'menu', 'aria-label': '网关工具' },
1006
- React.createElement('button', {
1007
- type: 'button', role: 'menuitem', disabled: toolBusy || stoppedRef.current || !status?.tools?.restartWeb,
1008
- style: { ...styles.toolsItem, opacity: status?.tools?.restartWeb ? 1 : .5 },
1009
- onClick: () => runTool('restart-web'),
1010
- }, '重启当前网关',
1011
- React.createElement('span', { style: { ...styles.muted, display: 'block', marginTop: 2 } }, '结束当前进程并重新启动 DSH Web')),
1012
- React.createElement('button', {
1013
- type: 'button', role: 'menuitem', disabled: toolBusy || stoppedRef.current || !status?.tools?.stopWeb,
1014
- style: { ...styles.toolsItem, color: colors.danger, opacity: status?.tools?.stopWeb ? 1 : .5 },
1015
- onClick: () => runTool('stop-web'),
1016
- }, '停止 DSH Web',
1017
- React.createElement('span', { style: { ...styles.muted, display: 'block', marginTop: 2 } }, '结束后台进程,所有连接将断开')))
1018
- : null),
1019
- React.createElement('button', { style: { ...styles.button, ...styles.headerButton }, onClick: () => setOpen(false), 'aria-label': '关闭' },
1020
- React.createElement('svg', { width: 20, height: 20, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 2.2, strokeLinecap: 'round', 'aria-hidden': true },
1021
- React.createElement('path', { d: 'M6 6l12 12M18 6L6 18' }))))),
1022
- React.createElement('div', { className: 'mgw-body' },
1023
- React.createElement('nav', { ref: navRef, className: 'mgw-nav', 'aria-label': '鲸尾移动网关设置分组' },
1024
- [['general', '通用设置'], ['pairing', '连接与配对'], ['devices', '可信设备']].map(([id, label]) =>
1025
- React.createElement('button', { key: id, type: 'button', 'aria-current': activeSection === id ? 'page' : undefined,
1026
- onClick: () => { setActiveSection(id); setConnectionHelpOpen(false); setToolsOpen(false) } }, label))),
1027
- React.createElement('div', { className: 'mgw-content', key: activeSection },
1028
- 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' },
1029
- React.createElement('button', { type: 'button', 'aria-label': '关闭重启提醒', title: '关闭提醒',
1030
- style: { ...styles.button, position: 'absolute', right: 8, top: 8, border: 0, width: 24, height: 24, padding: 0, color: colors.muted },
1031
- onClick: dismissRestartNotice }, '✕'),
1032
- React.createElement('strong', null, '若安装或更新后连接异常,请重启应用'),
1033
- React.createElement('div', { style: { color: colors.muted, marginTop: 4 } },
1034
- '完全退出并重启 APP/Desktop;Web UI 请重启 DSH Web 服务。'),
1035
- React.createElement('div', { style: { color: colors.muted, marginTop: 4 } },
1036
- '端口仍被占用时,请关闭其他 Harness 实例。')) : null,
1037
- toolNotice ? React.createElement('div', { style: { ...styles.muted, marginBottom: 10 } }, toolNotice) : null,
1038
- error ? React.createElement('div', { style: styles.error }, error) : null,
1039
- React.createElement('div', { hidden: activeSection !== 'general' },
1040
- React.createElement('section', { style: styles.card },
1041
- React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 14, alignItems: 'center' } },
1042
- React.createElement('div', null,
1043
- React.createElement('strong', null, '网关运行模式'),
1044
- React.createElement('div', { style: { ...styles.muted, marginTop: 4 } }, status && status.gatewayEnabled
1045
- ? status.gatewayMode === 'persistent'
1046
- ? '重启后保持开启'
1047
- : status.waitExpiresAt
1048
- ? `等待可信设备连接,约 ${Math.max(1, Math.ceil((status.waitExpiresAt - Date.now()) / 60000))} 分钟后自动关闭`
1049
- : '设备已连接过,本次运行保持开启;重启后重新计时'
1050
- : '不接受移动设备连接')),
1051
- React.createElement('span', { style: { position: 'relative', display: 'inline-flex', flexShrink: 0 } },
1052
- React.createElement(GatewaySelect, {
1053
- style: { ...styles.input, width: 'auto', marginBottom: 0, padding: '8px 40px 8px 12px', appearance: 'none', WebkitAppearance: 'none' },
1054
- 'aria-label': '网关运行模式',
1055
- value: status ? status.gatewayMode || (status.gatewayEnabled ? 'temporary' : 'disabled') : 'disabled',
1056
- disabled: busy || !status,
1057
- onChange: (event) => changeGatewayMode(event.target.value),
1058
- },
1059
- React.createElement('option', { value: 'disabled' }, '关闭'),
1060
- React.createElement('option', { value: 'temporary' }, '临时开启'),
1061
- React.createElement('option', { value: 'persistent' }, '常驻开启')),
1062
- )),
1063
- status && status.gatewayId ? React.createElement('div', { style: { ...styles.muted, marginTop: 12, overflowWrap: 'anywhere' } },
1064
- status.gatewayName) : null),
1065
- React.createElement('section', { style: styles.card },
1066
- React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 14, alignItems: 'center' } },
1067
- React.createElement('div', null,
1068
- React.createElement('strong', null, '设备鉴权'),
1069
- React.createElement('div', { style: { ...styles.muted, marginTop: 4 } }, status && status.requireAuth ? '已开启,仅允许可信设备连接' : '已关闭,仅影响本机 Debug 入口')),
1070
- React.createElement('label', { style: { ...styles.switch, opacity: busy || !status ? .55 : 1 }, title: status && status.requireAuth ? '关闭设备鉴权' : '开启设备鉴权' },
1071
- React.createElement('input', {
1072
- type: 'checkbox',
1073
- role: 'switch',
1074
- 'aria-label': '设备鉴权',
1075
- 'aria-checked': !!(status && status.requireAuth),
1076
- checked: !!(status && status.requireAuth),
1077
- disabled: busy || !status,
1078
- onChange: toggleAuth,
1079
- style: styles.switchInput,
1080
- }),
1081
- React.createElement('span', { style: { ...styles.switchTrack, background: status && status.requireAuth ? colors.success : colors.danger } }),
1082
- React.createElement('span', { style: { ...styles.switchKnob, left: status && status.requireAuth ? 21 : 3 } }))),
1083
- status && !status.requireAuth
1084
- ? React.createElement('p', { style: { ...styles.error, margin: '12px 0 0' } }, 'Debug 模式:本机 DSH 入口将跳过设备凭证校验;独立局域网入口仍强制鉴权。')
1085
- : null),
1086
- React.createElement('section', { style: styles.card },
1087
- React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 14, alignItems: 'flex-start' } },
1088
- React.createElement('div', null,
1089
- React.createElement('strong', null, '插件在线更新'),
1090
- React.createElement('div', { style: { ...styles.muted, marginTop: 4 } }, updateChecking
1091
- ? '正在检查 npm 最新版本…'
1092
- : updateInfo
1093
- ? `当前版本 v${updateInfo.currentVersion} · npm 最新 v${updateInfo.latestVersion}`
1094
- : '暂时无法获取版本信息'),
1095
- updateInfo?.updateAvailable
1096
- ? React.createElement('div', { style: { marginTop: 6, color: colors.success, fontWeight: 600 } }, '发现新版本,可直接升级安装。')
1097
- : null,
1098
- updateInfo && !updateInfo.updateAvailable
1099
- ? React.createElement('div', { style: { marginTop: 6, color: colors.success } }, '当前已是最新版本。')
1100
- : null,
1101
- updateNotice
1102
- ? React.createElement('div', { style: { ...styles.muted, marginTop: 6, overflowWrap: 'anywhere' }, role: 'status' }, updateNotice)
1103
- : null,
1104
- updateError
1105
- ? React.createElement('div', { style: { ...styles.muted, marginTop: 6, color: colors.danger, overflowWrap: 'anywhere' }, role: 'status' }, `检查失败:${updateError}`)
1106
- : null),
1107
- React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 8, minWidth: 100 } },
1108
- React.createElement('button', {
1109
- type: 'button',
1110
- style: { ...styles.button, ...styles.primary, opacity: updateBusy || !updateInfo?.updateAvailable ? .55 : 1 },
1111
- disabled: updateBusy || updateChecking || !updateInfo?.updateAvailable,
1112
- onClick: upgradePlugin,
1113
- }, updateBusy ? '正在升级…' : '立即升级'),
1114
- React.createElement('button', {
1115
- type: 'button',
1116
- style: styles.button,
1117
- disabled: updateChecking || updateBusy,
1118
- onClick: checkForPluginUpdate,
1119
- }, updateChecking ? '检查中…' : '重新检查')))),
1120
- ),
1121
- React.createElement('div', { hidden: activeSection !== 'pairing' },
1122
- React.createElement('section', { style: styles.card },
1123
- React.createElement('div', { className: 'mgw-setting-row' },
1124
- React.createElement('div', { style: { position: 'relative', display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }, onMouseLeave: () => setConnectionHelpOpen(false) },
1125
- React.createElement('h3', { className: 'mgw-section-title', style: { marginBottom: 0 } }, '配对连接方式'),
1126
- React.createElement('button', {
1127
- type: 'button',
1128
- style: styles.helpButton,
1129
- 'aria-label': '连接方式说明与场景建议',
1130
- 'aria-expanded': connectionHelpOpen,
1131
- 'aria-describedby': connectionHelpOpen ? 'mgw-route-help' : undefined,
1132
- onMouseEnter: () => setConnectionHelpOpen(true),
1133
- onFocus: () => setConnectionHelpOpen(true),
1134
- onBlur: () => setConnectionHelpOpen(false),
1135
- onClick: () => setConnectionHelpOpen(true),
1136
- onKeyDown: (event) => { if (event.key === 'Escape') setConnectionHelpOpen(false) },
1137
- }, '?'),
1138
- connectionHelpOpen ? React.createElement('div', { id: 'mgw-route-help', role: 'tooltip', style: styles.helpBubble },
1139
- React.createElement('strong', null, '怎么选连接方式'),
1140
- helpLine('局域网直连', '手机与 DSH 在同一个可互访的局域网,使用 ws:// 私有地址;离开该网络就无法直连。'),
1141
- helpLine('Cloudflare Channel(命名 Tunnel)', 'PC 主动连接 Cloudflare,外网用固定域名的 wss://;需要 Cloudflare 账户和域名。'),
1142
- helpLine('Quick Channel(Quick Tunnel)', '无需账户或域名,Cloudflare 分配临时 wss:// 地址;隧道重建后地址可能变化。'),
1143
- helpLine('公网服务器连接', 'DSH 运行在有固定公网 IPv4 的 Linux 服务器上,配置公网入口后用 wss:// 公网 IP 连接。'),
1144
- React.createElement('div', { style: { borderTop: `1px solid ${colors.border}`, marginTop: 10, paddingTop: 8 } },
1145
- React.createElement('strong', null, '结合当前环境'),
1146
- React.createElement('div', { style: { color: colors.muted, marginTop: 4 } }, advice.detected),
1147
- React.createElement('div', { style: { marginTop: 6 } }, advice.local),
1148
- React.createElement('div', { style: { marginTop: 6 } }, advice.remote),
1149
- React.createElement('div', { style: { color: colors.muted, marginTop: 6 } }, '面板无法判断手机当前网络;请按手机所在位置选择,提示不会替你修改选择。')))
1150
- : null),
1151
- React.createElement('div', { style: { display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: '8px 14px', maxWidth: '100%' } },
1152
- React.createElement(GatewaySelect, { style: styles.input, value: effectiveRoute, onChange: (event) => choosePairingRoute(event.target.value), disabled: !status, 'aria-label': '配对连接方式' },
1153
- React.createElement('option', { value: 'auto' }, '自动选择 · 优先外网'),
1154
- lanPairingUrl(status) || pairingRoute === 'lan'
1155
- ? React.createElement('option', { value: 'lan', disabled: !lanPairingUrl(status) }, lanPairingUrl(status)
1156
- ? '局域网直连'
1157
- : '局域网直连 · 当前不可用')
1158
- : null,
1159
- status?.cloudflare?.enabled ? React.createElement('option', { value: 'cloudflare' }, 'Cloudflare 外网') : null,
1160
- React.createElement('option', { value: 'relay' }, '鲸尾公网 · 小程序'),
1161
- React.createElement('option', { value: 'custom' }, '手动输入地址')),
1162
- (pairingRoute === 'auto' || pairingRoute === 'cloudflare') && status?.cloudflare?.supported
1163
- ? React.createElement('span', { style: { fontSize: 12, lineHeight: 1.5, fontWeight: 500,
1164
- color: 'var(--dsw-alias-link, #4176e6)' } }, '外网使用 Cloudflare Tunnel 进行连接,请在下方进行设置。') : null),
1165
- // Fork: 中继模式下展示连接器状态与已注册中继信息
1166
- pairingMode === 'relay'
1167
- ? (relayInfo
1168
- ? React.createElement('div', { style: { ...styles.muted, margin: '2px 0 0', fontWeight: 500 } },
1169
- '鲸尾公网服务 · 已注册', ' · ',
1170
- React.createElement('span', { style: { opacity: .8 } }, `设备 ID ${relayInfo.nodeId.slice(0, 8)}… · ${relayInfo.gatewayName}`),
1171
- React.createElement('div', { style: { marginTop: 6, padding: '9px 11px', borderRadius: 10, border: '1px solid color-mix(in srgb, var(--dsw-alias-state-warning-primary, #d98324) 26%, transparent)', background: 'color-mix(in srgb, var(--dsw-alias-state-warning-primary, #d98324) 9%, transparent)', fontWeight: 400 } },
1172
- React.createElement('div', null, '连接地址由插件自动配置,无需填写。用户在小程序兑换公网有效期后,扫描本机二维码连接。'),
1173
- React.createElement('div', { style: { marginTop: 5 } }, '设备配对与公网有效期独立;公网到期不影响局域网。已注册不代表手机端完整链路已通过验证。')))
1174
- : relayConnector && relayConnector.running
1175
- ? React.createElement('div', { style: { ...styles.muted, margin: '2px 0 0', fontWeight: 500,
1176
- color: 'var(--dsw-alias-link, #4176e6)' } }, '内置连接器已自动启动,正在连接中继并上报身份…')
1177
- : relayConnector && relayConnector.lastError
1178
- ? React.createElement('div', { style: { ...styles.muted, margin: '2px 0 0', fontWeight: 500, color: colors.danger } },
1179
- '公网连接器暂时不可用,请检查网络或重新开启公网连接。', ' ',
1180
- React.createElement('span', { style: { opacity: .8 } }, '如已自行部署连接器,请执行 systemctl restart dsh-connector。'))
1181
- : React.createElement('div', { style: { ...styles.muted, margin: '2px 0 0' } }, '正在启动内置连接器…(中继模式需要一个本地连接器把小程序流量桥接进来,插件会自动准备)'))
1182
- : null),
1183
- pairingMode !== 'relay' ? React.createElement('label', { style: styles.label }, 'WebSocket 地址') : null,
1184
- pairingMode !== 'relay' ? React.createElement('input', { style: styles.input, value: publicUrl, onChange: (event) => { choosePairingRoute('custom'); setPublicUrl(event.target.value) }, placeholder: 'ws://192.168.1.10:3081/ws/mobile', spellCheck: false }) : null,
1185
- status && status.lan && status.lan.enabled
1186
- ? 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)' } },
1187
- status.lan.error
1188
- ? `局域网监听失败:${status.lan.error}`
1189
- : status.lan.listening
1190
- ? `局域网入口已开启${status.lan.urls && status.lan.urls.length ? `:${status.lan.urls.join('、')}` : `,端口 ${status.lan.port}`}`
1191
- : '局域网入口启动中…')
1192
- : null,
1193
- React.createElement('button', {
1194
- style: { ...styles.button, ...styles.primary, opacity: busy || !(status && status.gatewayEnabled) || (pairingMode !== 'relay' && !publicUrl.trim()) ? .65 : 1 },
1195
- disabled: busy || !(status && status.gatewayEnabled) || (pairingMode !== 'relay' && !publicUrl.trim()),
1196
- onClick: pair,
1197
- }, busy ? '正在生成…' : !(status && status.gatewayEnabled) ? '请先开启移动网关' : (pairingMode !== 'relay' && !publicUrl.trim()) ? '等待连接地址' : '生成配对二维码'),
1198
- React.createElement('p', { style: { ...styles.muted, margin: '10px 0 0' } }, '配对码仅可使用一次,5 分钟内有效。')),
1199
- (pairingRoute === 'auto' || pairingRoute === 'cloudflare') && status?.cloudflare?.supported
1200
- ? React.createElement('section', { className: 'mgw-cloudflare-block', style: { ...styles.card, background: colors.card, border: 0, borderRadius: 16, padding: 18, marginTop: 16 } },
1201
- React.createElement('h3', { className: 'mgw-section-title' }, 'Cloudflare Tunnel · 外网接入'),
1202
- React.createElement('p', { style: styles.muted }, status.platform === 'linux'
1203
- ? 'Linux 服务器不自动下载:请先安装 cloudflared(Cloudflare 官方源 pkg.cloudflare.com 的 cloudflared 包),或将插件配置 cloudflaredPath 指向已有可执行文件。公网入口只接受已鉴权的移动 WebSocket。'
1204
- : '首次开启自动准备 Tunnel 组件。'),
1205
- React.createElement('div', { className: 'mgw-setting-row' },
1206
- React.createElement('span', { className: 'mgw-setting-label' }, '接入方式'),
1207
- React.createElement(GatewaySelect, { style: styles.input, value: cloudflareMode, 'aria-label': 'Cloudflare 接入方式', onChange: (event) => {
1208
- const mode = event.target.value
1209
- setCloudflareMode(mode)
1210
- if (status.cloudflare.enabled && mode !== status.cloudflare.mode &&
1211
- (mode === 'quick' || (status.cloudflare.configured && cloudflareHost === status.cloudflare.hostname && !cloudflareToken))) {
1212
- void configureCloudflare(true, mode)
1213
- }
1214
- }, disabled: cloudflareBusy },
1215
- React.createElement('option', { value: 'quick' }, 'Quick Tunnel · 无需域名'),
1216
- React.createElement('option', { value: 'named' }, '命名 Tunnel · 固定域名'))),
1217
- cloudflareMode === 'quick'
1218
- ? React.createElement('p', { style: styles.muted }, '临时地址可能变化,变化后需重新扫码。')
1219
- : React.createElement(React.Fragment, null,
1220
- 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 记录。'),
1221
- React.createElement('div', { style: { display: 'flex', gap: 14, flexWrap: 'wrap', margin: '2px 0 4px' } },
1222
- 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 控制台 → 隧道 ↗'),
1223
- 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' } }, '官方创建教程 ↗')),
1224
- React.createElement('p', { style: styles.muted }, 'Token 在控制台建好 Tunnel 后选择操作系统给出的安装命令里,是 eyJ… 开头的一段(只用它,不需要在 NAS 上执行该命令)。'),
1225
- React.createElement('label', { style: styles.label }, '公开域名'),
1226
- React.createElement('input', { style: styles.input, value: cloudflareHost, onChange: (event) => setCloudflareHost(event.target.value.trim()), placeholder: 'gateway.example.com', spellCheck: false }),
1227
- React.createElement('label', { style: styles.label }, 'Tunnel Token'),
1228
- 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 })),
1229
- (!status.cloudflare.enabled || (cloudflareMode === 'named' &&
1230
- (status.cloudflare.mode !== 'named' || cloudflareHost !== status.cloudflare.hostname || !!cloudflareToken)))
1231
- ? React.createElement('button', {
1232
- style: { ...styles.button, ...styles.primary, opacity: cloudflareBusy || (cloudflareMode === 'named' && (!cloudflareHost || (!cloudflareToken && !status.cloudflare.configured))) ? .65 : 1 },
1233
- disabled: cloudflareBusy || (cloudflareMode === 'named' && (!cloudflareHost || (!cloudflareToken && !status.cloudflare.configured))),
1234
- onClick: () => configureCloudflare(true),
1235
- }, cloudflareBusy ? '正在处理…' : status.cloudflare.enabled ? '保存并连接' : cloudflareMode === 'quick' ? '一键开启 Quick Tunnel' : '开启命名 Tunnel') : null,
1236
- status.cloudflare.enabled
1237
- ? React.createElement(React.Fragment, null,
1238
- React.createElement('button', { style: { ...styles.button, width: '100%', marginTop: 8 }, disabled: cloudflareBusy || status.cloudflare.state !== 'online', onClick: checkCloudflare }, '检测公网 DNS / TLS / WebSocket'),
1239
- React.createElement('button', { style: { ...styles.button, width: '100%', marginTop: 8 }, disabled: cloudflareBusy || !status.gatewayEnabled, onClick: restartCloudflare }, '重启 Tunnel'),
1240
- React.createElement('button', { style: { ...styles.button, width: '100%', marginTop: 8 }, disabled: cloudflareBusy, onClick: () => configureCloudflare(false) }, '关闭 Cloudflare Tunnel'),
1241
- React.createElement('p', { style: styles.muted }, '重启会短暂断开连接。'))
1242
- : null,
1243
- 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 } },
1244
- status.cloudflare.error || ({ disabled: '未开启', starting: '正在启动本机入口…', preparing: '正在准备 cloudflared(首次需下载)…', connecting: '正在连接 Cloudflare…', online: '隧道传输已连接(不等于公网入口可达)', 'waiting-for-gateway': '等待移动网关开启' }[status.cloudflare.state] || status.cloudflare.state),
1245
- status.cloudflare.publicUrl ? ` · ${status.cloudflare.publicUrl}` : ''),
1246
- status.cloudflare.enabled && status.cloudflare.endpointHealth
1247
- ? 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 } },
1248
- status.cloudflare.endpointHealth.message,
1249
- status.cloudflare.endpointHealth.checkedAt ? `(检测时间:${status.cloudflare.endpointHealth.checkedAt})` : '')
1250
- : null)
1251
- : null,
1252
- status && status.platform === 'linux' ? React.createElement('section', { style: styles.card },
1253
- React.createElement('h3', { className: 'mgw-section-title' }, pairingMode === 'relay' ? '公网接入(中继模式下只影响上面透传的网关地址)' : '公网接入'),
1254
- publicSetup === null
1255
- ? React.createElement('p', { style: styles.muted }, '正在检查系统组件…')
1256
- : publicSetup.installed
1257
- ? React.createElement(React.Fragment, null,
1258
- React.createElement('div', { style: { ...styles.muted, margin: '5px 0 12px' } }, publicSetup.configured
1259
- ? publicSetup.backendPort && status && status.webPort && publicSetup.backendPort !== status.webPort
1260
- ? `端口需要更新:Nginx 当前为 ${publicSetup.backendPort},DSH 当前为 ${status.webPort}`
1261
- : `已配置${publicSetup.backendPort ? `,Nginx 转发至 DSH 端口 ${publicSetup.backendPort}` : ''}`
1262
- : `Helper 已就绪,将自动使用当前 DSH 端口${status && status.webPort ? ` ${status.webPort}` : ''}`),
1263
- React.createElement('label', { style: styles.label }, '服务器公网 IPv4'),
1264
- React.createElement('input', {
1265
- style: styles.input,
1266
- value: publicIp,
1267
- onChange: (event) => setPublicIp(event.target.value.trim()),
1268
- placeholder: '203.0.113.10',
1269
- inputMode: 'decimal',
1270
- spellCheck: false,
1271
- }),
1272
- React.createElement('button', {
1273
- style: { ...styles.button, ...styles.primary, opacity: publicSetupBusy || !publicIp ? .65 : 1 },
1274
- disabled: publicSetupBusy || !publicIp,
1275
- onClick: configurePublicAccess,
1276
- }, publicSetupBusy ? '正在配置 Nginx 与证书…' : publicSetup.configured ? '更新公网配置' : '配置公网接入'),
1277
- publicSetup.publicUrl
1278
- ? React.createElement('div', { style: { ...styles.muted, marginTop: 9, overflowWrap: 'anywhere' } }, publicSetup.publicUrl)
1279
- : null)
1280
- : React.createElement(React.Fragment, null,
1281
- React.createElement('p', { style: { ...styles.muted, marginBottom: 8 } }, '尚未安装系统 Helper。请在服务器执行一次初始化:'),
1282
- React.createElement('code', { style: { display: 'block', fontSize: 10, lineHeight: 1.5, overflowWrap: 'anywhere', userSelect: 'all' } }, 'npx --yes dsh-plugin-mobile-gateway@latest init'))) : null,
1283
-
1284
- ),
1285
- React.createElement('div', { hidden: activeSection !== 'devices' },
1286
- React.createElement('section', { style: styles.card },
1287
- React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center' } },
1288
- React.createElement('h3', { className: 'mgw-section-title', style: { marginBottom: 0 } }, '可信设备'),
1289
- React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 10 } },
1290
- deviceNotice || refreshNotice ? React.createElement('span', {
1291
- style: { ...styles.muted, color: deviceNoticeError ? colors.danger : colors.success },
1292
- }, deviceNotice || refreshNotice) : null,
1293
- React.createElement('button', {
1294
- style: { ...styles.button, opacity: refreshing ? .6 : 1 },
1295
- disabled: refreshing,
1296
- onClick: manualRefresh,
1297
- }, refreshing ? '刷新中…' : '刷新'))),
1298
- devices === null
1299
- ? React.createElement('p', { style: styles.muted }, '加载中…')
1300
- : devices.length === 0
1301
- ? React.createElement('p', { style: styles.muted }, '暂无已配对设备。')
1302
- : React.createElement(React.Fragment, null,
1303
- visibleDevices.length === 0 ? React.createElement('p', { style: styles.muted }, '当前没有在线设备。') : null,
1304
- visibleDevices.map((device) => React.createElement(DeviceRow, {
1305
- key: device.id,
1306
- device,
1307
- onRevoke: revoke,
1308
- revoking: revokingIds.has(device.id),
1309
- })),
1310
- offlineDevices.length > 0 ? React.createElement('button', {
1311
- type: 'button',
1312
- style: { ...styles.button, marginTop: 10, color: colors.muted },
1313
- 'aria-expanded': showAllDevices,
1314
- onClick: () => setShowAllDevices((value) => !value),
1315
- }, showAllDevices ? '收起离线设备' : `展开其他已配对设备(${offlineDevices.length})`) : null)),
1316
- )),
1317
- ),
1318
- status && status.version
1319
- ? React.createElement('div', { style: styles.version, 'aria-label': `插件版本 ${status.version}` }, `v${status.version}`)
1320
- : null))
1321
- }
1322
-
1323
- // Fork: the entry is a Settings section instead of a sidebar footer button.
1324
- // Tapping the Settings nav item opens the management dialog directly — the
1325
- // dialog itself is upstream's unchanged shell.
1326
- function SettingsEntry() {
1327
- const isOpen = React.useSyncExternalStore(subscribe, getOpen, () => false)
1328
- React.useEffect(() => { setOpen(true) }, [])
1329
- return isOpen ? React.createElement(DevicePanel) : null
1330
- }
1331
-
1332
- const inject = ['slots']
1333
- function apply(ctx) {
1334
- // Upstream 0.10.1: the panel stylesheet is injected once through an
1335
- // effect instead of being re-rendered inside the component tree.
1336
- ctx.effect(() => {
1337
- const style = document.createElement('style')
1338
- style.textContent = panelCss
1339
- document.head.appendChild(style)
1340
- return () => style.remove()
1341
- }, 'mobile-gateway: panel styles')
1342
- pinNavGlyph([NAV_LABEL], NAV_ICON_MARK, navGlyph)
1343
- // Fork: the entry is a Settings section, not the upstream sidebar footer
1344
- // button. The id deliberately stays 'mobile-gateway' (not the package
1345
- // name): it is a slot key that pinned-section state and the settings
1346
- // plugin-hub map against, so renaming it would drop existing pins.
1347
- ctx.slots.inject('settings.section', () => ctx.slots.register(
1348
- { name: 'settings.section', id: 'mobile-gateway', order: 35, label: () => NAV_LABEL },
1349
- () => React.createElement(SettingsEntry, null),
1350
- ))
1351
- }
1352
-
1353
- exports.apply = apply
1354
- exports.inject = inject
1355
- exports.pinNavGlyph = pinNavGlyph
1356
- // Exposed for tests: the Settings entry and the dialog body render separately.
1357
- exports.SettingsEntry = SettingsEntry
1358
- exports.DevicePanel = DevicePanel
1359
- return module.exports
1360
- },
1361
- })
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
+ // Shared Web UI / Desktop semantic tokens update with the host theme.
24
+ const restartNoticeStorageKey = 'mobile-gateway-dismissed-restart-notice'
25
+ let dismissedRestartInstance = null
26
+ try { dismissedRestartInstance = window.localStorage.getItem(restartNoticeStorageKey) } catch { /* storage unavailable */ }
27
+
28
+ const colors = {
29
+ panel: 'var(--dsw-alias-bg-layer-2, var(--color-bg, Canvas))',
30
+ card: 'var(--dsw-alias-bg-module-platform, var(--color-bg-elevated, Canvas))',
31
+ text: 'var(--dsw-alias-label-primary, var(--color-text, CanvasText))',
32
+ muted: 'var(--dsw-alias-label-secondary, var(--color-text-muted, GrayText))',
33
+ border: 'var(--dsw-alias-border-l3, var(--color-border, rgba(127,127,127,.24)))',
34
+ accent: 'var(--dsw-alias-button-primary-fill, var(--color-primary, #4f7cff))',
35
+ accentText: 'var(--dsw-alias-label-primary-foreground, #fff)',
36
+ danger: 'var(--dsw-alias-state-error-primary, #dc4c64)',
37
+ success: 'var(--dsw-alias-state-success-primary, #2fb171)',
38
+ }
39
+ const styles = {
40
+ backdrop: {
41
+ position: 'fixed', inset: 0, zIndex: 1200, pointerEvents: 'auto',
42
+ background: 'var(--dsw-alias-bg-mask-1, rgba(0,0,0,.32))', display: 'flex',
43
+ justifyContent: 'center', alignItems: 'center',
44
+ padding: 'max(16px, var(--dsh-frame-overlay-top, 16px)) 16px', boxSizing: 'border-box',
45
+ },
46
+ panel: {
47
+ width: 'clamp(640px, 84vw, 1120px)', maxWidth: '100%', maxHeight: '100%', minHeight: 0, height: 'min(780px, calc(100dvh - 48px))', overflow: 'hidden',
48
+ scrollbarWidth: 'none', msOverflowStyle: 'none',
49
+ display: 'flex', flexDirection: 'column',
50
+ background: colors.panel, color: colors.text, border: `1px solid ${colors.border}`, borderRadius: 'var(--dsw-radius-panel, 16px)',
51
+ boxShadow: 'var(--dsw-elevation-prominent, 0 20px 60px rgba(0,0,0,.22))', padding: 24,
52
+ fontFamily: 'var(--dsw-font-family, system-ui, sans-serif)', fontSize: 13, boxSizing: 'border-box',
53
+ },
54
+ header: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18, flexShrink: 0 },
55
+ title: { margin: 0, fontSize: 22, fontWeight: 650 },
56
+ card: { background: 'transparent', border: 0, borderBottom: `1px solid ${colors.border}`, borderRadius: 0, padding: '16px 0', marginBottom: 0, flexShrink: 0 },
57
+ label: { display: 'block', color: colors.muted, fontSize: 12, marginBottom: 6 },
58
+ 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' },
59
+ 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' },
60
+ button: { cursor: 'pointer', border: `1px solid ${colors.border}`, background: 'transparent', borderRadius: 8, padding: '7px 11px', color: 'inherit', font: 'inherit' },
61
+ headerButton: { width: 34, height: 34, boxSizing: 'border-box', border: 0, padding: 0, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 },
62
+ primary: { background: colors.accent, color: colors.accentText, borderColor: colors.accent, width: '100%' },
63
+ muted: { color: colors.muted, fontSize: 12, lineHeight: 1.45 },
64
+ row: { display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) auto', columnGap: 12, alignItems: 'center', padding: '12px 0', borderBottom: `1px solid ${colors.border}` },
65
+ badge: { display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11, marginLeft: 8, color: colors.muted },
66
+ dot: { width: 7, height: 7, borderRadius: 99, display: 'inline-block' },
67
+ error: { color: colors.danger, background: 'rgba(220,76,100,.12)', borderRadius: 8, padding: 10, marginBottom: 12 },
68
+ qr: { display: 'block', width: 220, height: 220, margin: '12px auto', background: '#fff', borderRadius: 10, padding: 8 },
69
+ 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 },
70
+ 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 },
71
+ 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)' },
72
+ toolsItem: { display: 'block', width: '100%', padding: '9px 10px', textAlign: 'left', border: 0, borderRadius: 7, background: 'transparent', color: colors.text, font: 'inherit', cursor: 'pointer' },
73
+ switch: { position: 'relative', display: 'inline-flex', width: 42, height: 24, flexShrink: 0 },
74
+ switchInput: { position: 'absolute', opacity: 0, width: 1, height: 1 },
75
+ switchTrack: { position: 'absolute', inset: 0, borderRadius: 99, transition: 'background .18s ease', cursor: 'pointer' },
76
+ 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' },
77
+ version: { flexShrink: 0, marginTop: 'auto', padding: '18px 2px 0', color: colors.muted, fontSize: 11, lineHeight: 1.4, textAlign: 'right', letterSpacing: '.02em' },
78
+ }
79
+
80
+ const panelCss = `
81
+ @keyframes mgw-pairing-enter {
82
+ from { opacity: 0; transform: scale(.82); }
83
+ to { opacity: 1; transform: scale(1); }
84
+ }
85
+ .mgw-pairing-dialog {
86
+ transform-origin: center;
87
+ animation: mgw-pairing-enter 240ms cubic-bezier(.2, .8, .2, 1);
88
+ }
89
+ @keyframes mgw-pairing-exit {
90
+ from { opacity: 1; transform: scale(1); }
91
+ to { opacity: 0; transform: scale(.82); }
92
+ }
93
+ .mgw-pairing-dialog[data-closing="true"] {
94
+ animation: mgw-pairing-exit 180ms ease-in forwards;
95
+ pointer-events: none;
96
+ }
97
+ @media (prefers-reduced-motion: reduce) {
98
+ .mgw-pairing-dialog { animation: none; }
99
+ }
100
+ .mobile-gateway-panel, .mobile-gateway-panel *, .mgw-pairing-dialog, .mgw-pairing-dialog *, .mgw-select-menu {
101
+ scrollbar-width: none !important;
102
+ -ms-overflow-style: none;
103
+ }
104
+ .mobile-gateway-panel::-webkit-scrollbar, .mobile-gateway-panel *::-webkit-scrollbar,
105
+ .mgw-pairing-dialog::-webkit-scrollbar, .mgw-pairing-dialog *::-webkit-scrollbar, .mgw-select-menu::-webkit-scrollbar {
106
+ display: none !important;
107
+ width: 0;
108
+ height: 0;
109
+ }
110
+ .mobile-gateway-panel .mgw-body { display: grid; grid-template-columns: 180px minmax(0, 1fr); gap: 28px; flex: 1; min-height: 0; }
111
+ .mobile-gateway-panel .mgw-nav { display: flex; flex-direction: column; gap: 4px; }
112
+ .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; }
113
+ .mobile-gateway-panel .mgw-nav button[aria-current="page"] { background: var(--dsw-alias-bg-overlay, rgba(127,127,127,.12)); font-weight: 500; }
114
+ .mobile-gateway-panel .mgw-nav button:hover { background: var(--dsw-alias-interactive-bg-hover, rgba(127,127,127,.08)); }
115
+ .mobile-gateway-panel .mgw-content { min-width: 0; overflow-y: auto; scrollbar-width: none; padding-right: 4px; }
116
+ .mobile-gateway-panel .mgw-content::-webkit-scrollbar { display: none; }
117
+ .mobile-gateway-panel .mgw-content p { margin: 6px 0 10px; }
118
+ .mobile-gateway-panel strong { font-weight: 550; }
119
+ .mobile-gateway-panel .mgw-section-title { margin: 0 0 10px; font-size: 17px; line-height: 1.4; font-weight: 650; color: inherit; }
120
+ .mobile-gateway-panel .mgw-setting-row { display: flex; flex-direction: column; align-items: flex-start; gap: 8px; margin-bottom: 12px; }
121
+ .mobile-gateway-panel .mgw-setting-row select { width: auto !important; max-width: 100%; min-width: 150px; margin-bottom: 0 !important; flex-shrink: 1; }
122
+ .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; }
123
+ .mobile-gateway-panel .mgw-setting-label { font-size: 14px; font-weight: 550; color: inherit; }
124
+
125
+ .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; }
126
+ @media (max-width: 640px) {
127
+ .mobile-gateway-panel .mgw-body { grid-template-columns: minmax(0, 1fr); gap: 8px; }
128
+ /* Fork: the dialog nav is not the settings rail — keep it a tab strip.
129
+ dsh-settings-mobile-nav collapses the first <nav> of any settings
130
+ dialog, which used to swallow ours and leave a lone expand button.
131
+ A stable height plus the marker below opts out. */
132
+ .mobile-gateway-panel .mgw-nav { flex-direction: row; flex-wrap: nowrap; }
133
+ .mobile-gateway-panel .mgw-nav button {
134
+ flex: 1 1 0; min-width: 0; min-height: 40px; height: 40px;
135
+ padding: 8px 6px; text-align: center; white-space: nowrap;
136
+ overflow: hidden; text-overflow: ellipsis;
137
+ }
138
+ }
139
+ `
140
+
141
+ function GatewaySelect({ style, children, value, onChange, disabled, ...props }) {
142
+ const options = React.Children.toArray(children).filter((child) => React.isValidElement(child))
143
+ const [menu, setMenu] = React.useState(null)
144
+ const [active, setActive] = React.useState(0)
145
+ const buttonRef = React.useRef(null)
146
+ const menuRef = React.useRef(null)
147
+ const menuId = React.useId()
148
+ const selected = options.find((option) => option.props.value === value)
149
+ const enabled = options.map((option, index) => option.props.disabled ? -1 : index).filter((index) => index >= 0)
150
+ const close = (restoreFocus = false) => {
151
+ setMenu(null)
152
+ if (restoreFocus) buttonRef.current?.focus()
153
+ }
154
+ const openMenu = () => {
155
+ if (disabled) return
156
+ const rect = buttonRef.current.getBoundingClientRect()
157
+ const computed = window.getComputedStyle(buttonRef.current)
158
+ const fontSize = parseFloat(computed.fontSize) || 14
159
+ const lineHeight = parseFloat(computed.lineHeight) || fontSize * 1.5
160
+ const measure = document.createElement('canvas').getContext('2d')
161
+ if (measure) measure.font = computed.font || `${fontSize}px sans-serif`
162
+ const longest = Math.max(...options.map((option) => measure
163
+ ? measure.measureText(String(option.props.children)).width : String(option.props.children).length * fontSize))
164
+ const height = Math.min(options.length * Math.max(40, lineHeight + 16) + 14, window.innerHeight - 24)
165
+ const width = Math.min(Math.max(rect.width, longest + 72, 200), window.innerWidth - 24)
166
+ setActive(Math.max(0, options.findIndex((option) => option.props.value === value && !option.props.disabled)))
167
+ setMenu({ left: Math.max(12, Math.min(rect.left, window.innerWidth - width - 12)),
168
+ top: Math.max(12, rect.bottom + height + 6 <= window.innerHeight - 12 ? rect.bottom + 6 : rect.top - height - 6), width, maxHeight: window.innerHeight - 24 })
169
+ }
170
+ const choose = (index) => {
171
+ const option = options[index]
172
+ if (!option || option.props.disabled) return
173
+ onChange?.({ target: { value: option.props.value } })
174
+ close(true)
175
+ }
176
+ React.useEffect(() => {
177
+ if (!menu) return
178
+ menuRef.current?.focus()
179
+ const outside = (event) => {
180
+ if (!buttonRef.current?.contains(event.target) && !menuRef.current?.contains(event.target)) close()
181
+ }
182
+ const scrolled = (event) => { if (!menuRef.current?.contains(event.target)) close() }
183
+ const resized = () => close()
184
+ document.addEventListener('pointerdown', outside)
185
+ document.addEventListener('scroll', scrolled, true)
186
+ window.addEventListener('resize', resized)
187
+ return () => {
188
+ document.removeEventListener('pointerdown', outside)
189
+ document.removeEventListener('scroll', scrolled, true)
190
+ window.removeEventListener('resize', resized)
191
+ }
192
+ }, [menu])
193
+ React.useEffect(() => {
194
+ if (menu) document.getElementById(`${menuId}-${active}`)?.scrollIntoView({ block: 'nearest' })
195
+ }, [active, menu])
196
+ return React.createElement('span', { style: { display: 'inline-flex', maxWidth: '100%', minWidth: 0 } },
197
+ React.createElement('button', { ...props, className: 'mgw-select-trigger', ref: buttonRef, type: 'button', disabled,
198
+ 'aria-haspopup': 'listbox', 'aria-expanded': !!menu, 'aria-controls': menu ? menuId : undefined,
199
+ onClick: () => menu ? close() : openMenu(),
200
+ onKeyDown: (event) => {
201
+ if (['ArrowDown', 'ArrowUp'].includes(event.key)) { event.preventDefault(); openMenu() }
202
+ },
203
+ style: { ...style, width: 'auto', maxWidth: '100%', marginBottom: 0, border: 0, borderRadius: 12,
204
+ padding: '10px 16px', background: colors.card, color: colors.text, font: 'inherit', cursor: disabled ? 'default' : 'pointer',
205
+ display: 'inline-flex', alignItems: 'center', gap: 18, opacity: disabled ? .5 : 1 } },
206
+ React.createElement('span', { style: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, selected?.props.children || value),
207
+ React.createElement('svg', { width: 14, height: 14, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor',
208
+ strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true, style: { flexShrink: 0 } },
209
+ React.createElement('path', { d: 'M6 9l6 6 6-6' }))),
210
+ menu ? React.createElement('div', { className: 'mgw-select-menu', ref: menuRef, id: menuId, role: 'listbox', tabIndex: -1,
211
+ 'aria-label': props['aria-label'], 'aria-activedescendant': `${menuId}-${active}`,
212
+ style: { ...menu, position: 'fixed', zIndex: 1250, boxSizing: 'border-box', overflowY: 'auto', padding: 6,
213
+ background: colors.panel, color: colors.text, border: `1px solid ${colors.border}`, borderRadius: 14,
214
+ boxShadow: 'var(--dsw-elevation-prominent, 0 8px 28px rgba(0,0,0,.12))', outline: 'none' },
215
+ onKeyDown: (event) => {
216
+ if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); close(true) }
217
+ else if (event.key === 'Tab') close()
218
+ else if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); choose(active) }
219
+ else if (['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) {
220
+ event.preventDefault()
221
+ const index = enabled.indexOf(active)
222
+ setActive(event.key === 'Home' ? enabled[0] : event.key === 'End' ? enabled[enabled.length - 1]
223
+ : enabled[(index + (event.key === 'ArrowDown' ? 1 : -1) + enabled.length) % enabled.length])
224
+ }
225
+ } }, options.map((option, index) => React.createElement('div', { key: option.props.value,
226
+ id: `${menuId}-${index}`, role: 'option', 'aria-selected': option.props.value === value, 'aria-disabled': !!option.props.disabled,
227
+ onPointerMove: () => { if (!option.props.disabled) setActive(index) }, onClick: () => choose(index),
228
+ style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, minHeight: 40, whiteSpace: 'nowrap',
229
+ boxSizing: 'border-box', padding: '8px 12px', borderRadius: 8, cursor: option.props.disabled ? 'default' : 'pointer',
230
+ opacity: option.props.disabled ? .4 : 1, background: active === index ? 'var(--dsw-alias-interactive-bg-hover, rgba(127,127,127,.08))' : 'transparent' } },
231
+ 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',
232
+ fill: 'none', stroke: 'currentColor', strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true, style: { flexShrink: 0 } },
233
+ React.createElement('path', { d: 'M5 12l4 4L19 6' })) : null))) : null)
234
+ }
235
+
236
+ // --------------------------------------------------------------------------
237
+ // Settings-nav glyph, pinned by the plugin itself.
238
+ //
239
+ // The `settings.section` contract carries no icon field — the core reads
240
+ // only id/label/order and `navIcon(id)` falls back to the gear for every
241
+ // unknown id. Patching that core bundle is not durable: a DSH runtime
242
+ // re-extract, or any other plugin installing/removing its own patch, wipes
243
+ // it. So this plugin pins its own glyph at runtime instead.
244
+ //
245
+ // It finds its nav cell by label text and rewrites the existing <svg> in
246
+ // place, keeping the shell's element, class and box — nothing here depends
247
+ // on the shell's hashed class names, so a DSH upgrade cannot break it. A
248
+ // MutationObserver re-applies the glyph whenever the shell re-renders the
249
+ // nav and restores the gear.
250
+ //
251
+ // `glyph()` is pure and returns the markup: it runs BEFORE any DOM mutation,
252
+ // so a throwing glyph leaves the shell's own icon in place rather than
253
+ // blanking the cell.
254
+ // --------------------------------------------------------------------------
255
+ const NAV_LABEL = '鲸尾移动网关'
256
+ const NAV_ICON_MARK = 'data-mgw-nav-icon'
257
+
258
+ function navGlyph() {
259
+ return {
260
+ viewBox: '0 0 24 24',
261
+ stroke: 'currentColor',
262
+ markup: '<rect x="6" y="2" width="12" height="20" rx="2.5"></rect><path d="M10 18h4"></path>',
263
+ }
264
+ }
265
+
266
+ function pinNavGlyph(labels, mark, glyph) {
267
+ if (typeof document === 'undefined' || typeof MutationObserver === 'undefined') return
268
+ const apply = () => {
269
+ // Cheap guard: the nav only exists while the settings panel is open.
270
+ if (document.querySelector('[role="dialog"]') === null) return
271
+ const cells = document.querySelectorAll('[role="dialog"] nav button')
272
+ for (const cell of cells) {
273
+ // An <svg> contributes no text, so this is exactly the nav label.
274
+ if (labels.indexOf(cell.textContent.trim()) < 0) continue
275
+ const svg = cell.querySelector('svg')
276
+ if (svg === null || svg.getAttribute(mark) === '1') continue
277
+ let spec
278
+ try {
279
+ spec = glyph()
280
+ } catch (error) {
281
+ console.warn('[dsh-plugin-weapp-gateway] nav glyph failed; keeping the shell icon', error)
282
+ continue
283
+ }
284
+ svg.setAttribute('viewBox', spec.viewBox)
285
+ svg.setAttribute('fill', 'none')
286
+ if (spec.stroke) {
287
+ svg.setAttribute('stroke', spec.stroke)
288
+ svg.setAttribute('stroke-width', spec.strokeWidth || '1.8')
289
+ svg.setAttribute('stroke-linecap', 'round')
290
+ svg.setAttribute('stroke-linejoin', 'round')
291
+ }
292
+ svg.innerHTML = spec.markup
293
+ svg.setAttribute('aria-hidden', 'true')
294
+ svg.setAttribute(mark, '1')
295
+ }
296
+ }
297
+ apply()
298
+ // The shell re-renders the nav on ledger/locale changes; without this the
299
+ // gear would come back on the next re-render.
300
+ new MutationObserver(apply).observe(document.body, { childList: true, subtree: true })
301
+ }
302
+
303
+ // Fork: management RPC must resolve against the document base, not the
304
+ // origin root. Behind the fnOS gateway the whole WebUI is served under
305
+ // /app/deepseek-harness/fngateway/, where an absolute /mgw/... request
306
+ // hits the gateway's own router and 404s. DSH serves its own assets
307
+ // document-relative for exactly this reason.
308
+ function apiPath(path) {
309
+ let base = '/'
310
+ try { base = new URL('.', document.baseURI).pathname } catch { base = '/' }
311
+ if (!base.endsWith('/')) base += '/'
312
+ return base + String(path).replace(/^\/+/, '')
313
+ }
314
+
315
+ async function request(path, options) {
316
+ const response = await fetch(apiPath(path), { credentials: 'same-origin', ...options })
317
+ const body = await response.json().catch(() => ({}))
318
+ if (!response.ok) throw new Error(body.message || body.error || `HTTP ${response.status}`)
319
+ return body
320
+ }
321
+
322
+ function inferredUrl(wsPath) {
323
+ const scheme = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
324
+ return `${scheme}//${window.location.host}${wsPath || '/ws/mobile'}`
325
+ }
326
+
327
+ function lanPairingUrl(status) {
328
+ const urls = status?.lan?.listening && Array.isArray(status.lan.urls) ? status.lan.urls : []
329
+ return urls.find((url) => !/^ws:\/\/169\.254\./.test(url)) || urls[0] || ''
330
+ }
331
+
332
+ function pairingUrlFor(route, status) {
333
+ const lanUrl = lanPairingUrl(status)
334
+ const tunnelUrl = status.cloudflare?.enabled && status.cloudflare.publicReady === true
335
+ ? status.cloudflare.publicUrl || '' : ''
336
+ if (route === 'lan') return lanUrl
337
+ if (route === 'relay') return status.relay?.relay || ''
338
+ if (route === 'cloudflare') return tunnelUrl
339
+ const statusUrl = status.cloudflare?.enabled && status.cloudflare.publicReady !== true &&
340
+ status.publicUrl === status.cloudflare.publicUrl ? '' : status.publicUrl
341
+ return tunnelUrl || statusUrl || lanUrl || inferredUrl(status.wsPath)
342
+ }
343
+
344
+ function connectionAdvice(status, publicSetup) {
345
+ if (!status) return { detected: '正在读取网关环境…', local: '', remote: '' }
346
+ const system = status.platform === 'darwin' ? 'macOS 电脑' : status.platform === 'win32' ? 'Windows 电脑' : status.platform === 'linux' ? 'Linux 服务器' : '当前设备'
347
+ const lanReady = !!lanPairingUrl(status)
348
+ const tunnel = status.cloudflare
349
+ const tunnelReady = !!(tunnel?.enabled && tunnel.publicReady === true && tunnel.publicUrl)
350
+ const statusUrlIsUnreadyTunnel = !!(tunnel?.enabled && tunnel.publicReady !== true &&
351
+ status.publicUrl === tunnel.publicUrl)
352
+ const serverReady = status.platform === 'linux' && !!(
353
+ (publicSetup?.configured && publicSetup.publicUrl) || (!statusUrlIsUnreadyTunnel && /^wss:\/\//.test(status.publicUrl || '')))
354
+ const detected = `当前检测:${system};局域网入口${lanReady ? '已就绪' : '未就绪'};${serverReady ? '公网服务器入口已配置' : tunnelReady ? `${tunnel.mode === 'quick' ? 'Quick' : '命名'} Tunnel 已连接` : tunnel?.enabled ? (tunnel.state === 'online' ? '隧道已连接,公网入口未验证或检测失败' : 'Cloudflare Tunnel 连接中') : '外网入口未连接'}。`
355
+ const local = lanReady
356
+ ? 'DSH App 和小程序都可以通过局域网或 VPN 连接;手机与 DSH 同网时可使用局域网地址。'
357
+ : '两种客户端都可使用局域网连接;先确认局域网入口已开启并监听成功。'
358
+ let remote
359
+ if (serverReady) remote = '两种客户端在外网时都可使用已配置的公网 WSS;自动选择会同时保留局域网候选地址。'
360
+ else if (tunnelReady && tunnel.mode === 'named') remote = '两种客户端在外网时都可使用固定域名的 Cloudflare Tunnel;自动选择也会保留局域网候选地址。'
361
+ else if (tunnelReady) remote = '两种客户端在外网时都可使用 Cloudflare Quick Tunnel;地址变化后需重新配对。'
362
+ else if (status.platform === 'darwin' || status.platform === 'win32') remote = '外网使用可开启 Quick Tunnel;需要固定地址时可配置命名 Tunnel。'
363
+ else if (status.platform === 'linux') remote = '外网使用可配置 Linux 公网入口或 Cloudflare Tunnel。'
364
+ else remote = '外网连接需要可访问的 wss:// 公网地址;两种客户端都支持公网或局域网。'
365
+ return { detected, local, remote }
366
+ }
367
+
368
+ // 可信设备徽标:按手机当前连接入口标注 局域网 / 公网 / Cloudflare 外网。
369
+ // routes 来自 /mgw/devices 的实时连接统计,面板每 3 秒轮询,手机切网后
370
+ // 重连即换徽标;离线设备没有连接,不显示线路徽标。
371
+ const ROUTE_BADGES = {
372
+ lan: { label: '局域网', color: colors.success, title: '手机当前通过局域网直连(同一 Wi-Fi 或 VPN)' },
373
+ public: { label: '公网', color: 'var(--dsw-alias-link, #4176e6)', title: '手机当前通过公网入口连接(公网服务器或鲸尾中继)' },
374
+ cloudflare: { label: 'Cloudflare 外网', color: 'var(--dsw-alias-state-warning-primary, #d98324)', title: '手机当前通过 Cloudflare Tunnel 外网连接' },
375
+ }
376
+ function routeBadges(device) {
377
+ if (!device || !device.online || !Array.isArray(device.routes)) return []
378
+ return device.routes.map((route) => ROUTE_BADGES[route]).filter(Boolean)
379
+ }
380
+
381
+ function DeviceRow({ device, onRevoke, revoking }) {
382
+ const triggerRevoke = (event) => {
383
+ event.preventDefault()
384
+ event.stopPropagation()
385
+ if (!revoking) onRevoke(device)
386
+ }
387
+ return React.createElement('div', { style: styles.row },
388
+ React.createElement('div', { style: { minWidth: 0, overflow: 'hidden' } },
389
+ React.createElement('div', { style: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } },
390
+ device.displayName || device.name,
391
+ React.createElement('span', { style: styles.badge },
392
+ React.createElement('span', { style: { ...styles.dot, background: device.online ? colors.success : colors.muted } }),
393
+ device.online ? '在线' : '离线'),
394
+ routeBadges(device).map((badge) => React.createElement('span', { key: badge.label, style: styles.badge, title: badge.title },
395
+ React.createElement('span', { style: { ...styles.dot, background: badge.color } }),
396
+ badge.label))),
397
+ React.createElement('div', { style: { ...styles.muted, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', marginTop: 3 } },
398
+ device.lastSeenAt ? `最近连接:${new Date(device.lastSeenAt).toLocaleString()}` : '尚未连接')),
399
+ React.createElement('button', {
400
+ type: 'button',
401
+ disabled: revoking,
402
+ style: {
403
+ ...styles.button,
404
+ color: colors.danger,
405
+ background: 'transparent',
406
+ borderColor: 'rgba(220,76,100,.55)',
407
+ flexShrink: 0,
408
+ minWidth: 54,
409
+ opacity: revoking ? .6 : 1,
410
+ },
411
+ title: `吊销 ${device.displayName || device.name}`,
412
+ // Pointer-up is more reliable than click inside the management dialog on
413
+ // touch devices. The click handler remains for keyboard activation.
414
+ onPointerUp: triggerRevoke,
415
+ onClick: (event) => {
416
+ if (event.detail === 0) triggerRevoke(event)
417
+ },
418
+ }, revoking ? '吊销中…' : '吊销'))
419
+ }
420
+
421
+ function DevicePanel() {
422
+ const [activeSection, setActiveSection] = React.useState('general')
423
+ const [devices, setDevices] = React.useState(null)
424
+ const [showAllDevices, setShowAllDevices] = React.useState(false)
425
+ const [status, setStatus] = React.useState(null)
426
+ const [dismissedNotice, setDismissedNotice] = React.useState(() => dismissedRestartInstance)
427
+ const [publicUrl, setPublicUrl] = React.useState('')
428
+ const [pairingRoute, setPairingRoute] = React.useState('auto')
429
+ const [connectionHelpOpen, setConnectionHelpOpen] = React.useState(false)
430
+ const [toolsOpen, setToolsOpen] = React.useState(false)
431
+ const [toolBusy, setToolBusy] = React.useState(false)
432
+ const [toolNotice, setToolNotice] = React.useState('')
433
+ const stoppedRef = React.useRef(false)
434
+ const [publicIp, setPublicIp] = React.useState('')
435
+ const [publicSetup, setPublicSetup] = React.useState(null)
436
+ const [publicSetupBusy, setPublicSetupBusy] = React.useState(false)
437
+ const [cloudflareHost, setCloudflareHost] = React.useState('')
438
+ const [cloudflareToken, setCloudflareToken] = React.useState('')
439
+ const [cloudflareMode, setCloudflareMode] = React.useState('quick')
440
+ const [cloudflareBusy, setCloudflareBusy] = React.useState(false)
441
+ const [qr, setQr] = React.useState(null)
442
+ const pairingDialogRef = React.useRef(null)
443
+ const navRef = React.useRef(null)
444
+ // Fork: id of the pairing code currently shown as a QR. The panel polls
445
+ // the server's pending list and closes the dialog as soon as this id is
446
+ // gone — a successful scan consumes the code immediately.
447
+ const pairingIdRef = React.useRef(null)
448
+ const [pairingClosing, setPairingClosing] = React.useState(false)
449
+ const pairingCloseTimer = React.useRef(null)
450
+ const closePairingDialog = () => {
451
+ pairingIdRef.current = null
452
+ setCopyNotice(null)
453
+ if (pairingCloseTimer.current !== null) return
454
+ if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
455
+ setQr(null)
456
+ return
457
+ }
458
+ setPairingClosing(true)
459
+ pairingCloseTimer.current = window.setTimeout(() => {
460
+ pairingCloseTimer.current = null
461
+ setQr(null)
462
+ setPairingClosing(false)
463
+ }, 180)
464
+ }
465
+ React.useEffect(() => {
466
+ setPairingClosing(false)
467
+ return () => {
468
+ if (pairingCloseTimer.current !== null) {
469
+ window.clearTimeout(pairingCloseTimer.current)
470
+ pairingCloseTimer.current = null
471
+ }
472
+ }
473
+ }, [qr])
474
+ const [error, setError] = React.useState(null)
475
+ const [busy, setBusy] = React.useState(false)
476
+ const [updateInfo, setUpdateInfo] = React.useState(null)
477
+ const [updateChecking, setUpdateChecking] = React.useState(true)
478
+ const [updateBusy, setUpdateBusy] = React.useState(false)
479
+ const [updateNotice, setUpdateNotice] = React.useState('')
480
+ const [updateError, setUpdateError] = React.useState('')
481
+ const [refreshing, setRefreshing] = React.useState(false)
482
+ const [refreshNotice, setRefreshNotice] = React.useState(null)
483
+ const [pairingTokenCopied, setPairingTokenCopied] = React.useState(false)
484
+ // Copy feedback that must live inside the QR dialog: the panel's error
485
+ // banner is behind the modal, so a clipboard failure looked like "the
486
+ // button does nothing".
487
+ const [copyNotice, setCopyNotice] = React.useState(null)
488
+ const [deviceNotice, setDeviceNotice] = React.useState(null)
489
+ const [deviceNoticeError, setDeviceNoticeError] = React.useState(false)
490
+ const [revokingIds, setRevokingIds] = React.useState(() => new Set())
491
+ const revokingIdsRef = React.useRef(new Set())
492
+ const automaticUrlRef = React.useRef('')
493
+ const pairingRouteRef = React.useRef('auto')
494
+ const pairingRouteSelectedRef = React.useRef(false)
495
+ const cloudflareModeLoadedRef = React.useRef(false)
496
+
497
+ const refresh = React.useCallback(async () => {
498
+ try {
499
+ const [deviceData, statusData] = await Promise.all([
500
+ request('/mgw/devices'),
501
+ request('/mgw/status'),
502
+ ])
503
+ const nextDevices = deviceData.devices || []
504
+ // Keep existing DOM rows alive when polling returns identical data.
505
+ // Replacing them every three seconds can swallow a pointer/click that
506
+ // started on the old button and ended after React replaced the row.
507
+ if (revokingIdsRef.current.size === 0) {
508
+ setDevices((current) => JSON.stringify(current) === JSON.stringify(nextDevices) ? current : nextDevices)
509
+ }
510
+ setStatus((current) => JSON.stringify(current) === JSON.stringify(statusData) ? current : statusData)
511
+ // Fork: the QR dialog closes itself once the code is consumed. The
512
+ // server drops a redeemed code from its pending list, so the poll
513
+ // sees our id disappear and dismisses the dialog (with animation).
514
+ if (pairingIdRef.current !== null && Array.isArray(statusData.pendingPairings)
515
+ && !statusData.pendingPairings.includes(pairingIdRef.current)) {
516
+ pairingIdRef.current = null
517
+ setQr(null)
518
+ }
519
+ if (statusData.cloudflare && statusData.cloudflare.hostname) {
520
+ setCloudflareHost((current) => current || statusData.cloudflare.hostname)
521
+ }
522
+ if (statusData.cloudflare && !cloudflareModeLoadedRef.current) {
523
+ cloudflareModeLoadedRef.current = true
524
+ setCloudflareMode(statusData.cloudflare.mode || 'quick')
525
+ }
526
+ // Adopt the saved legacy mode only until the operator makes a choice;
527
+ // polling must not overwrite an in-progress route change.
528
+ if (!pairingRouteSelectedRef.current) {
529
+ const savedRoute = statusData.pairingMode === 'relay' ? 'relay' : 'auto'
530
+ pairingRouteRef.current = savedRoute
531
+ setPairingRoute(savedRoute)
532
+ }
533
+ if (pairingRouteRef.current !== 'custom') {
534
+ const preferredUrl = pairingUrlFor(pairingRouteRef.current, statusData)
535
+ if (automaticUrlRef.current && preferredUrl !== automaticUrlRef.current) setQr(null)
536
+ automaticUrlRef.current = preferredUrl
537
+ setPublicUrl(preferredUrl)
538
+ }
539
+ return true
540
+ } catch (cause) {
541
+ setError(cause.message)
542
+ return false
543
+ }
544
+ }, [])
545
+
546
+ const manualRefresh = async () => {
547
+ if (refreshing) return
548
+ setRefreshing(true)
549
+ setRefreshNotice(null)
550
+ const succeeded = await refresh()
551
+ setRefreshing(false)
552
+ if (succeeded) {
553
+ setError(null)
554
+ setRefreshNotice(`已刷新 · ${new Date().toLocaleTimeString()}`)
555
+ window.setTimeout(() => setRefreshNotice(null), 2200)
556
+ }
557
+ }
558
+
559
+ const checkForPluginUpdate = async () => {
560
+ setUpdateChecking(true)
561
+ setUpdateError('')
562
+ try {
563
+ setUpdateInfo(await request('/mgw/update-check'))
564
+ } catch (cause) {
565
+ setUpdateError(cause.message)
566
+ } finally {
567
+ setUpdateChecking(false)
568
+ }
569
+ }
570
+
571
+ const upgradePlugin = async () => {
572
+ if (updateBusy || !updateInfo?.updateAvailable) return
573
+ setUpdateBusy(true)
574
+ setUpdateNotice('')
575
+ setUpdateError('')
576
+ try {
577
+ const result = await request('/mgw/update', { method: 'POST' })
578
+ if (result.reason === 'plugin-manager-unavailable') {
579
+ setUpdateNotice(`当前 DSH 不支持面板内更新。请在 Terminal 执行:${result.command}`)
580
+ } else if (result.reason === 'already-current') {
581
+ setUpdateInfo(result)
582
+ setUpdateNotice('插件已是最新版本。')
583
+ } else if (result.installed) {
584
+ const application = result.installation?.application
585
+ const pendingBuilds = result.installation?.pendingBuilds
586
+ if (Array.isArray(pendingBuilds) && pendingBuilds.length > 0) {
587
+ setUpdateNotice(`更新等待构建脚本审核(${pendingBuilds.join('、')});未自动批准。请到 DSH 插件管理中审核。`)
588
+ } else if (application === 'restart-required') {
589
+ setUpdateInfo({ ...result, currentVersion: result.latestVersion, updateAvailable: false })
590
+ setUpdateNotice(`已安装 v${result.latestVersion},需要重启 DSH 后生效。`)
591
+ } else if (application === 'failed' || application === 'cancelled' || application === 'refused') {
592
+ const installError = result.installation?.error
593
+ const detail = result.installation?.errorMessage
594
+ || (typeof installError === 'string' ? installError : '')
595
+ || (typeof installError?.message === 'string' ? installError.message : '')
596
+ || (typeof installError?.code === 'string' ? installError.code : '')
597
+ || '请在 DSH 插件管理中查看安装详情。'
598
+ setUpdateNotice(`安装未完成:${application}(${detail})`)
599
+ } else {
600
+ setUpdateInfo({ ...result, currentVersion: result.latestVersion, updateAvailable: false })
601
+ setUpdateNotice(`已安装 v${result.latestVersion}。如界面尚未更新,请重启 DSH。`)
602
+ }
603
+ }
604
+ } catch (cause) {
605
+ setUpdateError(cause.message)
606
+ } finally {
607
+ setUpdateBusy(false)
608
+ }
609
+ }
610
+
611
+ const runTool = async (tool) => {
612
+ if (toolBusy) return
613
+ setToolsOpen(false)
614
+ setToolBusy(true)
615
+ setToolNotice('')
616
+ setError(null)
617
+ try {
618
+ const oldPid = status?.webPid
619
+ await request(`/mgw/tools/${tool}`, { method: 'POST' })
620
+ if (tool === 'stop-web') {
621
+ stoppedRef.current = true
622
+ setToolNotice('DSH Web 已收到停止指令。需要时可在 Terminal 运行 dsh web 重新启动。')
623
+ return
624
+ }
625
+ if (tool === 'restart-web') {
626
+ setToolNotice('正在重启 DSH Web,当前连接会短暂中断…')
627
+ const deadline = Date.now() + 60_000
628
+ while (Date.now() < deadline) {
629
+ await new Promise((resolve) => window.setTimeout(resolve, 700))
630
+ try {
631
+ const next = await request('/mgw/status')
632
+ if (next.webPid && next.webPid !== oldPid) {
633
+ window.location.reload()
634
+ return
635
+ }
636
+ } catch { /* old process is shutting down */ }
637
+ }
638
+ throw new Error('DSH Web 重启超时,请检查 /tmp/mobile-gateway.log')
639
+ }
640
+ } catch (cause) {
641
+ setError(cause.message)
642
+ setToolNotice('')
643
+ } finally {
644
+ setToolBusy(false)
645
+ }
646
+ }
647
+
648
+ // Fork: dsh-settings-mobile-nav collapses the first <nav> of any settings
649
+ // dialog on narrow viewports (it assumes the settings rail). Our dialog nav
650
+ // is that first nav, so tapping a section used to hide the whole strip and
651
+ // leave a lone ☰ button. Never intercept the click itself — React delegates
652
+ // onClick at the document root, so stopPropagation in the capture phase
653
+ // would kill our own handler. Instead, make the nav un-collapsible: a
654
+ // MutationObserver reverts the display/aria-hidden edits (and drops the
655
+ // stray expand button) the moment they land.
656
+ React.useEffect(() => {
657
+ const nav = navRef.current
658
+ if (nav === null || typeof MutationObserver === 'undefined') return undefined
659
+ const restore = () => {
660
+ if (nav.style.display === 'none') nav.style.display = ''
661
+ if (nav.getAttribute('aria-hidden') === 'true') nav.removeAttribute('aria-hidden')
662
+ const stray = nav.closest('[role="dialog"]')?.querySelector('[data-dsh-settings-nav-expand]')
663
+ if (stray !== null && stray !== undefined) stray.remove()
664
+ }
665
+ const observer = new MutationObserver(restore)
666
+ observer.observe(nav, { attributes: true, attributeFilter: ['style', 'aria-hidden'] })
667
+ const dialog = nav.closest('[role="dialog"]')
668
+ if (dialog !== null) observer.observe(dialog, { childList: true })
669
+ return () => observer.disconnect()
670
+ }, [])
671
+
672
+ React.useEffect(() => {
673
+ let active = true
674
+ refresh()
675
+ request('/mgw/update-check').then((data) => {
676
+ if (active) setUpdateInfo(data)
677
+ }).catch((cause) => {
678
+ if (active) setUpdateError(cause.message)
679
+ }).finally(() => {
680
+ if (active) setUpdateChecking(false)
681
+ })
682
+ request('/mgw/public-setup').then((data) => {
683
+ if (!active) return
684
+ setPublicSetup(data)
685
+ if (data.publicUrl) {
686
+ const match = /^wss:\/\/([^/]+)\/ws\/mobile$/.exec(data.publicUrl)
687
+ if (match) setPublicIp(match[1])
688
+ }
689
+ }).catch((cause) => active && setPublicSetup({ installed: false, configured: false, error: cause.message }))
690
+ const timer = window.setInterval(() => { if (!stoppedRef.current) refresh() }, 3000)
691
+ return () => { active = false; window.clearInterval(timer) }
692
+ }, [refresh])
693
+
694
+ React.useEffect(() => {
695
+ if (!qr) return
696
+ const previousFocus = document.activeElement
697
+ pairingDialogRef.current?.querySelector('button')?.focus()
698
+ return () => previousFocus?.focus()
699
+ }, [qr])
700
+
701
+ const changePairingMode = async (mode) => {
702
+ setBusy(true)
703
+ setError(null)
704
+ try {
705
+ const data = await request('/mgw/mode', {
706
+ method: 'POST',
707
+ headers: { 'Content-Type': 'application/json' },
708
+ body: JSON.stringify({ mode }),
709
+ })
710
+ setStatus((current) => ({ ...(current || {}), pairingMode: data.pairingMode, relay: data.relay }))
711
+ } catch (cause) {
712
+ setError(cause.message)
713
+ } finally {
714
+ setBusy(false)
715
+ }
716
+ }
717
+
718
+ const choosePairingRoute = (route) => {
719
+ setQr(null)
720
+ const previousRoute = pairingRouteRef.current
721
+ pairingRouteSelectedRef.current = true
722
+ pairingRouteRef.current = route
723
+ setPairingRoute(route)
724
+ if (route === 'custom') {
725
+ automaticUrlRef.current = ''
726
+ } else if (status) {
727
+ const nextUrl = pairingUrlFor(route, status)
728
+ automaticUrlRef.current = nextUrl
729
+ setPublicUrl(nextUrl)
730
+ }
731
+ const targetMode = route === 'relay' ? 'relay' : 'direct'
732
+ if (status && status.pairingMode !== targetMode &&
733
+ (route === 'relay' || previousRoute === 'relay')) {
734
+ void changePairingMode(targetMode)
735
+ }
736
+ }
737
+
738
+ const configurePublicAccess = async () => {
739
+ if (publicSetupBusy) return
740
+ setPublicSetupBusy(true)
741
+ setError(null)
742
+ try {
743
+ const data = await request('/mgw/public-setup', {
744
+ method: 'POST',
745
+ headers: { 'Content-Type': 'application/json' },
746
+ body: JSON.stringify({ publicIp }),
747
+ })
748
+ setPublicSetup(data)
749
+ if (data.publicUrl && pairingRouteRef.current === 'auto') {
750
+ automaticUrlRef.current = data.publicUrl
751
+ setPublicUrl(data.publicUrl)
752
+ }
753
+ } catch (cause) {
754
+ setError(cause.message)
755
+ } finally {
756
+ setPublicSetupBusy(false)
757
+ }
758
+ }
759
+
760
+ const configureCloudflare = async (enabled, mode = cloudflareMode) => {
761
+ if (cloudflareBusy) return
762
+ setCloudflareBusy(true)
763
+ setError(null)
764
+ try {
765
+ const data = await request('/mgw/cloudflare', {
766
+ method: 'POST',
767
+ headers: { 'Content-Type': 'application/json' },
768
+ body: JSON.stringify({ enabled, ...(enabled ? {
769
+ mode,
770
+ ...(mode === 'named' ? { hostname: cloudflareHost, token: cloudflareToken } : {}),
771
+ } : {}) }),
772
+ })
773
+ setCloudflareToken('')
774
+ setStatus((current) => ({ ...(current || {}), cloudflare: data, gatewayEnabled: data.gatewayEnabled, gatewayMode: data.gatewayMode, publicUrl: data.publicUrl || null }))
775
+ await refresh()
776
+ } catch (cause) {
777
+ setError(cause.message)
778
+ } finally {
779
+ setCloudflareBusy(false)
780
+ }
781
+ }
782
+
783
+ const checkCloudflare = async () => {
784
+ if (cloudflareBusy) return
785
+ setCloudflareBusy(true)
786
+ setError(null)
787
+ try {
788
+ const data = await request('/mgw/cloudflare/check', { method: 'POST' })
789
+ setStatus((current) => ({ ...(current || {}), cloudflare: data }))
790
+ } catch (cause) { setError(cause.message) }
791
+ finally { setCloudflareBusy(false) }
792
+ }
793
+
794
+ const restartCloudflare = async () => {
795
+ if (cloudflareBusy) return
796
+ setCloudflareBusy(true)
797
+ setError(null)
798
+ try {
799
+ const data = await request('/mgw/cloudflare/restart', { method: 'POST' })
800
+ if (data.mode === 'quick') setQr(null)
801
+ setStatus((current) => ({ ...(current || {}), cloudflare: data }))
802
+ await refresh()
803
+ } catch (cause) {
804
+ setError(cause.message)
805
+ } finally {
806
+ setCloudflareBusy(false)
807
+ }
808
+ }
809
+
810
+ const createPairing = async (endpoint) => request('/mgw/pair', {
811
+ method: 'POST',
812
+ headers: { 'Content-Type': 'application/json' },
813
+ body: JSON.stringify({
814
+ publicUrl: endpoint,
815
+ route: pairingRoute,
816
+ lanUrl: lanPairingUrl(status),
817
+ }),
818
+ })
819
+
820
+ const pair = async () => {
821
+ setBusy(true)
822
+ setError(null)
823
+ setPairingTokenCopied(false)
824
+ try {
825
+ if (pairingRoute === 'relay' && status?.pairingMode !== 'relay') {
826
+ const modeData = await request('/mgw/mode', {
827
+ method: 'POST',
828
+ headers: { 'Content-Type': 'application/json' },
829
+ body: JSON.stringify({ mode: 'relay' }),
830
+ })
831
+ setStatus((current) => ({ ...(current || {}), pairingMode: modeData.pairingMode, relay: modeData.relay }))
832
+ }
833
+ const data = await createPairing(publicUrl)
834
+ pairingIdRef.current = data.pairing?.id || null
835
+ setQr(data)
836
+ } catch (cause) {
837
+ setError(cause.message)
838
+ } finally {
839
+ setBusy(false)
840
+ }
841
+ }
842
+
843
+ // Fork: the pairing payload must be copyable wherever the WebUI is
844
+ // opened. navigator.clipboard only exists in a secure context, and the
845
+ // fnOS gateway embedding is plain http — there the async API is simply
846
+ // missing. Fall back to the deprecated-but-universal execCommand path
847
+ // before giving up, and report failures inside the QR dialog (the
848
+ // panel's error banner sits behind the modal and is invisible).
849
+ const writeClipboard = (text) => {
850
+ if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
851
+ return navigator.clipboard.writeText(text)
852
+ }
853
+ return new Promise((resolve, reject) => {
854
+ const holder = document.createElement('textarea')
855
+ holder.value = text
856
+ holder.setAttribute('readonly', '')
857
+ holder.style.position = 'fixed'
858
+ holder.style.top = '-1000px'
859
+ holder.style.opacity = '0'
860
+ document.body.appendChild(holder)
861
+ holder.select()
862
+ holder.setSelectionRange(0, text.length)
863
+ let copied = false
864
+ try {
865
+ copied = document.execCommand('copy')
866
+ } catch (error) {
867
+ copied = false
868
+ }
869
+ document.body.removeChild(holder)
870
+ if (copied) resolve()
871
+ else reject(new Error('浏览器拒绝写入剪贴板'))
872
+ })
873
+ }
874
+
875
+ const copyPairingText = async () => {
876
+ if (!qr || !qr.qrPayload) return
877
+ try {
878
+ await writeClipboard(qr.qrPayload)
879
+ setError(null)
880
+ setCopyNotice(null)
881
+ setPairingTokenCopied(true)
882
+ window.setTimeout(() => setPairingTokenCopied(false), 2200)
883
+ } catch (cause) {
884
+ setPairingTokenCopied(false)
885
+ setCopyNotice(`${cause.message || '复制失败'},请选中上面文本后按 Ctrl/Cmd+C`)
886
+ window.setTimeout(() => setCopyNotice(null), 6000)
887
+ // Leave the payload selected so the manual copy is one keystroke away.
888
+ const area = pairingDialogRef.current && pairingDialogRef.current.querySelector('textarea')
889
+ if (area) { area.focus(); area.select() }
890
+ }
891
+ }
892
+
893
+ const changeGatewayMode = async (mode) => {
894
+ setBusy(true)
895
+ setError(null)
896
+ try {
897
+ const data = await request('/mgw/gateway', {
898
+ method: 'POST',
899
+ headers: { 'Content-Type': 'application/json' },
900
+ body: JSON.stringify({ mode }),
901
+ })
902
+ setStatus((current) => ({ ...(current || {}), ...data }))
903
+ if (mode === 'disabled') setQr(null)
904
+ } catch (cause) {
905
+ setError(cause.message)
906
+ } finally {
907
+ setBusy(false)
908
+ }
909
+ }
910
+
911
+ const toggleAuth = async () => {
912
+ const enabled = !(status && status.requireAuth)
913
+ if (!enabled && !window.confirm('关闭设备鉴权后,任何能访问移动网关的人都可以控制 DSH。此选项仅限 Debug 阶段使用,确定继续吗?')) return
914
+ setBusy(true)
915
+ setError(null)
916
+ try {
917
+ const data = await request('/mgw/auth', {
918
+ method: 'POST',
919
+ headers: { 'Content-Type': 'application/json' },
920
+ body: JSON.stringify({ enabled }),
921
+ })
922
+ setStatus((current) => ({ ...(current || {}), requireAuth: data.requireAuth }))
923
+ } catch (cause) {
924
+ setError(cause.message)
925
+ } finally {
926
+ setBusy(false)
927
+ }
928
+ }
929
+
930
+ const revoke = async (device) => {
931
+ if (revokingIdsRef.current.has(device.id)) return
932
+ setDeviceNotice(null)
933
+ setDeviceNoticeError(false)
934
+ setError(null)
935
+ revokingIdsRef.current.add(device.id)
936
+ setRevokingIds((current) => new Set(current).add(device.id))
937
+ try {
938
+ await request(`/mgw/devices/${encodeURIComponent(device.id)}/revoke`, { method: 'POST' })
939
+ setDevices((current) => Array.isArray(current) ? current.filter((item) => item.id !== device.id) : current)
940
+ setDeviceNotice(`已吊销 ${device.displayName || device.name}`)
941
+ window.setTimeout(() => setDeviceNotice(null), 2200)
942
+ } catch (cause) {
943
+ setDeviceNoticeError(true)
944
+ setDeviceNotice(`吊销失败:${cause.message}`)
945
+ setError(cause.message)
946
+ } finally {
947
+ revokingIdsRef.current.delete(device.id)
948
+ setRevokingIds((current) => {
949
+ const next = new Set(current)
950
+ next.delete(device.id)
951
+ return next
952
+ })
953
+ await refresh()
954
+ }
955
+ }
956
+
957
+ const restartNoticeInstance = status?.gatewayInstanceId || (status?.webPid ? String(status.webPid) : null)
958
+ const dismissRestartNotice = () => {
959
+ dismissedRestartInstance = restartNoticeInstance
960
+ setDismissedNotice(restartNoticeInstance)
961
+ try { window.localStorage.setItem(restartNoticeStorageKey, restartNoticeInstance) } catch { /* keep in-memory dismissal */ }
962
+ }
963
+
964
+ const onlineDevices = (devices || []).filter((device) => device.online)
965
+ const offlineDevices = (devices || []).filter((device) => !device.online)
966
+ const visibleDevices = showAllDevices ? [...onlineDevices, ...offlineDevices] : onlineDevices
967
+
968
+ // The same v2 QR is native-app compatible; mini-program-only public
969
+ // routing is carried in an optional field that older apps ignore.
970
+ const relayInfo = status && status.relay ? status.relay : null
971
+ const relayConnector = status && status.relayConnector ? status.relayConnector : null
972
+ const effectiveRoute = pairingRoute
973
+ const cloudflareReady = !!(status?.cloudflare?.enabled && status.cloudflare.publicReady === true && status.cloudflare.publicUrl)
974
+
975
+ const advice = connectionAdvice(status, publicSetup)
976
+ const helpLine = (name, description) => React.createElement('div', { style: { marginTop: 7 } },
977
+ React.createElement('strong', null, name), ':', description)
978
+
979
+ return React.createElement('div', { style: styles.backdrop, onMouseDown: () => setOpen(false) },
980
+ qr ? React.createElement('div', { style: { ...styles.backdrop, zIndex: 1201 },
981
+ onMouseDown: (event) => { event.stopPropagation(); closePairingDialog() } },
982
+ React.createElement('div', { className: 'mgw-pairing-dialog', 'data-closing': pairingClosing, ref: pairingDialogRef, role: 'dialog', 'aria-modal': true, 'aria-label': '设备配对二维码', tabIndex: -1,
983
+ style: { ...styles.panel, width: 'min(520px, 100%)', height: 'auto', overflowY: 'auto', scrollbarWidth: 'none' },
984
+ onMouseDown: (event) => event.stopPropagation(),
985
+ onKeyDown: (event) => {
986
+ if (event.key === 'Escape') { event.stopPropagation(); closePairingDialog() }
987
+ if (event.key === 'Tab') {
988
+ const items = [...event.currentTarget.querySelectorAll('button, textarea')]
989
+ const first = items[0], last = items[items.length - 1]
990
+ if (event.shiftKey && (document.activeElement === first || document.activeElement === event.currentTarget)) { event.preventDefault(); last?.focus() }
991
+ else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first?.focus() }
992
+ }
993
+ } },
994
+ React.createElement('div', { style: { display: 'flex', justifyContent: 'flex-end' } },
995
+ React.createElement('button', { type: 'button', style: { ...styles.button, ...styles.headerButton }, 'aria-label': '关闭配对窗口', onClick: closePairingDialog }, '✕')),
996
+ React.createElement('section', { style: { textAlign: 'center' } },
997
+ React.createElement('strong', null, qr.payload?.version === 3 && qr.payload?.mode === 'relay'
998
+ ? '使用鲸尾小程序扫码(此二维码仅适用于小程序)'
999
+ : '使用 DSH App 或鲸尾小程序扫码'),
1000
+ React.createElement('img', { style: styles.qr, src: `data:image/svg+xml;charset=utf-8,${encodeURIComponent(qr.svg)}`, alt: '一次性设备配对二维码' }),
1001
+ qr.payload?.version === 3 && qr.payload?.mode === 'relay'
1002
+ ? React.createElement('p', { style: { ...styles.muted, textAlign: 'left' } }, '这是小程序专用的鲸尾公网中继二维码,DSH App 不能使用。需要同时配对 DSH App 和小程序时,请改选“自动选择”。')
1003
+ : qr.payload?.miniProgramRoute?.mode === 'direct'
1004
+ ? React.createElement('p', { style: { ...styles.muted, textAlign: 'left' } }, '此二维码为 DSH App 和小程序提供公网与局域网候选地址;客户端会自动尝试可达线路。')
1005
+ : qr.payload?.miniProgramRoute?.mode === 'relay'
1006
+ ? React.createElement('p', { style: { ...styles.muted, textAlign: 'left' } }, '当前没有可用公网 WSS:DSH App 使用局域网,小程序使用鲸尾公网中继。选择“局域网直连”时,两端都直接使用局域网。')
1007
+ : React.createElement('p', { style: { ...styles.muted, textAlign: 'left' } }, '此二维码含当前可用的连接地址;DSH App 和小程序均可通过公网或局域网连接。'),
1008
+ React.createElement('label', { style: { ...styles.label, textAlign: 'left' } }, 'Base64URL 配对字符串'),
1009
+ React.createElement('textarea', { style: styles.pairingText, value: qr.qrPayload, readOnly: true, spellCheck: false, onFocus: (event) => event.target.select() }),
1010
+ 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'),
1011
+ pairingTokenCopied ? React.createElement('div', { style: { ...styles.muted, color: colors.success, marginBottom: 8 } }, '已复制到剪贴板') : null,
1012
+ copyNotice ? React.createElement('div', { role: 'alert', style: { ...styles.muted, color: colors.danger, marginBottom: 8 } }, copyNotice) : null,
1013
+ React.createElement('div', { style: styles.muted }, `有效期至 ${new Date(qr.pairing.expiresAt).toLocaleTimeString()};扫码成功后此二维码立即失效。`)))) : null,
1014
+ 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': '鲸尾移动网关管理' },
1015
+ React.createElement('div', { style: styles.header },
1016
+ React.createElement('div', null,
1017
+ React.createElement('h2', { style: styles.title }, '鲸尾移动网关'),
1018
+ React.createElement('div', { style: styles.muted }, !status ? '正在加载网关状态…' : status.gatewayEnabled ? `移动网关已开启 · ${status.requireAuth ? '设备鉴权已开启' : '本机设备鉴权已关闭'}` : '移动网关已关闭 · 普通 WebUI 模式')),
1019
+ React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 6 } },
1020
+ React.createElement('div', { style: { position: 'relative' }, onMouseDown: (event) => event.stopPropagation() },
1021
+ React.createElement('button', {
1022
+ type: 'button', style: { ...styles.button, ...styles.headerButton, borderRadius: '50%' }, title: '工具', 'aria-label': '工具',
1023
+ 'aria-haspopup': 'menu', 'aria-expanded': toolsOpen,
1024
+ onClick: () => setToolsOpen((value) => !value),
1025
+ }, 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 },
1026
+ 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' }),
1027
+ React.createElement('circle', { cx: 12, cy: 12.7, r: 3.1 }))),
1028
+ toolsOpen ? React.createElement('div', { style: styles.toolsMenu, role: 'menu', 'aria-label': '网关工具' },
1029
+ React.createElement('button', {
1030
+ type: 'button', role: 'menuitem', disabled: toolBusy || stoppedRef.current || !status?.tools?.restartWeb,
1031
+ style: { ...styles.toolsItem, opacity: status?.tools?.restartWeb ? 1 : .5 },
1032
+ onClick: () => runTool('restart-web'),
1033
+ }, '重启当前网关',
1034
+ React.createElement('span', { style: { ...styles.muted, display: 'block', marginTop: 2 } }, '结束当前进程并重新启动 DSH Web')),
1035
+ React.createElement('button', {
1036
+ type: 'button', role: 'menuitem', disabled: toolBusy || stoppedRef.current || !status?.tools?.stopWeb,
1037
+ style: { ...styles.toolsItem, color: colors.danger, opacity: status?.tools?.stopWeb ? 1 : .5 },
1038
+ onClick: () => runTool('stop-web'),
1039
+ }, '停止 DSH Web',
1040
+ React.createElement('span', { style: { ...styles.muted, display: 'block', marginTop: 2 } }, '结束后台进程,所有连接将断开')))
1041
+ : null),
1042
+ React.createElement('button', { style: { ...styles.button, ...styles.headerButton }, onClick: () => setOpen(false), 'aria-label': '关闭' },
1043
+ React.createElement('svg', { width: 20, height: 20, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 2.2, strokeLinecap: 'round', 'aria-hidden': true },
1044
+ React.createElement('path', { d: 'M6 6l12 12M18 6L6 18' }))))),
1045
+ React.createElement('div', { className: 'mgw-body' },
1046
+ React.createElement('nav', { ref: navRef, className: 'mgw-nav', 'aria-label': '鲸尾移动网关设置分组' },
1047
+ [['general', '通用设置'], ['pairing', '连接与配对'], ['devices', '可信设备']].map(([id, label]) =>
1048
+ React.createElement('button', { key: id, type: 'button', 'aria-current': activeSection === id ? 'page' : undefined,
1049
+ onClick: () => { setActiveSection(id); setConnectionHelpOpen(false); setToolsOpen(false) } }, label))),
1050
+ React.createElement('div', { className: 'mgw-content', key: activeSection },
1051
+ 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' },
1052
+ React.createElement('button', { type: 'button', 'aria-label': '关闭重启提醒', title: '关闭提醒',
1053
+ style: { ...styles.button, position: 'absolute', right: 8, top: 8, border: 0, width: 24, height: 24, padding: 0, color: colors.muted },
1054
+ onClick: dismissRestartNotice }, '✕'),
1055
+ React.createElement('strong', null, '若安装或更新后连接异常,请重启应用'),
1056
+ React.createElement('div', { style: { color: colors.muted, marginTop: 4 } },
1057
+ '完全退出并重启 APP/Desktop;Web UI 请重启 DSH Web 服务。'),
1058
+ React.createElement('div', { style: { color: colors.muted, marginTop: 4 } },
1059
+ '端口仍被占用时,请关闭其他 Harness 实例。')) : null,
1060
+ toolNotice ? React.createElement('div', { style: { ...styles.muted, marginBottom: 10 } }, toolNotice) : null,
1061
+ error ? React.createElement('div', { style: styles.error }, error) : null,
1062
+ React.createElement('div', { hidden: activeSection !== 'general' },
1063
+ React.createElement('section', { style: styles.card },
1064
+ React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 14, alignItems: 'center' } },
1065
+ React.createElement('div', null,
1066
+ React.createElement('strong', null, '网关运行模式'),
1067
+ React.createElement('div', { style: { ...styles.muted, marginTop: 4 } }, status && status.gatewayEnabled
1068
+ ? status.gatewayMode === 'persistent'
1069
+ ? '重启后保持开启'
1070
+ : status.waitExpiresAt
1071
+ ? `等待可信设备连接,约 ${Math.max(1, Math.ceil((status.waitExpiresAt - Date.now()) / 60000))} 分钟后自动关闭`
1072
+ : '设备已连接过,本次运行保持开启;重启后重新计时'
1073
+ : '不接受移动设备连接')),
1074
+ React.createElement('span', { style: { position: 'relative', display: 'inline-flex', flexShrink: 0 } },
1075
+ React.createElement(GatewaySelect, {
1076
+ style: { ...styles.input, width: 'auto', marginBottom: 0, padding: '8px 40px 8px 12px', appearance: 'none', WebkitAppearance: 'none' },
1077
+ 'aria-label': '网关运行模式',
1078
+ value: status ? status.gatewayMode || (status.gatewayEnabled ? 'temporary' : 'disabled') : 'disabled',
1079
+ disabled: busy || !status,
1080
+ onChange: (event) => changeGatewayMode(event.target.value),
1081
+ },
1082
+ React.createElement('option', { value: 'disabled' }, '关闭'),
1083
+ React.createElement('option', { value: 'temporary' }, '临时开启'),
1084
+ React.createElement('option', { value: 'persistent' }, '常驻开启')),
1085
+ )),
1086
+ status && status.gatewayId ? React.createElement('div', { style: { ...styles.muted, marginTop: 12, overflowWrap: 'anywhere' } },
1087
+ status.gatewayName) : null),
1088
+ React.createElement('section', { style: styles.card },
1089
+ React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 14, alignItems: 'center' } },
1090
+ React.createElement('div', null,
1091
+ React.createElement('strong', null, '设备鉴权'),
1092
+ React.createElement('div', { style: { ...styles.muted, marginTop: 4 } }, status && status.requireAuth ? '已开启,仅允许可信设备连接' : '已关闭,仅影响本机 Debug 入口')),
1093
+ React.createElement('label', { style: { ...styles.switch, opacity: busy || !status ? .55 : 1 }, title: status && status.requireAuth ? '关闭设备鉴权' : '开启设备鉴权' },
1094
+ React.createElement('input', {
1095
+ type: 'checkbox',
1096
+ role: 'switch',
1097
+ 'aria-label': '设备鉴权',
1098
+ 'aria-checked': !!(status && status.requireAuth),
1099
+ checked: !!(status && status.requireAuth),
1100
+ disabled: busy || !status,
1101
+ onChange: toggleAuth,
1102
+ style: styles.switchInput,
1103
+ }),
1104
+ React.createElement('span', { style: { ...styles.switchTrack, background: status && status.requireAuth ? colors.success : colors.danger } }),
1105
+ React.createElement('span', { style: { ...styles.switchKnob, left: status && status.requireAuth ? 21 : 3 } }))),
1106
+ status && !status.requireAuth
1107
+ ? React.createElement('p', { style: { ...styles.error, margin: '12px 0 0' } }, 'Debug 模式:本机 DSH 入口将跳过设备凭证校验;独立局域网入口仍强制鉴权。')
1108
+ : null),
1109
+ React.createElement('section', { style: styles.card },
1110
+ React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 14, alignItems: 'flex-start' } },
1111
+ React.createElement('div', null,
1112
+ React.createElement('strong', null, '插件在线更新'),
1113
+ React.createElement('div', { style: { ...styles.muted, marginTop: 4 } }, updateChecking
1114
+ ? '正在检查 npm 最新版本…'
1115
+ : updateInfo
1116
+ ? `当前版本 v${updateInfo.currentVersion} · npm 最新 v${updateInfo.latestVersion}`
1117
+ : '暂时无法获取版本信息'),
1118
+ updateInfo?.updateAvailable
1119
+ ? React.createElement('div', { style: { marginTop: 6, color: colors.success, fontWeight: 600 } }, '发现新版本,可直接升级安装。')
1120
+ : null,
1121
+ updateInfo && !updateInfo.updateAvailable
1122
+ ? React.createElement('div', { style: { marginTop: 6, color: colors.success } }, '当前已是最新版本。')
1123
+ : null,
1124
+ updateNotice
1125
+ ? React.createElement('div', { style: { ...styles.muted, marginTop: 6, overflowWrap: 'anywhere' }, role: 'status' }, updateNotice)
1126
+ : null,
1127
+ updateError
1128
+ ? React.createElement('div', { style: { ...styles.muted, marginTop: 6, color: colors.danger, overflowWrap: 'anywhere' }, role: 'status' }, `检查失败:${updateError}`)
1129
+ : null),
1130
+ React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 8, minWidth: 100 } },
1131
+ React.createElement('button', {
1132
+ type: 'button',
1133
+ style: { ...styles.button, ...styles.primary, opacity: updateBusy || !updateInfo?.updateAvailable ? .55 : 1 },
1134
+ disabled: updateBusy || updateChecking || !updateInfo?.updateAvailable,
1135
+ onClick: upgradePlugin,
1136
+ }, updateBusy ? '正在升级…' : '立即升级'),
1137
+ React.createElement('button', {
1138
+ type: 'button',
1139
+ style: styles.button,
1140
+ disabled: updateChecking || updateBusy,
1141
+ onClick: checkForPluginUpdate,
1142
+ }, updateChecking ? '检查中…' : '重新检查')))),
1143
+ ),
1144
+ React.createElement('div', { hidden: activeSection !== 'pairing' },
1145
+ React.createElement('section', { style: styles.card },
1146
+ React.createElement('div', { className: 'mgw-setting-row' },
1147
+ React.createElement('div', { style: { position: 'relative', display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }, onMouseLeave: () => setConnectionHelpOpen(false) },
1148
+ React.createElement('h3', { className: 'mgw-section-title', style: { marginBottom: 0 } }, '配对连接方式'),
1149
+ React.createElement('button', {
1150
+ type: 'button',
1151
+ style: styles.helpButton,
1152
+ 'aria-label': '连接方式说明与场景建议',
1153
+ 'aria-expanded': connectionHelpOpen,
1154
+ 'aria-describedby': connectionHelpOpen ? 'mgw-route-help' : undefined,
1155
+ onMouseEnter: () => setConnectionHelpOpen(true),
1156
+ onFocus: () => setConnectionHelpOpen(true),
1157
+ onBlur: () => setConnectionHelpOpen(false),
1158
+ onClick: () => setConnectionHelpOpen(true),
1159
+ onKeyDown: (event) => { if (event.key === 'Escape') setConnectionHelpOpen(false) },
1160
+ }, '?'),
1161
+ connectionHelpOpen ? React.createElement('div', { id: 'mgw-route-help', role: 'tooltip', style: styles.helpBubble },
1162
+ React.createElement('strong', null, '怎么选连接方式'),
1163
+ helpLine('局域网直连', 'DSH App 和鲸尾小程序都可使用 ws:// 私有地址;手机与 DSH 位于可互访的局域网或 VPN 时可直连。'),
1164
+ helpLine('Cloudflare Tunnel(命名)', 'PC 主动连接 Cloudflare,DSH App 和小程序都可通过固定域名的 wss:// 公网入口连接;需要 Cloudflare 账户和域名。'),
1165
+ helpLine('Quick Tunnel', '无需账户或域名,两种客户端都可通过临时 wss:// 地址连接;隧道重建后地址可能变化。'),
1166
+ helpLine('公网服务器连接', '配置 Linux 服务器公网 WSS 入口,DSH App 和小程序都可使用。'),
1167
+ helpLine('鲸尾公网 · 小程序', '生成仅供小程序使用的鲸尾中继二维码;要同时配对 DSH App 和小程序,请选“自动选择”。'),
1168
+ React.createElement('div', { style: { borderTop: `1px solid ${colors.border}`, marginTop: 10, paddingTop: 8 } },
1169
+ React.createElement('strong', null, '结合当前环境'),
1170
+ React.createElement('div', { style: { color: colors.muted, marginTop: 4 } }, advice.detected),
1171
+ React.createElement('div', { style: { marginTop: 6 } }, advice.local),
1172
+ React.createElement('div', { style: { marginTop: 6 } }, advice.remote),
1173
+ React.createElement('div', { style: { color: colors.muted, marginTop: 6 } }, '面板无法判断手机当前网络;请按手机所在位置选择,提示不会替你修改选择。')))
1174
+ : null),
1175
+ React.createElement('div', { style: { display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: '8px 14px', maxWidth: '100%' } },
1176
+ React.createElement(GatewaySelect, { style: styles.input, value: effectiveRoute, onChange: (event) => choosePairingRoute(event.target.value), disabled: !status, 'aria-label': '配对连接方式' },
1177
+ React.createElement('option', { value: 'auto' }, '自动选择'),
1178
+ React.createElement('option', { value: 'relay', disabled: !status?.relay }, status?.relay
1179
+ ? '鲸尾公网 · 小程序' : '鲸尾公网 · 尚未注册'),
1180
+ lanPairingUrl(status) || pairingRoute === 'lan'
1181
+ ? React.createElement('option', { value: 'lan', disabled: !lanPairingUrl(status) }, lanPairingUrl(status)
1182
+ ? '局域网直连'
1183
+ : '局域网直连 · 当前不可用')
1184
+ : null,
1185
+ status?.cloudflare?.supported
1186
+ ? React.createElement('option', {
1187
+ value: 'cloudflare',
1188
+ }, status.cloudflare.enabled && status.cloudflare.publicReady === true && status.cloudflare.publicUrl
1189
+ ? 'Cloudflare 外网' : 'Cloudflare 外网 · 尚未就绪') : null,
1190
+ React.createElement('option', { value: 'custom' }, '手动输入地址')),
1191
+ status?.cloudflare?.supported && pairingRoute === 'auto'
1192
+ ? React.createElement('span', { style: { fontSize: 12, lineHeight: 1.5, fontWeight: 500,
1193
+ color: 'var(--dsw-alias-link, #4176e6)' } }, '自动选择会优先尝试已就绪的公网入口,并同时保留局域网地址;DSH App 和小程序都可使用两类地址。配置 Cloudflare 请切换到“Cloudflare 外网”。')
1194
+ : status?.cloudflare?.supported && pairingRoute === 'cloudflare'
1195
+ ? React.createElement('span', { style: { fontSize: 12, lineHeight: 1.5, fontWeight: 500,
1196
+ color: 'var(--dsw-alias-link, #4176e6)' } }, cloudflareReady
1197
+ ? 'Cloudflare 外网已就绪;DSH App 和小程序都可使用公网入口,也会保留局域网候选地址。'
1198
+ : 'Cloudflare 尚未就绪,可在本页 Cloudflare 设置中开启并完成连通性检测。')
1199
+ : null),
1200
+ React.createElement('p', { style: { ...styles.muted, margin: '-6px 0 10px' } }, pairingRoute === 'relay'
1201
+ ? '此模式生成仅供鲸尾小程序使用的中继二维码;DSH App 请选“自动选择”或“局域网直连”。'
1202
+ : '公网 WSS 就绪时,DSH App 和小程序都会尝试公网与局域网地址;没有公网入口时,App 使用局域网,小程序优先使用已注册的鲸尾中继,否则也使用局域网。生成新二维码不会断开已连接设备。'),
1203
+ // Fork: 中继模式下展示连接器状态与已注册中继信息
1204
+ (relayInfo || relayConnector?.running || relayConnector?.delegatedTo || relayConnector?.lastError)
1205
+ ? (relayInfo
1206
+ ? React.createElement('div', { style: { ...styles.muted, margin: '2px 0 0', fontWeight: 500 } },
1207
+ '鲸尾公网服务 · 已注册', ' · ',
1208
+ React.createElement('span', { style: { opacity: .8 } }, `设备 ID ${relayInfo.nodeId.slice(0, 8)}… · ${relayInfo.gatewayName}`),
1209
+ React.createElement('div', { style: { marginTop: 6, padding: '9px 11px', borderRadius: 10, border: '1px solid color-mix(in srgb, var(--dsw-alias-state-warning-primary, #d98324) 26%, transparent)', background: 'color-mix(in srgb, var(--dsw-alias-state-warning-primary, #d98324) 9%, transparent)', fontWeight: 400 } },
1210
+ React.createElement('div', null, '公网 WSS 就绪时,DSH App 和小程序都会获得公网与局域网候选地址;没有公网入口时,App 使用局域网,小程序优先使用已注册的鲸尾公网中继,否则使用局域网。也可单独选择“鲸尾公网 · 小程序”强制生成专用中继二维码。'),
1211
+ React.createElement('div', { style: { marginTop: 5 } }, relayConnector?.running || relayConnector?.delegatedTo
1212
+ ? '中继连接保持运行;切换配对方式不会断开已配对设备。'
1213
+ : relayConnector?.lastError ? '中继连接器暂不可用,请检查网络或重新开启公网连接。'
1214
+ : '中继身份已保存,连接器正在恢复…'),
1215
+ React.createElement('div', { style: { marginTop: 5 } }, '设备配对与公网有效期独立;公网到期不影响局域网。已注册不代表手机端完整链路已通过验证。')))
1216
+ : relayConnector && relayConnector.running
1217
+ ? React.createElement('div', { style: { ...styles.muted, margin: '2px 0 0', fontWeight: 500,
1218
+ color: 'var(--dsw-alias-link, #4176e6)' } }, '内置连接器已自动启动,正在连接中继并上报身份…')
1219
+ : relayConnector && relayConnector.lastError
1220
+ ? React.createElement('div', { style: { ...styles.muted, margin: '2px 0 0', fontWeight: 500, color: colors.danger } },
1221
+ '公网连接器暂时不可用,请检查网络或重新开启公网连接。', ' ',
1222
+ React.createElement('span', { style: { opacity: .8 } }, '如已自行部署连接器,请执行 systemctl restart dsh-connector。'))
1223
+ : React.createElement('div', { style: { ...styles.muted, margin: '2px 0 0' } }, '正在启动内置连接器…(中继模式需要一个本地连接器把小程序流量桥接进来,插件会自动准备)'))
1224
+ : null),
1225
+ pairingRoute === 'custom' ? React.createElement('label', { style: styles.label }, 'DSH App / 小程序连接地址') : null,
1226
+ pairingRoute === 'custom' ? React.createElement('input', { style: styles.input, value: publicUrl, onChange: (event) => setPublicUrl(event.target.value), placeholder: 'ws://192.168.1.10:3081/ws/mobile 或 wss://gateway.example.com/ws/mobile', spellCheck: false }) : null,
1227
+ status && status.lan && status.lan.enabled
1228
+ ? 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)' } },
1229
+ status.lan.error
1230
+ ? `局域网监听失败:${status.lan.error}`
1231
+ : status.lan.listening
1232
+ ? `局域网入口已开启${status.lan.urls && status.lan.urls.length ? `:${status.lan.urls.join('、')}` : `,端口 ${status.lan.port}`}`
1233
+ : '局域网入口启动中…')
1234
+ : null,
1235
+ React.createElement('button', {
1236
+ style: { ...styles.button, ...styles.primary, opacity: busy || !(status && status.gatewayEnabled) || (pairingRoute === 'custom' && !publicUrl.trim()) || (pairingRoute === 'cloudflare' && !cloudflareReady) ? .65 : 1 },
1237
+ disabled: busy || !(status && status.gatewayEnabled) ||
1238
+ (pairingRoute === 'custom' && !publicUrl.trim()) ||
1239
+ (pairingRoute === 'cloudflare' && !cloudflareReady) ||
1240
+ (pairingRoute === 'relay' && !status?.relay),
1241
+ onClick: pair,
1242
+ }, busy ? '正在生成…' : !(status && status.gatewayEnabled) ? '请先开启移动网关'
1243
+ : pairingRoute === 'cloudflare' && !cloudflareReady
1244
+ ? status?.cloudflare?.enabled ? '等待 Cloudflare 外网就绪' : '先开启 Cloudflare Tunnel'
1245
+ : (pairingRoute === 'custom' && !publicUrl.trim()) ? '等待连接地址' : '生成配对二维码'),
1246
+ React.createElement('p', { style: { ...styles.muted, margin: '10px 0 0' } }, '配对码仅可使用一次,5 分钟内有效。')),
1247
+ pairingRoute === 'cloudflare' && status?.cloudflare?.supported
1248
+ ? React.createElement('section', { className: 'mgw-cloudflare-block', style: { ...styles.card, background: colors.card, border: 0, borderRadius: 16, padding: 18, marginTop: 16 } },
1249
+ React.createElement('h3', { className: 'mgw-section-title' }, 'Cloudflare Tunnel · 外网接入'),
1250
+ React.createElement('p', { style: styles.muted }, status.platform === 'linux'
1251
+ ? 'Linux 服务器不自动下载:请先安装 cloudflared(Cloudflare 官方源 pkg.cloudflare.com 的 cloudflared 包),或将插件配置 cloudflaredPath 指向已有可执行文件。DSH App 和小程序均可使用已配置的公网入口,并且仍要求设备鉴权。'
1252
+ : '首次开启自动准备 Tunnel 组件。'),
1253
+ React.createElement('div', { className: 'mgw-setting-row' },
1254
+ React.createElement('span', { className: 'mgw-setting-label' }, '接入方式'),
1255
+ React.createElement(GatewaySelect, { style: styles.input, value: cloudflareMode, 'aria-label': 'Cloudflare 接入方式', onChange: (event) => {
1256
+ const mode = event.target.value
1257
+ setCloudflareMode(mode)
1258
+ if (status.cloudflare.enabled && mode !== status.cloudflare.mode &&
1259
+ (mode === 'quick' || (status.cloudflare.configured && cloudflareHost === status.cloudflare.hostname && !cloudflareToken))) {
1260
+ void configureCloudflare(true, mode)
1261
+ }
1262
+ }, disabled: cloudflareBusy },
1263
+ React.createElement('option', { value: 'quick' }, 'Quick Tunnel · 无需域名'),
1264
+ React.createElement('option', { value: 'named' }, '命名 Tunnel · 固定域名'))),
1265
+ cloudflareMode === 'quick'
1266
+ ? React.createElement('p', { style: styles.muted }, '临时地址可能变化,变化后需重新扫码。')
1267
+ : React.createElement(React.Fragment, null,
1268
+ 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 记录。'),
1269
+ React.createElement('div', { style: { display: 'flex', gap: 14, flexWrap: 'wrap', margin: '2px 0 4px' } },
1270
+ 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 控制台 → 隧道 ↗'),
1271
+ 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' } }, '官方创建教程 ↗')),
1272
+ React.createElement('p', { style: styles.muted }, 'Token 在控制台建好 Tunnel 后选择操作系统给出的安装命令里,是 eyJ… 开头的一段(只用它,不需要在 NAS 上执行该命令)。'),
1273
+ React.createElement('label', { style: styles.label }, '公开域名'),
1274
+ React.createElement('input', { style: styles.input, value: cloudflareHost, onChange: (event) => setCloudflareHost(event.target.value.trim()), placeholder: 'gateway.example.com', spellCheck: false }),
1275
+ React.createElement('label', { style: styles.label }, 'Tunnel Token'),
1276
+ 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 })),
1277
+ (!status.cloudflare.enabled || (cloudflareMode === 'named' &&
1278
+ (status.cloudflare.mode !== 'named' || cloudflareHost !== status.cloudflare.hostname || !!cloudflareToken)))
1279
+ ? React.createElement('button', {
1280
+ style: { ...styles.button, ...styles.primary, opacity: cloudflareBusy || (cloudflareMode === 'named' && (!cloudflareHost || (!cloudflareToken && !status.cloudflare.configured))) ? .65 : 1 },
1281
+ disabled: cloudflareBusy || (cloudflareMode === 'named' && (!cloudflareHost || (!cloudflareToken && !status.cloudflare.configured))),
1282
+ onClick: () => configureCloudflare(true),
1283
+ }, cloudflareBusy ? '正在处理…' : status.cloudflare.enabled ? '保存并连接' : cloudflareMode === 'quick' ? '一键开启 Quick Tunnel' : '开启命名 Tunnel') : null,
1284
+ status.cloudflare.enabled
1285
+ ? React.createElement(React.Fragment, null,
1286
+ React.createElement('button', { style: { ...styles.button, width: '100%', marginTop: 8 }, disabled: cloudflareBusy || status.cloudflare.state !== 'online', onClick: checkCloudflare }, '检测公网 DNS / TLS / WebSocket'),
1287
+ React.createElement('button', { style: { ...styles.button, width: '100%', marginTop: 8 }, disabled: cloudflareBusy || !status.gatewayEnabled, onClick: restartCloudflare }, '重启 Tunnel'),
1288
+ React.createElement('button', { style: { ...styles.button, width: '100%', marginTop: 8 }, disabled: cloudflareBusy, onClick: () => configureCloudflare(false) }, '关闭 Cloudflare Tunnel'),
1289
+ React.createElement('p', { style: styles.muted }, '重启会短暂断开连接。'))
1290
+ : null,
1291
+ 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 } },
1292
+ status.cloudflare.error || ({ disabled: '未开启', starting: '正在启动本机入口…', preparing: '正在准备 cloudflared(首次需下载)…', connecting: '正在连接 Cloudflare…', online: '隧道传输已连接(不等于公网入口可达)', 'waiting-for-gateway': '等待移动网关开启' }[status.cloudflare.state] || status.cloudflare.state),
1293
+ status.cloudflare.publicUrl ? ` · ${status.cloudflare.publicUrl}` : ''),
1294
+ status.cloudflare.enabled && status.cloudflare.endpointHealth
1295
+ ? 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 } },
1296
+ status.cloudflare.endpointHealth.message,
1297
+ status.cloudflare.endpointHealth.checkedAt ? `(检测时间:${status.cloudflare.endpointHealth.checkedAt})` : '')
1298
+ : null)
1299
+ : null,
1300
+ status && status.platform === 'linux' ? React.createElement('section', { style: styles.card },
1301
+ React.createElement('h3', { className: 'mgw-section-title' }, '公网接入'),
1302
+ publicSetup === null
1303
+ ? React.createElement('p', { style: styles.muted }, '正在检查系统组件…')
1304
+ : publicSetup.installed
1305
+ ? React.createElement(React.Fragment, null,
1306
+ React.createElement('div', { style: { ...styles.muted, margin: '5px 0 12px' } }, publicSetup.configured
1307
+ ? publicSetup.backendPort && status && status.webPort && publicSetup.backendPort !== status.webPort
1308
+ ? `端口需要更新:Nginx 当前为 ${publicSetup.backendPort},DSH 当前为 ${status.webPort}`
1309
+ : `已配置${publicSetup.backendPort ? `,Nginx 转发至 DSH 端口 ${publicSetup.backendPort}` : ''}`
1310
+ : `Helper 已就绪,将自动使用当前 DSH 端口${status && status.webPort ? ` ${status.webPort}` : ''}`),
1311
+ React.createElement('label', { style: styles.label }, '服务器公网 IPv4'),
1312
+ React.createElement('input', {
1313
+ style: styles.input,
1314
+ value: publicIp,
1315
+ onChange: (event) => setPublicIp(event.target.value.trim()),
1316
+ placeholder: '203.0.113.10',
1317
+ inputMode: 'decimal',
1318
+ spellCheck: false,
1319
+ }),
1320
+ React.createElement('button', {
1321
+ style: { ...styles.button, ...styles.primary, opacity: publicSetupBusy || !publicIp ? .65 : 1 },
1322
+ disabled: publicSetupBusy || !publicIp,
1323
+ onClick: configurePublicAccess,
1324
+ }, publicSetupBusy ? '正在配置 Nginx 与证书…' : publicSetup.configured ? '更新公网配置' : '配置公网接入'),
1325
+ publicSetup.publicUrl
1326
+ ? React.createElement('div', { style: { ...styles.muted, marginTop: 9, overflowWrap: 'anywhere' } }, publicSetup.publicUrl)
1327
+ : null)
1328
+ : React.createElement(React.Fragment, null,
1329
+ React.createElement('p', { style: { ...styles.muted, marginBottom: 8 } }, '尚未安装系统 Helper。请在服务器执行一次初始化:'),
1330
+ React.createElement('code', { style: { display: 'block', fontSize: 10, lineHeight: 1.5, overflowWrap: 'anywhere', userSelect: 'all' } }, 'npx --yes dsh-plugin-mobile-gateway@latest init'))) : null,
1331
+
1332
+ ),
1333
+ React.createElement('div', { hidden: activeSection !== 'devices' },
1334
+ React.createElement('section', { style: styles.card },
1335
+ React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center' } },
1336
+ React.createElement('h3', { className: 'mgw-section-title', style: { marginBottom: 0 } }, '可信设备'),
1337
+ React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 10 } },
1338
+ deviceNotice || refreshNotice ? React.createElement('span', {
1339
+ style: { ...styles.muted, color: deviceNoticeError ? colors.danger : colors.success },
1340
+ }, deviceNotice || refreshNotice) : null,
1341
+ React.createElement('button', {
1342
+ style: { ...styles.button, opacity: refreshing ? .6 : 1 },
1343
+ disabled: refreshing,
1344
+ onClick: manualRefresh,
1345
+ }, refreshing ? '刷新中…' : '刷新'))),
1346
+ devices === null
1347
+ ? React.createElement('p', { style: styles.muted }, '加载中…')
1348
+ : devices.length === 0
1349
+ ? React.createElement('p', { style: styles.muted }, '暂无已配对设备。')
1350
+ : React.createElement(React.Fragment, null,
1351
+ visibleDevices.length === 0 ? React.createElement('p', { style: styles.muted }, '当前没有在线设备。') : null,
1352
+ visibleDevices.map((device) => React.createElement(DeviceRow, {
1353
+ key: device.id,
1354
+ device,
1355
+ onRevoke: revoke,
1356
+ revoking: revokingIds.has(device.id),
1357
+ })),
1358
+ offlineDevices.length > 0 ? React.createElement('button', {
1359
+ type: 'button',
1360
+ style: { ...styles.button, marginTop: 10, color: colors.muted },
1361
+ 'aria-expanded': showAllDevices,
1362
+ onClick: () => setShowAllDevices((value) => !value),
1363
+ }, showAllDevices ? '收起离线设备' : `展开其他已配对设备(${offlineDevices.length})`) : null)),
1364
+ )),
1365
+ ),
1366
+ status && status.version
1367
+ ? React.createElement('div', { style: styles.version, 'aria-label': `插件版本 ${status.version}` }, `v${status.version}`)
1368
+ : null))
1369
+ }
1370
+
1371
+ // Fork: the entry is a Settings section instead of a sidebar footer button.
1372
+ // Tapping the Settings nav item opens the management dialog directly — the
1373
+ // dialog itself is upstream's unchanged shell.
1374
+ function SettingsEntry() {
1375
+ const isOpen = React.useSyncExternalStore(subscribe, getOpen, () => false)
1376
+ React.useEffect(() => { setOpen(true) }, [])
1377
+ return isOpen ? React.createElement(DevicePanel) : null
1378
+ }
1379
+
1380
+ const inject = ['slots']
1381
+ function apply(ctx) {
1382
+ // Upstream 0.10.1: the panel stylesheet is injected once through an
1383
+ // effect instead of being re-rendered inside the component tree.
1384
+ ctx.effect(() => {
1385
+ const style = document.createElement('style')
1386
+ style.textContent = panelCss
1387
+ document.head.appendChild(style)
1388
+ return () => style.remove()
1389
+ }, 'mobile-gateway: panel styles')
1390
+ pinNavGlyph([NAV_LABEL], NAV_ICON_MARK, navGlyph)
1391
+ // Fork: the entry is a Settings section, not the upstream sidebar footer
1392
+ // button. The id deliberately stays 'mobile-gateway' (not the package
1393
+ // name): it is a slot key that pinned-section state and the settings
1394
+ // plugin-hub map against, so renaming it would drop existing pins.
1395
+ ctx.slots.inject('settings.section', () => ctx.slots.register(
1396
+ { name: 'settings.section', id: 'mobile-gateway', order: 35, label: () => NAV_LABEL },
1397
+ () => React.createElement(SettingsEntry, null),
1398
+ ))
1399
+ }
1400
+
1401
+ exports.apply = apply
1402
+ exports.inject = inject
1403
+ exports.pinNavGlyph = pinNavGlyph
1404
+ // Exposed for tests: the Settings entry and the dialog body render separately.
1405
+ exports.SettingsEntry = SettingsEntry
1406
+ exports.DevicePanel = DevicePanel
1407
+ return module.exports
1408
+ },
1409
+ })