universal-plugin-hub 1.0.5 → 1.0.12

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
@@ -6,6 +6,173 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
6
6
 
7
7
  const React = require("react");
8
8
  const { createElement: h, useState, useEffect, useCallback, useMemo, useRef, useLayoutEffect } = React;
9
+ // Manifests spell a remote transport three ways (`http`, `sse`,
10
+ // `streamable-http`). The editor only has two modes; anything unrecognised
11
+ // used to fall through to the stdio form and show an empty local command
12
+ // for a connector that is actually a remote URL.
13
+ function isRemoteTransport(transport) {
14
+ return transport === "http" || transport === "sse" || transport === "streamable-http" || transport === "streamableHttp";
15
+ }
16
+
17
+ function cleanMcpErrorText(err) {
18
+ if (!err) return "操作失败";
19
+ const msg = String(err.message || err).replace(/^Error:\s*/i, "").trim();
20
+ return msg.length > 50 ? msg.slice(0, 48) + "…" : msg;
21
+ }
22
+
23
+ // Inline progress card shown while a browser sign-in is in flight. Rendered
24
+ // as part of the dialog body (not a labelled grid row) so it reads as one
25
+ // object with its own title, message and actions, using the same tokens as
26
+ // the rest of the dialog.
27
+ function OauthPendingCard({ pending, onCancel }) {
28
+ return h("div", { className: "cpm-oauth-pending", role: "status", "aria-live": "polite" },
29
+ h("span", { className: "cpm-spin-ring", style: { width: 15, height: 15, borderWidth: 2, flexShrink: 0, marginTop: 1 } }),
30
+ h("div", { className: "cpm-oauth-pending-body" },
31
+ h("div", { className: "cpm-oauth-pending-title" }, "等待浏览器授权"),
32
+ h("div", { className: "cpm-oauth-pending-text" }, (pending && pending.message) || "正在准备 OAuth 授权…"),
33
+ h("div", { className: "cpm-oauth-pending-actions" },
34
+ pending && pending.authorizationUrl && h("a", {
35
+ className: "cpm-oauth-link",
36
+ href: pending.authorizationUrl,
37
+ target: "_blank",
38
+ rel: "noopener noreferrer",
39
+ }, h(IconLink, { size: 12 }), "重新打开授权页"),
40
+ h("button", { type: "button", className: "cpm-btn-ghost cpm-oauth-cancel", onClick: onCancel }, "取消"),
41
+ ),
42
+ ),
43
+ );
44
+ }
45
+
46
+ function OauthFields({ form, onChange, idPrefix }) {
47
+ if (form.oauth !== "custom") return null;
48
+ const update = (patch) => onChange({ ...form, ...patch, status: "untested" });
49
+ const input = (label, key, placeholder, type = "text") => h("div", { className: "cpm-mcp-row" },
50
+ h("label", { className: "cpm-mcp-label", htmlFor: `${idPrefix}-${key}` }, label),
51
+ h("div", { className: "cpm-mcp-control" }, h("input", {
52
+ id: `${idPrefix}-${key}`, className: "cpm-mcp-input", type,
53
+ value: form[key] || "", placeholder, autoComplete: "off",
54
+ onChange: (event) => update({ [key]: event.target.value }),
55
+ })),
56
+ );
57
+ return h(React.Fragment, null,
58
+ input("Client ID", "oauthClientId", "OAuth client ID"),
59
+ input("Client Secret", "oauthClientSecret", form.oauthHasClientSecret ? "已保存,留空保持不变" : "Public client 可留空", "password"),
60
+ input("Callback port", "oauthCallbackPort", "留空则随机;固定端口需与注册 URI 一致", "number"),
61
+ input("Scope", "oauthScope", "可选,默认由服务发现"),
62
+ );
63
+ }
64
+
65
+ function useOauthVerification({ form, verifyPath, userMcp, onFinished, onCancel, onError }) {
66
+ const [pending, setPending] = useState(null);
67
+ const pendingRef = useRef(null);
68
+ const startingRef = useRef(false);
69
+ const startControllerRef = useRef(null);
70
+ const operationRef = useRef(0);
71
+ const latestForm = useRef(form);
72
+ latestForm.current = form;
73
+ const callbacks = useRef({ onFinished, onCancel, onError });
74
+ callbacks.current = { onFinished, onCancel, onError };
75
+ const cancelPending = useCallback(async (notify = true) => {
76
+ operationRef.current += 1;
77
+ startingRef.current = false;
78
+ const controller = startControllerRef.current;
79
+ startControllerRef.current = null;
80
+ const session = pendingRef.current;
81
+ pendingRef.current = null;
82
+ setPending(null);
83
+ const path = userMcp ? "/mcps/oauth-status" : verifyPath.replace(/\/verify$/, "/oauth-status");
84
+ try {
85
+ const response = await window.fetch("/universal-plugin-hub/api" + path, {
86
+ method: "POST", headers: { "Content-Type": "application/json" },
87
+ body: JSON.stringify({ sessionId: session?.sessionId || "" }), keepalive: true,
88
+ });
89
+ if (!session && response.ok && (await response.json()).found === false) controller?.abort();
90
+ } catch { controller?.abort(); }
91
+ if (notify) callbacks.current.onCancel?.();
92
+ }, [userMcp, verifyPath]);
93
+ const cancel = useCallback(() => cancelPending(true), [cancelPending]);
94
+ const formFingerprint = JSON.stringify(form, (key, value) => ["testing", "saving", "status", "statusMessage", "lastResult", "oauthSessionId", "diagHover"].includes(key) ? undefined : value);
95
+ useEffect(() => {
96
+ if (pendingRef.current || startingRef.current) void cancelPending(false);
97
+ }, [formFingerprint, cancelPending]);
98
+ useEffect(() => () => { void cancelPending(false); }, [cancelPending]);
99
+ useEffect(() => {
100
+ if (!pending) return;
101
+ let stopped = false;
102
+ let timer;
103
+ const poll = async () => {
104
+ let final = null;
105
+ try {
106
+ const path = userMcp ? "/mcps/oauth-status" : pending.statusPath;
107
+ const response = await window.fetch(`/universal-plugin-hub/api${path}?sessionId=${encodeURIComponent(pending.sessionId)}`);
108
+ const result = await response.json();
109
+ if (!response.ok) throw new Error(result.error || `HTTP ${response.status}`);
110
+ if (stopped || pendingRef.current?.sessionId !== pending.sessionId) return;
111
+ if (result.pending) {
112
+ setPending((previous) => previous?.sessionId === pending.sessionId ? { ...previous, status: result.status, message: result.message, authorizationUrl: result.authorizationUrl } : previous);
113
+ timer = window.setTimeout(poll, 350);
114
+ return;
115
+ }
116
+ final = result;
117
+ } catch (error) {
118
+ if (stopped || pendingRef.current?.sessionId !== pending.sessionId) return;
119
+ pendingRef.current = null;
120
+ setPending(null);
121
+ callbacks.current.onError?.(error);
122
+ return;
123
+ }
124
+ pendingRef.current = null;
125
+ setPending(null);
126
+ // Outside the try: the caller's onFinished may itself reject (saving
127
+ // the verified configuration can fail), and that is a save problem,
128
+ // not a failed verification.
129
+ try {
130
+ await callbacks.current.onFinished?.(final);
131
+ } catch (error) {
132
+ callbacks.current.onError?.(error);
133
+ }
134
+ };
135
+ timer = window.setTimeout(poll, 100);
136
+ return () => { stopped = true; window.clearTimeout(timer); };
137
+ }, [pending?.sessionId, userMcp]);
138
+ const start = async (payload) => {
139
+ if (startingRef.current || pendingRef.current) return;
140
+ startingRef.current = true;
141
+ const operation = ++operationRef.current;
142
+ const controller = new AbortController();
143
+ startControllerRef.current = controller;
144
+ try {
145
+ const response = await window.fetch("/universal-plugin-hub/api" + verifyPath, {
146
+ method: "POST", headers: { "Content-Type": "application/json" },
147
+ body: JSON.stringify(payload || latestForm.current), signal: controller.signal,
148
+ });
149
+ const result = await response.json();
150
+ if (operation !== operationRef.current) {
151
+ if (result.sessionId) {
152
+ const path = userMcp ? "/mcps/oauth-status" : verifyPath.replace(/\/verify$/, "/oauth-status");
153
+ void window.fetch("/universal-plugin-hub/api" + path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ sessionId: result.sessionId }), keepalive: true }).catch(() => {});
154
+ }
155
+ return;
156
+ }
157
+ if (!response.ok) throw new Error(result.error || `HTTP ${response.status}`);
158
+ if (result.pending) {
159
+ const session = { ...result, statusPath: verifyPath.replace(/\/verify$/, "/oauth-status") };
160
+ pendingRef.current = session;
161
+ setPending(session);
162
+ return;
163
+ }
164
+ await callbacks.current.onFinished?.(result);
165
+ } catch (error) {
166
+ if (operation === operationRef.current && error.name !== "AbortError") callbacks.current.onError?.(error);
167
+ } finally {
168
+ if (operation === operationRef.current) {
169
+ startingRef.current = false;
170
+ startControllerRef.current = null;
171
+ }
172
+ }
173
+ };
174
+ return { pending, start, cancel };
175
+ }
9
176
  const useSafeLayoutEffect = typeof useLayoutEffect === "function" ? useLayoutEffect : useEffect;
