dsh-model-capability-sync 0.1.0 → 0.2.1

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.
@@ -5,72 +5,25 @@
5
5
  * Pure props — no context access, no subscriptions. Everything arrives through
6
6
  * the inject face `apply` builds, including the bound translate function.
7
7
  */
8
- import { useEffect, useState } from 'react'
8
+ import { useEffect, useRef, useState } from 'react'
9
9
  import type { ReactNode } from 'react'
10
10
  import type { CapabilityFields, LiveResponse, LiveRow, PreviewResponse, PreviewRow, RpcEnvelope } from '../types.ts'
11
+ import type { SortMode } from '../sort.ts'
11
12
  import { sortByModelId } from '../sort.ts'
12
-
13
- /** One settings descriptor as the remote reports it (only the fields used here). */
14
- export interface SettingsDescriptor {
15
- ns: string
16
- revision: number
17
- value: Record<string, unknown>
18
- }
19
-
20
- /** One ordered form edit understood by `settings.mutate`. */
21
- export interface SettingsPathOp {
22
- op: 'set' | 'unset'
23
- path: string[]
24
- value?: unknown
25
- }
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'
26
16
 
27
17
  /** What `apply` injects into this component. */
28
- export interface SyncSectionInjected {
29
- preview(request: { ids: string[]; aliases?: Record<string, string>; refresh?: boolean }): Promise<RpcEnvelope<PreviewResponse>>
18
+ export interface SyncSectionInjected extends SettingsInjected {
19
+ preview(request: { ids: string[]; aliases?: Record<string, string>; names?: Record<string, string>; refresh?: boolean }): Promise<RpcEnvelope<PreviewResponse>>
30
20
  live(request: { provider: string; ids: string[] }): Promise<RpcEnvelope<LiveResponse>>
31
- describeSettings(): Promise<SettingsDescriptor[]>
32
- mutateSettings(ns: string, ops: SettingsPathOp[], expectedRevision?: number): Promise<SettingsDescriptor>
33
21
  }
34
22
 
35
23
  export interface SyncSectionProps extends SyncSectionInjected {
36
24
  t: (key: string, params?: Record<string, unknown>) => string
37
25
  }
38
26
 
39
- /** A model entry as the provider stores it: structurally open, so unknown fields survive. */
40
- type ModelDraft = Record<string, unknown>
41
-
42
- /** The official adapter this plugin fills capabilities into. */
43
- const TARGET_DEFAULT = 'llm-pi-ai'
44
-
45
- /**
46
- * How a writable settings namespace reads to a person.
47
- *
48
- * A namespace id is an internal identity, so the page names the thing it
49
- * configures instead. Provenance is a table, not a guess: the client cannot
50
- * see which package owns a namespace (`settings.describe` reports only
51
- * `ns/revision/value/base/user`), and inferring "official" from an `llm-`
52
- * prefix would eventually mislabel a third-party plugin. A namespace this
53
- * table does not know is shown as a plugin, with its id.
54
- */
55
- const TARGET_DIRECTORY: Record<string, { native: boolean; nameKey: string }> = {
56
- 'llm-pi-ai': { native: true, nameKey: 'nameLlmPiAi' },
57
- 'llm-deepseek': { native: true, nameKey: 'nameLlmDeepseek' },
58
- 'llm-deepseek-account': { native: true, nameKey: 'nameLlmDeepseekAccount' },
59
- 'llm-newapi': { native: false, nameKey: 'nameLlmNewapi' },
60
- }
61
-
62
- /**
63
- * Render one namespace as provenance plus a name.
64
- * @param ns - the settings namespace id.
65
- * @param t - the bound translate function.
66
- * @returns copy such as `原生配置 · pi-ai`, never a bare namespace id.
67
- */
68
- function targetLabelOf(ns: string, t: SyncSectionProps['t']): string {
69
- const known = TARGET_DIRECTORY[ns]
70
- if (known === undefined) return `${t('sourcePlugin')} · ${ns}`
71
- return `${known.native ? t('sourceNative') : t('sourcePlugin')} · ${t(known.nameKey)}`
72
- }
73
-
74
27
  /** One capability field that applying a row would rewrite. */
75
28
  interface FieldChange {
76
29
  key: keyof CapabilityFields
@@ -82,34 +35,13 @@ interface FieldChange {
82
35
  interface PlanRow {
83
36
  row: PreviewRow
84
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
85
42
  changes: FieldChange[]
86
43
  }
87
44
 
88
- /** Read a string field, or the empty string. */
89
- function textOf(model: ModelDraft, key: string): string {
90
- const value = model[key]
91
- return typeof value === 'string' ? value : ''
92
- }
93
-
94
- /** The provider dict inside one descriptor's live value. */
95
- function providersOf(descriptor: SettingsDescriptor | undefined): Record<string, Record<string, unknown>> {
96
- const providers = descriptor?.value?.providers
97
- return typeof providers === 'object' && providers !== null
98
- ? providers as Record<string, Record<string, unknown>>
99
- : {}
100
- }
101
-
102
- /** The models array of one provider profile. */
103
- function modelsOf(provider: Record<string, unknown> | undefined): ModelDraft[] {
104
- const models = provider?.models
105
- return Array.isArray(models) ? models.filter((entry): entry is ModelDraft => typeof entry === 'object' && entry !== null) : []
106
- }
107
-
108
- /** The models of one provider profile, in display order. */
109
- function sortedModelsOf(provider: Record<string, unknown> | undefined): ModelDraft[] {
110
- return sortByModelId(modelsOf(provider), model => textOf(model, 'id'))
111
- }
112
-
113
45
  /** Human token count: 128000 → `128K`, 1000000 → `1M`. */
114
46
  function tokens(value: unknown): string {
115
47
  if (typeof value !== 'number') return '—'
@@ -126,27 +58,15 @@ function viaLabel(row: PreviewRow, t: SyncSectionProps['t']): string {
126
58
  case 'folded': return t('viaFolded')
127
59
  case 'basename': return t('viaBasename')
128
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')
129
66
  default: return ''
130
67
  }
131
68
  }
132
69
 
133
- /**
134
- * Whether a stored value carries no decision of its own.
135
- *
136
- * The provider schema materializes defaults, so a field the user never set can
137
- * arrive as `[]` or `{}` rather than as `undefined`. Treating those as "already
138
- * set" is what made an empty `input: []` survive every fill — the field looked
139
- * answered while it said nothing. `false` and `0` are decisions, not blanks.
140
- * @param value - the stored value.
141
- * @returns true when filling the field loses no user intent.
142
- */
143
- function isBlank(value: unknown): boolean {
144
- if (value === undefined || value === null || value === '') return true
145
- if (Array.isArray(value)) return value.length === 0
146
- if (typeof value === 'object') return Object.keys(value as Record<string, unknown>).length === 0
147
- return false
148
- }
149
-
150
70
  /**
151
71
  * Merge one row's capability fields into an existing model entry.
152
72
  *
@@ -158,11 +78,20 @@ function isBlank(value: unknown): boolean {
158
78
  * @param overwrite - replace values the user already set.
159
79
  * @returns a new entry; the input is never mutated.
160
80
  */
161
- function mergeModel(model: ModelDraft, fields: CapabilityFields, overwrite: boolean): ModelDraft {
81
+ function mergeModel(
82
+ model: ModelDraft,
83
+ fields: CapabilityFields,
84
+ overwrite: boolean,
85
+ manual?: CapabilityFields,
86
+ ): ModelDraft {
162
87
  const next: ModelDraft = { ...model }
163
88
  for (const [key, value] of Object.entries(fields)) {
164
89
  if (key === 'name' || value === undefined) continue
165
- if (!overwrite && !isBlank(next[key])) 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
166
95
  next[key] = value
167
96
  }
168
97
  return next
@@ -175,8 +104,13 @@ function mergeModel(model: ModelDraft, fields: CapabilityFields, overwrite: bool
175
104
  * @param overwrite - replace values the user already set.
176
105
  * @returns one entry per changed field, in field order; empty when nothing moves.
177
106
  */
178
- function changesBetween(model: ModelDraft, fields: CapabilityFields, overwrite: boolean): FieldChange[] {
179
- const next = mergeModel(model, fields, overwrite)
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)
180
114
  const changes: FieldChange[] = []
181
115
  for (const key of Object.keys(fields) as Array<keyof CapabilityFields>) {
182
116
  const before = model[key]
@@ -204,6 +138,17 @@ function reasoningText(value: unknown): string {
204
138
  return '—'
205
139
  }
206
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
+
207
152
  /** The image verdict the owning adapter reports right now. */
208
153
  function liveLabel(row: LiveRow | undefined, t: SyncSectionProps['t']): string {
209
154
  if (row === undefined) return '—'
@@ -229,6 +174,49 @@ function valueCell(change: FieldChange | undefined, current: unknown, format: (v
229
174
  )
230
175
  }
231
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
+
232
220
  /**
233
221
  * Render the section.
234
222
  * @param props - injected wire face plus the bound translate function.
@@ -242,12 +230,32 @@ export function SyncSection(props: SyncSectionProps): ReactNode {
242
230
  const [targetNs, setTargetNs] = useState(TARGET_DEFAULT)
243
231
  const [providerKey, setProviderKey] = useState('')
244
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[]>([])
245
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())
246
251
  const [liveRows, setLiveRows] = useState<ReadonlyMap<string, LiveRow>>(new Map())
247
252
  const [selected, setSelected] = useState<ReadonlySet<string>>(new Set())
248
253
  const [overwrite, setOverwrite] = useState(false)
249
254
  const [query, setQuery] = useState('')
250
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)
251
259
  const [busy, setBusy] = useState<'idle' | 'analyzing' | 'applying'>('idle')
252
260
  const [notice, setNotice] = useState<string | undefined>(undefined)
253
261
  const [catalogInfo, setCatalogInfo] = useState<string | undefined>(undefined)
@@ -259,16 +267,21 @@ export function SyncSection(props: SyncSectionProps): ReactNode {
259
267
  const stored = new Map(models.map(model => [textOf(model, 'id'), model]))
260
268
  return rows.map((row) => {
261
269
  const model = stored.get(row.id) ?? {}
262
- const fields = row.fields
270
+ const manual = typed.get(row.id)
271
+ const fields = mergeFields(row.fields, manual)
263
272
  return {
264
273
  row,
265
274
  model,
266
- changes: fields === undefined ? [] : changesBetween(model, fields, overwrite),
275
+ ...fields === undefined ? {} : { fields },
276
+ ...manual === undefined ? {} : { manual },
277
+ changes: fields === undefined ? [] : changesBetween(model, fields, overwrite, manual),
267
278
  }
268
279
  })
269
280
  })()
270
- const matched = plan.filter(entry => entry.row.fields !== undefined)
271
- const unmatched = plan.filter(entry => entry.row.fields === undefined)
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)
272
285
  const changing = matched.filter(entry => entry.changes.length > 0)
273
286
  const changeFields = changing.reduce((total, entry) => total + entry.changes.length, 0)
274
287
  const liveImage = matched.filter(entry => liveRows.get(entry.row.id)?.input?.includes('image') === true).length
@@ -278,7 +291,7 @@ export function SyncSection(props: SyncSectionProps): ReactNode {
278
291
  }).length
279
292
 
280
293
  /** Read every configurable entry and select the default target. */
281
- const load = async (): Promise<void> => {
294
+ const load = async (mode: SortMode = sortMode): Promise<void> => {
282
295
  setStatus('loading')
283
296
  setErrorText(undefined)
284
297
  try {
@@ -295,7 +308,7 @@ export function SyncSection(props: SyncSectionProps): ReactNode {
295
308
  const firstKey = Object.keys(providers)[0] ?? ''
296
309
  setTargetNs(target.ns)
297
310
  setProviderKey(firstKey)
298
- setModels(sortedModelsOf(providers[firstKey]))
311
+ putModels(sortedModelsOf(providers[firstKey], mode))
299
312
  setRows(undefined)
300
313
  setLiveRows(new Map())
301
314
  setSelected(new Set())
@@ -310,12 +323,12 @@ export function SyncSection(props: SyncSectionProps): ReactNode {
310
323
  useEffect(() => { void load() }, [])
311
324
 
312
325
  /** Show one provider's models, in display order, with a clean slate. */
313
- const showProvider = (ns: string, key: string): void => {
326
+ const showProvider = (ns: string, key: string, mode: SortMode = sortMode): void => {
314
327
  const providers = providersOf(descriptors.find(entry => entry.ns === ns))
315
328
  const resolved = key !== '' && providers[key] !== undefined ? key : Object.keys(providers)[0] ?? ''
316
329
  setTargetNs(ns)
317
330
  setProviderKey(resolved)
318
- setModels(sortedModelsOf(providers[resolved]))
331
+ putModels(sortedModelsOf(providers[resolved], mode))
319
332
  setRows(undefined)
320
333
  setLiveRows(new Map())
321
334
  setSelected(new Set())
@@ -338,7 +351,7 @@ export function SyncSection(props: SyncSectionProps): ReactNode {
338
351
  const list = await describeSettings()
339
352
  setDescriptors(list)
340
353
  const descriptor = list.find(entry => entry.ns === targetNs)
341
- if (descriptor !== undefined) setModels(sortedModelsOf(providersOf(descriptor)[providerKey]))
354
+ if (descriptor !== undefined) putModels(sortedModelsOf(providersOf(descriptor)[providerKey], sortMode))
342
355
  }
343
356
 
344
357
  /** Preselect every row that would actually change. */
@@ -357,7 +370,22 @@ export function SyncSection(props: SyncSectionProps): ReactNode {
357
370
  setStaleInfo(undefined)
358
371
  try {
359
372
  const ids = models.map(model => textOf(model, 'id')).filter(id => id.length > 0)
360
- const result = await preview({ ids, ...refresh ? { refresh: true } : {} })
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
+ })
361
389
  if (!result.ok) throw new Error(result.error.message)
362
390
  setRows(result.value.rows)
363
391
  selectChanging(result.value.rows, models, overwrite)
@@ -378,6 +406,19 @@ export function SyncSection(props: SyncSectionProps): ReactNode {
378
406
  }
379
407
  }
380
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
+
381
422
  /** Switch the overwrite mode and follow it with the selection. */
382
423
  const setOverwriteMode = (mode: boolean): void => {
383
424
  setOverwrite(mode)
@@ -385,39 +426,142 @@ export function SyncSection(props: SyncSectionProps): ReactNode {
385
426
  selectChanging(rows, models, mode)
386
427
  }
387
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
+
388
534
  /** Write the selected rows into the provider entry. */
389
535
  const applyRows = async (): Promise<void> => {
390
536
  const descriptor = descriptors.find(entry => entry.ns === targetNs)
391
537
  if (descriptor === undefined) return
392
538
  const targets = new Map(changing
393
- .filter(entry => selected.has(entry.row.id))
539
+ .filter(entry => selected.has(entry.row.id) && entry.fields !== undefined)
394
540
  .map(entry => [entry.row.id, entry]))
395
541
  if (targets.size === 0) {
396
542
  setNotice(t('nothingSelected'))
397
543
  return
398
544
  }
399
545
  let written = 0
400
- const next = models.map((model) => {
546
+ const next = modelsRef.current.map((model) => {
401
547
  const entry = targets.get(textOf(model, 'id'))
402
- if (entry?.row.fields === undefined) return model
548
+ if (entry?.fields === undefined) return model
403
549
  written += 1
404
- return mergeModel(model, entry.row.fields, overwrite)
550
+ return mergeModel(model, entry.fields, overwrite, entry.manual)
405
551
  })
406
552
  setBusy('applying')
407
553
  setErrorText(undefined)
408
554
  setNotice(undefined)
409
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)
410
559
  const view = await mutateSettings(targetNs, [{
411
560
  op: 'set',
412
561
  path: ['providers', providerKey, 'models'],
413
- value: next,
562
+ value: ordered,
414
563
  }], descriptor.revision)
415
- setModels(next)
416
- // Keep the held revision current, so a second apply does not conflict.
417
- setDescriptors(previous => previous.map(entry =>
418
- entry.ns === targetNs && typeof view.revision === 'number'
419
- ? { ...entry, revision: view.revision }
420
- : entry))
564
+ commitWrite(ordered, view)
421
565
  setNotice(t('applied', { count: written }))
422
566
  await refreshLive(providerKey, next.map(model => textOf(model, 'id')).filter(id => id.length > 0))
423
567
  } catch (error) {
@@ -455,7 +599,7 @@ export function SyncSection(props: SyncSectionProps): ReactNode {
455
599
  const candidates = descriptors.filter(entry => Object.keys(providersOf(entry)).length > 0)
456
600
  const providerKeys = Object.keys(providersOf(descriptor))
457
601
  const needle = query.trim().toLowerCase()
458
- const visible = matched.filter((entry) => {
602
+ const visible = plan.filter((entry) => {
459
603
  if (onlyChanged && entry.changes.length === 0) return false
460
604
  if (needle === '') return true
461
605
  return entry.row.id.toLowerCase().includes(needle)
@@ -498,6 +642,17 @@ export function SyncSection(props: SyncSectionProps): ReactNode {
498
642
  </select>
499
643
  </label>
500
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>
501
656
  <span className="cs-hint">{t('willSort')}</span>
502
657
  </div>
503
658
 
@@ -515,6 +670,22 @@ export function SyncSection(props: SyncSectionProps): ReactNode {
515
670
  <input type="checkbox" checked={overwrite} onChange={(event) => { setOverwriteMode(event.target.checked) }} />
516
671
  {' '}{t('overwrite')}
517
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>
518
689
  </div>
519
690
  )}
520
691
 
@@ -523,9 +694,10 @@ export function SyncSection(props: SyncSectionProps): ReactNode {
523
694
  {catalogInfo !== undefined ? <p className="cs-hint">{catalogInfo}</p> : null}
524
695
  {staleInfo !== undefined ? <p className="cs-warn">{staleInfo}</p> : null}
525
696
 
526
- {rows !== undefined && matched.length > 0
697
+ {rows !== undefined && plan.length > 0
527
698
  ? (
528
699
  <>
700
+ <p className="cs-hint">{t('editHint')}</p>
529
701
  <div className="cs-row">
530
702
  <input
531
703
  className="cs-input"
@@ -550,6 +722,17 @@ export function SyncSection(props: SyncSectionProps): ReactNode {
550
722
  : (
551
723
  <div className="cs-table-wrap">
552
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>
553
736
  <thead>
554
737
  <tr>
555
738
  <th>
@@ -564,6 +747,7 @@ export function SyncSection(props: SyncSectionProps): ReactNode {
564
747
  />
565
748
  </th>
566
749
  <th>{t('colModel')}</th>
750
+ <th>{t('colName')}</th>
567
751
  <th>{t('colMatch')}</th>
568
752
  <th>{t('colContext')}</th>
569
753
  <th>{t('colOutput')}</th>
@@ -573,7 +757,8 @@ export function SyncSection(props: SyncSectionProps): ReactNode {
573
757
  </tr>
574
758
  </thead>
575
759
  <tbody>
576
- {visible.map(({ row, model, changes }) => {
760
+ {visible.map((entry) => {
761
+ const { row, model, changes } = entry
577
762
  const changeOf = (key: keyof CapabilityFields): FieldChange | undefined =>
578
763
  changes.find(change => change.key === key)
579
764
  return (
@@ -588,14 +773,63 @@ export function SyncSection(props: SyncSectionProps): ReactNode {
588
773
  />
589
774
  </td>
590
775
  <td className="cs-id">{row.id}</td>
776
+ <td>
777
+ {redirectName(row.id, textOf(model, 'name')).after}
778
+ </td>
591
779
  <td className="cs-dim">
592
- {row.match === undefined ? '—' : `${row.match.provider}/${row.match.modelId}`}
593
- {' '}<span className="cs-badge">{viaLabel(row, t)}</span>
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
+ )}
594
788
  </td>
595
- <td>{valueCell(changeOf('contextWindow'), model.contextWindow, tokens)}</td>
596
- <td>{valueCell(changeOf('maxTokens'), model.maxTokens, tokens)}</td>
597
789
  <td>
598
- {valueCell(changeOf('input'), model.input, value => imageText(value, t))}
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
+ )}
599
833
  </td>
600
834
  <td>
601
835
  <span className={liveRows.get(row.id)?.input?.includes('image') === true ? 'cs-badge cs-badge--image' : 'cs-dim'}>
@@ -630,21 +864,7 @@ export function SyncSection(props: SyncSectionProps): ReactNode {
630
864
  )
631
865
  : null}
632
866
 
633
- {unmatched.length > 0
634
- ? (
635
- <div>
636
- <p className="cs-hint">{t('unmatchedHint')}</p>
637
- <ul className="cs-unmatched">
638
- {unmatched.map(entry => (
639
- <li key={entry.row.id}>
640
- {entry.row.id}
641
- {entry.row.reason === undefined ? null : <span className="cs-dim"> — {entry.row.reason}</span>}
642
- </li>
643
- ))}
644
- </ul>
645
- </div>
646
- )
647
- : null}
867
+ {unmatched.length > 0 ? <p className="cs-hint">{t('unmatchedHint', { count: unmatched.length })}</p> : null}
648
868
  </div>
649
869
  )
650
870
  }