dsh-session-guard 4.3.0 → 4.4.0

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": "dsh-session-guard",
3
- "version": "4.3.0",
3
+ "version": "4.4.0",
4
4
  "publishConfig": {
5
5
  "registry": "https://registry.npmjs.org",
6
6
  "tag": "latest"
@@ -0,0 +1,368 @@
1
+ /**
2
+ * ⚠️ 生成副本 —— 请勿手改。真源:mine-dsh-plugins/_tools/guide-kit/guide.tsx
3
+ * 重新同步:node _tools/guide-kit/sync.mjs
4
+ */
5
+ /**
6
+ * guide-kit —— 九插件共用的「首次使用引导」件(**生成副本,勿手改**)。
7
+ *
8
+ * 唯一真源:`mine-dsh-plugins/_tools/guide-kit/guide.tsx`
9
+ * 同步命令:`node _tools/guide-kit/sync.mjs`(会覆盖本文件;改这里等于白改)
10
+ *
11
+ * 六条契约(见 .agents/plans/unified-i18n-onboarding/spec.md §2):
12
+ * 1. Skip 恒定可见,任何步骤都能退;
13
+ * 2. 永远有字:引导外壳(标题/按钮/步进)自带 10 语词表,按 <html lang> 取词,
14
+ * 认不出的一律落 en;步骤正文按「本语 → en → zh → 任意可用」逐级回退,绝不留空白;
15
+ * 3. 重启入口:`GuideRestartButton`(或自己调 `resetGuide(ns)` + setOpen(true))就地重开;
16
+ * 4. 零依赖:只 react + localStorage,不 import 平台包,不抢宿主设置表单;
17
+ * 5. 引导自己绝不能成为卡面渲染的失败点:样式注入与存储访问全部 try/catch + 能力探测;
18
+ * 6. 外壳词表与步骤正文分离:外壳跨插件统一(本文件),正文每插件一份 `guide-steps.ts`。
19
+ */
20
+ import { useEffect, useState } from 'react'
21
+ import type { CSSProperties, JSX } from 'react'
22
+
23
+ export interface GuideStep {
24
+ title: string
25
+ body: string
26
+ }
27
+
28
+ export interface GuideLabels {
29
+ title: string
30
+ skip: string
31
+ next: string
32
+ prev: string
33
+ done: string
34
+ restart: string
35
+ stepOf: (_current: number, _total: number) => string
36
+ }
37
+
38
+ /** 生态通用的十个语言码(与各插件 `locale/*.json`、README 的十语镜像同口径)。 */
39
+ export const GUIDE_LOCALES = ['zh', 'en', 'ja', 'ko', 'fr', 'de', 'it', 'ru', 'es', 'pt'] as const
40
+ export type GuideLocale = (typeof GUIDE_LOCALES)[number]
41
+
42
+ /**
43
+ * 引导外壳词表(10 语)。
44
+ *
45
+ * 为什么不塞进各插件 locales:这七个词是**跨插件同一套**,塞进九个字典要重复翻译
46
+ * 9×10 次,且一旦措辞调整就得动九个仓。外壳留在本文件,正文留各插件。
47
+ */
48
+ export const GUIDE_COPY: Record<GuideLocale, GuideLabels> = {
49
+ zh: {
50
+ title: '快速上手',
51
+ skip: '跳过引导',
52
+ next: '下一步',
53
+ prev: '上一步',
54
+ done: '开始使用',
55
+ restart: '重新查看引导',
56
+ stepOf: (current, total) => `第 ${current} / ${total} 步`,
57
+ },
58
+ en: {
59
+ title: 'Quick start',
60
+ skip: 'Skip guide',
61
+ next: 'Next',
62
+ prev: 'Back',
63
+ done: 'Get started',
64
+ restart: 'Show guide again',
65
+ stepOf: (current, total) => `Step ${current} of ${total}`,
66
+ },
67
+ ja: {
68
+ title: 'クイックスタート',
69
+ skip: 'ガイドをスキップ',
70
+ next: '次へ',
71
+ prev: '戻る',
72
+ done: 'はじめる',
73
+ restart: 'ガイドをもう一度表示',
74
+ stepOf: (current, total) => `ステップ ${current} / ${total}`,
75
+ },
76
+ ko: {
77
+ title: '빠른 시작',
78
+ skip: '가이드 건너뛰기',
79
+ next: '다음',
80
+ prev: '이전',
81
+ done: '시작하기',
82
+ restart: '가이드 다시 보기',
83
+ stepOf: (current, total) => `${current} / ${total} 단계`,
84
+ },
85
+ fr: {
86
+ title: 'Démarrage rapide',
87
+ skip: 'Ignorer le guide',
88
+ next: 'Suivant',
89
+ prev: 'Retour',
90
+ done: 'Commencer',
91
+ restart: 'Revoir le guide',
92
+ stepOf: (current, total) => `Étape ${current} sur ${total}`,
93
+ },
94
+ de: {
95
+ title: 'Schnellstart',
96
+ skip: 'Anleitung überspringen',
97
+ next: 'Weiter',
98
+ prev: 'Zurück',
99
+ done: 'Loslegen',
100
+ restart: 'Anleitung erneut anzeigen',
101
+ stepOf: (current, total) => `Schritt ${current} von ${total}`,
102
+ },
103
+ it: {
104
+ title: 'Avvio rapido',
105
+ skip: 'Salta la guida',
106
+ next: 'Avanti',
107
+ prev: 'Indietro',
108
+ done: 'Inizia',
109
+ restart: 'Rivedi la guida',
110
+ stepOf: (current, total) => `Passo ${current} di ${total}`,
111
+ },
112
+ ru: {
113
+ title: 'Быстрый старт',
114
+ skip: 'Пропустить руководство',
115
+ next: 'Далее',
116
+ prev: 'Назад',
117
+ done: 'Начать',
118
+ restart: 'Показать руководство снова',
119
+ stepOf: (current, total) => `Шаг ${current} из ${total}`,
120
+ },
121
+ es: {
122
+ title: 'Inicio rápido',
123
+ skip: 'Omitir la guía',
124
+ next: 'Siguiente',
125
+ prev: 'Atrás',
126
+ done: 'Empezar',
127
+ restart: 'Ver la guía de nuevo',
128
+ stepOf: (current, total) => `Paso ${current} de ${total}`,
129
+ },
130
+ pt: {
131
+ title: 'Início rápido',
132
+ skip: 'Ignorar o guia',
133
+ next: 'Próximo',
134
+ prev: 'Voltar',
135
+ done: 'Começar',
136
+ restart: 'Ver o guia novamente',
137
+ stepOf: (current, total) => `Passo ${current} de ${total}`,
138
+ },
139
+ }
140
+
141
+ /** 语言标签 → 语言码:只认主标签,认不出的落 null(由调用方回退 en)。 */
142
+ export function normalizeGuideLocale(tag: string): GuideLocale | null {
143
+ const primary = tag.toLowerCase().trim().split(/[-_]/)[0] ?? ''
144
+ return (GUIDE_LOCALES as readonly string[]).includes(primary) ? (primary as GuideLocale) : null
145
+ }
146
+
147
+ function htmlLang(): string {
148
+ try {
149
+ return typeof document === 'undefined' ? '' : (document.documentElement?.lang ?? '')
150
+ } catch {
151
+ return ''
152
+ }
153
+ }
154
+
155
+ /**
156
+ * 当前引导语言:以宿主 `<html lang>` 为准(语言切换会改写这个属性)。
157
+ *
158
+ * 认不出 → en:引导是「帮助」面,宁可给英文也不能给空白或中文硬串。
159
+ */
160
+ export function currentGuideLocale(): GuideLocale {
161
+ return normalizeGuideLocale(htmlLang()) ?? 'en'
162
+ }
163
+
164
+ /** 兼容旧调用(1.x 版本只区分 zh/en):需要细分语种请用 `currentGuideLocale()`。 */
165
+ export function guideLang(): GuideLocale {
166
+ return currentGuideLocale()
167
+ }
168
+
169
+ /** 引导外壳取词。 */
170
+ export function guideLabels(locale: GuideLocale = currentGuideLocale()): GuideLabels {
171
+ return GUIDE_COPY[locale] ?? GUIDE_COPY.en
172
+ }
173
+
174
+ /**
175
+ * 步骤正文取词:本语 → en → zh → 表里第一个可用。
176
+ *
177
+ * 为什么需要回退链:九插件分批补语种,某个插件可能只有 zh/en 而宿主是 ru;
178
+ * 这时给英文是可用的,给空白等于「引导坏了」。`undefined` 步骤表按空表处理。
179
+ */
180
+ export function guideSteps(
181
+ map: Partial<Record<GuideLocale, readonly GuideStep[]>> | undefined,
182
+ ): readonly GuideStep[] {
183
+ if (map === undefined) return []
184
+ const order: (GuideLocale | undefined)[] = [currentGuideLocale(), 'en', 'zh']
185
+ for (const key of order) {
186
+ const hit = key === undefined ? undefined : map[key]
187
+ if (hit !== undefined && hit.length > 0) return hit
188
+ }
189
+ for (const key of GUIDE_LOCALES) {
190
+ const hit = map[key]
191
+ if (hit !== undefined && hit.length > 0) return hit
192
+ }
193
+ return []
194
+ }
195
+
196
+ function guideStorageKey(ns: string): string {
197
+ return `dsh.guide.${ns}.skipped`
198
+ }
199
+
200
+ /** 是否已跳过(存储不可用时按「未跳过」处理:宁可多教一次,不要静默不教)。 */
201
+ export function isGuideSkipped(ns: string): boolean {
202
+ try {
203
+ return typeof localStorage !== 'undefined' && localStorage.getItem(guideStorageKey(ns)) === '1'
204
+ } catch {
205
+ return false
206
+ }
207
+ }
208
+
209
+ /** 记下跳过;写失败不抛(隐私模式 / 存储禁用)。 */
210
+ export function skipGuide(ns: string): void {
211
+ try {
212
+ localStorage?.setItem(guideStorageKey(ns), '1')
213
+ } catch {
214
+ /* ignore */
215
+ }
216
+ }
217
+
218
+ /** 清标记 = 允许重新教学。 */
219
+ export function resetGuide(ns: string): void {
220
+ try {
221
+ localStorage?.removeItem(guideStorageKey(ns))
222
+ } catch {
223
+ /* ignore */
224
+ }
225
+ }
226
+
227
+ const GUIDE_CSS = `
228
+ .sgGuide{border:1px solid var(--dsw-alias-border-l2, rgba(127,127,127,.28));background:var(--dsw-alias-bg-layer-2, rgba(127,127,127,.06));border-radius:12px;padding:14px 16px;margin:0 0 12px}
229
+ .sgGuideHead{display:flex;align-items:center;gap:8px;margin:0 0 10px}
230
+ .sgGuideTitle{font-size:14px;font-weight:600;color:var(--dsw-alias-label-primary, currentColor)}
231
+ .sgGuideStep{font-size:12px;color:var(--dsw-alias-label-tertiary, rgba(127,127,127,.9));margin-left:auto}
232
+ .sgGuideBody{font-size:13px;line-height:1.6;color:var(--dsw-alias-label-secondary, currentColor);min-height:52px}
233
+ .sgGuideBody b{color:var(--dsw-alias-label-primary, currentColor);font-weight:600}
234
+ .sgGuideDots{display:flex;gap:6px;margin:10px 0 0}
235
+ .sgGuideDot{width:6px;height:6px;border-radius:50%;background:var(--dsw-alias-border-l2, rgba(127,127,127,.3))}
236
+ .sgGuideDot-on{background:var(--dsw-alias-button-primary-fill, #4d6bfe)}
237
+ .sgGuideFoot{display:flex;align-items:center;gap:8px;margin:12px 0 0}
238
+ .sgGuideBtn{appearance:none;font:inherit;font-size:12px;padding:5px 12px;border-radius:8px;border:1px solid var(--dsw-alias-border-l2, rgba(127,127,127,.3));background:transparent;color:var(--dsw-alias-label-primary, currentColor);cursor:pointer}
239
+ .sgGuideBtn-primary{background:var(--dsw-alias-button-primary-fill, #4d6bfe);border-color:transparent;color:#fff}
240
+ .sgGuideBtn-skip{margin-right:auto;color:var(--dsw-alias-label-tertiary, rgba(127,127,127,.9));border-color:transparent;text-decoration:underline}
241
+ .sgGuideRestart{appearance:none;font:inherit;font-size:12px;padding:0;border:0;background:transparent;color:var(--dsw-alias-link-primary, #4d6bfe);cursor:pointer;text-decoration:underline}
242
+ `
243
+
244
+ function injectGuideCss(): void {
245
+ // 宿主是浏览器,但**测试替身**常常只给一个残缺的 document(无 querySelector /
246
+ // 无 head)——样式注入是纯装饰,任何缺失都安静跳过,绝不让引导把卡面炸掉。
247
+ try {
248
+ if (typeof document === 'undefined') return
249
+ if (typeof document.querySelector !== 'function') return
250
+ if (typeof document.createElement !== 'function') return
251
+ if (!document.head) return
252
+ if (document.querySelector('style[data-plugin-css="guide-kit"]') !== null) return
253
+ const tag = document.createElement('style')
254
+ tag.dataset.pluginCss = 'guide-kit'
255
+ tag.textContent = GUIDE_CSS
256
+ document.head.appendChild(tag)
257
+ } catch {
258
+ /* 残缺 DOM:跳过样式,行为不受影响 */
259
+ }
260
+ }
261
+
262
+ /** 语言变更订阅:语言切换后重渲染词表(引导是短生命周期,直接跟随 <html lang>)。 */
263
+ function useLangTick(): void {
264
+ const [, setTick] = useState(0)
265
+ useEffect(() => {
266
+ try {
267
+ if (typeof MutationObserver === 'undefined' || typeof document === 'undefined') return
268
+ if (!document.documentElement) return
269
+ const observer = new MutationObserver(() => setTick((n) => n + 1))
270
+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ['lang'] })
271
+ return () => observer.disconnect()
272
+ } catch {
273
+ return
274
+ }
275
+ }, [])
276
+ }
277
+
278
+ /**
279
+ * 引导主体:3 步以内的小教学 + 恒定可见的 Skip。
280
+ *
281
+ * `onClose` 由宿主卡面传:Skip/Done 都会调用它(Skip 同时写标记)。
282
+ */
283
+ export function GuidePanel(props: {
284
+ ns: string
285
+ steps: readonly GuideStep[]
286
+ onClose: () => void
287
+ }): JSX.Element | null {
288
+ const { ns, steps, onClose } = props
289
+ const [index, setIndex] = useState(0)
290
+ useLangTick()
291
+ const labels = guideLabels()
292
+ useEffect(() => {
293
+ injectGuideCss()
294
+ }, [])
295
+ if (steps.length === 0) return null
296
+ const current = steps[Math.min(index, steps.length - 1)]!
297
+ const last = index >= steps.length - 1
298
+ // Skip 与 Done 都写标记:**「看过」= 不再自动弹**。只给 Skip 写字会让点
299
+ // 「开始使用」走完的用户每次进设置面都被再教一遍(认真看完的人最烦这个)。
300
+ const finish = (): void => {
301
+ skipGuide(ns)
302
+ onClose()
303
+ }
304
+ return (
305
+ <section className="sgGuide" aria-label={labels.title}>
306
+ <header className="sgGuideHead">
307
+ <span className="sgGuideTitle">{labels.title}</span>
308
+ <span className="sgGuideStep">{labels.stepOf(index + 1, steps.length)}</span>
309
+ </header>
310
+ <div className="sgGuideBody">
311
+ <b>{current.title}</b>
312
+ <div>{current.body}</div>
313
+ </div>
314
+ <div className="sgGuideDots" aria-hidden="true">
315
+ {steps.map((step, i) => (
316
+ <span key={step.title} className={'sgGuideDot' + (i === index ? ' sgGuideDot-on' : '')} />
317
+ ))}
318
+ </div>
319
+ <footer className="sgGuideFoot">
320
+ <button type="button" className="sgGuideBtn sgGuideBtn-skip" onClick={() => finish()}>
321
+ {labels.skip}
322
+ </button>
323
+ {index > 0 && (
324
+ <button type="button" className="sgGuideBtn" onClick={() => setIndex(index - 1)}>
325
+ {labels.prev}
326
+ </button>
327
+ )}
328
+ {last ? (
329
+ <button type="button" className="sgGuideBtn sgGuideBtn-primary" onClick={() => finish()}>
330
+ {labels.done}
331
+ </button>
332
+ ) : (
333
+ <button type="button" className="sgGuideBtn sgGuideBtn-primary" onClick={() => setIndex(index + 1)}>
334
+ {labels.next}
335
+ </button>
336
+ )}
337
+ </footer>
338
+ </section>
339
+ )
340
+ }
341
+
342
+ /**
343
+ * 重启入口:清标记 + 就地重开引导。
344
+ *
345
+ * 统一件,避免九插件各写一份(措辞/样式/清标记时机容易走样)。跳过之后
346
+ * 用户想再看一次,不需要去清浏览器存储。
347
+ */
348
+ export function GuideRestartButton(props: {
349
+ ns: string
350
+ onOpen: () => void
351
+ style?: CSSProperties
352
+ }): JSX.Element {
353
+ const { ns, onOpen, style } = props
354
+ useLangTick()
355
+ return (
356
+ <button
357
+ type="button"
358
+ className="sgGuideRestart"
359
+ style={style}
360
+ onClick={() => {
361
+ resetGuide(ns)
362
+ onOpen()
363
+ }}
364
+ >
365
+ {guideLabels().restart}
366
+ </button>
367
+ )
368
+ }
@@ -13,6 +13,39 @@
13
13
  import { useEffect, useState, useSyncExternalStore } from 'react'
