universal-plugin-hub 1.5.5 → 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;
@@ -6072,6 +6240,15 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
6072
6240
  h("circle", { cx: 12, cy: 12, r: 3 }),
6073
6241
  );
6074
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
+
6075
6252
  function CustomSelect({ value, options, onChange, openUp = false }) {
6076
6253
  const [open, setOpen] = useState(false);
6077
6254
  const ref = useRef(null);
@@ -6083,8 +6260,17 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
6083
6260
  setOpen(false);
6084
6261
  }
6085
6262
  };
6263
+ const handleKeyDown = (e) => {
6264
+ if (e.key === "Escape") {
6265
+ setOpen(false);
6266
+ }
6267
+ };
6086
6268
  document.addEventListener("mousedown", handleOutside);
6087
- return () => document.removeEventListener("mousedown", handleOutside);
6269
+ document.addEventListener("keydown", handleKeyDown);
6270
+ return () => {
6271
+ document.removeEventListener("mousedown", handleOutside);
6272
+ document.removeEventListener("keydown", handleKeyDown);
6273
+ };
6088
6274
  }, [open]);
6089
6275
 
6090
6276
  const activeOption = options.find((o) => o.value === value) || options[0];
@@ -6093,6 +6279,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
6093
6279
  h("button", {
6094
6280
  type: "button",
6095
6281
  className: "cpm-select-trigger" + (open ? " open" : ""),
6282
+ "aria-expanded": open,
6096
6283
  onClick: () => setOpen(!open),
6097
6284
  },
6098
6285
  h("span", null, activeOption?.label || ""),
@@ -6468,31 +6655,72 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
6468
6655
 
6469
6656
  let currentTabAnim = null;
6470
6657
  let currentTabTarget = null;
6471
- // Per-source tab scroll position the user had when they navigated away
6472
- // from BrowseView. Restored on remount so the user comes back to the
6473
- // exact tabs they were looking at, not the auto-scroll's "active tab
6474
- // near the left edge" default.
6475
- 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
+
6476
6703
  function smoothScrollTabsTo(container, targetLeft, duration = 280, onUpdate) {
6477
6704
  if (!container) return;
6478
6705
  const startLeft = container.scrollLeft;
6479
6706
  const maxLeft = Math.max(0, container.scrollWidth - container.clientWidth);
6480
6707
  const clampTarget = Math.max(0, Math.min(maxLeft, targetLeft));
6708
+ const reducedMotion = typeof window !== "undefined" && Boolean(window.matchMedia?.("(prefers-reduced-motion: reduce)").matches);
6481
6709
 
6482
- // If already at target, finish instantly and cleanly
6483
- 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) {
6484
6712
  container.scrollLeft = clampTarget;
6485
6713
  if (currentTabAnim) {
6486
6714
  cancelAnimationFrame(currentTabAnim);
6487
6715
  currentTabAnim = null;
6488
6716
  }
6489
6717
  currentTabTarget = null;
6718
+ if (typeof SESSION_STORE === "object" && SESSION_STORE) SESSION_STORE.tabsScrollLeft = clampTarget;
6490
6719
  if (typeof onUpdate === "function") onUpdate();
6491
6720
  return;
6492
6721
  }
6493
6722
 
6494
- // If an animation is already in progress to this exact target (within 6px tolerance for active font-weight expansion), do not interrupt or twitch!
6495
- if (currentTabAnim && currentTabTarget !== null && Math.abs(currentTabTarget - clampTarget) < 6) {
6723
+ if (currentTabAnim && currentTabTarget !== null && Math.abs(currentTabTarget - clampTarget) < 0.5) {
6496
6724
  return;
6497
6725
  }
6498
6726
 
@@ -6523,6 +6751,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
6523
6751
  container.scrollLeft = clampTarget;
6524
6752
  currentTabAnim = null;
6525
6753
  currentTabTarget = null;
6754
+ if (typeof SESSION_STORE === "object" && SESSION_STORE) SESSION_STORE.tabsScrollLeft = clampTarget;
6526
6755
  if (typeof onUpdate === "function") onUpdate();
6527
6756
  }
6528
6757
  }
@@ -6600,10 +6829,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
6600
6829
  }
6601
6830
  }
6602
6831
  } catch {}
6603
- return {
6604
- sources: [{ id: "anthropic", name: "Anthropic", url: "https://github.com/anthropics/claude-plugins-official.git", builtin: true }],
6605
- plugins: [],
6606
- };
6832
+ return { sources: [], plugins: [] };
6607
6833
  }
6608
6834
 
6609
6835
  function loadCachedRows() {
@@ -6727,24 +6953,22 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
6727
6953
  }, [rootRef]);
6728
6954
  }
6729
6955
 
6956
+ const cachedState = loadCachedState();
6730
6957
  const SESSION_STORE = {
6731
6958
  view: { type: "browse" },
6732
6959
  sourceViews: {},
6960
+ mcpView: { type: "mcp", expandedServers: new Set() },
6733
6961
  browseSortSnapshots: Object.create(null),
6734
6962
  query: "",
6735
- filter: "all",
6963
+ installedFilterSources: new Set(),
6736
6964
  sortBy: "default",
6737
- activeSourceId: "anthropic",
6965
+ activeSourceId: cachedState.sources[0]?.id || "",
6738
6966
  rows: loadCachedRows(),
6739
- state: loadCachedState(),
6967
+ state: cachedState,
6740
6968
  scrollTops: {},
6741
6969
  scrollTop: 0,
6742
- // Survives the BrowseView unmount caused by opening the manage page, so
6743
- // returning from a plugin's MCP page lands back on the MCP tab.
6744
- mcpsOpen: false,
6745
- // Same reason: the MCP tab only renders when `mcps.length > 0`, so an
6746
- // empty first render after Back dropped it for a frame and Anthropic
6747
- // 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.
6748
6972
  mcps: null,
6749
6973
  };
6750
6974
 
@@ -6761,7 +6985,6 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
6761
6985
 
6762
6986
  // Persistent browse state across views and sidebar tab switching
6763
6987
  const [query, setQueryRaw] = useState(() => SESSION_STORE.query);
6764
- const [filter, setFilterRaw] = useState(() => SESSION_STORE.filter);
6765
6988
  const [sortBy, setSortByRaw] = useState(() => SESSION_STORE.sortBy);
6766
6989
  const [activeSourceId, setActiveSourceIdRaw] = useState(() => SESSION_STORE.activeSourceId);
6767
6990
  const [rows, setRowsRaw] = useState(() => SESSION_STORE.rows || loadCachedRows());
@@ -6770,57 +6993,30 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
6770
6993
 
6771
6994
  const setView = useCallback((v) => {
6772
6995
  SESSION_STORE.view = v;
6773
- if (!SESSION_STORE.sourceViews) SESSION_STORE.sourceViews = {};
6774
- const sId = (v && v.sourceId) || SESSION_STORE.activeSourceId;
6775
- if (sId) {
6776
- 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;
6777
6999
  }
6778
7000
  setViewRaw(v);
6779
7001
  }, []);
6780
7002
 
6781
- const switchSource = useCallback((newSourceId, nextFilter) => {
6782
- if (!newSourceId) return;
6783
- if (!SESSION_STORE.sourceViews) SESSION_STORE.sourceViews = {};
6784
- if (SESSION_STORE.activeSourceId && SESSION_STORE.view) {
6785
- SESSION_STORE.sourceViews[SESSION_STORE.activeSourceId] = SESSION_STORE.view;
6786
- }
7003
+ const setActiveSourceId = useCallback((newSourceId) => {
6787
7004
  SESSION_STORE.activeSourceId = newSourceId;
6788
7005
  setActiveSourceIdRaw(newSourceId);
6789
- if (nextFilter) {
6790
- SESSION_STORE.filter = nextFilter;
6791
- if (!SESSION_STORE.sourceFilters) SESSION_STORE.sourceFilters = {};
6792
- SESSION_STORE.sourceFilters[newSourceId] = nextFilter;
6793
- setFilterRaw(nextFilter);
6794
- }
6795
7006
  const targetView = SESSION_STORE.sourceViews[newSourceId] || { type: "browse", sourceId: newSourceId };
6796
- SESSION_STORE.view = targetView;
6797
- setViewRaw(targetView);
6798
- }, []);
7007
+ setView(targetView);
7008
+ }, [setView]);
6799
7009
 
6800
7010
  const setQuery = useCallback((q) => {
6801
7011
  SESSION_STORE.query = q;
6802
7012
  setQueryRaw(q);
6803
7013
  }, []);
6804
7014
 
6805
- const setFilter = useCallback((f) => {
6806
- SESSION_STORE.filter = f;
6807
- SESSION_STORE.preferredFilter = f;
6808
- if (!SESSION_STORE.sourceFilters) SESSION_STORE.sourceFilters = {};
6809
- if (SESSION_STORE.activeSourceId) {
6810
- SESSION_STORE.sourceFilters[SESSION_STORE.activeSourceId] = f;
6811
- }
6812
- setFilterRaw(f);
6813
- }, []);
6814
-
6815
7015
  const setSortBy = useCallback((s) => {
6816
7016
  SESSION_STORE.sortBy = s;
6817
7017
  setSortByRaw(s);
6818
7018
  }, []);
6819
7019
 
