@huaqiu/dsh-auth 0.5.8 → 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/client.js +124 -27
- package/lib/client.js.map +1 -1
- package/lib/index.d.mts +14 -2
- package/lib/index.mjs +77 -8
- package/package.json +2 -2
- package/src/apiKeySync.ts +24 -3
- package/src/client/client.ts +16 -0
- package/src/client/i18n.ts +16 -0
- package/src/client/lib.ts +31 -0
- package/src/client/transport.ts +23 -1
- package/src/client/ui/sidebar-action.tsx +118 -26
- package/src/index.ts +15 -3
- package/src/routes.ts +95 -0
package/lib/index.d.mts
CHANGED
|
@@ -236,6 +236,18 @@ interface CredentialStore {
|
|
|
236
236
|
set(ref: string, value: string): Promise<void>;
|
|
237
237
|
unset(ref: string): Promise<void>;
|
|
238
238
|
}
|
|
239
|
+
/**
|
|
240
|
+
* Resolves the credential store lazily on every sync round.
|
|
241
|
+
*
|
|
242
|
+
* The DSH `credentials` service may not be activated yet when this plugin
|
|
243
|
+
* boots (service activation order), and direct `ctx.credentials` property
|
|
244
|
+
* access throws "cannot get property ... without inject" in that window.
|
|
245
|
+
* Resolving through `ctx.get('credentials')` per round returns `undefined`
|
|
246
|
+
* while the service is unavailable — the round is skipped and retried on the
|
|
247
|
+
* next poll, so the sync self-heals once the service activates, without a
|
|
248
|
+
* restart (cordis guidance: "switch to `ctx.get('x')` with an absence check").
|
|
249
|
+
*/
|
|
250
|
+
type CredentialStoreProvider = () => CredentialStore | null;
|
|
239
251
|
/** Logger surface used by the sync (kept small so tests can pass a spy). */
|
|
240
252
|
interface SyncLogger {
|
|
241
253
|
debug(msg: string, ctx?: Record<string, unknown>): void;
|
|
@@ -247,7 +259,7 @@ declare class HuaqiuApiKeySync {
|
|
|
247
259
|
readonly baseUrl: string;
|
|
248
260
|
/** Token path on the host; default "/api/v1/auth/token". */
|
|
249
261
|
readonly path: string;
|
|
250
|
-
private readonly
|
|
262
|
+
private readonly storeProvider;
|
|
251
263
|
private readonly log;
|
|
252
264
|
private readonly intervalMs;
|
|
253
265
|
private readonly doFetch;
|
|
@@ -260,7 +272,7 @@ declare class HuaqiuApiKeySync {
|
|
|
260
272
|
/** HQ Edge base URL ("" → disabled, matches HostSessionResolver.enabled). */
|
|
261
273
|
baseUrl: string,
|
|
262
274
|
/** Token path on the host; default "/api/v1/auth/token". */
|
|
263
|
-
path: string,
|
|
275
|
+
path: string, storeProvider: CredentialStoreProvider, log: SyncLogger, intervalMs?: number, doFetch?: typeof fetch);
|
|
264
276
|
/** Host-mode sync is active iff a base URL was configured. */
|
|
265
277
|
get enabled(): boolean;
|
|
266
278
|
/** Kick off an immediate sync, then poll on a non-overlapping interval. */
|
package/lib/index.mjs
CHANGED
|
@@ -205,7 +205,7 @@ const DEFAULT_HUAQIU_API_KEY_SYNC_MS = 5e3;
|
|
|
205
205
|
var HuaqiuApiKeySync = class {
|
|
206
206
|
baseUrl;
|
|
207
207
|
path;
|
|
208
|
-
|
|
208
|
+
storeProvider;
|
|
209
209
|
log;
|
|
210
210
|
intervalMs;
|
|
211
211
|
doFetch;
|
|
@@ -214,10 +214,10 @@ var HuaqiuApiKeySync = class {
|
|
|
214
214
|
inFlight = false;
|
|
215
215
|
/** Last token mirrored into the credential store (change detection). */
|
|
216
216
|
lastToken = null;
|
|
217
|
-
constructor(baseUrl, path,
|
|
217
|
+
constructor(baseUrl, path, storeProvider, log, intervalMs = DEFAULT_HUAQIU_API_KEY_SYNC_MS, doFetch = globalThis.fetch.bind(globalThis)) {
|
|
218
218
|
this.baseUrl = baseUrl;
|
|
219
219
|
this.path = path;
|
|
220
|
-
this.
|
|
220
|
+
this.storeProvider = storeProvider;
|
|
221
221
|
this.log = log;
|
|
222
222
|
this.intervalMs = intervalMs;
|
|
223
223
|
this.doFetch = doFetch;
|
|
@@ -249,6 +249,11 @@ var HuaqiuApiKeySync = class {
|
|
|
249
249
|
* rounds deterministically without timers.
|
|
250
250
|
*/
|
|
251
251
|
async syncNow() {
|
|
252
|
+
const store = this.storeProvider();
|
|
253
|
+
if (store === null) {
|
|
254
|
+
this.log.debug("huaqiu api-key sync skipped: credentials service unavailable");
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
252
257
|
const url = `${this.baseUrl}${this.path}`;
|
|
253
258
|
let res = null;
|
|
254
259
|
let info = null;
|
|
@@ -268,7 +273,7 @@ var HuaqiuApiKeySync = class {
|
|
|
268
273
|
if (info !== null && info.authenticated) {
|
|
269
274
|
if (info.token !== this.lastToken) {
|
|
270
275
|
this.lastToken = info.token;
|
|
271
|
-
await
|
|
276
|
+
await store.set(HUAQIU_API_KEY_REF, info.token);
|
|
272
277
|
this.log.info("huaqiu api-key credential synced", { userId: info.id });
|
|
273
278
|
}
|
|
274
279
|
return;
|
|
@@ -276,7 +281,7 @@ var HuaqiuApiKeySync = class {
|
|
|
276
281
|
if (res !== null && res.ok) {
|
|
277
282
|
if (this.lastToken !== null) {
|
|
278
283
|
this.lastToken = null;
|
|
279
|
-
await
|
|
284
|
+
await store.unset(HUAQIU_API_KEY_REF);
|
|
280
285
|
this.log.info("huaqiu api-key credential cleared", { explicit: true });
|
|
281
286
|
}
|
|
282
287
|
return;
|
|
@@ -757,6 +762,57 @@ async function fetchEdaUserProfile(token, doFetch = globalThis.fetch.bind(global
|
|
|
757
762
|
}
|
|
758
763
|
}
|
|
759
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
|
+
}
|
|
760
816
|
function sendJson(res, status, body) {
|
|
761
817
|
res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
|
|
762
818
|
res.end(JSON.stringify(body));
|
|
@@ -824,6 +880,15 @@ function createAuthHandler(service) {
|
|
|
824
880
|
sendJson(res, 200, { userInfo: await fetchEdaUserProfile(token) });
|
|
825
881
|
return;
|
|
826
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
|
+
}
|
|
827
892
|
if (req.method === "POST" && pathname === `/api/v1/huaqiu/auth/login`) {
|
|
828
893
|
await service.auth.login();
|
|
829
894
|
const user = await service.auth.getUserInfo();
|
|
@@ -871,9 +936,13 @@ function apply(ctx, config) {
|
|
|
871
936
|
}));
|
|
872
937
|
if (service.hostMode) ctx.effect(() => {
|
|
873
938
|
const resolved = resolveHostConfig(config);
|
|
874
|
-
const sync = new HuaqiuApiKeySync(resolved.hqEdgeBaseUrl ?? "", resolved.hostAuthPath ?? "/api/v1/auth/token", {
|
|
875
|
-
|
|
876
|
-
|
|
939
|
+
const sync = new HuaqiuApiKeySync(resolved.hqEdgeBaseUrl ?? "", resolved.hostAuthPath ?? "/api/v1/auth/token", () => {
|
|
940
|
+
const credentials = ctx.get("credentials");
|
|
941
|
+
if (credentials === void 0) return null;
|
|
942
|
+
return {
|
|
943
|
+
set: (ref, value) => credentials.set(ref, value),
|
|
944
|
+
unset: (ref) => credentials.unset(ref)
|
|
945
|
+
};
|
|
877
946
|
}, {
|
|
878
947
|
debug: (msg, ctx2) => log.debug(msg, ctx2),
|
|
879
948
|
info: (msg, ctx2) => log.info(msg, ctx2),
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@huaqiu/dsh-auth",
|
|
3
|
-
"version": "0.5.
|
|
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.
|
|
36
|
+
"@huaqiu/dsh-plugin-log": "0.5.21"
|
|
37
37
|
},
|
|
38
38
|
"files": [
|
|
39
39
|
"lib",
|
package/src/apiKeySync.ts
CHANGED
|
@@ -35,6 +35,19 @@ export interface CredentialStore {
|
|
|
35
35
|
unset(ref: string): Promise<void>
|
|
36
36
|
}
|
|
37
37
|
|
|
38
|
+
/**
|
|
39
|
+
* Resolves the credential store lazily on every sync round.
|
|
40
|
+
*
|
|
41
|
+
* The DSH `credentials` service may not be activated yet when this plugin
|
|
42
|
+
* boots (service activation order), and direct `ctx.credentials` property
|
|
43
|
+
* access throws "cannot get property ... without inject" in that window.
|
|
44
|
+
* Resolving through `ctx.get('credentials')` per round returns `undefined`
|
|
45
|
+
* while the service is unavailable — the round is skipped and retried on the
|
|
46
|
+
* next poll, so the sync self-heals once the service activates, without a
|
|
47
|
+
* restart (cordis guidance: "switch to `ctx.get('x')` with an absence check").
|
|
48
|
+
*/
|
|
49
|
+
export type CredentialStoreProvider = () => CredentialStore | null
|
|
50
|
+
|
|
38
51
|
/** Logger surface used by the sync (kept small so tests can pass a spy). */
|
|
39
52
|
export interface SyncLogger {
|
|
40
53
|
debug(msg: string, ctx?: Record<string, unknown>): void
|
|
@@ -54,7 +67,7 @@ export class HuaqiuApiKeySync {
|
|
|
54
67
|
readonly baseUrl: string,
|
|
55
68
|
/** Token path on the host; default "/api/v1/auth/token". */
|
|
56
69
|
readonly path: string,
|
|
57
|
-
private readonly
|
|
70
|
+
private readonly storeProvider: CredentialStoreProvider,
|
|
58
71
|
private readonly log: SyncLogger,
|
|
59
72
|
private readonly intervalMs: number = DEFAULT_HUAQIU_API_KEY_SYNC_MS,
|
|
60
73
|
private readonly doFetch: typeof fetch = globalThis.fetch.bind(globalThis),
|
|
@@ -91,6 +104,14 @@ export class HuaqiuApiKeySync {
|
|
|
91
104
|
* rounds deterministically without timers.
|
|
92
105
|
*/
|
|
93
106
|
async syncNow(): Promise<void> {
|
|
107
|
+
// Resolve the credential store lazily: the `credentials` service may not
|
|
108
|
+
// be activated yet while this plugin boots (activation order). Skipping
|
|
109
|
+
// the round is safe — the next poll retries once the service is live.
|
|
110
|
+
const store = this.storeProvider()
|
|
111
|
+
if (store === null) {
|
|
112
|
+
this.log.debug('huaqiu api-key sync skipped: credentials service unavailable')
|
|
113
|
+
return
|
|
114
|
+
}
|
|
94
115
|
const url = `${this.baseUrl}${this.path}`
|
|
95
116
|
let res: Response | null = null
|
|
96
117
|
let info: ResolvedHostUser | null = null
|
|
@@ -111,7 +132,7 @@ export class HuaqiuApiKeySync {
|
|
|
111
132
|
if (info !== null && info.authenticated) {
|
|
112
133
|
if (info.token !== this.lastToken) {
|
|
113
134
|
this.lastToken = info.token
|
|
114
|
-
await
|
|
135
|
+
await store.set(HUAQIU_API_KEY_REF, info.token)
|
|
115
136
|
this.log.info('huaqiu api-key credential synced', { userId: info.id })
|
|
116
137
|
}
|
|
117
138
|
return
|
|
@@ -123,7 +144,7 @@ export class HuaqiuApiKeySync {
|
|
|
123
144
|
if (res !== null && res.ok) {
|
|
124
145
|
if (this.lastToken !== null) {
|
|
125
146
|
this.lastToken = null
|
|
126
|
-
await
|
|
147
|
+
await store.unset(HUAQIU_API_KEY_REF)
|
|
127
148
|
this.log.info('huaqiu api-key credential cleared', { explicit: true })
|
|
128
149
|
}
|
|
129
150
|
return
|
package/src/client/client.ts
CHANGED
|
@@ -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()
|
package/src/client/i18n.ts
CHANGED
|
@@ -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
|
package/src/client/transport.ts
CHANGED
|
@@ -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
|
-
|
|
399
|
+
reading,
|
|
357
400
|
gradient,
|
|
358
401
|
palette,
|
|
359
402
|
}: {
|
|
360
403
|
label: string
|
|
361
404
|
icon: React.JSX.Element
|
|
362
|
-
|
|
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
|
|
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:
|
|
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
|
-
|
|
649
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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}
|