10
177
 
11
178
  // ────────────────────────────── Styles ──────────────────────────────
@@ -1892,6 +2059,81 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
1892
2059
  border-color: var(--cpm-accent);
1893
2060
  }
1894
2061
 
2062
+ /* Inline browser sign-in progress, shown inside the connector dialog body. */
2063
+ .cpm-oauth-pending {
2064
+ display: flex;
2065
+ align-items: flex-start;
2066
+ gap: 11px;
2067
+ padding: 12px 14px;
2068
+ border-radius: 12px;
2069
+ background: rgba(0, 0, 0, 0.032);
2070
+ border: 1px solid rgba(0, 0, 0, 0.07);
2071
+ animation: cpm-oauth-card-in 0.18s cubic-bezier(0.16, 1, 0.3, 1);
2072
+ }
2073
+ .cpm-dark .cpm-oauth-pending {
2074
+ background: rgba(255, 255, 255, 0.05);
2075
+ border: 1px solid rgba(255, 255, 255, 0.09);
2076
+ }
2077
+ @keyframes cpm-oauth-card-in {
2078
+ from { opacity: 0; transform: translateY(-3px); }
2079
+ to { opacity: 1; transform: none; }
2080
+ }
2081
+ .cpm-oauth-pending-body {
2082
+ min-width: 0;
2083
+ flex: 1;
2084
+ display: flex;
2085
+ flex-direction: column;
2086
+ gap: 3px;
2087
+ }
2088
+ .cpm-oauth-pending-title {
2089
+ font-size: 13px;
2090
+ font-weight: 600;
2091
+ line-height: 1.35;
2092
+ color: var(--cpm-text);
2093
+ }
2094
+ .cpm-oauth-pending-text {
2095
+ font-size: 12.5px;
2096
+ line-height: 1.45;
2097
+ color: var(--cpm-muted);
2098
+ word-break: break-word;
2099
+ }
2100
+ .cpm-oauth-pending-actions {
2101
+ display: flex;
2102
+ align-items: center;
2103
+ gap: 10px;
2104
+ margin-top: 6px;
2105
+ }
2106
+ .cpm-oauth-link {
2107
+ display: inline-flex;
2108
+ align-items: center;
2109
+ gap: 5px;
2110
+ font-size: 12.5px;
2111
+ font-weight: 500;
2112
+ color: var(--cpm-accent);
2113
+ text-decoration: none;
2114
+ border-radius: 6px;
2115
+ padding: 3px 6px;
2116
+ margin-left: -6px;
2117
+ transition: background 0.15s ease;
2118
+ }
2119
+ .cpm-oauth-link:hover {
2120
+ background: var(--cpm-tab-hover);
2121
+ text-decoration: underline;
2122
+ }
2123
+ /* Two classes so it outranks the later cpm-btn-ghost rule for the sizing. */
2124
+ .cpm-oauth-pending .cpm-oauth-cancel {
2125
+ height: 26px;
2126
+ padding: 0 8px;
2127
+ font-size: 12.5px;
2128
+ color: var(--cpm-muted);
2129
+ }
2130
+ .cpm-dark .cpm-oauth-link {
2131
+ color: #60a5fa;
2132
+ }
2133
+ @media (prefers-reduced-motion: reduce) {
2134
+ .cpm-oauth-pending { animation: none; }
2135
+ }
2136
+
1895
2137
  /* Custom Dropdown Styles */