6820
- const setActiveSourceId = useCallback((id, nextFilter) => {
6821
- switchSource(id, nextFilter);
6822
- }, [switchSource]);
6823
-
6824
7020
  const setRows = useCallback((r) => {
6825
7021
  setRowsRaw((prev) => {
6826
7022
  const next = typeof r === "function" ? r(prev) : r;
@@ -7145,25 +7341,22 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
7145
7341
  refreshState();
7146
7342
  }, [refreshState]);
7147
7343
 
7148
- // The plugin panel itself is being closed (MarketApp unmounts). Reset
7149
- // the scroll memory so a fresh open of the panel starts at the top —
7150
- // the user explicitly wants panel close/reopen to reset scroll. This
7151
- // does NOT run when opening management inside BrowseView, so returning
7152
- // 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.
7153
7346
  useEffect(() => {
7347
+ SESSION_STORE.panelUnmounting = false;
7154
7348
  return () => {
7349
+ SESSION_STORE.panelUnmounting = true;
7155
7350
  if (SESSION_STORE.scrollTops) SESSION_STORE.scrollTops = {};
7156
- // Closing the panel is a fresh start: reopen on the plugin list,
7157
- // not on whichever MCP tab happened to be active.
7158
- SESSION_STORE.mcpsOpen = false;
7351
+ SESSION_STORE.tabsScrollLeft = null;
7159
7352
  };
7160
7353
  }, []);
7161
7354
 
7162
- const openManage = useCallback((record, fromView, tab, connector, returnToMcp = false) => {
7355
+ const openManage = useCallback((record, fromView, tab, connector) => {
7163
7356
  if (!record) return;
7164
7357
  setView({ type: "manage", sourceId: activeSourceId, pluginName: record.name,
7165
7358
  initialTab: tab || null, initialConnector: connector || null,
7166
- returnView: returnToMcp || fromView?.type === "detail" ? fromView : undefined, returnToMcp });
7359
+ returnView: fromView?.type === "mcp" || fromView?.type === "detail" ? fromView : undefined });
7167
7360
  }, [activeSourceId, setView]);
7168
7361
 
7169
7362
  return h("div", {
@@ -7190,8 +7383,6 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
7190
7383
  isDark,
7191
7384
  query,
7192
7385
  setQuery,
7193
- filter,
7194
- setFilter,
7195
7386
  sortBy,
7196
7387
  setSortBy,
7197
7388
  activeSourceId,
@@ -7777,13 +7968,13 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
7777
7968
  }
7778
7969
 
7779
7970
  // ────────────────────────────── Browse & Detail Container ──────────────────────────────
7780
- function McpOverview({ serverRows, pluginRows }) {
7781
- const rootRef = useRef(null);
7971
+ function McpOverview({ serverRows, pluginRows, containerRef, scrollState, maskClass, updateMask, suspendHover }) {
7782
7972
  const serverRef = useRef(null);
7783
7973
  const [reservedHeight, setReservedHeight] = useState(0);
7784
7974
  const reserveSpace = serverRows.length > 0 && pluginRows.length > 0;
7975
+ useRememberedDetailScroll("overview", containerRef, scrollState, updateMask);
7785
7976
  useSafeLayoutEffect(() => {
7786
- const viewport = rootRef.current?.parentElement;
7977
+ const viewport = containerRef.current;
7787
7978
  const server = serverRef.current;
7788
7979
  if (!viewport || !reserveSpace || !server) { setReservedHeight(0); return; }
7789
7980
  // A window resize and the observer's own viewport callback describe the
@@ -7795,7 +7986,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
7795
7986
  frame = requestAnimationFrame(() => { frame = 0; measure(); });
7796
7987
  };
7797
7988
  const measure = () => {
7798
- const style = getComputedStyle(viewport);
7989
+ const style = window.getComputedStyle(viewport);
7799
7990
  const available = viewport.clientHeight - (parseFloat(style.paddingTop) || 0) - (parseFloat(style.paddingBottom) || 0);
7800
7991
  // Anchor the plugin section's top edge to the midpoint. Only the
7801
7992
  // server section's actual, current height may push it down; never
@@ -7813,19 +8004,26 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
7813
8004
  observer?.disconnect();
7814
8005
  window.removeEventListener("resize", schedule);
7815
8006
  };
7816
- }, [reserveSpace]);
7817
- return h("div", { ref: rootRef, className: "cpm-mcp-overview", style: { position: "relative", maxWidth: "var(--cpm-grid-width)", margin: "0 auto", width: "100%" } },
7818
- serverRows.length > 0 && h("section", { className: "cpm-mcp-user-section", style: { display: "flow-root", minHeight: reserveSpace ? reservedHeight : undefined } },
7819
- // Measure the intrinsic content, not the section with minHeight applied:
7820
- // expansion can push the next section down, and collapse can release it.
7821
- h("div", { ref: serverRef, style: { display: "flow-root" } },
7822
- h("div", { style: { fontSize: 14, fontWeight: 700, color: "var(--cpm-text)", margin: "8px 4px 12px" } }, "服务器"),
7823
- 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),
7824
8026
  ),
7825
- ),
7826
- pluginRows.length > 0 && h("section", { className: "cpm-mcp-plugin-section", style: { display: "flow-root" } },
7827
- h("div", { style: { fontSize: 14, fontWeight: 700, color: "var(--cpm-text)", margin: "22px 4px 12px" } }, "来自插件"),
7828
- h("div", { style: { borderRadius: 16, border: "1px solid var(--cpm-border)", background: "var(--cpm-card-bg)", overflow: "hidden" } }, pluginRows),
7829
8027
  ),
7830
8028
  );
7831
8029
  }
@@ -7879,13 +8077,11 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
7879
8077
  refreshState,
7880
8078
  patchPluginInState,
7881
8079
  showToast,
7882
- openManage: openManageView,
8080
+ openManage,
7883
8081
  onInstalled,
7884
8082
  isDark,
7885
8083
  query,
7886
8084
  setQuery,
7887
- filter,
7888
- setFilter,
7889
8085
  sortBy,
7890
8086
  setSortBy,
7891
8087
  activeSourceId,
@@ -7895,8 +8091,16 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
7895
8091
  addedGitSourceIds,
7896
8092
  scrollTopRef,
7897
8093
  }) {
7898
- const [showFilter, setShowFilter] = useState(false);
7899
- 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";
7900
8104
  const [busy, setBusy] = useState(null);
7901
8105
  const [isRefreshing, setIsRefreshing] = useState(false);
7902
8106
  const [skillBusy, setSkillBusy] = useState(null);
@@ -7908,26 +8112,22 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
7908
8112
  useEffect(() => {
7909
8113
  if (!addDialog) addDialogBusyRef.current = false;
7910
8114
  }, [addDialog]);
7911
- const [showAddMenu, setShowAddMenu] = useState(false);
7912
8115
  const localSource = state.sources.find((s) => s.id === "local");
7913
8116
  const hasLocalPlugins = typeof localSource?.pluginCount === "number" ? localSource.pluginCount > 0 : (rows?.local?.length || 0) > 0;
7914
- useEffect(() => {
7915
- if (activeSourceId === "local" && !hasLocalPlugins) {
7916
- const next = state.sources.find((s) => s.id !== "local");
7917
- if (next) setActiveSourceId(next.id);
7918
- }
7919
- }, [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]);
7920
8127
  const [mcpDialog, setMcpDialog] = useState(false);
7921
8128
  const [mcps, setMcps] = useState(() => SESSION_STORE.mcps || []);
7922
- const [mcpsOpen, setMcpsOpenRaw] = useState(() => !!SESSION_STORE.mcpsOpen);
7923
- const setMcpsOpen = useCallback((v) => {
7924
- SESSION_STORE.mcpsOpen = v;
7925
- setMcpsOpenRaw(v);
7926
- }, []);
7927
- const openManage = (record, fromView, tab, connector) => {
7928
- setMcpsOpen(false);
7929
- openManageView(record, mcpsOpen ? view : fromView, tab, connector, mcpsOpen);
7930
- };
8129
+ const mcpsOpen = view.type === "mcp";
8130
+ const isMcpTab = mcpsOpen || view.returnView?.type === "mcp";
7931
8131
  const [editMcp, setEditMcp] = useState(null);
7932
8132
  // Plugin name when the editor was opened from a plugin-provided server;
7933
8133
  // null means the editor targets a user-added MCP.
@@ -7943,16 +8143,29 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
7943
8143
  }
7944
8144
  return initial;
7945
8145
  });
7946
- const [globalExpanded, setGlobalExpanded] = useState({});
8146
+ const [globalExpanded, setGlobalExpanded] = useState(() => SESSION_STORE.mcpView.expandedServers);
7947
8147
  const [globalHoveredTool, closeGlobalHover, globalHover] = useHoverPreview();
7948
8148
  useEffect(() => { closeGlobalHover(); }, [mcpsOpen, view?.type, closeGlobalHover]);
7949
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
+
7950
8160
  const refreshMcps = useCallback(async () => {
7951
8161
  try {
7952
8162
  const res = await api("/mcps");
7953
8163
  SESSION_STORE.mcps = res.mcps || [];
7954
- setMcps(SESSION_STORE.mcps);
7955
- } catch {}
8164
+ if (!browseUnmountedRef.current) setMcps(SESSION_STORE.mcps);
8165
+ return SESSION_STORE.mcps;
8166
+ } catch {
8167
+ return null;
8168
+ }
7956
8169
  }, []);
7957
8170
 
7958
8171
  useEffect(() => {
@@ -7978,47 +8191,106 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
7978
8191
  }).filter((c) => typeof c.name === "string" && c.name.trim())
7979
8192
  ), [state.plugins]);
7980
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]);
7981
8216
 
7982
- const loadGlobalTools = useCallback(async (owner, connectorName, forceFresh = false) => {
8217
+ const autoLoadGlobalTools = useCallback((owner, connectorName) => {
7983
8218
  const key = `${owner}::${connectorName}`;
8219
+ const forceStdio = typeof consumeStdioForceRefresh === "function" && consumeStdioForceRefresh(key);
7984
8220
  const cached = GLOBAL_MCP_TOOLS_CACHE[key];
7985
- setGlobalToolData((prev) => ({
7986
- ...prev,
7987
- [key]: { ...(cached || prev[key]), loading: forceFresh || !Array.isArray(cached?.tools), error: null, warning: null },
7988
- }));
7989
- try {
7990
- const url = owner === "user-mcp"
7991
- ? `/mcps/${encodeURIComponent(connectorName)}/tools`
7992
- : `/plugins/${encodeURIComponent(owner)}/connectors/${encodeURIComponent(connectorName)}/tools`;
7993
- const res = await api(url + (forceFresh ? "?fresh=1" : ""));
7994
- const tools = Array.isArray(res.tools) ? res.tools : [];
7995
- const disabledTools = Array.isArray(res.disabledTools) ? res.disabledTools : [];
7996
- if (res.ok) saveMcpToolsCache(key, { tools, disabledTools });
7997
- setGlobalToolData((prev) => ({
7998
- ...prev,
7999
- [key]: {
8000
- loading: false,
8001
- error: res.ok ? null : (res.message || "获取能力列表失败"),
8002
- warning: res.ok && res.stale ? (res.message || "获取能力列表失败") : null,
8003
- tools: res.ok ? tools : (prev[key]?.tools || tools),
8004
- disabledTools,
8005
- },
8006
- }));
8007
- } catch (e) {
8008
- 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;
8009
8226
  }
8010
- }, []);
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]);
8011
8281
 
8012
8282
  useAutoMcpTools([
8013
- ...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]) })),
8014
8284
  ...mcps.map(row => ({ owner: "user-mcp", name: row.name, connected: row.enabled === true, revision: JSON.stringify(row) })),
8015
- ], loadGlobalTools);
8285
+ ], autoLoadGlobalTools);
8016
8286
 
