@surfishs/dsh-prompt-enhance 0.1.1 → 0.1.2

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.
@@ -6,12 +6,12 @@
6
6
  * @module dsh-prompt-enhance/client/ResultPanel
7
7
  */
8
8
 
9
- import { useCallback, useState, type ReactNode } from 'react'
9
+ import { useCallback, useRef, useState, type ReactNode } from 'react'
10
10
  import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'
11
11
  import type { EnhanceError, EnhanceUsage, ClientFailureReason } from '../shared/protocol'
12
12
  import type { PromptEnhanceKey } from './locales'
13
13
  import type { PanelState } from './ui-state'
14
- import { CopyIcon, FillIcon, RegenerateIcon, UndoIcon } from './ActionIcons'
14
+ import { ChevronIcon, CopyIcon, FillIcon, RegenerateIcon, UndoIcon, XIcon } from './ActionIcons'
15
15
  import { SparkleFishIcon } from './SparkleFishIcon'
16
16
 
17
17
  /** Props of the result card. */
@@ -32,10 +32,16 @@ export interface ResultPanelProps {
32
32
  onRegenerate?: () => void
33
33
  /** Show the transient "regenerated" label on that button instead of its normal text. */
34
34
  regenerated?: boolean
35
+ /** Hide the body, keeping the header and the footer rows (and their actions). */
36
+ collapsed?: boolean
37
+ /** Toggle {@link collapsed}. */
38
+ onToggleCollapsed?: () => void
39
+ /** Play the fold transition; false switches instantly (a setting). */
40
+ foldAnimation?: boolean
35
41
  }
36
42
 
37
- /** Whether one error phase is worth retrying (model/transport failures). */
38
- const retryable = (code: string | undefined): boolean => code === 'upstream' || code === 'timeout' || code === 'internal'
43
+ /** Whether one error phase is worth retrying: model/transport failures, but never a call the user cancelled. */
44
+ const retryable = (error: EnhanceError | undefined): boolean => error?.code === 'upstream' || error?.code === 'timeout' || (error?.code === 'internal' && error.params?.reason !== 'cancelled')
39
45
 
40
46
  /**
41
47
  * Wire `reason` (`UpstreamReason`, kebab-case as the host sends it) → the
@@ -152,6 +158,16 @@ function formatTokens(tokens: number): string {
152
158
  return tokens.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
153
159
  }
154
160
 
161
+ /**
162
+ * Title-case an adapter-owned effort id for the badge ("off" → "Off"). Ids are
163
+ * opaque strings, so only a leading ASCII letter is changed.
164
+ * @param value - the effort id the host reported.
165
+ * @returns the label shown in the badge.
166
+ */
167
+ function capitalizeEffort(value: string): string {
168
+ return value.charAt(0).toUpperCase() + value.slice(1)
169
+ }
170
+
155
171
  /**
156
172
  * The call's billed total: the provider's own number when it reported one,
157
173
  * otherwise the disjoint counters added up (uncached input + output + cache
@@ -163,15 +179,21 @@ function totalTokensOf(usage: EnhanceUsage): number {
163
179
 
164
180
  /** One enhancement result card. */
