dsh-model-capability-sync 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,870 @@
1
+ /**
2
+ * The capability-sync settings section: pick the provider entry, analyze its
3
+ * models against models.dev, review what would change, then apply.
4
+ *
5
+ * Pure props — no context access, no subscriptions. Everything arrives through
6
+ * the inject face `apply` builds, including the bound translate function.
7
+ */
8
+ import { useEffect, useRef, useState } from 'react'
9
+ import type { ReactNode } from 'react'
10
+ import type { CapabilityFields, LiveResponse, LiveRow, PreviewResponse, PreviewRow, RpcEnvelope } from '../types.ts'
11
+ import type { SortMode } from '../sort.ts'
12
+ import { sortByModelId } from '../sort.ts'
13
+ import type { ModelDraft, SettingsDescriptor, SettingsInjected, SettingsPathOp } from './shared.ts'
14
+ import { isBlank, mergeFields, modelsOf, parseTokenCount, providersOf, sortedModelsOf, TARGET_DEFAULT, targetLabelOf, textOf, withWrittenModels } from './shared.ts'
15
+ import { planNames, renameModels, redirectName } from './rename.ts'
16
+
17
+ /** What `apply` injects into this component. */
18
+ export interface SyncSectionInjected extends SettingsInjected {
19
+ preview(request: { ids: string[]; aliases?: Record<string, string>; names?: Record<string, string>; refresh?: boolean }): Promise<RpcEnvelope<PreviewResponse>>
20
+ live(request: { provider: string; ids: string[] }): Promise<RpcEnvelope<LiveResponse>>
21
+ }
22
+
23
+ export interface SyncSectionProps extends SyncSectionInjected {
24
+ t: (key: string, params?: Record<string, unknown>) => string
25
+ }
26
+
27
+ /** One capability field that applying a row would rewrite. */
28
+ interface FieldChange {
29
+ key: keyof CapabilityFields
30
+ before: unknown
31
+ after: unknown
32
+ }
33
+
34
+ /** One preview row joined with the stored entry it would rewrite. */
35
+ interface PlanRow {
36
+ row: PreviewRow
37
+ model: ModelDraft
38
+ /** What a write would use: catalog values with typed ones on top. */
39
+ fields?: CapabilityFields
40
+ /** The subset that was typed in the table. */
41
+ manual?: CapabilityFields
42
+ changes: FieldChange[]
43
+ }
44
+
45
+ /** Human token count: 128000 → `128K`, 1000000 → `1M`. */
46
+ function tokens(value: unknown): string {
47
+ if (typeof value !== 'number') return '—'
48
+ if (value >= 1_000_000) return `${String(Number((value / 1_000_000).toFixed(1)))}M`
49
+ if (value >= 1000) return `${String(Number((value / 1000).toFixed(0)))}K`
50
+ return String(value)
51
+ }
52
+
53
+ /** Which rule produced a match, as section copy. */
54
+ function viaLabel(row: PreviewRow, t: SyncSectionProps['t']): string {
55
+ switch (row.match?.via) {
56
+ case 'alias': return t('viaAlias')
57
+ case 'exact': return t('viaExact')
58
+ case 'folded': return t('viaFolded')
59
+ case 'basename': return t('viaBasename')
60
+ case 'suffix': return t('viaSuffix')
61
+ case 'prefix': return t('viaPrefix')
62
+ case 'vendor': return t('viaVendor')
63
+ case 'spelling': return t('viaSpelling')
64
+ case 'name': return t('viaName')
65
+ case 'nameSuffix': return t('viaNameSuffix')
66
+ default: return ''
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Merge one row's capability fields into an existing model entry.
72
+ *
73
+ * `name` is never written: a label is the user's or the gateway's choice, and
74
+ * renaming models is not this page's job. The host no longer returns one, and
75
+ * the explicit skip keeps that true even against an older host build.
76
+ * @param model - the entry as stored.
77
+ * @param fields - catalog capabilities.
78
+ * @param overwrite - replace values the user already set.
79
+ * @returns a new entry; the input is never mutated.
80
+ */
81
+ function mergeModel(
82
+ model: ModelDraft,
83
+ fields: CapabilityFields,
84
+ overwrite: boolean,
85
+ manual?: CapabilityFields,
86
+ ): ModelDraft {
87
+ const next: ModelDraft = { ...model }
88
+ for (const [key, value] of Object.entries(fields)) {
89
+ if (key === 'name' || value === undefined) continue
90
+ // A value typed in the table is an instruction, not a suggestion: it is
91
+ // applied even when the entry already holds something and "overwrite" is
92
+ // off, because that switch is about the catalog replacing stored values.
93
+ const typed = manual !== undefined && key in manual
94
+ if (!typed && !overwrite && !isBlank(next[key])) continue
95
+ next[key] = value
96
+ }
97
+ return next
98
+ }
99
+
100
+ /**
101
+ * The fields applying one row would actually rewrite.
102
+ * @param model - the entry as stored.
103
+ * @param fields - catalog capabilities.
104
+ * @param overwrite - replace values the user already set.
105
+ * @returns one entry per changed field, in field order; empty when nothing moves.
106
+ */
107
+ function changesBetween(
108
+ model: ModelDraft,
109
+ fields: CapabilityFields,
110
+ overwrite: boolean,
111
+ manual?: CapabilityFields,
112
+ ): FieldChange[] {
113
+ const next = mergeModel(model, fields, overwrite, manual)
114
+ const changes: FieldChange[] = []
115
+ for (const key of Object.keys(fields) as Array<keyof CapabilityFields>) {
116
+ const before = model[key]
117
+ const after = next[key]
118
+ if (JSON.stringify(before) === JSON.stringify(after)) continue
119
+ changes.push({ key, before, after })
120
+ }
121
+ return changes
122
+ }
123
+
124
+ /** The image verdict of one modality list. */
125
+ function imageText(value: unknown, t: SyncSectionProps['t']): string {
126
+ if (Array.isArray(value) && value.includes('image')) return t('imageYes')
127
+ if (isBlank(value)) return t('fieldEmpty')
128
+ return t('imageNo')
129
+ }
130
+
131
+ /** The reasoning verdict of one effort value. */
132
+ function reasoningText(value: unknown): string {
133
+ if (value === false) return 'off'
134
+ if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
135
+ const keys = Object.keys(value as Record<string, unknown>)
136
+ return keys.length === 0 ? '—' : keys.join(' / ')
137
+ }
138
+ return '—'
139
+ }
140
+
141
+ /**
142
+ * Which option the image select should show.
143
+ * @param value - the effective modality list, manual or stored.
144
+ * @returns `yes`, `no`, or `default` when it is not set.
145
+ */
146
+ function imageChoice(value: unknown): 'yes' | 'no' | 'default' {
147
+ if (Array.isArray(value) && value.includes('image')) return 'yes'
148
+ if (isBlank(value)) return 'default'
149
+ return 'no'
150
+ }
151
+
152
+ /** The image verdict the owning adapter reports right now. */
153
+ function liveLabel(row: LiveRow | undefined, t: SyncSectionProps['t']): string {
154
+ if (row === undefined) return '—'
155
+ if (row.error !== undefined) return t('liveError')
156
+ if (row.input === undefined) return '—'
157
+ return row.input.includes('image') ? t('imageYes') : t('imageNo')
158
+ }
159
+
160
+ /**
161
+ * One value cell: the stored value alone, or `before → after` when it moves.
162
+ * @param change - the change for this field, when there is one.
163
+ * @param current - the stored value.
164
+ * @param format - renders one value as section copy.
165
+ * @returns the cell body.
166
+ */
167
+ function valueCell(change: FieldChange | undefined, current: unknown, format: (value: unknown) => string): ReactNode {
168
+ if (change === undefined) return <span className="cs-dim">{format(current)}</span>
169
+ return (
170
+ <span className="cs-change">
171
+ <span className="cs-from">{format(change.before)}</span>
172
+ {' → '}{format(change.after)}
173
+ </span>
174
+ )
175
+ }
176
+
177
+ /**
178
+ * An editable capability cell: the stored value, with a box to override it.
179
+ *
180
+ * The catalog is a suggestion. A proxy route may need a smaller window than the
181
+ * upstream model advertises, and a model the catalog never listed has no
182
+ * values at all — so every number here is also typeable, and a typed value
183
+ * shows next to the catalog one instead of replacing what the catalog said.
184
+ * @param props - the field, its values and the change for this row.
185
+ * @returns the cell body.
186
+ */
187
+ function EditableNumber(props: {
188
+ field: 'contextWindow' | 'maxTokens'
189
+ model: ModelDraft
190
+ manual?: CapabilityFields
191
+ change?: FieldChange
192
+ label: string
193
+ onType: (value: number | undefined) => void
194
+ }): ReactNode {
195
+ const { field, model, manual, change, label, onType } = props
196
+ const typed = manual?.[field]
197
+ const shown = typed !== undefined ? String(typed) : change === undefined ? '' : String(model[field] ?? '')
198
+ return (
199
+ <span className="cs-cell">
200
+ {change === undefined
201
+ ? null
202
+ : (
203
+ <span className="cs-change">
204
+ <span className="cs-from">{tokens(change.before)}</span>
205
+ {' → '}{tokens(change.after)}
206
+ </span>
207
+ )}
208
+ <input
209
+ className={typed !== undefined ? 'cs-input cs-input--cell cs-input--typed' : 'cs-input cs-input--cell'}
210
+ aria-label={label}
211
+ inputMode="numeric"
212
+ value={typed !== undefined ? String(typed) : change === undefined ? (isBlank(model[field]) ? '' : tokens(model[field])) : ''}
213
+ placeholder={change === undefined ? tokens(model[field]) : tokens(change.after)}
214
+ onChange={(event) => { onType(parseTokenCount(event.target.value)) }}
215
+ />
216
+ </span>
217
+ )
218
+ }
219
+
220
+ /**
221
+ * Render the section.
222
+ * @param props - injected wire face plus the bound translate function.
223
+ * @returns the section body.
224
+ */
225
+ export function SyncSection(props: SyncSectionProps): ReactNode {
226
+ const { t, preview, live, describeSettings, mutateSettings } = props
227
+ const [status, setStatus] = useState<'loading' | 'ready' | 'error'>('loading')
228
+ const [errorText, setErrorText] = useState<string | undefined>(undefined)
229
+ const [descriptors, setDescriptors] = useState<SettingsDescriptor[]>([])
230
+ const [targetNs, setTargetNs] = useState(TARGET_DEFAULT)
231
+ const [providerKey, setProviderKey] = useState('')
232
+ const [models, setModels] = useState<ModelDraft[]>([])
233
+ /**
234
+ * The same list as `models`, readable synchronously.
235
+ *
236
+ * Two writes in a row (rename, then reorder) run before React has committed
237
+ * the first `setModels`, so the second handler would sort the pre-rename list
238
+ * and write the old names back. Reading the ref instead of the state closes
239
+ * that gap.
240
+ */
241
+ const modelsRef = useRef<ModelDraft[]>([])
242
+ const [rows, setRows] = useState<PreviewRow[] | undefined>(undefined)
243
+ /**
244
+ * Values typed into the table, keyed by model id then field.
245
+ *
246
+ * Held apart from `models` so an edit survives re-analysis: the catalog is a
247
+ * source of suggestions, and re-querying it must not discard what a person
248
+ * decided the entry should say.
249
+ */
250
+ const [typed, setTyped] = useState<ReadonlyMap<string, CapabilityFields>>(new Map())
251
+ const [liveRows, setLiveRows] = useState<ReadonlyMap<string, LiveRow>>(new Map())
252
+ const [selected, setSelected] = useState<ReadonlySet<string>>(new Set())
253
+ const [overwrite, setOverwrite] = useState(false)
254
+ const [query, setQuery] = useState('')
255
+ const [onlyChanged, setOnlyChanged] = useState(false)
256
+ const [sortMode, setSortMode] = useState<SortMode>('prefix')
257
+ const [renaming, setRenaming] = useState(false)
258
+ const [reordering, setReordering] = useState(false)
259
+ const [busy, setBusy] = useState<'idle' | 'analyzing' | 'applying'>('idle')
260
+ const [notice, setNotice] = useState<string | undefined>(undefined)
261
+ const [catalogInfo, setCatalogInfo] = useState<string | undefined>(undefined)
262
+ const [staleInfo, setStaleInfo] = useState<string | undefined>(undefined)
263
+
264
+ /** Everything a write would touch, joined with the stored entries. */
265
+ const plan: PlanRow[] = (() => {
266
+ if (rows === undefined) return []
267
+ const stored = new Map(models.map(model => [textOf(model, 'id'), model]))
268
+ return rows.map((row) => {
269
+ const model = stored.get(row.id) ?? {}
270
+ const manual = typed.get(row.id)
271
+ const fields = mergeFields(row.fields, manual)
272
+ return {
273
+ row,
274
+ model,
275
+ ...fields === undefined ? {} : { fields },
276
+ ...manual === undefined ? {} : { manual },
277
+ changes: fields === undefined ? [] : changesBetween(model, fields, overwrite, manual),
278
+ }
279
+ })
280
+ })()
281
+ // A row with no catalog entry is still workable: the whole entry can be
282
+ // typed by hand, which is the point of the editable cells.
283
+ const matched = plan.filter(entry => entry.fields !== undefined)
284
+ const unmatched = plan.filter(entry => entry.fields === undefined)
285
+ const changing = matched.filter(entry => entry.changes.length > 0)
286
+ const changeFields = changing.reduce((total, entry) => total + entry.changes.length, 0)
287
+ const liveImage = matched.filter(entry => liveRows.get(entry.row.id)?.input?.includes('image') === true).length
288
+ const liveText = matched.filter((entry) => {
289
+ const answer = liveRows.get(entry.row.id)
290
+ return answer?.input !== undefined && !answer.input.includes('image')
291
+ }).length
292
+
293
+ /** Read every configurable entry and select the default target. */
294
+ const load = async (mode: SortMode = sortMode): Promise<void> => {
295
+ setStatus('loading')
296
+ setErrorText(undefined)
297
+ try {
298
+ const list = await describeSettings()
299
+ setDescriptors(list)
300
+ const candidates = list.filter(entry => Object.keys(providersOf(entry)).length > 0)
301
+ const target = candidates.find(entry => entry.ns === TARGET_DEFAULT) ?? candidates[0]
302
+ if (target === undefined) {
303
+ setStatus('error')
304
+ setErrorText(t('noTarget'))
305
+ return
306
+ }
307
+ const providers = providersOf(target)
308
+ const firstKey = Object.keys(providers)[0] ?? ''
309
+ setTargetNs(target.ns)
310
+ setProviderKey(firstKey)
311
+ putModels(sortedModelsOf(providers[firstKey], mode))
312
+ setRows(undefined)
313
+ setLiveRows(new Map())
314
+ setSelected(new Set())
315
+ setQuery('')
316
+ setStatus('ready')
317
+ } catch (error) {
318
+ setStatus('error')
319
+ setErrorText(error instanceof Error ? error.message : String(error))
320
+ }
321
+ }
322
+
323
+ useEffect(() => { void load() }, [])
324
+
325
+ /** Show one provider's models, in display order, with a clean slate. */
326
+ const showProvider = (ns: string, key: string, mode: SortMode = sortMode): void => {
327
+ const providers = providersOf(descriptors.find(entry => entry.ns === ns))
328
+ const resolved = key !== '' && providers[key] !== undefined ? key : Object.keys(providers)[0] ?? ''
329
+ setTargetNs(ns)
330
+ setProviderKey(resolved)
331
+ putModels(sortedModelsOf(providers[resolved], mode))
332
+ setRows(undefined)
333
+ setLiveRows(new Map())
334
+ setSelected(new Set())
335
+ setNotice(undefined)
336
+ setQuery('')
337
+ }
338
+
339
+ /** Ask the owning adapter what a request sees for these ids. */
340
+ const refreshLive = async (provider: string, ids: string[]): Promise<void> => {
341
+ try {
342
+ const answer = await live({ provider, ids })
343
+ setLiveRows(answer.ok ? new Map(answer.value.rows.map(row => [row.id, row])) : new Map())
344
+ } catch {
345
+ setLiveRows(new Map())
346
+ }
347
+ }
348
+
349
+ /** Re-read the configuration without losing the analysis on screen. */
350
+ const reloadConfig = async (): Promise<void> => {
351
+ const list = await describeSettings()
352
+ setDescriptors(list)
353
+ const descriptor = list.find(entry => entry.ns === targetNs)
354
+ if (descriptor !== undefined) putModels(sortedModelsOf(providersOf(descriptor)[providerKey], sortMode))
355
+ }
356
+
357
+ /** Preselect every row that would actually change. */
358
+ const selectChanging = (source: readonly PreviewRow[], stored: readonly ModelDraft[], mode: boolean): void => {
359
+ const byId = new Map(stored.map(model => [textOf(model, 'id'), model]))
360
+ setSelected(new Set(source
361
+ .filter(row => row.fields !== undefined && changesBetween(byId.get(row.id) ?? {}, row.fields, mode).length > 0)
362
+ .map(row => row.id)))
363
+ }
364
+
365
+ /** Resolve every configured id against the catalog. */
366
+ const analyze = async (refresh: boolean): Promise<void> => {
367
+ setBusy('analyzing')
368
+ setErrorText(undefined)
369
+ setNotice(undefined)
370
+ setStaleInfo(undefined)
371
+ try {
372
+ const ids = models.map(model => textOf(model, 'id')).filter(id => id.length > 0)
373
+ // Names travel with the ids: a gateway may hide the model behind an
374
+ // opaque id (`qoder/qfmodel` for Qwen3.8-Flash), and the label is the
375
+ // only place the real model shows up. Sending them makes the id-only
376
+ // rows resolvable, and since the host strips source annotations, a
377
+ // renamed label resolves exactly like the original.
378
+ const names: Record<string, string> = {}
379
+ for (const model of models) {
380
+ const id = textOf(model, 'id')
381
+ const name = textOf(model, 'name')
382
+ if (id !== '' && name !== '' && name !== id) names[id] = name
383
+ }
384
+ const result = await preview({
385
+ ids,
386
+ ...Object.keys(names).length > 0 ? { names } : {},
387
+ ...refresh ? { refresh: true } : {},
388
+ })
389
+ if (!result.ok) throw new Error(result.error.message)
390
+ setRows(result.value.rows)
391
+ selectChanging(result.value.rows, models, overwrite)
392
+ setCatalogInfo(t('catalogInfo', {
393
+ models: result.value.catalogModels,
394
+ time: new Date(result.value.fetchedAt).toLocaleString(),
395
+ }))
396
+ setStaleInfo(result.value.stale === true
397
+ ? t('catalogStale', { time: new Date(result.value.fetchedAt).toLocaleString() })
398
+ : undefined)
399
+ // The entry we are about to write may not be the route a request takes,
400
+ // so this is the only honest answer to "did the write take effect".
401
+ await refreshLive(providerKey, ids)
402
+ } catch (error) {
403
+ setErrorText(error instanceof Error ? error.message : String(error))
404
+ } finally {
405
+ setBusy('idle')
406
+ }
407
+ }
408
+
409
+ /**
410
+ * Switch the ordering and re-sort the list on screen.
411
+ *
412
+ * The analysis is kept: the mode only changes the order of the same entries,
413
+ * so re-querying the catalog would only cost time. Rows are re-read from the
414
+ * stored order, not from the sorted array, so switching back is exact.
415
+ */
416
+ const setSortModeAndApply = (mode: SortMode): void => {
417
+ setSortMode(mode)
418
+ const descriptor = descriptors.find(entry => entry.ns === targetNs)
419
+ if (descriptor !== undefined) putModels(sortedModelsOf(providersOf(descriptor)[providerKey], mode))
420
+ }
421
+
422
+ /** Switch the overwrite mode and follow it with the selection. */
423
+ const setOverwriteMode = (mode: boolean): void => {
424
+ setOverwrite(mode)
425
+ if (rows === undefined) return
426
+ selectChanging(rows, models, mode)
427
+ }
428
+
429
+ /**
430
+ * Replace the model list, keeping the synchronous mirror in step.
431
+ *
432
+ * All writers and loaders go through this so `modelsRef.current` is always
433
+ * the list the latest render would show.
434
+ * @param next - the list to show.
435
+ */
436
+ const putModels = (next: ModelDraft[]): void => {
437
+ modelsRef.current = next
438
+ setModels(next)
439
+ }
440
+
441
+ /**
442
+ * Record a successful write: the new list and its revision replace what the
443
+ * held descriptor says, and the on-screen list follows.
444
+ *
445
+ * Without this the descriptor kept the pre-write models while `models` held
446
+ * the new ones, so anything that rebuilt the list from the descriptor — a
447
+ * sort-mode switch, a provider switch, a conflict reload — put the old names
448
+ * back. That is the "rename then reorder loses the names" report.
449
+ * @param ordered - the list that was just written.
450
+ * @param view - the namespace view the settings service answered with.
451
+ */
452
+ const commitWrite = (ordered: ModelDraft[], view: SettingsDescriptor): void => {
453
+ putModels(ordered)
454
+ setDescriptors(previous => previous.map(entry =>
455
+ entry.ns === targetNs
456
+ ? withWrittenModels(entry, providerKey, ordered, view.revision)
457
+ : entry))
458
+ }
459
+
460
+ /** Rename all models that would change: one-shot action. */
461
+ const doRename = async (): Promise<void> => {
462
+ const descriptor = descriptors.find(entry => entry.ns === targetNs)
463
+ if (descriptor === undefined) return
464
+ // Read the live list: a write may have landed since the last render.
465
+ const live = modelsRef.current
466
+ // Auto-redirect now applies to ALL models, not just those with changes
467
+ const targets = new Set(live.map(model => textOf(model, 'id')))
468
+ if (targets.size === 0) {
469
+ setNotice(t('redirectNoChanges'))
470
+ return
471
+ }
472
+ const renamed = renameModels(live, targets)
473
+ setRenaming(true)
474
+ setErrorText(undefined)
475
+ setNotice(undefined)
476
+ try {
477
+ const ordered = sortByModelId(renamed.next, model => textOf(model, 'id'), model => textOf(model, 'name'), sortMode)
478
+ const view = await mutateSettings(targetNs, [{
479
+ op: 'set',
480
+ path: ['providers', providerKey, 'models'],
481
+ value: ordered,
482
+ }], descriptor.revision)
483
+ commitWrite(ordered, view)
484
+ setNotice(`${t('redirectApplied', { count: renamed.written })}`)
485
+ } catch (error) {
486
+ setErrorText(error instanceof Error ? error.message : String(error))
487
+ } finally {
488
+ setRenaming(false)
489
+ }
490
+ }
491
+
492
+ /** Reorder models to match the chosen sort mode. */
493
+ const doReorder = async (): Promise<void> => {
494
+ const descriptor = descriptors.find(entry => entry.ns === targetNs)
495
+ if (descriptor === undefined) return
496
+ setReordering(true)
497
+ setErrorText(undefined)
498
+ setNotice(undefined)
499
+ try {
500
+ const ordered = sortByModelId(modelsRef.current, model => textOf(model, 'id'), model => textOf(model, 'name'), sortMode)
501
+ const view = await mutateSettings(targetNs, [{
502
+ op: 'set',
503
+ path: ['providers', providerKey, 'models'],
504
+ value: ordered,
505
+ }], descriptor.revision)
506
+ commitWrite(ordered, view)
507
+ setNotice(t('reordered'))
508
+ } catch (error) {
509
+ setErrorText(error instanceof Error ? error.message : String(error))
510
+ } finally {
511
+ setReordering(false)
512
+ }
513
+ }
514
+
515
+ /**
516
+ * Record one typed value for a model, or clear it when the box is emptied.
517
+ * @param id - the gateway model id.
518
+ * @param key - which capability field.
519
+ * @param value - the parsed value, or undefined to drop the manual entry.
520
+ */
521
+ const typeField = (id: string, key: keyof CapabilityFields, value: unknown): void => {
522
+ setTyped((previous) => {
523
+ const next = new Map(previous)
524
+ const current: CapabilityFields = next.get(id) ?? {}
525
+ const updated = { ...current } as Record<string, unknown>
526
+ if (value === undefined) delete updated[key]
527
+ else updated[key] = value
528
+ if (Object.keys(updated).length === 0) next.delete(id)
529
+ else next.set(id, updated as CapabilityFields)
530
+ return next
531
+ })
532
+ }
533
+
534
+ /** Write the selected rows into the provider entry. */
535
+ const applyRows = async (): Promise<void> => {
536
+ const descriptor = descriptors.find(entry => entry.ns === targetNs)
537
+ if (descriptor === undefined) return
538
+ const targets = new Map(changing
539
+ .filter(entry => selected.has(entry.row.id) && entry.fields !== undefined)
540
+ .map(entry => [entry.row.id, entry]))
541
+ if (targets.size === 0) {
542
+ setNotice(t('nothingSelected'))
543
+ return
544
+ }
545
+ let written = 0
546
+ const next = modelsRef.current.map((model) => {
547
+ const entry = targets.get(textOf(model, 'id'))
548
+ if (entry?.fields === undefined) return model
549
+ written += 1
550
+ return mergeModel(model, entry.fields, overwrite, entry.manual)
551
+ })
552
+ setBusy('applying')
553
+ setErrorText(undefined)
554
+ setNotice(undefined)
555
+ try {
556
+ // The order is written with the rows: it is a choice the user made
557
+ // about the list, not an artifact of how the page happened to load.
558
+ const ordered = sortByModelId(next, model => textOf(model, 'id'), model => textOf(model, 'name'), sortMode)
559
+ const view = await mutateSettings(targetNs, [{
560
+ op: 'set',
561
+ path: ['providers', providerKey, 'models'],
562
+ value: ordered,
563
+ }], descriptor.revision)
564
+ commitWrite(ordered, view)
565
+ setNotice(t('applied', { count: written }))
566
+ await refreshLive(providerKey, next.map(model => textOf(model, 'id')).filter(id => id.length > 0))
567
+ } catch (error) {
568
+ const code = (error as { code?: string } | undefined)?.code
569
+ if (code === 'settings/conflict') {
570
+ // Someone else wrote this entry while the page was open. Reload the
571
+ // baseline instead of retrying blindly: a silent retry would overwrite
572
+ // whatever they just saved.
573
+ try {
574
+ await reloadConfig()
575
+ } catch {
576
+ // Keep the conflict message; the reload is only a convenience.
577
+ }
578
+ setNotice(t('conflictReload'))
579
+ } else {
580
+ setErrorText(error instanceof Error ? error.message : String(error))
581
+ }
582
+ } finally {
583
+ setBusy('idle')
584
+ }
585
+ }
586
+
587
+ if (status === 'loading') return <div className="cs-hint">{t('loading')}</div>
588
+
589
+ if (status === 'error') {
590
+ return (
591
+ <div className="cs-field">
592
+ <p className="cs-error">{t('loadFailed')}: {errorText}</p>
593
+ <button type="button" className="cs-button" onClick={() => { void load() }}>{t('retry')}</button>
594
+ </div>
595
+ )
596
+ }
597
+
598
+ const descriptor = descriptors.find(entry => entry.ns === targetNs)
599
+ const candidates = descriptors.filter(entry => Object.keys(providersOf(entry)).length > 0)
600
+ const providerKeys = Object.keys(providersOf(descriptor))
601
+ const needle = query.trim().toLowerCase()
602
+ const visible = plan.filter((entry) => {
603
+ if (onlyChanged && entry.changes.length === 0) return false
604
+ if (needle === '') return true
605
+ return entry.row.id.toLowerCase().includes(needle)
606
+ || entry.row.match?.modelId.toLowerCase().includes(needle) === true
607
+ })
608
+ const selectable = visible.filter(entry => entry.changes.length > 0)
609
+ const toggle = (id: string): void => {
610
+ const next = new Set(selected)
611
+ if (next.has(id)) next.delete(id)
612
+ else next.add(id)
613
+ setSelected(next)
614
+ }
615
+
616
+ return (
617
+ <div>
618
+ <p className="cs-hint">{t('intro')}</p>
619
+
620
+ <div className="cs-row">
621
+ {candidates.length > 1
622
+ ? (
623
+ <label className="cs-field">
624
+ <span className="cs-hint">{t('writeTarget')}</span>
625
+ <select className="cs-select" value={targetNs} onChange={(event) => { showProvider(event.target.value, '') }}>
626
+ {candidates.map(entry => (
627
+ <option key={entry.ns} value={entry.ns}>{targetLabelOf(entry.ns, t)}</option>
628
+ ))}
629
+ </select>
630
+ </label>
631
+ )
632
+ : (
633
+ <div className="cs-field" title={targetNs}>
634
+ <span className="cs-hint">{t('writeTarget')}</span>
635
+ <span className="cs-target">{targetLabelOf(targetNs, t)}</span>
636
+ </div>
637
+ )}
638
+ <label className="cs-field">
639
+ <span className="cs-hint">{t('provider')}</span>
640
+ <select className="cs-select" value={providerKey} onChange={(event) => { showProvider(targetNs, event.target.value) }}>
641
+ {providerKeys.map(key => <option key={key} value={key}>{key}</option>)}
642
+ </select>
643
+ </label>
644
+ <span className="cs-hint">{t('modelCount', { count: models.length })}</span>
645
+ <label className="cs-field">
646
+ <span className="cs-hint">{t('sortMode')}</span>
647
+ <select
648
+ className="cs-select"
649
+ value={sortMode}
650
+ onChange={(event) => { setSortModeAndApply(event.target.value as SortMode) }}
651
+ >
652
+ <option value="prefix">{t('sortByPrefix')}</option>
653
+ <option value="redirected">{t('sortByRedirected')}</option>
654
+ </select>
655
+ </label>
656
+ <span className="cs-hint">{t('willSort')}</span>
657
+ </div>
658
+
659
+ {models.length === 0
660
+ ? <p className="cs-hint">{t('noModels')}</p>
661
+ : (
662
+ <div className="cs-row">
663
+ <button type="button" className="cs-button cs-button--primary" disabled={busy !== 'idle'} onClick={() => { void analyze(false) }}>
664
+ {busy === 'analyzing' ? t('analyzing') : t('analyze')}
665
+ </button>
666
+ <button type="button" className="cs-button" disabled={busy !== 'idle'} onClick={() => { void analyze(true) }}>
667
+ {t('refreshCatalog')}
668
+ </button>
669
+ <label className="cs-hint" title={t('overwriteHint')}>
670
+ <input type="checkbox" checked={overwrite} onChange={(event) => { setOverwriteMode(event.target.checked) }} />
671
+ {' '}{t('overwrite')}
672
+ </label>
673
+ <button
674
+ type="button"
675
+ className="cs-button"
676
+ disabled={renaming}
677
+ onClick={() => { void doRename() }}
678
+ >
679
+ {renaming ? t('redirectApplying') : t('redirectApply')}
680
+ </button>
681
+ <button
682
+ type="button"
683
+ className="cs-button"
684
+ disabled={reordering}
685
+ onClick={() => { void doReorder() }}
686
+ >
687
+ {reordering ? t('reordering') : t('reorder')}
688
+ </button>
689
+ </div>
690
+ )}
691
+
692
+ {errorText !== undefined ? <p className="cs-error">{errorText}</p> : null}
693
+ {notice !== undefined ? <p className="cs-hint">{notice}</p> : null}
694
+ {catalogInfo !== undefined ? <p className="cs-hint">{catalogInfo}</p> : null}
695
+ {staleInfo !== undefined ? <p className="cs-warn">{staleInfo}</p> : null}
696
+
697
+ {rows !== undefined && plan.length > 0
698
+ ? (
699
+ <>
700
+ <p className="cs-hint">{t('editHint')}</p>
701
+ <div className="cs-row">
702
+ <input
703
+ className="cs-input"
704
+ type="search"
705
+ value={query}
706
+ placeholder={t('search')}
707
+ onChange={(event) => { setQuery(event.target.value) }}
708
+ />
709
+ <label className="cs-hint">
710
+ <input type="checkbox" checked={onlyChanged} onChange={(event) => { setOnlyChanged(event.target.checked) }} />
711
+ {' '}{t('onlyChanged')}
712
+ </label>
713
+ <span className="cs-hint">
714
+ {changing.length === 0
715
+ ? t('noChanges')
716
+ : t('changeSummary', { rows: changing.length, fields: changeFields })}
717
+ </span>
718
+ </div>
719
+
720
+ {visible.length === 0
721
+ ? <p className="cs-hint">{t('filteredEmpty')}</p>
722
+ : (
723
+ <div className="cs-table-wrap">
724
+ <table className="cs-table">
725
+ <colgroup>
726
+ <col className="cs-col-check" />
727
+ <col className="cs-col-id" />
728
+ <col className="cs-col-name" />
729
+ <col className="cs-col-match" />
730
+ <col className="cs-col-context" />
731
+ <col className="cs-col-output" />
732
+ <col className="cs-col-image" />
733
+ <col className="cs-col-live" />
734
+ <col className="cs-col-reasoning" />
735
+ </colgroup>
736
+ <thead>
737
+ <tr>
738
+ <th>
739
+ <input
740
+ type="checkbox"
741
+ aria-label={t('selectAll')}
742
+ checked={selectable.length > 0 && selectable.every(entry => selected.has(entry.row.id))}
743
+ onChange={(event) => {
744
+ const keep = event.target.checked ? new Set(selectable.map(entry => entry.row.id)) : new Set<string>()
745
+ setSelected(keep)
746
+ }}
747
+ />
748
+ </th>
749
+ <th>{t('colModel')}</th>
750
+ <th>{t('colName')}</th>
751
+ <th>{t('colMatch')}</th>
752
+ <th>{t('colContext')}</th>
753
+ <th>{t('colOutput')}</th>
754
+ <th>{t('colImage')}</th>
755
+ <th title={t('colLiveHint')}>{t('colLive')}</th>
756
+ <th>{t('colReasoning')}</th>
757
+ </tr>
758
+ </thead>
759
+ <tbody>
760
+ {visible.map((entry) => {
761
+ const { row, model, changes } = entry
762
+ const changeOf = (key: keyof CapabilityFields): FieldChange | undefined =>
763
+ changes.find(change => change.key === key)
764
+ return (
765
+ <tr key={row.id} className={changes.length > 0 ? 'cs-row--changed' : undefined}>
766
+ <td>
767
+ <input
768
+ type="checkbox"
769
+ aria-label={row.id}
770
+ checked={selected.has(row.id)}
771
+ disabled={changes.length === 0}
772
+ onChange={() => { toggle(row.id) }}
773
+ />
774
+ </td>
775
+ <td className="cs-id">{row.id}</td>
776
+ <td>
777
+ {redirectName(row.id, textOf(model, 'name')).after}
778
+ </td>
779
+ <td className="cs-dim">
780
+ {row.match === undefined
781
+ ? <span className="cs-badge">{t('notListed')}</span>
782
+ : (
783
+ <>
784
+ {`${row.match.provider}/${row.match.modelId}`}
785
+ {' '}<span className="cs-badge">{viaLabel(row, t)}</span>
786
+ </>
787
+ )}
788
+ </td>
789
+ <td>
790
+ <EditableNumber
791
+ field="contextWindow"
792
+ label={`${row.id} ${t('colContext')}`}
793
+ model={model}
794
+ manual={entry.manual}
795
+ change={changeOf('contextWindow')}
796
+ onType={(value) => { typeField(row.id, 'contextWindow', value) }}
797
+ />
798
+ </td>
799
+ <td>
800
+ <EditableNumber
801
+ field="maxTokens"
802
+ label={`${row.id} ${t('colOutput')}`}
803
+ model={model}
804
+ manual={entry.manual}
805
+ change={changeOf('maxTokens')}
806
+ onType={(value) => { typeField(row.id, 'maxTokens', value) }}
807
+ />
808
+ </td>
809
+ <td>
810
+ <select
811
+ className={entry.manual?.input === undefined ? 'cs-select cs-select--cell' : 'cs-select cs-select--cell cs-select--typed'}
812
+ aria-label={`${row.id} ${t('colImage')}`}
813
+ value={imageChoice(entry.manual?.input ?? model.input)}
814
+ onChange={(event) => {
815
+ const choice = event.target.value
816
+ typeField(row.id, 'input', choice === 'default'
817
+ ? undefined
818
+ : choice === 'yes' ? ['text', 'image'] : ['text'])
819
+ }}
820
+ >
821
+ <option value="default">{imageText(model.input, t)}</option>
822
+ <option value="yes">{t('imageYes')}</option>
823
+ <option value="no">{t('imageNo')}</option>
824
+ </select>
825
+ {changeOf('input') === undefined
826
+ ? null
827
+ : (
828
+ <span className="cs-change cs-change--block">
829
+ <span className="cs-from">{imageText(changeOf('input')?.before, t)}</span>
830
+ {' → '}{imageText(changeOf('input')?.after, t)}
831
+ </span>
832
+ )}
833
+ </td>
834
+ <td>
835
+ <span className={liveRows.get(row.id)?.input?.includes('image') === true ? 'cs-badge cs-badge--image' : 'cs-dim'}>
836
+ {liveLabel(liveRows.get(row.id), t)}
837
+ </span>
838
+ </td>
839
+ <td className="cs-dim">
840
+ {valueCell(changeOf('reasoningEfforts'), model.reasoningEfforts, reasoningText)}
841
+ </td>
842
+ </tr>
843
+ )
844
+ })}
845
+ </tbody>
846
+ </table>
847
+ </div>
848
+ )}
849
+
850
+ {liveRows.size > 0
851
+ ? <p className="cs-hint">{t('liveSummary', { image: liveImage, text: liveText })}</p>
852
+ : null}
853
+ <div className="cs-row">
854
+ <button
855
+ type="button"
856
+ className="cs-button cs-button--primary"
857
+ disabled={busy !== 'idle' || !changing.some(entry => selected.has(entry.row.id))}
858
+ onClick={() => { void applyRows() }}
859
+ >
860
+ {busy === 'applying' ? t('applying') : t('apply')}
861
+ </button>
862
+ </div>
863
+ </>
864
+ )
865
+ : null}
866
+
867
+ {unmatched.length > 0 ? <p className="cs-hint">{t('unmatchedHint', { count: unmatched.length })}</p> : null}
868
+ </div>
869
+ )
870
+ }