universal-plugin-hub 1.5.1 → 1.6.0

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
@@ -599,6 +599,9 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
599
599
  --cpm-toast-shadow: 0 8px 30px rgba(0, 0, 0, 0.12), 0 2px 8px rgba(0, 0, 0, 0.06);
600
600
  --cpm-scroll-thumb: rgba(0, 0, 0, 0.18);
601
601
  --cpm-scroll-thumb-hover: rgba(0, 0, 0, 0.3);
602
+ --cpm-dup-surface: rgba(15, 23, 42, 0.032);
603
+ --cpm-dup-border: rgba(15, 23, 42, 0.08);
604
+ --cpm-dup-new-text: #1d4ed8;
602
605
 
603
606
  width: 100%;
604
607
  height: 100%;
@@ -662,6 +665,9 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
662
665
  --cpm-toast-shadow: 0 8px 30px rgba(0, 0, 0, 0.6);
663
666
  --cpm-scroll-thumb: rgba(255, 255, 255, 0.22);
664
667
  --cpm-scroll-thumb-hover: rgba(255, 255, 255, 0.36);
668
+ --cpm-dup-surface: rgba(255, 255, 255, 0.038);
669
+ --cpm-dup-border: rgba(255, 255, 255, 0.085);
670
+ --cpm-dup-new-text: #60a5fa;
665
671
  }
666
672
 
667
673
  .cpm-root,
@@ -693,7 +699,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
693
699
  /* 24px inset, matching the list's own padding. The bar is not a scroll
694
700
  container, so it carries no scrollbar reserve of its own; the list's
695
701
  symmetric gutter below keeps the two on one axis instead. */
696
- padding: 14px 24px 10px 24px;
702
+ padding: 14px 24px 0;
697
703
  background: var(--cpm-bg);
698
704
  width: 100%;
699
705
  box-sizing: border-box;
@@ -755,6 +761,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
755
761
  z-index: 10;
756
762
  }
757
763
  .cpm-topbar-left {
764
+ position: relative;
758
765
  display: flex;
759
766
  align-items: center;
760
767
  gap: 2px;
@@ -764,6 +771,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
764
771
  min-width: 0;
765
772
  scrollbar-width: none;
766
773
  -ms-overflow-style: none;
774
+ scroll-padding-inline: 28px;
767
775
  padding: 4px 0;
768
776
  }
769
777
  .cpm-topbar-left::-webkit-scrollbar {
@@ -957,13 +965,17 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
957
965
  z-index: 10;
958
966
  background: transparent;
959
967
  }
