@surfishs/dsh-prompt-enhance 0.0.6 → 0.0.8

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.
Files changed (57) hide show
  1. package/README.en.md +3 -0
  2. package/README.md +3 -0
  3. package/cordis.patch.yml +1 -1
  4. package/lib/client.js +454 -397
  5. package/lib/index.js +67 -56
  6. package/lib/index.js.map +3 -3
  7. package/package.json +23 -15
  8. package/src/client/ActionIcons.tsx +4 -17
  9. package/src/client/EnhanceButton.tsx +52 -48
  10. package/src/client/ResultDock.tsx +22 -9
  11. package/src/client/ResultPanel.tsx +83 -52
  12. package/src/client/SparkleFishIcon.tsx +3 -13
  13. package/src/client/SparkleIcon.tsx +2 -12
  14. package/src/client/UndoBar.tsx +11 -6
  15. package/src/client/enhance-client.ts +44 -40
  16. package/src/client/index.tsx +3 -12
  17. package/src/client/llm-catalog.ts +14 -16
  18. package/src/client/locales.ts +20 -4
  19. package/src/client/reasoning-options.ts +7 -15
  20. package/src/client/settings-page-controls.tsx +449 -0
  21. package/src/client/settings-page-copy.ts +112 -0
  22. package/src/client/settings-page-spec.ts +330 -0
  23. package/src/client/settings-page-styles.ts +161 -0
  24. package/src/client/settings-page.tsx +166 -1109
  25. package/src/client/settings-source.ts +41 -31
  26. package/src/client/settings.ts +17 -12
  27. package/src/client/shortcut.ts +7 -6
  28. package/src/client/styles.ts +52 -0
  29. package/src/client/useDockAlignment.ts +5 -15
  30. package/src/config.ts +84 -27
  31. package/src/context.ts +1 -5
  32. package/src/enhance-routes.ts +8 -8
  33. package/src/enhancer.ts +43 -34
  34. package/src/orchestrate.ts +19 -23
  35. package/src/prompts.ts +4 -4
  36. package/src/provider-catalog.ts +1 -1
  37. package/src/reasoning-cache.ts +4 -4
  38. package/src/reasoning-efforts.ts +4 -9
  39. package/src/settings-source.ts +37 -23
  40. package/src/shared/limits.ts +38 -0
  41. package/src/shared/normalize.ts +4 -1
  42. package/src/shared/protocol.ts +27 -23
  43. package/src/shared/reasoning.ts +1 -7
  44. package/src/shared/stream-text.ts +0 -6
  45. package/src/shared/validate.ts +3 -9
  46. package/docs/code-review-2026-09.md +0 -211
  47. package/docs/handoff-settings-page.md +0 -195
  48. package/docs/release-0.2.3.md +0 -47
  49. package/docs/release-0.2.4.md +0 -20
  50. package/docs/release-0.2.5.md +0 -28
  51. package/docs/release-0.2.6.md +0 -33
  52. package/docs/release-0.2.7.md +0 -22
  53. package/docs/release-0.3.0.md +0 -36
  54. package/docs/release-0.3.1.md +0 -50
  55. package/docs/release-0.3.2.md +0 -41
  56. package/docs/release-0.3.3.md +0 -53
  57. package/docs/release-0.3.4.md +0 -43
@@ -1,56 +1,62 @@
1
1
  /**
2
- * The dsh-prompt-enhance configuration surfaces of the dsh web GUI.
2
+ * The plugin's two configuration surfaces — the Settings dialog section and the
3
+ * plugin row's config page — rendered over one staged form.
3
4
  *
4
- * The plugin ships two entry points to the same staged form:
5
- *
6
- * - **Settings dialog** — a `settings.section` entry titled 提示词增强, the page
7
- * this plugin has always drawn for hosts that no longer generate one from
8
- * the schema. It keeps the diagnostic presentation: the raw config key beside
9
- * the Chinese name, and a bilingual hint.
10
- * - **Plugins page** — a `plugins.row.config` entry for the row this bundle's
11
- * patch declares. That slot is the host's documented seat for a plugin's own
12
- * configuration (keyed `<bundle package>#<row id>`); the manager draws the
13
- * chrome, asks for `view: 'page' | 'summary'`, and the row gains a configure
14
- * control. Copy there is single-language, read through the locale seat.
15
- *
16
- * Both surfaces share one staged form: value rows draw a native input, boolean
17
- * rows the shell's `Switch`, enum rows its `SegmentedControl`. The primitives
18
- * package ships field helpers only for text and numbers, so this module
19
- * supplies the boolean and enum descriptors itself — a descriptor is
20
- * `{ field, format, parse }`, and `parse` decides the JSON value written,
21
- * which is what keeps a switch writing `true` instead of the string `"true"`.
5
+ * This module owns the rendering, the page registration, and the re-exports the
6
+ * rest of the plugin imports. The row table lives in `settings-page-spec`, the
7
+ * copy in `settings-page-copy`, the inline styles in `settings-page-styles`, and
8
+ * the per-kind row controls in `settings-page-controls`.
22
9
  * @module dsh-prompt-enhance/client/settings-page
23
10
  */
24
11
 
25
- import { useEffect, useRef, useState, type CSSProperties, type ReactElement, type ReactNode } from 'react'
12
+ import { useEffect, useRef, useState, type ReactElement } from 'react'
26
13
  import type { Context as ClientContext } from '@deepseek-ai/cordis'
27
- import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'
28
- import type { ReasoningCapabilities } from '../shared/reasoning'
29
- import { DEFAULT_VALUES } from '../shared/defaults'
30
- import { fetchReasoningCapabilities } from './reasoning-options'
31
- import { useLlmRouting, type LlmRoutingState } from './llm-catalog'
32
- import {
33
- SegmentedControl,
34
- SettingsFormModel,
35
- Switch,
36
- settingsNumberField,
37
- settingsTextField,
38
- } from '@deepseek-ai/dsh-client-ui-primitives'
39
- import type { SettingsFieldDescriptor } from '@deepseek-ai/dsh-client-ui-primitives'
40
- import { NS as LOCALE_NS, zh } from './locales'
41
- import type { PromptEnhanceKey } from './locales'
42
-
43
- /** The settings dialog's navigation slot. */
44
- export const SETTINGS_SECTION_SLOT = 'settings.section'
14
+ import { SettingsFormModel } from '@deepseek-ai/dsh-client-ui-primitives'
15
+ import type {} from '../shared/reasoning'
16
+ import { useLlmRouting } from './llm-catalog'
17
+ import type { LlmRoutingState } from './llm-catalog'
18
+ import { NS as LOCALE_NS } from './locales'
45
19
 
46
- /** Cell id of the settings-dialog page, and the locale namespace its label uses. */
47
- export const SETTINGS_SECTION_ID = 'dsh-prompt-enhance'
48
-
49
- /** Where the page sits among the dialog's sections. */
50
- export const SETTINGS_SECTION_ORDER = 70
51
-
52
- /** The settings-dialog row's title, used when no locale service is mounted. */
53
- export const SETTINGS_SECTION_LABEL = '提示词增强'
20
+ import {
21
+ ADVANCED_ROWS,
22
+ BASIC_ROWS,
23
+ FIELD_SPECS,
24
+ ROWS,
25
+ SETTINGS_NAMESPACE,
26
+ SETTINGS_ROW_CONFIG_KEY,
27
+ SETTINGS_ROW_CONFIG_SLOT,
28
+ SETTINGS_SECTION_ID,
29
+ SETTINGS_SECTION_LABEL,
30
+ SETTINGS_SECTION_ORDER,
31
+ SETTINGS_SECTION_SLOT,
32
+ STRATEGY_OPTIONS,
33
+ atDefaultValue,
34
+ createSettingsForm,
35
+ defaultTextOf,
36
+ viewOf,
37
+ } from './settings-page-spec'
38
+ import type { FieldView, LocaleFaceLike, PageProps, Row, SectionProps, SettingsSnapshot } from './settings-page-spec'
39
+ import { pageCopy, sectionCopy, translator } from './settings-page-copy'
40
+ import type { RowCopy } from './settings-page-copy'
41
+ import { BooleanRow, ChoiceRow, ModelRow, ProviderRow, ReasoningRow, ValueRow } from './settings-page-controls'
42
+ import {
43
+ HEADER_DESCRIPTION_STYLE,
44
+ HEADER_LINK_STYLE,
45
+ HEADER_ROW_STYLE,
46
+ HEADER_STYLE,
47
+ HEADER_TITLE_STYLE,
48
+ HEADER_VERSION_STYLE,
49
+ NPM_MARK,
50
+ NPM_URL,
51
+ PLUGIN_VERSION,
52
+ REPOSITORY_URL,
53
+ SEPARATOR_STYLE,
54
+ GITHUB_MARK,
55
+ } from './settings-page-styles'
56
+
57
+ export { SETTINGS_ROW_CONFIG_KEY, SETTINGS_ROW_CONFIG_SLOT, SETTINGS_SECTION_ID, SETTINGS_SECTION_LABEL, SETTINGS_SECTION_ORDER, SETTINGS_SECTION_SLOT } from './settings-page-spec'
58
+ export { createSettingsForm } from './settings-page-spec'
59
+ export type { LocaleFaceLike } from './settings-page-spec'
54
60
 
