@linxin666/dsh-liangshen 0.4.2 → 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -463,38 +463,111 @@ const LIANGSHEN_PRESET_ID = "liangshen";
463
463
  * the loader accepts a standalone install of the same package side by side;
464
464
  * without this guard the second instance would still re-register the same
465
465
  * webserver routes, tools, settings namespaces, and system-prompt sections
466
- * and fail the boot. mountOnce makes the second host apply a no-op for the
467
- * lifetime of the first instance (the browser half is already deduped by
468
- * package name in the client module host).
466
+ * and fail the boot. mountOnce makes a mount of an already-mounted package a
467
+ * no-op for as long as the first instance lives (the browser half is already
468
+ * deduped by package name in the client module host).
469
+ *
470
+ * A no-op is only safe while the holder is ALIVE. The holder can be disposed
471
+ * long after the refused mount ran its course: the Host reloads a profile by
472
+ * creating the new loader entries before the old ones are torn down (a
473
+ * plugin-manager enable/disable/install write, a settings-driven row reload,
474
+ * HMR), so the new aggregate shell entry mounts its family plugin while the
475
+ * previous entry still owns the name. Dropping that refused mount lost the
476
+ * plugin for good - the previous entry then disposed its own mount, releasing
477
+ * the name with nobody left to take it, and the family row stayed listed as
478
+ * active while its host routes 404ed (the task-board panel showed
479
+ * "board.hostError.notMounted", no degraded record appeared, and only a Host
480
+ * restart recovered it).
481
+ *
482
+ * The refused mount is therefore QUEUED, not dropped, and replayed the moment
483
+ * the holder releases the name - if the waiting fiber is still alive then. The
484
+ * single-instance guarantee is unchanged: exactly one mount is live per
485
+ * package name, and the replay re-enters the guard so a later mount still
486
+ * dedupes against it.
469
487
  *
470
488
  * The registry rides a global symbol so two module instances of the same
471
- * package (npm copy vs repository link) still share one verdict. cordis
472
- * `ctx.effect` runs its callback immediately and treats the callback's
489
+ * package (npm copy vs repository link) still share one verdict. That symbol
490
+ * is a CROSS-REPOSITORY contract, not this file's private state: the four
491
+ * satellite packages (dsh-skins / dsh-pet / dsh-presets /
492
+ * dsh-community-plugins) are separate repositories carrying their own copy of
493
+ * this guard, rebuilt on their own schedule, so the value under `MOUNTED`
494
+ * must keep the shape every published copy reads (a `Set` of package names
495
+ * with `has`/`add`/`delete`). The wait queues this guard added therefore live
496
+ * under their own additive key, and the registry reads back a `Set` even when
497
+ * some other build left a different value there. Changing `MOUNTED`'s shape
498
+ * in place broke that contract once: a satellite's legacy copy created a
499
+ * `Set`, the family's new copy read it as a `Map`, and every family row
500
+ * mounted after it failed with "claims.get is not a function".
501
+ *
502
+ * cordis `ctx.effect` runs its callback immediately and treats the callback's
473
503
  * return value as the fiber disposer, so the unmarker is returned, not run.
474
504
  */
505
+ /** Published cross-repository contract: package names currently mounted. */
475
506
  const MOUNTED = Symbol.for("dsh-web.mounted-plugins");
507
+ /** Additive key this guard owns: refused mounts waiting for the name. */
508
+ const WAITERS = Symbol.for("dsh-web.mounted-plugins.waiters");
509
+ /**
510
+ * The shared name registry, always a `Set` whatever another build stored here:
511
+ * a foreign value (an interim shape, a hand-written global) must not take every
512
+ * family plugin down with it.
513
+ * @returns the process-wide set of mounted package names.
514
+ */
476
515
  function mountedSet() {
477
516
  const registry = globalThis;
478
- return registry[MOUNTED] ??= /* @__PURE__ */ new Set();
517
+ const existing = registry[MOUNTED];
518
+ if (existing instanceof Set) return existing;
519
+ const created = /* @__PURE__ */ new Set();
520
+ registry[MOUNTED] = created;
521
+ return created;
522
+ }
523
+ /** Queue per package name for mounts refused while a holder was alive. */
524
+ function mountWaiters() {
525
+ const registry = globalThis;
526
+ return registry[WAITERS] ??= /* @__PURE__ */ new Map();
479
527
  }
480
528
  /**
481
529
  * Wrap a cordis plugin apply so the package runs at most once per process.
482
- * The first mount registers normally and unmarks when its fiber disposes;
483
- * any later mount of the same package name is a no-op.
530
+ * The first mount registers normally and releases the name when its fiber
531
+ * disposes; a mount refused while that name is held waits for the release and
532
+ * then runs, unless its own fiber disposes first.
484
533
  * @param packageName - npm package identity shared by every install source.
485
534
  * @param fn - the original plugin apply.
486
535
  * @returns an apply of the same shape.
487
536
  */
