@deep-podder/dsh-remote-mobile 0.0.0-stage → 0.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js ADDED
@@ -0,0 +1,692 @@
1
+ // Client half of dsh-remote-mobile (browser module of the DSH Web UI).
2
+ // Renders the pairing panel inside Settings: QR, fallback PIN, address,
3
+ // expiry countdown and paired-device management. All data comes from the Host
4
+ // server over a key-gated loopback endpoint.
5
+ window.__ModuleLoader__.load({
6
+ // The registration id MUST equal the client module's manifest row id (the
7
+ // package name). The module system keys factories by package name; a short
8
+ // id (e.g. `dsh-remote-mobile`) leaves the package row unresolved, so the
9
+ // bundle is loaded a second time and the second registration throws
10
+ // "duplicate factory registration".
11
+ id: '@deep-podder/dsh-remote-mobile',
12
+ factory(require) {
13
+ const React = require('react')
14
+ const h = React.createElement
15
+ const { useCallback, useEffect, useMemo, useRef, useState } = React
16
+
17
+ const styles = {
18
+ page: {
19
+ display: 'flex',
20
+ flexDirection: 'column',
21
+ gap: '18px',
22
+ maxWidth: '720px',
23
+ color: 'var(--dsw-alias-label-primary)',
24
+ },
25
+ header: {
26
+ display: 'flex',
27
+ flexDirection: 'column',
28
+ gap: '4px',
29
+ },
30
+ title: {
31
+ margin: 0,
32
+ fontSize: '18px',
33
+ fontWeight: 600,
34
+ letterSpacing: '-0.01em',
35
+ },
36
+ subtitle: {
37
+ margin: 0,
38
+ fontSize: '13px',
39
+ lineHeight: 1.5,
40
+ color: 'var(--dsw-alias-label-secondary)',
41
+ },
42
+ card: {
43
+ display: 'flex',
44
+ gap: '24px',
45
+ flexWrap: 'wrap',
46
+ padding: '20px',
47
+ borderRadius: '14px',
48
+ background: 'var(--dsw-alias-bg-layer-1)',
49
+ border: '1px solid var(--dsw-alias-border-l1)',
50
+ },
51
+ qrWrap: {
52
+ width: '196px',
53
+ height: '196px',
54
+ padding: '10px',
55
+ borderRadius: '12px',
56
+ background: '#FFFFFF',
57
+ boxSizing: 'border-box',
58
+ flex: '0 0 auto',
59
+ },
60
+ qrImg: { width: '100%', height: '100%', display: 'block' },
61
+ details: {
62
+ display: 'flex',
63
+ flex: '1 1 260px',
64
+ minWidth: '240px',
65
+ flexDirection: 'column',
66
+ gap: '14px',
67
+ },
68
+ label: {
69
+ fontSize: '11px',
70
+ fontWeight: 600,
71
+ letterSpacing: '0.08em',
72
+ textTransform: 'uppercase',
73
+ color: 'var(--dsw-alias-label-secondary)',
74
+ },
75
+ pin: {
76
+ fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',
77
+ fontSize: '34px',
78
+ fontWeight: 600,
79
+ letterSpacing: '0.28em',
80
+ lineHeight: 1.1,
81
+ margin: 0,
82
+ color: 'var(--dsw-alias-label-primary)',
83
+ },
84
+ address: {
85
+ fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',
86
+ fontSize: '12px',
87
+ lineHeight: 1.5,
88
+ wordBreak: 'break-all',
89
+ margin: 0,
90
+ color: 'var(--dsw-alias-label-secondary)',
91
+ },
92
+ row: { display: 'flex', gap: '8px', flexWrap: 'wrap', alignItems: 'center' },
93
+ button: {
94
+ appearance: 'none',
95
+ border: '1px solid var(--dsw-alias-border-l2)',
96
+ background: 'var(--dsw-alias-bg-layer-2)',
97
+ color: 'var(--dsw-alias-label-primary)',
98
+ borderRadius: '8px',
99
+ padding: '7px 12px',
100
+ fontSize: '12px',
101
+ fontWeight: 500,
102
+ cursor: 'pointer',
103
+ lineHeight: 1.4,
104
+ },
105
+ muted: {
106
+ appearance: 'none',
107
+ border: 'none',
108
+ background: 'transparent',
109
+ color: 'var(--dsw-alias-label-secondary)',
110
+ fontSize: '12px',
111
+ cursor: 'pointer',
112
+ padding: 0,
113
+ textDecoration: 'underline',
114
+ textUnderlineOffset: '2px',
115
+ },
116
+ meta: { fontSize: '12px', color: 'var(--dsw-alias-label-secondary)' },
117
+ banner: {
118
+ padding: '10px 12px',
119
+ borderRadius: '10px',
120
+ fontSize: '12px',
121
+ lineHeight: 1.5,
122
+ border: '1px solid var(--dsw-alias-border-l1)',
123
+ background: 'var(--dsw-alias-bg-layer-2)',
124
+ color: 'var(--dsw-alias-label-secondary)',
125
+ },
126
+ warn: {
127
+ padding: '10px 12px',
128
+ borderRadius: '10px',
129
+ fontSize: '12px',
130
+ lineHeight: 1.5,
131
+ border: '1px solid var(--dsw-alias-state-warn-primary)',
132
+ background: 'var(--dsw-alias-bg-layer-2)',
133
+ color: 'var(--dsw-alias-state-warn-primary)',
134
+ },
135
+ error: {
136
+ padding: '10px 12px',
137
+ borderRadius: '10px',
138
+ fontSize: '12px',
139
+ lineHeight: 1.5,
140
+ border: '1px solid var(--dsw-alias-state-error-primary)',
141
+ color: 'var(--dsw-alias-state-error-primary)',
142
+ background: 'var(--dsw-alias-bg-layer-2)',
143
+ },
144
+ devices: {
145
+ display: 'flex',
146
+ flexDirection: 'column',
147
+ gap: '8px',
148
+ },
149
+ device: {
150
+ display: 'flex',
151
+ alignItems: 'center',
152
+ gap: '10px',
153
+ padding: '10px 12px',
154
+ borderRadius: '10px',
155
+ background: 'var(--dsw-alias-bg-layer-2)',
156
+ border: '1px solid var(--dsw-alias-border-l1)',
157
+ },
158
+ dot: {
159
+ width: '7px',
160
+ height: '7px',
161
+ borderRadius: '50%',
162
+ background: 'var(--dsw-alias-state-success-primary)',
163
+ flex: '0 0 auto',
164
+ },
165
+ spacer: { flex: '1 1 auto' },
166
+ toggleRow: {
167
+ display: 'flex',
168
+ alignItems: 'center',
169
+ gap: '14px',
170
+ padding: '12px 14px',
171
+ borderRadius: '12px',
172
+ border: '1px solid var(--dsw-alias-border-l1)',
173
+ background: 'var(--dsw-alias-bg-layer-1)',
174
+ },
175
+ confirmRow: {
176
+ display: 'flex',
177
+ alignItems: 'center',
178
+ gap: '12px',
179
+ flexWrap: 'wrap',
180
+ padding: '12px 14px',
181
+ borderRadius: '12px',
182
+ border: '1px solid var(--dsw-alias-state-warn-primary)',
183
+ background: 'var(--dsw-alias-bg-layer-1)',
184
+ color: 'var(--dsw-alias-label-primary)',
185
+ lineHeight: 1.5,
186
+ },
187
+ }
188
+
189
+ function switchStyle(on) {
190
+ return {
191
+ position: 'relative',
192
+ width: '42px',
193
+ height: '24px',
194
+ flex: '0 0 auto',
195
+ padding: 0,
196
+ border: 'none',
197
+ borderRadius: '999px',
198
+ cursor: 'pointer',
199
+ background: on ? 'var(--dsw-alias-state-success-primary)' : 'var(--dsw-alias-border-l2)',
200
+ transition: 'background 160ms ease',
201
+ }
202
+ }
203
+
204
+ function switchKnobStyle(on) {
205
+ return {
206
+ position: 'absolute',
207
+ top: '3px',
208
+ left: on ? '21px' : '3px',
209
+ width: '18px',
210
+ height: '18px',
211
+ borderRadius: '50%',
212
+ background: '#FFFFFF',
213
+ transition: 'left 160ms ease',
214
+ boxShadow: '0 1px 2px rgba(0, 0, 0, 0.28)',
215
+ }
216
+ }
217
+
218
+ function formatRelative(ts) {
219
+ if (!Number.isFinite(ts)) return ''
220
+ const delta = Date.now() - ts
221
+ if (delta < 60_000) return 'just now'
222
+ if (delta < 3_600_000) return `${Math.floor(delta / 60_000)} min ago`
223
+ if (delta < 86_400_000) return `${Math.floor(delta / 3_600_000)} h ago`
224
+ return `${Math.floor(delta / 86_400_000)} d ago`
225
+ }
226
+
227
+ function formatCountdown(ms) {
228
+ if (!Number.isFinite(ms) || ms <= 0) return 'expired'
229
+ const seconds = Math.ceil(ms / 1000)
230
+ if (seconds < 60) return `${seconds}s`
231
+ return `${Math.floor(seconds / 60)}m ${String(seconds % 60).padStart(2, '0')}s`
232
+ }
233
+
234
+ function PairingPanel() {
235
+ const injected = typeof window !== 'undefined' ? window.__DSH_REMOTE_MOBILE__ : undefined
236
+ const bootstrap = injected !== undefined && typeof injected === 'object' && Number.isInteger(injected.port)
237
+ ? injected
238
+ : undefined
239
+ const localPage = typeof window !== 'undefined' && (
240
+ window.location.protocol === 'file:'
241
+ || window.location.hostname === '127.0.0.1'
242
+ || window.location.hostname === 'localhost'
243
+ || window.location.hostname === '::1'
244
+ || window.location.hostname === '[::1]'
245
+ )
246
+ const [status, setStatus] = useState(null)
247
+ const [error, setError] = useState(null)
248
+ const [busy, setBusy] = useState(false)
249
+ const [busyToggle, setBusyToggle] = useState(false)
250
+ const [confirmOff, setConfirmOff] = useState(false)
251
+ const [copied, setCopied] = useState(false)
252
+ const copiedTimer = useRef(null)
253
+ const [tick, setTick] = useState(0)
254
+ const [selectedAddress, setSelectedAddress] = useState(null)
255
+
256
+ // Try the injected keyed endpoint first, then the DSH web server's
257
+ // same-origin route (immune to page CSP and file:// origins), then the
258
+ // bare loopback endpoint. The first one that answers is reused.
259
+ const sources = useMemo(() => {
260
+ const list = []
261
+ if (bootstrap !== undefined) {
262
+ list.push({ base: `http://127.0.0.1:${bootstrap.port}`, key: bootstrap.key })
263
+ }
264
+ list.push({ base: '', key: null })
265
+ if (localPage) {
266
+ list.push({ base: `http://127.0.0.1:${bootstrap !== undefined ? bootstrap.port : 3456}`, key: null })
267
+ }
268
+ return list
269
+ }, [bootstrap, localPage])
270
+ const activeIndex = useRef(-1)
271
+
272
+ const opUrl = useCallback((source, op, query) => {
273
+ const base = source.base === ''
274
+ ? (op === 'status' ? '/remote-mobile/pairing' : `/remote-mobile/pairing/${op}`)
275
+ : (source.key
276
+ ? `${source.base}${op === 'status' ? '/api/desktop/status' : `/api/desktop/${op}`}?key=${encodeURIComponent(source.key)}`
277
+ : `${source.base}${op === 'status' ? '/api/desktop/status' : `/api/desktop/${op}`}`)
278
+ if (!query) return base
279
+ return `${base}${base.includes('?') ? '&' : '?'}${query}`
280
+ }, [])
281
+
282
+ const request = useCallback(async (op, options = {}) => {
283
+ const failures = []
284
+ const order = []
285
+ if (activeIndex.current >= 0) order.push(activeIndex.current)
286
+ for (let index = 0; index < sources.length; index += 1) {
287
+ if (!order.includes(index)) order.push(index)
288
+ }
289
+ const { query, ...init } = options
290
+ for (const index of order) {
291
+ const source = sources[index]
292
+ try {
293
+ const response = await fetch(opUrl(source, op, query), {
294
+ cache: 'no-store',
295
+ mode: 'cors',
296
+ credentials: 'omit',
297
+ ...init,
298
+ headers: init.body === undefined
299
+ ? undefined
300
+ : { 'content-type': 'application/json', ...(init.headers ?? {}) },
301
+ })
302
+ if (!response.ok) {
303
+ failures.push(`${source.base === '' ? 'same-origin' : source.base}: HTTP ${response.status}`)
304
+ continue
305
+ }
306
+ const data = await response.json()
307
+ activeIndex.current = index
308
+ return data
309
+ } catch (cause) {
310
+ failures.push(`${source.base === '' ? 'same-origin' : source.base}: ${cause instanceof Error ? cause.message : String(cause)}`)
311
+ }
312
+ }
313
+ throw new Error(`Could not reach the local pairing server (${failures.join('; ')})`)
314
+ }, [opUrl, sources])
315
+
316
+ const load = useCallback(async () => {
317
+ try {
318
+ const next = await request('status', selectedAddress === null ? {} : { query: `address=${encodeURIComponent(selectedAddress)}` })
319
+ setStatus(next)
320
+ setError(null)
321
+ if (next !== null && next.enabled === false) setConfirmOff(false)
322
+ } catch (cause) {
323
+ setError(cause instanceof Error ? cause.message : String(cause))
324
+ }
325
+ }, [request, selectedAddress])
326
+
327
+ useEffect(() => {
328
+ void load()
329
+ const poll = setInterval(() => void load(), 5000)
330
+ const clock = setInterval(() => setTick((value) => value + 1), 1000)
331
+ return () => {
332
+ clearInterval(poll)
333
+ clearInterval(clock)
334
+ if (copiedTimer.current !== null) clearTimeout(copiedTimer.current)
335
+ }
336
+ }, [load])
337
+
338
+ const rotate = useCallback(async () => {
339
+ setBusy(true)
340
+ try {
341
+ await request('rotate', { method: 'POST', body: '{}' })
342
+ await load()
343
+ } catch (cause) {
344
+ setError(cause instanceof Error ? cause.message : String(cause))
345
+ } finally {
346
+ setBusy(false)
347
+ }
348
+ }, [request, load])
349
+
350
+ const revoke = useCallback(async (deviceId) => {
351
+ setBusy(true)
352
+ try {
353
+ await request('revoke', { method: 'POST', body: JSON.stringify({ deviceId }) })
354
+ await load()
355
+ } catch (cause) {
356
+ setError(cause instanceof Error ? cause.message : String(cause))
357
+ } finally {
358
+ setBusy(false)
359
+ }
360
+ }, [request, load])
361
+
362
+ const revokeAll = useCallback(async () => {
363
+ setBusy(true)
364
+ try {
365
+ await request('revoke', { method: 'POST', body: JSON.stringify({ all: true }) })
366
+ await load()
367
+ } catch (cause) {
368
+ setError(cause instanceof Error ? cause.message : String(cause))
369
+ } finally {
370
+ setBusy(false)
371
+ }
372
+ }, [request, load])
373
+
374
+ const setDevicePermission = useCallback(async (deviceId, canApprove) => {
375
+ setBusy(true)
376
+ try {
377
+ await request('device', { method: 'POST', body: JSON.stringify({ deviceId, canApprove }) })
378
+ await load()
379
+ setError(null)
380
+ } catch (cause) {
381
+ setError(cause instanceof Error ? cause.message : String(cause))
382
+ } finally {
383
+ setBusy(false)
384
+ }
385
+ }, [request, load])
386
+
387
+ const copy = useCallback(async () => {
388
+ if (status === null || status.url === null) return
389
+ try {
390
+ await navigator.clipboard.writeText(status.url)
391
+ setCopied(true)
392
+ copiedTimer.current = setTimeout(() => {
393
+ copiedTimer.current = null
394
+ setCopied(false)
395
+ }, 1600)
396
+ } catch {
397
+ setError('Clipboard is not available in this browser.')
398
+ }
399
+ }, [status])
400
+
401
+ const toggleEnabled = useCallback(async (next) => {
402
+ setBusyToggle(true)
403
+ setConfirmOff(false)
404
+ try {
405
+ await request(next ? 'enable' : 'disable', { method: 'POST', body: '{}' })
406
+ await load()
407
+ setError(null)
408
+ } catch (cause) {
409
+ setError(cause instanceof Error ? cause.message : String(cause))
410
+ } finally {
411
+ setBusyToggle(false)
412
+ }
413
+ }, [request, load])
414
+
415
+ const pinRemaining = status === null || status.enabled === false ? 0 : status.pinExpiresAt - Date.now()
416
+
417
+ const deviceList = status !== null && status.devices.length > 0
418
+ ? h('div', { style: styles.devices }, status.devices.map((device) => h('div', { key: device.id, style: styles.device },
419
+ h('span', { style: styles.dot }),
420
+ h('div', null,
421
+ h('div', { style: { fontSize: '13px', fontWeight: 500 } }, device.name),
422
+ h('div', { style: styles.meta }, `Paired ${formatRelative(device.createdAt)} · last seen ${formatRelative(device.lastSeenAt)}`)),
423
+ h('span', { style: styles.spacer }),
424
+ h('button', {
425
+ type: 'button',
426
+ role: 'switch',
427
+ 'aria-checked': device.canApprove !== false,
428
+ 'aria-label': `Allow ${device.name} to answer approvals`,
429
+ title: device.canApprove !== false
430
+ ? 'This device can answer approvals'
431
+ : 'This device cannot answer approvals',
432
+ disabled: busy,
433
+ style: switchStyle(device.canApprove !== false),
434
+ onClick: () => setDevicePermission(device.id, !(device.canApprove !== false)),
435
+ }, h('span', { style: switchKnobStyle(device.canApprove !== false) })),
436
+ h('button', { type: 'button', style: styles.muted, disabled: busy, onClick: () => revoke(device.id) }, 'Revoke'))))
437
+ : h('div', { style: styles.banner }, 'No devices paired yet.')
438
+
439
+ const pairingCard = h('div', { style: styles.card },
440
+ h('div', { style: styles.qrWrap },
441
+ h('img', {
442
+ style: styles.qrImg,
443
+ alt: 'Pairing QR code',
444
+ src: `data:image/svg+xml;charset=utf-8,${encodeURIComponent(status === null ? '' : status.qrSvg)}`,
445
+ })),
446
+ h('div', { style: styles.details },
447
+ h('div', null,
448
+ h('div', { style: styles.label }, 'PIN'),
449
+ h('p', { style: styles.pin, 'aria-label': `PIN ${status === null ? '' : status.pin}` }, status === null ? '' : status.pin)),
450
+ h('div', null,
451
+ h('div', { style: styles.label }, 'Address'),
452
+ h('p', { style: styles.address }, status === null ? '' : status.url),
453
+ status !== null && Array.isArray(status.addressDetails) && status.addressDetails.length > 1
454
+ ? h('div', { style: { display: 'flex', flexWrap: 'wrap', gap: '6px', marginTop: '6px' } },
455
+ status.addressDetails.map((entry) => h('button', {
456
+ key: entry.address,
457
+ type: 'button',
458
+ onClick: () => setSelectedAddress(entry.address),
459
+ 'aria-pressed': status.address === entry.address,
460
+ style: status.address === entry.address
461
+ ? { ...styles.button, borderColor: 'var(--dsw-alias-brand-primary)', color: 'var(--dsw-alias-brand-primary)' }
462
+ : { ...styles.button, fontSize: '11px', padding: '5px 8px' },
463
+ }, entry.address.startsWith('http') ? entry.name : `${entry.address}${entry.name ? ` · ${entry.name}` : ''}`)))
464
+ : null,
465
+ status !== null && Array.isArray(status.addresses) && status.addresses.some((address) => address.startsWith('100.') || address.startsWith('https://'))
466
+ ? h('p', { style: styles.meta }, 'Use the Tailscale address when the phone is away from this Wi-Fi. Open Tailscale on the phone first.')
467
+ : null),
468
+ h('div', { style: styles.row },
469
+ h('button', { type: 'button', style: styles.button, onClick: copy }, copied ? 'Copied' : 'Copy link'),
470
+ h('button', { type: 'button', style: styles.button, disabled: busy, onClick: rotate }, 'New PIN')),
471
+ h('div', { style: styles.meta }, `PIN expires in ${formatCountdown(pinRemaining)}`)))
472
+
473
+ const devicesSection = h('div', null,
474
+ h('div', { style: styles.label }, 'Paired devices'),
475
+ deviceList,
476
+ status !== null && status.devices.length > 0
477
+ ? h('div', { style: { marginTop: '12px' } },
478
+ h('button', { type: 'button', style: styles.muted, disabled: busy, onClick: revokeAll }, 'Revoke all devices'))
479
+ : null)
480
+
481
+ const body = status === null
482
+ ? h('div', { style: styles.banner }, 'Starting the local mobile server…')
483
+ : h('div', { style: { display: 'flex', flexDirection: 'column', gap: '18px' } },
484
+ status.enabled === false
485
+ ? h('div', { style: styles.banner }, 'Remote access is off. The phone cannot pair or connect while the switch is off.')
486
+ : pairingCard,
487
+ status.enabled === false
488
+ ? null
489
+ : status.loopbackOnly
490
+ ? h('div', { style: styles.warn }, 'Only a loopback address was detected. A phone cannot reach this machine until it has a LAN or Tailscale address.')
491
+ : null,
492
+ devicesSection)
493
+
494
+ const connectedNames = status !== null && Array.isArray(status.connectedNames) ? status.connectedNames : []
495
+ const connectedCount = status !== null && Number.isFinite(status.connectedDevices) ? status.connectedDevices : 0
496
+ const lastConnectedLabel = status === null || !status.lastConnectedAt ? 'never' : formatRelative(status.lastConnectedAt)
497
+ const toggleSubtitle = status === null
498
+ ? 'Checking…'
499
+ : status.enabled === false
500
+ ? `Off · last connected ${lastConnectedLabel}`
501
+ : connectedCount > 0
502
+ ? `${connectedNames.length > 0 ? connectedNames.join(', ') : 'A device'} connected now`
503
+ : `Last connected ${lastConnectedLabel}`
504
+
505
+ return h('div', { style: styles.page },
506
+ h('div', { style: styles.header },
507
+ h('h2', { style: styles.title }, 'Remote mobile access'),
508
+ h('p', { style: styles.subtitle }, 'Scan the QR code with your phone, or open the address and enter the PIN. Devices must be on the same network — preferably Tailscale or a trusted Wi-Fi.')),
509
+ h('div', { style: styles.toggleRow },
510
+ h('div', { style: { flex: '1 1 auto' } },
511
+ h('div', { style: { fontSize: '13px', fontWeight: 600 } },
512
+ status !== null && status.enabled === false ? 'Remote access is off' : 'Remote access is on'),
513
+ h('div', { style: styles.meta }, toggleSubtitle)),
514
+ h('button', {
515
+ type: 'button',
516
+ role: 'switch',
517
+ 'aria-checked': status !== null && status.enabled !== false,
518
+ 'aria-label': 'Enable remote mobile access',
519
+ disabled: busyToggle || status === null,
520
+ onClick: () => {
521
+ if (status === null) return
522
+ if (status.enabled === false) {
523
+ void toggleEnabled(true)
524
+ return
525
+ }
526
+ if (connectedCount > 0) {
527
+ setConfirmOff(true)
528
+ return
529
+ }
530
+ void toggleEnabled(false)
531
+ },
532
+ style: switchStyle(status !== null && status.enabled !== false),
533
+ }, h('span', { style: switchKnobStyle(status !== null && status.enabled !== false) }))),
534
+ confirmOff && status !== null && status.enabled !== false
535
+ ? h('div', { style: styles.confirmRow },
536
+ h('div', { style: { flex: '1 1 240px', fontSize: '12px' } },
537
+ `${connectedNames.length > 0 ? connectedNames.join(', ') : 'A phone'} is connected. Turning access off disconnects it until you turn it back on.`),
538
+ h('button', {
539
+ type: 'button',
540
+ style: styles.button,
541
+ disabled: busyToggle,
542
+ onClick: () => void toggleEnabled(false),
543
+ }, 'Turn off'),
544
+ h('button', {
545
+ type: 'button',
546
+ style: styles.muted,
547
+ onClick: () => setConfirmOff(false),
548
+ }, 'Cancel'))
549
+ : null,
550
+ error !== null ? h('div', { style: styles.error }, error) : null,
551
+ body)
552
+ }
553
+
554
+ /**
555
+ * Desktop approval dock. Both the phone and the desktop show the same
556
+ * pending approvals; whichever answers first settles the request, and the
557
+ * dock disappears on the next poll. It only appears while a phone is
558
+ * connected (otherwise the shipped desktop approval UI owns the request).
559
+ */
560
+ function ApprovalDock() {
561
+ const [approvals, setApprovals] = useState([])
562
+ const [busyId, setBusyId] = useState(null)
563
+
564
+ const load = useCallback(async () => {
565
+ const sources = ['/remote-mobile/pairing/pending', 'http://127.0.0.1:3456/api/desktop/pending']
566
+ for (const url of sources) {
567
+ try {
568
+ const response = await fetch(url, {
569
+ cache: 'no-store',
570
+ credentials: 'omit',
571
+ mode: url.startsWith('http') ? 'cors' : 'same-origin',
572
+ })
573
+ if (!response.ok) continue
574
+ const data = await response.json()
575
+ setApprovals(Array.isArray(data && data.approvals) ? data.approvals : [])
576
+ return
577
+ } catch {
578
+ // try the next source
579
+ }
580
+ }
581
+ }, [])
582
+
583
+ useEffect(() => {
584
+ void load()
585
+ const timer = setInterval(() => void load(), 1500)
586
+ return () => clearInterval(timer)
587
+ }, [load])
588
+
589
+ const answer = useCallback(async (requestId, decision) => {
590
+ setBusyId(requestId)
591
+ try {
592
+ const sources = ['/remote-mobile/pairing/answer', 'http://127.0.0.1:3456/api/desktop/answer']
593
+ for (const url of sources) {
594
+ try {
595
+ const response = await fetch(url, {
596
+ method: 'POST',
597
+ headers: { 'content-type': 'application/json' },
598
+ body: JSON.stringify({ requestId, decision }),
599
+ cache: 'no-store',
600
+ credentials: 'omit',
601
+ mode: url.startsWith('http') ? 'cors' : 'same-origin',
602
+ })
603
+ if (!response.ok) continue
604
+ setApprovals((previous) => previous.filter((item) => item.requestId !== requestId))
605
+ return
606
+ } catch {
607
+ // try the next source
608
+ }
609
+ }
610
+ } catch {
611
+ // Both sources refused; the approval dock stays available for a retry.
612
+ } finally {
613
+ setBusyId(null)
614
+ }
615
+ }, [])
616
+
617
+ if (approvals.length === 0) return null
618
+ const item = approvals[0]
619
+ const reason = item.displayReason || item.reason || ''
620
+ const card = {
621
+ position: 'fixed',
622
+ right: '20px',
623
+ bottom: '20px',
624
+ zIndex: 60,
625
+ width: 'min(420px, calc(100vw - 40px))',
626
+ display: 'flex',
627
+ flexDirection: 'column',
628
+ gap: '10px',
629
+ padding: '14px 16px',
630
+ borderRadius: '14px',
631
+ background: 'var(--dsw-alias-bg-overlay)',
632
+ border: '1px solid var(--dsw-alias-border-l2)',
633
+ boxShadow: '0 12px 32px rgba(0, 0, 0, 0.28)',
634
+ color: 'var(--dsw-alias-label-primary)',
635
+ }
636
+ const eyebrow = {
637
+ display: 'flex',
638
+ alignItems: 'center',
639
+ gap: '8px',
640
+ fontSize: '11px',
641
+ fontWeight: 600,
642
+ letterSpacing: '0.08em',
643
+ textTransform: 'uppercase',
644
+ color: 'var(--dsw-alias-state-warn-primary)',
645
+ }
646
+ const tool = {
647
+ fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',
648
+ fontSize: '13px',
649
+ fontWeight: 600,
650
+ }
651
+ const body = { margin: 0, fontSize: '12px', lineHeight: 1.5, color: 'var(--dsw-alias-label-secondary)' }
652
+ const actions = { display: 'flex', justifyContent: 'flex-end', gap: '8px' }
653
+ const button = {
654
+ appearance: 'none',
655
+ borderRadius: '8px',
656
+ padding: '7px 12px',
657
+ fontSize: '12px',
658
+ fontWeight: 500,
659
+ cursor: 'pointer',
660
+ border: '1px solid var(--dsw-alias-border-l2)',
661
+ background: 'var(--dsw-alias-bg-layer-2)',
662
+ color: 'var(--dsw-alias-label-primary)',
663
+ }
664
+ const primary = { ...button, background: 'var(--dsw-alias-label-primary)', borderColor: 'transparent', color: 'var(--dsw-alias-bg-base)', fontWeight: 600 }
665
+ const busy = busyId === item.requestId
666
+ return h('div', { style: card, role: 'status', 'aria-live': 'polite' },
667
+ h('div', { style: eyebrow }, `Approval needed${approvals.length > 1 ? ` · ${approvals.length}` : ''}`),
668
+ h('div', { style: tool }, item.toolName || 'tool'),
669
+ reason.length > 0 ? h('p', { style: body }, reason) : null,
670
+ h('div', { style: actions },
671
+ h('button', { type: 'button', style: button, disabled: busy, onClick: () => void answer(item.requestId, 'reject') }, busy ? 'Sending…' : 'Reject'),
672
+ h('button', { type: 'button', style: primary, disabled: busy, onClick: () => void answer(item.requestId, 'allow') }, busy ? 'Sending…' : 'Approve')))
673
+ }
674
+
675
+ return {
676
+ inject: ['slots'],
677
+ apply(ctx) {
678
+ ctx.slots.inject('settings.section', () => ctx.slots.register({
679
+ name: 'settings.section',
680
+ id: 'remote-mobile',
681
+ order: 60,
682
+ label: 'Remote mobile access',
683
+ }, PairingPanel))
684
+ ctx.slots.inject('shell.overlay', () => ctx.slots.register({
685
+ name: 'shell.overlay',
686
+ id: 'remote-mobile-approvals',
687
+ order: 20,
688
+ }, ApprovalDock))
689
+ },
690
+ }
691
+ },
692
+ })