1896
2138
  .cpm-custom-select {
1897
2139
  position: relative;
@@ -8222,14 +8464,19 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8222
8464
  function AddMcpDialog({ onCancel, onSaved, showToast, initial, owner }) {
8223
8465
  const [form, setForm] = useState(() => initial ? {
8224
8466
  name: initial.name || "",
8225
- transport: initial.transport === "http" ? "http" : "stdio",
8467
+ transport: isRemoteTransport(initial.transport) ? "http" : "stdio",
8226
8468
  url: initial.url || "",
8227
8469
  oauth: initial.oauth || "none",
8470
+ oauthClientId: initial.oauthClientId || "",
8471
+ oauthClientSecret: "",
8472
+ oauthHasClientSecret: initial.oauthHasClientSecret === true,
8473
+ oauthCallbackPort: initial.oauthCallbackPort || "",
8474
+ oauthScope: initial.oauthScope || "",
8228
8475
  command: initial.command || "",
8229
8476
  args: Array.isArray(initial.args) ? JSON.stringify(initial.args) : (initial.args || ""),
8230
8477
  headersList: Object.entries(initial.headers || {}).map(([k, v], i) => ({ _id: `hi_${i}`, key: k, value: String(v), isSecret: true })),
8231
8478
  envList: Object.entries(initial.env || {}).map(([k, v], i) => ({ _id: `ei_${i}`, key: k, value: String(v), isSecret: true })),
8232
- } : { name: "", transport: "stdio", url: "", oauth: "none", command: "", args: "", headersList: [], envList: [] });
8479
+ } : { name: "", transport: "stdio", url: "", oauth: "none", oauthClientId: "", oauthClientSecret: "", oauthHasClientSecret: false, oauthCallbackPort: "", oauthScope: "", command: "", args: "", headersList: [], envList: [] });
8233
8480
  const [testing, setTesting] = useState(false);
8234
8481
  const [saving, setSaving] = useState(false);
8235
8482
  const upd = (patch) => setForm((prev) => ({ ...prev, ...patch }));
@@ -8275,65 +8522,79 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8275
8522
  command: form.transport === "stdio" ? (form.command.trim() || null) : null,
8276
8523
  headers,
8277
8524
  oauth: form.transport === "http" ? form.oauth : "none",
