universal-plugin-hub 1.3.1 → 1.5.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.
package/client/client.js CHANGED
@@ -641,7 +641,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
641
641
  --cpm-pill-bg: rgba(255, 255, 255, 0.08);
642
642
  --cpm-pill-border: rgba(255, 255, 255, 0.12);
643
643
  --cpm-pill-text: #f4f4f5;
644
- --cpm-icon-btn-bg: #373739;
644
+ --cpm-icon-btn-bg: #202023;
645
645
  --cpm-icon-btn-border: rgba(255, 255, 255, 0.14);
646
646
  --cpm-icon-btn-hover: rgba(255, 255, 255, 0.12);
647
647
  --cpm-accent: #3b82f6;
@@ -653,10 +653,10 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
653
653
  --cpm-toggle-knob-shadow: 0 1px 4px rgba(0, 0, 0, 0.45), 0 1px 1px rgba(0, 0, 0, 0.35);
654
654
  --cpm-toggle-on: #2563eb;
655
655
  --cpm-toggle-on-border: #2563eb;
656
- --cpm-modal-bg: #373739;
656
+ --cpm-modal-bg: #202023;
657
657
  --cpm-modal-border: rgba(255, 255, 255, 0.14);
658
658
  --cpm-shadow: 0 12px 36px rgba(0, 0, 0, 0.6);
659
- --cpm-toast-bg: #373739;
659
+ --cpm-toast-bg: #202023;
660
660
  --cpm-toast-text: #f4f4f5;
661
661
  --cpm-toast-border: rgba(255, 255, 255, 0.14);
662
662
  --cpm-toast-shadow: 0 8px 30px rgba(0, 0, 0, 0.6);
@@ -1015,7 +1015,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
1015
1015
  flex-direction: column;
1016
1016
  }
1017
1017
  .cpm-dark .cpm-preview-popover {
1018
- background: rgba(55, 55, 57, 0.75);
1018
+ background: rgba(32, 32, 35, 0.75);
1019
1019
  backdrop-filter: blur(22px) saturate(180%);
1020
1020
  -webkit-backdrop-filter: blur(22px) saturate(180%);
1021
1021
  border: 1px solid var(--cpm-modal-border);
@@ -1266,12 +1266,43 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
1266
1266
  overflow: hidden;
1267
1267
  text-overflow: ellipsis;
1268
1268
  }
1269
+ .cpm-root :is(.cpm-card-pill, .cpm-toggle) {
1270
+ border-radius: 9999px;
1271
+ corner-shape: initial;
1272
+ }
1273
+ @supports (border-shape: shape(from 0 0, line to 100% 100%, close)) {
1274
+ /* Each end keeps its middle 120° of circular arc. The cubic shoulders
1275
+ match the tangent and curvature of the straight edge and the arc. */
1276
+ .cpm-root :is(.cpm-card-pill, .cpm-toggle) {
1277
+ --cap-start: calc(var(--cap-radius) * 1.1);
1278
+ --cap-control-flat: calc(var(--cap-radius) * .947441);
1279
+ --cap-control-arc: calc(var(--cap-radius) * .732051);
1280
+ --cap-join-x: calc(var(--cap-radius) * .5);
1281
+ --cap-join-y: calc(var(--cap-radius) * .133975);
1282
+ border-shape: shape(
1283
+ from var(--cap-start) 0,
1284
+ line to calc(100% - var(--cap-start)) 0,
1285
+ curve to calc(100% - var(--cap-join-x)) var(--cap-join-y)
1286
+ with calc(100% - var(--cap-control-flat)) 0 / calc(100% - var(--cap-control-arc)) 0,
1287
+ arc to calc(100% - var(--cap-join-x)) calc(100% - var(--cap-join-y)) of var(--cap-radius) cw,
1288
+ curve to calc(100% - var(--cap-start)) 100%
1289
+ with calc(100% - var(--cap-control-arc)) 100% / calc(100% - var(--cap-control-flat)) 100%,
1290
+ line to var(--cap-start) 100%,
1291
+ curve to var(--cap-join-x) calc(100% - var(--cap-join-y))
1292
+ with var(--cap-control-flat) 100% / var(--cap-control-arc) 100%,
1293
+ arc to var(--cap-join-x) var(--cap-join-y) of var(--cap-radius) cw,
1294
+ curve to var(--cap-start) 0 with var(--cap-control-arc) 0 / var(--cap-control-flat) 0,
1295
+ close
1296
+ );
1297
+ }
1298
+ }
1269
1299
  .cpm-card-pill {
1300
+ /* Radius of the border's centerline: half the line-height, padding and one border edge. */
1301
+ --cap-radius: calc(.7em + 3.5px);
1270
1302
  display: inline-flex;
1271
1303
  align-items: center;
1272
1304
  justify-content: center;
1273
1305
  padding: 3px 12px;
1274
- border-radius: 9999px;
1275
1306
  font-size: 12px;
1276
1307
  font-weight: 500;
1277
1308
  cursor: pointer;
@@ -1649,20 +1680,25 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
1649
1680
  }
1650
1681
  .cpm-meta {
1651
1682
  display: flex;
1652
- gap: 32px;
1653
- margin-top: 14px;
1654
- padding-bottom: 14px;
1655
- border-bottom: 1px solid var(--cpm-border);
1683
+ gap: 12px 32px;
1684
+ margin-block: 14px 0;
1685
+ padding-block-end: 14px;
1686
+ border-block-end: 1px solid var(--cpm-border);
1656
1687
  flex-wrap: wrap;
1657
1688
  }
1658
- .cpm-meta div { font-size: 13px; }
1689
+ .cpm-meta > div { font-size: 13px; min-inline-size: 0; }
1659
1690
  .cpm-meta .k {
1660
1691
  color: var(--cpm-muted);
1661
1692
  display: block;
1662
1693
  font-size: 11.5px;
1663
- margin-bottom: 2px;
1694
+ margin-block-end: 2px;
1695
+ }
1696
+ .cpm-meta .v {
1697
+ margin-inline-start: 0;
1698
+ color: var(--cpm-text);
1699
+ font-weight: 500;
1700
+ overflow-wrap: anywhere;
1664
1701
  }
1665
- .cpm-meta .v { color: var(--cpm-text); font-weight: 500; }
1666
1702
  .cpm-meta .v a { color: var(--cpm-accent); text-decoration: none; }