8017
- const toggleGlobalExpand = useCallback((owner, connectorName) => {
8287
+ const toggleGlobalExpand = useCallback((owner, connectorName) => {
8018
8288
  const key = `${owner}::${connectorName}`;
8019
- const willExpand = !globalExpanded[key];
8020
- setGlobalExpanded((prev) => ({ ...prev, [key]: willExpand }));
8021
- }, [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
+ }, []);
8022
8294
 
8023
8295
  const toggleGlobalTool = useCallback(async (owner, connectorName, toolName) => {
8024
8296
  const key = `${owner}::${connectorName}`;
@@ -8059,7 +8331,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8059
8331
  const serverEnabled = canEdit ? connected : conn?.enabled === true;
8060
8332
  const enabled = Object.prototype.hasOwnProperty.call(optimisticMcp, key) ? optimisticMcp[key] : serverEnabled;
8061
8333
  const toggling = pendingMcpToggles[key] === true;
8062
- const isExpanded = !!globalExpanded[key];
8334
+ const isExpanded = globalExpanded.has(key);
8063
8335
  const info = globalToolData[key];
8064
8336
  const toolsList = info?.tools || [];
8065
8337
  const disabledTools = info?.disabledTools || [];
@@ -8080,6 +8352,16 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8080
8352
  showToast("操作失败", res.error || "请稍后重试", { restart: false });
8081
8353
  return;
8082
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
+ }
8083
8365
  if (canEdit) await refreshMcps();
8084
8366
  else if (res?.plugin && patchPluginInState) {
8085
8367
  patchPluginInState(res.plugin);
@@ -8113,7 +8395,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8113
8395
  // Buttons inside the row keep their own handlers.
8114
8396
  const onRowClick = canEdit ? undefined : (e) => {
8115
8397
  if (e.target.closest("button, .cpm-mcp-tools-panel")) return;
8116
- if (record) openManage(record, { type: "browse", sourceId: activeSourceId }, "connectors");
8398
+ if (record) openManage(record, view, "connectors");
8117
8399
  };
8118
8400
 
8119
8401
  return h("div", {
@@ -8191,6 +8473,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8191
8473
  const installedByName = useMemo(() => new Map(state.plugins.map(plugin => [plugin.name, plugin])), [state.plugins]);
8192
8474
  const resolveMarketplaceIcon = useMemo(() => createMarketplaceIconResolver(installedByName, state.sources), [installedByName, state.sources]);
8193
8475
  const gridRef = useRef(null);
8476
+ const mcpGridRef = useRef(null);
8194
8477
  const detailContainerRef = useRef(null);
8195
8478
  const tabsRef = useRef(null);
8196
8479
  const tabRefs = useRef({});
@@ -8263,7 +8546,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8263
8546
  }, []);
8264
8547
 
8265
8548
  const updateGridMask = useCallback(() => {
8266
- const el = gridRef.current;
8549
+ const el = mcpGridRef.current || gridRef.current;
8267
8550
  if (!el) return;
8268
8551
  const maxScroll = el.scrollHeight - el.clientHeight;
8269
8552
  setGridMaskClass(maxScroll > 4 && el.scrollTop < maxScroll - 4 ? " mask-bottom" : "");
@@ -8365,7 +8648,8 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8365
8648
 
8366
8649
  if (hoveredPreview) closePluginHover();
8367
8650
 
8368
- 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));
8369
8653
  smoothScrollTabsTo(el, targetLeft, 180, updateTabsMask);
8370
8654
  };
8371
8655
 
@@ -8379,53 +8663,33 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8379
8663
  closePluginHover();
8380
8664
  }, [activeSourceId, view?.type]);
8381
8665
 
8382
- useEffect(() => {
8383
- return () => {
8384
- if (scrollTimerRef.current) clearTimeout(scrollTimerRef.current);
8385
- if (currentTabAnim) {
8386
- cancelAnimationFrame(currentTabAnim);
8387
- currentTabAnim = null;
8388
- currentTabTarget = null;
8389
- }
8390
- };
8391
- }, []);
8392
-
8393
- useSafeLayoutEffect(() => {
8394
- updateTabsMask();
8395
- window.addEventListener("resize", updateTabsMask);
8396
- return () => {
8397
- window.removeEventListener("resize", updateTabsMask);
8398
- };
8399
- }, [updateTabsMask, state.sources, view?.type]);
8400
-
8401
- 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);
8402
8671
 
8403
8672
  const scrollActiveTabIntoView = useCallback((tabId, animated = true) => {
8404
8673
  const container = tabsRef.current;
8405
8674
  const tabEl = tabRefs.current[tabId];
8406
8675
  if (!container || !tabEl) return;
8407
8676
 
8408
- const tabLeft = tabEl.offsetLeft;
8409
- const tabWidth = tabEl.offsetWidth;
8410
- const tabRight = tabLeft + tabWidth;
8411
- const currentScroll = (currentTabTarget !== null) ? currentTabTarget : container.scrollLeft;
8412
- const containerWidth = container.clientWidth;
8413
-
8414
- let targetScroll = currentScroll;
8415
- // 1. Rightward overflow: if tab is covered by right feathering mask (28px)
8416
- if (tabRight > currentScroll + containerWidth - 28) {
8417
- targetScroll = tabRight - containerWidth + 26;
8418
- }
8419
- // 2. Leftward overflow: if tab is covered by left feathering mask (26px safe distance)
8420
- else if (tabLeft < currentScroll + 26) {
8421
- targetScroll = Math.max(0, tabLeft - 26);
8422
- }
8677
+ const baseScroll = (currentTabAnim && currentTabTarget !== null) ? currentTabTarget : container.scrollLeft;
8678
+ const targetScroll = computeTabRevealScrollLeft(container, tabEl, baseScroll);
8679
+ if (targetScroll === null) return;
8423
8680
 
8424
8681
  if (Math.abs(targetScroll - container.scrollLeft) > 1) {
8425
8682
  if (animated) {
8426
8683
  smoothScrollTabsTo(container, targetScroll, 280, updateTabsMask);
8427
8684
  } else {
8685
+ if (currentTabAnim) {
8686
+ cancelAnimationFrame(currentTabAnim);
8687
+ currentTabAnim = null;
8688
+ }
8689
+ currentTabTarget = null;
8428
8690
  container.scrollLeft = targetScroll;
8691
+ tabsScrollLeftRef.current = targetScroll;
8692
+ if (didRestoreTabScrollRef.current) SESSION_STORE.tabsScrollLeft = targetScroll;
8429
8693
  updateTabsMask();
8430
8694
  }
8431
8695
  } else {
@@ -8433,6 +8697,59 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8433
8697
  }
8434
8698
  }, [updateTabsMask]);
8435
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
+
8436
8753
  useSafeLayoutEffect(() => {
8437
8754
  if (view?.type === "browse" || !view?.type) {
8438
8755
  updateTabsMask();
@@ -8440,77 +8757,51 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8440
8757
  }, [view?.type, updateTabsMask]);
8441
8758
 
8442
8759
  useEffect(() => {
8443
- if (prevSourceRef.current !== activeSourceId) {
8444
- prevSourceRef.current = activeSourceId;
8445
- scrollActiveTabIntoView(activeSourceId, true);
8446
- setMcpsOpen(false);
8447
- }
8448
- }, [activeSourceId, scrollActiveTabIntoView]);
8449
-
8450
- // Restore the user's previous tab-bar scroll position on remount.
8451
- // The tab container is a horizontal scroller the user controls with
8452
- // the wheel, by dragging, or by clicking the feathered edges. Their
8453
- // chosen position is a real UI state. `scrollActiveTabIntoView` is
8454
- // designed to drag the active tab to a "near the left edge" default
8455
- // and would overwrite that position on every Back, so:
8456
- // - first mount (no saved value): auto-scroll to bring the active
8457
- // tab into view, as a convenience
8458
- // - every remount after that: restore the exact saved scroll and
8459
- // skip the auto-scroll entirely
8460
- //
8461
- // `currentTabTarget` is also reset so the auto-scroll's `currentScroll`
8462
- // baseline is the DOM's real scrollLeft, not an in-flight target from
8463
- // an animation that the BrowseView unmount interrupted.
8464
- //
8465
- // The deps include `state.sources` (and its length) so a state
8466
- // refresh that changes the source list after mount re-applies the
8467
- // correct position once the new layout is committed.
8468
- useSafeLayoutEffect(() => {
8469
- currentTabTarget = null;
8470
- const container = tabsRef.current;
8471
- if (!container) return;
8472
- const saved = savedTabScrolls.get(activeSourceId);
8473
- if (typeof saved === "number") {
8474
- container.scrollLeft = saved;
8475
- updateTabsMask();
8476
- 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
+ }
8477
8768
  }
8478
- scrollActiveTabIntoView(activeSourceId, false);
8479
- }, [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]);
8480
8777
 
8481
- // Mirror the tab container's scrollLeft into a regular ref so the
8482
- // unmount-cleanup below can read it after `tabsRef.current` is nulled
8483
- // (React detaches DOM refs before running useEffect cleanups). Without
8484
- // this, the save on manage→back never lands and the new mount falls
8485
- // through to the auto-scroll default.
8486
- const tabsScrollLeftRef = useRef(0);
8487
8778
  useEffect(() => {
8488
8779
  const el = tabsRef.current;
8489
8780
  if (!el) return;
8490
- tabsScrollLeftRef.current = el.scrollLeft;
8491
8781
  const handler = () => {
8492
8782
  tabsScrollLeftRef.current = el.scrollLeft;
8783
+ if (didRestoreTabScrollRef.current) SESSION_STORE.tabsScrollLeft = el.scrollLeft;
8493
8784
  };
8494
8785
  el.addEventListener("scroll", handler, { passive: true });
8495
8786
  return () => el.removeEventListener("scroll", handler);
8496
- }, [state.sources, state.sources.length]);
8787
+ }, []);
8497
8788
 
8498
- // Persist the user's current scroll for the active source so a later
8499
- // remount of BrowseView (e.g. after the user opens and closes an
8500
- // installed plugin's manage page) lands them at the exact same
8501
- // scroll position rather than at scrollLeft=0.
8502
8789
  useEffect(() => {
8503
8790
  return () => {
8504
- if (!activeSourceId) return;
8505
- // Prefer the in-flight animation target if the user navigated
8506
- // away mid-scroll — the mid-animation scrollLeft is a value
8507
- // they never saw.
8508
- const final = (currentTabAnim && currentTabTarget !== null)
8509
- ? currentTabTarget
8510
- : tabsScrollLeftRef.current;
8511
- 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
+ }
8512
8803
  };
8513
- }, [activeSourceId]);
8804
+ }, []);
8514
8805
 
8515
8806
  // ────────────────────────────── Tab Long-Press Drag Reorder ──────────────────────────────
8516
8807
  const [dragState, setDragState] = useState(null);
@@ -8583,7 +8874,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8583
8874
  // reachable even when a short tab sits between two much wider tabs.
8584
8875
  // Frozen geometry also prevents animated neighbors feeding back on hit tests.
