@huaqiu/dsh-auth 0.5.9 → 0.5.21

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/index.mjs CHANGED
@@ -762,6 +762,57 @@ async function fetchEdaUserProfile(token, doFetch = globalThis.fetch.bind(global
762
762
  }
763
763
  }
764
764
  const AUTH_ROUTE_PREFIX = "/api/v1/huaqiu/auth";
765
+ /**
766
+ * The account's AI balance endpoint.
767
+ *
768
+ * It is served over PLAIN `http`, which is why the node half must be the one to
769
+ * call it: a WebView fetch is refused by App Transport Security ("the resource
770
+ * could not be loaded because the App Transport Security policy requires the
771
+ * use of a secure connection") and, independently, by CORS (the response sends
772
+ * no `Access-Control-Allow-Origin`). Node's fetch is subject to neither, and
773
+ * this process already talks to this very host for the Huaqiu AI gateway
774
+ * (`http://www.fdatasheets.com/user-rest/ai/v1`, see hq-edge's
775
+ * `HUAQIU_AI_GATEWAY_BASE_URL`) — so the call is known to work from here.
776
+ */
777
+ const AI_USAGE_URL = "http://www.fdatasheets.com/user-rest/api/ai/usage";
778
+ /**
779
+ * Fetch the account's AI token usage for a token. Null on any failure (the UI
780
+ * degrades to「—」) — never throws.
781
+ *
782
+ * The header is `X-Token` (capital T), which is what this endpoint expects; the
783
+ * subscription endpoint next door uses `x-token` + `X-User-Id`.
784
+ */
785
+ async function fetchAiTokenUsage(token, doFetch = globalThis.fetch.bind(globalThis)) {
786
+ try {
787
+ const res = await doFetch(AI_USAGE_URL, {
788
+ method: "GET",
789
+ headers: {
790
+ Accept: "application/json, text/plain, */*",
791
+ "Content-Type": "application/json",
792
+ "X-Token": token
793
+ }
794
+ });
795
+ if (!res.ok) return null;
796
+ const body = await res.json();
797
+ if (body.code !== 2e5 || !body.result) return null;
798
+ const result = body.result;
799
+ const num = (key) => {
800
+ const v = Number(result[key]);
801
+ return Number.isFinite(v) ? v : 0;
802
+ };
803
+ return {
804
+ availablePoints: num("availablePoints"),
805
+ availableQuota: num("availableQuota"),
806
+ availableUsd: num("availableUsd"),
807
+ usedPoints: num("usedPoints"),
808
+ usedQuota: num("usedQuota"),
809
+ usedUsd: num("usedUsd")
810
+ };
811
+ } catch (err) {
812
+ log$1().warn("fetchAiTokenUsage failed", { error: String(err?.message || err) });
813
+ return null;
814
+ }
815
+ }
765
816
  function sendJson(res, status, body) {
766
817
  res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
767
818
  res.end(JSON.stringify(body));
@@ -829,6 +880,15 @@ function createAuthHandler(service) {
829
880
  sendJson(res, 200, { userInfo: await fetchEdaUserProfile(token) });
830
881
  return;
831
882
  }
883
+ if (req.method === "GET" && pathname === `/api/v1/huaqiu/auth/ai-usage`) {
884
+ const token = await service.auth.getAccessToken();
885
+ if (!token) {
886
+ sendJson(res, 200, { usage: null });
887
+ return;
888
+ }
889
+ sendJson(res, 200, { usage: await fetchAiTokenUsage(token) });
890
+ return;
891
+ }
832
892
  if (req.method === "POST" && pathname === `/api/v1/huaqiu/auth/login`) {
833
893
  await service.auth.login();
834
894
  const user = await service.auth.getUserInfo();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@huaqiu/dsh-auth",
3
- "version": "0.5.9",
3
+ "version": "0.5.21",
4
4
  "type": "module",
5
5
  "main": "./lib/index.mjs",
6
6
  "types": "./lib/index.d.mts",
@@ -33,7 +33,7 @@
33
33
  },
34
34
  "dependencies": {
35
35
  "@deepseek-ai/dsh-home-paths": "^0.1.0-rc.0",
36
- "@huaqiu/dsh-plugin-log": "0.5.9"
36
+ "@huaqiu/dsh-plugin-log": "0.5.21"
37
37
  },
38
38
  "files": [
39
39
  "lib",
@@ -9,6 +9,7 @@ import {
9
9
  fetchSubscriptionQuota,
10
10
  handleAuthMessage,
11
11
  SUBSCRIPTION_PREFERRED_SIZE,
12
+ type AiTokenUsage,
12
13
  type AuthMessageEventLike,
13
14
  type AuthTokenPayload,
14
15
  type LoginOptions,
@@ -71,6 +72,14 @@ export interface AuthClient {
71
72
  * failure / no credential (callers decide fail-open vs fail-closed).
72
73
  */
73
74
  getSubscriptionQuota(productCode: string): Promise<SubscriptionQuota | null>
75
+ /**
76
+ * AI token usage for the signed-in account. Resolved by the NODE half
77
+ * (`GET /api/v1/huaqiu/auth/ai-usage`) — the endpoint is served over plain
78
+ * `http`, which this WebView refuses (App Transport Security + CORS), so the
79
+ * request must not be made from here. Null on fetch failure / no credential,
80
+ * the same one-round-trip shape as {@link getSubscriptionQuota}.
81
+ */
82
+ getAiTokenUsage(): Promise<AiTokenUsage | null>
74
83
  /**
75
84
  * Open the subscription landing page (`gen.eda.cn/subscription` with the
76
85
  * token). Host mode: ask the EDA host to open its NATIVE dialog through
@@ -238,6 +247,13 @@ export function createAuthClient(deps: AuthClientDeps): AuthClient {
238
247
  if (!token || !id) return null
239
248
  return fetchSubscriptionQuota({ userId: id, token, productCode })
240
249
  },
250
+ getAiTokenUsage: async (): Promise<AiTokenUsage | null> => {
251
+ if (hostMode && !hostSessionLoaded) await resolveHost()
252
+ // Gate on a credential first: the node route resolves the token itself,
253
+ // so a request without one is a guaranteed-null round trip.
254
+ if (!(await auth.getAccessToken())) return null
255
+ return transport.fetchAiUsage()
256
+ },
241
257
  openSubscriptionDialog: async (): Promise<void> => {
242
258
  if (hostMode && !hostSessionLoaded) await resolveHost()
243
259
  const token = await auth.getAccessToken()
@@ -44,6 +44,14 @@ const zh = {
44
44
  'subscription.quotaHeader': '套餐与使用额度',
45
45
  'subscription.upgrade': '订阅 / 升级套餐',
46
46
  'subscription.online': '在线',
47
+ // AI token usage (`/user-rest/api/ai/usage`) — the third metric beside GEN
48
+ // and ERC. `aiUsageCount` is the used/total point balance;
49
+ // `aiUsagePercent` is the hover detail, because the bar itself only shows
50
+ // the ratio visually.
51
+ 'subscription.ai': 'AI 用量',
52
+ 'subscription.aiUsageCount': '{used} / {total} 点',
53
+ 'subscription.aiUsagePercent': '已使用 {percent}%',
54
+ 'subscription.aiUsageUnknown': '暂无数据',
47
55
 
48
56
  'card.title': '华秋 EDA AI(eda.cn)登录',
49
57
  'card.desc': '工具「{tool}」需要登录华秋 EDA AI 账号才能继续。请在下方的登录框完成登录(或点击左侧「华秋EDA AI登录」按钮);登录完成后,回复助手「已登录,请重试」,助手会自动重新调用该工具。',
@@ -88,6 +96,14 @@ const en: Record<AuthCopyKey, string> = {
88
96
  'subscription.quotaHeader': 'Plan & usage quota',
89
97
  'subscription.upgrade': 'Subscribe / Upgrade plan',
90
98
  'subscription.online': 'Online',
99
+ // AI token usage (`/user-rest/api/ai/usage`) — the third metric beside GEN
100
+ // and ERC. `aiUsageCount` is the used/total point balance;
101
+ // `aiUsagePercent` is the hover detail, because the bar itself only shows
102
+ // the ratio visually.
103
+ 'subscription.ai': 'AI usage',
104
+ 'subscription.aiUsageCount': '{used} / {total} pts',
105
+ 'subscription.aiUsagePercent': '{percent}% used',
106
+ 'subscription.aiUsageUnknown': 'No data',
91
107
 
92
108
  'card.title': 'Huaqiu EDA AI (eda.cn) login',
93
109
  // The reply phrase used to be hardcoded to the Chinese "已登录,请重试" even
package/src/client/lib.ts CHANGED
@@ -48,6 +48,37 @@ export const SUBSCRIPTION_PREFERRED_SIZE = { width: 1400, height: 740 } as const
48
48
  export const GEN_PRODUCT_CODE = 'auto-design'
49
49
  export const ERC_PRODUCT_CODE = 'erc'
50
50
 
51
+ // ── AI token usage ──────────────────────────────────────────────────────────
52
+
53
+ /**
54
+ * Normalized AI token usage — the shape the node half's `/ai-usage` route
55
+ * returns (the node half owns the upstream call; see
56
+ * `routes.ts#fetchAiTokenUsage`).
57
+ *
58
+ * `points` is the account-level token balance (what the user thinks of as
59
+ * "tokens"); `quota` is the same figure in the gateway's internal unit
60
+ * (points × 50) and `usd` its money equivalent. All three pairs are reported
61
+ * because the endpoint reports all three; the UI reads `points`.
62
+ *
63
+ * WHY THE BROWSER NEVER CALLS THIS ENDPOINT DIRECTLY: it is served over plain
64
+ * `http` (`http://www.fdatasheets.com/user-rest/api/ai/usage`), which the
65
+ * WebView refuses twice over — App Transport Security ("the resource could not
66
+ * be loaded because the App Transport Security policy requires the use of a
67
+ * secure connection") and CORS (the response carries no
68
+ * `Access-Control-Allow-Origin`). The node half has neither restriction — it is
69
+ * the same process that already calls this host for the Huaqiu AI gateway — so
70
+ * IT performs the fetch and this half reads a same-origin route, exactly like
71
+ * the eda.cn profile on `/user-info`.
72
+ */
73
+ export interface AiTokenUsage {
74
+ availablePoints: number
75
+ availableQuota: number
76
+ availableUsd: number
77
+ usedPoints: number
78
+ usedQuota: number
79
+ usedUsd: number
80
+ }
81
+
51
82
  /**
52
83
  * Build the subscription landing URL. Mirrors `buildProfileUrl`: the token is
53
84
  * always attached — `gen.eda.cn/subscription` consumes it to establish the
@@ -4,7 +4,7 @@
4
4
  * browser→host channel — `apiProxy`'s dispatch table is closed, so a
5
5
  * plugin-owned `webServer` route is the smallest supported extension point.
6
6
  */
7
- import type { AuthTokenPayload } from './lib.js'
7
+ import type { AiTokenUsage, AuthTokenPayload } from './lib.js'
8
8
 
9
9
  export interface AuthTransport {
10
10
  pushSession(info: AuthTokenPayload): Promise<void>
@@ -37,6 +37,15 @@ export interface AuthTransport {
37
37
  * carries only {token, userId} — e.g. host mode under kicad.
38
38
  */
39
39
  fetchUserInfo(): Promise<EdaUserProfile | null>
40
+ /**
41
+ * Fetch the account's AI token usage from the NODE half (`/ai-usage`), which
42
+ * performs the upstream `GET http://www.fdatasheets.com/user-rest/api/ai/usage`
43
+ * with the `X-Token` header. This half must NOT call that endpoint itself: it
44
+ * is plain `http`, which the WebView refuses on two independent grounds — App
45
+ * Transport Security and CORS — and the failures are what the browser console
46
+ * reports as a blocked resource. Null on failure (the sidebar shows「—」).
47
+ */
48
+ fetchAiUsage(): Promise<AiTokenUsage | null>
40
49
  }
41
50
 
42
51
  /** Minimal session user shape returned by the node `/session` route. */
@@ -123,5 +132,18 @@ export function createWebServerAuthTransport(
123
132
  return null
124
133
  }
125
134
  },
135
+ async fetchAiUsage() {
136
+ try {
137
+ const res = await doFetch(`${base}/ai-usage`, {
138
+ method: 'GET',
139
+ headers: { accept: 'application/json' },
140
+ })
141
+ if (!res.ok) return null
142
+ const body = await res.json() as { usage?: AiTokenUsage | null }
143
+ return body.usage ?? null
144
+ } catch {
145
+ return null
146
+ }
147
+ },
126
148
  }
127
149
  }
@@ -26,9 +26,9 @@
26
26
  import { memo, useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore, type CSSProperties } from 'react'
27
27
  import { createPortal } from 'react-dom'
28
28
  import { getAuth, getAuthState, getHqEdge, setProfile, subscribeAuth } from '../auth-state.js'
29
- import { buildProfileUrl, ERC_PRODUCT_CODE, GEN_PRODUCT_CODE, type SubscriptionQuota } from '../lib.js'
29
+ import { buildProfileUrl, ERC_PRODUCT_CODE, GEN_PRODUCT_CODE, type AiTokenUsage, type SubscriptionQuota } from '../lib.js'
30
30
  import { useIsDark, useLocale } from '../ui-env.js'
31
- import { useT } from '../i18n.js'
31
+ import { useT, type Translate } from '../i18n.js'
32
32
  import { HQ_ICON } from './hq-icon.jsx'
33
33
 
34
34
  export interface SidebarFooterActionOwnerProps {
@@ -63,9 +63,10 @@ interface Palette {
63
63
  primarySoft: string
64
64
  /** Progress-bar track (prototype `dark:bg-gray-800`). */
65
65
  track: string
66
- /** GEN / ERC progress gradients (prototype blue→indigo, purple→pink). */
66
+ /** GEN / ERC / AI progress gradients (prototype blue→indigo, purple→pink). */
67
67
  genGradient: string
68
68
  ercGradient: string
69
+ aiGradient: string
69
70
  /** "Online" dot green. */
70
71
  online: string
71
72
  }
@@ -90,6 +91,7 @@ const LIGHT_PALETTE: Palette = {
90
91
  track: '#e4e7ec',
91
92
  genGradient: 'linear-gradient(90deg, #3b82f6, #6366f1)',
92
93
  ercGradient: 'linear-gradient(90deg, #a855f7, #ec4899)',
94
+ aiGradient: 'linear-gradient(90deg, #10b981, #06b6d4)',
93
95
  online: '#10b981',
94
96
  }
95
97
 
@@ -113,6 +115,7 @@ const DARK_PALETTE: Palette = {
113
115
  track: 'rgba(255, 255, 255, 0.10)',
114
116
  genGradient: 'linear-gradient(90deg, #3b82f6, #6366f1)',
115
117
  ercGradient: 'linear-gradient(90deg, #a855f7, #ec4899)',
118
+ aiGradient: 'linear-gradient(90deg, #10b981, #06b6d4)',
116
119
  online: '#10b981',
117
120
  }
118
121
 
@@ -349,34 +352,63 @@ function ChevronRightIcon(): React.JSX.Element {
349
352
  )
350
353
  }
351
354
 
355
+ /** AI usage metric glyph (lucide `sparkles`) — the token balance. */
356
+ function SparklesIcon(): React.JSX.Element {
357
+ return (
358
+ <svg
359
+ xmlns="http://www.w3.org/2000/svg"
360
+ width={14}
361
+ height={14}
362
+ viewBox="0 0 24 24"
363
+ fill="none"
364
+ stroke="#10b981"
365
+ strokeWidth={2}
366
+ strokeLinecap="round"
367
+ strokeLinejoin="round"
368
+ aria-hidden
369
+ style={{ flex: '0 0 auto' }}
370
+ >
371
+ <path d="M12 3l1.9 5.1L19 10l-5.1 1.9L12 17l-1.9-5.1L5 10l5.1-1.9L12 3z" />
372
+ <path d="M19 15l.9 2.1L22 18l-2.1.9L19 21l-.9-2.1L16 18l2.1-.9L19 15z" />
373
+ </svg>
374
+ )
375
+ }
376
+
377
+ /**
378
+ * One normalized metric reading — everything {@link QuotaMetric} renders.
379
+ *
380
+ * The card itself knows nothing about where a reading comes from, so GEN, ERC
381
+ * and the AI token balance are three small pure adapters over the same
382
+ * presentational component (and each is unit-testable without a DOM).
383
+ */
384
+ interface MetricReading {
385
+ /** Right-aligned mono text (already localized and formatted). */
386
+ value: string
387
+ /** Hover detail; defaults to `value`. */
388
+ title?: string
389
+ /** Bar fill, 0–100. Fractional is allowed (sub-1% usage is normal for tokens). */
390
+ percent: number
391
+ /** false → the value renders in the danger color (unsubscribed / no data). */
392
+ ok: boolean
393
+ }
394
+
352
395
  /** Quota metric card: icon + label, mono count and a gradient progress bar. */
353
396
  function QuotaMetric({
354
397
  label,
355
398
  icon,
356
- quota,
399
+ reading,
357
400
  gradient,
358
401
  palette,
359
402
  }: {
360
403
  label: string
361
404
  icon: React.JSX.Element
362
- quota: SubscriptionQuota | null
405
+ reading: MetricReading | null
363
406
  gradient: string
364
407
  palette: Palette
365
408
  }): React.JSX.Element {
366
409
  const t = useT()
367
410
  const [hovered, setHovered] = useState(false)
368
- const used = quota?.currentQuota
369
- const total = quota?.totalQuota
370
- const percent = quota?.hasSubscription && typeof total === 'number' && total > 0
371
- ? Math.max(0, Math.min(100, Math.round(((used ?? 0) / total) * 100)))
372
- : 0
373
- const value = quota
374
- ? (quota.hasSubscription
375
- ? (typeof total === 'number'
376
- ? t('subscription.quotaCount', { used: used ?? 0, total })
377
- : String(used ?? 0))
378
- : t('subscription.unsubscribed'))
379
- : '—'
411
+ const value = reading?.value ?? '—'
380
412
  return (
381
413
  <div
382
414
  role="presentation"
@@ -399,24 +431,73 @@ function QuotaMetric({
399
431
  <span
400
432
  style={{
401
433
  fontWeight: 700,
402
- color: quota?.hasSubscription ? palette.text : palette.danger,
434
+ color: reading?.ok ? palette.text : palette.danger,
403
435
  fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',
404
436
  fontSize: 12,
405
437
  whiteSpace: 'nowrap',
406
438
  flexShrink: 0,
407
439
  }}
408
- title={value}
440
+ title={reading?.title ?? value}
409
441
  >
410
442
  {value}
411
443
  </span>
412
444
  </div>
413
445
  <div style={{ width: '100%', height: 6, borderRadius: 999, background: palette.track, overflow: 'hidden' }}>
414
- <div style={{ width: `${percent}%`, height: '100%', borderRadius: 999, background: gradient }} />
446
+ <div style={{ width: `${reading?.percent ?? 0}%`, height: '100%', borderRadius: 999, background: gradient }} />
415
447
  </div>
416
448
  </div>
417
449
  )
418
450
  }
419
451
 
452
+ /**
453
+ * GEN / ERC reading from an eda.cn active-subscription payload.
454
+ *
455
+ * `hasSubscription` false (or an unknown total) is NOT an error: it is an
456
+ * account with no plan, which reads as 0% plus the "not subscribed" copy in
457
+ * the danger color.
458
+ */
459
+ export function quotaReading(quota: SubscriptionQuota | null, t: Translate): MetricReading | null {
460
+ if (!quota) return null
461
+ const used = quota.currentQuota
462
+ const total = quota.totalQuota
463
+ const percent = quota.hasSubscription && typeof total === 'number' && total > 0
464
+ ? Math.max(0, Math.min(100, Math.round((used / total) * 100)))
465
+ : 0
466
+ return {
467
+ value: quota.hasSubscription
468
+ ? (typeof total === 'number'
469
+ ? t('subscription.quotaCount', { used, total })
470
+ : String(used))
471
+ : t('subscription.unsubscribed'),
472
+ percent,
473
+ ok: quota.hasSubscription,
474
+ }
475
+ }
476
+
477
+ /**
478
+ * AI token reading from `/user-rest/api/ai/usage`.
479
+ *
480
+ * The balance is reported as `usedPoints` + `availablePoints`, so the total is
481
+ * their sum — there is no separate `totalPoints` field to read. Percent keeps
482
+ * one decimal: a fresh account burns well under 1% of its balance, and rounding
483
+ * 0.6% up to "1%" would overstate consumption fourfold.
484
+ */
485
+ export function aiUsageReading(usage: AiTokenUsage | null, t: Translate): MetricReading | null {
486
+ if (!usage) return null
487
+ const used = Math.max(0, usage.usedPoints)
488
+ const available = Math.max(0, usage.availablePoints)
489
+ const total = used + available
490
+ const percent = total > 0
491
+ ? Math.min(100, Math.round((used / total) * 1000) / 10)
492
+ : 0
493
+ return {
494
+ value: t('subscription.aiUsageCount', { used, total }),
495
+ title: t('subscription.aiUsagePercent', { percent }),
496
+ percent,
497
+ ok: true,
498
+ }
499
+ }
500
+
420
501
  /**
421
502
  * Profile header card (prototype): name + plan badge + phone line on the
422
503
  * left, an "online" pill on the right. No redundant avatar — the trigger
@@ -578,7 +659,7 @@ export const HuaqiuAuthSidebarAction = memo(function HuaqiuAuthSidebarAction({ w
578
659
  const [menuStyle, setMenuStyle] = useState<CSSProperties | null>(null)
579
660
  const [avatarBroken, setAvatarBroken] = useState(false)
580
661
  const [hovered, setHovered] = useState(false)
581
- const [quota, setQuota] = useState<{ gen: SubscriptionQuota | null; erc: SubscriptionQuota | null } | null>(null)
662
+ const [quota, setQuota] = useState<{ gen: SubscriptionQuota | null; erc: SubscriptionQuota | null; ai: AiTokenUsage | null } | null>(null)
582
663
  const [subscribing, setSubscribing] = useState(false)
583
664
  const triggerRef = useRef<HTMLButtonElement | null>(null)
584
665
  const menuRef = useRef<HTMLDivElement | null>(null)
@@ -635,7 +716,10 @@ export const HuaqiuAuthSidebarAction = memo(function HuaqiuAuthSidebarAction({ w
635
716
 
636
717
  // Live quota: EVERY time the menu opens (and every time the auth state
637
718
  // flips to authenticated) re-fetch the active subscription for GEN and ERC
638
- // DIRECTLY from eda.cn — the sidebar must never show a stale count.
719
+ // DIRECTLY from eda.cn — the sidebar must never show a stale count. The AI
720
+ // token balance rides the same pass (`/user-rest/api/ai/usage`, one GET, no
721
+ // hq-edge hop), so all three metrics share one loading window instead of
722
+ // three staggered ones.
639
723
  useEffect(() => {
640
724
  if (!menuOpen || !authenticated) {
641
725
  if (!menuOpen) setQuota(null)
@@ -645,8 +729,9 @@ export const HuaqiuAuthSidebarAction = memo(function HuaqiuAuthSidebarAction({ w
645
729
  void Promise.all([
646
730
  auth?.getSubscriptionQuota?.(GEN_PRODUCT_CODE).catch(() => null) ?? Promise.resolve(null),
647
731
  auth?.getSubscriptionQuota?.(ERC_PRODUCT_CODE).catch(() => null) ?? Promise.resolve(null),
648
- ]).then(([gen, erc]) => {
649
- if (!cancelled) setQuota({ gen, erc })
732
+ auth?.getAiTokenUsage?.().catch(() => null) ?? Promise.resolve(null),
733
+ ]).then(([gen, erc, ai]) => {
734
+ if (!cancelled) setQuota({ gen, erc, ai })
650
735
  })
651
736
  return () => { cancelled = true }
652
737
  // eslint-disable-next-line react-hooks/exhaustive-deps
@@ -822,17 +907,24 @@ export const HuaqiuAuthSidebarAction = memo(function HuaqiuAuthSidebarAction({ w
822
907
  <QuotaMetric
823
908
  label={t('subscription.gen')}
824
909
  icon={<CpuIcon />}
825
- quota={quota?.gen ?? null}
910
+ reading={quotaReading(quota?.gen ?? null, t)}
826
911
  gradient={palette.genGradient}
827
912
  palette={palette}
828
913
  />
829
914
  <QuotaMetric
830
915
  label={t('subscription.erc')}
831
916
  icon={<WaveIcon />}
832
- quota={quota?.erc ?? null}
917
+ reading={quotaReading(quota?.erc ?? null, t)}
833
918
  gradient={palette.ercGradient}
834
919
  palette={palette}
835
920
  />
921
+ <QuotaMetric
922
+ label={t('subscription.ai')}
923
+ icon={<SparklesIcon />}
924
+ reading={aiUsageReading(quota?.ai ?? null, t)}
925
+ gradient={palette.aiGradient}
926
+ palette={palette}
927
+ />
836
928
  </div>
837
929
  <UpgradeButton
838
930
  subscribing={subscribing}
package/src/routes.ts CHANGED
@@ -6,6 +6,8 @@
6
6
  * POST /api/v1/huaqiu/auth/logout → cache cleared
7
7
  * GET /api/v1/huaqiu/auth/session → { authenticated, user }
8
8
  * GET /api/v1/huaqiu/auth/config → { hostMode }
9
+ * GET /api/v1/huaqiu/auth/user-info → { userInfo } (node-side eda.cn call)
10
+ * GET /api/v1/huaqiu/auth/ai-usage → { usage } (node-side AI balance call)
9
11
  *
10
12
  * `config` tells the browser half whether it is running under an HQ Edge host
11
13
  * (hq-edge passes the operator credential to hq-edge itself, so the sidebar
@@ -73,6 +75,85 @@ export async function fetchEdaUserProfile(
73
75
 
74
76
  export const AUTH_ROUTE_PREFIX = '/api/v1/huaqiu/auth'
75
77
 
78
+ // ── AI token usage (proxied by the node half) ────────────────────────────────
79
+
80
+ /**
81
+ * The account's AI balance endpoint.
82
+ *
83
+ * It is served over PLAIN `http`, which is why the node half must be the one to
84
+ * call it: a WebView fetch is refused by App Transport Security ("the resource
85
+ * could not be loaded because the App Transport Security policy requires the
86
+ * use of a secure connection") and, independently, by CORS (the response sends
87
+ * no `Access-Control-Allow-Origin`). Node's fetch is subject to neither, and
88
+ * this process already talks to this very host for the Huaqiu AI gateway
89
+ * (`http://www.fdatasheets.com/user-rest/ai/v1`, see hq-edge's
90
+ * `HUAQIU_AI_GATEWAY_BASE_URL`) — so the call is known to work from here.
91
+ */
92
+ export const AI_USAGE_URL = 'http://www.fdatasheets.com/user-rest/api/ai/usage'
93
+
94
+ /**
95
+ * Normalized AI token usage — the `/user-rest/api/ai/usage` result.
96
+ *
97
+ * `points` is the account-level token balance (what the user thinks of as
98
+ * "tokens"); `quota` is the same figure in the gateway's internal unit
99
+ * (points × 50) and `usd` its money equivalent. All three pairs are reported
100
+ * because the endpoint reports all three; the UI reads `points`.
101
+ *
102
+ * (Mirrored as a type-only declaration in `client/lib.ts` — the browser half
103
+ * must not import node modules, and the two halves are built as separate
104
+ * bundles.)
105
+ */
106
+ export interface AiTokenUsage {
107
+ availablePoints: number
108
+ availableQuota: number
109
+ availableUsd: number
110
+ usedPoints: number
111
+ usedQuota: number
112
+ usedUsd: number
113
+ }
114
+
115
+ /**
116
+ * Fetch the account's AI token usage for a token. Null on any failure (the UI
117
+ * degrades to「—」) — never throws.
118
+ *
119
+ * The header is `X-Token` (capital T), which is what this endpoint expects; the
120
+ * subscription endpoint next door uses `x-token` + `X-User-Id`.
121
+ */
122
+ export async function fetchAiTokenUsage(
123
+ token: string,
124
+ doFetch: typeof fetch = globalThis.fetch.bind(globalThis),
125
+ ): Promise<AiTokenUsage | null> {
126
+ try {
127
+ const res = await doFetch(AI_USAGE_URL, {
128
+ method: 'GET',
129
+ headers: {
130
+ Accept: 'application/json, text/plain, */*',
131
+ 'Content-Type': 'application/json',
132
+ 'X-Token': token,
133
+ },
134
+ })
135
+ if (!res.ok) return null
136
+ const body = (await res.json()) as { code?: number; result?: Record<string, unknown> }
137
+ if (body.code !== 200000 || !body.result) return null
138
+ const result = body.result
139
+ const num = (key: string): number => {
140
+ const v = Number(result[key])
141
+ return Number.isFinite(v) ? v : 0
142
+ }
143
+ return {
144
+ availablePoints: num('availablePoints'),
145
+ availableQuota: num('availableQuota'),
146
+ availableUsd: num('availableUsd'),
147
+ usedPoints: num('usedPoints'),
148
+ usedQuota: num('usedQuota'),
149
+ usedUsd: num('usedUsd'),
150
+ }
151
+ } catch (err) {
152
+ log().warn('fetchAiTokenUsage failed', { error: String((err as Error)?.message || err) })
153
+ return null
154
+ }
155
+ }
156
+
76
157
  export type AuthHandler = (req: IncomingMessage, res: ServerResponse) => Promise<void> | void
77
158
 
78
159
  function sendJson(res: ServerResponse, status: number, body: unknown): void {
@@ -165,6 +246,20 @@ export function createAuthHandler(service: HuaqiuAuthService): AuthHandler {
165
246
  return
166
247
  }
167
248
 
249
+ if (req.method === 'GET' && pathname === `${AUTH_ROUTE_PREFIX}/ai-usage`) {
250
+ // The WebView CANNOT reach this endpoint itself (plain http → ATS +
251
+ // CORS, see AI_USAGE_URL), so the node half performs the call with the
252
+ // credential IT resolved (host → pushed → persisted) — the same shape
253
+ // as /user-info above.
254
+ const token = await service.auth.getAccessToken()
255
+ if (!token) {
256
+ sendJson(res, 200, { usage: null })
257
+ return
258
+ }
259
+ sendJson(res, 200, { usage: await fetchAiTokenUsage(token) })
260
+ return
261
+ }
262
+
168
263
  if (req.method === 'POST' && pathname === `${AUTH_ROUTE_PREFIX}/login`) {
169
264
  // Host-mode login: forward to HQ Edge, which asks EDA (KiCad) to open
170
265
  // its TriggerLoginDialog. Blocks until the dialog is completed.