@linxin666/dsh-remote-web-ui 0.4.2 → 0.4.3

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 (69) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +8 -6
  3. package/README.zh.md +8 -6
  4. package/lib/client.js +154 -594
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +323 -908
  7. package/lib/types/client/RemoteEntry.d.ts.map +1 -1
  8. package/lib/types/client/RemoteEntry.js +8 -9
  9. package/lib/types/client/RemoteSettingsCard.d.ts.map +1 -1
  10. package/lib/types/client/RemoteSettingsCard.js +1 -1
  11. package/lib/types/client/index.d.ts +32 -3
  12. package/lib/types/client/index.d.ts.map +1 -1
  13. package/lib/types/client/index.js +51 -8
  14. package/lib/types/client/locales.d.ts +0 -84
  15. package/lib/types/client/locales.d.ts.map +1 -1
  16. package/lib/types/client/locales.js +0 -84
  17. package/lib/types/client/settings-entry-form.d.ts +50 -0
  18. package/lib/types/client/settings-entry-form.d.ts.map +1 -0
  19. package/lib/types/client/settings-entry-form.js +98 -0
  20. package/lib/types/index.d.ts +99 -7
  21. package/lib/types/index.d.ts.map +1 -1
  22. package/lib/types/index.js +104 -137
  23. package/lib/types/lan-bind-plan.d.ts +14 -0
  24. package/lib/types/lan-bind-plan.d.ts.map +1 -1
  25. package/lib/types/lan-bind-plan.js +16 -0
  26. package/lib/types/lan-bind.d.ts +1 -1
  27. package/lib/types/lan-bind.js +1 -1
  28. package/lib/types/mount-once.d.ts +38 -7
  29. package/lib/types/mount-once.d.ts.map +1 -1
  30. package/lib/types/mount-once.js +96 -12
  31. package/lib/types/tunnel.d.ts +60 -3
  32. package/lib/types/tunnel.d.ts.map +1 -1
  33. package/lib/types/tunnel.js +136 -3
  34. package/package.json +2 -2
  35. package/src/client/RemoteEntry.tsx +7 -9
  36. package/src/client/RemoteSettingsCard.tsx +0 -2
  37. package/src/client/index.ts +53 -9
  38. package/src/client/locales.ts +0 -84
  39. package/src/client/remote.module.css +50 -200
  40. package/src/client/settings-entry-form.ts +142 -0
  41. package/src/index.ts +156 -152
  42. package/src/lan-bind-plan.ts +22 -0
  43. package/src/lan-bind.ts +1 -1
  44. package/src/mount-once.ts +107 -13
  45. package/src/tunnel.ts +142 -3
  46. package/lib/types/client/UpdateEntry.d.ts +0 -14
  47. package/lib/types/client/UpdateEntry.d.ts.map +0 -1
  48. package/lib/types/client/UpdateEntry.js +0 -112
  49. package/lib/types/client/UpdatePanel.d.ts +0 -42
  50. package/lib/types/client/UpdatePanel.d.ts.map +0 -1
  51. package/lib/types/client/UpdatePanel.js +0 -101
  52. package/lib/types/client/update-api.d.ts +0 -29
  53. package/lib/types/client/update-api.d.ts.map +0 -1
  54. package/lib/types/client/update-api.js +0 -47
  55. package/lib/types/console-output.d.ts +0 -41
  56. package/lib/types/console-output.d.ts.map +0 -1
  57. package/lib/types/console-output.js +0 -89
  58. package/lib/types/update-routes.d.ts +0 -30
  59. package/lib/types/update-routes.d.ts.map +0 -1
  60. package/lib/types/update-routes.js +0 -47
  61. package/lib/types/update.d.ts +0 -282
  62. package/lib/types/update.d.ts.map +0 -1
  63. package/lib/types/update.js +0 -773
  64. package/src/client/UpdateEntry.tsx +0 -144
  65. package/src/client/UpdatePanel.tsx +0 -256
  66. package/src/client/update-api.ts +0 -49
  67. package/src/console-output.ts +0 -97
  68. package/src/update-routes.ts +0 -65
  69. package/src/update.ts +0 -915
package/src/index.ts CHANGED
@@ -8,13 +8,12 @@
8
8
  * phone-side pair/accept + deep-link flow.
9
9
  */
10
10
 
11
- import { createRequire } from 'node:module'
12
11
  import { join } from 'node:path'
13
12
  import { setInterval as nodeSetInterval, setTimeout as nodeSetTimeout } from 'node:timers'
14
13
  import type { IncomingMessage } from 'node:http'
15
14
  import type { Context } from '@deepseek-ai/cordis'
16
15
  import type { SettingsNamespace } from '@deepseek-ai/dsh-settings'