8525
+ oauthClientId: form.oauthClientId,
8526
+ oauthClientSecret: form.oauthClientSecret,
8527
+ oauthCallbackPort: form.oauthCallbackPort,
8528
+ oauthScope: form.oauthScope,
8278
8529
  args,
8279
8530
  env,
8280
8531
  };
8281
8532
  };
8282
8533
 
8283
- const cleanMcpError = (err) => {
8284
- if (!err) return "操作失败";
8285
- let msg = String(err.message || err).replace(/^Error:\s*/i, "").trim();
8286
- return msg.length > 50 ? msg.slice(0, 48) + "…" : msg;
8287
- };
8288
-
8534
+ const cleanMcpError = (err) => cleanMcpErrorText(err);
8535
+ // The payload that was actually sent for verification. A finished OAuth
8536
+ // handshake must save exactly that configuration, not whatever the form
8537
+ // holds by the time the browser comes back.
8538
+ const verifiedPayloadRef = useRef(null);
8539
+ const oauthFlow = useOauthVerification({
8540
+ form,
8541
+ verifyPath: owner ? `/plugins/${encodeURIComponent(owner)}/connectors/${encodeURIComponent(form.name.trim())}/verify` : "/mcps/verify",
8542
+ userMcp: !owner,
8543
+ onFinished: async (res) => {
8544
+ showToast(res.ok ? "验证成功" : "验证失败", res.message || (res.ok ? "MCP 服务连接正常" : "请检查配置后重试"), { restart: false });
8545
+ // A finished sign-in is the whole point of the OAuth mode, so
8546
+ // register the connector now. Otherwise the dialog reopens on
8547
+ // `None` and the user has to save a second time.
8548
+ if (res.ok) await save(verifiedPayloadRef.current);
8549
+ },
8550
+ onError: (err) => showToast("验证失败", cleanMcpError(err), { restart: false }),
8551
+ });
8289
8552
  const test = async () => {
8290
8553
  if (!form.name.trim()) {
8291
8554
  showToast("请输入名称", "为这个 MCP 服务起一个名字,如 github、notion", { restart: false });
8292
8555
  return;
8293
8556
  }
8557
+ const payload = buildPayload();
8558
+ verifiedPayloadRef.current = payload;
8294
8559
  setTesting(true);
8295
8560
  try {
8296
- const verifyUrl = owner
8297
- ? `/plugins/${encodeURIComponent(owner)}/connectors/${encodeURIComponent(form.name.trim())}/verify`
8298
- : "/mcps/verify";
8299
- const res = await api(verifyUrl, { method: "POST", body: JSON.stringify(buildPayload()) });
8300
- showToast(res.ok ? "验证成功" : "验证失败", res.message || (res.ok ? "MCP 服务连接正常" : "请检查配置后重试"), { restart: false });
8301
- } catch (err) {
8302
- showToast("验证失败", cleanMcpError(err), { restart: false });
8561
+ await oauthFlow.start(payload);
8303
8562
  } finally {
8304
8563
  setTesting(false);
8305
8564
  }
8306
8565
  };
8307
8566
 
8308
- const save = async () => {
8309
- if (!form.name.trim()) {
8567
+ const save = async (payload, quiet = false) => {
8568
+ const data = payload || buildPayload();
8569
+ if (!data.name) {
8310
8570
  showToast("请输入名称", "为这个 MCP 服务起一个名字,如 github、notion", { restart: false });
8311
8571
  return;
8312
8572
  }
8313
- if (form.transport === "http" && !form.url.trim()) {
8573
+ if (data.transport === "http" && !String(data.url || "").trim()) {
8314
8574
  showToast("请输入服务 URL", "HTTP 连接需要有效的 MCP 服务地址,如 https://mcp.notion.com/mcp", { restart: false });
8315
8575
  return;
8316
8576
  }
8317
- if (form.transport === "stdio" && !form.command.trim()) {
8577
+ if (data.transport === "stdio" && !data.command) {
8318
8578
  showToast("请输入启动命令", "stdio 连接需要本地启动命令,如 npx、node 或 uvx", { restart: false });
8319
8579
  return;
8320
8580
  }
8321
8581
  setSaving(true);
8322
8582
  try {
8323
8583
  const saveUrl = owner
8324
- ? `/plugins/${encodeURIComponent(owner)}/connectors/${encodeURIComponent(form.name.trim())}/auth`
8584
+ ? `/plugins/${encodeURIComponent(owner)}/connectors/${encodeURIComponent(data.name)}/auth`
8325
8585
  : (initial ? "/mcps/update" : "/mcps");
8326
- const res = await api(saveUrl, { method: "POST", body: JSON.stringify(buildPayload()) });
8586
+ const res = await api(saveUrl, { method: "POST", body: JSON.stringify(data) });
8327
8587
  if (res && res.ok === false) {
8328
8588
  showToast("保存失败", res.error || "配置校验未通过,请检查填写内容", { restart: false });
8329
8589
  setSaving(false);
8330
8590
  return;
8331
8591
  }
8332
- showToast(initial ? "MCP 已更新" : "MCP 已添加", `「${form.name.trim()}」已${initial ? "更新" : "注册为可用 MCP 服务"}`, { restart: false });
8592
+ showToast(initial ? "MCP 已更新" : "MCP 已添加", `「${data.name}」已${initial ? "更新" : "注册为可用 MCP 服务"}`, { restart: false });
8333
8593
  await onSaved();
8334
8594
  } catch (err) {
8335
8595
  showToast("保存失败", cleanMcpError(err), { restart: false });
8336
8596
  setSaving(false);
8597
+ throw err;
8337
8598
  }
8338
8599
  };
8339
8600
 
@@ -8448,6 +8709,8 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8448
8709
  }),
8449
8710
  ),
8450
8711
  ),