55
61
  /**
56
62
  * The settings dialog's navigation title in the active language, with the
@@ -68,411 +74,6 @@ function sectionTitle(getLocale: (() => LocaleFaceLike | undefined) | undefined)
68
74
  }
69
75
  }
70
76
 
71
- /** The plugin manager's keyed slot for one row's configuration page. */
72
- export const SETTINGS_ROW_CONFIG_SLOT = 'plugins.row.config'
73
-
74
- /**
75
- * Settings namespace the host half registers. Spelled here rather than
76
- * imported from `../config`: a client package must not depend on a host
77
- * package, whose module would drag the schema runtime into the browser
78
- * bundle.
79
- */
80
- const SETTINGS_NAMESPACE = 'dsh-prompt-enhance'
81
-
82
- /** The bundle whose patch declares the row, and that row's id. */
83
- const SETTINGS_BUNDLE = '@surfishs/dsh-prompt-enhance'
84
- const SETTINGS_ROW_ID = 'dsh-prompt-enhance'
85
-
86
- /**
87
- * Key of the Plugins-page entry: the plugin manager keys a row as
88
- * `<bundle package name>#<row id>`, so this must stay in step with
89
- * `cordis.patch.yml`'s `id` for the row.
90
- */
91
- export const SETTINGS_ROW_CONFIG_KEY = `${SETTINGS_BUNDLE}#${SETTINGS_ROW_ID}`
92
-
93
- /**
94
- * A boolean descriptor: `true`/`false` in text form, and a real boolean back
95
- * out of `parse`, so a switch writes the JSON type the schema declares.
96
- * Blank text means "clear", matching the bundled helpers' convention.
97
- * @param key - the config key the row edits.
98
- * @returns the descriptor for that key.
99
- */
100
- function settingsBooleanField(key: string): SettingsFieldDescriptor {
101
- return {
102
- field: key,
103
- format: (value) => (typeof value === 'boolean' ? String(value) : ''),
104
- parse: (text) => {
105
- const trimmed = text.trim()
106
- if (trimmed === '') return { kind: 'clear' }
107
- if (trimmed === 'true') return { kind: 'set', value: true }
108
- if (trimmed === 'false') return { kind: 'set', value: false }
109
- return undefined
110
- },
111
- }
112
- }
113
-
114
- /**
115
- * An enum descriptor over a fixed set of strings. Text outside the set is
116
- * staged as invalid instead of being written, so a stale stored value cannot
117
- * be saved back by an accidental edit.
118
- * @param key - the config key the row edits.
119
- * @param options - the accepted values, in display order.
120
- * @returns the descriptor for that key.
121
- */
122
- function settingsEnumField(key: string, options: readonly string[]): SettingsFieldDescriptor {
123
- return {
124
- field: key,
125
- format: (value) => (typeof value === 'string' ? value : ''),
126
- parse: (text) => {
127
- const trimmed = text.trim()
128
- if (trimmed === '') return { kind: 'clear' }
129
- return options.includes(trimmed) ? { kind: 'set', value: trimmed } : undefined
130
- },
131
- }
132
- }
133
-
134
- /** Choices of `strategyMode`, by dictionary key. */
135
- const STRATEGY_OPTIONS: readonly { value: string; label: PromptEnhanceKey }[] = [
136
- { value: 'replace-default', label: 'settings.strategy.replace' },
137
- { value: 'extend-default', label: 'settings.strategy.extend' },
138
- ]
139
-
140
- /** How one row is edited, which picks both its control and its descriptor. */
141
- type RowKind = 'text' | 'number' | 'boolean' | 'strategy' | 'reasoning' | 'provider' | 'model'
142
-
143
- /** One row of both pages, in display order. */
144
- interface Row {
145
- /** The config key; the form reads and writes it by this name. */
146
- readonly key: string
147
- /** Which control renders it. */
148
- readonly kind: RowKind
149
- /** Dictionary key of the row's name. */
150
- readonly label: PromptEnhanceKey
151
- /** Dictionary key of the hint under the row. */
152
- readonly hint: PromptEnhanceKey
153
- /**
154
- * Dictionary key of an example shown greyed out while the input is empty.
155
- * It teaches the expected format without writing any value into the config.
156
- */
157
- readonly placeholder?: PromptEnhanceKey
158
- }
159
-
160
- /**
161
- * Every row both pages edit, in display order: the master switch and the two
162
- * display/context switches first, then routing and generation, then the
163
- * context window, then the host-side resource caps, and the shortcut last.
164
- */
165
- const ROWS: readonly Row[] = [
166
- { key: 'enabled', kind: 'boolean', label: 'settings.row.enabled.label', hint: 'settings.row.enabled.hint' },
167
- { key: 'contextAware', kind: 'boolean', label: 'settings.row.contextAware.label', hint: 'settings.row.contextAware.hint' },
168
- { key: 'streaming', kind: 'boolean', label: 'settings.row.streaming.label', hint: 'settings.row.streaming.hint' },
169
- { key: 'provider', kind: 'provider', label: 'settings.row.provider.label', hint: 'settings.row.provider.hint' },
170
- { key: 'model', kind: 'model', label: 'settings.row.model.label', hint: 'settings.row.model.hint' },
171
- { key: 'reasoningEffort', kind: 'reasoning', label: 'settings.row.reasoningEffort.label', hint: 'settings.row.reasoningEffort.hint' },
172
- { key: 'temperature', kind: 'number', label: 'settings.row.temperature.label', hint: 'settings.row.temperature.hint' },
173
- { key: 'maxOutputTokens', kind: 'number', label: 'settings.row.maxOutputTokens.label', hint: 'settings.row.maxOutputTokens.hint' },
174
- { key: 'maxInputChars', kind: 'number', label: 'settings.row.maxInputChars.label', hint: 'settings.row.maxInputChars.hint' },
175
- { key: 'timeoutMs', kind: 'number', label: 'settings.row.timeoutMs.label', hint: 'settings.row.timeoutMs.hint' },
176
- { key: 'strategyMode', kind: 'strategy', label: 'settings.row.strategyMode.label', hint: 'settings.row.strategyMode.hint' },
177
- { key: 'systemPrompt', kind: 'text', label: 'settings.row.systemPrompt.label', hint: 'settings.row.systemPrompt.hint', placeholder: 'settings.row.systemPrompt.placeholder' },
178
- { key: 'contextMaxMessages', kind: 'number', label: 'settings.row.contextMaxMessages.label', hint: 'settings.row.contextMaxMessages.hint' },
179
- { key: 'contextMaxChars', kind: 'number', label: 'settings.row.contextMaxChars.label', hint: 'settings.row.contextMaxChars.hint' },
180
- { key: 'maxConcurrent', kind: 'number', label: 'settings.row.maxConcurrent.label', hint: 'settings.row.maxConcurrent.hint' },
181
- { key: 'rateLimitPerMinute', kind: 'number', label: 'settings.row.rateLimitPerMinute.label', hint: 'settings.row.rateLimitPerMinute.hint' },
182
- { key: 'shortcut', kind: 'text', label: 'settings.row.shortcut.label', hint: 'settings.row.shortcut.hint', placeholder: 'settings.row.shortcut.placeholder' },
183
- ]
184
-
185
- /**
186
- * The staged form's descriptor for one row.
187
- * @param row - the row to describe.
188
- * @returns its field descriptor.
189
- */
190
- function descriptorOf(row: Row): SettingsFieldDescriptor {
191
- switch (row.kind) {
192
- case 'number':
193
- return settingsNumberField(row.key)
194
- case 'boolean':
195
- return settingsBooleanField(row.key)
196
- case 'strategy':
197
- return settingsEnumField(row.key, STRATEGY_OPTIONS.map((option) => option.value))
198
- case 'reasoning':
199
- // Effort ids are adapter-owned and discovered at render time, so the
200
- // descriptor cannot enumerate them; the segmented control is the only
201
- // writer, and the host validates the id against the route's declaration.
202
- return settingsTextField(row.key)
203
- default:
204
- return settingsTextField(row.key)
205
- }
206
- }
207
-
208
- /** Descriptors in display order; the form model holds one per row. */
209
- const FIELD_SPECS: readonly SettingsFieldDescriptor[] = ROWS.map((row) => descriptorOf(row))
210
-
211
- /**
212
- * Build the staged form these pages render over one settings scope.
213
- *
214
- * Exported so a test can drive the same descriptors the pages use — the
215
- * boolean and enum rows exist precisely because their staged text must parse
216
- * back into a JSON boolean and a known enum string, and that contract is worth
217
- * holding down outside the minified shell.
218
- * @param scope - the settings scope of the plugin's entry.
219
- * @returns the staged form over every row.
220
- */
221
- export function createSettingsForm(scope: unknown): SettingsFormModel {
222
- return new SettingsFormModel(scope, FIELD_SPECS)
223
- }
224
-
225
- /** The translate seat the slot framework injects for the declared namespace. */
226
- type Translate = TranslateNS<typeof LOCALE_NS>
227
-
228
- /** The shipped Chinese dictionary, used when a host projects no `t` seat. */
229
- const ZH_COPY: Readonly<Record<string, string>> = zh
230
-
231
- /**
232
- * Resolve the Plugins-page copy reader: the injected `t` when present, the
233
- * shipped Chinese dictionary otherwise. Falling back keeps an older host (or a
234
- * test) from rendering dictionary keys instead of copy.
235
- * @param t - the injected translate seat, if any.
236
- * @returns a reader for this page's keys.
237
- */
238
- function translator(t: Translate | undefined): Translate {
239
- if (typeof t === 'function') return t
240
- // The fallback dictionary must interpolate `{name}` placeholders too, or a
241
- // parameterized line would render its raw template.
242
- return ((key: string, params?: Readonly<Record<string, unknown>>) => {
243
- let text = ZH_COPY[key] ?? key
244
- for (const [name, value] of Object.entries(params ?? {})) {
245
- text = text.split(`{${name}}`).join(String(value))
246
- }
247
- return text
248
- }) as unknown as Translate
249
- }
250
-
251
- /** How one surface titles and explains the rows. */
252
- interface RowCopy {
253
- /** Copy of the shared form frame, plus the labels the custom rows draw. */
254
- readonly labels: Readonly<Record<string, string>>
255
- /** The row's title. */
256
- readonly title: (row: Row) => string
257
- /** The hint under the row. */
258
- readonly hint: (row: Row) => string
259
- /** An example shown greyed out while the input is empty, when the row has one. */
260
- readonly placeholder: (row: Row) => string | undefined
261
- /** One choice label of a segmented control. */
262
- readonly choice: (key: PromptEnhanceKey) => string
263
- /** One parameterized status line (dynamic reasoning tiers). */
264
- readonly interpolate: (key: PromptEnhanceKey, params: Record<string, string>) => string
265
- }
266
-
267
- /**
268
- * The settings dialog's copy: the raw config key first, then the localized
269
- * name in parentheses while the client is Chinese, and one single-language
270
- * hint. English mode drops the parenthesized Chinese name entirely — the key
271
- * alone is the title there.
272
- * @param t - the locale-bound translate seat.
273
- * @param chinese - whether the active locale is Chinese.
274
- * @returns the row copy for that language.
275
- */
276
- function sectionCopy(t: Translate, chinese: boolean): RowCopy {
277
- return {
278
- labels: {
279
- unavailable: t('settings.unavailable'),
280
- readOnly: t('settings.readOnly'),
281
- saveFailed: t('settings.saveFailed'),
282
- saveFailedShort: t('settings.saveFailedShort'),
283
- save: t('settings.save'),
284
- saving: t('settings.saving'),
285
- saved: t('settings.saved'),
286
- reset: t('settings.reset'),
287
- invalidNumber: t('settings.invalidNumber'),
288
- },
289
- title: (row) => (chinese ? `${row.key}(${t(row.label)})` : row.key),
290
- hint: (row) => t(row.hint),
291
- placeholder: (row) => (row.placeholder === undefined ? undefined : t(row.placeholder)),
292
- choice: (key) => t(key),
293
- interpolate: (key, params) => t(key, params),
294
- }
295
- }
296
-
297
- /**
298
- * The Plugins page's copy: the active locale's title and single-sentence hint,
299
- * as the host's own configuration pages read.
300
- * @param t - the injected translate seat.
301
- * @returns the row copy for that locale.
302
- */
303
- function pageCopy(t: Translate): RowCopy {
304
- return {
305
- labels: {
306
- unavailable: t('settings.unavailable'),
307
- readOnly: t('settings.readOnly'),
308
- saveFailed: t('settings.saveFailed'),
309
- saveFailedShort: t('settings.saveFailedShort'),
310
- save: t('settings.save'),
311
- saving: t('settings.saving'),
312
- saved: t('settings.saved'),
313
- reset: t('settings.reset'),
314
- invalidNumber: t('settings.invalidNumber'),
315
- },
316
- title: (row) => t(row.label),
317
- hint: (row) => t(row.hint),
318
- placeholder: (row) => (row.placeholder === undefined ? undefined : t(row.placeholder)),
319
- choice: (key) => t(key),
320
- interpolate: (key, params) => t(key, params),
321
- }
322
- }
323
-
324
- /**
325
- * Inline copies of the host form's row metrics (the shell's `181ew` styles
326
- * module), so a switch or segmented row lines up with the text rows the
327
- * primitives render instead of looking like a foreign control.
328
- */
329
- const ROW_STYLE: CSSProperties = { display: 'flex', flexDirection: 'column', gap: 6, padding: '12px 0' }
330
- const HEAD_STYLE: CSSProperties = { display: 'flex', alignItems: 'center', gap: 8 }
331
- const LABEL_STYLE: CSSProperties = {
332
- flex: 1,
333
- minWidth: 0,
334
- fontSize: 13,
335
- fontWeight: 500,
336
- lineHeight: 1.5,
337
- color: 'var(--dsw-alias-label-primary, inherit)',
338
- }
339
- const HINT_STYLE: CSSProperties = {
340
- margin: 0,
341
- fontSize: 12,
342
- lineHeight: 1.5,
343
- color: 'var(--dsw-alias-label-tertiary, inherit)',
344
- }
345
- /** Dynamic-tier status line under the reasoning control. */
346
- const STATUS_STYLE: CSSProperties = {
347
- margin: 0,
348
- fontSize: 12,
349
- lineHeight: 1.5,
350
- color: 'var(--dsw-alias-label-secondary, inherit)',
351
- }
352
- /** The neutral chip surface shared by the row's quiet actions. */
353
- const CHIP_STYLE: CSSProperties = {
354
- display: 'inline-flex',
355
- alignItems: 'center',
356
- padding: '1px 8px',
357
- border: 'none',
358
- borderRadius: 999,
359
- background: 'var(--dsw-alias-bg-module-platform, rgba(128, 128, 128, 0.12))',
360
- fontFamily: 'inherit',
361
- fontSize: 11,
362
- fontWeight: 500,
363
- lineHeight: '17px',
364
- color: 'var(--dsw-alias-label-secondary, inherit)',
365
- textDecoration: 'underline',
366
- textUnderlineOffset: 2,
367
- cursor: 'pointer',
368
- }
369
- /** The tier refetch action, in the same chip surface. */
370
- const REFRESH_STYLE: CSSProperties = { ...CHIP_STYLE, flex: 'none' }
371
- /** The reset action: the neutral chip surface, with an underline for affordance. */
372
- const RESET_STYLE: CSSProperties = CHIP_STYLE
373
- /** One border for every form control, so focus never changes the outline width. */
374
- const FIELD_BORDER = '1px solid rgba(128, 128, 128, 0.38)'
375
- /** The form input, mirroring the host's `input` metrics for a native control. */
376
- const INPUT_STYLE: CSSProperties = {
377
- boxSizing: 'border-box',
378
- width: '100%',
379
- height: 34,
380
- padding: '0 12px',
381
- border: FIELD_BORDER,
382
- borderRadius: 'var(--dsw-radius-md, 8px)',
383
- background: 'var(--dsw-alias-bg-layer-3, transparent)',
384
- font: 'inherit',
385
- fontSize: 13,
386
- lineHeight: 1.5,
387
- color: 'var(--dsw-alias-label-primary, inherit)',
388
- outline: 'none',
389
- }
390
- /** The error line under an invalid numeric row. */
391
- const INVALID_STYLE: CSSProperties = {
392
- margin: 0,
393
- fontSize: 12,
394
- lineHeight: 1.5,
395
- color: 'var(--dsw-alias-state-error-primary, #f85149)',
396
- }
397
- /** The warning line under the routing rows; saves are not blocked by it. */
398
- const WARN_STYLE: CSSProperties = {
399
- margin: 0,
400
- fontSize: 12,
401
- lineHeight: 1.5,
402
- color: 'var(--dsw-alias-state-error-primary, #f85149)',
403
- }
404
- /** The provider/model select, sharing the value input's metrics. */
405
- const SELECT_STYLE: CSSProperties = {
406
- ...INPUT_STYLE,
407
- cursor: 'pointer',
408
- }
409
- const SEPARATOR_STYLE: CSSProperties = {
410
- borderTop: '0.5px solid var(--dsw-alias-border-l2, rgba(128, 128, 128, 0.24))',
411
- }
412
-
413
- /** Public repository behind this build, linked from the page header. */
414
- const REPOSITORY_URL = 'https://github.com/surfishs/dsh-prompt-enhance'
415
-
416
- /** Public npm package page, linked from the page header next to the repository. */
417
- const NPM_URL = 'https://www.npmjs.com/package/@surfishs/dsh-prompt-enhance'
418
-
419
- /** The GitHub mark (16×16), painted with the current text color. */
420
- const GITHUB_MARK =
421
- 'M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82a7.6 7.6 0 0 1 2-.27c.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.01 8.01 0 0 0 16 8c0-4.42-3.58-8-8-8z'
422
-
423
- /** The npm mark (24×24), painted with the current text color. */
424
- const NPM_MARK =
425
- 'M1.763 0C.786 0 0 .786 0 1.763v20.474C0 23.214.786 24 1.763 24h20.474c.977 0 1.763-.786 1.763-1.763V1.763C24 .786 23.214 0 22.237 0zM5.13 5.323l13.837.019-.009 13.836h-3.464l.01-10.382h-3.456L12.04 19.17H5.113z'
426
-
427
- /** The version this bundle was built from; guarded for environments without the define. */
428
- const PLUGIN_VERSION = typeof __PLUGIN_VERSION__ === 'string' ? __PLUGIN_VERSION__ : '0.0.0'
429
-
430
- /** Header block: title, repository link, version, and one description line. */
431
- const HEADER_STYLE: CSSProperties = { display: 'flex', flexDirection: 'column', gap: 12, padding: '2px 0' }
432
- const HEADER_ROW_STYLE: CSSProperties = { display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }
433
- const HEADER_TITLE_STYLE: CSSProperties = {
434
- fontSize: 18,
435
- fontWeight: 600,
436
- letterSpacing: '-0.012em',
437
- lineHeight: 1.3,
438
- color: 'var(--dsw-alias-label-primary, inherit)',
439
- }
440
- const HEADER_LINK_STYLE: CSSProperties = {
441
- display: 'inline-flex',
442
- alignItems: 'center',
443
- gap: 3,
444
- height: 18,
445
- padding: '0 7px',
446
- border: '1px solid var(--dsw-alias-border-l4, rgba(128, 128, 128, 0.35))',
447
- borderRadius: 999,
448
- background: 'var(--dsw-alias-bg-layer-3, transparent)',
449
- fontSize: 10.5,
450
- fontWeight: 500,
451
- lineHeight: 1,
452
- color: 'var(--dsw-alias-label-secondary, inherit)',
453
- textDecoration: 'none',
454
- }
455
- const HEADER_VERSION_STYLE: CSSProperties = {
456
- display: 'inline-flex',
457
- alignItems: 'center',
458
- height: 18,
459
- padding: '0 7px',
460
- borderRadius: 999,
461
- background: 'var(--dsw-alias-bg-layer-4, transparent)',
462
- fontSize: 10.5,
463
- lineHeight: 1,
464
- color: 'var(--dsw-alias-label-tertiary, inherit)',
465
- fontVariantNumeric: 'tabular-nums',
466
- }
467
- const HEADER_DESCRIPTION_STYLE: CSSProperties = {
468
- margin: 0,
469
- fontSize: 13,
470
- lineHeight: 1.65,
471
- color: 'var(--dsw-alias-label-tertiary, inherit)',
472
- textWrap: 'pretty',
473
- maxWidth: '72ch',
474
- }
475
-
476
77
  /**
477
78
  * The page header the settings dialog shows above the form: the plugin title,
478
79
  * a repository link chip and the shipped version, with one description line.
@@ -503,582 +104,23 @@ function PageHeader(props: { title: string; description: string; version: string
503
104
  )
504
105
  }
505
106
 
506
- /** One projection of the pages' form store. */
507
- interface SettingsSnapshot {
508
- writable?: boolean
509
- [key: string]: unknown
510
- }
511
-
512
- /** One row's projection inside that snapshot. */
513
- interface FieldView {
514
- text: string
515
- overridden: boolean
516
- invalid: boolean
517
- }
518
-
519
- /** The staged form's actions, as both slots hand them over. */
520
- interface FormProps {
521
- /**
522
- * The store hook, named after the `inject()` hook key (`promptEnhance`).
523
- * Absent when the host does not project hooks for this slot; the component
524
- * renders the explanation instead of throwing, because a throwing page
525
- * blanks the pane.
526
- */
527
- usePromptEnhance?: (selector: (snapshot: SettingsSnapshot) => SettingsSnapshot) => SettingsSnapshot
528
- edit?: (key: string, text: string) => void
529
- resetField?: (key: string) => void
530
- save?: () => void
531
- discard?: () => void
532
- writeField?: (key: string, text: string) => Promise<'saved' | 'invalid' | 'failed'>
533
- }
534
-
535
- /** One locale snapshot, as the client locale service exposes it. */
536
- interface LocaleSnapshotLike {
537
- /** Active locale id, e.g. `zh` or `en`. */
538
- active?: string
539
- /** Monotonic revision; changes on locale switches and dictionary registration. */
540
- revision?: number
541
- }
542
-
543
- /** The client locale service, reached structurally so no package type is needed. */
544
- export interface LocaleFaceLike {
545
- bind(namespace: string): Translate
546
- getSnapshot(): LocaleSnapshotLike
547
- subscribe(listener: () => void): () => void
548
- }
549
-
550
- /** Props of the settings-dialog page. */
551
- type SectionProps = FormProps & {
552
- /** The locale-bound translate seat this plugin projects into the page. */
553
- translate?: Translate
554
- /** Locale snapshot selector hook; re-renders the page when the language changes. */
555
- usePromptEnhanceLocale?: (selector: (snapshot: LocaleSnapshotLike) => LocaleSnapshotLike) => LocaleSnapshotLike
556
- }
557
-
558
- /** Props the plugin manager hands a configuration page. */
559
- interface PageProps extends FormProps {
560
- /** Translate seat of this page's locale namespace, injected by the slot. */
561
- t?: Translate
562
- /** Which view the manager asks for: the form, or the one-line summary. */
563
- view?: 'page' | 'summary'
564
- }
565
-
566
- /** Props shared by every row component: the row, its copy, its state, its actions. */
567
- interface RowProps {
568
- /** The DOM id of the row's control. */
569
- id: string
570
- /** The row's title, already resolved. */
571
- label: string
572
- /** The hint under the row, already resolved. */
573
- hint: string
574
- /** The frame's copy, for the overridden badge and its reset button. */
107
+ /**
108
+ * One row, rendered as the control its kind asks for.
109
+ * @param props - the row, its copy, its state, its actions, and the pinned pair.
110
+ * @returns the row element.
111
+ */
112
+ function SettingsRow(props: {
113
+ row: Row
575
114
  copy: RowCopy
576
- /** The row's staged state. */
577
115
  view: FieldView
578
- /** Whether writes are refused by this deployment. */
579
116
  disabled: boolean
580
- /** Stage new text for this row. */
117
+ reasoningPair: { provider: string; model: string }
118
+ routing: LlmRoutingState
119
+ providerValue: string
581
120
  onEdit: (text: string) => void
582
- /** Clear the stored value so the row re-inherits the composition default. */
583
121
  onReset: () => void
584
- /** Commit the current text now, e.g. on blur or Enter. */
585
- onCommit?: () => void
586
- }
587
-
588
- /**
589
- * Read one row's projection out of the page snapshot.
590
- *
591
- * A row the host schema does not declare is absent from the projection; it
592
- * renders as an empty, non-overridden field rather than throwing.
593
- * @param snapshot - the page's current snapshot.
594
- * @param key - the row's config key.
595
- * @returns the row's text form and staging flags.
596
- */
597
- function viewOf(snapshot: SettingsSnapshot, key: string): FieldView {
598
- const value = snapshot[key]
599
- if (value === null || typeof value !== 'object') return { text: '', overridden: false, invalid: false }
600
- const field = value as { text?: unknown; overridden?: unknown; invalid?: unknown }
601
- return {
602
- text: typeof field.text === 'string' ? field.text : '',
603
- overridden: field.overridden === true,
604
- invalid: field.invalid === true,
605
- }
606
- }
607
-
608
- /**
609
- * Whether one row's current text equals its shipped default.
610
- *
611
- * The host form reports `overridden` as "this field was written explicitly"
612
- * (stored value or a staged set), which stays true even when the user edits
613
- * the value back to the default. The badge and its reset action only make
614
- * sense while there is something to reset, so visibility is derived from this
615
- * comparison instead — for text/number/enum rows alike.
616
- * @param key - the config key.
617
- * @param text - the row's current staged text.
618
- * @returns true when editing can no longer change anything from the default.
619
- */
620
- function atDefaultValue(key: string, text: string): boolean {
621
- const fallback = (DEFAULT_VALUES as Record<string, unknown>)[key]
622
- // provider/model are absent from the defaults on purpose: empty means follow.
623
- if (fallback === undefined) return text.trim() === ''
624
- if (typeof fallback === 'boolean') return text.trim() === String(fallback)
625
- if (typeof fallback === 'number') {
626
- const parsed = Number(text.trim())
627
- return Number.isFinite(parsed) && parsed === fallback
628
- }
629
- return text.trim() === String(fallback)
630
- }
631
-
632
- /**
633
- * The "overridden" badge and its reset button, as the text rows draw them.
634
- * @param props - the frame copy, whether writes are refused, and the reset handler.
635
- * @returns the badge pair.
636
- */
637
- function OverrideActions(props: { copy: RowCopy; disabled: boolean; onReset: () => void }): ReactElement {
638
- return (
639
- <button
640
- type="button"
641
- style={{ ...RESET_STYLE, ...props.disabled ? { opacity: 0.5, cursor: 'default' } : {} }}
642
- disabled={props.disabled}
643
- onClick={props.onReset}
644
- >
645
- {props.copy.labels.reset}
646
- </button>
647
- )
648
- }
649
-
650
- /**
651
- * A boolean row: the title and the shell's switch on one line, the hint below.
652
- * @param props - the row, its copy, its state, and its actions.
653
- * @returns the row element.
654
- */
655
- function BooleanRow(props: RowProps): ReactElement {
656
- return (
657
- <div style={ROW_STYLE}>
658
- <div style={HEAD_STYLE}>
659
- <span style={LABEL_STYLE}>{props.label}</span>
660
- {props.view.overridden ? <OverrideActions copy={props.copy} disabled={props.disabled} onReset={props.onReset} /> : null}
661
- <Switch
662
- checked={props.view.text === 'true'}
663
- disabled={props.disabled}
664
- label={props.label}
665
- onChange={(next: boolean) => props.onEdit(next ? 'true' : 'false')}
666
- />
667
- </div>
668
- <p style={HINT_STYLE}>{props.hint}</p>
669
- </div>
670
- )
671
- }
672
-
673
- /**
674
- * A fixed-choice row: the shell's segmented control under the title.
675
- * @param props - the row, its choices, its state, and its actions.
676
- * @returns the row element.
677
- */
678
- function ChoiceRow(props: RowProps & { options: readonly { value: string; label: string; title?: string }[] }): ReactElement {
679
- return (
680
- <div style={ROW_STYLE}>
681
- <div style={HEAD_STYLE}>
682
- <span style={LABEL_STYLE}>{props.label}</span>
683
- {props.view.overridden ? <OverrideActions copy={props.copy} disabled={props.disabled} onReset={props.onReset} /> : null}
684
- </div>
685
- <SegmentedControl
686
- id={props.id}
687
- className="dsh-pe-segmented-labels"
688
- value={props.view.text}
689
- options={props.options.map((option) => ({ ...option, title: option.title ?? option.label }))}
690
- disabled={props.disabled}
691
- label={props.label}
692
- onChange={(next: string) => props.onEdit(next)}
693
- />
694
- <p style={HINT_STYLE}>{props.hint}</p>
695
- </div>
696
- )
697
- }
698
-
699
- /**
700
- * The reasoning row: choices come from what the configured route declares.
701
- *
702
- * - Both provider/model empty → follow the default model; the host answers from
703
- * its static DeepSeek catalog, or reports unavailable when the default is not
704
- * DeepSeek. This path is not cached (the page cannot observe the default).
705
- * - A pinned pair → the answer is cached in `localStorage` with no TTL; it is
706
- * replaced only when the pair changes or the user presses refresh.
707
- *
708
- * While the answer is pending, or when it is unavailable, the control offers
709
- * only "follow provider default" instead of guessing a tier list.
710
- * @param props - the row, its copy, state, actions, and the pinned pair.
711
- * @returns the row element.
712
- */
713
- function ReasoningRow(props: RowProps & { provider: string; model: string }): ReactElement {
714
- const pair = props.provider !== '' && props.model !== '' ? `${props.provider}/${props.model}` : ''
715
- const [phase, setPhase] = useState<'loading' | 'ready'>('loading')
716
- const [capabilities, setCapabilities] = useState<ReasoningCapabilities | undefined>(undefined)
717
- const [refreshToken, setRefreshToken] = useState(0)
718
- const [feedback, setFeedback] = useState<'idle' | 'refreshing' | 'ok' | 'failed'>('idle')
719
- const forceRef = useRef(false)
720
- const feedbackTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
721
-
722
- useEffect(() => {
723
- const controller = new AbortController()
724
- const force = forceRef.current
725
- forceRef.current = false
726
- setPhase('loading')
727
- setCapabilities(undefined)
728
- setFeedback(force ? 'refreshing' : 'idle')
729
- if (feedbackTimer.current !== undefined) {
730
- clearTimeout(feedbackTimer.current)
731
- feedbackTimer.current = undefined
732
- }
733
- /** Settle the manual-refresh feedback; initial loads show no outcome. */
734
- const settle = (result: 'ok' | 'failed'): void => {
735
- if (!force) return
736
- setFeedback(result)
737
- feedbackTimer.current = setTimeout(() => {
738
- setFeedback('idle')
739
- feedbackTimer.current = undefined
740
- }, 3000)
741
- }
742
- fetchReasoningCapabilities(
743
- props.provider === '' ? undefined : props.provider,
744
- props.model === '' ? undefined : props.model,
745
- { refresh: force, signal: controller.signal },
746
- )
747
- .then((answer) => {
748
- if (controller.signal.aborted) return
749
- setCapabilities(answer)
750
- setPhase('ready')
751
- settle(answer.source === 'unavailable' ? 'failed' : 'ok')
752
- })
753
- .catch(() => {
754
- if (controller.signal.aborted) return
755
- setCapabilities({ efforts: [], source: 'unavailable', reason: 'resolve-failed' })
756
- setPhase('ready')
757
- settle('failed')
758
- })
759
- return () => {
760
- controller.abort()
761
- if (feedbackTimer.current !== undefined) {
762
- clearTimeout(feedbackTimer.current)
763
- feedbackTimer.current = undefined
764
- }
765
- }
766
- // `pair` covers both ids; the default path reuses the empty string.
767
- // eslint-disable-next-line react-hooks/exhaustive-deps
768
- }, [pair, refreshToken])
769
-
770
- // Every provider — DeepSeek included — shows the adapter's own tier names;
771
- // only the "follow provider default" sentinel is plugin copy.
772
- const current = props.view.text
773
- const realTierKnown = phase === 'ready' && capabilities !== undefined && capabilities.source !== 'unavailable'
774
- && capabilities.efforts.some((effort) => effort.id === current)
775
- const noTiers = phase === 'ready' && capabilities !== undefined && capabilities.source === 'unavailable' && capabilities.reason === 'no-efforts'
776
- const options: { value: string; label: string; title?: string }[] = []
777
- // A value the route does not declare (stale config, or while the list is
778
- // still loading) is kept as a visible synthetic choice. Without it the
779
- // segmented control's indicator has no matching option and slides off the
780
- // left edge.
781
- if (!noTiers && current !== '' && current !== 'inherit' && !realTierKnown) {
782
- options.push({
783
- value: current,
784
- label: props.copy.interpolate('settings.reasoning.current', { value: current }),
785
- title: props.copy.choice('settings.reasoning.currentTitle'),
786
- })
787
- }
788
- if (phase === 'ready' && capabilities !== undefined && capabilities.source !== 'unavailable') {
789
- for (const effort of capabilities.efforts) {
790
- options.push({
791
- value: effort.id,
792
- label: effort.name,
793
- title: effort.description === undefined ? effort.name : `${effort.name} — ${effort.description}`,
794
- })
795
- }
796
- }
797
- options.push({
798
- value: 'inherit',
799
- label: props.copy.choice('settings.reasoning.inherit'),
800
- title: props.copy.choice('settings.reasoning.inherit'),
801
- })
802
- const unsupported = !noTiers && phase === 'ready' && capabilities?.source !== 'unavailable'
803
- && current !== '' && current !== 'inherit' && !realTierKnown
804
- const refreshing = feedback === 'refreshing'
805
- const refresh = (): void => {
806
- forceRef.current = true
807
- setRefreshToken((token) => token + 1)
808
- }
809
- return (
810
- <div style={ROW_STYLE}>
811
- <div style={HEAD_STYLE}>
812
- <span style={LABEL_STYLE}>{props.label}</span>
813
- {phase === 'ready' || refreshing
814
- ? (
815
- <button
816
- type="button"
817
- style={{ ...REFRESH_STYLE, opacity: props.disabled || refreshing ? 0.5 : 1 }}
818
- disabled={props.disabled || refreshing}
819
- onClick={refresh}
820
- >
821
- {props.copy.choice(refreshing ? 'settings.reasoning.refreshing' : 'settings.reasoning.refresh')}
822
- </button>
823
- )
824
- : null}
825
- {props.view.overridden ? <OverrideActions copy={props.copy} disabled={props.disabled} onReset={props.onReset} /> : null}
826
- </div>
827
- <SegmentedControl
828
- id={props.id}
829
- className="dsh-pe-segmented-labels"
830
- // A route that declares no tiers is presented as "follow provider
831
- // default"; the stored tier stays in the config and the host omits it
832
- // on the call, so the displayed state matches what actually happens.
833
- value={noTiers ? 'inherit' : props.view.text}
834
- options={options}
835
- // "Follow provider default" stays selectable while the tier list is
836
- // still loading; the tier choices themselves only appear once known.
837
- disabled={props.disabled}
838
- label={props.label}
839
- onChange={(next: string) => props.onEdit(next)}
840
- />
841
- <p style={HINT_STYLE}>{props.hint}</p>
842
- {phase === 'loading' ? <p style={STATUS_STYLE}>{props.copy.choice('settings.reasoning.loading')}</p> : null}
843
- {phase === 'ready' && capabilities?.source === 'unavailable'
844
- ? <p style={STATUS_STYLE}>{props.copy.choice(noTiers ? 'settings.reasoning.noTiers' : 'settings.reasoning.unavailable')}</p>
845
- : null}
846
- {unsupported ? (
847
- <p style={STATUS_STYLE}>{props.copy.interpolate('settings.reasoning.unsupported', { effort: props.view.text })}</p>
848
- ) : null}
849
- {feedback === 'ok' ? <p style={STATUS_STYLE} aria-live="polite">{props.copy.choice('settings.reasoning.refreshOk')}</p> : null}
850
- {feedback === 'failed' ? <p style={STATUS_STYLE} aria-live="polite">{props.copy.choice('settings.reasoning.refreshFailed')}</p> : null}
851
- </div>
852
- )
853
- }
854
-
855
- /**
856
- * The shared select control: a 1px resting border (a hairline can vanish at
857
- * some scale factors) and a business-colour border while focused, so the
858
- * control's outline never depends on the browser's focus ring.
859
- */
860
- function SelectControl(props: { id: string; value: string; disabled?: boolean; onChange: (value: string) => void; children: ReactNode }): ReactElement {
861
- const [focused, setFocused] = useState(false)
862
- return (
863
- <select
864
- id={props.id}
865
- style={{ ...SELECT_STYLE, ...focused ? { borderColor: 'var(--dsw-alias-state-business-primary, #4f8cff)' } : {} }}
866
- value={props.value}
867
- disabled={props.disabled}
868
- onFocus={() => setFocused(true)}
869
- onBlur={() => setFocused(false)}
870
- onChange={(event) => props.onChange(event.target.value)}
871
- >
872
- {props.children}
873
- </select>
874
- )
875
- }
876
-
877
- /**
878
- * The provider select: registered providers plus dormant ones rendered
879
- * disabled, and a synthetic entry for a stored value outside the registry.
880
- * @param props - the row, its state, and the catalog reads.
881
- * @returns the row element.
882
- */
883
- function ProviderRow(props: RowProps & { routing: LlmRoutingState }): ReactElement {
884
- const current = props.view.text
885
- const known = props.routing.providers.entries.find((entry) => entry.id === current)
886
- const missing = current !== '' && known === undefined
887
- const unconfigured = known !== undefined && !known.registered
888
- return (
889
- <div style={ROW_STYLE}>
890
- <div style={HEAD_STYLE}>
891
- <label htmlFor={props.id} style={LABEL_STYLE}>{props.label}</label>
892
- {props.view.overridden ? <OverrideActions copy={props.copy} disabled={props.disabled} onReset={props.onReset} /> : null}
893
- </div>
894
- <SelectControl id={props.id} value={current} disabled={props.disabled} onChange={(value) => props.onEdit(value)}>
895
- <option value="">{props.copy.choice('settings.routing.followSession')}</option>
896
- {missing ? <option value={current} title={current}>{props.copy.interpolate('settings.routing.currentProvider', { value: current })}</option> : null}
897
- <optgroup label={props.copy.choice('settings.routing.groupRegistered')}>
898
- {props.routing.providers.entries.filter((entry) => entry.registered).map((entry) => (
899
- <option key={entry.id} value={entry.id} title={entry.id}>{entry.name}</option>
900
- ))}
901
- </optgroup>
902
- {props.routing.providers.entries.some((entry) => !entry.registered)
903
- ? (
904
- <optgroup label={props.copy.choice('settings.routing.groupDormant')}>
905
- {props.routing.providers.entries.filter((entry) => !entry.registered).map((entry) => (
906
- <option key={entry.id} value={entry.id} disabled title={props.copy.choice('settings.routing.unconfiguredTitle')}>
907
- {entry.name}{props.copy.choice('settings.routing.unconfiguredSuffix')}
908
- </option>
909
- ))}
910
- </optgroup>
911
- )
912
- : null}
913
- </SelectControl>
914
- <p style={HINT_STYLE}>{props.hint}</p>
915
- {props.routing.providers.loading ? <p style={STATUS_STYLE}>{props.copy.choice('settings.routing.providersLoading')}</p> : null}
916
- {props.routing.providers.failed ? <p style={STATUS_STYLE}>{props.copy.choice('settings.routing.providersFailed')}</p> : null}
917
- {props.routing.providers.failed ? (
918
- <button type="button" style={REFRESH_STYLE} onClick={props.routing.providers.reload}>
919
- {props.copy.choice('settings.routing.retry')}
920
- </button>
921
- ) : null}
922
- {missing ? <p style={WARN_STYLE}>{props.copy.interpolate('settings.routing.providerMissing', { value: current })}</p> : null}
923
- {unconfigured ? <p style={WARN_STYLE}>{props.copy.interpolate('settings.routing.providerUnconfigured', { name: known.name })}</p> : null}
924
- </div>
925
- )
926
- }
927
-
928
- /**
929
- * The model select: the provider's advertised models, a "custom…" entry that
930
- * reveals a free-text input, and warnings (incomplete pair / unresolvable
931
- * route) that never block saving.
932
- * @param props - the row, its state, the catalog reads, and the provider value.
933
- * @returns the row element.
934
- */
935
- function ModelRow(props: RowProps & { routing: LlmRoutingState; providerValue: string }): ReactElement {
936
- const current = props.view.text
937
- const provider = props.providerValue
938
- const [customMode, setCustomMode] = useState(false)
939
- const known = props.routing.models.entries.some((entry) => entry.id === current)
940
- // A stored model outside the advertised catalog is still editable, so the
941
- // custom input opens automatically for it instead of hiding the value.
942
- const showCustom = provider !== '' && (customMode || (current !== '' && !known))
943
- const pairIncomplete = provider !== '' && current === ''
944
- const routeUnavailable = provider !== '' && current !== '' && props.routing.route.available === false
945
- return (
946
- <div style={ROW_STYLE}>
947
- <div style={HEAD_STYLE}>
948
- <label htmlFor={props.id} style={LABEL_STYLE}>{props.label}</label>
949
- {props.view.overridden ? <OverrideActions copy={props.copy} disabled={props.disabled} onReset={props.onReset} /> : null}
950
- </div>
951
- <SelectControl
952
- id={props.id}
953
- value={showCustom ? '__custom__' : current}
954
- disabled={props.disabled || provider === ''}
955
- onChange={(value) => {
956
- if (value === '__custom__') {
957
- setCustomMode(true)
958
- return
959
- }
960
- setCustomMode(false)
961
- props.onEdit(value)
962
- }}
963
- >
964
- <option value="">{provider === '' ? props.copy.choice('settings.routing.followSession') : props.copy.choice('settings.routing.selectModel')}</option>
965
- {props.routing.models.entries.map((entry) => (
966
- <option key={entry.id} value={entry.id} title={entry.id}>{entry.name}</option>
967
- ))}
968
- {provider !== '' && current !== '' && !known
969
- ? <option value={current} title={current}>{props.copy.interpolate('settings.routing.currentModel', { value: current })}</option>
970
- : null}
971
- {provider !== '' ? <option value="__custom__">{props.copy.choice('settings.routing.custom')}</option> : null}
972
- </SelectControl>
973
- {showCustom ? (
974
- <TextControl
975
- value={current}
976
- placeholder={props.copy.choice('settings.routing.customPlaceholder')}
977
- disabled={props.disabled}
978
- onChange={props.onEdit}
979
- />
980
- ) : null}
981
- <p style={HINT_STYLE}>{props.hint}</p>
982
- {props.routing.models.loading ? <p style={STATUS_STYLE}>{props.copy.choice('settings.routing.modelsLoading')}</p> : null}
983
- {props.routing.models.failed && !showCustom ? <p style={STATUS_STYLE}>{props.copy.choice('settings.routing.modelsFailed')}</p> : null}
984
- {pairIncomplete ? <p style={WARN_STYLE}>{props.copy.choice('settings.routing.pairIncomplete')}</p> : null}
985
- {routeUnavailable ? <p style={WARN_STYLE}>{props.copy.choice('settings.routing.routeUnavailable')}</p> : null}
986
- </div>
987
- )
988
- }
989
-
990
- /**
991
- * A text/number row: the title and the reset chip on one line, a native input,
992
- * then the hint. The host's `SettingsValueField` draws its own badge and reset
993
- * link, which would diverge from the chip the other rows use, so value rows
994
- * share this control instead.
995
- * @param props - the row, its copy, state, and whether it is numeric.
996
- * @returns the row element.
997
- */
998
- /**
999
- * The shared text/number control: the same 1px border as the selects, turning
1000
- * the same business colour while focused (the invalid state wins over focus).
1001
- */
1002
- function TextControl(props: {
1003
- id?: string
1004
- value: string
1005
- placeholder?: string
1006
- numeric?: boolean
1007
- invalid?: boolean
1008
- disabled?: boolean
1009
- onChange: (value: string) => void
1010
122
  onCommit?: () => void
1011
123
  }): ReactElement {
1012
- const [focused, setFocused] = useState(false)
1013
- const [revealedInvalid, setRevealedInvalid] = useState(false)
1014
- useEffect(() => {
1015
- if (props.invalid !== true) setRevealedInvalid(false)
1016
- }, [props.invalid])
1017
- const showInvalid = props.invalid === true && revealedInvalid
1018
- const borderColor = showInvalid
1019
- ? 'var(--dsw-alias-state-error-primary, #f85149)'
1020
- : focused ? 'var(--dsw-alias-state-business-primary, #4f8cff)' : undefined
1021
- return (
1022
- <input
1023
- id={props.id}
1024
- type="text"
1025
- inputMode={props.numeric === true ? 'numeric' : undefined}
1026
- aria-invalid={showInvalid || undefined}
1027
- disabled={props.disabled}
1028
- placeholder={props.placeholder}
1029
- value={props.value}
1030
- style={{
1031
- ...INPUT_STYLE,
1032
- ...props.disabled === true ? { color: 'var(--dsw-alias-label-tertiary, inherit)', cursor: 'default' } : {},
1033
- ...borderColor === undefined ? {} : { borderColor },
1034
- }}
1035
- onFocus={() => setFocused(true)}
1036
- onBlur={() => {
1037
- setFocused(false)
1038
- if (props.invalid === true) setRevealedInvalid(true)
1039
- props.onCommit?.()
1040
- }}
1041
- onKeyDown={(event) => {
1042
- if (event.key !== 'Enter') return
1043
- event.preventDefault()
1044
- if (props.invalid === true) setRevealedInvalid(true)
1045
- props.onCommit?.()
1046
- }}
1047
- onChange={(event) => props.onChange(event.target.value)}
1048
- />
1049
- )
1050
- }
1051
-
1052
- function ValueRow(props: RowProps & { numeric: boolean; placeholder?: string }): ReactElement {
1053
- const invalid = props.view.invalid
1054
- return (
1055
- <div style={ROW_STYLE}>
1056
- <div style={HEAD_STYLE}>
1057
- <label htmlFor={props.id} style={LABEL_STYLE}>{props.label}</label>
1058
- {props.view.overridden ? <OverrideActions copy={props.copy} disabled={props.disabled} onReset={props.onReset} /> : null}
1059
- </div>
1060
- <TextControl
1061
- id={props.id}
1062
- value={props.view.text}
1063
- placeholder={props.placeholder}
1064
- numeric={props.numeric}
1065
- invalid={invalid}
1066
- disabled={props.disabled}
1067
- onChange={props.onEdit}
1068
- onCommit={props.onCommit}
1069
- />
1070
- <p style={HINT_STYLE}>{props.hint}</p>
1071
- {invalid ? <p style={INVALID_STYLE}>{props.copy.labels.invalidNumber}</p> : null}
1072
- </div>
1073
- )
1074
- }
1075
-
1076
- /**
1077
- * One row, rendered as the control its kind asks for.
1078
- * @param props - the row, its copy, its state, its actions, and the pinned pair.
1079
- * @returns the row element.
1080
- */
1081
- function SettingsRow(props: { row: Row; copy: RowCopy; view: FieldView; disabled: boolean; reasoningPair: { provider: string; model: string }; routing: LlmRoutingState; providerValue: string; onEdit: (text: string) => void; onReset: () => void; onCommit?: () => void }): ReactElement {
1082
124
  const shared = {
1083
125
  id: `dsh-prompt-enhance-${props.row.key}`,
1084
126
  label: props.copy.title(props.row),
@@ -1169,6 +211,31 @@ function SettingsRows(props: {
1169
211
  }, 2000)
1170
212
  }
1171
213
 
214
+ const runReset = async (key: string, fallback: string): Promise<void> => {
215
+ if (props.writeField === undefined) return
216
+ const ticket = ++sequence.current
217
+ setSaveState('saving')
218
+ const result = await props.writeField(key, '')
219
+ if (ticket !== sequence.current) return
220
+ if (result === 'failed') {
221
+ setSaveState('failed')
222
+ return
223
+ }
224
+ if (result === 'invalid') {
225
+ setSaveState('idle')
226
+ return
227
+ }
228
+ savedValues.current.set(key, fallback)
229
+ markSaved()
230
+ }
231
+
232
+ const resetAndSave = (key: string): void => {
233
+ props.resetField(key)
234
+ const fallback = defaultTextOf(key)
235
+ savedValues.current.set(key, fallback)
236
+ void runReset(key, fallback)
237
+ }
238
+
1172
239
  const manualSave = async (): Promise<void> => {
1173
240
  if (props.writeField === undefined) {
1174
241
  // Hosts without per-field writes keep the original whole-form action.
@@ -1176,9 +243,7 @@ function SettingsRows(props: {
1176
243
  markSaved()
1177
244
  return
1178
245
  }
1179
- const changed = ROWS
1180
- .map((row) => ({ key: row.key, text: viewOf(props.state, row.key).text }))
1181
- .filter((item) => savedValues.current.get(item.key) !== item.text)
246
+ const changed = ROWS.map((row) => ({ key: row.key, text: viewOf(props.state, row.key).text })).filter((item) => savedValues.current.get(item.key) !== item.text)
1182
247
  if (changed.length === 0) {
1183
248
  markSaved()
1184
249
  return
@@ -1230,56 +295,70 @@ function SettingsRows(props: {
1230
295
  void runSave(key, text ?? viewOf(props.state, key).text)
1231
296
  }
1232
297
 
1233
- useEffect(() => () => {
1234
- for (const timer of timers.current.values()) clearTimeout(timer)
1235
- timers.current.clear()
1236
- if (savedTimer.current !== undefined) clearTimeout(savedTimer.current)
1237
- }, [])
298
+ useEffect(
299
+ () => () => {
300
+ for (const timer of timers.current.values()) clearTimeout(timer)
301
+ timers.current.clear()
302
+ if (savedTimer.current !== undefined) clearTimeout(savedTimer.current)
303
+ },
304
+ [],
305
+ )
1238
306
 
1239
- const statusText = props.state.writable === false
1240
- ? props.copy.labels.readOnly
1241
- : saveState === 'saving'
1242
- ? props.copy.labels.saving
1243
- : saveState === 'saved'
1244
- ? props.copy.labels.saved
1245
- : saveState === 'failed'
1246
- ? props.copy.labels.saveFailedShort
1247
- : ''
307
+ const statusText =
308
+ props.state.writable === false
309
+ ? props.copy.labels.readOnly
310
+ : saveState === 'saving'
311
+ ? props.copy.labels.saving
312
+ : saveState === 'saved'
313
+ ? props.copy.labels.saved
314
+ : saveState === 'failed'
315
+ ? props.copy.labels.saveFailedShort
316
+ : ''
317
+
318
+ const renderRow = (row: Row, index: number): ReactElement => {
319
+ const raw = viewOf(props.state, row.key)
320
+ // Hide the override badge once the value is back at its default; the
321
+ // host's `overridden` flag alone would keep it visible.
322
+ const view = raw.overridden && atDefaultValue(row.key, raw.text) ? { ...raw, overridden: false } : raw
323
+ return (
324
+ <div key={row.key} style={index === 0 ? undefined : SEPARATOR_STYLE}>
325
+ <SettingsRow
326
+ row={row}
327
+ copy={props.copy}
328
+ view={view}
329
+ disabled={!props.state.writable}
330
+ reasoningPair={{ provider, model }}
331
+ routing={routing}
332
+ providerValue={provider}
333
+ onEdit={(text: string) => onEdit(row.key, text)}
334
+ onReset={() => resetAndSave(row.key)}
335
+ onCommit={() => flushField(row.key, viewOf(props.state, row.key).text)}
336
+ />
337
+ </div>
338
+ )
339
+ }
1248
340
 
1249
341
  return (
1250
342
  <div className="dsh-pe-form">
1251
- {ROWS.map((row, index) => {
1252
- const raw = viewOf(props.state, row.key)
1253
- // Hide the override badge once the value is back at its default; the
1254
- // host's `overridden` flag alone would keep it visible.
1255
- const view = raw.overridden && atDefaultValue(row.key, raw.text) ? { ...raw, overridden: false } : raw
1256
- return (
1257
- <div key={row.key} style={index === 0 ? undefined : SEPARATOR_STYLE}>
1258
- <SettingsRow
1259
- row={row}
1260
- copy={props.copy}
1261
- view={view}
1262
- disabled={!props.state.writable}
1263
- reasoningPair={{ provider, model }}
1264
- routing={routing}
1265
- providerValue={provider}
1266
- onEdit={(text: string) => onEdit(row.key, text)}
1267
- onReset={() => props.resetField(row.key)}
1268
- onCommit={() => flushField(row.key, viewOf(props.state, row.key).text)}
1269
- />
1270
- </div>
1271
- )
1272
- })}
343
+ {BASIC_ROWS.map(renderRow)}
344
+ <details className="dsh-pe-advanced">
345
+ <summary>{props.copy.labels.advanced}</summary>
346
+ {ADVANCED_ROWS.map(renderRow)}
347
+ </details>
1273
348
  <div className="dsh-pe-form-footer">
1274
349
  <div className="dsh-pe-save-group">
1275
- {statusText === ''
1276
- ? null
1277
- : <span className="dsh-pe-save-status" role="status" aria-live="polite">{statusText}</span>}
350
+ {statusText === '' ? null : (
351
+ <span className="dsh-pe-save-status" role="status" aria-live="polite">
352
+ {statusText}
353
+ </span>
354
+ )}
1278
355
  <button
1279
356
  type="button"
1280
357
  className="dsh-pe-save-button"
1281
358
  disabled={props.save === undefined || props.state.writable === false}
1282
- onClick={() => { void manualSave() }}
359
+ onClick={() => {
360
+ void manualSave()
361
+ }}
1283
362
  >
1284
363
  {props.copy.labels.save}
1285
364
  </button>
@@ -1314,15 +393,7 @@ export function SettingsSection(props: SectionProps): unknown {
1314
393
  return (
1315
394
  <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
1316
395
  <PageHeader title={t('settings.title')} description={t('settings.description')} version={PLUGIN_VERSION} />
1317
- <SettingsRows
1318
- copy={sectionCopy(t, chinese)}
1319
- state={state}
1320
- edit={edit}
1321
- resetField={resetField}
1322
- save={props.save}
1323
- discard={props.discard}
1324
- writeField={props.writeField}
1325
- />
396
+ <SettingsRows copy={sectionCopy(t, chinese)} state={state} edit={edit} resetField={resetField} save={props.save} discard={props.discard} writeField={props.writeField} />
1326
397
  </div>
1327
398
  )
1328
399
  }
@@ -1346,17 +417,7 @@ export function SettingsPage(props: PageProps): unknown {
1346
417
  }
1347
418
  const edit = props.edit ?? ((): void => {})
1348
419
  const resetField = props.resetField ?? ((): void => {})
1349
- return (
1350
- <SettingsRows
1351
- copy={pageCopy(t)}
1352
- state={state}
1353
- edit={edit}
1354
- resetField={resetField}
1355
- save={props.save}
1356
- discard={props.discard}
1357
- writeField={props.writeField}
1358
- />
1359
- )
420
+ return <SettingsRows copy={pageCopy(t)} state={state} edit={edit} resetField={resetField} save={props.save} discard={props.discard} writeField={props.writeField} />
1360
421
  }
1361
422
 
1362
423
  /** Structural face of one bound settings scope. */
@@ -1489,20 +550,18 @@ export function installSettingsPages(ctx: ClientContext, getLocale?: () => Local
1489
550
  // The Settings dialog's page, unchanged in behaviour: a fresh id puts it
1490
551
  // beside the shipped sections, and the frame handles an unloaded plugin.
1491
552
  ctx.effect(() => {
1492
- const stop = slots.inject(
1493
- SETTINGS_SECTION_SLOT,
1494
- () =>
1495
- slots.register(
1496
- {
1497
- name: SETTINGS_SECTION_SLOT,
1498
- id: SETTINGS_SECTION_ID,
1499
- order: SETTINGS_SECTION_ORDER,
1500
- label: () => sectionTitle(getLocale),
1501
- locale: LOCALE_NS,
1502
- inject: () => controller.inject(),
1503
- },
1504
- SettingsSection,
1505
- ),
553
+ const stop = slots.inject(SETTINGS_SECTION_SLOT, () =>
554
+ slots.register(
555
+ {
556
+ name: SETTINGS_SECTION_SLOT,
557
+ id: SETTINGS_SECTION_ID,
558
+ order: SETTINGS_SECTION_ORDER,
559
+ label: () => sectionTitle(getLocale),
560
+ locale: LOCALE_NS,
561
+ inject: () => controller.inject(),
562
+ },
563
+ SettingsSection,
564
+ ),
1506
565
  ) as () => void
1507
566
  return stop
1508
567
  }, 'dsh-prompt-enhance: settings section')
@@ -1512,18 +571,16 @@ export function installSettingsPages(ctx: ClientContext, getLocale?: () => Local
1512
571
  // for a namespace the Host does not serve.
1513
572
  const whileServed = typeof forms.whileServed === 'function' ? forms.whileServed.bind(forms) : undefined
1514
573
  const registerRowPage = (): (() => void) => {
1515
- const stop = slots.inject(
1516
- SETTINGS_ROW_CONFIG_SLOT,
1517
- () =>
1518
- slots.register(
1519
- {
1520
- name: SETTINGS_ROW_CONFIG_SLOT,
1521
- key: SETTINGS_ROW_CONFIG_KEY,
1522
- locale: LOCALE_NS,
1523
- inject: () => controller.inject(),
1524
- },
1525
- SettingsPage,
1526
- ),
574
+ const stop = slots.inject(SETTINGS_ROW_CONFIG_SLOT, () =>
575
+ slots.register(
576
+ {
577
+ name: SETTINGS_ROW_CONFIG_SLOT,
578
+ key: SETTINGS_ROW_CONFIG_KEY,
579
+ locale: LOCALE_NS,
580
+ inject: () => controller.inject(),
581
+ },
582
+ SettingsPage,
583
+ ),
1527
584
  ) as () => void
1528
585
  return stop
1529
586
  }