17
- import z from 'schemastery'
16
+ import z from '@deepseek-ai/schemastery'
18
17
  import type {} from '@deepseek-ai/dsh-host-webserver'
19
18
  import type {} from '@deepseek-ai/dsh-agent'
20
19
  import type {} from '@deepseek-ai/dsh-commands'
@@ -34,29 +33,26 @@ import { ensureFirewallRule, firewallSummary, removeFirewallRule } from './firew
34
33
  import { lanBindState, writeLanBind } from './lan-bind.ts'
35
34
  import { isHttpUrl, tunnelPlanOf } from './tunnel-plan.ts'
36
35
  import { loadRelayIdentity, RelayRegistrar, type RelayState } from './relay-registry.ts'
37
- import { desiredBindHost, desiredBindPort, firewallActionNeeded, pendingRestartOf, type AppliedFirewallState, type StartupFacts } from './lan-bind-plan.ts'
36
+ import { desiredBindHost, desiredBindPort, firewallActionNeeded, pendingRestartOf, resolveManagedProfile, type AppliedFirewallState, type StartupFacts } from './lan-bind-plan.ts'
38
37
  import { createInnerAuth } from './inner-auth.ts'
39
38
  import { withIdentityEncoding } from './http.ts'
40
39
  import { TunnelManager, type TunnelInfo } from './tunnel.ts'
41
40
  import { PublicBaseKeeper } from './public-base.ts'
42
- import {
43
- checkUpdates,
44
- fetchGitHubReleaseNotes,
45
- fetchLatestVersion,
46
- RELEASE_NOTES_CACHE_TTL_MS,
47
- resolveAnchorManifest,
48
- resolveUpdateTarget,
49
- runUpdateVerified,
50
- type UpdateReleaseNotes,
51
- type UpdateRunResult,
52
- } from './update.ts'
53
- import { makeUpdateRoutes } from './update-routes.ts'
54
41
  import { mountOnce } from './mount-once.ts'
55
42
  import { REMOTE_CHANNEL_BOOT_SCRIPT } from './remote-channel-boot.ts'
56
43
  import { UUID_POLYFILL_SCRIPT } from './uuid-polyfill.ts'
57
44
 
