@huaqiu/dsh-auth 0.6.22 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@huaqiu/dsh-auth",
3
- "version": "0.6.22",
3
+ "version": "0.6.23",
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.6.22"
36
+ "@huaqiu/dsh-plugin-log": "0.6.23"
37
37
  },
38
38
  "files": [
39
39
  "lib",
@@ -33,8 +33,8 @@ export interface AuthClientDeps {
33
33
  * `hqEdge` service). In host mode the subscription dialog must be opened by
34
34
  * the EDA host through DialogService.OpenUrl (hqEdge.openUrl) — a browser
35
35
  * iframe cannot be shown over the host UI. Absent/undefined = the host has
36
- * no dialog service; `openSubscriptionDialog()` then no-ops and the caller
37
- * degrades gracefully.
36
+ * no dialog service; `openSubscriptionDialog()` then resolves
37
+ * `host-unavailable` and the caller degrades gracefully.
38
38
  */
39
39
  openHostDialog?: (url: string, options: {
40
40
  title?: string
@@ -43,6 +43,15 @@ export interface AuthClientDeps {
43
43
  }) => Promise<void>
44
44
  }
45
45
 
46
+ /** Explicit result of {@link AuthClient['auth']['openSubscriptionDialog']}. */
47
+ export type SubscriptionDialogOutcome =
48
+ | { readonly status: 'opened' }
49
+ | { readonly status: 'already-open' }
50
+ /** No usable credential; the caller should offer login. */
51
+ | { readonly status: 'signed-out' }
52
+ /** Host mode with no dialog service wired (or nothing to open). */
53
+ | { readonly status: 'host-unavailable' }
54
+
46
55
  export interface AuthClient {
47
56
  auth: {
48
57
  isAuthenticated(): boolean
@@ -85,11 +94,14 @@ export interface AuthClient {
85
94
  * Open the subscription landing page (`gen.eda.cn/subscription` with the
86
95
  * token). Host mode: ask the EDA host to open its NATIVE dialog through
87
96
  * DialogService.OpenUrl (preferred size 1400×740). Standalone DSH: open
88
- * the in-app iframe dialog at the same preferred size. No-op when the
89
- * credential is missing; host mode without a dialog service no-ops too
90
- * (the UI falls back to its own subscribe button + error copy).
97
+ * the in-app iframe dialog at the same preferred size.
98
+ *
99
+ * Returns an explicit outcome instead of silently no-op'ing: without a
100
+ * credential the caller may open login; without a host dialog service it
101
+ * shows its own fallback copy; when a standalone dialog is already open
102
+ * it is left untouched. Transport/dialog failures reject.
91
103
  */
92
- openSubscriptionDialog(): Promise<void>
104
+ openSubscriptionDialog(): Promise<SubscriptionDialogOutcome>
93
105
  onAuthStateChanged(listener: (info: AuthTokenPayload | null) => void): () => void
94
106
  }
95
107
  /** Route window 'message' events here. Exposed for direct testing. */
@@ -123,6 +135,12 @@ export function createAuthClient(deps: AuthClientDeps): AuthClient {
123
135
  let hostMode = false
124
136
  let hostSession: AuthTokenPayload | null = null
125
137
  let hostSessionLoaded = false
138
+ /**
139
+ * Why the last host-session resolution failed, if it did. Transport errors
140
+ * must NOT masquerade as a healthy `signed-out`: the dialog opener surfaces
141
+ * them as a rejection so callers can show retry copy instead of "sign in".
142
+ */
143
+ let hostResolveError: unknown
126
144
  /**
127
145
  * Subscription origin resolved by HQ Edge from `HQ_AI_ENV` and served on the
128
146
  * node `/config` route. Null in standalone → lib's PROD fallback.
@@ -176,6 +194,7 @@ export function createAuthClient(deps: AuthClientDeps): AuthClient {
176
194
  */
177
195
  const resolveHost = async (): Promise<void> => {
178
196
  hostSessionLoaded = true
197
+ hostResolveError = undefined
179
198
  if (!hostMode) {
180
199
  hostSession = null
181
200
  return
@@ -183,9 +202,12 @@ export function createAuthClient(deps: AuthClientDeps): AuthClient {
183
202
  try {
184
203
  const session = await transport.fetchSession()
185
204
  hostSession = session.authenticated ? normalizeHostUserPayload(session.user) : null
186
- } catch {
205
+ } catch (error) {
187
206
  // Host unreachable: stay logged out rather than inventing a session.
207
+ // The error is retained for the dialog opener, which must not report it
208
+ // as a genuine signed-out state.
188
209
  hostSession = null
210
+ hostResolveError = error
189
211
  }
190
212
  }
191
213
 
@@ -270,27 +292,32 @@ export function createAuthClient(deps: AuthClientDeps): AuthClient {
270
292
  if (!(await auth.getAccessToken())) return null
271
293
  return transport.fetchAiUsage()
272
294
  },
273
- openSubscriptionDialog: async (): Promise<void> => {
295
+ openSubscriptionDialog: async (): Promise<SubscriptionDialogOutcome> => {
274
296
  if (hostMode && !hostSessionLoaded) await resolveHost()
275
297
  const token = await auth.getAccessToken()
276
- if (!token) return
298
+ if (!token) {
299
+ // A failed host resolution is a transport failure, not "signed out".
300
+ if (hostMode && hostResolveError !== undefined) throw hostResolveError
301
+ return { status: 'signed-out' }
302
+ }
277
303
  const url = buildSubscriptionUrl({
278
304
  token,
279
305
  ...(subscriptionOrigin ? { origin: subscriptionOrigin } : {}),
280
306
  })
281
307
  if (hostMode) {
282
- // The EDA host owns the UI — open its native dialog (fire-and-forget).
283
- // No dialog service → no-op; the caller keeps its subscribe button.
284
- if (!deps.openHostDialog) return
308
+ // The EDA host owns the UI — open its native dialog. No dialog service
309
+ // means the caller keeps its own affordance and shows fallback copy.
310
+ if (!deps.openHostDialog) return { status: 'host-unavailable' }
285
311
  await deps.openHostDialog(url, {
286
312
  title: 'Huaqiu EDA subscription',
287
313
  size: { width: SUBSCRIPTION_PREFERRED_SIZE.width, height: SUBSCRIPTION_PREFERRED_SIZE.height },
288
314
  key: 'hq-subscription-dialog',
289
315
  })
290
- return
316
+ return { status: 'opened' }
291
317
  }
292
- if (isSubscriptionDialogOpen()) return
318
+ if (isSubscriptionDialogOpen()) return { status: 'already-open' }
293
319
  openSubscriptionDialog(url, { size: SUBSCRIPTION_PREFERRED_SIZE })
320
+ return { status: 'opened' }
294
321
  },
295
322
  onAuthStateChanged: (listener: (info: AuthTokenPayload | null) => void): (() => void) => {
296
323
  listeners.add(listener)
@@ -50,6 +50,11 @@ const zh = {
50
50
  'subscription.ai': 'AI 用量',
51
51
  'subscription.aiUsagePercent': '{percent}%',
52
52
  'subscription.aiUsageUnknown': '暂无数据',
53
+ // Turn-error quota CTA (rendered inside the Chat turn-error card when the
54
+ // huaqiu gateway reports `insufficient_user_quota`).
55
+ 'turnError.aiQuotaCta': '升级获取更多 AI 额度',
56
+ 'turnError.aiQuotaSignIn': '登录后升级',
57
+ 'turnError.aiQuotaOpenFailed': '无法打开订阅页面,请稍后重试。',
53
58
 
54
59
  'card.title': '华秋 EDA AI(eda.cn)登录',
55
60
  'card.desc': '工具「{tool}」需要登录华秋 EDA AI 账号才能继续。请在下方的登录框完成登录(或点击左侧「华秋EDA AI登录」按钮);登录完成后,回复助手「已登录,请重试」,助手会自动重新调用该工具。',
@@ -100,6 +105,11 @@ const en: Record<AuthCopyKey, string> = {
100
105
  'subscription.ai': 'AI usage',
101
106
  'subscription.aiUsagePercent': '{percent}%',
102
107
  'subscription.aiUsageUnknown': 'No data',
108
+ // Turn-error quota CTA (rendered inside the Chat turn-error card when the
109
+ // huaqiu gateway reports `insufficient_user_quota`).
110
+ 'turnError.aiQuotaCta': 'Upgrade for more AI tokens',
111
+ 'turnError.aiQuotaSignIn': 'Sign in to upgrade',
112
+ 'turnError.aiQuotaOpenFailed': 'Could not open the subscription page. Please try again later.',
103
113
 
104
114
  'card.title': 'Huaqiu EDA AI (eda.cn) login',
105
115
  // The reply phrase used to be hardcoded to the Chinese "已登录,请重试" even
@@ -21,6 +21,7 @@ import { createAuthClient, type AuthClient } from './client.js'
21
21
  import { disposeAuth, registerAuth, registerAuthSync, registerHqEdgeGetter } from './auth-state.js'
22
22
  import { HuaqiuToolView } from './ui/needs-auth-toolview.jsx'
23
23
  import { HuaqiuAuthSidebarAction } from './ui/sidebar-action.jsx'
24
+ import { HuaqiuTurnErrorSubscribeAction } from './ui/turn-error-cta.jsx'
24
25
  import { disposeUiEnv } from './ui-env.js'
25
26
 
26
27
  /**
@@ -75,13 +76,17 @@ export function apply(ctx: ClientContext): () => void {
75
76
  documentLike: document,
76
77
  // Host mode subscription dialog: the EDA host owns the UI. Open its
77
78
  // native window through the hqEdge service's DialogService.OpenUrl
78
- // bridge (fire-and-forget); absent hqEdge → no-op, the caller's
79
- // subscribe button stays usable and reports the limitation.
79
+ // bridge, which acknowledges once the dialog is launched.
80
80
  openHostDialog: async (url, options) => {
81
81
  const hqEdge = ctx.get?.<{
82
82
  openUrl?(url: string, opts?: Record<string, unknown>): Promise<unknown>
83
83
  } | undefined>('hqEdge')
84
- if (!hqEdge || typeof hqEdge.openUrl !== 'function') return
84
+ if (!hqEdge || typeof hqEdge.openUrl !== 'function') {
85
+ // Without the EDA bridge no native dialog can ever appear. Reject so
86
+ // callers surface their fallback copy instead of reporting a launch
87
+ // that never happened.
88
+ throw new Error('hqEdge.openUrl is unavailable')
89
+ }
85
90
  await hqEdge.openUrl(url, {
86
91
  ...(options.title ? { title: options.title } : {}),
87
92
  ...(options.size ? { size: options.size } : {}),
@@ -170,6 +175,13 @@ export function apply(ctx: ClientContext): () => void {
170
175
  disposers.push(slots.inject('tool.call.toolview', () => slots.register({ name: 'tool.call.toolview', key: toolName }, HuaqiuToolView) as () => void))
171
176
  }
172
177
  disposers.push(slots.inject('sidebar.footer.action', () => slots.register({ name: 'sidebar.footer.action', id: 'huaqiu-auth' }, HuaqiuAuthSidebarAction) as () => void))
178
+ // The turn-error action slot only exists on harness versions that ship
179
+ // the seam; `inject` waits for its declaration, so an older harness
180
+ // simply never calls this and the shipped error card stays unchanged.
181
+ disposers.push(slots.inject('conversation.chat.turn-error.action', () => slots.register({
182
+ name: 'conversation.chat.turn-error.action',
183
+ id: 'huaqiu-turn-error-cta',
184
+ }, HuaqiuTurnErrorSubscribeAction) as () => void))
173
185
  }
174
186
  })
175
187
 
@@ -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
+ })