968
+ .cpm-root .cpm-tab-close {
969
+ border-radius: 50%;
970
+ corner-shape: initial;
971
+ }
960
972
  .cpm-tab-close {
961
973
  display: inline-flex;
962
974
  align-items: center;
963
975
  justify-content: center;
964
976
  width: 14px;
965
977
  height: 14px;
966
- border-radius: 50%;
978
+ flex-shrink: 0;
967
979
  border: 1px solid var(--cpm-border);
968
980
  background: var(--cpm-card-bg, #fff);
969
981
  color: var(--cpm-muted);
@@ -1100,9 +1112,8 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
1100
1112
  .cpm-grid, .cpm-grid-container {
1101
1113
  flex: 1;
1102
1114
  overflow-y: auto;
1103
- /* The top bar's last row already ends ~10px above the rule under it, so the
1104
- full 16px grid inset left the first card floating well clear of it. */
1105
- padding: 10px 24px 28px 24px;
1115
+ /* The first row's inset scrolls away with the content. */
1116
+ padding: 20px 24px 28px;
1106
1117
  box-sizing: border-box;
1107
1118
  width: 100%;
1108
1119
  /* Reserve the scrollbar track on every list surface. Centered columns are
@@ -1266,14 +1277,14 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
1266
1277
  overflow: hidden;
1267
1278
  text-overflow: ellipsis;
1268
1279
  }
1269
- .cpm-root :is(.cpm-card-pill, .cpm-toggle) {
1280
+ .cpm-root :is(.cpm-card-pill, .cpm-toggle, .cpm-badge.is-capsule) {
1270
1281
  border-radius: 9999px;
1271
1282
  corner-shape: initial;
1272
1283
  }
1273
1284
  @supports (border-shape: shape(from 0 0, line to 100% 100%, close)) {
1274
1285
  /* Each end keeps its middle 120° of circular arc. The cubic shoulders
1275
1286
  match the tangent and curvature of the straight edge and the arc. */
1276
- .cpm-root :is(.cpm-card-pill, .cpm-toggle) {
1287
+ .cpm-root :is(.cpm-card-pill, .cpm-toggle, .cpm-badge.is-capsule) {
1277
1288
  --cap-start: calc(var(--cap-radius) * 1.1);
1278
1289
  --cap-control-flat: calc(var(--cap-radius) * .947441);
1279
1290
  --cap-control-arc: calc(var(--cap-radius) * .732051);
@@ -1382,7 +1393,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
1382
1393
  .cpm-detail {
1383
1394
  flex: 1;
1384
1395
  overflow-y: auto;
1385
- padding: 11px 24px 28px 24px;
1396
+ padding: 21px 24px 28px;
1386
1397
  width: 100%;
1387
1398
  display: flex;
1388
1399
  flex-direction: column;
@@ -1561,18 +1572,38 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
1561
1572
  font-weight: 700;
1562
1573
  color: var(--cpm-text);
1563
1574
  }
1575
+ .cpm-root .cpm-badge {
1576
+ border-radius: 50%;
1577
+ corner-shape: initial;
1578
+ }
1564
1579
  .cpm-badge {
1580
+ width: 20px;
1565
1581
  min-width: 20px;
1566
1582
  height: 20px;
1567
- border-radius: 50%;
1568
1583
  background: var(--cpm-pill-bg);
1569
1584
  border: 1px solid var(--cpm-pill-border);
1570
1585
  display: inline-flex;
1571
1586
  align-items: center;
1572
1587
  justify-content: center;
1588
+ flex-shrink: 0;
1573
1589
  font-size: 11.5px;
1574
- padding: 0 5px;
1590
+ font-weight: 500;
1591
+ line-height: 1;
1592
+ padding: 0;
1575
1593
  color: var(--cpm-text);
1594
+ white-space: nowrap;
1595
+ }
1596
+ .cpm-badge.is-capsule {
1597
+ --cap-radius: 9.5px;
1598
+ width: auto;
1599
+ min-width: 26px;
1600
+ padding: 0 6px;
1601
+ }
1602
+ .cpm-badge-num {
1603
+ display: block;
1604
+ line-height: 1;
1605
+ font-variant-numeric: tabular-nums;
1606
+ text-box: trim-both cap alphabetic;
1576
1607
  }
1577
1608
  .cpm-section-sub {
1578
1609
  color: var(--cpm-muted);
@@ -1647,7 +1678,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
1647
1678
  .cpm-manage {
1648
1679
  flex: 1;
1649
1680
  overflow-y: auto;
1650
- padding: 11px 24px 28px 24px;
1681
+ padding: 21px 24px 28px;
1651
1682
  width: 100%;
1652
1683
  background: var(--cpm-bg);
1653
1684
  display: flex;
@@ -1812,20 +1843,36 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
1812
1843
  position: absolute;
1813
1844
  right: 0;
1814
1845
  top: 34px;
1815
- background: var(--cpm-modal-bg);
1816
- border: 1px solid var(--cpm-modal-border);
1817
- border-radius: var(--dsw-radius-md, 12px);
1818
- padding: 5px;
1819
1846
  z-index: 100;
1820
1847
  min-width: 120px;
1821
- box-shadow: var(--cpm-shadow);
1822
- backdrop-filter: blur(16px);
1823
- animation: cpmPopIn 0.15s cubic-bezier(0.16, 1, 0.3, 1) forwards;
1824
1848
  transform-origin: top right;
1825
1849
  }
1850
+ .cpm-menu-pop,
1851
+ .cpm-select-menu {
1852
+ background: rgba(255, 255, 255, 0.72);
1853
+ backdrop-filter: blur(20px) saturate(180%);
1854
+ -webkit-backdrop-filter: blur(20px) saturate(180%);
1855
+ border: 1px solid rgba(0, 0, 0, 0.08);
1856
+ border-radius: var(--dsw-radius-lg, 16px);
1857
+ corner-shape: squircle;
1858
+ padding: 5px;
1859
+ box-shadow: 0 16px 36px -4px rgba(0, 0, 0, 0.10), 0 2px 8px rgba(0, 0, 0, 0.04);
1860
+ animation: cpmPopIn 0.15s cubic-bezier(0.16, 1, 0.3, 1) forwards;
1861
+ }
1862
+ .cpm-dark :is(.cpm-menu-pop, .cpm-select-menu) {
1863
+ background: rgba(32, 32, 35, 0.75);
1864
+ backdrop-filter: blur(22px) saturate(180%);
1865
+ -webkit-backdrop-filter: blur(22px) saturate(180%);
1866
+ border: 1px solid var(--cpm-modal-border);
1867
+ box-shadow: var(--cpm-shadow);
1868
+ }
1869
+ .cpm-menu-item,
1870
+ .cpm-select-item {
1871
+ border-radius: calc(var(--dsw-radius-lg, 16px) - 5px);
1872
+ corner-shape: squircle;
1873
+ }
1826
1874
  .cpm-menu-item {
1827
1875
  padding: 7px 10px;
1828
- border-radius: var(--dsw-radius-md, 12px);
1829
1876
  font-size: 12.5px;
1830
1877
  cursor: pointer;
1831
1878
  color: var(--cpm-text);
@@ -2451,50 +2498,46 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
2451
2498
  display: block;
2452
2499
  width: 100%;
2453
2500
  height: 6px;
2454
- border: none;
2455
- border-radius: 999px;
2501
+ border: 0 solid;
2502
+ --progress-bar-radius: 999px;
2503
+ --progress-bar-indeterminate-size: 32%;
2504
+ --progress-bar-indeterminate-animation-duration: 1.4s;
2505
+ border-radius: var(--progress-bar-radius);
2456
2506
  background: rgba(15, 23, 42, 0.1);
2457
- overflow: hidden;
2507
+ overflow: clip;
2458
2508
  container-type: inline-size;
2459
2509
  }
2460
2510
  .cpm-dark .cpm-upload-progress {
2461
2511
  background: rgba(255, 255, 255, 0.12);
2462
2512
  }
2463
- .cpm-upload-progress::-webkit-progress-bar {
2464
- background: rgba(15, 23, 42, 0.1);
2465
- border-radius: 999px;
2513
+ .cpm-upload-progress:dir(rtl) {
2514
+ --progress-bar-indeterminate-animation: progress-bar-indeterminate var(--progress-bar-indeterminate-animation-duration) infinite linear reverse;
2466
2515
  }
2467
- .cpm-dark .cpm-upload-progress::-webkit-progress-bar {
2468
- background: rgba(255, 255, 255, 0.12);
2516
+ .cpm-upload-progress:indeterminate {
2517
+ --progress-bar-animation: var(--progress-bar-indeterminate-animation, progress-bar-indeterminate var(--progress-bar-indeterminate-animation-duration) infinite linear);
2518
+ }
2519
+ .cpm-upload-progress::-webkit-progress-bar {
2520
+ background: transparent;
2469
2521
  }
2470
2522
  .cpm-upload-progress::-webkit-progress-value {
2471
2523
  background: var(--cpm-accent);
2472
- border-radius: 999px;
2473
- transition: inline-size 120ms linear;
2524
+ border-radius: var(--progress-bar-radius);
2525
+ transition: inline-size 180ms cubic-bezier(0.22, 1, 0.36, 1);
2526
+ animation: var(--progress-bar-animation, revert-rule);
2474
2527
  }
2475
2528
  .cpm-upload-progress::-moz-progress-bar {
2476
2529
  background: var(--cpm-accent);
2477
- border-radius: 999px;
2478
- }
2479
- @keyframes cpm-upload-sweep {
2480
- 0% { background-position: -125% 0; }
2481
- 100% { background-position: 225% 0; }
2482
- }
2483
- .cpm-upload-progress:indeterminate::-webkit-progress-bar {
2484
- background-color: rgba(15, 23, 42, 0.1);
2485
- background-image: linear-gradient(90deg, transparent 0%, var(--cpm-accent) 45%, #60a5fa 60%, transparent 100%);
2486
- background-size: 55% 100%;
2487
- background-repeat: no-repeat;
2488
- animation: cpm-upload-sweep 1.35s ease-in-out infinite;
2489
- }
2490
- .cpm-dark .cpm-upload-progress:indeterminate::-webkit-progress-bar {
2491
- background-color: rgba(255, 255, 255, 0.12);
2492
- }
2493
- .cpm-upload-progress:indeterminate::-moz-progress-bar {
2494
- background-image: linear-gradient(90deg, transparent 0%, var(--cpm-accent) 45%, #60a5fa 60%, transparent 100%);
2495
- background-size: 55% 100%;
2496
- background-repeat: no-repeat;
2497
- animation: cpm-upload-sweep 1.35s ease-in-out infinite;
2530
+ border-radius: var(--progress-bar-radius);
2531
+ transition: inline-size 180ms cubic-bezier(0.22, 1, 0.36, 1);
2532
+ animation: var(--progress-bar-animation, revert-rule);
2533
+ }
2534
+ @keyframes progress-bar-indeterminate {
2535
+ from, to {
2536
+ inline-size: var(--progress-bar-indeterminate-size);
2537
+ margin-right: auto;
2538
+ }
2539
+ from { translate: -100%; }
2540
+ to { translate: 100cqi; }
2498
2541
  }
2499
2542
  .cpm-upload-status {
2500
2543
  margin-top: 8px;
@@ -2620,44 +2663,114 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
2620
2663
  .cpm-local-preview-card .cpm-card-pill {
2621
2664
  margin-left: 0;
2622
2665
  }
2623
- .cpm-local-dup-card {
2624
- padding: 14px 16px;
2625
- border-radius: var(--dsw-radius-md, 12px);
2626
- background: rgba(245, 158, 11, 0.06);
2627
- border: 1px solid rgba(245, 158, 11, 0.25);
2628
- margin: 12px 0 16px 0;
2666
+ .cpm-dup-title {
2667
+ margin: 0;
2668
+ font-size: 16px;
2669
+ font-weight: 650;
2670
+ letter-spacing: -0.015em;
2671
+ color: var(--cpm-text);
2672
+ }
2673
+ .cpm-dup-body {
2674
+ display: flex;
2675
+ flex-direction: column;
2676
+ gap: 14px;
2677
+ margin: 16px 0 20px;
2678
+ }
2679
+ .cpm-dup-identity {
2680
+ display: flex;
2681
+ align-items: center;
2682
+ gap: 12px;
2683
+ padding-top: 14px;
2684
+ border-top: 1px solid var(--cpm-border);
2629
2685
  }
2630
- .cpm-local-dup-grid {
2686
+ .cpm-dup-name {
2687
+ font-size: 15px;
2688
+ font-weight: 650;
2689
+ color: var(--cpm-text);
2690
+ letter-spacing: -0.01em;
2691
+ line-height: 1.3;
2692
+ min-width: 0;
2693
+ overflow: hidden;
2694
+ text-overflow: ellipsis;
2695
+ white-space: nowrap;
2696
+ }
2697
+ .cpm-dup-compare {
2631
2698
  display: grid;
2632
- grid-template-columns: 1fr 1fr;
2633
- gap: 10px;
2634
- padding: 10px 12px;
2635
- background: var(--cpm-modal-bg);
2636
- border: 1px solid var(--cpm-border);
2637
- border-radius: 8px;
2638
- margin: 10px 0 8px 0;
2699
+ grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr);
2700
+ align-items: center;
2701
+ gap: 14px;
2702
+ padding: 14px 16px;
2703
+ border-radius: 12px;
2704
+ background: var(--cpm-dup-surface);
2705
+ border: 1px solid var(--cpm-dup-border);
2706
+ }
2707
+ .cpm-dup-ver-col {
2708
+ display: flex;
2709
+ flex-direction: column;
2710
+ gap: 3px;
2711
+ min-width: 0;
2712
+ }
2713
+ .cpm-dup-ver-label {
2714
+ font-size: 12px;
2715
+ font-weight: 500;
2716
+ color: var(--cpm-muted);
2717
+ line-height: 1.3;
2718
+ }
2719
+ .cpm-dup-ver-value {
2720
+ font-size: 16px;
2721
+ font-weight: 650;
2722
+ color: var(--cpm-text);
2723
+ font-variant-numeric: tabular-nums;
2724
+ letter-spacing: -0.01em;
2725
+ line-height: 1.3;
2726
+ }
2727
+ .cpm-dup-ver-value.is-new {
2728
+ color: var(--cpm-dup-new-text);
2729
+ }
2730
+ .cpm-dup-ver-sub {
2731
+ font-size: 12px;
2732
+ color: var(--cpm-muted);
2733
+ font-variant-numeric: tabular-nums;
2734
+ line-height: 1.3;
2735
+ }
2736
+ .cpm-dup-arrow {
2737
+ display: inline-flex;
2738
+ align-items: center;
2739
+ justify-content: center;
2740
+ color: var(--cpm-muted);
2741
+ opacity: 0.65;
2742
+ flex-shrink: 0;
2743
+ }
2744
+ .cpm-dup-multi-lead {
2745
+ font-size: 13px;
2746
+ font-weight: 500;
2747
+ color: var(--cpm-text-sub);
2748
+ line-height: 1.45;
2749
+ padding-top: 14px;
2750
+ border-top: 1px solid var(--cpm-border);
2639
2751
  }
2640
2752
  .cpm-local-dup-list {
2641
2753
  list-style: none;
2642
- margin: 10px 0 8px;
2643
- padding: 4px;
2644
- max-height: 156px;
2754
+ margin: 0;
2755
+ padding: 4px 12px;
2756
+ max-height: 180px;
2645
2757
  overflow-y: auto;
2646
- background: var(--cpm-modal-bg);
2647
- border: 1px solid var(--cpm-border);
2648
- border-radius: 8px;
2758
+ background: var(--cpm-dup-surface);
2759
+ border: 1px solid var(--cpm-dup-border);
2760
+ border-radius: 12px;
2649
2761
  display: flex;
2650
2762
  flex-direction: column;
2651
- gap: 4px;
2652
2763
  }
2653
2764
  .cpm-local-dup-item {
2654
2765
  display: flex;
2655
2766
  align-items: center;
2656
2767
  justify-content: space-between;
2657
2768
  gap: 10px;
2658
- padding: 6px 8px;
2659
- border-radius: 6px;
2660
- font-size: 12px;
2769
+ padding: 9px 2px;
2770
+ font-size: 12.5px;
2771
+ }
2772
+ .cpm-local-dup-item:not(:last-child) {
2773
+ border-bottom: 1px solid var(--cpm-border);
2661
2774
  }
2662
2775
  .cpm-local-dup-item-name {
2663
2776
  font-weight: 600;
@@ -2672,25 +2785,13 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
2672
2785
  align-items: center;
2673
2786
  gap: 5px;
2674
2787
  flex-shrink: 0;
2675
- font-size: 11px;
2788
+ font-size: 12px;
2676
2789
  font-variant-numeric: tabular-nums;
2677
2790
  color: var(--cpm-muted);
2678
2791
  }
2679
2792
  .cpm-local-dup-item-new {
2680
2793
  font-weight: 600;
2681
- color: #059669;
2682
- }
2683
- .cpm-dark .cpm-local-dup-item-new {
2684
- color: #34d399;
2685
- }
2686
- .cpm-btn-warning {
2687
- background: #d97706 !important;
2688
- border-color: #d97706 !important;
2689
- color: #ffffff !important;
2690
- }
2691
- .cpm-btn-warning:hover {
2692
- background: #b45309 !important;
2693
- border-color: #b45309 !important;
2794
+ color: var(--cpm-dup-new-text);
2694
2795
  }
2695
2796
 
2696
2797
  .cpm-source-header {
@@ -3557,24 +3658,14 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
3557
3658
  top: calc(100% + 4px);
3558
3659
  left: 0;
3559
3660
  right: 0;
3560
- background: #ffffff;
3561
- border: 1px solid rgba(0, 0, 0, 0.12);
3562
- border-radius: 8px;
3563
- padding: 4px;
3564
3661
  z-index: 10005;
3565
- box-shadow: 0 12px 32px rgba(0, 0, 0, 0.14), 0 2px 8px rgba(0, 0, 0, 0.08);
3566
- }
3567
- .cpm-dark .cpm-select-menu {
3568
- background: #1f1f23;
3569
- border: 1px solid rgba(255, 255, 255, 0.14);
3570
- box-shadow: 0 16px 40px rgba(0, 0, 0, 0.6), 0 4px 12px rgba(0, 0, 0, 0.4);
3662
+ transform-origin: top center;
3571
3663
  }
3572
3664
  .cpm-select-item {
3573
3665
  display: flex;
3574
3666
  align-items: center;
3575
3667
  justify-content: space-between;
3576
3668
  padding: 7px 10px;
3577
- border-radius: 8px;
3578
3669
  font-size: 13px;
3579
3670
  color: #18181b;
3580
3671
  cursor: pointer;
@@ -3959,16 +4050,14 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
3959
4050
  }
3960
4051
 
3961
4052
  .cpm-mcp-tools-panel {
3962
- margin-top: 10px;
3963
- padding: 12px 14px;
3964
- border-radius: 8px;
3965
- background: rgba(0, 0, 0, 0.02);
3966
- border: 1px solid var(--cpm-border);
3967
- animation: cpmToolsIn 0.2s cubic-bezier(0.16, 1, 0.3, 1) forwards;
4053
+ margin-block-start: 12px;
4054
+ padding-block: 0 4px;
4055
+ padding-inline: 0;
3968
4056
  }
3969
- .cpm-dark .cpm-mcp-tools-panel {
3970
- background: rgba(255, 255, 255, 0.03);
3971
- border: 1px solid rgba(255, 255, 255, 0.08);
4057
+ @media (prefers-reduced-motion: no-preference) {
4058
+ .cpm-mcp-tools-panel {
4059
+ animation: cpmToolsIn 0.2s cubic-bezier(0.22, 1, 0.36, 1) forwards;
4060
+ }
3972
4061
  }
3973
4062
  @keyframes cpmToolsIn {
3974
4063
  from {
@@ -4820,6 +4909,10 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
4820
4909
  will-change: opacity;
4821
4910
  transition: opacity 0.1s ease;
4822
4911
  }
4912
+ .cpm-menu-pop,
4913
+ .cpm-select-menu {
4914
+ animation: none;
4915
+ }
4823
4916
  .cpm-tooltip:is(:popover-open, .\\:popover-open, [data-open="true"]) .cpm-tooltip-surface {
4824
4917
  transform: none;
4825
4918
  transition: opacity 0.1s ease;
@@ -4862,9 +4955,9 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
4862
4955
  .cpm-dropzone:hover .cpm-dropzone-icon,
4863
4956
  .cpm-dropzone.is-active .cpm-dropzone-icon,
4864
4957
  .cpm-radio-card:hover { transform: none; }
4958
+ .cpm-upload-progress { --progress-bar-indeterminate-animation-duration: 10s; }
4865
4959
  .cpm-upload-progress::-webkit-progress-value { transition: none; }
4866
- .cpm-upload-progress:indeterminate::-webkit-progress-bar { animation-duration: 10s; }
4867
- .cpm-upload-progress:indeterminate::-moz-progress-bar { animation-duration: 10s; }
4960
+ .cpm-upload-progress::-moz-progress-bar { transition: none; }
4868
4961
  .cpm-upload-dialog .cpm-spin-ring { animation-duration: 3s; }
4869
4962
  }
4870
4963
  @media (prefers-reduced-transparency: reduce) {
@@ -4877,6 +4970,14 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
4877
4970
  .cpm-tooltip.cpm-dark .cpm-tooltip-surface {
4878
4971
  background: #222226;
4879
4972
  }
4973
+ .cpm-root :is(.cpm-menu-pop, .cpm-select-menu) {
4974
+ backdrop-filter: none;
4975
+ -webkit-backdrop-filter: none;
4976
+ background: #ffffff;
4977
+ }
4978
+ .cpm-root.cpm-dark :is(.cpm-menu-pop, .cpm-select-menu) {
4979
+ background: #202023;
4980
+ }
4880
4981
  }
4881
4982
  @media (prefers-contrast: more) {
4882
4983
  .cpm-tooltip-surface {
@@ -4888,6 +4989,14 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
4888
4989
  background: rgba(34, 34, 38, 0.96);
4889
4990
  border-color: rgba(255, 255, 255, 0.34);
4890
4991
  }
4992
+ .cpm-root :is(.cpm-menu-pop, .cpm-select-menu) {
4993
+ background: rgba(255, 255, 255, 0.96);
4994
+ border-color: rgba(0, 0, 0, 0.28);
4995
+ }
4996
+ .cpm-root.cpm-dark :is(.cpm-menu-pop, .cpm-select-menu) {
4997
+ background: rgba(32, 32, 35, 0.96);
4998
+ border-color: rgba(255, 255, 255, 0.34);
4999
+ }
4891
5000
  }
4892
5001
  @media (prefers-reduced-transparency: reduce), (prefers-contrast: more) {
4893
5002
  .cpm-dialog {
@@ -4912,6 +5021,15 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
4912
5021
  border: 1px solid CanvasText;
4913
5022
  box-shadow: none;
4914
5023
  }
5024
+ .cpm-root :is(.cpm-menu-pop, .cpm-select-menu),
5025
+ .cpm-root.cpm-dark :is(.cpm-menu-pop, .cpm-select-menu) {
5026
+ backdrop-filter: none;
5027
+ -webkit-backdrop-filter: none;
5028
+ background: Canvas;
5029
+ color: CanvasText;
5030
+ border: 1px solid CanvasText;
5031
+ box-shadow: none;
5032
+ }
4915
5033
  .cpm-dialog-box, .cpm-source-dialog-box, .cpm-mcp-modal {
4916
5034
  border: 1px solid CanvasText;
4917
5035
  box-shadow: none;
@@ -4963,6 +5081,13 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
4963
5081
  color: ButtonText;
4964
5082
  box-shadow: none;
4965
5083
  }
5084
+ .cpm-dup-compare, .cpm-local-dup-list {
5085
+ border: 1px solid CanvasText;
5086
+ background: Canvas;
5087
+ }
5088
+ .cpm-dup-ver-value.is-new, .cpm-local-dup-item-new {
5089
+ color: Highlight;
5090
+ }
4966
5091
  }
4967
5092
  `;
4968
5093
 
@@ -5040,13 +5165,56 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
5040
5165
  }
5041
5166
 
5042
5167
  // ────────────────────────────── API ──────────────────────────────
5043
- async function api(path, options) {
5168
+ async function api(path, options, onProgress) {
5169
+ const wantsStream = typeof onProgress === "function";
5044
5170
  const res = await fetch("/universal-plugin-hub/api" + path, {
5045
- headers: { "Content-Type": "application/json" },
5046
5171
  ...options,
5172
+ headers: {
5173
+ "Content-Type": "application/json",
5174
+ ...(wantsStream ? { Accept: "application/x-ndjson" } : {}),
5175
+ ...(options?.headers || {}),
5176
+ },
5047
5177
  });
5048
5178
  let body = null;
5049
- try { body = await res.json(); } catch { /* no body */ }
5179
+ const contentType = String(res.headers?.get?.("content-type") || "").toLowerCase();
5180
+ if (res.ok && wantsStream && contentType.includes("application/x-ndjson") && res.body?.getReader) {
5181
+ const reader = res.body.getReader();
5182
+ const decoder = new TextDecoder();
5183
+ let buf = "";
5184
+ let hasResult = false;
5185
+ const processLine = (line) => {
5186
+ const trimmed = line.trim();
5187
+ if (!trimmed) return;
5188
+ const msg = JSON.parse(trimmed);
5189
+ if (msg?.type === "progress") {
5190
+ onProgress(msg);
5191
+ } else if (msg?.type === "result") {
5192
+ hasResult = true;
5193
+ body = msg.data;
5194
+ } else if (msg?.type === "error") {
5195
+ const err = new Error(msg.error || "操作失败");
5196
+ err.status = msg.status || 500;
5197
+ throw err;
5198
+ }
5199
+ };
5200
+ while (true) {
5201
+ const { value, done } = await reader.read();
5202
+ if (done) break;
5203
+ buf += decoder.decode(value, { stream: true });
5204
+ const lines = buf.split("\n");
5205
+ buf = lines.pop() ?? "";
5206
+ for (const line of lines) processLine(line);
5207
+ }
5208
+ buf += decoder.decode();
5209
+ if (buf.trim()) processLine(buf);
5210
+ if (!hasResult) {
5211
+ const err = new Error("连接意外中断,未收到完整结果");
5212
+ err.status = 502;
5213
+ throw err;
5214
+ }
5215
+ } else {
5216
+ try { body = await res.json(); } catch { /* no body */ }
5217
+ }
5050
5218
  if (!res.ok) {
5051
5219
  const err = new Error((body && body.error) || `HTTP ${res.status}`);
5052
5220
  err.status = res.status;
@@ -5383,7 +5551,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
5383
5551
  }
5384
5552
 
5385
5553
  function AnthropicIcon({ isDark }) {
5386
- return h("div", {
5554
+ return h("span", {
5387
5555
  className: "cpm-card-icon",
5388
5556
  style: {
5389
5557
  background: isDark ? "#18181b" : "#f4f1ea",
@@ -5403,7 +5571,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
5403
5571
  }
5404
5572
 
5405
5573
  function Context7Icon({ isDark }) {
5406
- return h("div", {
5574
+ return h("span", {
5407
5575
  className: "cpm-card-icon",
5408
5576
  style: {
5409
5577
  background: isDark ? "#09090b" : "#000000",
@@ -5605,8 +5773,8 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
5605
5773
  const renderedFallback = (!inline && typeof React !== "undefined" && typeof PluginIconFallback === "function" && React.isValidElement?.(fallback) && fallback.type === PluginIconFallback)
5606
5774
  ? React.cloneElement(fallback, { underlay: !!avatarUrl })
5607
5775
  : fallback;
5608
- return h("div", { className: "cpm-card-icon", style: { position: "relative", overflow: "hidden" } },
5609
- h("div", { className: "cpm-icon-underlay", "aria-hidden": true, style: { position: "absolute", inset: 0, opacity: imgLoaded ? 0 : 1 } }, inline ? null : renderedFallback),
5776
+ return h("span", { className: "cpm-card-icon", style: { position: "relative", overflow: "hidden" } },
5777
+ h("span", { className: "cpm-icon-underlay", "aria-hidden": true, style: { position: "absolute", inset: 0, opacity: imgLoaded ? 0 : 1 } }, inline ? null : renderedFallback),
5610
5778
  // A plugin-local icon is a same-origin disk read, so deferring it to
5611
5779
  // the viewport buys nothing and costs a visible placeholder on scroll.
5612
5780
  // Only remote avatars are worth deferring — and never above the fold.
@@ -5668,7 +5836,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
5668
5836
  }
5669
5837
 
5670
5838
  // Use the upstream 3D PNG unchanged; declared logos retain priority.
5671
- return h("div", {
5839
+ return h("span", {
5672
5840
  className: "cpm-card-icon cpm-fallback-icon",
5673
5841
  "aria-hidden": true,
5674
5842
  style: {
@@ -5685,6 +5853,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
5685
5853
  plugin,
5686
5854
  iconPlugin = plugin,
5687
5855
  installed,
5856
+ installing = false,
5688
5857
  eagerIcon = false,
5689
5858
  isDark,
5690
5859
  onMouseEnter,
@@ -5715,8 +5884,9 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
5715
5884
  }, "管理")
5716
5885
  : h("button", {
5717
5886
  className: "cpm-card-pill",
5718
- onClick: onInstall,
5719
- }, "安装")),
5887
+ disabled: installing,
5888
+ onClick: installing ? (e) => e.stopPropagation() : onInstall,
5889
+ }, installing ? "安装中…" : "安装")),
5720
5890
  );
5721
5891
  }
5722
5892
 
@@ -6070,6 +6240,15 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
6070
6240
  h("circle", { cx: 12, cy: 12, r: 3 }),
6071
6241
  );
6072
6242
 
6243
+ function renderCountBadge(value) {
6244
+ const text = String(value ?? "");
6245
+ return h(
6246
+ "span",
6247
+ { className: "cpm-badge" + (text.length > 1 ? " is-capsule" : "") },
6248
+ h("span", { className: "cpm-badge-num" }, text),
6249
+ );
6250
+ }
6251
+
6073
6252
  function CustomSelect({ value, options, onChange, openUp = false }) {
6074
6253
  const [open, setOpen] = useState(false);
6075
6254
  const ref = useRef(null);
@@ -6081,8 +6260,17 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
6081
6260
  setOpen(false);
6082
6261
  }
6083
6262
  };
6263
+ const handleKeyDown = (e) => {
6264
+ if (e.key === "Escape") {
6265
+ setOpen(false);
6266
+ }
6267
+ };
6084
6268
  document.addEventListener("mousedown", handleOutside);
6085
- return () => document.removeEventListener("mousedown", handleOutside);
6269
+ document.addEventListener("keydown", handleKeyDown);
6270
+ return () => {
6271
+ document.removeEventListener("mousedown", handleOutside);
6272
+ document.removeEventListener("keydown", handleKeyDown);
6273
+ };
6086
6274
  }, [open]);
6087
6275
 
6088
6276
  const activeOption = options.find((o) => o.value === value) || options[0];
@@ -6091,6 +6279,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
6091
6279
  h("button", {
6092
6280
  type: "button",
6093
6281
  className: "cpm-select-trigger" + (open ? " open" : ""),
6282
+ "aria-expanded": open,
6094
6283
  onClick: () => setOpen(!open),
6095
6284
  },
6096
6285
  h("span", null, activeOption?.label || ""),
@@ -6466,31 +6655,72 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
6466
6655
 
6467
6656
  let currentTabAnim = null;
6468
6657
  let currentTabTarget = null;
6469
- // Per-source tab scroll position the user had when they navigated away
6470
- // from BrowseView. Restored on remount so the user comes back to the
6471
- // exact tabs they were looking at, not the auto-scroll's "active tab
6472
- // near the left edge" default.
6473
- const savedTabScrolls = new Map();
6658
+ /** Compute the clamped scrollLeft needed to fully expose a tab outside edge fade masks. */
6659
+ function computeTabRevealScrollLeft(container, tabEl, baseScroll) {
6660
+ if (!container || !tabEl) return null;
6661
+ const containerWidth = container.clientWidth;
6662
+ const scrollWidth = container.scrollWidth;
6663
+ if (!Number.isFinite(containerWidth) || !Number.isFinite(scrollWidth) || containerWidth <= 0) return null;
6664
+ const maxScroll = Math.max(0, scrollWidth - containerWidth);
6665
+ if (maxScroll <= 0) return 0;
6666
+
6667
+ const rawBase = typeof baseScroll === "number" ? baseScroll : container.scrollLeft;
6668
+ const currentScroll = Math.max(0, Math.min(maxScroll, Number.isFinite(rawBase) ? rawBase : 0));
6669
+
6670
+ let tabLeft = tabEl.offsetLeft;
6671
+ let tabWidth = tabEl.offsetWidth;
6672
+ if (typeof container.getBoundingClientRect === "function" && typeof tabEl.getBoundingClientRect === "function") {
6673
+ const cRect = container.getBoundingClientRect();
6674
+ const tRect = tabEl.getBoundingClientRect();
6675
+ if (cRect && tRect && Number.isFinite(tRect.left) && Number.isFinite(cRect.left) && Number.isFinite(tRect.width) && tRect.width > 0) {
6676
+ tabLeft = tRect.left - cRect.left + (Number.isFinite(container.scrollLeft) ? container.scrollLeft : 0);
6677
+ tabWidth = tRect.width;
6678
+ }
6679
+ }
6680
+ if (!Number.isFinite(tabLeft) || !Number.isFinite(tabWidth) || tabWidth <= 0) return null;
6681
+ const tabRight = tabLeft + tabWidth;
6682
+
6683
+ const LEFT_CLEARANCE = 28;
6684
+ const RIGHT_CLEARANCE = 32;
6685
+ if (tabWidth >= containerWidth - LEFT_CLEARANCE - RIGHT_CLEARANCE) {
6686
+ return Math.max(0, Math.min(maxScroll, tabLeft <= LEFT_CLEARANCE ? 0 : tabLeft - LEFT_CLEARANCE));
6687
+ }
6688
+
6689
+ const hasLeftFade = currentScroll > 2;
6690
+ const hasRightFade = currentScroll < maxScroll - 2;
6691
+ const visibleLeft = currentScroll + (hasLeftFade ? LEFT_CLEARANCE : 0);
6692
+ const visibleRight = currentScroll + containerWidth - (hasRightFade ? RIGHT_CLEARANCE : 0);
6693
+
6694
+ let targetScroll = currentScroll;
6695
+ if (tabLeft < visibleLeft) {
6696
+ targetScroll = tabLeft <= LEFT_CLEARANCE ? 0 : (tabLeft - LEFT_CLEARANCE);
6697
+ } else if (tabRight > visibleRight) {
6698
+ targetScroll = (scrollWidth - tabRight) <= RIGHT_CLEARANCE ? maxScroll : (tabRight - containerWidth + RIGHT_CLEARANCE);
6699
+ }
6700
+ return Math.max(0, Math.min(maxScroll, targetScroll));
6701
+ }
6702
+
6474
6703
  function smoothScrollTabsTo(container, targetLeft, duration = 280, onUpdate) {
6475
6704
  if (!container) return;
6476
6705
  const startLeft = container.scrollLeft;
6477
6706
  const maxLeft = Math.max(0, container.scrollWidth - container.clientWidth);
6478
6707
  const clampTarget = Math.max(0, Math.min(maxLeft, targetLeft));
6708
+ const reducedMotion = typeof window !== "undefined" && Boolean(window.matchMedia?.("(prefers-reduced-motion: reduce)").matches);
6479
6709
 
6480
- // If already at target, finish instantly and cleanly
6481
- if (Math.abs(startLeft - clampTarget) < 0.5) {
6710
+ // Finish instantly when already at target or when reduced motion is enabled.
6711
+ if (Math.abs(startLeft - clampTarget) < 0.5 || reducedMotion || duration <= 0) {
6482
6712
  container.scrollLeft = clampTarget;
6483
6713
  if (currentTabAnim) {
6484
6714
  cancelAnimationFrame(currentTabAnim);
6485
6715
  currentTabAnim = null;
6486
6716
  }
6487
6717
  currentTabTarget = null;
6718
+ if (typeof SESSION_STORE === "object" && SESSION_STORE) SESSION_STORE.tabsScrollLeft = clampTarget;
6488
6719
  if (typeof onUpdate === "function") onUpdate();
6489
6720
  return;
6490
6721
  }
6491
6722
 
6492
- // If an animation is already in progress to this exact target (within 6px tolerance for active font-weight expansion), do not interrupt or twitch!
6493
- if (currentTabAnim && currentTabTarget !== null && Math.abs(currentTabTarget - clampTarget) < 6) {
6723
+ if (currentTabAnim && currentTabTarget !== null && Math.abs(currentTabTarget - clampTarget) < 0.5) {
6494
6724
  return;
6495
6725
  }
6496
6726
 
@@ -6521,6 +6751,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
6521
6751
  container.scrollLeft = clampTarget;
6522
6752
  currentTabAnim = null;
6523
6753
  currentTabTarget = null;
6754
+ if (typeof SESSION_STORE === "object" && SESSION_STORE) SESSION_STORE.tabsScrollLeft = clampTarget;
6524
6755
  if (typeof onUpdate === "function") onUpdate();
6525
6756
  }
6526
6757
  }
@@ -6598,10 +6829,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
6598
6829
  }
6599
6830
  }
6600
6831
  } catch {}
6601
- return {
6602
- sources: [{ id: "anthropic", name: "Anthropic", url: "https://github.com/anthropics/claude-plugins-official.git", builtin: true }],
6603
- plugins: [],
6604
- };
6832
+ return { sources: [], plugins: [] };
6605
6833
  }
6606
6834
 
6607
6835
  function loadCachedRows() {
@@ -6725,24 +6953,22 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
6725
6953
  }, [rootRef]);
6726
6954
  }
6727
6955
 
6956
+ const cachedState = loadCachedState();
6728
6957
  const SESSION_STORE = {
6729
6958
  view: { type: "browse" },
6730
6959
  sourceViews: {},
6960
+ mcpView: { type: "mcp", expandedServers: new Set() },
6731
6961
  browseSortSnapshots: Object.create(null),
6732
6962
  query: "",
6733
- filter: "all",
6963
+ installedFilterSources: new Set(),
6734
6964
  sortBy: "default",
6735
- activeSourceId: "anthropic",
6965
+ activeSourceId: cachedState.sources[0]?.id || "",
6736
6966
  rows: loadCachedRows(),
6737
- state: loadCachedState(),
6967
+ state: cachedState,
6738
6968
  scrollTops: {},
6739
6969
  scrollTop: 0,
6740
- // Survives the BrowseView unmount caused by opening the manage page, so
6741
- // returning from a plugin's MCP page lands back on the MCP tab.
6742
- mcpsOpen: false,
6743
- // Same reason: the MCP tab only renders when `mcps.length > 0`, so an
6744
- // empty first render after Back dropped it for a frame and Anthropic
6745
- // took the leftmost slot, producing a visible tab-bar jump.
6970
+ tabsScrollLeft: null,
6971
+ // Keep the server catalog available for the first render on return.
6746
6972
  mcps: null,
6747
6973
  };
6748
6974
 
@@ -6759,7 +6985,6 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
6759
6985
 
6760
6986
  // Persistent browse state across views and sidebar tab switching
6761
6987
  const [query, setQueryRaw] = useState(() => SESSION_STORE.query);
6762
- const [filter, setFilterRaw] = useState(() => SESSION_STORE.filter);
6763
6988
  const [sortBy, setSortByRaw] = useState(() => SESSION_STORE.sortBy);
6764
6989
  const [activeSourceId, setActiveSourceIdRaw] = useState(() => SESSION_STORE.activeSourceId);
6765
6990
  const [rows, setRowsRaw] = useState(() => SESSION_STORE.rows || loadCachedRows());
@@ -6768,57 +6993,30 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
6768
6993
 
6769
6994
  const setView = useCallback((v) => {
6770
6995
  SESSION_STORE.view = v;
6771
- if (!SESSION_STORE.sourceViews) SESSION_STORE.sourceViews = {};
6772
- const sId = (v && v.sourceId) || SESSION_STORE.activeSourceId;
6773
- if (sId) {
6774
- SESSION_STORE.sourceViews[sId] = v;
6996
+ if (v.type !== "mcp" && v.returnView?.type !== "mcp") {
6997
+ const sourceId = v.sourceId || SESSION_STORE.activeSourceId;
6998
+ if (sourceId) SESSION_STORE.sourceViews[sourceId] = v;
6775
6999
  }
6776
7000
  setViewRaw(v);
6777
7001
  }, []);
6778
7002
 
6779
- const switchSource = useCallback((newSourceId, nextFilter) => {
6780
- if (!newSourceId) return;
6781
- if (!SESSION_STORE.sourceViews) SESSION_STORE.sourceViews = {};
6782
- if (SESSION_STORE.activeSourceId && SESSION_STORE.view) {
6783
- SESSION_STORE.sourceViews[SESSION_STORE.activeSourceId] = SESSION_STORE.view;
6784
- }
7003
+ const setActiveSourceId = useCallback((newSourceId) => {
6785
7004
  SESSION_STORE.activeSourceId = newSourceId;
6786
7005
  setActiveSourceIdRaw(newSourceId);
6787
- if (nextFilter) {
6788
- SESSION_STORE.filter = nextFilter;
6789
- if (!SESSION_STORE.sourceFilters) SESSION_STORE.sourceFilters = {};
6790
- SESSION_STORE.sourceFilters[newSourceId] = nextFilter;
6791
- setFilterRaw(nextFilter);
6792
- }
6793
7006
  const targetView = SESSION_STORE.sourceViews[newSourceId] || { type: "browse", sourceId: newSourceId };
6794
- SESSION_STORE.view = targetView;
6795
- setViewRaw(targetView);
6796
- }, []);
7007
+ setView(targetView);
7008
+ }, [setView]);
6797
7009
 
6798
7010
  const setQuery = useCallback((q) => {
6799
7011
  SESSION_STORE.query = q;
6800
7012
  setQueryRaw(q);
6801
7013
  }, []);
6802
7014
 
6803
- const setFilter = useCallback((f) => {
6804
- SESSION_STORE.filter = f;
6805
- SESSION_STORE.preferredFilter = f;
6806
- if (!SESSION_STORE.sourceFilters) SESSION_STORE.sourceFilters = {};
6807
- if (SESSION_STORE.activeSourceId) {
6808
- SESSION_STORE.sourceFilters[SESSION_STORE.activeSourceId] = f;
6809
- }
6810
- setFilterRaw(f);
6811
- }, []);
6812
-
6813
7015
  const setSortBy = useCallback((s) => {
6814
7016
  SESSION_STORE.sortBy = s;
6815
7017
  setSortByRaw(s);
6816
7018
  }, []);
6817
7019
 
6818
- const setActiveSourceId = useCallback((id, nextFilter) => {
6819
- switchSource(id, nextFilter);
6820
- }, [switchSource]);
6821
-
6822
7020
  const setRows = useCallback((r) => {
6823
7021
  setRowsRaw((prev) => {
6824
7022
  const next = typeof r === "function" ? r(prev) : r;
@@ -7143,25 +7341,22 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
7143
7341
  refreshState();
7144
7342
  }, [refreshState]);
7145
7343
 
7146
- // The plugin panel itself is being closed (MarketApp unmounts). Reset
7147
- // the scroll memory so a fresh open of the panel starts at the top —
7148
- // the user explicitly wants panel close/reopen to reset scroll. This
7149
- // does NOT run when opening management inside BrowseView, so returning
7150
- // from manage still restores the saved position.
7344
+ // Marketplace lists and the tab strip start fresh on panel reopen.
7345
+ // The current view and its own scroll positions survive the unmount.
7151
7346
  useEffect(() => {
7347
+ SESSION_STORE.panelUnmounting = false;
7152
7348
  return () => {
7349
+ SESSION_STORE.panelUnmounting = true;
7153
7350
  if (SESSION_STORE.scrollTops) SESSION_STORE.scrollTops = {};
7154
- // Closing the panel is a fresh start: reopen on the plugin list,
7155
- // not on whichever MCP tab happened to be active.
7156
- SESSION_STORE.mcpsOpen = false;
7351
+ SESSION_STORE.tabsScrollLeft = null;
7157
7352
  };
7158
7353
  }, []);
7159
7354
 
7160
- const openManage = useCallback((record, fromView, tab, connector, returnToMcp = false) => {
7355
+ const openManage = useCallback((record, fromView, tab, connector) => {
7161
7356
  if (!record) return;
7162
7357
  setView({ type: "manage", sourceId: activeSourceId, pluginName: record.name,
7163
7358
  initialTab: tab || null, initialConnector: connector || null,
7164
- returnView: returnToMcp || fromView?.type === "detail" ? fromView : undefined, returnToMcp });
7359
+ returnView: fromView?.type === "mcp" || fromView?.type === "detail" ? fromView : undefined });
7165
7360
  }, [activeSourceId, setView]);
7166
7361
 
7167
7362
  return h("div", {
@@ -7188,8 +7383,6 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
7188
7383
  isDark,
7189
7384
  query,
7190
7385
  setQuery,
7191
- filter,
7192
- setFilter,
7193
7386
  sortBy,
7194
7387
  setSortBy,
7195
7388
  activeSourceId,
@@ -7775,13 +7968,13 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
7775
7968
  }
7776
7969
 
7777
7970
  // ────────────────────────────── Browse & Detail Container ──────────────────────────────
7778
- function McpOverview({ serverRows, pluginRows }) {
7779
- const rootRef = useRef(null);
7971
+ function McpOverview({ serverRows, pluginRows, containerRef, scrollState, maskClass, updateMask, suspendHover }) {
7780
7972
  const serverRef = useRef(null);
7781
7973
  const [reservedHeight, setReservedHeight] = useState(0);
7782
7974
  const reserveSpace = serverRows.length > 0 && pluginRows.length > 0;
7975
+ useRememberedDetailScroll("overview", containerRef, scrollState, updateMask);
7783
7976
  useSafeLayoutEffect(() => {
7784
- const viewport = rootRef.current?.parentElement;
7977
+ const viewport = containerRef.current;
7785
7978
  const server = serverRef.current;
7786
7979
  if (!viewport || !reserveSpace || !server) { setReservedHeight(0); return; }
7787
7980
  // A window resize and the observer's own viewport callback describe the
@@ -7793,7 +7986,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
7793
7986
  frame = requestAnimationFrame(() => { frame = 0; measure(); });
7794
7987
  };
7795
7988
  const measure = () => {
7796
- const style = getComputedStyle(viewport);
7989
+ const style = window.getComputedStyle(viewport);
7797
7990
  const available = viewport.clientHeight - (parseFloat(style.paddingTop) || 0) - (parseFloat(style.paddingBottom) || 0);
7798
7991
  // Anchor the plugin section's top edge to the midpoint. Only the
7799
7992
  // server section's actual, current height may push it down; never
@@ -7811,19 +8004,26 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
7811
8004
  observer?.disconnect();
7812
8005
  window.removeEventListener("resize", schedule);
7813
8006
  };
7814
- }, [reserveSpace]);
7815
- return h("div", { ref: rootRef, className: "cpm-mcp-overview", style: { position: "relative", maxWidth: "var(--cpm-grid-width)", margin: "0 auto", width: "100%" } },
7816
- serverRows.length > 0 && h("section", { className: "cpm-mcp-user-section", style: { display: "flow-root", minHeight: reserveSpace ? reservedHeight : undefined } },
7817
- // Measure the intrinsic content, not the section with minHeight applied:
7818
- // expansion can push the next section down, and collapse can release it.
7819
- h("div", { ref: serverRef, style: { display: "flow-root" } },
7820
- h("div", { style: { fontSize: 14, fontWeight: 700, color: "var(--cpm-text)", margin: "8px 4px 12px" } }, "服务器"),
7821
- h("div", { style: { borderRadius: 16, border: "1px solid var(--cpm-border)", background: "var(--cpm-card-bg)", overflow: "hidden" } }, serverRows),
8007
+ }, [containerRef, reserveSpace]);
8008
+ return h("div", {
8009
+ ref: containerRef,
8010
+ className: "cpm-grid-container" + maskClass,
8011
+ onWheelCapture: suspendHover,
8012
+ onScroll: () => { suspendHover(); updateMask(); },
8013
+ },
8014
+ serverRows.length === 0 && pluginRows.length === 0 && h("div", { className: "cpm-empty", style: { textAlign: "center", padding: "40px 16px" } }, "还没有添加 MCP,点右上角「添加」→「添加 MCP」"),
8015
+ h("div", { className: "cpm-mcp-overview", style: { position: "relative", maxWidth: "var(--cpm-grid-width)", margin: "0 auto", width: "100%" } },
8016
+ serverRows.length > 0 && h("section", { className: "cpm-mcp-user-section", style: { display: "flow-root", minHeight: reserveSpace ? reservedHeight : undefined } },
8017
+ // The wrapper stays at its intrinsic height as tools expand and collapse.
8018
+ h("div", { ref: serverRef, style: { display: "flow-root" } },
8019
+ h("div", { style: { fontSize: 14, fontWeight: 700, color: "var(--cpm-text)", margin: "8px 4px 12px" } }, "服务器"),
8020
+ h("div", { style: { borderRadius: 16, border: "1px solid var(--cpm-border)", background: "var(--cpm-card-bg)", overflow: "hidden" } }, serverRows),
8021
+ ),
8022
+ ),
8023
+ pluginRows.length > 0 && h("section", { className: "cpm-mcp-plugin-section", style: { display: "flow-root" } },
8024
+ h("div", { style: { fontSize: 14, fontWeight: 700, color: "var(--cpm-text)", margin: "22px 4px 12px" } }, "来自插件"),
8025
+ h("div", { style: { borderRadius: 16, border: "1px solid var(--cpm-border)", background: "var(--cpm-card-bg)", overflow: "hidden" } }, pluginRows),
7822
8026
  ),
7823
- ),
7824
- pluginRows.length > 0 && h("section", { className: "cpm-mcp-plugin-section", style: { display: "flow-root" } },
7825
- h("div", { style: { fontSize: 14, fontWeight: 700, color: "var(--cpm-text)", margin: "22px 4px 12px" } }, "来自插件"),
7826
- h("div", { style: { borderRadius: 16, border: "1px solid var(--cpm-border)", background: "var(--cpm-card-bg)", overflow: "hidden" } }, pluginRows),
7827
8027
  ),
7828
8028
  );
7829
8029
  }
@@ -7877,13 +8077,11 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
7877
8077
  refreshState,
7878
8078
  patchPluginInState,
7879
8079
  showToast,
7880
- openManage: openManageView,
8080
+ openManage,
7881
8081
  onInstalled,
7882
8082
  isDark,
7883
8083
  query,
7884
8084
  setQuery,
7885
- filter,
7886
- setFilter,
7887
8085
  sortBy,
7888
8086
  setSortBy,
7889
8087
  activeSourceId,
@@ -7893,8 +8091,16 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
7893
8091
  addedGitSourceIds,
7894
8092
  scrollTopRef,
7895
8093
  }) {
7896
- const [showFilter, setShowFilter] = useState(false);
7897
- const [showSort, setShowSort] = useState(false);
8094
+ const [installedFilterSources, setInstalledFilterSourcesRaw] = useState(() => SESSION_STORE.installedFilterSources);
8095
+ const filter = installedFilterSources.has(activeSourceId) ? "installed" : "all";
8096
+ const setInstalledFilterSources = (sourceIds) => {
8097
+ SESSION_STORE.installedFilterSources = sourceIds;
8098
+ setInstalledFilterSourcesRaw(sourceIds);
8099
+ };
8100
+ const [openTopMenu, setOpenTopMenu] = useState(null);
8101
+ const showFilter = openTopMenu === "filter";
8102
+ const showSort = openTopMenu === "sort";
8103
+ const showAddMenu = openTopMenu === "add";
7898
8104
  const [busy, setBusy] = useState(null);
7899
8105
  const [isRefreshing, setIsRefreshing] = useState(false);
7900
8106
  const [skillBusy, setSkillBusy] = useState(null);
@@ -7906,26 +8112,22 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
7906
8112
  useEffect(() => {
7907
8113
  if (!addDialog) addDialogBusyRef.current = false;
7908
8114
  }, [addDialog]);
7909
- const [showAddMenu, setShowAddMenu] = useState(false);
7910
8115
  const localSource = state.sources.find((s) => s.id === "local");
7911
8116
  const hasLocalPlugins = typeof localSource?.pluginCount === "number" ? localSource.pluginCount > 0 : (rows?.local?.length || 0) > 0;
7912
- useEffect(() => {
7913
- if (activeSourceId === "local" && !hasLocalPlugins) {
7914
- const next = state.sources.find((s) => s.id !== "local");
7915
- if (next) setActiveSourceId(next.id);
7916
- }
7917
- }, [hasLocalPlugins, activeSourceId, state.sources, setActiveSourceId]);
8117
+ const ensureActiveSource = useCallback((sources) => {
8118
+ const currentView = SESSION_STORE.view;
8119
+ if (currentView.type === "mcp" || currentView.returnView?.type === "mcp") return;
8120
+ const visibleSources = sources.filter((s) => s.id !== "local" || hasLocalPlugins);
8121
+ const selectedId = SESSION_STORE.activeSourceId;
8122
+ if (visibleSources.some((s) => s.id === selectedId)) return;
8123
+ const nextSourceId = visibleSources[0]?.id || "";
8124
+ if (nextSourceId !== selectedId) setActiveSourceId(nextSourceId);
8125
+ }, [hasLocalPlugins, setActiveSourceId]);
8126
+ useSafeLayoutEffect(() => { ensureActiveSource(state.sources); }, [state.sources, ensureActiveSource]);
7918
8127
  const [mcpDialog, setMcpDialog] = useState(false);
7919
8128
  const [mcps, setMcps] = useState(() => SESSION_STORE.mcps || []);
7920
- const [mcpsOpen, setMcpsOpenRaw] = useState(() => !!SESSION_STORE.mcpsOpen);
7921
- const setMcpsOpen = useCallback((v) => {
7922
- SESSION_STORE.mcpsOpen = v;
7923
- setMcpsOpenRaw(v);
7924
- }, []);
7925
- const openManage = (record, fromView, tab, connector) => {
7926
- setMcpsOpen(false);
7927
- openManageView(record, mcpsOpen ? view : fromView, tab, connector, mcpsOpen);
7928
- };
8129
+ const mcpsOpen = view.type === "mcp";
8130
+ const isMcpTab = mcpsOpen || view.returnView?.type === "mcp";
7929
8131
  const [editMcp, setEditMcp] = useState(null);
7930
8132
  // Plugin name when the editor was opened from a plugin-provided server;
7931
8133
  // null means the editor targets a user-added MCP.
@@ -7941,16 +8143,29 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
7941
8143
  }
7942
8144
  return initial;
7943
8145
  });
7944
- const [globalExpanded, setGlobalExpanded] = useState({});
8146
+ const [globalExpanded, setGlobalExpanded] = useState(() => SESSION_STORE.mcpView.expandedServers);
7945
8147
  const [globalHoveredTool, closeGlobalHover, globalHover] = useHoverPreview();
7946
8148
  useEffect(() => { closeGlobalHover(); }, [mcpsOpen, view?.type, closeGlobalHover]);
7947
8149
 
8150
+ const browseUnmountedRef = useRef(false);
8151
+ const bgRefreshQueueRef = useRef(null);
8152
+ useEffect(() => {
8153
+ browseUnmountedRef.current = false;
8154
+ return () => {
8155
+ browseUnmountedRef.current = true;
8156
+ bgRefreshQueueRef.current?.dispose();
8157
+ };
8158
+ }, []);
8159
+
7948
8160
  const refreshMcps = useCallback(async () => {
7949
8161
  try {
7950
8162
  const res = await api("/mcps");
7951
8163
  SESSION_STORE.mcps = res.mcps || [];
7952
- setMcps(SESSION_STORE.mcps);
7953
- } catch {}
8164
+ if (!browseUnmountedRef.current) setMcps(SESSION_STORE.mcps);
8165
+ return SESSION_STORE.mcps;
8166
+ } catch {
8167
+ return null;
8168
+ }
7954
8169
  }, []);
7955
8170
 
7956
8171
  useEffect(() => {
@@ -7976,47 +8191,106 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
7976
8191
  }).filter((c) => typeof c.name === "string" && c.name.trim())
7977
8192
  ), [state.plugins]);
7978
8193
  const hasMcps = mcps.some((m) => m?.name) || pluginMcpRows.length > 0;
8194
+ const showMcpTab = hasMcps || isMcpTab;
8195
+
8196
+ const loadGlobalTools = useCallback((owner, connectorName, forceFresh = false, options = {}) => (
8197
+ runMcpToolsLoad({
8198
+ owner,
8199
+ connectorName,
8200
+ forceFresh,
8201
+ options,
8202
+ setData: setGlobalToolData,
8203
+ stateKey: `${owner}::${connectorName}`,
8204
+ })
8205
+ ), []);
8206
+
8207
+ const enqueueBgGlobalRefresh = useCallback((owner, connectorName) => {
8208
+ if (browseUnmountedRef.current) return;
8209
+ const key = `${owner}::${connectorName}`;
8210
+ if (!bgRefreshQueueRef.current) bgRefreshQueueRef.current = createMcpRefreshQueue(MCP_TOOLS_BG_CONCURRENCY);
8211
+ bgRefreshQueueRef.current.enqueue(key, () => {
8212
+ if (browseUnmountedRef.current) return;
8213
+ return loadGlobalTools(owner, connectorName, true, { background: true });
8214
+ });
8215
+ }, [loadGlobalTools]);
7979
8216
 
7980
- const loadGlobalTools = useCallback(async (owner, connectorName, forceFresh = false) => {
8217
+ const autoLoadGlobalTools = useCallback((owner, connectorName) => {
7981
8218
  const key = `${owner}::${connectorName}`;
8219
+ const forceStdio = typeof consumeStdioForceRefresh === "function" && consumeStdioForceRefresh(key);
7982
8220
  const cached = GLOBAL_MCP_TOOLS_CACHE[key];
7983
- setGlobalToolData((prev) => ({
7984
- ...prev,
7985
- [key]: { ...(cached || prev[key]), loading: forceFresh || !Array.isArray(cached?.tools), error: null, warning: null },
7986
- }));
7987
- try {
7988
- const url = owner === "user-mcp"
7989
- ? `/mcps/${encodeURIComponent(connectorName)}/tools`
7990
- : `/plugins/${encodeURIComponent(owner)}/connectors/${encodeURIComponent(connectorName)}/tools`;
7991
- const res = await api(url + (forceFresh ? "?fresh=1" : ""));
7992
- const tools = Array.isArray(res.tools) ? res.tools : [];
7993
- const disabledTools = Array.isArray(res.disabledTools) ? res.disabledTools : [];
7994
- if (res.ok) saveMcpToolsCache(key, { tools, disabledTools });
7995
- setGlobalToolData((prev) => ({
7996
- ...prev,
7997
- [key]: {
7998
- loading: false,
7999
- error: res.ok ? null : (res.message || "获取能力列表失败"),
8000
- warning: res.ok && res.stale ? (res.message || "获取能力列表失败") : null,
8001
- tools: res.ok ? tools : (prev[key]?.tools || tools),
8002
- disabledTools,
8003
- },
8004
- }));
8005
- } catch (e) {
8006
- setGlobalToolData((prev) => ({ ...prev, [key]: { ...(prev[key] || cached), loading: false, error: e.message } }));
8221
+ const hasCached = Array.isArray(cached?.tools);
8222
+ if (forceStdio) {
8223
+ if (hasCached) enqueueBgGlobalRefresh(owner, connectorName);
8224
+ else void loadGlobalTools(owner, connectorName, true);
8225
+ return;
8007
8226
  }
8008
- }, []);
8227
+ if (!hasCached) {
8228
+ void loadGlobalTools(owner, connectorName, false).then((res) => {
8229
+ if (res?.ok && res.cached && typeof isMcpRefreshDue === "function" && isMcpRefreshDue(key)) {
8230
+ enqueueBgGlobalRefresh(owner, connectorName);
8231
+ }
8232
+ });
8233
+ return;
8234
+ }
8235
+ if (typeof isMcpRefreshDue === "function" && isMcpRefreshDue(key)) {
8236
+ enqueueBgGlobalRefresh(owner, connectorName);
8237
+ return;
8238
+ }
8239
+ void loadGlobalTools(owner, connectorName, false);
8240
+ }, [enqueueBgGlobalRefresh, loadGlobalTools]);
8241
+
8242
+ const mcpsRef = useRef(mcps);
8243
+ mcpsRef.current = mcps;
8244
+ const pluginMcpRowsRef = useRef(pluginMcpRows);
8245
+ pluginMcpRowsRef.current = pluginMcpRows;
8246
+
8247
+ const scheduleDueGlobalMcpRefreshes = useCallback((overrideMcps) => {
8248
+ const userList = Array.isArray(overrideMcps) ? overrideMcps : mcpsRef.current;
8249
+ for (const row of (pluginMcpRowsRef.current || [])) {
8250
+ if (!row?.name || row.record?.enabled === false || row.conn?.enabled !== true || (row.conn?.pending && row.conn?.connected !== true)) continue;
8251
+ const key = `${row.owner}::${row.name}`;
8252
+ if (Array.isArray(GLOBAL_MCP_TOOLS_CACHE[key]?.tools) && isMcpRefreshDue(key)) {
8253
+ enqueueBgGlobalRefresh(row.owner, row.name);
8254
+ }
8255
+ }
8256
+ for (const row of (userList || [])) {
8257
+ if (!row?.name || row.enabled !== true) continue;
8258
+ const key = `user-mcp::${row.name}`;
8259
+ if (Array.isArray(GLOBAL_MCP_TOOLS_CACHE[key]?.tools) && isMcpRefreshDue(key)) {
8260
+ enqueueBgGlobalRefresh("user-mcp", row.name);
8261
+ }
8262
+ }
8263
+ }, [enqueueBgGlobalRefresh]);
8264
+
8265
+ useEffect(() => {
8266
+ if (!mcpsOpen) return;
8267
+ setGlobalToolData((prev) => {
8268
+ let next = prev;
8269
+ for (const [key, cached] of Object.entries(GLOBAL_MCP_TOOLS_CACHE)) {
8270
+ if (!cached || !Array.isArray(cached.tools)) continue;
8271
+ const cur = prev[key];
8272
+ if (cur && cur.loading) continue;
8273
+ if (cur && cur.tools === cached.tools && cur.disabledTools === cached.disabledTools) continue;
8274
+ if (next === prev) next = { ...prev };
8275
+ next[key] = { loading: false, error: null, warning: null, tools: cached.tools, disabledTools: cached.disabledTools || [] };
8276
+ }
8277
+ return next;
8278
+ });
8279
+ scheduleDueGlobalMcpRefreshes();
8280
+ }, [mcpsOpen, scheduleDueGlobalMcpRefreshes]);
8009
8281
 
8010
8282
  useAutoMcpTools([
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]) })),
8283
+ ...pluginMcpRows.map(row => ({ owner: row.owner, name: row.name, connected: row.conn.enabled === true && !(row.conn.pending && row.conn.connected !== true), revision: JSON.stringify([row.record.installedAt, row.conn]) })),
8012
8284
  ...mcps.map(row => ({ owner: "user-mcp", name: row.name, connected: row.enabled === true, revision: JSON.stringify(row) })),
8013
- ], loadGlobalTools);
8285
+ ], autoLoadGlobalTools);
8014
8286
 
8015
- const toggleGlobalExpand = useCallback((owner, connectorName) => {
8287
+ const toggleGlobalExpand = useCallback((owner, connectorName) => {
8016
8288
  const key = `${owner}::${connectorName}`;
8017
- const willExpand = !globalExpanded[key];
8018
- setGlobalExpanded((prev) => ({ ...prev, [key]: willExpand }));
8019
- }, [globalExpanded]);
8289
+ const expanded = new Set(SESSION_STORE.mcpView.expandedServers);
8290
+ if (!expanded.delete(key)) expanded.add(key);
8291
+ SESSION_STORE.mcpView.expandedServers = expanded;
8292
+ setGlobalExpanded(expanded);
8293
+ }, []);
8020
8294
 
8021
8295
  const toggleGlobalTool = useCallback(async (owner, connectorName, toolName) => {
8022
8296
  const key = `${owner}::${connectorName}`;
@@ -8057,7 +8331,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8057
8331
  const serverEnabled = canEdit ? connected : conn?.enabled === true;
8058
8332
  const enabled = Object.prototype.hasOwnProperty.call(optimisticMcp, key) ? optimisticMcp[key] : serverEnabled;
8059
8333
  const toggling = pendingMcpToggles[key] === true;
8060
- const isExpanded = !!globalExpanded[key];
8334
+ const isExpanded = globalExpanded.has(key);
8061
8335
  const info = globalToolData[key];
8062
8336
  const toolsList = info?.tools || [];
8063
8337
  const disabledTools = info?.disabledTools || [];
@@ -8078,6 +8352,16 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8078
8352
  showToast("操作失败", res.error || "请稍后重试", { restart: false });
8079
8353
  return;
8080
8354
  }
8355
+ if (nextEnabled) {
8356
+ if (String(transport || "stdio").toLowerCase() === "stdio") {
8357
+ clearMcpRefreshCooldown(key);
8358
+ queueStdioForceRefresh(key);
8359
+ } else {
8360
+ markMcpRefreshCooldown(key);
8361
+ }
8362
+ } else {
8363
+ bumpMcpToolsSeq(key);
8364
+ }
8081
8365
  if (canEdit) await refreshMcps();
8082
8366
  else if (res?.plugin && patchPluginInState) {
8083
8367
  patchPluginInState(res.plugin);
@@ -8111,7 +8395,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8111
8395
  // Buttons inside the row keep their own handlers.
8112
8396
  const onRowClick = canEdit ? undefined : (e) => {
8113
8397
  if (e.target.closest("button, .cpm-mcp-tools-panel")) return;
8114
- if (record) openManage(record, { type: "browse", sourceId: activeSourceId }, "connectors");
8398
+ if (record) openManage(record, view, "connectors");
8115
8399
  };
8116
8400
 
8117
8401
  return h("div", {
@@ -8178,10 +8462,18 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8178
8462
 
8179
8463
  const [confirmRemoveSource, setConfirmRemoveSource] = useState(null);
8180
8464
  const [installFor, setInstallFor] = useState(null);
8465
+ const installDialogBusyRef = useRef(false);
8466
+ useEffect(() => {
8467
+ if (!installFor) installDialogBusyRef.current = false;
8468
+ }, [installFor]);
8469
+ const installingNamesRef = useRef(new Set());
8470
+ const [installingNames, setInstallingNames] = useState(() => new Set());
8471
+ const isPluginInstalling = (name) => installingNames.has(String(name || "").toLowerCase());
8181
8472
  const [hoveredPreview, closePluginHover, pluginHover] = useHoverPreview(240);
8182
8473
  const installedByName = useMemo(() => new Map(state.plugins.map(plugin => [plugin.name, plugin])), [state.plugins]);
8183
8474
  const resolveMarketplaceIcon = useMemo(() => createMarketplaceIconResolver(installedByName, state.sources), [installedByName, state.sources]);
8184
8475
  const gridRef = useRef(null);
8476
+ const mcpGridRef = useRef(null);
8185
8477
  const detailContainerRef = useRef(null);
8186
8478
  const tabsRef = useRef(null);
8187
8479
  const tabRefs = useRef({});
@@ -8254,7 +8546,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8254
8546
  }, []);
8255
8547
 
8256
8548
  const updateGridMask = useCallback(() => {
8257
- const el = gridRef.current;
8549
+ const el = mcpGridRef.current || gridRef.current;
8258
8550
  if (!el) return;
8259
8551
  const maxScroll = el.scrollHeight - el.clientHeight;
8260
8552
  setGridMaskClass(maxScroll > 4 && el.scrollTop < maxScroll - 4 ? " mask-bottom" : "");
@@ -8356,7 +8648,8 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8356
8648
 
8357
8649
  if (hoveredPreview) closePluginHover();
8358
8650
 
8359
- const targetLeft = Math.max(0, Math.min(maxLeft, el.scrollLeft + delta));
8651
+ const baseLeft = (currentTabAnim && currentTabTarget !== null) ? currentTabTarget : el.scrollLeft;
8652
+ const targetLeft = Math.max(0, Math.min(maxLeft, baseLeft + delta));
8360
8653
  smoothScrollTabsTo(el, targetLeft, 180, updateTabsMask);
8361
8654
  };
8362
8655
 
@@ -8370,53 +8663,33 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8370
8663
  closePluginHover();
8371
8664
  }, [activeSourceId, view?.type]);
8372
8665
 
8373
- useEffect(() => {
8374
- return () => {
8375
- if (scrollTimerRef.current) clearTimeout(scrollTimerRef.current);
8376
- if (currentTabAnim) {
8377
- cancelAnimationFrame(currentTabAnim);
8378
- currentTabAnim = null;
8379
- currentTabTarget = null;
8380
- }
8381
- };
8382
- }, []);
8383
-
8384
- useSafeLayoutEffect(() => {
8385
- updateTabsMask();
8386
- window.addEventListener("resize", updateTabsMask);
8387
- return () => {
8388
- window.removeEventListener("resize", updateTabsMask);
8389
- };
8390
- }, [updateTabsMask, state.sources, view?.type]);
8391
-
8392
- const prevSourceRef = useRef(activeSourceId);
8666
+ const activeTabId = isMcpTab ? "__mcps" : activeSourceId;
8667
+ const prevTabIdRef = useRef(activeTabId);
8668
+ const pendingRevealTabRef = useRef(null);
8669
+ const didRestoreTabScrollRef = useRef(false);
8670
+ const tabsScrollLeftRef = useRef(typeof SESSION_STORE.tabsScrollLeft === "number" ? SESSION_STORE.tabsScrollLeft : 0);
8393
8671
 
8394
8672
  const scrollActiveTabIntoView = useCallback((tabId, animated = true) => {
8395
8673
  const container = tabsRef.current;
8396
8674
  const tabEl = tabRefs.current[tabId];
8397
8675
  if (!container || !tabEl) return;
8398
8676
 
8399
- const tabLeft = tabEl.offsetLeft;
8400
- const tabWidth = tabEl.offsetWidth;
8401
- const tabRight = tabLeft + tabWidth;
8402
- const currentScroll = (currentTabTarget !== null) ? currentTabTarget : container.scrollLeft;
8403
- const containerWidth = container.clientWidth;
8404
-
8405
- let targetScroll = currentScroll;
8406
- // 1. Rightward overflow: if tab is covered by right feathering mask (28px)
8407
- if (tabRight > currentScroll + containerWidth - 28) {
8408
- targetScroll = tabRight - containerWidth + 26;
8409
- }
8410
- // 2. Leftward overflow: if tab is covered by left feathering mask (26px safe distance)
8411
- else if (tabLeft < currentScroll + 26) {
8412
- targetScroll = Math.max(0, tabLeft - 26);
8413
- }
8677
+ const baseScroll = (currentTabAnim && currentTabTarget !== null) ? currentTabTarget : container.scrollLeft;
8678
+ const targetScroll = computeTabRevealScrollLeft(container, tabEl, baseScroll);
8679
+ if (targetScroll === null) return;
8414
8680
 
8415
8681
  if (Math.abs(targetScroll - container.scrollLeft) > 1) {
8416
8682
  if (animated) {
8417
8683
  smoothScrollTabsTo(container, targetScroll, 280, updateTabsMask);
8418
8684
  } else {
8685
+ if (currentTabAnim) {
8686
+ cancelAnimationFrame(currentTabAnim);
8687
+ currentTabAnim = null;
8688
+ }
8689
+ currentTabTarget = null;
8419
8690
  container.scrollLeft = targetScroll;
8691
+ tabsScrollLeftRef.current = targetScroll;
8692
+ if (didRestoreTabScrollRef.current) SESSION_STORE.tabsScrollLeft = targetScroll;
8420
8693
  updateTabsMask();
8421
8694
  }
8422
8695
  } else {
@@ -8424,6 +8697,59 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8424
8697
  }
8425
8698
  }, [updateTabsMask]);
8426
8699
 
8700
+ const restoreOrRevealTabScroll = useCallback(() => {
8701
+ const container = tabsRef.current;
8702
+ if (!container) return;
8703
+ if (didRestoreTabScrollRef.current) {
8704
+ if (pendingRevealTabRef.current && tabRefs.current[pendingRevealTabRef.current]) {
8705
+ const pendingId = pendingRevealTabRef.current;
8706
+ pendingRevealTabRef.current = null;
8707
+ scrollActiveTabIntoView(pendingId, true);
8708
+ }
8709
+ updateTabsMask();
8710
+ return;
8711
+ }
8712
+ // Wait until the tab strip has a measurable box before locking in initial scroll.
8713
+ if (container.clientWidth <= 0) return;
8714
+ currentTabTarget = null;
8715
+ const saved = SESSION_STORE.tabsScrollLeft;
8716
+ if (typeof saved === "number") {
8717
+ if (container.scrollWidth > container.clientWidth || state.sources.length > 0 || showMcpTab) {
8718
+ const maxScroll = Math.max(0, container.scrollWidth - container.clientWidth);
8719
+ const restored = Math.max(0, Math.min(maxScroll, saved));
8720
+ container.scrollLeft = restored;
8721
+ tabsScrollLeftRef.current = restored;
8722
+ didRestoreTabScrollRef.current = true;
8723
+ updateTabsMask();
8724
+ }
8725
+ return;
8726
+ }
8727
+ if (tabRefs.current[activeTabId]) {
8728
+ didRestoreTabScrollRef.current = true;
8729
+ scrollActiveTabIntoView(activeTabId, false);
8730
+ tabsScrollLeftRef.current = container.scrollLeft;
8731
+ SESSION_STORE.tabsScrollLeft = container.scrollLeft;
8732
+ return;
8733
+ }
8734
+ updateTabsMask();
8735
+ }, [activeTabId, state.sources.length, showMcpTab, scrollActiveTabIntoView, updateTabsMask]);
8736
+
8737
+ useSafeLayoutEffect(() => {
8738
+ updateTabsMask();
8739
+ const el = tabsRef.current;
8740
+ const onTabsResize = () => {
8741
+ if (!didRestoreTabScrollRef.current) restoreOrRevealTabScroll();
8742
+ else updateTabsMask();
8743
+ };
8744
+ const observer = el && typeof ResizeObserver === "function" ? new ResizeObserver(onTabsResize) : null;
8745
+ if (observer) observer.observe(el);
8746
+ window.addEventListener("resize", onTabsResize);
8747
+ return () => {
8748
+ observer?.disconnect();
8749
+ window.removeEventListener("resize", onTabsResize);
8750
+ };
8751
+ }, [updateTabsMask, restoreOrRevealTabScroll, state.sources, showMcpTab, activeTabId, view?.type]);
8752
+
8427
8753
  useSafeLayoutEffect(() => {
8428
8754
  if (view?.type === "browse" || !view?.type) {
8429
8755
  updateTabsMask();
@@ -8431,77 +8757,51 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8431
8757
  }, [view?.type, updateTabsMask]);
8432
8758
 
8433
8759
  useEffect(() => {
8434
- if (prevSourceRef.current !== activeSourceId) {
8435
- prevSourceRef.current = activeSourceId;
8436
- scrollActiveTabIntoView(activeSourceId, true);
8437
- setMcpsOpen(false);
8438
- }
8439
- }, [activeSourceId, scrollActiveTabIntoView]);
8440
-
8441
- // Restore the user's previous tab-bar scroll position on remount.
8442
- // The tab container is a horizontal scroller the user controls with
8443
- // the wheel, by dragging, or by clicking the feathered edges. Their
8444
- // chosen position is a real UI state. `scrollActiveTabIntoView` is
8445
- // designed to drag the active tab to a "near the left edge" default
8446
- // and would overwrite that position on every Back, so:
8447
- // - first mount (no saved value): auto-scroll to bring the active
8448
- // tab into view, as a convenience
8449
- // - every remount after that: restore the exact saved scroll and
8450
- // skip the auto-scroll entirely
8451
- //
8452
- // `currentTabTarget` is also reset so the auto-scroll's `currentScroll`
8453
- // baseline is the DOM's real scrollLeft, not an in-flight target from
8454
- // an animation that the BrowseView unmount interrupted.
8455
- //
8456
- // The deps include `state.sources` (and its length) so a state
8457
- // refresh that changes the source list after mount re-applies the
8458
- // correct position once the new layout is committed.
8459
- useSafeLayoutEffect(() => {
8460
- currentTabTarget = null;
8461
- const container = tabsRef.current;
8462
- if (!container) return;
8463
- const saved = savedTabScrolls.get(activeSourceId);
8464
- if (typeof saved === "number") {
8465
- container.scrollLeft = saved;
8466
- updateTabsMask();
8467
- return;
8760
+ if (prevTabIdRef.current !== activeTabId) {
8761
+ prevTabIdRef.current = activeTabId;
8762
+ if (tabRefs.current[activeTabId]) {
8763
+ pendingRevealTabRef.current = null;
8764
+ scrollActiveTabIntoView(activeTabId, true);
8765
+ } else {
8766
+ pendingRevealTabRef.current = activeTabId;
8767
+ }
8468
8768
  }
8469
- scrollActiveTabIntoView(activeSourceId, false);
8470
- }, [activeSourceId, state.sources, state.sources.length, scrollActiveTabIntoView, updateTabsMask]);
8769
+ }, [activeTabId, scrollActiveTabIntoView]);
8770
+
8771
+ // Restore or initially reveal the active tab once on mount, and never
8772
+ // clobber the user's current tab scroll when `state.sources` refreshes
8773
+ // (e.g. entering ManagePage or background polling).
8774
+ useSafeLayoutEffect(() => {
8775
+ restoreOrRevealTabScroll();
8776
+ }, [restoreOrRevealTabScroll, state.sources]);
8471
8777
 
8472
- // Mirror the tab container's scrollLeft into a regular ref so the
8473
- // unmount-cleanup below can read it after `tabsRef.current` is nulled
8474
- // (React detaches DOM refs before running useEffect cleanups). Without
8475
- // this, the save on manage→back never lands and the new mount falls
8476
- // through to the auto-scroll default.
8477
- const tabsScrollLeftRef = useRef(0);
8478
8778
  useEffect(() => {
8479
8779
  const el = tabsRef.current;
8480
8780
  if (!el) return;
8481
- tabsScrollLeftRef.current = el.scrollLeft;
8482
8781
  const handler = () => {
8483
8782
  tabsScrollLeftRef.current = el.scrollLeft;
8783
+ if (didRestoreTabScrollRef.current) SESSION_STORE.tabsScrollLeft = el.scrollLeft;
8484
8784
  };
8485
8785
  el.addEventListener("scroll", handler, { passive: true });
8486
8786
  return () => el.removeEventListener("scroll", handler);
8487
- }, [state.sources, state.sources.length]);
8787
+ }, []);
8488
8788
 
8489
- // Persist the user's current scroll for the active source so a later
8490
- // remount of BrowseView (e.g. after the user opens and closes an
8491
- // installed plugin's manage page) lands them at the exact same
8492
- // scroll position rather than at scrollLeft=0.
8493
8789
  useEffect(() => {
8494
8790
  return () => {
8495
- if (!activeSourceId) return;
8496
- // Prefer the in-flight animation target if the user navigated
8497
- // away mid-scroll — the mid-animation scrollLeft is a value
8498
- // they never saw.
8499
- const final = (currentTabAnim && currentTabTarget !== null)
8500
- ? currentTabTarget
8501
- : tabsScrollLeftRef.current;
8502
- savedTabScrolls.set(activeSourceId, final);
8791
+ if (scrollTimerRef.current) clearTimeout(scrollTimerRef.current);
8792
+ if (!SESSION_STORE.panelUnmounting && didRestoreTabScrollRef.current) {
8793
+ const final = (currentTabAnim && currentTabTarget !== null)
8794
+ ? currentTabTarget
8795
+ : tabsScrollLeftRef.current;
8796
+ SESSION_STORE.tabsScrollLeft = final;
8797
+ }
8798
+ if (currentTabAnim) {
8799
+ cancelAnimationFrame(currentTabAnim);
8800
+ currentTabAnim = null;
8801
+ currentTabTarget = null;
8802
+ }
8503
8803
  };
8504
- }, [activeSourceId]);
8804
+ }, []);
8505
8805
 
8506
8806
  // ────────────────────────────── Tab Long-Press Drag Reorder ──────────────────────────────
8507
8807
  const [dragState, setDragState] = useState(null);
@@ -8574,7 +8874,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8574
8874
  // reachable even when a short tab sits between two much wider tabs.
8575
8875
  // Frozen geometry also prevents animated neighbors feeding back on hit tests.
8576
8876
  for (const slot of baseSlots) {
8577
- if (!slot || !slot.movable) continue;
8877
+ if (!slot) continue;
8578
8878
  const left = slot.offsetLeft + (slot.index > fromIndex ? slot.width - draggedWidth : 0);
8579
8879
  const distance = Math.abs(contentCenter - (left + draggedWidth / 2));
8580
8880
  if (distance < nearestDistance) {
@@ -8661,8 +8961,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8661
8961
  if (dragLiveRef.current.active || dragState) {
8662
8962
  cancelOrResetDrag();
8663
8963
  }
8664
- if (s.builtin || idx === 0 || (s.id && s.id.toLowerCase() === "anthropic")) return;
8665
- if (!state.sources || state.sources.length < 3) return;
8964
+ if (!state.sources.some((item) => item.id !== s.id && tabRefs.current[item.id]?.isConnected)) return;
8666
8965
 
8667
8966
  const pointerId = e.pointerId;
8668
8967
  const clientX = e.clientX;
@@ -8710,7 +9009,6 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8710
9009
  return {
8711
9010
  id: item.id,
8712
9011
  index: mIdx,
8713
- movable: mIdx !== 0 && !item.builtin && item.id?.toLowerCase() !== "anthropic",
8714
9012
  offsetLeft: rect.left - cRect.left + curScroll,
8715
9013
  width: rect.width,
8716
9014
  height: rect.height || 30,
@@ -8800,7 +9098,20 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8800
9098
  }
8801
9099
  }, [startAutoScroll, stopAutoScroll, updateDragPosition]);
8802
9100
 
8803
- const handleTabPointerUp = useCallback((e, s, idx) => {
9101
+ const selectSourceTab = useCallback((sourceId) => {
9102
+ if (isMcpTab || sourceId !== activeSourceId) {
9103
+ if (gridRef.current && view.type === "browse") {
9104
+ SESSION_STORE.scrollTops[activeSourceId] = gridRef.current.scrollTop;
9105
+ }
9106
+ setActiveSourceId(sourceId);
9107
+ return;
9108
+ }
9109
+ scrollActiveTabIntoView(sourceId, true);
9110
+ SESSION_STORE.scrollTops[sourceId] = 0;
9111
+ scrollContentToTop();
9112
+ }, [isMcpTab, activeSourceId, view.type, setActiveSourceId, scrollActiveTabIntoView, scrollContentToTop]);
9113
+
9114
+ const handleTabPointerUp = useCallback((e, s) => {
8804
9115
  if (dragLiveRef.current.isSnapping) return;
8805
9116
  if (dragLiveRef.current.pointerId !== null && e?.pointerId !== dragLiveRef.current.pointerId) return;
8806
9117
  if (longPressTimerRef.current) {
@@ -8848,17 +9159,18 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8848
9159
  if (!dragLiveRef.current.isSnapping) return;
8849
9160
  clearTimeout(snapTimerRef.current);
8850
9161
  snapFinishRef.current = null;
8851
- if (toIndex !== fromIndex && fromIndex >= 1 && toIndex >= 1) {
8852
- // Keep the tab bar where the user left it: the state.sources
8853
- // change re-runs the tab-scroll restore layout effect, which
8854
- // would otherwise snap back to the active (leftmost) tab and
8855
- // hide the tab the user just dropped at the end. Save the
8856
- // current scroll so that restore keeps the dropped tab visible.
9162
+ const currentSources = SESSION_STORE.state?.sources || state.sources;
9163
+ const currentFrom = currentSources.findIndex((item) => item.id === baseSlots[fromIndex]?.id);
9164
+ const currentTo = currentSources.findIndex((item) => item.id === baseSlots[toIndex]?.id);
9165
+ if (currentFrom !== currentTo && currentFrom >= 0 && currentTo >= 0) {
8857
9166
  const scrollEl = tabsRef.current;
8858
- if (scrollEl) savedTabScrolls.set(activeSourceId, scrollEl.scrollLeft);
8859
- const newSources = [...state.sources];
8860
- const [moved] = newSources.splice(fromIndex, 1);
8861
- newSources.splice(toIndex, 0, moved);
9167
+ if (scrollEl && typeof scrollEl.scrollLeft === "number") {
9168
+ if (typeof tabsScrollLeftRef === "object" && tabsScrollLeftRef) tabsScrollLeftRef.current = scrollEl.scrollLeft;
9169
+ SESSION_STORE.tabsScrollLeft = scrollEl.scrollLeft;
9170
+ }
9171
+ const newSources = [...currentSources];
9172
+ const [moved] = newSources.splice(currentFrom, 1);
9173
+ newSources.splice(currentTo, 0, moved);
8862
9174
  setState((prev) => ({ ...prev, sources: newSources }));
8863
9175
  SESSION_STORE.state = { ...(SESSION_STORE.state || {}), sources: newSources };
8864
9176
  try {
@@ -8868,7 +9180,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8868
9180
  method: "POST",
8869
9181
  body: JSON.stringify({ sourceIds: newSources.map((item) => item.id) }),
8870
9182
  }).catch(() => {});
8871
- showToast("标签排序已更新", `已将「${moved.name}」移至第 ${toIndex + 1} 位`, { restart: false });
9183
+ showToast("标签排序已更新", `已将「${moved.name}」移至第 ${currentTo + 1} 位`, { restart: false });
8872
9184
  }
8873
9185
  dragLiveRef.current.active = false;
8874
9186
  dragLiveRef.current.isSnapping = false;
@@ -8887,38 +9199,8 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8887
9199
  return;
8888
9200
  }
8889
9201
 
8890
- // Normal click action
8891
- if (!isLongPressTriggeredRef.current && s) {
8892
- const isBrowseView = !view || view.type === "browse";
8893
- if (mcpsOpen) setMcpsOpen(false);
8894
- const listedNames = new Set((SESSION_STORE.rows?.[s.id] || []).map(p => p.name));
8895
- const hasInstalled = (state.plugins || []).some(p => (p.sourceId || "").toLowerCase() === s.id.toLowerCase() || p.id?.startsWith(s.id + "/") || listedNames.has(p.name));
8896
- if (s.id !== activeSourceId) {
8897
- if (gridRef.current && isBrowseView && !mcpsOpen) {
8898
- if (!SESSION_STORE.scrollTops) SESSION_STORE.scrollTops = {};
8899
- SESSION_STORE.scrollTops[activeSourceId] = gridRef.current.scrollTop;
8900
- }
8901
- if (!SESSION_STORE.sourceFilters) SESSION_STORE.sourceFilters = {};
8902
-
8903
- let targetFilter = filter;
8904
- if (!hasInstalled) {
8905
- if (filter === "installed") {
8906
- SESSION_STORE.preferredFilter = "installed";
8907
- }
8908
- targetFilter = "all";
8909
- } else {
8910
- targetFilter = SESSION_STORE.sourceFilters[s.id] || SESSION_STORE.preferredFilter || (filter === "installed" ? "installed" : "all");
8911
- }
8912
- setActiveSourceId(s.id, targetFilter);
8913
- } else if (!mcpsOpen) {
8914
- // Clicking the current source's tab scrolls its list back to the top.
8915
- scrollActiveTabIntoView(s.id, true);
8916
- if (!SESSION_STORE.scrollTops) SESSION_STORE.scrollTops = {};
8917
- SESSION_STORE.scrollTops[s.id] = 0;
8918
- scrollContentToTop();
8919
- }
8920
- }
8921
- }, [state.sources, state.plugins, activeSourceId, view, filter, mcpsOpen, setMcpsOpen, setActiveSourceId, scrollActiveTabIntoView, scrollContentToTop, setState, showToast, stopAutoScroll, updateTabsMask, updateDragPosition]);
9202
+ if (!isLongPressTriggeredRef.current && s) selectSourceTab(s.id);
9203
+ }, [state.sources, selectSourceTab, setState, showToast, stopAutoScroll, updateTabsMask, updateDragPosition]);
8922
9204
 
8923
9205
  useEffect(() => {
8924
9206
  const handleWindowBlurOrCancel = () => {
@@ -8927,7 +9209,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8927
9209
 
8928
9210
  const handleGlobalPointerUp = (e) => {
8929
9211
  if ((dragLiveRef.current.active || longPressTimerRef.current) && !dragLiveRef.current.isSnapping) {
8930
- handleTabPointerUp(e, null, dragLiveRef.current.fromIndex);
9212
+ handleTabPointerUp(e, null);
8931
9213
  }
8932
9214
  };
8933
9215
 
@@ -9004,10 +9286,8 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9004
9286
  // grid should be scrolled to after the next commit:
9005
9287
  // - { type: "restore" } — active source changed: back to the saved
9006
9288
  // scrollTop for the source the user switched to.
9007
- // - { type: "reset" } — filter/sort explicitly changed
9008
- // (全部插件/已安装/排序): back to 0. Deliberately does NOT zero
9009
- // the saved `scrollTops[...]` for the source, so a filter/sort
9010
- // change doesn't wipe the tab-switch memory.
9289
+ // - { type: "reset", filter } — the current source switched
9290
+ // between 全部插件 and 已安装: back to 0.
9011
9291
  // - null — nothing pending: installs, detail view
9012
9292
  // open/close, plain re-renders leave scroll alone.
9013
9293
  //
@@ -9024,7 +9304,6 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9024
9304
  const pendingScrollTopRef = useRef(null);
9025
9305
  const lastActiveSourceRef = useRef(activeSourceId);
9026
9306
  const lastFilterRef = useRef(filter);
9027
- const lastSortByRef = useRef(sortBy);
9028
9307
  const prevIsBrowseRef = useRef(isSourceBrowse);
9029
9308
  const firstBrowseRenderRef = useRef(true);
9030
9309
 
@@ -9040,13 +9319,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9040
9319
  // you left that source, not at the top. So only set reset when
9041
9320
  // there is no restore already pending for this commit.
9042
9321
  if (pendingScrollTopRef.current?.type !== "restore") {
9043
- pendingScrollTopRef.current = { type: "reset", filter, sortBy };
9044
- }
9045
- }
9046
- if (sortBy !== lastSortByRef.current) {
9047
- lastSortByRef.current = sortBy;
9048
- if (pendingScrollTopRef.current?.type !== "restore") {
9049
- pendingScrollTopRef.current = { type: "reset", filter, sortBy };
9322
+ pendingScrollTopRef.current = { type: "reset", filter };
9050
9323
  }
9051
9324
  }
9052
9325
  // Details and MCP both unmount the source grid. Returning to either the
@@ -9084,7 +9357,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9084
9357
  if (!isSourceBrowse || !gridRef.current) return;
9085
9358
  const pending = pendingScrollTopRef.current;
9086
9359
  if (!pending) return;
9087
- if (pending.type === "reset" && (pending.filter !== filter || pending.sortBy !== sortBy)) return;
9360
+ if (pending.type === "reset" && pending.filter !== filter) return;
9088
9361
  const target = pending.type === "restore"
9089
9362
  ? ((SESSION_STORE.scrollTops && SESSION_STORE.scrollTops[activeSourceId]) || 0)
9090
9363
  : 0;
@@ -9130,16 +9403,27 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9130
9403
  useEffect(() => {
9131
9404
  const onDocClick = (e) => {
9132
9405
  if (!e.target.closest(".cpm-filter") && !e.target.closest(".cpm-sort") && !e.target.closest(".cpm-add-btn") && !e.target.closest(".cpm-menu-pop")) {
9133
- setShowFilter(false);
9134
- setShowSort(false);
9135
- setShowAddMenu(false);
9406
+ setOpenTopMenu(null);
9407
+ }
9408
+ };
9409
+ const onKeyDown = (e) => {
9410
+ if (e.key === "Escape") {
9411
+ setOpenTopMenu(null);
9136
9412
  }
9137
9413
  };
9138
- if (showFilter || showSort || showAddMenu) {
9414
+ if (openTopMenu) {
9139
9415
  document.addEventListener("mousedown", onDocClick);
9140
- return () => document.removeEventListener("mousedown", onDocClick);
9416
+ document.addEventListener("keydown", onKeyDown);
9417
+ return () => {
9418
+ document.removeEventListener("mousedown", onDocClick);
9419
+ document.removeEventListener("keydown", onKeyDown);
9420
+ };
9141
9421
  }
9142
- }, [showFilter, showSort, showAddMenu]);
9422
+ }, [openTopMenu]);
9423
+
9424
+ useEffect(() => {
9425
+ setOpenTopMenu(null);
9426
+ }, [activeSourceId, mcpsOpen, view.type]);
9143
9427
 
9144
9428
  const loadMarket = useCallback(async (sourceId) => {
9145
9429
  if (!sourceId) return;
@@ -9198,6 +9482,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9198
9482
  SESSION_STORE.browseSortSnapshots[activeSourceId] = { filter, query, sortBy, names: currentSourceInstalledNames };
9199
9483
  }, [activeSourceId, filter, query, sortBy, currentSourceInstalledNames]);
9200
9484
  const installedNames = useMemo(() => new Set(state.plugins.map((p) => p.name)), [state.plugins]);
9485
+ const totalInstalledCount = Array.isArray(state?.plugins) ? state.plugins.length : 0;
9201
9486
  const currentSourcePlugins = useMemo(() => (rows && rows[activeSourceId]) || [], [rows, activeSourceId]);
9202
9487
  const totalSourcePluginsCount = currentSourcePlugins.length;
9203
9488
 
@@ -9308,9 +9593,9 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9308
9593
  }, [view]);
9309
9594
 
9310
9595
  useDialogEscape(!!(installFor || addDialog || confirmRemoveSource || mcpDialog), () => {
9311
- if (installFor) setInstallFor(null);
9596
+ if (installFor && !installDialogBusyRef.current) setInstallFor(null);
9312
9597
  if (addDialog && !addDialogBusyRef.current) setAddDialog(false);
9313
- if (confirmRemoveSource) setConfirmRemoveSource(null);
9598
+ if (confirmRemoveSource && !busy) setConfirmRemoveSource(null);
9314
9599
  if (mcpDialog) {
9315
9600
  setMcpDialog(false);
9316
9601
  setEditMcp(null);
@@ -9318,6 +9603,69 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9318
9603
  }
9319
9604
  });
9320
9605
 
9606
+ const cleanupRemovedSource = (removedId) => {
9607
+ invalidateSourceDetailCache(removedId);
9608
+ const currentSources = SESSION_STORE.state?.sources || state.sources;
9609
+ const remainingSources = currentSources.filter((s) => s && s.id !== removedId);
9610
+ ensureActiveSource(remainingSources);
9611
+ const remainingFilters = new Set(SESSION_STORE.installedFilterSources);
9612
+ if (remainingFilters.delete(removedId)) setInstalledFilterSources(remainingFilters);
9613
+ for (const mapKey of ["sourceViews", "scrollTops", "browseSortSnapshots"]) {
9614
+ if (SESSION_STORE[mapKey]) delete SESSION_STORE[mapKey][removedId];
9615
+ }
9616
+ if (SESSION_STORE.checkedCatalogs) SESSION_STORE.checkedCatalogs.delete(removedId);
9617
+ addedGitSourceIds.current.delete(removedId);
9618
+ if (tabRefs?.current) delete tabRefs.current[removedId];
9619
+ setRows((prev) => omitSourceKey(prev, removedId));
9620
+ syncCachedStore("rows", STORAGE_KEY_ROWS, rows, (prev) => omitSourceKey(prev, removedId));
9621
+ setState((prev) => stripDeletedSource(prev, removedId));
9622
+ syncCachedStore("state", STORAGE_KEY_STATE, state, (prev) => stripDeletedSource(prev, removedId));
9623
+ const nextVisible = remainingSources.filter((s) => s.id !== "local" || hasLocalPlugins);
9624
+ return nextVisible[0]?.id || "";
9625
+ };
9626
+
9627
+ const deleteLocalPlugin = async (plugin) => {
9628
+ if (!plugin?.name) return;
9629
+ try {
9630
+ const result = await api("/plugins/local/" + encodeURIComponent(plugin.name), { method: "DELETE" });
9631
+ if (result?.ok === false) {
9632
+ await refreshState();
9633
+ showToast("删除失败", result.error || "删除未能完成,请稍后重试", { restart: false });
9634
+ return;
9635
+ }
9636
+ const localName = state.sources.find((s) => s.id === "local")?.name || "Local Plugins";
9637
+ if (result?.sourceRemoved) {
9638
+ const nextSourceId = cleanupRemovedSource("local");
9639
+ showToast("已删除本地插件", `已删除「${plugin.displayName || plugin.name}」,空的「${localName}」标签页已自动移除`, { restart: false });
9640
+ setView({ type: "browse", sourceId: nextSourceId });
9641
+ try { await refreshState(); } catch {}
9642
+ return;
9643
+ }
9644
+ invalidateSourceDetailCache("local");
9645
+ const nextLocalPlugins = Array.isArray(result?.plugins)
9646
+ ? result.plugins
9647
+ : ((SESSION_STORE.rows?.local || rows?.local || []).filter((p) => p?.name !== plugin.name));
9648
+ const nextCount = typeof result?.remainingCount === "number" ? result.remainingCount : nextLocalPlugins.length;
9649
+ const updateLocalRows = (prev) => ({ ...(prev || {}), local: nextLocalPlugins });
9650
+ const updateLocalCount = (prev) => {
9651
+ if (!prev || !Array.isArray(prev.sources)) return prev;
9652
+ return {
9653
+ ...prev,
9654
+ sources: prev.sources.map((s) => (s && s.id === "local" ? { ...s, pluginCount: nextCount } : s)),
9655
+ };
9656
+ };
9657
+ setRows(updateLocalRows);
9658
+ syncCachedStore("rows", STORAGE_KEY_ROWS, rows, updateLocalRows);
9659
+ setState(updateLocalCount);
9660
+ syncCachedStore("state", STORAGE_KEY_STATE, state, updateLocalCount);
9661
+ showToast("已删除本地插件", `已从「${localName}」列表中移除「${plugin.displayName || plugin.name}」`, { restart: false });
9662
+ setView({ type: "browse", sourceId: "local" });
9663
+ try { await refreshState(); } catch {}
9664
+ } catch (e) {
9665
+ showToast("删除失败", cleanError(e), { restart: false });
9666
+ }
9667
+ };
9668
+
9321
9669
  const removePlugin = async (pluginName) => {
9322
9670
  try {
9323
9671
  const result = await api("/plugins/" + encodeURIComponent(pluginName), { method: "DELETE" });
@@ -9366,6 +9714,79 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9366
9714
  }, [currentSourcePlugins, query, sortBy, sortInstalledNames, crossSourceInstalledNames]);
9367
9715
 
9368
9716
  const refresh = async () => {
9717
+ if (isRefreshing) return;
9718
+ if (mcpsOpen) {
9719
+ setIsRefreshing(true);
9720
+ bgRefreshQueueRef.current?.clearPending();
9721
+ try {
9722
+ const [freshMcps, freshState] = await Promise.all([
9723
+ refreshMcps(),
9724
+ refreshState({ quiet: true }),
9725
+ ]);
9726
+ if (browseUnmountedRef.current) return;
9727
+ bgRefreshQueueRef.current?.clearPending();
9728
+ if (freshMcps === null && freshState === null) {
9729
+ showToast("刷新失败", "无法获取最新 MCP 列表", { restart: false });
9730
+ return;
9731
+ }
9732
+ const latestMcps = Array.isArray(freshMcps) ? freshMcps : mcpsRef.current;
9733
+ const latestPlugins = Array.isArray(freshState?.plugins) ? freshState.plugins : (state?.plugins || []);
9734
+ const targets = [];
9735
+ const seenTargets = new Set();
9736
+ for (const m of (latestMcps || [])) {
9737
+ if (!m?.name || m.enabled !== true) continue;
9738
+ const key = `user-mcp::${m.name}`;
9739
+ if (seenTargets.has(key)) continue;
9740
+ seenTargets.add(key);
9741
+ targets.push({ owner: "user-mcp", name: m.name });
9742
+ }
9743
+ for (const rec of (latestPlugins || [])) {
9744
+ if (!rec?.name || rec.enabled === false) continue;
9745
+ for (const c of (Array.isArray(rec.connectors) ? rec.connectors : [])) {
9746
+ const obj = typeof c === "object" && c ? c : { name: String(c) };
9747
+ if (!obj.name || !String(obj.name).trim()) continue;
9748
+ if (obj.enabled !== true || (obj.pending && obj.connected !== true)) continue;
9749
+ const key = `${rec.name}::${obj.name}`;
9750
+ if (seenTargets.has(key)) continue;
9751
+ seenTargets.add(key);
9752
+ targets.push({ owner: rec.name, name: obj.name });
9753
+ }
9754
+ }
9755
+ if (targets.length === 0) {
9756
+ showToast("已刷新", "MCP 列表已更新", { restart: false });
9757
+ return;
9758
+ }
9759
+ const outcomes = await runWithConcurrency(
9760
+ targets,
9761
+ MCP_TOOLS_MANUAL_CONCURRENCY,
9762
+ (target) => loadGlobalTools(target.owner, target.name, true, { preserveDisplay: true }),
9763
+ );
9764
+ if (browseUnmountedRef.current) return;
9765
+ const failures = [];
9766
+ outcomes.forEach((outcome, idx) => {
9767
+ if (outcome && !outcome.ok && !outcome.superseded) {
9768
+ failures.push({ name: targets[idx].name, error: outcome.error });
9769
+ }
9770
+ });
9771
+ if (failures.length === 0) {
9772
+ showToast("已刷新", "MCP 工具列表已更新", { restart: false });
9773
+ } else if (failures.length < targets.length) {
9774
+ const preview = failures.slice(0, 3).map((f) => f.name).join("、");
9775
+ const suffix = failures.length > 3 ? ` 等 ${failures.length} 个` : "";
9776
+ showToast("部分 MCP 刷新失败", `${preview}${suffix} 保留了上次解析结果`, { restart: false });
9777
+ } else {
9778
+ const detailMsg = failures.length === 1 && failures[0].error
9779
+ ? failures[0].error
9780
+ : `共 ${failures.length} 个已启用 MCP 刷新失败,已保留旧缓存`;
9781
+ showToast("刷新失败", detailMsg, { restart: false });
9782
+ }
9783
+ } catch (e) {
9784
+ if (!browseUnmountedRef.current) showToast("刷新失败", e.message, { restart: false });
9785
+ } finally {
9786
+ if (!browseUnmountedRef.current) setIsRefreshing(false);
9787
+ }
9788
+ return;
9789
+ }
9369
9790
  const refreshSourceId = activeSourceId;
9370
9791
  setIsRefreshing(true);
9371
9792
  if (detailEpochRef.current) {
@@ -9379,6 +9800,10 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9379
9800
  const refreshEpoch = (refreshSourceId && detailEpochRef.current?.[refreshSourceId]) || 0;
9380
9801
  if (detailCacheRef.current) detailCacheRef.current = {};
9381
9802
  try {
9803
+ if (!refreshSourceId) {
9804
+ await refreshState();
9805
+ return;
9806
+ }
9382
9807
  if (refreshSourceId === "skills-local") {
9383
9808
  const body = await api("/skills/refresh", { method: "POST" });
9384
9809
  setRows(prev => ({ ...(prev || {}), "skills-local": body.skills || [] }));
@@ -9433,12 +9858,18 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9433
9858
  };
9434
9859
 
9435
9860
  const doInstall = async () => {
9861
+ const target = installFor;
9862
+ if (!target) return;
9863
+ const key = String(target.name || "").toLowerCase();
9864
+ if (installingNamesRef.current.has(key)) return;
9865
+ installingNamesRef.current.add(key);
9866
+ setInstallingNames((prev) => { const next = new Set(prev); next.add(key); return next; });
9436
9867
  try {
9437
9868
  const result = await api("/plugins/install", {
9438
9869
  method: "POST",
9439
9870
  body: JSON.stringify({
9440
- sourceId: installFor.sourceId,
9441
- pluginName: installFor.name,
9871
+ sourceId: target.sourceId,
9872
+ pluginName: target.name,
9442
9873
  }),
9443
9874
  });
9444
9875
  const parts = [];
@@ -9448,11 +9879,14 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9448
9879
  if (result.connectors && result.connectors.length) parts.push(`${result.connectors.length} 个 MCP 服务`);
9449
9880
  const summary = parts.length ? `${parts.join("、")}已就绪。` : "插件已安装就绪。";
9450
9881
  void showApplicationToast(showToast, result, "安装完成", summary);
9451
- setInstallFor(null);
9882
+ setInstallFor((cur) => (cur && cur.name === target.name && cur.sourceId === target.sourceId ? null : cur));
9452
9883
  await refreshState();
9453
9884
  onInstalled();
9454
9885
  } catch (e) {
9455
9886
  showToast("安装失败", e.message, { restart: false });
9887
+ } finally {
9888
+ installingNamesRef.current.delete(key);
9889
+ setInstallingNames((prev) => { if (!prev.has(key)) return prev; const next = new Set(prev); next.delete(key); return next; });
9456
9890
  }
9457
9891
  };
9458
9892
 
@@ -9462,7 +9896,6 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9462
9896
  // A removal can finish after the user has switched to another tab.
9463
9897
  if (SESSION_STORE.view !== view) return;
9464
9898
  setView(view.returnView || { type: "browse", sourceId: activeSourceId });
9465
- if (view.returnToMcp) setMcpsOpen(true);
9466
9899
  };
9467
9900
  const openPlugin = (plugin) => {
9468
9901
  closePluginHover();
@@ -9498,29 +9931,28 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9498
9931
  // MCP is a fixed entry pinned ahead of the source tabs; it has no
9499
9932
  // drag handlers, so it can never be reordered. It must also show
9500
9933
  // when only plugin-provided servers exist — the page lists both.
9501
- hasMcps && h("button", {
9934
+ showMcpTab && h("button", {
9502
9935
  key: "__mcps",
9503
- className: "cpm-tab" + (mcpsOpen ? " active" : ""),
9936
+ ref: (el) => { tabRefs.current["__mcps"] = el; },
9937
+ className: "cpm-tab" + (isMcpTab ? " active" : ""),
9504
9938
  onClick: () => {
9505
9939
  if (isSourceBrowse && gridRef.current) {
9506
9940
  if (!SESSION_STORE.scrollTops) SESSION_STORE.scrollTops = {};
9507
9941
  SESSION_STORE.scrollTops[activeSourceId] = gridRef.current.scrollTop;
9508
9942
  }
9509
9943
  stopScrollTopAnim();
9510
- setMcpsOpen(true); refreshMcps();
9944
+ setView(SESSION_STORE.mcpView);
9945
+ refreshMcps();
9946
+ if (isMcpTab) scrollActiveTabIntoView("__mcps", true);
9511
9947
  },
9512
9948
  }, h("span", null, "MCP")),
9513
9949
  state.sources.map((s, idx) => {
9514
9950
  if (s.id === "local" && !hasLocalPlugins) return null;
9515
- const isAnthropic = idx === 0 || s.builtin || (s.id && s.id.toLowerCase() === "anthropic");
9516
9951
  const isBeingDragged = dragState?.active && dragState.sourceId === s.id;
9517
9952
  let tabTransform = undefined;
9518
9953
  let tabClassExtra = "";
9519
9954
 
9520
- if (isAnthropic) {
9521
- tabTransform = undefined;
9522
- tabClassExtra = "";
9523
- } else if (dragState?.active) {
9955
+ if (dragState?.active) {
9524
9956
  if (isBeingDragged) {
9525
9957
  tabClassExtra = " is-placeholder";
9526
9958
  } else {
@@ -9547,21 +9979,21 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9547
9979
  return h("button", {
9548
9980
  key: s.id,
9549
9981
  ref: (el) => { tabRefs.current[s.id] = el; },
9550
- className: "cpm-tab" + (s.id === activeSourceId && !mcpsOpen ? " active" : "") + tabClassExtra,
9982
+ className: "cpm-tab" + (s.id === activeSourceId && !isMcpTab ? " active" : "") + tabClassExtra,
9551
9983
  style: tabTransform ? { transform: tabTransform } : undefined,
9552
9984
  onPointerDown: (e) => handleTabPointerDown(e, s, idx),
9553
9985
  onPointerMove: handleTabPointerMove,
9554
- onPointerUp: (e) => handleTabPointerUp(e, s, idx),
9986
+ onPointerUp: (e) => handleTabPointerUp(e, s),
9555
9987
  onPointerCancel: cancelOrResetDrag,
9556
9988
  onLostPointerCapture: (e) => {
9557
9989
  if (e.pointerId === dragLiveRef.current.pointerId && !dragLiveRef.current.isSnapping) cancelOrResetDrag();
9558
9990
  },
9559
9991
  onContextMenu: (e) => e.preventDefault(),
9560
9992
  onMouseDown: (e) => e.preventDefault(),
9561
- onClick: () => setMcpsOpen(false),
9993
+ onClick: (e) => { if (e.detail === 0) selectSourceTab(s.id); },
9562
9994
  },
9563
9995
  h("span", null, s.name),
9564
- !s.builtin && !s.virtual && h("span", {
9996
+ !s.virtual && h("span", {
9565
9997
  className: "cpm-tab-del-zone",
9566
9998
  onPointerDown: (e) => e.stopPropagation(),
9567
9999
  onClick: (e) => {
@@ -9590,70 +10022,65 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9590
10022
  ),
9591
10023
  h("div", { className: "cpm-topbar-right" },
9592
10024
  h("button", { className: "cpm-icon-btn" + (isRefreshing ? " is-refreshing" : ""), onClick: refresh, disabled: isRefreshing }, h(IconRefresh)),
9593
- activeSourceId !== "skills-local" && h("div", { style: { position: "relative" } },
9594
- h("button", { className: "cpm-filter" + (showFilter ? " open" : ""), onClick: () => { setShowFilter(!showFilter); setShowSort(false); } },
9595
- h("span", null, filter === "installed" ? "已安装" : (filter === "all" ? "全部插件" : "Filter by")),
10025
+ activeSourceId && activeSourceId !== "skills-local" && h("div", { style: { position: "relative" } },
10026
+ h("button", { type: "button", className: "cpm-filter" + (showFilter ? " open" : ""), "aria-expanded": showFilter, onClick: () => setOpenTopMenu((cur) => cur === "filter" ? null : "filter") },
10027
+ h("span", null, filter === "installed" ? "已安装" : "全部插件"),
9596
10028
  h("span", { className: "cpm-filter-chevron" }, h(IconArrow)),
9597
10029
  ),
9598
10030
  showFilter && h("div", { className: "cpm-menu-pop", style: { top: 34, right: 0, minWidth: 120 } },
9599
10031
  h("div", { className: "cpm-menu-item", onClick: () => {
9600
- setFilter("all");
9601
- setShowFilter(false);
10032
+ setOpenTopMenu(null);
10033
+ if (filter !== "installed") return;
9602
10034
  if (!SESSION_STORE.scrollTops) SESSION_STORE.scrollTops = {};
10035
+ for (const sourceId of installedFilterSources) delete SESSION_STORE.scrollTops[sourceId];
10036
+ setInstalledFilterSources(new Set());
9603
10037
  SESSION_STORE.scrollTops[activeSourceId] = 0;
9604
10038
  scrollContentToTop();
9605
10039
  } }, `全部插件 (${totalSourcePluginsCount})`),
9606
10040
  h("div", { className: "cpm-menu-item", onClick: () => {
9607
- setFilter("installed");
9608
- setShowFilter(false);
10041
+ setInstalledFilterSources(new Set(installedFilterSources).add(activeSourceId));
10042
+ setOpenTopMenu(null);
9609
10043
  if (!SESSION_STORE.scrollTops) SESSION_STORE.scrollTops = {};
9610
10044
  SESSION_STORE.scrollTops[activeSourceId] = 0;
9611
10045
  scrollContentToTop();
9612
- } }, "已安装"),
10046
+ } }, `已安装 (${totalInstalledCount})`),
9613
10047
  ),
9614
10048
  ),
9615
10049
  h("div", { style: { position: "relative" } },
9616
- h("button", { className: "cpm-sort" + (showSort ? " open" : ""), onClick: () => { setShowSort(!showSort); setShowFilter(false); } },
10050
+ h("button", { type: "button", className: "cpm-sort" + (showSort ? " open" : ""), "aria-expanded": showSort, onClick: () => setOpenTopMenu((cur) => cur === "sort" ? null : "sort") },
9617
10051
  h("span", null, sortBy === "name-asc" ? "名称 A-Z" : sortBy === "name-desc" ? "名称 Z-A" : "默认排序"),
9618
10052
  h("span", { className: "cpm-filter-chevron" }, h(IconArrow)),
9619
10053
  ),
9620
10054
  showSort && h("div", { className: "cpm-menu-pop", style: { top: 34, right: 0, minWidth: 120 } },
9621
10055
  h("div", { className: "cpm-menu-item", onClick: () => {
9622
10056
  setSortBy("default");
9623
- setShowSort(false);
9624
- if (!SESSION_STORE.scrollTops) SESSION_STORE.scrollTops = {};
9625
- SESSION_STORE.scrollTops[activeSourceId] = 0;
9626
- scrollContentToTop();
10057
+ setOpenTopMenu(null);
9627
10058
  } }, "默认排序"),
9628
10059
  h("div", { className: "cpm-menu-item", onClick: () => {
9629
10060
  setSortBy("name-asc");
9630
- setShowSort(false);
9631
- if (!SESSION_STORE.scrollTops) SESSION_STORE.scrollTops = {};
9632
- SESSION_STORE.scrollTops[activeSourceId] = 0;
9633
- scrollContentToTop();
10061
+ setOpenTopMenu(null);
9634
10062
  } }, "名称 (A-Z)"),
9635
10063
  h("div", { className: "cpm-menu-item", onClick: () => {
9636
10064
  setSortBy("name-desc");
9637
- setShowSort(false);
9638
- if (!SESSION_STORE.scrollTops) SESSION_STORE.scrollTops = {};
9639
- SESSION_STORE.scrollTops[activeSourceId] = 0;
9640
- scrollContentToTop();
10065
+ setOpenTopMenu(null);
9641
10066
  } }, "名称 (Z-A)"),
9642
10067
  ),
9643
10068
  ),
9644
10069
  h("div", { style: { position: "relative" } },
9645
10070
  h("button", {
10071
+ type: "button",
9646
10072
  className: "cpm-add-btn" + (showAddMenu ? " open" : ""),
10073
+ "aria-expanded": showAddMenu,
9647
10074
  style: { width: "auto", padding: "0 8px", gap: 3 },
9648
- onClick: () => { setShowAddMenu(!showAddMenu); },
10075
+ onClick: () => setOpenTopMenu((cur) => cur === "add" ? null : "add"),
9649
10076
  },
9650
10077
  h(IconPlus),
9651
10078
  h("span", { className: "cpm-filter-chevron" }, h(IconArrow)),
9652
10079
  ),
9653
10080
  showAddMenu && h("div", { className: "cpm-menu-pop", style: { top: 34, right: 0, minWidth: 150 } },
9654
- h("div", { className: "cpm-menu-item", onClick: () => { setShowAddMenu(false); setAddDialog({ initialPhase: "url" }); } }, "添加插件市场"),
9655
- h("div", { className: "cpm-menu-item", onClick: () => { setShowAddMenu(false); setAddDialog({ initialPhase: "upload" }); } }, "上传插件 / Skills"),
9656
- h("div", { className: "cpm-menu-item", onClick: () => { setShowAddMenu(false); setEditMcp(null); setMcpDialog(true); } }, "添加 MCP"),
10081
+ h("div", { className: "cpm-menu-item", onClick: () => { setOpenTopMenu(null); setAddDialog({ initialPhase: "url" }); } }, "添加插件市场"),
10082
+ h("div", { className: "cpm-menu-item", onClick: () => { setOpenTopMenu(null); setAddDialog({ initialPhase: "upload" }); } }, "上传插件 / Skills"),
10083
+ h("div", { className: "cpm-menu-item", onClick: () => { setOpenTopMenu(null); setEditMcp(null); setMcpDialog(true); } }, "添加 MCP"),
9657
10084
  ),
9658
10085
  ),
9659
10086
  ),
@@ -9686,16 +10113,26 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9686
10113
  pluginRecord: state.plugins.find((r) => r.name === currentDetailPlugin.name),
9687
10114
  scrollState: view,
9688
10115
  isDark,
10116
+ installing: Boolean(currentDetailPlugin && isPluginInstalling(currentDetailPlugin.name)),
9689
10117
  containerRef: detailContainerRef,
10118
+ canDeleteLocal: (currentDetailPlugin.sourceId || view.sourceId || activeSourceId) === "local" && state.sources.some((s) => s.id === "local"),
10119
+ localSourceName: state.sources.find((s) => s.id === "local")?.name || "Local Plugins",
9690
10120
  onBack: () => setView({ type: "browse", sourceId: activeSourceId }),
9691
- onInstall: () => setInstallFor(currentDetailPlugin),
10121
+ onInstall: () => { if (!installDialogBusyRef.current && !installingNamesRef.current.has(String(currentDetailPlugin.name || "").toLowerCase())) setInstallFor(currentDetailPlugin); },
9692
10122
  onRemove: () => removePlugin(currentDetailPlugin.name),
10123
+ onDeleteLocal: () => deleteLocalPlugin(currentDetailPlugin),
9693
10124
  onManage: () => openManage(state.plugins.find((r) => r.name === currentDetailPlugin.name), { type: "detail", sourceId: activeSourceId, plugin: currentDetailPlugin }),
9694
10125
  onTogglePlugin: async (enabled) => {
9695
10126
  const res = await api("/plugins/" + encodeURIComponent(currentDetailPlugin.name) + "/toggle", {
9696
10127
  method: "POST",
9697
10128
  body: JSON.stringify({ enabled }),
9698
10129
  });
10130
+ if (res?.ok !== false) {
10131
+ const targetRecord = res?.plugin || state.plugins.find((r) => r.name === currentDetailPlugin.name);
10132
+ if (targetRecord && typeof syncPluginToggleCooldown === "function") {
10133
+ syncPluginToggleCooldown(targetRecord, enabled);
10134
+ }
10135
+ }
9699
10136
  if (res?.ok !== false && res?.plugin && patchPluginInState) {
9700
10137
  patchPluginInState(res.plugin);
9701
10138
  void refreshState();
@@ -9728,7 +10165,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9728
10165
  h("div", { className: "cpm-installed-group-header" },
9729
10166
  h("div", { className: "cpm-installed-group-title-wrap" },
9730
10167
  h("span", { className: "cpm-installed-group-title" }, grp.source.name),
9731
- h("span", { className: "cpm-badge" }, grp.plugins.length),
10168
+ renderCountBadge(grp.plugins.length),
9732
10169
  ),
9733
10170
  idx > 0 && h("div", { className: "cpm-installed-group-line" }),
9734
10171
  ),
@@ -9798,6 +10235,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9798
10235
  iconPlugin: resolveMarketplaceIcon(p),
9799
10236
  eagerIcon: index < 12,
9800
10237
  installed,
10238
+ installing: isPluginInstalling(p.name),
9801
10239
  isDark,
9802
10240
  onMouseEnter: (e) => handleCardMouseEnter(p, e.currentTarget, { x: e.clientX, y: e.clientY, buttons: e.buttons }),
9803
10241
  onMouseLeave: () => handleCardMouseLeave(p),
@@ -9809,43 +10247,42 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9809
10247
  onInstall: (e) => {
9810
10248
  e.stopPropagation();
9811
10249
  closePluginHover();
9812
- setInstallFor(p);
10250
+ if (!installDialogBusyRef.current && !installingNamesRef.current.has(String(p.name || "").toLowerCase())) {
10251
+ setInstallFor(p);
10252
+ }
9813
10253
  },
9814
10254
  });
9815
10255
  }),
9816
10256
  ],
9817
10257
  ),
9818
10258
 
9819
- isBrowse && mcpsOpen && h("div", {
9820
- ref: gridRef,
9821
- className: "cpm-grid-container" + gridMaskClass,
9822
- onWheelCapture: globalHover.suspend,
9823
- onScroll: () => { globalHover.suspend(); updateGridMask(); },
9824
- },
9825
- !hasMcps && h("div", { className: "cpm-empty", style: { textAlign: "center", padding: "40px 16px" } }, "还没有添加 MCP,点右上角「添加」→「添加 MCP」"),
9826
- h(McpOverview, {
9827
- serverRows: mcps.map((m, i) => renderMcpServerRow({
9828
- owner: "user-mcp",
9829
- row: m,
9830
- name: m.name,
9831
- transport: m.transport,
9832
- connected: m.enabled === true,
9833
- canEdit: true,
9834
- first: i === 0,
9835
- })),
9836
- pluginRows: pluginMcpRows.map((r, i) => renderMcpServerRow({
9837
- owner: r.owner,
9838
- record: r.record,
9839
- plugin: r.record,
9840
- name: r.name,
9841
- transport: r.type,
9842
- connected: r.connected,
9843
- conn: r.conn,
9844
- canEdit: false,
9845
- first: i === 0,
9846
- })),
9847
- }),
9848
- ),
10259
+ mcpsOpen && h(McpOverview, {
10260
+ containerRef: mcpGridRef,
10261
+ scrollState: view,
10262
+ maskClass: gridMaskClass,
10263
+ updateMask: updateGridMask,
10264
+ suspendHover: globalHover.suspend,
10265
+ serverRows: mcps.map((m, i) => renderMcpServerRow({
10266
+ owner: "user-mcp",
10267
+ row: m,
10268
+ name: m.name,
10269
+ transport: m.transport,
10270
+ connected: m.enabled === true,
10271
+ canEdit: true,
10272
+ first: i === 0,
10273
+ })),
10274
+ pluginRows: pluginMcpRows.map((r, i) => renderMcpServerRow({
10275
+ owner: r.owner,
10276
+ record: r.record,
10277
+ plugin: r.record,
10278
+ name: r.name,
10279
+ transport: r.type,
10280
+ connected: r.connected,
10281
+ conn: r.conn,
10282
+ canEdit: false,
10283
+ first: i === 0,
10284
+ })),
10285
+ }),
9849
10286
 
9850
10287
  globalHoveredTool && isBrowse && mcpsOpen && h(McpToolPopover, {
9851
10288
  hovered: globalHoveredTool,
@@ -9868,7 +10305,8 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9868
10305
  installFor && h(InstallDialog, {
9869
10306
  plugin: installFor,
9870
10307
  isDark,
9871
- onCancel: () => setInstallFor(null),
10308
+ onBusyChange: (v) => { installDialogBusyRef.current = !!v; },
10309
+ onCancel: () => { if (!installDialogBusyRef.current) setInstallFor(null); },
9872
10310
  onConfirm: doInstall,
9873
10311
  }),
9874
10312
 
@@ -9885,7 +10323,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9885
10323
  setRows((prev) => ({ ...prev, [newSourceId]: market.plugins }));
9886
10324
  setState((prev) => prev.sources.some((source) => source.id === newSourceId)
9887
10325
  ? prev : { ...prev, sources: [...prev.sources, market.source] });
9888
- if (newSourceId !== activeSourceId) setActiveSourceId(newSourceId);
10326
+ if (isMcpTab || newSourceId !== activeSourceId) setActiveSourceId(newSourceId);
9889
10327
  void refreshState({ quiet: true });
9890
10328
  return;
9891
10329
  }
@@ -9909,7 +10347,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9909
10347
  }
9910
10348
  } catch {}
9911
10349
  };
9912
- if (newSourceId !== activeSourceId) setActiveSourceId(newSourceId);
10350
+ if (isMcpTab || newSourceId !== activeSourceId) setActiveSourceId(newSourceId);
9913
10351
  // A tab that is already active has no effect to re-run for the
9914
10352
  // same id, and the Skills tab has no browse effect at all, so
9915
10353
  // both need the load here. A newly opened market tab refetches
@@ -9927,7 +10365,8 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9927
10365
  onSaved: async () => {
9928
10366
  await refreshMcps();
9929
10367
  await refreshState();
9930
- setMcpsOpen(true);
10368
+ if (browseUnmountedRef.current) return;
10369
+ if (SESSION_STORE.view === view) setView(SESSION_STORE.mcpView);
9931
10370
  setMcpDialog(false);
9932
10371
  setEditMcp(null);
9933
10372
  setEditMcpOwner(null);
@@ -9935,7 +10374,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9935
10374
  showToast,
9936
10375
  }),
9937
10376
 
9938
- confirmRemoveSource && h("div", { className: "cpm-dialog", ...backdropDismissProps(() => setConfirmRemoveSource(null)) },
10377
+ confirmRemoveSource && h("div", { className: "cpm-dialog", ...backdropDismissProps(() => { if (!busy) setConfirmRemoveSource(null); }) },
9939
10378
  h(ConfirmDialogBox, {
9940
10379
  titleId: "cpm-confirm-remove-source-title",
9941
10380
  title: `删除插件源「${confirmRemoveSource.name}」`,
@@ -9952,38 +10391,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9952
10391
  try {
9953
10392
  await api("/sources/" + encodeURIComponent(toRemove.id), { method: "DELETE" });
9954
10393
  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);
9974
- }
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));
10394
+ cleanupRemovedSource(toRemove.id);
9987
10395
  try { await refreshState(); } catch {}
9988
10396
  } catch (e) {
9989
10397
  showToast("删除失败", cleanError(e), { restart: false });
@@ -10089,10 +10497,34 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10089
10497
  }
10090
10498
 
10091
10499
  // ────────────────────────────── Modern Install Dialog ──────────────────────────────
10092
- function InstallDialog({ plugin, isDark, onCancel, onConfirm }) {
10093
- const [busy, setBusy] = useState(false);
10500
+ function InstallDialog({ plugin, isDark, onCancel, onConfirm, onBusyChange }) {
10501
+ const [busy, setBusyState] = useState(false);
10502
+ const busyRef = useRef(false);
10503
+ const unmountedRef = useRef(false);
10504
+ useEffect(() => () => { unmountedRef.current = true; }, []);
10505
+ const setBusy = (next) => {
10506
+ const val = !!next;
10507
+ busyRef.current = val;
10508
+ if (!unmountedRef.current) {
10509
+ setBusyState(val);
10510
+ if (typeof onBusyChange === "function") onBusyChange(val);
10511
+ }
10512
+ };
10513
+ const handleCancel = () => {
10514
+ if (busyRef.current) return;
10515
+ onCancel();
10516
+ };
10517
+ const handleConfirm = async () => {
10518
+ if (busyRef.current) return;
10519
+ setBusy(true);
10520
+ try {
10521
+ await onConfirm();
10522
+ } finally {
10523
+ setBusy(false);
10524
+ }
10525
+ };
10094
10526
  const titleId = "cpm-install-dialog-title";
10095
- return h("div", { className: "cpm-dialog", ...backdropDismissProps(onCancel) },
10527
+ return h("div", { className: "cpm-dialog", ...backdropDismissProps(handleCancel) },
10096
10528
  h("div", {
10097
10529
  className: "cpm-dialog-box cpm-install-dialog",
10098
10530
  role: "dialog",
@@ -10109,11 +10541,11 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10109
10541
  ),
10110
10542
  plugin.description && h("div", { className: "cpm-install-desc" }, plugin.description),
10111
10543
  h("div", { className: "cpm-dialog-actions", style: { marginTop: 18 } },
10112
- h("button", { className: "cpm-btn cpm-btn-secondary", onClick: onCancel, disabled: busy }, "取消"),
10544
+ h("button", { className: "cpm-btn cpm-btn-secondary", onClick: handleCancel, disabled: busy }, "取消"),
10113
10545
  h("button", {
10114
10546
  className: "cpm-btn cpm-btn-primary",
10115
10547
  disabled: busy,
10116
- onClick: async () => { setBusy(true); await onConfirm(); setBusy(false); },
10548
+ onClick: handleConfirm,
10117
10549
  }, busy ? "正在安装…" : "确认安装"),
10118
10550
  ),
10119
10551
  ),
@@ -10141,6 +10573,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10141
10573
  const [pluginCount, setPluginCount] = useState(0);
10142
10574
  const [busy, setBusyState] = useState(false);
10143
10575
  const [uploadProgress, setUploadProgress] = useState(null);
10576
+ const [importProgress, setImportProgress] = useState(null);
10144
10577
  const [isDragging, setIsDragging] = useState(false);
10145
10578
  const [localPreview, setLocalPreview] = useState(null);
10146
10579
  const [localDuplicate, setLocalDuplicate] = useState(null);
@@ -10385,11 +10818,22 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10385
10818
  const clean = String(rawPath || "").trim();
10386
10819
  if (!clean) return;
10387
10820
  const payload = { path: clean };
10821
+ const baseName = clean.split(/[\\/]/).pop() || clean;
10388
10822
  setBusy(true);
10823
+ setUploadProgress(null);
10389
10824
  try {
10390
10825
  const res = await api("/plugins/local/inspect", {
10391
10826
  method: "POST",
10392
10827
  body: JSON.stringify(payload)
10828
+ }, (evt) => {
10829
+ if (unmountedRef.current) return;
10830
+ setUploadProgress((prev) => ({
10831
+ ...(prev || {}),
10832
+ stage: evt.stage || "extracting",
10833
+ percent: Math.max(prev?.percent || 0, Math.min(99, Number(evt.percent) || 0)),
10834
+ detail: evt.detail || prev?.detail || "",
10835
+ filename: baseName,
10836
+ }));
10393
10837
  });
10394
10838
  if (unmountedRef.current) return;
10395
10839
  if (!res.ok) {
@@ -10401,7 +10845,10 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10401
10845
  if (unmountedRef.current) return;
10402
10846
  showToast("不符合规范,不可以上传", cleanError(e), { restart: false });
10403
10847
  } finally {
10404
- if (!unmountedRef.current) setBusy(false);
10848
+ if (!unmountedRef.current) {
10849
+ setBusy(false);
10850
+ setUploadProgress(null);
10851
+ }
10405
10852
  }
10406
10853
  };
10407
10854
 
@@ -10474,37 +10921,114 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10474
10921
  activeXhrRef.current = xhr;
10475
10922
  xhr.open("POST", "/universal-plugin-hub/api/plugins/local/inspect?filename=" + encodeURIComponent(file.name || "plugin.zip"), true);
10476
10923
  xhr.setRequestHeader("Content-Type", "application/octet-stream");
10924
+ xhr.setRequestHeader("Accept", "application/x-ndjson");
10477
10925
  xhr.timeout = 0;
10926
+
10927
+ let parsedOffset = 0;
10928
+ let streamResult = null;
10929
+ let hasStreamResult = false;
10930
+ let streamError = null;
10931
+
10932
+ const consumeStreamChunks = (flushAll = false) => {
10933
+ const text = String(xhr.responseText || "");
10934
+ if (text.length <= parsedOffset) return;
10935
+ let end = text.length;
10936
+ if (!flushAll) {
10937
+ const lastNl = text.lastIndexOf("\n");
10938
+ if (lastNl < parsedOffset) return;
10939
+ end = lastNl + 1;
10940
+ }
10941
+ const chunk = text.slice(parsedOffset, end);
10942
+ parsedOffset = end;
10943
+ for (const rawLine of chunk.split("\n")) {
10944
+ const line = rawLine.trim();
10945
+ if (!line) continue;
10946
+ let msg;
10947
+ try { msg = JSON.parse(line); } catch { continue; }
10948
+ if (!msg || typeof msg !== "object") continue;
10949
+ if (msg.type === "progress") {
10950
+ const pct = Math.min(99, Math.max(0, Number(msg.percent) || 0));
10951
+ setUploadProgress((prev) => ({
10952
+ ...(prev || {}),
10953
+ stage: msg.stage || "extracting",
10954
+ percent: Math.max(prev?.percent || 0, pct),
10955
+ detail: msg.detail || prev?.detail || "",
10956
+ extracted: msg.extracted,
10957
+ totalEntries: msg.totalEntries,
10958
+ filename: file.name,
10959
+ }));
10960
+ } else if (msg.type === "result") {
10961
+ streamResult = msg.data;
10962
+ hasStreamResult = true;
10963
+ setUploadProgress((prev) => ({
10964
+ ...(prev || {}),
10965
+ stage: "finalizing",
10966
+ percent: 100,
10967
+ detail: "解析完成",
10968
+ filename: file.name,
10969
+ }));
10970
+ } else if (msg.type === "error") {
10971
+ const err = new Error(msg.error || "解析失败");
10972
+ err.status = msg.status || 500;
10973
+ streamError = err;
10974
+ }
10975
+ }
10976
+ };
10977
+
10478
10978
  if (xhr.upload) {
10479
10979
  xhr.upload.onprogress = (ev) => {
10480
10980
  if (unmountedRef.current) return;
10481
10981
  const total = ev.lengthComputable && ev.total > 0 ? ev.total : (file.size || 0);
10482
10982
  const loaded = total > 0 ? Math.min(ev.loaded, total) : ev.loaded;
10483
- const percent = total > 0 ? Math.min(100, Math.round((loaded / total) * 100)) : 0;
10484
- setUploadProgress({
10485
- stage: percent >= 100 ? "parsing" : "uploading",
10983
+ const doneUpload = total > 0 && loaded >= total;
10984
+ const percent = total > 0 ? Math.min(30, Math.round((loaded / total) * 30)) : 0;
10985
+ setUploadProgress((prev) => ({
10986
+ ...(prev || {}),
10987
+ stage: doneUpload ? (prev?.stage && prev.stage !== "uploading" ? prev.stage : "extracting") : "uploading",
10486
10988
  loaded,
10487
10989
  total,
10488
- percent,
10990
+ percent: doneUpload ? Math.max(prev?.percent || 0, 30) : Math.max(prev?.percent || 0, percent),
10991
+ detail: doneUpload ? (prev?.detail || "上传完成,正在解压档案…") : undefined,
10489
10992
  filename: file.name,
10490
- });
10993
+ }));
10491
10994
  };
10492
10995
  xhr.upload.onload = () => {
10493
10996
  if (unmountedRef.current) return;
10494
10997
  setUploadProgress((prev) => ({
10495
- stage: "parsing",
10998
+ ...(prev || {}),
10999
+ stage: prev?.stage && prev.stage !== "uploading" ? prev.stage : "extracting",
10496
11000
  loaded: file.size || prev?.total || 0,
10497
11001
  total: file.size || prev?.total || 0,
10498
- percent: 100,
11002
+ percent: Math.max(prev?.percent || 0, 30),
11003
+ detail: prev?.detail || "上传完成,正在解压档案…",
10499
11004
  filename: file.name,
10500
11005
  }));
10501
11006
  };
10502
11007
  }
11008
+ xhr.onprogress = () => {
11009
+ if (unmountedRef.current) return;
11010
+ consumeStreamChunks(false);
11011
+ };
10503
11012
  const clearXhr = () => {
10504
11013
  if (activeXhrRef.current === xhr) activeXhrRef.current = null;
10505
11014
  };
10506
11015
  xhr.onload = () => {
10507
11016
  clearXhr();
11017
+ consumeStreamChunks(true);
11018
+ if (streamError) {
11019
+ reject(streamError);
11020
+ return;
11021
+ }
11022
+ if (hasStreamResult) {
11023
+ if (xhr.status >= 200 && xhr.status < 300) {
11024
+ resolve(streamResult || {});
11025
+ return;
11026
+ }
11027
+ const err = new Error((streamResult && streamResult.error) || `HTTP ${xhr.status}`);
11028
+ err.status = xhr.status;
11029
+ reject(err);
11030
+ return;
11031
+ }
10508
11032
  let body = null;
10509
11033
  try { body = JSON.parse(xhr.responseText || "null"); } catch {}
10510
11034
  if (xhr.status >= 200 && xhr.status < 300) {
@@ -10551,16 +11075,27 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10551
11075
  const data = await fileToBase64(file);
10552
11076
  if (unmountedRef.current) return;
10553
11077
  setUploadProgress((prev) => ({
10554
- stage: "parsing",
11078
+ stage: "extracting",
10555
11079
  loaded: file.size || prev?.total || 0,
10556
11080
  total: file.size || prev?.total || 0,
10557
- percent: 100,
11081
+ percent: 30,
11082
+ detail: "上传完成,正在解压档案…",
10558
11083
  filename: file.name,
10559
11084
  }));
10560
11085
  payload = { data, filename: file.name };
10561
11086
  res = await api("/plugins/local/inspect", {
10562
11087
  method: "POST",
10563
11088
  body: JSON.stringify(payload)
11089
+ }, (evt) => {
11090
+ if (unmountedRef.current) return;
11091
+ const pct = Math.min(99, Math.max(30, Number(evt?.percent) || 30));
11092
+ setUploadProgress((prev) => ({
11093
+ ...(prev || {}),
11094
+ stage: evt.stage || "extracting",
11095
+ percent: Math.max(prev?.percent || 0, pct),
11096
+ detail: evt.detail || prev?.detail || "",
11097
+ filename: file.name,
11098
+ }));
10564
11099
  });
10565
11100
  if (res?.uploadId) payload = { uploadId: res.uploadId, filename: file.name };
10566
11101
  }
@@ -10598,6 +11133,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10598
11133
  async function handleImportLocal(payload, overwrite, sourceName, kindOverride, overwriteNames, targetOverride) {
10599
11134
  if (busyRef.current) return;
10600
11135
  setBusy(true);
11136
+ setImportProgress(null);
10601
11137
  try {
10602
11138
  // A pure skill package must not go through the plugin pipeline:
10603
11139
  // it belongs in the Skills tab as a directly managed skill.
@@ -10614,6 +11150,13 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10614
11150
  body: JSON.stringify(isSkillPackage
10615
11151
  ? { ...payload, overwrite, ...(overwriteNames?.length ? { overwriteNames } : {}) }
10616
11152
  : { ...payload, overwrite, sourceName, ...(targetOverride ? { target: targetOverride } : {}) })
11153
+ }, (evt) => {
11154
+ if (unmountedRef.current) return;
11155
+ setImportProgress((prev) => ({
11156
+ stage: evt.stage || "copying",
11157
+ percent: Math.max(prev?.percent || 0, Math.min(99, Number(evt.percent) || 0)),
11158
+ detail: evt.detail || prev?.detail || "",
11159
+ }));
10617
11160
  });
10618
11161
  if (payload?.uploadId && payload.uploadId === stagedUploadIdRef.current) {
10619
11162
  stagedUploadIdRef.current = null;
@@ -10667,7 +11210,10 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10667
11210
  }
10668
11211
  showToast("添加本地插件失败", msg, { restart: false });
10669
11212
  } finally {
10670
- if (!unmountedRef.current) setBusy(false);
11213
+ if (!unmountedRef.current) {
11214
+ setBusy(false);
11215
+ setImportProgress(null);
11216
+ }
10671
11217
  }
10672
11218
  }
10673
11219
 
@@ -10717,7 +11263,10 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10717
11263
  if (unmountedRef.current) return;
10718
11264
  showToast("校验失败", cleanError(e), { restart: false });
10719
11265
  } finally {
10720
- if (!unmountedRef.current) setBusy(false);
11266
+ if (!unmountedRef.current) {
11267
+ setBusy(false);
11268
+ setImportProgress(null);
11269
+ }
10721
11270
  }
10722
11271
  };
10723
11272
 
@@ -10742,15 +11291,28 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10742
11291
  if (unmountedRef.current) return;
10743
11292
  showToast("添加源失败", cleanError(e), { restart: false });
10744
11293
  } finally {
10745
- if (!unmountedRef.current) setBusy(false);
11294
+ if (!unmountedRef.current) {
11295
+ setBusy(false);
11296
+ setImportProgress(null);
11297
+ }
10746
11298
  }
10747
11299
  };
10748
11300
 
10749
11301
  const urlBusyLabel = isLocalPath(url) ? "正在解析…" : "正在安装…";
10750
- const inlineBusyProgress = () => busy && h("div", { className: "cpm-upload-inline-progress", key: "imp-prog" },
10751
- h("progress", { className: "cpm-upload-progress", "aria-label": "正在导入插件" }),
10752
- h("div", { className: "cpm-upload-status", role: "status", "aria-live": "polite", style: { marginTop: 0 } }, "正在导入文件,请勿关闭弹窗…"),
10753
- );
11302
+ const inlineBusyProgress = () => {
11303
+ if (!busy) return null;
11304
+ const hasDet = importProgress && typeof importProgress.percent === "number";
11305
+ return h("div", { className: "cpm-upload-inline-progress", key: "imp-prog" },
11306
+ hasDet && h("div", { className: "cpm-upload-progress-meta" },
11307
+ h("span", null, importProgress.detail || "正在导入文件…"),
11308
+ h("span", null, `${importProgress.percent}%`),
11309
+ ),
11310
+ hasDet
11311
+ ? h("progress", { className: "cpm-upload-progress", max: 100, value: importProgress.percent, "aria-label": "正在导入插件" })
11312
+ : h("progress", { className: "cpm-upload-progress", "aria-label": "正在导入插件" }),
11313
+ !hasDet && h("div", { className: "cpm-upload-status", role: "status", "aria-live": "polite", style: { marginTop: 0 } }, "正在导入文件,请勿关闭弹窗…"),
11314
+ );
11315
+ };
10754
11316
 
10755
11317
  return h("div", { className: "cpm-dialog" },
10756
11318
  h("div", {
@@ -10833,26 +11395,30 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10833
11395
  busy ? h("span", { className: "cpm-spin-ring", style: { width: 18, height: 18, borderWidth: 2 } }) : h(UploadDropIcon)
10834
11396
  ),
10835
11397
  h("span", { className: "cpm-dropzone-title" }, busy
10836
- ? (uploadProgress?.stage === "uploading" ? "正在流式上传文件…" : "正在解压并解析文件…")
11398
+ ? (uploadProgress?.stage === "uploading"
11399
+ ? "正在流式上传文件…"
11400
+ : uploadProgress?.stage === "extracting"
11401
+ ? "正在解压档案…"
11402
+ : (uploadProgress?.stage === "analyzing" || uploadProgress?.stage === "finalizing" || uploadProgress?.stage === "parsing")
11403
+ ? "正在解析插件内容…"
11404
+ : "正在解压并解析文件…")
10837
11405
  : "拖入插件 / Skills,或点击上传"),
10838
11406
  busy
10839
11407
  ? h("span", { className: "cpm-upload-progress-wrap" },
10840
11408
  h("span", { className: "cpm-upload-progress-meta" },
10841
11409
  h("span", null, uploadProgress?.stage === "uploading" && uploadProgress.total > 0
10842
11410
  ? `${formatUploadBytes(uploadProgress.loaded)} / ${formatUploadBytes(uploadProgress.total)}`
10843
- : (uploadProgress?.stage === "parsing"
10844
- ? (uploadProgress.filename || "等待服务端完成解析")
10845
- : "正在校验本地路径与清单")),
10846
- h("span", null, uploadProgress?.stage === "uploading" && uploadProgress.total > 0
11411
+ : (uploadProgress?.detail || uploadProgress?.filename || "正在校验本地路径与清单")),
11412
+ h("span", null, (typeof uploadProgress?.percent === "number" && (uploadProgress.total > 0 || uploadProgress.stage !== "uploading"))
10847
11413
  ? `${uploadProgress.percent}%`
10848
11414
  : "请勿关闭弹窗"),
10849
11415
  ),
10850
- uploadProgress?.stage === "uploading" && uploadProgress.total > 0
11416
+ (typeof uploadProgress?.percent === "number" && (uploadProgress.total > 0 || uploadProgress.stage !== "uploading"))
10851
11417
  ? h("progress", {
10852
11418
  className: "cpm-upload-progress",
10853
11419
  max: 100,
10854
11420
  value: uploadProgress.percent,
10855
- "aria-label": "文件上传进度",
11421
+ "aria-label": uploadProgress?.stage === "uploading" ? "文件上传进度" : "文件解压与解析进度",
10856
11422
  })
10857
11423
  : h("progress", {
10858
11424
  className: "cpm-upload-progress",
@@ -10879,8 +11445,8 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10879
11445
  busy && h("div", { className: "cpm-upload-status", role: "status", "aria-live": "polite", key: "status" },
10880
11446
  uploadProgress?.stage === "uploading"
10881
11447
  ? `正在上传${uploadProgress?.filename ? `「${uploadProgress.filename}」` : "文件"},上传与解析完成前无法关闭…`
10882
- : uploadProgress?.stage === "parsing"
10883
- ? "文件已上传,正在等待服务端解压与识别,请勿关闭弹窗…"
11448
+ : (uploadProgress?.stage === "extracting" || uploadProgress?.stage === "analyzing" || uploadProgress?.stage === "finalizing" || uploadProgress?.stage === "parsing")
11449
+ ? (uploadProgress.detail ? `${uploadProgress.detail},请勿关闭弹窗…` : "正在解压并识别插件内容,请勿关闭弹窗…")
10884
11450
  : "正在读取并解析本地内容,完成前无法关闭…"
10885
11451
  ),
10886
11452
  h("div", { className: "cpm-dialog-actions", key: "a" },
@@ -11109,20 +11675,18 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
11109
11675
  ],
11110
11676
  phase === "local-duplicate" && localDuplicate && [
11111
11677
  h("div", { className: "cpm-source-header", key: "header" },
11112
- h("div", { className: "cpm-source-header-title", id: "cpm-dialog-title", style: { color: "#d97706" } }, "存在同名插件 / Skills"),
11678
+ h("h2", { className: "cpm-source-header-title cpm-dup-title", id: "cpm-dialog-title" }, "存在同名插件 / Skills"),
11113
11679
  h("div", { className: "cpm-source-meta-row" },
11114
11680
  h("span", { className: "cpm-source-repo-text" }, localDuplicate.plugin.name),
11115
11681
  localDuplicate.localTabName && h("span", { className: "cpm-source-meta-sep" }, "·"),
11116
11682
  localDuplicate.localTabName && h("span", { className: "cpm-source-count-text" }, `目标标签:${localDuplicate.localTabName}`),
11117
- formatVersionBadge(localDuplicate.existingVersion) && h("span", { className: "cpm-source-meta-sep" }, "·"),
11118
- formatVersionBadge(localDuplicate.existingVersion) && h("span", { className: "cpm-source-count-text" }, `已安装版本: ${formatVersionBadge(localDuplicate.existingVersion)}`),
11119
11683
  ),
11120
11684
  ),
11121
- h("div", { className: "cpm-local-dup-card", key: "info" },
11685
+ h("div", { className: "cpm-dup-body", key: "info" },
11122
11686
  localDuplicate.conflicts?.length > 1
11123
11687
  ? [
11124
- h("div", { key: "desc", style: { fontSize: 12.5, fontWeight: 600, color: "var(--cpm-text)", marginBottom: 4 } },
11125
- `「${localDuplicate.localTabName || "本地插件"}」中已存在 ${localDuplicate.conflicts.length} 个同名插件,覆盖更新将完整替换旧文件与已安装版本:`),
11688
+ h("div", { key: "desc", className: "cpm-dup-multi-lead" },
11689
+ `已有 ${localDuplicate.conflicts.length} 个同名插件将被新版本覆盖`),
11126
11690
  h("ul", { className: "cpm-local-dup-list", key: "clist" }, localDuplicate.conflicts.map((c) => {
11127
11691
  const oldVer = formatVersionBadge(c.existingVersion) || "未声明";
11128
11692
  const newVer = formatVersionBadge(c.newVersion) || "未声明";
@@ -11130,45 +11694,43 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
11130
11694
  h("span", { className: "cpm-local-dup-item-name" }, c.displayName || c.name),
11131
11695
  h("span", { className: "cpm-local-dup-item-vers" },
11132
11696
  h("span", null, oldVer),
11133
- h("span", null, "→"),
11697
+ h("span", { "aria-hidden": "true" }, "→"),
11134
11698
  h("span", { className: "cpm-local-dup-item-new" }, newVer),
11135
11699
  ),
11136
11700
  );
11137
11701
  })),
11138
11702
  ]
11139
11703
  : [
11140
- h("div", { key: "top", style: { display: "flex", alignItems: "center", gap: 12, marginBottom: 8 } },
11704
+ h("div", { key: "top", className: "cpm-dup-identity" },
11141
11705
  h(PluginIcon, { plugin: localDuplicate.plugin, isDark }),
11142
- h("div", null,
11143
- h("div", { style: { fontSize: 14, fontWeight: 700, color: "var(--cpm-text)" } }, localDuplicate.plugin.displayName || localDuplicate.plugin.name),
11144
- h("div", { style: { fontSize: 11.5, color: "var(--cpm-muted)" } }, `标识:${localDuplicate.plugin.name}`),
11145
- ),
11706
+ h("div", { className: "cpm-dup-name" }, localDuplicate.plugin.displayName || localDuplicate.plugin.name),
11146
11707
  ),
11147
- h("div", { className: "cpm-local-dup-grid", key: "grid" },
11148
- h("div", null,
11149
- h("div", { style: { color: "var(--cpm-muted)", fontSize: 11, marginBottom: 2 } }, "当前已安装版本"),
11150
- h("div", { style: { fontWeight: 600, color: "var(--cpm-text)", fontVariantNumeric: "tabular-nums" } }, formatVersionBadge(localDuplicate.existingVersion) || "未声明"),
11151
- localDuplicate.existingUpdatedAt && h("div", { style: { fontSize: 10.5, color: "var(--cpm-muted)", marginTop: 2 } }, new Date(localDuplicate.existingUpdatedAt).toLocaleDateString()),
11708
+ h("div", { className: "cpm-dup-compare", key: "grid" },
11709
+ h("div", { className: "cpm-dup-ver-col" },
11710
+ h("div", { className: "cpm-dup-ver-label" }, "当前版本"),
11711
+ h("div", { className: "cpm-dup-ver-value" }, formatVersionBadge(localDuplicate.existingVersion) || "未声明"),
11712
+ h("div", { className: "cpm-dup-ver-sub" }, localDuplicate.existingUpdatedAt ? new Date(localDuplicate.existingUpdatedAt).toLocaleDateString() : "已存在"),
11152
11713
  ),
11153
- h("div", null,
11154
- h("div", { style: { color: "var(--cpm-muted)", fontSize: 11, marginBottom: 2 } }, "新导入版本"),
11155
- h("div", { style: { fontWeight: 600, color: "#10b981", fontVariantNumeric: "tabular-nums" } }, formatVersionBadge(localDuplicate.plugin.version) || "未声明"),
11156
- h("div", { style: { fontSize: 10.5, color: "var(--cpm-muted)", marginTop: 2 } }, "准备覆盖"),
11714
+ h("span", { className: "cpm-dup-arrow", "aria-hidden": "true" },
11715
+ h("svg", { width: 16, height: 16, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round" },
11716
+ h("path", { d: "M5 12h14" }),
11717
+ h("path", { d: "M13 6l6 6-6 6" }),
11718
+ ),
11719
+ ),
11720
+ h("div", { className: "cpm-dup-ver-col" },
11721
+ h("div", { className: "cpm-dup-ver-label" }, "新导入版本"),
11722
+ h("div", { className: "cpm-dup-ver-value is-new" }, formatVersionBadge(localDuplicate.plugin.version) || "未声明"),
11723
+ h("div", { className: "cpm-dup-ver-sub" }, "准备覆盖"),
11157
11724
  ),
11158
11725
  ),
11159
11726
  ],
11160
- h("div", { style: { fontSize: 11.5, color: "var(--cpm-muted)", lineHeight: 1.4 } },
11161
- localDuplicate.target === "local"
11162
- ? `「${localDuplicate.localTabName || "本地插件"}」中同名插件及其已安装副本将被新版完全覆盖更新,其余插件保持不变。`
11163
- : "覆盖更新将替换本次导入中所有同名插件 / Skills 的文件与已安装副本。",
11164
- ),
11165
11727
  !localDuplicate.conflicts?.length && localDuplicate.plugins?.length > 1 && h("ul", { className: "cpm-local-dup-list" }, localDuplicate.plugins.map((p) => h("li", { className: "cpm-local-dup-item", key: p.name }, h("span", { className: "cpm-local-dup-item-name" }, p.displayName || p.name), formatVersionBadge(p.version) && h("span", { className: "cpm-local-dup-item-vers" }, formatVersionBadge(p.version))))),
11166
11728
  ),
11167
11729
  inlineBusyProgress(),
11168
11730
  h("div", { className: "cpm-dialog-actions", key: "a" },
11169
- h("button", { className: "cpm-btn cpm-btn-secondary", type: "button", disabled: busy, onClick: () => { discardStagedUpload(localDuplicate?.payload?.uploadId); setLocalDuplicate(null); setPhase(initialPhase || "url"); } }, "取消"),
11731
+ h("button", { className: "cpm-btn cpm-btn-secondary", type: "button", autoFocus: true, disabled: busy, onClick: () => { discardStagedUpload(localDuplicate?.payload?.uploadId); setLocalDuplicate(null); setPhase(initialPhase || "url"); } }, "取消"),
11170
11732
  h("button", {
11171
- className: "cpm-btn cpm-btn-warning",
11733
+ className: "cpm-btn cpm-btn-primary",
11172
11734
  disabled: busy,
11173
11735
  onClick: () => handleImportLocal(localDuplicate.payload, true, undefined, localDuplicate.kind, undefined, localDuplicate.target),
11174
11736
  }, busy ? "正在覆盖…" : "覆盖更新"),
@@ -11763,7 +12325,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
11763
12325
  return h("div", { ref: sectionRef, className: "cpm-section" },
11764
12326
  h("div", { className: "cpm-section-title" },
11765
12327
  title,
11766
- h("span", { className: "cpm-badge" }, count !== undefined ? count : total),
12328
+ renderCountBadge(count !== undefined ? count : total),
11767
12329
  isLong && expanded && h("button", {
11768
12330
  type: "button",
11769
12331
  className: "cpm-section-collapse-btn",
@@ -11797,14 +12359,20 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
11797
12359
  }
11798
12360
 
11799
12361
  // ────────────────────────────── Detail View ──────────────────────────────
11800
- function DetailView({ plugin, pluginRecord, isDark, onBack, onInstall, onRemove, onManage, onTogglePlugin, showToast, containerRef, scrollState }) {
12362
+ function DetailView({ plugin, pluginRecord, isDark, installing = false, canDeleteLocal = false, localSourceName = "Local Plugins", onBack, onInstall, onRemove, onDeleteLocal, onManage, onTogglePlugin, showToast, containerRef, scrollState }) {
11801
12363
  const [busy, setBusy] = useState(false);
11802
12364
  const [confirmRemove, setConfirmRemove] = useState(false);
12365
+ const [confirmDeleteLocal, setConfirmDeleteLocal] = useState(false);
11803
12366
  const [toggling, setToggling] = useState(false);
11804
12367
  const [optimisticEnabled, setOptimisticEnabled] = useState(null);
11805
12368
  const { detailRef, maskClass: detailMaskClass, updateMask: updateDetailMask } = useDetailScrollMask(plugin?.name, containerRef, plugin, scrollState);
11806
- useEffect(() => { setOptimisticEnabled(null); }, [plugin?.name]);
11807
- useDialogEscape(confirmRemove, () => { if (!busy) setConfirmRemove(false); });
12369
+ useEffect(() => { setOptimisticEnabled(null); setConfirmRemove(false); setConfirmDeleteLocal(false); }, [plugin?.name]);
12370
+ useDialogEscape(confirmRemove || confirmDeleteLocal, () => {
12371
+ if (!busy) {
12372
+ setConfirmRemove(false);
12373
+ setConfirmDeleteLocal(false);
12374
+ }
12375
+ });
11808
12376
 
11809
12377
  if (!plugin) return null;
11810
12378
  const dark = typeof isDark === "boolean" ? isDark : (typeof isDarkMode === "function" ? isDarkMode() : false);
@@ -11908,12 +12476,21 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
11908
12476
  if (navigator.clipboard) navigator.clipboard.writeText(plugin.homepage);
11909
12477
  },
11910
12478
  }, h(IconLink)),
11911
- !installed &&
12479
+ !installed && [
12480
+ canDeleteLocal && onDeleteLocal && h("button", {
12481
+ key: "d",
12482
+ type: "button",
12483
+ className: "cpm-btn cpm-btn-danger",
12484
+ disabled: busy || installing,
12485
+ onClick: () => setConfirmDeleteLocal(true),
12486
+ }, "Delete"),
11912
12487
  h("button", {
12488
+ key: "i",
11913
12489
  className: "cpm-btn cpm-btn-primary",
11914
- disabled: busy,
11915
- onClick: async () => { setBusy(true); try { await onInstall(); } finally { setBusy(false); } },
11916
- }, busy ? "安装中…" : "Install"),
12490
+ disabled: busy || installing,
12491
+ onClick: async () => { if (busy || installing) return; setBusy(true); try { await onInstall(); } finally { setBusy(false); } },
12492
+ }, (busy || installing) ? "安装中…" : "Install"),
12493
+ ],
11917
12494
  installed && [
11918
12495
  h("button", {
11919
12496
  key: "r",
@@ -12049,11 +12626,325 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
12049
12626
  }
12050
12627
  },
12051
12628
  }),
12629
+ ),
12630
+
12631
+ confirmDeleteLocal && h("div", { className: "cpm-dialog", ...backdropDismissProps(() => { if (!busy) setConfirmDeleteLocal(false); }) },
12632
+ h(ConfirmDialogBox, {
12633
+ titleId: "cpm-confirm-delete-local-title",
12634
+ title: `永久删除 ${plugin.displayName || plugin.name}?`,
12635
+ description: `将从「${localSourceName}」列表中永久删除该本地插件的源文件,之后如需使用需要重新上传。`,
12636
+ descriptionStyle: { color: "var(--cpm-muted)", fontSize: "13px", lineHeight: 1.5, marginBottom: "20px" },
12637
+ confirmLabel: "删除",
12638
+ confirmBusyLabel: "删除中…",
12639
+ confirmStyle: { background: "#ef4444", borderColor: "#ef4444", color: "#ffffff" },
12640
+ busy,
12641
+ cancelDisabled: busy,
12642
+ onCancel: () => { if (!busy) setConfirmDeleteLocal(false); },
12643
+ onConfirm: async () => {
12644
+ if (busy) return;
12645
+ setBusy(true);
12646
+ try {
12647
+ await onDeleteLocal();
12648
+ } finally {
12649
+ setBusy(false);
12650
+ setConfirmDeleteLocal(false);
12651
+ }
12652
+ },
12653
+ }),
12052
12654
  )
12053
12655
  );
12054
12656
  }
12055
12657
 
12056
12658
  // ────────────────────────── MCP Tool Popover ──────────────────────────
12659
+ const MCP_TOOLS_REFRESH_COOLDOWN_MS = 60_000;
12660
+ const MCP_TOOLS_BG_CONCURRENCY = 2;
12661
+ const MCP_TOOLS_MANUAL_CONCURRENCY = 3;
12662
+ const MCP_TOOLS_REFRESH_COOLDOWN = new Map();
12663
+ const MCP_TOOLS_LOAD_SEQ = new Map();
12664
+ const MCP_TOOLS_ACTIVE_EXPLICIT = new Map();
12665
+ const MCP_STDIO_FORCE_REFRESH = new Set();
12666
+
12667
+ function isMcpRefreshDue(key, cooldownMs = MCP_TOOLS_REFRESH_COOLDOWN_MS, now = Date.now()) {
12668
+ if (!MCP_TOOLS_REFRESH_COOLDOWN.has(key)) return true;
12669
+ return now - MCP_TOOLS_REFRESH_COOLDOWN.get(key) >= cooldownMs;
12670
+ }
12671
+
12672
+ function markMcpRefreshCooldown(key, now = Date.now()) {
12673
+ MCP_TOOLS_REFRESH_COOLDOWN.set(key, now);
12674
+ }
12675
+
12676
+ function clearMcpRefreshCooldown(matcher) {
12677
+ if (typeof matcher !== "function") {
12678
+ MCP_TOOLS_REFRESH_COOLDOWN.delete(matcher);
12679
+ return;
12680
+ }
12681
+ for (const k of MCP_TOOLS_REFRESH_COOLDOWN.keys()) {
12682
+ if (matcher(k)) MCP_TOOLS_REFRESH_COOLDOWN.delete(k);
12683
+ }
12684
+ }
12685
+
12686
+ function nextMcpToolsSeq(key) {
12687
+ const next = (MCP_TOOLS_LOAD_SEQ.get(key) || 0) + 1;
12688
+ MCP_TOOLS_LOAD_SEQ.set(key, next);
12689
+ return next;
12690
+ }
12691
+
12692
+ function isLatestMcpToolsSeq(key, seq) {
12693
+ return (MCP_TOOLS_LOAD_SEQ.get(key) || 0) === seq;
12694
+ }
12695
+
12696
+ function bumpMcpToolsSeq(matcher) {
12697
+ if (typeof matcher !== "function") {
12698
+ MCP_TOOLS_LOAD_SEQ.set(matcher, (MCP_TOOLS_LOAD_SEQ.get(matcher) || 0) + 1);
12699
+ MCP_TOOLS_ACTIVE_EXPLICIT.delete(matcher);
12700
+ MCP_STDIO_FORCE_REFRESH.delete(matcher);
12701
+ return;
12702
+ }
12703
+ for (const k of MCP_TOOLS_LOAD_SEQ.keys()) {
12704
+ if (matcher(k)) MCP_TOOLS_LOAD_SEQ.set(k, (MCP_TOOLS_LOAD_SEQ.get(k) || 0) + 1);
12705
+ }
12706
+ for (const k of MCP_TOOLS_ACTIVE_EXPLICIT.keys()) {
12707
+ if (matcher(k)) MCP_TOOLS_ACTIVE_EXPLICIT.delete(k);
12708
+ }
12709
+ for (const k of MCP_STDIO_FORCE_REFRESH.keys()) {
12710
+ if (matcher(k)) MCP_STDIO_FORCE_REFRESH.delete(k);
12711
+ }
12712
+ }
12713
+
12714
+ function markExplicitMcpLoad(key, seq) {
12715
+ MCP_TOOLS_ACTIVE_EXPLICIT.set(key, seq);
12716
+ }
12717
+
12718
+ function clearExplicitMcpLoad(key, seq) {
12719
+ if (MCP_TOOLS_ACTIVE_EXPLICIT.get(key) === seq) MCP_TOOLS_ACTIVE_EXPLICIT.delete(key);
12720
+ }
12721
+
12722
+ function isExplicitMcpLoadActive(key) {
12723
+ return MCP_TOOLS_ACTIVE_EXPLICIT.has(key);
12724
+ }
12725
+
12726
+ function queueStdioForceRefresh(key) {
12727
+ MCP_STDIO_FORCE_REFRESH.add(key);
12728
+ }
12729
+
12730
+ function consumeStdioForceRefresh(key) {
12731
+ return MCP_STDIO_FORCE_REFRESH.delete(key);
12732
+ }
12733
+
12734
+ function syncPluginToggleCooldown(record, nextEnabled) {
12735
+ if (!record?.name) return;
12736
+ if (!nextEnabled) {
12737
+ bumpMcpToolsSeq((k) => k.startsWith(`${record.name}::`));
12738
+ return;
12739
+ }
12740
+ for (const c of (Array.isArray(record.connectors) ? record.connectors : [])) {
12741
+ const cName = typeof c === "string" ? c : c?.name;
12742
+ if (!cName) continue;
12743
+ const isStdio = typeof c === "object"
12744
+ ? (String(c.type || (c.url ? "http" : "stdio")).toLowerCase() === "stdio")
12745
+ : true;
12746
+ if (isStdio) {
12747
+ clearMcpRefreshCooldown(`${record.name}::${cName}`);
12748
+ queueStdioForceRefresh(`${record.name}::${cName}`);
12749
+ }
12750
+ }
12751
+ }
12752
+
12753
+ function mcpToolNamesSignature(tools) {
12754
+ return Array.isArray(tools)
12755
+ ? tools.map((t) => (typeof t === "string" ? t : (t?.name || ""))).join("\0")
12756
+ : null;
12757
+ }
12758
+
12759
+ function notifyMcpToolsBrandingIfChanged(owner, prevTools, nextTools) {
12760
+ if (!owner || owner === "user-mcp" || typeof document === "undefined") return;
12761
+ if (mcpToolNamesSignature(prevTools) !== mcpToolNamesSignature(nextTools)) {
12762
+ document.dispatchEvent(new Event("uph-mcp-branding-changed"));
12763
+ }
12764
+ }
12765
+
12766
+ async function runWithConcurrency(items, limit, worker, signal) {
12767
+ const list = Array.isArray(items) ? items : [];
12768
+ if (!list.length) return [];
12769
+ const cap = Math.max(1, Math.min(limit || 1, list.length));
12770
+ const results = new Array(list.length);
12771
+ let index = 0;
12772
+ const runWorker = async () => {
12773
+ while (!signal?.aborted) {
12774
+ const current = index++;
12775
+ if (current >= list.length) break;
12776
+ results[current] = await worker(list[current], current);
12777
+ }
12778
+ };
12779
+ await Promise.all(Array.from({ length: cap }, runWorker));
12780
+ return results;
12781
+ }
12782
+
12783
+ function createMcpRefreshQueue(limit = MCP_TOOLS_BG_CONCURRENCY) {
12784
+ const cap = Math.max(1, limit || 1);
12785
+ const pending = [];
12786
+ const queuedKeys = new Set();
12787
+ const runningKeys = new Set();
12788
+ let active = 0;
12789
+ let disposed = false;
12790
+
12791
+ const pump = () => {
12792
+ if (disposed) return;
12793
+ while (active < cap && pending.length > 0) {
12794
+ const item = pending.shift();
12795
+ queuedKeys.delete(item.key);
12796
+ if (runningKeys.has(item.key)) continue;
12797
+ runningKeys.add(item.key);
12798
+ active++;
12799
+ Promise.resolve()
12800
+ .then(() => (disposed ? undefined : item.task()))
12801
+ .catch(() => {})
12802
+ .finally(() => {
12803
+ runningKeys.delete(item.key);
12804
+ active--;
12805
+ pump();
12806
+ });
12807
+ }
12808
+ };
12809
+
12810
+ return {
12811
+ enqueue(key, task) {
12812
+ if (disposed || !key || typeof task !== "function") return false;
12813
+ if (queuedKeys.has(key) || runningKeys.has(key)) return false;
12814
+ queuedKeys.add(key);
12815
+ pending.push({ key, task });
12816
+ pump();
12817
+ return true;
12818
+ },
12819
+ clearPending() {
12820
+ pending.length = 0;
12821
+ queuedKeys.clear();
12822
+ },
12823
+ dispose() {
12824
+ disposed = true;
12825
+ pending.length = 0;
12826
+ queuedKeys.clear();
12827
+ },
12828
+ };
12829
+ }
12830
+
12831
+ async function runMcpToolsLoad({ owner, connectorName, forceFresh = false, options = {}, setData, stateKey }) {
12832
+ const key = `${owner}::${connectorName}`;
12833
+ const slotKey = stateKey ?? key;
12834
+ const cached = GLOBAL_MCP_TOOLS_CACHE[key];
12835
+ const background = options?.background === true;
12836
+ const preserveDisplay = options?.preserveDisplay === true;
12837
+ const hasCachedList = Array.isArray(cached?.tools);
12838
+ const activeExplicit = typeof isExplicitMcpLoadActive === "function" && isExplicitMcpLoadActive(key);
12839
+ if (activeExplicit && (background || !forceFresh)) {
12840
+ return { ok: false, stale: false, skipped: true, error: null, tools: cached?.tools || [], disabledTools: cached?.disabledTools || [] };
12841
+ }
12842
+ const reqSeq = typeof nextMcpToolsSeq === "function" ? nextMcpToolsSeq(key) : null;
12843
+ const isStaleReq = () => reqSeq !== null && typeof isLatestMcpToolsSeq === "function" && !isLatestMcpToolsSeq(key, reqSeq);
12844
+ const isExplicit = !background && forceFresh && reqSeq !== null && typeof markExplicitMcpLoad === "function";
12845
+ if (isExplicit) markExplicitMcpLoad(key, reqSeq);
12846
+ if (!background || !hasCachedList) {
12847
+ setData((prev) => {
12848
+ const existing = cached || prev[slotKey];
12849
+ const hasAnyTools = Array.isArray(existing?.tools);
12850
+ if (background && hasAnyTools) return prev;
12851
+ const nextLoading = preserveDisplay ? !hasAnyTools : (forceFresh || !hasCachedList);
12852
+ return {
12853
+ ...prev,
12854
+ [slotKey]: { ...existing, loading: nextLoading, error: null, warning: null },
12855
+ };
12856
+ });
12857
+ }
12858
+ try {
12859
+ const url = owner === "user-mcp"
12860
+ ? `/mcps/${encodeURIComponent(connectorName)}/tools`
12861
+ : `/plugins/${encodeURIComponent(owner)}/connectors/${encodeURIComponent(connectorName)}/tools`;
12862
+ const res = await api(url + (forceFresh ? "?fresh=1" : ""));
12863
+ if (isStaleReq()) {
12864
+ return { ok: false, stale: false, superseded: true, error: null, tools: [], disabledTools: [] };
12865
+ }
12866
+ const tools = Array.isArray(res.tools) ? res.tools : [];
12867
+ const disabledTools = Array.isArray(res.disabledTools) ? res.disabledTools : [];
12868
+ const fromCache = res.cached === true;
12869
+ if (res.ok && !res.stale) {
12870
+ const prevTools = cached?.tools;
12871
+ saveMcpToolsCache(key, { tools, disabledTools });
12872
+ if ((forceFresh || (!hasCachedList && !fromCache)) && typeof markMcpRefreshCooldown === "function") {
12873
+ markMcpRefreshCooldown(key);
12874
+ }
12875
+ if (typeof notifyMcpToolsBrandingIfChanged === "function") {
12876
+ notifyMcpToolsBrandingIfChanged(owner, prevTools, tools);
12877
+ }
12878
+ setData((prev) => {
12879
+ const cur = prev[slotKey];
12880
+ if (background && cur && !cur.loading && !cur.error && !cur.warning
12881
+ && JSON.stringify(cur.tools) === JSON.stringify(tools)
12882
+ && JSON.stringify(cur.disabledTools) === JSON.stringify(disabledTools)) {
12883
+ return prev;
12884
+ }
12885
+ return {
12886
+ ...prev,
12887
+ [slotKey]: { loading: false, error: null, warning: null, tools, disabledTools },
12888
+ };
12889
+ });
12890
+ return { ok: true, stale: false, cached: fromCache, error: null, tools, disabledTools };
12891
+ }
12892
+ const msg = res.message || "获取能力列表失败";
12893
+ if (background && typeof markMcpRefreshCooldown === "function") markMcpRefreshCooldown(key);
12894
+ if (res.ok && res.stale) {
12895
+ setData((prev) => {
12896
+ const cur = prev[slotKey];
12897
+ if (background) {
12898
+ if (cur && !cur.loading && !cur.error && !cur.warning && Array.isArray(cur.tools)) return prev;
12899
+ return { ...prev, [slotKey]: { loading: false, error: null, warning: null, tools: cur?.tools || tools, disabledTools } };
12900
+ }
12901
+ return { ...prev, [slotKey]: { loading: false, error: null, warning: msg, tools, disabledTools } };
12902
+ });
12903
+ return { ok: false, stale: true, error: msg, tools, disabledTools };
12904
+ }
12905
+ setData((prev) => {
12906
+ const cur = prev[slotKey] || cached;
12907
+ const hasAnyTools = Array.isArray(cur?.tools);
12908
+ if (background) {
12909
+ if (hasAnyTools) {
12910
+ if (prev[slotKey] && !prev[slotKey].loading && !prev[slotKey].error && !prev[slotKey].warning) return prev;
12911
+ return { ...prev, [slotKey]: { loading: false, error: null, warning: null, tools: cur.tools, disabledTools: cur.disabledTools || disabledTools } };
12912
+ }
12913
+ return { ...prev, [slotKey]: { loading: false, error: msg, warning: null, tools: [], disabledTools } };
12914
+ }
12915
+ if (preserveDisplay && hasAnyTools) {
12916
+ return { ...prev, [slotKey]: { ...cur, loading: false, error: null, warning: msg, disabledTools: Array.isArray(res.disabledTools) ? disabledTools : (cur.disabledTools || []) } };
12917
+ }
12918
+ return { ...prev, [slotKey]: { loading: false, error: msg, warning: null, tools: prev[slotKey]?.tools || tools, disabledTools } };
12919
+ });
12920
+ return { ok: false, stale: false, error: msg, tools: cached?.tools || [], disabledTools };
12921
+ } catch (e) {
12922
+ if (isStaleReq()) {
12923
+ return { ok: false, stale: false, superseded: true, error: null, tools: [], disabledTools: [] };
12924
+ }
12925
+ const msg = e?.message || "获取能力列表失败";
12926
+ if (background && typeof markMcpRefreshCooldown === "function") markMcpRefreshCooldown(key);
12927
+ setData((prev) => {
12928
+ const cur = prev[slotKey] || cached;
12929
+ const hasAnyTools = Array.isArray(cur?.tools);
12930
+ if (background) {
12931
+ if (hasAnyTools) {
12932
+ if (prev[slotKey] && !prev[slotKey].loading && !prev[slotKey].error && !prev[slotKey].warning) return prev;
12933
+ return { ...prev, [slotKey]: { loading: false, error: null, warning: null, tools: cur.tools, disabledTools: cur.disabledTools || [] } };
12934
+ }
12935
+ return { ...prev, [slotKey]: { loading: false, error: msg, warning: null } };
12936
+ }
12937
+ if (preserveDisplay && hasAnyTools) {
12938
+ return { ...prev, [slotKey]: { ...cur, loading: false, error: null, warning: msg } };
12939
+ }
12940
+ return { ...prev, [slotKey]: { ...(prev[slotKey] || cached), loading: false, error: msg } };
12941
+ });
12942
+ return { ok: false, stale: false, error: msg, tools: cached?.tools || [], disabledTools: cached?.disabledTools || [] };
12943
+ } finally {
12944
+ if (isExplicit && typeof clearExplicitMcpLoad === "function") clearExplicitMcpLoad(key, reqSeq);
12945
+ }
12946
+ }
12947
+
12057
12948
  const GLOBAL_MCP_TOOLS_CACHE = (() => {
12058
12949
  try {
12059
12950
  const raw = localStorage.getItem("cpm_mcp_tools_cache_v1");
@@ -12082,6 +12973,8 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
12082
12973
  if (changed) {
12083
12974
  try { localStorage.setItem("cpm_mcp_tools_cache_v1", JSON.stringify(GLOBAL_MCP_TOOLS_CACHE)); } catch {}
12084
12975
  }
12976
+ clearMcpRefreshCooldown(matcher);
12977
+ bumpMcpToolsSeq(matcher);
12085
12978
  }
12086
12979
 
12087
12980
  function useAutoMcpTools(servers, loadTools) {
@@ -12109,11 +13002,13 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
12109
13002
  h("button", { type: "button", className: "cpm-mcp-retry", onClick: event => { event.stopPropagation(); onRetry(); } }, "重新解析"));
12110
13003
  if (info.error) return retryNotice(`解析失败:${info.error}`);
12111
13004
  const tools = info.tools || [], disabled = info.disabledTools || [];
12112
- const active = tools.filter(tool => !disabled.includes(typeof tool === "string" ? tool : tool.name)).length;
13005
+ const disabledSet = new Set(disabled);
13006
+ const disabledCount = tools.filter(tool => disabledSet.has(typeof tool === "string" ? tool : tool.name)).length;
13007
+ const active = tools.length - disabledCount;
12113
13008
  const expand = h("button", { type: "button", className: "cpm-mcp-expand", "aria-expanded": !!expanded,
12114
13009
  onClick: event => { event.stopPropagation(); onExpand(); } },
12115
13010
  h("span", { className: "cpm-connector-collapse-btn" + (expanded ? " is-expanded" : ""), "aria-hidden": "true" }, h(IconArrow, { size: 10 })),
12116
- h("span", null, `${active} tools enabled${disabled.length ? ` (${disabled.length} disabled)` : ""}`));
13011
+ h("span", null, `${active} tools enabled${disabledCount ? ` (${disabledCount} disabled)` : ""}`));
12117
13012
  return info.warning
12118
13013
  ? h("span", { className: "cpm-mcp-discovery" }, expand, retryNotice(`刷新失败,显示上次解析结果:${info.warning}`))
12119
13014
  : expand;
@@ -12319,39 +13214,26 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
12319
13214
  const [hoveredTool, closeToolHover, toolHover] = useHoverPreview();
12320
13215
  useEffect(() => { closeToolHover(); }, [record?.name, closeToolHover]);
12321
13216
 
12322
- const loadConnectorTools = useCallback(async (connectorName, forceFresh = false) => {
12323
- const key = `${record.name}::${connectorName}`;
12324
- const cached = GLOBAL_MCP_TOOLS_CACHE[key];
12325
- setConnectorToolsData((prev) => ({
12326
- ...prev,
12327
- [connectorName]: { ...(cached || prev[connectorName]), loading: forceFresh || !Array.isArray(cached?.tools), error: null, warning: null },
12328
- }));
12329
-
12330
- try {
12331
- const res = await api(`/plugins/${encodeURIComponent(record.name)}/connectors/${encodeURIComponent(connectorName)}/tools${forceFresh ? "?fresh=1" : ""}`);
12332
- const tools = Array.isArray(res.tools) ? res.tools : [];
12333
- const disabledTools = Array.isArray(res.disabledTools) ? res.disabledTools : [];
12334
-
12335
- if (res.ok) {
12336
- saveMcpToolsCache(key, { tools, disabledTools });
12337
- }
13217
+ const manageUnmountedRef = useRef(false);
13218
+ const manageBgQueueRef = useRef(null);
13219
+ useEffect(() => {
13220
+ manageUnmountedRef.current = false;
13221
+ return () => {
13222
+ manageUnmountedRef.current = true;
13223
+ manageBgQueueRef.current?.dispose();
13224
+ };
13225
+ }, []);
12338
13226
 
12339
- setConnectorToolsData((prev) => ({
12340
- ...prev,
12341
- [connectorName]: {
12342
- loading: false,
12343
- error: res.ok ? null : (res.message || "获取能力列表失败"),
12344
- warning: res.ok && res.stale ? (res.message || "获取能力列表失败") : null,
12345
- tools: res.ok ? tools : (prev[connectorName]?.tools || tools),
12346
- disabledTools,
12347
- },
12348
- }));
12349
- } catch (e) {
12350
- setConnectorToolsData((prev) => ({
12351
- ...prev, [connectorName]: { ...(prev[connectorName] || cached), loading: false, error: e.message },
12352
- }));
12353
- }
12354
- }, [record?.name]);
13227
+ const loadConnectorTools = useCallback((connectorName, forceFresh = false, options = {}) => (
13228
+ runMcpToolsLoad({
13229
+ owner: record.name,
13230
+ connectorName,
13231
+ forceFresh,
13232
+ options,
13233
+ setData: setConnectorToolsData,
13234
+ stateKey: connectorName,
13235
+ })
13236
+ ), [record?.name]);
12355
13237
 
12356
13238
  const updateAuthDialog = (patch) => setAuthDialog((prev) => prev
12357
13239
  ? { ...prev, ...patch, status: "untested", statusMessage: "", lastResult: null }
@@ -12532,9 +13414,43 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
12532
13414
  }
12533
13415
  };
12534
13416
 
12535
- const autoLoadConnectorTools = useCallback((_owner, name) => loadConnectorTools(name), [loadConnectorTools]);
13417
+ const enqueueManageBgRefresh = useCallback((connectorName) => {
13418
+ if (manageUnmountedRef.current || !record?.name) return;
13419
+ const key = `${record.name}::${connectorName}`;
13420
+ if (!manageBgQueueRef.current) manageBgQueueRef.current = createMcpRefreshQueue(MCP_TOOLS_BG_CONCURRENCY);
13421
+ manageBgQueueRef.current.enqueue(key, () => {
13422
+ if (manageUnmountedRef.current) return;
13423
+ return loadConnectorTools(connectorName, true, { background: true });
13424
+ });
13425
+ }, [record?.name, loadConnectorTools]);
13426
+
13427
+ const autoLoadConnectorTools = useCallback((_owner, name) => {
13428
+ if (!record?.name) return;
13429
+ const key = `${record.name}::${name}`;
13430
+ const forceStdio = typeof consumeStdioForceRefresh === "function" && consumeStdioForceRefresh(key);
13431
+ const cached = GLOBAL_MCP_TOOLS_CACHE[key];
13432
+ const hasCached = Array.isArray(cached?.tools);
13433
+ if (forceStdio) {
13434
+ if (hasCached) enqueueManageBgRefresh(name);
13435
+ else void loadConnectorTools(name, true);
13436
+ return;
13437
+ }
13438
+ if (!hasCached) {
13439
+ void loadConnectorTools(name, false).then((res) => {
13440
+ if (res?.ok && res.cached && typeof isMcpRefreshDue === "function" && isMcpRefreshDue(key)) {
13441
+ enqueueManageBgRefresh(name);
13442
+ }
13443
+ });
13444
+ return;
13445
+ }
13446
+ if (typeof isMcpRefreshDue === "function" && isMcpRefreshDue(key)) {
13447
+ enqueueManageBgRefresh(name);
13448
+ return;
13449
+ }
13450
+ void loadConnectorTools(name, false);
13451
+ }, [record?.name, enqueueManageBgRefresh, loadConnectorTools]);
12536
13452
  useAutoMcpTools((record.connectors || []).map(connector => ({
12537
- owner: record.name, name: connector.name, connected: connector.enabled === true && !connector.pending,
13453
+ owner: record.name, name: connector.name, connected: connector.enabled === true && !(connector.pending && connector.connected !== true),
12538
13454
  revision: JSON.stringify([record.installedAt, connector]),
12539
13455
  })), autoLoadConnectorTools);
12540
13456
 
@@ -12765,6 +13681,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
12765
13681
  showToast("操作失败", result.error || "插件状态已变更,请刷新后重试", { restart: false });
12766
13682
  return;
12767
13683
  }
13684
+ syncPluginToggleCooldown(record, next);
12768
13685
  await applyToggleState(result);
12769
13686
  void showApplicationToast(showToast, result, next ? "已启用插件" : "已禁用插件", "插件状态已实时更新并生效。");
12770
13687
  } catch (e) {
@@ -12792,6 +13709,23 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
12792
13709
  showToast("操作失败", result.error || "请检查 MCP 配置后重试", { restart: false });
12793
13710
  return;
12794
13711
  }
13712
+ const connKey = `${record.name}::${connectorName}`;
13713
+ const connMeta = Array.isArray(record?.connectors)
13714
+ ? record.connectors.find((c) => (typeof c === "string" ? c : c?.name) === connectorName)
13715
+ : null;
13716
+ const isStdio = connMeta && typeof connMeta === "object"
13717
+ ? (String(connMeta.type || (connMeta.url ? "http" : "stdio")).toLowerCase() === "stdio")
13718
+ : true;
13719
+ if (nextConnected) {
13720
+ if (isStdio) {
13721
+ clearMcpRefreshCooldown(connKey);
13722
+ queueStdioForceRefresh(connKey);
13723
+ } else {
13724
+ markMcpRefreshCooldown(connKey);
13725
+ }
13726
+ } else {
13727
+ bumpMcpToolsSeq(connKey);
13728
+ }
12795
13729
  await applyToggleState(result);
12796
13730
  void showApplicationToast(showToast, result, nextConnected ? "已连接 Connector" : "已断开 Connector", `MCP 服务 ${connectorName} 配置已实时更新。`);
12797
13731
  } catch (e) {
@@ -13997,6 +14931,8 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
13997
14931
  const AT_PLUGIN_RAW_TOKEN_RE = /@([^\s\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul},。;:、!?()【】《》“”‘’」』]+)/uy;
13998
14932
  const AT_PLUGIN_LEFT_ALLOWED_RE = /[\s(\[{"'“‘(【《,。;:、!?\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
13999
14933
  const AT_PLUGIN_TRAILING_PUNCT_RE = /[.,;:!?,。;:!?)"'\]”’)】》]+$/u;
14934
+ const EASY_REWRITE_BUBBLE = '[data-dsh-easyrewrite="user"] .dsh-easyrewrite-bubble';
14935
+ const AT_PLUGIN_CLIPBOARD = "data-uph-plugin-clipboard";
14000
14936
  const AT_PLUGINS_CSS = `
14001
14937
  [role="listbox"] button[id^="dsh-slash-option-plugins-"] {
14002
14938
  gap: 8px;
@@ -14060,8 +14996,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
14060
14996
  object-fit: contain !important;
14061
14997
  display: block;
14062
14998
  }
14063
- [data-composer-chip="plugins"],
14064
- .cpm-at-plugin-chip {
14999
+ [data-composer-chip="plugins"] {
14065
15000
  display: inline-flex;
14066
15001
  align-items: baseline;
14067
15002
  gap: 4px;
@@ -14077,6 +15012,27 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
14077
15012
  cursor: default;
14078
15013
  transition: background-color 120ms ease;
14079
15014
  }
15015
+ .cpm-at-plugin-chip {
15016
+ display: inline;
15017
+ margin: 0 2px;
15018
+ border-radius: var(--dsw-radius-sm, 4px);
15019
+ color: var(--dsw-alias-label-primary, #18181b);
15020
+ font-weight: 600;
15021
+ overflow-wrap: anywhere;
15022
+ user-select: all;
15023
+ }
15024
+ .cpm-at-plugin-chip > .cpm-at-plugin-chip-icon-wrap {
15025
+ display: inline-block;
15026
+ margin-inline-end: 4px;
15027
+ vertical-align: -0.125em;
15028
+ top: auto;
15029
+ pointer-events: none;
15030
+ }
15031
+ .cpm-at-plugin-chip .cpm-at-plugin-chip-icon,
15032
+ .cpm-at-plugin-chip .cpm-card-icon {
15033
+ display: inline-block;
15034
+ vertical-align: top;
15035
+ }
14080
15036
  body[data-ds-dark-theme] [data-composer-chip="plugins"],
14081
15037
  body[data-ds-dark-theme] .cpm-at-plugin-chip {
14082
15038
  color: var(--dsw-alias-label-primary, #f4f4f5);
@@ -14133,11 +15089,6 @@ body[data-ds-dark-theme] .cpm-at-plugin-chip {
14133
15089
  position: relative;
14134
15090
  top: 0.05em;
14135
15091
  }
14136
- .cpm-at-plugin-chip-label {
14137
- overflow: hidden;
14138
- text-overflow: ellipsis;
14139
- white-space: nowrap;
14140
- }
14141
15092
  .cpm-at-plugin-popover {
14142
15093
  position: fixed;
14143
15094
  inset: auto;
@@ -14348,6 +15299,106 @@ body[data-ds-dark-theme] .cpm-at-plugin-popover,
14348
15299
  return { source: "plugins", ref: mention, label, clipboardText: mention };
14349
15300
  }
14350
15301
 
15302
+ function copyAtPluginReferences(event) {
15303
+ if (event.defaultPrevented || !event.clipboardData || event.target?.isContentEditable ||
15304
+ event.target?.closest?.("input, textarea")) return;
15305
+ const selection = document.getSelection?.();
15306
+ if (selection?.rangeCount !== 1 || selection.isCollapsed) return;
15307
+ const range = selection.getRangeAt(0);
15308
+ const common = range.commonAncestorContainer;
15309
+ const element = common.nodeType === 1 ? common : common.parentElement;
15310
+ const bubble = element?.closest('[data-message-bubble], ' + EASY_REWRITE_BUBBLE);
15311
+ const chipSelector = '[' + AT_PLUGIN_CLIPBOARD + ']';
15312
+ if (!bubble?.querySelector(chipSelector)) return;
15313
+
15314
+ const fragment = range.cloneContents();
15315
+ // User text is inline. Leave structured content such as a host JSON block
15316
+ // to the browser so its formatting and rich clipboard formats are kept.
15317
+ if (fragment.querySelector("div, p, pre, table, ul, ol, blockquote")) return;
15318
+ const enclosingChip = element.closest(chipSelector);
15319
+ let text;
15320
+ if (enclosingChip && fragment.textContent === enclosingChip.textContent) {
15321
+ text = enclosingChip.getAttribute(AT_PLUGIN_CLIPBOARD);
15322
+ } else {
15323
+ let replaced = false;
15324
+ for (const chip of fragment.querySelectorAll(chipSelector)) {
15325
+ // A clipped label is ordinary selected text. A whole chip carries the original reference.
15326
+ if (chip.querySelector(".cpm-at-plugin-chip-label")?.textContent !== chip.getAttribute("data-uph-plugin-label")) continue;
15327
+ chip.replaceWith(chip.getAttribute(AT_PLUGIN_CLIPBOARD));
15328
+ replaced = true;
15329
+ }
15330
+ if (!replaced) return;
15331
+ for (const br of fragment.querySelectorAll("br")) br.replaceWith("\n");
15332
+ text = fragment.textContent;
15333
+ }
15334
+ event.clipboardData.setData("text/plain", text);
15335
+ event.preventDefault();
15336
+ }
15337
+
15338
+ function restoreEasyRewriteBubble({ bubble, mount, original }) {
15339
+ if (mount.parentElement === bubble) mount.replaceWith(original);
15340
+ }
15341
+
15342
+ function watchEasyRewriteBubbles(publish) {
15343
+ const entries = new Map();
15344
+ let nextId = 0;
15345
+
15346
+ function collect(root, bubbles) {
15347
+ if (root.nodeType !== 1) return;
15348
+ if (root.matches(EASY_REWRITE_BUBBLE)) bubbles.add(root);
15349
+ for (const bubble of root.querySelectorAll(EASY_REWRITE_BUBBLE)) bubbles.add(bubble);
15350
+ }
15351
+
15352
+ function update(bubbles) {
15353
+ let changed = false;
15354
+ for (const bubble of bubbles) {
15355
+ const previous = entries.get(bubble);
15356
+ const original = bubble.firstChild;
15357
+ if (bubble.isConnected && original && !original.nextSibling &&
15358
+ (previous?.mount === original || (previous?.original === original && previous.text === original.data))) continue;
15359
+ if (entries.delete(bubble)) changed = true;
15360
+ // EasyRewrite renders the resting bubble as one text node. Leave its editor,
15361
+ // attachments, buttons and any future renderer using structured children alone.
15362
+ if (!bubble.isConnected || original?.nodeType !== 3 || original.nextSibling) continue;
15363
+ const text = original.data;
15364
+ const first = matchAtPluginMention(text, 0, null, true);
15365
+ if (!first) continue;
15366
+ const mount = document.createElement("span");
15367
+ mount.style.display = "contents";
15368
+ entries.set(bubble, { id: nextId++, bubble, original, text, first, mount });
15369
+ changed = true;
15370
+ }
15371
+ if (changed) publish([...entries.values()]);
15372
+ }
15373
+
15374
+ const observer = new MutationObserver((mutations) => {
15375
+ const bubbles = new Set();
15376
+ let removed = false;
15377
+ for (const mutation of mutations) {
15378
+ const target = mutation.type === "characterData" ? mutation.target.parentElement : mutation.target;
15379
+ if (target?.matches?.(EASY_REWRITE_BUBBLE)) bubbles.add(target);
15380
+ for (const node of mutation.addedNodes) collect(node, bubbles);
15381
+ if (!removed && entries.size > 0 && mutation.removedNodes.length > 0) {
15382
+ removed = Array.from(mutation.removedNodes).some((node) => node.nodeType === 1);
15383
+ }
15384
+ }
15385
+ if (removed) {
15386
+ for (const bubble of entries.keys()) {
15387
+ if (!bubble.isConnected) bubbles.add(bubble);
15388
+ }
15389
+ }
15390
+ update(bubbles);
15391
+ });
15392
+ observer.observe(document.body, { subtree: true, childList: true, characterData: true });
15393
+ update(document.querySelectorAll(EASY_REWRITE_BUBBLE));
15394
+ return () => {
15395
+ observer.disconnect();
15396
+ // Restore text before another client instance scans the bubbles.
15397
+ for (const entry of entries.values()) restoreEasyRewriteBubble(entry);
15398
+ entries.clear();
15399
+ };
15400
+ }
15401
+
14351
15402
  function pasteAtPluginReferences(event, byLowerName) {
14352
15403
  const clipboard = event.clipboardData;
14353
15404
  if (event.defaultPrevented || !clipboard || clipboard.files?.length ||
@@ -14782,12 +15833,13 @@ body[data-ds-dark-theme] .cpm-at-plugin-popover,
14782
15833
  const ReactDOM = (() => { try { return require("react-dom") || null; } catch { return null; } })();
14783
15834
  const ReactDOMClient = (() => { try { return require("react-dom/client") || null; } catch { return null; } })();
14784
15835
 
14785
- function PluginMentionChip({ node }) {
15836
+ function PluginMentionChip({ node, raw }) {
14786
15837
  const [revision, setRevision] = useState(0);
14787
15838
  useEffect(() => {
14788
15839
  const bump = () => setRevision((r) => r + 1);
14789
15840
  const offStore = store.subscribe(bump);
14790
15841
  const offTheme = store.subscribeTheme(bump);
15842
+ store.warm();
14791
15843
  return () => {
14792
15844
  offStore();
14793
15845
  offTheme();
@@ -14801,6 +15853,7 @@ body[data-ds-dark-theme] .cpm-at-plugin-popover,
14801
15853
  "data-uph-plugin-chip": "true",
14802
15854
  "data-uph-plugin-name": live?.name || node?.data?.name || "",
14803
15855
  "data-uph-plugin-label": label,
15856
+ [AT_PLUGIN_CLIPBOARD]: raw,
14804
15857
  },
14805
15858
  live
14806
15859
  ? h("span", { className: "cpm-at-plugin-chip-icon-wrap", "aria-hidden": "true" },
@@ -14813,6 +15866,27 @@ body[data-ds-dark-theme] .cpm-at-plugin-popover,
14813
15866
  );
14814
15867
  }
14815
15868
 
15869
+ function EasyRewritePluginText({ entry }) {
15870
+ const { bubble, original, text, first, mount } = entry;
15871
+ useSafeLayoutEffect(() => {
15872
+ // Stage the portal off-DOM, then swap only the same plain text once
15873
+ // the chips have rendered. EasyRewrite still owns the bubble and its events.
15874
+ if (!bubble.isConnected || bubble.firstChild !== original || original.nextSibling || original.data !== text) return;
15875
+ original.replaceWith(mount);
15876
+ return () => restoreEasyRewriteBubble(entry);
15877
+ }, [entry]);
15878
+ const children = [];
15879
+ let cursor = 0;
15880
+ for (let node = first; node; node = matchAtPluginMention(text, cursor, null, true)) {
15881
+ children.push(text.slice(cursor, node.start), h(PluginMentionChip, {
15882
+ key: node.start, node, raw: text.slice(node.start, node.end),
15883
+ }));
15884
+ cursor = node.end;
15885
+ }
15886
+ children.push(text.slice(cursor));
15887
+ return children;
15888
+ }
15889
+
14816
15890
  function PluginChipHoverPopover({ hovered, isDark, session }) {
14817
15891
  const popRef = useRef(null);
14818
15892
  const [position, setPosition] = useState(null);
@@ -14905,7 +15979,7 @@ body[data-ds-dark-theme] .cpm-at-plugin-popover,
14905
15979
  let knownComposerEl = null;
14906
15980
  let syncQueued = false;
14907
15981
  let blockDisposed = false;
14908
- let activeOverlayState = { chips: [], hovered: null, isDark: store.isDark() };
15982
+ let activeOverlayState = { chips: [], rewriteBubbles: [], hovered: null, isDark: store.isDark() };
14909
15983
  let setOverlayState = null;
14910
15984
  let hoverSession = null;
14911
15985
 
@@ -15190,11 +16264,13 @@ body[data-ds-dark-theme] .cpm-at-plugin-popover,
15190
16264
 
15191
16265
  if (typeof document.addEventListener === "function") {
15192
16266
  const onPaste = (event) => pasteAtPluginReferences(event, store.getByLowerName());
16267
+ document.addEventListener("copy", copyAtPluginReferences);
15193
16268
  document.addEventListener("paste", onPaste, true);
15194
16269
  document.addEventListener("pointerover", onPointerOver, true);
15195
16270
  document.addEventListener("focusin", onFocusIn, true);
15196
16271
  document.addEventListener("keydown", onComposerKeyDown, true);
15197
16272
  disposers.push(() => {
16273
+ document.removeEventListener("copy", copyAtPluginReferences);
15198
16274
  document.removeEventListener("paste", onPaste, true);
15199
16275
  document.removeEventListener("pointerover", onPointerOver, true);
15200
16276
  document.removeEventListener("focusin", onFocusIn, true);
@@ -15246,6 +16322,9 @@ body[data-ds-dark-theme] .cpm-at-plugin-popover,
15246
16322
  setLocalState(activeOverlayState);
15247
16323
  return () => { if (setOverlayState === setLocalState) setOverlayState = null; };
15248
16324
  }, []);
16325
+ const rewritePortals = useMemo(() => overlayState.rewriteBubbles.map((entry) => ReactDOM.createPortal(
16326
+ h(EasyRewritePluginText, { entry }), entry.mount, "easyrewrite-" + entry.id,
16327
+ )), [overlayState.rewriteBubbles]);
15249
16328
  return h(React.Fragment, null,
15250
16329
  overlayState.chips.map((entry) => (
15251
16330
  entry.iconSlot?.isConnected
@@ -15258,6 +16337,7 @@ body[data-ds-dark-theme] .cpm-at-plugin-popover,
15258
16337
  )
15259
16338
  : null
15260
16339
  )),
16340
+ rewritePortals,
15261
16341
  h(PluginChipHoverPopover, {
15262
16342
  hovered: overlayState.hovered,
15263
16343
  isDark: overlayState.isDark,
@@ -15270,11 +16350,17 @@ body[data-ds-dark-theme] .cpm-at-plugin-popover,
15270
16350
  overlayRoot.render(h(AtPluginsOverlay));
15271
16351
  disposers.push(() => {
15272
16352
  setOverlayState = null;
15273
- activeOverlayState = { chips: [], hovered: null, isDark: false };
16353
+ activeOverlayState = { chips: [], rewriteBubbles: [], hovered: null, isDark: false };
15274
16354
  cleanupStaleAtPluginDom();
15275
16355
  try { overlayRoot.unmount(); } catch {}
15276
16356
  try { overlayHost.remove(); } catch {}
15277
16357
  });
16358
+ if (typeof MutationObserver === "function") {
16359
+ disposers.push(watchEasyRewriteBubbles((rewriteBubbles) => {
16360
+ activeOverlayState = { ...activeOverlayState, rewriteBubbles };
16361
+ setOverlayState?.(activeOverlayState);
16362
+ }));
16363
+ }
15278
16364
  } else {
15279
16365
  disposers.push(() => cleanupStaleAtPluginDom());
15280
16366
  }