@surfishs/dsh-prompt-enhance 0.1.1 → 0.1.3

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
- import type { EnhanceError, EnhanceUsage, ClientFailureReason } from '../shared/protocol'
11
+ import type { ContextUsage, 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
@@ -161,17 +177,79 @@ function totalTokensOf(usage: EnhanceUsage): number {
161
177
  return usage.totalTokens ?? usage.inputTokens + usage.outputTokens + (usage.cacheReadTokens ?? 0) + (usage.cacheWriteTokens ?? 0)
162
178
  }
163
179
 
180
+ /**
181
+ * Footer info button: the call's context usage, on hover/focus (and a tap on
182
+ * touch devices, where there is no hover). The card has no room for this in
183
+ * its header, and the footer keeps the action row intact.
184
+ * @param props - the usage numbers and the locale seat.
185
+ * @returns the info button and its tooltip.
186
+ */
187
+ function ContextUsageInfo(props: { usage?: ContextUsage; t: TranslateNS<'dsh-prompt-enhance'> }): ReactNode {
188
+ const { usage, t } = props
189
+ const [open, setOpen] = useState(false)
190
+ // Reaching the turn cap is the normal shape of the window, not a warning;
191
+ // only a character squeeze or a cut turn needs the amber treatment.
192
+ const limited = usage !== undefined && (usage.cutTurn || usage.limitedBy === 'chars')
193
+ const percent = usage !== undefined && usage.maxChars > 0 ? Math.round((usage.usedChars / usage.maxChars) * 100) : 0
194
+ const stats =
195
+ usage === undefined
196
+ ? t('panel.contextUnused')
197
+ : t('panel.contextStats', {
198
+ turns: usage.usedTurns,
199
+ maxTurns: usage.maxTurns,
200
+ chars: formatTokens(usage.usedChars),
201
+ maxChars: formatTokens(usage.maxChars),
202
+ percent,
203
+ })
204
+ const reason = usage === undefined ? '' : usage.cutTurn ? t('panel.contextCut') : usage.limitedBy === 'chars' ? t('panel.contextCharsLimited') : ''
205
+ return (
206
+ <span className="dsh-pe-context-wrap">
207
+ <button
208
+ type="button"
209
+ className={`dsh-pe-context${limited ? ' is-limited' : ''}`}
210
+ aria-label={t('panel.contextUsage')}
211
+ aria-expanded={open}
212
+ onMouseEnter={() => setOpen(true)}
213
+ onMouseLeave={() => setOpen(false)}
214
+ onFocus={() => setOpen(true)}
215
+ onBlur={() => setOpen(false)}
216
+ onClick={() => setOpen((value) => !value)}
217
+ onKeyDown={(event) => {
218
+ if (event.key === 'Escape') setOpen(false)
219
+ }}
220
+ >
221
+ <svg className="dsh-pe-context-icon" viewBox="0 0 16 16" aria-hidden="true" focusable="false">
222
+ <rect x="2.2" y="3.4" width="11.6" height="9.2" rx="2.2" fill="none" stroke="currentColor" strokeWidth="1.2" />
223
+ <path d="M5.2 6.6h5.6M5.2 9.2h3.8" fill="none" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" />
224
+ </svg>
225
+ </button>
226
+ {open && (
227
+ <span role="tooltip" className="dsh-pe-context-tip">
228
+ <span className="dsh-pe-context-stats">{stats}</span>
229
+ {reason !== '' && <span className="dsh-pe-context-reason">{reason}</span>}
230
+ </span>
231
+ )}
232
+ </span>
233
+ )
234
+ }
235
+
164
236
  /** One enhancement result card. */
165
237
  export function ResultPanel(props: ResultPanelProps): ReactNode {
166
- const { state, t, onApply, onCancel, onRetry, applied = false, onUndo, onRegenerate, regenerated = false } = props
238
+ const { state, t, onApply, onCancel, onRetry, applied = false, onUndo, onRegenerate, regenerated = false, collapsed = false, onToggleCollapsed, foldAnimation = true } = props
167
239
  const [copied, setCopied] = useState<'idle' | 'ok' | 'failed'>('idle')
240
+ /** Pending reset of the copy label; one timer only, so a second copy cannot be cut short by the first. */
241
+ const copyTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
168
242
 
169
243
  const copy = useCallback((): void => {
170
244
  if (state.result === undefined) return
171
245
  const text = state.result.text
172
246
  const done = (ok: boolean): void => {
173
247
  setCopied(ok ? 'ok' : 'failed')
174
- if (ok) setTimeout(() => setCopied('idle'), 2500)
248
+ // Both outcomes are transient. A failure used to stay on the button until
249
+ // the next click, which reads as a stuck control rather than an error; the
250
+ // label now clears the same way a success does.
251
+ if (copyTimer.current !== undefined) clearTimeout(copyTimer.current)
252
+ copyTimer.current = setTimeout(() => setCopied('idle'), 2500)
175
253
  }
176
254
  // navigator.clipboard only exists in secure contexts (https / localhost);
177
255
  // guard the dereference and fall back for plain-http LAN access.
@@ -222,7 +300,7 @@ export function ResultPanel(props: ResultPanelProps): ReactNode {
222
300
  )
223
301
 
224
302
  return (
225
- <section className="dsh-pe-panel" role="region" aria-label={t('panel.title')}>
303
+ <section className={`dsh-pe-panel${collapsed ? ' is-collapsed' : ''}${foldAnimation ? '' : ' is-static'}`} role="region" aria-label={t('panel.title')}>
226
304
  <header className="dsh-pe-head">
227
305
  <span className="dsh-pe-title">
228
306
  <SparkleFishIcon size={15} />
@@ -231,7 +309,15 @@ export function ResultPanel(props: ResultPanelProps): ReactNode {
231
309
  <div className="dsh-pe-head-actions">
232
310
  {state.phase === 'result' && state.result !== undefined && (
233
311
  <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) })}
312
+ {t('panel.model', { provider: state.result.provider, model: state.result.model })}
313
+ {state.result.reasoningEffort === undefined ? null : (
314
+ <>
315
+ {' · '}
316
+ {state.result.reasoningEffort === 'inherit' ? t('panel.effortDefault') : capitalizeEffort(state.result.reasoningEffort)}
317
+ </>
318
+ )}
319
+ {' · '}
320
+ {t('panel.elapsed', { ms: formatMs(state.result.elapsedMs) })}
235
321
  {state.result.usage === undefined ? null : (
236
322
  <>
237
323
  {' · '}
@@ -240,59 +326,78 @@ export function ResultPanel(props: ResultPanelProps): ReactNode {
240
326
  )}
241
327
  </span>
242
328
  )}
329
+ {/* Collapsed, the body — and with it the warnings — is hidden, so the
330
+ header carries a marker instead of silently swallowing one. */}
331
+ {collapsed && (state.stale === true || state.result?.truncated === true) ? (
332
+ <span className="dsh-pe-warn-dot" title={state.stale === true ? t('panel.stale.warn') : t('panel.truncated')} aria-hidden="true">
333
+ ⚠
334
+ </span>
335
+ ) : null}
336
+ <button type="button" className="dsh-pe-collapse" aria-label={collapsed ? t('panel.expand') : t('panel.collapse')} aria-expanded={!collapsed} onClick={onToggleCollapsed}>
337
+ <ChevronIcon open={!collapsed} />
338
+ </button>
243
339
  <button type="button" className="dsh-pe-close" aria-label={t('panel.close')} onClick={onCancel}>
244
- ✕
340
+ <XIcon />
245
341
  </button>
246
342
  </div>
247
343
  </header>
248
344
 
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>
345
+ {/* The body keeps the header above and the footer below; only it folds.
346
+ It stays mounted so the fold can animate (grid track 1fr ↔ 0fr) and the
347
+ result's scroll position survives a fold. Collapsed, the CSS hides it
348
+ from painting, selection and assistive tech. */}
349
+ <div className="dsh-pe-body" aria-hidden={collapsed || undefined}>
350
+ <div className="dsh-pe-body-inner">
351
+ {state.phase === 'loading' && (
352
+ <div className="dsh-pe-loading">
353
+ {state.streaming === undefined || state.streaming === '' ? (
354
+ <>
355
+ <div className="dsh-pe-spin" aria-hidden />
356
+ <div>{t('panel.loading')}</div>
357
+ <div className="dsh-pe-hint">{t('panel.loading.hint')}</div>
358
+ </>
359
+ ) : (
360
+ <div className="dsh-pe-stream">
361
+ <div className="dsh-pe-col-title">
362
+ <span className="dsh-pe-spin small" aria-hidden />
363
+ {t('panel.streaming')}
364
+ </div>
365
+ <pre className="dsh-pe-result-text">{state.streaming}</pre>
366
+ </div>
367
+ )}
264
368
  </div>
265
369
  )}
266
- </div>
267
- )}
268
370
 
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
- </>
371
+ {state.phase === 'error' && state.error !== undefined && (
372
+ <div className="dsh-pe-error">
373
+ {state.error.localized !== undefined ? (
374
+ <div>{state.error.localized}</div>
375
+ ) : (
376
+ <>
377
+ <div>{localizedErrorMessage(t, state.error.code, state.error.params)}</div>
378
+ {state.error.message !== undefined && state.error.message !== '' && <div className="dsh-pe-error-detail">{state.error.message}</div>}
379
+ </>
380
+ )}
381
+ </div>
278
382
  )}
279
- </div>
280
- )}
281
383
 
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
- )}
384
+ {state.phase === 'result' && state.result !== undefined && (
385
+ <div className="dsh-pe-result">
386
+ <pre className="dsh-pe-result-text">{state.result.text}</pre>
387
+ </div>
388
+ )}
287
389
 