8712
+ h(OauthFields, { form, onChange: upd, idPrefix: "add-mcp" }),
8713
+ oauthFlow.pending && h(OauthPendingCard, { pending: oauthFlow.pending, onCancel: oauthFlow.cancel }),
8451
8714
  form.transport === "stdio" && h("div", { className: "cpm-mcp-row" },
8452
8715
  h("div", { className: "cpm-mcp-label" }, "Command"),
8453
8716
  h("div", { className: "cpm-mcp-control" },
@@ -8545,11 +8808,13 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
8545
8808
  className: "cpm-btn cpm-btn-secondary",
8546
8809
  disabled: testing || saving || (form.transport === "stdio" && !!argsError),
8547
8810
  onClick: test,
8548
- }, testing ? "测试中…" : "测试连接"),
8811
+ }, testing ? "测试中…" : (oauthFlow.pending ? "等待授权…" : (
8812
+ form.transport === "http" && form.oauth !== "none" ? "登录并连接" : "测试连接"
8813
+ ))),
8549
8814
  h("button", {
8550
8815
  className: "cpm-btn cpm-btn-primary",
8551
- disabled: testing || saving || (form.transport === "stdio" && !!argsError),
8552
- onClick: save,
8816
+ disabled: testing || saving || !!oauthFlow.pending || (form.transport === "stdio" && !!argsError),
8817
+ onClick: () => save(),
8553
8818
  }, saving ? "保存中…" : "保存并启用"),
8554
8819
  ),
8555
8820
  ),
@@ -9108,7 +9373,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9108
9373
  const [hoveredTool, closeToolHover, toolHover] = useHoverPreview();
9109
9374
  useEffect(() => { closeToolHover(); }, [record?.name, closeToolHover]);
9110
9375
 