14
14
  import type { JSX } from 'react'
15
15
  import type { SettingsScope } from './scope-face.ts'
16
+ import { GuidePanel, GuideRestartButton, guideSteps, isGuideSkipped, type GuideLocale, type GuideStep } from './guide.tsx'
17
+
18
+ /** 首次使用引导文案(zh/en 为一等公民;其余语种由 guide-kit 的回退链落到 en)。 */
19
+ const GUIDE_STEPS: Partial<Record<GuideLocale, readonly GuideStep[]>> = {
20
+ zh: [
21
+ {
22
+ title: '它会替你踩刹车',
23
+ body: '高峰时段自动暂停运行中的会话,退峰后自动续跑;周末模式让你无视峰谷畅快跑。',
24
+ },
25
+ {
26
+ title: '判定口径按「官方源」',
27
+ body: '默认只拦 DeepSeek 官方源,本地/第三方 provider 照常跑;需要更严时再打开「官方源二维判定」下的名单。',
28
+ },
29
+ {
30
+ title: '状态永远可见',
31
+ body: '输入框右侧的徽标显示当前状态(正常 / 峰值暂停中);停不下来时用旁边的暂停按钮手动接管。',
32
+ },
33
+ ],
34
+ en: [
35
+ {
36
+ title: 'It pumps the brakes for you',
37
+ body: 'Running sessions auto-pause during peak hours and resume off-peak. Weekend mode ignores peaks entirely.',
38
+ },
39
+ {
40
+ title: 'Official-source scoping',
41
+ body: 'By default only the DeepSeek official source is gated; local/third-party providers keep running. Tighten it via the official-source allowlists when needed.',
42
+ },
43
+ {
44
+ title: 'Status stays visible',
45
+ body: 'The badge right of the composer shows the current state (Normal / Peak paused). Use the pause button beside it to take over manually.',
46
+ },
47
+ ],
48
+ }
16
49
 