8585
8876
  for (const slot of baseSlots) {
8586
- if (!slot || !slot.movable) continue;
8877
+ if (!slot) continue;
8587
8878
  const left = slot.offsetLeft + (slot.index > fromIndex ? slot.width - draggedWidth : 0);
8588
8879
  const distance = Math.abs(contentCenter - (left + draggedWidth / 2));
8589
8880
  if (distance < nearestDistance) {
@@ -8670,8 +8961,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8670
8961
  if (dragLiveRef.current.active || dragState) {
8671
8962
  cancelOrResetDrag();
8672
8963
  }
8673
- if (s.builtin || idx === 0 || (s.id && s.id.toLowerCase() === "anthropic")) return;
8674
- if (!state.sources || state.sources.length < 3) return;
8964
+ if (!state.sources.some((item) => item.id !== s.id && tabRefs.current[item.id]?.isConnected)) return;
8675
8965
 
8676
8966
  const pointerId = e.pointerId;
8677
8967
  const clientX = e.clientX;
@@ -8719,7 +9009,6 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8719
9009
  return {
8720
9010
  id: item.id,
8721
9011
  index: mIdx,
8722
- movable: mIdx !== 0 && !item.builtin && item.id?.toLowerCase() !== "anthropic",
8723
9012
  offsetLeft: rect.left - cRect.left + curScroll,
8724
9013
  width: rect.width,
8725
9014
  height: rect.height || 30,
@@ -8809,7 +9098,20 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8809
9098
  }
8810
9099
  }, [startAutoScroll, stopAutoScroll, updateDragPosition]);
8811
9100
 
8812
- 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) => {
8813
9115
  if (dragLiveRef.current.isSnapping) return;
8814
9116
  if (dragLiveRef.current.pointerId !== null && e?.pointerId !== dragLiveRef.current.pointerId) return;
8815
9117
  if (longPressTimerRef.current) {
@@ -8857,17 +9159,18 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8857
9159
  if (!dragLiveRef.current.isSnapping) return;
8858
9160
  clearTimeout(snapTimerRef.current);
8859
9161
  snapFinishRef.current = null;
8860
- if (toIndex !== fromIndex && fromIndex >= 1 && toIndex >= 1) {
8861
- // Keep the tab bar where the user left it: the state.sources
8862
- // change re-runs the tab-scroll restore layout effect, which
8863
- // would otherwise snap back to the active (leftmost) tab and
8864
- // hide the tab the user just dropped at the end. Save the
8865
- // 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) {
8866
9166
  const scrollEl = tabsRef.current;
8867
- if (scrollEl) savedTabScrolls.set(activeSourceId, scrollEl.scrollLeft);
8868
- const newSources = [...state.sources];
8869
- const [moved] = newSources.splice(fromIndex, 1);
8870
- 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);
8871
9174
  setState((prev) => ({ ...prev, sources: newSources }));
8872
9175
  SESSION_STORE.state = { ...(SESSION_STORE.state || {}), sources: newSources };
8873
9176
  try {
@@ -8877,7 +9180,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8877
9180
  method: "POST",
8878
9181
  body: JSON.stringify({ sourceIds: newSources.map((item) => item.id) }),
8879
9182
  }).catch(() => {});
8880
- showToast("标签排序已更新", `已将「${moved.name}」移至第 ${toIndex + 1} 位`, { restart: false });
9183
+ showToast("标签排序已更新", `已将「${moved.name}」移至第 ${currentTo + 1} 位`, { restart: false });
8881
9184
  }
8882
9185
  dragLiveRef.current.active = false;
8883
9186
  dragLiveRef.current.isSnapping = false;
@@ -8896,38 +9199,8 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8896
9199
  return;
8897
9200
  }
8898
9201
 
8899
- // Normal click action
8900
- if (!isLongPressTriggeredRef.current && s) {
8901
- const isBrowseView = !view || view.type === "browse";
8902
- if (mcpsOpen) setMcpsOpen(false);
8903
- const listedNames = new Set((SESSION_STORE.rows?.[s.id] || []).map(p => p.name));
8904
- const hasInstalled = (state.plugins || []).some(p => (p.sourceId || "").toLowerCase() === s.id.toLowerCase() || p.id?.startsWith(s.id + "/") || listedNames.has(p.name));
8905
- if (s.id !== activeSourceId) {
8906
- if (gridRef.current && isBrowseView && !mcpsOpen) {
8907
- if (!SESSION_STORE.scrollTops) SESSION_STORE.scrollTops = {};
8908
- SESSION_STORE.scrollTops[activeSourceId] = gridRef.current.scrollTop;
8909
- }
8910
- if (!SESSION_STORE.sourceFilters) SESSION_STORE.sourceFilters = {};
8911
-
8912
- let targetFilter = filter;
8913
- if (!hasInstalled) {
8914
- if (filter === "installed") {
8915
- SESSION_STORE.preferredFilter = "installed";
8916
- }
8917
- targetFilter = "all";
8918
- } else {
8919
- targetFilter = SESSION_STORE.sourceFilters[s.id] || SESSION_STORE.preferredFilter || (filter === "installed" ? "installed" : "all");
8920
- }
8921
- setActiveSourceId(s.id, targetFilter);
8922
- } else if (!mcpsOpen) {
8923
- // Clicking the current source's tab scrolls its list back to the top.
8924
- scrollActiveTabIntoView(s.id, true);
8925
- if (!SESSION_STORE.scrollTops) SESSION_STORE.scrollTops = {};
8926
- SESSION_STORE.scrollTops[s.id] = 0;
8927
- scrollContentToTop();
8928
- }
8929
- }
8930
- }, [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]);
8931
9204
 
8932
9205
  useEffect(() => {
8933
9206
  const handleWindowBlurOrCancel = () => {
@@ -8936,7 +9209,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8936
9209
 
8937
9210
  const handleGlobalPointerUp = (e) => {
8938
9211
  if ((dragLiveRef.current.active || longPressTimerRef.current) && !dragLiveRef.current.isSnapping) {
8939
- handleTabPointerUp(e, null, dragLiveRef.current.fromIndex);
9212
+ handleTabPointerUp(e, null);
8940
9213
  }
8941
9214
  };
8942
9215
 
@@ -9013,10 +9286,8 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9013
9286
  // grid should be scrolled to after the next commit:
9014
9287
  // - { type: "restore" } — active source changed: back to the saved
9015
9288
  // scrollTop for the source the user switched to.
9016
- // - { type: "reset" } — filter/sort explicitly changed
9017
- // (全部插件/已安装/排序): back to 0. Deliberately does NOT zero
9018
- // the saved `scrollTops[...]` for the source, so a filter/sort
9019
- // change doesn't wipe the tab-switch memory.
9289
+ // - { type: "reset", filter } — the current source switched
9290
+ // between 全部插件 and 已安装: back to 0.
9020
9291
  // - null — nothing pending: installs, detail view
9021
9292
  // open/close, plain re-renders leave scroll alone.
9022
9293
  //
@@ -9033,7 +9304,6 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9033
9304
  const pendingScrollTopRef = useRef(null);
9034
9305
  const lastActiveSourceRef = useRef(activeSourceId);
9035
9306
  const lastFilterRef = useRef(filter);
9036
- const lastSortByRef = useRef(sortBy);
9037
9307
  const prevIsBrowseRef = useRef(isSourceBrowse);
9038
9308
  const firstBrowseRenderRef = useRef(true);
9039
9309
 
@@ -9049,13 +9319,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9049
9319
  // you left that source, not at the top. So only set reset when
9050
9320
  // there is no restore already pending for this commit.
9051
9321
  if (pendingScrollTopRef.current?.type !== "restore") {
9052
- pendingScrollTopRef.current = { type: "reset", filter, sortBy };
9053
- }
9054
- }
9055
- if (sortBy !== lastSortByRef.current) {
9056
- lastSortByRef.current = sortBy;
9057
- if (pendingScrollTopRef.current?.type !== "restore") {
9058
- pendingScrollTopRef.current = { type: "reset", filter, sortBy };
9322
+ pendingScrollTopRef.current = { type: "reset", filter };
9059
9323
  }
9060
9324
  }
9061
9325
  // Details and MCP both unmount the source grid. Returning to either the
@@ -9093,7 +9357,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9093
9357
  if (!isSourceBrowse || !gridRef.current) return;
9094
9358
  const pending = pendingScrollTopRef.current;
9095
9359
  if (!pending) return;
9096
- if (pending.type === "reset" && (pending.filter !== filter || pending.sortBy !== sortBy)) return;
9360
+ if (pending.type === "reset" && pending.filter !== filter) return;
9097
9361
  const target = pending.type === "restore"
9098
9362
  ? ((SESSION_STORE.scrollTops && SESSION_STORE.scrollTops[activeSourceId]) || 0)
9099
9363
  : 0;
@@ -9139,16 +9403,27 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9139
9403
  useEffect(() => {
9140
9404
  const onDocClick = (e) => {
9141
9405
  if (!e.target.closest(".cpm-filter") && !e.target.closest(".cpm-sort") && !e.target.closest(".cpm-add-btn") && !e.target.closest(".cpm-menu-pop")) {
9142
- setShowFilter(false);
9143
- setShowSort(false);
9144
- setShowAddMenu(false);
9406
+ setOpenTopMenu(null);
9407
+ }
9408
+ };
9409
+ const onKeyDown = (e) => {
9410
+ if (e.key === "Escape") {
9411
+ setOpenTopMenu(null);
9145
9412
  }
9146
9413
  };
9147
- if (showFilter || showSort || showAddMenu) {
9414
+ if (openTopMenu) {
9148
9415
  document.addEventListener("mousedown", onDocClick);
9149
- return () => document.removeEventListener("mousedown", onDocClick);
9416
+ document.addEventListener("keydown", onKeyDown);
9417
+ return () => {
9418
+ document.removeEventListener("mousedown", onDocClick);
9419
+ document.removeEventListener("keydown", onKeyDown);
9420
+ };
9150
9421
  }
9151
- }, [showFilter, showSort, showAddMenu]);
9422
+ }, [openTopMenu]);
9423
+
9424
+ useEffect(() => {
9425
+ setOpenTopMenu(null);
9426
+ }, [activeSourceId, mcpsOpen, view.type]);
9152
9427
 
9153
9428
  const loadMarket = useCallback(async (sourceId) => {
9154
9429
  if (!sourceId) return;
@@ -9328,6 +9603,69 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9328
9603
  }
9329
9604
  });
9330
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
+
9331
9669
  const removePlugin = async (pluginName) => {
9332
9670
  try {
9333
9671
  const result = await api("/plugins/" + encodeURIComponent(pluginName), { method: "DELETE" });
@@ -9376,6 +9714,79 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9376
9714
  }, [currentSourcePlugins, query, sortBy, sortInstalledNames, crossSourceInstalledNames]);
9377
9715
 
9378
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
+ }
9379
9790
  const refreshSourceId = activeSourceId;