9111
- const loadConnectorTools = useCallback(async (connectorName) => {
9376
+ const loadConnectorTools = useCallback(async (connectorName, forceFresh = false) => {
9112
9377
  const key = `${record.name}::${connectorName}`;
9113
9378
  const cached = GLOBAL_MCP_TOOLS_CACHE[key];
9114
9379
  const hasCachedTools = Array.isArray(cached?.tools) && cached.tools.length > 0;
@@ -9122,7 +9387,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9122
9387
  }
9123
9388
 
9124
9389
  try {
9125
- const res = await api(`/plugins/${encodeURIComponent(record.name)}/connectors/${encodeURIComponent(connectorName)}/tools`);
9390
+ const res = await api(`/plugins/${encodeURIComponent(record.name)}/connectors/${encodeURIComponent(connectorName)}/tools${forceFresh ? "?fresh=1" : ""}`);
9126
9391
  const tools = Array.isArray(res.tools) ? res.tools : [];
9127
9392
  const disabledTools = Array.isArray(res.disabledTools) ? res.disabledTools : [];
9128
9393
 
@@ -9154,7 +9419,103 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9154
9419
  }
9155
9420
  }, [record?.name]);
9156
9421
 
9157
- // Pre-fetch tools in background as soon as ManagePage opens for connected connectors
9422
+ const buildAuthPayload = () => {
9423
+ const headers = {};
9424
+ for (const item of authDialog?.headersList || []) {
9425
+ const value = (item.value || "").trim();
9426
+ if (value) headers[(item.key || "").trim() || "Authorization"] = value;
9427
+ }
9428
+ return {
9429
+ transport: authDialog.transport, url: authDialog.url, headers,
9430
+ oauth: authDialog.oauth, oauthClientId: authDialog.oauthClientId,
9431
+ oauthClientSecret: authDialog.oauthClientSecret,
9432
+ oauthCallbackPort: authDialog.oauthCallbackPort, oauthScope: authDialog.oauthScope,
9433
+ };
9434
+ };
9435
+ // Persist the dialog's configuration. Signing in is only half of an OAuth
9436
+ // connector: the tokens live in the credential store, but the connector
9437
+ // itself is not registered until this writes the bridge entry. Without it
9438
+ // the dialog reopened on whatever was saved before — usually `None`.
9439
+ const persistAuthDialog = async (payload) => {
9440
+ const data = payload || buildAuthPayload();
9441
+ const headers = { ...(data.headers || {}) };
9442
+ let parsedArgs = [];
9443
+ if (data.transport === "stdio" && authDialog.args.trim()) {
9444
+ try {
9445
+ const parsed = JSON.parse(authDialog.args);
9446
+ parsedArgs = Array.isArray(parsed) ? parsed : [String(parsed)];
9447
+ } catch {
9448
+ parsedArgs = [];
9449
+ }
9450
+ }
9451
+ const envMap = {};
9452
+ if (data.transport === "stdio") {
9453
+ for (const eItem of authDialog.envList) {
9454
+ if (eItem.key.trim()) envMap[eItem.key.trim()] = eItem.value;
9455
+ }
9456
+ }
9457
+ return api(`/plugins/${encodeURIComponent(record.name)}/connectors/${encodeURIComponent(authDialog.connectorName)}/auth`, {
9458
+ method: "POST",
9459
+ body: JSON.stringify({
9460
+ transport: data.transport,
9461
+ url: data.url,
9462
+ headers,
9463
+ oauth: data.oauth,
9464
+ oauthClientId: data.oauthClientId,
9465
+ oauthClientSecret: data.oauthClientSecret,
9466
+ oauthCallbackPort: data.oauthCallbackPort,
9467
+ oauthScope: data.oauthScope,
9468
+ args: parsedArgs,
9469
+ env: envMap,
9470
+ }),
9471
+ });
9472
+ };
9473
+ const setAuthError = (message) => setAuthDialog((prev) => prev ? {
9474
+ ...prev, testing: false, status: "error", statusMessage: message,
9475
+ lastResult: { ok: false, message, status: 500, server: prev.connectorName, transport: prev.transport, endpoint: prev.url, errorDetails: message },
9476
+ } : null);
9477
+ const oauthFlow = useOauthVerification({
9478
+ form: authDialog,
9479
+ verifyPath: `/plugins/${encodeURIComponent(record.name)}/connectors/${encodeURIComponent(authDialog?.connectorName || "")}/verify`,
9480
+ onFinished: async (res) => {
9481
+ setAuthDialog((prev) => prev ? { ...prev, testing: false, status: res.ok ? "success" : "error", statusMessage: res.message || (res.ok ? "验证成功" : "验证失败"), lastResult: res } : null);
9482
+ // A successful sign-in is also the moment the connector becomes
9483
+ // usable, so register it right away. Leaving that to the Save
9484
+ // button is what made a completed sign-in reopen as `None`.
9485
+ // A failure here is a save problem and must not read as a failed
9486
+ // verification, so it stays out of the polling error path.
9487
+ if (res.ok) {
9488
+ try {
9489
+ const saved = await persistAuthDialog(verifiedPayloadRef.current);
9490
+ if (saved && saved.ok === false) {
9491
+ showToast("保存失败", saved.error || "配置校验未通过,请检查填写内容", { restart: false });
9492
+ }
9493
+ } catch (error) {
9494
+ showToast("保存失败", cleanMcpError(error), { restart: false });
9495
+ }
9496
+ }
9497
+ await refreshState();
9498
+ if (res.ok && res.server) await loadConnectorTools(res.server, true);
9499
+ },
9500
+ onCancel: () => setAuthDialog((prev) => prev ? { ...prev, testing: false, status: "untested", statusMessage: "" } : null),
9501
+ onError: (error) => setAuthError(error.message),
9502
+ });
9503
+ const closeAuthDialog = useCallback(() => {
9504
+ setAuthDialog(null);
9505
+ void oauthFlow.cancel();
9506
+ }, [oauthFlow.cancel]);
9507
+ // Which configuration the running verification was started with. The
9508
+ // dialog can be edited while the browser is open, so the auto-save after
9509
+ // a finished sign-in must persist the verified one, not the latest form.
9510
+ const verifiedPayloadRef = useRef(null);
9511
+ const runAuthTest = async () => {
9512
+ if (!authDialog) return;
9513
+ const payload = buildAuthPayload();
9514
+ verifiedPayloadRef.current = payload;
9515
+ setAuthDialog((prev) => prev ? { ...prev, testing: true, status: "testing", statusMessage: "" } : null);
9516
+ await oauthFlow.start(payload);
9517
+ };
9518
+
9158
9519
  useEffect(() => {
9159
9520
  if (record && Array.isArray(record.connectors)) {
9160
9521
  record.connectors.forEach((c) => {
@@ -9512,10 +9873,10 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9512
9873
  isSecret: true,
9513
9874
  }));
9514
9875
 
9515
- const isHttpOnly = !!(connObj && (connObj.url || connObj.type === "http" || connObj.type === "sse") && !connObj.command);
9876
+ const isHttpOnly = !!(connObj && (connObj.url || isRemoteTransport(connObj.type)) && !connObj.command);
9516
9877
  const isStdioOnly = !!(connObj && (connObj.command || connObj.type === "stdio") && !connObj.url);
9517
9878
  const allowedTransports = isHttpOnly ? ["http"] : (isStdioOnly ? ["stdio"] : ["http", "stdio"]);
9518
- const initialTransport = isHttpOnly ? "http" : (isStdioOnly ? "stdio" : ((connObj && connObj.type === "stdio") ? "stdio" : "http"));
9879
+ const initialTransport = isHttpOnly ? "http" : (isStdioOnly ? "stdio" : (connObj && connObj.type === "stdio" ? "stdio" : "http"));
9519
9880
 
9520
9881
  let rawArgs = "";
9521
9882
  if (connObj && connObj.args) {
@@ -9536,6 +9897,11 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9536
9897
  args: rawArgs,
9537
9898
  envList: envEntries,
9538
9899
  oauth: (connObj && connObj.oauth) || "none",
9900
+ oauthClientId: (connObj && connObj.oauthClientId) || "",
9901
+ oauthClientSecret: "",
9902
+ oauthHasClientSecret: (connObj && connObj.oauthHasClientSecret) === true,
9903
+ oauthCallbackPort: (connObj && connObj.oauthCallbackPort) || "",
9904
+ oauthScope: (connObj && connObj.oauthScope) || "",
9539
9905
  testing: false,
9540
9906
  saving: false,
9541
9907
  status: "untested",
@@ -9561,7 +9927,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9561
9927
  if (!authDialog && !confirmRemove) return;
9562
9928
  const onKey = (e) => {
9563
9929
  if (e.key === "Escape") {
9564
- if (authDialog) setAuthDialog(null);
9930
+ if (authDialog) closeAuthDialog();
9565
9931
  if (confirmRemove) setConfirmRemove(false);
9566
9932
  }
9567
9933
  };
@@ -9880,9 +10246,11 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9880
10246
  const needsAuth = typeof c === "object" ? (c.needsAuth === true) : false;
9881
10247
  const isAuthenticated = typeof c === "object" ? (c.authenticated === true) : true;
9882
10248
  const isConnected = typeof c === "object" ? (c.connected === true) : false;
10249
+ const isEnabled = typeof c === "object" ? (c.enabled === true) : isConnected;
9883
10250
  const transport = typeof c === "object" ? (c.type || (c.url ? "HTTP" : "stdio")) : "MCP";
9884
10251
  const endpoint = typeof c === "object" ? (c.url || (c.command ? `${c.command} ${(c.args || []).join(" ")}` : "")) : "";
9885
- const isPendingVerify = needsAuth && !isAuthenticated;
10252
+ const isRemote = transport !== "stdio";
10253
+ const isPendingVerify = isRemote ? !isConnected : (needsAuth && !isAuthenticated);
9886
10254
  const isExpanded = !!expandedConnectors[cName];
9887
10255
  const toolsInfo = connectorToolsData[cName];
9888
10256
  const toolsList = toolsInfo?.tools || [];
@@ -9958,13 +10326,14 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9958
10326
  onClick: () => openAuthDialog(cName, c),
9959
10327
  }, h(IconSettings, { size: 14 })),
9960
10328
  h("button", {
9961
- className: "cpm-toggle" + (isConnected ? " on" : ""),
10329
+ className: "cpm-toggle" + (isEnabled ? " on" : ""),
10330
+ "aria-label": isEnabled ? "停用" : "启用",
9962
10331
  disabled: togglingConn === cName || busy,
9963
10332
  onClick: () => {
9964
- if (needsAuth && !isAuthenticated && !isConnected) {
10333
+ if (!isEnabled && ((isRemote && !isConnected) || (needsAuth && !isAuthenticated))) {
9965
10334
  openAuthDialog(cName, c);
9966
10335
  } else {
9967
- toggleConn(cName, isConnected);
10336
+ toggleConn(cName, isEnabled);
9968
10337
  }
9969
10338
  },
9970
10339
  }),
@@ -9988,11 +10357,11 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
9988
10357
  ),
9989
10358
  ),
9990
10359
 
9991
- authDialog && h("div", { className: "cpm-dialog", onClick: () => setAuthDialog(null) },
10360
+ authDialog && h("div", { className: "cpm-dialog", onClick: closeAuthDialog },
9992
10361
  h("div", { className: "cpm-mcp-modal", onClick: (e) => e.stopPropagation() },
9993
10362
  h("button", {
9994
10363
  className: "cpm-mcp-close-top",
9995
- onClick: () => setAuthDialog(null),
10364
+ onClick: closeAuthDialog,
9996
10365
  }, h(IconClose, { size: 14 })),
9997
10366
 
9998
10367
  h("div", { className: "cpm-mcp-body" },
@@ -10192,6 +10561,8 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10192
10561
  }),
10193
10562
  ),
10194
10563
  ),
10564
+ h(OauthFields, { form: authDialog, onChange: setAuthDialog, idPrefix: "edit-mcp" }),
10565
+ oauthFlow.pending && h(OauthPendingCard, { pending: oauthFlow.pending, onCancel: oauthFlow.cancel }),
10195
10566
  ),
