@surfishs/dsh-prompt-enhance 0.0.7 → 0.0.9

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 +24 -18
  2. package/README.md +24 -18
  3. package/cordis.patch.yml +1 -1
  4. package/icon.svg +14 -0
  5. package/lib/client.js +343 -383
  6. package/lib/index.js +67 -56
  7. package/lib/index.js.map +3 -3
  8. package/package.json +26 -16
  9. package/src/client/ActionIcons.tsx +4 -17
  10. package/src/client/EnhanceButton.tsx +52 -48
  11. package/src/client/ResultDock.tsx +22 -9
  12. package/src/client/ResultPanel.tsx +83 -52
  13. package/src/client/SparkleFishIcon.tsx +25 -20
  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 +18 -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 +113 -1110
  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/useDockAlignment.ts +5 -15
  29. package/src/config.ts +84 -27
  30. package/src/context.ts +1 -5
  31. package/src/enhance-routes.ts +8 -8
  32. package/src/enhancer.ts +43 -34
  33. package/src/orchestrate.ts +19 -23
  34. package/src/prompts.ts +4 -4
  35. package/src/provider-catalog.ts +1 -1
  36. package/src/reasoning-cache.ts +4 -4
  37. package/src/reasoning-efforts.ts +4 -9
  38. package/src/settings-source.ts +37 -23
  39. package/src/shared/limits.ts +38 -0
  40. package/src/shared/normalize.ts +4 -1
  41. package/src/shared/protocol.ts +27 -23
  42. package/src/shared/reasoning.ts +1 -7
  43. package/src/shared/stream-text.ts +0 -6
  44. package/src/shared/validate.ts +3 -9
  45. package/docs/code-review-2026-09.md +0 -211
  46. package/docs/handoff-settings-page.md +0 -195
  47. package/docs/release-0.2.3.md +0 -47
  48. package/docs/release-0.2.4.md +0 -20
  49. package/docs/release-0.2.5.md +0 -28
  50. package/docs/release-0.2.6.md +0 -33
  51. package/docs/release-0.2.7.md +0 -22
  52. package/docs/release-0.3.0.md +0 -36
  53. package/docs/release-0.3.1.md +0 -50
  54. package/docs/release-0.3.2.md +0 -41
  55. package/docs/release-0.3.3.md +0 -53
  56. package/docs/release-0.3.4.md +0 -43
  57. package/src/client/SparkleIcon.tsx +0 -33