9380
9791
  setIsRefreshing(true);
9381
9792
  if (detailEpochRef.current) {
@@ -9389,6 +9800,10 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9389
9800
  const refreshEpoch = (refreshSourceId && detailEpochRef.current?.[refreshSourceId]) || 0;
9390
9801
  if (detailCacheRef.current) detailCacheRef.current = {};
9391
9802
  try {
9803
+ if (!refreshSourceId) {
9804
+ await refreshState();
9805
+ return;
9806
+ }
9392
9807
  if (refreshSourceId === "skills-local") {
9393
9808
  const body = await api("/skills/refresh", { method: "POST" });
9394
9809
  setRows(prev => ({ ...(prev || {}), "skills-local": body.skills || [] }));
@@ -9481,7 +9896,6 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9481
9896
  // A removal can finish after the user has switched to another tab.
9482
9897
  if (SESSION_STORE.view !== view) return;
9483
9898
  setView(view.returnView || { type: "browse", sourceId: activeSourceId });
9484
- if (view.returnToMcp) setMcpsOpen(true);
9485
9899
  };
9486
9900
  const openPlugin = (plugin) => {
9487
9901
  closePluginHover();
@@ -9517,29 +9931,28 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9517
9931
  // MCP is a fixed entry pinned ahead of the source tabs; it has no
9518
9932
  // drag handlers, so it can never be reordered. It must also show
9519
9933
  // when only plugin-provided servers exist — the page lists both.
9520
- hasMcps && h("button", {
9934
+ showMcpTab && h("button", {
9521
9935
  key: "__mcps",
9522
- className: "cpm-tab" + (mcpsOpen ? " active" : ""),
9936
+ ref: (el) => { tabRefs.current["__mcps"] = el; },
9937
+ className: "cpm-tab" + (isMcpTab ? " active" : ""),
9523
9938
  onClick: () => {
9524
9939
  if (isSourceBrowse && gridRef.current) {
9525
9940
  if (!SESSION_STORE.scrollTops) SESSION_STORE.scrollTops = {};
9526
9941
  SESSION_STORE.scrollTops[activeSourceId] = gridRef.current.scrollTop;
9527
9942
  }
9528
9943
  stopScrollTopAnim();
9529
- setMcpsOpen(true); refreshMcps();
9944
+ setView(SESSION_STORE.mcpView);
9945
+ refreshMcps();
9946
+ if (isMcpTab) scrollActiveTabIntoView("__mcps", true);
9530
9947
  },
9531
9948
  }, h("span", null, "MCP")),
9532
9949
  state.sources.map((s, idx) => {
9533
9950
  if (s.id === "local" && !hasLocalPlugins) return null;
9534
- const isAnthropic = idx === 0 || s.builtin || (s.id && s.id.toLowerCase() === "anthropic");
9535
9951
  const isBeingDragged = dragState?.active && dragState.sourceId === s.id;
9536
9952
  let tabTransform = undefined;
9537
9953
  let tabClassExtra = "";
9538
9954
 
9539
- if (isAnthropic) {
9540
- tabTransform = undefined;
9541
- tabClassExtra = "";
9542
- } else if (dragState?.active) {
9955
+ if (dragState?.active) {
9543
9956
  if (isBeingDragged) {
9544
9957
  tabClassExtra = " is-placeholder";
9545
9958
  } else {
@@ -9566,21 +9979,21 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9566
9979
  return h("button", {
9567
9980
  key: s.id,
9568
9981
  ref: (el) => { tabRefs.current[s.id] = el; },
9569
- className: "cpm-tab" + (s.id === activeSourceId && !mcpsOpen ? " active" : "") + tabClassExtra,
9982
+ className: "cpm-tab" + (s.id === activeSourceId && !isMcpTab ? " active" : "") + tabClassExtra,
9570
9983
  style: tabTransform ? { transform: tabTransform } : undefined,
9571
9984
  onPointerDown: (e) => handleTabPointerDown(e, s, idx),
9572
9985
  onPointerMove: handleTabPointerMove,
9573
- onPointerUp: (e) => handleTabPointerUp(e, s, idx),
9986
+ onPointerUp: (e) => handleTabPointerUp(e, s),
9574
9987
  onPointerCancel: cancelOrResetDrag,
9575
9988
  onLostPointerCapture: (e) => {
9576
9989
  if (e.pointerId === dragLiveRef.current.pointerId && !dragLiveRef.current.isSnapping) cancelOrResetDrag();
9577
9990
  },
9578
9991
  onContextMenu: (e) => e.preventDefault(),
9579
9992
  onMouseDown: (e) => e.preventDefault(),
9580
- onClick: () => setMcpsOpen(false),
9993
+ onClick: (e) => { if (e.detail === 0) selectSourceTab(s.id); },
9581
9994
  },
9582
9995
  h("span", null, s.name),
9583
- !s.builtin && !s.virtual && h("span", {
9996
+ !s.virtual && h("span", {
9584
9997
  className: "cpm-tab-del-zone",
9585
9998
  onPointerDown: (e) => e.stopPropagation(),
9586
9999
  onClick: (e) => {
@@ -9609,22 +10022,24 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9609
10022
  ),
9610
10023
  h("div", { className: "cpm-topbar-right" },
9611
10024
  h("button", { className: "cpm-icon-btn" + (isRefreshing ? " is-refreshing" : ""), onClick: refresh, disabled: isRefreshing }, h(IconRefresh)),
9612
- activeSourceId !== "skills-local" && h("div", { style: { position: "relative" } },
9613
- h("button", { className: "cpm-filter" + (showFilter ? " open" : ""), onClick: () => { setShowFilter(!showFilter); setShowSort(false); } },
9614
- 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" ? "已安装" : "全部插件"),
9615
10028
  h("span", { className: "cpm-filter-chevron" }, h(IconArrow)),
9616
10029
  ),
9617
10030
  showFilter && h("div", { className: "cpm-menu-pop", style: { top: 34, right: 0, minWidth: 120 } },
9618
10031
  h("div", { className: "cpm-menu-item", onClick: () => {
9619
- setFilter("all");
9620
- setShowFilter(false);
10032
+ setOpenTopMenu(null);
10033
+ if (filter !== "installed") return;
9621
10034
  if (!SESSION_STORE.scrollTops) SESSION_STORE.scrollTops = {};
10035
+ for (const sourceId of installedFilterSources) delete SESSION_STORE.scrollTops[sourceId];
10036
+ setInstalledFilterSources(new Set());
9622
10037
  SESSION_STORE.scrollTops[activeSourceId] = 0;
9623
10038
  scrollContentToTop();
9624
10039
  } }, `全部插件 (${totalSourcePluginsCount})`),
9625
10040
  h("div", { className: "cpm-menu-item", onClick: () => {
9626
- setFilter("installed");
9627
- setShowFilter(false);
10041
+ setInstalledFilterSources(new Set(installedFilterSources).add(activeSourceId));
10042
+ setOpenTopMenu(null);
9628
10043
  if (!SESSION_STORE.scrollTops) SESSION_STORE.scrollTops = {};
9629
10044
  SESSION_STORE.scrollTops[activeSourceId] = 0;
9630
10045
  scrollContentToTop();
@@ -9632,47 +10047,40 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9632
10047
  ),
9633
10048
  ),
9634
10049
  h("div", { style: { position: "relative" } },
9635
- 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") },
9636
10051
  h("span", null, sortBy === "name-asc" ? "名称 A-Z" : sortBy === "name-desc" ? "名称 Z-A" : "默认排序"),
9637
10052
  h("span", { className: "cpm-filter-chevron" }, h(IconArrow)),
9638
10053
  ),
9639
10054
  showSort && h("div", { className: "cpm-menu-pop", style: { top: 34, right: 0, minWidth: 120 } },
9640
10055
  h("div", { className: "cpm-menu-item", onClick: () => {
9641
10056
  setSortBy("default");
9642
- setShowSort(false);
9643
- if (!SESSION_STORE.scrollTops) SESSION_STORE.scrollTops = {};
9644
- SESSION_STORE.scrollTops[activeSourceId] = 0;
9645
- scrollContentToTop();
10057
+ setOpenTopMenu(null);
9646
10058
  } }, "默认排序"),
9647
10059
  h("div", { className: "cpm-menu-item", onClick: () => {
9648
10060
  setSortBy("name-asc");
9649
- setShowSort(false);
9650
- if (!SESSION_STORE.scrollTops) SESSION_STORE.scrollTops = {};
9651
- SESSION_STORE.scrollTops[activeSourceId] = 0;
9652
- scrollContentToTop();
10061
+ setOpenTopMenu(null);
9653
10062
  } }, "名称 (A-Z)"),
9654
10063
  h("div", { className: "cpm-menu-item", onClick: () => {
9655
10064
  setSortBy("name-desc");
9656
- setShowSort(false);
9657
- if (!SESSION_STORE.scrollTops) SESSION_STORE.scrollTops = {};
9658
- SESSION_STORE.scrollTops[activeSourceId] = 0;
9659
- scrollContentToTop();
10065
+ setOpenTopMenu(null);
9660
10066
  } }, "名称 (Z-A)"),
9661
10067
  ),
9662
10068
  ),
9663
10069
  h("div", { style: { position: "relative" } },
9664
10070
  h("button", {
10071
+ type: "button",
9665
10072
  className: "cpm-add-btn" + (showAddMenu ? " open" : ""),
10073
+ "aria-expanded": showAddMenu,
9666
10074
  style: { width: "auto", padding: "0 8px", gap: 3 },
9667
- onClick: () => { setShowAddMenu(!showAddMenu); },
10075
+ onClick: () => setOpenTopMenu((cur) => cur === "add" ? null : "add"),
9668
10076
  },
9669
10077
  h(IconPlus),
9670
10078
  h("span", { className: "cpm-filter-chevron" }, h(IconArrow)),
9671
10079
  ),
9672
10080
  showAddMenu && h("div", { className: "cpm-menu-pop", style: { top: 34, right: 0, minWidth: 150 } },
9673
- h("div", { className: "cpm-menu-item", onClick: () => { setShowAddMenu(false); setAddDialog({ initialPhase: "url" }); } }, "添加插件市场"),
9674
- h("div", { className: "cpm-menu-item", onClick: () => { setShowAddMenu(false); setAddDialog({ initialPhase: "upload" }); } }, "上传插件 / Skills"),
9675
- 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"),
9676
10084
  ),
9677
10085
  ),
9678
10086
  ),
@@ -9707,15 +10115,24 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9707
10115
  isDark,
9708
10116
  installing: Boolean(currentDetailPlugin && isPluginInstalling(currentDetailPlugin.name)),
9709
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",
9710
10120
  onBack: () => setView({ type: "browse", sourceId: activeSourceId }),
9711
10121
  onInstall: () => { if (!installDialogBusyRef.current && !installingNamesRef.current.has(String(currentDetailPlugin.name || "").toLowerCase())) setInstallFor(currentDetailPlugin); },
9712
10122
  onRemove: () => removePlugin(currentDetailPlugin.name),
10123
+ onDeleteLocal: () => deleteLocalPlugin(currentDetailPlugin),
9713
10124
  onManage: () => openManage(state.plugins.find((r) => r.name === currentDetailPlugin.name), { type: "detail", sourceId: activeSourceId, plugin: currentDetailPlugin }),
9714
10125
  onTogglePlugin: async (enabled) => {
9715
10126
  const res = await api("/plugins/" + encodeURIComponent(currentDetailPlugin.name) + "/toggle", {
9716
10127
  method: "POST",
9717
10128
  body: JSON.stringify({ enabled }),
9718
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
+ }
9719
10136
  if (res?.ok !== false && res?.plugin && patchPluginInState) {
9720
10137
  patchPluginInState(res.plugin);
9721
10138
  void refreshState();
@@ -9748,7 +10165,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9748
10165
  h("div", { className: "cpm-installed-group-header" },
9749
10166
  h("div", { className: "cpm-installed-group-title-wrap" },
9750
10167
  h("span", { className: "cpm-installed-group-title" }, grp.source.name),
9751
- h("span", { className: "cpm-badge" }, grp.plugins.length),
10168
+ renderCountBadge(grp.plugins.length),
9752
10169
  ),
9753
10170
  idx > 0 && h("div", { className: "cpm-installed-group-line" }),
9754
10171
  ),
@@ -9839,36 +10256,33 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9839
10256
  ],
9840
10257
  ),
9841
10258
 
9842
- isBrowse && mcpsOpen && h("div", {
9843
- ref: gridRef,
9844
- className: "cpm-grid-container" + gridMaskClass,
9845
- onWheelCapture: globalHover.suspend,
9846
- onScroll: () => { globalHover.suspend(); updateGridMask(); },
9847
- },
9848
- !hasMcps && h("div", { className: "cpm-empty", style: { textAlign: "center", padding: "40px 16px" } }, "还没有添加 MCP,点右上角「添加」→「添加 MCP」"),
9849
- h(McpOverview, {
9850
- serverRows: mcps.map((m, i) => renderMcpServerRow({
9851
- owner: "user-mcp",
9852
- row: m,
9853
- name: m.name,
9854
- transport: m.transport,
9855
- connected: m.enabled === true,
9856
- canEdit: true,
9857
- first: i === 0,
9858
- })),
9859
- pluginRows: pluginMcpRows.map((r, i) => renderMcpServerRow({
9860
- owner: r.owner,
9861
- record: r.record,
9862
- plugin: r.record,
9863
- name: r.name,
9864
- transport: r.type,
9865
- connected: r.connected,
9866
- conn: r.conn,
9867
- canEdit: false,
9868
- first: i === 0,
9869
- })),
9870
- }),
9871
- ),
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
+ }),
9872
10286
 
9873
10287
  globalHoveredTool && isBrowse && mcpsOpen && h(McpToolPopover, {
9874
10288
  hovered: globalHoveredTool,
@@ -9909,7 +10323,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9909
10323
  setRows((prev) => ({ ...prev, [newSourceId]: market.plugins }));
9910
10324
  setState((prev) => prev.sources.some((source) => source.id === newSourceId)
9911
10325
  ? prev : { ...prev, sources: [...prev.sources, market.source] });
9912
- if (newSourceId !== activeSourceId) setActiveSourceId(newSourceId);
10326
+ if (isMcpTab || newSourceId !== activeSourceId) setActiveSourceId(newSourceId);
9913
10327
  void refreshState({ quiet: true });
9914
10328
  return;
9915
10329
  }
@@ -9933,7 +10347,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9933
10347
  }
9934
10348
  } catch {}
9935
10349
  };
9936
- if (newSourceId !== activeSourceId) setActiveSourceId(newSourceId);
10350
+ if (isMcpTab || newSourceId !== activeSourceId) setActiveSourceId(newSourceId);
9937
10351
  // A tab that is already active has no effect to re-run for the
9938
10352
  // same id, and the Skills tab has no browse effect at all, so
9939
10353
  // both need the load here. A newly opened market tab refetches
@@ -9951,7 +10365,8 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9951
10365
  onSaved: async () => {
9952
10366
  await refreshMcps();
9953
10367
  await refreshState();
9954
- setMcpsOpen(true);
10368
+ if (browseUnmountedRef.current) return;
10369
+ if (SESSION_STORE.view === view) setView(SESSION_STORE.mcpView);
9955
10370
  setMcpDialog(false);
9956
10371
  setEditMcp(null);
9957
10372
  setEditMcpOwner(null);
@@ -9976,38 +10391,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9976
10391
  try {
9977
10392
  await api("/sources/" + encodeURIComponent(toRemove.id), { method: "DELETE" });
9978
10393
  showToast("插件源已删除", `已移除分类「${toRemove.name}」`, { restart: false });
9979
- invalidateSourceDetailCache(toRemove.id);
9980
- const currentSources = Array.isArray(SESSION_STORE.state?.sources)
9981
- ? SESSION_STORE.state.sources
9982
- : (Array.isArray(state?.sources) ? state.sources : []);
9983
- const remainingSources = currentSources.filter((s) => s && s.id !== toRemove.id);
9984
- const fallbackSourceId = remainingSources.some((s) => s.id === "anthropic")
9985
- ? "anthropic"
9986
- : (remainingSources.find((s) => s.id !== "local" || hasLocalPlugins) || remainingSources[0])?.id;
9987
- if (SESSION_STORE.activeSourceId === toRemove.id || activeSourceId === toRemove.id) {
9988
- if (fallbackSourceId) {
9989
- setActiveSourceId(fallbackSourceId, SESSION_STORE.sourceFilters?.[fallbackSourceId] || "all");
9990
- } else {
9991
- SESSION_STORE.activeSourceId = "";
9992
- setActiveSourceIdRaw("");
9993
- SESSION_STORE.filter = "all";
9994
- setFilterRaw("all");
9995
- const emptyView = { type: "browse" };
9996
- SESSION_STORE.view = emptyView;
9997
- setViewRaw(emptyView);
9998
- }
9999
- }
10000
- for (const mapKey of ["sourceViews", "scrollTops", "sourceFilters", "browseSortSnapshots"]) {
10001
- if (SESSION_STORE[mapKey]) delete SESSION_STORE[mapKey][toRemove.id];
10002
- }
10003
- if (SESSION_STORE.checkedCatalogs) SESSION_STORE.checkedCatalogs.delete(toRemove.id);
10004
- addedGitSourceIds.current.delete(toRemove.id);
10005
- savedTabScrolls.delete(toRemove.id);
10006
- if (tabRefs?.current) delete tabRefs.current[toRemove.id];
10007
- setRows((prev) => omitSourceKey(prev, toRemove.id));
10008
- syncCachedStore("rows", STORAGE_KEY_ROWS, rows, (prev) => omitSourceKey(prev, toRemove.id));
10009
- setState((prev) => stripDeletedSource(prev, toRemove.id));
10010
- syncCachedStore("state", STORAGE_KEY_STATE, state, (prev) => stripDeletedSource(prev, toRemove.id));
10394
+ cleanupRemovedSource(toRemove.id);
10011
10395
  try { await refreshState(); } catch {}
10012
10396
  } catch (e) {
10013
10397
  showToast("删除失败", cleanError(e), { restart: false });
@@ -10189,6 +10573,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10189
10573
  const [pluginCount, setPluginCount] = useState(0);
10190
10574
  const [busy, setBusyState] = useState(false);
10191
10575
  const [uploadProgress, setUploadProgress] = useState(null);
10576
+ const [importProgress, setImportProgress] = useState(null);
10192
10577
  const [isDragging, setIsDragging] = useState(false);
10193
10578
  const [localPreview, setLocalPreview] = useState(null);
10194
10579
  const [localDuplicate, setLocalDuplicate] = useState(null);
@@ -10433,11 +10818,22 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10433
10818
  const clean = String(rawPath || "").trim();
10434
10819
  if (!clean) return;
10435
10820
  const payload = { path: clean };
10821
+ const baseName = clean.split(/[\\/]/).pop() || clean;
10436
10822
  setBusy(true);
10823
+ setUploadProgress(null);
10437
10824
  try {
10438
10825
  const res = await api("/plugins/local/inspect", {
10439
10826
  method: "POST",
10440
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
+ }));
10441
10837
  });
10442
10838
  if (unmountedRef.current) return;
10443
10839
  if (!res.ok) {
@@ -10449,7 +10845,10 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10449
10845
  if (unmountedRef.current) return;
10450
10846
  showToast("不符合规范,不可以上传", cleanError(e), { restart: false });
10451
10847
  } finally {
10452
- if (!unmountedRef.current) setBusy(false);
10848
+ if (!unmountedRef.current) {
10849
+ setBusy(false);
10850
+ setUploadProgress(null);
10851
+ }
10453
10852
  }
10454
10853
  };
10455
10854
 
@@ -10522,37 +10921,114 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10522
10921
  activeXhrRef.current = xhr;
10523
10922
  xhr.open("POST", "/universal-plugin-hub/api/plugins/local/inspect?filename=" + encodeURIComponent(file.name || "plugin.zip"), true);
10524
10923
  xhr.setRequestHeader("Content-Type", "application/octet-stream");
10924
+ xhr.setRequestHeader("Accept", "application/x-ndjson");
10525
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
+
10526
10978
  if (xhr.upload) {
10527
10979
  xhr.upload.onprogress = (ev) => {
10528
10980
  if (unmountedRef.current) return;
10529
10981
  const total = ev.lengthComputable && ev.total > 0 ? ev.total : (file.size || 0);
10530
10982
  const loaded = total > 0 ? Math.min(ev.loaded, total) : ev.loaded;
10531
- const percent = total > 0 ? Math.min(100, Math.round((loaded / total) * 100)) : 0;
10532
- setUploadProgress({
10533
- 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",
10534
10988
  loaded,
10535
10989
  total,
10536
- percent,
10990
+ percent: doneUpload ? Math.max(prev?.percent || 0, 30) : Math.max(prev?.percent || 0, percent),
10991
+ detail: doneUpload ? (prev?.detail || "上传完成,正在解压档案…") : undefined,
10537
10992
  filename: file.name,
10538
- });
10993
+ }));
10539
10994
  };
10540
10995
  xhr.upload.onload = () => {
10541
10996
  if (unmountedRef.current) return;
10542
10997
  setUploadProgress((prev) => ({
10543
- stage: "parsing",
10998
+ ...(prev || {}),
10999
+ stage: prev?.stage && prev.stage !== "uploading" ? prev.stage : "extracting",
10544
11000
  loaded: file.size || prev?.total || 0,
10545
11001
  total: file.size || prev?.total || 0,
10546
- percent: 100,
11002
+ percent: Math.max(prev?.percent || 0, 30),
11003
+ detail: prev?.detail || "上传完成,正在解压档案…",
10547
11004
  filename: file.name,
10548
11005
  }));
10549
11006
  };
10550
11007
  }
11008
+ xhr.onprogress = () => {
11009
+ if (unmountedRef.current) return;
11010
+ consumeStreamChunks(false);
11011
+ };
10551
11012
  const clearXhr = () => {
10552
11013
  if (activeXhrRef.current === xhr) activeXhrRef.current = null;
10553
11014
  };
10554
11015
  xhr.onload = () => {
10555
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
+ }
10556
11032
  let body = null;
10557
11033
  try { body = JSON.parse(xhr.responseText || "null"); } catch {}
10558
11034
  if (xhr.status >= 200 && xhr.status < 300) {
@@ -10599,16 +11075,27 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10599
11075
  const data = await fileToBase64(file);
10600
11076
  if (unmountedRef.current) return;
10601
11077
  setUploadProgress((prev) => ({
10602
- stage: "parsing",
11078
+ stage: "extracting",
10603
11079
  loaded: file.size || prev?.total || 0,
10604
11080
  total: file.size || prev?.total || 0,
10605
- percent: 100,
11081
+ percent: 30,
11082
+ detail: "上传完成,正在解压档案…",
10606
11083
  filename: file.name,
10607
11084
  }));
10608
11085
  payload = { data, filename: file.name };
10609
11086
  res = await api("/plugins/local/inspect", {
10610
11087
  method: "POST",
10611
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
+ }));
10612
11099
  });
10613
11100
  if (res?.uploadId) payload = { uploadId: res.uploadId, filename: file.name };
10614
11101
  }
@@ -10646,6 +11133,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10646
11133
  async function handleImportLocal(payload, overwrite, sourceName, kindOverride, overwriteNames, targetOverride) {
10647
11134
  if (busyRef.current) return;
10648
11135
  setBusy(true);
11136
+ setImportProgress(null);
10649
11137
  try {
10650
11138
  // A pure skill package must not go through the plugin pipeline:
10651
11139
  // it belongs in the Skills tab as a directly managed skill.
@@ -10662,6 +11150,13 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10662
11150
  body: JSON.stringify(isSkillPackage
10663
11151
  ? { ...payload, overwrite, ...(overwriteNames?.length ? { overwriteNames } : {}) }
10664
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
+ }));
10665
11160
  });
10666
11161
  if (payload?.uploadId && payload.uploadId === stagedUploadIdRef.current) {
10667
11162
  stagedUploadIdRef.current = null;
@@ -10715,7 +11210,10 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10715
11210
  }
10716
11211
  showToast("添加本地插件失败", msg, { restart: false });
10717
11212
  } finally {
10718
- if (!unmountedRef.current) setBusy(false);
11213
+ if (!unmountedRef.current) {
11214
+ setBusy(false);
11215
+ setImportProgress(null);
11216
+ }
10719
11217
  }
10720
11218
  }
10721
11219
 
@@ -10765,7 +11263,10 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10765
11263
  if (unmountedRef.current) return;
10766
11264
  showToast("校验失败", cleanError(e), { restart: false });
10767
11265
  } finally {
10768
- if (!unmountedRef.current) setBusy(false);
11266
+ if (!unmountedRef.current) {
11267
+ setBusy(false);
11268
+ setImportProgress(null);
11269
+ }
10769
11270
  }
10770
11271
  };
10771
11272
 
@@ -10790,15 +11291,28 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10790
11291
  if (unmountedRef.current) return;
10791
11292
  showToast("添加源失败", cleanError(e), { restart: false });
10792
11293
  } finally {
10793
- if (!unmountedRef.current) setBusy(false);
11294
+ if (!unmountedRef.current) {
11295
+ setBusy(false);
11296
+ setImportProgress(null);
11297
+ }
10794
11298
  }