288
- {state.phase === 'result' && state.result?.truncated === true && <div className="dsh-pe-stale">⚠ {t('panel.truncated')}</div>}
390
+ {state.phase === 'result' && state.result?.truncated === true && <div className="dsh-pe-stale">⚠ {t('panel.truncated')}</div>}
289
391
 
290
- {state.phase === 'result' && state.stale && <div className="dsh-pe-stale">⚠ {t('panel.stale.warn')}</div>}
392
+ {state.phase === 'result' && state.stale && <div className="dsh-pe-stale">⚠ {t('panel.stale.warn')}</div>}
393
+ </div>
394
+ </div>
291
395
 
292
396
  <footer className="dsh-pe-foot">
397
+ {state.phase === 'result' && <ContextUsageInfo usage={state.result?.context} t={t} />}
293
398
  <span className="dsh-pe-grow" />
294
399
  {state.phase === 'result' && (
295
- <button type="button" className="dsh-pe-btn-action plain dsh-pe-btn-swap" onClick={onRegenerate} disabled={onRegenerate === undefined}>
400
+ <button type="button" className="dsh-pe-btn-action plain dsh-pe-btn-floor" onClick={onRegenerate} disabled={onRegenerate === undefined}>
296
401
  <RegenerateIcon />
297
402
  <span className="dsh-pe-swap">
298
403
  {swapLabel(!regenerated, t('panel.regenerate'))}
@@ -302,21 +407,21 @@ export function ResultPanel(props: ResultPanelProps): ReactNode {
302
407
  )}
303
408
  {state.phase === 'error' && (
304
409
  <>
305
- {retryable(state.error?.code) && onRetry !== undefined && (
306
- <button type="button" className="dsh-pe-btn-action plain" onClick={onRetry}>
410
+ {retryable(state.error) && onRetry !== undefined && (
411
+ <button type="button" className="dsh-pe-btn-action plain dsh-pe-btn-floor" onClick={onRetry}>
307
412
  {t('panel.retry')}
308
413
  </button>
309
414
  )}
310
415
  </>
311
416
  )}
312
417
  {state.phase === 'loading' && (
313
- <button type="button" className="dsh-pe-btn-action plain" onClick={onCancel}>
418
+ <button type="button" className="dsh-pe-btn-action plain dsh-pe-btn-floor" onClick={onCancel}>
314
419
  {t('panel.cancel')}
315
420
  </button>
316
421
  )}
317
422
  {state.phase === 'result' && (
318
423
  <>
319
- <button type="button" className="dsh-pe-btn-action plain dsh-pe-btn-swap" onClick={copy}>
424
+ <button type="button" className="dsh-pe-btn-action plain dsh-pe-btn-floor" onClick={copy}>
320
425
  <CopyIcon />
321
426
  <span className="dsh-pe-swap">
322
427
  {swapLabel(copied === 'idle', t('panel.copy'))}
@@ -325,7 +430,7 @@ export function ResultPanel(props: ResultPanelProps): ReactNode {
325
430
  </span>
326
431
  </button>
327
432
  {applied ? (
328
- <button type="button" className="dsh-pe-btn-action primary dsh-pe-btn-swap" onClick={onUndo} disabled={onUndo === undefined}>
433
+ <button type="button" className="dsh-pe-btn-action primary dsh-pe-btn-floor" onClick={onUndo} disabled={onUndo === undefined}>
329
434
  <UndoIcon />
330
435
  {/* The undo label reserves the width of the fill label it replaces,
331
436
  so switching between the two does not resize the footer. */}
@@ -335,7 +440,7 @@ export function ResultPanel(props: ResultPanelProps): ReactNode {
335
440
  </span>
336
441
  </button>
337
442
  ) : (
338
- <button type="button" className="dsh-pe-btn-action primary dsh-pe-btn-swap" onClick={onApply}>
443
+ <button type="button" className="dsh-pe-btn-action primary dsh-pe-btn-floor" onClick={onApply}>
339
444
  <FillIcon />
340
445
  <span className="dsh-pe-swap">
341
446
  {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}>
@@ -11,6 +11,7 @@ import {
11
11
  type EnhanceError,
12
12
  type EnhanceErrorCode,
13
13
  type EnhanceRequestBody,
14
+ type ContextUsage,
14
15
  type EnhanceResult,
15
16
  type EnhanceStreamEvent,
16
17
  type EnhanceUsage,
@@ -82,6 +83,41 @@ function parseUsage(value: unknown): EnhanceUsage | undefined {
82
83
  }
83
84
 
84
85
  /** Strictly narrow one success value; anything malformed is a client-visible error. */
86
+ /**
87
+ * Validate the optional context-usage block the host sends with a result.
88
+ *
89
+ * The panel relies on the numbers being integers (malformed fractions would
90
+ * format oddly) and on `limitedBy` being one of the two caps; anything else
91
+ * is treated as "no usage" rather than surfacing a broken tooltip.
92
+ * @param value - the untrusted wire value.
93
+ * @returns the usage, or undefined when absent/malformed.
94
+ */
95
+ function parseContextUsage(value: unknown): ContextUsage | undefined {
96
+ const record = value as Partial<ContextUsage> | null
97
+ if (record === null || typeof record !== 'object') return undefined
98
+ const integer = (field: unknown): field is number => typeof field === 'number' && Number.isInteger(field) && field >= 0
99
+ if (
100
+ !integer(record.usedTurns) ||
101
+ !integer(record.maxTurns) ||
102
+ !integer(record.usedChars) ||
103
+ !integer(record.maxChars) ||
104
+ !integer(record.droppedTurns) ||
105
+ (record.limitedBy !== null && record.limitedBy !== 'turns' && record.limitedBy !== 'chars') ||
106
+ typeof record.cutTurn !== 'boolean'
107
+ ) {
108
+ return undefined
109
+ }
110
+ return {
111
+ usedTurns: record.usedTurns,
112
+ maxTurns: record.maxTurns,
113
+ usedChars: record.usedChars,
114
+ maxChars: record.maxChars,
115
+ droppedTurns: record.droppedTurns,
116
+ limitedBy: record.limitedBy,
117
+ cutTurn: record.cutTurn,
118
+ }
119
+ }
120
+
85
121
  function parseResult(value: unknown): EnhanceResult {
86
122
  const record = value as Partial<EnhanceResult> | null
87
123
  if (
@@ -97,6 +133,7 @@ function parseResult(value: unknown): EnhanceResult {
97
133
  Number.isFinite(record.elapsedMs)
98
134
  ) {
99
135
  const usage = parseUsage((record as { usage?: unknown }).usage)
136
+ const context = parseContextUsage((record as { context?: unknown }).context)
100
137
  return {
101
138
  text: record.text,
102
139
  provider: record.provider,
@@ -109,6 +146,11 @@ function parseResult(value: unknown): EnhanceResult {
109
146
  // the UI never seeing it. Only `true` is ever normalized in, matching the
110
147
  // host, which sets the field solely on a capped finish.
111
148
  ...(record.truncated === true ? { truncated: true } : {}),
149
+ // Same trap as runcated above: rebuilding the object field by field
150
+ // drops anything not listed here, so a new result field has to be added
151
+ // in this exact place or the UI silently never sees it.
152
+ ...(typeof record.reasoningEffort === 'string' ? { reasoningEffort: record.reasoningEffort } : {}),
153
+ ...(context === undefined ? {} : { context }),
112
154
  }
113
155
  }
114
156
  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) {