dsh-zen-remote 1.1.16 → 2.0.1

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 (261) hide show
  1. package/AGENTS.md +54 -9
  2. package/README.md +249 -190
  3. package/README.zh-CN.md +247 -201
  4. package/assets/home.png +0 -0
  5. package/assets/info.png +0 -0
  6. package/assets/pairing.png +0 -0
  7. package/assets/session.png +0 -0
  8. package/assets/sheet.png +0 -0
  9. package/cordis.patch.yml +12 -11
  10. package/cordis.patch.yml.example +24 -9
  11. package/docs/interface.md +57 -2
  12. package/docs/remote-access.en.md +99 -58
  13. package/docs/remote-access.md +99 -42
  14. package/dsh-push.mjs +67 -54
  15. package/lan-gate.mjs +88 -20
  16. package/lib/activity.js +168 -0
  17. package/lib/activity.js.map +1 -0
  18. package/lib/admin-routes.js +526 -0
  19. package/lib/admin-routes.js.map +1 -0
  20. package/lib/client-pairing.js +224 -0
  21. package/lib/client-pairing.js.map +1 -0
  22. package/lib/client-routes.js +674 -0
  23. package/lib/client-routes.js.map +1 -0
  24. package/lib/client.js +11498 -5990
  25. package/lib/config.js +346 -0
  26. package/lib/config.js.map +1 -0
  27. package/lib/fetch-route-intercept.js +418 -0
  28. package/lib/fetch-route-intercept.js.map +1 -0
  29. package/lib/fingerprint.js +365 -0
  30. package/lib/fingerprint.js.map +1 -0
  31. package/lib/http.js +69 -0
  32. package/lib/http.js.map +1 -0
  33. package/lib/index.js +675 -54
  34. package/lib/index.js.map +1 -1
  35. package/lib/intercept-shape.js +81 -0
  36. package/lib/intercept-shape.js.map +1 -0
  37. package/lib/intercept.js +3181 -0
  38. package/lib/intercept.js.map +1 -0
  39. package/lib/lan-gate-server.cjs +532 -121
  40. package/lib/merge-streams.js +1172 -0
  41. package/lib/merge-streams.js.map +1 -0
  42. package/lib/relay-access.js +496 -0
  43. package/lib/relay-access.js.map +1 -0
  44. package/lib/relay-client.js +1303 -0
  45. package/lib/relay-client.js.map +1 -0
  46. package/lib/relay-filter.js +282 -0
  47. package/lib/relay-filter.js.map +1 -0
  48. package/lib/relay-server.js +1813 -0
  49. package/lib/relay-server.js.map +1 -0
  50. package/lib/restart-fields.js +34 -0
  51. package/lib/restart-fields.js.map +1 -0
  52. package/lib/restart-watcher.js +106 -0
  53. package/lib/restart-watcher.js.map +1 -0
  54. package/lib/session-reference.js +157 -0
  55. package/lib/session-reference.js.map +1 -0
  56. package/lib/share-export.js +16 -1
  57. package/lib/share-export.js.map +1 -1
  58. package/lib/share-ops.js +86 -0
  59. package/lib/share-ops.js.map +1 -0
  60. package/lib/share-store.js +294 -0
  61. package/lib/share-store.js.map +1 -0
  62. package/lib/types/activity.d.ts +99 -0
  63. package/lib/types/activity.d.ts.map +1 -0
  64. package/lib/types/admin-routes.d.ts +129 -0
  65. package/lib/types/admin-routes.d.ts.map +1 -0
  66. package/lib/types/client/MobileDrawerFooter.d.ts.map +1 -1
  67. package/lib/types/client/MobileHome.d.ts +1 -1
  68. package/lib/types/client/MobileHome.d.ts.map +1 -1
  69. package/lib/types/client/MobileHomeChips.d.ts +1 -1
  70. package/lib/types/client/MobileHomeChips.d.ts.map +1 -1
  71. package/lib/types/client/MobileSessionHeader.d.ts +13 -2
  72. package/lib/types/client/MobileSessionHeader.d.ts.map +1 -1
  73. package/lib/types/client/MobileSessionInfo.d.ts +20 -3
  74. package/lib/types/client/MobileSessionInfo.d.ts.map +1 -1
  75. package/lib/types/client/RemoteComposerBanner.d.ts +42 -0
  76. package/lib/types/client/RemoteComposerBanner.d.ts.map +1 -0
  77. package/lib/types/client/RemoteHeaderIcon.d.ts +37 -0
  78. package/lib/types/client/RemoteHeaderIcon.d.ts.map +1 -0
  79. package/lib/types/client/RemoteShareMenu.d.ts +28 -0
  80. package/lib/types/client/RemoteShareMenu.d.ts.map +1 -0
  81. package/lib/types/client/RemoteStatusIcon.d.ts +36 -0
  82. package/lib/types/client/RemoteStatusIcon.d.ts.map +1 -0
  83. package/lib/types/client/compat/desktop.d.ts +21 -0
  84. package/lib/types/client/compat/desktop.d.ts.map +1 -0
  85. package/lib/types/client/compat/types.d.ts +57 -0
  86. package/lib/types/client/compat/types.d.ts.map +1 -1
  87. package/lib/types/client/current-session-report.d.ts +37 -0
  88. package/lib/types/client/current-session-report.d.ts.map +1 -0
  89. package/lib/types/client/effects/header-status.d.ts.map +1 -1
  90. package/lib/types/client/effects/keyboard-guard.d.ts.map +1 -1
  91. package/lib/types/client/effects/model-group-side.d.ts +13 -0
  92. package/lib/types/client/effects/model-group-side.d.ts.map +1 -0
  93. package/lib/types/client/effects/permission-sheet.d.ts +39 -0
  94. package/lib/types/client/effects/permission-sheet.d.ts.map +1 -0
  95. package/lib/types/client/effects/remote-session.d.ts +25 -0
  96. package/lib/types/client/effects/remote-session.d.ts.map +1 -0
  97. package/lib/types/client/effects/turn-fold.d.ts +9 -0
  98. package/lib/types/client/effects/turn-fold.d.ts.map +1 -1
  99. package/lib/types/client/index.d.ts.map +1 -1
  100. package/lib/types/client/locales.d.ts +187 -2
  101. package/lib/types/client/locales.d.ts.map +1 -1
  102. package/lib/types/client/remote-fetch.d.ts +51 -0
  103. package/lib/types/client/remote-fetch.d.ts.map +1 -0
  104. package/lib/types/client/remote-group-expansion.d.ts +41 -0
  105. package/lib/types/client/remote-group-expansion.d.ts.map +1 -0
  106. package/lib/types/client/remote-share-css.d.ts +19 -0
  107. package/lib/types/client/remote-share-css.d.ts.map +1 -0
  108. package/lib/types/client/remote-share-register.d.ts +113 -0
  109. package/lib/types/client/remote-share-register.d.ts.map +1 -0
  110. package/lib/types/client/remote-status-css.d.ts +15 -0
  111. package/lib/types/client/remote-status-css.d.ts.map +1 -0
  112. package/lib/types/client/remote-status-register.d.ts +46 -0
  113. package/lib/types/client/remote-status-register.d.ts.map +1 -0
  114. package/lib/types/client/settings/SettingsSection.d.ts +46 -0
  115. package/lib/types/client/settings/SettingsSection.d.ts.map +1 -0
  116. package/lib/types/client/settings/register-settings.d.ts +58 -0
  117. package/lib/types/client/settings/register-settings.d.ts.map +1 -0
  118. package/lib/types/client/settings/settings-css.d.ts +10 -0
  119. package/lib/types/client/settings/settings-css.d.ts.map +1 -0
  120. package/lib/types/client/share/share-preview.d.ts.map +1 -1
  121. package/lib/types/client/styles/composer.css.d.ts +1 -1
  122. package/lib/types/client/styles/composer.css.d.ts.map +1 -1
  123. package/lib/types/client/styles/header.css.d.ts +1 -1
  124. package/lib/types/client/styles/header.css.d.ts.map +1 -1
  125. package/lib/types/client/styles/info.css.d.ts +1 -1
  126. package/lib/types/client/styles/info.css.d.ts.map +1 -1
  127. package/lib/types/client/styles/remote-session.css.d.ts +2 -0
  128. package/lib/types/client/styles/remote-session.css.d.ts.map +1 -0
  129. package/lib/types/client-data/current-session.d.ts +41 -0
  130. package/lib/types/client-data/current-session.d.ts.map +1 -0
  131. package/lib/types/client-data/model-group-side.d.ts +44 -0
  132. package/lib/types/client-data/model-group-side.d.ts.map +1 -0
  133. package/lib/types/client-data/remote-group-expansion.d.ts +76 -0
  134. package/lib/types/client-data/remote-group-expansion.d.ts.map +1 -0
  135. package/lib/types/client-data/remote-status.d.ts +148 -0
  136. package/lib/types/client-data/remote-status.d.ts.map +1 -0
  137. package/lib/types/client-data/settings-form.d.ts +774 -0
  138. package/lib/types/client-data/settings-form.d.ts.map +1 -0
  139. package/lib/types/client-data/shares.d.ts +211 -0
  140. package/lib/types/client-data/shares.d.ts.map +1 -0
  141. package/lib/types/client-pairing.d.ts +114 -0
  142. package/lib/types/client-pairing.d.ts.map +1 -0
  143. package/lib/types/client-routes.d.ts +112 -0
  144. package/lib/types/client-routes.d.ts.map +1 -0
  145. package/lib/types/config.d.ts +200 -0
  146. package/lib/types/config.d.ts.map +1 -0
  147. package/lib/types/fetch-route-intercept.d.ts +156 -0
  148. package/lib/types/fetch-route-intercept.d.ts.map +1 -0
  149. package/lib/types/fingerprint.d.ts +166 -0
  150. package/lib/types/fingerprint.d.ts.map +1 -0
  151. package/lib/types/http.d.ts +41 -0
  152. package/lib/types/http.d.ts.map +1 -0
  153. package/lib/types/index.d.ts +56 -24
  154. package/lib/types/index.d.ts.map +1 -1
  155. package/lib/types/intercept-shape.d.ts +32 -0
  156. package/lib/types/intercept-shape.d.ts.map +1 -0
  157. package/lib/types/intercept.d.ts +442 -0
  158. package/lib/types/intercept.d.ts.map +1 -0
  159. package/lib/types/merge-streams.d.ts +398 -0
  160. package/lib/types/merge-streams.d.ts.map +1 -0
  161. package/lib/types/relay-access.d.ts +310 -0
  162. package/lib/types/relay-access.d.ts.map +1 -0
  163. package/lib/types/relay-client.d.ts +274 -0
  164. package/lib/types/relay-client.d.ts.map +1 -0
  165. package/lib/types/relay-filter.d.ts +103 -0
  166. package/lib/types/relay-filter.d.ts.map +1 -0
  167. package/lib/types/relay-server.d.ts +208 -0
  168. package/lib/types/relay-server.d.ts.map +1 -0
  169. package/lib/types/restart-fields.d.ts +22 -0
  170. package/lib/types/restart-fields.d.ts.map +1 -0
  171. package/lib/types/restart-watcher.d.ts +83 -0
  172. package/lib/types/restart-watcher.d.ts.map +1 -0
  173. package/lib/types/session-reference.d.ts +66 -0
  174. package/lib/types/session-reference.d.ts.map +1 -0
  175. package/lib/types/share-export.d.ts +14 -1
  176. package/lib/types/share-export.d.ts.map +1 -1
  177. package/lib/types/share-ops.d.ts +79 -0
  178. package/lib/types/share-ops.d.ts.map +1 -0
  179. package/lib/types/share-store.d.ts +87 -0
  180. package/lib/types/share-store.d.ts.map +1 -0
  181. package/lib/types/virtual-id.d.ts +52 -0
  182. package/lib/types/virtual-id.d.ts.map +1 -0
  183. package/lib/virtual-id.js +66 -0
  184. package/lib/virtual-id.js.map +1 -0
  185. package/llms.txt +17 -14
  186. package/package.json +60 -50
  187. package/scripts/build-client.mjs +5 -3
  188. package/scripts/check-host-shadow.mjs +19 -2
  189. package/scripts/check-settings-form.mjs +933 -0
  190. package/scripts/check-shares.mjs +397 -0
  191. package/scripts/check-upload-endpoint.mjs +59 -3
  192. package/scripts/sync-doc-version.mjs +8 -15
  193. package/scripts/verify-fingerprint-live.mjs +111 -0
  194. package/src/activity.ts +218 -0
  195. package/src/admin-routes.ts +627 -0
  196. package/src/client/MobileAttachButton.tsx +2 -2
  197. package/src/client/MobileAttachChips.tsx +3 -3
  198. package/src/client/MobileDrawerFooter.tsx +7 -4
  199. package/src/client/MobileHome.tsx +20 -16
  200. package/src/client/MobileHomeChips.tsx +16 -16
  201. package/src/client/MobileNavOverlay.tsx +2 -2
  202. package/src/client/MobileNavToggle.tsx +3 -3
  203. package/src/client/MobileSessionHeader.tsx +63 -42
  204. package/src/client/MobileSessionInfo.tsx +118 -17
  205. package/src/client/RemoteComposerBanner.tsx +76 -0
  206. package/src/client/RemoteHeaderIcon.tsx +103 -0
  207. package/src/client/RemoteShareMenu.tsx +57 -0
  208. package/src/client/RemoteStatusIcon.tsx +91 -0
  209. package/src/client/compat/desktop.ts +22 -0
  210. package/src/client/compat/types.ts +62 -0
  211. package/src/client/current-session-report.ts +164 -0
  212. package/src/client/effects/header-status.ts +21 -17
  213. package/src/client/effects/keyboard-guard.ts +65 -1
  214. package/src/client/effects/model-group-side.ts +132 -0
  215. package/src/client/effects/permission-sheet.ts +149 -0
  216. package/src/client/effects/remote-session.ts +68 -0
  217. package/src/client/effects/turn-fold.ts +52 -0
  218. package/src/client/index.tsx +158 -36
  219. package/src/client/locales.ts +396 -2
  220. package/src/client/remote-fetch.ts +125 -0
  221. package/src/client/remote-group-expansion.ts +190 -0
  222. package/src/client/remote-share-css.ts +54 -0
  223. package/src/client/remote-share-register.ts +244 -0
  224. package/src/client/remote-status-css.ts +64 -0
  225. package/src/client/remote-status-register.ts +107 -0
  226. package/src/client/settings/SettingsSection.tsx +1229 -0
  227. package/src/client/settings/register-settings.ts +116 -0
  228. package/src/client/settings/settings-css.ts +236 -0
  229. package/src/client/share/share-preview.tsx +6 -3
  230. package/src/client/share/share-sheet.tsx +3 -3
  231. package/src/client/styles/composer.css.ts +119 -26
  232. package/src/client/styles/header.css.ts +7 -7
  233. package/src/client/styles/info.css.ts +74 -0
  234. package/src/client/styles/remote-session.css.ts +274 -0
  235. package/src/client-data/current-session.ts +57 -0
  236. package/src/client-data/model-group-side.ts +65 -0
  237. package/src/client-data/remote-group-expansion.ts +145 -0
  238. package/src/client-data/remote-status.ts +374 -0
  239. package/src/client-data/settings-form.ts +1371 -0
  240. package/src/client-data/shares.ts +467 -0
  241. package/src/client-pairing.ts +244 -0
  242. package/src/client-routes.ts +732 -0
  243. package/src/config.ts +447 -0
  244. package/src/fetch-route-intercept.ts +510 -0
  245. package/src/fingerprint.ts +410 -0
  246. package/src/http.ts +68 -0
  247. package/src/index.ts +719 -62
  248. package/src/intercept-shape.ts +87 -0
  249. package/src/intercept.ts +3510 -0
  250. package/src/merge-streams.ts +1279 -0
  251. package/src/relay-access.ts +672 -0
  252. package/src/relay-client.ts +1514 -0
  253. package/src/relay-filter.ts +291 -0
  254. package/src/relay-server.ts +2063 -0
  255. package/src/restart-fields.ts +36 -0
  256. package/src/restart-watcher.ts +140 -0
  257. package/src/session-reference.ts +156 -0
  258. package/src/share-export.ts +26 -1
  259. package/src/share-ops.ts +114 -0
  260. package/src/share-store.ts +373 -0
  261. package/src/virtual-id.ts +74 -0