10795
11299
  };
10796
11300
 
10797
11301
  const urlBusyLabel = isLocalPath(url) ? "正在解析…" : "正在安装…";
10798
- const inlineBusyProgress = () => busy && h("div", { className: "cpm-upload-inline-progress", key: "imp-prog" },
10799
- h("progress", { className: "cpm-upload-progress", "aria-label": "正在导入插件" }),
10800
- h("div", { className: "cpm-upload-status", role: "status", "aria-live": "polite", style: { marginTop: 0 } }, "正在导入文件,请勿关闭弹窗…"),
10801
- );
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
+ };
10802
11316
 
10803
11317
  return h("div", { className: "cpm-dialog" },
10804
11318
  h("div", {
@@ -10881,26 +11395,30 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10881
11395
  busy ? h("span", { className: "cpm-spin-ring", style: { width: 18, height: 18, borderWidth: 2 } }) : h(UploadDropIcon)
10882
11396
  ),
10883
11397
  h("span", { className: "cpm-dropzone-title" }, busy
10884
- ? (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
+ : "正在解压并解析文件…")
10885
11405
  : "拖入插件 / Skills,或点击上传"),
10886
11406
  busy
10887
11407
  ? h("span", { className: "cpm-upload-progress-wrap" },
10888
11408
  h("span", { className: "cpm-upload-progress-meta" },
10889
11409
  h("span", null, uploadProgress?.stage === "uploading" && uploadProgress.total > 0
10890
11410
  ? `${formatUploadBytes(uploadProgress.loaded)} / ${formatUploadBytes(uploadProgress.total)}`
10891
- : (uploadProgress?.stage === "parsing"
10892
- ? (uploadProgress.filename || "等待服务端完成解析")
10893
- : "正在校验本地路径与清单")),
10894
- 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"))
10895
11413
  ? `${uploadProgress.percent}%`
10896
11414
  : "请勿关闭弹窗"),
10897
11415
  ),
10898
- uploadProgress?.stage === "uploading" && uploadProgress.total > 0
11416
+ (typeof uploadProgress?.percent === "number" && (uploadProgress.total > 0 || uploadProgress.stage !== "uploading"))
10899
11417
  ? h("progress", {
10900
11418
  className: "cpm-upload-progress",
10901
11419
  max: 100,
10902
11420
  value: uploadProgress.percent,
10903
- "aria-label": "文件上传进度",
11421
+ "aria-label": uploadProgress?.stage === "uploading" ? "文件上传进度" : "文件解压与解析进度",
10904
11422
  })
10905
11423
  : h("progress", {
10906
11424
  className: "cpm-upload-progress",
@@ -10927,8 +11445,8 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10927
11445
  busy && h("div", { className: "cpm-upload-status", role: "status", "aria-live": "polite", key: "status" },
10928
11446
  uploadProgress?.stage === "uploading"
10929
11447
  ? `正在上传${uploadProgress?.filename ? `「${uploadProgress.filename}」` : "文件"},上传与解析完成前无法关闭…`
10930
- : uploadProgress?.stage === "parsing"
10931
- ? "文件已上传,正在等待服务端解压与识别,请勿关闭弹窗…"
11448
+ : (uploadProgress?.stage === "extracting" || uploadProgress?.stage === "analyzing" || uploadProgress?.stage === "finalizing" || uploadProgress?.stage === "parsing")
11449
+ ? (uploadProgress.detail ? `${uploadProgress.detail},请勿关闭弹窗…` : "正在解压并识别插件内容,请勿关闭弹窗…")
10932
11450
  : "正在读取并解析本地内容,完成前无法关闭…"
10933
11451
  ),
10934
11452
  h("div", { className: "cpm-dialog-actions", key: "a" },
@@ -11157,20 +11675,18 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
11157
11675
  ],
11158
11676
  phase === "local-duplicate" && localDuplicate && [
11159
11677
  h("div", { className: "cpm-source-header", key: "header" },
11160
- 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"),
11161
11679
  h("div", { className: "cpm-source-meta-row" },
11162
11680
  h("span", { className: "cpm-source-repo-text" }, localDuplicate.plugin.name),
11163
11681
  localDuplicate.localTabName && h("span", { className: "cpm-source-meta-sep" }, "·"),
11164
11682
  localDuplicate.localTabName && h("span", { className: "cpm-source-count-text" }, `目标标签:${localDuplicate.localTabName}`),
11165
- formatVersionBadge(localDuplicate.existingVersion) && h("span", { className: "cpm-source-meta-sep" }, "·"),
11166
- formatVersionBadge(localDuplicate.existingVersion) && h("span", { className: "cpm-source-count-text" }, `已安装版本: ${formatVersionBadge(localDuplicate.existingVersion)}`),
11167
11683
  ),
11168
11684
  ),
11169
- h("div", { className: "cpm-local-dup-card", key: "info" },
11685
+ h("div", { className: "cpm-dup-body", key: "info" },
11170
11686
  localDuplicate.conflicts?.length > 1
11171
11687
  ? [
11172
- h("div", { key: "desc", style: { fontSize: 12.5, fontWeight: 600, color: "var(--cpm-text)", marginBottom: 4 } },
11173
- `「${localDuplicate.localTabName || "本地插件"}」中已存在 ${localDuplicate.conflicts.length} 个同名插件,覆盖更新将完整替换旧文件与已安装版本:`),
11688
+ h("div", { key: "desc", className: "cpm-dup-multi-lead" },
11689
+ `已有 ${localDuplicate.conflicts.length} 个同名插件将被新版本覆盖`),
11174
11690
  h("ul", { className: "cpm-local-dup-list", key: "clist" }, localDuplicate.conflicts.map((c) => {
11175
11691
  const oldVer = formatVersionBadge(c.existingVersion) || "未声明";
11176
11692
  const newVer = formatVersionBadge(c.newVersion) || "未声明";
@@ -11178,45 +11694,43 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
11178
11694
  h("span", { className: "cpm-local-dup-item-name" }, c.displayName || c.name),
11179
11695
  h("span", { className: "cpm-local-dup-item-vers" },
11180
11696
  h("span", null, oldVer),
11181
- h("span", null, "→"),
11697
+ h("span", { "aria-hidden": "true" }, "→"),
11182
11698
  h("span", { className: "cpm-local-dup-item-new" }, newVer),
11183
11699
  ),
11184
11700
  );
11185
11701
  })),
11186
11702
  ]
11187
11703
  : [
11188
- h("div", { key: "top", style: { display: "flex", alignItems: "center", gap: 12, marginBottom: 8 } },
11704
+ h("div", { key: "top", className: "cpm-dup-identity" },
11189
11705
  h(PluginIcon, { plugin: localDuplicate.plugin, isDark }),
11190
- h("div", null,
11191
- h("div", { style: { fontSize: 14, fontWeight: 700, color: "var(--cpm-text)" } }, localDuplicate.plugin.displayName || localDuplicate.plugin.name),
11192
- h("div", { style: { fontSize: 11.5, color: "var(--cpm-muted)" } }, `标识:${localDuplicate.plugin.name}`),
11193
- ),
11706
+ h("div", { className: "cpm-dup-name" }, localDuplicate.plugin.displayName || localDuplicate.plugin.name),
11194
11707
  ),
11195
- h("div", { className: "cpm-local-dup-grid", key: "grid" },
11196
- h("div", null,
11197
- h("div", { style: { color: "var(--cpm-muted)", fontSize: 11, marginBottom: 2 } }, "当前已安装版本"),
11198
- h("div", { style: { fontWeight: 600, color: "var(--cpm-text)", fontVariantNumeric: "tabular-nums" } }, formatVersionBadge(localDuplicate.existingVersion) || "未声明"),
11199
- 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() : "已存在"),
11713
+ ),
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
+ ),
11200
11719
  ),
11201
- h("div", null,
11202
- h("div", { style: { color: "var(--cpm-muted)", fontSize: 11, marginBottom: 2 } }, "新导入版本"),
11203
- h("div", { style: { fontWeight: 600, color: "#10b981", fontVariantNumeric: "tabular-nums" } }, formatVersionBadge(localDuplicate.plugin.version) || "未声明"),
11204
- h("div", { style: { fontSize: 10.5, color: "var(--cpm-muted)", marginTop: 2 } }, "准备覆盖"),
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" }, "准备覆盖"),
11205
11724
  ),
11206
11725
  ),
11207
11726
  ],
11208
- h("div", { style: { fontSize: 11.5, color: "var(--cpm-muted)", lineHeight: 1.4 } },
11209
- localDuplicate.target === "local"
11210
- ? `「${localDuplicate.localTabName || "本地插件"}」中同名插件及其已安装副本将被新版完全覆盖更新,其余插件保持不变。`
11211
- : "覆盖更新将替换本次导入中所有同名插件 / Skills 的文件与已安装副本。",
11212
- ),
11213
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))))),
11214
11728
  ),
