@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 +217 -43
- package/lib/client.js.map +1 -1
- package/lib/index.d.mts +18 -10
- package/lib/index.mjs +141 -36
- package/package.json +2 -2
- package/src/client/client.ts +63 -22
- package/src/client/i18n.ts +14 -10
- package/src/client/index.tsx +15 -3
- package/src/client/lib.ts +20 -27
- package/src/client/transport.ts +41 -14
- package/src/client/ui/sidebar-action.tsx +15 -33
- package/src/client/ui/turn-error-cta.tsx +165 -0
- package/src/host.ts +10 -6
- package/src/routes.ts +79 -59
- package/src/service.ts +32 -8
- package/src/subscription-balances.ts +122 -0
package/src/client/lib.ts
CHANGED
|
@@ -52,35 +52,23 @@ export const SUBSCRIPTION_PREFERRED_SIZE = { width: 1400, height: 740 } as const
|
|
|
52
52
|
export const GEN_PRODUCT_CODE = 'auto-design'
|
|
53
53
|
export const ERC_PRODUCT_CODE = 'erc'
|
|
54
54
|
|
|
55
|
-
// ── AI
|
|
55
|
+
// ── AI usage (subscription balances) ────────────────────────────────────────
|
|
56
56
|
|
|
57
57
|
/**
|
|
58
|
-
*
|
|
59
|
-
*
|
|
60
|
-
*
|
|
58
|
+
* Client-facing AI usage shape. Re-exported (type-only) from the single
|
|
59
|
+
* authoritative contract in `../subscription-balances.ts`; the browser half
|
|
60
|
+
* must not import node modules, and a type-only re-export adds no runtime
|
|
61
|
+
* code to this bundle.
|
|
61
62
|
*
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
* (points × 50) and `usd` its money equivalent. All three pairs are reported
|
|
65
|
-
* because the endpoint reports all three; the UI reads `points`.
|
|
66
|
-
*
|
|
67
|
-
* WHY THE BROWSER NEVER CALLS THIS ENDPOINT DIRECTLY: the TEST endpoint is
|
|
68
|
-
* served over plain `http`, which the WebView refuses twice over — App
|
|
63
|
+
* WHY THE BROWSER NEVER CALLS THE UPSTREAM ENDPOINT DIRECTLY: the TEST endpoint
|
|
64
|
+
* is served over plain `http`, which the WebView refuses twice over — App
|
|
69
65
|
* Transport Security ("the resource could not be loaded because the App
|
|
70
66
|
* Transport Security policy requires the use of a secure connection") and CORS
|
|
71
67
|
* (the response carries no `Access-Control-Allow-Origin`). The node half has
|
|
72
|
-
* neither restriction
|
|
73
|
-
* for the Huaqiu gateway — so IT performs the fetch and this half reads a
|
|
68
|
+
* neither restriction, so IT performs the fetch and this half reads a
|
|
74
69
|
* same-origin route, exactly like the eda.cn profile on `/user-info`.
|
|
75
70
|
*/
|
|
76
|
-
export
|
|
77
|
-
availablePoints: number
|
|
78
|
-
availableQuota: number
|
|
79
|
-
availableUsd: number
|
|
80
|
-
usedPoints: number
|
|
81
|
-
usedQuota: number
|
|
82
|
-
usedUsd: number
|
|
83
|
-
}
|
|
71
|
+
export type { AiUsage } from '../subscription-balances.js'
|
|
84
72
|
|
|
85
73
|
/**
|
|
86
74
|
* Build the subscription landing URL. Mirrors `buildProfileUrl`: the token is
|
|
@@ -132,11 +120,15 @@ function quotaOf(subscription: Record<string, unknown> | null | undefined): Subs
|
|
|
132
120
|
}
|
|
133
121
|
|
|
134
122
|
/**
|
|
135
|
-
* Fetch the active subscription quota
|
|
136
|
-
*
|
|
137
|
-
* `
|
|
138
|
-
*
|
|
139
|
-
*
|
|
123
|
+
* Fetch the active subscription quota (`GET {baseUrl}/sub-api/subscriptions/
|
|
124
|
+
* active?userId&productCode` with `x-token` + `X-User-Id` headers) — the same
|
|
125
|
+
* API `hq-eda-ai`'s `getActiveSubscription` and `hq-edge`'s ERC quota proxy
|
|
126
|
+
* call.
|
|
127
|
+
*
|
|
128
|
+
* `baseUrl` is the origin the node half derives from the resolved
|
|
129
|
+
* subscription-balances endpoint (`HQ_AI_ENV`), so this call follows the
|
|
130
|
+
* selected environment and DSH Auth never hardcodes a production host. No
|
|
131
|
+
* configured origin → null (the UI shows「—」).
|
|
140
132
|
*
|
|
141
133
|
* Returns null when the fetch/unwrap fails (callers decide fail-open vs
|
|
142
134
|
* fail-closed); a well-formed response always yields a `SubscriptionQuota`
|
|
@@ -149,7 +141,8 @@ export async function fetchSubscriptionQuota(options: {
|
|
|
149
141
|
baseUrl?: string
|
|
150
142
|
fetchImpl?: typeof fetch
|
|
151
143
|
}): Promise<SubscriptionQuota | null> {
|
|
152
|
-
const { userId, token, productCode, baseUrl
|
|
144
|
+
const { userId, token, productCode, baseUrl } = options
|
|
145
|
+
if (!baseUrl) return null
|
|
153
146
|
const fetchImpl = options.fetchImpl ?? fetch
|
|
154
147
|
const url = `${baseUrl}${SUB_API_PREFIX}/subscriptions/active?${new URLSearchParams({
|
|
155
148
|
userId: String(userId),
|
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 {
|
|
7
|
+
import type { AiUsage, AuthTokenPayload } from './lib.js'
|
|
8
8
|
|
|
9
9
|
export interface AuthTransport {
|
|
10
10
|
pushSession(info: AuthTokenPayload): Promise<void>
|
|
@@ -14,7 +14,9 @@ export interface AuthTransport {
|
|
|
14
14
|
* - `hostMode`: whether the plugin runs under an HQ Edge host (in host mode
|
|
15
15
|
* the browser half's own login UI is suppressed);
|
|
16
16
|
* - `subscriptionOrigin`: the SAME `HQ_AI_ENV`-resolved origin used for the
|
|
17
|
-
* subscription dialog (null → standalone PROD fallback)
|
|
17
|
+
* subscription dialog (null → standalone PROD fallback);
|
|
18
|
+
* - `subscriptionApiBaseUrl`: origin of the resolved balances API, used for
|
|
19
|
+
* the GEN/ERC active-subscription calls (null → quota unavailable).
|
|
18
20
|
*/
|
|
19
21
|
fetchRuntimeConfig(): Promise<AuthRuntimeConfig>
|
|
20
22
|
/**
|
|
@@ -40,15 +42,14 @@ export interface AuthTransport {
|
|
|
40
42
|
*/
|
|
41
43
|
fetchUserInfo(): Promise<EdaUserProfile | null>
|
|
42
44
|
/**
|
|
43
|
-
* Fetch the account's AI
|
|
44
|
-
* performs the upstream
|
|
45
|
-
* `HQ_AI_ENV`) with the `X-Token` header. This half must NOT call
|
|
46
|
-
* endpoint itself: the TEST endpoint is plain `http`, which the WebView
|
|
47
|
-
* refuses on two independent grounds — App Transport Security and CORS
|
|
48
|
-
* the failures are what the browser console reports as a blocked resource.
|
|
45
|
+
* Fetch the account's AI usage from the NODE half (`/ai-usage`), which
|
|
46
|
+
* performs the upstream subscription-balances call (endpoint resolved by HQ
|
|
47
|
+
* Edge from `HQ_AI_ENV`) with the `X-Token` header. This half must NOT call
|
|
48
|
+
* that endpoint itself: the TEST endpoint is plain `http`, which the WebView
|
|
49
|
+
* refuses on two independent grounds — App Transport Security and CORS.
|
|
49
50
|
* Null on failure (the sidebar shows「—」).
|
|
50
51
|
*/
|
|
51
|
-
fetchAiUsage(): Promise<
|
|
52
|
+
fetchAiUsage(): Promise<AiUsage | null>
|
|
52
53
|
}
|
|
53
54
|
|
|
54
55
|
/** Minimal session user shape returned by the node `/session` route. */
|
|
@@ -64,6 +65,8 @@ export interface AuthRuntimeConfig {
|
|
|
64
65
|
hostMode: boolean
|
|
65
66
|
/** Absolute http(s) origin; null = standalone (client keeps its default). */
|
|
66
67
|
subscriptionOrigin: string | null
|
|
68
|
+
/** Origin for GEN/ERC quota calls; null = no environment configured. */
|
|
69
|
+
subscriptionApiBaseUrl: string | null
|
|
67
70
|
}
|
|
68
71
|
|
|
69
72
|
/** Accept only an absolute http(s) origin; anything else → null. */
|
|
@@ -80,6 +83,15 @@ function normalizeOrigin(value: unknown): string | null {
|
|
|
80
83
|
}
|
|
81
84
|
}
|
|
82
85
|
|
|
86
|
+
/** Accept only a finite `quotaRemainPercent`; anything else → unavailable. */
|
|
87
|
+
function normalizeUsage(value: unknown): AiUsage | null {
|
|
88
|
+
if (value === null || typeof value !== 'object') return null
|
|
89
|
+
const percent = (value as { quotaRemainPercent?: unknown }).quotaRemainPercent
|
|
90
|
+
return typeof percent === 'number' && Number.isFinite(percent)
|
|
91
|
+
? { quotaRemainPercent: percent }
|
|
92
|
+
: null
|
|
93
|
+
}
|
|
94
|
+
|
|
83
95
|
/** Rich eda.cn profile served by the node `/user-info` route. */
|
|
84
96
|
export interface EdaUserProfile {
|
|
85
97
|
nickname?: string
|
|
@@ -116,17 +128,32 @@ export function createWebServerAuthTransport(
|
|
|
116
128
|
method: 'GET',
|
|
117
129
|
headers: { accept: 'application/json' },
|
|
118
130
|
})
|
|
119
|
-
if (!res.ok)
|
|
120
|
-
|
|
131
|
+
if (!res.ok) {
|
|
132
|
+
return {
|
|
133
|
+
hostMode: false,
|
|
134
|
+
subscriptionOrigin: null,
|
|
135
|
+
subscriptionApiBaseUrl: null,
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
const body = await res.json() as {
|
|
139
|
+
hostMode?: unknown
|
|
140
|
+
subscriptionOrigin?: unknown
|
|
141
|
+
subscriptionApiBaseUrl?: unknown
|
|
142
|
+
}
|
|
121
143
|
return {
|
|
122
144
|
hostMode: body.hostMode === true,
|
|
123
145
|
subscriptionOrigin: normalizeOrigin(body.subscriptionOrigin),
|
|
146
|
+
subscriptionApiBaseUrl: normalizeOrigin(body.subscriptionApiBaseUrl),
|
|
124
147
|
}
|
|
125
148
|
} catch {
|
|
126
149
|
// Offline/same-origin failure: fall back to standalone (show the login
|
|
127
150
|
// entrypoint) rather than hiding it — a login UI is never a security
|
|
128
151
|
// regression, but a missing one in standalone would lock the user out.
|
|
129
|
-
return {
|
|
152
|
+
return {
|
|
153
|
+
hostMode: false,
|
|
154
|
+
subscriptionOrigin: null,
|
|
155
|
+
subscriptionApiBaseUrl: null,
|
|
156
|
+
}
|
|
130
157
|
}
|
|
131
158
|
},
|
|
132
159
|
async fetchSession() {
|
|
@@ -166,8 +193,8 @@ export function createWebServerAuthTransport(
|
|
|
166
193
|
headers: { accept: 'application/json' },
|
|
167
194
|
})
|
|
168
195
|
if (!res.ok) return null
|
|
169
|
-
const body = await res.json() as { usage?:
|
|
170
|
-
return body.usage
|
|
196
|
+
const body = await res.json() as { usage?: unknown }
|
|
197
|
+
return normalizeUsage(body.usage)
|
|
171
198
|
} catch {
|
|
172
199
|
return null
|
|
173
200
|
}
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
import { memo, useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore, type CSSProperties } from 'react'
|
|
31
31
|
import { createPortal } from 'react-dom'
|
|
32
32
|
import { getAuth, getAuthState, getHqEdge, setProfile, subscribeAuth } from '../auth-state.js'
|
|
33
|
-
import { buildProfileUrl, ERC_PRODUCT_CODE, GEN_PRODUCT_CODE, type
|
|
33
|
+
import { buildProfileUrl, ERC_PRODUCT_CODE, GEN_PRODUCT_CODE, type AiUsage, type SubscriptionQuota } from '../lib.js'
|
|
34
34
|
import { useIsDark, useLocale } from '../ui-env.js'
|
|
35
35
|
import { useT, type Translate } from '../i18n.js'
|
|
36
36
|
import { HQ_ICON } from './hq-icon.jsx'
|
|
@@ -546,36 +546,19 @@ export function quotaReading(quota: SubscriptionQuota | null, t: Translate): Met
|
|
|
546
546
|
}
|
|
547
547
|
|
|
548
548
|
/**
|
|
549
|
-
* AI
|
|
549
|
+
* AI reading from the subscription-balances AI Points group.
|
|
550
550
|
*
|
|
551
|
-
* The
|
|
552
|
-
*
|
|
553
|
-
* `
|
|
554
|
-
*
|
|
555
|
-
* `usedPoints` here made the AI card the only surface in the product that
|
|
556
|
-
* reported consumption as the balance: an account that burned 77 of its 100
|
|
557
|
-
* points read "77 / 100 pts" where the user expects "23 / 100 pts".
|
|
558
|
-
*
|
|
559
|
-
* The balance is reported as `usedPoints` + `availablePoints`, so the total is
|
|
560
|
-
* their sum — there is no separate `totalPoints` field to read. Percent keeps
|
|
561
|
-
* one decimal: a fresh account has well over 99% of its balance left, and
|
|
562
|
-
* rounding 99.6% up to "100%" would read as an exhausted account.
|
|
551
|
+
* The percentage is the upstream `quotaRemainPercent` — the REMAINING share —
|
|
552
|
+
* passed through unchanged: no local ratio and no re-rounding, so `99.68`
|
|
553
|
+
* renders as `99.68%`. A missing / `null` / non-finite value is unavailable
|
|
554
|
+
* (the card shows「—」); the bar clamps to 0–100 while the label does not.
|
|
563
555
|
*/
|
|
564
|
-
export function aiUsageReading(usage:
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
const available = Math.max(0, usage.availablePoints)
|
|
568
|
-
const total = used + available
|
|
569
|
-
const percent = total > 0
|
|
570
|
-
? Math.min(100, Math.round((available / total) * 1000) / 10)
|
|
571
|
-
: 0
|
|
572
|
-
// Headline shows the usage percent (e.g. "65%"); the exact
|
|
573
|
-
// "{available} / {total} pts" balance is preserved as the hover title.
|
|
574
|
-
const displayPercent = Math.round(percent)
|
|
556
|
+
export function aiUsageReading(usage: AiUsage | null, t: Translate): MetricReading | null {
|
|
557
|
+
const percent = usage?.quotaRemainPercent
|
|
558
|
+
if (typeof percent !== 'number' || !Number.isFinite(percent)) return null
|
|
575
559
|
return {
|
|
576
|
-
value: t('subscription.aiUsagePercent', { percent
|
|
577
|
-
|
|
578
|
-
percent,
|
|
560
|
+
value: t('subscription.aiUsagePercent', { percent }),
|
|
561
|
+
percent: Math.max(0, Math.min(100, percent)),
|
|
579
562
|
ok: true,
|
|
580
563
|
}
|
|
581
564
|
}
|
|
@@ -739,7 +722,7 @@ export const HuaqiuAuthSidebarAction = memo(function HuaqiuAuthSidebarAction({ w
|
|
|
739
722
|
const [menuStyle, setMenuStyle] = useState<CSSProperties | null>(null)
|
|
740
723
|
const [avatarBroken, setAvatarBroken] = useState(false)
|
|
741
724
|
const [hovered, setHovered] = useState(false)
|
|
742
|
-
const [quota, setQuota] = useState<{ gen: SubscriptionQuota | null; erc: SubscriptionQuota | null; ai:
|
|
725
|
+
const [quota, setQuota] = useState<{ gen: SubscriptionQuota | null; erc: SubscriptionQuota | null; ai: AiUsage | null } | null>(null)
|
|
743
726
|
const [subscribing, setSubscribing] = useState(false)
|
|
744
727
|
const triggerRef = useRef<HTMLButtonElement | null>(null)
|
|
745
728
|
const menuRef = useRef<HTMLDivElement | null>(null)
|
|
@@ -796,10 +779,9 @@ export const HuaqiuAuthSidebarAction = memo(function HuaqiuAuthSidebarAction({ w
|
|
|
796
779
|
|
|
797
780
|
// Live quota: EVERY time the menu opens (and every time the auth state
|
|
798
781
|
// flips to authenticated) re-fetch the active subscription for GEN and ERC
|
|
799
|
-
//
|
|
800
|
-
//
|
|
801
|
-
//
|
|
802
|
-
// three staggered ones.
|
|
782
|
+
// from the environment's subscription API, and the AI percentage from the
|
|
783
|
+
// node-proxied subscription balances. All three share one loading window
|
|
784
|
+
// instead of three staggered ones.
|
|
803
785
|
useEffect(() => {
|
|
804
786
|
if (!menuOpen || !authenticated) {
|
|
805
787
|
if (!menuOpen) setQuota(null)
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `conversation.chat.turn-error.action` entry: a subscription button inside
|
|
3
|
+
* the Chat terminal-failure card.
|
|
4
|
+
*
|
|
5
|
+
* The huaqiu gateway reports an exhausted token balance as a provider error
|
|
6
|
+
* whose own payload code is `insufficient_user_quota`. The harness keeps that
|
|
7
|
+
* code on the durable failure as `providerErrorCode` and attributes the
|
|
8
|
+
* failure to the routed `provider`; this entry gates on those structured
|
|
9
|
+
* fields only, so a wording change or an unrelated error simply renders no
|
|
10
|
+
* button. Clicking it opens the subscription dialog owned by this package's
|
|
11
|
+
* auth client (`openSubscriptionDialog`), which is the same path the sidebar
|
|
12
|
+
* upgrade entry uses.
|
|
13
|
+
*
|
|
14
|
+
* Fallbacks stay inside the card: no host dialog service → the existing
|
|
15
|
+
* "host provides no dialog service" copy; transport failure → retry copy; no
|
|
16
|
+
* credential → the auth client's login surface. The entry never throws, so a
|
|
17
|
+
* missing or older slot harness degrades to the shipped card.
|
|
18
|
+
*/
|
|
19
|
+
import { memo, useCallback, useState, useSyncExternalStore, type CSSProperties } from 'react'
|
|
20
|
+
import { getAuth, getAuthState, subscribeAuth } from '../auth-state.js'
|
|
21
|
+
import { useT } from '../i18n.js'
|
|
22
|
+
import { useIsDark, useLocale } from '../ui-env.js'
|
|
23
|
+
|
|
24
|
+
/** Structural view of the durable turn-error node this entry receives. */
|
|
25
|
+
export interface TurnErrorCtaNode {
|
|
26
|
+
readonly code?: string
|
|
27
|
+
readonly message: string
|
|
28
|
+
readonly provider?: string
|
|
29
|
+
readonly providerErrorCode?: string
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Gateway provider whose balance signature this entry understands. */
|
|
33
|
+
const QUOTA_PROVIDER = 'huaqiu'
|
|
34
|
+
/** The gateway's own code for a token balance that can be topped up. */
|
|
35
|
+
const HUAQIU_QUOTA_SIGNATURE = 'insufficient_user_quota'
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Whether a durable failure is the huaqiu gateway's exhausted token balance.
|
|
39
|
+
*
|
|
40
|
+
* Two structured shapes qualify:
|
|
41
|
+
* - the adapter extracted the gateway's own `insufficient_user_quota` code, or
|
|
42
|
+
* - the routed provider is huaqiu and the harness classified the failure as
|
|
43
|
+
* `QUOTA` (covers classifier fixes that stop carrying the payload code).
|
|
44
|
+
*
|
|
45
|
+
* Never gate on `message`: unrelated failures can quote provider text, and a
|
|
46
|
+
* payload/wording change must degrade to "no button", not to a false positive.
|
|
47
|
+
* @param node - durable turn-error node, possibly absent at runtime boundaries.
|
|
48
|
+
* @returns true only for the huaqiu token-quota signature.
|
|
49
|
+
*/
|
|
50
|
+
export function isHuaqiuQuotaFailure(node: TurnErrorCtaNode | null | undefined): boolean {
|
|
51
|
+
if (node === null || node === undefined) return false
|
|
52
|
+
if (node.code !== 'PI_AI_ERROR' && node.code !== 'QUOTA') return false
|
|
53
|
+
if (node.providerErrorCode === HUAQIU_QUOTA_SIGNATURE) return true
|
|
54
|
+
return node.provider === QUOTA_PROVIDER && node.code === 'QUOTA'
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const ctaStyle: CSSProperties = {
|
|
58
|
+
display: 'block',
|
|
59
|
+
width: 'fit-content',
|
|
60
|
+
marginTop: 4,
|
|
61
|
+
padding: '1px 10px',
|
|
62
|
+
border: '1px solid var(--dsw-alias-brand-primary, #e62e2d)',
|
|
63
|
+
borderRadius: 999,
|
|
64
|
+
background: 'transparent',
|
|
65
|
+
color: 'var(--dsw-alias-brand-primary, #e62e2d)',
|
|
66
|
+
font: 'inherit',
|
|
67
|
+
fontSize: 13,
|
|
68
|
+
lineHeight: '20px',
|
|
69
|
+
cursor: 'pointer',
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const noticeStyle: CSSProperties = {
|
|
73
|
+
display: 'block',
|
|
74
|
+
marginTop: 2,
|
|
75
|
+
color: 'var(--dsw-alias-state-error-primary, #d4380d)',
|
|
76
|
+
fontSize: 12,
|
|
77
|
+
lineHeight: '18px',
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const stopStyle: CSSProperties = { borderRadius: 999, opacity: 0.6, cursor: 'default' }
|
|
81
|
+
|
|
82
|
+
/** Turn-error recovery affordance for the huaqiu token quota. */
|
|
83
|
+
export const HuaqiuTurnErrorSubscribeAction = memo(function HuaqiuTurnErrorSubscribeAction(
|
|
84
|
+
{ node }: { node: TurnErrorCtaNode },
|
|
85
|
+
) {
|
|
86
|
+
const auth = getAuth()
|
|
87
|
+
const authState = useSyncExternalStore(subscribeAuth, getAuthState, getAuthState)
|
|
88
|
+
const locale = useLocale()
|
|
89
|
+
const dark = useIsDark()
|
|
90
|
+
const t = useT()
|
|
91
|
+
const [busy, setBusy] = useState(false)
|
|
92
|
+
const [hovered, setHovered] = useState(false)
|
|
93
|
+
const [notice, setNotice] = useState<{ readonly key: string; readonly text: string } | null>(null)
|
|
94
|
+
|
|
95
|
+
// A projection may hand a fresh node object to the same mounted instance;
|
|
96
|
+
// scope the notice to the failure it describes so a later turn never inherits
|
|
97
|
+
// stale copy.
|
|
98
|
+
const nodeKey = node.message
|
|
99
|
+
const visibleNotice = notice !== null && notice.key === nodeKey ? notice.text : null
|
|
100
|
+
|
|
101
|
+
const open = useCallback(() => {
|
|
102
|
+
if (busy) return
|
|
103
|
+
const fail = (): void => {
|
|
104
|
+
setNotice({ key: nodeKey, text: t('turnError.aiQuotaOpenFailed') })
|
|
105
|
+
}
|
|
106
|
+
if (!auth) {
|
|
107
|
+
fail()
|
|
108
|
+
return
|
|
109
|
+
}
|
|
110
|
+
// Host mode's login blocks until its dialog completes, so it is never
|
|
111
|
+
// awaited here; `busy` belongs to the subscription request only.
|
|
112
|
+
const requestLogin = (): void => {
|
|
113
|
+
try {
|
|
114
|
+
void auth.login({ lang: locale, theme: dark ? 'dark' : 'light' }).catch(fail)
|
|
115
|
+
} catch {
|
|
116
|
+
fail()
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
if (!authState.authenticated) {
|
|
120
|
+
requestLogin()
|
|
121
|
+
return
|
|
122
|
+
}
|
|
123
|
+
setNotice(null)
|
|
124
|
+
setBusy(true)
|
|
125
|
+
void auth.openSubscriptionDialog()
|
|
126
|
+
.then((outcome) => {
|
|
127
|
+
if (outcome.status === 'host-unavailable') {
|
|
128
|
+
setNotice({ key: nodeKey, text: t('subscription.hostUnavailable') })
|
|
129
|
+
} else if (outcome.status === 'signed-out') {
|
|
130
|
+
requestLogin()
|
|
131
|
+
}
|
|
132
|
+
})
|
|
133
|
+
.catch(fail)
|
|
134
|
+
.finally(() => setBusy(false))
|
|
135
|
+
}, [auth, authState.authenticated, busy, dark, locale, nodeKey, t])
|
|
136
|
+
|
|
137
|
+
if (!isHuaqiuQuotaFailure(node)) return null
|
|
138
|
+
|
|
139
|
+
const label = busy
|
|
140
|
+
? t('subscription.subscribing')
|
|
141
|
+
: authState.authenticated
|
|
142
|
+
? t('turnError.aiQuotaCta')
|
|
143
|
+
: t('turnError.aiQuotaSignIn')
|
|
144
|
+
|
|
145
|
+
return (
|
|
146
|
+
<>
|
|
147
|
+
<button
|
|
148
|
+
type="button"
|
|
149
|
+
style={{
|
|
150
|
+
...ctaStyle,
|
|
151
|
+
...(hovered && !busy ? { background: 'var(--dsw-alias-interactive-bg-hover, rgba(230, 46, 45, 0.08))' } : {}),
|
|
152
|
+
...(busy ? stopStyle : {}),
|
|
153
|
+
}}
|
|
154
|
+
disabled={busy}
|
|
155
|
+
aria-busy={busy}
|
|
156
|
+
onClick={open}
|
|
157
|
+
onMouseEnter={() => setHovered(true)}
|
|
158
|
+
onMouseLeave={() => setHovered(false)}
|
|
159
|
+
>
|
|
160
|
+
{label}
|
|
161
|
+
</button>
|
|
162
|
+
{visibleNotice === null ? null : <span style={noticeStyle} aria-live="polite">{visibleNotice}</span>}
|
|
163
|
+
</>
|
|
164
|
+
)
|
|
165
|
+
})
|
package/src/host.ts
CHANGED
|
@@ -46,11 +46,11 @@ export interface HuaqiuAuthConfig {
|
|
|
46
46
|
/** Seconds remote token-validation results are cached. Default 60. */
|
|
47
47
|
validationTtlSeconds?: number
|
|
48
48
|
/**
|
|
49
|
-
*
|
|
50
|
-
*
|
|
51
|
-
* instead of calling a stale/default endpoint.
|
|
49
|
+
* Subscription balances endpoint resolved by HQ Edge from `HQ_AI_ENV`
|
|
50
|
+
* (`GET /sub-api/subscriptions/balances/current`). Absent → `/ai-usage`
|
|
51
|
+
* returns null instead of calling a stale/default endpoint.
|
|
52
52
|
*/
|
|
53
|
-
|
|
53
|
+
subscriptionBalancesUrl?: string
|
|
54
54
|
/**
|
|
55
55
|
* Subscription landing-page origin resolved by HQ Edge from the SAME
|
|
56
56
|
* `HQ_AI_ENV`. Absent → the browser half keeps its standalone PROD default.
|
|
@@ -104,7 +104,11 @@ export function resolveHostConfig(
|
|
|
104
104
|
// Resolved AI endpoints: overlay config (what HQ Edge injects) wins; explicit
|
|
105
105
|
// env URLs are the standalone escape hatch. HQ_AI_ENV itself is NOT read here
|
|
106
106
|
// — the prod/test mapping lives only in HQ Edge's central config.
|
|
107
|
-
const
|
|
107
|
+
const subscriptionBalancesUrl = (
|
|
108
|
+
config?.subscriptionBalancesUrl
|
|
109
|
+
?? env.HQ_AI_SUBSCRIPTION_BALANCES_URL
|
|
110
|
+
?? ''
|
|
111
|
+
).trim()
|
|
108
112
|
const subscriptionOrigin = (config?.subscriptionOrigin ?? env.HQ_AI_SUBSCRIPTION_ORIGIN ?? '')
|
|
109
113
|
.trim()
|
|
110
114
|
.replace(/\/+$/, '')
|
|
@@ -115,7 +119,7 @@ export function resolveHostConfig(
|
|
|
115
119
|
hostLogoutPath,
|
|
116
120
|
hostSessionTtlSeconds: ttl,
|
|
117
121
|
validationTtlSeconds,
|
|
118
|
-
|
|
122
|
+
subscriptionBalancesUrl,
|
|
119
123
|
subscriptionOrigin,
|
|
120
124
|
}
|
|
121
125
|
}
|