1667
1703
  .cpm-skill-warning { color: #c26a24; font-size: 13px; }
1668
1704
  .cpm-card-open { border: 0; padding: 0; background: transparent; color: inherit; font: inherit; text-align: left; cursor: pointer; }
@@ -1683,6 +1719,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
1683
1719
  look like a cut-down copy. */
1684
1720
  --sw-w: 40px;
1685
1721
  --sw-h: 22px;
1722
+ --cap-radius: calc(var(--sw-h) / 2);
1686
1723
  --sw-knob: calc(var(--sw-h) * 0.7);
1687
1724
  --sw-inset: calc((var(--sw-h) - var(--sw-knob)) / 2);
1688
1725
  position: relative;
@@ -1698,7 +1735,6 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
1698
1735
  align-self: center;
1699
1736
  padding: 0;
1700
1737
  box-sizing: border-box;
1701
- border-radius: 9999px;
1702
1738
  background: var(--cpm-toggle-off);
1703
1739
  /* The hairline is an inset box-shadow, not a border and not an outline.
1704
1740
  A border pushes the box unless border-box survives a host reset; an
@@ -1720,16 +1756,10 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
1720
1756
  .cpm-toggle:focus-visible {
1721
1757
  box-shadow: inset 0 0 0 1px var(--cpm-toggle-off-border), 0 0 0 2px var(--cpm-toggle-on);
1722
1758
  }
1723
- /* The knob.
1724
- *
1725
- * Its silhouette comes from border-radius. In the host a radius declaration
1726
- * was being clamped (a 27px knob painted with a ~3px radius), and clip-path
1727
- * was the workaround — but clip-path clips the element's own box-shadow too,
1728
- * which silently deleted the lift under the knob that makes the mockup read
1729
- * as a physical control. The radius is kept here (Browsers honour it in every
1730
- * panel surface now that the switch is out of the host's generic input rules)
1731
- * so the drop shadow survives.
1732
- */
1759
+ .cpm-root .cpm-toggle::after {
1760
+ border-radius: 50%;
1761
+ corner-shape: initial;
1762
+ }
1733
1763
  .cpm-toggle::after {
1734
1764
  content: "";
1735
1765
  position: absolute;
@@ -1740,7 +1770,6 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
1740
1770
  left: var(--sw-inset);
1741
1771
  width: var(--sw-knob);
1742
1772
  height: var(--sw-knob);
1743
- border-radius: 50%;
1744
1773
  background: var(--cpm-toggle-knob);
1745
1774
  /* Two stops, the same construction as the mockup: a tight contact shadow
1746
1775
  under the knob plus a soft ambient one. This is the detail that reads
@@ -2053,12 +2082,18 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
2053
2082
  .cpm-dialog {
2054
2083
  position: fixed;
2055
2084
  inset: 0;
2056
- padding: 16px;
2085
+ box-sizing: border-box;
2086
+ padding-block: 16px;
2087
+ padding-left: calc(var(--cpm-dialog-inset-left, 0px) + 16px);
2088
+ padding-right: calc(var(--cpm-dialog-inset-right, 0px) + 16px);
2057
2089
  background: rgba(15, 23, 42, 0.38);
2058
2090
  z-index: 10000;
2059
2091
  display: flex;
2060
2092
  align-items: center;
2093
+ align-items: safe center;
2061
2094
  justify-content: center;
2095
+ justify-content: safe center;
2096
+ overflow-y: auto;
2062
2097
  overscroll-behavior: contain;
2063
2098
  backdrop-filter: blur(8px) saturate(140%);
2064
2099
  -webkit-backdrop-filter: blur(8px) saturate(140%);
@@ -2977,10 +3012,14 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
2977
3012
  outline: 2px solid var(--cpm-accent, #3b82f6);
2978
3013
  outline-offset: 2px;
2979
3014
  }
3015
+ .cpm-radio-card > .cpm-custom-radio,
3016
+ .cpm-custom-radio > .cpm-custom-radio-inner {
3017
+ border-radius: 50%;
3018
+ corner-shape: initial;
3019
+ }
2980
3020
  .cpm-custom-radio {
2981
3021
  width: 17px;
2982
3022
  height: 17px;
2983
- border-radius: 50%;
2984
3023
  border: 1.5px solid var(--cpm-border);
2985
3024
  display: flex;
2986
3025
  align-items: center;
@@ -2998,7 +3037,6 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
2998
3037
  .cpm-custom-radio-inner {
2999
3038
  width: 5px;
3000
3039
  height: 5px;
3001
- border-radius: 50%;
3002
3040
  background: #ffffff;
3003
3041
  transform: scale(0);
3004
3042
  transition: transform 0.15s cubic-bezier(0.34, 1.56, 0.64, 1);
@@ -3145,14 +3183,18 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
3145
3183
 
3146
3184
  /* ────────────────────────────── MCP Connector Modal Styles (Refined) ────────────────────────────── */
3147
3185
  .cpm-mcp-modal {
3186
+ box-sizing: border-box;
3148
3187
  width: 540px;
3149
- max-width: calc(100vw - 32px);
3188
+ max-width: 100%;
3150
3189
  border-radius: var(--dsw-radius-lg, 16px);
3151
3190
  background: #ffffff;
3152
3191
  border: 1px solid rgba(0, 0, 0, 0.08);
3153
3192
  box-shadow: 0 20px 50px rgba(0, 0, 0, 0.16), 0 4px 16px rgba(0, 0, 0, 0.06);
3154
3193
  padding: 0;
3155
3194
  overflow: visible;
3195
+ overscroll-behavior: contain;
3196
+ transform-origin: center 45%;
3197
+ animation: cpm-dialog-in 0.22s cubic-bezier(0.22, 1, 0.36, 1) both;
3156
3198
  color: #18181b;
3157
3199
  display: flex;
3158
3200
  flex-direction: column;
@@ -4108,9 +4150,12 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
4108
4150
  font-family: inherit;
4109
4151
  box-sizing: border-box;
4110
4152
  }
4153
+ .cpm-tooltip-surface,
4111
4154
  .cpm-smart-hover {
4112
4155
  border-radius: var(--dsw-radius-lg, 16px);
4113
4156
  corner-shape: squircle;
4157
+ }
4158
+ .cpm-smart-hover {
4114
4159
  user-select: text;
4115
4160
  }
4116
4161
  .cpm-root:has(.cpm-smart-hover[data-pointer-inside="true"]) :is(.cpm-card, .cpm-mcp-tool-dot) {
@@ -4126,7 +4171,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
4126
4171
  overscroll-behavior: contain;
4127
4172
  }
4128
4173
  .cpm-dark .cpm-mcp-tool-popover {
4129
- background: rgba(55, 55, 57, 0.75);
4174
+ background: rgba(32, 32, 35, 0.75);
4130
4175
  backdrop-filter: blur(22px) saturate(180%);
4131
4176
  -webkit-backdrop-filter: blur(22px) saturate(180%);
4132
4177
  border: 1px solid var(--cpm-modal-border);
@@ -4507,7 +4552,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
4507
4552
  user-select: none;
4508
4553
  }
4509
4554
  .cpm-dark .cpm-toast {
4510
- background: rgba(55, 55, 57, 0.75);
4555
+ background: rgba(32, 32, 35, 0.75);
4511
4556
  color: #f4f4f5;
4512
4557
  backdrop-filter: blur(22px) saturate(180%);
4513
4558
  -webkit-backdrop-filter: blur(22px) saturate(180%);
@@ -4657,37 +4702,136 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
4657
4702
  animation: cpm-rot 0.75s linear infinite;
4658
4703
  }
4659
4704
  .cpm-tooltip {
4660
- padding: 5px 10px;
4661
- border-radius: 8px;
4662
- font-size: 11.5px;
4705
+ position: fixed;
4706
+ padding: 0;
4707
+ border: 0;
4708
+ background: transparent;
4709
+ color: inherit;
4710
+ overflow: visible;
4711
+ pointer-events: none;
4712
+ z-index: 999999;
4713
+ width: fit-content;
4714
+ max-width: calc(100vw - 24px);
4715
+ transition:
4716
+ display 0.09s,
4717
+ overlay 0.09s;
4718
+ transition-behavior: allow-discrete;
4719
+ }
4720
+ .cpm-tooltip:not(:is(:popover-open, .\\:popover-open, [data-open="true"])) {
4721
+ display: none;
4722
+ }
4723
+ .cpm-tooltip-surface {
4724
+ --cpm-tip-y: 4px;
4725
+ --cpm-tip-origin-x: 50%;
4726
+ max-width: min(280px, calc(100vw - 24px));
4727
+ padding: 6px 12px;
4728
+ font-size: 12px;
4663
4729
  font-weight: 500;
4664
4730
  line-height: 1.35;
4731
+ letter-spacing: 0.005em;
4665
4732
  white-space: nowrap;
4666
- box-shadow: 0 4px 14px rgba(0, 0, 0, 0.08), 0 1px 3px rgba(0, 0, 0, 0.04);
4667
- background: #ffffff;
4733
+ overflow: hidden;
4734
+ text-overflow: ellipsis;
4668
4735
  color: #18181b;
4669
- border: 1px solid rgba(0, 0, 0, 0.12);
4670
- animation: cpmTipIn 0.12s cubic-bezier(0.16, 1, 0.3, 1) forwards;
4736
+ background: rgba(255, 255, 255, 0.88);
4737
+ background-clip: padding-box;
4738
+ border: 1px solid rgba(0, 0, 0, 0.08);
4739
+ box-shadow:
4740
+ 0 6px 20px rgba(0, 0, 0, 0.1),
4741
+ 0 2px 6px rgba(0, 0, 0, 0.05);
4742
+ backdrop-filter: blur(20px) saturate(180%);
4743
+ -webkit-backdrop-filter: blur(20px) saturate(180%);
4744
+ transform-origin: var(--cpm-tip-origin-x) bottom;
4745
+ opacity: 0;
4746
+ transform: translateY(var(--cpm-tip-y)) scale(0.94);
4747
+ will-change: opacity, transform;
4748
+ transition:
4749
+ opacity 0.09s cubic-bezier(0.22, 1, 0.36, 1),
4750
+ transform 0.09s cubic-bezier(0.22, 1, 0.36, 1);
4671
4751
  }
4672
- .cpm-root.cpm-dark .cpm-tooltip, .cpm-tooltip.cpm-dark {
4673
- background: #27272a;
4752
+ .cpm-root.cpm-dark .cpm-tooltip-surface,
4753
+ .cpm-tooltip.cpm-dark .cpm-tooltip-surface {
4674
4754
  color: #f4f4f5;
4675
- border: 1px solid rgba(255, 255, 255, 0.14);
4676
- box-shadow: 0 6px 20px rgba(0, 0, 0, 0.55), 0 2px 6px rgba(0, 0, 0, 0.3);
4755
+ background: rgba(34, 34, 38, 0.88);
4756
+ border: 1px solid rgba(255, 255, 255, 0.12);
4757
+ box-shadow:
4758
+ 0 8px 24px rgba(0, 0, 0, 0.5),
4759
+ 0 2px 6px rgba(0, 0, 0, 0.32);
4677
4760
  }
4678
- @keyframes cpmTipIn {
4679
- from {
4761
+ .cpm-tooltip:is(:popover-open, .\\:popover-open, [data-open="true"]) .cpm-tooltip-surface {
4762
+ opacity: 1;
4763
+ transform: translateY(0) scale(1);
4764
+ transition:
4765
+ opacity 0.09s cubic-bezier(0.22, 1, 0.36, 1),
4766
+ transform 0.14s cubic-bezier(0.22, 1, 0.36, 1);
4767
+ transition:
4768
+ opacity 0.09s cubic-bezier(0.22, 1, 0.36, 1),
4769
+ transform 0.14s linear(0, 0.1293 3.6%, 0.2747 7.1%, 0.4206 10.7%, 0.5566 14.3%, 0.6768 17.9%, 0.7782 21.4%, 0.8602 25%, 0.9238 28.6%, 0.9709 32.1%, 1.004 35.7%, 1.0255 39.3%, 1.0379 42.9%, 1.0435 46.4%, 1.0443 50%, 1.0419 53.6%, 1.0374 57.1%, 1.0321 60.7%, 1.0264 64.3%, 1.021 67.9%, 1.016 71.4%, 1.0118 75%, 1.0083 78.6%, 1.0056 82.1%, 1.0035 85.7%, 1.002 89.3%, 1.001 92.9%, 1.0003 96.4%, 1);
4770
+ }
4771
+ @starting-style {
4772
+ .cpm-tooltip:is(:popover-open, .\\:popover-open, [data-open="true"]) .cpm-tooltip-surface {
4680
4773
  opacity: 0;
4681
- transform: translateY(3px) scale(0.96);
4774
+ transform: translateY(var(--cpm-tip-y)) scale(0.94);
4682
4775
  }
4683
- to {
4684
- opacity: 1;
4685
- transform: translateY(0) scale(1);
4776
+ }
4777
+ .cpm-tooltip[data-placement="bottom"] .cpm-tooltip-surface {
4778
+ --cpm-tip-y: -4px;
4779
+ transform-origin: var(--cpm-tip-origin-x) top;
4780
+ }
4781
+ .cpm-tooltip[data-anchored="false"] {
4782
+ position-area: none;
4783
+ position-anchor: auto;
4784
+ inset: auto;
4785
+ right: auto;
4786
+ bottom: auto;
4787
+ margin: 0;
4788
+ }
4789
+ @supports (position-area: block-start) and (anchor-name: --cpm-tip-anchor) {
4790
+ .cpm-tooltip:not([data-anchored="false"]) {
4791
+ position-anchor: --cpm-tip-anchor;
4792
+ position-area: block-start;
4793
+ position-try-fallbacks: flip-block;
4794
+ justify-self: anchor-center;
4795
+ margin-inline: 12px;
4796
+ margin-block-end: 8px;
4797
+ }
4798
+ }
4799
+ @supports (container-type: anchored) {
4800
+ .cpm-tooltip:not([data-anchored="false"]) {
4801
+ container-type: anchored;
4802
+ }
4803
+ @container anchored(fallback: flip-block) {
4804
+ .cpm-tooltip-surface {
4805
+ --cpm-tip-y: -4px;
4806
+ transform-origin: var(--cpm-tip-origin-x) top;
4807
+ }
4686
4808
  }
4687
4809
  }
4688
4810
  @media (prefers-reduced-motion: reduce) {
4811
+ .cpm-tooltip {
4812
+ transition:
4813
+ display 0.1s,
4814
+ overlay 0.1s;
4815
+ transition-behavior: allow-discrete;
4816
+ }
4817
+ .cpm-tooltip-surface {
4818
+ --cpm-tip-y: 0px;
4819
+ transform: none;
4820
+ will-change: opacity;
4821
+ transition: opacity 0.1s ease;
4822
+ }
4823
+ .cpm-tooltip:is(:popover-open, .\\:popover-open, [data-open="true"]) .cpm-tooltip-surface {
4824
+ transform: none;
4825
+ transition: opacity 0.1s ease;
4826
+ }
4827
+ @starting-style {
4828
+ .cpm-tooltip:is(:popover-open, .\\:popover-open, [data-open="true"]) .cpm-tooltip-surface {
4829
+ opacity: 0;
4830
+ transform: none;
4831
+ }
4832
+ }
4689
4833
  .cpm-dialog { animation-duration: 0.08s; }
4690
- .cpm-dialog-box { animation-name: cpm-dialog-fade; animation-duration: 0.1s; }
4834
+ .cpm-dialog-box, .cpm-mcp-modal { animation-name: cpm-dialog-fade; animation-duration: 0.1s; }
4691
4835
  .cpm-source-dialog-box { transition: border-color 100ms ease, box-shadow 100ms ease; }
4692
4836
  .cpm-source-drag-overlay,
4693
4837
  .cpm-source-drag-content {
@@ -4723,6 +4867,28 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
4723
4867
  .cpm-upload-progress:indeterminate::-moz-progress-bar { animation-duration: 10s; }
4724
4868
  .cpm-upload-dialog .cpm-spin-ring { animation-duration: 3s; }
4725
4869
  }
4870
+ @media (prefers-reduced-transparency: reduce) {
4871
+ .cpm-tooltip-surface {
4872
+ backdrop-filter: none;
4873
+ -webkit-backdrop-filter: none;
4874
+ background: #ffffff;
4875
+ }
4876
+ .cpm-root.cpm-dark .cpm-tooltip-surface,
4877
+ .cpm-tooltip.cpm-dark .cpm-tooltip-surface {
4878
+ background: #222226;
4879
+ }
4880
+ }
4881
+ @media (prefers-contrast: more) {
4882
+ .cpm-tooltip-surface {
4883
+ background: rgba(255, 255, 255, 0.96);
4884
+ border-color: rgba(0, 0, 0, 0.28);
4885
+ }
4886
+ .cpm-root.cpm-dark .cpm-tooltip-surface,
4887
+ .cpm-tooltip.cpm-dark .cpm-tooltip-surface {
4888
+ background: rgba(34, 34, 38, 0.96);
4889
+ border-color: rgba(255, 255, 255, 0.34);
4890
+ }
4891
+ }
4726
4892
  @media (prefers-reduced-transparency: reduce), (prefers-contrast: more) {
4727
4893
  .cpm-dialog {
4728
4894
  backdrop-filter: none;
@@ -4734,11 +4900,19 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
4734
4900
  border-color: var(--cpm-accent);
4735
4901
  box-shadow: none;
4736
4902
  }
4737
- .cpm-dialog-box, .cpm-source-dialog-box { border-color: var(--cpm-text-sub); }
4903
+ .cpm-dialog-box, .cpm-source-dialog-box, .cpm-mcp-modal { border-color: var(--cpm-text-sub); }
4738
4904
  .cpm-upload-dialog .cpm-dropzone { border-color: var(--cpm-text-sub); }
4739
4905
  }
4740
4906
  @media (forced-colors: active) {
4741
- .cpm-dialog-box, .cpm-source-dialog-box {
4907
+ .cpm-tooltip-surface {
4908
+ backdrop-filter: none;
4909
+ -webkit-backdrop-filter: none;
4910
+ background: Canvas;
4911
+ color: CanvasText;
4912
+ border: 1px solid CanvasText;
4913
+ box-shadow: none;
4914
+ }
4915
+ .cpm-dialog-box, .cpm-source-dialog-box, .cpm-mcp-modal {
4742
4916
  border: 1px solid CanvasText;
4743
4917
  box-shadow: none;
4744
4918
  }
@@ -4878,9 +5052,13 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
4878
5052
  err.status = res.status;
4879
5053
  throw err;
4880
5054
  }
4881
- if (body?.ok !== false && !body?.error && /^(POST|PUT|PATCH|DELETE)$/.test(options?.method || "") &&
4882
- /^\/(plugins|mcps)(\/|$)/.test(path) && !/\/(verify|oauth-status|inspect|tools\/toggle)$/.test(path)) {
4883
- document.dispatchEvent(new Event("uph-mcp-branding-changed"));
5055
+ if (typeof document !== "undefined" && body?.ok !== false && !body?.error && /^(POST|PUT|PATCH|DELETE)$/i.test(options?.method || "") &&
5056
+ !/\/(verify|oauth-status|inspect|tools\/toggle)$/.test(path) && path !== "/sources/ensure") {
5057
+ if (/^\/(plugins|mcps)(\/|$)/.test(path)) {
5058
+ document.dispatchEvent(new Event("uph-mcp-branding-changed"));
5059
+ } else if (/^\/(sources|marketplaces|market)(\/|$)/.test(path)) {
5060
+ document.dispatchEvent(new Event("uph-at-plugins-changed"));
5061
+ }
4884
5062
  }
4885
5063
  return body;
4886
5064
  }
@@ -5941,26 +6119,349 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
5941
6119
  );
5942
6120
  }
5943
6121
 
5944
- function CustomTooltip({ text, rect, isDark }) {
5945
- if (!text || !rect) return null;
5946
- const tipWidth = Math.min(280, Math.max(60, text.length * 12 + 20));
5947
- let left = rect.left + rect.width / 2 - tipWidth / 2;
5948
- left = Math.max(8, Math.min(window.innerWidth - tipWidth - 8, left));
5949
- let top = rect.top - 30;
5950
- if (top < 8) {
5951
- top = rect.bottom + 6;
6122
+ const CPM_TOOLTIP_MARGIN = 12;
6123
+ const CPM_TOOLTIP_MARGIN_Y = 8;
6124
+ const CPM_TOOLTIP_GAP = 8;
6125
+
6126
+ function getTooltipViewport(viewport) {
6127
+ return {
6128
+ width: viewport && viewport.width > 0 ? viewport.width : (typeof window !== "undefined" ? window.innerWidth : 1280),
6129
+ height: viewport && viewport.height > 0 ? viewport.height : (typeof window !== "undefined" ? window.innerHeight : 800),
6130
+ };
6131
+ }
6132
+
6133
+ /**
6134
+ * Compute viewport-safe coordinates and flip direction for a floating tooltip.
6135
+ * Keeps the tooltip horizontally centered over its trigger (clamped to margin)
6136
+ * and sets transform-origin to track the trigger's center across clamps/flips.
6137
+ */
6138
+ function placeTooltip(anchorRect, tipWidth, tipHeight, viewport) {
6139
+ const { width: vw, height: vh } = getTooltipViewport(viewport);
6140
+ const anchorW = anchorRect.width != null ? anchorRect.width : (anchorRect.right - anchorRect.left);
6141
+ const anchorBottom = anchorRect.bottom != null ? anchorRect.bottom : anchorRect.top + (anchorRect.height || 0);
6142
+ const triggerCenterX = anchorRect.left + anchorW / 2;
6143
+ const maxLeft = Math.max(CPM_TOOLTIP_MARGIN, vw - tipWidth - CPM_TOOLTIP_MARGIN);
6144
+ const left = Math.round(Math.max(CPM_TOOLTIP_MARGIN, Math.min(maxLeft, triggerCenterX - tipWidth / 2)));
6145
+ const originPx = tipWidth > 0 ? Math.max(8, Math.min(tipWidth - 8, triggerCenterX - left)) : 0;
6146
+ const originX = tipWidth > 0 ? (Math.round((originPx / tipWidth) * 1000) / 10) + "%" : "50%";
6147
+
6148
+ const aboveTop = anchorRect.top - tipHeight - CPM_TOOLTIP_GAP;
6149
+ const belowTop = anchorBottom + CPM_TOOLTIP_GAP;
6150
+ const spaceAbove = anchorRect.top - CPM_TOOLTIP_MARGIN_Y;
6151
+ const spaceBelow = vh - CPM_TOOLTIP_MARGIN_Y - anchorBottom;
6152
+
6153
+ if (aboveTop >= CPM_TOOLTIP_MARGIN_Y) {
6154
+ return {
6155
+ left,
6156
+ top: Math.round(aboveTop),
6157
+ placement: "top",
6158
+ originX,
6159
+ originY: "100%",
6160
+ };
6161
+ }
6162
+ if (spaceBelow > spaceAbove) {
6163
+ const maxTop = Math.max(CPM_TOOLTIP_MARGIN_Y, vh - tipHeight - CPM_TOOLTIP_MARGIN_Y);
6164
+ return {
6165
+ left,
6166
+ top: Math.round(Math.min(maxTop, Math.max(CPM_TOOLTIP_MARGIN_Y, belowTop))),
6167
+ placement: "bottom",
6168
+ originX,
6169
+ originY: "0%",
6170
+ };
6171
+ }
6172
+ return {
6173
+ left,
6174
+ top: Math.round(CPM_TOOLTIP_MARGIN_Y),
6175
+ placement: "top",
6176
+ originX,
6177
+ originY: "100%",
6178
+ };
6179
+ }
6180
+
6181
+ /**
6182
+ * Verify CSS Anchor Positioning actually aligned the popover to its trigger.
6183
+ * Catches ancestor containment / anchor-scope isolation where CSS anchor fails silently.
6184
+ */
6185
+ function isAnchoredTipAligned(anchorRect, tipRect, viewport) {
6186
+ if (!anchorRect || !tipRect || !(tipRect.width > 0) || !(tipRect.height > 0)) return false;
6187
+ const expected = placeTooltip(anchorRect, tipRect.width, tipRect.height, viewport);
6188
+ const anchorBottom = anchorRect.bottom != null ? anchorRect.bottom : anchorRect.top + (anchorRect.height || 0);
6189
+ const tipBottom = tipRect.bottom != null ? tipRect.bottom : tipRect.top + tipRect.height;
6190
+ const aboveGap = anchorRect.top - tipBottom;
6191
+ const belowGap = tipRect.top - anchorBottom;
6192
+ const horizOk = Math.abs(tipRect.left - expected.left) <= 4;
6193
+ const vertOk = Math.abs(aboveGap - CPM_TOOLTIP_GAP) <= 4 || Math.abs(belowGap - CPM_TOOLTIP_GAP) <= 4;
6194
+ return horizOk && vertOk;
6195
+ }
6196
+
6197
+ let _cachedTipReactDOM;
6198
+ function getTooltipReactDOM() {
6199
+ if (_cachedTipReactDOM !== undefined) return _cachedTipReactDOM;
6200
+ try {
6201
+ const mod = typeof require === "function" ? require("react-dom") : null;
6202
+ _cachedTipReactDOM = mod && typeof mod.createPortal === "function" ? mod : null;
6203
+ } catch {
6204
+ _cachedTipReactDOM = null;
6205
+ }
6206
+ return _cachedTipReactDOM;
6207
+ }
6208
+
6209
+ function restoreAnchorTarget(entry) {
6210
+ if (!entry || !entry.target) return;
6211
+ const target = entry.target;
6212
+ if (target.style && typeof target.style.setProperty === "function") {
6213
+ if (entry.prevAnchorName) {
6214
+ target.style.setProperty("anchor-name", entry.prevAnchorName, entry.prevAnchorPriority || "");
6215
+ } else if (typeof target.style.removeProperty === "function") {
6216
+ target.style.removeProperty("anchor-name");
6217
+ }
5952
6218
  }
6219
+ }
5953
6220
 
5954
- return h("div", {
6221
+ function restoreDescribedBy(entry) {
6222
+ if (!entry || !entry.addedDescribedBy || !entry.target || typeof entry.target.getAttribute !== "function") return;
6223
+ const target = entry.target;
6224
+ const tokens = (target.getAttribute("aria-describedby") || "").split(/\s+/).filter((t) => t && t !== "cpm-tooltip");
6225
+ if (tokens.length === 0) {
6226
+ if (typeof target.removeAttribute === "function") target.removeAttribute("aria-describedby");
6227
+ } else if (typeof target.setAttribute === "function") {
6228
+ target.setAttribute("aria-describedby", tokens.join(" "));
6229
+ }
6230
+ }
6231
+
6232
+ function applyFallbackPlacement(el, target) {
6233
+ if (!el || !target || typeof target.getBoundingClientRect !== "function" || typeof el.getBoundingClientRect !== "function") return;
6234
+ const anchorRect = target.getBoundingClientRect();
6235
+ const tipRect = el.getBoundingClientRect();
6236
+ if (!(tipRect.width > 0) || !(tipRect.height > 0)) return;
6237
+ const pos = placeTooltip(anchorRect, tipRect.width, tipRect.height, getTooltipViewport());
6238
+ if (typeof el.setAttribute === "function") {
6239
+ el.setAttribute("data-anchored", "false");
6240
+ el.setAttribute("data-placement", pos.placement);
6241
+ }
6242
+ if (el.style) {
6243
+ el.style.left = pos.left + "px";
6244
+ el.style.top = pos.top + "px";
6245
+ if (typeof el.style.setProperty === "function") {
6246
+ el.style.setProperty("--cpm-tip-origin-x", pos.originX);
6247
+ }
6248
+ }
6249
+ }
6250
+
6251
+ function CustomTooltip({ tooltip, isDark }) {
6252
+ const popRef = useRef(null);
6253
+ const anchorSessionRef = useRef(null);
6254
+ const closingAnchorRef = useRef(null);
6255
+ const exitGenRef = useRef(0);
6256
+ const exitTimerRef = useRef(null);
6257
+ const lastTextRef = useRef("");
6258
+
6259
+ const target = tooltip && tooltip.target ? tooltip.target : null;
6260
+ const text = tooltip && tooltip.text ? tooltip.text : "";
6261
+ const isOpen = Boolean(target && text);
6262
+ // Retain last label text across close so the 0.16s exit fade never collapses to an empty box.
6263
+ if (isOpen) lastTextRef.current = text;
6264
+ const displayText = isOpen ? text : lastTextRef.current;
6265
+
6266
+ // Ensure popover="hint" attribute is wired once on mount.
6267
+ useSafeLayoutEffect(() => {
6268
+ const el = popRef.current;
6269
+ if (!el || typeof el.setAttribute !== "function") return;
6270
+ try {
6271
+ el.setAttribute("popover", "hint");
6272
+ } catch {
6273
+ // Ignore in non-DOM test renderers or browsers rejecting hint.
6274
+ }
6275
+ }, []);
6276
+
6277
+ useSafeLayoutEffect(() => {
6278
+ const el = popRef.current;
6279
+ const hasTargetDom = Boolean(target && typeof target.getAttribute === "function");
6280
+
6281
+ if (!isOpen || !hasTargetDom) {
6282
+ const prev = anchorSessionRef.current;
6283
+ anchorSessionRef.current = null;
6284
+ if (prev) restoreDescribedBy(prev);
6285
+ const exitGen = ++exitGenRef.current;
6286
+ if (exitTimerRef.current) {
6287
+ clearTimeout(exitTimerRef.current);
6288
+ exitTimerRef.current = null;
6289
+ }
6290
+ if (el && typeof HTMLElement !== "undefined" && typeof el.hidePopover === "function") {
6291
+ try {
6292
+ if (typeof el.matches === "function" && el.matches(":popover-open")) el.hidePopover();
6293
+ } catch {
6294
+ // Ignore hide errors if already closed or detached.
6295
+ }
6296
+ }
6297
+ if (prev) {
6298
+ if (closingAnchorRef.current && closingAnchorRef.current !== prev) {
6299
+ restoreAnchorTarget(closingAnchorRef.current);
6300
+ }
6301
+ closingAnchorRef.current = prev;
6302
+ const finishClose = () => {
6303
+ if (exitGenRef.current !== exitGen) return;
6304
+ if (closingAnchorRef.current === prev) closingAnchorRef.current = null;
6305
+ restoreAnchorTarget(prev);
6306
+ };
6307
+ const anims = el && typeof el.getAnimations === "function" ? el.getAnimations({ subtree: true }) : [];
6308
+ if (anims.length > 0 && typeof Promise !== "undefined") {
6309
+ Promise.allSettled(anims.map((a) => a.finished)).then(finishClose);
6310
+ exitTimerRef.current = setTimeout(finishClose, 150);
6311
+ } else {
6312
+ finishClose();
6313
+ }
6314
+ }
6315
+ return;
6316
+ }
6317
+
6318
+ exitGenRef.current += 1;
6319
+ if (exitTimerRef.current) {
6320
+ clearTimeout(exitTimerRef.current);
6321
+ exitTimerRef.current = null;
6322
+ }
6323
+
6324
+ const existing = anchorSessionRef.current;
6325
+ if (existing && existing.target !== target) {
6326
+ restoreDescribedBy(existing);
6327
+ restoreAnchorTarget(existing);
6328
+ anchorSessionRef.current = null;
6329
+ }
6330
+
6331
+ const attachTarget = (sessionEntry) => {
6332
+ const tokens = (target.getAttribute("aria-describedby") || "").split(/\s+/).filter(Boolean);
6333
+ const addedDescribedBy = !tokens.includes("cpm-tooltip");
6334
+ if (addedDescribedBy) {
6335
+ tokens.push("cpm-tooltip");
6336
+ target.setAttribute("aria-describedby", tokens.join(" "));
6337
+ }
6338
+ if (target.style && typeof target.style.setProperty === "function") {
6339
+ target.style.setProperty("anchor-name", "--cpm-tip-anchor");
6340
+ }
6341
+ sessionEntry.addedDescribedBy = sessionEntry.addedDescribedBy || addedDescribedBy;
6342
+ anchorSessionRef.current = sessionEntry;
6343
+ };
6344
+
6345
+ const pendingClose = closingAnchorRef.current;
6346
+ if (pendingClose) {
6347
+ if (pendingClose.target === target && !anchorSessionRef.current) {
6348
+ // Reclaim original saved anchor state before restoring if re-hovered mid-exit.
6349
+ closingAnchorRef.current = null;
6350
+ attachTarget(pendingClose);
6351
+ } else {
6352
+ closingAnchorRef.current = null;
6353
+ restoreAnchorTarget(pendingClose);
6354
+ }
6355
+ }
6356
+
6357
+ if (!anchorSessionRef.current) {
6358
+ const prevAnchorName = target.style && typeof target.style.getPropertyValue === "function"
6359
+ ? target.style.getPropertyValue("anchor-name")
6360
+ : "";
6361
+ const prevAnchorPriority = target.style && typeof target.style.getPropertyPriority === "function"
6362
+ ? target.style.getPropertyPriority("anchor-name")
6363
+ : "";
6364
+ attachTarget({ target, prevAnchorName, prevAnchorPriority, addedDescribedBy: false });
6365
+ }
6366
+
6367
+ if (!el) return;
6368
+
6369
+ const supportsAnchorPos = typeof window !== "undefined" && Boolean(
6370
+ window.CSS &&
6371
+ typeof window.CSS.supports === "function" &&
6372
+ window.CSS.supports("position-area", "block-start") &&
6373
+ window.CSS.supports("anchor-name", "--cpm-tip-anchor")
6374
+ );
6375
+
6376
+ if (supportsAnchorPos) {
6377
+ if (typeof el.removeAttribute === "function") {
6378
+ el.removeAttribute("data-anchored");
6379
+ el.removeAttribute("data-placement");
6380
+ }
6381
+ if (el.style) {
6382
+ el.style.left = "";
6383
+ el.style.top = "";
6384
+ if (typeof el.style.removeProperty === "function") {
6385
+ el.style.removeProperty("--cpm-tip-origin-x");
6386
+ }
6387
+ }
6388
+ } else if (typeof el.setAttribute === "function") {
6389
+ el.setAttribute("data-anchored", "false");
6390
+ }
6391
+
6392
+ if (typeof el.showPopover === "function") {
6393
+ try {
6394
+ if (typeof el.matches !== "function" || !el.matches(":popover-open")) {
6395
+ el.showPopover();
6396
+ }
6397
+ } catch {
6398
+ // Ignore if browser rejects showPopover in current state.
6399
+ }
6400
+ }
6401
+
6402
+ if (typeof target.getBoundingClientRect === "function" && typeof el.getBoundingClientRect === "function") {
6403
+ if (!supportsAnchorPos || !isAnchoredTipAligned(target.getBoundingClientRect(), el.getBoundingClientRect(), getTooltipViewport())) {
6404
+ applyFallbackPlacement(el, target);
6405
+ }
6406
+ }
6407
+ }, [isOpen, target, text]);
6408
+
6409
+ // Keep fallback position synced on window resize or live size/text changes.
6410
+ useEffect(() => {
6411
+ const el = popRef.current;
6412
+ if (!isOpen || !el || !target) return;
6413
+ const syncIfFallback = () => {
6414
+ if (!el.getAttribute || el.getAttribute("data-anchored") !== "false") return;
6415
+ applyFallbackPlacement(el, target);
6416
+ };
6417
+ let ro = null;
6418
+ if (typeof window !== "undefined" && typeof window.ResizeObserver === "function") {
6419
+ ro = new window.ResizeObserver(syncIfFallback);
6420
+ ro.observe(el);
6421
+ if (typeof target.getBoundingClientRect === "function") ro.observe(target);
6422
+ }
6423
+ if (typeof window !== "undefined" && typeof window.addEventListener === "function") {
6424
+ window.addEventListener("resize", syncIfFallback);
6425
+ }
6426
+ return () => {
6427
+ if (ro) ro.disconnect();
6428
+ if (typeof window !== "undefined" && typeof window.removeEventListener === "function") {
6429
+ window.removeEventListener("resize", syncIfFallback);
6430
+ }
6431
+ };
6432
+ }, [isOpen, target, text]);
6433
+
6434
+ // Restore trigger attributes if CustomTooltip itself unmounts mid-display.
6435
+ useEffect(() => {
6436
+ return () => {
6437
+ if (exitTimerRef.current) clearTimeout(exitTimerRef.current);
6438
+ const pendingClose = closingAnchorRef.current;
6439
+ closingAnchorRef.current = null;
6440
+ if (pendingClose) restoreAnchorTarget(pendingClose);
6441
+ const current = anchorSessionRef.current;
6442
+ anchorSessionRef.current = null;
6443
+ if (current) {
6444
+ restoreDescribedBy(current);
6445
+ restoreAnchorTarget(current);
6446
+ }
6447
+ };
6448
+ }, []);
6449
+
6450
+ const node = h("div", {
6451
+ id: "cpm-tooltip",
6452
+ ref: popRef,
6453
+ role: "tooltip",
5955
6454
  className: "cpm-tooltip" + (isDark ? " cpm-dark" : ""),
5956
- style: {
5957
- position: "fixed",
5958
- left,
5959
- top,
5960
- zIndex: 999999,
5961
- pointerEvents: "none",
5962
- },
5963
- }, text);
6455
+ "data-open": isOpen ? "true" : "false",
6456
+ "aria-hidden": isOpen ? undefined : "true",
6457
+ }, h("div", { className: "cpm-tooltip-surface" }, displayText));
6458
+
6459
+ const needsBodyPortal = typeof HTMLElement === "undefined" || typeof HTMLElement.prototype?.showPopover !== "function";
6460
+ const ReactDOM = needsBodyPortal ? getTooltipReactDOM() : null;
6461
+ if (needsBodyPortal && ReactDOM && typeof document !== "undefined" && document.body) {
6462
+ return ReactDOM.createPortal(node, document.body);
6463
+ }
6464
+ return node;
5964
6465
  }
5965
6466
 
5966
6467
  let currentTabAnim = null;
@@ -6116,6 +6617,114 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
6116
6617
  return {};
6117
6618
  }
6118
6619
 
6620
+ function normalizePanelInset(value) {
6621
+ if (!Number.isFinite(value) || value < 0.01) return 0;
6622
+ return Math.round(value * 100) / 100;
6623
+ }
6624
+
6625
+ function computePanelHorizontalInsets(rootEl, doc = rootEl?.ownerDocument || globalThis.document) {
6626
+ if (!rootEl || typeof rootEl.getBoundingClientRect !== "function") {
6627
+ return { left: 0, right: 0 };
6628
+ }
6629
+ const rect = rootEl.getBoundingClientRect();
6630
+ const win = doc?.defaultView;
6631
+ const docWidth = doc?.documentElement?.clientWidth;
6632
+ const viewportWidth = Number.isFinite(docWidth) && docWidth > 0
6633
+ ? docWidth
6634
+ : (Number.isFinite(win?.innerWidth) && win.innerWidth > 0 ? win.innerWidth : 0);
6635
+ if (!rect || !(rect.width > 0) || !(viewportWidth > 0)) {
6636
+ return { left: 0, right: 0 };
6637
+ }
6638
+ const left = normalizePanelInset(rect.left);
6639
+ const right = normalizePanelInset(Number.isFinite(rect.right) ? viewportWidth - rect.right : 0);
6640
+ // Guard degenerate narrow/transient rects so dialog padding never collapses usable width below 32px
6641
+ if (left + right >= viewportWidth - 32) {
6642
+ return { left: 0, right: 0 };
6643
+ }
6644
+ return { left, right };
6645
+ }
6646
+
6647
+ function usePanelHorizontalInsets(rootRef) {
6648
+ useSafeLayoutEffect(() => {
6649
+ const rootEl = rootRef?.current;
6650
+ if (!rootEl || typeof rootEl.style?.setProperty !== "function") return undefined;
6651
+ const doc = rootEl.ownerDocument || (typeof document !== "undefined" ? document : null);
6652
+ const win = doc?.defaultView || (typeof window !== "undefined" ? window : null);
6653
+ let lastLeft = "";
6654
+ let lastRight = "";
6655
+ let rafId = 0;
6656
+
6657
+ const sync = () => {
6658
+ const { left, right } = computePanelHorizontalInsets(rootEl, doc);
6659
+ const nextLeft = `${left}px`;
6660
+ const nextRight = `${right}px`;
6661
+ if (nextLeft !== lastLeft) {
6662
+ rootEl.style.setProperty("--cpm-dialog-inset-left", nextLeft);
6663
+ lastLeft = nextLeft;
6664
+ }
6665
+ if (nextRight !== lastRight) {
6666
+ rootEl.style.setProperty("--cpm-dialog-inset-right", nextRight);
6667
+ lastRight = nextRight;
6668
+ }
6669
+ };
6670
+
6671
+ const scheduleSync = () => {
6672
+ if (rafId || typeof win?.requestAnimationFrame !== "function") {
6673
+ if (!rafId) sync();
6674
+ return;
6675
+ }
6676
+ rafId = win.requestAnimationFrame(() => {
6677
+ rafId = 0;
6678
+ sync();
6679
+ });
6680
+ };
6681
+
6682
+ sync();
6683
+
6684
+ const ResizeObserverCtor = win?.ResizeObserver || globalThis.ResizeObserver;
6685
+ let observer = null;
6686
+ const p1 = rootEl.parentElement;
6687
+ const p2 = p1?.parentElement;
6688
+ const p3 = p2?.parentElement;
6689
+ const frameRoot = p3 || p2 || p1 || rootEl;
6690
+
6691
+ if (typeof ResizeObserverCtor === "function") {
6692
+ observer = new ResizeObserverCtor(() => { sync(); });
6693
+ const targets = new Set([
6694
+ rootEl,
6695
+ p1,
6696
+ p1?.previousElementSibling,
6697
+ p1?.nextElementSibling,
6698
+ p2,
6699
+ p2?.previousElementSibling,
6700
+ p2?.nextElementSibling,
6701
+ p3,
6702
+ doc?.documentElement,
6703
+ ]);
6704
+ for (const target of targets) {
6705
+ if (target) observer.observe(target);
6706
+ }
6707
+ }
6708
+
6709
+ if (typeof win?.addEventListener === "function") win.addEventListener("resize", sync);
6710
+ if (typeof frameRoot?.addEventListener === "function") frameRoot.addEventListener("transitionend", scheduleSync);
6711
+
6712
+ return () => {
6713
+ if (rafId && typeof win?.cancelAnimationFrame === "function") {
6714
+ win.cancelAnimationFrame(rafId);
6715
+ rafId = 0;
6716
+ }
6717
+ if (observer) observer.disconnect();
6718
+ if (typeof win?.removeEventListener === "function") win.removeEventListener("resize", sync);
6719
+ if (typeof frameRoot?.removeEventListener === "function") frameRoot.removeEventListener("transitionend", scheduleSync);
6720
+ if (typeof rootEl.style?.removeProperty === "function") {
6721
+ rootEl.style.removeProperty("--cpm-dialog-inset-left");
6722
+ rootEl.style.removeProperty("--cpm-dialog-inset-right");
6723
+ }
6724
+ };
6725
+ }, [rootRef]);
6726
+ }
6727
+
6119
6728
  const SESSION_STORE = {
6120
6729
  view: { type: "browse" },
6121
6730
  sourceViews: {},
@@ -6140,6 +6749,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
6140
6749
  // ────────────────────────────── Root App ──────────────────────────────
6141
6750
  function MarketApp({ ctx }) {
6142
6751
  const rootRef = useRef(null);
6752
+ usePanelHorizontalInsets(rootRef);
6143
6753
  const getEffectiveTheme = useCallback(() => {
6144
6754
  return isDarkMode(ctx, rootRef.current);
6145
6755
  }, [ctx]);
@@ -6277,66 +6887,244 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
6277
6887
  }, duration);
6278
6888
  }, []);
6279
6889
 
6890
+ const [tipMounted, setTipMounted] = useState(false);
6280
6891
  const [activeTooltip, setActiveTooltip] = useState(null);
6892
+ const activeTipTargetRef = useRef(null);
6893
+ activeTipTargetRef.current = activeTooltip ? activeTooltip.target : null;
6281
6894
  const tipTimerRef = useRef(null);
6895
+ const pendingTipTargetRef = useRef(null);
6896
+ const tipPointerTypeRef = useRef("");
6282
6897
 
6283
- const handleRootMouseOver = useCallback((e) => {
6284
- const target = e.target && e.target.closest && e.target.closest("[data-cpm-tip]");
6285
- if (!target) {
6286
- if (tipTimerRef.current) clearTimeout(tipTimerRef.current);
6287
- setActiveTooltip(null);
6898
+ const dismissTooltip = useCallback(() => {
6899
+ pendingTipTargetRef.current = null;
6900
+ if (tipTimerRef.current) {
6901
+ clearTimeout(tipTimerRef.current);
6902
+ tipTimerRef.current = null;
6903
+ }
6904
+ setActiveTooltip(null);
6905
+ }, []);
6906
+
6907
+ const scheduleTooltip = useCallback((target, delayMs, source) => {
6908
+ if (delayMs > 0 && tipTimerRef.current && pendingTipTargetRef.current === target) {
6288
6909
  return;
6289
6910
  }
6290
- const text = target.getAttribute("data-cpm-tip");
6291
- if (!text) {
6911
+ pendingTipTargetRef.current = null;
6912
+ if (tipTimerRef.current) {
6913
+ clearTimeout(tipTimerRef.current);
6914
+ tipTimerRef.current = null;
6915
+ }
6916
+ const text = target && typeof target.getAttribute === "function" ? target.getAttribute("data-cpm-tip") : "";
6917
+ if (!target || !text) {
6292
6918
  setActiveTooltip(null);
6293
6919
  return;
6294
6920
  }
6295
- if (tipTimerRef.current) clearTimeout(tipTimerRef.current);
6921
+ setTipMounted(true);
6922
+ if (delayMs <= 0) {
6923
+ setActiveTooltip((prev) => (prev && prev.target === target && prev.text === text && prev.source === source ? prev : { target, text, source }));
6924
+ return;
6925
+ }
6926
+ pendingTipTargetRef.current = target;
6296
6927
  tipTimerRef.current = setTimeout(() => {
6297
- const rect = target.getBoundingClientRect();
6298
- setActiveTooltip({ text, rect });
6299
- }, 100);
6928
+ tipTimerRef.current = null;
6929
+ pendingTipTargetRef.current = null;
6930
+ if (target.isConnected === false) return;
6931
+ const latestText = target.getAttribute("data-cpm-tip");
6932
+ if (!latestText) {
6933
+ setActiveTooltip(null);
6934
+ return;
6935
+ }
6936
+ setActiveTooltip((prev) => (prev && prev.target === target && prev.text === latestText && prev.source === source ? prev : { target, text: latestText, source }));
6937
+ }, delayMs);
6300
6938
  }, []);
6301
6939
 
6302
- const handleRootMouseOut = useCallback((e) => {
6303
- const related = e.relatedTarget;
6304
- if (related && related.closest && related.closest("[data-cpm-tip]")) {
6305
- return;
6306
- }
6307
- if (tipTimerRef.current) clearTimeout(tipTimerRef.current);
6308
- setActiveTooltip(null);
6940
+ const handleRootPointerOverCapture = useCallback((e) => {
6941
+ tipPointerTypeRef.current = e.pointerType || "";
6309
6942
  }, []);
6310
6943
 
6311
- const refreshState = useCallback(async () => {
6312
- try {
6313
- const res = await api("/state");
6314
- setState(res);
6315
- } catch (e) {
6316
- showToast("加载状态失败", e.message, { restart: false });
6317
- }
6318
- }, [showToast]);
6944
+ const handleRootPointerDownCapture = useCallback((e) => {
6945
+ if (e.pointerType) tipPointerTypeRef.current = e.pointerType;
6946
+ if (e.pointerType === "touch") dismissTooltip();
6947
+ }, [dismissTooltip]);
6948
+
6949
+ const handleRootScrollCapture = useCallback(() => {
6950
+ if (tipTimerRef.current || activeTipTargetRef.current) dismissTooltip();
6951
+ }, [dismissTooltip]);
6952
+
6953
+ const handleRootMouseOver = useCallback((e) => {
6954
+ if (tipPointerTypeRef.current === "touch") return;
6955
+ const target = e.target && e.target.closest && e.target.closest("[data-cpm-tip]");
6956
+ if (!target) {
6957
+ dismissTooltip();
6958
+ return;
6959
+ }
6960
+ if (activeTipTargetRef.current === target) return;
6961
+ scheduleTooltip(target, 45, "pointer");
6962
+ }, [dismissTooltip, scheduleTooltip]);
6963
+
6964
+ const handleRootMouseOut = useCallback((e) => {
6965
+ const leaving = e.target && e.target.closest && e.target.closest("[data-cpm-tip]");
6966
+ const related = e.relatedTarget;
6967
+ const entering = related && related.closest && related.closest("[data-cpm-tip]");
6968
+ if (entering && (!leaving || entering === leaving)) return;
6969
+ dismissTooltip();
6970
+ }, [dismissTooltip]);
6971
+
6972
+ const handleRootFocus = useCallback((e) => {
6973
+ const target = e.target && e.target.closest && e.target.closest("[data-cpm-tip]");
6974
+ if (!target) return;
6975
+ let isFocusVisible = true;
6976
+ try {
6977
+ isFocusVisible = typeof target.matches === "function" ? target.matches(":focus-visible") : true;
6978
+ } catch {
6979
+ // Fallback to showing on focus when :focus-visible is unsupported.
6980
+ }
6981
+ if (!isFocusVisible) return;
6982
+ scheduleTooltip(target, 0, "focus");
6983
+ }, [scheduleTooltip]);
6984
+
6985
+ const handleRootBlur = useCallback((e) => {
6986
+ const related = e.relatedTarget;
6987
+ if (related && related.closest && related.closest("[data-cpm-tip]")) return;
6988
+ dismissTooltip();
6989
+ }, [dismissTooltip]);
6990
+
6991
+ useEffect(() => {
6992
+ const target = activeTooltip && activeTooltip.target;
6993
+ if (!target) return undefined;
6994
+ const rootEl = rootRef.current;
6995
+
6996
+ const handleScroll = () => dismissTooltip();
6997
+ const handleWindowBlur = () => dismissTooltip();
6998
+ const handleKeyDown = (e) => {
6999
+ if (e.key === "Escape") dismissTooltip();
7000
+ };
7001
+
7002
+ let attrObs = null;
7003
+ let treeObs = null;
7004
+ if (typeof window !== "undefined" && typeof window.MutationObserver === "function") {
7005
+ attrObs = new window.MutationObserver(() => {
7006
+ if (target.isConnected === false) {
7007
+ dismissTooltip();
7008
+ return;
7009
+ }
7010
+ const nextText = target.getAttribute("data-cpm-tip");
7011
+ if (!nextText) {
7012
+ dismissTooltip();
7013
+ return;
7014
+ }
7015
+ setActiveTooltip((prev) => (prev && prev.target === target && prev.text !== nextText ? { ...prev, text: nextText } : prev));
7016
+ });
7017
+ if (typeof target.nodeType === "number") {
7018
+ attrObs.observe(target, { attributes: true, attributeFilter: ["data-cpm-tip"] });
7019
+ }
7020
+ if (rootEl && typeof rootEl.nodeType === "number") {
7021
+ treeObs = new window.MutationObserver(() => {
7022
+ if (target.isConnected === false) dismissTooltip();
7023
+ });
7024
+ treeObs.observe(rootEl, { childList: true, subtree: true });
7025
+ }
7026
+ }
7027
+
7028
+ if (typeof window !== "undefined" && typeof window.addEventListener === "function") {
7029
+ window.addEventListener("scroll", handleScroll, { passive: true });
7030
+ window.addEventListener("blur", handleWindowBlur);
7031
+ window.addEventListener("keydown", handleKeyDown, true);
7032
+ }
7033
+
7034
+ return () => {
7035
+ if (attrObs) attrObs.disconnect();
7036
+ if (treeObs) treeObs.disconnect();
7037
+ if (typeof window !== "undefined" && typeof window.removeEventListener === "function") {
7038
+ window.removeEventListener("scroll", handleScroll);
7039
+ window.removeEventListener("blur", handleWindowBlur);
7040
+ window.removeEventListener("keydown", handleKeyDown, true);
7041
+ }
7042
+ };
7043
+ }, [activeTooltip && activeTooltip.target, dismissTooltip]);
7044
+
7045
+ useEffect(() => () => {
7046
+ if (tipTimerRef.current) clearTimeout(tipTimerRef.current);
7047
+ }, []);
7048
+
7049
+ const stateSeqRef = useRef(0);
7050
+ const mountedRef = useRef(true);
7051
+ useEffect(() => {
7052
+ mountedRef.current = true;
7053
+ return () => {
7054
+ mountedRef.current = false;
7055
+ };
7056
+ }, []);
7057
+
7058
+ const refreshState = useCallback(async ({ quiet = false, signal } = {}) => {
7059
+ const seq = ++stateSeqRef.current;
7060
+ try {
7061
+ const res = await api("/state", signal ? { signal } : undefined);
7062
+ if (mountedRef.current && !signal?.aborted && seq === stateSeqRef.current) {
7063
+ setState(res);
7064
+ if (typeof document !== "undefined") document.dispatchEvent(new Event("uph-at-plugins-changed"));
7065
+ }
7066
+ return res;
7067
+ } catch (e) {
7068
+ if (!quiet && mountedRef.current) showToast("加载状态失败", e.message, { restart: false });
7069
+ return null;
7070
+ }
7071
+ }, [showToast]);
7072
+
7073
+ const patchPluginInState = useCallback((updatedPlugin) => {
7074
+ if (!updatedPlugin || !updatedPlugin.name) return;
7075
+ const pluginName = updatedPlugin.name;
7076
+ stateSeqRef.current += 1;
7077
+ setState((prev) => ({
7078
+ ...prev,
7079
+ plugins: Array.isArray(prev.plugins)
7080
+ ? prev.plugins.map((p) => (p.name === pluginName ? updatedPlugin : p))
7081
+ : prev.plugins,
7082
+ }));
7083
+ if (typeof document !== "undefined") document.dispatchEvent(new Event("uph-at-plugins-changed"));
7084
+ }, []);
7085
+
7086
+ const hasPendingConnectors = (state.plugins || []).some(plugin =>
7087
+ plugin.enabled !== false && plugin.connectors?.some(connector => connector.pending));
7088
+ useEffect(() => {
7089
+ if (!hasPendingConnectors) return;
7090
+ const controller = new AbortController();
7091
+ let delay = 250;
7092
+ const refreshPending = async () => {
7093
+ await refreshState({ quiet: true, signal: controller.signal });
7094
+ if (controller.signal.aborted) return;
7095
+ delay = Math.min(delay * 2, 3000);
7096
+ timer = setTimeout(refreshPending, delay);
7097
+ };
7098
+ let timer = setTimeout(refreshPending, delay);
7099
+ return () => {
7100
+ controller.abort();
7101
+ clearTimeout(timer);
7102
+ };
7103
+ }, [hasPendingConnectors, refreshState]);
6319
7104
 
6320
7105
  useEffect(() => {
6321
7106
  refreshState();
6322
7107
  }, [refreshState]);
6323
7108
 
6324
7109
  // Read cached catalogs immediately, then update Git sources in the background.
6325
- const sourceIdsKey = (state.sources || []).map((s) => s.id).sort().join(",");
7110
+ const addedGitSourceIds = useRef(new Set());
7111
+ // Markets added in this panel already returned their catalog. Keep them
7112
+ // out of the startup refresh, which also pulls Git.
7113
+ const sourcesToWarm = (state.sources || []).filter((source) => !source.virtual && !addedGitSourceIds.current.has(source.id));
7114
+ const sourceIdsKey = sourcesToWarm.map((s) => s.id).sort().join(",");
6326
7115
  useEffect(() => {
6327
- if (!state.sources || state.sources.length === 0) return;
7116
+ if (sourcesToWarm.length === 0) return;
6328
7117
  let isMounted = true;
6329
7118
  (async () => {
6330
- await Promise.allSettled(state.sources.map(async (s) => {
6331
- if (s.virtual) return;
7119
+ await Promise.allSettled(sourcesToWarm.map(async (s) => {
6332
7120
  try {
6333
7121
  const res = await api("/market?sourceId=" + encodeURIComponent(s.id));
6334
7122
  if (isMounted && Array.isArray(res?.plugins)) setRows((prev) => ({ ...(prev || {}), [s.id]: res.plugins }));
6335
7123
  } catch {}
6336
7124
  }));
6337
- for (const s of state.sources) {
7125
+ for (const s of sourcesToWarm) {
6338
7126
  if (!isMounted) break;
6339
- if (s.id === "local" || s.virtual) continue;
7127
+ if (s.id === "local") continue;
6340
7128
  try {
6341
7129
  const res = await api("/market/refresh", {
6342
7130
  method: "POST",
@@ -6379,8 +7167,13 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
6379
7167
  return h("div", {
6380
7168
  ref: rootRef,
6381
7169
  className: "cpm-root" + (isDark ? " cpm-dark" : ""),
7170
+ onPointerOverCapture: handleRootPointerOverCapture,
7171
+ onPointerDownCapture: handleRootPointerDownCapture,
7172
+ onScrollCapture: handleRootScrollCapture,
6382
7173
  onMouseOver: handleRootMouseOver,
6383
7174
  onMouseOut: handleRootMouseOut,
7175
+ onFocus: handleRootFocus,
7176
+ onBlur: handleRootBlur,
6384
7177
  },
6385
7178
  h(BrowseView, {
6386
7179
  view,
@@ -6388,6 +7181,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
6388
7181
  state,
6389
7182
  setState,
6390
7183
  refreshState,
7184
+ patchPluginInState,
6391
7185
  showToast,
6392
7186
  openManage,
6393
7187
  onInstalled,
@@ -6402,6 +7196,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
6402
7196
  setActiveSourceId,
6403
7197
  rows,
6404
7198
  setRows,
7199
+ addedGitSourceIds,
6405
7200
  scrollTopRef,
6406
7201
  }),
6407
7202
  toast && h("div", {
@@ -6415,7 +7210,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
6415
7210
  toast.body && h("div", { className: "cpm-toast-body" }, toast.body),
6416
7211
  ),
6417
7212
  ),
6418
- activeTooltip && h(CustomTooltip, { text: activeTooltip.text, rect: activeTooltip.rect, isDark }),
7213
+ (tipMounted || activeTooltip) && h(CustomTooltip, { tooltip: activeTooltip, isDark }),
6419
7214
  );
6420
7215
  }
6421
7216
 
@@ -7080,6 +7875,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
7080
7875
  state,
7081
7876
  setState,
7082
7877
  refreshState,
7878
+ patchPluginInState,
7083
7879
  showToast,
7084
7880
  openManage: openManageView,
7085
7881
  onInstalled,
@@ -7094,6 +7890,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
7094
7890
  setActiveSourceId,
7095
7891
  rows,
7096
7892
  setRows,
7893
+ addedGitSourceIds,
7097
7894
  scrollTopRef,
7098
7895
  }) {
7099
7896
  const [showFilter, setShowFilter] = useState(false);
@@ -7211,7 +8008,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
7211
8008
  }, []);
7212
8009
 
7213
8010
  useAutoMcpTools([
7214
- ...pluginMcpRows.map(row => ({ owner: row.owner, name: row.name, connected: row.conn.enabled === true, revision: JSON.stringify([row.record.installedAt, row.conn]) })),
8011
+ ...pluginMcpRows.map(row => ({ owner: row.owner, name: row.name, connected: row.conn.enabled === true && !row.conn.pending, revision: JSON.stringify([row.record.installedAt, row.conn]) })),
7215
8012
  ...mcps.map(row => ({ owner: "user-mcp", name: row.name, connected: row.enabled === true, revision: JSON.stringify(row) })),
7216
8013
  ], loadGlobalTools);
7217
8014
 
@@ -7282,7 +8079,12 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
7282
8079
  return;
7283
8080
  }
7284
8081
  if (canEdit) await refreshMcps();
7285
- else await refreshState();
8082
+ else if (res?.plugin && patchPluginInState) {
8083
+ patchPluginInState(res.plugin);
8084
+ void refreshState();
8085
+ } else {
8086
+ await refreshState();
8087
+ }
7286
8088
  } catch (err) {
7287
8089
  setOptimisticMcp(prev => { const n = { ...prev }; delete n[key]; return n; });
7288
8090
  showToast("操作失败", cleanError(err), { restart: false });
@@ -8396,7 +9198,6 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8396
9198
  SESSION_STORE.browseSortSnapshots[activeSourceId] = { filter, query, sortBy, names: currentSourceInstalledNames };
8397
9199
  }, [activeSourceId, filter, query, sortBy, currentSourceInstalledNames]);
8398
9200
  const installedNames = useMemo(() => new Set(state.plugins.map((p) => p.name)), [state.plugins]);
8399
- const totalInstalledCount = state.plugins.length;
8400
9201
  const currentSourcePlugins = useMemo(() => (rows && rows[activeSourceId]) || [], [rows, activeSourceId]);
8401
9202
  const totalSourcePluginsCount = currentSourcePlugins.length;
8402
9203
 
@@ -8506,19 +9307,16 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8506
9307
  return () => { alive = false; };
8507
9308
  }, [view]);
8508
9309
 
8509
- useEffect(() => {
8510
- if (!installFor && !addDialog && !confirmRemoveSource && !mcpDialog) return;
8511
- const onKey = (e) => {
8512
- if (e.key === "Escape") {
8513
- if (installFor) setInstallFor(null);
8514
- if (addDialog && !addDialogBusyRef.current) setAddDialog(false);
8515
- if (confirmRemoveSource) setConfirmRemoveSource(null);
8516
- if (mcpDialog) setMcpDialog(false);
8517
- }
8518
- };
8519
- window.addEventListener("keydown", onKey);
8520
- return () => window.removeEventListener("keydown", onKey);
8521
- }, [installFor, addDialog, confirmRemoveSource, mcpDialog]);
9310
+ useDialogEscape(!!(installFor || addDialog || confirmRemoveSource || mcpDialog), () => {
9311
+ if (installFor) setInstallFor(null);
9312
+ if (addDialog && !addDialogBusyRef.current) setAddDialog(false);
9313
+ if (confirmRemoveSource) setConfirmRemoveSource(null);
9314
+ if (mcpDialog) {
9315
+ setMcpDialog(false);
9316
+ setEditMcp(null);
9317
+ setEditMcpOwner(null);
9318
+ }
9319
+ });
8522
9320
 
8523
9321
  const removePlugin = async (pluginName) => {
8524
9322
  try {
@@ -8528,6 +9326,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8528
9326
  showToast("卸载失败", result.error || "卸载未能完成,请稍后重试", { restart: false });
8529
9327
  return;
8530
9328
  }
9329
+ clearMcpToolsCache((k) => k.startsWith(`${pluginName}::`));
8531
9330
  void showApplicationToast(showToast, result, "已卸载插件", "插件副本与技能注册已实时移除并生效。");
8532
9331
  setView({ type: "browse", sourceId: activeSourceId });
8533
9332
  await refreshState();
@@ -8810,7 +9609,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8810
9609
  if (!SESSION_STORE.scrollTops) SESSION_STORE.scrollTops = {};
8811
9610
  SESSION_STORE.scrollTops[activeSourceId] = 0;
8812
9611
  scrollContentToTop();
8813
- } }, `已安装 (${totalInstalledCount})`),
9612
+ } }, "已安装"),
8814
9613
  ),
8815
9614
  ),
8816
9615
  h("div", { style: { position: "relative" } },
@@ -8897,14 +9696,19 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8897
9696
  method: "POST",
8898
9697
  body: JSON.stringify({ enabled }),
8899
9698
  });
8900
- await refreshState();
9699
+ if (res?.ok !== false && res?.plugin && patchPluginInState) {
9700
+ patchPluginInState(res.plugin);
9701
+ void refreshState();
9702
+ } else {
9703
+ await refreshState();
9704
+ }
8901
9705
  return res;
8902
9706
  },
8903
9707
  showToast,
8904
9708
  }),
8905
9709
  !mcpsOpen && view.type === "manage" && h(ManagePage, {
8906
9710
  key: view.pluginName || manageRecord?.name,
8907
- record: manageRecord || null, state, rows, isDark, refreshState, showToast,
9711
+ record: manageRecord || null, state, rows, isDark, refreshState, patchPluginInState, showToast,
8908
9712
  containerRef: detailContainerRef,
8909
9713
  initialTab: view.initialTab, initialConnector: view.initialConnector,
8910
9714
  scrollState: view,
@@ -9073,8 +9877,18 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9073
9877
  initialPhase: addDialog.initialPhase,
9074
9878
  onBusyChange: (v) => { addDialogBusyRef.current = !!v; },
9075
9879
  onCancel: () => { if (!addDialogBusyRef.current) setAddDialog(false); },
9076
- onAdded: async (newSourceId, keepOpen) => {
9880
+ onAdded: async (newSourceId, keepOpen, market) => {
9077
9881
  if (!keepOpen) setAddDialog(false);
9882
+ if (newSourceId && market?.source?.id === newSourceId && Array.isArray(market.plugins)) {
9883
+ addedGitSourceIds.current.add(newSourceId);
9884
+ (SESSION_STORE.checkedCatalogs ||= new Set()).add(newSourceId);
9885
+ setRows((prev) => ({ ...prev, [newSourceId]: market.plugins }));
9886
+ setState((prev) => prev.sources.some((source) => source.id === newSourceId)
9887
+ ? prev : { ...prev, sources: [...prev.sources, market.source] });
9888
+ if (newSourceId !== activeSourceId) setActiveSourceId(newSourceId);
9889
+ void refreshState({ quiet: true });
9890
+ return;
9891
+ }
9078
9892
  await refreshState();
9079
9893
  // The tab list and the rows both come from the server state.
9080
9894
  if (newSourceId) {
@@ -9122,68 +9936,62 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9122
9936
  }),
9123
9937
 
9124
9938
  confirmRemoveSource && h("div", { className: "cpm-dialog", ...backdropDismissProps(() => setConfirmRemoveSource(null)) },
9125
- h("div", { className: "cpm-dialog-box", onClick: (e) => e.stopPropagation() },
9126
- h("div", { className: "cpm-dialog-title" }, `删除插件源「${confirmRemoveSource.name}」`),
9127
- h("div", { className: "cpm-field", style: { fontSize: 13, lineHeight: 1.6, color: "var(--cpm-muted)" } },
9128
- "将从插件市场中移除该源及其分类标签。如需再次使用,可随时通过右上角「+」重新添加。",
9129
- ),
9130
- h("div", { className: "cpm-dialog-actions" },
9131
- h("button", {
9132
- className: "cpm-btn cpm-btn-secondary",
9133
- onClick: () => setConfirmRemoveSource(null),
9134
- }, "取消"),
9135
- h("button", {
9136
- className: "cpm-btn cpm-btn-primary",
9137
- style: { background: "#dc2626", borderColor: "#dc2626", color: "#fff" },
9138
- disabled: !!busy,
9139
- onClick: async () => {
9140
- const toRemove = confirmRemoveSource;
9141
- setConfirmRemoveSource(null);
9142
- setBusy("正在删除插件源…");
9143
- try {
9144
- await api("/sources/" + encodeURIComponent(toRemove.id), { method: "DELETE" });
9145
- showToast("插件源已删除", `已移除分类「${toRemove.name}」`, { restart: false });
9146
- invalidateSourceDetailCache(toRemove.id);
9147
- const currentSources = Array.isArray(SESSION_STORE.state?.sources)
9148
- ? SESSION_STORE.state.sources
9149
- : (Array.isArray(state?.sources) ? state.sources : []);
9150
- const remainingSources = currentSources.filter((s) => s && s.id !== toRemove.id);
9151
- const fallbackSourceId = remainingSources.some((s) => s.id === "anthropic")
9152
- ? "anthropic"
9153
- : (remainingSources.find((s) => s.id !== "local" || hasLocalPlugins) || remainingSources[0])?.id;
9154
- if (SESSION_STORE.activeSourceId === toRemove.id || activeSourceId === toRemove.id) {
9155
- if (fallbackSourceId) {
9156
- setActiveSourceId(fallbackSourceId, SESSION_STORE.sourceFilters?.[fallbackSourceId] || "all");
9157
- } else {
9158
- SESSION_STORE.activeSourceId = "";
9159
- setActiveSourceIdRaw("");
9160
- SESSION_STORE.filter = "all";
9161
- setFilterRaw("all");
9162
- const emptyView = { type: "browse" };
9163
- SESSION_STORE.view = emptyView;
9164
- setViewRaw(emptyView);
9165
- }
9166
- }
9167
- for (const mapKey of ["sourceViews", "scrollTops", "sourceFilters", "browseSortSnapshots"]) {
9168
- if (SESSION_STORE[mapKey]) delete SESSION_STORE[mapKey][toRemove.id];
9169
- }
9170
- if (SESSION_STORE.checkedCatalogs) SESSION_STORE.checkedCatalogs.delete(toRemove.id);
9171
- savedTabScrolls.delete(toRemove.id);
9172
- if (tabRefs?.current) delete tabRefs.current[toRemove.id];
9173
- setRows((prev) => omitSourceKey(prev, toRemove.id));
9174
- syncCachedStore("rows", STORAGE_KEY_ROWS, rows, (prev) => omitSourceKey(prev, toRemove.id));
9175
- setState((prev) => stripDeletedSource(prev, toRemove.id));
9176
- syncCachedStore("state", STORAGE_KEY_STATE, state, (prev) => stripDeletedSource(prev, toRemove.id));
9177
- try { await refreshState(); } catch {}
9178
- } catch (e) {
9179
- showToast("删除失败", cleanError(e), { restart: false });
9180
- } finally {
9181
- setBusy(null);
9939
+ h(ConfirmDialogBox, {
9940
+ titleId: "cpm-confirm-remove-source-title",
9941
+ title: `删除插件源「${confirmRemoveSource.name}」`,
9942
+ description: "将从插件市场中移除该源及其分类标签。如需再次使用,可随时通过右上角「+」重新添加。",
9943
+ confirmLabel: "确认删除",
9944
+ confirmBusyLabel: "删除中…",
9945
+ confirmStyle: { background: "#dc2626", borderColor: "#dc2626", color: "#fff" },
9946
+ busy: !!busy,
9947
+ onCancel: () => setConfirmRemoveSource(null),
9948
+ onConfirm: async () => {
9949
+ const toRemove = confirmRemoveSource;
9950
+ setConfirmRemoveSource(null);
9951
+ setBusy("正在删除插件源…");
9952
+ try {
9953
+ await api("/sources/" + encodeURIComponent(toRemove.id), { method: "DELETE" });
9954
+ showToast("插件源已删除", `已移除分类「${toRemove.name}」`, { restart: false });
9955
+ invalidateSourceDetailCache(toRemove.id);
9956
+ const currentSources = Array.isArray(SESSION_STORE.state?.sources)
9957
+ ? SESSION_STORE.state.sources
9958
+ : (Array.isArray(state?.sources) ? state.sources : []);
9959
+ const remainingSources = currentSources.filter((s) => s && s.id !== toRemove.id);
9960
+ const fallbackSourceId = remainingSources.some((s) => s.id === "anthropic")
9961
+ ? "anthropic"
9962
+ : (remainingSources.find((s) => s.id !== "local" || hasLocalPlugins) || remainingSources[0])?.id;
9963
+ if (SESSION_STORE.activeSourceId === toRemove.id || activeSourceId === toRemove.id) {
9964
+ if (fallbackSourceId) {
9965
+ setActiveSourceId(fallbackSourceId, SESSION_STORE.sourceFilters?.[fallbackSourceId] || "all");
9966
+ } else {
9967
+ SESSION_STORE.activeSourceId = "";
9968
+ setActiveSourceIdRaw("");
9969
+ SESSION_STORE.filter = "all";
9970
+ setFilterRaw("all");
9971
+ const emptyView = { type: "browse" };
9972
+ SESSION_STORE.view = emptyView;
9973
+ setViewRaw(emptyView);
9182
9974
  }
9183
- },
9184
- }, busy ? "删除中…" : "确认删除"),
9185
- ),
9186
- ),
9975
+ }
9976
+ for (const mapKey of ["sourceViews", "scrollTops", "sourceFilters", "browseSortSnapshots"]) {
9977
+ if (SESSION_STORE[mapKey]) delete SESSION_STORE[mapKey][toRemove.id];
9978
+ }
9979
+ if (SESSION_STORE.checkedCatalogs) SESSION_STORE.checkedCatalogs.delete(toRemove.id);
9980
+ addedGitSourceIds.current.delete(toRemove.id);
9981
+ savedTabScrolls.delete(toRemove.id);
9982
+ if (tabRefs?.current) delete tabRefs.current[toRemove.id];
9983
+ setRows((prev) => omitSourceKey(prev, toRemove.id));
9984
+ syncCachedStore("rows", STORAGE_KEY_ROWS, rows, (prev) => omitSourceKey(prev, toRemove.id));
9985
+ setState((prev) => stripDeletedSource(prev, toRemove.id));
9986
+ syncCachedStore("state", STORAGE_KEY_STATE, state, (prev) => stripDeletedSource(prev, toRemove.id));
9987
+ try { await refreshState(); } catch {}
9988
+ } catch (e) {
9989
+ showToast("删除失败", cleanError(e), { restart: false });
9990
+ } finally {
9991
+ setBusy(null);
9992
+ }
9993
+ },
9994
+ }),
9187
9995
  ),
9188
9996
 
9189
9997
  // ────────────────────────────── Modern Floating Drag Overlay (Zero Container Clipping) ──────────────────────────────
@@ -9220,15 +10028,82 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9220
10028
  };
9221
10029
  }
9222
10030
 
10031
+ function useDialogEscape(open, onDismiss, capture = false) {
10032
+ const onDismissRef = useRef(onDismiss);
10033
+ onDismissRef.current = onDismiss;
10034
+ useEffect(() => {
10035
+ if (!open) return undefined;
10036
+ const onKey = (e) => {
10037
+ if (e.key !== "Escape") return;
10038
+ if (capture) {
10039
+ e.stopPropagation();
10040
+ e.preventDefault();
10041
+ }
10042
+ onDismissRef.current?.(e);
10043
+ };
10044
+ window.addEventListener("keydown", onKey, capture);
10045
+ return () => window.removeEventListener("keydown", onKey, capture);
10046
+ }, [open, capture]);
10047
+ }
10048
+
10049
+ function ConfirmDialogBox({
10050
+ titleId,
10051
+ title,
10052
+ description,
10053
+ descriptionStyle,
10054
+ cancelLabel = "取消",
10055
+ confirmLabel,
10056
+ confirmBusyLabel,
10057
+ confirmStyle,
10058
+ busy = false,
10059
+ cancelDisabled = false,
10060
+ onCancel,
10061
+ onConfirm,
10062
+ }) {
10063
+ return h("div", {
10064
+ className: "cpm-dialog-box",
10065
+ role: "dialog",
10066
+ "aria-modal": "true",
10067
+ "aria-labelledby": titleId,
10068
+ onClick: (e) => e.stopPropagation(),
10069
+ },
10070
+ h("div", { id: titleId, className: "cpm-dialog-title" }, title),
10071
+ description && h("div", {
10072
+ className: "cpm-field",
10073
+ style: descriptionStyle || { fontSize: 13, lineHeight: 1.6, color: "var(--cpm-muted)" },
10074
+ }, description),
10075
+ h("div", { className: "cpm-dialog-actions" },
10076
+ h("button", {
10077
+ className: "cpm-btn cpm-btn-secondary",
10078
+ disabled: !!cancelDisabled,
10079
+ onClick: onCancel,
10080
+ }, cancelLabel),
10081
+ h("button", {
10082
+ className: "cpm-btn cpm-btn-primary",
10083
+ style: confirmStyle,
10084
+ disabled: !!busy,
10085
+ onClick: onConfirm,
10086
+ }, busy && confirmBusyLabel ? confirmBusyLabel : confirmLabel),
10087
+ ),
10088
+ );
10089
+ }
10090
+
9223
10091
  // ────────────────────────────── Modern Install Dialog ──────────────────────────────
9224
10092
  function InstallDialog({ plugin, isDark, onCancel, onConfirm }) {
9225
10093
  const [busy, setBusy] = useState(false);
10094
+ const titleId = "cpm-install-dialog-title";
9226
10095
  return h("div", { className: "cpm-dialog", ...backdropDismissProps(onCancel) },
9227
- h("div", { className: "cpm-dialog-box cpm-install-dialog", onClick: (e) => e.stopPropagation() },
10096
+ h("div", {
10097
+ className: "cpm-dialog-box cpm-install-dialog",
10098
+ role: "dialog",
10099
+ "aria-modal": "true",
10100
+ "aria-labelledby": titleId,
10101
+ onClick: (e) => e.stopPropagation(),
10102
+ },
9228
10103
  h("div", { className: "cpm-install-dialog-header" },
9229
10104
  h(PluginIcon, { plugin, isDark }),
9230
10105
  h("div", { className: "cpm-install-dialog-header-info" },
9231
- h("div", { className: "cpm-install-dialog-title" }, `安装 ${plugin.displayName || plugin.name}`),
10106
+ h("div", { id: titleId, className: "cpm-install-dialog-title" }, `安装 ${plugin.displayName || plugin.name}`),
9232
10107
  plugin.author && h("div", { className: "cpm-install-dialog-sub" }, `by ${plugin.author}`),
9233
10108
  ),
9234
10109
  ),
@@ -9808,65 +10683,6 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9808
10683
  return s.replace(/^https?:\/\//i, "").replace(/\.git$/i, "");
9809
10684
  };
9810
10685
 
9811
- const computeSmartSuggestedName = (rawInput, serverSuggested) => {
9812
- const s = String(rawInput || "").trim().replace(/^['"]|['"]$/g, "");
9813
- let owner = "";
9814
- let repo = "";
9815
- const sshMatch = s.match(/^git@[^:]+:([^/]+)\/(.+?)(\.git)?$/);
9816
- if (sshMatch) {
9817
- owner = sshMatch[1];
9818
- repo = sshMatch[2];
9819
- } else {
9820
- const httpMatch = s.match(/^https?:\/\/[^/]+\/([^/]+)\/([^/]+?)(\.git)?$/i);
9821
- if (httpMatch) {
9822
- owner = httpMatch[1];
9823
- repo = httpMatch[2];
9824
- } else {
9825
- const shortMatch = s.match(/^([a-zA-Z0-9._-]+)\/([a-zA-Z0-9._-]+?)(\.git)?$/);
9826
- if (shortMatch) {
9827
- owner = shortMatch[1];
9828
- repo = shortMatch[2];
9829
- } else {
9830
- repo = s.replace(/^https?:\/\//i, "").replace(/\.git$/i, "").split("/").pop() || "";
9831
- }
9832
- }
9833
- }
9834
-
9835
- const ownerLower = (owner || "").toLowerCase();
9836
- const repoLower = (repo || "").toLowerCase();
9837
-
9838
- if (repoLower === "claude-plugins-official") return "Anthropic";
9839
- if (repoLower === "claude-plugins-community") return "Community";
9840
-
9841
- const genericWords = new Set([
9842
- "skills", "skill", "plugins", "plugin", "agents", "agent", "tools", "tool",
9843
- "marketplace", "hub", "claude-skills", "claude-plugins", "claude-agents",
9844
- "dsh-plugins", "extensions", "packages", "repo", "repository", "custom"
9845
- ]);
9846
-
9847
- if (serverSuggested && !genericWords.has(serverSuggested.toLowerCase())) {
9848
- return serverSuggested;
9849
- }
9850
-
9851
- if (genericWords.has(repoLower) && owner) {
9852
- return owner.charAt(0).toUpperCase() + owner.slice(1);
9853
- }
9854
-
9855
- const simplified = repo
9856
- .replace(/^(claude|dsh|anthropic)[-_]?(plugins?)?[-_]?/i, "")
9857
- .replace(/[-_]?(plugins?|skills?|agents?|official|marketplace)$/i, "");
9858
-
9859
- const clean = simplified || repo;
9860
- if (genericWords.has(clean.toLowerCase()) && owner) {
9861
- return owner.charAt(0).toUpperCase() + owner.slice(1);
9862
- }
9863
-
9864
- if (clean) {
9865
- return clean.charAt(0).toUpperCase() + clean.slice(1);
9866
- }
9867
- return serverSuggested || "Custom";
9868
- };
9869
-
9870
10686
  const cleanError = (err) => {
9871
10687
  if (!err) return "操作失败";
9872
10688
  let msg = String(err.message || err).replace(/^Error:\s*/i, "").trim();
@@ -9890,9 +10706,8 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9890
10706
  const body = await api("/sources/ensure", { method: "POST", body: JSON.stringify({ url: raw }) });
9891
10707
  if (unmountedRef.current) return;
9892
10708
  const finalRepoLabel = body.repoLabel || extractRepoLabel(raw);
9893
- const finalSuggested = computeSmartSuggestedName(raw, body.suggestedName);
9894
10709
  setRepoLabel(finalRepoLabel);
9895
- setSuggested(finalSuggested);
10710
+ setSuggested(body.suggestedName || finalRepoLabel.split("/").pop() || "Custom");
9896
10711
  setCustomName("");
9897
10712
  setMode("suggest");
9898
10713
  setNormalizedUrl(body.normalizedUrl || raw);
@@ -9922,7 +10737,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9922
10737
  if (unmountedRef.current) return;
9923
10738
  const count = res.pluginCount !== undefined ? res.pluginCount : pluginCount;
9924
10739
  showToast("插件源已添加", `分类「${name}」已创建,成功导入 ${count} 个插件`, { restart: false });
9925
- await onAdded(res.source?.id);
10740
+ await onAdded(res.source?.id, false, res);
9926
10741
  } catch (e) {
9927
10742
  if (unmountedRef.current) return;
9928
10743
  showToast("添加源失败", cleanError(e), { restart: false });
@@ -9931,6 +10746,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9931
10746
  }
9932
10747
  };
9933
10748
 
10749
+ const urlBusyLabel = isLocalPath(url) ? "正在解析…" : "正在安装…";
9934
10750
  const inlineBusyProgress = () => busy && h("div", { className: "cpm-upload-inline-progress", key: "imp-prog" },
9935
10751
  h("progress", { className: "cpm-upload-progress", "aria-label": "正在导入插件" }),
9936
10752
  h("div", { className: "cpm-upload-status", role: "status", "aria-live": "polite", style: { marginTop: 0 } }, "正在导入文件,请勿关闭弹窗…"),
@@ -10108,7 +10924,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10108
10924
  ),
10109
10925
  h("div", { className: "cpm-dialog-actions", key: "a" },
10110
10926
  h("button", { className: "cpm-btn cpm-btn-secondary", disabled: busy, onClick: onCancel }, "取消"),
10111
- h("button", { className: "cpm-btn cpm-btn-primary", disabled: busy || !url.trim(), onClick: ensure }, busy ? "正在解析…" : "下一步"),
10927
+ h("button", { className: "cpm-btn cpm-btn-primary", disabled: busy || !url.trim(), onClick: ensure }, busy ? urlBusyLabel : "下一步"),
10112
10928
  ),
10113
10929
  ],
10114
10930
  phase === "local-preview" && localPreview && localPreview.kind === "marketplace" && [
@@ -10149,7 +10965,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10149
10965
  value: "suggest",
10150
10966
  selected: mode === "suggest",
10151
10967
  onSelect: () => setMode("suggest"),
10152
- title: "使用系统建议简化名",
10968
+ title: "使用推荐市场名",
10153
10969
  desc: [
10154
10970
  "分类标签名:",
10155
10971
  // Only the market's own name: falling back to the local
@@ -10384,7 +11200,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10384
11200
  value: "suggest",
10385
11201
  selected: mode === "suggest",
10386
11202
  onSelect: () => setMode("suggest"),
10387
- title: "使用系统建议简化名",
11203
+ title: "使用推荐市场名",
10388
11204
  desc: ["分类标签名:", h("span", { className: "cpm-tag-preview", key: "tag" }, suggested)],
10389
11205
  }),
10390
11206
  renderChoiceCard({
@@ -10415,7 +11231,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10415
11231
  ),
10416
11232
  h("div", { className: "cpm-dialog-actions", key: "a" },
10417
11233
  h("button", { className: "cpm-btn cpm-btn-secondary", type: "button", disabled: busy, onClick: () => setPhase("url") }, "上一步"),
10418
- h("button", { className: "cpm-btn cpm-btn-primary", disabled: busy || (mode === "custom" && !customName.trim()), onClick: confirm }, busy ? "正在保存…" : "确认添加"),
11234
+ h("button", { className: "cpm-btn cpm-btn-primary", disabled: busy || (mode === "custom" && !customName.trim()), onClick: confirm }, busy ? "正在安装…" : "确认添加"),
10419
11235
  ),
10420
11236
  ],
10421
11237
  ),
@@ -10436,8 +11252,12 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10436
11252
  oauthScope: initial.oauthScope || "",
10437
11253
  command: initial.command || "",
10438
11254
  args: Array.isArray(initial.args) ? JSON.stringify(initial.args) : (initial.args || ""),
10439
- headersList: Object.entries(initial.headers || {}).map(([k, v], i) => makeKvRow("header", `hi_${i}`, k, String(v))),
10440
- envList: Object.entries(initial.env || {}).map(([k, v], i) => makeKvRow("env", `ei_${i}`, k, String(v))),
11255
+ headersList: Object.entries(initial.headers || {})
11256
+ .filter(([, v]) => !hasUnresolvedVarPlaceholder(String(v ?? "")))
11257
+ .map(([k, v], i) => makeKvRow("header", `hi_${i}`, k, String(v))),
11258
+ envList: Object.entries(initial.env || {})
11259
+ .filter(([, v]) => !hasUnresolvedVarPlaceholder(String(v ?? "")))
11260
+ .map(([k, v], i) => makeKvRow("env", `ei_${i}`, k, String(v))),
10441
11261
  } : { name: "", transport: "stdio", url: "", oauth: "none", oauthClientId: "", oauthClientSecret: "", oauthHasClientSecret: false, oauthCallbackPort: "", oauthScope: "", command: "", args: "", headersList: [], envList: [] });
10442
11262
  const [oauthBaseline, setOauthBaseline] = useState(() => initial ? {
10443
11263
  name: initial.name || "",
@@ -10456,17 +11276,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10456
11276
  // The confirmation renders inside this dialog, so it must handle Escape
10457
11277
  // first: the outer handler would otherwise close the whole editor and
10458
11278
  // discard the form behind it.
10459
- useEffect(() => {
10460
- if (!confirmDelete) return;
10461
- const onKey = (e) => {
10462
- if (e.key !== "Escape") return;
10463
- e.stopPropagation();
10464
- e.preventDefault();
10465
- setConfirmDelete(false);
10466
- };
10467
- window.addEventListener("keydown", onKey, true);
10468
- return () => window.removeEventListener("keydown", onKey, true);
10469
- }, [confirmDelete]);
11279
+ useDialogEscape(confirmDelete, () => setConfirmDelete(false), true);
10470
11280
  const upd = (patch) => {
10471
11281
  setForm((prev) => ({ ...prev, ...patch }));
10472
11282
  setConnState((prev) => prev.status === "untested" ? prev : { status: "untested", statusMessage: "", lastResult: null });
@@ -10657,7 +11467,9 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10657
11467
  showToast("保存失败", res.error || "配置校验未通过,请检查填写内容", { restart: false });
10658
11468
  return;
10659
11469
  }
11470
+ clearMcpToolsCache(owner ? `${owner}::${data.name}` : `user-mcp::${data.name}`);
10660
11471
  if (initial && data.previousName) {
11472
+ clearMcpToolsCache(`user-mcp::${data.previousName}`);
10661
11473
  void showApplicationToast(showToast, res, "MCP 已重命名", `「${data.previousName}」已改名为「${data.name}」`);
10662
11474
  } else {
10663
11475
  void showApplicationToast(showToast, res, initial ? "MCP 已更新" : "MCP 已添加", `「${data.name}」已${initial ? "更新" : "注册为可用 MCP 服务"}`);
@@ -10674,11 +11486,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10674
11486
  setDeleting(true);
10675
11487
  try {
10676
11488
  const result = await api(`/mcps/${encodeURIComponent(initial.name)}`, { method: "DELETE" });
10677
- const cacheKey = `user-mcp::${initial.name}`;
10678
- if (GLOBAL_MCP_TOOLS_CACHE[cacheKey]) {
10679
- delete GLOBAL_MCP_TOOLS_CACHE[cacheKey];
10680
- try { localStorage.setItem("cpm_mcp_tools_cache_v1", JSON.stringify(GLOBAL_MCP_TOOLS_CACHE)); } catch {}
10681
- }
11489
+ clearMcpToolsCache(`user-mcp::${initial.name}`);
10682
11490
  setConfirmDelete(false);
10683
11491
  void showApplicationToast(showToast, result, "MCP 已删除", `「${initial.name}」已从服务器列表移除`);
10684
11492
  await onSaved();
@@ -10689,7 +11497,13 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10689
11497
  };
10690
11498
 
10691
11499
  return h("div", { className: "cpm-dialog" },
10692
- h("div", { className: "cpm-mcp-modal", onClick: (e) => e.stopPropagation() },
11500
+ h("div", {
11501
+ className: "cpm-mcp-modal",
11502
+ role: "dialog",
11503
+ "aria-modal": "true",
11504
+ "aria-label": initial?.name ? `编辑 MCP「${initial.name}」` : "添加 MCP",
11505
+ onClick: (e) => e.stopPropagation(),
11506
+ },
10693
11507
  h("button", { type: "button", className: "cpm-mcp-close-top", "aria-label": "关闭", onClick: onCancel }, h(IconClose, { size: 14 })),
10694
11508
  h("div", { className: "cpm-mcp-body" },
10695
11509
  h("div", { className: "cpm-mcp-row" },
@@ -10850,24 +11664,17 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10850
11664
  ),
10851
11665
  ),
10852
11666
  confirmDelete && h("div", { className: "cpm-dialog", ...backdropDismissProps(() => setConfirmDelete(false)) },
10853
- h("div", { className: "cpm-dialog-box", onClick: (e) => e.stopPropagation() },
10854
- h("div", { className: "cpm-dialog-title" }, `删除 MCP「${initial.name}」`),
10855
- h("div", { className: "cpm-field", style: { fontSize: 13, lineHeight: 1.6, color: "var(--cpm-muted)" } },
10856
- "将移除它的连接配置、已保存的授权和工具开关记录。如需再次使用,可在「添加」里重新配置。",
10857
- ),
10858
- h("div", { className: "cpm-dialog-actions" },
10859
- h("button", {
10860
- className: "cpm-btn cpm-btn-secondary",
10861
- onClick: () => setConfirmDelete(false),
10862
- }, "取消"),
10863
- h("button", {
10864
- className: "cpm-btn cpm-btn-primary",
10865
- style: { background: "#dc2626", borderColor: "#dc2626", color: "#fff" },
10866
- disabled: deleting,
10867
- onClick: removeMcp,
10868
- }, deleting ? "删除中…" : "确认删除"),
10869
- ),
10870
- ),
11667
+ h(ConfirmDialogBox, {
11668
+ titleId: "cpm-confirm-delete-mcp-title",
11669
+ title: `删除 MCP「${initial.name}」`,
11670
+ description: "将移除它的连接配置、已保存的授权和工具开关记录。如需再次使用,可在「添加」里重新配置。",
11671
+ confirmLabel: "确认删除",
11672
+ confirmBusyLabel: "删除中…",
11673
+ confirmStyle: { background: "#dc2626", borderColor: "#dc2626", color: "#fff" },
11674
+ busy: deleting,
11675
+ onCancel: () => setConfirmDelete(false),
11676
+ onConfirm: removeMcp,
11677
+ }),
10871
11678
  ),
10872
11679
  );
10873
11680
  }
@@ -10997,6 +11804,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10997
11804
  const [optimisticEnabled, setOptimisticEnabled] = useState(null);
10998
11805
  const { detailRef, maskClass: detailMaskClass, updateMask: updateDetailMask } = useDetailScrollMask(plugin?.name, containerRef, plugin, scrollState);
10999
11806
  useEffect(() => { setOptimisticEnabled(null); }, [plugin?.name]);
11807
+ useDialogEscape(confirmRemove, () => { if (!busy) setConfirmRemove(false); });
11000
11808
 
11001
11809
  if (!plugin) return null;
11002
11810
  const dark = typeof isDark === "boolean" ? isDark : (typeof isDarkMode === "function" ? isDarkMode() : false);
@@ -11219,28 +12027,28 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
11219
12027
  ),
11220
12028
 
11221
12029
  confirmRemove && h("div", { className: "cpm-dialog", ...backdropDismissProps(() => { if (!busy) setConfirmRemove(false); }) },
11222
- h("div", { className: "cpm-dialog-box", onClick: (e) => e.stopPropagation() },
11223
- h("div", { className: "cpm-dialog-title" }, `卸载 ${plugin.displayName || plugin.name}?`),
11224
- h("div", { className: "cpm-field", style: { color: "var(--cpm-muted)", fontSize: "13px", lineHeight: 1.5, marginBottom: "20px" } }, "将删除插件副本、技能与子代理注册及 MCP 配置。"),
11225
- h("div", { className: "cpm-dialog-actions" },
11226
- h("button", { className: "cpm-btn cpm-btn-secondary", disabled: busy, onClick: () => { if (!busy) setConfirmRemove(false); } }, "取消"),
11227
- h("button", {
11228
- className: "cpm-btn cpm-btn-primary",
11229
- style: { background: "#ef4444", borderColor: "#ef4444", color: "#ffffff" },
11230
- disabled: busy,
11231
- onClick: async () => {
11232
- if (busy) return;
11233
- setBusy(true);
11234
- try {
11235
- await onRemove();
11236
- } finally {
11237
- setBusy(false);
11238
- setConfirmRemove(false);
11239
- }
11240
- },
11241
- }, busy ? "卸载中…" : "卸载"),
11242
- ),
11243
- ),
12030
+ h(ConfirmDialogBox, {
12031
+ titleId: "cpm-confirm-remove-detail-title",
12032
+ title: `卸载 ${plugin.displayName || plugin.name}?`,
12033
+ description: "将删除插件副本、技能与子代理注册及 MCP 配置。",
12034
+ descriptionStyle: { color: "var(--cpm-muted)", fontSize: "13px", lineHeight: 1.5, marginBottom: "20px" },
12035
+ confirmLabel: "卸载",
12036
+ confirmBusyLabel: "卸载中…",
12037
+ confirmStyle: { background: "#ef4444", borderColor: "#ef4444", color: "#ffffff" },
12038
+ busy,
12039
+ cancelDisabled: busy,
12040
+ onCancel: () => { if (!busy) setConfirmRemove(false); },
12041
+ onConfirm: async () => {
12042
+ if (busy) return;
12043
+ setBusy(true);
12044
+ try {
12045
+ await onRemove();
12046
+ } finally {
12047
+ setBusy(false);
12048
+ setConfirmRemove(false);
12049
+ }
12050
+ },
12051
+ }),
11244
12052
  )
11245
12053
  );
11246
12054
  }
@@ -11262,6 +12070,20 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
11262
12070
  } catch {}
11263
12071
  }
11264
12072
 
12073
+ function clearMcpToolsCache(matcher) {
12074
+ const matchFn = typeof matcher === "function" ? matcher : (k) => k === matcher;
12075
+ let changed = false;
12076
+ for (const k of Object.keys(GLOBAL_MCP_TOOLS_CACHE)) {
12077
+ if (matchFn(k)) {
12078
+ delete GLOBAL_MCP_TOOLS_CACHE[k];
12079
+ changed = true;
12080
+ }
12081
+ }
12082
+ if (changed) {
12083
+ try { localStorage.setItem("cpm_mcp_tools_cache_v1", JSON.stringify(GLOBAL_MCP_TOOLS_CACHE)); } catch {}
12084
+ }
12085
+ }
12086
+
11265
12087
  function useAutoMcpTools(servers, loadTools) {
11266
12088
  const attempted = useRef(new Map());
11267
12089
  useEffect(() => {
@@ -11444,7 +12266,21 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
11444
12266
  return props.record ? h(ManagePageContent, props) : null;
11445
12267
  }
11446
12268
 
11447
- function ManagePageContent({ record, state, rows, isDark, refreshState, showToast, onBack, onClose, initialTab, initialConnector, containerRef, scrollState }) {
12269
+ /** Return the first non-empty author name that is not an unknown placeholder. */
12270
+ function resolveKnownAuthor(...candidates) {
12271
+ for (const candidate of candidates) {
12272
+ let raw = "";
12273
+ if (typeof candidate === "string") raw = candidate;
12274
+ else if (candidate && typeof candidate === "object" && typeof candidate.name === "string") raw = candidate.name;
12275
+ const trimmed = raw.trim();
12276
+ if (!trimmed) continue;
12277
+ if (trimmed === "未知" || trimmed.toLowerCase() === "unknown") continue;
12278
+ return trimmed;
12279
+ }
12280
+ return "";
12281
+ }
12282
+
12283
+ function ManagePageContent({ record, state, rows, isDark, refreshState, patchPluginInState, showToast, onBack, onClose, initialTab, initialConnector, containerRef, scrollState }) {
11448
12284
  const dark = typeof isDark === "boolean" ? isDark : (typeof isDarkMode === "function" ? isDarkMode() : false);
11449
12285
  const [tab, setTabRaw] = useState(scrollState?.manageTab || initialTab || "skills");
11450
12286
  const setTab = (next) => { if (scrollState) scrollState.manageTab = next; setTabRaw(next); };
@@ -11550,11 +12386,18 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
11550
12386
  args: parsedArgs, env: envMap,
11551
12387
  };
11552
12388
  };
11553
- const persistAuthDialog = (payload = buildAuthPayload()) =>
11554
- api(`/plugins/${encodeURIComponent(record.name)}/connectors/${encodeURIComponent(authDialog.connectorName)}/auth`, {
12389
+ const persistAuthDialog = async (payload = buildAuthPayload()) => {
12390
+ const connName = authDialog.connectorName;
12391
+ const res = await api(`/plugins/${encodeURIComponent(record.name)}/connectors/${encodeURIComponent(connName)}/auth`, {
11555
12392
  method: "POST",
11556
12393
  body: JSON.stringify(payload),
11557
12394
  });
12395
+ if (res?.ok !== false && connName) {
12396
+ clearMcpToolsCache(`${record.name}::${connName}`);
12397
+ if (res?.plugin && patchPluginInState) patchPluginInState(res.plugin);
12398
+ }
12399
+ return res;
12400
+ };
11558
12401
  const setAuthError = (message) => setAuthDialog((prev) => prev ? {
11559
12402
  ...prev, testing: false, status: "error", statusMessage: message,
11560
12403
  lastResult: { ok: false, message, status: 500, server: prev.connectorName, transport: prev.transport, endpoint: prev.url, errorDetails: message },
@@ -11646,7 +12489,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
11646
12489
  return;
11647
12490
  }
11648
12491
  await refreshState();
11649
- if (connName) await loadConnectorTools(connName);
12492
+ if (connName) await loadConnectorTools(connName, true);
11650
12493
  if (typeof showApplicationToast === "function") {
11651
12494
  void showApplicationToast(showToast, saved, "配置成功", `已成功保存 ${connName} 认证信息并注册为可用 MCP 服务`);
11652
12495
  }
@@ -11691,7 +12534,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
11691
12534
 
11692
12535
  const autoLoadConnectorTools = useCallback((_owner, name) => loadConnectorTools(name), [loadConnectorTools]);
11693
12536
  useAutoMcpTools((record.connectors || []).map(connector => ({
11694
- owner: record.name, name: connector.name, connected: connector.enabled === true,
12537
+ owner: record.name, name: connector.name, connected: connector.enabled === true && !connector.pending,
11695
12538
  revision: JSON.stringify([record.installedAt, connector]),
11696
12539
  })), autoLoadConnectorTools);
11697
12540
 
@@ -11850,6 +12693,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
11850
12693
  }, []);
11851
12694
 
11852
12695
  const source = state.sources.find((s) => s.id === record.sourceId);
12696
+ const authorName = resolveKnownAuthor(record?.author, marketPlugin?.author, marketPlugin?.detail?.author);
11853
12697
  const skills = (Array.isArray(record.skills) && record.skills.length > 0)
11854
12698
  ? record.skills
11855
12699
  : (marketPlugin?.detail?.skills && Array.isArray(marketPlugin.detail.skills) && marketPlugin.detail.skills.length > 0)
@@ -11896,6 +12740,15 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
11896
12740
  const serverEnabled = record.enabled !== false;
11897
12741
  const pluginEnabled = optimisticEnabled !== null ? optimisticEnabled : serverEnabled;
11898
12742
 
12743
+ const applyToggleState = async (result) => {
12744
+ if (result?.plugin && patchPluginInState) {
12745
+ patchPluginInState(result.plugin);
12746
+ void refreshState();
12747
+ } else {
12748
+ await refreshState();
12749
+ }
12750
+ };
12751
+
11899
12752
  const toggle = async () => {
11900
12753
  if (toggling || updating || busy || togglingConn) return;
11901
12754
  const next = !serverEnabled;
@@ -11912,7 +12765,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
11912
12765
  showToast("操作失败", result.error || "插件状态已变更,请刷新后重试", { restart: false });
11913
12766
  return;
11914
12767
  }
11915
- await refreshState();
12768
+ await applyToggleState(result);
11916
12769
  void showApplicationToast(showToast, result, next ? "已启用插件" : "已禁用插件", "插件状态已实时更新并生效。");
11917
12770
  } catch (e) {
11918
12771
  setOptimisticEnabled(null);
@@ -11939,7 +12792,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
11939
12792
  showToast("操作失败", result.error || "请检查 MCP 配置后重试", { restart: false });
11940
12793
  return;
11941
12794
  }
11942
- await refreshState();
12795
+ await applyToggleState(result);
11943
12796
  void showApplicationToast(showToast, result, nextConnected ? "已连接 Connector" : "已断开 Connector", `MCP 服务 ${connectorName} 配置已实时更新。`);
11944
12797
  } catch (e) {
11945
12798
  setOptimisticConn((prev) => { const n = { ...prev }; delete n[connectorName]; return n; });
@@ -11960,6 +12813,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
11960
12813
  showToast("更新失败", result.error || "更新未能完成,请刷新后重试", { restart: false });
11961
12814
  return;
11962
12815
  }
12816
+ clearMcpToolsCache((k) => k.startsWith(`${record.name}::`));
11963
12817
  await refreshState();
11964
12818
  void showApplicationToast(showToast, result, "更新完成", `${(result.skills || []).length} 个技能已实时重新就绪并生效。`);
11965
12819
  } catch (e) {
@@ -11979,14 +12833,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
11979
12833
  showToast("卸载失败", result.error || "卸载未能完成,请稍后重试", { restart: false });
11980
12834
  return;
11981
12835
  }
11982
- for (const k of Object.keys(GLOBAL_MCP_TOOLS_CACHE)) {
11983
- if (k.startsWith(`${record.name}::`)) {
11984
- delete GLOBAL_MCP_TOOLS_CACHE[k];
11985
- }
11986
- }
11987
- try {
11988
- localStorage.setItem("cpm_mcp_tools_cache_v1", JSON.stringify(GLOBAL_MCP_TOOLS_CACHE));
11989
- } catch {}
12836
+ clearMcpToolsCache((k) => k.startsWith(`${record.name}::`));
11990
12837
  await refreshState();
11991
12838
  void showApplicationToast(showToast, result, "已卸载插件", "插件副本与技能注册已实时移除并生效。");
11992
12839
  onClose();
@@ -12116,17 +12963,10 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
12116
12963
  openAuthDialog(initialConnector, found);
12117
12964
  }, [record, connectors, initialConnector]);
12118
12965
 
12119
- useEffect(() => {
12120
- if (!authDialog && !confirmRemove) return;
12121
- const onKey = (e) => {
12122
- if (e.key === "Escape") {
12123
- if (authDialog) closeAuthDialog();
12124
- if (confirmRemove && !busy) setConfirmRemove(false);
12125
- }
12126
- };
12127
- window.addEventListener("keydown", onKey);
12128
- return () => window.removeEventListener("keydown", onKey);
12129
- }, [authDialog, confirmRemove, busy]);
12966
+ useDialogEscape(!!(authDialog || confirmRemove), () => {
12967
+ if (authDialog) closeAuthDialog();
12968
+ if (confirmRemove && !busy) setConfirmRemove(false);
12969
+ });
12130
12970
 
12131
12971
  return h(React.Fragment, null,
12132
12972
  h("div", {
@@ -12146,12 +12986,12 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
12146
12986
  ...marketPlugin,
12147
12987
  ...record,
12148
12988
  icons: (record?.icons && (record.icons.light?.length || record.icons.dark?.length)) ? record.icons : marketPlugin.icons,
12149
- author: record?.author || marketPlugin.author,
12989
+ author: authorName || undefined,
12150
12990
  homepage: record?.homepage || marketPlugin.homepage,
12151
12991
  description: record?.description || marketPlugin.description,
12152
12992
  displayName: record?.displayName || marketPlugin.displayName,
12153
12993
  source: record?.source || marketPlugin.source,
12154
- } : record,
12994
+ } : { ...record, author: authorName || undefined },
12155
12995
  isDark: dark,
12156
12996
  eager: true,
12157
12997
  }),
@@ -12175,23 +13015,23 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
12175
13015
  }),