11215
11729
  inlineBusyProgress(),
11216
11730
  h("div", { className: "cpm-dialog-actions", key: "a" },
11217
- 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"); } }, "取消"),
11218
11732
  h("button", {
11219
- className: "cpm-btn cpm-btn-warning",
11733
+ className: "cpm-btn cpm-btn-primary",
11220
11734
  disabled: busy,
11221
11735
  onClick: () => handleImportLocal(localDuplicate.payload, true, undefined, localDuplicate.kind, undefined, localDuplicate.target),
11222
11736
  }, busy ? "正在覆盖…" : "覆盖更新"),
@@ -11811,7 +12325,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
11811
12325
  return h("div", { ref: sectionRef, className: "cpm-section" },
11812
12326
  h("div", { className: "cpm-section-title" },
11813
12327
  title,
11814
- h("span", { className: "cpm-badge" }, count !== undefined ? count : total),
12328
+ renderCountBadge(count !== undefined ? count : total),
11815
12329
  isLong && expanded && h("button", {
11816
12330
  type: "button",
11817
12331
  className: "cpm-section-collapse-btn",
@@ -11845,14 +12359,20 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
11845
12359
  }
11846
12360
 
11847
12361
  // ────────────────────────────── Detail View ──────────────────────────────
11848
- function DetailView({ plugin, pluginRecord, isDark, installing = false, 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 }) {
11849
12363
  const [busy, setBusy] = useState(false);
11850
12364
  const [confirmRemove, setConfirmRemove] = useState(false);
12365
+ const [confirmDeleteLocal, setConfirmDeleteLocal] = useState(false);
11851
12366
  const [toggling, setToggling] = useState(false);
11852
12367
  const [optimisticEnabled, setOptimisticEnabled] = useState(null);
11853
12368
  const { detailRef, maskClass: detailMaskClass, updateMask: updateDetailMask } = useDetailScrollMask(plugin?.name, containerRef, plugin, scrollState);
11854
- useEffect(() => { setOptimisticEnabled(null); }, [plugin?.name]);
11855
- 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
+ });
11856
12376
 
11857
12377
  if (!plugin) return null;
11858
12378
  const dark = typeof isDark === "boolean" ? isDark : (typeof isDarkMode === "function" ? isDarkMode() : false);
@@ -11956,12 +12476,21 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
11956
12476
  if (navigator.clipboard) navigator.clipboard.writeText(plugin.homepage);
11957
12477
  },
11958
12478
  }, h(IconLink)),