17
50
  /** 命名空间值形状(与 host 的 DEFAULT_SETTINGS 对应)。 */
18
51
  export interface SessionGuardConfig {
@@ -239,6 +272,8 @@ export function SessionGuardCard({ scope }: SettingsCardProps): JSX.Element {
239
272
  const readonly = unavailable || !snapshot.writable
240
273
  const value = (snapshot.value ?? {}) as Partial<SessionGuardConfig>
241
274
  const [open, setOpen] = useState(true)
275
+ // 首次使用引导:本地标记放在 localStorage,跨会话持久;卡底「重新查看引导」清标记重开。
276
+ const [guideOpen, setGuideOpen] = useState(() => !isGuideSkipped('session-guard'))
242
277
 
243
278
  injectCss()
244
279
 
@@ -268,6 +303,13 @@ export function SessionGuardCard({ scope }: SettingsCardProps): JSX.Element {
268
303
  </button>
269
304
  {open && (
270
305
  <div className="sgCardBody">
306
+ {guideOpen && (
307
+ <GuidePanel
308
+ ns="session-guard"
309
+ steps={guideSteps(GUIDE_STEPS)}
310
+ onClose={() => setGuideOpen(false)}
311
+ />
312
+ )}
271
313
  {unavailable ? (
272
314
  <p style={{ margin: '0', padding: '12px 0', fontSize: '13px', color: 'var(--dsw-alias-label-tertiary)' }}>
273
315
  设置命名空间不可用:请确认 dsh-session-guard 已装配进此 profile。
@@ -388,6 +430,9 @@ export function SessionGuardCard({ scope }: SettingsCardProps): JSX.Element {
388
430
  排查误判访问 /session-guard/provider?provider=&lt;id&gt; 看 matchedBy。
389
431
  </p>
390
432
  {!snapshot.writable && <p className="sgReadonly">当前只读,无法修改。</p>}
433
+ <p className="sgHint" style={{ marginTop: 12 }}>
434
+ <GuideRestartButton ns="session-guard" onOpen={() => setGuideOpen(true)} />
435
+ </p>
391
436
  </>
392
437
  )}
393
438
  </div>