165
181
  export function ResultPanel(props: ResultPanelProps): ReactNode {
166
- const { state, t, onApply, onCancel, onRetry, applied = false, onUndo, onRegenerate, regenerated = false } = props
182
+ const { state, t, onApply, onCancel, onRetry, applied = false, onUndo, onRegenerate, regenerated = false, collapsed = false, onToggleCollapsed, foldAnimation = true } = props
167
183
  const [copied, setCopied] = useState<'idle' | 'ok' | 'failed'>('idle')
184
+ /** Pending reset of the copy label; one timer only, so a second copy cannot be cut short by the first. */
185
+ const copyTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
168
186
 
169
187
  const copy = useCallback((): void => {
170
188
  if (state.result === undefined) return
171
189
  const text = state.result.text
172
190
  const done = (ok: boolean): void => {
173
191
  setCopied(ok ? 'ok' : 'failed')
174
- if (ok) setTimeout(() => setCopied('idle'), 2500)
192
+ // Both outcomes are transient. A failure used to stay on the button until
193
+ // the next click, which reads as a stuck control rather than an error; the
194
+ // label now clears the same way a success does.
195
+ if (copyTimer.current !== undefined) clearTimeout(copyTimer.current)
196
+ copyTimer.current = setTimeout(() => setCopied('idle'), 2500)
175
197
  }
176
198
  // navigator.clipboard only exists in secure contexts (https / localhost);
177
199
  // guard the dereference and fall back for plain-http LAN access.
@@ -222,7 +244,7 @@ export function ResultPanel(props: ResultPanelProps): ReactNode {
222
244
  )
223
245
 
224
246
  return (
225
- <section className="dsh-pe-panel" role="region" aria-label={t('panel.title')}>
247
+ <section className={`dsh-pe-panel${collapsed ? ' is-collapsed' : ''}${foldAnimation ? '' : ' is-static'}`} role="region" aria-label={t('panel.title')}>
226
248
  <header className="dsh-pe-head">
227
249
  <span className="dsh-pe-title">
228
250
  <SparkleFishIcon size={15} />
@@ -231,7 +253,15 @@ export function ResultPanel(props: ResultPanelProps): ReactNode {
231
253
  <div className="dsh-pe-head-actions">
232
254
  {state.phase === 'result' && state.result !== undefined && (
233
255
  <span className="dsh-pe-badge">
234
- {t('panel.model', { provider: state.result.provider, model: state.result.model })} · {t('panel.elapsed', { ms: formatMs(state.result.elapsedMs) })}
256
+ {t('panel.model', { provider: state.result.provider, model: state.result.model })}
257
+ {state.result.reasoningEffort === undefined ? null : (
258
+ <>
259
+ {' · '}
260
+ {state.result.reasoningEffort === 'inherit' ? t('panel.effortDefault') : capitalizeEffort(state.result.reasoningEffort)}
261
+ </>
262
+ )}
263
+ {' · '}
264
+ {t('panel.elapsed', { ms: formatMs(state.result.elapsedMs) })}
235
265
  {state.result.usage === undefined ? null : (
236
266
  <>
237
267
  {' · '}
@@ -240,59 +270,77 @@ export function ResultPanel(props: ResultPanelProps): ReactNode {
240
270
  )}
241
271
  </span>
242
272
  )}
273
+ {/* Collapsed, the body — and with it the warnings — is hidden, so the
274
+ header carries a marker instead of silently swallowing one. */}
275
+ {collapsed && (state.stale === true || state.result?.truncated === true) ? (
276
+ <span className="dsh-pe-warn-dot" title={state.stale === true ? t('panel.stale.warn') : t('panel.truncated')} aria-hidden="true">
277
+ ⚠
278
+ </span>
279
+ ) : null}
280
+ <button type="button" className="dsh-pe-collapse" aria-label={collapsed ? t('panel.expand') : t('panel.collapse')} aria-expanded={!collapsed} onClick={onToggleCollapsed}>
281
+ <ChevronIcon open={!collapsed} />
282
+ </button>
243
283
  <button type="button" className="dsh-pe-close" aria-label={t('panel.close')} onClick={onCancel}>
244
- ✕
284
+ <XIcon />
245
285
  </button>
246
286
  </div>
247
287
  </header>
248
288
 
249
- {state.phase === 'loading' && (
250
- <div className="dsh-pe-loading">
251
- {state.streaming === undefined || state.streaming === '' ? (
252
- <>
253
- <div className="dsh-pe-spin" aria-hidden />
254
- <div>{t('panel.loading')}</div>
255
- <div className="dsh-pe-hint">{t('panel.loading.hint')}</div>
256
- </>
257
- ) : (
258
- <div className="dsh-pe-stream">
259
- <div className="dsh-pe-col-title">
260
- <span className="dsh-pe-spin small" aria-hidden />
261
- {t('panel.streaming')}
262
- </div>
263
- <pre className="dsh-pe-result-text">{state.streaming}</pre>
289
+ {/* The body keeps the header above and the footer below; only it folds.
290
+ It stays mounted so the fold can animate (grid track 1fr ↔ 0fr) and the
291
+ result's scroll position survives a fold. Collapsed, the CSS hides it
292
+ from painting, selection and assistive tech. */}
293
+ <div className="dsh-pe-body" aria-hidden={collapsed || undefined}>
294
+ <div className="dsh-pe-body-inner">
295
+ {state.phase === 'loading' && (
296
+ <div className="dsh-pe-loading">
297
+ {state.streaming === undefined || state.streaming === '' ? (
298
+ <>
299
+ <div className="dsh-pe-spin" aria-hidden />
300
+ <div>{t('panel.loading')}</div>
301
+ <div className="dsh-pe-hint">{t('panel.loading.hint')}</div>
302
+ </>
303
+ ) : (
304
+ <div className="dsh-pe-stream">
305
+ <div className="dsh-pe-col-title">
306
+ <span className="dsh-pe-spin small" aria-hidden />
307
+ {t('panel.streaming')}
308
+ </div>
309
+ <pre className="dsh-pe-result-text">{state.streaming}</pre>
310
+ </div>
311
+ )}
264
312
  </div>
265
313
  )}
266
- </div>
267
- )}
268
314
 
269
- {state.phase === 'error' && state.error !== undefined && (
270
- <div className="dsh-pe-error">
271
- {state.error.localized !== undefined ? (
272
- <div>{state.error.localized}</div>
273
- ) : (
274
- <>
275
- <div>{localizedErrorMessage(t, state.error.code, state.error.params)}</div>
276
- {state.error.message !== undefined && state.error.message !== '' && <div className="dsh-pe-error-detail">{state.error.message}</div>}
277
- </>
315
+ {state.phase === 'error' && state.error !== undefined && (
316
+ <div className="dsh-pe-error">
317
+ {state.error.localized !== undefined ? (
318
+ <div>{state.error.localized}</div>
319
+ ) : (
320
+ <>
321
+ <div>{localizedErrorMessage(t, state.error.code, state.error.params)}</div>
322
+ {state.error.message !== undefined && state.error.message !== '' && <div className="dsh-pe-error-detail">{state.error.message}</div>}
323
+ </>
324
+ )}
325
+ </div>
278
326
  )}
279
- </div>
280
- )}
281
327
 
282
- {state.phase === 'result' && state.result !== undefined && (
283
- <div className="dsh-pe-result">
284
- <pre className="dsh-pe-result-text">{state.result.text}</pre>
285
- </div>
286
- )}
328
+ {state.phase === 'result' && state.result !== undefined && (
329
+ <div className="dsh-pe-result">
330
+ <pre className="dsh-pe-result-text">{state.result.text}</pre>
331
+ </div>
332
+ )}
287
333
 
288
- {state.phase === 'result' && state.result?.truncated === true && <div className="dsh-pe-stale">⚠ {t('panel.truncated')}</div>}
334
+ {state.phase === 'result' && state.result?.truncated === true && <div className="dsh-pe-stale">⚠ {t('panel.truncated')}</div>}
289
335
 
290
- {state.phase === 'result' && state.stale && <div className="dsh-pe-stale">⚠ {t('panel.stale.warn')}</div>}
336
+ {state.phase === 'result' && state.stale && <div className="dsh-pe-stale">⚠ {t('panel.stale.warn')}</div>}
337
+ </div>
338
+ </div>
291
339
 
292
340
  <footer className="dsh-pe-foot">
293
341
  <span className="dsh-pe-grow" />
294
342
  {state.phase === 'result' && (
295
- <button type="button" className="dsh-pe-btn-action plain dsh-pe-btn-swap" onClick={onRegenerate} disabled={onRegenerate === undefined}>
343
+ <button type="button" className="dsh-pe-btn-action plain dsh-pe-btn-floor" onClick={onRegenerate} disabled={onRegenerate === undefined}>
296
344
  <RegenerateIcon />
297
345
  <span className="dsh-pe-swap">
298
346
  {swapLabel(!regenerated, t('panel.regenerate'))}
@@ -302,21 +350,21 @@ export function ResultPanel(props: ResultPanelProps): ReactNode {
302
350
  )}
303
351
  {state.phase === 'error' && (
304
352
  <>
305
- {retryable(state.error?.code) && onRetry !== undefined && (
306
- <button type="button" className="dsh-pe-btn-action plain" onClick={onRetry}>
353
+ {retryable(state.error) && onRetry !== undefined && (
354
+ <button type="button" className="dsh-pe-btn-action plain dsh-pe-btn-floor" onClick={onRetry}>
307
355
  {t('panel.retry')}
308
356
  </button>
309
357
  )}
310
358
  </>
311
359
  )}
312
360
  {state.phase === 'loading' && (
313
- <button type="button" className="dsh-pe-btn-action plain" onClick={onCancel}>
361
+ <button type="button" className="dsh-pe-btn-action plain dsh-pe-btn-floor" onClick={onCancel}>
314
362
  {t('panel.cancel')}
315
363
  </button>
316
364
  )}
317
365
  {state.phase === 'result' && (
318
366
  <>
319
- <button type="button" className="dsh-pe-btn-action plain dsh-pe-btn-swap" onClick={copy}>
367
+ <button type="button" className="dsh-pe-btn-action plain dsh-pe-btn-floor" onClick={copy}>
320
368
  <CopyIcon />
321
369
  <span className="dsh-pe-swap">
322
370
  {swapLabel(copied === 'idle', t('panel.copy'))}
@@ -325,7 +373,7 @@ export function ResultPanel(props: ResultPanelProps): ReactNode {
325
373
  </span>
326
374
  </button>
327
375
  {applied ? (
328
- <button type="button" className="dsh-pe-btn-action primary dsh-pe-btn-swap" onClick={onUndo} disabled={onUndo === undefined}>
376
+ <button type="button" className="dsh-pe-btn-action primary dsh-pe-btn-floor" onClick={onUndo} disabled={onUndo === undefined}>
329
377
  <UndoIcon />
330
378
  {/* The undo label reserves the width of the fill label it replaces,
331
379
  so switching between the two does not resize the footer. */}
@@ -335,7 +383,7 @@ export function ResultPanel(props: ResultPanelProps): ReactNode {
335
383
  </span>
336
384
  </button>
337
385
  ) : (
338
- <button type="button" className="dsh-pe-btn-action primary dsh-pe-btn-swap" onClick={onApply}>
386
+ <button type="button" className="dsh-pe-btn-action primary dsh-pe-btn-floor" onClick={onApply}>
339
387
  <FillIcon />
340
388
  <span className="dsh-pe-swap">
341
389
  {swapLabel(true, t('panel.apply'))}
@@ -12,7 +12,7 @@ import type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots
12
12
  import type {} from '@deepseek-ai/dsh-client-ui-conversation/client'
13
13
  import * as ui from './ui-state'
14
14
  import { useSessionKey } from './session-key'
15
- import { UndoIcon } from './ActionIcons'
15
+ import { CheckIcon, UndoIcon } from './ActionIcons'
16
16
  import { useDockAlignment } from './useDockAlignment'
17
17
 
18
18
  /** Props of the input.dock entry: the InputZone owner share + session kit + locale seat. */
@@ -58,7 +58,7 @@ export function UndoBar(props: UndoBarProps): ReactNode {
58
58
  <div ref={rootRef} className="dsh-pe-dock">
59
59
  <div className="dsh-pe-undo">
60
60
  <span className="dsh-pe-undo-check" aria-hidden>
61
- ✓
61
+ <CheckIcon />
62
62
  </span>
63
63
  <span>{t('undo.applied')}</span>
64
64
  <button type="button" className="dsh-pe-undo-link" onClick={undo}>
@@ -109,6 +109,10 @@ function parseResult(value: unknown): EnhanceResult {
109
109
  // the UI never seeing it. Only `true` is ever normalized in, matching the
110
110
  // host, which sets the field solely on a capped finish.
111
111
  ...(record.truncated === true ? { truncated: true } : {}),
112
+ // Same trap as runcated above: rebuilding the object field by field
113
+ // drops anything not listed here, so a new result field has to be added
114
+ // in this exact place or the UI silently never sees it.
115
+ ...(typeof record.reasoningEffort === 'string' ? { reasoningEffort: record.reasoningEffort } : {}),
112
116
  }
113
117
  }
114
118
  throw new EnhanceClientError({ code: 'internal', params: { reason: 'malformed' } })
@@ -15,6 +15,7 @@
15
15
  * @module dsh-prompt-enhance/client
16
16
  */
17
17
 
18
+ import type { ReactNode } from 'react'
18
19
  import type { Context as ClientContext } from '@deepseek-ai/cordis'
19
20
  import type {} from '@deepseek-ai/dsh-client-ui-slots'
20
21
  import type {} from '@deepseek-ai/dsh-client-locale/client'
@@ -26,6 +27,7 @@ import type {} from '@deepseek-ai/dsh-client-ui-settings/client'
26
27
  import type {} from '@deepseek-ai/dsh-client-ui-session/client'
27
28
  import type {} from '@deepseek-ai/dsh-client-store'
28
29
  import { EnhanceButton } from './EnhanceButton'
30
+ import type { EnhanceButtonProps } from './EnhanceButton'
29
31
  import { ResultDock } from './ResultDock'
30
32
  import { UndoBar } from './UndoBar'
31
33
  import * as ui from './ui-state'
@@ -129,7 +131,12 @@ export function apply(ctx: ClientContext): void {
129
131
  if (slots === undefined) return
130
132
  return slots.inject('conversation.input.right', () => {
131
133
  try {
132
- return slots.register({ name: 'conversation.input.right', id: 'dsh-prompt-enhance', order: 60, locale: NS }, EnhanceButton as unknown as never)
134
+ // The quick-settings menu needs the client context (model directories)
135
+ // but slot components only receive their standard props, so hand the
136
+ // context down through the closure — the same shape other composer
137
+ // plugins in this ecosystem use.
138
+ const Bound = (buttonProps: EnhanceButtonProps): ReactNode => <EnhanceButton {...buttonProps} __ctx={ctx as never} />
139
+ return slots.register({ name: 'conversation.input.right', id: 'dsh-prompt-enhance', order: 60, locale: NS }, Bound as unknown as never)
133
140
  } catch (error) {
134
141
  return report('composer enhance button slot', error)
135
142
  }
@@ -35,6 +35,31 @@ async function getJson<T>(url: URL, signal?: AbortSignal): Promise<T | undefined
35
35
  }
36
36
  }
37
37
 
38
+ /**
39
+ * How long one catalog answer stays usable. Provider/model names change only
40
+ * when the host registry does, so a short window is enough to make repeated
41
+ * card opens and page mounts free without showing stale names for long.
42
+ */
43
+ export const CATALOG_TTL_MS = 60_000
44
+
45
+ /** One memoized answer. */
46
+ interface Memo<T> {
47
+ value: T
48
+ at: number
49
+ }
50
+
51
+ let providersMemo: Memo<ProviderCatalogEntry[]> | undefined
52
+ const modelsMemo = new Map<string, Memo<ModelCatalog>>()
53
+
54
+ /**
55
+ * Drop every memoized catalog answer. The settings reload controls bypass the
56
+ * cache per call; tests and deployments that swap the registry call this.
57
+ */
58
+ export function clearCatalogCache(): void {
59
+ providersMemo = undefined
60
+ modelsMemo.clear()
61
+ }
62
+
38
63
  /** Resolve one endpoint against the current page origin. */
39
64
  function endpoint(path: string, params: Record<string, string> = {}): URL {
40
65
  const url = new URL(path, globalThis.location?.origin ?? 'http://127.0.0.1')
@@ -42,18 +67,38 @@ function endpoint(path: string, params: Record<string, string> = {}): URL {
42
67
  return url
43
68
  }
44
69
 
45
- /** Registered + dormant providers, or undefined when the read failed. */
46
- export async function fetchProviders(signal?: AbortSignal): Promise<ProviderCatalogEntry[] | undefined> {
70
+ /**
71
+ * Registered + dormant providers, or undefined when the read failed.
72
+ * @param signal - cancels the request.
73
+ * @param options - `refresh` bypasses the short-lived memo.
74
+ * @returns the provider entries, or undefined on failure (failures are not cached).
75
+ */
76
+ export async function fetchProviders(signal?: AbortSignal, options: { refresh?: boolean } = {}): Promise<ProviderCatalogEntry[] | undefined> {
77
+ const cached = providersMemo
78
+ if (options.refresh !== true && cached !== undefined && Date.now() - cached.at <= CATALOG_TTL_MS) return cached.value
47
79
  const value = await getJson<ProviderCatalog>(endpoint(LLM_PROVIDERS_ENDPOINT), signal)
48
80
  if (value === undefined || !Array.isArray(value.providers)) return undefined
49
- return value.providers.filter(
81
+ const providers = value.providers.filter(
50
82
  (entry): entry is ProviderCatalogEntry =>
51
83
  entry !== null && typeof entry === 'object' && typeof entry.id === 'string' && entry.id !== '' && typeof entry.name === 'string' && entry.name !== '' && typeof entry.registered === 'boolean',
52
84
  )
85
+ providersMemo = { value: providers, at: Date.now() }
86
+ return providers
53
87
  }
54
88
 
55
- /** Models of one provider, or undefined when the read failed. */
56
- export async function fetchModels(provider: string, signal?: AbortSignal): Promise<ModelCatalog | undefined> {
89
+ /**
90
+ * Models of one provider, or undefined when the read failed.
91
+ *
92
+ * An empty list is not memoized: it is what a transient adapter failure looks
93
+ * like, and caching it would keep the select empty for the whole window.
94
+ * @param provider - provider id.
95
+ * @param signal - cancels the request.
96
+ * @param options - `refresh` bypasses the short-lived memo.
97
+ * @returns the catalog, or undefined on failure.
98
+ */
99
+ export async function fetchModels(provider: string, signal?: AbortSignal, options: { refresh?: boolean } = {}): Promise<ModelCatalog | undefined> {
100
+ const cached = modelsMemo.get(provider)
101
+ if (options.refresh !== true && cached !== undefined && Date.now() - cached.at <= CATALOG_TTL_MS) return cached.value
57
102
  const value = await getJson<ModelCatalog>(endpoint(LLM_MODELS_ENDPOINT, { provider }), signal)
58
103
  if (value === undefined || !Array.isArray(value.models)) return undefined
59
104
  const models = value.models
@@ -65,7 +110,9 @@ export async function fetchModels(provider: string, signal?: AbortSignal): Promi
65
110
  name: entry.name,
66
111
  ...(typeof entry.description === 'string' && entry.description !== '' ? { description: entry.description } : {}),
67
112
  }))
68
- return { models, ...(typeof value.reason === 'string' ? { reason: value.reason as ModelCatalog['reason'] } : {}) }
113
+ const answer: ModelCatalog = { models, ...(typeof value.reason === 'string' ? { reason: value.reason as ModelCatalog['reason'] } : {}) }
114
+ if (models.length > 0) modelsMemo.set(provider, { value: answer, at: Date.now() })
115
+ return answer
69
116
  }
70
117
 
71
118
  /** Whether one exact route resolves; undefined when the check itself failed. */
@@ -110,7 +157,7 @@ export function useLlmRouting(provider: string, model: string): LlmRoutingState
110
157
  const controller = new AbortController()
111
158
  setProvidersLoading(true)
112
159
  setProvidersFailed(false)
113
- void fetchProviders(controller.signal).then((entries) => {
160
+ void fetchProviders(controller.signal, { refresh: providersToken > 0 }).then((entries) => {
114
161
  if (controller.signal.aborted) return
115
162
  setProvidersLoading(false)
116
163
  if (entries === undefined) {
@@ -134,7 +181,7 @@ export function useLlmRouting(provider: string, model: string): LlmRoutingState
134
181
  setModels([])
135
182
  setModelsLoading(true)
136
183
  setModelsFailed(false)
137
- void fetchModels(provider, controller.signal).then((answer) => {
184
+ void fetchModels(provider, controller.signal, { refresh: modelsToken > 0 }).then((answer) => {
138
185
  if (controller.signal.aborted) return
139
186
  setModelsLoading(false)
140
187
  if (answer === undefined) {