11959
- !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"),
11960
12487
  h("button", {
12488
+ key: "i",
11961
12489
  className: "cpm-btn cpm-btn-primary",
11962
12490
  disabled: busy || installing,
11963
12491
  onClick: async () => { if (busy || installing) return; setBusy(true); try { await onInstall(); } finally { setBusy(false); } },
11964
12492
  }, (busy || installing) ? "安装中…" : "Install"),
12493
+ ],
11965
12494
  installed && [
11966
12495
  h("button", {
11967
12496
  key: "r",
@@ -12097,11 +12626,325 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
12097
12626
  }
12098
12627
  },
12099
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
+ }),
12100
12654
  )
12101
12655
  );
12102
12656
  }
12103
12657
 
12104
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
+
12105
12948
  const GLOBAL_MCP_TOOLS_CACHE = (() => {
12106
12949
  try {
12107
12950
  const raw = localStorage.getItem("cpm_mcp_tools_cache_v1");
@@ -12130,6 +12973,8 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
12130
12973
  if (changed) {
12131
12974
  try { localStorage.setItem("cpm_mcp_tools_cache_v1", JSON.stringify(GLOBAL_MCP_TOOLS_CACHE)); } catch {}
12132
12975
  }
12976
+ clearMcpRefreshCooldown(matcher);
12977
+ bumpMcpToolsSeq(matcher);
12133
12978
  }
12134
12979
 
12135
12980
  function useAutoMcpTools(servers, loadTools) {
@@ -12157,11 +13002,13 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
12157
13002
  h("button", { type: "button", className: "cpm-mcp-retry", onClick: event => { event.stopPropagation(); onRetry(); } }, "重新解析"));
12158
13003
  if (info.error) return retryNotice(`解析失败:${info.error}`);
12159
13004
  const tools = info.tools || [], disabled = info.disabledTools || [];
12160
- 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;
12161
13008
  const expand = h("button", { type: "button", className: "cpm-mcp-expand", "aria-expanded": !!expanded,
12162
13009
  onClick: event => { event.stopPropagation(); onExpand(); } },
12163
13010
  h("span", { className: "cpm-connector-collapse-btn" + (expanded ? " is-expanded" : ""), "aria-hidden": "true" }, h(IconArrow, { size: 10 })),
12164
- h("span", null, `${active} tools enabled${disabled.length ? ` (${disabled.length} disabled)` : ""}`));
13011
+ h("span", null, `${active} tools enabled${disabledCount ? ` (${disabledCount} disabled)` : ""}`));
12165
13012
  return info.warning
12166
13013
  ? h("span", { className: "cpm-mcp-discovery" }, expand, retryNotice(`刷新失败,显示上次解析结果:${info.warning}`))
12167
13014
  : expand;
@@ -12367,39 +13214,26 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
12367
13214
  const [hoveredTool, closeToolHover, toolHover] = useHoverPreview();
12368
13215
  useEffect(() => { closeToolHover(); }, [record?.name, closeToolHover]);
12369
13216
 
12370
- const loadConnectorTools = useCallback(async (connectorName, forceFresh = false) => {
12371
- const key = `${record.name}::${connectorName}`;
12372
- const cached = GLOBAL_MCP_TOOLS_CACHE[key];
12373
- setConnectorToolsData((prev) => ({
12374
- ...prev,
12375
- [connectorName]: { ...(cached || prev[connectorName]), loading: forceFresh || !Array.isArray(cached?.tools), error: null, warning: null },
12376
- }));
12377
-
12378
- try {
12379
- const res = await api(`/plugins/${encodeURIComponent(record.name)}/connectors/${encodeURIComponent(connectorName)}/tools${forceFresh ? "?fresh=1" : ""}`);
12380
- const tools = Array.isArray(res.tools) ? res.tools : [];
12381
- const disabledTools = Array.isArray(res.disabledTools) ? res.disabledTools : [];
12382
-
12383
- if (res.ok) {
12384
- saveMcpToolsCache(key, { tools, disabledTools });
12385
- }
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
+ }, []);
12386
13226
 
12387
- setConnectorToolsData((prev) => ({
12388
- ...prev,
12389
- [connectorName]: {
12390
- loading: false,
12391
- error: res.ok ? null : (res.message || "获取能力列表失败"),
12392
- warning: res.ok && res.stale ? (res.message || "获取能力列表失败") : null,
12393
- tools: res.ok ? tools : (prev[connectorName]?.tools || tools),
12394
- disabledTools,
12395
- },
12396
- }));
12397
- } catch (e) {
12398
- setConnectorToolsData((prev) => ({
12399
- ...prev, [connectorName]: { ...(prev[connectorName] || cached), loading: false, error: e.message },
12400
- }));
12401
- }
12402
- }, [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]);
12403
13237
 
12404
13238
  const updateAuthDialog = (patch) => setAuthDialog((prev) => prev
12405
13239
  ? { ...prev, ...patch, status: "untested", statusMessage: "", lastResult: null }
@@ -12580,9 +13414,43 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
12580
13414
  }
12581
13415
  };
12582
13416
 
12583
- 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]);
12584
13452
  useAutoMcpTools((record.connectors || []).map(connector => ({
12585
- 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),
12586
13454
  revision: JSON.stringify([record.installedAt, connector]),
12587
13455
  })), autoLoadConnectorTools);
12588
13456
 
@@ -12813,6 +13681,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
12813
13681
  showToast("操作失败", result.error || "插件状态已变更,请刷新后重试", { restart: false });
12814
13682
  return;
12815
13683
  }
13684
+ syncPluginToggleCooldown(record, next);
12816
13685
  await applyToggleState(result);
12817
13686
  void showApplicationToast(showToast, result, next ? "已启用插件" : "已禁用插件", "插件状态已实时更新并生效。");
12818
13687
  } catch (e) {
@@ -12840,6 +13709,23 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
12840
13709
  showToast("操作失败", result.error || "请检查 MCP 配置后重试", { restart: false });
12841
13710
  return;
12842
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
+ }
12843
13729
  await applyToggleState(result);
12844
13730
  void showApplicationToast(showToast, result, nextConnected ? "已连接 Connector" : "已断开 Connector", `MCP 服务 ${connectorName} 配置已实时更新。`);
12845
13731
  } catch (e) {