@@ -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,420 +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 BASIC_ROWS: readonly Row[] = [
166
- { key: 'enabled', kind: 'boolean', label: 'settings.row.enabled.label', hint: 'settings.row.enabled.hint' },
167
- { key: 'provider', kind: 'provider', label: 'settings.row.provider.label', hint: 'settings.row.provider.hint' },
168
- { key: 'model', kind: 'model', label: 'settings.row.model.label', hint: 'settings.row.model.hint' },
169
- { key: 'reasoningEffort', kind: 'reasoning', label: 'settings.row.reasoningEffort.label', hint: 'settings.row.reasoningEffort.hint' },
170
- { key: 'temperature', kind: 'number', label: 'settings.row.temperature.label', hint: 'settings.row.temperature.hint' },
171
- { key: 'contextAware', kind: 'boolean', label: 'settings.row.contextAware.label', hint: 'settings.row.contextAware.hint' },
172
- { key: 'streaming', kind: 'boolean', label: 'settings.row.streaming.label', hint: 'settings.row.streaming.hint' },
173
- { key: 'systemPrompt', kind: 'text', label: 'settings.row.systemPrompt.label', hint: 'settings.row.systemPrompt.hint', placeholder: 'settings.row.systemPrompt.placeholder' },
174
- { key: 'shortcut', kind: 'text', label: 'settings.row.shortcut.label', hint: 'settings.row.shortcut.hint', placeholder: 'settings.row.shortcut.placeholder' },
175
- ]
176
-
177
- /** Tuning and deployment limits, hidden behind the Advanced disclosure by default. */
178
- const ADVANCED_ROWS: readonly Row[] = [
179
- { key: 'strategyMode', kind: 'strategy', label: 'settings.row.strategyMode.label', hint: 'settings.row.strategyMode.hint' },
180
- { key: 'maxInputChars', kind: 'number', label: 'settings.row.maxInputChars.label', hint: 'settings.row.maxInputChars.hint' },
181
- { key: 'maxOutputTokens', kind: 'number', label: 'settings.row.maxOutputTokens.label', hint: 'settings.row.maxOutputTokens.hint' },
182
- { key: 'timeoutMs', kind: 'number', label: 'settings.row.timeoutMs.label', hint: 'settings.row.timeoutMs.hint' },
183
- { key: 'contextMaxMessages', kind: 'number', label: 'settings.row.contextMaxMessages.label', hint: 'settings.row.contextMaxMessages.hint' },
184
- { key: 'contextMaxChars', kind: 'number', label: 'settings.row.contextMaxChars.label', hint: 'settings.row.contextMaxChars.hint' },
185
- { key: 'maxConcurrent', kind: 'number', label: 'settings.row.maxConcurrent.label', hint: 'settings.row.maxConcurrent.hint' },
186
- { key: 'rateLimitPerMinute', kind: 'number', label: 'settings.row.rateLimitPerMinute.label', hint: 'settings.row.rateLimitPerMinute.hint' },
187
- ]
188
-
189
- /** Every row both pages edit; the renderer splits it at the Advanced boundary. */
190
- const ROWS: readonly Row[] = [...BASIC_ROWS, ...ADVANCED_ROWS]
191
-
192
- /**
193
- * The staged form's descriptor for one row.
194
- * @param row - the row to describe.
195
- * @returns its field descriptor.
196
- */
197
- function descriptorOf(row: Row): SettingsFieldDescriptor {
198
- switch (row.kind) {
199
- case 'number':
200
- return settingsNumberField(row.key)
201
- case 'boolean':
202
- return settingsBooleanField(row.key)
203
- case 'strategy':
204
- return settingsEnumField(row.key, STRATEGY_OPTIONS.map((option) => option.value))
205
- case 'reasoning':
206
- // Effort ids are adapter-owned and discovered at render time, so the
207
- // descriptor cannot enumerate them; the segmented control is the only
208
- // writer, and the host validates the id against the route's declaration.
209
- return settingsTextField(row.key)
210
- default:
211
- return settingsTextField(row.key)
212
- }
213
- }
214
-
215
- /** Descriptors in display order; the form model holds one per row. */
216
- const FIELD_SPECS: readonly SettingsFieldDescriptor[] = ROWS.map((row) => descriptorOf(row))
217
-
218
- /**
219
- * Build the staged form these pages render over one settings scope.
220
- *
221
- * Exported so a test can drive the same descriptors the pages use — the
222
- * boolean and enum rows exist precisely because their staged text must parse
223
- * back into a JSON boolean and a known enum string, and that contract is worth
224
- * holding down outside the minified shell.
225
- * @param scope - the settings scope of the plugin's entry.
226
- * @returns the staged form over every row.
227
- */
228
- export function createSettingsForm(scope: unknown): SettingsFormModel {
229
- return new SettingsFormModel(scope, FIELD_SPECS)
230
- }
231
-
232
- /** The translate seat the slot framework injects for the declared namespace. */
233
- type Translate = TranslateNS<typeof LOCALE_NS>
234
-
235
- /** The shipped Chinese dictionary, used when a host projects no `t` seat. */
236
- const ZH_COPY: Readonly<Record<string, string>> = zh
237
-
238
- /**
239
- * Resolve the Plugins-page copy reader: the injected `t` when present, the
240
- * shipped Chinese dictionary otherwise. Falling back keeps an older host (or a
241
- * test) from rendering dictionary keys instead of copy.
242
- * @param t - the injected translate seat, if any.
243
- * @returns a reader for this page's keys.
244
- */
245
- function translator(t: Translate | undefined): Translate {
246
- if (typeof t === 'function') return t
247
- // The fallback dictionary must interpolate `{name}` placeholders too, or a
248
- // parameterized line would render its raw template.
249
- return ((key: string, params?: Readonly<Record<string, unknown>>) => {
250
- let text = ZH_COPY[key] ?? key
251
- for (const [name, value] of Object.entries(params ?? {})) {
252
- text = text.split(`{${name}}`).join(String(value))
253
- }
254
- return text
255
- }) as unknown as Translate
256
- }
257
-
258
- /** How one surface titles and explains the rows. */
259
- interface RowCopy {
260
- /** Copy of the shared form frame, plus the labels the custom rows draw. */
261
- readonly labels: Readonly<Record<string, string>>
262
- /** The row's title. */
263
- readonly title: (row: Row) => string
264
- /** The hint under the row. */
265
- readonly hint: (row: Row) => string
266
- /** An example shown greyed out while the input is empty, when the row has one. */
267
- readonly placeholder: (row: Row) => string | undefined
268
- /** One choice label of a segmented control. */
269
- readonly choice: (key: PromptEnhanceKey) => string
270
- /** One parameterized status line (dynamic reasoning tiers). */
271
- readonly interpolate: (key: PromptEnhanceKey, params: Record<string, string>) => string
272
- }
273
-
274
- /**
275
- * The settings dialog's copy: the raw config key first, then the localized
276
- * name in parentheses while the client is Chinese, and one single-language
277
- * hint. English mode drops the parenthesized Chinese name entirely — the key
278
- * alone is the title there.
279
- * @param t - the locale-bound translate seat.
280
- * @param chinese - whether the active locale is Chinese.
281
- * @returns the row copy for that language.
282
- */
283
- function sectionCopy(t: Translate, chinese: boolean): RowCopy {
284
- return {
285
- labels: {
286
- unavailable: t('settings.unavailable'),
287
- readOnly: t('settings.readOnly'),
288
- saveFailed: t('settings.saveFailed'),
289
- saveFailedShort: t('settings.saveFailedShort'),
290
- save: t('settings.save'),
291
- saving: t('settings.saving'),
292
- saved: t('settings.saved'),
293
- advanced: t('settings.advanced'),
294
- reset: t('settings.reset'),
295
- invalidNumber: t('settings.invalidNumber'),
296
- },
297
- title: (row) => (chinese ? `${row.key}(${t(row.label)})` : row.key),
298
- hint: (row) => t(row.hint),
299
- placeholder: (row) => (row.placeholder === undefined ? undefined : t(row.placeholder)),
300
- choice: (key) => t(key),
301
- interpolate: (key, params) => t(key, params),
302
- }
303
- }
304
-
305
- /**
306
- * The Plugins page's copy: the active locale's title and single-sentence hint,
307
- * as the host's own configuration pages read.
308
- * @param t - the injected translate seat.
309
- * @returns the row copy for that locale.
310
- */
311
- function pageCopy(t: Translate): RowCopy {
312
- return {
313
- labels: {
314
- unavailable: t('settings.unavailable'),
315
- readOnly: t('settings.readOnly'),
316
- saveFailed: t('settings.saveFailed'),
317
- saveFailedShort: t('settings.saveFailedShort'),
318
- save: t('settings.save'),
319
- saving: t('settings.saving'),
320
- saved: t('settings.saved'),
321
- advanced: t('settings.advanced'),
322
- reset: t('settings.reset'),
323
- invalidNumber: t('settings.invalidNumber'),
324
- },
325
- title: (row) => t(row.label),
326
- hint: (row) => t(row.hint),
327
- placeholder: (row) => (row.placeholder === undefined ? undefined : t(row.placeholder)),
328
- choice: (key) => t(key),
329
- interpolate: (key, params) => t(key, params),
330
- }
331
- }
332
-
333
- /**
334
- * Inline copies of the host form's row metrics (the shell's `181ew` styles
335
- * module), so a switch or segmented row lines up with the text rows the
336
- * primitives render instead of looking like a foreign control.
337
- */
338
- const ROW_STYLE: CSSProperties = { display: 'flex', flexDirection: 'column', gap: 6, padding: '12px 0' }
339
- const HEAD_STYLE: CSSProperties = { display: 'flex', alignItems: 'center', gap: 8 }
340
- const LABEL_STYLE: CSSProperties = {
341
- flex: 1,
342
- minWidth: 0,
343
- fontSize: 13,
344
- fontWeight: 500,
345
- lineHeight: 1.5,
346
- color: 'var(--dsw-alias-label-primary, inherit)',
347
- }
348
- const HINT_STYLE: CSSProperties = {
349
- margin: 0,
350
- fontSize: 12,
351
- lineHeight: 1.5,
352
- color: 'var(--dsw-alias-label-tertiary, inherit)',
353
- }
354
- /** Dynamic-tier status line under the reasoning control. */
355
- const STATUS_STYLE: CSSProperties = {
356
- margin: 0,
357
- fontSize: 12,
358
- lineHeight: 1.5,
359
- color: 'var(--dsw-alias-label-secondary, inherit)',
360
- }
361
- /** The neutral chip surface shared by the row's quiet actions. */
362
- const CHIP_STYLE: CSSProperties = {
363
- display: 'inline-flex',
364
- alignItems: 'center',
365
- padding: '1px 8px',
366
- border: 'none',
367
- borderRadius: 999,
368
- background: 'var(--pe-chip-bg, var(--dsw-alias-bg-module-platform, rgba(128, 128, 128, 0.12)))',
369
- fontFamily: 'inherit',
370
- fontSize: 11,
371
- fontWeight: 500,
372
- lineHeight: '17px',
373
- color: 'var(--pe-chip-color, var(--dsw-alias-label-secondary, inherit))',
374
- textDecoration: 'underline',
375
- textUnderlineOffset: 2,
376
- cursor: 'pointer',
377
- }
378
- /** The tier refetch action, in the same chip surface. */
379
- const REFRESH_STYLE: CSSProperties = { ...CHIP_STYLE, flex: 'none' }
380
- /** The reset action: the neutral chip surface, with an underline for affordance. */
381
- const RESET_STYLE: CSSProperties = CHIP_STYLE
382
- /** One border for every form control, so focus never changes the outline width. */
383
- const FIELD_BORDER = '1px solid rgba(128, 128, 128, 0.38)'
384
- /** The form input, mirroring the host's `input` metrics for a native control. */
385
- const INPUT_STYLE: CSSProperties = {
386
- boxSizing: 'border-box',
387
- width: '100%',
388
- height: 34,
389
- padding: '0 12px',
390
- border: FIELD_BORDER,
391
- borderRadius: 'var(--dsw-radius-md, 8px)',
392
- background: 'var(--dsw-alias-bg-layer-3, transparent)',
393
- font: 'inherit',
394
- fontSize: 13,
395
- lineHeight: 1.5,
396
- color: 'var(--dsw-alias-label-primary, inherit)',
397
- outline: 'none',
398
- }
399
- /** The error line under an invalid numeric row. */
400
- const INVALID_STYLE: CSSProperties = {
401
- margin: 0,
402
- fontSize: 12,
403
- lineHeight: 1.5,
404
- color: 'var(--dsw-alias-state-error-primary, #f85149)',
405
- }
406
- /** The warning line under the routing rows; saves are not blocked by it. */
407
- const WARN_STYLE: CSSProperties = {
408
- margin: 0,
409
- fontSize: 12,
410
- lineHeight: 1.5,
411
- color: 'var(--dsw-alias-state-error-primary, #f85149)',
412
- }
413
- /** The provider/model select, sharing the value input's metrics. */
414
- const SELECT_STYLE: CSSProperties = {
415
- ...INPUT_STYLE,
416
- cursor: 'pointer',
417
- }
418
- const SEPARATOR_STYLE: CSSProperties = {
419
- borderTop: '0.5px solid var(--dsw-alias-border-l2, rgba(128, 128, 128, 0.24))',
420
- }
421
-
422
- /** Public repository behind this build, linked from the page header. */
423
- const REPOSITORY_URL = 'https://github.com/surfishs/dsh-prompt-enhance'
424
-
425
- /** Public npm package page, linked from the page header next to the repository. */
426
- const NPM_URL = 'https://www.npmjs.com/package/@surfishs/dsh-prompt-enhance'
427
-
428
- /** The GitHub mark (16×16), painted with the current text color. */
429
- const GITHUB_MARK =
430
- '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'
431
-
432
- /** The npm mark (24×24), painted with the current text color. */
433
- const NPM_MARK =
434
- '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'
435
-
436
- /** The version this bundle was built from; guarded for environments without the define. */
437
- const PLUGIN_VERSION = typeof __PLUGIN_VERSION__ === 'string' ? __PLUGIN_VERSION__ : '0.0.0'
438
-
439
- /** Header block: title, repository link, version, and one description line. */
440
- const HEADER_STYLE: CSSProperties = { display: 'flex', flexDirection: 'column', gap: 12, padding: '2px 0' }
441
- const HEADER_ROW_STYLE: CSSProperties = { display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }
442
- const HEADER_TITLE_STYLE: CSSProperties = {
443
- fontSize: 18,
444
- fontWeight: 600,
445
- letterSpacing: '-0.012em',
446
- lineHeight: 1.3,
447
- color: 'var(--dsw-alias-label-primary, inherit)',
448
- }
449
- const HEADER_LINK_STYLE: CSSProperties = {
450
- display: 'inline-flex',
451
- alignItems: 'center',
452
- gap: 3,
453
- height: 18,
454
- padding: '0 7px',
455
- border: '1px solid var(--dsw-alias-border-l4, rgba(128, 128, 128, 0.35))',
456
- borderRadius: 999,
457
- background: 'var(--dsw-alias-bg-layer-3, transparent)',
458
- fontSize: 10.5,
459
- fontWeight: 500,
460
- lineHeight: 1,
461
- color: 'var(--dsw-alias-label-secondary, inherit)',
462
- textDecoration: 'none',
463
- }
464
- const HEADER_VERSION_STYLE: CSSProperties = {
465
- display: 'inline-flex',
466
- alignItems: 'center',
467
- height: 18,
468
- padding: '0 7px',
469
- borderRadius: 999,
470
- background: 'var(--dsw-alias-bg-layer-4, transparent)',
471
- fontSize: 10.5,
472
- lineHeight: 1,
473
- color: 'var(--dsw-alias-label-tertiary, inherit)',
474
- fontVariantNumeric: 'tabular-nums',
475
- }
476
- const HEADER_DESCRIPTION_STYLE: CSSProperties = {
477
- margin: 0,
478
- fontSize: 13,
479
- lineHeight: 1.65,
480
- color: 'var(--dsw-alias-label-tertiary, inherit)',
481
- textWrap: 'pretty',
482
- maxWidth: '72ch',
483
- }
484
-
485
77
  /**
486
78
  * The page header the settings dialog shows above the form: the plugin title,
487
79
  * a repository link chip and the shipped version, with one description line.
@@ -512,596 +104,23 @@ function PageHeader(props: { title: string; description: string; version: string
512
104
  )
513
105
  }
514
106
 
515
- /** One projection of the pages' form store. */
516
- interface SettingsSnapshot {
517
- writable?: boolean
518
- [key: string]: unknown
519
- }
520
-
521
- /** One row's projection inside that snapshot. */
522
- interface FieldView {
523
- text: string
524
- overridden: boolean
525
- invalid: boolean
526
- }
527
-
528
- /** The staged form's actions, as both slots hand them over. */
529
- interface FormProps {
530
- /**
531
- * The store hook, named after the `inject()` hook key (`promptEnhance`).
532
- * Absent when the host does not project hooks for this slot; the component
533
- * renders the explanation instead of throwing, because a throwing page
534
- * blanks the pane.
535
- */
536
- usePromptEnhance?: (selector: (snapshot: SettingsSnapshot) => SettingsSnapshot) => SettingsSnapshot
537
- edit?: (key: string, text: string) => void
538
- resetField?: (key: string) => void
539
- save?: () => void
540
- discard?: () => void
541
- writeField?: (key: string, text: string) => Promise<'saved' | 'invalid' | 'failed'>
542
- }
543
-
544
- /** One locale snapshot, as the client locale service exposes it. */
545
- interface LocaleSnapshotLike {
546
- /** Active locale id, e.g. `zh` or `en`. */
547
- active?: string
548
- /** Monotonic revision; changes on locale switches and dictionary registration. */
549
- revision?: number
550
- }
551
-
552
- /** The client locale service, reached structurally so no package type is needed. */
553
- export interface LocaleFaceLike {
554
- bind(namespace: string): Translate
555
- getSnapshot(): LocaleSnapshotLike
556
- subscribe(listener: () => void): () => void
557
- }
558
-
559
- /** Props of the settings-dialog page. */
560
- type SectionProps = FormProps & {
561
- /** The locale-bound translate seat this plugin projects into the page. */
562
- translate?: Translate
563
- /** Locale snapshot selector hook; re-renders the page when the language changes. */
564
- usePromptEnhanceLocale?: (selector: (snapshot: LocaleSnapshotLike) => LocaleSnapshotLike) => LocaleSnapshotLike
565
- }
566
-
567
- /** Props the plugin manager hands a configuration page. */
568
- interface PageProps extends FormProps {
569
- /** Translate seat of this page's locale namespace, injected by the slot. */
570
- t?: Translate
571
- /** Which view the manager asks for: the form, or the one-line summary. */
572
- view?: 'page' | 'summary'
573
- }
574
-
575
- /** Props shared by every row component: the row, its copy, its state, its actions. */
576
- interface RowProps {
577
- /** The DOM id of the row's control. */
578
- id: string
579
- /** The row's title, already resolved. */
580
- label: string
581
- /** The hint under the row, already resolved. */
582
- hint: string
583
- /** 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
584
114
  copy: RowCopy
585
- /** The row's staged state. */
586
115
  view: FieldView
587
- /** Whether writes are refused by this deployment. */
588
116
  disabled: boolean
589
- /** Stage new text for this row. */
117
+ reasoningPair: { provider: string; model: string }
118
+ routing: LlmRoutingState
119
+ providerValue: string
590
120
  onEdit: (text: string) => void
591
- /** Clear the stored value so the row re-inherits the composition default. */
592
121
  onReset: () => void
593
- /** Commit the current text now, e.g. on blur or Enter. */
594
- onCommit?: () => void
595
- }
596
-
597
- /**
598
- * Read one row's projection out of the page snapshot.
599
- *
600
- * A row the host schema does not declare is absent from the projection; it
601
- * renders as an empty, non-overridden field rather than throwing.
602
- * @param snapshot - the page's current snapshot.
603
- * @param key - the row's config key.
604
- * @returns the row's text form and staging flags.
605
- */
606
- function viewOf(snapshot: SettingsSnapshot, key: string): FieldView {
607
- const value = snapshot[key]
608
- if (value === null || typeof value !== 'object') return { text: '', overridden: false, invalid: false }
609
- const field = value as { text?: unknown; overridden?: unknown; invalid?: unknown }
610
- return {
611
- text: typeof field.text === 'string' ? field.text : '',
612
- overridden: field.overridden === true,
613
- invalid: field.invalid === true,
614
- }
615
- }
616
-
617
- /**
618
- * Whether one row's current text equals its shipped default.
619
- *
620
- * The host form reports `overridden` as "this field was written explicitly"
621
- * (stored value or a staged set), which stays true even when the user edits
622
- * the value back to the default. The badge and its reset action only make
623
- * sense while there is something to reset, so visibility is derived from this
624
- * comparison instead — for text/number/enum rows alike.
625
- * @param key - the config key.
626
- * @param text - the row's current staged text.
627
- * @returns true when editing can no longer change anything from the default.
628
- */
629
- /** The display text a reset row falls back to, from the shared defaults. */
630
- function defaultTextOf(key: string): string {
631
- const descriptor = FIELD_SPECS.find((item) => item.field === key)
632
- const fallback = (DEFAULT_VALUES as Record<string, unknown>)[key]
633
- if (descriptor === undefined || fallback === undefined) return ''
634
- try {
635
- return descriptor.format(fallback)
636
- } catch {
637
- return ''
638
- }
639
- }
640
-
641
- function atDefaultValue(key: string, text: string): boolean {
642
- const fallback = (DEFAULT_VALUES as Record<string, unknown>)[key]
643
- // provider/model are absent from the defaults on purpose: empty means follow.
644
- if (fallback === undefined) return text.trim() === ''
645
- if (typeof fallback === 'boolean') return text.trim() === String(fallback)
646
- if (typeof fallback === 'number') {
647
- const parsed = Number(text.trim())
648
- return Number.isFinite(parsed) && parsed === fallback
649
- }
650
- return text.trim() === String(fallback)
651
- }
652
-
653
- /**
654
- * The "overridden" badge and its reset button, as the text rows draw them.
655
- * @param props - the frame copy, whether writes are refused, and the reset handler.
656
- * @returns the badge pair.
657
- */
658
- function OverrideActions(props: { copy: RowCopy; disabled: boolean; onReset: () => void }): ReactElement {
659
- return (
660
- <button
661
- type="button"
662
- className="dsh-pe-chip-reset"
663
- style={{ ...RESET_STYLE, ...props.disabled ? { opacity: 0.5, cursor: 'default' } : {} }}
664
- disabled={props.disabled}
665
- onClick={props.onReset}
666
- >
667
- {props.copy.labels.reset}
668
- </button>
669
- )
670
- }
671
-
672
- /**
673
- * A boolean row: the title and the shell's switch on one line, the hint below.
674
- * @param props - the row, its copy, its state, and its actions.
675
- * @returns the row element.
676
- */
677
- function BooleanRow(props: RowProps): ReactElement {
678
- return (
679
- <div style={ROW_STYLE}>
680
- <div style={HEAD_STYLE}>
681
- <span style={LABEL_STYLE}>{props.label}</span>
682
- {props.view.overridden ? <OverrideActions copy={props.copy} disabled={props.disabled} onReset={props.onReset} /> : null}
683
- <Switch
684
- checked={props.view.text === 'true'}
685
- disabled={props.disabled}
686
- label={props.label}
687
- onChange={(next: boolean) => props.onEdit(next ? 'true' : 'false')}
688
- />
689
- </div>
690
- <p style={HINT_STYLE}>{props.hint}</p>
691
- </div>
692
- )
693
- }
694
-
695
- /**
696
- * A fixed-choice row: the shell's segmented control under the title.
697
- * @param props - the row, its choices, its state, and its actions.
698
- * @returns the row element.
699
- */
700
- function ChoiceRow(props: RowProps & { options: readonly { value: string; label: string; title?: string }[] }): ReactElement {
701
- return (
702
- <div style={ROW_STYLE}>
703
- <div style={HEAD_STYLE}>
704
- <span style={LABEL_STYLE}>{props.label}</span>
705
- {props.view.overridden ? <OverrideActions copy={props.copy} disabled={props.disabled} onReset={props.onReset} /> : null}
706
- </div>
707
- <SegmentedControl
708
- id={props.id}
709
- className="dsh-pe-segmented-labels"
710
- value={props.view.text}
711
- options={props.options.map((option) => ({ ...option, title: option.title ?? option.label }))}
712
- disabled={props.disabled}
713
- label={props.label}
714
- onChange={(next: string) => props.onEdit(next)}
715
- />
716
- <p style={HINT_STYLE}>{props.hint}</p>
717
- </div>
718
- )
719
- }
720
-
721
- /**
722
- * The reasoning row: choices come from what the configured route declares.
723
- *
724
- * - Both provider/model empty → follow the default model; the host answers from
725
- * its static DeepSeek catalog, or reports unavailable when the default is not
726
- * DeepSeek. This path is not cached (the page cannot observe the default).
727
- * - A pinned pair → the answer is cached in `localStorage` with no TTL; it is
728
- * replaced only when the pair changes or the user presses refresh.
729
- *
730
- * While the answer is pending, or when it is unavailable, the control offers
731
- * only "follow provider default" instead of guessing a tier list.
732
- * @param props - the row, its copy, state, actions, and the pinned pair.
733
- * @returns the row element.
734
- */
735
- function ReasoningRow(props: RowProps & { provider: string; model: string }): ReactElement {
736
- const pair = props.provider !== '' && props.model !== '' ? `${props.provider}/${props.model}` : ''
737
- const [phase, setPhase] = useState<'loading' | 'ready'>('loading')
738
- const [capabilities, setCapabilities] = useState<ReasoningCapabilities | undefined>(undefined)
739
- const [refreshToken, setRefreshToken] = useState(0)
740
- const [feedback, setFeedback] = useState<'idle' | 'refreshing' | 'ok' | 'failed'>('idle')
741
- const forceRef = useRef(false)
742
- const feedbackTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
743
-
744
- useEffect(() => {
745
- const controller = new AbortController()
746
- const force = forceRef.current
747
- forceRef.current = false
748
- setPhase('loading')
749
- setCapabilities(undefined)
750
- setFeedback(force ? 'refreshing' : 'idle')
751
- if (feedbackTimer.current !== undefined) {
752
- clearTimeout(feedbackTimer.current)
753
- feedbackTimer.current = undefined
754
- }
755
- /** Settle the manual-refresh feedback; initial loads show no outcome. */
756
- const settle = (result: 'ok' | 'failed'): void => {
757
- if (!force) return
758
- setFeedback(result)
759
- feedbackTimer.current = setTimeout(() => {
760
- setFeedback('idle')
761
- feedbackTimer.current = undefined
762
- }, 3000)
763
- }
764
- fetchReasoningCapabilities(
765
- props.provider === '' ? undefined : props.provider,
766
- props.model === '' ? undefined : props.model,
767
- { refresh: force, signal: controller.signal },
768
- )
769
- .then((answer) => {
770
- if (controller.signal.aborted) return
771
- setCapabilities(answer)
772
- setPhase('ready')
773
- settle(answer.source === 'unavailable' ? 'failed' : 'ok')
774
- })
775
- .catch(() => {
776
- if (controller.signal.aborted) return
777
- setCapabilities({ efforts: [], source: 'unavailable', reason: 'resolve-failed' })
778
- setPhase('ready')
779
- settle('failed')
780
- })
781
- return () => {
782
- controller.abort()
783
- if (feedbackTimer.current !== undefined) {
784
- clearTimeout(feedbackTimer.current)
785
- feedbackTimer.current = undefined
786
- }
787
- }
788
- // `pair` covers both ids; the default path reuses the empty string.
789
- // eslint-disable-next-line react-hooks/exhaustive-deps
790
- }, [pair, refreshToken])
791
-
792
- // Every provider — DeepSeek included — shows the adapter's own tier names;
793
- // only the "follow provider default" sentinel is plugin copy.
794
- const current = props.view.text
795
- const realTierKnown = phase === 'ready' && capabilities !== undefined && capabilities.source !== 'unavailable'
796
- && capabilities.efforts.some((effort) => effort.id === current)
797
- const noTiers = phase === 'ready' && capabilities !== undefined && capabilities.source === 'unavailable' && capabilities.reason === 'no-efforts'
798
- const options: { value: string; label: string; title?: string }[] = []
799
- // A value the route does not declare (stale config, or while the list is
800
- // still loading) is kept as a visible synthetic choice. Without it the
801
- // segmented control's indicator has no matching option and slides off the
802
- // left edge.
803
- if (!noTiers && current !== '' && current !== 'inherit' && !realTierKnown) {
804
- options.push({
805
- value: current,
806
- label: props.copy.interpolate('settings.reasoning.current', { value: current }),
807
- title: props.copy.choice('settings.reasoning.currentTitle'),
808
- })
809
- }
810
- if (phase === 'ready' && capabilities !== undefined && capabilities.source !== 'unavailable') {
811
- for (const effort of capabilities.efforts) {
812
- options.push({
813
- value: effort.id,
814
- label: effort.name,
815
- title: effort.description === undefined ? effort.name : `${effort.name} — ${effort.description}`,
816
- })
817
- }
818
- }
819
- options.push({
820
- value: 'inherit',
821
- label: props.copy.choice('settings.reasoning.inherit'),
822
- title: props.copy.choice('settings.reasoning.inherit'),
823
- })
824
- const unsupported = !noTiers && phase === 'ready' && capabilities?.source !== 'unavailable'
825
- && current !== '' && current !== 'inherit' && !realTierKnown
826
- const refreshing = feedback === 'refreshing'
827
- const refresh = (): void => {
828
- forceRef.current = true
829
- setRefreshToken((token) => token + 1)
830
- }
831
- return (
832
- <div style={ROW_STYLE}>
833
- <div style={HEAD_STYLE}>
834
- <span style={LABEL_STYLE}>{props.label}</span>
835
- {phase === 'ready' || refreshing
836
- ? (
837
- <button
838
- type="button"
839
- className="dsh-pe-chip-refresh"
840
- style={{ ...REFRESH_STYLE, opacity: props.disabled || refreshing ? 0.5 : 1 }}
841
- disabled={props.disabled || refreshing}
842
- onClick={refresh}
843
- >
844
- {props.copy.choice(refreshing ? 'settings.reasoning.refreshing' : 'settings.reasoning.refresh')}
845
- </button>
846
- )
847
- : null}
848
- {props.view.overridden ? <OverrideActions copy={props.copy} disabled={props.disabled} onReset={props.onReset} /> : null}
849
- </div>
850
- <SegmentedControl
851
- id={props.id}
852
- className="dsh-pe-segmented-labels"
853
- // A route that declares no tiers is presented as "follow provider
854
- // default"; the stored tier stays in the config and the host omits it
855
- // on the call, so the displayed state matches what actually happens.
856
- value={noTiers ? 'inherit' : props.view.text}
857
- options={options}
858
- // "Follow provider default" stays selectable while the tier list is
859
- // still loading; the tier choices themselves only appear once known.
860
- disabled={props.disabled}
861
- label={props.label}
862
- onChange={(next: string) => props.onEdit(next)}
863
- />
864
- <p style={HINT_STYLE}>{props.hint}</p>
865
- {phase === 'loading' ? <p style={STATUS_STYLE}>{props.copy.choice('settings.reasoning.loading')}</p> : null}
866
- {phase === 'ready' && capabilities?.source === 'unavailable'
867
- ? <p style={STATUS_STYLE}>{props.copy.choice(noTiers ? 'settings.reasoning.noTiers' : 'settings.reasoning.unavailable')}</p>
868
- : null}
869
- {unsupported ? (
870
- <p style={STATUS_STYLE}>{props.copy.interpolate('settings.reasoning.unsupported', { effort: props.view.text })}</p>
871
- ) : null}
872
- {feedback === 'ok' ? <p style={STATUS_STYLE} aria-live="polite">{props.copy.choice('settings.reasoning.refreshOk')}</p> : null}
873
- {feedback === 'failed' ? <p style={STATUS_STYLE} aria-live="polite">{props.copy.choice('settings.reasoning.refreshFailed')}</p> : null}
874
- </div>
875
- )
876
- }
877
-
878
- /**
879
- * The shared select control: a 1px resting border (a hairline can vanish at
880
- * some scale factors) and a business-colour border while focused, so the
881
- * control's outline never depends on the browser's focus ring.
882
- */
883
- function SelectControl(props: { id: string; value: string; disabled?: boolean; onChange: (value: string) => void; children: ReactNode }): ReactElement {
884
- const [focused, setFocused] = useState(false)
885
- return (
886
- <select
887
- id={props.id}
888
- style={{ ...SELECT_STYLE, ...focused ? { borderColor: 'var(--dsw-alias-state-business-primary, #4f8cff)' } : {} }}
889
- value={props.value}
890
- disabled={props.disabled}
891
- onFocus={() => setFocused(true)}
892
- onBlur={() => setFocused(false)}
893
- onChange={(event) => props.onChange(event.target.value)}
894
- >
895
- {props.children}
896
- </select>
897
- )
898
- }
899
-
900
- /**
901
- * The provider select: registered providers plus dormant ones rendered
902
- * disabled, and a synthetic entry for a stored value outside the registry.
903
- * @param props - the row, its state, and the catalog reads.
904
- * @returns the row element.
905
- */
906
- function ProviderRow(props: RowProps & { routing: LlmRoutingState }): ReactElement {
907
- const current = props.view.text
908
- const known = props.routing.providers.entries.find((entry) => entry.id === current)
909
- const missing = current !== '' && known === undefined
910
- const unconfigured = known !== undefined && !known.registered
911
- return (
912
- <div style={ROW_STYLE}>
913
- <div style={HEAD_STYLE}>
914
- <label htmlFor={props.id} style={LABEL_STYLE}>{props.label}</label>
915
- {props.view.overridden ? <OverrideActions copy={props.copy} disabled={props.disabled} onReset={props.onReset} /> : null}
916
- </div>
917
- <SelectControl id={props.id} value={current} disabled={props.disabled} onChange={(value) => props.onEdit(value)}>
918
- <option value="">{props.copy.choice('settings.routing.followSession')}</option>
919
- {missing ? <option value={current} title={current}>{props.copy.interpolate('settings.routing.currentProvider', { value: current })}</option> : null}
920
- <optgroup label={props.copy.choice('settings.routing.groupRegistered')}>
921
- {props.routing.providers.entries.filter((entry) => entry.registered).map((entry) => (
922
- <option key={entry.id} value={entry.id} title={entry.id}>{entry.name}</option>
923
- ))}
924
- </optgroup>
925
- {props.routing.providers.entries.some((entry) => !entry.registered)
926
- ? (
927
- <optgroup label={props.copy.choice('settings.routing.groupDormant')}>
928
- {props.routing.providers.entries.filter((entry) => !entry.registered).map((entry) => (
929
- <option key={entry.id} value={entry.id} disabled title={props.copy.choice('settings.routing.unconfiguredTitle')}>
930
- {entry.name}{props.copy.choice('settings.routing.unconfiguredSuffix')}
931
- </option>
932
- ))}
933
- </optgroup>
934
- )
935
- : null}
936
- </SelectControl>
937
- <p style={HINT_STYLE}>{props.hint}</p>
938
- {props.routing.providers.loading ? <p style={STATUS_STYLE}>{props.copy.choice('settings.routing.providersLoading')}</p> : null}
939
- {props.routing.providers.failed ? <p style={STATUS_STYLE}>{props.copy.choice('settings.routing.providersFailed')}</p> : null}
940
- {props.routing.providers.failed ? (
941
- <button type="button" style={REFRESH_STYLE} onClick={props.routing.providers.reload}>
942
- {props.copy.choice('settings.routing.retry')}
943
- </button>
944
- ) : null}
945
- {missing ? <p style={WARN_STYLE}>{props.copy.interpolate('settings.routing.providerMissing', { value: current })}</p> : null}
946
- {unconfigured ? <p style={WARN_STYLE}>{props.copy.interpolate('settings.routing.providerUnconfigured', { name: known.name })}</p> : null}
947
- </div>
948
- )
949
- }
950
-
951
- /**
952
- * The model select: the provider's advertised models, a "custom…" entry that
953
- * reveals a free-text input, and warnings (incomplete pair / unresolvable
954
- * route) that never block saving.
955
- * @param props - the row, its state, the catalog reads, and the provider value.
956
- * @returns the row element.
957
- */
958
- function ModelRow(props: RowProps & { routing: LlmRoutingState; providerValue: string }): ReactElement {
959
- const current = props.view.text
960
- const provider = props.providerValue
961
- const [customMode, setCustomMode] = useState(false)
962
- const known = props.routing.models.entries.some((entry) => entry.id === current)
963
- // A stored model outside the advertised catalog is still editable, so the
964
- // custom input opens automatically for it instead of hiding the value.
965
- const showCustom = provider !== '' && (customMode || (current !== '' && !known))
966
- const pairIncomplete = provider !== '' && current === ''
967
- const routeUnavailable = provider !== '' && current !== '' && props.routing.route.available === false
968
- return (
969
- <div style={ROW_STYLE}>
970
- <div style={HEAD_STYLE}>
971
- <label htmlFor={props.id} style={LABEL_STYLE}>{props.label}</label>
972
- {props.view.overridden ? <OverrideActions copy={props.copy} disabled={props.disabled} onReset={props.onReset} /> : null}
973
- </div>
974
- <SelectControl
975
- id={props.id}
976
- value={showCustom ? '__custom__' : current}
977
- disabled={props.disabled || provider === ''}
978
- onChange={(value) => {
979
- if (value === '__custom__') {
980
- setCustomMode(true)
981
- return
982
- }
983
- setCustomMode(false)
984
- props.onEdit(value)
985
- }}
986
- >
987
- <option value="">{provider === '' ? props.copy.choice('settings.routing.followSession') : props.copy.choice('settings.routing.selectModel')}</option>
988
- {props.routing.models.entries.map((entry) => (
989
- <option key={entry.id} value={entry.id} title={entry.id}>{entry.name}</option>
990
- ))}
991
- {provider !== '' && current !== '' && !known
992
- ? <option value={current} title={current}>{props.copy.interpolate('settings.routing.currentModel', { value: current })}</option>
993
- : null}
994
- {provider !== '' ? <option value="__custom__">{props.copy.choice('settings.routing.custom')}</option> : null}
995
- </SelectControl>
996
- {showCustom ? (
997
- <TextControl
998
- value={current}
999
- placeholder={props.copy.choice('settings.routing.customPlaceholder')}
1000
- disabled={props.disabled}
1001
- onChange={props.onEdit}
1002
- />
1003
- ) : null}
1004
- <p style={HINT_STYLE}>{props.hint}</p>
1005
- {props.routing.models.loading ? <p style={STATUS_STYLE}>{props.copy.choice('settings.routing.modelsLoading')}</p> : null}
1006
- {props.routing.models.failed && !showCustom ? <p style={STATUS_STYLE}>{props.copy.choice('settings.routing.modelsFailed')}</p> : null}
1007
- {pairIncomplete ? <p style={WARN_STYLE}>{props.copy.choice('settings.routing.pairIncomplete')}</p> : null}
1008
- {routeUnavailable ? <p style={WARN_STYLE}>{props.copy.choice('settings.routing.routeUnavailable')}</p> : null}
1009
- </div>
1010
- )
1011
- }
1012
-
1013
- /**
1014
- * A text/number row: the title and the reset chip on one line, a native input,
1015
- * then the hint. The host's `SettingsValueField` draws its own badge and reset
1016
- * link, which would diverge from the chip the other rows use, so value rows
1017
- * share this control instead.
1018
- * @param props - the row, its copy, state, and whether it is numeric.
1019
- * @returns the row element.
1020
- */
1021
- /**
1022
- * The shared text/number control: the same 1px border as the selects, turning
1023
- * the same business colour while focused (the invalid state wins over focus).
1024
- */
1025
- function TextControl(props: {
1026
- id?: string
1027
- value: string
1028
- placeholder?: string
1029
- numeric?: boolean
1030
- invalid?: boolean
1031
- disabled?: boolean
1032
- onChange: (value: string) => void
1033
122
  onCommit?: () => void
1034
123
  }): ReactElement {
1035
- const [focused, setFocused] = useState(false)
1036
- const [revealedInvalid, setRevealedInvalid] = useState(false)
1037
- useEffect(() => {
1038
- if (props.invalid !== true) setRevealedInvalid(false)
1039
- }, [props.invalid])
1040
- const showInvalid = props.invalid === true && revealedInvalid
1041
- const borderColor = showInvalid
1042
- ? 'var(--dsw-alias-state-error-primary, #f85149)'
1043
- : focused ? 'var(--dsw-alias-state-business-primary, #4f8cff)' : undefined
1044
- return (
1045
- <input
1046
- id={props.id}
1047
- type="text"
1048
- inputMode={props.numeric === true ? 'numeric' : undefined}
1049
- aria-invalid={showInvalid || undefined}
1050
- disabled={props.disabled}
1051
- placeholder={props.placeholder}
1052
- value={props.value}
1053
- style={{
1054
- ...INPUT_STYLE,
1055
- ...props.disabled === true ? { color: 'var(--dsw-alias-label-tertiary, inherit)', cursor: 'default' } : {},
1056
- ...borderColor === undefined ? {} : { borderColor },
1057
- }}
1058
- onFocus={() => setFocused(true)}
1059
- onBlur={() => {
1060
- setFocused(false)
1061
- if (props.invalid === true) setRevealedInvalid(true)
1062
- props.onCommit?.()
1063
- }}
1064
- onKeyDown={(event) => {
1065
- if (event.key !== 'Enter') return
1066
- event.preventDefault()
1067
- if (props.invalid === true) setRevealedInvalid(true)
1068
- props.onCommit?.()
1069
- }}
1070
- onChange={(event) => props.onChange(event.target.value)}
1071
- />
1072
- )
1073
- }
1074
-
1075
- function ValueRow(props: RowProps & { numeric: boolean; placeholder?: string }): ReactElement {
1076
- const invalid = props.view.invalid
1077
- return (
1078
- <div style={ROW_STYLE}>
1079
- <div style={HEAD_STYLE}>
1080
- <label htmlFor={props.id} style={LABEL_STYLE}>{props.label}</label>
1081
- {props.view.overridden ? <OverrideActions copy={props.copy} disabled={props.disabled} onReset={props.onReset} /> : null}
1082
- </div>
1083
- <TextControl
1084
- id={props.id}
1085
- value={props.view.text}
1086
- placeholder={props.placeholder}
1087
- numeric={props.numeric}
1088
- invalid={invalid}
1089
- disabled={props.disabled}
1090
- onChange={props.onEdit}
1091
- onCommit={props.onCommit}
1092
- />
1093
- <p style={HINT_STYLE}>{props.hint}</p>
1094
- {invalid ? <p style={INVALID_STYLE}>{props.copy.labels.invalidNumber}</p> : null}
1095
- </div>
1096
- )
1097
- }
1098
-
1099
- /**
1100
- * One row, rendered as the control its kind asks for.
1101
- * @param props - the row, its copy, its state, its actions, and the pinned pair.
1102
- * @returns the row element.
1103
- */
1104
- 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 {
1105
124
  const shared = {
1106
125
  id: `dsh-prompt-enhance-${props.row.key}`,
1107
126
  label: props.copy.title(props.row),
@@ -1224,9 +243,7 @@ function SettingsRows(props: {
1224
243
  markSaved()
1225
244
  return
1226
245
  }
1227
- const changed = ROWS
1228
- .map((row) => ({ key: row.key, text: viewOf(props.state, row.key).text }))
1229
- .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)
1230
247
  if (changed.length === 0) {
1231
248
  markSaved()
1232
249
  return
@@ -1278,21 +295,25 @@ function SettingsRows(props: {
1278
295
  void runSave(key, text ?? viewOf(props.state, key).text)
1279
296
  }
1280
297
 
1281
- useEffect(() => () => {
1282
- for (const timer of timers.current.values()) clearTimeout(timer)
1283
- timers.current.clear()
1284
- if (savedTimer.current !== undefined) clearTimeout(savedTimer.current)
1285
- }, [])
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
+ )
1286
306
 
1287
- const statusText = props.state.writable === false
1288
- ? props.copy.labels.readOnly
1289
- : saveState === 'saving'
1290
- ? props.copy.labels.saving
1291
- : saveState === 'saved'
1292
- ? props.copy.labels.saved
1293
- : saveState === 'failed'
1294
- ? props.copy.labels.saveFailedShort
1295
- : ''
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
+ : ''
1296
317
 
1297
318
  const renderRow = (row: Row, index: number): ReactElement => {
1298
319
  const raw = viewOf(props.state, row.key)
@@ -1326,14 +347,18 @@ function SettingsRows(props: {
1326
347
  </details>
1327
348
  <div className="dsh-pe-form-footer">
1328
349
  <div className="dsh-pe-save-group">
1329
- {statusText === ''
1330
- ? null
1331
- : <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
+ )}
1332
355
  <button
1333
356
  type="button"
1334
357
  className="dsh-pe-save-button"
1335
358
  disabled={props.save === undefined || props.state.writable === false}
1336
- onClick={() => { void manualSave() }}
359
+ onClick={() => {
360
+ void manualSave()
361
+ }}
1337
362
  >
1338
363
  {props.copy.labels.save}
1339
364
  </button>
@@ -1368,15 +393,7 @@ export function SettingsSection(props: SectionProps): unknown {
1368
393
  return (
1369
394
  <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
1370
395
  <PageHeader title={t('settings.title')} description={t('settings.description')} version={PLUGIN_VERSION} />
1371
- <SettingsRows
1372
- copy={sectionCopy(t, chinese)}
1373
- state={state}
1374
- edit={edit}
1375
- resetField={resetField}
1376
- save={props.save}
1377
- discard={props.discard}
1378
- writeField={props.writeField}
1379
- />
396
+ <SettingsRows copy={sectionCopy(t, chinese)} state={state} edit={edit} resetField={resetField} save={props.save} discard={props.discard} writeField={props.writeField} />
1380
397
  </div>
1381
398
  )
1382
399
  }
@@ -1400,17 +417,7 @@ export function SettingsPage(props: PageProps): unknown {
1400
417
  }
1401
418
  const edit = props.edit ?? ((): void => {})
1402
419
  const resetField = props.resetField ?? ((): void => {})
1403
- return (
1404
- <SettingsRows
1405
- copy={pageCopy(t)}
1406
- state={state}
1407
- edit={edit}
1408
- resetField={resetField}
1409
- save={props.save}
1410
- discard={props.discard}
1411
- writeField={props.writeField}
1412
- />
1413
- )
420
+ return <SettingsRows copy={pageCopy(t)} state={state} edit={edit} resetField={resetField} save={props.save} discard={props.discard} writeField={props.writeField} />
1414
421
  }
1415
422
 
1416
423
  /** Structural face of one bound settings scope. */
@@ -1543,20 +550,18 @@ export function installSettingsPages(ctx: ClientContext, getLocale?: () => Local
1543
550
  // The Settings dialog's page, unchanged in behaviour: a fresh id puts it
1544
551
  // beside the shipped sections, and the frame handles an unloaded plugin.
1545
552
  ctx.effect(() => {
1546
- const stop = slots.inject(
1547
- SETTINGS_SECTION_SLOT,
1548
- () =>
1549
- slots.register(
1550
- {
1551
- name: SETTINGS_SECTION_SLOT,
1552
- id: SETTINGS_SECTION_ID,
1553
- order: SETTINGS_SECTION_ORDER,
1554
- label: () => sectionTitle(getLocale),
1555
- locale: LOCALE_NS,
1556
- inject: () => controller.inject(),
1557
- },
1558
- SettingsSection,
1559
- ),
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
+ ),
1560
565
  ) as () => void
1561
566
  return stop
1562
567
  }, 'dsh-prompt-enhance: settings section')
@@ -1566,18 +571,16 @@ export function installSettingsPages(ctx: ClientContext, getLocale?: () => Local
1566
571
  // for a namespace the Host does not serve.
1567
572
  const whileServed = typeof forms.whileServed === 'function' ? forms.whileServed.bind(forms) : undefined
1568
573
  const registerRowPage = (): (() => void) => {
1569
- const stop = slots.inject(
1570
- SETTINGS_ROW_CONFIG_SLOT,
1571
- () =>
1572
- slots.register(
1573
- {
1574
- name: SETTINGS_ROW_CONFIG_SLOT,
1575
- key: SETTINGS_ROW_CONFIG_KEY,
1576
- locale: LOCALE_NS,
1577
- inject: () => controller.inject(),
1578
- },
1579
- SettingsPage,
1580
- ),
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
+ ),
1581
584
  ) as () => void
1582
585
  return stop
1583
586
  }