@@ -0,0 +1,1229 @@
1
+ /**
2
+ * The dsh-zen-remote plugin row's settings block on the Plugins manager
3
+ * (T15 + T15-fix + T16 + T17): the staged row fields inside the official
4
+ * settings-form frame ending in its one save control, and BELOW the form —
5
+ * outside it, so they still render when the configuration namespace is not
6
+ * served — the instant-operation areas. Which areas render follows the row's
7
+ * SAVED role, read from the configForms snapshot's row document — never from
8
+ * a status body (T16-fix 3); when that document carries no role at all (the
9
+ * value lives only in `lan-gate.config.json`), the page probes the
10
+ * lightweight client-config route (both roles register it) for the EFFECTIVE
11
+ * role (T17). A host shows gateway status, pairing, device list and the push
12
+ * probe (POSTing the same-origin admin routes and re-reading `admin/status`);
13
+ * a client shows the server connection form, the connection status line and
14
+ * unpairing (against `client/status`, T16) and NEVER polls `admin/*` — on a
15
+ * client deployment those routes do not exist, and a stale kept body would
16
+ * pin the page to the old role. The poll choice waits out the snapshot's
17
+ * loading state — and the probe, when the row cannot answer — for the same
18
+ * reason. Only field edits stage and save through `ZenRemoteSettingsForm`.
19
+ *
20
+ * Status refreshes never clear what is already on screen (T15-fix 1): a
21
+ * failed refresh keeps the last ready data and says so in a banner — only a
22
+ * failed FIRST load enters the error state, because saving a restart-required
23
+ * field reloads the plugin row (T17) and the first post-save refresh can land
24
+ * inside that reload window (further pulls follow at 1.5s, and for a
25
+ * row-reloading save at 3s and 6s, T17b). Every status request carries a
26
+ * latest-wins ticket (T15-fix 4), so an earlier request that answers late
27
+ * cannot overwrite newer data.
28
+ *
29
+ * Opened through the gateway (`viaGateway`, i.e. on a phone or another
30
+ * browser) the server-local buttons disable and a notice says so — and until
31
+ * one status load answers from the server itself, they count as remote. The
32
+ * summary view renders its one-liner alone and never fetches a thing.
33
+ */
34
+
35
+ import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
36
+ import type { ReactNode } from 'react'
37
+ import type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
38
+ import { Button, SettingsForm, SettingsValueField } from '@deepseek-ai/dsh-client-ui-primitives'
39
+ import type { SettingsFormLabels } from '@deepseek-ai/dsh-client-ui-primitives'
40
+ import {
41
+ ADMIN_ACTION_ROUTE,
42
+ ADMIN_PAIR_ROUTE,
43
+ ADMIN_PUSH_TEST_ROUTE,
44
+ ADMIN_STATUS_ROUTE,
45
+ CLIENT_CLAIM_ROUTE,
46
+ CLIENT_CONFIG_ROUTE,
47
+ CLIENT_RECONNECT_ROUTE,
48
+ CLIENT_STATUS_ROUTE,
49
+ claimDeviceNameOf,
50
+ createLatestGate,
51
+ clientStatusLineOf,
52
+ deriveClientStatusView,
53
+ deriveSettingsView,
54
+ localOpsAllowed,
55
+ normalizePairingCode,
56
+ shouldFollowServerDeviceName,
57
+ } from '../../client-data/settings-form.ts'
58
+ import type {
59
+ AdminStatusBody,
60
+ ClaimRouteBody,
61
+ ClientConfigBody,
62
+ ClientConnectionView,
63
+ ClientStatusBody,
64
+ SettingsDeviceView,
65
+ SettingsFieldState,
66
+ SettingsFieldView,
67
+ SettingsPairingView,
68
+ ZenRemoteSettingsForm,
69
+ } from '../../client-data/settings-form.ts'
70
+ import { NS } from '../locales.ts'
71
+ import { describeShare } from '../../client-data/shares.ts'
72
+ import type { ShareEntryView, SharesStore } from '../../client-data/shares.ts'
73
+
74
+ export interface SettingsSectionProps extends PropsRuntime<'plugins.row.config'>, PropsLocale<typeof NS> {
75
+ /** The staged configuration form (injected share). */
76
+ config: ZenRemoteSettingsForm
77
+ /** The shared shares store (injected share, T33b) — the same singleton the
78
+ * title-row icon and the session menu read. */
79
+ shares: SharesStore
80
+ }
81
+
82
+ /** Device roles the pairing picker offers, in display order. */
83
+ const PAIR_ROLES = ['web', 'desktop-client'] as const
84
+ type PairRole = (typeof PAIR_ROLES)[number]
85
+
86
+ /** Display layouts a device can be pinned to (the gateway's `kind` field). */
87
+ const DEVICE_KINDS = ['auto', 'phone', 'desktop'] as const
88
+
89
+ /** Longest device name, mirroring the gateway's rename cap. */
90
+ const DEVICE_NAME_MAX = 40
91
+
92
+ type PushTest =
93
+ | { state: 'idle' }
94
+ | { state: 'busy' }
95
+ | { state: 'ok', sent: number, failed: number }
96
+ | { state: 'fail' }
97
+
98
+ /** One admin-status load's outcome; `error.status` is undefined for network /
99
+ * non-JSON failures. `stale` keeps the last ready body on screen after a
100
+ * failed refresh (T15-fix 1). */
101
+ type Load =
102
+ | { state: 'loading' }
103
+ | { state: 'ready', body: AdminStatusBody }
104
+ | { state: 'stale', body: AdminStatusBody }
105
+ | { state: 'error', status: number | undefined }
106
+
107
+ /** One client-status load's outcome, same stale contract as {@link Load}. */
108
+ type ClientLoad =
109
+ | { state: 'loading' }
110
+ | { state: 'ready', view: ClientConnectionView }
111
+ | { state: 'stale', view: ClientConnectionView }
112
+ | { state: 'error' }
113
+
114
+ /** One pairing attempt's classified failure, rendered by code. */
115
+ interface PairFail {
116
+ code: string
117
+ retryAfterMs?: number
118
+ }
119
+
120
+ async function postJson(url: string, payload: Record<string, unknown>): Promise<{ ok: boolean, sent: number, failed: number }> {
121
+ try {
122
+ const res = await fetch(url, {
123
+ method: 'POST',
124
+ headers: { 'Content-Type': 'application/json' },
125
+ body: JSON.stringify(payload),
126
+ })
127
+ const body = await res.json().catch(() => ({})) as { ok?: boolean, sent?: unknown, failed?: unknown }
128
+ return {
129
+ ok: res.ok && body.ok === true,
130
+ sent: typeof body.sent === 'number' ? body.sent : 0,
131
+ failed: typeof body.failed === 'number' ? body.failed : 0,
132
+ }
133
+ } catch {
134
+ return { ok: false, sent: 0, failed: 0 }
135
+ }
136
+ }
137
+
138
+ export function SettingsSection(props: SettingsSectionProps) {
139
+ // The summary view is a one-liner only — it must not even fetch
140
+ // admin/status, so every hook (and the fetch) lives in the page component.
141
+ if (props.view === 'summary') {
142
+ return (
143
+ <div data-zen-remote="settings">
144
+ <p className="zr-settings-summary">{props.t('settings.summary')}</p>
145
+ </div>
146
+ )
147
+ }
148
+ return <SettingsSectionPage {...props} />
149
+ }
150
+
151
+ /** Fetch error carrying the HTTP status (undefined for network / non-JSON failures). */
152
+ class StatusError extends Error {
153
+ readonly status: number | undefined
154
+
155
+ constructor(status: number | undefined) {
156
+ super(status === undefined ? 'status unavailable' : `status ${status}`)
157
+ this.name = 'StatusError'
158
+ this.status = status
159
+ }
160
+ }
161
+
162
+ type SectionT = SettingsSectionProps['t']
163
+
164
+ /** Copy of the client group's connection line (T43): the pure
165
+ * {@link clientStatusLineOf} picks the case; this table only binds copy. */
166
+ function clientStatusText(view: ClientConnectionView, now: number, t: SectionT): string {
167
+ const line = clientStatusLineOf(view, now)
168
+ switch (line.kind) {
169
+ case 'connectedName': return t('settings.client.statusConnectedName', { serverName: line.serverName })
170
+ case 'connected': return t('settings.client.statusConnected', { serverUrl: line.serverUrl })
171
+ case 'offlineRetry': return t('settings.client.statusOfflineRetry', { seconds: line.seconds })
172
+ case 'offlineRetrySoon': return t('settings.client.statusOfflineRetrySoon')
173
+ case 'unreachable': return t('settings.client.statusUnreachable')
174
+ case 'revoked': return t('settings.client.statusRevoked')
175
+ case 'incompatible': return t('settings.client.statusIncompatible')
176
+ case 'unexpected': return t('settings.client.statusUnexpected')
177
+ case 'invalidUrl': return t('settings.client.statusInvalidUrl')
178
+ default: return t('settings.client.statusUnpaired')
179
+ }
180
+ }
181
+
182
+ /** Copy of the pairing failure line, one case per claim failure code. The
183
+ * wording is always LOCAL (this build's dictionary), never the server's
184
+ * message — a remote message arrives in the server's language and can leak
185
+ * its internals. */
186
+ function pairFailText(fail: PairFail, t: SectionT): string {
187
+ switch (fail.code) {
188
+ case 'invalid': return t('settings.client.failInvalid')
189
+ case 'insecure-http': return t('settings.client.failInsecureHttp')
190
+ case 'bad-code': return t('settings.client.failBadCode')
191
+ case 'locked': {
192
+ const minutes = Math.max(1, Math.ceil((fail.retryAfterMs ?? 0) / 60000))
193
+ return t('settings.client.failLocked', { minutes })
194
+ }
195
+ case 'unreachable': return t('settings.client.failUnreachable')
196
+ case 'role-mismatch': return t('settings.client.failRoleMismatch')
197
+ default: return t('settings.client.failUnexpected')
198
+ }
199
+ }
200
+
201
+ function SettingsSectionPage({ config, shares, t }: SettingsSectionProps) {
202
+ const form = useSyncExternalStore(
203
+ useCallback((cb: () => void) => config.subscribe(cb), [config]),
204
+ () => config.getSnapshot(),
205
+ )
206
+
207
+ // Latest-wins gates (T15-fix 4): every status request takes a ticket and
208
+ // only the newest may apply its result.
209
+ const statusGate = useMemo(createLatestGate, [])
210
+ const clientGate = useMemo(createLatestGate, [])
211
+
212
+ const [load, setLoad] = useState<Load>({ state: 'loading' })
213
+ const [clientLoad, setClientLoad] = useState<ClientLoad>({ state: 'loading' })
214
+ const [now, setNow] = useState(() => Date.now())
215
+ const [pairRole, setPairRole] = useState<PairRole>('web')
216
+ const [pairBusy, setPairBusy] = useState(false)
217
+ const [pairFailed, setPairFailed] = useState(false)
218
+ // The code the pair route just minted, shown before the status refresh
219
+ // lands (and dropped once it does — the refreshed status carries it).
220
+ const [freshPairing, setFreshPairing] = useState<{ code: string, expiresAt: number, role: 'web' | 'desktop-client' } | null>(null)
221
+ const [deviceBusy, setDeviceBusy] = useState(false)
222
+ const [deviceFailed, setDeviceFailed] = useState(false)
223
+ // The device row currently renamed in place (Electron lacks the blocking
224
+ // JS dialog methods, so renames edit inline).
225
+ const [renaming, setRenaming] = useState<{ id: string, draft: string } | null>(null)
226
+ const [pushTest, setPushTest] = useState<PushTest>({ state: 'idle' })
227
+
228
+ // The client group's pairing form (T16). The address prefills from the row
229
+ // (once the shared form's document is served) until the user types into it;
230
+ // the code normalizes as typed. The registered name is the shared 设备名称
231
+ // field in the role card above (T57) — no separate name box here.
232
+ const [pairUrl, setPairUrl] = useState('')
233
+ const [pairUrlTouched, setPairUrlTouched] = useState(false)
234
+ const [pairCode, setPairCode] = useState('')
235
+ const [claimBusy, setClaimBusy] = useState(false)
236
+ const [claimFail, setClaimFail] = useState<PairFail | null>(null)
237
+ const [claimWriteFailed, setClaimWriteFailed] = useState(false)
238
+ const [unpairBusy, setUnpairBusy] = useState(false)
239
+ const [unpairDone, setUnpairDone] = useState(false)
240
+ // T43: the 立即重连 button's in-flight marker.
241
+ const [reconnectBusy, setReconnectBusy] = useState(false)
242
+
243
+ const loadStatus = useCallback(() => {
244
+ const ticket = statusGate.next()
245
+ fetch(ADMIN_STATUS_ROUTE)
246
+ .then((res) => {
247
+ if (!res.ok) return Promise.reject(new StatusError(res.status))
248
+ return res.json() as Promise<AdminStatusBody>
249
+ })
250
+ .then((body) => {
251
+ // A 200 whose body is not ok:true is a FAILED load (T16-fix2): it
252
+ // throws into the catch, which keeps the last ready data instead of
253
+ // letting a broken body overwrite it.
254
+ if (body?.ok !== true) throw new StatusError(undefined)
255
+ if (!statusGate.isLatest(ticket)) return
256
+ setLoad({ state: 'ready', body })
257
+ setNow(Date.now())
258
+ setFreshPairing(null)
259
+ })
260
+ .catch((error: unknown) => {
261
+ if (!statusGate.isLatest(ticket)) return
262
+ // T15-fix 1: a failed REFRESH keeps the last ready data on screen and
263
+ // says so; only a failed FIRST load enters the error state. Saving a
264
+ // restart-required field reloads the plugin row (T17), so the first
265
+ // post-save refresh can land inside that reload window — the second
266
+ // pull (1.5s later) then lands the fresh values.
267
+ setLoad((prev) => prev.state === 'ready' || prev.state === 'stale'
268
+ ? { state: 'stale', body: prev.body }
269
+ : { state: 'error', status: error instanceof StatusError ? error.status : undefined })
270
+ })
271
+ }, [statusGate])
272
+
273
+ // T59: the SERVER's record of this device's name wins over the row —
274
+ // unless the user is mid-edit (a staged draft in the field). One direct
275
+ // write lands it in the row's serverName; that write's own volatile
276
+ // update reaches the backend with both sides now EQUAL, so the push path
277
+ // stays silent and the two ends cannot bounce the name back and forth.
278
+ // T59-fix: the decision runs HERE, on each FRESH answer, judging the row
279
+ // and the draft AS THEY ARE at that moment — never off a stale
280
+ // `clientView` racing a row change (an effect keyed on the row value
281
+ // would fire on every save with the PREVIOUS poll's name and write the
282
+ // old one straight back over the user's fresh save).
283
+ const followServerDeviceName = useCallback((view: ClientConnectionView): void => {
284
+ if (!config.savedRoleIsClient()) return
285
+ if (view.state !== 'connected') return
286
+ const rowName = typeof config.rowValue('serverName') === 'string' ? config.rowValue('serverName') as string : ''
287
+ if (!shouldFollowServerDeviceName(view.deviceName, rowName, config.hasDraft('serverName'))) return
288
+ void config.writeDeviceName(view.deviceName)
289
+ }, [config])
290
+
291
+ const loadClientStatus = useCallback(() => {
292
+ const ticket = clientGate.next()
293
+ fetch(CLIENT_STATUS_ROUTE)
294
+ .then((res) => {
295
+ if (!res.ok) return Promise.reject(new StatusError(res.status))
296
+ return res.json() as Promise<ClientStatusBody>
297
+ })
298
+ .then((body) => {
299
+ if (!clientGate.isLatest(ticket)) return
300
+ const view = deriveClientStatusView(body)
301
+ setClientLoad({ state: 'ready', view })
302
+ followServerDeviceName(view)
303
+ })
304
+ .catch(() => {
305
+ if (!clientGate.isLatest(ticket)) return
306
+ setClientLoad((prev) => prev.state === 'ready' || prev.state === 'stale'
307
+ ? { state: 'stale', view: prev.view }
308
+ : { state: 'error' })
309
+ })
310
+ }, [clientGate, followServerDeviceName])
311
+
312
+ // The client group's rendered view, hoisted for the countdown ticker and
313
+ // the retry-follow refresh below (T43).
314
+ const clientView = clientLoad.state === 'ready' || clientLoad.state === 'stale' ? clientLoad.view : undefined
315
+ const clientRetryAt = clientView?.nextRetryAt
316
+ const clientCountingDown = clientRetryAt !== undefined
317
+
318
+ // Offline with a pending retry: refresh the status shortly after the
319
+ // retry comes due, so a server that came back flips the line to connected
320
+ // without a manual refresh. A still-offline answer carries the NEXT
321
+ // nextRetryAt and re-arms this effect. A HIDDEN page does not fire the
322
+ // refresh: the timer marks the round missed, and becoming visible catches
323
+ // up once (the same visibility-shaped cadence the stores keep).
324
+ useEffect(() => {
325
+ if (!clientCountingDown) return
326
+ let missed = false
327
+ const timer = window.setTimeout(() => {
328
+ if (document.visibilityState === 'hidden') {
329
+ missed = true
330
+ return
331
+ }
332
+ loadClientStatus()
333
+ }, Math.max(0, (clientRetryAt ?? 0) + 1500 - Date.now()))
334
+ const onVisibility = (): void => {
335
+ if (!missed || document.visibilityState !== 'visible') return
336
+ missed = false
337
+ loadClientStatus()
338
+ }
339
+ document.addEventListener('visibilitychange', onVisibility)
340
+ return () => {
341
+ window.clearTimeout(timer)
342
+ document.removeEventListener('visibilitychange', onVisibility)
343
+ }
344
+ }, [clientCountingDown, clientRetryAt, loadClientStatus])
345
+
346
+ // T43 立即重连: one POST, then refresh now (the state is at least
347
+ // "connecting") and once more after the attempt can have settled.
348
+ const runReconnect = async (): Promise<void> => {
349
+ setReconnectBusy(true)
350
+ try {
351
+ const res = await fetch(CLIENT_RECONNECT_ROUTE, {
352
+ method: 'POST',
353
+ headers: { 'Content-Type': 'application/json' },
354
+ body: '{}',
355
+ })
356
+ if (res.ok) {
357
+ loadClientStatus()
358
+ refreshTimers.current.push(window.setTimeout(() => { loadClientStatus() }, 1500))
359
+ }
360
+ } catch {
361
+ // The refreshes tell the story; nothing to add here.
362
+ }
363
+ setReconnectBusy(false)
364
+ }
365
+
366
+ // The page's role is the SAVED row role from the configForms snapshot —
367
+ // nothing else (T16-fix 3): a client deployment has no admin route at all,
368
+ // so a role judged from admin/status either 404s into host, or — with a
369
+ // stale kept body after a role switch — stays pinned to the old role. The
370
+ // poll choice waits out the snapshot's loading state, so a client row never
371
+ // fires a wasted admin/status; once settled, client polls ONLY
372
+ // client/status.
373
+ const data = load.state === 'ready' || load.state === 'stale'
374
+ ? deriveSettingsView(load.body, { now, rowUser: config.rowUser() })
375
+ : undefined
376
+ const clientRole = config.savedRoleIsClient()
377
+ const statusPoll = config.statusPoll()
378
+
379
+ useEffect(() => {
380
+ if (statusPoll === 'client') loadClientStatus()
381
+ else if (statusPoll === 'admin') loadStatus()
382
+ }, [statusPoll, loadClientStatus, loadStatus])
383
+
384
+ // T59: while CONNECTED the status refreshes on a steady 15s cadence (the
385
+ // heartbeat pace) — that is the channel a server-side rename of this
386
+ // device arrives through; offline the retry-follow effect above owns the
387
+ // timing, and unpaired pages simply never arm this.
388
+ const clientConnected = clientView?.state === 'connected'
389
+ useEffect(() => {
390
+ if (!clientConnected) return
391
+ const timer = window.setInterval(() => { loadClientStatus() }, 15_000)
392
+ return () => { window.clearInterval(timer) }
393
+ }, [clientConnected, loadClientStatus])
394
+
395
+ // T17: when the row document cannot answer the saved role (the value lives
396
+ // only in lan-gate.config.json), probe the client-config route — registered
397
+ // wherever a webServer exists, on either role — for the EFFECTIVE role. A
398
+ // stored row role always wins, so this only fills the gap; a failed probe
399
+ // keeps the pre-T17 host default. Waits out the mirror's loading phase,
400
+ // like the poll choice above.
401
+ const scopeStatus = form.scopeStatus
402
+ const roleKnown = config.rowRoleKnown()
403
+ useEffect(() => {
404
+ if (scopeStatus === 'loading' || roleKnown) return
405
+ let cancelled = false
406
+ fetch(CLIENT_CONFIG_ROUTE)
407
+ .then((res) => (res.ok ? (res.json() as Promise<ClientConfigBody>) : undefined))
408
+ .then((body) => {
409
+ if (!cancelled) config.setProbedRole(body?.role === 'client' ? 'client' : 'host')
410
+ })
411
+ .catch(() => {
412
+ if (!cancelled) config.setProbedRole('host')
413
+ })
414
+ return () => { cancelled = true }
415
+ }, [scopeStatus, roleKnown, config])
416
+
417
+ // Feed the effective values the fields display (and compare drafts against)
418
+ // — but ONLY while the page actually polls the admin source (T55): a role
419
+ // switch leaves the host page's kept status load (and its fed baseline) in
420
+ // place forever, because a client page never refreshes admin/status again.
421
+ // The form also refuses the baseline under a client poll, but the stale
422
+ // values are dropped here as well, so the fields fall back to the row's
423
+ // stored values the moment the row moves.
424
+ useEffect(() => {
425
+ if (statusPoll !== 'admin') {
426
+ config.setBaseline(undefined)
427
+ return
428
+ }
429
+ if (load.state !== 'ready') return
430
+ config.setBaseline(load.body.config?.values)
431
+ }, [load, config, statusPoll])
432
+
433
+ // Re-render every second while a pairing code is on screen so the countdown
434
+ // follows; both display paths drop the code once `expiresAt` passes. T43:
435
+ // the same ticker drives the offline "将于 N 秒后重试" countdown.
436
+ const pairingShown = data?.pairing !== null && data?.pairing !== undefined
437
+ || (freshPairing !== null && freshPairing.expiresAt > now)
438
+ useEffect(() => {
439
+ if (!pairingShown && !clientCountingDown) return
440
+ const timer = window.setInterval(() => { setNow(Date.now()) }, 1000)
441
+ return () => { window.clearInterval(timer) }
442
+ }, [pairingShown, clientCountingDown])
443
+
444
+ // Environment-locked fields cannot be staged: a written value would be
445
+ // shadowed by the variable anyway. The controller refuses them; this effect
446
+ // keeps its lock set in step with admin/status. The same pass feeds the
447
+ // saved-invalid set (T15-fix 3): those fields keep showing the RAW stored
448
+ // value instead of the resolved one.
449
+ const fieldEntries = data === undefined ? [] : Object.entries(data.fields)
450
+ const lockedKey = fieldEntries
451
+ .filter(([, fv]) => fv.locked)
452
+ .map(([field]) => field)
453
+ .join(',')
454
+ const rowInvalidKey = fieldEntries
455
+ .filter(([, fv]) => fv.savedRowInvalid)
456
+ .map(([field]) => field)
457
+ .join(',')
458
+ useEffect(() => {
459
+ config.setLockedFields(lockedKey === '' ? [] : lockedKey.split(','))
460
+ }, [lockedKey, config])
461
+ useEffect(() => {
462
+ config.setRowInvalidFields(rowInvalidKey === '' ? [] : rowInvalidKey.split(','))
463
+ }, [rowInvalidKey, config])
464
+
465
+ // Post-save double refresh (T15-fix 1): once immediately, once after 1.5s —
466
+ // saving a restart-required field reloads the plugin row (T17) and the
467
+ // first refresh can land inside that window. Timers are released if the
468
+ // page unmounts.
469
+ const refreshTimers = useRef<number[]>([])
470
+ useEffect(() => () => {
471
+ for (const timer of refreshTimers.current) window.clearTimeout(timer)
472
+ refreshTimers.current = []
473
+ }, [])
474
+
475
+ // Pairing, device management and the push probe are server-local acts: they
476
+ // stay disabled until a status load answers AND it answered as the local
477
+ // machine (a remote device gets viaGateway: true) — localOpsAllowed.
478
+ const localOps = localOpsAllowed(data)
479
+ const localBusy = pairBusy || deviceBusy
480
+
481
+ const runPair = async (): Promise<void> => {
482
+ setPairBusy(true)
483
+ setPairFailed(false)
484
+ try {
485
+ const res = await fetch(ADMIN_PAIR_ROUTE, {
486
+ method: 'POST',
487
+ headers: { 'Content-Type': 'application/json' },
488
+ body: JSON.stringify({ role: pairRole }),
489
+ })
490
+ const body = await res.json().catch(() => ({})) as { ok?: boolean, code?: unknown, expiresAt?: unknown, role?: unknown }
491
+ if (res.ok && body.ok === true && typeof body.code === 'string' && body.code !== '' && typeof body.expiresAt === 'number') {
492
+ setFreshPairing({
493
+ code: body.code,
494
+ expiresAt: body.expiresAt,
495
+ role: body.role === 'desktop-client' ? 'desktop-client' : 'web',
496
+ })
497
+ setNow(Date.now())
498
+ loadStatus()
499
+ } else {
500
+ setPairFailed(true)
501
+ }
502
+ } catch {
503
+ setPairFailed(true)
504
+ }
505
+ setPairBusy(false)
506
+ }
507
+
508
+ const runDeviceAction = async (payload: Record<string, unknown>): Promise<void> => {
509
+ setDeviceBusy(true)
510
+ setDeviceFailed(false)
511
+ const result = await postJson(ADMIN_ACTION_ROUTE, payload)
512
+ if (result.ok) loadStatus()
513
+ else setDeviceFailed(true)
514
+ setDeviceBusy(false)
515
+ }
516
+
517
+ const commitRename = (device: SettingsDeviceView): void => {
518
+ if (renaming === null || renaming.id !== device.id) return
519
+ const name = renaming.draft.trim()
520
+ setRenaming(null)
521
+ if (name === '' || name === device.name) return
522
+ void runDeviceAction({ action: 'rename', id: device.id, name })
523
+ }
524
+
525
+ const runPushTest = async (): Promise<void> => {
526
+ setPushTest({ state: 'busy' })
527
+ const result = await postJson(ADMIN_PUSH_TEST_ROUTE, {})
528
+ setPushTest(result.ok ? { state: 'ok', sent: result.sent, failed: result.failed } : { state: 'fail' })
529
+ }
530
+
531
+ // --- client group (T16) ----------------------------------------------------
532
+
533
+ // The address prefill reads the row's stored serverUrl while the user has
534
+ // not typed anything of their own.
535
+ const rowServerUrl = typeof config.rowValue('serverUrl') === 'string' ? config.rowValue('serverUrl') as string : ''
536
+ useEffect(() => {
537
+ if (pairUrlTouched || pairUrl !== '' || rowServerUrl === '') return
538
+ setPairUrl(rowServerUrl)
539
+ }, [pairUrlTouched, pairUrl, rowServerUrl])
540
+
541
+ const codeNormalized = normalizePairingCode(pairCode)
542
+ // T60: an INVALID device-name draft (red box — blank-but-nonempty or over
543
+ // the cap) blocks the pairing: the claim would silently substitute the
544
+ // default copy and the server would register a name the user never asked
545
+ // for. A VALID draft pairs fine — it lands in the row with the write.
546
+ const claimAllowed = form.available && form.writable && !claimBusy && codeNormalized.length === 8 && !form.serverName.invalid
547
+
548
+ const runClaim = async (): Promise<void> => {
549
+ setClaimBusy(true)
550
+ setClaimFail(null)
551
+ setClaimWriteFailed(false)
552
+ // T60: one name for both halves of the round-trip — trimmed and legal
553
+ // ({@link claimDeviceNameOf}), sent to the server AND written into the
554
+ // row when the claim lands.
555
+ const claimName = claimDeviceNameOf(form.serverName.text, t('settings.client.deviceNameDefault'))
556
+ try {
557
+ const res = await fetch(CLIENT_CLAIM_ROUTE, {
558
+ method: 'POST',
559
+ headers: { 'Content-Type': 'application/json' },
560
+ // T57: the name registers under the shared 设备名称 field's current
561
+ // displayed value (a staged draft counts), falling back to the
562
+ // default copy when the field is empty — the client page reads no
563
+ // admin baseline (T55), so an unstored name displays empty here.
564
+ body: JSON.stringify({
565
+ serverUrl: pairUrl.trim(),
566
+ code: codeNormalized,
567
+ name: claimName,
568
+ }),
569
+ })
570
+ const body = await res.json().catch(() => ({})) as ClaimRouteBody
571
+ if (res.ok && body.ok === true && typeof body.token === 'string' && body.token !== '') {
572
+ // The backend echoes the address it validated; write the credentials
573
+ // AND the registered name through ONE mutate, then clear the code
574
+ // and re-read the connection state. The name is the SERVER's
575
+ // confirmed echo when the claim carried one (the gateway may have
576
+ // trimmed or uniquified it at registration), else the name we
577
+ // actually sent (T60) — either way the row now matches the server.
578
+ const urlToWrite = typeof body.serverUrl === 'string' && body.serverUrl !== '' ? body.serverUrl : pairUrl.trim()
579
+ // T59-fix: the echo is judged by the SAME rules as our own draft
580
+ // (claimDeviceNameOf trims and validates) — a server answer we
581
+ // could not store falls back to the name we actually sent.
582
+ const echoed = typeof body.deviceName === 'string' && body.deviceName !== '' ? claimDeviceNameOf(body.deviceName, claimName) : claimName
583
+ const landed = await config.writeClientPairing(urlToWrite, body.token, echoed)
584
+ if (landed) {
585
+ // The draft did its job — it now equals the displayed value, and
586
+ // keeping it would be a phantom edit (T60).
587
+ config.discardField('serverName')
588
+ setPairCode('')
589
+ setPairUrl(urlToWrite)
590
+ setUnpairDone(false)
591
+ loadClientStatus()
592
+ } else {
593
+ setClaimWriteFailed(true)
594
+ }
595
+ } else {
596
+ // Every other shape is a failure (T16-fix): a non-OK status, a body
597
+ // whose `ok` is not true, a missing token — shown with the classified
598
+ // code when the route sent one. The body's `message` is ignored: the
599
+ // wording is this build's dictionary (pairFailText).
600
+ const fail: PairFail = { code: typeof body.code === 'string' && body.code !== '' ? body.code : 'unexpected' }
601
+ if (typeof body.retryAfterMs === 'number') fail.retryAfterMs = body.retryAfterMs
602
+ setClaimFail(fail)
603
+ }
604
+ } catch {
605
+ setClaimFail({ code: 'unexpected' })
606
+ }
607
+ setClaimBusy(false)
608
+ }
609
+
610
+ const runUnpair = async (): Promise<void> => {
611
+ if (!window.confirm(t('settings.client.unpairConfirm'))) return
612
+ setUnpairBusy(true)
613
+ const landed = await config.clearDeviceToken()
614
+ setUnpairBusy(false)
615
+ if (landed) {
616
+ setUnpairDone(true)
617
+ loadClientStatus()
618
+ }
619
+ }
620
+
621
+ const formDisabled = !form.available || !form.writable
622
+
623
+ // T17: saving any restart-required field (the role among them) moves the
624
+ // row, and the host half's watcher reloads it — the gateway child restarts
625
+ // with it. T17b narrowed the flag to drafts that would actually change the
626
+ // effective value (a re-typed identical value or an env-locked field no
627
+ // longer promise a reload), so the note appears exactly when a save will
628
+ // move the row, and vanishes on discard or save.
629
+ const reloadPending = form.restartPending
630
+
631
+ // The code shown under the pairing controls: the refreshed status's, or the
632
+ // one the pair route just returned while the refresh is in flight.
633
+ const shownPairing: SettingsPairingView | null = data?.pairing
634
+ ?? (freshPairing !== null && freshPairing.expiresAt > now
635
+ ? {
636
+ code: freshPairing.code,
637
+ role: freshPairing.role,
638
+ remainingSeconds: Math.max(0, Math.ceil((freshPairing.expiresAt - now) / 1000)),
639
+ }
640
+ : null)
641
+
642
+ const labels: SettingsFormLabels = {
643
+ unavailable: t('settings.unavailable'),
644
+ readOnly: t('settings.readOnly'),
645
+ saveFailed: t('settings.saveFailed'),
646
+ save: t('settings.save'),
647
+ saving: t('settings.saving'),
648
+ }
649
+
650
+ /** The per-field source annotations (file badge, env lock, invalid saved value). */
651
+ const annotations = (field: string): ReactNode => {
652
+ const fv: SettingsFieldView | undefined = data?.fields[field as keyof typeof data.fields]
653
+ if (fv === undefined) return null
654
+ return (
655
+ <>
656
+ {fv.fromFile && <p className="zr-settings-hint">{t('settings.sourceFileBadge')}</p>}
657
+ {fv.locked && <p className="zr-settings-hint" data-invalid="true">{t('settings.sourceEnvBadge')}</p>}
658
+ {fv.savedRowInvalid && (
659
+ <p className="zr-settings-hint" data-invalid="true">
660
+ {t('settings.savedInvalid', { source: sourceName(fv.source, t) })}
661
+ </p>
662
+ )}
663
+ </>
664
+ )
665
+ }
666
+
667
+ /** The "saving a staged clear reverts to the next layer" hint (T15-fix 2). */
668
+ const clearPreviewNote = (state: SettingsFieldState): ReactNode =>
669
+ state.cleared ? <p className="zr-settings-hint">{t('settings.resetPreview')}</p> : null
670
+
671
+ const text = (state: SettingsFieldState, field: string, label: string, hint: string, invalidLabel: string, numeric = false, note?: string) => (
672
+ <div className="zr-settings-field" key={field}>
673
+ <SettingsValueField
674
+ id={`zr-settings-${field}`}
675
+ label={label}
676
+ hint={hint}
677
+ numeric={numeric}
678
+ overriddenLabel={t('settings.overridden')}
679
+ resetLabel={t('settings.reset')}
680
+ invalidLabel={invalidLabel}
681
+ disabled={formDisabled || state.locked}
682
+ text={state.text}
683
+ overridden={state.overridden}
684
+ invalid={state.invalid}
685
+ onEdit={(value) => { config.stage(field, value) }}
686
+ onReset={() => { config.resetField(field) }}
687
+ />
688
+ {note !== undefined && <p className="zr-settings-hint">{note}</p>}
689
+ {clearPreviewNote(state)}
690
+ {annotations(field)}
691
+ </div>
692
+ )
693
+
694
+ // One-of control (the shared fields have no select): the shared field chrome, a select body.
695
+ const select = (state: SettingsFieldState, field: string, label: string, hint: string, options: readonly string[], optionLabel: (option: string) => string) => (
696
+ <div className="zr-settings-field" key={field}>
697
+ <div className="zr-settings-head">
698
+ <label htmlFor={`zr-settings-${field}`}>{label}</label>
699
+ {state.overridden && <span className="zr-settings-badge">{t('settings.overridden')}</span>}
700
+ {state.overridden && (
701
+ <button type="button" className="zr-settings-reset" disabled={formDisabled || state.locked} onClick={() => { config.resetField(field) }}>{t('settings.reset')}</button>
702
+ )}
703
+ </div>
704
+ <select
705
+ id={`zr-settings-${field}`}
706
+ className="zr-settings-input"
707
+ disabled={formDisabled || state.locked}
708
+ value={state.text}
709
+ onChange={(e) => { config.stage(field, e.currentTarget.value) }}
710
+ >
711
+ {options.map((option) => <option key={option} value={option}>{optionLabel(option)}</option>)}
712
+ </select>
713
+ {hint !== '' && <p className="zr-settings-hint">{hint}</p>}
714
+ {clearPreviewNote(state)}
715
+ {annotations(field)}
716
+ </div>
717
+ )
718
+
719
+ // Boolean control (the shared fields have no checkbox): label row + switch.
720
+ const bool = (state: SettingsFieldState, field: string, label: string, hint: string) => (
721
+ <div className="zr-settings-field" key={field}>
722
+ <div className="zr-settings-head">
723
+ <label htmlFor={`zr-settings-${field}`}>{label}</label>
724
+ {state.overridden && <span className="zr-settings-badge">{t('settings.overridden')}</span>}
725
+ {state.overridden && (
726
+ <button type="button" className="zr-settings-reset" disabled={formDisabled || state.locked} onClick={() => { config.resetField(field) }}>{t('settings.reset')}</button>
727
+ )}
728
+ <span className="zr-settings-check-row">
729
+ <input
730
+ id={`zr-settings-${field}`}
731
+ type="checkbox"
732
+ disabled={formDisabled || state.locked}
733
+ checked={state.text === 'true'}
734
+ onChange={(e) => { config.stage(field, e.currentTarget.checked ? 'true' : 'false') }}
735
+ />
736
+ </span>
737
+ </div>
738
+ <p className="zr-settings-hint">{hint}</p>
739
+ {clearPreviewNote(state)}
740
+ {annotations(field)}
741
+ </div>
742
+ )
743
+
744
+ const deviceRow = (device: SettingsDeviceView) => (
745
+ <div className="zr-settings-device" key={device.id}>
746
+ <div className="zr-settings-device-head">
747
+ <span className="zr-settings-device-name">{device.name}</span>
748
+ <span className="zr-settings-badge">{device.role === 'web' ? t('settings.deviceRoleWeb') : t('settings.deviceRoleDesktop')}</span>
749
+ <span className="zr-settings-badge">{device.hasPush ? t('settings.devicePushOn') : t('settings.devicePushOff')}</span>
750
+ <span className="zr-settings-hint">{t('settings.deviceLastSeen', { time: new Date(device.lastSeen).toLocaleString() })}</span>
751
+ </div>
752
+ <div className="zr-settings-device-actions">
753
+ <select
754
+ className="zr-settings-input"
755
+ aria-label={t('settings.deviceRoleSelect', { name: device.name })}
756
+ disabled={!localOps || localBusy}
757
+ value={device.role}
758
+ onChange={(e) => { void runDeviceAction({ action: 'set-role', id: device.id, role: e.currentTarget.value }) }}
759
+ >
760
+ <option value="web">{t('settings.deviceRoleWeb')}</option>
761
+ <option value="desktop-client">{t('settings.deviceRoleDesktop')}</option>
762
+ </select>
763
+ <select
764
+ className="zr-settings-input"
765
+ aria-label={t('settings.deviceKindSelect', { name: device.name })}
766
+ disabled={!localOps || localBusy}
767
+ value={device.kind}
768
+ onChange={(e) => { void runDeviceAction({ action: 'set-kind', id: device.id, kind: e.currentTarget.value }) }}
769
+ >
770
+ {DEVICE_KINDS.map((kind) => (
771
+ <option key={kind} value={kind}>
772
+ {kind === 'auto' ? t('settings.kindAuto') : kind === 'phone' ? t('settings.kindPhone') : t('settings.kindDesktop')}
773
+ </option>
774
+ ))}
775
+ </select>
776
+ <Button variant="ghost" size="sm" disabled={!localOps || localBusy} onClick={() => { setRenaming({ id: device.id, draft: device.name }) }}>
777
+ {t('settings.deviceRename')}
778
+ </Button>
779
+ <Button variant="ghost" size="sm" disabled={!localOps || localBusy} onClick={() => {
780
+ if (window.confirm(t('settings.revokeConfirm'))) void runDeviceAction({ action: 'revoke', id: device.id })
781
+ }}>{t('settings.deviceRevoke')}</Button>
782
+ </div>
783
+ {renaming?.id === device.id && (
784
+ <div className="zr-settings-row">
785
+ {/* Electron lacks the blocking JS dialog methods: the rename edits in place. */}
786
+ <input
787
+ className="zr-settings-input"
788
+ aria-label={t('settings.renamePrompt')}
789
+ maxLength={DEVICE_NAME_MAX}
790
+ value={renaming.draft}
791
+ autoFocus
792
+ onChange={(e) => { setRenaming({ id: device.id, draft: e.currentTarget.value }) }}
793
+ onKeyDown={(e) => {
794
+ if (e.key === 'Enter') commitRename(device)
795
+ if (e.key === 'Escape') setRenaming(null)
796
+ }}
797
+ />
798
+ <Button variant="outline" size="sm" disabled={localBusy} onClick={() => { commitRename(device) }}>{t('settings.renameSave')}</Button>
799
+ <Button variant="ghost" size="sm" disabled={localBusy} onClick={() => { setRenaming(null) }}>{t('settings.renameCancel')}</Button>
800
+ </div>
801
+ )}
802
+ </div>
803
+ )
804
+
805
+ // Whether a landed save moved a restart-required field — read BEFORE save()
806
+ // clears the staged drafts (T17b): the projected snapshot's restartPending
807
+ // is exactly "the plan writes a restart-field op" (value actually differs,
808
+ // not env-locked), which is what decides the refresh cadence below.
809
+ const saveReloadsRow = (): boolean => config.getSnapshot().restartPending
810
+ const saveLanded = (reloadsRow: boolean): void => {
811
+ // A landed save that switched the role drops the OTHER role's data right
812
+ // away (T16-fix 3) — a stale device list or connection line must not
813
+ // survive the switch, and the poll effect alone would leave the old
814
+ // body on screen. The delayed pulls re-read the role at fire time: the
815
+ // first pull can land inside a row-restart window.
816
+ if (config.savedRoleIsClient()) setLoad({ state: 'loading' })
817
+ else setClientLoad({ state: 'loading' })
818
+ const refresh = config.savedRoleIsClient() ? loadClientStatus : loadStatus
819
+ refresh()
820
+ // Immediate pull + 1.5s covers a hot-only save. A save that reloads the
821
+ // plugin row (T17) restarts the row and the gateway child with it — the
822
+ // reload and the gateway's rebinding of its port both take longer than
823
+ // one slot, so two more pulls at 3s and 6s cover the whole window
824
+ // (T17b); each pull re-reads the role in case the switch lands mid-way.
825
+ const pulls: readonly number[] = reloadsRow ? [1500, 3000, 6000] : [1500]
826
+ for (const delay of pulls) {
827
+ refreshTimers.current.push(window.setTimeout(() => {
828
+ if (config.savedRoleIsClient()) loadClientStatus()
829
+ else loadStatus()
830
+ }, delay))
831
+ }
832
+ }
833
+
834
+ return (
835
+ <div data-zen-remote="settings">
836
+ {!clientRole && load.state === 'error' && (
837
+ <p className="zr-settings-hint" data-invalid="true">
838
+ {load.status === undefined
839
+ ? t('settings.statusUnknown')
840
+ : t('settings.statusUnavailable', { code: load.status })}
841
+ </p>
842
+ )}
843
+ {!clientRole && load.state === 'stale' && (
844
+ <p className="zr-settings-hint" data-invalid="true">{t('settings.refreshFailed')}</p>
845
+ )}
846
+ {clientRole && clientLoad.state === 'error' && (
847
+ <p className="zr-settings-hint" data-invalid="true">{t('settings.statusUnknown')}</p>
848
+ )}
849
+ {clientRole && clientLoad.state === 'stale' && (
850
+ <p className="zr-settings-hint" data-invalid="true">{t('settings.refreshFailed')}</p>
851
+ )}
852
+ {data?.viaGateway === true && <p className="zr-settings-notice">{t('settings.remoteNotice')}</p>}
853
+
854
+ {/* The staged row fields — the only part the settings-form frame owns. */}
855
+ <div className="zr-settings-card">
856
+ <SettingsForm
857
+ labels={labels}
858
+ state={form}
859
+ onSave={() => {
860
+ const reloadsRow = saveReloadsRow()
861
+ void config.save().then((landed) => { if (landed) saveLanded(reloadsRow) })
862
+ }}
863
+ onDiscard={() => { config.discard() }}
864
+ >
865
+ <h3 className="zr-settings-card-title">{t('settings.roleTitle')}</h3>
866
+ {select(form.role, 'role', t('settings.role'), t('settings.roleHint'), ['host', 'client'], (option) => (
867
+ option === 'host' ? t('settings.roleHost') : t('settings.roleClient')
868
+ ))}
869
+ {/* T57: the device name — the row's serverName field — lives in the
870
+ role card on BOTH roles: on a host it is the server display name
871
+ other devices' sidebars show; on a client it is the name a
872
+ pairing registers with. The hint is the one role fact that
873
+ differs. */}
874
+ {text(
875
+ form.serverName,
876
+ 'serverName',
877
+ t('settings.fieldServerName'),
878
+ t(clientRole ? 'settings.fieldServerNameHintClient' : 'settings.fieldServerNameHint'),
879
+ t('settings.invalidName'),
880
+ )}
881
+ {reloadPending && <p className="zr-settings-status-line">{t('settings.reloadNote')}</p>}
882
+
883
+ {!clientRole && (
884
+ <>
885
+ <h3 className="zr-settings-card-title">{t('settings.gatewayTitle')}</h3>
886
+ {text(form.host, 'host', t('settings.fieldHost'), t('settings.fieldHostHint'), '', false, t('settings.fieldHostNote'))}
887
+ {text(form.port, 'port', t('settings.fieldPort'), t('settings.fieldPortHint'), t('settings.invalidPort'), true)}
888
+ {text(form.trustedProxies, 'trustedProxies', t('settings.fieldTrustedProxies'), t('settings.fieldTrustedProxiesHint'), '')}
889
+ {text(form.rateLimit, 'rateLimit', t('settings.fieldRateLimit'), t('settings.fieldRateLimitHint'), t('settings.invalidPositiveInt'), true)}
890
+ {text(form.vapidSubject, 'vapidSubject', t('settings.fieldVapidSubject'), t('settings.fieldVapidSubjectHint'), '')}
891
+
892
+ <h3 className="zr-settings-card-title">{t('settings.pushTitle')}</h3>
893
+ {bool(form.pushSummary, 'pushSummary', t('settings.fieldPushSummary'), t('settings.fieldPushSummaryHint'))}
894
+ {bool(form.pushTurnEnd, 'pushTurnEnd', t('settings.fieldPushTurnEnd'), t('settings.fieldPushTurnEndHint'))}
895
+ {bool(form.pushTool, 'pushTool', t('settings.fieldPushTool'), t('settings.fieldPushToolHint'))}
896
+ {text(form.pushDebounceMs, 'pushDebounceMs', t('settings.fieldPushDebounceMs'), t('settings.fieldPushDebounceMsHint'), t('settings.invalidNonNegativeInt'), true)}
897
+ {select(form.lang, 'lang', t('settings.fieldLang'), t('settings.fieldLangHint'), ['auto', 'zh', 'en'], (option) => (
898
+ option === 'auto' ? t('settings.langAuto') : option === 'zh' ? t('settings.langZh') : t('settings.langEn')
899
+ ))}
900
+
901
+ <h3 className="zr-settings-card-title">{t('settings.shareTitle')}</h3>
902
+ {text(form.idleHours, 'idleHours', t('settings.fieldIdleHours'), t('settings.fieldIdleHoursHint'), t('settings.invalidHours'), true)}
903
+ {bool(form.autoShareNewSessions, 'autoShareNewSessions', t('settings.fieldAutoShare'), t('settings.fieldAutoShareHint'))}
904
+ </>
905
+ )}
906
+ </SettingsForm>
907
+ </div>
908
+
909
+ {/* Instant operations — outside the form frame, so pairing, device
910
+ management and the gateway status stay visible even while the
911
+ configuration namespace is unavailable or read-only. */}
912
+ {!clientRole && (
913
+ <div className="zr-settings-card">
914
+ <p className="zr-settings-status-line" data-down={data !== undefined && !data.gatewayReachable && !data.gatewayAbnormal ? 'true' : undefined}>
915
+ {data === undefined
916
+ ? ''
917
+ : data.gatewayAbnormal
918
+ ? t('settings.gatewayAbnormal', { code: data.gatewayStatus })
919
+ : data.gatewayReachable
920
+ ? t('settings.gatewayRunning', { port: data.gatewayPort ?? '?', target: data.gatewayTarget ?? '?' })
921
+ : t('settings.gatewayDown')}
922
+ </p>
923
+
924
+ <h3 className="zr-settings-card-title">{t('settings.pairingTitle')}</h3>
925
+ <div className="zr-settings-role-cards">
926
+ {PAIR_ROLES.map((role) => (
927
+ <label className="zr-settings-role-card" key={role} data-active={pairRole === role ? 'true' : undefined}>
928
+ <span className="zr-settings-role-card-title">
929
+ <input
930
+ type="radio"
931
+ name="zr-settings-pair-role"
932
+ checked={pairRole === role}
933
+ onChange={() => { setPairRole(role) }}
934
+ />
935
+ {role === 'web' ? t('settings.deviceRoleWeb') : t('settings.deviceRoleDesktop')}
936
+ </span>
937
+ <span className="zr-settings-hint">
938
+ {role === 'web' ? t('settings.pairingWebGuide') : t('settings.pairingDesktopGuide')}
939
+ </span>
940
+ </label>
941
+ ))}
942
+ </div>
943
+ <div className="zr-settings-row" style={{ paddingBottom: 12 }}>
944
+ <Button variant="outline" size="sm" disabled={!localOps || pairBusy} onClick={() => { void runPair() }}>
945
+ {pairBusy ? t('settings.pairingGenerating') : t('settings.pairingGenerate')}
946
+ </Button>
947
+ {pairFailed && <span className="zr-settings-hint" data-invalid="true">{t('settings.pairingFail')}</span>}
948
+ </div>
949
+ {shownPairing !== null && (
950
+ <div className="zr-settings-field">
951
+ <div className="zr-settings-head">
952
+ {/* Not a form control anywhere near: a span, not a control-less label. */}
953
+ <span className="zr-settings-head-title">{t('settings.pairingCodeLabel')}</span>
954
+ <span className="zr-settings-badge">{shownPairing.role === 'web' ? t('settings.deviceRoleWeb') : t('settings.deviceRoleDesktop')}</span>
955
+ <span className="zr-settings-badge" data-warn="true">{t('settings.pairingRemaining', { count: shownPairing.remainingSeconds })}</span>
956
+ </div>
957
+ <p className="zr-settings-pair-code">{shownPairing.code}</p>
958
+ </div>
959
+ )}
960
+
961
+ <h3 className="zr-settings-card-title">{t('settings.devicesTitle')}</h3>
962
+ {(data?.devices.length ?? 0) === 0 && <p className="zr-settings-hint">{t('settings.devicesEmpty')}</p>}
963
+ {data?.devices.map(deviceRow)}
964
+ {deviceFailed && <p className="zr-settings-hint" data-invalid="true">{t('settings.actionFail')}</p>}
965
+ {(data?.devices.length ?? 0) > 0 && (
966
+ <div className="zr-settings-row" style={{ paddingBottom: 12 }}>
967
+ <Button variant="ghost" size="sm" disabled={!localOps || localBusy} onClick={() => {
968
+ if (window.confirm(t('settings.revokeAllConfirm'))) void runDeviceAction({ action: 'revoke-all' })
969
+ }}>{t('settings.revokeAll')}</Button>
970
+ </div>
971
+ )}
972
+
973
+ <div className="zr-settings-field">
974
+ <div className="zr-settings-head">
975
+ {/* The row's control is a Button (not labelable): a span, not a control-less label. */}
976
+ <span className="zr-settings-head-title">{t('settings.pushTestLabel')}</span>
977
+ <span style={{ flex: 1 }} />
978
+ <Button variant="outline" size="sm" disabled={!localOps || pushTest.state === 'busy'} onClick={() => { void runPushTest() }}>
979
+ {pushTest.state === 'busy' ? t('settings.pushTestRunning') : t('settings.pushTestRun')}
980
+ </Button>
981
+ </div>
982
+ {pushTest.state === 'ok' && <p className="zr-settings-hint">{t('settings.pushTestOk', { sent: pushTest.sent, failed: pushTest.failed })}</p>}
983
+ {pushTest.state === 'fail' && <p className="zr-settings-hint" data-invalid="true">{t('settings.pushTestFail')}</p>}
984
+ </div>
985
+
986
+ <SharesList shares={shares} t={t} />
987
+ </div>
988
+ )}
989
+
990
+ {/* The client group (T16): server connection, connection status and
991
+ unpairing — same outside-the-frame placement as the host's instant
992
+ operations, so they render even while the namespace is read-only. */}
993
+ {clientRole && (
994
+ <div className="zr-settings-card">
995
+ <h3 className="zr-settings-card-title">{t('settings.client.connectTitle')}</h3>
996
+ <div className="zr-settings-field">
997
+ <div className="zr-settings-head">
998
+ <label htmlFor="zr-settings-client-server">{t('settings.client.serverUrl')}</label>
999
+ </div>
1000
+ <input
1001
+ id="zr-settings-client-server"
1002
+ className="zr-settings-input"
1003
+ type="text"
1004
+ autoComplete="off"
1005
+ spellCheck={false}
1006
+ value={pairUrl}
1007
+ onChange={(e) => { setPairUrl(e.currentTarget.value); setPairUrlTouched(true) }}
1008
+ />
1009
+ <p className="zr-settings-hint">{t('settings.client.serverUrlHint')}</p>
1010
+ </div>
1011
+ <div className="zr-settings-field">
1012
+ <div className="zr-settings-head">
1013
+ <label htmlFor="zr-settings-client-code">{t('settings.client.pairingCode')}</label>
1014
+ </div>
1015
+ <input
1016
+ id="zr-settings-client-code"
1017
+ className="zr-settings-input zr-settings-code-input"
1018
+ type="text"
1019
+ autoComplete="off"
1020
+ spellCheck={false}
1021
+ // No maxLength: the draft is normalized (uppercased, spaces and
1022
+ // hyphens stripped) on every keystroke, and only the
1023
+ // NORMALIZED length gates the pair button — a code pasted with
1024
+ // separators must survive pasting intact.
1025
+ value={pairCode}
1026
+ onChange={(e) => { setPairCode(normalizePairingCode(e.currentTarget.value)) }}
1027
+ />
1028
+ <p className="zr-settings-hint">{t('settings.client.pairingCodeHint')}</p>
1029
+ </div>
1030
+ <div className="zr-settings-row" style={{ paddingBottom: 12 }}>
1031
+ <Button variant="outline" size="sm" disabled={!claimAllowed} onClick={() => { void runClaim() }}>
1032
+ {claimBusy ? t('settings.client.pairing') : t('settings.client.pair')}
1033
+ </Button>
1034
+ {/* T60: the pairing button is disabled while the device-name
1035
+ draft is invalid — this line says why. */}
1036
+ {form.serverName.invalid && <span className="zr-settings-hint" data-invalid="true">{t('settings.client.fixDeviceName')}</span>}
1037
+ {claimFail !== null && <span className="zr-settings-hint" data-invalid="true">{pairFailText(claimFail, t)}</span>}
1038
+ {claimWriteFailed && <span className="zr-settings-hint" data-invalid="true">{t('settings.client.failWrite')}</span>}
1039
+ </div>
1040
+
1041
+ <h3 className="zr-settings-card-title">{t('settings.client.statusTitle')}</h3>
1042
+ <div className="zr-settings-row" style={{ paddingBottom: 4 }}>
1043
+ <p className="zr-settings-status-line" style={{ flex: 1 }} data-down={clientView !== undefined && (clientView.state === 'unreachable' || clientView.state === 'unexpected' || clientView.state === 'revoked' || clientView.state === 'invalid-url' || clientView.state === 'incompatible') ? 'true' : undefined}>
1044
+ {clientView === undefined ? '' : clientStatusText(clientView, now, t)}
1045
+ </p>
1046
+ {/* T43 立即重连: the response carrying a nextRetryAt is the one
1047
+ honest "the relay is offline with a retry armed" signal — the
1048
+ probe word underneath may be unreachable or unexpected; the
1049
+ route 409s anything else anyway (T43-fix). */}
1050
+ <Button
1051
+ variant="outline"
1052
+ size="sm"
1053
+ disabled={clientView === undefined || clientView.nextRetryAt === undefined || reconnectBusy}
1054
+ onClick={() => { void runReconnect() }}
1055
+ >
1056
+ {reconnectBusy ? t('settings.client.reconnectBusy') : t('settings.client.reconnect')}
1057
+ </Button>
1058
+ <Button variant="outline" size="sm" disabled={clientLoad.state === 'loading'} onClick={loadClientStatus}>
1059
+ {clientLoad.state === 'loading' ? t('settings.client.statusRefreshing') : t('settings.client.statusRefresh')}
1060
+ </Button>
1061
+ </div>
1062
+ {form.deviceToken.configured && (
1063
+ <div className="zr-settings-row" style={{ paddingBottom: 12 }}>
1064
+ <span className="zr-settings-badge">{t('settings.client.tokenSet')}</span>
1065
+ <Button variant="ghost" size="sm" disabled={!form.available || !form.writable || unpairBusy} onClick={() => { void runUnpair() }}>
1066
+ {unpairBusy ? t('settings.client.unpairBusy') : t('settings.client.unpair')}
1067
+ </Button>
1068
+ </div>
1069
+ )}
1070
+ {unpairDone && <p className="zr-settings-hint" style={{ paddingBottom: 12 }}>{t('settings.client.unpairDone')}</p>}
1071
+
1072
+ {/* 诊断 (T43): everything on this section comes from the same
1073
+ client/status body. The interceptor (T23b) and compat (T42)
1074
+ groups render only when the response carried their fields —
1075
+ earlier servers answer neither, and the section itself only
1076
+ exists when there is at least one line to show. */}
1077
+ {clientView !== undefined && (clientView.lastError !== '' || clientView.intercept !== undefined || clientView.compat !== undefined) && (
1078
+ <>
1079
+ <h3 className="zr-settings-card-title">{t('settings.client.diagTitle')}</h3>
1080
+ {clientView.lastError !== '' && (
1081
+ <p className="zr-settings-hint" data-invalid={clientView.state === 'unreachable' ? 'true' : undefined}>
1082
+ {t('settings.client.diagLastError', { code: clientView.lastError })}
1083
+ </p>
1084
+ )}
1085
+ {clientView.intercept !== undefined && (
1086
+ <>
1087
+ <p className="zr-settings-hint">
1088
+ {clientView.intercept.installed
1089
+ ? t('settings.client.diagInterceptInstalled')
1090
+ : t('settings.client.diagInterceptMissing')}
1091
+ </p>
1092
+ {clientView.intercept.reasons.length > 0 && (
1093
+ <p className="zr-settings-hint" data-invalid="true">
1094
+ {t('settings.client.diagInterceptDisabled')}
1095
+ {clientView.intercept.reasons.map((reason, index) => (
1096
+ <span key={index} className="zr-settings-hint">{reason}</span>
1097
+ ))}
1098
+ </p>
1099
+ )}
1100
+ {clientView.intercept.recentFailures.length > 0 && (
1101
+ <div className="zr-settings-field">
1102
+ <div className="zr-settings-head">
1103
+ <label>{t('settings.client.diagRecentFailures')}</label>
1104
+ </div>
1105
+ {clientView.intercept.recentFailures.map((failure, index) => (
1106
+ <p key={index} className="zr-settings-hint">
1107
+ {new Date(failure.time).toLocaleString()} · {failure.method !== '' ? failure.method : '—'} · {failure.code}
1108
+ </p>
1109
+ ))}
1110
+ </div>
1111
+ )}
1112
+ </>
1113
+ )}
1114
+ {clientView.compat !== undefined && (
1115
+ <>
1116
+ {clientView.compat.mismatchedGroups.length > 0 && (
1117
+ <p className="zr-settings-hint" data-invalid="true">
1118
+ {t('settings.client.diagCompatGroups', { groups: clientView.compat.mismatchedGroups.join(', ') })}
1119
+ </p>
1120
+ )}
1121
+ {clientView.compat.recentCalls.length > 0 && (
1122
+ <div className="zr-settings-field">
1123
+ <div className="zr-settings-head">
1124
+ <label>{t('settings.client.diagCompatCalls')}</label>
1125
+ </div>
1126
+ {clientView.compat.recentCalls.map((failure, index) => (
1127
+ <p key={index} className="zr-settings-hint">
1128
+ {new Date(failure.time).toLocaleString()} · {failure.method !== '' ? failure.method : '—'} · {failure.code}
1129
+ </p>
1130
+ ))}
1131
+ </div>
1132
+ )}
1133
+ </>
1134
+ )}
1135
+ </>
1136
+ )}
1137
+ </div>
1138
+ )}
1139
+ </div>
1140
+ )
1141
+ }
1142
+
1143
+ /** Display name of a value's source layer for the invalid-saved-value note. */
1144
+ function sourceName(source: SettingsFieldView['source'], t: SectionT): string {
1145
+ if (source === 'env') return t('settings.sourceEnv')
1146
+ if (source === 'file') return t('settings.sourceFile')
1147
+ return t('settings.sourceDefault')
1148
+ }
1149
+
1150
+ /**
1151
+ * The shared-session list (T33b entry 3), inside the host instant-operations
1152
+ * card — outside the settings-form frame like the pairing and device areas,
1153
+ * so it renders while the configuration namespace is unavailable or
1154
+ * read-only. It reads the SAME shares store singleton as the title-row icon
1155
+ * and the session menu (one poll loop for all three, started by this page's
1156
+ * subscription while mounted). Renders nothing until the first GET answers
1157
+ * and nothing while the store's wired role is not host (T33b-fix: the role
1158
+ * comes from the settings page's own two-level decision — this component
1159
+ * additionally sits inside the page's `!clientRole` branch, judged the T16
1160
+ * way off the saved row role). A failed GET keeps the last table on screen.
1161
+ *
1162
+ * Unlike pairing and device management these actions are NOT gated by
1163
+ * `viaGateway`: toggling shares through the gateway is the T33a-sanctioned
1164
+ * exception, so a phone may close a session's remote access.
1165
+ */
1166
+ function SharesList({ shares, t }: { shares: SharesStore, t: SectionT }) {
1167
+ const snap = useSyncExternalStore(
1168
+ useCallback((onStoreChange: () => void) => shares.subscribe(onStoreChange), [shares]),
1169
+ () => shares.getSnapshot(),
1170
+ )
1171
+ const [shareBusy, setShareBusy] = useState(false)
1172
+ const [shareFailed, setShareFailed] = useState(false)
1173
+
1174
+ if (!snap.ready || snap.role !== 'host') return null
1175
+ const entries = snap.entries
1176
+ // Fresh clock per render — the 30 s poll replaces the snapshot, which is
1177
+ // the re-render that keeps every countdown text within one poll of truth.
1178
+ const now = Date.now()
1179
+
1180
+ const runUnshare = async (sessionId: string): Promise<void> => {
1181
+ setShareBusy(true)
1182
+ setShareFailed(false)
1183
+ const outcome = await shares.unshare(sessionId)
1184
+ if (!outcome.ok) setShareFailed(true)
1185
+ setShareBusy(false)
1186
+ }
1187
+
1188
+ const runUnshareAll = async (): Promise<void> => {
1189
+ if (!window.confirm(t('settings.shareCloseAllConfirm'))) return
1190
+ setShareBusy(true)
1191
+ setShareFailed(false)
1192
+ const outcome = await shares.unshareAll()
1193
+ if (!outcome.ok) setShareFailed(true)
1194
+ setShareBusy(false)
1195
+ }
1196
+
1197
+ const shareRow = (entry: ShareEntryView) => (
1198
+ <div className="zr-settings-share-row" key={entry.sessionId}>
1199
+ <div className="zr-settings-device-head">
1200
+ <span className="zr-settings-device-name">{entry.title ?? entry.sessionId}</span>
1201
+ {entry.viewers > 0 && (
1202
+ <span className="zr-settings-badge" data-live="true">
1203
+ {t('settings.shareViewers', { count: entry.viewers })}
1204
+ </span>
1205
+ )}
1206
+ <span className="zr-settings-hint">{describeShare(entry, now, t).remainingText}</span>
1207
+ </div>
1208
+ <Button variant="ghost" size="sm" disabled={shareBusy} onClick={() => { void runUnshare(entry.sessionId) }}>
1209
+ {t('settings.shareClose')}
1210
+ </Button>
1211
+ </div>
1212
+ )
1213
+
1214
+ return (
1215
+ <>
1216
+ <h3 className="zr-settings-card-title">{t('settings.shareListTitle')}</h3>
1217
+ {entries.length === 0 && <p className="zr-settings-hint">{t('settings.shareListEmpty')}</p>}
1218
+ {entries.map(shareRow)}
1219
+ {shareFailed && <p className="zr-settings-hint" data-invalid="true">{t('settings.shareActionFail')}</p>}
1220
+ {entries.length > 0 && (
1221
+ <div className="zr-settings-row" style={{ paddingBottom: 12 }}>
1222
+ <Button variant="ghost" size="sm" disabled={shareBusy} onClick={() => { void runUnshareAll() }}>
1223
+ {t('settings.shareCloseAll')}
1224
+ </Button>
1225
+ </div>
1226
+ )}
1227
+ </>
1228
+ )
1229
+ }