10196
10567
 
10197
10568
  h("div", { className: "cpm-mcp-footer" },
@@ -10293,54 +10664,11 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10293
10664
  h("button", {
10294
10665
  className: "cpm-btn cpm-btn-secondary",
10295
10666
  disabled: authDialog.testing || authDialog.saving || (authDialog.transport === "stdio" && !!getArgsJsonError(authDialog.args)),
10296
- onClick: async () => {
10297
- const computedHeaders = {};
10298
- for (const hItem of authDialog.headersList) {
10299
- const v = (hItem.value || "").trim();
10300
- if (!v) continue;
10301
- const k = (hItem.key || "").trim() || "Authorization";
10302
- computedHeaders[k] = v;
10303
- }
10304
- setAuthDialog((prev) => prev ? { ...prev, testing: true, status: "testing", statusMessage: "" } : null);
10305
- try {
10306
- const res = await api(`/plugins/${record.name}/connectors/${authDialog.connectorName}/verify`, {
10307
- method: "POST",
10308
- body: JSON.stringify({
10309
- transport: authDialog.transport,
10310
- url: authDialog.url,
10311
- headers: computedHeaders,
10312
- oauth: authDialog.oauth,
10313
- }),
10314
- });
10315
- setAuthDialog((prev) => prev ? {
10316
- ...prev,
10317
- testing: false,
10318
- status: res.ok ? "success" : "error",
10319
- statusMessage: res.message || (res.ok ? "验证成功" : "验证失败"),
10320
- lastResult: res,
10321
- } : null);
10322
- } catch (err) {
10323
- setAuthDialog((prev) => prev ? {
10324
- ...prev,
10325
- testing: false,
10326
- status: "error",
10327
- statusMessage: err.message,
10328
- lastResult: {
10329
- ok: false,
10330
- message: err.message,
10331
- status: 500,
10332
- server: prev.connectorName,
10333
- transport: prev.transport,
10334
- endpoint: prev.url,
10335
- errorDetails: err.message,
10336
- },
10337
- } : null);
10338
- }
10339
- },
10340
- }, authDialog.testing ? "测试中…" : (
10667
+ onClick: runAuthTest,
10668
+ }, authDialog.testing ? (authDialog.oauth !== "none" ? "等待授权…" : "测试中…") : (
10341
10669
  authDialog.transport === "stdio" ? "测试连接" : (
10342
- (authDialog.oauth && authDialog.oauth !== "none") ? "Sign in & test" : (
10343
- (authDialog.headersList && authDialog.headersList.some(h => (h.value || '').trim())) ? "验证并测试" : "测试连接"
10670
+ (authDialog.oauth && authDialog.oauth !== "none") ? "登录并连接" : (
10671
+ (authDialog.headersList && authDialog.headersList.some(h => (h.value || '').trim())) ? "验证并连接" : "测试连接"
10344
10672
  )
10345
10673
  )
10346
10674
  )),
@@ -10349,41 +10677,9 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10349
10677
  className: "cpm-btn cpm-btn-primary",
10350
10678
  disabled: authDialog.saving || authDialog.testing || (authDialog.transport === "stdio" && !!getArgsJsonError(authDialog.args)),
10351
10679
  onClick: async () => {
10352
- const computedHeaders = {};
10353
- for (const hItem of authDialog.headersList) {
10354
- const v = (hItem.value || "").trim();
10355
- if (!v) continue;
10356
- const k = (hItem.key || "").trim() || "Authorization";
10357
- computedHeaders[k] = v;
10358
- }
10359
10680
  setAuthDialog((prev) => prev ? { ...prev, saving: true } : null);
10360
10681
  try {
10361
- let parsedArgs = [];
10362
- if (authDialog.transport === "stdio" && authDialog.args.trim()) {
10363
- try {
10364
- const parsed = JSON.parse(authDialog.args);
10365
- parsedArgs = Array.isArray(parsed) ? parsed : [String(parsed)];
10366
- } catch {
10367
- parsedArgs = [];
10368
- }
10369
- }
10370
- const envMap = {};
10371
- if (authDialog.transport === "stdio") {
10372
- for (const eItem of authDialog.envList) {
10373
- if (eItem.key.trim()) envMap[eItem.key.trim()] = eItem.value;
10374
- }
10375
- }
10376
- const res = await api(`/plugins/${record.name}/connectors/${authDialog.connectorName}/auth`, {
10377
- method: "POST",
10378
- body: JSON.stringify({
10379
- transport: authDialog.transport,
10380
- url: authDialog.url,
10381
- headers: computedHeaders,
10382
- oauth: authDialog.oauth,
10383
- args: parsedArgs,
10384
- env: envMap,
10385
- }),
10386
- });
10682
+ const res = await persistAuthDialog();
10387
10683
  if (res && res.ok === false) {
10388
10684
  showToast("保存失败", res.error || "配置校验未通过,请检查填写内容", { restart: false });
10389
10685
  setAuthDialog((prev) => prev ? { ...prev, saving: false } : null);
@@ -10391,7 +10687,7 @@ window.__ModuleLoader__.load({ id: "universal-plugin-hub", factory: (require) =>
10391
10687
  }
10392
10688
  await refreshState();
10393
10689
  showToast("配置成功", `已成功保存 ${authDialog.connectorName} 认证信息并注册为可用 MCP 服务`, { restart: false });
10394
- setAuthDialog(null);
10690
+ closeAuthDialog();
10395
10691
  } catch (err) {
10396
10692
  showToast("保存失败", err.message);
10397
10693
  setAuthDialog((prev) => prev ? { ...prev, saving: false, status: "error", statusMessage: err.message } : null);