488
537
  function mountOnce(packageName, fn) {
489
- return ((...args) => {
538
+ const mount = (...args) => {
490
539
  const mounted = mountedSet();
491
- if (mounted.has(packageName)) return;
540
+ const ctx = args[0];
541
+ if (mounted.has(packageName)) {
542
+ const waiters = mountWaiters();
543
+ const queue = waiters.get(packageName) ?? [];
544
+ let alive = true;
545
+ const pending = { run: () => {
546
+ if (alive) mount(...args);
547
+ } };
548
+ ctx?.effect?.(() => () => {
549
+ alive = false;
550
+ const index = queue.indexOf(pending);
551
+ if (index >= 0) queue.splice(index, 1);
552
+ });
553
+ queue.push(pending);
554
+ waiters.set(packageName, queue);
555
+ return;
556
+ }
492
557
  mounted.add(packageName);
493
- args[0]?.effect?.(() => () => {
558
+ ctx?.effect?.(() => () => {
494
559
  mounted.delete(packageName);
560
+ const waiters = mountWaiters();
561
+ const queue = waiters.get(packageName);
562
+ if (queue === void 0) return;
563
+ waiters.delete(packageName);
564
+ for (const waiter of queue.splice(0)) queueMicrotask(() => {
565
+ waiter.run();
566
+ });
495
567
  });
496
568
  return fn(...args);
497
- });
569
+ };
570
+ return mount;
498
571
  }
499
572
  //#endregion
500
573
  //#region src/index.ts
@@ -656,6 +729,12 @@ function applyImpl(ctx, config) {
656
729
  let closed = false;
657
730
  /** Serializes declaration work, so a settings write cannot interleave with an in-flight activation. */
658
731
  let queue = Promise.resolve();
732
+ /**
733
+ * True when the last declaration attempt found no registry. It is the ONLY
734
+ * state the late-registry recovery below acts on, so a registry that was
735
+ * already present at activation is never re-declared.
736
+ */
737
+ let registryMissing = false;
659
738
  const warn = (message) => {
660
739
  ctx.logger?.warn?.(`dsh-liangshen: ${message}`);
661
740
  };
@@ -681,14 +760,19 @@ function applyImpl(ctx, config) {
681
760
  if (closed || target !== generation) return;
682
761
  await undeclare();
683
762
  const values = resolveConfig(config);
684
- if (!values.enabled) return;
763
+ if (!values.enabled) {
764
+ registryMissing = false;
765
+ return;
766
+ }
685
767
  const registry = registryOf();
686
768
  if (registry === void 0) {
769
+ registryMissing = true;
687
770
  warn("the agent-preset registry is unavailable; the preset is not declared");
688
771
  return;
689
772
  }
690
773
  try {
691
774
  release = await registry.register(declaration(values));
775
+ registryMissing = false;
692
776
  ctx.logger?.info?.(`liangshen: preset ${LIANGSHEN_PRESET_ID} declared`);
693
777
  } catch (error) {
694
778
  warn(`declaring the preset failed: ${error instanceof Error ? error.message : String(error)}`);
@@ -719,6 +803,34 @@ function applyImpl(ctx, config) {
719
803
  ctx.on("loader/volatile-update", () => {
720
804
  rearm();
721
805
  });
806
+ /**
807
+ * Recover the declaration when the agent-preset registry appears.
808
+ *
809
+ * The registry is deliberately NOT a hard inject: a deployment may compose no
810
+ * preset registry at all, and waiting on it would then pend this row forever
811
+ * -- which under the host's boot gate fails the entire web boot, not just this
812
+ * plugin (issue #1712). But the registry's own publication is decided by its
813
+ * dependency chain (the official registry injects `loader` and
814
+ * `sessionProjections`, and reaches `settings` through `ctx.inject`), so this
815
+ * row's single activation can land BEFORE the service exists. Without this
816
+ * edge the one declaration attempt was simply lost until an unrelated settings
817
+ * write happened to re-arm -- exactly the "toggle any switch and the preset
818
+ * appears, and only then" report (issue #1721).
819
+ *
820
+ * `registryMissing` is the gate rather than a plain `rearm()`: the registry is
821
+ * normally already present at activation, and this callback fires
822
+ * asynchronously even then, so re-arming unconditionally would release and
823
+ * re-declare the preset the activation had just registered (and swap the
824
+ * announcement section for nothing). The callback only repairs the missed
825
+ * case -- the one where the earlier attempt warned and gave up -- and `declare`
826
+ * is idempotent (it undeclares first and carries a generation guard), so a
827
+ * recovery racing an in-flight declaration still settles on one live
828
+ * registration. The fiber's `closed` flag keeps a late arrival from declaring
829
+ * after this row unloads.
830
+ */
831
+ ctx.inject(["agentPresets"], () => {
832
+ if (registryMissing) rearm();
833
+ });
722
834
  ctx.effect(() => {
723
835
  rearm();
724
836
  return async () => {
@@ -18,18 +18,50 @@
18
18
  * thrown — one external plugin must not take the GUI boot down.
19
19
  */
20
20
  import type { Context as ClientContext } from '@deepseek-ai/cordis';
21
- import type { ConfigForm } from '@deepseek-ai/dsh-client-ui-settings/client';
21
+ import type { ConfigForm, ConfigForms } from '@deepseek-ai/dsh-client-ui-settings/client';
22
+ import { type LiangShenSettings } from './LiangShenSettingsCard.tsx';
22
23
  import { type LiangShenKey } from './locales.ts';
23
24
  /** Locale namespace this half owns. */
24
25
  export declare const NS = "liangshen";
25
26
  /**
26
- * Settings namespace the settings card edits. Under the 0.1.7 settings
27
- * contract the namespace IS the Host profile entry id, so this names the
28
- * standalone row; the aggregate install mounts the generated
29
- * `web-ui-liangshen` row instead and the family binder resolves between the
30
- * two. Without that binder the card binds the entry id directly.
27
+ * Settings namespace the settings card edits: the family identity of this
28
+ * plugin's own settings form, and the row id a standalone bundle install
29
+ * carries. The aggregate install mounts the generated `web-ui-liangshen` row
30
+ * instead, and the family binder resolves between the two.
31
31
  */
32
32
  export declare const SETTINGS_NAMESPACE = "liangshen";
33
+ /**
34
+ * The profile entry id this package's own row carries, for a page that serves
35
+ * no family binder.
36
+ *
37
+ * The shared describe mirror is the only local evidence of which row id this
38
+ * profile actually serves, but it answers asynchronously: at plugin activation
39
+ * it usually holds nothing yet. An unanswered or empty mirror is therefore NOT
40
+ * evidence of absence, and binding the bare namespace there is what made every
41
+ * save fail with `No configurable plugin entry "liangshen"` — the form is
42
+ * bound once per session, so a wrong guess never recovers. The aggregate row id
43
+ * is the answer that matches nearly every deployment; only a mirror that
44
+ * answers with OTHER plugins' rows keeps the namespace as the last resort (the
45
+ * pre-0.1.7 keying shape), because that answer is the one that actually proves
46
+ * this package's own row is not served.
47
+ * @param forms - the shared configuration forms service.
48
+ * @returns the entry id to bind.
49
+ */
50
+ export declare function servedEntryId(forms: ConfigForms): string;
51
+ /**
52
+ * Bind the settings form the card stages over.
53
+ *
54
+ * The family binder comes first: it is what resolves this package's family
55
+ * namespace onto the profile entry id the Host serves the form under, and it
56
+ * keeps the loopback bridge as its own fallback. A page without that group (or
57
+ * one where its client half has not applied yet) binds through the shared forms
58
+ * service, on the entry id the describe mirror justifies and rebound as soon as
59
+ * the mirror answers — see {@link createServedEntryForm} for why a one-shot
60
+ * guess cannot be right for both an aggregate and a standalone install.
61
+ * @param ctx - the browser plugin context.
62
+ * @returns the form the settings card reads and writes.
63
+ */
64
+ export declare function bindSettingsForm(ctx: ClientContext): ConfigForm<LiangShenSettings>;
33
65
  /** Owner share of a plugin card (the section supplies nothing). */
34
66
  export interface SettingsPluginItemOwnerProps {
35
67
  /** Marker field: card owner props are intentionally empty. */
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Family settings form bound to the profile entry id a Host actually serves.
3
+ *
4
+ * Under the 0.1.7 settings model a form is addressed by PROFILE ENTRY ID, while
5
+ * a family card knows only its own settings namespace. The family binder
6
+ * (`ctx.get('webUiSettings')`, published by dsh-web-settings) resolves one onto
7
+ * the other and is the preferred transport; this module is the fallback for a
8
+ * page that serves no binder — the group plugin is not installed, or its client
9
+ * half has not applied yet (the aggregate mounts its children in order, and a
10
+ * child still waiting on its own injects publishes nothing).
11
+ *
12
+ * The shared describe mirror is the only local evidence of which row id this
13
+ * profile serves, but it answers asynchronously: at plugin activation it usually
14
+ * holds nothing yet. A one-shot guess therefore cannot be right for every
15
+ * deployment, and the form is bound once per session:
16
+ *
17
+ * - binding the bare namespace made every save answer `No configurable plugin
18
+ * entry "<namespace>"` on an aggregate install (the namespace is not an entry
19
+ * id there), which the card reported as "the deployment did not accept these
20
+ * values";
21
+ * - binding the aggregate row id would break a standalone install, whose row id
22
+ * is the namespace or the package's own `ui-*` row.
23
+ *
24
+ * So the fallback starts on the most likely row and REBINDS the moment the
25
+ * mirror names one of this package's rows. Until the mirror answers, the form
26
+ * reports the binding it holds (usually `loading`), which the card renders as an
27
+ * unavailable form rather than a doomed one.
28
+ */
29
+ import type { ConfigForm, ConfigForms } from '@deepseek-ai/dsh-client-ui-settings/client';
30
+ /** Options of {@link createServedEntryForm}. */
31
+ export interface ServedEntryFormOptions<T> {
32
+ /** The shared configuration forms service (`ctx.configForms`). */
33
+ forms: ConfigForms;
34
+ /**
35
+ * Profile entry ids this package's rows carry, most likely first: the
36
+ * aggregate's generated row, the package's own standalone row, then the bare
37
+ * namespace. The first is the fallback while the mirror has no answer; the
38
+ * last is the answer when the mirror serves none of them.
39
+ */
40
+ entryIds: readonly string[];
41
+ }
42
+ /**
43
+ * Create a settings form bound to the profile entry id this Host serves, and
44
+ * rebound whenever the shared describe mirror names a different one of this
45
+ * package's rows.
46
+ * @param options - the shared forms service and this package's candidate row ids.
47
+ * @returns a form delegating to the currently resolved entry's own form.
48
+ */
49
+ export declare function createServedEntryForm<T>(options: ServedEntryFormOptions<T>): ConfigForm<T>;
@@ -4,19 +4,50 @@
4
4
  * the loader accepts a standalone install of the same package side by side;
5
5
  * without this guard the second instance would still re-register the same
6
6
  * webserver routes, tools, settings namespaces, and system-prompt sections
7
- * and fail the boot. mountOnce makes the second host apply a no-op for the
8
- * lifetime of the first instance (the browser half is already deduped by
9
- * package name in the client module host).
7
+ * and fail the boot. mountOnce makes a mount of an already-mounted package a
8
+ * no-op for as long as the first instance lives (the browser half is already
9
+ * deduped by package name in the client module host).
10
+ *
11
+ * A no-op is only safe while the holder is ALIVE. The holder can be disposed
12
+ * long after the refused mount ran its course: the Host reloads a profile by
13
+ * creating the new loader entries before the old ones are torn down (a
14
+ * plugin-manager enable/disable/install write, a settings-driven row reload,
15
+ * HMR), so the new aggregate shell entry mounts its family plugin while the
16
+ * previous entry still owns the name. Dropping that refused mount lost the
17
+ * plugin for good - the previous entry then disposed its own mount, releasing
18
+ * the name with nobody left to take it, and the family row stayed listed as
19
+ * active while its host routes 404ed (the task-board panel showed
20
+ * "board.hostError.notMounted", no degraded record appeared, and only a Host
21
+ * restart recovered it).
22
+ *
23
+ * The refused mount is therefore QUEUED, not dropped, and replayed the moment
24
+ * the holder releases the name - if the waiting fiber is still alive then. The
25
+ * single-instance guarantee is unchanged: exactly one mount is live per
26
+ * package name, and the replay re-enters the guard so a later mount still
27
+ * dedupes against it.
10
28
  *
11
29
  * The registry rides a global symbol so two module instances of the same
12
- * package (npm copy vs repository link) still share one verdict. cordis
13
- * `ctx.effect` runs its callback immediately and treats the callback's
30
+ * package (npm copy vs repository link) still share one verdict. That symbol
31
+ * is a CROSS-REPOSITORY contract, not this file's private state: the four
32
+ * satellite packages (dsh-skins / dsh-pet / dsh-presets /
33
+ * dsh-community-plugins) are separate repositories carrying their own copy of
34
+ * this guard, rebuilt on their own schedule, so the value under `MOUNTED`
35
+ * must keep the shape every published copy reads (a `Set` of package names
36
+ * with `has`/`add`/`delete`). The wait queues this guard added therefore live
37
+ * under their own additive key, and the registry reads back a `Set` even when
38
+ * some other build left a different value there. Changing `MOUNTED`'s shape
39
+ * in place broke that contract once: a satellite's legacy copy created a
40
+ * `Set`, the family's new copy read it as a `Map`, and every family row
41
+ * mounted after it failed with "claims.get is not a function".
42
+ *
43
+ * cordis `ctx.effect` runs its callback immediately and treats the callback's
14
44
  * return value as the fiber disposer, so the unmarker is returned, not run.
15
45
  */
16
46
  /**
17
47
  * Wrap a cordis plugin apply so the package runs at most once per process.
18
- * The first mount registers normally and unmarks when its fiber disposes;
19
- * any later mount of the same package name is a no-op.
48
+ * The first mount registers normally and releases the name when its fiber
49
+ * disposes; a mount refused while that name is held waits for the release and
50
+ * then runs, unless its own fiber disposes first.
20
51
  * @param packageName - npm package identity shared by every install source.
21
52
  * @param fn - the original plugin apply.
22
53
  * @returns an apply of the same shape.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@linxin666/dsh-liangshen",
3
3
  "description": "LiangShen (梁神) agent preset plus its composer lever for the dsh web GUI. The host half declares the bundled preset to the harness's agent-preset registry at activation (declare = enabled), so the preset is selectable for new sessions without writing anything into the harness home; the preset keeps a minimal persona with standing working discipline while the harness's own user-role agent-instructions injection delivers the workspace instructions (the optional `instructionSource: system-prompt` mode lifts them into the prompt instead), and declares one tool presentation for the session's whole lifetime (default `presentation: 'both'`, where the wire collapses to the `run_code` transport and every other tool is reached through the generated SDK; `native` keeps the assembled roster, `ptc` keeps only the transport). High-fan-out tool families (default `mcp__*`) stay paged out of the wire until the preset's own `tool_activate` tool loads their namespace (LRU cap three, state replayed from the durable session event stream), and the tool catalog — exactly the on-wire tools plus paged-out namespace summaries — and a one-line working-context projection travel as durable user messages republished only on change. The browser half adds a slot-machine lever left of the model selector on the new-session screen to toggle the mode. Hot-pluggable via cordis.patch.yml + profile symlink, no dsh source changes.",
4
- "version": "0.4.2",
4
+ "version": "0.4.4",
5
5
  "icon": "icon.svg",
6
6
  "type": "module",
7
7
  "engines": {
@@ -23,7 +23,7 @@
23
23
  },
24
24
  "dsh": {
25
25
  "engines": {
26
- "dsh": ">=0.1.7-rc.2"
26
+ "dsh": ">=0.2.0-rc.1"
27
27
  },
28
28
  "bundle": {
29
29
  "patch": "./cordis.patch.yml"
@@ -40,25 +40,25 @@
40
40
  }
41
41
  },
42
42
  "peerDependencies": {
43
- "@deepseek-ai/dsh": ">=0.1.7-rc.2"
43
+ "@deepseek-ai/dsh": ">=0.2.0-rc.1"
44
44
  },
45
45
  "dependencies": {
46
46
  "@deepseek-ai/schemastery": "^3.18.4"
47
47
  },
48
48
  "devDependencies": {
49
49
  "@deepseek-ai/cordis": "^4.0.4",
50
- "@deepseek-ai/dsh-agent-preset-registry": "^0.1.7-rc.2",
51
- "@deepseek-ai/dsh-api-remotes": "^0.1.7-rc.2",
52
- "@deepseek-ai/dsh-api-session-controller": "^0.1.7-rc.2",
53
- "@deepseek-ai/dsh-client-connection": "^0.1.7-rc.2",
54
- "@deepseek-ai/dsh-client-locale": "^0.1.7-rc.2",
55
- "@deepseek-ai/dsh-client-store": "^0.1.7-rc.2",
56
- "@deepseek-ai/dsh-client-ui-conversation": "^0.1.7-rc.2",
57
- "@deepseek-ai/dsh-client-ui-renderer": "^0.1.7-rc.2",
58
- "@deepseek-ai/dsh-client-ui-settings": "^0.1.7-rc.2",
59
- "@deepseek-ai/dsh-client-ui-slots": "^0.1.7-rc.2",
60
- "@deepseek-ai/dsh-settings": "^0.1.7-rc.2",
61
- "@deepseek-ai/dsh-system-prompt": "^0.1.7-rc.2",
50
+ "@deepseek-ai/dsh-agent-preset-registry": "^0.2.0-rc.1",
51
+ "@deepseek-ai/dsh-api-remotes": "^0.2.0-rc.1",
52
+ "@deepseek-ai/dsh-api-session-controller": "^0.2.0-rc.1",
53
+ "@deepseek-ai/dsh-client-connection": "^0.2.0-rc.1",
54
+ "@deepseek-ai/dsh-client-locale": "^0.2.0-rc.1",
55
+ "@deepseek-ai/dsh-client-store": "^0.2.0-rc.1",
56
+ "@deepseek-ai/dsh-client-ui-conversation": "^0.2.0-rc.1",
57
+ "@deepseek-ai/dsh-client-ui-renderer": "^0.2.0-rc.1",
58
+ "@deepseek-ai/dsh-client-ui-settings": "^0.2.0-rc.1",
59
+ "@deepseek-ai/dsh-client-ui-slots": "^0.2.0-rc.1",
60
+ "@deepseek-ai/dsh-settings": "^0.2.0-rc.1",
61
+ "@deepseek-ai/dsh-system-prompt": "^0.2.0-rc.1",
62
62
  "@testing-library/react": "^16.1.0",
63
63
  "@types/node": "^22.20.0",
64
64
  "@types/react": "~18.3.1",
@@ -35,15 +35,24 @@ interface FakeHost {
35
35
  unload(): Promise<void>
36
36
  /** Dispatch `loader/volatile-update` to this fiber's listeners. */
37
37
  commit(): void
38
+ /** Publish the registry service late and run the waiting `ctx.inject` callbacks. */
39
+ publishRegistry(): void
38
40
  }
39
41
 
40
42
  /** Build a fake host context; `withRegistry: false` models a deployment without one. */
41
- function makeHost(options: { withRegistry?: boolean } = {}): FakeHost {
43
+ function makeHost(options: { withRegistry?: boolean, deferRegistry?: boolean } = {}): FakeHost {
42
44
  const sections: FakeHost['sections'] = []
43
45
  const declarations: FakeRegistration[] = []
44
46
  const warnings: string[] = []
45
47
  const effects: unknown[] = []
46
48
  const listeners = new Map<string, ((...args: unknown[]) => void)[]>()
49
+ /**
50
+ * Pending `ctx.inject` callbacks, keyed by dependency. `deferRegistry` models
51
+ * the cold-start race (issue #1721): the registry service is published AFTER
52
+ * this row's activation, so the activation's own declaration attempt misses it
53
+ * and only a later publication can recover the preset.
54
+ */
55
+ const injectCallbacks = new Map<string, (() => void)[]>()
47
56
  const registry = options.withRegistry === false ? undefined : {
48
57
  register: async (definition: PresetDefinition) => {
49
58
  const record: FakeRegistration = { definition, released: false }
@@ -51,6 +60,7 @@ function makeHost(options: { withRegistry?: boolean } = {}): FakeHost {
51
60
  return async () => { record.released = true }
52
61
  },
53
62
  }
63
+ const published = { registry: options.deferRegistry === true ? undefined : registry }
54
64
  const ctx = {
55
65
  systemPrompt: {
56
66
  section: (spec: { name: string, order: number, text: string }) => {
@@ -69,7 +79,14 @@ function makeHost(options: { withRegistry?: boolean } = {}): FakeHost {
69
79
  listeners.set(event, list)
70
80
  return () => { listeners.set(event, (listeners.get(event) ?? []).filter(entry => entry !== listener)) }
71
81
  },
72
- get: (name: string) => (name === 'agentPresets' ? registry : undefined),
82
+ inject: (deps: string[], callback: () => void) => {
83
+ for (const dep of deps) {
84
+ const list = injectCallbacks.get(dep) ?? []
85
+ list.push(callback)
86
+ injectCallbacks.set(dep, list)
87
+ }
88
+ },
89
+ get: (name: string) => (name === 'agentPresets' ? published.registry : undefined),
73
90
  logger: { warn: (message: string) => { warnings.push(message) }, info: () => {} },
74
91
  }
75
92
  return {
@@ -85,6 +102,14 @@ function makeHost(options: { withRegistry?: boolean } = {}): FakeHost {
85
102
  commit() {
86
103
  for (const listener of listeners.get('loader/volatile-update') ?? []) listener([])
87
104
  },
105
+ /**
106
+ * Publish the registry service and run the pending `ctx.inject` callbacks,
107
+ * the way cordis does when the dependency's fiber activates.
108
+ */
109
+ publishRegistry() {
110
+ published.registry = registry
111
+ for (const callback of injectCallbacks.get('agentPresets') ?? []) callback()
112
+ },
88
113
  }
89
114
  }
90
115
 
@@ -110,7 +135,7 @@ afterEach(async () => {
110
135
  /** One loaded module plus the host it was applied to. */
111
136
  async function mount(
112
137
  config?: Record<string, unknown>,
113
- options: { withRegistry?: boolean } = {},
138
+ options: { withRegistry?: boolean, deferRegistry?: boolean } = {},
114
139
  ): Promise<{ mod: typeof import('../src/index.ts'), host: FakeHost }> {
115
140
  vi.resetModules()
116
141
  const mod = await import('../src/index.ts')
@@ -250,6 +275,55 @@ describe('dsh-liangshen preset declaration', () => {
250
275
  expect(host.warnings.join('\n')).toContain('agent-preset registry is unavailable')
251
276
  })
252
277
 
278
+ // #1721: the registry's publication is decided by its own dependency chain, so
279
+ // a cold start can activate this row BEFORE the service exists. The single
280
+ // declaration attempt then warned and gave up, and the preset stayed missing
281
+ // until an unrelated settings write re-armed the row -- the report's "toggle
282
+ // any switch and it appears". A hard `inject` would fix the ordering but pend
283
+ // the row forever on a registry-less deployment, which the host's boot gate
284
+ // turns into a failed web boot (#1712), so the row waits through `ctx.inject`
285
+ // and recovers when the service arrives.
286
+ it('operator gets the preset declared when the registry appears after activation', async () => {
287
+ // Given a cold start where the registry is not published yet at activation
288
+ const { host } = await mount(undefined, { deferRegistry: true })
289
+ // When the plugin activates before the service exists
290
+ // Then nothing is declared yet, and the operator is told why
291
+ expect(host.declarations.length).toBe(0)
292
+ expect(host.warnings.join('\n')).toContain('agent-preset registry is unavailable')
293
+
294
+ // And when the registry's own fiber activates and publishes the service
295
+ host.publishRegistry()
296
+ await settle()
297
+ // Then the preset is declared without any user interaction
298
+ const live = host.declarations.filter(record => !record.released)
299
+ expect(live.length).toBe(1)
300
+ })
301
+
302
+ it('operator keeps running when the registry never appears', async () => {
303
+ // Given a deployment that composes no registry at all, When the late-arrival
304
+ // edge never fires, Then the plugin stays mounted and declares nothing --
305
+ // it must not pend the row (which the host's boot gate fails the whole boot on).
306
+ const { host } = await mount(undefined, { withRegistry: false })
307
+ host.publishRegistry()
308
+ await settle()
309
+ expect(host.declarations.length).toBe(0)
310
+ expect(host.sections.length).toBe(0)
311
+ })
312
+
313
+ it('operator does not get a redundant re-declaration when the registry was already up', async () => {
314
+ // Given a warm start where the registry is already present at activation
315
+ const { host } = await mount(undefined)
316
+ expect(host.declarations.length).toBe(1)
317
+ // When the inject edge fires (it does so asynchronously even for an
318
+ // already-present service)
319
+ host.publishRegistry()
320
+ await settle()
321
+ // Then the live declaration is the same one: the recovery edge acts only on
322
+ // the missed case, so it must not release and re-declare for nothing
323
+ expect(host.declarations.length).toBe(1)
324
+ expect(host.declarations.filter(record => !record.released).length).toBe(1)
325
+ })
326
+
253
327
  it('operator gets no declaration when a write lands while the row unloads', async () => {
254
328
  // Given an unloaded row, When a settings write still reaches its
255
329
  // listener, Then no preset is declared for it.
@@ -32,32 +32,82 @@ import { LeverController } from './lever-controller.ts'
32
32
  import { LiangShenSettingsCard, LiangShenSettingsCardController, type LiangShenSettings } from './LiangShenSettingsCard.tsx'
33
33
  import { en, zh, type LiangShenKey } from './locales.ts'
34
34
  import { installPluginCard } from './plugin-card-seat.ts'
35
+ import { createServedEntryForm } from './settings-entry-form.ts'
35
36
 
36
37
  /** Locale namespace this half owns. */
37
38
  export const NS = 'liangshen'
38
39
 
39
40
  /**
40
- * Settings namespace the settings card edits. Under the 0.1.7 settings
41
- * contract the namespace IS the Host profile entry id, so this names the
42
- * standalone row; the aggregate install mounts the generated
43
- * `web-ui-liangshen` row instead and the family binder resolves between the
44
- * two. Without that binder the card binds the entry id directly.
41
+ * Settings namespace the settings card edits: the family identity of this
42
+ * plugin's own settings form, and the row id a standalone bundle install
43
+ * carries. The aggregate install mounts the generated `web-ui-liangshen` row
44
+ * instead, and the family binder resolves between the two.
45
45
  */
46
46
  export const SETTINGS_NAMESPACE = 'liangshen'
47
+
48
+ /**
49
+ * Profile entry id the family aggregate's generated row carries — the shape
50
+ * nearly every user runs, and the id the shared-forms fallback binds when the
51
+ * family binder cannot resolve the namespace.
52
+ */
47
53
  const AGGREGATE_ENTRY_ID = 'web-ui-liangshen'
54
+
55
+ /** Profile entry ids this package's patch rows carry, most specific first. */
48
56
  const LIANGSHEN_ENTRY_IDS: readonly string[] = [AGGREGATE_ENTRY_ID, 'ui-liangshen', SETTINGS_NAMESPACE]
49
57
 
50
- function servedEntryId(forms: ConfigForms): string {
58
+ /**
59
+ * The profile entry id this package's own row carries, for a page that serves
60
+ * no family binder.
61
+ *
62
+ * The shared describe mirror is the only local evidence of which row id this
63
+ * profile actually serves, but it answers asynchronously: at plugin activation
64
+ * it usually holds nothing yet. An unanswered or empty mirror is therefore NOT
65
+ * evidence of absence, and binding the bare namespace there is what made every
66
+ * save fail with `No configurable plugin entry "liangshen"` — the form is
67
+ * bound once per session, so a wrong guess never recovers. The aggregate row id
68
+ * is the answer that matches nearly every deployment; only a mirror that
69
+ * answers with OTHER plugins' rows keeps the namespace as the last resort (the
70
+ * pre-0.1.7 keying shape), because that answer is the one that actually proves
71
+ * this package's own row is not served.
72
+ * @param forms - the shared configuration forms service.
73
+ * @returns the entry id to bind.
74
+ */
75
+ export function servedEntryId(forms: ConfigForms): string {
51
76
  let served: readonly string[] | undefined
52
77
  try {
53
78
  served = forms.describe().getSnapshot().view?.namespaces.map(view => view.ns)
54
79
  } catch {
80
+ // A mirror that refuses the read is unanswered too, not absent.
55
81
  served = undefined
56
82
  }
57
- if (!served || served.length === 0) return SETTINGS_NAMESPACE
83
+ if (served === undefined || served.length === 0) return AGGREGATE_ENTRY_ID
58
84
  return LIANGSHEN_ENTRY_IDS.find(id => served.includes(id)) ?? SETTINGS_NAMESPACE
59
85
  }
60
86
 
87
+ /**
88
+ * Bind the settings form the card stages over.
89
+ *
90
+ * The family binder comes first: it is what resolves this package's family
91
+ * namespace onto the profile entry id the Host serves the form under, and it
92
+ * keeps the loopback bridge as its own fallback. A page without that group (or
93
+ * one where its client half has not applied yet) binds through the shared forms
94
+ * service, on the entry id the describe mirror justifies and rebound as soon as
95
+ * the mirror answers — see {@link createServedEntryForm} for why a one-shot
96
+ * guess cannot be right for both an aggregate and a standalone install.
97
+ * @param ctx - the browser plugin context.
98
+ * @returns the form the settings card reads and writes.
99
+ */
100
+ export function bindSettingsForm(ctx: ClientContext): ConfigForm<LiangShenSettings> {
101
+ const binder = ctx.get('webUiSettings')
102
+ if (binder !== undefined && typeof binder.bind === 'function') {
103
+ return binder.bind<LiangShenSettings>({ namespace: SETTINGS_NAMESPACE })
104
+ }
105
+ return createServedEntryForm<LiangShenSettings>({
106
+ forms: ctx.configForms,
107
+ entryIds: LIANGSHEN_ENTRY_IDS,
108
+ })
109
+ }
110
+
61
111
  /** Owner share of a plugin card (the section supplies nothing). */
62
112
  export interface SettingsPluginItemOwnerProps {
63
113
  /** Marker field: card owner props are intentionally empty. */
@@ -146,14 +196,7 @@ export function apply(ctx: ClientContext): void {
146
196
  // namespace, contributed to the Web UI plugin group beside the
147
197
  // remote-access and task-board cards.
148
198
  try {
149
- // The family binder resolves the family namespace onto this row's profile
150
- // entry id and binds the native shared form; a deployment without the group
151
- // plugin addresses the entry id directly (the standalone bundle row id).
152
- const binder = ctx.get('webUiSettings')
153
- const settingsForm = binder !== undefined && typeof binder.bind === 'function'
154
- ? binder.bind<LiangShenSettings>({ namespace: SETTINGS_NAMESPACE })
155
- : ctx.configForms.get<LiangShenSettings>(servedEntryId(ctx.configForms))
156
- const settingsCard = new LiangShenSettingsCardController(settingsForm)
199
+ const settingsCard = new LiangShenSettingsCardController(bindSettingsForm(ctx))
157
200
  // Card seat: the family group's list seat, or the official
158
201
  // bundle-configuration seat when the group is not installed.
159
202
  installPluginCard(ctx, {