@huaqiu/dsh-auth 0.6.21 → 0.6.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.js CHANGED
@@ -49,6 +49,12 @@ window.__ModuleLoader__.load({
49
49
  return null;
50
50
  }
51
51
  }
52
+ /** Accept only a finite `quotaRemainPercent`; anything else → unavailable. */
53
+ function normalizeUsage(value) {
54
+ if (value === null || typeof value !== "object") return null;
55
+ const percent = value.quotaRemainPercent;
56
+ return typeof percent === "number" && Number.isFinite(percent) ? { quotaRemainPercent: percent } : null;
57
+ }
52
58
  function createWebServerAuthTransport(base = "/api/v1/huaqiu/auth", doFetch = globalThis.fetch.bind(globalThis)) {
53
59
  return {
54
60
  async pushSession(info) {
@@ -76,17 +82,20 @@ window.__ModuleLoader__.load({
76
82
  });
77
83
  if (!res.ok) return {
78
84
  hostMode: false,
79
- subscriptionOrigin: null
85
+ subscriptionOrigin: null,
86
+ subscriptionApiBaseUrl: null
80
87
  };
81
88
  const body = await res.json();
82
89
  return {
83
90
  hostMode: body.hostMode === true,
84
- subscriptionOrigin: normalizeOrigin(body.subscriptionOrigin)
91
+ subscriptionOrigin: normalizeOrigin(body.subscriptionOrigin),
92
+ subscriptionApiBaseUrl: normalizeOrigin(body.subscriptionApiBaseUrl)
85
93
  };
86
94
  } catch {
87
95
  return {
88
96
  hostMode: false,
89
- subscriptionOrigin: null
97
+ subscriptionOrigin: null,
98
+ subscriptionApiBaseUrl: null
90
99
  };
91
100
  }
92
101
  },
@@ -132,7 +141,7 @@ window.__ModuleLoader__.load({
132
141
  headers: { accept: "application/json" }
133
142
  });
134
143
  if (!res.ok) return null;
135
- return (await res.json()).usage ?? null;
144
+ return normalizeUsage((await res.json()).usage);
136
145
  } catch {
137
146
  return null;
138
147
  }
@@ -186,18 +195,23 @@ window.__ModuleLoader__.load({
186
195
  };
187
196
  }
188
197
  /**
189
- * Fetch the active subscription quota DIRECTLY from eda.cn
190
- * (`GET {baseUrl}/sub-api/subscriptions/active?userId&productCode` with
191
- * `x-token` + `X-User-Id` headers) — the same API `hq-eda-ai`'s
192
- * `getActiveSubscription` and `hq-edge`'s ERC quota proxy call, so displaying
193
- * the available quota never depends on an hq-edge hop.
198
+ * Fetch the active subscription quota (`GET {baseUrl}/sub-api/subscriptions/
199
+ * active?userId&productCode` with `x-token` + `X-User-Id` headers) — the same
200
+ * API `hq-eda-ai`'s `getActiveSubscription` and `hq-edge`'s ERC quota proxy
201
+ * call.
202
+ *
203
+ * `baseUrl` is the origin the node half derives from the resolved
204
+ * subscription-balances endpoint (`HQ_AI_ENV`), so this call follows the
205
+ * selected environment and DSH Auth never hardcodes a production host. No
206
+ * configured origin → null (the UI shows「—」).
194
207
  *
195
208
  * Returns null when the fetch/unwrap fails (callers decide fail-open vs
196
209
  * fail-closed); a well-formed response always yields a `SubscriptionQuota`
197
210
  * (possibly with `hasSubscription: false`).
198
211
  */