58
45
  declare module '@deepseek-ai/cordis' {
59
46
  interface Events {
47
+ /**
48
+ * Volatile config values were committed into the running fiber without a
49
+ * remount; dispatched to the owning fiber only. Spelled here because the
50
+ * Loader package is not a dependency of this plugin, with the Loader's own
51
+ * shape so the two declarations merge when a Host program carries both.
52
+ * @param paths - changed config paths as key arrays; every value is committed before dispatch.
53
+ * @mode emit
54
+ */
55
+ 'loader/volatile-update'(paths: readonly (readonly string[])[]): void
60
56
  /**
61
57
  * Waterfall seam on the /api transport fence: the connection plugin
62
58
  * fires this per /api request before bridging to the API proxy on
@@ -199,44 +195,60 @@ export interface Config {
199
195
  */
200
196
  lanBind?: boolean
201
197
  /**
202
- * The profile whose cordis.patch.yml the LAN bind toggle manages.
203
- * Defaults to the DSH_PROFILE environment variable, then "web". Must be
204
- * a single safe path segment (the DSH_PROFILE env fallback bypasses this
205
- * schema, so the path builder asserts containment independently).
198
+ * The profile whose cordis.patch.yml the LAN bind toggle manages. Defaults
199
+ * to the profile the Host booted (its `profileContext`), then to the
200
+ * DSH_PROFILE environment variable, then "web" — the Desktop client boots
201
+ * "desktop" without exporting DSH_PROFILE, so the environment alone names
202
+ * the wrong profile there. Must be a single safe path segment (the runtime
203
+ * and environment fallbacks bypass this schema, so the path builder asserts
204
+ * containment independently).
206
205
  */
207
206
  profile?: string
208
207
  /** Master switch for the plugin (browser half + host pairing surfaces). */
209
208
  enabled?: boolean
210
209
  }
211
210
 
212
- export const Config: z<Config> = z.object({
213
- tokenTtlMs: z.number().step(1).min(60_000).default(10 * 60_000),
214
- offlineAfterMs: z.number().step(1).min(5_000).default(25_000),
215
- maxDevices: z.number().step(1).min(1).max(64).default(4),
216
- idleExpireMs: z.number().step(1).min(60_000).default(DEFAULT_IDLE_EXPIRE_MS),
217
- cookieName: z.string().min(1).default('dsh_pair'),
218
- requirePairingForLan: z.boolean().default(true),
219
- publicBaseUrl: z.string(),
211
+ /**
212
+ * Plugin config schema. Under the 0.1.7 settings model this schema IS the
213
+ * entry's settings page: the Host derives one form per profile entry from it
214
+ * and serves that form only when at least one field is `volatile()`. The marker
215
+ * is also what admits a write and what keeps the edit on the live path — the
216
+ * Loader commits the new value into the field's reference and announces
217
+ * `loader/volatile-update` on this fiber instead of remounting the row, so the
218
+ * pairing service, its device sessions, the tunnel and the route registrations
219
+ * survive a settings save (see {@link applyImpl}'s sync).
220
+ *
221
+ * The schema is left to inference rather than annotated with `z<Config>`: a
222
+ * volatile field's parsed output is a live reference while its accepted input
223
+ * stays the plain value, so the two sides no longer share one shape and the
224
+ * annotation would reject the schema the Host must be given.
225
+ *
226
+ * The deployment-level fields (`trustedHosts`, `devicesFile`, `profile`) are
227
+ * deliberately NOT volatile: they belong in the profile patch, so the form
228
+ * leaves them to the operator instead of offering a card control that a
229
+ * document write could not honor.
230
+ */
231
+ export const Config = z.object({
232
+ tokenTtlMs: z.number().step(1).min(60_000).default(10 * 60_000).volatile(),
233
+ offlineAfterMs: z.number().step(1).min(5_000).default(25_000).volatile(),
234
+ maxDevices: z.number().step(1).min(1).max(64).default(4).volatile(),
235
+ idleExpireMs: z.number().step(1).min(60_000).default(DEFAULT_IDLE_EXPIRE_MS).volatile(),
236
+ cookieName: z.string().min(1).default('dsh_pair').volatile(),
237
+ requirePairingForLan: z.boolean().default(true).volatile(),
238
+ publicBaseUrl: z.string().volatile(),
220
239
  trustedHosts: z.array(z.string()),
221
240
  devicesFile: z.string(),
222
- autoTunnel: z.boolean().default(false),
223
- tunnelToken: z.string().role('secret'),
224
- relay: z.boolean().default(true),
225
- lanBind: z.boolean(),
241
+ autoTunnel: z.boolean().default(false).volatile(),
242
+ tunnelToken: z.string().role('secret').volatile(),
243
+ relay: z.boolean().default(true).volatile(),
244
+ lanBind: z.boolean().volatile(),
226
245
  profile: z.string().pattern(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),
227
- enabled: z.boolean().default(true),
246
+ enabled: z.boolean().default(true).volatile(),
228
247
  })
229
248
 
230
249
  /** Presence sweep cadence (a stale device flips to disconnected within two sweeps). */
231
250
  const SWEEP_INTERVAL_MS = 10_000
232
251
 
233
- /**
234
- * How long one update-status probe answer is reused. The probe fans out one
235
- * registry GET per family package plus a GitHub call, and the sidebar update
236
- * entry asks for the status on every GUI page load.
237
- */
238
- const UPDATE_STATUS_TTL_MS = 60_000
239
-
240
252
  /**
241
253
  * Fully resolved config: every field non-optional except `publicBaseUrl`,
242
254
  * which legitimately resolves to `undefined` when unset (the schema keeps it
@@ -252,6 +264,60 @@ type ResolvedConfig = Required<Omit<Config, 'publicBaseUrl' | 'trustedHosts' | '
252
264
  profile: string
253
265
  }
254
266
 
267
+ /**
268
+ * The stable reference a `volatile()` config field resolves to; its owner
269
+ * updates it in place when the user saves.
270
+ */
271
+ interface ConfigRef<T> {
272
+ /** @returns the value currently committed for the running instance. */
273
+ get(): T
274
+ }
275
+
276
+ /** One resolved config field: a live reference, or a plain value from a hand-built context. */
277
+ type ConfigField<T> = ConfigRef<T> | T
278
+
279
+ /** The config the Host hands {@link applyImpl} — the runtime face of {@link Config}. */
280
+ export interface ResolvedConfigFields {
281
+ tokenTtlMs?: ConfigField<number>
282
+ offlineAfterMs?: ConfigField<number>
283
+ maxDevices?: ConfigField<number>
284
+ idleExpireMs?: ConfigField<number>
285
+ cookieName?: ConfigField<string>
286
+ requirePairingForLan?: ConfigField<boolean>
287
+ publicBaseUrl?: ConfigField<string>
288
+ trustedHosts?: ConfigField<string[]>
289
+ devicesFile?: ConfigField<string>
290
+ autoTunnel?: ConfigField<boolean>
291
+ tunnelToken?: ConfigField<string>
292
+ relay?: ConfigField<boolean>
293
+ lanBind?: ConfigField<boolean>
294
+ profile?: ConfigField<string>
295
+ enabled?: ConfigField<boolean>
296
+ }
297
+
298
+ /** Read one resolved config field, following the live reference the schema produces. */
299
+ function readConfigField<T>(field: ConfigField<T> | undefined, fallback: T): T {
300
+ if (field === undefined) return fallback
301
+ if (typeof field === 'object' && field !== null && typeof (field as ConfigRef<T>).get === 'function') {
302
+ const value = (field as ConfigRef<T>).get()
303
+ return value === undefined ? fallback : value
304
+ }
305
+ return field as T
306
+ }
307
+
308
+ /**
309
+ * Read one optional resolved config field. A volatile reference is read at
310
+ * call time, so an unset field stays `undefined` rather than falling back to a
311
+ * schema default (the distinction the LAN toggle and the tunnel plan depend on).
312
+ */
313
+ function readOptionalConfigField<T>(field: ConfigField<T> | undefined): T | undefined {
314
+ if (field === undefined) return undefined
315
+ if (typeof field === 'object' && field !== null && typeof (field as ConfigRef<T>).get === 'function') {
316
+ return (field as ConfigRef<T>).get()
317
+ }
318
+ return field as T
319
+ }
320
+
255
321
  /**
256
322
  * The single mapping from resolved plugin config to the pairing service
257
323
  * config. Both the constructed service and every later apply of this row
@@ -291,10 +357,24 @@ const DEFAULTS: ResolvedConfig = {
291
357
  tunnelToken: undefined,
292
358
  relay: true,
293
359
  lanBind: undefined,
294
- profile: process.env.DSH_PROFILE ?? 'web',
360
+ profile: resolveManagedProfile(undefined, undefined, process.env.DSH_PROFILE),
295
361
  enabled: true,
296
362
  }
297
363
 
364
+ /**
365
+ * The launched profile the Host publishes on its `profileContext` service
366
+ * (`{ name, dir, patchPath, … }`). The Desktop client boots the "desktop"
367
+ * profile without exporting DSH_PROFILE, so the environment alone resolves
368
+ * the wrong profile there and the LAN bind toggle would edit a profile that
369
+ * is not running.
370
+ * @param ctx - host plugin context.
371
+ * @returns the profile name when the Host publishes one; undefined otherwise.
372
+ */
373
+ function launchedProfileName(ctx: Context): string | undefined {
374
+ const fact = ctx.get('profileContext') as { name?: unknown } | undefined
375
+ return typeof fact?.name === 'string' && fact.name.length > 0 ? fact.name : undefined
376
+ }
377
+
298
378
  /**
299
379
  * Mount the pairing service, routes, gate listener, and presence sweep.
300
380
  * @param ctx - host plugin context carrying webServer.
@@ -302,32 +382,31 @@ const DEFAULTS: ResolvedConfig = {
302
382
  */
303
383
  export const apply = mountOnce('@linxin666/dsh-remote-web-ui', applyImpl)
304
384
 
305
- function applyImpl(ctx: Context, config?: Config): void {
385
+ function applyImpl(ctx: Context, config?: ResolvedConfigFields): void {
306
386
  const envPublicBase = process.env.DSH_REMOTE_PUBLIC_BASE_URL?.trim() || undefined
307
- const resolved: ResolvedConfig = {
308
- tokenTtlMs: config?.tokenTtlMs ?? DEFAULTS.tokenTtlMs,
309
- offlineAfterMs: config?.offlineAfterMs ?? DEFAULTS.offlineAfterMs,
310
- maxDevices: config?.maxDevices ?? DEFAULTS.maxDevices,
311
- idleExpireMs: config?.idleExpireMs ?? DEFAULTS.idleExpireMs,
312
- cookieName: config?.cookieName ?? DEFAULTS.cookieName,
313
- requirePairingForLan: config?.requirePairingForLan ?? DEFAULTS.requirePairingForLan,
314
- publicBaseUrl: config?.publicBaseUrl ?? envPublicBase,
315
- trustedHosts: config?.trustedHosts,
316
- devicesFile: config?.devicesFile ?? DEFAULTS.devicesFile,
317
- autoTunnel: config?.autoTunnel ?? DEFAULTS.autoTunnel,
318
- tunnelToken: config?.tunnelToken,
319
- relay: config?.relay ?? DEFAULTS.relay,
320
- lanBind: config?.lanBind,
321
- profile: config?.profile ?? process.env.DSH_PROFILE ?? DEFAULTS.profile,
322
- enabled: config?.enabled ?? DEFAULTS.enabled,
323
- }
324
- // The effective configuration this activation runs on: under the 0.1.7
325
- // settings model the plugin's own Config IS its settings document, so the
326
- // Host serves the settings page from this schema and reloads the row after a
327
- // save — a live edit re-enters apply() with the new value instead of being
328
- // pushed into a running instance.
329
- const resolve = (): ResolvedConfig => resolved
330
- const service = new PairingService(pairingConfigOf(resolved))
387
+ // The settings are read through the volatile references at every call rather
388
+ // than captured once: a settings save commits into those references and
389
+ // announces `loader/volatile-update` (see the listener below), so resolving
390
+ // them here is what makes a live edit reach the running instance without a
391
+ // remount — and keeps the device sessions, the tunnel and the routes alive.
392
+ const resolve = (): ResolvedConfig => ({
393
+ tokenTtlMs: readConfigField(config?.tokenTtlMs, DEFAULTS.tokenTtlMs),
394
+ offlineAfterMs: readConfigField(config?.offlineAfterMs, DEFAULTS.offlineAfterMs),
395
+ maxDevices: readConfigField(config?.maxDevices, DEFAULTS.maxDevices),
396
+ idleExpireMs: readConfigField(config?.idleExpireMs, DEFAULTS.idleExpireMs),
397
+ cookieName: readConfigField(config?.cookieName, DEFAULTS.cookieName),
398
+ requirePairingForLan: readConfigField(config?.requirePairingForLan, DEFAULTS.requirePairingForLan),
399
+ publicBaseUrl: readOptionalConfigField(config?.publicBaseUrl) ?? envPublicBase,
400
+ trustedHosts: readOptionalConfigField(config?.trustedHosts),
401
+ devicesFile: readConfigField(config?.devicesFile, DEFAULTS.devicesFile),
402
+ autoTunnel: readConfigField(config?.autoTunnel, DEFAULTS.autoTunnel),
403
+ tunnelToken: readOptionalConfigField(config?.tunnelToken),
404
+ relay: readConfigField(config?.relay, DEFAULTS.relay),
405
+ lanBind: readOptionalConfigField(config?.lanBind),
406
+ profile: resolveManagedProfile(readOptionalConfigField(config?.profile), launchedProfileName(ctx), process.env.DSH_PROFILE),
407
+ enabled: readConfigField(config?.enabled, DEFAULTS.enabled),
408
+ })
409
+ const service = new PairingService(pairingConfigOf(resolve()))
331
410
 
332
411
  // ── auto tunnel ─────────────────────────────────────────────────────────
333
412
  // The minted public URL becomes the QR base (and the pairing fence's
@@ -394,7 +473,7 @@ function applyImpl(ctx: Context, config?: Config): void {
394
473
  }
395
474
  // 'off' until a sync pass turns a mode on; the phase listener only feeds
396
475
  // the public base while a plugin-managed tunnel (quick or named) runs.
397
- let tunnelMode: 'off' | 'quick' | 'named' = resolved.autoTunnel ? 'quick' : 'off'
476
+ let tunnelMode: 'off' | 'quick' | 'named' = resolve().autoTunnel ? 'quick' : 'off'
398
477
  tunnel.onPhase((info: TunnelInfo) => {
399
478
  if (tunnelMode === 'off') return
400
479
  if (info.phase === 'running' && info.url !== undefined) {
@@ -450,89 +529,6 @@ function applyImpl(ctx: Context, config?: Config): void {
450
529
  // request) instead of opening the fence.
451
530
  let disposeRoutes: (() => void) | undefined
452
531
  let disposeSweep: (() => void) | undefined
453
- // ── remote update ────────────────────────────────────────────────────────
454
- // The dsh-web self-update surface: probe the npm registry for family
455
- // releases and run `pnpm update --latest` in the owning profile. Resolutions
456
- // anchor on the host process's own module graph, so the update always
457
- // targets the profile the running web GUI was booted from. The anchor path
458
- // is re-resolved per operation: pnpm removes the old version's .pnpm
459
- // directory on update, so a boot-time captured path would fail to read
460
- // after a successful update; versions are re-read from disk per check.
461
- const requireFromHost = createRequire(import.meta.url)
462
- /** Host-process resolve that degrades to "not installed" (undefined) instead of throwing. */
463
- const hostResolve = (specifier: string): string | undefined => {
464
- try {
465
- return requireFromHost.resolve(specifier)
466
- } catch {
467
- return undefined
468
- }
469
- }
470
- const resolveAnchorPath = (): string | undefined => resolveAnchorManifest(hostResolve)
471
-
472
- const releaseNotesCache = new Map<string, { at: number; notes?: UpdateReleaseNotes }>()
473
- const fetchReleaseNotesCached = async (version: string): Promise<UpdateReleaseNotes | undefined> => {
474
- const cached = releaseNotesCache.get(version)
475
- if (cached !== undefined && Date.now() - cached.at < RELEASE_NOTES_CACHE_TTL_MS) return cached.notes
476
- const notes = await fetchGitHubReleaseNotes(version, fetch)
477
- releaseNotesCache.set(version, { at: Date.now(), notes })
478
- return notes
479
- }
480
- // The status probe fans out one registry GET per family package (plus a
481
- // GitHub release-notes call), and the sidebar update entry asks for it on
482
- // every GUI page load — so the answer is memoized briefly and concurrent
483
- // callers share one probe. A completed update invalidates it.
484
- let updateStatusCache: { at: number; value: Awaited<ReturnType<typeof checkUpdates>> } | undefined
485
- let updateStatusInFlight: Promise<Awaited<ReturnType<typeof checkUpdates>>> | undefined
486
- const checkStatusCached = (): Promise<Awaited<ReturnType<typeof checkUpdates>>> => {
487
- const cached = updateStatusCache
488
- if (cached !== undefined && Date.now() - cached.at < UPDATE_STATUS_TTL_MS) return Promise.resolve(cached.value)
489
- if (updateStatusInFlight !== undefined) return updateStatusInFlight
490
- updateStatusInFlight = checkUpdates({
491
- anchorManifestPath: resolveAnchorPath(),
492
- resolve: hostResolve,
493
- fetchLatest: name => fetchLatestVersion(name, fetch),
494
- fetchReleaseNotes: fetchReleaseNotesCached,
495
- }).then((value) => {
496
- updateStatusCache = { at: Date.now(), value }
497
- return value
498
- }).finally(() => { updateStatusInFlight = undefined })
499
- return updateStatusInFlight
500
- }
501
- const updateRoutes = makeUpdateRoutes({
502
- // Control endpoints are host-surface only: a LAN/phone origin must never
503
- // trigger a real install on this machine.
504
- fence: request => isTrustedApiRequest(request, []),
505
- check: () => checkStatusCached(),
506
- run: async (): Promise<UpdateRunResult> => {
507
- const target = resolveUpdateTarget({ anchorManifestPath: resolveAnchorPath() })
508
- if ('error' in target) {
509
- const code = target.error
510
- return {
511
- ok: false,
512
- exitCode: null,
513
- output: '',
514
- error: code === 'not-found' ? 'dsh-web aggregate not installed' : 'local link install — update unavailable',
515
- errorCode: code,
516
- }
517
- }
518
- // Verify the versions actually moved after a green pnpm exit: the pnpm
519
- // 11 minimumReleaseAge gate can silently keep the installed versions
520
- // (same-day releases), which a plain exit-0 check would report as
521
- // success — the user then restarts and nothing changed.
522
- const result = await runUpdateVerified({
523
- run: { profileDir: target.profileDir, packages: target.packages },
524
- check: {
525
- anchorManifestPath: resolveAnchorPath(),
526
- resolve: hostResolve,
527
- fetchLatest: name => fetchLatestVersion(name, fetch),
528
- fetchReleaseNotes: fetchReleaseNotesCached,
529
- },
530
- })
531
- // The install moved (or failed) the versions the cached status reported.
532
- updateStatusCache = undefined
533
- return result
534
- },
535
- })
536
532
  // LAN-bind facts for the settings card, re-read per request so a hot
537
533
  // rebind (the patch watcher recomposes the process) and a fresh toggle
538
534
  // round are both reflected without a restart.
@@ -653,7 +649,6 @@ function applyImpl(ctx: Context, config?: Config): void {
653
649
  port: ctx.webServer.port,
654
650
  auth: innerAuth,
655
651
  }),
656
- ...updateRoutes,
657
652
  ]
658
653
  const upgrades = makeRemoteApiUpgradeRoutes({
659
654
  service,
@@ -917,8 +912,17 @@ function applyImpl(ctx: Context, config?: Config): void {
917
912
  table.push({ kind: 'script', placement: 'head', text: REMOTE_CHANNEL_BOOT_SCRIPT })
918
913
  }), 'remote-web-ui: remote channel boot patch')
919
914
 
915
+ // The settings write path. The Host commits the new values into this row's
916
+ // volatile references and announces it here instead of remounting the row, so
917
+ // `sync` is what re-applies them: it re-reads every field through those
918
+ // references (see `resolve`) and is idempotent, so a save that changes
919
+ // nothing observable is a no-op while a disable, a bind flip or a tunnel
920
+ // change lands on the live instance without dropping the pairing service,
921
+ // its device sessions or the route registrations.
922
+ ctx.on('loader/volatile-update', () => { sync() })
923
+
920
924
  // No settings registration: the Host derives this plugin's settings page
921
- // from the exported `Config` schema and reloads the row after a save, so
922
- // every write re-enters apply() with the new config (see `resolve`).
925
+ // from the exported `Config` schema, whose volatile fields are what make the
926
+ // page writable and what route a save through the live path above.
923
927
  sync()
924
928
  }
@@ -64,6 +64,28 @@ export interface AppliedFirewallState {
64
64
  port: number
65
65
  }
66
66
 
67
+ /** The managed profile when neither the config nor the runtime names one. */
68
+ export const DEFAULT_MANAGED_PROFILE = 'web'
69
+
70
+ /**
71
+ * The profile whose `cordis.patch.yml` the LAN bind toggle manages. An
72
+ * explicit `profile` config wins; otherwise the launched profile the Host
73
+ * publishes is authoritative, because the DSH Desktop client boots the
74
+ * `desktop` profile without exporting `DSH_PROFILE` — an environment-only
75
+ * fallback edited `profiles/web` there, so the toggle looked applied while
76
+ * the running host never followed the block.
77
+ * @param configured - the explicit `profile` plugin config, when set.
78
+ * @param launched - the launched profile name the Host published, when available.
79
+ * @param env - the DSH_PROFILE environment value, when set.
80
+ */
81
+ export function resolveManagedProfile(
82
+ configured: string | undefined,
83
+ launched: string | undefined,
84
+ env: string | undefined,
85
+ ): string {
86
+ return configured ?? launched ?? env ?? DEFAULT_MANAGED_PROFILE
87
+ }
88
+
67
89
  /**
68
90
  * Whether the firewall rule must be (re)applied: only when the toggle or the
69
91
  * bound port moved since the last application. Keeps unrelated settings
package/src/lan-bind.ts CHANGED
@@ -35,7 +35,7 @@ export type LanBindHost = '0.0.0.0' | '127.0.0.1'
35
35
 
36
36
  /**
37
37
  * The absolute path of the profile patch file this toggle manages. The value
38
- * is config-controlled (and the DSH_PROFILE env fallback bypasses schema
38
+ * is config-controlled (and the runtime/environment fallbacks bypass schema
39
39
  * validation entirely), so the path is guarded twice: the profile must be a
40
40
  * single safe path segment, and the resolved file must stay under the
41
41
  * profiles directory.
package/src/mount-once.ts CHANGED
@@ -5,44 +5,138 @@
5
5
  * the loader accepts a standalone install of the same package side by side;
6
6
  * without this guard the second instance would still re-register the same
7
7
  * webserver routes, tools, settings namespaces, and system-prompt sections
8
- * and fail the boot. mountOnce makes the second host apply a no-op for the
9
- * lifetime of the first instance (the browser half is already deduped by
10
- * package name in the client module host).
8
+ * and fail the boot. mountOnce makes a mount of an already-mounted package a
9
+ * no-op for as long as the first instance lives (the browser half is already
10
+ * deduped by package name in the client module host).
11
+ *
12
+ * A no-op is only safe while the holder is ALIVE. The holder can be disposed
13
+ * long after the refused mount ran its course: the Host reloads a profile by
14
+ * creating the new loader entries before the old ones are torn down (a
15
+ * plugin-manager enable/disable/install write, a settings-driven row reload,
16
+ * HMR), so the new aggregate shell entry mounts its family plugin while the
17
+ * previous entry still owns the name. Dropping that refused mount lost the
18
+ * plugin for good - the previous entry then disposed its own mount, releasing
19
+ * the name with nobody left to take it, and the family row stayed listed as
20
+ * active while its host routes 404ed (the task-board panel showed
21
+ * "board.hostError.notMounted", no degraded record appeared, and only a Host
22
+ * restart recovered it).
23
+ *
24
+ * The refused mount is therefore QUEUED, not dropped, and replayed the moment
25
+ * the holder releases the name - if the waiting fiber is still alive then. The
26
+ * single-instance guarantee is unchanged: exactly one mount is live per
27
+ * package name, and the replay re-enters the guard so a later mount still
28
+ * dedupes against it.
11
29
  *
12
30
  * The registry rides a global symbol so two module instances of the same
13
- * package (npm copy vs repository link) still share one verdict. cordis
14
- * `ctx.effect` runs its callback immediately and treats the callback's
31
+ * package (npm copy vs repository link) still share one verdict. That symbol
32
+ * is a CROSS-REPOSITORY contract, not this file's private state: the four
33
+ * satellite packages (dsh-skins / dsh-pet / dsh-presets /
34
+ * dsh-community-plugins) are separate repositories carrying their own copy of
35
+ * this guard, rebuilt on their own schedule, so the value under `MOUNTED`
36
+ * must keep the shape every published copy reads (a `Set` of package names
37
+ * with `has`/`add`/`delete`). The wait queues this guard added therefore live
38
+ * under their own additive key, and the registry reads back a `Set` even when
39
+ * some other build left a different value there. Changing `MOUNTED`'s shape
40
+ * in place broke that contract once: a satellite's legacy copy created a
41
+ * `Set`, the family's new copy read it as a `Map`, and every family row
42
+ * mounted after it failed with "claims.get is not a function".
43
+ *
44
+ * cordis `ctx.effect` runs its callback immediately and treats the callback's
15
45
  * return value as the fiber disposer, so the unmarker is returned, not run.
16
46
  */
17
47
 
48
+ /** Published cross-repository contract: package names currently mounted. */
18
49
  const MOUNTED = Symbol.for('dsh-web.mounted-plugins')
19
50
 
51
+ /** Additive key this guard owns: refused mounts waiting for the name. */
52
+ const WAITERS = Symbol.for('dsh-web.mounted-plugins.waiters')
53
+
54
+ /** The slice of a cordis context this guard touches. */
55
+ interface MountContext {
56
+ effect?: (effect: () => unknown) => unknown
57
+ }
58
+
59
+ /** One mount that was refused while another fiber owned the package name. */
60
+ interface PendingMount {
61
+ /** Replay the refused mount; a no-op once its own fiber has been disposed. */
62
+ run(): void
63
+ }
64
+
20
65
  interface MountRegistry {
21
- [MOUNTED]?: Set<string>
66
+ [MOUNTED]?: unknown
67
+ [WAITERS]?: Map<string, PendingMount[]>
22
68
  }
23
69
 
70
+ /**
71
+ * The shared name registry, always a `Set` whatever another build stored here:
72
+ * a foreign value (an interim shape, a hand-written global) must not take every
73
+ * family plugin down with it.
74
+ * @returns the process-wide set of mounted package names.
75
+ */
24
76
  function mountedSet(): Set<string> {
25
77
  const registry = globalThis as MountRegistry
26
- return (registry[MOUNTED] ??= new Set())
78
+ const existing = registry[MOUNTED]
79
+ if (existing instanceof Set) return existing as Set<string>
80
+ const created = new Set<string>()
81
+ registry[MOUNTED] = created
82
+ return created
83
+ }
84
+
85
+ /** Queue per package name for mounts refused while a holder was alive. */
86
+ function mountWaiters(): Map<string, PendingMount[]> {
87
+ const registry = globalThis as MountRegistry
88
+ return (registry[WAITERS] ??= new Map())
27
89
  }
28
90
 
29
91
  /**
30
92
  * Wrap a cordis plugin apply so the package runs at most once per process.
31
- * The first mount registers normally and unmarks when its fiber disposes;
32
- * any later mount of the same package name is a no-op.
93
+ * The first mount registers normally and releases the name when its fiber
94
+ * disposes; a mount refused while that name is held waits for the release and
95
+ * then runs, unless its own fiber disposes first.
33
96
  * @param packageName - npm package identity shared by every install source.
34
97
  * @param fn - the original plugin apply.
35
98
  * @returns an apply of the same shape.
36
99
  */
37
100
  export function mountOnce<T extends (...args: any[]) => unknown>(packageName: string, fn: T): T {
38
- return ((...args: unknown[]) => {
101
+ const mount = (...args: unknown[]): unknown => {
39
102
  const mounted = mountedSet()
40
- if (mounted.has(packageName)) return
103
+ const ctx = args[0] as MountContext | undefined
104
+ if (mounted.has(packageName)) {
105
+ // Another fiber (the aggregate row, a standalone install, or a copy built
106
+ // from an older revision of this guard) owns the name. Queue instead of
107
+ // dropping: dropping lost the plugin for the rest of the process when the
108
+ // holder was disposed by a reload.
109
+ const waiters = mountWaiters()
110
+ const queue = waiters.get(packageName) ?? []
111
+ let alive = true
112
+ const pending: PendingMount = {
113
+ run: () => {
114
+ if (alive) mount(...args)
115
+ },
116
+ }
117
+ // A fiber that dies while it waits must not be replayed afterwards: its
118
+ // context is disposed and registering effects on it would throw.
119
+ ctx?.effect?.(() => () => {
120
+ alive = false
121
+ const index = queue.indexOf(pending)
122
+ if (index >= 0) queue.splice(index, 1)
123
+ })
124
+ queue.push(pending)
125
+ waiters.set(packageName, queue)
126
+ return
127
+ }
41
128
  mounted.add(packageName)
42
- const ctx = args[0] as { effect?: (effect: () => unknown) => unknown } | undefined
43
129
  ctx?.effect?.(() => () => {
44
130
  mounted.delete(packageName)
131
+ const waiters = mountWaiters()
132
+ const queue = waiters.get(packageName)
133
+ if (queue === undefined) return
134
+ waiters.delete(packageName)
135
+ // Defer the handover one microtask so the disposing mount's own effects
136
+ // (routes, ledger, timers) are torn down before the next one registers.
137
+ for (const waiter of queue.splice(0)) queueMicrotask(() => { waiter.run() })
45
138
  })
46
139
  return fn(...args)
47
- }) as T
140
+ }
141
+ return mount as T
48
142
  }