12176
13016
  ),
12177
13017
 
12178
- h("div", { className: "cpm-meta" },
13018
+ h("dl", { className: "cpm-meta" },
12179
13019
  h("div", null,
12180
- h("span", { className: "k" }, "Source"),
12181
- h("span", { className: "v" },
13020
+ h("dt", { className: "k" }, "Source"),
13021
+ h("dd", { className: "v" },
12182
13022
  h("a", { href: source ? source.url : "#", target: "_blank", rel: "noreferrer" },
12183
13023
  `Marketplace (${source ? source.name : record.sourceId})`,
12184
13024
  ),
12185
13025
  ),
12186
13026
  ),
12187
13027
  h("div", null,
12188
- h("span", { className: "k" }, "Version"),
12189
- h("span", { className: "v" }, record.version || "1.0.0"),
12190
- ),
12191
- h("div", null,
12192
- h("span", { className: "k" }, "Author"),
12193
- h("span", { className: "v" }, record.author || "未知"),
13028
+ h("dt", { className: "k" }, "Version"),
13029
+ h("dd", { className: "v" }, record.version || "1.0.0"),
12194
13030
  ),
13031
+ authorName ? h("div", null,
13032
+ h("dt", { className: "k" }, "Author"),
13033
+ h("dd", { className: "v" }, authorName),
13034
+ ) : null,
12195
13035
  ),
12196
13036
 
12197
13037
  record.description && h("div", { className: "cpm-section" },
@@ -12498,7 +13338,13 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
12498
13338
  ),
12499
13339
 
12500
13340
  authDialog && h("div", { className: "cpm-dialog" },
12501
- h("div", { className: "cpm-mcp-modal", onClick: (e) => e.stopPropagation() },
13341
+ h("div", {
13342
+ className: "cpm-mcp-modal",
13343
+ role: "dialog",
13344
+ "aria-modal": "true",
13345
+ "aria-label": authDialog.connectorName ? `配置 MCP「${authDialog.connectorName}」` : "配置 MCP",
13346
+ onClick: (e) => e.stopPropagation(),
13347
+ },
12502
13348
  h("button", {
12503
13349
  type: "button",
12504
13350
  className: "cpm-mcp-close-top",
@@ -12650,14 +13496,20 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
12650
13496
  onClick: async () => {
12651
13497
  setAuthDialog((prev) => prev ? { ...prev, saving: true } : null);
12652
13498
  try {
13499
+ const connName = authDialog.connectorName;
12653
13500
  const res = await persistAuthDialog();
12654
13501
  if (res && res.ok === false) {
12655
13502
  showToast("保存失败", res.error || "配置校验未通过,请检查填写内容", { restart: false });
12656
13503
  setAuthDialog((prev) => prev ? { ...prev, saving: false } : null);
12657
13504
  return;
12658
13505
  }
12659
- await refreshState();
12660
- void showApplicationToast(showToast, res, "配置成功", `已成功保存 ${authDialog.connectorName} 认证信息并注册为可用 MCP 服务`);
13506
+ if (res?.plugin && patchPluginInState) {
13507
+ void refreshState();
13508
+ } else {
13509
+ await refreshState();
13510
+ }
13511
+ void loadConnectorTools(connName, true);
13512
+ void showApplicationToast(showToast, res, "配置成功", `已成功保存 ${connName} 认证信息并注册为可用 MCP 服务`);
12661
13513
  closeAuthDialog();
12662
13514
  } catch (err) {
12663
13515
  const rawMsg = err?.message || err;
@@ -12690,14 +13542,19 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
12690
13542
  ),
12691
13543
 
12692
13544
  confirmRemove && h("div", { className: "cpm-dialog", ...backdropDismissProps(() => { if (!busy) setConfirmRemove(false); }) },
12693
- h("div", { className: "cpm-dialog-box", onClick: (e) => e.stopPropagation() },
12694
- h("div", { className: "cpm-dialog-title" }, `卸载 ${record.displayName || record.name}?`),
12695
- h("div", { className: "cpm-field", style: { color: "var(--cpm-muted)", fontSize: "13px", lineHeight: 1.5, marginBottom: "20px" } }, "将删除插件副本、技能与子代理注册及 MCP 配置。"),
12696
- h("div", { className: "cpm-dialog-actions" },
12697
- h("button", { className: "cpm-btn cpm-btn-secondary", disabled: busy, onClick: () => { if (!busy) setConfirmRemove(false); } }, "取消"),
12698
- h("button", { className: "cpm-btn cpm-btn-primary", style: { background: "#ef4444", borderColor: "#ef4444", color: "#ffffff" }, disabled: busy, onClick: remove }, busy ? "卸载中…" : "卸载"),
12699
- ),
12700
- ),
13545
+ h(ConfirmDialogBox, {
13546
+ titleId: "cpm-confirm-remove-manage-title",
13547
+ title: `卸载 ${record.displayName || record.name}?`,
13548
+ description: "将删除插件副本、技能与子代理注册及 MCP 配置。",
13549
+ descriptionStyle: { color: "var(--cpm-muted)", fontSize: "13px", lineHeight: 1.5, marginBottom: "20px" },
13550
+ confirmLabel: "卸载",
13551
+ confirmBusyLabel: "卸载中…",
13552
+ confirmStyle: { background: "#ef4444", borderColor: "#ef4444", color: "#ffffff" },
13553
+ busy,
13554
+ cancelDisabled: busy,
13555
+ onCancel: () => { if (!busy) setConfirmRemove(false); },
13556
+ onConfirm: remove,
13557
+ }),
12701
13558
  ),
12702
13559
 
12703
13560
  hoveredTool && (() => {
@@ -13135,6 +13992,1387 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
13135
13992
  );
13136
13993
  }
13137
13994
 
13995
+ const AT_PLUGIN_SCHEME = "uph-plugin:";
13996
+ const AT_PLUGIN_WIRE_RE = /@\[([^\]\n]+)\]\(uph-plugin:([^)\s]+)\)/uy;
13997
+ const AT_PLUGIN_RAW_TOKEN_RE = /@([^\s\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul},。;:、!?()【】《》“”‘’」』]+)/uy;
13998
+ const AT_PLUGIN_LEFT_ALLOWED_RE = /[\s(\[{"'“‘(【《,。;:、!?\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
13999
+ const AT_PLUGIN_TRAILING_PUNCT_RE = /[.,;:!?,。;:!?)"'\]”’)】》]+$/u;
14000
+ const AT_PLUGINS_CSS = `
14001
+ [role="listbox"] button[id^="dsh-slash-option-plugins-"] {
14002
+ gap: 8px;
14003
+ }
14004
+ [role="listbox"] button[id^="dsh-slash-option-plugins-"] > span:first-child {
14005
+ width: 16px;
14006
+ height: 16px;
14007
+ border-radius: 4px;
14008
+ overflow: hidden;
14009
+ }
14010
+ [role="listbox"] button[id^="dsh-slash-option-plugins-"] > span:nth-child(2) {
14011
+ font-weight: 600;
14012
+ color: var(--dsw-alias-label-primary);
14013
+ }
14014
+ [role="listbox"] button[id^="dsh-slash-option-plugins-"] > span:nth-child(3) {
14015
+ text-align: left;
14016
+ }
14017
+ .cpm-at-plugin-icon,
14018
+ .cpm-at-plugin-chip-icon {
14019
+ position: relative;
14020
+ display: inline-flex;
14021
+ align-items: center;
14022
+ justify-content: center;
14023
+ width: 100%;
14024
+ height: 100%;
14025
+ flex: none;
14026
+ overflow: hidden;
14027
+ border-radius: 3px;
14028
+ }
14029
+ .cpm-at-plugin-icon .cpm-card-icon,
14030
+ .cpm-at-plugin-chip-icon .cpm-card-icon,
14031
+ .cpm-at-plugin-icon .cpm-icon-underlay > .cpm-card-icon,
14032
+ .cpm-at-plugin-chip-icon .cpm-icon-underlay > .cpm-card-icon {
14033
+ width: 100% !important;
14034
+ height: 100% !important;
14035
+ flex: none !important;
14036
+ margin: 0 !important;
14037
+ padding: 0 !important;
14038
+ border: none !important;
14039
+ border-radius: 3px !important;
14040
+ corner-shape: initial !important;
14041
+ box-shadow: none !important;
14042
+ background: transparent !important;
14043
+ display: flex;
14044
+ align-items: center;
14045
+ justify-content: center;
14046
+ position: relative;
14047
+ overflow: hidden;
14048
+ }
14049
+ .cpm-at-plugin-icon .cpm-card-icon img,
14050
+ .cpm-at-plugin-icon .cpm-card-icon svg,
14051
+ .cpm-at-plugin-icon > svg,
14052
+ .cpm-at-plugin-icon > img,
14053
+ .cpm-at-plugin-chip-icon .cpm-card-icon img,
14054
+ .cpm-at-plugin-chip-icon .cpm-card-icon svg,
14055
+ .cpm-at-plugin-chip-icon > svg,
14056
+ .cpm-at-plugin-chip-icon > img {
14057
+ width: 100% !important;
14058
+ height: 100% !important;
14059
+ border-radius: 3px !important;
14060
+ object-fit: contain !important;
14061
+ display: block;
14062
+ }
14063
+ [data-composer-chip="plugins"],
14064
+ .cpm-at-plugin-chip {
14065
+ display: inline-flex;
14066
+ align-items: baseline;
14067
+ gap: 4px;
14068
+ max-width: 240px;
14069
+ padding: 0 4px;
14070
+ border-radius: var(--dsw-radius-sm, 4px);
14071
+ color: var(--dsw-alias-label-primary, #18181b);
14072
+ background: transparent;
14073
+ font-weight: 600;
14074
+ line-height: inherit;
14075
+ vertical-align: baseline;
14076
+ user-select: none;
14077
+ cursor: default;
14078
+ transition: background-color 120ms ease;
14079
+ }
14080
+ body[data-ds-dark-theme] [data-composer-chip="plugins"],
14081
+ body[data-ds-dark-theme] .cpm-at-plugin-chip {
14082
+ color: var(--dsw-alias-label-primary, #f4f4f5);
14083
+ }
14084
+ @media (hover: hover) {
14085
+ [data-composer-chip="plugins"]:hover,
14086
+ .cpm-at-plugin-chip:hover {
14087
+ background: var(--dsw-alias-interactive-bg-hover, rgba(38, 49, 72, 0.06));
14088
+ }
14089
+ body[data-ds-dark-theme] [data-composer-chip="plugins"]:hover,
14090
+ body[data-ds-dark-theme] .cpm-at-plugin-chip:hover {
14091
+ background: var(--dsw-alias-interactive-bg-hover, rgba(255, 255, 255, 0.08));
14092
+ }
14093
+ }
14094
+ [data-composer-chip="plugins"] > span:not([data-uph-chip-icon]) {
14095
+ display: inline-flex;
14096
+ align-items: baseline;
14097
+ padding: 0 !important;
14098
+ margin: 0 !important;
14099
+ border-radius: 0 !important;
14100
+ background: transparent !important;
14101
+ color: inherit !important;
14102
+ font-weight: inherit !important;
14103
+ line-height: inherit !important;
14104
+ vertical-align: baseline !important;
14105
+ max-width: none !important;
14106
+ min-width: 0;
14107
+ overflow: hidden;
14108
+ }
14109
+ [data-composer-chip="plugins"][data-uph-plugin-resolved="true"] > span:not([data-uph-chip-icon]) > span:first-child:not(:last-child) {
14110
+ display: none !important;
14111
+ }
14112
+ [data-composer-chip="plugins"]:not([data-uph-plugin-resolved="true"]) > span:not([data-uph-chip-icon]) {
14113
+ gap: 3px;
14114
+ }
14115
+ .cpm-at-plugin-chip.is-unresolved {
14116
+ opacity: 0.72;
14117
+ font-weight: 500;
14118
+ }
14119
+ .cpm-at-plugin-chip-marker {
14120
+ flex: none;
14121
+ font-weight: 500;
14122
+ }
14123
+ .cpm-at-plugin-chip-icon-wrap {
14124
+ display: inline-flex;
14125
+ width: clamp(13px, 1em, 16px);
14126
+ height: clamp(13px, 1em, 16px);
14127
+ flex: none;
14128
+ align-items: center;
14129
+ justify-content: center;
14130
+ align-self: center;
14131
+ overflow: hidden;
14132
+ line-height: 1;
14133
+ position: relative;
14134
+ top: 0.05em;
14135
+ }
14136
+ .cpm-at-plugin-chip-label {
14137
+ overflow: hidden;
14138
+ text-overflow: ellipsis;
14139
+ white-space: nowrap;
14140
+ }
14141
+ .cpm-at-plugin-popover {
14142
+ position: fixed;
14143
+ inset: auto;
14144
+ right: auto;
14145
+ bottom: auto;
14146
+ margin: 0;
14147
+ z-index: 100040;
14148
+ width: max-content;
14149
+ min-width: 0;
14150
+ max-width: min(204px, calc(100vw - 24px));
14151
+ max-height: min(160px, 36vh);
14152
+ padding: 6px 10px;
14153
+ overflow-y: auto;
14154
+ overscroll-behavior: contain;
14155
+ box-sizing: border-box;
14156
+ border-radius: var(--dsw-radius-lg, 16px);
14157
+ corner-shape: squircle;
14158
+ background: rgba(255, 255, 255, 0.72);
14159
+ backdrop-filter: blur(20px) saturate(180%);
14160
+ -webkit-backdrop-filter: blur(20px) saturate(180%);
14161
+ border: 1px solid rgba(0, 0, 0, 0.08);
14162
+ box-shadow: 0 16px 36px -4px rgba(0, 0, 0, 0.10), 0 2px 8px rgba(0, 0, 0, 0.04);
14163
+ color: #18181b;
14164
+ font-size: 12px;
14165
+ line-height: 1.48;
14166
+ letter-spacing: -0.005em;
14167
+ overflow-wrap: break-word;
14168
+ user-select: text;
14169
+ }
14170
+ .cpm-at-plugin-popover:not(:popover-open):not(.\:popover-open):not([data-open="true"]) {
14171
+ display: none;
14172
+ }
14173
+ .cpm-at-plugin-popover:is(:popover-open, .\:popover-open, [data-open="true"]) {
14174
+ display: block;
14175
+ }
14176
+ body[data-ds-dark-theme] .cpm-at-plugin-popover,
14177
+ .cpm-at-plugin-popover.cpm-dark {
14178
+ background: rgba(32, 32, 35, 0.75);
14179
+ backdrop-filter: blur(22px) saturate(180%);
14180
+ -webkit-backdrop-filter: blur(22px) saturate(180%);
14181
+ border: 1px solid rgba(255, 255, 255, 0.14);
14182
+ box-shadow: 0 12px 36px rgba(0, 0, 0, 0.6);
14183
+ color: #f4f4f5;
14184
+ }
14185
+ .cpm-at-plugin-popover::-webkit-scrollbar {
14186
+ width: 0;
14187
+ height: 0;
14188
+ }
14189
+ .cpm-at-plugin-popover-desc {
14190
+ margin: 0;
14191
+ white-space: pre-wrap;
14192
+ text-wrap: pretty;
14193
+ color: inherit;
14194
+ }
14195
+ .cpm-at-plugin-popover[data-unresolved="true"] .cpm-at-plugin-popover-desc {
14196
+ opacity: 0.72;
14197
+ }
14198
+ @media (prefers-reduced-motion: no-preference) {
14199
+ .cpm-at-plugin-popover {
14200
+ opacity: 0;
14201
+ transform: translateY(4px) scale(0.96);
14202
+ transition:
14203
+ opacity 0.16s cubic-bezier(0.22, 1, 0.36, 1),
14204
+ transform 0.22s linear(0 0%, 0.049 2.9%, 0.1685 5.9%, 0.3235 8.8%, 0.4877 11.8%, 0.6428 14.7%, 0.7778 17.6%, 0.8871 20.6%, 0.9694 23.5%, 1.0265 26.5%, 1.0617 29.4%, 1.0792 32.4%, 1.0835 35.3%, 1.0787 38.2%, 1.0683 41.2%, 1.0551 44.1%, 1.0414 47.1%, 1.0286 50%, 1.0176 52.9%, 1.0086 55.9%, 1.002 58.8%, 0.9974 61.8%, 0.9946 64.7%, 0.9933 67.6%, 0.993 70.6%, 0.9935 73.5%, 0.9944 76.5%, 0.9955 79.4%, 0.9966 82.4%, 0.9977 85.3%, 0.9986 88.2%, 0.9993 91.2%, 0.9999 94.1%, 1 100%),
14205
+ display 0.16s,
14206
+ overlay 0.16s;
14207
+ transition-behavior: allow-discrete;
14208
+ }
14209
+ .cpm-at-plugin-popover[data-placement="bottom"] {
14210
+ transform: translateY(-4px) scale(0.96);
14211
+ }
14212
+ .cpm-at-plugin-popover:is(:popover-open, .\:popover-open, [data-open="true"]) {
14213
+ opacity: 1;
14214
+ transform: translateY(0) scale(1);
14215
+ }
14216
+ @starting-style {
14217
+ .cpm-at-plugin-popover:is(:popover-open, .\:popover-open, [data-open="true"]) {
14218
+ opacity: 0;
14219
+ transform: translateY(4px) scale(0.96);
14220
+ }
14221
+ .cpm-at-plugin-popover[data-placement="bottom"]:is(:popover-open, .\:popover-open, [data-open="true"]) {
14222
+ transform: translateY(-4px) scale(0.96);
14223
+ }
14224
+ }
14225
+ }
14226
+ @media (prefers-reduced-motion: reduce) {
14227
+ [data-composer-chip="plugins"],
14228
+ .cpm-at-plugin-chip,
14229
+ .cpm-at-plugin-popover {
14230
+ transition: none;
14231
+ }
14232
+ }
14233
+ @media (prefers-reduced-transparency: reduce) {
14234
+ .cpm-at-plugin-popover {
14235
+ background: #ffffff;
14236
+ backdrop-filter: none;
14237
+ -webkit-backdrop-filter: none;
14238
+ }
14239
+ body[data-ds-dark-theme] .cpm-at-plugin-popover,
14240
+ .cpm-at-plugin-popover.cpm-dark {
14241
+ background: #27272a;
14242
+ backdrop-filter: none;
14243
+ -webkit-backdrop-filter: none;
14244
+ }
14245
+ }
14246
+ @media (prefers-contrast: more) {
14247
+ .cpm-at-plugin-popover {
14248
+ border-color: rgba(0, 0, 0, 0.24);
14249
+ background: rgba(255, 255, 255, 0.94);
14250
+ }
14251
+ body[data-ds-dark-theme] .cpm-at-plugin-popover,
14252
+ .cpm-at-plugin-popover.cpm-dark {
14253
+ border-color: rgba(255, 255, 255, 0.32);
14254
+ background: rgba(39, 39, 42, 0.96);
14255
+ }
14256
+ }
14257
+ `;
14258
+
14259
+ function placePluginChipPopover(anchorRect, width, height, viewport) {
14260
+ const margin = 12, gap = 8;
14261
+ const vw = Math.max(margin * 2 + 80, Number(viewport?.width) || 0);
14262
+ const vh = Math.max(margin * 2 + 48, Number(viewport?.height) || 0);
14263
+ const w = Math.min(Number(width) || 0, vw - margin * 2);
14264
+ const h = Math.min(Number(height) || 0, vh - margin * 2);
14265
+ const anchorCenterX = anchorRect.left + anchorRect.width / 2;
14266
+ const left = Math.max(margin, Math.min(anchorCenterX - w / 2, vw - w - margin));
14267
+ const spaceAbove = anchorRect.top - gap - margin;
14268
+ const spaceBelow = vh - anchorRect.bottom - gap - margin;
14269
+ const preferBottom = anchorRect.top - h - gap < margin && spaceBelow > spaceAbove;
14270
+ const placement = preferBottom ? "bottom" : "top";
14271
+ const rawTop = preferBottom ? anchorRect.bottom + gap : anchorRect.top - h - gap;
14272
+ const top = Math.max(margin, Math.min(rawTop, vh - h - margin));
14273
+ const edgeInset = Math.min(12, Math.floor(w / 2));
14274
+ const originX = Math.max(edgeInset, Math.min(w - edgeInset, anchorCenterX - left));
14275
+ const originY = placement === "bottom" ? "0%" : "100%";
14276
+ return { left: Math.round(left), top: Math.round(top), placement, originX: Math.round(originX), originY };
14277
+ }
14278
+
14279
+ function formatAtPluginMention(pluginName, displayName) {
14280
+ const id = String(pluginName || "").trim();
14281
+ const label = String(displayName || id).replace(/[\r\n\[\]]+/g, " ").trim() || id;
14282
+ return `@[${label}](${AT_PLUGIN_SCHEME}${encodeURIComponent(id)})`;
14283
+ }
14284
+
14285
+ function parseAtPluginCandidateValue(value) {
14286
+ if (typeof value !== "string" || !value) return null;
14287
+ try {
14288
+ const parsed = JSON.parse(value);
14289
+ if (parsed && typeof parsed.name === "string" && parsed.name) {
14290
+ return { name: parsed.name, displayName: parsed.displayName || parsed.name };
14291
+ }
14292
+ } catch {}
14293
+ return null;
14294
+ }
14295
+
14296
+ function isAtPluginLeftBoundary(text, index) {
14297
+ return index === 0 || AT_PLUGIN_LEFT_ALLOWED_RE.test(text[index - 1]);
14298
+ }
14299
+
14300
+ function matchAtPluginMention(text, from, byLowerName, wireOnly = false) {
14301
+ if (typeof text !== "string" || !text.includes("@")) return undefined;
14302
+ let cursor = from;
14303
+ while (cursor < text.length) {
14304
+ const at = text.indexOf("@", cursor);
14305
+ if (at < 0) return undefined;
14306
+ AT_PLUGIN_WIRE_RE.lastIndex = at;
14307
+ const wire = AT_PLUGIN_WIRE_RE.exec(text);
14308
+ if (wire !== null) {
14309
+ if (isAtPluginLeftBoundary(text, at)) {
14310
+ try {
14311
+ const decoded = decodeURIComponent(wire[2]);
14312
+ const live = byLowerName?.get(decoded.toLowerCase()) || null;
14313
+ return {
14314
+ id: "uph-plugin",
14315
+ start: at,
14316
+ end: at + wire[0].length,
14317
+ data: { name: live?.name || decoded, label: live?.displayName || wire[1] },
14318
+ };
14319
+ } catch {}
14320
+ }
14321
+ cursor = at + wire[0].length;
14322
+ continue;
14323
+ }
14324
+ if (!wireOnly && isAtPluginLeftBoundary(text, at) && byLowerName && byLowerName.size > 0) {
14325
+ AT_PLUGIN_RAW_TOKEN_RE.lastIndex = at;
14326
+ const raw = AT_PLUGIN_RAW_TOKEN_RE.exec(text);
14327
+ if (raw !== null && !raw[1].startsWith("\"")) {
14328
+ const cleaned = raw[1].replace(AT_PLUGIN_TRAILING_PUNCT_RE, "");
14329
+ if (cleaned.length > 0) {
14330
+ const live = byLowerName.get(cleaned.toLowerCase());
14331
+ if (live) {
14332
+ return {
14333
+ id: "uph-plugin",
14334
+ start: at,
14335
+ end: at + 1 + cleaned.length,
14336
+ data: { name: live.name, label: live.displayName || live.name },
14337
+ };
14338
+ }
14339
+ }
14340
+ }
14341
+ }
14342
+ cursor = at + 1;
14343
+ }
14344
+ return undefined;
14345
+ }
14346
+
14347
+ function atPluginReference(mention, label) {
14348
+ return { source: "plugins", ref: mention, label, clipboardText: mention };
14349
+ }
14350
+
14351
+ function pasteAtPluginReferences(event, byLowerName) {
14352
+ const clipboard = event.clipboardData;
14353
+ if (event.defaultPrevented || !clipboard || clipboard.files?.length ||
14354
+ Array.from(clipboard.items || []).some((item) => item.kind === "file")) return;
14355
+ const root = event.target?.closest?.('[data-composer-input][contenteditable="true"]');
14356
+ if (!root || root.hasAttribute("data-composer-composing")) return;
14357
+ const text = clipboard.getData("text/plain");
14358
+ if (!text.includes("(uph-plugin:")) return;
14359
+
14360
+ // DSH bundles Lexical privately. Use the mounted editor and its registered
14361
+ // classes so the pasted nodes share the host's history and draft model.
14362
+ const editor = root.__lexicalEditor;
14363
+ if (editor?.getRootElement?.() !== root || !editor.isEditable?.() || editor.isComposing?.() ||
14364
+ typeof editor.update !== "function") return;
14365
+ const ReferenceChip = editor._nodes?.get?.("reference-chip")?.klass;
14366
+ const Text = editor._nodes?.get?.("text")?.klass;
14367
+ const LineBreak = editor._nodes?.get?.("linebreak")?.klass;
14368
+ if (!ReferenceChip || !Text || !LineBreak) return;
14369
+
14370
+ const clean = text.replace(/[\uE100-\uE11D\uFFFC]/gu, "").replace(/\r\n?/g, "\n");
14371
+ const first = matchAtPluginMention(clean, 0, byLowerName, true);
14372
+ if (!first) return;
14373
+
14374
+ let inserted = false;
14375
+ editor.update(() => {
14376
+ const selection = editor._pendingEditorState?._selection;
14377
+ if (!selection?.anchor || !selection?.focus || typeof selection.insertNodes !== "function") return;
14378
+ const nodes = [];
14379
+ const appendText = (segment) => {
14380
+ const lines = segment.split("\n");
14381
+ for (let i = 0; i < lines.length; i++) {
14382
+ if (i > 0) nodes.push(new LineBreak());
14383
+ if (lines[i]) nodes.push(new Text(lines[i]));
14384
+ }
14385
+ };
14386
+ let cursor = 0;
14387
+ for (let match = first; match; match = matchAtPluginMention(clean, cursor, byLowerName, true)) {
14388
+ appendText(clean.slice(cursor, match.start));
14389
+ const ref = atPluginReference(clean.slice(match.start, match.end), match.data.label);
14390
+ nodes.push(new ReferenceChip(ref));
14391
+ cursor = match.end;
14392
+ }
14393
+ appendText(clean.slice(cursor));
14394
+ selection.insertNodes(nodes);
14395
+ inserted = true;
14396
+ }, { tag: "paste", discrete: true });
14397
+ if (inserted) {
14398
+ event.preventDefault();
14399
+ event.stopPropagation();
14400
+ }
14401
+ }
14402
+
14403
+ function readComposerPluginReference(chip, byLowerName) {
14404
+ const editor = chip.closest?.("[data-composer-input]")?.__lexicalEditor;
14405
+ const state = editor?.getEditorState?.();
14406
+ const node = state?._nodeMap?.get?.(chip[`__lexicalKey_${editor.getKey?.()}`]);
14407
+ if (typeof node?.getReference !== "function" || typeof state.read !== "function") return undefined;
14408
+ return state.read(() => matchAtPluginMention(node.getReference(), 0, byLowerName, true));
14409
+ }
14410
+
14411
+ function filterAtPluginCandidates(plugins, query) {
14412
+ const q = String(query || "").trim().toLowerCase();
14413
+ if (!q) return plugins;
14414
+ const prefixed = [];
14415
+ const matched = [];
14416
+ for (const plugin of plugins) {
14417
+ const nameLower = String(plugin.name || "").toLowerCase();
14418
+ const titleLower = String(plugin.displayName || plugin.name || "").toLowerCase();
14419
+ if (titleLower.startsWith(q) || nameLower.startsWith(q)) prefixed.push(plugin);
14420
+ else if (titleLower.includes(q) || nameLower.includes(q)) matched.push(plugin);
14421
+ }
14422
+ return prefixed.length && matched.length ? [...prefixed, ...matched] : (prefixed.length ? prefixed : matched);
14423
+ }
14424
+
14425
+ function createAtPluginsStore(ctx) {
14426
+ let plugins = [];
14427
+ let byLowerName = new Map();
14428
+ let byDisplayNameLower = new Map();
14429
+ let lexiconNames = [];
14430
+ let currentSignature = "";
14431
+ let hydrated = false;
14432
+ let disposed = false;
14433
+ let checkedAt = -Infinity;
14434
+ let fetchSeq = 0;
14435
+ let inFlight = null;
14436
+ let inFlightController = null;
14437
+ const listeners = new Set();
14438
+ const themeListeners = new Set();
14439
+ const iconComponents = new Map();
14440
+ const iconPluginRefs = new Map();
14441
+ const recentPicks = [];
14442
+ const refreshInterval = 10000;
14443
+
14444
+ function readCurrentDark() {
14445
+ try {
14446
+ if (typeof document !== "undefined" && document.body?.hasAttribute?.("data-ds-dark-theme")) {
14447
+ return true;
14448
+ }
14449
+ } catch {}
14450
+ const root = typeof document !== "undefined" ? document.documentElement : null;
14451
+ return isDarkMode(ctx, root);
14452
+ }
14453
+
14454
+ let lastDark = readCurrentDark();
14455
+ const onThemePotentiallyChanged = () => {
14456
+ if (disposed) return;
14457
+ const nextDark = readCurrentDark();
14458
+ if (nextDark === lastDark) return;
14459
+ lastDark = nextDark;
14460
+ for (const listener of Array.from(themeListeners)) {
14461
+ try { listener(nextDark); } catch {}
14462
+ }
14463
+ };
14464
+
14465
+ let themeObserver = null;
14466
+ if (typeof document !== "undefined" && typeof MutationObserver === "function") {
14467
+ const watchAttrs = ["data-ds-dark-theme", "data-theme", "class"];
14468
+ themeObserver = new MutationObserver(onThemePotentiallyChanged);
14469
+ if (document.body) themeObserver.observe(document.body, { attributes: true, attributeFilter: watchAttrs });
14470
+ if (document.documentElement) themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: watchAttrs });
14471
+ }
14472
+ const darkMedia = typeof window !== "undefined" && typeof window.matchMedia === "function"
14473
+ ? window.matchMedia("(prefers-color-scheme: dark)")
14474
+ : null;
14475
+ darkMedia?.addEventListener?.("change", onThemePotentiallyChanged);
14476
+
14477
+ function applyList(list) {
14478
+ const normalized = Array.isArray(list) ? list.filter((p) => p && typeof p.name === "string" && p.name) : [];
14479
+ const signature = JSON.stringify(normalized);
14480
+ hydrated = true;
14481
+ if (signature === currentSignature) return false;
14482
+ currentSignature = signature;
14483
+ plugins = normalized;
14484
+ byLowerName = new Map(normalized.map((p) => [p.name.toLowerCase(), p]));
14485
+ byDisplayNameLower = new Map();
14486
+ for (const p of normalized) {
14487
+ const dKey = String(p.displayName || p.name || "").trim().toLowerCase();
14488
+ if (dKey && !byDisplayNameLower.has(dKey)) byDisplayNameLower.set(dKey, p);
14489
+ }
14490
+ lexiconNames = normalized.map((p) => p.name);
14491
+ for (const listener of Array.from(listeners)) {
14492
+ try { listener(); } catch {}
14493
+ }
14494
+ return true;
14495
+ }
14496
+
14497
+ function pruneRecentPicks(nowMs = Date.now()) {
14498
+ while (recentPicks.length && nowMs - recentPicks[0].at > 5000) {
14499
+ recentPicks.shift();
14500
+ }
14501
+ }
14502
+
14503
+ function recordPick(name, displayName) {
14504
+ if (!name) return;
14505
+ const nowMs = Date.now();
14506
+ pruneRecentPicks(nowMs);
14507
+ recentPicks.push({
14508
+ name: String(name),
14509
+ displayNameLower: String(displayName || name).trim().toLowerCase(),
14510
+ at: nowMs,
14511
+ });
14512
+ if (recentPicks.length > 24) recentPicks.shift();
14513
+ }
14514
+
14515
+ function resolveChipPlugin({ name, label, consumePick = false } = {}) {
14516
+ if (name) {
14517
+ const direct = byLowerName.get(String(name).trim().toLowerCase());
14518
+ if (direct) return direct;
14519
+ }
14520
+ const labelLower = String(label || "").trim().toLowerCase();
14521
+ if (!labelLower) return null;
14522
+ if (consumePick && recentPicks.length > 0) {
14523
+ pruneRecentPicks();
14524
+ for (let i = recentPicks.length - 1; i >= 0; i--) {
14525
+ if (recentPicks[i].displayNameLower === labelLower) {
14526
+ const candidate = byLowerName.get(recentPicks[i].name.toLowerCase()) || null;
14527
+ if (candidate) {
14528
+ recentPicks.splice(i, 1);
14529
+ return candidate;
14530
+ }
14531
+ }
14532
+ }
14533
+ }
14534
+ return byDisplayNameLower.get(labelLower) || byLowerName.get(labelLower) || null;
14535
+ }
14536
+
14537
+ function getDescription(plugin, resolved = true) {
14538
+ if (!resolved || !plugin) return "该插件当前未启用或未安装";
14539
+ return plugin.shortDescription || plugin.description || plugin.summary || (plugin.author ? `by ${plugin.author}` : "暂无插件描述");
14540
+ }
14541
+
14542
+ function getIconComponent(plugin) {
14543
+ const lower = String(plugin?.name || "").toLowerCase();
14544
+ if (iconPluginRefs.size >= 512 && !iconPluginRefs.has(lower)) iconPluginRefs.clear();
14545
+ iconPluginRefs.set(lower, plugin);
14546
+ let Comp = iconComponents.get(lower);
14547
+ if (!Comp) {
14548
+ Comp = function AtPluginMenuIcon() {
14549
+ const current = byLowerName.get(lower) || iconPluginRefs.get(lower) || plugin;
14550
+ return h("span", { className: "cpm-at-plugin-icon", "aria-hidden": "true" },
14551
+ h(PluginIcon, { plugin: current, isDark: readCurrentDark(), eager: true, preferPreview: true })
14552
+ );
14553
+ };
14554
+ if (iconComponents.size >= 512) iconComponents.clear();
14555
+ iconComponents.set(lower, Comp);
14556
+ }
14557
+ return Comp;
14558
+ }
14559
+
14560
+ async function fetchFresh(force = false) {
14561
+ if (disposed) return plugins;
14562
+ if (inFlight && !force) return inFlight;
14563
+ if (force && inFlightController) {
14564
+ inFlightController.abort();
14565
+ inFlightController = null;
14566
+ inFlight = null;
14567
+ }
14568
+ const seq = ++fetchSeq;
14569
+ const controller = typeof AbortController === "function" ? new AbortController() : null;
14570
+ inFlightController = controller;
14571
+ checkedAt = Date.now();
14572
+ const run = (async () => {
14573
+ try {
14574
+ const data = await api("/at-plugins", controller ? { cache: "no-store", signal: controller.signal } : { cache: "no-store" });
14575
+ if (!disposed && seq === fetchSeq && (!controller || !controller.signal.aborted) && Array.isArray(data?.plugins)) {
14576
+ applyList(data.plugins);
14577
+ checkedAt = Date.now();
14578
+ }
14579
+ } catch {
14580
+ // Keep the last known snapshot when a background refresh fails or aborts.
14581
+ } finally {
14582
+ if (inFlight === run) {
14583
+ inFlightController = null;
14584
+ inFlight = null;
14585
+ }
14586
+ }
14587
+ return plugins;
14588
+ })();
14589
+ inFlight = run;
14590
+ return run;
14591
+ }
14592
+
14593
+ function raceWithSignal(promise, signal) {
14594
+ if (!signal) return promise;
14595
+ if (signal.aborted) return Promise.resolve([]);
14596
+ return new Promise((resolve) => {
14597
+ const onAbort = () => {
14598
+ signal.removeEventListener?.("abort", onAbort);
14599
+ resolve([]);
14600
+ };
14601
+ signal.addEventListener?.("abort", onAbort, { once: true });
14602
+ void promise.then((value) => {
14603
+ signal.removeEventListener?.("abort", onAbort);
14604
+ resolve(signal.aborted ? [] : value);
14605
+ });
14606
+ });
14607
+ }
14608
+
14609
+ const boot = globalThis.__UPH_AT_PLUGINS__;
14610
+ if (Array.isArray(boot)) {
14611
+ delete globalThis.__UPH_AT_PLUGINS__;
14612
+ applyList(boot);
14613
+ checkedAt = Date.now();
14614
+ }
14615
+
14616
+ const onInvalidate = () => {
14617
+ if (disposed) return;
14618
+ checkedAt = -Infinity;
14619
+ void fetchFresh(true);
14620
+ };
14621
+ const onVisibility = () => {
14622
+ if (typeof document !== "undefined" && document.hidden) return;
14623
+ if (!hydrated || Date.now() - checkedAt >= refreshInterval) {
14624
+ void fetchFresh(false);
14625
+ }
14626
+ };
14627
+
14628
+ if (typeof document !== "undefined" && typeof document.addEventListener === "function") {
14629
+ document.addEventListener("uph-at-plugins-changed", onInvalidate);
14630
+ document.addEventListener("uph-mcp-branding-changed", onInvalidate);
14631
+ document.addEventListener("visibilitychange", onVisibility);
14632
+ }
14633
+ const offReset = ctx.on?.("connection/reset", onInvalidate);
14634
+ const offChanged = ctx.on?.("plugin-manager/changed", onInvalidate);
14635
+
14636
+ return {
14637
+ warm() {
14638
+ if (!hydrated || Date.now() - checkedAt >= refreshInterval) {
14639
+ void fetchFresh(false);
14640
+ }
14641
+ },
14642
+ async candidates({ query, quoted, signal } = {}) {
14643
+ if (quoted === true || signal?.aborted) return [];
14644
+ if (!hydrated) {
14645
+ await raceWithSignal(fetchFresh(false), signal);
14646
+ if (!hydrated && inFlight && !signal?.aborted) {
14647
+ await raceWithSignal(inFlight, signal);
14648
+ }
14649
+ if (signal?.aborted) return [];
14650
+ } else if (Date.now() - checkedAt >= refreshInterval) {
14651
+ void fetchFresh(false);
14652
+ }
14653
+ const matches = filterAtPluginCandidates(plugins, query);
14654
+ return matches.map((plugin) => {
14655
+ const title = plugin.displayName || plugin.name;
14656
+ const summary = plugin.summary || plugin.shortDescription || plugin.description || (plugin.author ? `by ${plugin.author}` : "");
14657
+ return {
14658
+ name: title,
14659
+ ...(summary ? { description: summary } : {}),
14660
+ icon: getIconComponent(plugin),
14661
+ section: "插件",
14662
+ value: JSON.stringify({ name: plugin.name, displayName: title }),
14663
+ };
14664
+ });
14665
+ },
14666
+ lexicon() {
14667
+ return hydrated ? lexiconNames : undefined;
14668
+ },
14669
+ lexiconKey() {
14670
+ return lexiconNames.join("\0");
14671
+ },
14672
+ subscribe(listener) {
14673
+ listeners.add(listener);
14674
+ return () => { listeners.delete(listener); };
14675
+ },
14676
+ subscribeTheme(listener) {
14677
+ themeListeners.add(listener);
14678
+ return () => { themeListeners.delete(listener); };
14679
+ },
14680
+ getByLowerName() {
14681
+ return byLowerName;
14682
+ },
14683
+ isHydrated() {
14684
+ return hydrated;
14685
+ },
14686
+ recordPick,
14687
+ resolveChipPlugin,
14688
+ getDescription,
14689
+ isDark() {
14690
+ return readCurrentDark();
14691
+ },
14692
+ dispose() {
14693
+ disposed = true;
14694
+ fetchSeq += 1;
14695
+ inFlightController?.abort();
14696
+ inFlightController = null;
14697
+ inFlight = null;
14698
+ listeners.clear();
14699
+ themeListeners.clear();
14700
+ iconComponents.clear();
14701
+ iconPluginRefs.clear();
14702
+ recentPicks.length = 0;
14703
+ try { themeObserver?.disconnect?.(); } catch {}
14704
+ themeObserver = null;
14705
+ try { darkMedia?.removeEventListener?.("change", onThemePotentiallyChanged); } catch {}
14706
+ if (typeof document !== "undefined" && typeof document.removeEventListener === "function") {
14707
+ document.removeEventListener("uph-at-plugins-changed", onInvalidate);
14708
+ document.removeEventListener("uph-mcp-branding-changed", onInvalidate);
14709
+ document.removeEventListener("visibilitychange", onVisibility);
14710
+ }
14711
+ try { offReset?.(); } catch {}
14712
+ try { offChanged?.(); } catch {}
14713
+ },
14714
+ };
14715
+ }
14716
+
14717
+ const AT_PLUGINS_ACTIVE_DISPOSE_KEY = "__UPH_AT_PLUGINS_DISPOSE__";
14718
+
14719
+ function cleanupStaleAtPluginDom(preserveOwnedSlots) {
14720
+ if (typeof document === "undefined" || typeof document.querySelectorAll !== "function") return;
14721
+ const oldHosts = document.querySelectorAll("[data-uph-at-plugins-overlay]");
14722
+ for (let i = 0; i < oldHosts.length; i++) oldHosts[i]?.remove?.();
14723
+ const oldSlots = document.querySelectorAll("[data-uph-chip-icon]");
14724
+ for (let i = 0; i < oldSlots.length; i++) {
14725
+ if (!preserveOwnedSlots || !preserveOwnedSlots.has(oldSlots[i])) oldSlots[i]?.remove?.();
14726
+ }
14727
+ if (!preserveOwnedSlots) {
14728
+ const oldStyles = document.querySelectorAll("style[data-uph-at-plugins]");
14729
+ for (let i = 0; i < oldStyles.length; i++) oldStyles[i]?.remove?.();
14730
+ const oldChips = document.querySelectorAll('[data-composer-chip="plugins"]');
14731
+ for (let i = 0; i < oldChips.length; i++) {
14732
+ const chip = oldChips[i];
14733
+ if (chip.dataset) {
14734
+ delete chip.dataset.uphPluginResolved;
14735
+ delete chip.dataset.uphPluginName;
14736
+ delete chip.dataset.uphPluginLabel;
14737
+ } else {
14738
+ chip.removeAttribute?.("data-uph-plugin-resolved");
14739
+ chip.removeAttribute?.("data-uph-plugin-name");
14740
+ chip.removeAttribute?.("data-uph-plugin-label");
14741
+ }
14742
+ }
14743
+ const oldDescribed = document.querySelectorAll('[aria-describedby="uph-at-plugin-hover-popover"]');
14744
+ for (let i = 0; i < oldDescribed.length; i++) oldDescribed[i]?.removeAttribute?.("aria-describedby");
14745
+ }
14746
+ }
14747
+
14748
+ function installAtPlugins(ctx) {
14749
+ if (typeof globalThis !== "undefined" && typeof globalThis[AT_PLUGINS_ACTIVE_DISPOSE_KEY] === "function") {
14750
+ try { globalThis[AT_PLUGINS_ACTIVE_DISPOSE_KEY](); } catch {}
14751
+ }
14752
+ cleanupStaleAtPluginDom();
14753
+ let disposed = false;
14754
+ const disposers = [];
14755
+ const disposeAll = () => {
14756
+ if (disposed) return;
14757
+ disposed = true;
14758
+ if (typeof globalThis !== "undefined" && globalThis[AT_PLUGINS_ACTIVE_DISPOSE_KEY] === disposeAll) {
14759
+ delete globalThis[AT_PLUGINS_ACTIVE_DISPOSE_KEY];
14760
+ }
14761
+ for (let i = disposers.length - 1; i >= 0; i--) {
14762
+ try { disposers[i]?.(); } catch {}
14763
+ }
14764
+ };
14765
+ const collectDisposer = (handle) => {
14766
+ if (typeof handle === "function") disposers.push(handle);
14767
+ else if (typeof handle?.dispose === "function") disposers.push(() => handle.dispose());
14768
+ };
14769
+ if (typeof globalThis !== "undefined") globalThis[AT_PLUGINS_ACTIVE_DISPOSE_KEY] = disposeAll;
14770
+ try {
14771
+ const store = createAtPluginsStore(ctx);
14772
+ disposers.push(() => store.dispose());
14773
+ if (typeof document !== "undefined" && document.head) {
14774
+ const style = document.createElement("style");
14775
+ style.dataset.plugin = "universal-plugin-hub";
14776
+ style.dataset.uphAtPlugins = "";
14777
+ style.textContent = AT_PLUGINS_CSS;
14778
+ document.head.append(style);
14779
+ disposers.push(() => style.remove());
14780
+ }
14781
+
14782
+ const ReactDOM = (() => { try { return require("react-dom") || null; } catch { return null; } })();
14783
+ const ReactDOMClient = (() => { try { return require("react-dom/client") || null; } catch { return null; } })();
14784
+
14785
+ function PluginMentionChip({ node }) {
14786
+ const [revision, setRevision] = useState(0);
14787
+ useEffect(() => {
14788
+ const bump = () => setRevision((r) => r + 1);
14789
+ const offStore = store.subscribe(bump);
14790
+ const offTheme = store.subscribeTheme(bump);
14791
+ return () => {
14792
+ offStore();
14793
+ offTheme();
14794
+ };
14795
+ }, []);
14796
+ void revision;
14797
+ const live = store.getByLowerName().get(String(node?.data?.name || "").toLowerCase()) || null;
14798
+ const label = live?.displayName || node?.data?.label || node?.data?.name || "";
14799
+ return h("span", {
14800
+ className: "cpm-at-plugin-chip" + (live ? "" : " is-unresolved"),
14801
+ "data-uph-plugin-chip": "true",
14802
+ "data-uph-plugin-name": live?.name || node?.data?.name || "",
14803
+ "data-uph-plugin-label": label,
14804
+ },
14805
+ live
14806
+ ? h("span", { className: "cpm-at-plugin-chip-icon-wrap", "aria-hidden": "true" },
14807
+ h("span", { className: "cpm-at-plugin-chip-icon" },
14808
+ h(PluginIcon, { plugin: live, isDark: store.isDark(), eager: true, preferPreview: true })
14809
+ )
14810
+ )
14811
+ : h("span", { className: "cpm-at-plugin-chip-marker", "aria-hidden": "true" }, "@"),
14812
+ h("span", { className: "cpm-at-plugin-chip-label" }, label)
14813
+ );
14814
+ }
14815
+
14816
+ function PluginChipHoverPopover({ hovered, isDark, session }) {
14817
+ const popRef = useRef(null);
14818
+ const [position, setPosition] = useState(null);
14819
+ const lastContentRef = useRef({ description: "", resolved: true });
14820
+ if (hovered) {
14821
+ lastContentRef.current = {
14822
+ description: hovered.description || "",
14823
+ resolved: hovered.resolved !== false,
14824
+ };
14825
+ }
14826
+
14827
+ useSafeLayoutEffect(() => {
14828
+ const popup = popRef.current;
14829
+ if (!popup) return;
14830
+ if (!popup.hasAttribute("popover")) {
14831
+ try { popup.setAttribute("popover", "hint"); } catch {}
14832
+ }
14833
+ if (!hovered?.anchor?.isConnected) {
14834
+ popup.removeAttribute("data-open");
14835
+ if (typeof popup.hidePopover === "function") {
14836
+ try { if (popup.matches?.(":popover-open")) popup.hidePopover(); } catch {}
14837
+ }
14838
+ setPosition(null);
14839
+ return;
14840
+ }
14841
+
14842
+ const anchor = hovered.anchor;
14843
+ const prevDescribedBy = anchor.getAttribute("aria-describedby");
14844
+ const ownsDescribedBy = prevDescribedBy === null;
14845
+ if (ownsDescribedBy) anchor.setAttribute("aria-describedby", "uph-at-plugin-hover-popover");
14846
+
14847
+ setPosition(null);
14848
+ popup.setAttribute("data-open", "true");
14849
+ if (typeof popup.showPopover === "function") {
14850
+ try { if (!popup.matches?.(":popover-open")) popup.showPopover(); } catch {}
14851
+ }
14852
+
14853
+ const measure = () => {
14854
+ if (!anchor.isConnected) return;
14855
+ const trigger = anchor.getBoundingClientRect();
14856
+ if (!trigger || (trigger.width <= 0 && trigger.height <= 0)) return;
14857
+ const measured = popup.getBoundingClientRect();
14858
+ const vw = typeof window !== "undefined" ? (window.innerWidth || 0) : 0;
14859
+ const vh = typeof window !== "undefined" ? (window.innerHeight || 0) : 0;
14860
+ setPosition(placePluginChipPopover(trigger, measured.width || 192, measured.height || 36, { width: vw, height: vh }));
14861
+ };
14862
+ measure();
14863
+ const observer = typeof ResizeObserver === "function" ? new ResizeObserver(measure) : null;
14864
+ observer?.observe(popup);
14865
+ const detach = session.attach(popup, anchor);
14866
+ return () => {
14867
+ observer?.disconnect();
14868
+ detach();
14869
+ if (ownsDescribedBy && anchor.getAttribute("aria-describedby") === "uph-at-plugin-hover-popover") {
14870
+ anchor.removeAttribute("aria-describedby");
14871
+ }
14872
+ };
14873
+ }, [hovered, session]);
14874
+
14875
+ const viewContent = hovered || lastContentRef.current;
14876
+ return h("div", {
14877
+ id: "uph-at-plugin-hover-popover",
14878
+ ref: popRef,
14879
+ role: "tooltip",
14880
+ className: "cpm-at-plugin-popover" + (isDark ? " cpm-dark" : ""),
14881
+ "data-placement": position?.placement || "top",
14882
+ "data-unresolved": viewContent.resolved === false ? "true" : undefined,
14883
+ style: {
14884
+ left: `${position?.left ?? 12}px`,
14885
+ top: `${position?.top ?? 12}px`,
14886
+ visibility: hovered && position ? "visible" : "hidden",
14887
+ pointerEvents: !hovered ? "none" : undefined,
14888
+ transformOrigin: position ? `${position.originX}px ${position.originY}` : "50% 100%",
14889
+ },
14890
+ onWheel: (e) => e.stopPropagation(),
14891
+ onScroll: (e) => e.stopPropagation(),
14892
+ },
14893
+ h("p", { className: "cpm-at-plugin-popover-desc" }, viewContent.description)
14894
+ );
14895
+ }
14896
+
14897
+ // Syncs DSH Lexical composer chips (`[data-composer-chip="plugins"]`): strips browser `title`,
14898
+ // replaces the default `@` marker with the crisp plugin icon without stretching line-height,
14899
+ // and shares one top-layer frosted glass description popover across composer + message chips.
14900
+ if (typeof document !== "undefined") {
14901
+ const chipIds = new WeakMap();
14902
+ const ownedSlots = new WeakSet();
14903
+ const selfRemovedSlots = new WeakSet();
14904
+ let nextChipId = 1;
14905
+ let knownComposerEl = null;
14906
+ let syncQueued = false;
14907
+ let blockDisposed = false;
14908
+ let activeOverlayState = { chips: [], hovered: null, isDark: store.isDark() };
14909
+ let setOverlayState = null;
14910
+ let hoverSession = null;
14911
+
14912
+ const getChipId = (el) => {
14913
+ let id = chipIds.get(el);
14914
+ if (!id) {
14915
+ id = `chip-${nextChipId++}`;
14916
+ chipIds.set(el, id);
14917
+ }
14918
+ return id;
14919
+ };
14920
+
14921
+ const stripNativeTitle = (el) => {
14922
+ if (el.hasAttribute?.("title")) el.removeAttribute("title");
14923
+ if (typeof el.querySelectorAll === "function") {
14924
+ const titled = el.querySelectorAll("[title]");
14925
+ for (let i = 0; i < titled.length; i++) titled[i].removeAttribute("title");
14926
+ }
14927
+ };
14928
+
14929
+ const readComposerChipLabel = (el) => {
14930
+ const children = Array.from(el.children || []);
14931
+ const reactSpan = children.find((c) => !c.hasAttribute?.("data-uph-chip-icon"));
14932
+ if (!reactSpan) return String(el.textContent || "").replace(/^@/, "").trim();
14933
+ const reactChildren = Array.from(reactSpan.children || []);
14934
+ if (reactChildren.length >= 2) {
14935
+ return String(reactChildren[reactChildren.length - 1]?.textContent || "").trim();
14936
+ }
14937
+ return String(reactSpan.textContent || "").replace(/^@/, "").trim();
14938
+ };
14939
+
14940
+ const syncComposerChips = () => {
14941
+ syncQueued = false;
14942
+ if (blockDisposed) return;
14943
+ const nodes = typeof document.querySelectorAll === "function"
14944
+ ? Array.from(document.querySelectorAll('[data-composer-chip="plugins"]'))
14945
+ : [];
14946
+ if (nodes.length > 0 && !store.isHydrated()) store.warm();
14947
+
14948
+ const nextChips = [];
14949
+ for (const el of nodes) {
14950
+ stripNativeTitle(el);
14951
+ const label = readComposerChipLabel(el);
14952
+ const reference = readComposerPluginReference(el, store.getByLowerName());
14953
+ const prevName = el.dataset?.uphPluginName || el.getAttribute?.("data-uph-plugin-name") || "";
14954
+ const prevLabel = el.dataset?.uphPluginLabel || el.getAttribute?.("data-uph-plugin-label") || "";
14955
+ const reusedForDifferentLabel = Boolean(prevLabel && label && prevLabel.toLowerCase() !== label.toLowerCase());
14956
+ let live = (prevName && !reusedForDifferentLabel)
14957
+ ? (store.getByLowerName().get(prevName.toLowerCase()) || null)
14958
+ : null;
14959
+ if (reference) {
14960
+ live = store.getByLowerName().get(reference.data.name.toLowerCase()) || null;
14961
+ } else if (!live) {
14962
+ live = store.resolveChipPlugin({ label, consumePick: true });
14963
+ }
14964
+
14965
+ const existingSlots = Array.from(el.children || []).filter((c) => c.hasAttribute?.("data-uph-chip-icon"));
14966
+ let ownedSlot = existingSlots.find((c) => ownedSlots.has(c)) || null;
14967
+ for (let i = 0; i < existingSlots.length; i++) {
14968
+ if (existingSlots[i] !== ownedSlot) {
14969
+ selfRemovedSlots.add(existingSlots[i]);
14970
+ existingSlots[i].remove?.();
14971
+ }
14972
+ }
14973
+ if (live) {
14974
+ if (el.dataset) {
14975
+ el.dataset.uphPluginResolved = "true";
14976
+ el.dataset.uphPluginName = live.name;
14977
+ el.dataset.uphPluginLabel = label || live.displayName || live.name;
14978
+ } else {
14979
+ el.setAttribute("data-uph-plugin-resolved", "true");
14980
+ el.setAttribute("data-uph-plugin-name", live.name);
14981
+ el.setAttribute("data-uph-plugin-label", label || live.displayName || live.name);
14982
+ }
14983
+ let iconSlot = ownedSlot;
14984
+ if (!iconSlot && typeof document.createElement === "function") {
14985
+ iconSlot = document.createElement("span");
14986
+ iconSlot.className = "cpm-at-plugin-chip-icon-wrap";
14987
+ iconSlot.setAttribute("data-uph-chip-icon", "");
14988
+ iconSlot.setAttribute("aria-hidden", "true");
14989
+ ownedSlots.add(iconSlot);
14990
+ el.prepend(iconSlot);
14991
+ } else if (iconSlot && el.children?.[0] !== iconSlot && typeof el.prepend === "function") {
14992
+ el.prepend(iconSlot);
14993
+ }
14994
+ if (iconSlot) {
14995
+ nextChips.push({ key: getChipId(el), chipEl: el, iconSlot, plugin: live });
14996
+ }
14997
+ } else {
14998
+ if (el.dataset) {
14999
+ delete el.dataset.uphPluginResolved;
15000
+ el.dataset.uphPluginName = "";
15001
+ el.dataset.uphPluginLabel = label;
15002
+ } else {
15003
+ el.removeAttribute?.("data-uph-plugin-resolved");
15004
+ el.setAttribute?.("data-uph-plugin-name", "");
15005
+ el.setAttribute?.("data-uph-plugin-label", label);
15006
+ }
15007
+ if (ownedSlot) {
15008
+ selfRemovedSlots.add(ownedSlot);
15009
+ ownedSlot.remove();
15010
+ }
15011
+ }
15012
+ }
15013
+
15014
+ const dark = (nextChips.length > 0 || activeOverlayState.chips.length > 0 || Boolean(activeOverlayState.hovered))
15015
+ ? store.isDark()
15016
+ : activeOverlayState.isDark;
15017
+ const sameChips = activeOverlayState.isDark === dark &&
15018
+ activeOverlayState.chips.length === nextChips.length &&
15019
+ activeOverlayState.chips.every((prev, i) => (
15020
+ prev.chipEl === nextChips[i].chipEl &&
15021
+ prev.iconSlot === nextChips[i].iconSlot &&
15022
+ prev.plugin === nextChips[i].plugin
15023
+ ));
15024
+ if (!sameChips) {
15025
+ activeOverlayState = { ...activeOverlayState, chips: nextChips, isDark: dark };
15026
+ setOverlayState?.(activeOverlayState);
15027
+ }
15028
+ if (activeOverlayState.hovered?.anchor && !activeOverlayState.hovered.anchor.isConnected) {
15029
+ hoverSession?.dismiss();
15030
+ }
15031
+ };
15032
+
15033
+ const scheduleChipSync = () => {
15034
+ if (blockDisposed || syncQueued) return;
15035
+ syncQueued = true;
15036
+ if (typeof queueMicrotask === "function") queueMicrotask(syncComposerChips);
15037
+ else Promise.resolve().then(syncComposerChips);
15038
+ };
15039
+
15040
+ const buildChipHoverPayload = (anchor) => {
15041
+ const name = anchor.dataset?.uphPluginName || anchor.getAttribute?.("data-uph-plugin-name") || "";
15042
+ const label = anchor.dataset?.uphPluginLabel || anchor.getAttribute?.("data-uph-plugin-label") || "";
15043
+ const live = store.resolveChipPlugin({ name, label });
15044
+ return live
15045
+ ? { name: live.name, description: store.getDescription(live, true), resolved: true }
15046
+ : { name, description: store.getDescription(null, false), resolved: false };
15047
+ };
15048
+
15049
+ hoverSession = createHoverSession({
15050
+ initialDelay: 160,
15051
+ onChange(next) {
15052
+ if (blockDisposed) return;
15053
+ activeOverlayState = { ...activeOverlayState, hovered: next, isDark: store.isDark() };
15054
+ setOverlayState?.(activeOverlayState);
15055
+ },
15056
+ });
15057
+
15058
+ const findPluginChipAnchor = (target) => (
15059
+ target?.closest?.('[data-composer-chip="plugins"], .cpm-at-plugin-chip') || null
15060
+ );
15061
+
15062
+ const onPointerOver = (event) => {
15063
+ if (blockDisposed || event.pointerType === "touch") return;
15064
+ const anchor = findPluginChipAnchor(event.target);
15065
+ if (!anchor) return;
15066
+ hoverSession.enter(
15067
+ buildChipHoverPayload(anchor),
15068
+ anchor,
15069
+ { x: event.clientX, y: event.clientY, buttons: event.buttons },
15070
+ false
15071
+ );
15072
+ };
15073
+
15074
+ const onFocusIn = (event) => {
15075
+ if (blockDisposed) return;
15076
+ const anchor = findPluginChipAnchor(event.target);
15077
+ if (!anchor) return;
15078
+ if (anchor === document.activeElement || anchor.contains?.(document.activeElement)) {
15079
+ hoverSession.enter(buildChipHoverPayload(anchor), anchor, null, true);
15080
+ }
15081
+ };
15082
+
15083
+ const onComposerKeyDown = (event) => {
15084
+ if (blockDisposed || !activeOverlayState.hovered) return;
15085
+ if (event.key === "Shift" || event.key === "Control" || event.key === "Alt" || event.key === "Meta") return;
15086
+ if (event.target?.closest?.("[data-composer-input]")) {
15087
+ hoverSession.dismiss();
15088
+ }
15089
+ };
15090
+
15091
+ const updateDarkOverlayState = () => {
15092
+ if (blockDisposed) return;
15093
+ const dark = store.isDark();
15094
+ if (dark !== activeOverlayState.isDark) {
15095
+ activeOverlayState = { ...activeOverlayState, isDark: dark };
15096
+ setOverlayState?.(activeOverlayState);
15097
+ }
15098
+ };
15099
+
15100
+ const isSelfOwnedIconMutation = (m) => {
15101
+ if (m.type !== "childList") return false;
15102
+ if (m.target?.getAttribute?.("data-composer-chip") !== "plugins") return false;
15103
+ const addedLen = m.addedNodes?.length || 0;
15104
+ const removedLen = m.removedNodes?.length || 0;
15105
+ if (addedLen === 0 && removedLen === 0) return false;
15106
+ for (let i = 0; i < addedLen; i++) {
15107
+ if (!ownedSlots.has(m.addedNodes[i])) return false;
15108
+ }
15109
+ for (let i = 0; i < removedLen; i++) {
15110
+ const rem = m.removedNodes[i];
15111
+ if (!selfRemovedSlots.has(rem) && !(addedLen > 0 && ownedSlots.has(rem))) return false;
15112
+ }
15113
+ return true;
15114
+ };
15115
+
15116
+ let domObserver = null;
15117
+ if (typeof MutationObserver === "function" && document.body) {
15118
+ knownComposerEl = document.querySelector?.("[data-composer-input]") || null;
15119
+ domObserver = new MutationObserver((mutations) => {
15120
+ if (blockDisposed) return;
15121
+ let needSync = false;
15122
+ let hasRemovals = false;
15123
+ let composerConnected = Boolean(knownComposerEl?.isConnected);
15124
+ let lookedUpComposer = false;
15125
+ const ensureComposer = () => {
15126
+ if (composerConnected) return knownComposerEl;
15127
+ if (!lookedUpComposer) {
15128
+ lookedUpComposer = true;
15129
+ knownComposerEl = document.querySelector?.("[data-composer-input]") || null;
15130
+ composerConnected = Boolean(knownComposerEl?.isConnected);
15131
+ if (composerConnected) needSync = true;
15132
+ }
15133
+ return composerConnected ? knownComposerEl : null;
15134
+ };
15135
+ for (const m of mutations) {
15136
+ if (m.target?.closest?.("[data-uph-chip-icon]")) continue;
15137
+ if (isSelfOwnedIconMutation(m)) continue;
15138
+ if (m.type === "attributes") {
15139
+ const tgt = m.target;
15140
+ if (tgt?.hasAttribute?.("title") && tgt.closest?.('[data-composer-chip="plugins"]')) {
15141
+ tgt.removeAttribute("title");
15142
+ }
15143
+ continue;
15144
+ }
15145
+ if (m.type === "childList") {
15146
+ if (m.removedNodes.length > 0) hasRemovals = true;
15147
+ if (composerConnected && knownComposerEl.contains(m.target)) {
15148
+ needSync = true;
15149
+ continue;
15150
+ }
15151
+ let hasAddedElement = false;
15152
+ for (let i = 0; i < m.addedNodes.length; i++) {
15153
+ const added = m.addedNodes[i];
15154
+ if (added?.nodeType !== 1) continue;
15155
+ hasAddedElement = true;
15156
+ if (
15157
+ added.getAttribute?.("data-composer-chip") === "plugins" ||
15158
+ added.getAttribute?.("data-composer-input") !== null ||
15159
+ added.querySelector?.('[data-composer-chip="plugins"]')
15160
+ ) {
15161
+ needSync = true;
15162
+ break;
15163
+ }
15164
+ }
15165
+ if (!composerConnected && hasAddedElement && !needSync) {
15166
+ ensureComposer();
15167
+ }
15168
+ }
15169
+ }
15170
+ if (hasRemovals) {
15171
+ if (activeOverlayState.hovered?.anchor && !activeOverlayState.hovered.anchor.isConnected) {
15172
+ hoverSession?.dismiss();
15173
+ }
15174
+ if (!needSync && activeOverlayState.chips.some((c) => !c.chipEl.isConnected)) {
15175
+ needSync = true;
15176
+ }
15177
+ }
15178
+ if (needSync) scheduleChipSync();
15179
+ });
15180
+ domObserver.observe(document.body, {
15181
+ childList: true,
15182
+ subtree: true,
15183
+ attributes: true,
15184
+ attributeFilter: ["title"],
15185
+ });
15186
+ disposers.push(() => domObserver.disconnect());
15187
+ }
15188
+
15189
+ disposers.push(store.subscribeTheme(updateDarkOverlayState));
15190
+
15191
+ if (typeof document.addEventListener === "function") {
15192
+ const onPaste = (event) => pasteAtPluginReferences(event, store.getByLowerName());
15193
+ document.addEventListener("paste", onPaste, true);
15194
+ document.addEventListener("pointerover", onPointerOver, true);
15195
+ document.addEventListener("focusin", onFocusIn, true);
15196
+ document.addEventListener("keydown", onComposerKeyDown, true);
15197
+ disposers.push(() => {
15198
+ document.removeEventListener("paste", onPaste, true);
15199
+ document.removeEventListener("pointerover", onPointerOver, true);
15200
+ document.removeEventListener("focusin", onFocusIn, true);
15201
+ document.removeEventListener("keydown", onComposerKeyDown, true);
15202
+ });
15203
+ }
15204
+
15205
+ if (typeof window !== "undefined" && typeof window.addEventListener === "function" && typeof document.addEventListener === "function") {
15206
+ const unbindHover = hoverSession.bind(document, window);
15207
+ disposers.push(unbindHover);
15208
+ } else {
15209
+ disposers.push(() => hoverSession.dismiss(false));
15210
+ }
15211
+
15212
+ const offStoreSync = store.subscribe(() => {
15213
+ if (blockDisposed) return;
15214
+ syncComposerChips();
15215
+ const curHovered = activeOverlayState.hovered;
15216
+ if (curHovered?.anchor?.isConnected) {
15217
+ const refreshed = buildChipHoverPayload(curHovered.anchor);
15218
+ const dark = store.isDark();
15219
+ if (
15220
+ dark !== activeOverlayState.isDark ||
15221
+ refreshed.name !== curHovered.name ||
15222
+ refreshed.description !== curHovered.description ||
15223
+ refreshed.resolved !== curHovered.resolved
15224
+ ) {
15225
+ activeOverlayState = {
15226
+ ...activeOverlayState,
15227
+ isDark: dark,
15228
+ hovered: { ...curHovered, ...refreshed },
15229
+ };
15230
+ setOverlayState?.(activeOverlayState);
15231
+ }
15232
+ }
15233
+ });
15234
+ disposers.push(offStoreSync);
15235
+
15236
+ if (ReactDOM?.createPortal && ReactDOMClient?.createRoot && document.body && typeof document.createElement === "function") {
15237
+ const overlayHost = document.createElement("div");
15238
+ overlayHost.setAttribute("data-uph-at-plugins-overlay", "");
15239
+ overlayHost.style.display = "contents";
15240
+ document.body.append(overlayHost);
15241
+
15242
+ function AtPluginsOverlay() {
15243
+ const [overlayState, setLocalState] = useState(activeOverlayState);
15244
+ useEffect(() => {
15245
+ setOverlayState = setLocalState;
15246
+ setLocalState(activeOverlayState);
15247
+ return () => { if (setOverlayState === setLocalState) setOverlayState = null; };
15248
+ }, []);
15249
+ return h(React.Fragment, null,
15250
+ overlayState.chips.map((entry) => (
15251
+ entry.iconSlot?.isConnected
15252
+ ? ReactDOM.createPortal(
15253
+ h("span", { className: "cpm-at-plugin-chip-icon" },
15254
+ h(PluginIcon, { plugin: entry.plugin, isDark: overlayState.isDark, eager: true, preferPreview: true })
15255
+ ),
15256
+ entry.iconSlot,
15257
+ entry.key
15258
+ )
15259
+ : null
15260
+ )),
15261
+ h(PluginChipHoverPopover, {
15262
+ hovered: overlayState.hovered,
15263
+ isDark: overlayState.isDark,
15264
+ session: hoverSession,
15265
+ })
15266
+ );
15267
+ }
15268
+
15269
+ const overlayRoot = ReactDOMClient.createRoot(overlayHost);
15270
+ overlayRoot.render(h(AtPluginsOverlay));
15271
+ disposers.push(() => {
15272
+ setOverlayState = null;
15273
+ activeOverlayState = { chips: [], hovered: null, isDark: false };
15274
+ cleanupStaleAtPluginDom();
15275
+ try { overlayRoot.unmount(); } catch {}
15276
+ try { overlayHost.remove(); } catch {}
15277
+ });
15278
+ } else {
15279
+ disposers.push(() => cleanupStaleAtPluginDom());
15280
+ }
15281
+ disposers.push(() => {
15282
+ blockDisposed = true;
15283
+ syncQueued = false;
15284
+ });
15285
+
15286
+ syncComposerChips();
15287
+ }
15288
+
15289
+ const triggerSource = {
15290
+ trigger: "@",
15291
+ name: "plugins",
15292
+ order: -1,
15293
+ showGroupTitle: false,
15294
+ warm() {
15295
+ store.warm();
15296
+ },
15297
+ lexicon() {
15298
+ return store.lexicon();
15299
+ },
15300
+ subscribeLexicon(_session, listener) {
15301
+ return store.subscribe(listener);
15302
+ },
15303
+ candidates(_session, req) {
15304
+ return store.candidates(req);
15305
+ },
15306
+ onPick({ candidate }) {
15307
+ const picked = parseAtPluginCandidateValue(candidate?.value);
15308
+ if (!picked) return undefined;
15309
+ store.recordPick(picked.name, picked.displayName);
15310
+ const mention = formatAtPluginMention(picked.name, picked.displayName);
15311
+ return { insert: atPluginReference(mention, picked.displayName) };
15312
+ },
15313
+ codec: {
15314
+ clipboardText: (ref) => ref,
15315
+ serialize: (ref) => Promise.resolve(ref),
15316
+ },
15317
+ };
15318
+
15319
+ collectDisposer(ctx.inject?.(["inputTriggers"], (hostCtx) => {
15320
+ if (typeof hostCtx?.inputTriggers?.registerSource !== "function") return;
15321
+ hostCtx.effect?.(() => hostCtx.inputTriggers.registerSource(triggerSource), "universal-plugin-hub: @ plugins trigger");
15322
+ }));
15323
+
15324
+ collectDisposer(ctx.inject?.(["uiConversation"], (hostCtx) => {
15325
+ const registerRule = () => hostCtx?.uiConversation?.userText?.register?.({
15326
+ id: "uph-plugin",
15327
+ order: 15,
15328
+ match(text, from) {
15329
+ return matchAtPluginMention(text, from, store.getByLowerName());
15330
+ },
15331
+ });
15332
+ if (typeof hostCtx?.uiConversation?.userText?.register !== "function") return;
15333
+ hostCtx.effect?.(() => {
15334
+ let effectDisposed = false;
15335
+ let offRule = registerRule();
15336
+ let prevLexKey = store.lexiconKey();
15337
+ const offSub = store.subscribe(() => {
15338
+ if (effectDisposed) return;
15339
+ const nextLexKey = store.lexiconKey();
15340
+ if (nextLexKey === prevLexKey) return;
15341
+ prevLexKey = nextLexKey;
15342
+ try { offRule?.(); } catch {}
15343
+ offRule = registerRule();
15344
+ });
15345
+ return () => {
15346
+ effectDisposed = true;
15347
+ offSub();
15348
+ try { offRule?.(); } catch {}
15349
+ };
15350
+ }, "universal-plugin-hub: @ plugins user-text");
15351
+ }));
15352
+
15353
+ if (typeof ctx.slots?.inject === "function") {
15354
+ const offSlotInject = ctx.slots.inject("conversation.user.text.node", () => ctx.slots.register({
15355
+ name: "conversation.user.text.node",
15356
+ key: "uph-plugin",
15357
+ priority: 100,
15358
+ }, PluginMentionChip));
15359
+ collectDisposer(offSlotInject);
15360
+ } else if (typeof ctx.slots?.register === "function") {
15361
+ const offNodeSlot = ctx.slots.register({
15362
+ name: "conversation.user.text.node",
15363
+ key: "uph-plugin",
15364
+ priority: 100,
15365
+ }, PluginMentionChip);
15366
+ collectDisposer(offNodeSlot);
15367
+ }
15368
+
15369
+ return disposeAll;
15370
+ } catch (err) {
15371
+ disposeAll();
15372
+ throw err;
15373
+ }
15374
+ }
15375
+
13138
15376
  const name = "universal-plugin-hub";
13139
15377
  const inject = ["slots", "theme"];
13140
15378
 
@@ -13145,6 +15383,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
13145
15383
  iconsReady = dispose.ready;
13146
15384
  return dispose;
13147
15385
  }, "universal-plugin-hub: tool call icons");
15386
+ ctx.effect?.(() => installAtPlugins(ctx), "universal-plugin-hub: @ plugins");
13148
15387
  ctx.slots.inject("sidebar.panellist", () => ctx.slots.register({
13149
15388
  name: "sidebar.panellist",
13150
15389
  id: "universal-plugin-hub",