199
212
  async function fetchSubscriptionQuota(options) {
200
- const { userId, token, productCode, baseUrl = "https://www.eda.cn" } = options;
213
+ const { userId, token, productCode, baseUrl } = options;
214
+ if (!baseUrl) return null;
201
215
  const fetchImpl = options.fetchImpl ?? fetch;
202
216
  const url = `${baseUrl}${SUB_API_PREFIX}/subscriptions/active?${new URLSearchParams({
203
217
  userId: String(userId),
@@ -615,9 +629,11 @@ window.__ModuleLoader__.load({
615
629
  "subscription.upgrade": "订阅 / 升级套餐",
616
630
  "subscription.online": "在线",
617
631
  "subscription.ai": "AI 用量",
618
- "subscription.aiUsageCount": "{available} / {total} 点",
619
632
  "subscription.aiUsagePercent": "{percent}%",
620
633
  "subscription.aiUsageUnknown": "暂无数据",
634
+ "turnError.aiQuotaCta": "升级获取更多 AI 额度",
635
+ "turnError.aiQuotaSignIn": "登录后升级",
636
+ "turnError.aiQuotaOpenFailed": "无法打开订阅页面,请稍后重试。",
621
637
  "card.title": "华秋 EDA AI(eda.cn)登录",
622
638
  "card.desc": "工具「{tool}」需要登录华秋 EDA AI 账号才能继续。请在下方的登录框完成登录(或点击左侧「华秋EDA AI登录」按钮);登录完成后,回复助手「已登录,请重试」,助手会自动重新调用该工具。",
623
639
  "card.loggedIn": "✓ 已登录{nickname} —— 现在可以回复助手「已登录,请重试」,助手会重新调用工具。",
@@ -654,9 +670,11 @@ window.__ModuleLoader__.load({
654
670
  "subscription.upgrade": "Subscribe / Upgrade plan",
655
671
  "subscription.online": "Online",
656
672
  "subscription.ai": "AI usage",
657
- "subscription.aiUsageCount": "{available} / {total} pts",
658
673
  "subscription.aiUsagePercent": "{percent}%",
659
674
  "subscription.aiUsageUnknown": "No data",
675
+ "turnError.aiQuotaCta": "Upgrade for more AI tokens",
676
+ "turnError.aiQuotaSignIn": "Sign in to upgrade",
677
+ "turnError.aiQuotaOpenFailed": "Could not open the subscription page. Please try again later.",
660
678
  "card.title": "Huaqiu EDA AI (eda.cn) login",
661
679
  "card.desc": "Tool \"{tool}\" needs a Huaqiu EDA AI account. Complete the login below (or use the Huaqiu EDA AI button in the sidebar), then reply \"I have logged in, please retry\" so the assistant can retry the tool.",
662
680
  "card.loggedIn": "✓ Logged in{nickname} — reply \"I have logged in, please retry\" and the assistant will retry the tool.",
@@ -1041,10 +1059,21 @@ window.__ModuleLoader__.load({
1041
1059
  let hostSession = null;
1042
1060
  let hostSessionLoaded = false;
1043
1061
  /**
1062
+ * Why the last host-session resolution failed, if it did. Transport errors
1063
+ * must NOT masquerade as a healthy `signed-out`: the dialog opener surfaces
1064
+ * them as a rejection so callers can show retry copy instead of "sign in".
1065
+ */
1066
+ let hostResolveError;
1067
+ /**
1044
1068
  * Subscription origin resolved by HQ Edge from `HQ_AI_ENV` and served on the
1045
1069
  * node `/config` route. Null in standalone → lib's PROD fallback.
1046
1070
  */
1047
1071
  let subscriptionOrigin = null;
1072
+ /**
1073
+ * Origin of the resolved subscription-balances API (node `/config`). Null
1074
+ * when no environment is configured → GEN/ERC quota calls are skipped.
1075
+ */
1076
+ let subscriptionApiBaseUrl = null;
1048
1077
  const emit = (info) => {
1049
1078
  for (const listener of listeners) listener(info);
1050
1079
  };
@@ -1075,6 +1104,7 @@ window.__ModuleLoader__.load({
1075
1104
  */
1076
1105
  const resolveHost = async () => {
1077
1106
  hostSessionLoaded = true;
1107
+ hostResolveError = void 0;
1078
1108
  if (!hostMode) {
1079
1109
  hostSession = null;
1080
1110
  return;
@@ -1082,8 +1112,9 @@ window.__ModuleLoader__.load({
1082
1112
  try {
1083
1113
  const session = await transport.fetchSession();
1084
1114
  hostSession = session.authenticated ? normalizeHostUserPayload(session.user) : null;
1085
- } catch {
1115
+ } catch (error) {
1086
1116
  hostSession = null;
1117
+ hostResolveError = error;
1087
1118
  }
1088
1119
  };
1089
1120
  const auth = {
@@ -1136,7 +1167,8 @@ window.__ModuleLoader__.load({
1136
1167
  return fetchSubscriptionQuota({
1137
1168
  userId: id,
1138
1169
  token,
1139
- productCode
1170
+ productCode,
1171
+ ...subscriptionApiBaseUrl ? { baseUrl: subscriptionApiBaseUrl } : {}
1140
1172
  });
1141
1173
  },
1142
1174
  getAiTokenUsage: async () => {
@@ -1147,13 +1179,16 @@ window.__ModuleLoader__.load({
1147
1179
  openSubscriptionDialog: async () => {
1148
1180
  if (hostMode && !hostSessionLoaded) await resolveHost();
1149
1181
  const token = await auth.getAccessToken();
1150
- if (!token) return;
1182
+ if (!token) {
1183
+ if (hostMode && hostResolveError !== void 0) throw hostResolveError;
1184
+ return { status: "signed-out" };
1185
+ }
1151
1186
  const url = buildSubscriptionUrl({
1152
1187
  token,
1153
1188
  ...subscriptionOrigin ? { origin: subscriptionOrigin } : {}
1154
1189
  });
1155
1190
  if (hostMode) {
1156
- if (!deps.openHostDialog) return;
1191
+ if (!deps.openHostDialog) return { status: "host-unavailable" };
1157
1192
  await deps.openHostDialog(url, {
1158
1193
  title: "Huaqiu EDA subscription",
1159
1194
  size: {
@@ -1162,10 +1197,11 @@ window.__ModuleLoader__.load({
1162
1197
  },
1163
1198
  key: "hq-subscription-dialog"
1164
1199
  });
1165
- return;
1200
+ return { status: "opened" };
1166
1201
  }
1167
- if (isSubscriptionDialogOpen()) return;
1202
+ if (isSubscriptionDialogOpen()) return { status: "already-open" };
1168
1203
  openSubscriptionDialog(url, { size: SUBSCRIPTION_PREFERRED_SIZE });
1204
+ return { status: "opened" };
1169
1205
  },
1170
1206
  onAuthStateChanged: (listener) => {
1171
1207
  listeners.add(listener);
@@ -1218,9 +1254,11 @@ window.__ModuleLoader__.load({
1218
1254
  const runtime = await transport.fetchRuntimeConfig();
1219
1255
  mode = runtime.hostMode;
1220
1256
  subscriptionOrigin = runtime.subscriptionOrigin;
1257
+ subscriptionApiBaseUrl = runtime.subscriptionApiBaseUrl;
1221
1258
  } catch {
1222
1259
  mode = false;
1223
1260
  subscriptionOrigin = null;
1261
+ subscriptionApiBaseUrl = null;
1224
1262
  }
1225
1263
  hostMode = mode;
1226
1264
  hostSessionLoaded = false;
@@ -1257,6 +1295,7 @@ window.__ModuleLoader__.load({
1257
1295
  hostSession = null;
1258
1296
  hostSessionLoaded = false;
1259
1297
  subscriptionOrigin = null;
1298
+ subscriptionApiBaseUrl = null;
1260
1299
  }
1261
1300
  };
1262
1301
  }
@@ -1886,34 +1925,19 @@ window.__ModuleLoader__.load({
1886
1925
  });
1887
1926
  }
1888
1927
  /**
1889
- * AI token reading from `/user-rest/api/ai/usage`.
1890
- *
1891
- * The headline number is the AVAILABLE (remaining) balance, not the consumed
1892
- * one — the same convention as the GEN/ERC cards beside it, which display
1893
- * `currentQuota` (the REMAINING quota: hq-edge exposes it as
1894
- * `availableQuota`/"Available Quota", hq-eda-ai as `remainingQuota`). Showing
1895
- * `usedPoints` here made the AI card the only surface in the product that
1896
- * reported consumption as the balance: an account that burned 77 of its 100
1897
- * points read "77 / 100 pts" where the user expects "23 / 100 pts".
1928
+ * AI reading from the subscription-balances AI Points group.
1898
1929
  *
1899
- * The balance is reported as `usedPoints` + `availablePoints`, so the total is
1900
- * their sum — there is no separate `totalPoints` field to read. Percent keeps
1901
- * one decimal: a fresh account has well over 99% of its balance left, and
1902
- * rounding 99.6% up to "100%" would read as an exhausted account.
1930
+ * The percentage is the upstream `quotaRemainPercent` — the REMAINING share —
1931
+ * passed through unchanged: no local ratio and no re-rounding, so `99.68`
1932
+ * renders as `99.68%`. A missing / `null` / non-finite value is unavailable
1933
+ * (the card shows「—」); the bar clamps to 0–100 while the label does not.
1903
1934
  */
1904
1935
  function aiUsageReading(usage, t) {
1905
- if (!usage) return null;
1906
- const used = Math.max(0, usage.usedPoints);
1907
- const available = Math.max(0, usage.availablePoints);
1908
- const total = used + available;
1909
- const percent = total > 0 ? Math.min(100, Math.round(available / total * 1e3) / 10) : 0;
1936
+ const percent = usage?.quotaRemainPercent;
1937
+ if (typeof percent !== "number" || !Number.isFinite(percent)) return null;
1910
1938
  return {
1911
- value: t("subscription.aiUsagePercent", { percent: Math.round(percent) }),
1912
- title: t("subscription.aiUsageCount", {
1913
- available,
1914
- total
1915
- }),
1916
- percent,
1939
+ value: t("subscription.aiUsagePercent", { percent }),
1940
+ percent: Math.max(0, Math.min(100, percent)),
1917
1941
  ok: true
1918
1942
  };
1919
1943
  }
@@ -2337,6 +2361,152 @@ window.__ModuleLoader__.load({
2337
2361
  });
2338
2362
  });
2339
2363
  //#endregion
2364
+ //#region src/client/ui/turn-error-cta.tsx
2365
+ /**
2366
+ * `conversation.chat.turn-error.action` entry: a subscription button inside
2367
+ * the Chat terminal-failure card.
2368
+ *
2369
+ * The huaqiu gateway reports an exhausted token balance as a provider error
2370
+ * whose own payload code is `insufficient_user_quota`. The harness keeps that
2371
+ * code on the durable failure as `providerErrorCode` and attributes the
2372
+ * failure to the routed `provider`; this entry gates on those structured
2373
+ * fields only, so a wording change or an unrelated error simply renders no
2374
+ * button. Clicking it opens the subscription dialog owned by this package's
2375
+ * auth client (`openSubscriptionDialog`), which is the same path the sidebar
2376
+ * upgrade entry uses.
2377
+ *
2378
+ * Fallbacks stay inside the card: no host dialog service → the existing
2379
+ * "host provides no dialog service" copy; transport failure → retry copy; no
2380
+ * credential → the auth client's login surface. The entry never throws, so a
2381
+ * missing or older slot harness degrades to the shipped card.
2382
+ */
2383
+ /** Gateway provider whose balance signature this entry understands. */
2384
+ const QUOTA_PROVIDER = "huaqiu";
2385
+ /** The gateway's own code for a token balance that can be topped up. */
2386
+ const HUAQIU_QUOTA_SIGNATURE = "insufficient_user_quota";
2387
+ /**
2388
+ * Whether a durable failure is the huaqiu gateway's exhausted token balance.
2389
+ *
2390
+ * Two structured shapes qualify:
2391
+ * - the adapter extracted the gateway's own `insufficient_user_quota` code, or
2392
+ * - the routed provider is huaqiu and the harness classified the failure as
2393
+ * `QUOTA` (covers classifier fixes that stop carrying the payload code).
2394
+ *
2395
+ * Never gate on `message`: unrelated failures can quote provider text, and a
2396
+ * payload/wording change must degrade to "no button", not to a false positive.
2397
+ * @param node - durable turn-error node, possibly absent at runtime boundaries.
2398
+ * @returns true only for the huaqiu token-quota signature.
2399
+ */
2400
+ function isHuaqiuQuotaFailure(node) {
2401
+ if (node === null || node === void 0) return false;
2402
+ if (node.code !== "PI_AI_ERROR" && node.code !== "QUOTA") return false;
2403
+ if (node.providerErrorCode === HUAQIU_QUOTA_SIGNATURE) return true;
2404
+ return node.provider === QUOTA_PROVIDER && node.code === "QUOTA";
2405
+ }
2406
+ const ctaStyle = {
2407
+ display: "block",
2408
+ width: "fit-content",
2409
+ marginTop: 4,
2410
+ padding: "1px 10px",
2411
+ border: "1px solid var(--dsw-alias-brand-primary, #e62e2d)",
2412
+ borderRadius: 999,
2413
+ background: "transparent",
2414
+ color: "var(--dsw-alias-brand-primary, #e62e2d)",
2415
+ font: "inherit",
2416
+ fontSize: 13,
2417
+ lineHeight: "20px",
2418
+ cursor: "pointer"
2419
+ };
2420
+ const noticeStyle = {
2421
+ display: "block",
2422
+ marginTop: 2,
2423
+ color: "var(--dsw-alias-state-error-primary, #d4380d)",
2424
+ fontSize: 12,
2425
+ lineHeight: "18px"
2426
+ };
2427
+ const stopStyle = {
2428
+ borderRadius: 999,
2429
+ opacity: .6,
2430
+ cursor: "default"
2431
+ };
2432
+ /** Turn-error recovery affordance for the huaqiu token quota. */
2433
+ const HuaqiuTurnErrorSubscribeAction = (0, react.memo)(function HuaqiuTurnErrorSubscribeAction({ node }) {
2434
+ const auth = getAuth();
2435
+ const authState = (0, react.useSyncExternalStore)(subscribeAuth, getAuthState, getAuthState);
2436
+ const locale = useLocale();
2437
+ const dark = useIsDark();
2438
+ const t = useT();
2439
+ const [busy, setBusy] = (0, react.useState)(false);
2440
+ const [hovered, setHovered] = (0, react.useState)(false);
2441
+ const [notice, setNotice] = (0, react.useState)(null);
2442
+ const nodeKey = node.message;
2443
+ const visibleNotice = notice !== null && notice.key === nodeKey ? notice.text : null;
2444
+ const open = (0, react.useCallback)(() => {
2445
+ if (busy) return;
2446
+ const fail = () => {
2447
+ setNotice({
2448
+ key: nodeKey,
2449
+ text: t("turnError.aiQuotaOpenFailed")
2450
+ });
2451
+ };
2452
+ if (!auth) {
2453
+ fail();
2454
+ return;
2455
+ }
2456
+ const requestLogin = () => {
2457
+ try {
2458
+ auth.login({
2459
+ lang: locale,
2460
+ theme: dark ? "dark" : "light"
2461
+ }).catch(fail);
2462
+ } catch {
2463
+ fail();
2464
+ }
2465
+ };
2466
+ if (!authState.authenticated) {
2467
+ requestLogin();
2468
+ return;
2469
+ }
2470
+ setNotice(null);
2471
+ setBusy(true);
2472
+ auth.openSubscriptionDialog().then((outcome) => {
2473
+ if (outcome.status === "host-unavailable") setNotice({
2474
+ key: nodeKey,
2475
+ text: t("subscription.hostUnavailable")
2476
+ });
2477
+ else if (outcome.status === "signed-out") requestLogin();
2478
+ }).catch(fail).finally(() => setBusy(false));
2479
+ }, [
2480
+ auth,
2481
+ authState.authenticated,
2482
+ busy,
2483
+ dark,
2484
+ locale,
2485
+ nodeKey,
2486
+ t
2487
+ ]);
2488
+ if (!isHuaqiuQuotaFailure(node)) return null;
2489
+ const label = busy ? t("subscription.subscribing") : authState.authenticated ? t("turnError.aiQuotaCta") : t("turnError.aiQuotaSignIn");
2490
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2491
+ type: "button",
2492
+ style: {
2493
+ ...ctaStyle,
2494
+ ...hovered && !busy ? { background: "var(--dsw-alias-interactive-bg-hover, rgba(230, 46, 45, 0.08))" } : {},
2495
+ ...busy ? stopStyle : {}
2496
+ },
2497
+ disabled: busy,
2498
+ "aria-busy": busy,
2499
+ onClick: open,
2500
+ onMouseEnter: () => setHovered(true),
2501
+ onMouseLeave: () => setHovered(false),
2502
+ children: label
2503
+ }), visibleNotice === null ? null : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2504
+ style: noticeStyle,
2505
+ "aria-live": "polite",
2506
+ children: visibleNotice
2507
+ })] });
2508
+ });
2509
+ //#endregion
2340
2510
  //#region src/client/index.tsx
2341
2511
  /**
2342
2512
  * `@huaqiu/dsh-auth` — browser half (the Phase 0A POC).
@@ -2394,7 +2564,7 @@ window.__ModuleLoader__.load({
2394
2564
  documentLike: document,
2395
2565
  openHostDialog: async (url, options) => {
2396
2566
  const hqEdge = ctx.get?.("hqEdge");
2397
- if (!hqEdge || typeof hqEdge.openUrl !== "function") return;
2567
+ if (!hqEdge || typeof hqEdge.openUrl !== "function") throw new Error("hqEdge.openUrl is unavailable");
2398
2568
  await hqEdge.openUrl(url, {
2399
2569
  ...options.title ? { title: options.title } : {},
2400
2570
  ...options.size ? { size: options.size } : {},
@@ -2464,6 +2634,10 @@ window.__ModuleLoader__.load({
2464
2634
  name: "sidebar.footer.action",
2465
2635
  id: "huaqiu-auth"
2466
2636
  }, HuaqiuAuthSidebarAction)));
2637
+ disposers.push(slots.inject("conversation.chat.turn-error.action", () => slots.register({
2638
+ name: "conversation.chat.turn-error.action",
2639
+ id: "huaqiu-turn-error-cta"
2640
+ }, HuaqiuTurnErrorSubscribeAction)));
2467
2641
  }
2468
2642
  });
2469
2643
  return () => {