Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

refactor(model-config): 按官方 0.1.7 重新 fork,自有能力迁到 dsh-tauri-ui

hairyfd979f1188b84
diff --git a/packages/dsh-tauri-model-config/README.md b/archiving/dsh-tauri-model-config/README.md
similarity index 100%
rename from packages/dsh-tauri-model-config/README.md
rename to archiving/dsh-tauri-model-config/README.md
diff --git a/archiving/dsh-tauri-model-config/cordis.patch.yml b/archiving/dsh-tauri-model-config/cordis.patch.yml
new file mode 100644
index 00000000..f21f25a3
--- /dev/null
+++ b/archiving/dsh-tauri-model-config/cordis.patch.yml
@@ -0,0 +1,9 @@
+# 官方「模型」设置页:本插件是它的完整 fork(新增「支持图片输入」开关、打开配置文件、
+# 从提供方端点补全模型上限)。两者在 `settings.section/models` 上互斥,同开会在
+# 加载期报槽位重复声明,因此必须关掉官方入口。
+- id: ui-settings-models
+ disabled: true
+
+- insert:
+ - id: dsh-tauri-model-config
+ name: dsh-tauri-model-config
diff --git a/archiving/dsh-tauri-model-config/package.json b/archiving/dsh-tauri-model-config/package.json
new file mode 100644
index 00000000..6ff90fb9
--- /dev/null
+++ b/archiving/dsh-tauri-model-config/package.json
@@ -0,0 +1,89 @@
+{
+ "name": "dsh-tauri-model-config",
+ "type": "module",
+ "version": "1.0.0",
+ "author": "Hairyf <[email protected]>",
+ "license": "MIT",
+ "homepage": "https://github.com/dsh-tauri-desk/dsh-tauri-plugins#readme",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/dsh-tauri-desk/dsh-tauri-plugins.git"
+ },
+ "bugs": "https://github.com/dsh-tauri-desk/dsh-tauri-plugins/issues",
+ "keywords": [
+ "dsh",
+ "plugin",
+ "dsh-plugin",
+ "tauri",
+ "deepseek-harness",
+ "models",
+ "model-capabilities",
+ "vision"
+ ],
+ "sideEffects": false,
+ "exports": {
+ ".": "./dist/index.js",
+ "./client": {
+ "types": "./dist/client.d.cts",
+ "default": "./dist/client.cjs"
+ },
+ "./package.json": "./package.json"
+ },
+ "main": "./dist/index.js",
+ "module": "./dist/index.js",
+ "types": "./dist/index.d.ts",
+ "files": [
+ "cordis.patch.yml",
+ "dist"
+ ],
+ "dsh": {
+ "client": {
+ "inject": [
+ "@deepseek-ai/dsh-client-connection",
+ "@deepseek-ai/dsh-client-locale",
+ "@deepseek-ai/dsh-client-store",
+ "@deepseek-ai/dsh-client-ui-primitives",
+ "@deepseek-ai/dsh-client-ui-renderer",
+ "@deepseek-ai/dsh-client-ui-settings",
+ "@deepseek-ai/dsh-client-ui-slots",
+ "dsh-tauri",
+ "dsh-tauri-ui"
+ ],
+ "external": [
+ "dsh-tauri/client",
+ "dsh-tauri-ui/client"
+ ],
+ "platform": "web"
+ },
+ "bundle": {
+ "patch": "./cordis.patch.yml"
+ }
+ },
+ "scripts": {
+ "build": "tsdown",
+ "dev": "tsdown --watch",
+ "prepublishOnly": "nr build",
+ "start": "tsx src/index.ts",
+ "test": "vitest run",
+ "typecheck": "tsc"
+ },
+ "dependencies": {
+ "dsh-tauri": "workspace:*",
+ "dsh-tauri-ui": "workspace:*"
+ },
+ "devDependencies": {
+ "@deepseek-ai/cordis": "catalog:dsh",
+ "@deepseek-ai/dsh-client-connection": "catalog:dsh",
+ "@deepseek-ai/dsh-client-locale": "catalog:dsh",
+ "@deepseek-ai/dsh-client-store": "catalog:dsh",
+ "@deepseek-ai/dsh-client-ui-primitives": "catalog:dsh",
+ "@deepseek-ai/dsh-client-ui-renderer": "catalog:dsh",
+ "@deepseek-ai/dsh-client-ui-settings": "catalog:dsh",
+ "@deepseek-ai/dsh-client-ui-slots": "catalog:dsh",
+ "@types/node": "catalog:types",
+ "dsh-tauri-tsdown": "workspace:*",
+ "react-if-lite": "catalog:runtime",
+ "tsdown": "catalog:cli",
+ "vitest": "catalog:testing"
+ }
+}
diff --git a/packages/dsh-tauri-model-config/src/client/apis/index.ts b/archiving/dsh-tauri-model-config/src/client/apis/index.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/client/apis/index.ts
rename to archiving/dsh-tauri-model-config/src/client/apis/index.ts
diff --git a/packages/dsh-tauri-model-config/src/client/apis/index.type.ts b/archiving/dsh-tauri-model-config/src/client/apis/index.type.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/client/apis/index.type.ts
rename to archiving/dsh-tauri-model-config/src/client/apis/index.type.ts
diff --git a/packages/dsh-tauri-model-config/src/client/components/config-editor.cssr.ts b/archiving/dsh-tauri-model-config/src/client/components/config-editor.cssr.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/client/components/config-editor.cssr.ts
rename to archiving/dsh-tauri-model-config/src/client/components/config-editor.cssr.ts
diff --git a/packages/dsh-tauri-model-config/src/client/components/config-editor.tsx b/archiving/dsh-tauri-model-config/src/client/components/config-editor.tsx
similarity index 100%
rename from packages/dsh-tauri-model-config/src/client/components/config-editor.tsx
rename to archiving/dsh-tauri-model-config/src/client/components/config-editor.tsx
diff --git a/archiving/dsh-tauri-model-config/src/client/constants/index.ts b/archiving/dsh-tauri-model-config/src/client/constants/index.ts
new file mode 100644
index 00000000..2b05d310
--- /dev/null
+++ b/archiving/dsh-tauri-model-config/src/client/constants/index.ts
@@ -0,0 +1,10 @@
+import { PLUGIN_ID } from '../../shared/constants'
+
+export const LOCALE_EFFECT = `${PLUGIN_ID}: locale dictionaries`
+
+export const STYLES_EFFECT = `${PLUGIN_ID}: page styles`
+
+export const MODELS_PAGE_EFFECT = `${PLUGIN_ID}: models page`
+
+/** 面板样式标签 id,避免热更新重复挂载同一条样式。 */
+export const STYLES_ID = `${PLUGIN_ID}-models-styles`
diff --git a/archiving/dsh-tauri-model-config/src/client/index.ts b/archiving/dsh-tauri-model-config/src/client/index.ts
new file mode 100644
index 00000000..b55aed34
--- /dev/null
+++ b/archiving/dsh-tauri-model-config/src/client/index.ts
@@ -0,0 +1,37 @@
+import type { ClientContext } from 'dsh-tauri/client'
+import { PLUGIN_ID } from '../shared/constants'
+import { LOCALE_EFFECT, MODELS_PAGE_EFFECT, STYLES_EFFECT } from './constants'
+import { locale } from './locales'
+import { registerModelsPage } from './register/models'
+import { registerStyles } from './register/styles'
+
+export const name = PLUGIN_ID
+
+export const inject = [
+ 'slots',
+ 'locale',
+ 'remote',
+ 'remote.credentials',
+ 'remote.llm',
+ 'remote.settings',
+ 'settingsSchema',
+]
+
+/**
+ * 设置命名空间服务跨内核代更名:≤0.1.6 是 `settingsScope`,≥0.1.7 是 `configForms`。
+ * 两者都不能写进 `inject`——缺席的服务会让 fiber 永久 pending,直接导致另一代内核
+ * 加载失败。因此各自独立等待,任意一代就绪即启动,且只启动一次。
+ */
+export function apply(ctx: ClientContext): void {
+ ctx.effect(locale.registerLocale, LOCALE_EFFECT)
+ ctx.effect(registerStyles, STYLES_EFFECT)
+ let started = false
+ const start = (): void => {
+ if (started)
+ return
+ started = true
+ ctx.effect(registerModelsPage, MODELS_PAGE_EFFECT)
+ }
+ ctx.inject(['configForms'], start)
+ ctx.inject(['settingsScope'], start)
+}
diff --git a/archiving/dsh-tauri-model-config/src/client/locales/index.ts b/archiving/dsh-tauri-model-config/src/client/locales/index.ts
new file mode 100644
index 00000000..72df8342
--- /dev/null
+++ b/archiving/dsh-tauri-model-config/src/client/locales/index.ts
@@ -0,0 +1,6 @@
+import { defineLocale } from 'dsh-tauri/client'
+import { PLUGIN_ID } from '../../shared/constants'
+import { en, zh } from '../models/locales'
+
+/** 模型配置页的文案命名空间(沿用官方 `settings.models` 的键集)。 */
+export const locale = defineLocale(PLUGIN_ID, { zh, en })
diff --git a/archiving/dsh-tauri-model-config/src/client/models/CustomProviderCard.tsx b/archiving/dsh-tauri-model-config/src/client/models/CustomProviderCard.tsx
new file mode 100644
index 00000000..cb0af9f9
--- /dev/null
+++ b/archiving/dsh-tauri-model-config/src/client/models/CustomProviderCard.tsx
@@ -0,0 +1,284 @@
+import type { ReactNode } from 'react'
+import type { JsonValue } from '../types/remotes.ts'
+import type { en } from './locales.ts'
+import type { ModelDraft } from './ModelListEditor.tsx'
+import type { ModelsOperations } from './operations.ts'
+import { useState } from 'react'
+import { loadModelCapacities } from '../service/model-config.ts'
+import { mergeModelCards, modelConfigNotice, withDetail } from '../service/model-config.utils.ts'
+import { ensurePresets } from '../service/presets.ts'
+import { apiKeyFailure } from './apiKey.ts'
+import { validateDeepSeekModels } from './DeepSeekModelsEditor.tsx'
+import { EditorFooter } from './EditorFooter.tsx'
+import { ModelListEditor } from './ModelListEditor.tsx'
+import { deriveKeyRef } from './store.ts'
+import { modelStyles as styles } from './styles.ts'
+
+const NS = 'llm-pi-ai'
+
+const ROUTE_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/
+
+function isHttpUrl(value: string): boolean {
+ try {
+ const protocol = new URL(value).protocol
+ return protocol === 'http:' || protocol === 'https:'
+ }
+ catch {
+ return false
+ }
+}
+
+export interface CustomProviderCardProps {
+
+ taken: readonly string[]
+
+ protocols: readonly string[]
+
+ revision: number
+
+ operations: ModelsOperations
+
+ t: (key: keyof typeof en) => string
+
+ readOnly: boolean
+
+ onClose: (changed: boolean) => void
+}
+
+export function CustomProviderCard(props: CustomProviderCardProps): ReactNode {
+ const { taken, protocols, operations, t } = props
+
+ const [openedAt] = useState(() => props.revision)
+ const [route, setRoute] = useState('')
+ const [displayName, setDisplayName] = useState('')
+ const [baseURL, setBaseURL] = useState('')
+ const [protocol, setProtocol] = useState(protocols[0] ?? '')
+ const [keyDraft, setKeyDraft] = useState('')
+ const [models, setModels] = useState<readonly ModelDraft[]>([])
+ const [busy, setBusy] = useState(false)
+ const [failure, setFailure] = useState<string | undefined>(undefined)
+ const [configBusy, setConfigBusy] = useState(false)
+ const [configNotice, setConfigNotice] = useState<string | undefined>(undefined)
+ const [configFailure, setConfigFailure] = useState<string | undefined>(undefined)
+
+ const [committed, setCommitted] = useState(false)
+ const disabled = props.readOnly || busy
+
+ const profileDisabled = disabled || committed
+
+ const routeInvalid = route.length > 0 && !ROUTE_PATTERN.test(route)
+ const routeTaken = taken.includes(route)
+ const normalizedBaseURL = baseURL.trim()
+ const baseUrlInvalid = baseURL.length > 0 && !isHttpUrl(normalizedBaseURL)
+
+ const modelFailure = validateDeepSeekModels(models)
+ const keyFailure = apiKeyFailure(keyDraft)
+
+ const keyValue = keyDraft.trim()
+ const ready = route.length > 0 && !routeInvalid && !routeTaken
+ && normalizedBaseURL.length > 0 && !baseUrlInvalid && models.length > 0 && modelFailure === undefined
+ && keyFailure === undefined
+
+ const hint = failure !== undefined || ready
+
+ || keyFailure !== undefined
+
+ || route.length === 0 || routeInvalid || routeTaken || baseUrlInvalid
+ ? undefined
+ : normalizedBaseURL.length === 0
+ ? t('customNeedsBaseUrl')
+ : modelFailure !== undefined
+ ? `${t('model')} ${String(modelFailure.index + 1)}: ${t(modelFailure.key)}`
+ : t('customNeedsModels')
+
+ const createOnce = async (): Promise<string | undefined> => {
+ const keyRef = deriveKeyRef(route)
+ const storesKey = keyValue.length > 0
+ if (!committed) {
+ const profile = {
+ ...displayName.length === 0 ? {} : { displayName },
+
+ ...storesKey ? { apiKeyEnv: keyRef } : {},
+ api: protocol,
+ baseURL: normalizedBaseURL,
+ models: models.map(model => ({ ...model })),
+ }
+
+ const written = await operations.writeSettings(
+ NS,
+ [{ op: 'set', path: ['providers', route], value: profile as JsonValue }],
+ openedAt,
+ )
+ if (written.kind !== 'written') {
+ return written.kind === 'conflict' ? t('conflict') : written.message
+ }
+
+ setCommitted(true)
+ }
+ if (storesKey) {
+ const stored = await operations.storeCredential(keyRef, keyValue)
+
+ if (stored !== undefined)
+ return stored
+ }
+ return undefined
+ }
+
+ const create = async (): Promise<void> => {
+ setBusy(true)
+ setFailure(undefined)
+ try {
+ const outcome = await createOnce()
+ if (outcome !== undefined) {
+ setFailure(outcome)
+ return
+ }
+ props.onClose(true)
+ }
+ finally {
+ setBusy(false)
+ }
+ }
+
+ const fetchConfig = (targets?: readonly string[]): void => {
+ void (async () => {
+ setConfigBusy(true)
+ setConfigFailure(undefined)
+ const [found] = await Promise.all([
+ loadModelCapacities({
+ settingsNs: NS,
+ profilePath: ['providers', route.trim()],
+ baseURL: normalizedBaseURL,
+ api: protocol,
+ ...keyValue.length === 0 ? {} : { apiKey: keyValue },
+ }, operations),
+ ensurePresets(),
+ ])
+ setConfigBusy(false)
+ if (!found.ok) {
+ setConfigNotice(undefined)
+ setConfigFailure(withDetail(t('configUnreachable'), found.error))
+ return
+ }
+ const merged = mergeModelCards(models, found.models, { targets, overwrite: targets === undefined })
+ if (merged.applied > 0)
+ setModels(merged.models)
+ setConfigNotice(modelConfigNotice(merged, {
+ applied: t('configApplied'),
+ none: t('configNoneApplied'),
+ undisclosed: t('configUndisclosed'),
+ }))
+ })()
+ }
+
+ return (
+ <div className={styles.editor}>
+ <div className={styles.editorHeader}>
+ <span className={styles.editorTitle}>{t('customTitle')}</span>
+ </div>
+ <div className={styles.field}>
+ <span className={styles.fieldLabel}>{t('customRoute')}</span>
+ <input
+ className={styles.input}
+ type="text"
+ value={route}
+ placeholder="acme-gateway"
+ aria-label={t('customRoute')}
+ disabled={profileDisabled}
+ onChange={(event) => { setRoute(event.target.value) }}
+ />
+ </div>
+
+ {routeInvalid || routeTaken
+ ? <p className={styles.error}>{t(routeInvalid ? 'customRouteInvalid' : 'customRouteTaken')}</p>
+ : <p className={styles.advancedHint}>{t('customRouteHint')}</p>}
+ <div className={styles.field}>
+ <span className={styles.fieldLabel}>{t('customDisplayName')}</span>
+ <input
+ className={styles.input}
+ type="text"
+ value={displayName}
+ placeholder={route.length === 0 ? t('customDisplayName') : route}
+ aria-label={t('customDisplayName')}
+ disabled={profileDisabled}
+ onChange={(event) => { setDisplayName(event.target.value) }}
+ />
+ </div>
+ <div className={styles.field}>
+ <span className={styles.fieldLabel}>{t('baseUrl')}</span>
+ <input
+ className={styles.input}
+ type="text"
+ value={baseURL}
+ placeholder={t('customBaseUrlPlaceholder')}
+ aria-label={t('baseUrl')}
+ aria-invalid={baseUrlInvalid}
+ disabled={profileDisabled}
+ onChange={(event) => { setBaseURL(event.target.value) }}
+ />
+ </div>
+ {baseUrlInvalid ? <p className={styles.error}>{t('customBaseUrlInvalid')}</p> : null}
+ <div className={styles.field}>
+ <span className={styles.fieldLabel}>{t('customApi')}</span>
+ <select
+ className={`${styles.input} ${styles.selectInput}`}
+ value={protocol}
+ aria-label={t('customApi')}
+ disabled={profileDisabled}
+ onChange={(event) => { setProtocol(event.target.value) }}
+ >
+ {protocols.map(choice => <option key={choice} value={choice}>{choice}</option>)}
+ </select>
+ </div>
+ <div className={styles.field}>
+ <span className={styles.fieldLabel}>{t('keyInput')}</span>
+ <input
+ className={styles.input}
+ type="password"
+ autoComplete="off"
+ value={keyDraft}
+ placeholder={t('keyPlaceholder')}
+ aria-label={t('keyInput')}
+ disabled={disabled}
+ onChange={(event) => { setKeyDraft(event.target.value) }}
+ />
+
+ {keyFailure === undefined
+ ? null
+ : <p className={styles.error}>{t(keyFailure === 'keyBlank' ? 'keyBlankNew' : keyFailure)}</p>}
+ </div>
+ <ModelListEditor
+ models={models}
+ onChange={setModels}
+ probe={{
+ settingsNs: NS,
+ baseURL: normalizedBaseURL,
+ api: protocol,
+ ...keyValue.length === 0 ? {} : { apiKey: keyValue },
+ }}
+ probeBlocked={baseUrlInvalid
+ ? 'customBaseUrlInvalid'
+ : keyFailure === 'keyBlank' ? 'keyBlankNew' : keyFailure}
+ operations={operations}
+ t={t}
+ disabled={profileDisabled}
+ onFetchConfig={fetchConfig}
+ configBusy={configBusy}
+ configNotice={configNotice}
+ configFailure={configFailure}
+ />
+ {failure !== undefined ? <p className={styles.error}>{failure}</p> : null}
+
+ {hint === undefined ? null : <p className={styles.advancedHint}>{hint}</p>}
+ <EditorFooter
+ t={t}
+ busy={busy}
+ submitDisabled={disabled || !ready}
+ submitLabelKey="create"
+ submitBusyLabelKey="creating"
+ onCancel={() => { props.onClose(committed) }}
+ onSubmit={() => { void create() }}
+ />
+ </div>
+ )
+}
diff --git a/archiving/dsh-tauri-model-config/src/client/models/DeepSeekModelsEditor.tsx b/archiving/dsh-tauri-model-config/src/client/models/DeepSeekModelsEditor.tsx
new file mode 100644
index 00000000..5e9106b6
--- /dev/null
+++ b/archiving/dsh-tauri-model-config/src/client/models/DeepSeekModelsEditor.tsx
@@ -0,0 +1,319 @@
+import type { ReactNode } from 'react'
+import type { en } from './locales.ts'
+import { ChevronDown, ChevronRight, Plus, TrashBin } from 'dsh-tauri-ui/client'
+import { useState } from 'react'
+import { modelStyles as styles } from './styles.ts'
+
+export type DeepSeekModelDraft = Record<string, unknown>
+
+type CatalogField = 'id' | 'name' | 'contextWindow' | 'maxTokens'
+
+type CapacityField = 'contextWindow' | 'maxTokens'
+
+function rowOf(key: string): number {
+ return Number(key.slice(0, key.indexOf(':')))
+}
+
+const CAPACITY_PATTERN = /^(\d+(?:\.\d+)?)([km])?$/i
+
+const CAPACITY_SCALE = { k: 1_000, m: 1_000_000 } as const
+
+export function parseCapacity(text: string): number | undefined {
+ const trimmed = text.trim()
+ if (trimmed.length === 0)
+ return undefined
+ const match = CAPACITY_PATTERN.exec(trimmed)
+ if (match === null)
+ return Number.NaN
+ const suffix = match[2]?.toLowerCase()
+ const scale = suffix === 'k' || suffix === 'm' ? CAPACITY_SCALE[suffix] : 1
+ const scaled = Number(match[1]) * scale
+
+ const rounded = Math.round(scaled)
+ return Math.abs(scaled - rounded) < 1e-6 ? rounded : scaled
+}
+
+export function formatCapacity(value: number): string {
+ if (!Number.isInteger(value) || value <= 0)
+ return String(value)
+ if (value % CAPACITY_SCALE.m === 0)
+ return `${String(value / CAPACITY_SCALE.m)}M`
+ if (value % CAPACITY_SCALE.k === 0)
+ return `${String(value / CAPACITY_SCALE.k)}K`
+ return String(value)
+}
+
+export interface DeepSeekModelsValidationFailure {
+
+ index: number
+
+ key: 'modelIdRequired' | 'modelIdDuplicate' | 'modelNameInvalid' | 'modelContextInvalid'
+ | 'modelMaxTokensInvalid'
+}
+
+export function modelDrafts(value: unknown): DeepSeekModelDraft[] {
+ if (!Array.isArray(value))
+ return []
+ return value.map(entry =>
+ typeof entry === 'object' && entry !== null && !Array.isArray(entry)
+ ? entry as DeepSeekModelDraft
+ : {})
+}
+
+export function validateDeepSeekModels(value: unknown): DeepSeekModelsValidationFailure | undefined {
+ if (value === undefined)
+ return undefined
+ const models = modelDrafts(value)
+ const seen = new Set<string>()
+ for (const [index, model] of models.entries()) {
+ const id = model.id
+ const trimmed = typeof id === 'string' ? id.trim() : undefined
+ if (trimmed === undefined || trimmed.length === 0)
+ return { index, key: 'modelIdRequired' }
+ if (seen.has(trimmed))
+ return { index, key: 'modelIdDuplicate' }
+ seen.add(trimmed)
+ const name = model.name
+ if (name !== undefined && (typeof name !== 'string' || name.length === 0)) {
+ return { index, key: 'modelNameInvalid' }
+ }
+ const contextWindow = model.contextWindow
+ if (contextWindow !== undefined
+ && (typeof contextWindow !== 'number' || !Number.isInteger(contextWindow) || contextWindow <= 0)) {
+ return { index, key: 'modelContextInvalid' }
+ }
+ const maxTokens = model.maxTokens
+ if (maxTokens !== undefined
+ && (typeof maxTokens !== 'number' || !Number.isInteger(maxTokens) || maxTokens <= 0)) {
+ return { index, key: 'modelMaxTokensInvalid' }
+ }
+ }
+ return undefined
+}
+
+export interface DeepSeekModelsEditorProps {
+
+ models: readonly DeepSeekModelDraft[]
+
+ overridden: boolean
+
+ defaultContextWindow: number | undefined
+
+ defaultMaxTokens: number | undefined
+
+ t: (key: keyof typeof en) => string
+
+ disabled: boolean
+
+ onChange: (models: DeepSeekModelDraft[]) => void
+
+ onReset: () => void
+}
+
+export function DeepSeekModelsEditor(props: DeepSeekModelsEditorProps): ReactNode {
+ const [editing, setEditing] = useState<ReadonlyMap<string, string>>(() => new Map())
+ const [expanded, setExpanded] = useState<ReadonlySet<number>>(() => new Set())
+
+ const update = (index: number, key: CatalogField, value: unknown): void => {
+ const next = props.models.map((model, at) => {
+ const copy = { ...model }
+ if (at !== index)
+ return copy
+ if (value === undefined)
+ Reflect.deleteProperty(copy, key)
+ else copy[key] = value
+ return copy
+ })
+ props.onChange(next)
+ }
+
+ const remove = (index: number): void => {
+ setEditing((current) => {
+ const next = new Map<string, string>()
+ for (const [key, text] of current) {
+ const at = rowOf(key)
+ if (at === index)
+ continue
+
+ next.set(at > index ? key.replace(/^\d+/, String(at - 1)) : key, text)
+ }
+ return next
+ })
+ setExpanded((current) => {
+ const next = new Set<number>()
+ for (const at of current) {
+ if (at === index)
+ continue
+ next.add(at > index ? at - 1 : at)
+ }
+ return next
+ })
+ props.onChange(props.models.filter((_model, at) => at !== index).map(model => ({ ...model })))
+ }
+
+ const reset = (): void => {
+ setEditing(new Map())
+ setExpanded(new Set())
+ props.onReset()
+ }
+
+ const toggle = (index: number): void => {
+ setExpanded((current) => {
+ const next = new Set(current)
+ if (!next.delete(index))
+ next.add(index)
+ return next
+ })
+ }
+
+ const capacityText = (model: DeepSeekModelDraft, index: number, field: CapacityField): string => {
+ const typed = editing.get(`${String(index)}:${field}`)
+ if (typed !== undefined)
+ return typed
+ const value = model[field]
+ return typeof value === 'number' ? formatCapacity(value) : ''
+ }
+
+ const settleCapacity = (index: number, field: CapacityField): void => {
+ const key = `${String(index)}:${field}`
+ const typed = editing.get(key)
+ if (typed === undefined)
+ return
+
+ const parsed = parseCapacity(typed)
+ if (parsed !== undefined && Number.isNaN(parsed))
+ return
+ setEditing((current) => {
+ const next = new Map(current)
+ next.delete(key)
+ return next
+ })
+ }
+
+ const capacityField = (
+ model: DeepSeekModelDraft,
+ index: number,
+ field: CapacityField,
+ fallback: number | undefined,
+ ): ReactNode => (
+ <label className={styles.modelField}>
+ <span className={styles.modelFieldLabel}>{props.t(field === 'contextWindow' ? 'contextWindow' : 'maxTokens')}</span>
+ <input
+ className={styles.input}
+ type="text"
+ inputMode="numeric"
+ value={capacityText(model, index, field)}
+ placeholder={fallback === undefined
+ ? props.t(field === 'contextWindow' ? 'contextWindowPlaceholder' : 'maxTokensPlaceholder')
+ : formatCapacity(fallback)}
+ aria-label={`${props.t(field === 'contextWindow' ? 'contextWindow' : 'maxTokens')} ${String(index + 1)}`}
+ disabled={props.disabled}
+ onChange={(event) => {
+ const text = event.target.value
+ setEditing(current => new Map(current).set(`${String(index)}:${field}`, text))
+ update(index, field, parseCapacity(text))
+ }}
+ onBlur={() => { settleCapacity(index, field) }}
+ />
+ </label>
+ )
+
+ return (
+ <section className={styles.modelCatalog} aria-label={props.t('models')}>
+ <div className={styles.modelListHead}>
+ <div className={styles.modelCatalogHeading}>
+ <span className={styles.modelCatalogTitle}>{props.t('models')}</span>
+ <span className={styles.modelCatalogMeta}>
+ {props.overridden ? props.t('modelsCustomized') : props.t('modelsInherited')}
+ </span>
+ </div>
+ {props.overridden
+ ? (
+ <button
+ type="button"
+ className={styles.linkButton}
+ disabled={props.disabled}
+ onClick={reset}
+ >
+ {props.t('resetModels')}
+ </button>
+ )
+ : null}
+ </div>
+ {props.models.length === 0
+ ? <p className={styles.modelEmpty}>{props.t('modelsEmpty')}</p>
+ : (
+ <div className={styles.modelList}>
+ {props.models.map((model, index) => (
+ <div className={styles.modelEntry} key={index}>
+ <div className={styles.modelRow}>
+ <input
+ className={styles.input}
+ type="text"
+ value={typeof model.id === 'string' ? model.id : ''}
+ placeholder={props.t('modelId')}
+ aria-label={`${props.t('modelId')} ${String(index + 1)}`}
+ disabled={props.disabled}
+ onChange={(event) => { update(index, 'id', event.target.value) }}
+ onBlur={(event) => {
+ const trimmed = event.target.value.trim()
+ if (trimmed !== event.target.value)
+ update(index, 'id', trimmed)
+ }}
+ />
+ <input
+ className={styles.input}
+ type="text"
+ value={typeof model.name === 'string' ? model.name : ''}
+ placeholder={props.t('modelName')}
+ aria-label={`${props.t('modelName')} ${String(index + 1)}`}
+ disabled={props.disabled}
+ onChange={(event) => {
+ update(index, 'name', event.target.value === '' ? undefined : event.target.value)
+ }}
+ />
+ <button
+ type="button"
+ className={styles.iconButton}
+ aria-label={`${props.t('modelAdvanced')} ${String(index + 1)}`}
+ aria-expanded={expanded.has(index)}
+ title={props.t('modelAdvanced')}
+ onClick={() => { toggle(index) }}
+ >
+ {expanded.has(index) ? <ChevronDown width={14} height={14} /> : <ChevronRight width={14} height={14} />}
+ </button>
+ <button
+ type="button"
+ className={`${styles.iconButton} ${styles.iconButtonDanger}`}
+ aria-label={`${props.t('removeModel')} ${String(index + 1)}`}
+ title={props.t('removeModel')}
+ disabled={props.disabled}
+ onClick={() => { remove(index) }}
+ >
+ <TrashBin width={14} height={14} />
+ </button>
+ </div>
+ {expanded.has(index)
+ ? (
+ <div className={styles.modelAdvanced}>
+ {capacityField(model, index, 'contextWindow', props.defaultContextWindow)}
+ {capacityField(model, index, 'maxTokens', props.defaultMaxTokens)}
+ </div>
+ )
+ : null}
+ </div>
+ ))}
+ </div>
+ )}
+ <button
+ type="button"
+ className={styles.addModelButton}
+ disabled={props.disabled}
+ onClick={() => { props.onChange([...props.models.map(model => ({ ...model })), { id: '' }]) }}
+ >
+ <Plus width={14} height={14} />
+ {props.t('addModel')}
+ </button>
+ </section>
+ )
+}
diff --git a/archiving/dsh-tauri-model-config/src/client/models/DeepSeekOnboardingDialog.tsx b/archiving/dsh-tauri-model-config/src/client/models/DeepSeekOnboardingDialog.tsx
new file mode 100644
index 00000000..15973ce7
--- /dev/null
+++ b/archiving/dsh-tauri-model-config/src/client/models/DeepSeekOnboardingDialog.tsx
@@ -0,0 +1,111 @@
+import type { SnapshotStore } from '@deepseek-ai/dsh-client-store'
+import type { InjectFace, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
+import type { ReactNode } from 'react'
+import type { en } from './locales.ts'
+import type { ModelsOperations } from './operations.ts'
+import type { SettingsSchemaOperations } from './schema-operations.ts'
+import type { ModelsSettingsState, ModelsSettingsStore } from './store.ts'
+import { useEffect } from 'react'
+import { OnboardingModal } from './OnboardingModal.tsx'
+import { ProviderEditor } from './ProviderEditor.tsx'
+import { onboardingReadiness } from './store.ts'
+import { onboardingDialogStyles as styles } from './styles.ts'
+
+export interface DeepSeekOnboardingInjected {
+ hooks: {
+
+ models: SnapshotStore<ModelsSettingsState>
+ }
+
+ controller: ModelsSettingsStore
+
+ operations: ModelsOperations
+
+ schema: SettingsSchemaOperations
+
+ t: (key: keyof typeof en) => string
+}
+
+export type DeepSeekOnboardingDialogProps
+ = PropsRuntime<'settings.onboarding'> & InjectFace<DeepSeekOnboardingInjected>
+
+function assertNever(_value: never): never {
+ throw new Error('unexpected DeepSeek onboarding state')
+}
+
+export function DeepSeekOnboardingDialog(props: DeepSeekOnboardingDialogProps): ReactNode {
+ const { complete, controller, useModels, operations, schema, t } = props
+ const state = useModels(snapshot => snapshot)
+ const readiness = onboardingReadiness(state)
+
+ useEffect(() => {
+ if (state.status === 'idle')
+ void controller.load()
+ }, [controller, state.status])
+
+ useEffect(() => {
+ if (
+ readiness.kind === 'adapter-absent'
+ || readiness.kind === 'provider-ready'
+ || readiness.kind === 'unavailable'
+ ) {
+ complete()
+ }
+ }, [complete, readiness.kind])
+
+ switch (readiness.kind) {
+ case 'loading':
+ case 'adapter-absent':
+ case 'provider-ready':
+ case 'unavailable':
+ return null
+ case 'credential-missing':
+ break
+
+ default:
+ return assertNever(readiness)
+ }
+
+ const row = state.rows.find(candidate =>
+ candidate.entry.provider === 'deepseek-official'
+ && candidate.entry.settingsNs === 'llm-deepseek'
+ && candidate.entry.settingsPath.length === 0)
+ const namespace = state.namespaces.get('llm-deepseek')
+
+ if (row === undefined || namespace === undefined)
+ return null
+
+ const finishCredential = (changed: boolean): void => {
+ if (!changed) {
+ complete()
+ return
+ }
+ void controller.load()
+ }
+
+ return (
+ <OnboardingModal title={t('onboardingTitle')}>
+ <p className={styles.description}>{t('onboardingDescription')}</p>
+ <div className={styles.editor}>
+ <ProviderEditor
+ provider={row.entry.provider}
+ displayName={row.entry.displayName}
+ namespace={namespace}
+ schema={schema}
+ settingsPath={row.entry.settingsPath}
+ operations={operations}
+ t={t}
+ readOnly={false}
+ hideTitle
+ credentialOnly
+ credentialRequired
+ autoFocusCredential
+ cancelLabelKey="onboardingLater"
+ submitLabelKey="onboardingSave"
+ submitBusyLabelKey="onboardingSaving"
+ onClose={finishCredential}
+ />
+ </div>
+ </OnboardingModal>
+ )
+}
diff --git a/archiving/dsh-tauri-model-config/src/client/models/EditorFooter.tsx b/archiving/dsh-tauri-model-config/src/client/models/EditorFooter.tsx
new file mode 100644
index 00000000..ca8ddffd
--- /dev/null
+++ b/archiving/dsh-tauri-model-config/src/client/models/EditorFooter.tsx
@@ -0,0 +1,46 @@
+import type { ReactNode } from 'react'
+import type { en } from './locales.ts'
+import { modelStyles as styles } from './styles.ts'
+
+export interface EditorFooterProps {
+
+ t: (key: keyof typeof en) => string
+
+ busy: boolean
+
+ submitDisabled: boolean
+
+ submitLabelKey: keyof typeof en
+
+ submitBusyLabelKey: keyof typeof en
+
+ cancelLabelKey?: keyof typeof en
+
+ onCancel: () => void
+
+ onSubmit: () => void
+}
+
+export function EditorFooter(props: EditorFooterProps): ReactNode {
+ const { t } = props
+ return (
+ <div className={styles.editorActions}>
+ <button
+ type="button"
+ className={styles.secondaryButton}
+ disabled={props.busy}
+ onClick={props.onCancel}
+ >
+ {t(props.cancelLabelKey ?? 'cancel')}
+ </button>
+ <button
+ type="button"
+ className={styles.primaryButton}
+ disabled={props.submitDisabled}
+ onClick={props.onSubmit}
+ >
+ {props.busy ? t(props.submitBusyLabelKey) : t(props.submitLabelKey)}
+ </button>
+ </div>
+ )
+}
diff --git a/archiving/dsh-tauri-model-config/src/client/models/ModelListEditor.tsx b/archiving/dsh-tauri-model-config/src/client/models/ModelListEditor.tsx
new file mode 100644
index 00000000..c8828262
--- /dev/null
+++ b/archiving/dsh-tauri-model-config/src/client/models/ModelListEditor.tsx
@@ -0,0 +1,596 @@
+import type { CSSProperties, ReactNode } from 'react'
+import type { LlmDiscoveredModel } from '../types/remotes.ts'
+import type { DeepSeekModelDraft } from './DeepSeekModelsEditor.tsx'
+import type { en } from './locales.ts'
+import type { ModelsOperations } from './operations.ts'
+import { Button, Modal, Switch } from '@deepseek-ai/dsh-client-ui-primitives'
+import { useState } from 'react'
+import {
+ declaredThinkingLevels,
+ enableThinking,
+ hasModelConfig,
+ imageInputValue,
+ supportsImageInput,
+ supportsTemplateThinking,
+ supportsThinking,
+ templateThinkingCompat,
+ THINKING_LEVELS,
+ thinkingEffortsOf,
+ toggleThinkingLevel,
+} from '../service/model-config.utils.ts'
+import { formatCapacity, parseCapacity } from './DeepSeekModelsEditor.tsx'
+import { modelStyles as styles } from './styles.ts'
+
+export type ModelDraft = DeepSeekModelDraft
+
+function textOf(model: ModelDraft, key: string): string {
+ const value = model[key]
+ return typeof value === 'string' ? value : ''
+}
+
+function numberOf(model: ModelDraft, key: string): number | undefined {
+ const value = model[key]
+ return typeof value === 'number' ? value : undefined
+}
+
+export interface ProbeTarget {
+
+ settingsNs: string
+
+ provider?: string
+
+ baseURL?: string
+
+ api?: string
+
+ apiKey?: string
+}
+
+export interface ModelListEditorProps {
+
+ models: readonly ModelDraft[]
+
+ overridden?: boolean
+
+ onChange: (models: ModelDraft[]) => void
+
+ onReset?: () => void
+
+ probe: ProbeTarget
+
+ probeBlocked?: keyof typeof en | undefined
+
+ operations: ModelsOperations
+
+ t: (key: keyof typeof en) => string
+
+ disabled: boolean
+
+ onFetchConfig: (targets?: readonly string[]) => void
+
+ configBusy: boolean
+
+ configNotice?: string | undefined
+
+ configFailure?: string | undefined
+}
+
+function IconChevron({ open }: { open: boolean }): ReactNode {
+ return (
+ <svg
+ width="14"
+ height="14"
+ viewBox="0 0 16 16"
+ fill="none"
+ aria-hidden
+ style={{ transform: open ? 'rotate(90deg)' : undefined, transition: 'transform 120ms ease' }}
+ >
+ <path d="M6 3.5L10.5 8L6 12.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
+ </svg>
+ )
+}
+
+function IconTrash(): ReactNode {
+ return (
+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden>
+ <path
+ d="M2.5 4h11M6.5 4V2.5h3V4M4 4l.7 9a1 1 0 001 .9h4.6a1 1 0 001-.9L12 4M6.5 6.8v4.4M9.5 6.8v4.4"
+ stroke="currentColor"
+ strokeWidth="1.3"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </svg>
+ )
+}
+
+type CapacityField = 'contextWindow' | 'maxTokens'
+
+/** 一个容量字段正在输入的原文与它当时解析出的数字(解析不出时为 NaN/undefined)。 */
+interface CapacityBuffer {
+ text: string
+ value: number | undefined
+}
+
+const CAPACITY_HINT: Readonly<Record<CapacityField, string>> = {
+ contextWindow: '256K',
+ maxTokens: '32K',
+}
+
+/** 上游给高级区留了 4px 左右内边距,会让首行比上面的模型行窄 8px、左边缘再右移 4px;这里去掉它。 */
+const ADVANCED_AREA_STYLE: CSSProperties = { paddingLeft: 0, paddingRight: 0 }
+
+/**
+ * 高级区首行横跨整个栅格:左半边是两个容量输入(彼此等宽),容量组本身按内容宽度;右半边是三个
+ * 开关,开关组吃掉剩余宽度——开关按内容宽度排布、不做拉伸,容器另加 4px 左外边距。
+ *
+ * `minWidth: 0` 是必须的:文本输入自带约 20 字符的固有宽度,flex 项的自动最小尺寸会让它拒绝收缩。
+ */
+const ADVANCED_ROW_STYLE: CSSProperties = { display: 'flex', gap: '6px', gridColumn: '1 / -1' }
+const ADVANCED_CAPACITIES_STYLE: CSSProperties = { display: 'flex', gap: '6px', minWidth: 0 }
+const ADVANCED_CAPACITY_STYLE: CSSProperties = { flex: 1, minWidth: 0 }
+const ADVANCED_SWITCHES_STYLE: CSSProperties = { display: 'flex', gap: '6px', flex: 1, minWidth: 0, marginLeft: '4px' }
+
+/**
+ * 「关闭 Developer 角色」开关只对 chat completions 协议有意义。
+ *
+ * pi-ai 的 compat 是逐协议校验的:`thinkingFormat` 与 `chatTemplateKwargs` 只有
+ * `openai-completions` 收,写到 Responses 或 Anthropic 路由的模型上会让整段配置解析失败。
+ * 路由没显式声明协议时(目录路由)无法判断,就不提供这个开关。
+ */
+const TEMPLATE_COMPAT_PROTOCOL = 'openai-completions'
+
+function capacitySpelling(value: number | undefined): string {
+ return value === undefined ? '' : formatCapacity(value)
+}
+
+function adopt(candidate: LlmDiscoveredModel): ModelDraft {
+ return {
+ id: candidate.id,
+ ...candidate.name === undefined ? {} : { name: candidate.name },
+ ...candidate.contextWindow === undefined ? {} : { contextWindow: candidate.contextWindow },
+ ...candidate.maxTokens === undefined ? {} : { maxTokens: candidate.maxTokens },
+ }
+}
+
+export function ModelListEditor(props: ModelListEditorProps): ReactNode {
+ const { models, onChange, probe, operations, t, disabled, onFetchConfig, configBusy, configNotice, configFailure } = props
+ const [busy, setBusy] = useState(false)
+ const [failure, setFailure] = useState<string | undefined>(undefined)
+ const [candidates, setCandidates] = useState<readonly LlmDiscoveredModel[] | undefined>(undefined)
+ const [picked, setPicked] = useState<ReadonlySet<string>>(() => new Set())
+ const [candidateQuery, setCandidateQuery] = useState('')
+
+ const [expanded, setExpanded] = useState<ReadonlySet<number>>(() => new Set())
+
+ const [editing, setEditing] = useState<ReadonlyMap<string, CapacityBuffer>>(() => new Map())
+
+ const bufferKey = (index: number, field: CapacityField): string => `${String(index)}:${field}`
+
+ const patch = (index: number, next: Record<string, unknown>): void => {
+ onChange(models.map((model, at) => {
+ if (at !== index)
+ return model
+ const cleared = new Set(
+ Object.entries(next).filter(([, value]) => value === undefined || value === '').map(([key]) => key),
+ )
+ return Object.fromEntries(
+ Object.entries({ ...model, ...next }).filter(([key]) => !cleared.has(key)),
+ )
+ }))
+ }
+
+ const editCapacity = (index: number, field: CapacityField, text: string): void => {
+ const value = parseCapacity(text)
+ setEditing(current => new Map(current).set(bufferKey(index, field), { text, value }))
+ patch(index, { [field]: value })
+ }
+
+ /**
+ * 输入框显示什么:打字期间用缓冲区,存量值被外部改写(端点配置)后立刻改读存量值。
+ *
+ * 只认「解析得出的数字与存量一致」的缓冲区,所以端点写回新容量时不会还被一行旧文本盖着;
+ * 解析不出数字(未写完的输入)时保留原文,好让保存期的报错能指着用户还看得见的那一行。
+ */
+ const capacityText = (model: ModelDraft, index: number, field: CapacityField): string => {
+ const buffer = editing.get(bufferKey(index, field))
+ if (buffer === undefined || buffer.value === undefined || Number.isNaN(buffer.value))
+ return buffer?.text ?? capacitySpelling(numberOf(model, field))
+ return buffer.value === numberOf(model, field) ? buffer.text : capacitySpelling(numberOf(model, field))
+ }
+
+ const reindexOnRemove = (
+ current: ReadonlyMap<string, CapacityBuffer>,
+ index: number,
+ ): Map<string, CapacityBuffer> => {
+ const next = new Map<string, CapacityBuffer>()
+ for (const [key, value] of current) {
+ const at = Number(key.slice(0, key.indexOf(':')))
+ if (at === index)
+ continue
+
+ next.set(at > index ? key.replace(/^\d+/, String(at - 1)) : key, value)
+ }
+ return next
+ }
+
+ const toggleExpanded = (index: number): void => {
+ setExpanded((current) => {
+ const next = new Set(current)
+ if (!next.delete(index))
+ next.add(index)
+ return next
+ })
+ }
+
+ const fetchModels = async (): Promise<void> => {
+ setBusy(true)
+ setFailure(undefined)
+ try {
+ const answer = await operations.discoverModels(probe.settingsNs, {
+ ...probe.provider === undefined ? {} : { provider: probe.provider },
+ ...probe.baseURL === undefined || probe.baseURL.length === 0 ? {} : { baseURL: probe.baseURL },
+ ...probe.api === undefined ? {} : { api: probe.api },
+ ...probe.apiKey === undefined ? {} : { apiKey: probe.apiKey },
+ })
+ if (answer.kind === 'refused') {
+ setFailure(answer.message)
+ return
+ }
+ const found = answer.models
+ if (found.length === 0) {
+ setFailure(t('fetchEmpty'))
+ return
+ }
+
+ const known = new Set(models.map(model => textOf(model, 'id')))
+ setCandidateQuery('')
+ setCandidates(found)
+ setPicked(new Set(found.filter(model => !known.has(model.id)).map(model => model.id)))
+ }
+ finally {
+ setBusy(false)
+ }
+ }
+
+ const closePicker = (): void => {
+ setCandidates(undefined)
+ setPicked(new Set())
+ setCandidateQuery('')
+ }
+
+ const adoptPicked = (): void => {
+ if (candidates === undefined)
+ return
+ const byId = new Map(models.map(model => [textOf(model, 'id'), model]))
+ for (const candidate of candidates) {
+ if (!picked.has(candidate.id))
+ continue
+
+ byId.set(candidate.id, byId.get(candidate.id) ?? adopt(candidate))
+ }
+ onChange([...byId.values()])
+ closePicker()
+ }
+
+ const toggle = (id: string): void => {
+ setPicked((current) => {
+ const next = new Set(current)
+ if (!next.delete(id))
+ next.add(id)
+ return next
+ })
+ }
+
+ const activeCandidates = candidates ?? []
+ const normalizedCandidateQuery = candidateQuery.trim().toLowerCase()
+ const visibleCandidates = normalizedCandidateQuery.length === 0
+ ? activeCandidates
+ : activeCandidates.filter(candidate => candidate.id.toLowerCase().includes(normalizedCandidateQuery)
+ || candidate.name?.toLowerCase().includes(normalizedCandidateQuery) === true)
+ const allVisibleCandidatesPicked = visibleCandidates.length > 0
+ && visibleCandidates.every(candidate => picked.has(candidate.id))
+
+ const toggleVisibleCandidates = (): void => {
+ setPicked((current) => {
+ if (visibleCandidates.every(candidate => current.has(candidate.id))) {
+ return new Set()
+ }
+ const next = new Set(current)
+ for (const candidate of visibleCandidates) next.add(candidate.id)
+ return next
+ })
+ }
+
+ const askable = probe.provider !== undefined || (probe.baseURL !== undefined && probe.baseURL.length > 0)
+ return (
+ <section className={styles.modelCatalog} aria-label={t('models')}>
+ <div className={styles.modelListHead}>
+ <div className={styles.modelCatalogHeading}>
+ <span className={styles.modelCatalogTitle}>{t('models')}</span>
+ {props.overridden === undefined
+ ? null
+ : (
+ <span className={styles.modelCatalogMeta}>
+ {props.overridden ? t('modelsCustomized') : t('modelsInherited')}
+ </span>
+ )}
+ </div>
+ {props.overridden === true && props.onReset !== undefined
+ ? (
+ <button
+ type="button"
+ className={styles.linkButton}
+ disabled={disabled}
+ onClick={props.onReset}
+ >
+ {t('resetModels')}
+ </button>
+ )
+ : null}
+ <button
+ type="button"
+ className={styles.linkButton}
+ disabled={disabled || busy || !askable || props.probeBlocked !== undefined}
+ title={props.probeBlocked !== undefined
+ ? t(props.probeBlocked)
+ : askable ? undefined : t('fetchNeedsBaseUrl')}
+ onClick={() => { void fetchModels() }}
+ >
+ {busy ? t('fetching') : t('fetchModels')}
+ </button>
+ <button
+ type="button"
+ className={styles.linkButton}
+ disabled={disabled || configBusy || models.length === 0}
+ title={t('autoConfigureModelsHint')}
+ onClick={() => { onFetchConfig() }}
+ >
+ {t('autoConfigureModels')}
+ </button>
+ </div>
+ {configFailure === undefined ? null : <p className={styles.error}>{configFailure}</p>}
+ {configNotice === undefined ? null : <p className={styles.advancedHint}>{configNotice}</p>}
+ {models.length === 0 ? <p className={styles.modelEmpty}>{t('modelsEmpty')}</p> : null}
+ {models.map((model, index) => (
+ <div key={index} className={styles.modelEntry}>
+ <div className={styles.modelRow}>
+ <input
+ className={styles.input}
+ type="text"
+ value={textOf(model, 'id')}
+ placeholder={t('modelId')}
+ aria-label={`${t('modelId')} ${index + 1}`}
+ disabled={disabled}
+ onChange={(event) => { patch(index, { id: event.target.value }) }}
+ />
+ <input
+ className={styles.input}
+ type="text"
+ value={textOf(model, 'name')}
+ placeholder={t('modelName')}
+ aria-label={`${t('modelName')} ${index + 1}`}
+ disabled={disabled}
+ onChange={(event) => { patch(index, { name: event.target.value === '' ? undefined : event.target.value }) }}
+ />
+ {hasModelConfig(model)
+ ? null
+ : (
+ <button
+ type="button"
+ className={styles.linkButton}
+ disabled={disabled || configBusy}
+ title={t('fetchModelConfigHint')}
+ onClick={() => { onFetchConfig([textOf(model, 'id')]) }}
+ >
+ {configBusy ? t('fetchingConfig') : t('fetchModelConfig')}
+ </button>
+ )}
+ <button
+ type="button"
+ className={styles.iconButton}
+ aria-label={`${t('modelAdvanced')} ${index + 1}`}
+ aria-expanded={expanded.has(index)}
+ title={t('modelAdvanced')}
+ onClick={() => { toggleExpanded(index) }}
+ >
+ <IconChevron open={expanded.has(index)} />
+ </button>
+ <button
+ type="button"
+ className={`${styles.iconButton} ${styles.iconButtonDanger}`}
+ aria-label={`${t('removeModel')} ${index + 1}`}
+ title={t('removeModel')}
+ disabled={disabled}
+ onClick={() => {
+ onChange(models.filter((_model, at) => at !== index))
+
+ setExpanded((current) => {
+ const next = new Set<number>()
+ for (const at of current) {
+ if (at < index)
+ next.add(at)
+ else if (at > index)
+ next.add(at - 1)
+ }
+ return next
+ })
+ setEditing(current => reindexOnRemove(current, index))
+ }}
+ >
+ <IconTrash />
+ </button>
+ </div>
+ {expanded.has(index)
+ ? (
+ <div className={styles.modelAdvanced} style={ADVANCED_AREA_STYLE}>
+ <div style={ADVANCED_ROW_STYLE}>
+ <div style={ADVANCED_CAPACITIES_STYLE}>
+ <label className={styles.modelField} style={ADVANCED_CAPACITY_STYLE}>
+ <span className={styles.modelFieldLabel}>{t('modelContextWindow')}</span>
+ <input
+ className={styles.input}
+ type="text"
+ inputMode="numeric"
+ value={capacityText(model, index, 'contextWindow')}
+ placeholder={CAPACITY_HINT.contextWindow}
+ aria-label={`${t('modelContextWindow')} ${index + 1}`}
+ disabled={disabled}
+ onChange={(event) => { editCapacity(index, 'contextWindow', event.target.value) }}
+ />
+ </label>
+ <label className={styles.modelField} style={ADVANCED_CAPACITY_STYLE}>
+ <span className={styles.modelFieldLabel}>{t('modelMaxTokens')}</span>
+ <input
+ className={styles.input}
+ type="text"
+ inputMode="numeric"
+ value={capacityText(model, index, 'maxTokens')}
+ placeholder={CAPACITY_HINT.maxTokens}
+ aria-label={`${t('modelMaxTokens')} ${index + 1}`}
+ disabled={disabled}
+ onChange={(event) => { editCapacity(index, 'maxTokens', event.target.value) }}
+ />
+ </label>
+ </div>
+ <div style={ADVANCED_SWITCHES_STYLE}>
+ <div className={styles.modelField}>
+ <span className={styles.modelFieldLabel} title={t('imageInputHint')}>{t('imageInput')}</span>
+ <div className={styles.modelSwitchRow}>
+ <Switch
+ checked={supportsImageInput(model)}
+ disabled={disabled}
+ label={`${t('imageInput')} ${index + 1}`}
+ title={t('imageInputHint')}
+ onChange={(next) => { patch(index, { input: imageInputValue(next) }) }}
+ />
+ </div>
+ </div>
+ <div className={styles.modelField}>
+ <span className={styles.modelFieldLabel} title={t('thinkingModeHint')}>{t('thinkingMode')}</span>
+ <div className={styles.modelSwitchRow}>
+ <Switch
+ checked={supportsThinking(model)}
+ disabled={disabled}
+ label={`${t('thinkingMode')} ${index + 1}`}
+ title={t('thinkingModeHint')}
+ onChange={(next) => {
+ patch(index, { reasoningEfforts: next ? enableThinking(model) : false })
+ }}
+ />
+ </div>
+ </div>
+ {probe.api === TEMPLATE_COMPAT_PROTOCOL
+ ? (
+ <div className={styles.modelField}>
+ <span className={styles.modelFieldLabel} title={t('developerRoleHint')}>
+ {t('developerRole')}
+ </span>
+ <div className={styles.modelSwitchRow}>
+ <Switch
+ checked={supportsTemplateThinking(model)}
+ disabled={disabled}
+ label={`${t('developerRole')} ${index + 1}`}
+ title={t('developerRoleHint')}
+ onChange={(next) => { patch(index, { compat: templateThinkingCompat(model, next) }) }}
+ />
+ </div>
+ </div>
+ )
+ : null}
+ </div>
+ </div>
+ {supportsThinking(model)
+ ? (
+ <div className={styles.modelEfforts} role="group" aria-label={`${t('thinkingLevels')} ${index + 1}`}>
+ {THINKING_LEVELS.map(level => (
+ <label key={level} className={styles.modelEffortChip}>
+ <input
+ type="checkbox"
+ checked={declaredThinkingLevels(model).includes(level)}
+ disabled={disabled}
+ onChange={(event) => {
+ patch(index, {
+ reasoningEfforts: toggleThinkingLevel(
+ thinkingEffortsOf(model),
+ level,
+ event.target.checked,
+ ),
+ })
+ }}
+ />
+ {level}
+ </label>
+ ))}
+ </div>
+ )
+ : null}
+ </div>
+ )
+ : null}
+ </div>
+ ))}
+ <button
+ type="button"
+ className={styles.addModelButton}
+ disabled={disabled}
+ onClick={() => { onChange([...models, { id: '' }]) }}
+ >
+ {t('addModel')}
+ </button>
+ {failure !== undefined ? <p className={styles.error}>{failure}</p> : null}
+ <Modal
+ open={candidates !== undefined}
+ onClose={closePicker}
+ title={t('fetchTitle')}
+ closeLabel={t('close')}
+ description={t('fetchDescription')}
+ className={styles.fetchDialog as string}
+ footer={(
+ <>
+ <Button variant="outline" onClick={closePicker}>{t('cancel')}</Button>
+ <Button variant="outline" onClick={adoptPicked}>{t('fetchAdopt')}</Button>
+ </>
+ )}
+ >
+ <div className={styles.candidateToolbar}>
+ <input
+ className={`${styles.input} ${styles.candidateSearch}`}
+ type="search"
+ value={candidateQuery}
+ placeholder={t('fetchSearch')}
+ aria-label={t('fetchSearch')}
+ onChange={(event) => { setCandidateQuery(event.target.value) }}
+ />
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={visibleCandidates.length === 0}
+ onClick={toggleVisibleCandidates}
+ >
+ {t(allVisibleCandidatesPicked ? 'fetchDeselectAll' : 'fetchSelectAll')}
+ </Button>
+ </div>
+ {visibleCandidates.length === 0
+ ? <p className={styles.candidateEmpty} role="status">{t('fetchNoMatches')}</p>
+ : (
+ <ul className={styles.candidateList}>
+ {visibleCandidates.map(candidate => (
+ <li key={candidate.id} className={styles.candidate}>
+ <label className={styles.candidateLabel}>
+ <input
+ type="checkbox"
+ checked={picked.has(candidate.id)}
+ onChange={() => { toggle(candidate.id) }}
+ />
+
+ <span className={styles.candidateId}>{candidate.id}</span>
+ </label>
+ </li>
+ ))}
+ </ul>
+ )}
+ </Modal>
+ </section>
+ )
+}
diff --git a/archiving/dsh-tauri-model-config/src/client/models/ModelsSection.tsx b/archiving/dsh-tauri-model-config/src/client/models/ModelsSection.tsx
new file mode 100644
index 00000000..47f4ed47
--- /dev/null
+++ b/archiving/dsh-tauri-model-config/src/client/models/ModelsSection.tsx
@@ -0,0 +1,561 @@
+import type { InjectFace, PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots'
+import type { ReactNode } from 'react'
+import type { ConfigFileOpen } from '../service/model-config.ts'
+import type { en } from './locales.ts'
+
+import type { ModelsOperations } from './operations.ts'
+import type { ProviderEditorProps } from './ProviderEditor.tsx'
+import type { SettingsSchemaOperations } from './schema-operations.ts'
+import type {} from './slot-contract.ts'
+import type { ModelsSettingsStore, ProviderRow } from './store.ts'
+import { Button, Modal } from '@deepseek-ai/dsh-client-ui-primitives'
+import { Plus } from 'dsh-tauri-ui/client'
+import { useEffect, useState } from 'react'
+import { ConfigEditor } from '../components/config-editor'
+import { withDetail, withPath } from '../service/model-config.utils.ts'
+import { ensurePresets } from '../service/presets.ts'
+import { CustomProviderCard } from './CustomProviderCard.tsx'
+import { ProviderEditor } from './ProviderEditor.tsx'
+import { deriveKeyRef, protocolChoices, providerUsable } from './store.ts'
+import { modelStyles as styles } from './styles.ts'
+
+export interface ModelsSectionInjected {
+
+ controller: ModelsSettingsStore
+ hooks: {
+
+ snapshot: ModelsSettingsStore['store']
+ }
+
+ operations: ModelsOperations
+
+ schema: SettingsSchemaOperations
+
+ t: (key: keyof typeof en) => string
+
+ openConfig: () => Promise<ConfigFileOpen>
+}
+
+type ModelsChildSlots = 'settings.models.provider-card' | 'settings.models.footer'
+
+type ModelsRenderSlot = PropsRenderSlots<ModelsChildSlots>['renderSlot']
+
+export type ModelsSectionProps = Partial<InjectFace<ModelsSectionInjected>> & PropsRenderSlots<ModelsChildSlots>
+
+type ModelsSectionFace = InjectFace<ModelsSectionInjected>
+
+export interface ProviderIdentity {
+
+ provider: string
+
+ displayName: string
+}
+
+interface EditorTarget extends ProviderIdentity {
+ settingsNs: string
+ settingsPath: readonly string[]
+
+ credentialRef?: string
+
+ declared?: boolean
+}
+
+interface ProviderEditorRenderProps extends Pick<
+ ProviderEditorProps,
+ 'namespace' | 'schema' | 'operations' | 't' | 'readOnly' | 'onClose'
+> {
+ target: EditorTarget
+}
+
+function renderProviderEditor({ target, ...props }: ProviderEditorRenderProps): ReactNode {
+ return (
+ <ProviderEditor
+ provider={target.provider}
+ displayName={target.displayName}
+ settingsPath={target.settingsPath}
+ {...target.declared === true ? { declared: true } : {}}
+ {...props}
+ />
+ )
+}
+
+export async function removeProviderProfile(
+ operations: ModelsOperations,
+ controller: ModelsSettingsStore,
+ target: { settingsNs: string, settingsPath: readonly string[], credentialRef?: string },
+): Promise<string | undefined> {
+ if (target.credentialRef !== undefined) {
+ const credential = await operations.removeCredential(target.credentialRef)
+ if (credential !== undefined)
+ return credential
+ }
+ const written = await operations.writeSettings(
+ target.settingsNs,
+ [{ op: 'unset', path: [...target.settingsPath] }],
+ undefined,
+ )
+ if (written.kind !== 'written')
+ return written.message
+ await controller.load()
+ return undefined
+}
+
+export function needsSetup(row: ProviderRow, anyUsable: boolean): boolean {
+ if (anyUsable)
+ return false
+ if (row.entry.settingsPath.length > 0)
+ return false
+ return row.credential?.configured !== true
+}
+
+function keyConfiguredOf(row: ProviderRow): boolean {
+ return row.apiKeyEnv !== undefined
+ ? row.credential?.configured === true
+ : row.derivedCredential?.configured === true
+}
+
+function targetOf(row: ProviderRow): EditorTarget {
+ const managedRef = deriveKeyRef(row.entry.provider)
+ const credentialRef = row.apiKeyEnv === managedRef
+ && row.credential?.configured === true
+ && row.credential.writable
+ ? managedRef
+ : undefined
+ return {
+ provider: row.entry.provider,
+ displayName: row.entry.displayName,
+ settingsNs: row.entry.settingsNs,
+ settingsPath: row.entry.settingsPath,
+ ...credentialRef === undefined ? {} : { credentialRef },
+
+ ...row.entry.declared === true ? { declared: true } : {},
+ }
+}
+
+export function providerTargetLabel(target: ProviderIdentity): string {
+ return target.provider === target.displayName
+ ? target.provider
+ : `${target.displayName} (${target.provider})`
+}
+
+export function providerCopy(template: string, target: ProviderIdentity): string {
+ return template.replace('{provider}', () => providerTargetLabel(target))
+}
+
+export function ModelsSection(props: ModelsSectionProps): ReactNode {
+ const { controller, useSnapshot, operations, schema, t, openConfig, renderSlot } = props
+ if (
+ controller === undefined || useSnapshot === undefined || operations === undefined
+ || schema === undefined || t === undefined || openConfig === undefined
+ ) {
+ return null
+ }
+ return <Loaded injected={{ controller, useSnapshot, operations, schema, t, openConfig }} renderSlot={renderSlot} />
+}
+
+function Loaded({ injected, renderSlot }: { injected: ModelsSectionFace, renderSlot: ModelsRenderSlot }): ReactNode {
+ const { controller, operations, schema, t } = injected
+ const state = injected.useSnapshot(snapshot => snapshot)
+ const [editing, setEditing] = useState<EditorTarget | undefined>(undefined)
+ const [adding, setAdding] = useState(false)
+ const [deleteTarget, setDeleteTarget] = useState<EditorTarget | undefined>(undefined)
+ const [deleting, setDeleting] = useState(false)
+ const [deleteFailure, setDeleteFailure] = useState<string | undefined>(undefined)
+ const [savedTarget, setSavedTarget] = useState<ProviderIdentity | undefined>(undefined)
+ const [declaring, setDeclaring] = useState(false)
+ const [dismissedSetup, setDismissedSetup] = useState<ReadonlySet<string>>(() => new Set())
+ const [configOpen, setConfigOpen] = useState<{ text: string, failed: boolean } | undefined>(undefined)
+
+ // 能力表是自动配置填图片与思考的来源,进页面就先取回来,别让第一次点击等下载。
+ useEffect(() => {
+ void ensurePresets()
+ }, [])
+
+ const openConfigFile = (): void => {
+ setConfigOpen(undefined)
+ void injected.openConfig().then((outcome) => {
+ setConfigOpen(outcome.ok
+ ? {
+ text: withPath(outcome.opened === 'file' ? t('openConfigFileLanded') : t('openConfigFileDirectory'), outcome.path),
+ failed: false,
+ }
+ : { text: withDetail(t('openConfigFileFailed'), outcome.error), failed: true })
+ })
+ }
+
+ const announceSaved = (target: ProviderIdentity): void => {
+ void controller.load().then(() => {
+ setSavedTarget(target)
+ })
+ }
+
+ const closeEditor = (changed: boolean, target: ProviderIdentity): void => {
+ setEditing(undefined)
+ setAdding(false)
+ setDeclaring(false)
+ if (changed)
+ announceSaved(target)
+ }
+
+ const closeSetup = (changed: boolean, target: ProviderIdentity): void => {
+ setDismissedSetup(previous => new Set([...previous, target.provider]))
+ if (changed)
+ announceSaved(target)
+ }
+
+ const closeDelete = (): void => {
+ if (deleting)
+ return
+ setDeleteTarget(undefined)
+ setDeleteFailure(undefined)
+ }
+
+ const confirmDelete = (): void => {
+ if (deleteTarget === undefined || deleting)
+ return
+ setDeleting(true)
+ setDeleteFailure(undefined)
+ void removeProviderProfile(operations, controller, deleteTarget)
+ .then((failure) => {
+ if (failure !== undefined) {
+ setDeleteFailure(failure)
+ return
+ }
+ setDeleteTarget(undefined)
+ })
+ .finally(() => { setDeleting(false) })
+ }
+
+ if (state.status === 'idle')
+ void controller.load()
+ if (state.status === 'error') {
+ const errorText = state.error ?? ''
+ return (
+ <div className={styles.section}>
+ <p className={styles.error}>{`${t('loadFailed')}: ${errorText}`}</p>
+ <button type="button" className={styles.secondaryButton} onClick={() => { void controller.load() }}>
+ {t('retry')}
+ </button>
+ </div>
+ )
+ }
+
+ const savedRow = savedTarget === undefined
+ ? undefined
+ : state.rows.find(row => row.entry.provider === savedTarget.provider)
+ const savedIdentity = savedRow === undefined
+ ? savedTarget
+ : { provider: savedRow.entry.provider, displayName: savedRow.entry.displayName }
+
+ const anyUsable = state.rows.some(providerUsable)
+ const configured = state.rows.filter(row => row.configured)
+ const configurable = state.rows.filter(row => state.namespaces.has(row.entry.settingsNs))
+ const addable = configurable.filter(row => !row.configured)
+ const addTarget = adding ? editing : undefined
+ const addNamespace = addTarget === undefined ? undefined : state.namespaces.get(addTarget.settingsNs)
+
+ const addRow = addTarget === undefined
+ ? undefined
+ : state.rows.find(row => row.entry.provider === addTarget.provider)
+
+ const protocols = protocolChoices(state.namespaces.get('llm-pi-ai'), schema)
+
+ return (
+ <div className={styles.section}>
+ <div className={styles.titleRow}>
+ <h2 className={styles.title}>{t('title')}</h2>
+ <div className={styles.rowActions}>
+ <ConfigEditor t={t} />
+ <button
+ type="button"
+ className={styles.linkButton}
+ title={t('openConfigFileHint')}
+ onClick={openConfigFile}
+ >
+ {t('openConfigFile')}
+ </button>
+ </div>
+ </div>
+ <p className={styles.intro}>{t('intro')}</p>
+ {configOpen === undefined
+ ? null
+ : (
+ <p
+ role={configOpen.failed ? 'alert' : 'status'}
+ className={configOpen.failed ? styles.error : styles.savedNotice}
+ >
+ {configOpen.text}
+ </p>
+ )}
+ {!state.writable && state.status === 'ready' ? <p className={styles.notice}>{t('readOnly')}</p> : null}
+ {savedIdentity === undefined
+ ? null
+ : (
+ <p className={styles.savedNotice} role="status" aria-live="polite">
+ {providerCopy(t('savedProvider'), savedIdentity)}
+ </p>
+ )}
+ <ul className={styles.rows}>
+ {configured.map((row) => {
+ const target = targetOf(row)
+ const namespace = state.namespaces.get(target.settingsNs)
+
+ if (namespace === undefined)
+ return null
+ const error = row.entry.error === undefined
+ ? null
+ : <p role="alert" className={styles.error}>{row.entry.error}</p>
+ if (needsSetup(row, anyUsable) && !dismissedSetup.has(row.entry.provider)) {
+ return (
+ <li key={row.entry.provider} className={styles.setupCard}>
+ {error}
+ {renderProviderEditor({
+ target,
+ namespace,
+ schema,
+ operations,
+ t,
+ readOnly: !state.writable,
+ onClose: (changed) => { closeSetup(changed, target) },
+ })}
+ {renderSlot(
+ 'settings.models.provider-card',
+ { provider: row.entry, configured: row.configured, keyConfigured: keyConfiguredOf(row) },
+ { entryKey: row.entry.settingsNs },
+ )}
+ </li>
+ )
+ }
+ const open = !adding && editing?.provider === row.entry.provider
+ const credentialConfigured = row.credential?.configured === true
+ const credentialMissing = !credentialConfigured
+ && row.apiKeyEnv !== undefined
+ && row.credential?.configured === false
+ return (
+ <li key={row.entry.provider} className={styles.rowCard}>
+ <div className={styles.rowHead}>
+ <span className={styles.rowIdentity}>
+ <span className={styles.rowName}>{row.entry.displayName}</span>
+
+ {row.entry.declared === true
+ ? <span className={styles.rowTag}>{t('customTag')}</span>
+ : null}
+ {credentialConfigured
+ ? (
+ <span
+ className={`${styles.credentialDot} ${styles.credentialDotConfigured}`}
+ role="img"
+ aria-label={t('credentialConfigured')}
+ title={t('credentialConfigured')}
+ />
+ )
+ : credentialMissing
+ ? (
+ <span
+ className={`${styles.credentialDot} ${styles.credentialDotMissing}`}
+ role="img"
+ aria-label={t('credentialMissing')}
+ title={t('credentialMissing')}
+ />
+ )
+ : null}
+ </span>
+ <span className={styles.rowActions}>
+ <button
+ type="button"
+ className={styles.secondaryButton}
+ aria-label={providerCopy(t('editProvider'), target)}
+ onClick={() => {
+ setSavedTarget(undefined)
+
+ setDeclaring(false)
+ setAdding(false)
+ setEditing(open ? undefined : target)
+ }}
+ >
+ {t('edit')}
+ </button>
+ {row.removable
+ ? (
+ <button
+ type="button"
+ className={styles.dangerButton}
+ aria-label={providerCopy(t('removeProvider'), target)}
+ disabled={!state.writable}
+ onClick={() => {
+ setSavedTarget(undefined)
+ setDeleteFailure(undefined)
+ setDeleteTarget(target)
+ }}
+ >
+ {t('remove')}
+ </button>
+ )
+ : null}
+ </span>
+ </div>
+ {error}
+ {renderSlot(
+ 'settings.models.provider-card',
+ { provider: row.entry, configured: row.configured, keyConfigured: keyConfiguredOf(row) },
+ { entryKey: row.entry.settingsNs },
+ )}
+ {open
+ ? renderProviderEditor({
+ target,
+ namespace,
+ schema,
+ operations,
+ t,
+ readOnly: !state.writable,
+ onClose: (changed) => { closeEditor(changed, target) },
+ })
+ : null}
+ </li>
+ )
+ })}
+ </ul>
+ <div className={styles.addBlock}>
+ {addTarget !== undefined && addNamespace !== undefined
+ ? (
+ <div className={styles.addCard}>
+ <div className={styles.field}>
+ <span className={styles.fieldLabel}>{t('provider')}</span>
+ <select
+ className={`${styles.input} ${styles.selectInput}`}
+ value={addTarget.provider}
+ aria-label={t('provider')}
+ onChange={(event) => {
+ const row = addable.find(candidate => candidate.entry.provider === event.target.value)
+
+ if (row === undefined)
+ return
+ setEditing(targetOf(row))
+ }}
+ >
+ {addable.map(row => (
+ <option key={row.entry.provider} value={row.entry.provider}>{row.entry.displayName}</option>
+ ))}
+ </select>
+ </div>
+ <ProviderEditor
+ key={addTarget.provider}
+ provider={addTarget.provider}
+ displayName={addTarget.displayName}
+ hideTitle
+ namespace={addNamespace}
+ schema={schema}
+ settingsPath={addTarget.settingsPath}
+ operations={operations}
+ t={t}
+ readOnly={!state.writable}
+ onClose={(changed) => { closeEditor(changed, addTarget) }}
+ />
+ {addRow === undefined
+ ? null
+ : renderSlot(
+ 'settings.models.provider-card',
+ { provider: addRow.entry, configured: addRow.configured, keyConfigured: keyConfiguredOf(addRow) },
+ { entryKey: addRow.entry.settingsNs },
+ )}
+ </div>
+ )
+ : declaring
+ ? (
+ <div className={styles.addCard}>
+ <CustomProviderCard
+ taken={state.rows.map(row => row.entry.provider)}
+ protocols={protocols}
+
+ revision={state.namespaces.get('llm-pi-ai')?.revision ?? 0}
+ operations={operations}
+ t={t}
+ readOnly={!state.writable}
+ onClose={(changed) => {
+ setDeclaring(false)
+ if (changed)
+ void controller.load()
+ }}
+ />
+ </div>
+ )
+ : (
+
+ <div className={styles.addActions}>
+ {configurable.length > 0 && (
+ <button
+ type="button"
+ className={styles.addButton}
+ disabled={addable.length === 0 || !state.writable}
+ onClick={() => {
+ const first = addable[0]
+
+ if (first === undefined)
+ return
+ setSavedTarget(undefined)
+ setDeclaring(false)
+ setAdding(true)
+ setEditing(targetOf(first))
+ }}
+ >
+ <Plus width={14} height={14} />
+ {t('add')}
+ </button>
+ )}
+ {state.namespaces.has('llm-pi-ai') && (
+ <button
+ type="button"
+ className={styles.addButton}
+ disabled={protocols.length === 0 || !state.writable}
+ onClick={() => {
+ setSavedTarget(undefined)
+ setAdding(false)
+ setEditing(undefined)
+ setDeclaring(true)
+ }}
+ >
+ <Plus width={14} height={14} />
+ {t('customAdd')}
+ </button>
+ )}
+ </div>
+ )}
+ </div>
+ {renderSlot('settings.models.footer', {})}
+ <Modal
+ open={deleteTarget !== undefined}
+ onClose={closeDelete}
+ title={deleteTarget === undefined ? '' : providerCopy(t('deleteTitle'), deleteTarget)}
+ closeLabel={t('close')}
+ description={deleteTarget === undefined
+ ? ''
+ : providerCopy(
+ deleteTarget.credentialRef === undefined
+ ? t('deleteDescription')
+ : t('deleteDescriptionWithCredential'),
+ deleteTarget,
+ )}
+ className={styles.deleteDialog as string}
+ footer={(
+ <>
+ <Button variant="outline" autoFocus disabled={deleting} onClick={closeDelete}>
+ {t('cancel')}
+ </Button>
+ <Button
+ variant="outline"
+ className={styles.deleteConfirm}
+ disabled={deleting}
+ onClick={confirmDelete}
+ >
+ {deleteTarget === undefined
+ ? ''
+ : providerCopy(deleting ? t('deleting') : t('deleteConfirm'), deleteTarget)}
+ </Button>
+ </>
+ )}
+ >
+ {deleteFailure === undefined ? null : <p className={styles.error}>{deleteFailure}</p>}
+ </Modal>
+ </div>
+ )
+}
diff --git a/archiving/dsh-tauri-model-config/src/client/models/OnboardingModal.tsx b/archiving/dsh-tauri-model-config/src/client/models/OnboardingModal.tsx
new file mode 100644
index 00000000..893c5c2b
--- /dev/null
+++ b/archiving/dsh-tauri-model-config/src/client/models/OnboardingModal.tsx
@@ -0,0 +1,49 @@
+import type { ReactNode } from 'react'
+import { Modal } from '@deepseek-ai/dsh-client-ui-primitives'
+import { useEffect, useRef } from 'react'
+import { onboardingStyles as css } from './styles.ts'
+
+function ignoreImplicitDismiss(): void {}
+
+export function OnboardingModal({
+ title,
+ focusTitle = false,
+ children,
+}: {
+ title: string
+ focusTitle?: boolean
+ children: ReactNode
+}): ReactNode {
+ const titleRef = useRef<HTMLHeadingElement | null>(null)
+
+ useEffect(() => {
+ const appRoot = document.getElementById('root')
+ if (appRoot === null)
+ return
+ const previous = appRoot.inert
+ appRoot.inert = true
+ return () => {
+ appRoot.inert = previous
+ }
+ }, [])
+
+ useEffect(() => {
+ if (focusTitle)
+ titleRef.current?.focus()
+ }, [focusTitle])
+
+ return (
+ <Modal
+ open
+ title={title}
+ onClose={ignoreImplicitDismiss}
+ headless
+ className={css.dialog as string}
+ >
+ <div className={css.content}>
+ <h2 ref={titleRef} className={css.title} tabIndex={focusTitle ? -1 : undefined}>{title}</h2>
+ <div className={css.body}>{children}</div>
+ </div>
+ </Modal>
+ )
+}
diff --git a/archiving/dsh-tauri-model-config/src/client/models/ProviderEditor.tsx b/archiving/dsh-tauri-model-config/src/client/models/ProviderEditor.tsx
new file mode 100644
index 00000000..45e39545
--- /dev/null
+++ b/archiving/dsh-tauri-model-config/src/client/models/ProviderEditor.tsx
@@ -0,0 +1,474 @@
+import type { ReactNode } from 'react'
+import type {
+ CredentialInfo,
+ JsonValue,
+ SettingsNamespaceView,
+ SettingsPathOpView,
+} from '../types/remotes.ts'
+import type { en } from './locales.ts'
+import type { ModelsOperations } from './operations.ts'
+import type { SettingsSchemaOperations } from './schema-operations.ts'
+import { useEffect, useMemo, useState } from 'react'
+import { loadModelCapacities } from '../service/model-config.ts'
+import { mergeModelCards, modelConfigNotice, withDetail } from '../service/model-config.utils.ts'
+import { ensurePresets } from '../service/presets.ts'
+import { apiKeyFailure } from './apiKey.ts'
+import {
+ DeepSeekModelsEditor,
+ modelDrafts,
+ validateDeepSeekModels,
+} from './DeepSeekModelsEditor.tsx'
+import { EditorFooter } from './EditorFooter.tsx'
+import { ModelListEditor } from './ModelListEditor.tsx'
+import { deriveKeyRef, protocolChoices } from './store.ts'
+import { modelStyles as styles } from './styles.ts'
+
+type EditorLayout = 'deepseek' | 'pi-ai' | 'unknown'
+
+const DEEPSEEK_PUBLIC_BASE_URL = 'https://api.deepseek.com'
+
+export interface ProviderEditorProps {
+
+ provider: string
+
+ displayName: string
+
+ hideTitle?: boolean
+
+ declared?: boolean
+
+ namespace: SettingsNamespaceView
+
+ schema: SettingsSchemaOperations
+
+ settingsPath: readonly string[]
+
+ operations: ModelsOperations
+
+ t: (key: keyof typeof en) => string
+
+ readOnly: boolean
+
+ credentialOnly?: boolean
+
+ credentialRequired?: boolean
+
+ autoFocusCredential?: boolean
+
+ cancelLabelKey?: keyof typeof en
+
+ submitLabelKey?: keyof typeof en
+
+ submitBusyLabelKey?: keyof typeof en
+
+ onClose: (changed: boolean) => void
+}
+
+function draftAt(
+ schema: SettingsSchemaOperations,
+ namespace: SettingsNamespaceView,
+ path: readonly string[],
+): Record<string, unknown> {
+ const subtree = schema.getPath(namespace.user, path)
+ if (typeof subtree !== 'object' || subtree === null || Array.isArray(subtree))
+ return {}
+ return structuredClone(subtree) as Record<string, unknown>
+}
+
+export function pathOps(
+ base: readonly string[],
+ before: unknown,
+ after: Record<string, unknown>,
+): SettingsPathOpView[] {
+ const previous = typeof before === 'object' && before !== null && !Array.isArray(before)
+ ? before as Record<string, unknown>
+ : {}
+ const ops: SettingsPathOpView[] = []
+ for (const [key, value] of Object.entries(after)) {
+ if (JSON.stringify(previous[key]) === JSON.stringify(value))
+ continue
+ ops.push({ op: 'set', path: [...base, key], value: value as JsonValue })
+ }
+ for (const key of Object.keys(previous)) {
+ if (!(key in after))
+ ops.push({ op: 'unset', path: [...base, key] })
+ }
+ return ops
+}
+
+function layoutOf(ns: string): EditorLayout {
+ if (ns === 'llm-deepseek')
+ return 'deepseek'
+ if (ns === 'llm-pi-ai')
+ return 'pi-ai'
+ return 'unknown'
+}
+
+function refFor(
+ schema: SettingsSchemaOperations,
+ namespace: SettingsNamespaceView,
+ path: readonly string[],
+ provider: string,
+): string {
+ const profile = schema.getPath(namespace.value, path)
+ const named = typeof profile === 'object' && profile !== null
+ ? (profile as { apiKeyEnv?: unknown }).apiKeyEnv
+ : undefined
+ return typeof named === 'string' && named.length > 0 ? named : deriveKeyRef(provider)
+}
+
+export function ProviderEditor(props: ProviderEditorProps): ReactNode {
+ const { namespace, schema, settingsPath, operations, t } = props
+ const [draft, setDraft] = useState<Record<string, unknown>>(() => draftAt(schema, namespace, settingsPath))
+ const [keyDraft, setKeyDraft] = useState('')
+ const [keyState, setKeyState] = useState<CredentialInfo | undefined>(undefined)
+ const [busy, setBusy] = useState(false)
+ const [failure, setFailure] = useState<string | undefined>(undefined)
+ const [configBusy, setConfigBusy] = useState(false)
+ const [configNotice, setConfigNotice] = useState<string | undefined>(undefined)
+ const [configFailure, setConfigFailure] = useState<string | undefined>(undefined)
+
+ const [committedOriginal, setCommittedOriginal] = useState<unknown>(
+ () => schema.getPath(namespace.user, settingsPath),
+ )
+ const [expectedRevision, setExpectedRevision] = useState(() => namespace.revision)
+ const root = useMemo(() => schema.rehydrate(namespace.schema), [namespace.schema, schema])
+ const node = useMemo(() => schema.nodeAtPath(root, settingsPath), [root, schema, settingsPath])
+ const fallback = schema.getPath(namespace.value, settingsPath)
+ const disabled = props.readOnly || busy
+ const layout = layoutOf(namespace.ns)
+ const keyRef = refFor(schema, namespace, settingsPath, props.provider)
+
+ const protocols = useMemo(
+ () => layout === 'pi-ai' ? protocolChoices(namespace, schema) : [],
+ [layout, namespace, schema],
+ )
+
+ useEffect(() => {
+ let stale = false
+ setKeyState(undefined)
+
+ void operations.describeCredential(keyRef).then((described) => {
+ if (stale)
+ return
+ setKeyState(described)
+ })
+ return () => {
+ stale = true
+ }
+ }, [operations, keyRef])
+
+ const stringAt = (source: unknown, key: string): string | undefined => {
+ const value = schema.getPath(source, [key])
+ return typeof value === 'string' && value.trim().length > 0 ? value : undefined
+ }
+ const setField = (key: string, next: string | undefined): void => {
+ const value = next === undefined || next.trim().length === 0 ? undefined : next
+ setDraft(current => value === undefined
+ ? schema.deletePath(current, [key])
+ : schema.setPath(current, [key], value))
+ }
+
+ const modelFailure = validateDeepSeekModels(schema.getPath(draft, ['models']))
+ const keyFailure = apiKeyFailure(keyDraft)
+
+ const keyValue = keyDraft.trim()
+ const credentialRequiredFailure = props.credentialRequired === true
+ && keyDraft.length > 0 && keyValue.length === 0
+ ? 'keyRequired' as const
+ : undefined
+ const shownKeyFailure = credentialRequiredFailure ?? keyFailure
+
+ const probeApi = stringAt(draft, 'api') ?? stringAt(fallback, 'api')
+ const probeBaseURL = stringAt(draft, 'baseURL') ?? stringAt(fallback, 'baseURL')
+ const probe = {
+ settingsNs: namespace.ns,
+
+ provider: props.provider,
+ ...probeBaseURL === undefined ? {} : { baseURL: probeBaseURL },
+ ...probeApi === undefined ? {} : { api: probeApi },
+ ...keyValue.length === 0 ? {} : { apiKey: keyValue },
+ }
+
+ const applyOnce = async (): Promise<string | undefined> => {
+ const ns = namespace.ns
+
+ const next = layout === 'pi-ai' && stringAt(draft, 'apiKeyEnv') === undefined
+ && stringAt(fallback, 'apiKeyEnv') === undefined && keyValue.length > 0
+ ? schema.setPath(draft, ['apiKeyEnv'], keyRef)
+ : draft
+ if (props.credentialOnly !== true) {
+ const failure = validateDeepSeekModels(schema.getPath(next, ['models']))
+
+ if (failure !== undefined) {
+ return `${t('model')} ${String(failure.index + 1)}: ${t(failure.key)}`
+ }
+ }
+
+ if (props.credentialOnly !== true && node !== undefined && settingsPath.length === 0) {
+ const sectionError = schema.validate(node, next)
+ if (sectionError !== undefined)
+ return sectionError
+ }
+ const materializesNativeProfile = layout === 'pi-ai'
+ && fallback === undefined
+ && committedOriginal === undefined
+ && Object.keys(next).length === 0
+ const ops: SettingsPathOpView[] = props.credentialOnly === true
+ ? []
+ : materializesNativeProfile
+ ? [{ op: 'set', path: [...settingsPath], value: {} }]
+ : pathOps(settingsPath, committedOriginal, next)
+ if (ops.length > 0) {
+ const written = await operations.writeSettings(ns, ops, expectedRevision)
+ if (written.kind !== 'written')
+ return written.kind === 'conflict' ? t('conflict') : written.message
+ setCommittedOriginal(schema.getPath(written.view.user, settingsPath))
+ setExpectedRevision(written.view.revision)
+ setDraft(next)
+ }
+ if (keyValue.length > 0) {
+ const stored = await operations.storeCredential(keyRef, keyValue)
+ if (stored !== undefined)
+ return stored
+ }
+ setKeyDraft('')
+ return undefined
+ }
+
+ const apply = async (): Promise<void> => {
+ setBusy(true)
+ setFailure(undefined)
+ try {
+ const failure = await applyOnce()
+ if (failure !== undefined) {
+ setFailure(failure)
+ return
+ }
+ props.onClose(true)
+ }
+ finally {
+ setBusy(false)
+ }
+ }
+
+ if (node === undefined) {
+ return (
+ <p className={styles.error}>
+ {props.provider}
+ :
+ {' '}
+ {props.t('settingsPathUnresolvable')}
+ </p>
+ )
+ }
+
+ const keyLocked = keyState?.writable === false
+
+ const inheritedModels = (): unknown => {
+ const pinned = schema.getPath(namespace.base, [...settingsPath, 'models'])
+ return pinned ?? schema.nodeAtPath(root, [...settingsPath, 'models'])?.meta.default
+ }
+
+ const curatedFields = (family: 'deepseek' | 'pi-ai'): ReactNode => {
+ const ownsIdentity = family === 'pi-ai' && props.declared === true
+ const customModels = schema.getPath(draft, ['models'])
+ const modelsOverridden = schema.hasPath(draft, ['models'])
+ const models = modelDrafts(modelsOverridden ? customModels : inheritedModels())
+ const defaultContextWindow = schema.getPath(fallback, ['defaultContextWindow'])
+ const defaultMaxTokens = schema.getPath(fallback, ['maxTokens'])
+ const keyPlaceholder = keyLocked
+ ? t('keyEnvLocked')
+ : keyState?.configured === true && props.credentialRequired !== true
+ ? t('keyStored')
+ : family === 'pi-ai' ? t('keyPlaceholderNative') : t('keyPlaceholder')
+
+ const catalogProps = {
+ models,
+ overridden: modelsOverridden,
+ t,
+ disabled,
+ onChange: (next: Record<string, unknown>[]) => {
+ setDraft(current => schema.setPath(current, ['models'], next))
+ },
+ onReset: () => { setDraft(current => schema.deletePath(current, ['models'])) },
+ }
+ const fetchConfig = (targets?: readonly string[]): void => {
+ void (async () => {
+ setConfigBusy(true)
+ setConfigFailure(undefined)
+ const [found] = await Promise.all([
+ loadModelCapacities({
+ settingsNs: namespace.ns,
+ profilePath: settingsPath,
+ provider: props.provider,
+ ...probeBaseURL === undefined ? {} : { baseURL: probeBaseURL },
+ ...probeApi === undefined ? {} : { api: probeApi },
+ ...keyValue.length === 0 ? {} : { apiKey: keyValue },
+ }, operations),
+ ensurePresets(),
+ ])
+ setConfigBusy(false)
+ if (!found.ok) {
+ setConfigNotice(undefined)
+ setConfigFailure(withDetail(t('configUnreachable'), found.error))
+ return
+ }
+ const merged = mergeModelCards(models, found.models, { targets, overwrite: targets === undefined })
+ if (merged.applied > 0)
+ catalogProps.onChange(merged.models)
+ setConfigNotice(modelConfigNotice(merged, {
+ applied: t('configApplied'),
+ none: t('configNoneApplied'),
+ undisclosed: t('configUndisclosed'),
+ }))
+ })()
+ }
+ return (
+ <>
+ <div className={styles.field}>
+ <span className={styles.fieldLabel}>{t('keyInput')}</span>
+ <input
+ className={styles.input}
+ type="password"
+ autoComplete="off"
+ value={keyDraft}
+ placeholder={keyPlaceholder}
+ aria-label={t('keyInput')}
+ aria-invalid={shownKeyFailure !== undefined}
+ required={props.credentialRequired === true}
+ autoFocus={props.autoFocusCredential === true}
+ disabled={disabled || keyLocked}
+ onChange={(event) => { setKeyDraft(event.target.value) }}
+ />
+ {shownKeyFailure === undefined ? null : <p className={styles.error}>{t(shownKeyFailure)}</p>}
+ </div>
+ {props.credentialOnly === true
+ ? null
+ : (
+ <details className={styles.customized}>
+ <summary className={styles.customizedSummary}>{t('customized')}</summary>
+ <div className={styles.customizedBody}>
+
+ {ownsIdentity
+ ? (
+ <div className={styles.field}>
+ <span className={styles.fieldLabel}>{t('customDisplayName')}</span>
+ <input
+ className={styles.input}
+ type="text"
+ value={stringAt(draft, 'displayName') ?? ''}
+
+ placeholder={stringAt(schema.getPath(namespace.base, settingsPath), 'displayName')
+ ?? props.provider}
+ aria-label={t('customDisplayName')}
+ disabled={disabled}
+ onChange={(event) => { setField('displayName', event.target.value) }}
+ />
+ </div>
+ )
+ : null}
+ <div className={styles.field}>
+ <span className={styles.fieldLabel}>{t('baseUrl')}</span>
+ <input
+ className={styles.input}
+ type="text"
+ value={stringAt(draft, 'baseURL') ?? ''}
+ placeholder={family === 'deepseek'
+ ? DEEPSEEK_PUBLIC_BASE_URL
+ : stringAt(fallback, 'baseURL') ?? t('baseUrlDefault')}
+ aria-label={t('baseUrl')}
+ disabled={disabled}
+ onChange={(event) => {
+ setField('baseURL', event.target.value === '' ? undefined : event.target.value)
+ }}
+ />
+ </div>
+
+ {ownsIdentity
+ ? (
+ <div className={styles.field}>
+ <span className={styles.fieldLabel}>{t('customApi')}</span>
+ <select
+ className={`${styles.input} ${styles.selectInput}`}
+ value={probeApi ?? ''}
+ aria-label={t('customApi')}
+ disabled={disabled}
+ onChange={(event) => { setField('api', event.target.value) }}
+ >
+
+ {probeApi === undefined ? <option value="">{t('customApiUnset')}</option> : null}
+ {protocols.map(choice => <option key={choice} value={choice}>{choice}</option>)}
+ </select>
+ </div>
+ )
+ : null}
+
+ {family === 'deepseek'
+ ? (
+ <DeepSeekModelsEditor
+ {...catalogProps}
+ defaultContextWindow={typeof defaultContextWindow === 'number'
+ ? defaultContextWindow
+ : undefined}
+ defaultMaxTokens={typeof defaultMaxTokens === 'number' ? defaultMaxTokens : undefined}
+ />
+ )
+ : (
+ <ModelListEditor
+ {...catalogProps}
+ probe={probe}
+ probeBlocked={keyFailure}
+ operations={operations}
+ onFetchConfig={fetchConfig}
+ configBusy={configBusy}
+ configNotice={configNotice}
+ configFailure={configFailure}
+ />
+ )}
+ </div>
+ </details>
+ )}
+ </>
+ )
+ }
+
+ return (
+ <div className={props.credentialOnly === true ? styles.addBlock : styles.editor}>
+ {props.hideTitle === true
+ ? null
+ : (
+ <div className={styles.editorHeader}>
+ <span className={styles.editorTitle}>{props.displayName}</span>
+ {props.provider !== props.displayName
+ ? <span className={styles.editorRoute}>{props.provider}</span>
+ : null}
+ </div>
+ )}
+ {layout === 'unknown'
+ ? <p className={styles.advancedHint}>{`${t('advancedHint')} (${namespace.ns})`}</p>
+ : curatedFields(layout)}
+ {failure !== undefined ? <p className={styles.error}>{failure}</p> : null}
+ {props.credentialOnly === true || modelFailure === undefined
+ ? null
+ : (
+ <p className={styles.advancedHint}>
+ {`${t('model')} ${String(modelFailure.index + 1)}: ${t(modelFailure.key)}`}
+ </p>
+ )}
+ <EditorFooter
+ t={t}
+ busy={busy}
+ submitDisabled={disabled || layout === 'unknown'
+ || (props.credentialOnly !== true && modelFailure !== undefined)
+ || shownKeyFailure !== undefined
+ || (props.credentialRequired === true && keyValue.length === 0)}
+ submitLabelKey={props.submitLabelKey ?? 'apply'}
+ submitBusyLabelKey={props.submitBusyLabelKey ?? 'applying'}
+ {...props.cancelLabelKey === undefined ? {} : { cancelLabelKey: props.cancelLabelKey }}
+ onCancel={() => { props.onClose(false) }}
+ onSubmit={() => { void apply() }}
+ />
+ </div>
+ )
+}
diff --git a/archiving/dsh-tauri-model-config/src/client/models/WelcomeNotice.tsx b/archiving/dsh-tauri-model-config/src/client/models/WelcomeNotice.tsx
new file mode 100644
index 00000000..e89c4555
--- /dev/null
+++ b/archiving/dsh-tauri-model-config/src/client/models/WelcomeNotice.tsx
@@ -0,0 +1,73 @@
+import type { SnapshotStore } from '@deepseek-ai/dsh-client-store'
+import type { InjectFace, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
+import type { ReactNode } from 'react'
+import type { en } from './locales.ts'
+import type { WelcomeNoticeState, WelcomeNoticeStore } from './welcome-store.ts'
+import { Button } from '@deepseek-ai/dsh-client-ui-primitives'
+import { useCallback, useEffect, useRef } from 'react'
+import { OnboardingModal } from './OnboardingModal.tsx'
+import { welcomeStyles as css } from './styles.ts'
+
+export interface WelcomeNoticeInjected {
+ hooks: {
+
+ welcome: SnapshotStore<WelcomeNoticeState>
+ }
+
+ controller: WelcomeNoticeStore
+
+ t: (key: keyof typeof en) => string
+}
+
+export type WelcomeNoticeProps
+ = PropsRuntime<'settings.onboarding'> & InjectFace<WelcomeNoticeInjected>
+
+export function WelcomeNotice(props: WelcomeNoticeProps): ReactNode {
+ const { complete, controller, useWelcome, t } = props
+ const state = useWelcome(snapshot => snapshot)
+ const finished = useRef(false)
+ const finish = useCallback((): void => {
+ if (finished.current)
+ return
+ finished.current = true
+ complete()
+ }, [complete])
+
+ useEffect(() => {
+ if (state.status === 'idle')
+ void controller.load()
+ }, [controller, state.status])
+
+ useEffect(() => {
+ if (state.acknowledged)
+ finish()
+ }, [finish, state.acknowledged])
+
+ if (state.status === 'idle' || state.status === 'loading' || state.acknowledged)
+ return null
+
+ const acknowledge = async (): Promise<void> => {
+ if (await controller.acknowledge())
+ finish()
+ }
+ const paragraphs = t('welcomeBody').split('\n\n')
+
+ return (
+ <OnboardingModal title={t('welcomeTitle')} focusTitle>
+ <div className={css.copy}>
+ {paragraphs.map(paragraph => <p key={paragraph}>{paragraph}</p>)}
+ </div>
+ {state.error === null ? null : <p className={css.error} role="alert">{t('welcomeError')}</p>}
+ <div className={css.actions}>
+ <Button
+ variant="primary"
+ className={css.primary}
+ disabled={state.status === 'saving'}
+ onClick={() => { void acknowledge() }}
+ >
+ {t('welcomeContinue')}
+ </Button>
+ </div>
+ </OnboardingModal>
+ )
+}
diff --git a/archiving/dsh-tauri-model-config/src/client/models/apiKey.ts b/archiving/dsh-tauri-model-config/src/client/models/apiKey.ts
new file mode 100644
index 00000000..5c959ae3
--- /dev/null
+++ b/archiving/dsh-tauri-model-config/src/client/models/apiKey.ts
@@ -0,0 +1,25 @@
+const LEGAL_API_KEY = /^[\x21-\x7E]+$/
+
+const ENV_LINE = /^[A-Z][A-Z0-9_]*=[^=]/
+
+export type ApiKeyFailureKey = 'keyBlank' | 'keyIllegalCharacters'
+
+function isQuoted(value: string): boolean {
+ const first = value[0]
+ if (first !== '"' && first !== '\'' && first !== '`')
+ return false
+ return value.length > 1 && value.endsWith(first)
+}
+
+export function apiKeyFailure(draft: string): ApiKeyFailureKey | undefined {
+ if (draft.length === 0)
+ return undefined
+ const value = draft.trim()
+ if (value.length === 0)
+ return 'keyBlank'
+ if (ENV_LINE.test(value) || isQuoted(value))
+ return 'keyIllegalCharacters'
+ if (!LEGAL_API_KEY.test(value))
+ return 'keyIllegalCharacters'
+ return undefined
+}
diff --git a/archiving/dsh-tauri-model-config/src/client/models/locales.ts b/archiving/dsh-tauri-model-config/src/client/models/locales.ts
new file mode 100644
index 00000000..73831e11
--- /dev/null
+++ b/archiving/dsh-tauri-model-config/src/client/models/locales.ts
@@ -0,0 +1,271 @@
+export const en = {
+ nav: 'Models',
+ title: 'Models',
+ intro: 'Enter your API keys to use models from the following providers.',
+ edit: 'Edit',
+ editProvider: 'Edit {provider}',
+ remove: 'Delete',
+ removeProvider: 'Delete {provider}',
+ deleteTitle: 'Delete {provider}?',
+ deleteDescription: 'Deleting {provider} removes its configuration. Any credential it uses is managed elsewhere and will be kept.',
+ deleteDescriptionWithCredential: 'Deleting {provider} removes its configuration and stored API key.',
+ deleteConfirm: 'Delete {provider}',
+ deleting: 'Deleting {provider}…',
+ add: 'Add provider',
+ provider: 'Provider',
+ close: 'Close',
+ cancel: 'Cancel',
+ apply: 'Apply',
+ applying: 'Applying…',
+ savedProvider: 'Saved {provider}.',
+ credentialConfigured: 'API key configured',
+ credentialMissing: 'API key missing',
+ readOnly: 'The settings document is read-only in this deployment.',
+ loadFailed: 'Loading the provider directory failed',
+ conflict: 'Someone else changed these settings while this card was open. Close it and reopen to edit the current values.',
+ retry: 'Retry',
+ keyInput: 'API key',
+ keyPlaceholder: 'Enter your API key',
+ keyPlaceholderNative: 'Enter an API key, or leave blank to use environment authentication',
+ keyStored: 'Configured — enter a new value to replace',
+ keyEnvLocked: 'Provided by the launch environment (read-only)',
+ customized: 'Customized settings',
+ baseUrl: 'Base URL',
+ baseUrlDefault: 'Provider default',
+ models: 'Models',
+ modelsInherited: 'Using the adapter defaults',
+ modelsCustomized: 'Customized model catalog',
+ resetModels: 'Restore defaults',
+ model: 'Model',
+ modelId: 'Model ID',
+ modelName: 'Display name',
+ modelNamePlaceholder: 'Uses the model ID when empty',
+ contextWindow: 'Context window',
+ contextWindowPlaceholder: 'Uses the provider default',
+ maxTokens: 'Max output tokens',
+ maxTokensPlaceholder: 'Uses the provider default',
+ modelAdvanced: 'Capacities',
+ addModel: 'Add model',
+ removeModel: 'Delete model',
+ modelsEmpty: 'No models will be shown in the selector. Unlisted IDs can still be sent directly.',
+ keyBlank: 'Enter the API key, or leave the field empty to keep the stored one.',
+ keyBlankNew: 'Enter the API key, or leave the field empty if this provider authenticates another way.',
+ keyIllegalCharacters: 'This API key is not in a valid format. Please check it.',
+ modelIdRequired: 'Model ID is required.',
+ modelIdDuplicate: 'Model ID must be unique.',
+ modelNameInvalid: 'Display name cannot be empty.',
+ modelContextInvalid: 'Context window must be a positive count, like 131072, 256K, or 1M.',
+ modelMaxTokensInvalid: 'Max output tokens must be a positive count, like 8192, 64K, or 1M.',
+ advancedHint: 'Other fields live in settings.yaml; edit that section directly.',
+ modelCapacityInvalid: 'A capacity must be a number, optionally suffixed K or M.',
+ modelDuplicate: 'Each model ID may appear once.',
+ modelContextWindow: 'Context window',
+ modelMaxTokens: 'Max output tokens',
+ fetchModels: 'Fetch available models',
+ fetching: 'Asking the provider\u2026',
+ fetchNeedsBaseUrl: 'Enter the base URL first, then fetch.',
+ fetchEmpty: 'The provider listed no models. Add them by hand.',
+ fetchTitle: 'Choose models to add',
+ fetchDescription: 'These are the models this provider has available. Choose the ones to add.',
+ fetchSearch: 'Search models',
+ fetchNoMatches: 'No matching models.',
+ fetchSelectAll: 'Select all',
+ fetchDeselectAll: 'Deselect all',
+ fetchAdopt: 'Add selected',
+ customAdd: 'Add a custom provider',
+ customTitle: 'Custom provider',
+ customTag: 'Custom',
+ customRoute: 'Provider ID',
+ customRouteHint: 'Lowercase identifier, starting with a letter, that uniquely names this provider in requests and as its credential name.',
+ customRouteInvalid: 'Start with a lowercase letter; then lowercase letters, digits, and dashes.',
+ customRouteTaken: 'A provider already uses this ID.',
+ customDisplayName: 'Display name',
+ customApi: 'API protocol',
+ customApiUnset: 'Not selected',
+ customNeedsBaseUrl: 'A custom provider needs a base URL.',
+ customBaseUrlInvalid: 'Enter a valid HTTP or HTTPS URL.',
+ customNeedsModels: 'A custom provider needs at least one model.',
+ customBaseUrlPlaceholder: 'https://gateway.example/v1',
+ settingsPathUnresolvable: 'unresolvable settings path',
+ create: 'Create provider',
+ creating: 'Creating\u2026',
+ welcomeTitle: 'Internal Testing Notice',
+ welcomeBody: 'DeepSeek Harness 0.1 remains in testing for Harness developers. Many areas need further improvement, and we welcome feedback from the developer community. DeepSeek Harness\'s core plugins and foundational APIs will continue to evolve rapidly over the coming months.\n\nWe look forward to exploring the limits of intelligence with developers around the world, building on open-source, open, reusable, and composable infrastructure. We welcome Harness developers everywhere to join the DSH plugin ecosystem.',
+ welcomeContinue: 'Continue',
+ welcomeError: 'The acknowledgement could not be saved. Please try again.',
+ onboardingTitle: 'Add an API key to get started',
+ onboardingDescription: 'Configure the official DeepSeek provider to start building.',
+ onboardingLater: 'Configure later',
+ onboardingSave: 'Save and continue',
+ onboardingSaving: 'Saving…',
+ keyRequired: 'Enter an API key to continue.',
+ openConfigFile: 'Open config file',
+ openConfigFileHint: 'Open the settings file that holds every model definition',
+ openConfigFileLanded: 'Opened {path}',
+ openConfigFileDirectory: 'The config file does not exist yet; opened {path} instead',
+ openConfigFileFailed: 'Could not open the config file. Check that your editor is installed, or change it in Text editor: {detail}',
+ textEditor: 'Text editor',
+ textEditorHint: 'This preference applies only to opening config files in the Models page.',
+ editorVSCode: 'VS Code',
+ editorCursor: 'Cursor',
+ editorSystem: 'System default (recommended)',
+ editorCustom: 'Custom editor',
+ editorCommand: 'Application name or executable path',
+ editorCommandPlaceholder: 'App name or executable path',
+ editorCommandHint: 'On macOS, enter an app name or .app path. On Windows, use the full .exe path. On Linux, use an executable name or path. Do not add quotes or arguments.',
+ editorLoadFailed: 'Could not load the editor preference: {detail}',
+ editorSaveFailed: 'Could not save the editor preference: {detail}',
+ imageInput: 'Image input',
+ imageInputHint: 'Declare whether this model accepts image content',
+ thinkingMode: 'Thinking mode',
+ thinkingLevels: 'Thinking levels',
+ thinkingModeHint: 'Declare whether this model thinks, then tick the levels it offers',
+ developerRole: 'Disable developer role',
+ developerRoleHint: 'Turn this on for an endpoint that rejects the developer role: system prompts stay system, and the effort travels through chat_template_kwargs; writes compat supportsDeveloperRole=false, thinkingFormat=chat-template and chatTemplateKwargs.reasoning_effort={$var: thinking.effort}',
+ fetchModelConfig: 'Fetch config',
+ fetchModelConfigHint: 'Fill in this model\'s limits from the endpoint and its image/thinking capabilities from the model capability table',
+ autoConfigureModels: 'Configure all models',
+ autoConfigureModelsHint: 'Fill in limits from the endpoint and image/thinking capabilities from the model capability table for every listed model',
+ fetchingConfig: 'Fetching…',
+ configUnreachable: 'Could not read the model list: {detail}',
+ configNoneApplied: 'Neither the endpoint nor the capability table had anything to write for these models.',
+ configApplied: 'Configured {n} model(s).',
+ configUndisclosed: '{n} model(s) were not disclosed by the endpoint.',
+}
+
+export type ModelsKey = keyof typeof en
+
+export const zh: { [Key in keyof typeof en]: string } = {
+ nav: '模型',
+ title: '模型',
+ intro: '填入各提供方的 API 密钥即可使用其模型。',
+ edit: '编辑',
+ editProvider: '编辑 {provider}',
+ remove: '删除',
+ removeProvider: '删除 {provider}',
+ deleteTitle: '删除 {provider}?',
+ deleteDescription: '删除 {provider} 会移除其配置;其使用的凭证(如有)由其他位置管理,将会保留。',
+ deleteDescriptionWithCredential: '删除 {provider} 会移除其配置和存储的 API 密钥。',
+ deleteConfirm: '删除 {provider}',
+ deleting: '正在删除 {provider}…',
+ add: '添加提供方',
+ provider: '提供方',
+ close: '关闭',
+ cancel: '取消',
+ apply: '保存',
+ applying: '保存中…',
+ savedProvider: '已保存 {provider}。',
+ credentialConfigured: 'API 密钥已配置',
+ credentialMissing: 'API 密钥缺失',
+ readOnly: '当前部署的设置文档为只读。',
+ loadFailed: '加载提供方目录失败',
+ conflict: '这张卡片打开期间,这些设置已被其他地方改动。请关闭后重新打开,在当前值上编辑。',
+ retry: '重试',
+ keyInput: 'API 密钥',
+ keyPlaceholder: '输入 API 密钥',
+ keyPlaceholderNative: '输入 API 密钥,或留空使用环境认证',
+ keyStored: '已配置——输入新值可替换',
+ keyEnvLocked: '由启动环境提供(只读)',
+ customized: '自定义设置',
+ baseUrl: 'API 地址',
+ baseUrlDefault: '提供方默认',
+ models: '模型目录',
+ modelsInherited: '正在使用适配器默认模型',
+ modelsCustomized: '已自定义模型目录',
+ resetModels: '恢复默认模型',
+ model: '模型',
+ modelId: '模型 ID',
+ modelName: '显示名称',
+ modelNamePlaceholder: '留空时使用模型 ID',
+ contextWindow: '上下文窗口',
+ contextWindowPlaceholder: '使用提供方默认值',
+ maxTokens: '最大输出 token 数',
+ maxTokensPlaceholder: '使用提供方默认值',
+ modelAdvanced: '容量',
+ addModel: '添加模型',
+ removeModel: '删除模型',
+ modelsEmpty: '模型选择器中将不显示任何模型;目录外 ID 仍可直接发送。',
+ keyBlank: '请输入 API 密钥;留空则保持已存储的密钥。',
+ keyBlankNew: '请输入 API 密钥;若该提供方以其他方式鉴权,可以留空。',
+ keyIllegalCharacters: '该 API 密钥格式错误,请检查。',
+ modelIdRequired: '模型 ID 不能为空。',
+ modelIdDuplicate: '模型 ID 不能重复。',
+ modelNameInvalid: '显示名称不能为空。',
+ modelContextInvalid: '上下文窗口必须是正数,例如 131072、256K 或 1M。',
+ modelMaxTokensInvalid: '最大输出 token 数必须是正数,例如 8192、64K 或 1M。',
+ advancedHint: '其余字段在 settings.yaml 中,请直接编辑对应段。',
+ modelCapacityInvalid: '容量需为数字,可加 K 或 M 后缀。',
+ modelDuplicate: '每个模型 ID 只能出现一次。',
+ modelContextWindow: '上下文窗口',
+ modelMaxTokens: '最大输出 token',
+ fetchModels: '获取可用模型',
+ fetching: '正在询问提供方\u2026',
+ fetchNeedsBaseUrl: '请先填写 API 地址,再获取。',
+ fetchEmpty: '该提供方没有列出任何模型,请手动添加。',
+ fetchTitle: '选择要添加的模型',
+ fetchDescription: '以下是模型提供方的可用模型,勾选要添加的模型。',
+ fetchSearch: '搜索模型',
+ fetchNoMatches: '没有匹配的模型。',
+ fetchSelectAll: '全选',
+ fetchDeselectAll: '取消全选',
+ fetchAdopt: '添加所选',
+ customAdd: '添加自定义提供方',
+ customTitle: '自定义提供方',
+ customTag: '自定义',
+ customRoute: 'Provider ID',
+ customRouteHint: '以小写字母开头的标识,在请求中唯一标识该提供方,并用于派生凭据名。',
+ customRouteInvalid: '需以小写字母开头,之后可用小写字母、数字和短横线。',
+ customRouteTaken: '已有提供方使用了这个 ID。',
+ customDisplayName: '显示名称',
+ customApi: 'API 协议',
+ customApiUnset: '未选择',
+ customNeedsBaseUrl: '自定义提供方需要填写 API 地址。',
+ customBaseUrlInvalid: '请输入有效的 HTTP 或 HTTPS 地址。',
+ customNeedsModels: '自定义提供方至少需要一个模型。',
+ customBaseUrlPlaceholder: 'https://gateway.example/v1',
+ settingsPathUnresolvable: '无法解析设置路径',
+ create: '创建提供方',
+ creating: '创建中\u2026',
+ welcomeTitle: '内测声明',
+ welcomeBody: 'DeepSeek Harness 目前的 0.1 版本仍处在面向 Harness 开发者进行测试的阶段,还有许多地方需要持续改进和打磨,希望听取广大开发者的反馈建议。预计 DeepSeek Harness 的核心插件以及基础 API 都会在接下来的一段时间内快速迭代、持续演化。\n\n我们期待与全球开发者一起,在开源、开放、可复用、可组合的基础设施之上,共同探索智能上限。欢迎全球 Harness 开发者加入 DSH 插件生态。',
+ welcomeContinue: '继续',
+ welcomeError: '暂时无法保存确认状态,请重试。',
+ onboardingTitle: '添加一个 API Key 开始使用',
+ onboardingDescription: '配置 DeepSeek 官方模型,即可开始使用。',
+ onboardingLater: '稍后配置',
+ onboardingSave: '保存并继续',
+ onboardingSaving: '保存中…',
+ keyRequired: '请输入 API 密钥后继续。',
+ openConfigFile: '打开配置文件',
+ openConfigFileHint: '打开承载全部模型定义的设置文件',
+ openConfigFileLanded: '已打开 {path}',
+ openConfigFileDirectory: '配置文件尚未创建,已改为打开 {path}',
+ openConfigFileFailed: '无法打开配置文件,请确认编辑器已安装,或在“文本编辑器”中更换:{detail}',
+ textEditor: '文本编辑器',
+ textEditorHint: '此设置仅用于模型页面的“打开配置文件”。',
+ editorVSCode: 'VS Code',
+ editorCursor: 'Cursor',
+ editorSystem: '系统默认(推荐)',
+ editorCustom: '自定义编辑器',
+ editorCommand: '应用名称或可执行文件路径',
+ editorCommandPlaceholder: '应用名称、.app 路径或可执行文件路径',
+ editorCommandHint: 'macOS 可填写应用名称或 .app 路径;Windows 请填写 .exe 完整路径;Linux 可填写程序名称或路径。无需引号,请勿附加启动参数。',
+ editorLoadFailed: '无法读取编辑器设置:{detail}',
+ editorSaveFailed: '无法保存编辑器设置:{detail}',
+ imageInput: '图片输入',
+ imageInputHint: '声明该模型是否接受图片内容',
+ thinkingMode: '思考模式',
+ thinkingLevels: '思考档位',
+ thinkingModeHint: '声明该模型是否支持思考,并勾选它提供的档位',
+ developerRole: '关闭 Developer 角色',
+ developerRoleHint: '端点是本地部署这类不认 developer 角色时打开:系统提示保持 system,思考档位改从 chat_template_kwargs 下发;开启后写入 compat:supportsDeveloperRole=false、thinkingFormat=chat-template、chatTemplateKwargs.reasoning_effort={$var: thinking.effort}',
+ fetchModelConfig: '获取配置',
+ fetchModelConfigHint: '从提供方端点读取该模型的上下文与输出上限,并按模型能力表补齐图片与思考档位',
+ autoConfigureModels: '自动配置所有模型',
+ autoConfigureModelsHint: '为列表中每个模型从端点读取上限,并按模型能力表补齐图片与思考档位',
+ fetchingConfig: '获取中…',
+ configUnreachable: '无法读取模型列表:{detail}',
+ configNoneApplied: '端点与模型能力表都没有为这些模型提供可写入的配置。',
+ configApplied: '已配置 {n} 个模型。',
+ configUndisclosed: '{n} 个模型未被端点披露。',
+}
diff --git a/archiving/dsh-tauri-model-config/src/client/models/operations.ts b/archiving/dsh-tauri-model-config/src/client/models/operations.ts
new file mode 100644
index 00000000..aafc30d3
--- /dev/null
+++ b/archiving/dsh-tauri-model-config/src/client/models/operations.ts
@@ -0,0 +1,69 @@
+import type {
+ ClientRemote,
+ CredentialInfo,
+ LlmDiscoveredModel,
+ LlmModelDiscoveryRequest,
+ SettingsNamespaceView,
+ SettingsPathOpView,
+} from '../types/remotes.ts'
+
+export type SettingsWriteOutcome
+
+ = | { readonly kind: 'written', readonly view: SettingsNamespaceView }
+
+ | { readonly kind: 'conflict', readonly message: string }
+
+ | { readonly kind: 'refused', readonly message: string }
+
+export type ModelDiscoveryOutcome
+
+ = | { readonly kind: 'found', readonly models: readonly LlmDiscoveredModel[] }
+
+ | { readonly kind: 'refused', readonly message: string }
+
+export interface ModelsOperations {
+
+ describeCredential: (ref: string) => Promise<CredentialInfo | undefined>
+
+ storeCredential: (ref: string, value: string) => Promise<string | undefined>
+
+ removeCredential: (ref: string) => Promise<string | undefined>
+
+ writeSettings: (
+ ns: string,
+ ops: SettingsPathOpView[],
+ expectedRevision: number | undefined,
+ ) => Promise<SettingsWriteOutcome>
+
+ discoverModels: (settingsNs: string, request: LlmModelDiscoveryRequest) => Promise<ModelDiscoveryOutcome>
+}
+
+export function createModelsOperations(remote: ClientRemote): ModelsOperations {
+ return {
+ describeCredential: async (ref) => {
+ const response = await remote.credentials.describe([ref])
+ return response.ok ? response.value[ref] : undefined
+ },
+ storeCredential: async (ref, value) => {
+ const response = await remote.credentials.set(ref, value)
+ return response.ok ? undefined : response.error.message
+ },
+ removeCredential: async (ref) => {
+ const response = await remote.credentials.unset(ref)
+ return response.ok ? undefined : response.error.message
+ },
+ writeSettings: async (ns, ops, expectedRevision) => {
+ const response = await remote.settings.mutate(ns, ops, expectedRevision)
+ if (response.ok)
+ return { kind: 'written', view: response.value }
+ const { code, message } = response.error
+ return code === 'settings/conflict' ? { kind: 'conflict', message } : { kind: 'refused', message }
+ },
+ discoverModels: async (settingsNs, request) => {
+ const response = await remote.llm.discoverModels(settingsNs, request)
+ return response.ok
+ ? { kind: 'found', models: response.value }
+ : { kind: 'refused', message: response.error.message }
+ },
+ }
+}
diff --git a/archiving/dsh-tauri-model-config/src/client/models/schema-operations.ts b/archiving/dsh-tauri-model-config/src/client/models/schema-operations.ts
new file mode 100644
index 00000000..8aeb4019
--- /dev/null
+++ b/archiving/dsh-tauri-model-config/src/client/models/schema-operations.ts
@@ -0,0 +1,20 @@
+import type {
+ SettingsSchemaService,
+} from '@deepseek-ai/dsh-client-ui-settings/client'
+
+export type SettingsSchemaOperations = Pick<
+ SettingsSchemaService,
+ 'rehydrate' | 'validate' | 'nodeAtPath' | 'getPath' | 'hasPath' | 'setPath' | 'deletePath'
+>
+
+export function createSettingsSchemaOperations(service: SettingsSchemaService): SettingsSchemaOperations {
+ return {
+ rehydrate: serialized => service.rehydrate(serialized),
+ validate: (schema, draft) => service.validate(schema, draft),
+ nodeAtPath: (root, path) => service.nodeAtPath(root, path),
+ getPath: (value, path) => service.getPath(value, path),
+ hasPath: (value, path) => service.hasPath(value, path),
+ setPath: (root, path, value) => service.setPath(root, path, value),
+ deletePath: (root, path) => service.deletePath(root, path),
+ }
+}
diff --git a/archiving/dsh-tauri-model-config/src/client/models/settings-forms.ts b/archiving/dsh-tauri-model-config/src/client/models/settings-forms.ts
new file mode 100644
index 00000000..721c4e29
--- /dev/null
+++ b/archiving/dsh-tauri-model-config/src/client/models/settings-forms.ts
@@ -0,0 +1,54 @@
+import type { SettingsDescribeFace } from '@deepseek-ai/dsh-client-ui-settings/client'
+import type { WelcomeSettingsForm } from './welcome-store.ts'
+import {
+ WELCOME_NOTICE_SETTINGS_NAMESPACE,
+ WELCOME_NOTICE_SETTINGS_NAMESPACE_LEGACY,
+} from '../../shared/onboarding-copy.ts'
+import { decodeWelcomeSection } from './welcome-store.ts'
+
+/** ≥0.1.7 的 `ctx.configForms`(源文件 `config-form.ts`)。 */
+interface ConfigFormsLike {
+ describe: () => SettingsDescribeFace
+ get: (namespace: string) => WelcomeSettingsForm
+}
+
+/** ≤0.1.6 的 `ctx.settingsScope`。 */
+interface SettingsScopeLike {
+ describe: () => SettingsDescribeFace
+ bind: (spec: { namespace: string, decode: (section: unknown) => Record<string, unknown> }) => WelcomeSettingsForm
+}
+
+/** 模型页所需的设置读写面,已抹平两代内核的服务名与绑定方式差异。 */
+export interface ModelsForms {
+ describe: SettingsDescribeFace
+ welcome: WelcomeSettingsForm
+}
+
+/** 只需要 cordis 的服务查询面,避免依赖 ctx 的宿主/客户端增广差异。 */
+export interface ServiceLookup {
+ get: (name: string) => unknown
+}
+
+/**
+ * 探测并解析设置命名空间服务。`configForms` 优先;缺席时退回 `settingsScope`
+ * 及其 `bind({namespace, decode})` 绑定形式,并换用该代的欢迎确认命名空间。
+ */
+export function resolveModelsForms(ctx: ServiceLookup): ModelsForms | undefined {
+ const forms = ctx.get('configForms') as ConfigFormsLike | undefined
+ if (forms !== undefined) {
+ return {
+ describe: forms.describe(),
+ welcome: forms.get(WELCOME_NOTICE_SETTINGS_NAMESPACE),
+ }
+ }
+ const scope = ctx.get('settingsScope') as SettingsScopeLike | undefined
+ if (scope === undefined)
+ return undefined
+ return {
+ describe: scope.describe(),
+ welcome: scope.bind({
+ namespace: WELCOME_NOTICE_SETTINGS_NAMESPACE_LEGACY,
+ decode: decodeWelcomeSection,
+ }),
+ }
+}
diff --git a/archiving/dsh-tauri-model-config/src/client/models/slot-contract.ts b/archiving/dsh-tauri-model-config/src/client/models/slot-contract.ts
new file mode 100644
index 00000000..41d691ec
--- /dev/null
+++ b/archiving/dsh-tauri-model-config/src/client/models/slot-contract.ts
@@ -0,0 +1,25 @@
+import type {} from '@deepseek-ai/dsh-client-ui-slots'
+import type { ProviderDirectoryEntry } from './store.ts'
+
+declare module '@deepseek-ai/dsh-client-ui-slots' {
+ interface SlotMap {
+
+ 'settings.models.provider-card': { kind: 'keyed', scope: 'root', owner: ProviderCardExtrasOwnerProps }
+
+ 'settings.models.footer': { kind: 'list', scope: 'root', owner: ModelsFooterOwnerProps }
+ }
+}
+
+export interface ProviderCardExtrasOwnerProps {
+
+ provider: ProviderDirectoryEntry
+
+ configured: boolean
+
+ keyConfigured: boolean
+}
+
+export interface ModelsFooterOwnerProps {
+
+ children?: never
+}
diff --git a/archiving/dsh-tauri-model-config/src/client/models/store.ts b/archiving/dsh-tauri-model-config/src/client/models/store.ts
new file mode 100644
index 00000000..2babb02a
--- /dev/null
+++ b/archiving/dsh-tauri-model-config/src/client/models/store.ts
@@ -0,0 +1,283 @@
+import type { SnapshotStore } from '@deepseek-ai/dsh-client-store'
+import type { SettingsDescribeFace } from '@deepseek-ai/dsh-client-ui-settings/client'
+import type {
+ ClientRemote,
+ CredentialInfo,
+ LlmConfigurableProvider,
+ LlmProviderInfo,
+ SettingsNamespaceView,
+} from '../types/remotes.ts'
+import type { SettingsSchemaOperations } from './schema-operations.ts'
+import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
+
+const PROBE_ROUTE = '\u0000probe'
+
+export interface ProviderDirectoryEntry {
+ readonly provider: string
+ readonly displayName: string
+ readonly settingsNs: string
+ readonly settingsPath: readonly string[]
+ readonly active: boolean
+ readonly declared?: boolean
+ readonly error?: string
+}
+
+export function joinProviderDirectory(
+ registered: readonly LlmProviderInfo[],
+ directory: readonly LlmConfigurableProvider[],
+): ProviderDirectoryEntry[] {
+ const active = new Set(registered.map(provider => provider.id))
+ const declared = new Set(directory.map(entry => entry.provider))
+ const rows: ProviderDirectoryEntry[] = directory.map(entry => ({
+ provider: entry.provider,
+ displayName: entry.displayName,
+ settingsNs: entry.settingsNs,
+ settingsPath: [...entry.settingsPath],
+ active: active.has(entry.provider),
+ ...entry.declared === undefined ? {} : { declared: entry.declared },
+ ...entry.error === undefined ? {} : { error: entry.error },
+ }))
+ for (const provider of registered) {
+ if (declared.has(provider.id))
+ continue
+ rows.push({
+ provider: provider.id,
+ displayName: provider.name,
+ settingsNs: '',
+ settingsPath: [],
+ active: true,
+ })
+ }
+ return rows
+}
+
+export interface ProviderRow {
+
+ entry: ProviderDirectoryEntry
+
+ configured: boolean
+
+ removable: boolean
+
+ apiKeyEnv: string | undefined
+
+ credential: CredentialInfo | undefined
+
+ derivedCredential?: CredentialInfo
+}
+
+export interface ModelsSettingsState {
+ status: 'idle' | 'loading' | 'ready' | 'error'
+
+ error: string | null
+
+ credentialError: string | null
+
+ writable: boolean
+
+ rows: readonly ProviderRow[]
+
+ namespaces: ReadonlyMap<string, SettingsNamespaceView>
+}
+
+export function deriveKeyRef(provider: string): string {
+ return `${provider.toUpperCase().replace(/[^A-Z0-9]+/g, '_')}_API_KEY`
+}
+
+export function protocolChoices(
+ namespace: SettingsNamespaceView | undefined,
+ schema: SettingsSchemaOperations,
+): string[] {
+ if (namespace === undefined)
+ return []
+ const node = schema.nodeAtPath(schema.rehydrate(namespace.schema), ['providers', PROBE_ROUTE, 'api'])
+ const list = node as { type?: string, list?: readonly { value?: unknown }[] } | undefined
+ if (list?.type !== 'union' || list.list === undefined)
+ return []
+ return list.list.map(entry => entry.value).filter((value): value is string => typeof value === 'string')
+}
+
+function apiKeyEnvOf(
+ namespace: SettingsNamespaceView | undefined,
+ path: readonly string[],
+ schema: SettingsSchemaOperations,
+): string | undefined {
+ if (namespace === undefined)
+ return undefined
+ const profile = schema.getPath(namespace.value, path)
+ if (typeof profile !== 'object' || profile === null)
+ return undefined
+ const ref = (profile as { apiKeyEnv?: unknown }).apiKeyEnv
+ return typeof ref === 'string' && ref.length > 0 ? ref : undefined
+}
+
+export class ModelsSettingsStore {
+ readonly store: SnapshotStore<ModelsSettingsState> = createSnapshotStore<ModelsSettingsState>({
+ status: 'idle',
+ error: null,
+ credentialError: null,
+ writable: false,
+ rows: [],
+ namespaces: new Map(),
+ })
+
+ private generation = 0
+
+ constructor(
+ private readonly remote: ClientRemote,
+ private readonly schema: SettingsSchemaOperations,
+ private readonly describeFace: SettingsDescribeFace,
+ ) {}
+
+ async load(): Promise<void> {
+ const generation = ++this.generation
+ this.store.update((s) => {
+ s.status = 'loading'
+ s.error = null
+ })
+ const [registered, declared] = await Promise.all([
+ this.remote.llm.listProviders(),
+ this.remote.llm.listConfigurableProviders(),
+ this.describeFace.ensure(),
+ ])
+ if (!registered.ok) {
+ this.failLoad(generation, registered.error.message)
+ return
+ }
+ if (!declared.ok) {
+ this.failLoad(generation, declared.error.message)
+ return
+ }
+ const mirrored = this.describeFace.getSnapshot()
+ if (mirrored.view === undefined) {
+ this.failLoad(generation, mirrored.error ?? 'settings are unavailable in this browser')
+ return
+ }
+ const providers = joinProviderDirectory(registered.value, declared.value)
+ const writable = mirrored.view.writable
+ const views: readonly SettingsNamespaceView[] = mirrored.view.namespaces
+ const namespaces = new Map(views.map(view => [view.ns, view]))
+ const rows: ProviderRow[] = providers.map((entry) => {
+ const namespace = namespaces.get(entry.settingsNs)
+ const configured = namespace !== undefined
+ && (entry.settingsPath.length === 0 || this.schema.getPath(namespace.value, entry.settingsPath) !== undefined)
+ const removable = namespace !== undefined
+ && entry.settingsPath.length > 0
+ && this.schema.hasPath(namespace.user, entry.settingsPath)
+ && !this.schema.hasPath(namespace.base, entry.settingsPath)
+ return {
+ entry,
+ configured,
+ removable,
+ apiKeyEnv: apiKeyEnvOf(namespace, entry.settingsPath, this.schema),
+ credential: undefined,
+ }
+ })
+ const refs = [...new Set(rows.map(row => row.apiKeyEnv ?? deriveKeyRef(row.entry.provider)))]
+ let credentials: Record<string, CredentialInfo> = {}
+ let credentialError: string | null = null
+ if (refs.length > 0) {
+ const response = await this.remote.credentials.describe(refs)
+
+ if (response.ok)
+ credentials = response.value
+ else credentialError = response.error.message
+ }
+ if (generation !== this.generation)
+ return
+ this.store.update((s) => {
+ s.status = 'ready'
+ s.error = null
+ s.credentialError = credentialError
+ s.writable = writable
+ s.rows = rows.map((row) => {
+ const named = row.apiKeyEnv === undefined ? undefined : credentials[row.apiKeyEnv]
+ const derived = row.apiKeyEnv !== undefined ? undefined : credentials[deriveKeyRef(row.entry.provider)]
+ return {
+ ...row,
+ ...named === undefined ? {} : { credential: named },
+ ...derived === undefined ? {} : { derivedCredential: derived },
+ }
+ })
+ s.namespaces = namespaces
+ })
+ }
+
+ private failLoad(generation: number, message: string): void {
+ if (generation !== this.generation)
+ return
+ this.store.update((s) => {
+ s.status = 'error'
+ s.error = message
+ })
+ }
+}
+
+export function providerUsable(row: ProviderRow): boolean {
+ if (!row.entry.active)
+ return false
+ if (row.apiKeyEnv === undefined)
+ return true
+ return row.credential?.configured === true
+}
+
+export type OnboardingReadiness
+ = | { kind: 'loading' }
+ | { kind: 'adapter-absent' }
+ | { kind: 'provider-ready' }
+ | { kind: 'credential-missing' }
+ | {
+ kind: 'unavailable'
+ reason:
+ | 'load-failed'
+ | 'provider-inactive'
+ | 'credentials-unavailable'
+ | 'settings-read-only'
+ | 'credential-read-only'
+ }
+
+export function onboardingReadiness(state: ModelsSettingsState): OnboardingReadiness {
+ if ((state.status === 'idle' || state.status === 'loading') && state.rows.length === 0) {
+ return { kind: 'loading' }
+ }
+ if (state.status === 'error') {
+ return {
+ kind: 'unavailable',
+ reason: 'load-failed',
+ }
+ }
+ if (state.rows.some(providerUsable))
+ return { kind: 'provider-ready' }
+ const row = state.rows.find(candidate =>
+ candidate.entry.provider === 'deepseek-official'
+ && candidate.entry.settingsNs === 'llm-deepseek'
+ && candidate.entry.settingsPath.length === 0)
+ if (row === undefined)
+ return { kind: 'adapter-absent' }
+ if (!row.entry.active) {
+ return {
+ kind: 'unavailable',
+ reason: 'provider-inactive',
+ }
+ }
+
+ if (state.credentialError !== null || row.credential === undefined) {
+ return {
+ kind: 'unavailable',
+ reason: 'credentials-unavailable',
+ }
+ }
+ if (!state.writable) {
+ return {
+ kind: 'unavailable',
+ reason: 'settings-read-only',
+ }
+ }
+ if (!row.credential.writable) {
+ return {
+ kind: 'unavailable',
+ reason: 'credential-read-only',
+ }
+ }
+ return { kind: 'credential-missing' }
+}
diff --git a/archiving/dsh-tauri-model-config/src/client/models/styles.ts b/archiving/dsh-tauri-model-config/src/client/models/styles.ts
new file mode 100644
index 00000000..3ae825f3
--- /dev/null
+++ b/archiving/dsh-tauri-model-config/src/client/models/styles.ts
@@ -0,0 +1,104 @@
+import { cssr } from 'dsh-tauri-ui/client'
+
+const { c } = cssr
+
+const MODELS_CSS = '.zGbnIq_section {\n display: flex;\n flex-direction: column;\n gap: 12px;\n max-width: 720px;\n color: var(--dsw-alias-label-primary);\n}\n\n.zGbnIq_title {\n margin: 0;\n font-size: 16px;\n line-height: 24px;\n font-weight: 500;\n color: var(--dsw-alias-label-primary);\n}\n\n.zGbnIq_intro {\n margin: 0;\n font-size: 14px;\n line-height: 22px;\n color: var(--dsw-alias-label-tertiary);\n}\n\n.zGbnIq_notice {\n margin: 0;\n font-size: 12px;\n line-height: 18px;\n color: var(--dsw-alias-state-warn-label);\n}\n\n.zGbnIq_savedNotice {\n margin: 0;\n font-size: 12px;\n line-height: 18px;\n color: var(--dsw-alias-state-success-primary);\n}\n\n.zGbnIq_rows {\n list-style: none;\n \n margin: 12px 0 0;\n padding: 0;\n display: flex;\n flex-direction: column;\n gap: 8px;\n}\n\n\n.zGbnIq_rowCard {\n border: 0.5px solid var(--dsw-alias-border-l4);\n border-radius: 16px;\n padding: 12px 14px;\n display: flex;\n flex-direction: column;\n gap: 12px;\n}\n\n.zGbnIq_rowHead {\n display: flex;\n align-items: center;\n gap: 10px;\n}\n\n.zGbnIq_rowIdentity {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n min-width: 0;\n}\n\n.zGbnIq_rowName {\n font-size: 14px;\n line-height: 22px;\n font-weight: 500;\n color: var(--dsw-alias-label-primary);\n}\n\n\n.zGbnIq_rowTag {\n flex: none;\n padding: 1px 6px;\n border: 0.5px solid var(--dsw-alias-border-l3);\n border-radius: 4px;\n font-size: 11px;\n line-height: 16px;\n color: var(--dsw-alias-label-secondary);\n}\n\n.zGbnIq_credentialDot {\n box-sizing: border-box;\n display: inline-block;\n flex: none;\n width: 8px;\n height: 8px;\n border-radius: 50%;\n corner-shape: round;\n}\n\n.zGbnIq_credentialDotConfigured {\n background: var(--dsw-alias-state-success-primary);\n}\n\n.zGbnIq_credentialDotMissing {\n background: var(--dsw-alias-state-error-primary);\n}\n\n.zGbnIq_rowActions {\n display: inline-flex;\n align-items: center;\n gap: 4px;\n margin-left: auto;\n}\n\n\n.zGbnIq_primaryButton,\n.zGbnIq_secondaryButton,\n.zGbnIq_addButton {\n box-sizing: border-box;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n gap: 4px;\n height: 36px;\n padding: 0 14px;\n border: none;\n border-radius: 18px;\n font: inherit;\n font-size: 14px;\n line-height: 22px;\n cursor: pointer;\n}\n\n.zGbnIq_primaryButton {\n background: var(--dsw-alias-button-primary-fill);\n color: var(--dsw-alias-label-primary-foreground);\n}\n\n.zGbnIq_primaryButton:hover:not(:disabled) {\n background: var(--dsw-alias-button-primary-hover);\n}\n\n.zGbnIq_secondaryButton,\n.zGbnIq_addButton {\n border: 0.5px solid var(--dsw-alias-border-l3);\n background: transparent;\n color: var(--dsw-alias-label-primary);\n}\n\n.zGbnIq_secondaryButton:hover:not(:disabled),\n.zGbnIq_addButton:hover:not(:disabled) {\n background: var(--dsw-alias-interactive-bg-hover);\n}\n\n.zGbnIq_secondaryButton:hover:not(:disabled) {\n background: var(--dsw-alias-interactive-bg-hover-solid);\n}\n\n.zGbnIq_dangerButton {\n box-sizing: border-box;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n height: 36px;\n padding: 0 14px;\n border: none;\n border-radius: 18px;\n background: transparent;\n color: var(--dsw-alias-state-error-primary);\n font: inherit;\n font-size: 14px;\n line-height: 22px;\n cursor: pointer;\n}\n\n.zGbnIq_dangerButton:hover:not(:disabled) {\n background: var(--dsw-alias-interactive-bg-hover-danger);\n}\n\n\n.zGbnIq_rowActions .zGbnIq_secondaryButton,\n.zGbnIq_rowActions .zGbnIq_dangerButton {\n height: 28px;\n padding: 0 10px;\n border-radius: 14px;\n font-size: 12px;\n line-height: 18px;\n}\n\n.zGbnIq_primaryButton:disabled,\n.zGbnIq_secondaryButton:disabled,\n.zGbnIq_dangerButton:disabled,\n.zGbnIq_addButton:disabled,\n.zGbnIq_linkButton:disabled,\n.zGbnIq_addModelButton:disabled {\n opacity: 0.4;\n cursor: default;\n}\n\n.zGbnIq_primaryButton:focus-visible,\n.zGbnIq_secondaryButton:focus-visible,\n.zGbnIq_dangerButton:focus-visible,\n.zGbnIq_addButton:focus-visible,\n.zGbnIq_linkButton:focus-visible,\n.zGbnIq_addModelButton:focus-visible,\n.zGbnIq_iconButton:focus-visible,\n.zGbnIq_customizedSummary:focus-visible {\n outline: none;\n box-shadow: 0 0 0 2px var(--dsw-alias-border-l3);\n}\n\n\n.zGbnIq_editor {\n border-radius: 12px;\n background: var(--dsw-alias-bg-module-platform);\n padding: 14px 16px;\n display: flex;\n flex-direction: column;\n gap: 14px;\n}\n\n.zGbnIq_editorHeader {\n display: flex;\n align-items: baseline;\n gap: 8px;\n}\n\n.zGbnIq_editorTitle {\n font-size: 14px;\n line-height: 22px;\n font-weight: 500;\n color: var(--dsw-alias-label-primary);\n}\n\n.zGbnIq_editorRoute {\n font-size: 12px;\n line-height: 18px;\n color: var(--dsw-alias-label-tertiary);\n}\n\n.zGbnIq_field {\n display: flex;\n flex-direction: column;\n gap: 6px;\n}\n\n.zGbnIq_fieldLabel {\n display: inline-flex;\n align-items: center;\n gap: 10px;\n font-size: 12px;\n line-height: 18px;\n font-weight: 500;\n color: var(--dsw-alias-label-secondary);\n}\n\n.zGbnIq_linkButton {\n box-sizing: border-box;\n display: inline-flex;\n align-items: center;\n height: 28px;\n padding: 0 10px;\n border: none;\n border-radius: 14px;\n background: transparent;\n color: var(--dsw-alias-label-tertiary);\n font: inherit;\n font-size: 12px;\n line-height: 18px;\n cursor: pointer;\n}\n\n.zGbnIq_linkButton:hover:not(:disabled) {\n background: var(--dsw-alias-interactive-bg-hover);\n color: var(--dsw-alias-label-secondary);\n}\n\n.zGbnIq_advancedHint {\n margin: 0;\n font-size: 12px;\n line-height: 18px;\n color: var(--dsw-alias-label-tertiary);\n}\n\n.zGbnIq_editorActions {\n display: flex;\n justify-content: flex-end;\n gap: 8px;\n}\n\n.zGbnIq_addBlock {\n display: flex;\n flex-direction: column;\n gap: 12px;\n}\n\n\n.zGbnIq_addActions {\n display: flex;\n flex-wrap: wrap;\n gap: 10px;\n}\n\n.zGbnIq_addButton {\n \n flex: 1 1 0;\n min-width: 180px;\n gap: 6px;\n height: 44px;\n border: 1px dashed var(--dsw-alias-border-l3);\n border-radius: 16px;\n}\n\n.zGbnIq_addCard,\n.zGbnIq_setupCard {\n border-radius: 12px;\n background: var(--dsw-alias-bg-module-platform);\n padding: 14px 16px;\n display: flex;\n flex-direction: column;\n gap: 14px;\n list-style: none;\n}\n\n\n.zGbnIq_addCard .zGbnIq_editor,\n.zGbnIq_setupCard .zGbnIq_editor {\n background: none;\n padding: 0;\n}\n\n.zGbnIq_customized {\n border-top: 0.5px solid var(--dsw-alias-border-l2);\n padding-top: 10px;\n}\n\n\n.zGbnIq_customizedSummary {\n display: flex;\n align-items: center;\n gap: 6px;\n width: fit-content;\n padding: 2px 4px;\n margin-left: -4px;\n border-radius: 6px;\n cursor: pointer;\n font-size: 12px;\n line-height: 18px;\n font-weight: 500;\n color: var(--dsw-alias-label-secondary);\n list-style: none;\n}\n\n.zGbnIq_customizedSummary::-webkit-details-marker {\n display: none;\n}\n\n.zGbnIq_customizedSummary::before {\n content: \'\';\n width: 5px;\n height: 5px;\n border-right: 1.5px solid currentcolor;\n border-bottom: 1.5px solid currentcolor;\n transform: rotate(-45deg) translate(-1px, -1px);\n transition: transform 120ms ease;\n}\n\n.zGbnIq_customized[open] > .zGbnIq_customizedSummary::before {\n transform: rotate(45deg) translate(-1px, -1px);\n}\n\n.zGbnIq_customizedSummary:hover {\n color: var(--dsw-alias-label-primary);\n}\n\n.zGbnIq_customizedBody {\n display: flex;\n flex-direction: column;\n gap: 12px;\n padding-top: 12px;\n}\n\n\n.zGbnIq_modelCatalog {\n display: flex;\n flex-direction: column;\n gap: 10px;\n padding-top: 12px;\n border-top: 0.5px solid var(--dsw-alias-border-l2);\n}\n\n.zGbnIq_modelCatalogHeading {\n display: flex;\n flex-direction: column;\n gap: 2px;\n}\n\n.zGbnIq_modelCatalogTitle {\n font-size: 12px;\n line-height: 18px;\n font-weight: 500;\n color: var(--dsw-alias-label-secondary);\n}\n\n.zGbnIq_modelCatalogMeta,\n.zGbnIq_modelEmpty {\n margin: 0;\n color: var(--dsw-alias-label-tertiary);\n font-size: 12px;\n line-height: 18px;\n}\n\n\n.zGbnIq_modelList {\n display: flex;\n flex-direction: column;\n gap: 8px;\n}\n\n.zGbnIq_modelListHead {\n display: flex;\n align-items: flex-start;\n justify-content: space-between;\n gap: 12px;\n}\n\n.zGbnIq_modelEntry {\n border: 0.5px solid var(--dsw-alias-border-l4);\n border-radius: 10px;\n padding: 6px;\n}\n\n.zGbnIq_modelRow {\n display: grid;\n grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr) auto auto;\n align-items: center;\n gap: 6px;\n}\n\n\n.zGbnIq_iconButton {\n box-sizing: border-box;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: 28px;\n height: 28px;\n border: none;\n border-radius: 6px;\n background: transparent;\n color: var(--dsw-alias-label-tertiary);\n cursor: pointer;\n}\n\n.zGbnIq_iconButton:hover:not(:disabled) {\n background: var(--dsw-alias-interactive-bg-hover);\n color: var(--dsw-alias-label-primary);\n}\n\n.zGbnIq_iconButton:disabled {\n cursor: default;\n opacity: 0.4;\n}\n\n\n.zGbnIq_iconButtonDanger:hover:not(:disabled) {\n background: var(--dsw-alias-interactive-bg-hover-danger);\n color: var(--dsw-alias-state-error-primary);\n}\n\n.zGbnIq_modelAdvanced {\n display: grid;\n grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));\n gap: 8px;\n padding: 8px 4px 2px;\n}\n\n.zGbnIq_modelField {\n display: flex;\n flex-direction: column;\n gap: 4px;\n}\n\n.zGbnIq_modelFieldLabel {\n color: var(--dsw-alias-label-tertiary);\n font-size: 12px;\n line-height: 18px;\n}\n\n.zGbnIq_modelEmpty {\n padding: 12px;\n border: 1px dashed var(--dsw-alias-border-l3);\n border-radius: 8px;\n text-align: center;\n}\n\n.zGbnIq_addModelButton {\n box-sizing: border-box;\n align-self: flex-start;\n display: inline-flex;\n align-items: center;\n gap: 4px;\n height: 28px;\n padding: 0 10px;\n border: 0.5px solid var(--dsw-alias-border-l3);\n border-radius: 14px;\n background: transparent;\n color: var(--dsw-alias-label-primary);\n font: inherit;\n font-size: 12px;\n line-height: 18px;\n cursor: pointer;\n}\n\n.zGbnIq_addModelButton:hover:not(:disabled) {\n background: var(--dsw-alias-interactive-bg-hover);\n}\n\n.zGbnIq_input {\n box-sizing: border-box;\n width: 100%;\n height: 32px;\n padding: 0 10px;\n border: 0.5px solid var(--dsw-alias-border-l4);\n border-radius: 8px;\n font: inherit;\n font-size: 14px;\n line-height: 22px;\n background: var(--dsw-alias-bg-layer-1);\n color: var(--dsw-alias-label-primary);\n}\n\n\nselect.zGbnIq_input {\n max-width: 240px;\n cursor: pointer;\n}\n\n.zGbnIq_input:focus {\n outline: none;\n border-color: var(--dsw-alias-brand-primary);\n}\n\n.zGbnIq_input::placeholder {\n color: var(--dsw-alias-label-dimmed);\n}\n\n.zGbnIq_input:disabled {\n opacity: 0.6;\n cursor: default;\n}\n\n\n.zGbnIq_selectInput {\n appearance: none;\n padding-right: 32px;\n \n background-image: url("data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' width=\'12\' height=\'12\' viewBox=\'0 0 12 12\' fill=\'none\'%3E%3Cpath d=\'M3 4.5L6 7.5L9 4.5\' stroke=\'%2381858C\' stroke-width=\'1.5\' stroke-linecap=\'round\' stroke-linejoin=\'round\'/%3E%3C/svg%3E");\n background-repeat: no-repeat;\n background-position: right 12px center;\n background-size: 12px 12px;\n}\n\n.zGbnIq_error {\n margin: 0;\n font-size: 12px;\n line-height: 18px;\n color: var(--dsw-alias-state-error-primary);\n}\n\n.zGbnIq_deleteDialog {\n width: min(480px, 100%);\n}\n\n.zGbnIq_deleteConfirm:not(:disabled) {\n border-color: var(--dsw-alias-state-error-primary);\n color: var(--dsw-alias-state-error-primary);\n}\n\n.zGbnIq_deleteConfirm:hover:not(:disabled) {\n background: var(--dsw-alias-interactive-bg-hover-danger);\n}\n\n\n.zGbnIq_hiddenLabel {\n position: absolute;\n width: 1px;\n height: 1px;\n overflow: hidden;\n clip: rect(0 0 0 0);\n white-space: nowrap;\n}\n\n@media (prefers-reduced-motion: reduce) {\n .zGbnIq_customizedSummary::before,\n .zGbnIq_switchThumb {\n transition: none;\n }\n}\n\n.zGbnIq_fetchDialog {\n max-width: 520px;\n\n \n --dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2);\n --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2);\n}\n\n.zGbnIq_candidateToolbar {\n display: flex;\n align-items: center;\n gap: 8px;\n margin-bottom: 6px;\n}\n\n.zGbnIq_candidateSearch {\n min-width: 0;\n flex: 1 1 240px;\n}\n\n.zGbnIq_candidateList {\n display: flex;\n flex-direction: column;\n gap: 2px;\n max-height: 320px;\n margin: 0;\n overflow-y: auto;\n padding: 0;\n list-style: none;\n}\n\n.zGbnIq_candidate {\n border-radius: 6px;\n}\n\n.zGbnIq_candidateLabel {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 6px 8px;\n cursor: pointer;\n}\n\n.zGbnIq_candidateId {\n flex: 1 1 auto;\n font-family: var(--ds-font-family-code);\n font-size: 13px;\n overflow-wrap: anywhere;\n}\n\n.zGbnIq_candidateEmpty {\n margin: 24px 0;\n color: var(--dsw-alias-label-secondary);\n font-size: 13px;\n line-height: 20px;\n text-align: center;\n}\n\n\n.zGbnIq_titleRow {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 12px;\n}\n\n.zGbnIq_modelCatalogHeading {\n flex: 1;\n}\n\n.zGbnIq_modelRow {\n grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto;\n}\n\n.zGbnIq_modelSwitchRow {\n display: flex;\n align-items: center;\n height: 32px;\n}\n\n.zGbnIq_modelEfforts {\n grid-column: 1 / -1;\n display: flex;\n flex-wrap: wrap;\n gap: 6px;\n}\n\n.zGbnIq_modelEffortChip {\n display: inline-flex;\n align-items: center;\n gap: 4px;\n height: 24px;\n padding: 0 8px;\n border: 0.5px solid var(--dsw-alias-border-l3);\n border-radius: 6px;\n font-size: 12px;\n line-height: 18px;\n color: var(--dsw-alias-label-secondary);\n cursor: pointer;\n}\n\n.zGbnIq_modelEffortChip:has(input:disabled) {\n opacity: 0.6;\n cursor: default;\n}\n\n.zGbnIq_modelEffortChip input {\n width: 12px;\n height: 12px;\n margin: 0;\n accent-color: var(--dsw-alias-brand-primary);\n}'
+
+const WELCOME_CSS = '.zGbnIqw_copy {\n font-size: 14px;\n line-height: 24px;\n color: var(--dsw-alias-label-secondary);\n}\n\n.zGbnIqw_copy p {\n margin: 0;\n}\n\n.zGbnIqw_copy p + p {\n margin-top: 12px;\n}\n\n.zGbnIqw_error {\n margin: 16px 0 0;\n font-size: 14px;\n line-height: 22px;\n color: var(--dsw-alias-state-error-primary);\n}\n\n.zGbnIqw_actions {\n display: flex;\n justify-content: flex-end;\n margin-top: 24px;\n}\n\n.zGbnIqw_primary {\n min-width: 120px;\n}\n\n@media (max-width: 560px) {\n .zGbnIqw_primary {\n width: 100%;\n }\n}'
+
+const ONBOARDING_CSS = '.zGbnIqo_dialog {\n width: min(600px, 100%);\n padding: 0;\n}\n\n.zGbnIqo_content {\n display: flex;\n flex-direction: column;\n max-height: calc(100vh - 48px);\n padding: 28px;\n box-sizing: border-box;\n overflow-y: auto;\n}\n\n.zGbnIqo_title {\n margin: 0;\n font-size: 20px;\n line-height: 28px;\n font-weight: 500;\n color: var(--dsw-alias-label-primary);\n outline: none;\n}\n\n.zGbnIqo_body {\n margin-top: 20px;\n}\n\n@media (max-width: 560px) {\n .zGbnIqo_content {\n padding: 24px;\n }\n}'
+
+const ONBOARDING_DIALOG_CSS = '.zGbnIqd_description {\n margin: 0;\n font-size: 14px;\n line-height: 24px;\n color: var(--dsw-alias-label-secondary);\n}\n\n.zGbnIqd_editor {\n margin-top: 24px;\n}\n\n@media (max-width: 560px) {\n .zGbnIqd_editor {\n margin-top: 20px;\n }\n}'
+
+export const modelStyles: Record<string, string> = {
+ addActions: 'zGbnIq_addActions',
+ addBlock: 'zGbnIq_addBlock',
+ addButton: 'zGbnIq_addButton',
+ addCard: 'zGbnIq_addCard',
+ addModelButton: 'zGbnIq_addModelButton',
+ advancedHint: 'zGbnIq_advancedHint',
+ candidate: 'zGbnIq_candidate',
+ candidateEmpty: 'zGbnIq_candidateEmpty',
+ candidateId: 'zGbnIq_candidateId',
+ candidateLabel: 'zGbnIq_candidateLabel',
+ candidateList: 'zGbnIq_candidateList',
+ candidateSearch: 'zGbnIq_candidateSearch',
+ candidateToolbar: 'zGbnIq_candidateToolbar',
+ credentialDot: 'zGbnIq_credentialDot',
+ credentialDotConfigured: 'zGbnIq_credentialDotConfigured',
+ credentialDotMissing: 'zGbnIq_credentialDotMissing',
+ customized: 'zGbnIq_customized',
+ customizedBody: 'zGbnIq_customizedBody',
+ customizedSummary: 'zGbnIq_customizedSummary',
+ dangerButton: 'zGbnIq_dangerButton',
+ deleteConfirm: 'zGbnIq_deleteConfirm',
+ deleteDialog: 'zGbnIq_deleteDialog',
+ editor: 'zGbnIq_editor',
+ editorActions: 'zGbnIq_editorActions',
+ editorHeader: 'zGbnIq_editorHeader',
+ editorRoute: 'zGbnIq_editorRoute',
+ editorTitle: 'zGbnIq_editorTitle',
+ error: 'zGbnIq_error',
+ fetchDialog: 'zGbnIq_fetchDialog',
+ field: 'zGbnIq_field',
+ fieldLabel: 'zGbnIq_fieldLabel',
+ hiddenLabel: 'zGbnIq_hiddenLabel',
+ iconButton: 'zGbnIq_iconButton',
+ iconButtonDanger: 'zGbnIq_iconButtonDanger',
+ input: 'zGbnIq_input',
+ intro: 'zGbnIq_intro',
+ linkButton: 'zGbnIq_linkButton',
+ modelAdvanced: 'zGbnIq_modelAdvanced',
+ modelCatalog: 'zGbnIq_modelCatalog',
+ modelCatalogHeading: 'zGbnIq_modelCatalogHeading',
+ modelCatalogMeta: 'zGbnIq_modelCatalogMeta',
+ modelCatalogTitle: 'zGbnIq_modelCatalogTitle',
+ modelEffortChip: 'zGbnIq_modelEffortChip',
+ modelEfforts: 'zGbnIq_modelEfforts',
+ modelEmpty: 'zGbnIq_modelEmpty',
+ modelEntry: 'zGbnIq_modelEntry',
+ modelField: 'zGbnIq_modelField',
+ modelFieldLabel: 'zGbnIq_modelFieldLabel',
+ modelList: 'zGbnIq_modelList',
+ modelListHead: 'zGbnIq_modelListHead',
+ modelRow: 'zGbnIq_modelRow',
+ modelSwitchRow: 'zGbnIq_modelSwitchRow',
+ notice: 'zGbnIq_notice',
+ primaryButton: 'zGbnIq_primaryButton',
+ rowActions: 'zGbnIq_rowActions',
+ rowCard: 'zGbnIq_rowCard',
+ rowHead: 'zGbnIq_rowHead',
+ rowIdentity: 'zGbnIq_rowIdentity',
+ rowName: 'zGbnIq_rowName',
+ rowTag: 'zGbnIq_rowTag',
+ rows: 'zGbnIq_rows',
+ savedNotice: 'zGbnIq_savedNotice',
+ secondaryButton: 'zGbnIq_secondaryButton',
+ section: 'zGbnIq_section',
+ selectInput: 'zGbnIq_selectInput',
+ setupCard: 'zGbnIq_setupCard',
+ switchThumb: 'zGbnIq_switchThumb',
+ title: 'zGbnIq_title',
+ titleRow: 'zGbnIq_titleRow',
+}
+
+export const welcomeStyles: Record<string, string> = {
+ actions: 'zGbnIqw_actions',
+ copy: 'zGbnIqw_copy',
+ error: 'zGbnIqw_error',
+ primary: 'zGbnIqw_primary',
+}
+
+export const onboardingStyles: Record<string, string> = {
+ body: 'zGbnIqo_body',
+ content: 'zGbnIqo_content',
+ dialog: 'zGbnIqo_dialog',
+ title: 'zGbnIqo_title',
+}
+
+export const onboardingDialogStyles: Record<string, string> = {
+ description: 'zGbnIqd_description',
+ editor: 'zGbnIqd_editor',
+}
+
+export const modelsStylesNode = c([MODELS_CSS, WELCOME_CSS, ONBOARDING_CSS, ONBOARDING_DIALOG_CSS])
diff --git a/archiving/dsh-tauri-model-config/src/client/models/welcome-store.ts b/archiving/dsh-tauri-model-config/src/client/models/welcome-store.ts
new file mode 100644
index 00000000..3c2af7ac
--- /dev/null
+++ b/archiving/dsh-tauri-model-config/src/client/models/welcome-store.ts
@@ -0,0 +1,130 @@
+import type { SnapshotStore } from '@deepseek-ai/dsh-client-store'
+import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
+import {
+ WELCOME_NOTICE_ACK_FIELD,
+ WELCOME_NOTICE_VERSION,
+} from '../../shared/onboarding-copy.ts'
+
+export interface WelcomeNoticeState {
+ status: 'idle' | 'loading' | 'ready' | 'saving' | 'error'
+ acknowledged: boolean
+ error: string | null
+}
+
+export type WelcomeSection = Record<string, unknown>
+
+/** `SettingsScope`(≤0.1.6)与 `ConfigForm`(≥0.1.7)共有的读/写面。 */
+export interface WelcomeSettingsForm {
+ getSnapshot: () => {
+ status: 'loading' | 'ready' | 'unavailable'
+ value?: WelcomeSection
+ mode: 'host' | 'memory'
+ }
+ subscribe: (listener: () => void) => () => void
+ set: (field: string, value: unknown) => Promise<boolean>
+}
+
+export function decodeWelcomeSection(section: unknown): WelcomeSection {
+ return typeof section === 'object' && section !== null && !Array.isArray(section)
+ ? section as WelcomeSection
+ : {}
+}
+
+function assertNever(_value: never): never {
+ throw new Error('unexpected welcome settings status')
+}
+
+export class WelcomeNoticeStore {
+ readonly store: SnapshotStore<WelcomeNoticeState> = createSnapshotStore<WelcomeNoticeState>({
+ status: 'idle',
+ acknowledged: false,
+ error: null,
+ })
+
+ private localAcknowledged = false
+ private saving = false
+ private following: (() => void) | undefined
+
+ constructor(private readonly scope: WelcomeSettingsForm) {}
+
+ load(): Promise<void> {
+ this.following ??= this.scope.subscribe(() => {
+ this.derive()
+ })
+ this.derive()
+ return Promise.resolve()
+ }
+
+ async acknowledge(): Promise<boolean> {
+ if (this.scope.getSnapshot().mode === 'memory') {
+ this.localAcknowledged = true
+ this.derive()
+ return true
+ }
+ this.saving = true
+ this.store.update((state) => {
+ state.status = 'saving'
+ state.error = null
+ })
+ try {
+ await this.scope.set(WELCOME_NOTICE_ACK_FIELD, WELCOME_NOTICE_VERSION)
+ }
+ finally {
+ this.saving = false
+ }
+ this.derive()
+ const { acknowledged } = this.store.getSnapshot()
+ if (!acknowledged) {
+ this.store.update((state) => {
+ state.status = 'error'
+ state.error = 'the acknowledgement did not persist'
+ })
+ }
+ return acknowledged
+ }
+
+ dispose(): void {
+ this.following?.()
+ this.following = undefined
+ }
+
+ private derive(): void {
+ if (this.saving)
+ return
+ const scope = this.scope.getSnapshot()
+ if (scope.mode === 'memory') {
+ this.store.update((state) => {
+ state.status = 'ready'
+ state.acknowledged = this.localAcknowledged
+ state.error = null
+ })
+ return
+ }
+ switch (scope.status) {
+ case 'loading':
+ this.store.update((state) => {
+ state.status = 'loading'
+ state.error = null
+ })
+ return
+ case 'unavailable':
+ this.store.update((state) => {
+ state.status = 'error'
+ state.acknowledged = false
+ state.error = 'welcome acknowledgement settings are unavailable'
+ })
+ return
+ case 'ready': {
+ const acknowledged = scope.value?.[WELCOME_NOTICE_ACK_FIELD] === WELCOME_NOTICE_VERSION
+ this.store.update((state) => {
+ state.status = 'ready'
+ state.acknowledged = acknowledged
+ state.error = null
+ })
+ return
+ }
+
+ default: return assertNever(scope.status)
+ }
+ }
+}
diff --git a/archiving/dsh-tauri-model-config/src/client/register/models.ts b/archiving/dsh-tauri-model-config/src/client/register/models.ts
new file mode 100644
index 00000000..dce77bbc
--- /dev/null
+++ b/archiving/dsh-tauri-model-config/src/client/register/models.ts
@@ -0,0 +1,103 @@
+import type { Context as ClientContext } from '@deepseek-ai/cordis'
+import type {} from '@deepseek-ai/dsh-client-connection/client'
+import type {} from '@deepseek-ai/dsh-client-locale/client'
+import type {} from '@deepseek-ai/dsh-client-ui-renderer/client'
+import type {} from '@deepseek-ai/dsh-client-ui-settings/client'
+import type { DeepSeekOnboardingInjected } from '../models/DeepSeekOnboardingDialog.tsx'
+import type { ModelsSectionInjected } from '../models/ModelsSection.tsx'
+import type { WelcomeNoticeInjected } from '../models/WelcomeNotice.tsx'
+import type { ClientRemote } from '../types/remotes.ts'
+import { defineRegister } from 'dsh-tauri/client'
+import { locale } from '../locales'
+import { DeepSeekOnboardingDialog } from '../models/DeepSeekOnboardingDialog.tsx'
+import { ModelsSection } from '../models/ModelsSection.tsx'
+import { createModelsOperations } from '../models/operations.ts'
+import { createSettingsSchemaOperations } from '../models/schema-operations.ts'
+import { resolveModelsForms } from '../models/settings-forms.ts'
+import { ModelsSettingsStore } from '../models/store.ts'
+import { WelcomeNoticeStore } from '../models/welcome-store.ts'
+import { WelcomeNotice } from '../models/WelcomeNotice.tsx'
+import { openConfigFile } from '../service/model-config.ts'
+
+function refreshIfLoaded(controller: ModelsSettingsStore): void {
+ if (controller.store.getSnapshot().status === 'idle')
+ return
+ void controller.load()
+}
+
+function remoteOf(ctx: ClientContext): ClientRemote | undefined {
+ return ctx.get('remote') as ClientRemote | undefined
+}
+
+/** 装配 fork 自官方 `ui-settings-models` 的模型设置页与其引导对话框。 */
+export const registerModelsPage = defineRegister<ClientContext>((controller, ctx) => {
+ const remote = remoteOf(ctx)
+ const schema = createSettingsSchemaOperations(ctx.settingsSchema)
+ const operations = createModelsOperations(remote as ClientRemote)
+ const forms = resolveModelsForms(ctx)
+ if (forms === undefined)
+ return
+ const page = new ModelsSettingsStore(remote as ClientRemote, schema, forms.describe)
+ const t = locale.text as ModelsSectionInjected['t']
+ const injected = (): ModelsSectionInjected => ({
+ controller: page,
+ hooks: { snapshot: page.store },
+ operations,
+ schema,
+ t,
+ openConfig: openConfigFile,
+ })
+ const deepSeekOnboardingInjected = (): DeepSeekOnboardingInjected => ({
+ controller: page,
+ hooks: { models: page.store },
+ operations,
+ schema,
+ t,
+ })
+ const welcome = new WelcomeNoticeStore(forms.welcome)
+ const welcomeInjected = (): WelcomeNoticeInjected => ({
+ controller: welcome,
+ hooks: { welcome: welcome.store },
+ t,
+ })
+
+ controller.add(ctx.slots.inject('settings.section', () => ctx.slots.register({
+ name: 'settings.section',
+ id: 'models',
+ order: 10,
+ label: () => locale.text('nav'),
+ inject: injected,
+ children: {
+ 'settings.models.provider-card': { kind: 'keyed', scope: 'root' },
+ 'settings.models.footer': { kind: 'list', scope: 'root' },
+ },
+ }, ModelsSection)))
+ controller.add(ctx.slots.inject('settings.onboarding', () => ctx.slots.register({
+ name: 'settings.onboarding',
+ id: 'welcome-notice',
+ order: -100,
+ inject: welcomeInjected,
+ }, WelcomeNotice)))
+ controller.add(ctx.slots.inject('settings.onboarding', () => ctx.slots.register({
+ name: 'settings.onboarding',
+ id: 'deepseek-official',
+ order: 0,
+ inject: deepSeekOnboardingInjected,
+ }, DeepSeekOnboardingDialog)))
+
+ controller.add(() => welcome.dispose())
+ if (remote !== undefined) {
+ controller.add(remote.$on('settings/document-updated', () => {
+ refreshIfLoaded(page)
+ }))
+ controller.add(remote.$on('credentials/reference-updated', () => {
+ refreshIfLoaded(page)
+ }))
+ controller.add(remote.$on('llm/adapters-updated', () => {
+ refreshIfLoaded(page)
+ }))
+ }
+ controller.add(ctx.on('connection/reset', () => {
+ refreshIfLoaded(page)
+ }))
+})
diff --git a/archiving/dsh-tauri-model-config/src/client/register/styles.ts b/archiving/dsh-tauri-model-config/src/client/register/styles.ts
new file mode 100644
index 00000000..4e61f84a
--- /dev/null
+++ b/archiving/dsh-tauri-model-config/src/client/register/styles.ts
@@ -0,0 +1,8 @@
+import { mountStyle } from 'dsh-tauri-ui/client'
+import { defineRegister } from 'dsh-tauri/client'
+import { STYLES_ID } from '../constants'
+import { modelsStylesNode } from '../models/styles'
+
+export const registerStyles = defineRegister((controller) => {
+ controller.add(mountStyle(modelsStylesNode, STYLES_ID))
+})
diff --git a/packages/dsh-tauri-model-config/src/client/service/editor.ts b/archiving/dsh-tauri-model-config/src/client/service/editor.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/client/service/editor.ts
rename to archiving/dsh-tauri-model-config/src/client/service/editor.ts
diff --git a/packages/dsh-tauri-model-config/src/client/service/model-config.ts b/archiving/dsh-tauri-model-config/src/client/service/model-config.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/client/service/model-config.ts
rename to archiving/dsh-tauri-model-config/src/client/service/model-config.ts
diff --git a/packages/dsh-tauri-model-config/src/client/service/model-config.utils.test.ts b/archiving/dsh-tauri-model-config/src/client/service/model-config.utils.test.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/client/service/model-config.utils.test.ts
rename to archiving/dsh-tauri-model-config/src/client/service/model-config.utils.test.ts
diff --git a/packages/dsh-tauri-model-config/src/client/service/model-config.utils.ts b/archiving/dsh-tauri-model-config/src/client/service/model-config.utils.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/client/service/model-config.utils.ts
rename to archiving/dsh-tauri-model-config/src/client/service/model-config.utils.ts
diff --git a/packages/dsh-tauri-model-config/src/client/service/model-preset-fixtures.ts b/archiving/dsh-tauri-model-config/src/client/service/model-preset-fixtures.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/client/service/model-preset-fixtures.ts
rename to archiving/dsh-tauri-model-config/src/client/service/model-preset-fixtures.ts
diff --git a/packages/dsh-tauri-model-config/src/client/service/model-presets.test.ts b/archiving/dsh-tauri-model-config/src/client/service/model-presets.test.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/client/service/model-presets.test.ts
rename to archiving/dsh-tauri-model-config/src/client/service/model-presets.test.ts
diff --git a/packages/dsh-tauri-model-config/src/client/service/model-presets.ts b/archiving/dsh-tauri-model-config/src/client/service/model-presets.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/client/service/model-presets.ts
rename to archiving/dsh-tauri-model-config/src/client/service/model-presets.ts
diff --git a/packages/dsh-tauri-model-config/src/client/service/presets.ts b/archiving/dsh-tauri-model-config/src/client/service/presets.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/client/service/presets.ts
rename to archiving/dsh-tauri-model-config/src/client/service/presets.ts
diff --git a/archiving/dsh-tauri-model-config/src/client/types/remotes.ts b/archiving/dsh-tauri-model-config/src/client/types/remotes.ts
new file mode 100644
index 00000000..44787517
--- /dev/null
+++ b/archiving/dsh-tauri-model-config/src/client/types/remotes.ts
@@ -0,0 +1,93 @@
+export type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }
+
+export interface RemoteFailure {
+ code: string
+ message: string
+}
+
+export type RemoteResult<T>
+ = | { ok: true, value: T }
+ | { ok: false, error: RemoteFailure }
+
+export interface CredentialInfo {
+ configured: boolean
+ source?: string
+ writable: boolean
+}
+
+export interface SettingsSecretView {
+ path: string[]
+ set: boolean
+}
+
+export interface SettingsNamespaceView {
+ ns: string
+ schema: JsonValue
+ value: JsonValue
+ base?: JsonValue
+ user?: JsonValue
+ applies: 'live' | 'restart'
+ secrets: SettingsSecretView[]
+ revision: number
+}
+
+export type SettingsPathOpView
+ = | { op: 'set', path: string[], value: JsonValue }
+ | { op: 'unset', path: string[] }
+
+export interface SettingsDescribeValue {
+ writable: boolean
+ hasDocument: boolean
+ namespaces: SettingsNamespaceView[]
+}
+
+export interface LlmProviderInfo {
+ id: string
+ name: string
+}
+
+export interface LlmConfigurableProvider {
+ provider: string
+ displayName: string
+ settingsNs: string
+ settingsPath: readonly string[]
+ declared?: boolean
+ error?: string
+}
+
+export interface LlmModelDiscoveryRequest {
+ provider?: string
+ baseURL?: string
+ api?: string
+ apiKey?: string
+}
+
+export interface LlmDiscoveredModel {
+ id: string
+ name?: string
+ contextWindow?: number
+ maxTokens?: number
+}
+
+export interface SettingsRemote {
+ mutate: (ns: string, ops: SettingsPathOpView[], expectedRevision?: number) => Promise<RemoteResult<SettingsNamespaceView>>
+}
+
+export interface CredentialsRemote {
+ describe: (refs: string[]) => Promise<RemoteResult<Record<string, CredentialInfo>>>
+ set: (ref: string, value: string) => Promise<RemoteResult<unknown>>
+ unset: (ref: string) => Promise<RemoteResult<unknown>>
+}
+
+export interface LlmRemote {
+ listProviders: () => Promise<RemoteResult<LlmProviderInfo[]>>
+ listConfigurableProviders: () => Promise<RemoteResult<LlmConfigurableProvider[]>>
+ discoverModels: (settingsNs: string, request: LlmModelDiscoveryRequest) => Promise<RemoteResult<LlmDiscoveredModel[]>>
+}
+
+export interface ClientRemote {
+ settings: SettingsRemote
+ credentials: CredentialsRemote
+ llm: LlmRemote
+ $on: (event: string, listener: () => void) => () => void
+}
diff --git a/archiving/dsh-tauri-model-config/src/host/apply.ts b/archiving/dsh-tauri-model-config/src/host/apply.ts
new file mode 100644
index 00000000..51cc5878
--- /dev/null
+++ b/archiving/dsh-tauri-model-config/src/host/apply.ts
@@ -0,0 +1,15 @@
+import type { HostContext } from './types'
+import { PLUGIN_ID } from '../shared/constants'
+import { setCurrentHostInstance } from './config/runtime'
+import { routes } from './routes'
+
+const ROUTES_EFFECT = `${PLUGIN_ID}: routes`
+
+const RUNTIME_EFFECT = `${PLUGIN_ID}: host runtime`
+
+export function apply(ctx: HostContext): void {
+ setCurrentHostInstance(ctx)
+
+ ctx.effect(() => routes(ctx), ROUTES_EFFECT)
+ ctx.effect(() => () => setCurrentHostInstance(undefined), RUNTIME_EFFECT)
+}
diff --git a/packages/dsh-tauri-model-config/src/host/config/runtime.ts b/archiving/dsh-tauri-model-config/src/host/config/runtime.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/host/config/runtime.ts
rename to archiving/dsh-tauri-model-config/src/host/config/runtime.ts
diff --git a/packages/dsh-tauri-model-config/src/host/routes/config/editor/get.ts b/archiving/dsh-tauri-model-config/src/host/routes/config/editor/get.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/host/routes/config/editor/get.ts
rename to archiving/dsh-tauri-model-config/src/host/routes/config/editor/get.ts
diff --git a/packages/dsh-tauri-model-config/src/host/routes/config/editor/put.ts b/archiving/dsh-tauri-model-config/src/host/routes/config/editor/put.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/host/routes/config/editor/put.ts
rename to archiving/dsh-tauri-model-config/src/host/routes/config/editor/put.ts
diff --git a/packages/dsh-tauri-model-config/src/host/routes/config/open/post.ts b/archiving/dsh-tauri-model-config/src/host/routes/config/open/post.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/host/routes/config/open/post.ts
rename to archiving/dsh-tauri-model-config/src/host/routes/config/open/post.ts
diff --git a/packages/dsh-tauri-model-config/src/host/routes/endpoint/models/get.ts b/archiving/dsh-tauri-model-config/src/host/routes/endpoint/models/get.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/host/routes/endpoint/models/get.ts
rename to archiving/dsh-tauri-model-config/src/host/routes/endpoint/models/get.ts
diff --git a/packages/dsh-tauri-model-config/src/host/routes/index.ts b/archiving/dsh-tauri-model-config/src/host/routes/index.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/host/routes/index.ts
rename to archiving/dsh-tauri-model-config/src/host/routes/index.ts
diff --git a/packages/dsh-tauri-model-config/src/host/routes/index.types.ts b/archiving/dsh-tauri-model-config/src/host/routes/index.types.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/host/routes/index.types.ts
rename to archiving/dsh-tauri-model-config/src/host/routes/index.types.ts
diff --git a/packages/dsh-tauri-model-config/src/host/routes/presets/get.ts b/archiving/dsh-tauri-model-config/src/host/routes/presets/get.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/host/routes/presets/get.ts
rename to archiving/dsh-tauri-model-config/src/host/routes/presets/get.ts
diff --git a/packages/dsh-tauri-model-config/src/host/service/config-file.test.ts b/archiving/dsh-tauri-model-config/src/host/service/config-file.test.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/host/service/config-file.test.ts
rename to archiving/dsh-tauri-model-config/src/host/service/config-file.test.ts
diff --git a/packages/dsh-tauri-model-config/src/host/service/config-file.ts b/archiving/dsh-tauri-model-config/src/host/service/config-file.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/host/service/config-file.ts
rename to archiving/dsh-tauri-model-config/src/host/service/config-file.ts
diff --git a/packages/dsh-tauri-model-config/src/host/service/config-file.types.ts b/archiving/dsh-tauri-model-config/src/host/service/config-file.types.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/host/service/config-file.types.ts
rename to archiving/dsh-tauri-model-config/src/host/service/config-file.types.ts
diff --git a/packages/dsh-tauri-model-config/src/host/service/config-file.utils.test.ts b/archiving/dsh-tauri-model-config/src/host/service/config-file.utils.test.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/host/service/config-file.utils.test.ts
rename to archiving/dsh-tauri-model-config/src/host/service/config-file.utils.test.ts
diff --git a/packages/dsh-tauri-model-config/src/host/service/config-file.utils.ts b/archiving/dsh-tauri-model-config/src/host/service/config-file.utils.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/host/service/config-file.utils.ts
rename to archiving/dsh-tauri-model-config/src/host/service/config-file.utils.ts
diff --git a/packages/dsh-tauri-model-config/src/host/service/endpoint-models.ts b/archiving/dsh-tauri-model-config/src/host/service/endpoint-models.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/host/service/endpoint-models.ts
rename to archiving/dsh-tauri-model-config/src/host/service/endpoint-models.ts
diff --git a/packages/dsh-tauri-model-config/src/host/service/endpoint-models.utils.test.ts b/archiving/dsh-tauri-model-config/src/host/service/endpoint-models.utils.test.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/host/service/endpoint-models.utils.test.ts
rename to archiving/dsh-tauri-model-config/src/host/service/endpoint-models.utils.test.ts
diff --git a/packages/dsh-tauri-model-config/src/host/service/endpoint-models.utils.ts b/archiving/dsh-tauri-model-config/src/host/service/endpoint-models.utils.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/host/service/endpoint-models.utils.ts
rename to archiving/dsh-tauri-model-config/src/host/service/endpoint-models.utils.ts
diff --git a/packages/dsh-tauri-model-config/src/host/service/model-presets.test.ts b/archiving/dsh-tauri-model-config/src/host/service/model-presets.test.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/host/service/model-presets.test.ts
rename to archiving/dsh-tauri-model-config/src/host/service/model-presets.test.ts
diff --git a/packages/dsh-tauri-model-config/src/host/service/model-presets.ts b/archiving/dsh-tauri-model-config/src/host/service/model-presets.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/host/service/model-presets.ts
rename to archiving/dsh-tauri-model-config/src/host/service/model-presets.ts
diff --git a/archiving/dsh-tauri-model-config/src/host/types/index.ts b/archiving/dsh-tauri-model-config/src/host/types/index.ts
new file mode 100644
index 00000000..b343b811
--- /dev/null
+++ b/archiving/dsh-tauri-model-config/src/host/types/index.ts
@@ -0,0 +1 @@
+export type HostContext = any
diff --git a/packages/dsh-tauri-model-config/src/host/utils/paths.test.ts b/archiving/dsh-tauri-model-config/src/host/utils/paths.test.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/host/utils/paths.test.ts
rename to archiving/dsh-tauri-model-config/src/host/utils/paths.test.ts
diff --git a/packages/dsh-tauri-model-config/src/host/utils/paths.ts b/archiving/dsh-tauri-model-config/src/host/utils/paths.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/host/utils/paths.ts
rename to archiving/dsh-tauri-model-config/src/host/utils/paths.ts
diff --git a/archiving/dsh-tauri-model-config/src/index.ts b/archiving/dsh-tauri-model-config/src/index.ts
new file mode 100644
index 00000000..cb1db366
--- /dev/null
+++ b/archiving/dsh-tauri-model-config/src/index.ts
@@ -0,0 +1,7 @@
+import { PLUGIN_ID } from './shared/constants'
+
+export const name = PLUGIN_ID
+
+export const inject = ['webServer', 'connection']
+
+export { apply } from './host/apply'
diff --git a/archiving/dsh-tauri-model-config/src/shared/constants.ts b/archiving/dsh-tauri-model-config/src/shared/constants.ts
new file mode 100644
index 00000000..364e63c2
--- /dev/null
+++ b/archiving/dsh-tauri-model-config/src/shared/constants.ts
@@ -0,0 +1,4 @@
+export const PLUGIN_ID = 'dsh-tauri-model-config'
+
+/** 承载全部模型配置的 DSH 设置文档文件名(位于 `$DSH_HOME` 之下)。 */
+export const SETTINGS_FILE_NAME = 'settings.yaml'
diff --git a/packages/dsh-tauri-model-config/src/shared/editor.ts b/archiving/dsh-tauri-model-config/src/shared/editor.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/shared/editor.ts
rename to archiving/dsh-tauri-model-config/src/shared/editor.ts
diff --git a/packages/dsh-tauri-model-config/src/shared/editor.types.ts b/archiving/dsh-tauri-model-config/src/shared/editor.types.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/shared/editor.types.ts
rename to archiving/dsh-tauri-model-config/src/shared/editor.types.ts
diff --git a/packages/dsh-tauri-model-config/src/shared/model-presets.test.ts b/archiving/dsh-tauri-model-config/src/shared/model-presets.test.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/shared/model-presets.test.ts
rename to archiving/dsh-tauri-model-config/src/shared/model-presets.test.ts
diff --git a/packages/dsh-tauri-model-config/src/shared/model-presets.ts b/archiving/dsh-tauri-model-config/src/shared/model-presets.ts
similarity index 100%
rename from packages/dsh-tauri-model-config/src/shared/model-presets.ts
rename to archiving/dsh-tauri-model-config/src/shared/model-presets.ts
diff --git a/archiving/dsh-tauri-model-config/src/shared/onboarding-copy.ts b/archiving/dsh-tauri-model-config/src/shared/onboarding-copy.ts
new file mode 100644
index 00000000..1e15894b
--- /dev/null
+++ b/archiving/dsh-tauri-model-config/src/shared/onboarding-copy.ts
@@ -0,0 +1,7 @@
+export const WELCOME_NOTICE_SETTINGS_NAMESPACE = 'ui-settings-general'
+
+export const WELCOME_NOTICE_SETTINGS_NAMESPACE_LEGACY = 'ui-onboarding'
+
+export const WELCOME_NOTICE_ACK_FIELD = 'welcomeNoticeVersion'
+
+export const WELCOME_NOTICE_VERSION = '2026-08-13.1'
diff --git a/archiving/dsh-tauri-model-config/tsdown.config.ts b/archiving/dsh-tauri-model-config/tsdown.config.ts
new file mode 100644
index 00000000..b889e553
--- /dev/null
+++ b/archiving/dsh-tauri-model-config/tsdown.config.ts
@@ -0,0 +1,8 @@
+import { defineDshConfig } from '../dsh-tauri-tsdown/src/index.ts'
+
+export default defineDshConfig({
+ client: {
+ dts: true,
+ noExternal: ['react-if-lite'],
+ },
+})
diff --git a/eslint.config.mjs b/eslint.config.mjs
index 86b4b372..fcdfdf25 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -9,6 +9,8 @@ export default antfu({
'AGENTS.*',
'docs',
'archive',
+ // 已归档的历史实现:保留供对照,不参与 lint 与类型检查
+ 'archiving',
// 技能目录:脚本与参考文档由技能作者维护(部分经 skills-lock.json 锁定上游哈希),
// 改动会偏离上游并破坏哈希校验,不参与本仓 lint 规约
'skills',
diff --git a/genapi.config.ts b/genapi.config.ts
index 47faaee2..5aa54f4c 100644
--- a/genapi.config.ts
+++ b/genapi.config.ts
@@ -1,8 +1,12 @@
import { defineConfig } from '@genapi/core'
import { pluginPipeline } from './genapi.pipeline'
+// 本列表的判据是「有需要生成的宿主 HTTP 路由」,不是「有宿主半区」:
+// `dsh-tauri`(3 条路由)与 `dsh-tauri-pet`(3 条)都自行手写调用层,没有列出。
+// `dsh-tauri-model-config` 是官方 `ui-settings-models` 的原样 fork:宿主半区只有
+// webserver 全局注入(`webserver/index-inject`),没有 HTTP 路由,因此没有可生成的 API;
+// 本仓库自有的 5 条路由已随自动配置/打开配置文件能力迁到 `dsh-tauri-ui`。
const plugins = [
- 'dsh-tauri-model-config',
'dsh-tauri-panel-extension',
'dsh-tauri-panel-scheduler',
'dsh-tauri-rightclick',
diff --git a/packages/dsh-tauri-model-config/cordis.patch.yml b/packages/dsh-tauri-model-config/cordis.patch.yml
index f21f25a3..4cd9b7ee 100644
--- a/packages/dsh-tauri-model-config/cordis.patch.yml
+++ b/packages/dsh-tauri-model-config/cordis.patch.yml
@@ -1,6 +1,5 @@
-# 官方「模型」设置页:本插件是它的完整 fork(新增「支持图片输入」开关、打开配置文件、
-# 从提供方端点补全模型上限)。两者在 `settings.section/models` 上互斥,同开会在
-# 加载期报槽位重复声明,因此必须关掉官方入口。
+# 官方「模型」设置页:本插件是它的完整 fork,注册同一个 `settings.section/models` 声明。
+# 两者在加载期互斥(同开会报槽位重复声明),因此必须关掉官方入口。
- id: ui-settings-models
disabled: true
diff --git a/packages/dsh-tauri-model-config/package.json b/packages/dsh-tauri-model-config/package.json
index 6ff90fb9..f1f7a55c 100644
--- a/packages/dsh-tauri-model-config/package.json
+++ b/packages/dsh-tauri-model-config/package.json
@@ -80,6 +80,7 @@
"@deepseek-ai/dsh-client-ui-renderer": "catalog:dsh",
"@deepseek-ai/dsh-client-ui-settings": "catalog:dsh",
"@deepseek-ai/dsh-client-ui-slots": "catalog:dsh",
+ "@deepseek-ai/dsh-util-values": "catalog:dsh",
"@types/node": "catalog:types",
"dsh-tauri-tsdown": "workspace:*",
"react-if-lite": "catalog:runtime",
diff --git a/packages/dsh-tauri-model-config/src/client/index.ts b/packages/dsh-tauri-model-config/src/client/index.ts
index b55aed34..9cfce08f 100644
--- a/packages/dsh-tauri-model-config/src/client/index.ts
+++ b/packages/dsh-tauri-model-config/src/client/index.ts
@@ -5,6 +5,12 @@ import { locale } from './locales'
import { registerModelsPage } from './register/models'
import { registerStyles } from './register/styles'
+export type { ModelsKey } from './models/locales.ts'
+export type { ModelsSectionInjected, ModelsSectionProps } from './models/ModelsSection.tsx'
+export type { ModelDiscoveryOutcome, ModelsOperations, SettingsWriteOutcome } from './models/operations.ts'
+export type { ModelsFooterOwnerProps, ProviderCardExtrasOwnerProps } from './models/slot-contract.ts'
+export type { ModelsSettingsState, ProviderDirectoryEntry, ProviderRow } from './models/store.ts'
+
export const name = PLUGIN_ID
export const inject = [
@@ -17,11 +23,6 @@ export const inject = [
'settingsSchema',
]
-/**
- * 设置命名空间服务跨内核代更名:≤0.1.6 是 `settingsScope`,≥0.1.7 是 `configForms`。
- * 两者都不能写进 `inject`——缺席的服务会让 fiber 永久 pending,直接导致另一代内核
- * 加载失败。因此各自独立等待,任意一代就绪即启动,且只启动一次。
- */
export function apply(ctx: ClientContext): void {
ctx.effect(locale.registerLocale, LOCALE_EFFECT)
ctx.effect(registerStyles, STYLES_EFFECT)
diff --git a/packages/dsh-tauri-model-config/src/client/locales/index.ts b/packages/dsh-tauri-model-config/src/client/locales/index.ts
index 72df8342..4f9777a8 100644
--- a/packages/dsh-tauri-model-config/src/client/locales/index.ts
+++ b/packages/dsh-tauri-model-config/src/client/locales/index.ts
@@ -2,5 +2,4 @@ import { defineLocale } from 'dsh-tauri/client'
import { PLUGIN_ID } from '../../shared/constants'
import { en, zh } from '../models/locales'
-/** 模型配置页的文案命名空间(沿用官方 `settings.models` 的键集)。 */
export const locale = defineLocale(PLUGIN_ID, { zh, en })
diff --git a/packages/dsh-tauri-model-config/src/client/models/CustomProviderCard.tsx b/packages/dsh-tauri-model-config/src/client/models/CustomProviderCard.tsx
index cb0af9f9..a6d65db0 100644
--- a/packages/dsh-tauri-model-config/src/client/models/CustomProviderCard.tsx
+++ b/packages/dsh-tauri-model-config/src/client/models/CustomProviderCard.tsx
@@ -1,16 +1,14 @@
+import type { JsonValue } from '@deepseek-ai/dsh-util-values'
import type { ReactNode } from 'react'
-import type { JsonValue } from '../types/remotes.ts'
import type { en } from './locales.ts'
import type { ModelDraft } from './ModelListEditor.tsx'
import type { ModelsOperations } from './operations.ts'
-import { useState } from 'react'
-import { loadModelCapacities } from '../service/model-config.ts'
-import { mergeModelCards, modelConfigNotice, withDetail } from '../service/model-config.utils.ts'
-import { ensurePresets } from '../service/presets.ts'
+import { useEffect, useState } from 'react'
import { apiKeyFailure } from './apiKey.ts'
import { validateDeepSeekModels } from './DeepSeekModelsEditor.tsx'
import { EditorFooter } from './EditorFooter.tsx'
import { ModelListEditor } from './ModelListEditor.tsx'
+import { protocolLabel } from './protocol-label.ts'
import { deriveKeyRef } from './store.ts'
import { modelStyles as styles } from './styles.ts'
@@ -29,24 +27,18 @@ function isHttpUrl(value: string): boolean {
}
export interface CustomProviderCardProps {
-
taken: readonly string[]
-
protocols: readonly string[]
-
revision: number
-
operations: ModelsOperations
-
t: (key: keyof typeof en) => string
-
readOnly: boolean
-
onClose: (changed: boolean) => void
+ onBusyChange?: (busy: boolean) => void
}
export function CustomProviderCard(props: CustomProviderCardProps): ReactNode {
- const { taken, protocols, operations, t } = props
+ const { taken, protocols, operations, t, onBusyChange } = props
const [openedAt] = useState(() => props.revision)
const [route, setRoute] = useState('')
@@ -56,10 +48,11 @@ export function CustomProviderCard(props: CustomProviderCardProps): ReactNode {
const [keyDraft, setKeyDraft] = useState('')
const [models, setModels] = useState<readonly ModelDraft[]>([])
const [busy, setBusy] = useState(false)
+ const [listBusy, setListBusy] = useState(false)
+ useEffect(() => {
+ onBusyChange?.(busy || listBusy)
+ }, [busy, listBusy, onBusyChange])
const [failure, setFailure] = useState<string | undefined>(undefined)
- const [configBusy, setConfigBusy] = useState(false)
- const [configNotice, setConfigNotice] = useState<string | undefined>(undefined)
- const [configFailure, setConfigFailure] = useState<string | undefined>(undefined)
const [committed, setCommitted] = useState(false)
const disabled = props.readOnly || busy
@@ -140,42 +133,8 @@ export function CustomProviderCard(props: CustomProviderCardProps): ReactNode {
}
}
- const fetchConfig = (targets?: readonly string[]): void => {
- void (async () => {
- setConfigBusy(true)
- setConfigFailure(undefined)
- const [found] = await Promise.all([
- loadModelCapacities({
- settingsNs: NS,
- profilePath: ['providers', route.trim()],
- baseURL: normalizedBaseURL,
- api: protocol,
- ...keyValue.length === 0 ? {} : { apiKey: keyValue },
- }, operations),
- ensurePresets(),
- ])
- setConfigBusy(false)
- if (!found.ok) {
- setConfigNotice(undefined)
- setConfigFailure(withDetail(t('configUnreachable'), found.error))
- return
- }
- const merged = mergeModelCards(models, found.models, { targets, overwrite: targets === undefined })
- if (merged.applied > 0)
- setModels(merged.models)
- setConfigNotice(modelConfigNotice(merged, {
- applied: t('configApplied'),
- none: t('configNoneApplied'),
- undisclosed: t('configUndisclosed'),
- }))
- })()
- }
-
return (
<div className={styles.editor}>
- <div className={styles.editorHeader}>
- <span className={styles.editorTitle}>{t('customTitle')}</span>
- </div>
<div className={styles.field}>
<span className={styles.fieldLabel}>{t('customRoute')}</span>
<input
@@ -210,7 +169,9 @@ export function CustomProviderCard(props: CustomProviderCardProps): ReactNode {
className={styles.input}
type="text"
value={baseURL}
- placeholder={t('customBaseUrlPlaceholder')}
+ placeholder={t(protocol === 'anthropic-messages'
+ ? 'customAnthropicBaseUrlPlaceholder'
+ : 'customBaseUrlPlaceholder')}
aria-label={t('baseUrl')}
aria-invalid={baseUrlInvalid}
disabled={profileDisabled}
@@ -227,7 +188,7 @@ export function CustomProviderCard(props: CustomProviderCardProps): ReactNode {
disabled={profileDisabled}
onChange={(event) => { setProtocol(event.target.value) }}
>
- {protocols.map(choice => <option key={choice} value={choice}>{choice}</option>)}
+ {protocols.map(choice => <option key={choice} value={choice}>{protocolLabel(t, choice)}</option>)}
</select>
</div>
<div className={styles.field}>
@@ -262,10 +223,7 @@ export function CustomProviderCard(props: CustomProviderCardProps): ReactNode {
operations={operations}
t={t}
disabled={profileDisabled}
- onFetchConfig={fetchConfig}
- configBusy={configBusy}
- configNotice={configNotice}
- configFailure={configFailure}
+ onBusyChange={setListBusy}
/>
{failure !== undefined ? <p className={styles.error}>{failure}</p> : null}
diff --git a/packages/dsh-tauri-model-config/src/client/models/DeepSeekModelsEditor.tsx b/packages/dsh-tauri-model-config/src/client/models/DeepSeekModelsEditor.tsx
index 5e9106b6..5a07e7f0 100644
--- a/packages/dsh-tauri-model-config/src/client/models/DeepSeekModelsEditor.tsx
+++ b/packages/dsh-tauri-model-config/src/client/models/DeepSeekModelsEditor.tsx
@@ -1,7 +1,8 @@
import type { ReactNode } from 'react'
import type { en } from './locales.ts'
-import { ChevronDown, ChevronRight, Plus, TrashBin } from 'dsh-tauri-ui/client'
+import { Plus } from 'dsh-tauri-ui/client'
import { useState } from 'react'
+import { ModelRow } from './ModelRow.tsx'
import { modelStyles as styles } from './styles.ts'
export type DeepSeekModelDraft = Record<string, unknown>
@@ -44,9 +45,7 @@ export function formatCapacity(value: number): string {
}
export interface DeepSeekModelsValidationFailure {
-
index: number
-
key: 'modelIdRequired' | 'modelIdDuplicate' | 'modelNameInvalid' | 'modelContextInvalid'
| 'modelMaxTokensInvalid'
}
@@ -92,21 +91,13 @@ export function validateDeepSeekModels(value: unknown): DeepSeekModelsValidation
}
export interface DeepSeekModelsEditorProps {
-
models: readonly DeepSeekModelDraft[]
-
overridden: boolean
-
defaultContextWindow: number | undefined
-
defaultMaxTokens: number | undefined
-
t: (key: keyof typeof en) => string
-
disabled: boolean
-
onChange: (models: DeepSeekModelDraft[]) => void
-
onReset: () => void
}
@@ -190,33 +181,17 @@ export function DeepSeekModelsEditor(props: DeepSeekModelsEditorProps): ReactNod
})
}
- const capacityField = (
- model: DeepSeekModelDraft,
- index: number,
- field: CapacityField,
- fallback: number | undefined,
- ): ReactNode => (
- <label className={styles.modelField}>
- <span className={styles.modelFieldLabel}>{props.t(field === 'contextWindow' ? 'contextWindow' : 'maxTokens')}</span>
- <input
- className={styles.input}
- type="text"
- inputMode="numeric"
- value={capacityText(model, index, field)}
- placeholder={fallback === undefined
- ? props.t(field === 'contextWindow' ? 'contextWindowPlaceholder' : 'maxTokensPlaceholder')
- : formatCapacity(fallback)}
- aria-label={`${props.t(field === 'contextWindow' ? 'contextWindow' : 'maxTokens')} ${String(index + 1)}`}
- disabled={props.disabled}
- onChange={(event) => {
- const text = event.target.value
- setEditing(current => new Map(current).set(`${String(index)}:${field}`, text))
- update(index, field, parseCapacity(text))
- }}
- onBlur={() => { settleCapacity(index, field) }}
- />
- </label>
- )
+ const capacityInput = (model: DeepSeekModelDraft, index: number, field: CapacityField, fallback: number | undefined) => ({
+ value: capacityText(model, index, field),
+ placeholder: fallback === undefined
+ ? props.t(field === 'contextWindow' ? 'contextWindowPlaceholder' : 'maxTokensPlaceholder')
+ : formatCapacity(fallback),
+ onChange: (text: string) => {
+ setEditing(current => new Map(current).set(`${String(index)}:${field}`, text))
+ update(index, field, parseCapacity(text))
+ },
+ onBlur: () => { settleCapacity(index, field) },
+ })
return (
<section className={styles.modelCatalog} aria-label={props.t('models')}>
@@ -245,63 +220,26 @@ export function DeepSeekModelsEditor(props: DeepSeekModelsEditorProps): ReactNod
: (
<div className={styles.modelList}>
{props.models.map((model, index) => (
- <div className={styles.modelEntry} key={index}>
- <div className={styles.modelRow}>
- <input
- className={styles.input}
- type="text"
- value={typeof model.id === 'string' ? model.id : ''}
- placeholder={props.t('modelId')}
- aria-label={`${props.t('modelId')} ${String(index + 1)}`}
- disabled={props.disabled}
- onChange={(event) => { update(index, 'id', event.target.value) }}
- onBlur={(event) => {
- const trimmed = event.target.value.trim()
- if (trimmed !== event.target.value)
- update(index, 'id', trimmed)
- }}
- />
- <input
- className={styles.input}
- type="text"
- value={typeof model.name === 'string' ? model.name : ''}
- placeholder={props.t('modelName')}
- aria-label={`${props.t('modelName')} ${String(index + 1)}`}
- disabled={props.disabled}
- onChange={(event) => {
- update(index, 'name', event.target.value === '' ? undefined : event.target.value)
- }}
- />
- <button
- type="button"
- className={styles.iconButton}
- aria-label={`${props.t('modelAdvanced')} ${String(index + 1)}`}
- aria-expanded={expanded.has(index)}
- title={props.t('modelAdvanced')}
- onClick={() => { toggle(index) }}
- >
- {expanded.has(index) ? <ChevronDown width={14} height={14} /> : <ChevronRight width={14} height={14} />}
- </button>
- <button
- type="button"
- className={`${styles.iconButton} ${styles.iconButtonDanger}`}
- aria-label={`${props.t('removeModel')} ${String(index + 1)}`}
- title={props.t('removeModel')}
- disabled={props.disabled}
- onClick={() => { remove(index) }}
- >
- <TrashBin width={14} height={14} />
- </button>
- </div>
- {expanded.has(index)
- ? (
- <div className={styles.modelAdvanced}>
- {capacityField(model, index, 'contextWindow', props.defaultContextWindow)}
- {capacityField(model, index, 'maxTokens', props.defaultMaxTokens)}
- </div>
- )
- : null}
- </div>
+ <ModelRow
+ key={index}
+ model={model}
+ position={index + 1}
+ inputField="inputModalities"
+ expanded={expanded.has(index)}
+ disabled={props.disabled}
+ t={props.t}
+ contextWindow={capacityInput(model, index, 'contextWindow', props.defaultContextWindow)}
+ maxTokens={capacityInput(model, index, 'maxTokens', props.defaultMaxTokens)}
+ onFieldChange={(field, value) => { update(index, field, value) }}
+ onIdBlur={(value) => {
+ const trimmed = value.trim()
+ if (trimmed !== value)
+ update(index, 'id', trimmed)
+ }}
+ onChange={(next) => { props.onChange(props.models.map((row, at) => at === index ? next : row)) }}
+ onToggle={() => { toggle(index) }}
+ onRemove={() => { remove(index) }}
+ />
))}
</div>
)}
diff --git a/packages/dsh-tauri-model-config/src/client/models/DeepSeekOnboardingDialog.tsx b/packages/dsh-tauri-model-config/src/client/models/DeepSeekOnboardingDialog.tsx
index 15973ce7..8d1c27f1 100644
--- a/packages/dsh-tauri-model-config/src/client/models/DeepSeekOnboardingDialog.tsx
+++ b/packages/dsh-tauri-model-config/src/client/models/DeepSeekOnboardingDialog.tsx
@@ -1,19 +1,20 @@
import type { SnapshotStore } from '@deepseek-ai/dsh-client-store'
-import type { InjectFace, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
+import type { InjectFace, PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
import type { ReactNode } from 'react'
import type { en } from './locales.ts'
import type { ModelsOperations } from './operations.ts'
import type { SettingsSchemaOperations } from './schema-operations.ts'
+import type {} from './slot-contract.ts'
import type { ModelsSettingsState, ModelsSettingsStore } from './store.ts'
-import { useEffect } from 'react'
+import { useEffect, useState } from 'react'
import { OnboardingModal } from './OnboardingModal.tsx'
import { ProviderEditor } from './ProviderEditor.tsx'
import { onboardingReadiness } from './store.ts'
import { onboardingDialogStyles as styles } from './styles.ts'
export interface DeepSeekOnboardingInjected {
+ automatic: boolean
hooks: {
-
models: SnapshotStore<ModelsSettingsState>
}
@@ -27,38 +28,46 @@ export interface DeepSeekOnboardingInjected {
}
export type DeepSeekOnboardingDialogProps
- = PropsRuntime<'settings.onboarding'> & InjectFace<DeepSeekOnboardingInjected>
+ = PropsRuntime<'settings.onboarding'> & PropsRenderSlots<'settings.models.sign-in'> & InjectFace<DeepSeekOnboardingInjected>
function assertNever(_value: never): never {
throw new Error('unexpected DeepSeek onboarding state')
}
export function DeepSeekOnboardingDialog(props: DeepSeekOnboardingDialogProps): ReactNode {
- const { complete, controller, useModels, operations, schema, t } = props
+ const { complete, controller, useModels, operations, schema, t, renderSlot, automatic, explicit = false } = props
+ const [apiKey, setApiKey] = useState(explicit)
const state = useModels(snapshot => snapshot)
const readiness = onboardingReadiness(state)
useEffect(() => {
- if (state.status === 'idle')
+ if ((automatic || explicit) && state.status === 'idle')
void controller.load()
- }, [controller, state.status])
+ }, [controller, state.status, automatic, explicit])
useEffect(() => {
if (
- readiness.kind === 'adapter-absent'
- || readiness.kind === 'provider-ready'
+ (!automatic && !explicit)
+ || readiness.kind === 'adapter-absent'
+ || (!explicit && readiness.kind === 'provider-ready')
|| readiness.kind === 'unavailable'
) {
complete()
}
- }, [complete, readiness.kind])
+ }, [complete, readiness.kind, explicit, automatic])
+
+ if (!automatic && !explicit)
+ return null
switch (readiness.kind) {
case 'loading':
case 'adapter-absent':
- case 'provider-ready':
case 'unavailable':
return null
+ case 'provider-ready':
+ if (!explicit)
+ return null
+ break
case 'credential-missing':
break
@@ -83,7 +92,7 @@ export function DeepSeekOnboardingDialog(props: DeepSeekOnboardingDialogProps):
void controller.load()
}
- return (
+ const editor = (
<OnboardingModal title={t('onboardingTitle')}>
<p className={styles.description}>{t('onboardingDescription')}</p>
<div className={styles.editor}>
@@ -108,4 +117,14 @@ export function DeepSeekOnboardingDialog(props: DeepSeekOnboardingDialogProps):
</div>
</OnboardingModal>
)
+ const enableApiKey = (): void => {
+ setApiKey(true)
+ }
+ return apiKey
+ ? editor
+ : renderSlot(
+ 'settings.models.sign-in',
+ { complete, useApiKey: enableApiKey },
+ { fallback: editor },
+ )
}
diff --git a/packages/dsh-tauri-model-config/src/client/models/EditorFooter.tsx b/packages/dsh-tauri-model-config/src/client/models/EditorFooter.tsx
index ca8ddffd..2bb8d8b4 100644
--- a/packages/dsh-tauri-model-config/src/client/models/EditorFooter.tsx
+++ b/packages/dsh-tauri-model-config/src/client/models/EditorFooter.tsx
@@ -3,21 +3,13 @@ import type { en } from './locales.ts'
import { modelStyles as styles } from './styles.ts'
export interface EditorFooterProps {
-
t: (key: keyof typeof en) => string
-
busy: boolean
-
submitDisabled: boolean
-
submitLabelKey: keyof typeof en
-
submitBusyLabelKey: keyof typeof en
-
cancelLabelKey?: keyof typeof en
-
onCancel: () => void
-
onSubmit: () => void
}
diff --git a/packages/dsh-tauri-model-config/src/client/models/ModelInputTypes.tsx b/packages/dsh-tauri-model-config/src/client/models/ModelInputTypes.tsx
new file mode 100644
index 00000000..7a50aa31
--- /dev/null
+++ b/packages/dsh-tauri-model-config/src/client/models/ModelInputTypes.tsx
@@ -0,0 +1,47 @@
+import type { ReactNode } from 'react'
+import type { DeepSeekModelDraft } from './DeepSeekModelsEditor.tsx'
+import type { ModelsKey } from './locales.ts'
+import { Checkbox } from 'dsh-tauri-ui/client'
+import { modelStyles as styles } from './styles.ts'
+
+interface ModelInputTypesProps {
+ model: DeepSeekModelDraft
+ field: 'inputModalities' | 'input'
+ position: number
+ disabled: boolean
+ fallback?: readonly string[] | undefined
+ t: (key: ModelsKey) => string
+ onChange: (model: DeepSeekModelDraft) => void
+}
+
+export function ModelInputTypes({ model, field, position, disabled, fallback, t, onChange }: ModelInputTypesProps): ReactNode {
+ const modalities = model[field]
+ const selected = Array.isArray(modalities) && modalities.length > 0 ? modalities : fallback ?? ['text']
+ return (
+ <fieldset className={styles.modelInputTypes} aria-label={`${t('modelInputTypes')} ${String(position)}`}>
+ <legend className={styles.modelFieldLabel}>{t('modelInputTypes')}</legend>
+ <div className={styles.modelInputChoices}>
+ {(['text', 'image'] as const).map(modality => (
+ <Checkbox
+ key={modality}
+ aria-label={t(modality === 'text' ? 'modelInputText' : 'modelInputImage')}
+ checked={selected.includes(modality)}
+ disabled={disabled || (selected.length === 1 && selected.includes(modality))}
+ onChange={(checked) => {
+ const nextSelected = (['text', 'image'] as const).filter(value =>
+ value === modality ? checked : selected.includes(value))
+ const next = { ...model, [field]: nextSelected }
+ if (field === 'inputModalities' && !nextSelected.includes('image')) {
+ Reflect.deleteProperty(next, 'imagePixelBudget')
+ Reflect.deleteProperty(next, 'imageMaxBytes')
+ }
+ onChange(next)
+ }}
+ >
+ {t(modality === 'text' ? 'modelInputText' : 'modelInputImage')}
+ </Checkbox>
+ ))}
+ </div>
+ </fieldset>
+ )
+}
diff --git a/packages/dsh-tauri-model-config/src/client/models/ModelListEditor.tsx b/packages/dsh-tauri-model-config/src/client/models/ModelListEditor.tsx
index c8828262..9437082e 100644
--- a/packages/dsh-tauri-model-config/src/client/models/ModelListEditor.tsx
+++ b/packages/dsh-tauri-model-config/src/client/models/ModelListEditor.tsx
@@ -1,24 +1,13 @@
-import type { CSSProperties, ReactNode } from 'react'
+import type { ReactNode } from 'react'
import type { LlmDiscoveredModel } from '../types/remotes.ts'
import type { DeepSeekModelDraft } from './DeepSeekModelsEditor.tsx'
import type { en } from './locales.ts'
import type { ModelsOperations } from './operations.ts'
-import { Button, Modal, Switch } from '@deepseek-ai/dsh-client-ui-primitives'
-import { useState } from 'react'
-import {
- declaredThinkingLevels,
- enableThinking,
- hasModelConfig,
- imageInputValue,
- supportsImageInput,
- supportsTemplateThinking,
- supportsThinking,
- templateThinkingCompat,
- THINKING_LEVELS,
- thinkingEffortsOf,
- toggleThinkingLevel,
-} from '../service/model-config.utils.ts'
+import { Button, Modal } from '@deepseek-ai/dsh-client-ui-primitives'
+import { AutoConfigAllButton, modelExtrasTranslate, ModelFetchConfigButton, Plus } from 'dsh-tauri-ui/client'
+import { useEffect, useMemo, useState } from 'react'
import { formatCapacity, parseCapacity } from './DeepSeekModelsEditor.tsx'
+import { ModelRow } from './ModelRow.tsx'
import { modelStyles as styles } from './styles.ts'
export type ModelDraft = DeepSeekModelDraft
@@ -34,112 +23,35 @@ function numberOf(model: ModelDraft, key: string): number | undefined {
}
export interface ProbeTarget {
-
settingsNs: string
-
provider?: string
-
baseURL?: string
-
api?: string
-
apiKey?: string
}
export interface ModelListEditorProps {
-
models: readonly ModelDraft[]
-
+ catalogProvider?: string | undefined
+ defaultInput?: readonly string[] | undefined
overridden?: boolean
-
onChange: (models: ModelDraft[]) => void
-
onReset?: () => void
-
probe: ProbeTarget
-
probeBlocked?: keyof typeof en | undefined
-
operations: ModelsOperations
-
t: (key: keyof typeof en) => string
-
disabled: boolean
-
- onFetchConfig: (targets?: readonly string[]) => void
-
- configBusy: boolean
-
- configNotice?: string | undefined
-
- configFailure?: string | undefined
-}
-
-function IconChevron({ open }: { open: boolean }): ReactNode {
- return (
- <svg
- width="14"
- height="14"
- viewBox="0 0 16 16"
- fill="none"
- aria-hidden
- style={{ transform: open ? 'rotate(90deg)' : undefined, transition: 'transform 120ms ease' }}
- >
- <path d="M6 3.5L10.5 8L6 12.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
- </svg>
- )
-}
-
-function IconTrash(): ReactNode {
- return (
- <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden>
- <path
- d="M2.5 4h11M6.5 4V2.5h3V4M4 4l.7 9a1 1 0 001 .9h4.6a1 1 0 001-.9L12 4M6.5 6.8v4.4M9.5 6.8v4.4"
- stroke="currentColor"
- strokeWidth="1.3"
- strokeLinecap="round"
- strokeLinejoin="round"
- />
- </svg>
- )
+ onBusyChange: (busy: boolean) => void
}
type CapacityField = 'contextWindow' | 'maxTokens'
-/** 一个容量字段正在输入的原文与它当时解析出的数字(解析不出时为 NaN/undefined)。 */
-interface CapacityBuffer {
- text: string
- value: number | undefined
-}
-
const CAPACITY_HINT: Readonly<Record<CapacityField, string>> = {
contextWindow: '256K',
maxTokens: '32K',
}
-/** 上游给高级区留了 4px 左右内边距,会让首行比上面的模型行窄 8px、左边缘再右移 4px;这里去掉它。 */
-const ADVANCED_AREA_STYLE: CSSProperties = { paddingLeft: 0, paddingRight: 0 }
-
-/**
- * 高级区首行横跨整个栅格:左半边是两个容量输入(彼此等宽),容量组本身按内容宽度;右半边是三个
- * 开关,开关组吃掉剩余宽度——开关按内容宽度排布、不做拉伸,容器另加 4px 左外边距。
- *
- * `minWidth: 0` 是必须的:文本输入自带约 20 字符的固有宽度,flex 项的自动最小尺寸会让它拒绝收缩。
- */
-const ADVANCED_ROW_STYLE: CSSProperties = { display: 'flex', gap: '6px', gridColumn: '1 / -1' }
-const ADVANCED_CAPACITIES_STYLE: CSSProperties = { display: 'flex', gap: '6px', minWidth: 0 }
-const ADVANCED_CAPACITY_STYLE: CSSProperties = { flex: 1, minWidth: 0 }
-const ADVANCED_SWITCHES_STYLE: CSSProperties = { display: 'flex', gap: '6px', flex: 1, minWidth: 0, marginLeft: '4px' }
-
-/**
- * 「关闭 Developer 角色」开关只对 chat completions 协议有意义。
- *
- * pi-ai 的 compat 是逐协议校验的:`thinkingFormat` 与 `chatTemplateKwargs` 只有
- * `openai-completions` 收,写到 Responses 或 Anthropic 路由的模型上会让整段配置解析失败。
- * 路由没显式声明协议时(目录路由)无法判断,就不提供这个开关。
- */
-const TEMPLATE_COMPAT_PROTOCOL = 'openai-completions'
-
function capacitySpelling(value: number | undefined): string {
return value === undefined ? '' : formatCapacity(value)
}
@@ -150,60 +62,55 @@ function adopt(candidate: LlmDiscoveredModel): ModelDraft {
...candidate.name === undefined ? {} : { name: candidate.name },
...candidate.contextWindow === undefined ? {} : { contextWindow: candidate.contextWindow },
...candidate.maxTokens === undefined ? {} : { maxTokens: candidate.maxTokens },
+ ...candidate.inputModalities === undefined ? {} : { input: [...candidate.inputModalities] },
}
}
export function ModelListEditor(props: ModelListEditorProps): ReactNode {
- const { models, onChange, probe, operations, t, disabled, onFetchConfig, configBusy, configNotice, configFailure } = props
+ const { models, onChange, probe, operations, t, disabled, onBusyChange } = props
+ const { catalogProvider } = props
const [busy, setBusy] = useState(false)
+ useEffect(() => {
+ onBusyChange(busy)
+ }, [busy, onBusyChange])
const [failure, setFailure] = useState<string | undefined>(undefined)
+ const [inheritedCatalog, setInheritedCatalog] = useState<{
+ provider: string
+ models: readonly LlmDiscoveredModel[]
+ } | undefined>(undefined)
+ useEffect(() => {
+ if (catalogProvider === undefined)
+ return
+ let current = true
+ void operations.discoverModels(probe.settingsNs, { provider: catalogProvider }).then((answer) => {
+ if (!current)
+ return
+ setInheritedCatalog({ provider: catalogProvider, models: answer.kind === 'found' ? answer.models : [] })
+ setFailure(answer.kind === 'refused' ? answer.message : undefined)
+ })
+ return () => {
+ current = false
+ }
+ }, [catalogProvider, operations, probe.settingsNs])
+ const catalog = inheritedCatalog?.provider === catalogProvider ? inheritedCatalog?.models : undefined
+ const inputDefaults = useMemo(() => new Map(catalog?.map(model => [model.id, model.inputModalities])), [catalog])
const [candidates, setCandidates] = useState<readonly LlmDiscoveredModel[] | undefined>(undefined)
- const [picked, setPicked] = useState<ReadonlySet<string>>(() => new Set())
+ const [picked, setPicked] = useState<ReadonlySet<string>>(new Set())
const [candidateQuery, setCandidateQuery] = useState('')
+ const [expanded, setExpanded] = useState<ReadonlySet<number>>(new Set())
- const [expanded, setExpanded] = useState<ReadonlySet<number>>(() => new Set())
-
- const [editing, setEditing] = useState<ReadonlyMap<string, CapacityBuffer>>(() => new Map())
+ const [editing, setEditing] = useState<ReadonlyMap<string, string>>(new Map())
const bufferKey = (index: number, field: CapacityField): string => `${String(index)}:${field}`
- const patch = (index: number, next: Record<string, unknown>): void => {
- onChange(models.map((model, at) => {
- if (at !== index)
- return model
- const cleared = new Set(
- Object.entries(next).filter(([, value]) => value === undefined || value === '').map(([key]) => key),
- )
- return Object.fromEntries(
- Object.entries({ ...model, ...next }).filter(([key]) => !cleared.has(key)),
- )
- }))
- }
-
- const editCapacity = (index: number, field: CapacityField, text: string): void => {
- const value = parseCapacity(text)
- setEditing(current => new Map(current).set(bufferKey(index, field), { text, value }))
- patch(index, { [field]: value })
- }
-
- /**
- * 输入框显示什么:打字期间用缓冲区,存量值被外部改写(端点配置)后立刻改读存量值。
- *
- * 只认「解析得出的数字与存量一致」的缓冲区,所以端点写回新容量时不会还被一行旧文本盖着;
- * 解析不出数字(未写完的输入)时保留原文,好让保存期的报错能指着用户还看得见的那一行。
- */
- const capacityText = (model: ModelDraft, index: number, field: CapacityField): string => {
- const buffer = editing.get(bufferKey(index, field))
- if (buffer === undefined || buffer.value === undefined || Number.isNaN(buffer.value))
- return buffer?.text ?? capacitySpelling(numberOf(model, field))
- return buffer.value === numberOf(model, field) ? buffer.text : capacitySpelling(numberOf(model, field))
- }
+ const capacityText = (model: ModelDraft, index: number, field: CapacityField): string =>
+ editing.get(bufferKey(index, field)) ?? capacitySpelling(numberOf(model, field))
const reindexOnRemove = (
- current: ReadonlyMap<string, CapacityBuffer>,
+ current: ReadonlyMap<string, string>,
index: number,
- ): Map<string, CapacityBuffer> => {
- const next = new Map<string, CapacityBuffer>()
+ ): Map<string, string> => {
+ const next = new Map<string, string>()
for (const [key, value] of current) {
const at = Number(key.slice(0, key.indexOf(':')))
if (at === index)
@@ -223,6 +130,25 @@ export function ModelListEditor(props: ModelListEditorProps): ReactNode {
})
}
+ const patch = (index: number, next: Record<string, string | number | undefined>): void => {
+ onChange(models.map((model, at) => {
+ if (at !== index)
+ return model
+
+ const cleared = new Set(
+ Object.entries(next).filter(([, value]) => value === undefined || value === '').map(([key]) => key),
+ )
+ return Object.fromEntries(
+ Object.entries({ ...model, ...next }).filter(([key]) => !cleared.has(key)),
+ )
+ }))
+ }
+
+ const editCapacity = (index: number, field: CapacityField, text: string): void => {
+ setEditing(current => new Map(current).set(bufferKey(index, field), text))
+ patch(index, { [field]: parseCapacity(text) })
+ }
+
const fetchModels = async (): Promise<void> => {
setBusy(true)
setFailure(undefined)
@@ -238,6 +164,8 @@ export function ModelListEditor(props: ModelListEditorProps): ReactNode {
return
}
const found = answer.models
+ if (catalogProvider !== undefined)
+ setInheritedCatalog({ provider: catalogProvider, models: found })
if (found.length === 0) {
setFailure(t('fetchEmpty'))
return
@@ -303,6 +231,14 @@ export function ModelListEditor(props: ModelListEditorProps): ReactNode {
}
const askable = probe.provider !== undefined || (probe.baseURL !== undefined && probe.baseURL.length > 0)
+ const target = {
+ settingsNs: probe.settingsNs,
+ profilePath: [],
+ ...probe.provider === undefined ? {} : { provider: probe.provider },
+ ...probe.baseURL === undefined ? {} : { baseURL: probe.baseURL },
+ ...probe.api === undefined ? {} : { api: probe.api },
+ ...probe.apiKey === undefined ? {} : { apiKey: probe.apiKey },
+ }
return (
<section className={styles.modelCatalog} aria-label={t('models')}>
<div className={styles.modelListHead}>
@@ -339,203 +275,74 @@ export function ModelListEditor(props: ModelListEditorProps): ReactNode {
>
{busy ? t('fetching') : t('fetchModels')}
</button>
- <button
- type="button"
- className={styles.linkButton}
- disabled={disabled || configBusy || models.length === 0}
- title={t('autoConfigureModelsHint')}
- onClick={() => { onFetchConfig() }}
- >
- {t('autoConfigureModels')}
- </button>
+ <AutoConfigAllButton
+ t={modelExtrasTranslate}
+ models={models}
+ probe={target}
+ disabled={disabled}
+ onApply={(next) => { onChange([...next]) }}
+ />
</div>
- {configFailure === undefined ? null : <p className={styles.error}>{configFailure}</p>}
- {configNotice === undefined ? null : <p className={styles.advancedHint}>{configNotice}</p>}
{models.length === 0 ? <p className={styles.modelEmpty}>{t('modelsEmpty')}</p> : null}
- {models.map((model, index) => (
- <div key={index} className={styles.modelEntry}>
- <div className={styles.modelRow}>
- <input
- className={styles.input}
- type="text"
- value={textOf(model, 'id')}
- placeholder={t('modelId')}
- aria-label={`${t('modelId')} ${index + 1}`}
- disabled={disabled}
- onChange={(event) => { patch(index, { id: event.target.value }) }}
- />
- <input
- className={styles.input}
- type="text"
- value={textOf(model, 'name')}
- placeholder={t('modelName')}
- aria-label={`${t('modelName')} ${index + 1}`}
- disabled={disabled}
- onChange={(event) => { patch(index, { name: event.target.value === '' ? undefined : event.target.value }) }}
- />
- {hasModelConfig(model)
- ? null
- : (
- <button
- type="button"
- className={styles.linkButton}
- disabled={disabled || configBusy}
- title={t('fetchModelConfigHint')}
- onClick={() => { onFetchConfig([textOf(model, 'id')]) }}
- >
- {configBusy ? t('fetchingConfig') : t('fetchModelConfig')}
- </button>
- )}
- <button
- type="button"
- className={styles.iconButton}
- aria-label={`${t('modelAdvanced')} ${index + 1}`}
- aria-expanded={expanded.has(index)}
- title={t('modelAdvanced')}
- onClick={() => { toggleExpanded(index) }}
- >
- <IconChevron open={expanded.has(index)} />
- </button>
- <button
- type="button"
- className={`${styles.iconButton} ${styles.iconButtonDanger}`}
- aria-label={`${t('removeModel')} ${index + 1}`}
- title={t('removeModel')}
- disabled={disabled}
- onClick={() => {
- onChange(models.filter((_model, at) => at !== index))
-
- setExpanded((current) => {
- const next = new Set<number>()
- for (const at of current) {
- if (at < index)
- next.add(at)
- else if (at > index)
- next.add(at - 1)
- }
- return next
- })
- setEditing(current => reindexOnRemove(current, index))
- }}
- >
- <IconTrash />
- </button>
- </div>
- {expanded.has(index)
- ? (
- <div className={styles.modelAdvanced} style={ADVANCED_AREA_STYLE}>
- <div style={ADVANCED_ROW_STYLE}>
- <div style={ADVANCED_CAPACITIES_STYLE}>
- <label className={styles.modelField} style={ADVANCED_CAPACITY_STYLE}>
- <span className={styles.modelFieldLabel}>{t('modelContextWindow')}</span>
- <input
- className={styles.input}
- type="text"
- inputMode="numeric"
- value={capacityText(model, index, 'contextWindow')}
- placeholder={CAPACITY_HINT.contextWindow}
- aria-label={`${t('modelContextWindow')} ${index + 1}`}
- disabled={disabled}
- onChange={(event) => { editCapacity(index, 'contextWindow', event.target.value) }}
- />
- </label>
- <label className={styles.modelField} style={ADVANCED_CAPACITY_STYLE}>
- <span className={styles.modelFieldLabel}>{t('modelMaxTokens')}</span>
- <input
- className={styles.input}
- type="text"
- inputMode="numeric"
- value={capacityText(model, index, 'maxTokens')}
- placeholder={CAPACITY_HINT.maxTokens}
- aria-label={`${t('modelMaxTokens')} ${index + 1}`}
- disabled={disabled}
- onChange={(event) => { editCapacity(index, 'maxTokens', event.target.value) }}
- />
- </label>
- </div>
- <div style={ADVANCED_SWITCHES_STYLE}>
- <div className={styles.modelField}>
- <span className={styles.modelFieldLabel} title={t('imageInputHint')}>{t('imageInput')}</span>
- <div className={styles.modelSwitchRow}>
- <Switch
- checked={supportsImageInput(model)}
- disabled={disabled}
- label={`${t('imageInput')} ${index + 1}`}
- title={t('imageInputHint')}
- onChange={(next) => { patch(index, { input: imageInputValue(next) }) }}
- />
- </div>
- </div>
- <div className={styles.modelField}>
- <span className={styles.modelFieldLabel} title={t('thinkingModeHint')}>{t('thinkingMode')}</span>
- <div className={styles.modelSwitchRow}>
- <Switch
- checked={supportsThinking(model)}
- disabled={disabled}
- label={`${t('thinkingMode')} ${index + 1}`}
- title={t('thinkingModeHint')}
- onChange={(next) => {
- patch(index, { reasoningEfforts: next ? enableThinking(model) : false })
- }}
- />
- </div>
- </div>
- {probe.api === TEMPLATE_COMPAT_PROTOCOL
- ? (
- <div className={styles.modelField}>
- <span className={styles.modelFieldLabel} title={t('developerRoleHint')}>
- {t('developerRole')}
- </span>
- <div className={styles.modelSwitchRow}>
- <Switch
- checked={supportsTemplateThinking(model)}
- disabled={disabled}
- label={`${t('developerRole')} ${index + 1}`}
- title={t('developerRoleHint')}
- onChange={(next) => { patch(index, { compat: templateThinkingCompat(model, next) }) }}
- />
- </div>
- </div>
- )
- : null}
- </div>
- </div>
- {supportsThinking(model)
- ? (
- <div className={styles.modelEfforts} role="group" aria-label={`${t('thinkingLevels')} ${index + 1}`}>
- {THINKING_LEVELS.map(level => (
- <label key={level} className={styles.modelEffortChip}>
- <input
- type="checkbox"
- checked={declaredThinkingLevels(model).includes(level)}
- disabled={disabled}
- onChange={(event) => {
- patch(index, {
- reasoningEfforts: toggleThinkingLevel(
- thinkingEffortsOf(model),
- level,
- event.target.checked,
- ),
- })
- }}
- />
- {level}
- </label>
- ))}
- </div>
- )
- : null}
- </div>
- )
- : null}
- </div>
- ))}
+ <div className={styles.modelList}>
+ {models.map((model, index) => (
+ <ModelRow
+ key={index}
+ model={model}
+ position={index + 1}
+ inputField="input"
+ inputFallback={inputDefaults.get(textOf(model, 'id')) ?? props.defaultInput}
+ inputLoading={catalogProvider !== undefined && catalog === undefined}
+ expanded={expanded.has(index)}
+ disabled={disabled}
+ t={t}
+ contextWindow={{
+ value: capacityText(model, index, 'contextWindow'),
+ placeholder: CAPACITY_HINT.contextWindow,
+ onChange: (text) => { editCapacity(index, 'contextWindow', text) },
+ }}
+ maxTokens={{
+ value: capacityText(model, index, 'maxTokens'),
+ placeholder: CAPACITY_HINT.maxTokens,
+ onChange: (text) => { editCapacity(index, 'maxTokens', text) },
+ }}
+ onFieldChange={(field, value) => { patch(index, { [field]: value }) }}
+ onChange={(next) => { onChange(models.map((row, at) => at === index ? next : row)) }}
+ onToggle={() => { toggleExpanded(index) }}
+ trailing={(
+ <ModelFetchConfigButton
+ t={modelExtrasTranslate}
+ modelId={typeof model.id === 'string' ? model.id : ''}
+ models={models}
+ probe={target}
+ disabled={disabled}
+ onApply={(next) => { onChange([...next]) }}
+ />
+ )}
+ onRemove={() => {
+ onChange(models.filter((_model, at) => at !== index))
+ setExpanded((current) => {
+ const next = new Set<number>()
+ for (const at of current) {
+ if (at < index)
+ next.add(at)
+ else if (at > index)
+ next.add(at - 1)
+ }
+ return next
+ })
+ setEditing(current => reindexOnRemove(current, index))
+ }}
+ />
+ ))}
+ </div>
<button
type="button"
className={styles.addModelButton}
disabled={disabled}
onClick={() => { onChange([...models, { id: '' }]) }}
>
+ <Plus width={14} height={14} />
{t('addModel')}
</button>
{failure !== undefined ? <p className={styles.error}>{failure}</p> : null}
diff --git a/packages/dsh-tauri-model-config/src/client/models/ModelRow.tsx b/packages/dsh-tauri-model-config/src/client/models/ModelRow.tsx
new file mode 100644
index 00000000..df285c39
--- /dev/null
+++ b/packages/dsh-tauri-model-config/src/client/models/ModelRow.tsx
@@ -0,0 +1,110 @@
+import type { ReactNode } from 'react'
+import type { DeepSeekModelDraft } from './DeepSeekModelsEditor.tsx'
+import type { ModelsKey } from './locales.ts'
+import { ChevronDown, ChevronRight, TrashBin } from 'dsh-tauri-ui/client'
+import { ModelInputTypes } from './ModelInputTypes.tsx'
+import { modelStyles as styles } from './styles.ts'
+
+interface CapacityInput {
+ value: string
+ placeholder: string
+ onChange: (value: string) => void
+ onBlur?: () => void
+}
+
+interface ModelRowProps {
+ model: DeepSeekModelDraft
+ position: number
+ inputField: 'inputModalities' | 'input'
+ inputFallback?: readonly string[] | undefined
+ inputLoading?: boolean
+ expanded: boolean
+ disabled: boolean
+ t: (key: ModelsKey) => string
+ contextWindow: CapacityInput
+ maxTokens: CapacityInput
+ onFieldChange: (field: 'id' | 'name', value: string | undefined) => void
+ onIdBlur?: (value: string) => void
+ onChange: (model: DeepSeekModelDraft) => void
+ onToggle: () => void
+ onRemove: () => void
+ trailing?: ReactNode
+}
+
+export function ModelRow(props: ModelRowProps): ReactNode {
+ const { model, position, t, disabled } = props
+ return (
+ <div className={styles.modelEntry}>
+ <div className={styles.modelRow}>
+ {(['id', 'name'] as const).map(field => (
+ <input
+ key={field}
+ className={styles.input}
+ type="text"
+ value={typeof model[field] === 'string' ? model[field] : ''}
+ placeholder={t(field === 'id' ? 'modelId' : 'modelName')}
+ aria-label={`${t(field === 'id' ? 'modelId' : 'modelName')} ${String(position)}`}
+ disabled={disabled}
+ onChange={(event) => {
+ const value = event.target.value
+ props.onFieldChange(field, field === 'name' && value === '' ? undefined : value)
+ }}
+ onBlur={field === 'id' ? event => props.onIdBlur?.(event.target.value) : undefined}
+ />
+ ))}
+ {props.trailing}
+ <button
+ type="button"
+ className={styles.iconButton}
+ aria-label={`${t('modelAdvanced')} ${String(position)}`}
+ aria-expanded={props.expanded}
+ title={t('modelAdvanced')}
+ onClick={props.onToggle}
+ >
+ {props.expanded ? <ChevronDown /> : <ChevronRight />}
+ </button>
+ <button
+ type="button"
+ className={`${styles.iconButton} ${styles.iconButtonDanger}`}
+ aria-label={`${t('removeModel')} ${String(position)}`}
+ title={t('removeModel')}
+ disabled={disabled}
+ onClick={props.onRemove}
+ >
+ <TrashBin width={14} height={14} />
+ </button>
+ </div>
+ {props.expanded
+ ? (
+ <div className={styles.modelAdvanced}>
+ {(['contextWindow', 'maxTokens'] as const).map(field => (
+ <label className={styles.modelField} key={field}>
+ <span className={styles.modelFieldLabel}>{t(field)}</span>
+ <input
+ className={styles.input}
+ type="text"
+ inputMode="numeric"
+ value={props[field].value}
+ placeholder={props[field].placeholder}
+ aria-label={`${t(field)} ${String(position)}`}
+ disabled={disabled}
+ onChange={(event) => { props[field].onChange(event.target.value) }}
+ onBlur={props[field].onBlur}
+ />
+ </label>
+ ))}
+ <ModelInputTypes
+ model={model}
+ field={props.inputField}
+ position={position}
+ fallback={props.inputFallback}
+ disabled={disabled || props.inputLoading === true}
+ t={t}
+ onChange={props.onChange}
+ />
+ </div>
+ )
+ : null}
+ </div>
+ )
+}
diff --git a/packages/dsh-tauri-model-config/src/client/models/ModelsSection.tsx b/packages/dsh-tauri-model-config/src/client/models/ModelsSection.tsx
index 47f4ed47..4074a20b 100644
--- a/packages/dsh-tauri-model-config/src/client/models/ModelsSection.tsx
+++ b/packages/dsh-tauri-model-config/src/client/models/ModelsSection.tsx
@@ -1,29 +1,32 @@
import type { InjectFace, PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots'
import type { ReactNode } from 'react'
-import type { ConfigFileOpen } from '../service/model-config.ts'
+import type { SettingsNamespaceView } from '../types/remotes.ts'
import type { en } from './locales.ts'
-
import type { ModelsOperations } from './operations.ts'
import type { ProviderEditorProps } from './ProviderEditor.tsx'
+
import type { SettingsSchemaOperations } from './schema-operations.ts'
import type {} from './slot-contract.ts'
import type { ModelsSettingsStore, ProviderRow } from './store.ts'
import { Button, Modal } from '@deepseek-ai/dsh-client-ui-primitives'
-import { Plus } from 'dsh-tauri-ui/client'
-import { useEffect, useState } from 'react'
-import { ConfigEditor } from '../components/config-editor'
-import { withDetail, withPath } from '../service/model-config.utils.ts'
-import { ensurePresets } from '../service/presets.ts'
+import {
+ loadEditor,
+ ModelConfigToolbar,
+ modelExtrasTranslate,
+ openConfigFile,
+ Plus,
+ saveEditor,
+ SegmentedControl,
+} from 'dsh-tauri-ui/client'
+import { useEffect, useId, useState } from 'react'
import { CustomProviderCard } from './CustomProviderCard.tsx'
import { ProviderEditor } from './ProviderEditor.tsx'
import { deriveKeyRef, protocolChoices, providerUsable } from './store.ts'
import { modelStyles as styles } from './styles.ts'
export interface ModelsSectionInjected {
-
controller: ModelsSettingsStore
hooks: {
-
snapshot: ModelsSettingsStore['store']
}
@@ -32,10 +35,10 @@ export interface ModelsSectionInjected {
schema: SettingsSchemaOperations
t: (key: keyof typeof en) => string
-
- openConfig: () => Promise<ConfigFileOpen>
}
+type AddMode = 'catalog' | 'custom'
+
type ModelsChildSlots = 'settings.models.provider-card' | 'settings.models.footer'
type ModelsRenderSlot = PropsRenderSlots<ModelsChildSlots>['renderSlot']
@@ -45,21 +48,27 @@ export type ModelsSectionProps = Partial<InjectFace<ModelsSectionInjected>> & Pr
type ModelsSectionFace = InjectFace<ModelsSectionInjected>
export interface ProviderIdentity {
-
provider: string
-
displayName: string
}
interface EditorTarget extends ProviderIdentity {
settingsNs: string
settingsPath: readonly string[]
-
credentialRef?: string
-
declared?: boolean
}
+interface AddableRow {
+ row: ProviderRow
+ namespace: SettingsNamespaceView
+}
+
+interface CatalogDraft {
+ target: EditorTarget
+ namespace: SettingsNamespaceView
+}
+
interface ProviderEditorRenderProps extends Pick<
ProviderEditorProps,
'namespace' | 'schema' | 'operations' | 't' | 'readOnly' | 'onClose'
@@ -143,45 +152,45 @@ export function providerCopy(template: string, target: ProviderIdentity): string
}
export function ModelsSection(props: ModelsSectionProps): ReactNode {
- const { controller, useSnapshot, operations, schema, t, openConfig, renderSlot } = props
+ const { controller, useSnapshot, operations, schema, t, renderSlot } = props
if (
controller === undefined || useSnapshot === undefined || operations === undefined
- || schema === undefined || t === undefined || openConfig === undefined
+ || schema === undefined || t === undefined
) {
return null
}
- return <Loaded injected={{ controller, useSnapshot, operations, schema, t, openConfig }} renderSlot={renderSlot} />
+ return <Loaded injected={{ controller, useSnapshot, operations, schema, t }} renderSlot={renderSlot} />
}
function Loaded({ injected, renderSlot }: { injected: ModelsSectionFace, renderSlot: ModelsRenderSlot }): ReactNode {
const { controller, operations, schema, t } = injected
const state = injected.useSnapshot(snapshot => snapshot)
const [editing, setEditing] = useState<EditorTarget | undefined>(undefined)
- const [adding, setAdding] = useState(false)
+ const [addOpen, setAddOpen] = useState(false)
+ const [addMode, setAddMode] = useState<AddMode>('catalog')
+
+ const [visited, setVisited] = useState<ReadonlySet<AddMode>>(() => new Set())
+
+ const [catalogBusy, setCatalogBusy] = useState(false)
+ const [customBusy, setCustomBusy] = useState(false)
+
+ const addId = useId()
const [deleteTarget, setDeleteTarget] = useState<EditorTarget | undefined>(undefined)
const [deleting, setDeleting] = useState(false)
const [deleteFailure, setDeleteFailure] = useState<string | undefined>(undefined)
const [savedTarget, setSavedTarget] = useState<ProviderIdentity | undefined>(undefined)
- const [declaring, setDeclaring] = useState(false)
const [dismissedSetup, setDismissedSetup] = useState<ReadonlySet<string>>(() => new Set())
- const [configOpen, setConfigOpen] = useState<{ text: string, failed: boolean } | undefined>(undefined)
-
- // 能力表是自动配置填图片与思考的来源,进页面就先取回来,别让第一次点击等下载。
+ const [editor, setEditor] = useState<Awaited<ReturnType<typeof loadEditor>>>()
useEffect(() => {
- void ensurePresets()
- }, [])
-
- const openConfigFile = (): void => {
- setConfigOpen(undefined)
- void injected.openConfig().then((outcome) => {
- setConfigOpen(outcome.ok
- ? {
- text: withPath(outcome.opened === 'file' ? t('openConfigFileLanded') : t('openConfigFileDirectory'), outcome.path),
- failed: false,
- }
- : { text: withDetail(t('openConfigFileFailed'), outcome.error), failed: true })
+ let current = true
+ void loadEditor().then((preference) => {
+ if (current)
+ setEditor(preference)
})
- }
+ return () => {
+ current = false
+ }
+ }, [])
const announceSaved = (target: ProviderIdentity): void => {
void controller.load().then(() => {
@@ -189,10 +198,15 @@ function Loaded({ injected, renderSlot }: { injected: ModelsSectionFace, renderS
})
}
- const closeEditor = (changed: boolean, target: ProviderIdentity): void => {
+ const closeAdd = (): void => {
setEditing(undefined)
- setAdding(false)
- setDeclaring(false)
+ setAddOpen(false)
+ setCatalogBusy(false)
+ setCustomBusy(false)
+ }
+
+ const closeEditor = (changed: boolean, target: ProviderIdentity): void => {
+ closeAdd()
if (changed)
announceSaved(target)
}
@@ -250,43 +264,50 @@ function Loaded({ injected, renderSlot }: { injected: ModelsSectionFace, renderS
const anyUsable = state.rows.some(providerUsable)
const configured = state.rows.filter(row => row.configured)
const configurable = state.rows.filter(row => state.namespaces.has(row.entry.settingsNs))
- const addable = configurable.filter(row => !row.configured)
- const addTarget = adding ? editing : undefined
- const addNamespace = addTarget === undefined ? undefined : state.namespaces.get(addTarget.settingsNs)
-
- const addRow = addTarget === undefined
+ const addable: AddableRow[] = state.rows.flatMap((row) => {
+ const namespace = state.namespaces.get(row.entry.settingsNs)
+ return namespace === undefined || row.configured ? [] : [{ row, namespace }]
+ })
+
+ const piAi = state.namespaces.get('llm-pi-ai')
+ const protocols = protocolChoices(piAi, schema)
+
+ const catalogOffered = configurable.length > 0
+ const catalogEnabled = addable.length > 0
+ const customOffered = piAi !== undefined
+ const customEnabled = protocols.length > 0
+ const bothOffered = catalogOffered && customOffered
+ const mode: AddMode = bothOffered ? addMode : customOffered ? 'custom' : 'catalog'
+ const mounted = (candidate: AddMode): boolean => mode === candidate || visited.has(candidate)
+ const switchLocked = catalogBusy || customBusy
+
+ const draft = ((): CatalogDraft | undefined => {
+ if (!addOpen || !catalogOffered)
+ return undefined
+ const kept = editing === undefined ? undefined : state.namespaces.get(editing.settingsNs)
+ if (editing !== undefined && kept !== undefined)
+ return { target: editing, namespace: kept }
+ const first = addable[0]
+ return first === undefined ? undefined : { target: targetOf(first.row), namespace: first.namespace }
+ })()
+
+ const addRow = draft === undefined
? undefined
- : state.rows.find(row => row.entry.provider === addTarget.provider)
-
- const protocols = protocolChoices(state.namespaces.get('llm-pi-ai'), schema)
+ : state.rows.find(row => row.entry.provider === draft.target.provider)
return (
<div className={styles.section}>
- <div className={styles.titleRow}>
- <h2 className={styles.title}>{t('title')}</h2>
- <div className={styles.rowActions}>
- <ConfigEditor t={t} />
- <button
- type="button"
- className={styles.linkButton}
- title={t('openConfigFileHint')}
- onClick={openConfigFile}
- >
- {t('openConfigFile')}
- </button>
- </div>
- </div>
+ <h2 className={styles.title}>{t('title')}</h2>
+ <ModelConfigToolbar
+ t={modelExtrasTranslate}
+ editor={editor}
+ onEditorChange={(next) => {
+ setEditor(next)
+ void saveEditor(next)
+ }}
+ onOpenConfig={() => { void openConfigFile() }}
+ />
<p className={styles.intro}>{t('intro')}</p>
- {configOpen === undefined
- ? null
- : (
- <p
- role={configOpen.failed ? 'alert' : 'status'}
- className={configOpen.failed ? styles.error : styles.savedNotice}
- >
- {configOpen.text}
- </p>
- )}
{!state.writable && state.status === 'ready' ? <p className={styles.notice}>{t('readOnly')}</p> : null}
{savedIdentity === undefined
? null
@@ -326,7 +347,7 @@ function Loaded({ injected, renderSlot }: { injected: ModelsSectionFace, renderS
</li>
)
}
- const open = !adding && editing?.provider === row.entry.provider
+ const open = !addOpen && editing?.provider === row.entry.provider
const credentialConfigured = row.credential?.configured === true
const credentialMissing = !credentialConfigured
&& row.apiKeyEnv !== undefined
@@ -368,8 +389,7 @@ function Loaded({ injected, renderSlot }: { injected: ModelsSectionFace, renderS
onClick={() => {
setSavedTarget(undefined)
- setDeclaring(false)
- setAdding(false)
+ setAddOpen(false)
setEditing(open ? undefined : target)
}}
>
@@ -416,110 +436,152 @@ function Loaded({ injected, renderSlot }: { injected: ModelsSectionFace, renderS
})}
</ul>
<div className={styles.addBlock}>
- {addTarget !== undefined && addNamespace !== undefined
+ {addOpen
? (
<div className={styles.addCard}>
- <div className={styles.field}>
- <span className={styles.fieldLabel}>{t('provider')}</span>
- <select
- className={`${styles.input} ${styles.selectInput}`}
- value={addTarget.provider}
- aria-label={t('provider')}
- onChange={(event) => {
- const row = addable.find(candidate => candidate.entry.provider === event.target.value)
-
- if (row === undefined)
- return
- setEditing(targetOf(row))
- }}
- >
- {addable.map(row => (
- <option key={row.entry.provider} value={row.entry.provider}>{row.entry.displayName}</option>
- ))}
- </select>
+ <div className={styles.addModes}>
+ {bothOffered
+ ? (
+ <SegmentedControl
+ id={addId}
+ label={t('addMode')}
+ value={mode}
+ disabled={switchLocked}
+ options={[
+ {
+ value: 'catalog',
+ label: t('addCatalog'),
+ disabled: !catalogEnabled,
+ ...catalogEnabled ? {} : { title: t('addCatalogExhausted') },
+ },
+ {
+ value: 'custom',
+ label: t('addCustom'),
+ disabled: !customEnabled,
+ ...customEnabled ? {} : { title: t('addCustomUnavailable') },
+ },
+ ]}
+ onChange={(next) => {
+ if (next !== 'catalog' && next !== 'custom')
+ return
+ setAddMode(next)
+ setVisited(previous => new Set([...previous, next]))
+ }}
+ />
+ )
+ : (
+
+ <div className={styles.editorHeader}>
+ <span className={styles.editorTitle}>{t(mode === 'catalog' ? 'addCatalog' : 'addCustom')}</span>
+ </div>
+ )}
+ <p className={styles.advancedHint}>
+ {t(mode === 'catalog' ? 'addCatalogHint' : 'addCustomHint')}
+ </p>
</div>
- <ProviderEditor
- key={addTarget.provider}
- provider={addTarget.provider}
- displayName={addTarget.displayName}
- hideTitle
- namespace={addNamespace}
- schema={schema}
- settingsPath={addTarget.settingsPath}
- operations={operations}
- t={t}
- readOnly={!state.writable}
- onClose={(changed) => { closeEditor(changed, addTarget) }}
- />
- {addRow === undefined
- ? null
- : renderSlot(
- 'settings.models.provider-card',
- { provider: addRow.entry, configured: addRow.configured, keyConfigured: keyConfiguredOf(addRow) },
- { entryKey: addRow.entry.settingsNs },
- )}
+ {mounted('catalog') && draft !== undefined
+ ? (
+ <div
+ id={`${addId}-catalog-panel`}
+ {...bothOffered ? { 'role': 'tabpanel', 'aria-labelledby': `${addId}-catalog` } : {}}
+ hidden={mode !== 'catalog'}
+ className={styles.addPanel}
+ >
+ <div className={styles.field}>
+ <span className={styles.fieldLabel}>{t('provider')}</span>
+ <select
+ className={`${styles.input} ${styles.selectInput}`}
+ value={draft.target.provider}
+ aria-label={t('provider')}
+ disabled={catalogBusy}
+ onChange={(event) => {
+ const picked = addable.find(candidate => candidate.row.entry.provider === event.target.value)
+
+ if (picked === undefined)
+ return
+ setEditing(targetOf(picked.row))
+ }}
+ >
+ {addable.map(({ row }) => (
+ <option key={row.entry.provider} value={row.entry.provider}>{row.entry.displayName}</option>
+ ))}
+ </select>
+ </div>
+ <ProviderEditor
+ key={draft.target.provider}
+ provider={draft.target.provider}
+ displayName={draft.target.displayName}
+ hideTitle
+ namespace={draft.namespace}
+ schema={schema}
+ settingsPath={draft.target.settingsPath}
+ operations={operations}
+ t={t}
+ readOnly={!state.writable}
+ onClose={(changed) => { closeEditor(changed, draft.target) }}
+ onBusyChange={setCatalogBusy}
+ />
+ {addRow === undefined
+ ? null
+ : renderSlot(
+ 'settings.models.provider-card',
+ { provider: addRow.entry, configured: addRow.configured, keyConfigured: keyConfiguredOf(addRow) },
+ { entryKey: addRow.entry.settingsNs },
+ )}
+ </div>
+ )
+ : null}
+ {mounted('custom') && piAi !== undefined
+ ? (
+ <div
+ id={`${addId}-custom-panel`}
+ {...bothOffered ? { 'role': 'tabpanel', 'aria-labelledby': `${addId}-custom` } : {}}
+ hidden={mode !== 'custom'}
+ className={styles.addPanel}
+ >
+ <CustomProviderCard
+ taken={state.rows.map(row => row.entry.provider)}
+ protocols={protocols}
+ revision={piAi.revision}
+ operations={operations}
+ t={t}
+ readOnly={!state.writable}
+ onClose={(changed) => {
+ closeAdd()
+ if (changed)
+ void controller.load()
+ }}
+ onBusyChange={setCustomBusy}
+ />
+ </div>
+ )
+ : null}
</div>
)
- : declaring
+ : catalogOffered || customOffered
? (
- <div className={styles.addCard}>
- <CustomProviderCard
- taken={state.rows.map(row => row.entry.provider)}
- protocols={protocols}
-
- revision={state.namespaces.get('llm-pi-ai')?.revision ?? 0}
- operations={operations}
- t={t}
- readOnly={!state.writable}
- onClose={(changed) => {
- setDeclaring(false)
- if (changed)
- void controller.load()
- }}
- />
- </div>
- )
- : (
<div className={styles.addActions}>
- {configurable.length > 0 && (
- <button
- type="button"
- className={styles.addButton}
- disabled={addable.length === 0 || !state.writable}
- onClick={() => {
- const first = addable[0]
-
- if (first === undefined)
- return
- setSavedTarget(undefined)
- setDeclaring(false)
- setAdding(true)
- setEditing(targetOf(first))
- }}
- >
- <Plus width={14} height={14} />
- {t('add')}
- </button>
- )}
- {state.namespaces.has('llm-pi-ai') && (
- <button
- type="button"
- className={styles.addButton}
- disabled={protocols.length === 0 || !state.writable}
- onClick={() => {
- setSavedTarget(undefined)
- setAdding(false)
- setEditing(undefined)
- setDeclaring(true)
- }}
- >
- <Plus width={14} height={14} />
- {t('customAdd')}
- </button>
- )}
+ <button
+ type="button"
+ className={styles.addButton}
+ disabled={!state.writable || (!catalogEnabled && !customEnabled)}
+ onClick={() => {
+ const first = addable[0]
+ const initial: AddMode = catalogEnabled ? 'catalog' : 'custom'
+ setSavedTarget(undefined)
+ setEditing(first === undefined ? undefined : targetOf(first.row))
+ setAddMode(initial)
+ setVisited(new Set([initial]))
+ setAddOpen(true)
+ }}
+ >
+ <Plus width={14} height={14} />
+ {t('add')}
+ </button>
</div>
- )}
+ )
+ : null}
</div>
{renderSlot('settings.models.footer', {})}
<Modal
diff --git a/packages/dsh-tauri-model-config/src/client/models/ProviderEditor.tsx b/packages/dsh-tauri-model-config/src/client/models/ProviderEditor.tsx
index 45e39545..13aacf8d 100644
--- a/packages/dsh-tauri-model-config/src/client/models/ProviderEditor.tsx
+++ b/packages/dsh-tauri-model-config/src/client/models/ProviderEditor.tsx
@@ -1,7 +1,7 @@
+import type { JsonValue } from '@deepseek-ai/dsh-util-values'
import type { ReactNode } from 'react'
import type {
CredentialInfo,
- JsonValue,
SettingsNamespaceView,
SettingsPathOpView,
} from '../types/remotes.ts'
@@ -9,9 +9,6 @@ import type { en } from './locales.ts'
import type { ModelsOperations } from './operations.ts'
import type { SettingsSchemaOperations } from './schema-operations.ts'
import { useEffect, useMemo, useState } from 'react'
-import { loadModelCapacities } from '../service/model-config.ts'
-import { mergeModelCards, modelConfigNotice, withDetail } from '../service/model-config.utils.ts'
-import { ensurePresets } from '../service/presets.ts'
import { apiKeyFailure } from './apiKey.ts'
import {
DeepSeekModelsEditor,
@@ -20,48 +17,31 @@ import {
} from './DeepSeekModelsEditor.tsx'
import { EditorFooter } from './EditorFooter.tsx'
import { ModelListEditor } from './ModelListEditor.tsx'
+import { protocolLabel } from './protocol-label.ts'
import { deriveKeyRef, protocolChoices } from './store.ts'
import { modelStyles as styles } from './styles.ts'
type EditorLayout = 'deepseek' | 'pi-ai' | 'unknown'
-const DEEPSEEK_PUBLIC_BASE_URL = 'https://api.deepseek.com'
-
export interface ProviderEditorProps {
-
provider: string
-
displayName: string
-
hideTitle?: boolean
-
declared?: boolean
-
namespace: SettingsNamespaceView
-
schema: SettingsSchemaOperations
-
settingsPath: readonly string[]
-
operations: ModelsOperations
-
t: (key: keyof typeof en) => string
-
readOnly: boolean
-
credentialOnly?: boolean
-
credentialRequired?: boolean
-
autoFocusCredential?: boolean
-
cancelLabelKey?: keyof typeof en
-
submitLabelKey?: keyof typeof en
-
submitBusyLabelKey?: keyof typeof en
-
onClose: (changed: boolean) => void
+ onBusyChange?: (busy: boolean) => void
}
function draftAt(
@@ -123,10 +103,12 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode {
const [keyDraft, setKeyDraft] = useState('')
const [keyState, setKeyState] = useState<CredentialInfo | undefined>(undefined)
const [busy, setBusy] = useState(false)
+ const [listBusy, setListBusy] = useState(false)
+ const { onBusyChange } = props
+ useEffect(() => {
+ onBusyChange?.(busy || listBusy)
+ }, [busy, listBusy, onBusyChange])
const [failure, setFailure] = useState<string | undefined>(undefined)
- const [configBusy, setConfigBusy] = useState(false)
- const [configNotice, setConfigNotice] = useState<string | undefined>(undefined)
- const [configFailure, setConfigFailure] = useState<string | undefined>(undefined)
const [committedOriginal, setCommittedOriginal] = useState<unknown>(
() => schema.getPath(namespace.user, settingsPath),
@@ -277,6 +259,7 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode {
const models = modelDrafts(modelsOverridden ? customModels : inheritedModels())
const defaultContextWindow = schema.getPath(fallback, ['defaultContextWindow'])
const defaultMaxTokens = schema.getPath(fallback, ['maxTokens'])
+ const defaultInput = schema.getPath(fallback, ['defaultInput'])
const keyPlaceholder = keyLocked
? t('keyEnvLocked')
: keyState?.configured === true && props.credentialRequired !== true
@@ -293,37 +276,6 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode {
},
onReset: () => { setDraft(current => schema.deletePath(current, ['models'])) },
}
- const fetchConfig = (targets?: readonly string[]): void => {
- void (async () => {
- setConfigBusy(true)
- setConfigFailure(undefined)
- const [found] = await Promise.all([
- loadModelCapacities({
- settingsNs: namespace.ns,
- profilePath: settingsPath,
- provider: props.provider,
- ...probeBaseURL === undefined ? {} : { baseURL: probeBaseURL },
- ...probeApi === undefined ? {} : { api: probeApi },
- ...keyValue.length === 0 ? {} : { apiKey: keyValue },
- }, operations),
- ensurePresets(),
- ])
- setConfigBusy(false)
- if (!found.ok) {
- setConfigNotice(undefined)
- setConfigFailure(withDetail(t('configUnreachable'), found.error))
- return
- }
- const merged = mergeModelCards(models, found.models, { targets, overwrite: targets === undefined })
- if (merged.applied > 0)
- catalogProps.onChange(merged.models)
- setConfigNotice(modelConfigNotice(merged, {
- applied: t('configApplied'),
- none: t('configNoneApplied'),
- undisclosed: t('configUndisclosed'),
- }))
- })()
- }
return (
<>
<div className={styles.field}>
@@ -375,14 +327,16 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode {
type="text"
value={stringAt(draft, 'baseURL') ?? ''}
placeholder={family === 'deepseek'
- ? DEEPSEEK_PUBLIC_BASE_URL
+ ? t('deepSeekBaseUrl')
: stringAt(fallback, 'baseURL') ?? t('baseUrlDefault')}
+ aria-describedby={family === 'deepseek' ? `${props.provider}-endpoint-hint` : undefined}
aria-label={t('baseUrl')}
disabled={disabled}
onChange={(event) => {
setField('baseURL', event.target.value === '' ? undefined : event.target.value)
}}
/>
+ {family === 'deepseek' ? <span id={`${props.provider}-endpoint-hint`} className={styles.advancedHint}>{t('deepSeekEndpointHint')}</span> : null}
</div>
{ownsIdentity
@@ -398,7 +352,7 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode {
>
{probeApi === undefined ? <option value="">{t('customApiUnset')}</option> : null}
- {protocols.map(choice => <option key={choice} value={choice}>{choice}</option>)}
+ {protocols.map(choice => <option key={choice} value={choice}>{protocolLabel(t, choice)}</option>)}
</select>
</div>
)
@@ -417,13 +371,12 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode {
: (
<ModelListEditor
{...catalogProps}
+ catalogProvider={props.declared === true ? undefined : props.provider}
+ defaultInput={Array.isArray(defaultInput) ? defaultInput : undefined}
probe={probe}
probeBlocked={keyFailure}
operations={operations}
- onFetchConfig={fetchConfig}
- configBusy={configBusy}
- configNotice={configNotice}
- configFailure={configFailure}
+ onBusyChange={setListBusy}
/>
)}
</div>
diff --git a/packages/dsh-tauri-model-config/src/client/models/WelcomeNotice.tsx b/packages/dsh-tauri-model-config/src/client/models/WelcomeNotice.tsx
index e89c4555..442fe352 100644
--- a/packages/dsh-tauri-model-config/src/client/models/WelcomeNotice.tsx
+++ b/packages/dsh-tauri-model-config/src/client/models/WelcomeNotice.tsx
@@ -10,7 +10,6 @@ import { welcomeStyles as css } from './styles.ts'
export interface WelcomeNoticeInjected {
hooks: {
-
welcome: SnapshotStore<WelcomeNoticeState>
}
diff --git a/packages/dsh-tauri-model-config/src/client/models/locales.ts b/packages/dsh-tauri-model-config/src/client/models/locales.ts
index 73831e11..fb7b1b4e 100644
--- a/packages/dsh-tauri-model-config/src/client/models/locales.ts
+++ b/packages/dsh-tauri-model-config/src/client/models/locales.ts
@@ -11,7 +11,14 @@ export const en = {
deleteDescriptionWithCredential: 'Deleting {provider} removes its configuration and stored API key.',
deleteConfirm: 'Delete {provider}',
deleting: 'Deleting {provider}…',
- add: 'Add provider',
+ add: 'Add model provider',
+ addMode: 'How to add',
+ addCatalog: 'Third-party model provider',
+ addCustom: 'Custom model API',
+ addCatalogHint: 'Pick OpenAI, Anthropic, Kimi, or another provider from the built-in catalog and enter its API key.',
+ addCustomHint: 'Connect a relay, a self-hosted server, or any other OpenAI- or Anthropic-compatible endpoint by its base URL, protocol, and models.',
+ addCatalogExhausted: 'Every catalog provider is already configured.',
+ addCustomUnavailable: 'No API protocol is available to declare.',
provider: 'Provider',
close: 'Close',
cancel: 'Cancel',
@@ -32,6 +39,8 @@ export const en = {
customized: 'Customized settings',
baseUrl: 'Base URL',
baseUrlDefault: 'Provider default',
+ deepSeekBaseUrl: 'https://api.deepseek.com/anthropic',
+ deepSeekEndpointHint: 'Use an API endpoint compatible with Anthropic Messages.',
models: 'Models',
modelsInherited: 'Using the adapter defaults',
modelsCustomized: 'Customized model catalog',
@@ -44,7 +53,10 @@ export const en = {
contextWindowPlaceholder: 'Uses the provider default',
maxTokens: 'Max output tokens',
maxTokensPlaceholder: 'Uses the provider default',
- modelAdvanced: 'Capacities',
+ modelAdvanced: 'Model options',
+ modelInputTypes: 'Input types',
+ modelInputText: 'Text',
+ modelInputImage: 'Image',
addModel: 'Add model',
removeModel: 'Delete model',
modelsEmpty: 'No models will be shown in the selector. Unlisted IDs can still be sent directly.',
@@ -56,11 +68,9 @@ export const en = {
modelNameInvalid: 'Display name cannot be empty.',
modelContextInvalid: 'Context window must be a positive count, like 131072, 256K, or 1M.',
modelMaxTokensInvalid: 'Max output tokens must be a positive count, like 8192, 64K, or 1M.',
- advancedHint: 'Other fields live in settings.yaml; edit that section directly.',
+ advancedHint: 'Other fields live in cordis.patch.yml; edit that section directly.',
modelCapacityInvalid: 'A capacity must be a number, optionally suffixed K or M.',
modelDuplicate: 'Each model ID may appear once.',
- modelContextWindow: 'Context window',
- modelMaxTokens: 'Max output tokens',
fetchModels: 'Fetch available models',
fetching: 'Asking the provider\u2026',
fetchNeedsBaseUrl: 'Enter the base URL first, then fetch.',
@@ -72,8 +82,6 @@ export const en = {
fetchSelectAll: 'Select all',
fetchDeselectAll: 'Deselect all',
fetchAdopt: 'Add selected',
- customAdd: 'Add a custom provider',
- customTitle: 'Custom provider',
customTag: 'Custom',
customRoute: 'Provider ID',
customRouteHint: 'Lowercase identifier, starting with a letter, that uniquely names this provider in requests and as its credential name.',
@@ -82,10 +90,14 @@ export const en = {
customDisplayName: 'Display name',
customApi: 'API protocol',
customApiUnset: 'Not selected',
+ protocolOpenAiCompletions: 'OpenAI Chat Completions',
+ protocolOpenAiResponses: 'OpenAI Responses',
+ protocolAnthropicMessages: 'Anthropic Messages',
customNeedsBaseUrl: 'A custom provider needs a base URL.',
customBaseUrlInvalid: 'Enter a valid HTTP or HTTPS URL.',
customNeedsModels: 'A custom provider needs at least one model.',
customBaseUrlPlaceholder: 'https://gateway.example/v1',
+ customAnthropicBaseUrlPlaceholder: 'https://gateway.example',
settingsPathUnresolvable: 'unresolvable settings path',
create: 'Create provider',
creating: 'Creating\u2026',
@@ -99,38 +111,6 @@ export const en = {
onboardingSave: 'Save and continue',
onboardingSaving: 'Saving…',
keyRequired: 'Enter an API key to continue.',
- openConfigFile: 'Open config file',
- openConfigFileHint: 'Open the settings file that holds every model definition',
- openConfigFileLanded: 'Opened {path}',
- openConfigFileDirectory: 'The config file does not exist yet; opened {path} instead',
- openConfigFileFailed: 'Could not open the config file. Check that your editor is installed, or change it in Text editor: {detail}',
- textEditor: 'Text editor',
- textEditorHint: 'This preference applies only to opening config files in the Models page.',
- editorVSCode: 'VS Code',
- editorCursor: 'Cursor',
- editorSystem: 'System default (recommended)',
- editorCustom: 'Custom editor',
- editorCommand: 'Application name or executable path',
- editorCommandPlaceholder: 'App name or executable path',
- editorCommandHint: 'On macOS, enter an app name or .app path. On Windows, use the full .exe path. On Linux, use an executable name or path. Do not add quotes or arguments.',
- editorLoadFailed: 'Could not load the editor preference: {detail}',
- editorSaveFailed: 'Could not save the editor preference: {detail}',
- imageInput: 'Image input',
- imageInputHint: 'Declare whether this model accepts image content',
- thinkingMode: 'Thinking mode',
- thinkingLevels: 'Thinking levels',
- thinkingModeHint: 'Declare whether this model thinks, then tick the levels it offers',
- developerRole: 'Disable developer role',
- developerRoleHint: 'Turn this on for an endpoint that rejects the developer role: system prompts stay system, and the effort travels through chat_template_kwargs; writes compat supportsDeveloperRole=false, thinkingFormat=chat-template and chatTemplateKwargs.reasoning_effort={$var: thinking.effort}',
- fetchModelConfig: 'Fetch config',
- fetchModelConfigHint: 'Fill in this model\'s limits from the endpoint and its image/thinking capabilities from the model capability table',
- autoConfigureModels: 'Configure all models',
- autoConfigureModelsHint: 'Fill in limits from the endpoint and image/thinking capabilities from the model capability table for every listed model',
- fetchingConfig: 'Fetching…',
- configUnreachable: 'Could not read the model list: {detail}',
- configNoneApplied: 'Neither the endpoint nor the capability table had anything to write for these models.',
- configApplied: 'Configured {n} model(s).',
- configUndisclosed: '{n} model(s) were not disclosed by the endpoint.',
}
export type ModelsKey = keyof typeof en
@@ -138,7 +118,7 @@ export type ModelsKey = keyof typeof en
export const zh: { [Key in keyof typeof en]: string } = {
nav: '模型',
title: '模型',
- intro: '填入各提供方的 API 密钥即可使用其模型。',
+ intro: '填入各提供商的 API 密钥即可使用其模型。',
edit: '编辑',
editProvider: '编辑 {provider}',
remove: '删除',
@@ -148,8 +128,15 @@ export const zh: { [Key in keyof typeof en]: string } = {
deleteDescriptionWithCredential: '删除 {provider} 会移除其配置和存储的 API 密钥。',
deleteConfirm: '删除 {provider}',
deleting: '正在删除 {provider}…',
- add: '添加提供方',
- provider: '提供方',
+ add: '添加模型提供商',
+ addMode: '添加方式',
+ addCatalog: '第三方模型提供商',
+ addCustom: '自定义模型 API',
+ addCatalogHint: '从内置目录中选择 OpenAI、Anthropic、Kimi 等提供商,填入其 API 密钥即可使用。',
+ addCustomHint: '连接中转站、自部署服务或其他兼容 OpenAI / Anthropic 协议的接口,需填写 API 地址、协议和模型。',
+ addCatalogExhausted: '目录中的提供商都已添加。',
+ addCustomUnavailable: '没有可用的 API 协议。',
+ provider: '提供商',
close: '关闭',
cancel: '取消',
apply: '保存',
@@ -158,7 +145,7 @@ export const zh: { [Key in keyof typeof en]: string } = {
credentialConfigured: 'API 密钥已配置',
credentialMissing: 'API 密钥缺失',
readOnly: '当前部署的设置文档为只读。',
- loadFailed: '加载提供方目录失败',
+ loadFailed: '加载提供商目录失败',
conflict: '这张卡片打开期间,这些设置已被其他地方改动。请关闭后重新打开,在当前值上编辑。',
retry: '重试',
keyInput: 'API 密钥',
@@ -168,7 +155,9 @@ export const zh: { [Key in keyof typeof en]: string } = {
keyEnvLocked: '由启动环境提供(只读)',
customized: '自定义设置',
baseUrl: 'API 地址',
- baseUrlDefault: '提供方默认',
+ baseUrlDefault: '提供商默认',
+ deepSeekBaseUrl: 'https://api.deepseek.com/anthropic',
+ deepSeekEndpointHint: '请填写兼容 Anthropic Messages 协议的 API 地址。',
models: '模型目录',
modelsInherited: '正在使用适配器默认模型',
modelsCustomized: '已自定义模型目录',
@@ -178,53 +167,56 @@ export const zh: { [Key in keyof typeof en]: string } = {
modelName: '显示名称',
modelNamePlaceholder: '留空时使用模型 ID',
contextWindow: '上下文窗口',
- contextWindowPlaceholder: '使用提供方默认值',
+ contextWindowPlaceholder: '使用提供商默认值',
maxTokens: '最大输出 token 数',
- maxTokensPlaceholder: '使用提供方默认值',
- modelAdvanced: '容量',
+ maxTokensPlaceholder: '使用提供商默认值',
+ modelAdvanced: '模型选项',
+ modelInputTypes: '输入类型',
+ modelInputText: '文本',
+ modelInputImage: '图片',
addModel: '添加模型',
removeModel: '删除模型',
modelsEmpty: '模型选择器中将不显示任何模型;目录外 ID 仍可直接发送。',
keyBlank: '请输入 API 密钥;留空则保持已存储的密钥。',
- keyBlankNew: '请输入 API 密钥;若该提供方以其他方式鉴权,可以留空。',
+ keyBlankNew: '请输入 API 密钥;若该提供商以其他方式鉴权,可以留空。',
keyIllegalCharacters: '该 API 密钥格式错误,请检查。',
modelIdRequired: '模型 ID 不能为空。',
modelIdDuplicate: '模型 ID 不能重复。',
modelNameInvalid: '显示名称不能为空。',
modelContextInvalid: '上下文窗口必须是正数,例如 131072、256K 或 1M。',
modelMaxTokensInvalid: '最大输出 token 数必须是正数,例如 8192、64K 或 1M。',
- advancedHint: '其余字段在 settings.yaml 中,请直接编辑对应段。',
+ advancedHint: '其余字段在 cordis.patch.yml 中,请直接编辑对应段。',
modelCapacityInvalid: '容量需为数字,可加 K 或 M 后缀。',
modelDuplicate: '每个模型 ID 只能出现一次。',
- modelContextWindow: '上下文窗口',
- modelMaxTokens: '最大输出 token',
fetchModels: '获取可用模型',
- fetching: '正在询问提供方\u2026',
+ fetching: '正在询问提供商\u2026',
fetchNeedsBaseUrl: '请先填写 API 地址,再获取。',
- fetchEmpty: '该提供方没有列出任何模型,请手动添加。',
+ fetchEmpty: '该提供商没有列出任何模型,请手动添加。',
fetchTitle: '选择要添加的模型',
- fetchDescription: '以下是模型提供方的可用模型,勾选要添加的模型。',
+ fetchDescription: '以下是模型提供商的可用模型,勾选要添加的模型。',
fetchSearch: '搜索模型',
fetchNoMatches: '没有匹配的模型。',
fetchSelectAll: '全选',
fetchDeselectAll: '取消全选',
fetchAdopt: '添加所选',
- customAdd: '添加自定义提供方',
- customTitle: '自定义提供方',
customTag: '自定义',
customRoute: 'Provider ID',
- customRouteHint: '以小写字母开头的标识,在请求中唯一标识该提供方,并用于派生凭据名。',
+ customRouteHint: '以小写字母开头的标识,在请求中唯一标识该提供商,并用于派生凭据名。',
customRouteInvalid: '需以小写字母开头,之后可用小写字母、数字和短横线。',
- customRouteTaken: '已有提供方使用了这个 ID。',
+ customRouteTaken: '已有提供商使用了这个 ID。',
customDisplayName: '显示名称',
customApi: 'API 协议',
customApiUnset: '未选择',
- customNeedsBaseUrl: '自定义提供方需要填写 API 地址。',
+ protocolOpenAiCompletions: 'OpenAI Chat Completions',
+ protocolOpenAiResponses: 'OpenAI Responses',
+ protocolAnthropicMessages: 'Anthropic Messages',
+ customNeedsBaseUrl: '自定义模型 API 需要填写 API 地址。',
customBaseUrlInvalid: '请输入有效的 HTTP 或 HTTPS 地址。',
- customNeedsModels: '自定义提供方至少需要一个模型。',
+ customNeedsModels: '自定义模型 API 至少需要一个模型。',
customBaseUrlPlaceholder: 'https://gateway.example/v1',
+ customAnthropicBaseUrlPlaceholder: 'https://gateway.example',
settingsPathUnresolvable: '无法解析设置路径',
- create: '创建提供方',
+ create: '创建提供商',
creating: '创建中\u2026',
welcomeTitle: '内测声明',
welcomeBody: 'DeepSeek Harness 目前的 0.1 版本仍处在面向 Harness 开发者进行测试的阶段,还有许多地方需要持续改进和打磨,希望听取广大开发者的反馈建议。预计 DeepSeek Harness 的核心插件以及基础 API 都会在接下来的一段时间内快速迭代、持续演化。\n\n我们期待与全球开发者一起,在开源、开放、可复用、可组合的基础设施之上,共同探索智能上限。欢迎全球 Harness 开发者加入 DSH 插件生态。',
@@ -236,36 +228,4 @@ export const zh: { [Key in keyof typeof en]: string } = {
onboardingSave: '保存并继续',
onboardingSaving: '保存中…',
keyRequired: '请输入 API 密钥后继续。',
- openConfigFile: '打开配置文件',
- openConfigFileHint: '打开承载全部模型定义的设置文件',
- openConfigFileLanded: '已打开 {path}',
- openConfigFileDirectory: '配置文件尚未创建,已改为打开 {path}',
- openConfigFileFailed: '无法打开配置文件,请确认编辑器已安装,或在“文本编辑器”中更换:{detail}',
- textEditor: '文本编辑器',
- textEditorHint: '此设置仅用于模型页面的“打开配置文件”。',
- editorVSCode: 'VS Code',
- editorCursor: 'Cursor',
- editorSystem: '系统默认(推荐)',
- editorCustom: '自定义编辑器',
- editorCommand: '应用名称或可执行文件路径',
- editorCommandPlaceholder: '应用名称、.app 路径或可执行文件路径',
- editorCommandHint: 'macOS 可填写应用名称或 .app 路径;Windows 请填写 .exe 完整路径;Linux 可填写程序名称或路径。无需引号,请勿附加启动参数。',
- editorLoadFailed: '无法读取编辑器设置:{detail}',
- editorSaveFailed: '无法保存编辑器设置:{detail}',
- imageInput: '图片输入',
- imageInputHint: '声明该模型是否接受图片内容',
- thinkingMode: '思考模式',
- thinkingLevels: '思考档位',
- thinkingModeHint: '声明该模型是否支持思考,并勾选它提供的档位',
- developerRole: '关闭 Developer 角色',
- developerRoleHint: '端点是本地部署这类不认 developer 角色时打开:系统提示保持 system,思考档位改从 chat_template_kwargs 下发;开启后写入 compat:supportsDeveloperRole=false、thinkingFormat=chat-template、chatTemplateKwargs.reasoning_effort={$var: thinking.effort}',
- fetchModelConfig: '获取配置',
- fetchModelConfigHint: '从提供方端点读取该模型的上下文与输出上限,并按模型能力表补齐图片与思考档位',
- autoConfigureModels: '自动配置所有模型',
- autoConfigureModelsHint: '为列表中每个模型从端点读取上限,并按模型能力表补齐图片与思考档位',
- fetchingConfig: '获取中…',
- configUnreachable: '无法读取模型列表:{detail}',
- configNoneApplied: '端点与模型能力表都没有为这些模型提供可写入的配置。',
- configApplied: '已配置 {n} 个模型。',
- configUndisclosed: '{n} 个模型未被端点披露。',
}
diff --git a/packages/dsh-tauri-model-config/src/client/models/operations.ts b/packages/dsh-tauri-model-config/src/client/models/operations.ts
index aafc30d3..09aba8ca 100644
--- a/packages/dsh-tauri-model-config/src/client/models/operations.ts
+++ b/packages/dsh-tauri-model-config/src/client/models/operations.ts
@@ -8,33 +8,23 @@ import type {
} from '../types/remotes.ts'
export type SettingsWriteOutcome
-
= | { readonly kind: 'written', readonly view: SettingsNamespaceView }
-
| { readonly kind: 'conflict', readonly message: string }
-
| { readonly kind: 'refused', readonly message: string }
export type ModelDiscoveryOutcome
-
= | { readonly kind: 'found', readonly models: readonly LlmDiscoveredModel[] }
-
| { readonly kind: 'refused', readonly message: string }
export interface ModelsOperations {
-
describeCredential: (ref: string) => Promise<CredentialInfo | undefined>
-
storeCredential: (ref: string, value: string) => Promise<string | undefined>
-
removeCredential: (ref: string) => Promise<string | undefined>
-
writeSettings: (
ns: string,
ops: SettingsPathOpView[],
expectedRevision: number | undefined,
) => Promise<SettingsWriteOutcome>
-
discoverModels: (settingsNs: string, request: LlmModelDiscoveryRequest) => Promise<ModelDiscoveryOutcome>
}
diff --git a/packages/dsh-tauri-model-config/src/client/models/protocol-label.ts b/packages/dsh-tauri-model-config/src/client/models/protocol-label.ts
new file mode 100644
index 00000000..ab7e676e
--- /dev/null
+++ b/packages/dsh-tauri-model-config/src/client/models/protocol-label.ts
@@ -0,0 +1,12 @@
+import type { ModelsKey } from './locales.ts'
+
+const PROTOCOL_LABEL_KEYS: Readonly<Record<string, ModelsKey>> = {
+ 'openai-completions': 'protocolOpenAiCompletions',
+ 'openai-responses': 'protocolOpenAiResponses',
+ 'anthropic-messages': 'protocolAnthropicMessages',
+}
+
+export function protocolLabel(t: (key: ModelsKey) => string, protocol: string): string {
+ const key = PROTOCOL_LABEL_KEYS[protocol]
+ return key === undefined ? protocol : t(key)
+}
diff --git a/packages/dsh-tauri-model-config/src/client/models/remote.ts b/packages/dsh-tauri-model-config/src/client/models/remote.ts
new file mode 100644
index 00000000..68822f06
--- /dev/null
+++ b/packages/dsh-tauri-model-config/src/client/models/remote.ts
@@ -0,0 +1,9 @@
+import type { ClientRemote } from '../types/remotes.ts'
+
+export interface ServiceLookup {
+ get: (name: string) => unknown
+}
+
+export function resolveRemote(ctx: ServiceLookup): ClientRemote | undefined {
+ return ctx.get('remote') as ClientRemote | undefined
+}
diff --git a/packages/dsh-tauri-model-config/src/client/models/settings-forms.ts b/packages/dsh-tauri-model-config/src/client/models/settings-forms.ts
index 721c4e29..8c7766af 100644
--- a/packages/dsh-tauri-model-config/src/client/models/settings-forms.ts
+++ b/packages/dsh-tauri-model-config/src/client/models/settings-forms.ts
@@ -6,33 +6,25 @@ import {
} from '../../shared/onboarding-copy.ts'
import { decodeWelcomeSection } from './welcome-store.ts'
-/** ≥0.1.7 的 `ctx.configForms`(源文件 `config-form.ts`)。 */
interface ConfigFormsLike {
describe: () => SettingsDescribeFace
get: (namespace: string) => WelcomeSettingsForm
}
-/** ≤0.1.6 的 `ctx.settingsScope`。 */
interface SettingsScopeLike {
describe: () => SettingsDescribeFace
bind: (spec: { namespace: string, decode: (section: unknown) => Record<string, unknown> }) => WelcomeSettingsForm
}
-/** 模型页所需的设置读写面,已抹平两代内核的服务名与绑定方式差异。 */
export interface ModelsForms {
describe: SettingsDescribeFace
welcome: WelcomeSettingsForm
}
-/** 只需要 cordis 的服务查询面,避免依赖 ctx 的宿主/客户端增广差异。 */
export interface ServiceLookup {
get: (name: string) => unknown
}
-/**
- * 探测并解析设置命名空间服务。`configForms` 优先;缺席时退回 `settingsScope`
- * 及其 `bind({namespace, decode})` 绑定形式,并换用该代的欢迎确认命名空间。
- */
export function resolveModelsForms(ctx: ServiceLookup): ModelsForms | undefined {
const forms = ctx.get('configForms') as ConfigFormsLike | undefined
if (forms !== undefined) {
diff --git a/packages/dsh-tauri-model-config/src/client/models/slot-contract.ts b/packages/dsh-tauri-model-config/src/client/models/slot-contract.ts
index 41d691ec..7e73237f 100644
--- a/packages/dsh-tauri-model-config/src/client/models/slot-contract.ts
+++ b/packages/dsh-tauri-model-config/src/client/models/slot-contract.ts
@@ -3,23 +3,18 @@ import type { ProviderDirectoryEntry } from './store.ts'
declare module '@deepseek-ai/dsh-client-ui-slots' {
interface SlotMap {
-
'settings.models.provider-card': { kind: 'keyed', scope: 'root', owner: ProviderCardExtrasOwnerProps }
-
+ 'settings.models.sign-in': { kind: 'single', scope: 'root', owner: { complete: () => void, useApiKey: () => void } }
'settings.models.footer': { kind: 'list', scope: 'root', owner: ModelsFooterOwnerProps }
}
}
export interface ProviderCardExtrasOwnerProps {
-
provider: ProviderDirectoryEntry
-
configured: boolean
-
keyConfigured: boolean
}
export interface ModelsFooterOwnerProps {
-
children?: never
}
diff --git a/packages/dsh-tauri-model-config/src/client/models/store.ts b/packages/dsh-tauri-model-config/src/client/models/store.ts
index 2babb02a..8b6dbd05 100644
--- a/packages/dsh-tauri-model-config/src/client/models/store.ts
+++ b/packages/dsh-tauri-model-config/src/client/models/store.ts
@@ -52,31 +52,20 @@ export function joinProviderDirectory(
}
export interface ProviderRow {
-
entry: ProviderDirectoryEntry
-
configured: boolean
-
removable: boolean
-
apiKeyEnv: string | undefined
-
credential: CredentialInfo | undefined
-
derivedCredential?: CredentialInfo
}
export interface ModelsSettingsState {
status: 'idle' | 'loading' | 'ready' | 'error'
-
error: string | null
-
credentialError: string | null
-
writable: boolean
-
rows: readonly ProviderRow[]
-
namespaces: ReadonlyMap<string, SettingsNamespaceView>
}
diff --git a/packages/dsh-tauri-model-config/src/client/models/styles.ts b/packages/dsh-tauri-model-config/src/client/models/styles.ts
index 3ae825f3..d832e171 100644
--- a/packages/dsh-tauri-model-config/src/client/models/styles.ts
+++ b/packages/dsh-tauri-model-config/src/client/models/styles.ts
@@ -2,13 +2,771 @@ import { cssr } from 'dsh-tauri-ui/client'
const { c } = cssr
-const MODELS_CSS = '.zGbnIq_section {\n display: flex;\n flex-direction: column;\n gap: 12px;\n max-width: 720px;\n color: var(--dsw-alias-label-primary);\n}\n\n.zGbnIq_title {\n margin: 0;\n font-size: 16px;\n line-height: 24px;\n font-weight: 500;\n color: var(--dsw-alias-label-primary);\n}\n\n.zGbnIq_intro {\n margin: 0;\n font-size: 14px;\n line-height: 22px;\n color: var(--dsw-alias-label-tertiary);\n}\n\n.zGbnIq_notice {\n margin: 0;\n font-size: 12px;\n line-height: 18px;\n color: var(--dsw-alias-state-warn-label);\n}\n\n.zGbnIq_savedNotice {\n margin: 0;\n font-size: 12px;\n line-height: 18px;\n color: var(--dsw-alias-state-success-primary);\n}\n\n.zGbnIq_rows {\n list-style: none;\n \n margin: 12px 0 0;\n padding: 0;\n display: flex;\n flex-direction: column;\n gap: 8px;\n}\n\n\n.zGbnIq_rowCard {\n border: 0.5px solid var(--dsw-alias-border-l4);\n border-radius: 16px;\n padding: 12px 14px;\n display: flex;\n flex-direction: column;\n gap: 12px;\n}\n\n.zGbnIq_rowHead {\n display: flex;\n align-items: center;\n gap: 10px;\n}\n\n.zGbnIq_rowIdentity {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n min-width: 0;\n}\n\n.zGbnIq_rowName {\n font-size: 14px;\n line-height: 22px;\n font-weight: 500;\n color: var(--dsw-alias-label-primary);\n}\n\n\n.zGbnIq_rowTag {\n flex: none;\n padding: 1px 6px;\n border: 0.5px solid var(--dsw-alias-border-l3);\n border-radius: 4px;\n font-size: 11px;\n line-height: 16px;\n color: var(--dsw-alias-label-secondary);\n}\n\n.zGbnIq_credentialDot {\n box-sizing: border-box;\n display: inline-block;\n flex: none;\n width: 8px;\n height: 8px;\n border-radius: 50%;\n corner-shape: round;\n}\n\n.zGbnIq_credentialDotConfigured {\n background: var(--dsw-alias-state-success-primary);\n}\n\n.zGbnIq_credentialDotMissing {\n background: var(--dsw-alias-state-error-primary);\n}\n\n.zGbnIq_rowActions {\n display: inline-flex;\n align-items: center;\n gap: 4px;\n margin-left: auto;\n}\n\n\n.zGbnIq_primaryButton,\n.zGbnIq_secondaryButton,\n.zGbnIq_addButton {\n box-sizing: border-box;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n gap: 4px;\n height: 36px;\n padding: 0 14px;\n border: none;\n border-radius: 18px;\n font: inherit;\n font-size: 14px;\n line-height: 22px;\n cursor: pointer;\n}\n\n.zGbnIq_primaryButton {\n background: var(--dsw-alias-button-primary-fill);\n color: var(--dsw-alias-label-primary-foreground);\n}\n\n.zGbnIq_primaryButton:hover:not(:disabled) {\n background: var(--dsw-alias-button-primary-hover);\n}\n\n.zGbnIq_secondaryButton,\n.zGbnIq_addButton {\n border: 0.5px solid var(--dsw-alias-border-l3);\n background: transparent;\n color: var(--dsw-alias-label-primary);\n}\n\n.zGbnIq_secondaryButton:hover:not(:disabled),\n.zGbnIq_addButton:hover:not(:disabled) {\n background: var(--dsw-alias-interactive-bg-hover);\n}\n\n.zGbnIq_secondaryButton:hover:not(:disabled) {\n background: var(--dsw-alias-interactive-bg-hover-solid);\n}\n\n.zGbnIq_dangerButton {\n box-sizing: border-box;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n height: 36px;\n padding: 0 14px;\n border: none;\n border-radius: 18px;\n background: transparent;\n color: var(--dsw-alias-state-error-primary);\n font: inherit;\n font-size: 14px;\n line-height: 22px;\n cursor: pointer;\n}\n\n.zGbnIq_dangerButton:hover:not(:disabled) {\n background: var(--dsw-alias-interactive-bg-hover-danger);\n}\n\n\n.zGbnIq_rowActions .zGbnIq_secondaryButton,\n.zGbnIq_rowActions .zGbnIq_dangerButton {\n height: 28px;\n padding: 0 10px;\n border-radius: 14px;\n font-size: 12px;\n line-height: 18px;\n}\n\n.zGbnIq_primaryButton:disabled,\n.zGbnIq_secondaryButton:disabled,\n.zGbnIq_dangerButton:disabled,\n.zGbnIq_addButton:disabled,\n.zGbnIq_linkButton:disabled,\n.zGbnIq_addModelButton:disabled {\n opacity: 0.4;\n cursor: default;\n}\n\n.zGbnIq_primaryButton:focus-visible,\n.zGbnIq_secondaryButton:focus-visible,\n.zGbnIq_dangerButton:focus-visible,\n.zGbnIq_addButton:focus-visible,\n.zGbnIq_linkButton:focus-visible,\n.zGbnIq_addModelButton:focus-visible,\n.zGbnIq_iconButton:focus-visible,\n.zGbnIq_customizedSummary:focus-visible {\n outline: none;\n box-shadow: 0 0 0 2px var(--dsw-alias-border-l3);\n}\n\n\n.zGbnIq_editor {\n border-radius: 12px;\n background: var(--dsw-alias-bg-module-platform);\n padding: 14px 16px;\n display: flex;\n flex-direction: column;\n gap: 14px;\n}\n\n.zGbnIq_editorHeader {\n display: flex;\n align-items: baseline;\n gap: 8px;\n}\n\n.zGbnIq_editorTitle {\n font-size: 14px;\n line-height: 22px;\n font-weight: 500;\n color: var(--dsw-alias-label-primary);\n}\n\n.zGbnIq_editorRoute {\n font-size: 12px;\n line-height: 18px;\n color: var(--dsw-alias-label-tertiary);\n}\n\n.zGbnIq_field {\n display: flex;\n flex-direction: column;\n gap: 6px;\n}\n\n.zGbnIq_fieldLabel {\n display: inline-flex;\n align-items: center;\n gap: 10px;\n font-size: 12px;\n line-height: 18px;\n font-weight: 500;\n color: var(--dsw-alias-label-secondary);\n}\n\n.zGbnIq_linkButton {\n box-sizing: border-box;\n display: inline-flex;\n align-items: center;\n height: 28px;\n padding: 0 10px;\n border: none;\n border-radius: 14px;\n background: transparent;\n color: var(--dsw-alias-label-tertiary);\n font: inherit;\n font-size: 12px;\n line-height: 18px;\n cursor: pointer;\n}\n\n.zGbnIq_linkButton:hover:not(:disabled) {\n background: var(--dsw-alias-interactive-bg-hover);\n color: var(--dsw-alias-label-secondary);\n}\n\n.zGbnIq_advancedHint {\n margin: 0;\n font-size: 12px;\n line-height: 18px;\n color: var(--dsw-alias-label-tertiary);\n}\n\n.zGbnIq_editorActions {\n display: flex;\n justify-content: flex-end;\n gap: 8px;\n}\n\n.zGbnIq_addBlock {\n display: flex;\n flex-direction: column;\n gap: 12px;\n}\n\n\n.zGbnIq_addActions {\n display: flex;\n flex-wrap: wrap;\n gap: 10px;\n}\n\n.zGbnIq_addButton {\n \n flex: 1 1 0;\n min-width: 180px;\n gap: 6px;\n height: 44px;\n border: 1px dashed var(--dsw-alias-border-l3);\n border-radius: 16px;\n}\n\n.zGbnIq_addCard,\n.zGbnIq_setupCard {\n border-radius: 12px;\n background: var(--dsw-alias-bg-module-platform);\n padding: 14px 16px;\n display: flex;\n flex-direction: column;\n gap: 14px;\n list-style: none;\n}\n\n\n.zGbnIq_addCard .zGbnIq_editor,\n.zGbnIq_setupCard .zGbnIq_editor {\n background: none;\n padding: 0;\n}\n\n.zGbnIq_customized {\n border-top: 0.5px solid var(--dsw-alias-border-l2);\n padding-top: 10px;\n}\n\n\n.zGbnIq_customizedSummary {\n display: flex;\n align-items: center;\n gap: 6px;\n width: fit-content;\n padding: 2px 4px;\n margin-left: -4px;\n border-radius: 6px;\n cursor: pointer;\n font-size: 12px;\n line-height: 18px;\n font-weight: 500;\n color: var(--dsw-alias-label-secondary);\n list-style: none;\n}\n\n.zGbnIq_customizedSummary::-webkit-details-marker {\n display: none;\n}\n\n.zGbnIq_customizedSummary::before {\n content: \'\';\n width: 5px;\n height: 5px;\n border-right: 1.5px solid currentcolor;\n border-bottom: 1.5px solid currentcolor;\n transform: rotate(-45deg) translate(-1px, -1px);\n transition: transform 120ms ease;\n}\n\n.zGbnIq_customized[open] > .zGbnIq_customizedSummary::before {\n transform: rotate(45deg) translate(-1px, -1px);\n}\n\n.zGbnIq_customizedSummary:hover {\n color: var(--dsw-alias-label-primary);\n}\n\n.zGbnIq_customizedBody {\n display: flex;\n flex-direction: column;\n gap: 12px;\n padding-top: 12px;\n}\n\n\n.zGbnIq_modelCatalog {\n display: flex;\n flex-direction: column;\n gap: 10px;\n padding-top: 12px;\n border-top: 0.5px solid var(--dsw-alias-border-l2);\n}\n\n.zGbnIq_modelCatalogHeading {\n display: flex;\n flex-direction: column;\n gap: 2px;\n}\n\n.zGbnIq_modelCatalogTitle {\n font-size: 12px;\n line-height: 18px;\n font-weight: 500;\n color: var(--dsw-alias-label-secondary);\n}\n\n.zGbnIq_modelCatalogMeta,\n.zGbnIq_modelEmpty {\n margin: 0;\n color: var(--dsw-alias-label-tertiary);\n font-size: 12px;\n line-height: 18px;\n}\n\n\n.zGbnIq_modelList {\n display: flex;\n flex-direction: column;\n gap: 8px;\n}\n\n.zGbnIq_modelListHead {\n display: flex;\n align-items: flex-start;\n justify-content: space-between;\n gap: 12px;\n}\n\n.zGbnIq_modelEntry {\n border: 0.5px solid var(--dsw-alias-border-l4);\n border-radius: 10px;\n padding: 6px;\n}\n\n.zGbnIq_modelRow {\n display: grid;\n grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr) auto auto;\n align-items: center;\n gap: 6px;\n}\n\n\n.zGbnIq_iconButton {\n box-sizing: border-box;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: 28px;\n height: 28px;\n border: none;\n border-radius: 6px;\n background: transparent;\n color: var(--dsw-alias-label-tertiary);\n cursor: pointer;\n}\n\n.zGbnIq_iconButton:hover:not(:disabled) {\n background: var(--dsw-alias-interactive-bg-hover);\n color: var(--dsw-alias-label-primary);\n}\n\n.zGbnIq_iconButton:disabled {\n cursor: default;\n opacity: 0.4;\n}\n\n\n.zGbnIq_iconButtonDanger:hover:not(:disabled) {\n background: var(--dsw-alias-interactive-bg-hover-danger);\n color: var(--dsw-alias-state-error-primary);\n}\n\n.zGbnIq_modelAdvanced {\n display: grid;\n grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));\n gap: 8px;\n padding: 8px 4px 2px;\n}\n\n.zGbnIq_modelField {\n display: flex;\n flex-direction: column;\n gap: 4px;\n}\n\n.zGbnIq_modelFieldLabel {\n color: var(--dsw-alias-label-tertiary);\n font-size: 12px;\n line-height: 18px;\n}\n\n.zGbnIq_modelEmpty {\n padding: 12px;\n border: 1px dashed var(--dsw-alias-border-l3);\n border-radius: 8px;\n text-align: center;\n}\n\n.zGbnIq_addModelButton {\n box-sizing: border-box;\n align-self: flex-start;\n display: inline-flex;\n align-items: center;\n gap: 4px;\n height: 28px;\n padding: 0 10px;\n border: 0.5px solid var(--dsw-alias-border-l3);\n border-radius: 14px;\n background: transparent;\n color: var(--dsw-alias-label-primary);\n font: inherit;\n font-size: 12px;\n line-height: 18px;\n cursor: pointer;\n}\n\n.zGbnIq_addModelButton:hover:not(:disabled) {\n background: var(--dsw-alias-interactive-bg-hover);\n}\n\n.zGbnIq_input {\n box-sizing: border-box;\n width: 100%;\n height: 32px;\n padding: 0 10px;\n border: 0.5px solid var(--dsw-alias-border-l4);\n border-radius: 8px;\n font: inherit;\n font-size: 14px;\n line-height: 22px;\n background: var(--dsw-alias-bg-layer-1);\n color: var(--dsw-alias-label-primary);\n}\n\n\nselect.zGbnIq_input {\n max-width: 240px;\n cursor: pointer;\n}\n\n.zGbnIq_input:focus {\n outline: none;\n border-color: var(--dsw-alias-brand-primary);\n}\n\n.zGbnIq_input::placeholder {\n color: var(--dsw-alias-label-dimmed);\n}\n\n.zGbnIq_input:disabled {\n opacity: 0.6;\n cursor: default;\n}\n\n\n.zGbnIq_selectInput {\n appearance: none;\n padding-right: 32px;\n \n background-image: url("data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' width=\'12\' height=\'12\' viewBox=\'0 0 12 12\' fill=\'none\'%3E%3Cpath d=\'M3 4.5L6 7.5L9 4.5\' stroke=\'%2381858C\' stroke-width=\'1.5\' stroke-linecap=\'round\' stroke-linejoin=\'round\'/%3E%3C/svg%3E");\n background-repeat: no-repeat;\n background-position: right 12px center;\n background-size: 12px 12px;\n}\n\n.zGbnIq_error {\n margin: 0;\n font-size: 12px;\n line-height: 18px;\n color: var(--dsw-alias-state-error-primary);\n}\n\n.zGbnIq_deleteDialog {\n width: min(480px, 100%);\n}\n\n.zGbnIq_deleteConfirm:not(:disabled) {\n border-color: var(--dsw-alias-state-error-primary);\n color: var(--dsw-alias-state-error-primary);\n}\n\n.zGbnIq_deleteConfirm:hover:not(:disabled) {\n background: var(--dsw-alias-interactive-bg-hover-danger);\n}\n\n\n.zGbnIq_hiddenLabel {\n position: absolute;\n width: 1px;\n height: 1px;\n overflow: hidden;\n clip: rect(0 0 0 0);\n white-space: nowrap;\n}\n\n@media (prefers-reduced-motion: reduce) {\n .zGbnIq_customizedSummary::before,\n .zGbnIq_switchThumb {\n transition: none;\n }\n}\n\n.zGbnIq_fetchDialog {\n max-width: 520px;\n\n \n --dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2);\n --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2);\n}\n\n.zGbnIq_candidateToolbar {\n display: flex;\n align-items: center;\n gap: 8px;\n margin-bottom: 6px;\n}\n\n.zGbnIq_candidateSearch {\n min-width: 0;\n flex: 1 1 240px;\n}\n\n.zGbnIq_candidateList {\n display: flex;\n flex-direction: column;\n gap: 2px;\n max-height: 320px;\n margin: 0;\n overflow-y: auto;\n padding: 0;\n list-style: none;\n}\n\n.zGbnIq_candidate {\n border-radius: 6px;\n}\n\n.zGbnIq_candidateLabel {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 6px 8px;\n cursor: pointer;\n}\n\n.zGbnIq_candidateId {\n flex: 1 1 auto;\n font-family: var(--ds-font-family-code);\n font-size: 13px;\n overflow-wrap: anywhere;\n}\n\n.zGbnIq_candidateEmpty {\n margin: 24px 0;\n color: var(--dsw-alias-label-secondary);\n font-size: 13px;\n line-height: 20px;\n text-align: center;\n}\n\n\n.zGbnIq_titleRow {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 12px;\n}\n\n.zGbnIq_modelCatalogHeading {\n flex: 1;\n}\n\n.zGbnIq_modelRow {\n grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto;\n}\n\n.zGbnIq_modelSwitchRow {\n display: flex;\n align-items: center;\n height: 32px;\n}\n\n.zGbnIq_modelEfforts {\n grid-column: 1 / -1;\n display: flex;\n flex-wrap: wrap;\n gap: 6px;\n}\n\n.zGbnIq_modelEffortChip {\n display: inline-flex;\n align-items: center;\n gap: 4px;\n height: 24px;\n padding: 0 8px;\n border: 0.5px solid var(--dsw-alias-border-l3);\n border-radius: 6px;\n font-size: 12px;\n line-height: 18px;\n color: var(--dsw-alias-label-secondary);\n cursor: pointer;\n}\n\n.zGbnIq_modelEffortChip:has(input:disabled) {\n opacity: 0.6;\n cursor: default;\n}\n\n.zGbnIq_modelEffortChip input {\n width: 12px;\n height: 12px;\n margin: 0;\n accent-color: var(--dsw-alias-brand-primary);\n}'
+const MODELS_CSS = `.zGbnIq_section {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ max-width: 720px;
+ color: var(--dsw-alias-label-primary);
+}
+
+.zGbnIq_title {
+ margin: 0;
+ font-size: 16px;
+ line-height: 24px;
+ font-weight: 500;
+ color: var(--dsw-alias-label-primary);
+}
+
+.zGbnIq_intro {
+ margin: 0;
+ font-size: 14px;
+ line-height: 22px;
+ color: var(--dsw-alias-label-tertiary);
+}
+
+.zGbnIq_notice {
+ margin: 0;
+ font-size: 12px;
+ line-height: 18px;
+ color: var(--dsw-alias-state-warn-label);
+}
+
+.zGbnIq_savedNotice {
+ margin: 0;
+ font-size: 12px;
+ line-height: 18px;
+ color: var(--dsw-alias-state-success-primary);
+}
+
+.zGbnIq_rows {
+ list-style: none;
+
+ margin: 12px 0 0;
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+}
+
+.zGbnIq_rowCard {
+ border: 0.5px solid var(--dsw-alias-border-l4);
+ border-radius: 16px;
+ padding: 12px 14px;
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+}
+
+.zGbnIq_rowHead {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+}
+
+.zGbnIq_rowIdentity {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ min-width: 0;
+}
+
+.zGbnIq_rowName {
+ font-size: 14px;
+ line-height: 22px;
+ font-weight: 500;
+ color: var(--dsw-alias-label-primary);
+}
+
+.zGbnIq_rowTag {
+ flex: none;
+ padding: 1px 6px;
+ border: 0.5px solid var(--dsw-alias-border-l3);
+ border-radius: 4px;
+ font-size: 11px;
+ line-height: 16px;
+ color: var(--dsw-alias-label-secondary);
+}
+
+.zGbnIq_credentialDot {
+ box-sizing: border-box;
+ display: inline-block;
+ flex: none;
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ corner-shape: round;
+}
+
+.zGbnIq_credentialDotConfigured {
+ background: var(--dsw-alias-state-success-primary);
+}
+
+.zGbnIq_credentialDotMissing {
+ background: var(--dsw-alias-state-error-primary);
+}
+
+.zGbnIq_rowActions {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ margin-left: auto;
+}
+
+.zGbnIq_primaryButton,
+.zGbnIq_secondaryButton,
+.zGbnIq_addButton {
+ box-sizing: border-box;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 4px;
+ height: 36px;
+ padding: 0 14px;
+ border: none;
+ border-radius: 18px;
+ font: inherit;
+ font-size: 14px;
+ line-height: 22px;
+ cursor: pointer;
+}
+
+.zGbnIq_primaryButton {
+ background: var(--dsw-alias-button-primary-fill);
+ color: var(--dsw-alias-label-primary-foreground);
+}
+
+.zGbnIq_primaryButton:hover:not(:disabled) {
+ background: var(--dsw-alias-button-primary-hover);
+}
+
+.zGbnIq_secondaryButton,
+.zGbnIq_addButton {
+ border: 0.5px solid var(--dsw-alias-border-l3);
+ background: transparent;
+ color: var(--dsw-alias-label-primary);
+}
+
+.zGbnIq_secondaryButton:hover:not(:disabled),
+.zGbnIq_addButton:hover:not(:disabled) {
+ background: var(--dsw-alias-interactive-bg-hover);
+}
+
+.zGbnIq_secondaryButton:hover:not(:disabled) {
+ background: var(--dsw-alias-interactive-bg-hover-solid);
+}
+
+.zGbnIq_dangerButton {
+ box-sizing: border-box;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ height: 36px;
+ padding: 0 14px;
+ border: none;
+ border-radius: 18px;
+ background: transparent;
+ color: var(--dsw-alias-state-error-primary);
+ font: inherit;
+ font-size: 14px;
+ line-height: 22px;
+ cursor: pointer;
+}
+
+.zGbnIq_dangerButton:hover:not(:disabled) {
+ background: var(--dsw-alias-interactive-bg-hover-danger);
+}
+
+.zGbnIq_rowActions .zGbnIq_secondaryButton,
+.zGbnIq_rowActions .zGbnIq_dangerButton {
+ height: 28px;
+ padding: 0 10px;
+ border-radius: 14px;
+ font-size: 12px;
+ line-height: 18px;
+}
+
+.zGbnIq_primaryButton:disabled,
+.zGbnIq_secondaryButton:disabled,
+.zGbnIq_dangerButton:disabled,
+.zGbnIq_addButton:disabled,
+.zGbnIq_linkButton:disabled,
+.zGbnIq_addModelButton:disabled {
+ opacity: 0.4;
+ cursor: default;
+}
+
+.zGbnIq_primaryButton:focus-visible,
+.zGbnIq_secondaryButton:focus-visible,
+.zGbnIq_dangerButton:focus-visible,
+.zGbnIq_addButton:focus-visible,
+.zGbnIq_linkButton:focus-visible,
+.zGbnIq_addModelButton:focus-visible,
+.zGbnIq_iconButton:focus-visible,
+.zGbnIq_customizedSummary:focus-visible {
+ outline: none;
+ box-shadow: 0 0 0 2px var(--dsw-alias-border-l3);
+}
+
+.zGbnIq_editor {
+ border-radius: 12px;
+ background: var(--dsw-alias-bg-module-platform);
+ padding: 14px 16px;
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+}
-const WELCOME_CSS = '.zGbnIqw_copy {\n font-size: 14px;\n line-height: 24px;\n color: var(--dsw-alias-label-secondary);\n}\n\n.zGbnIqw_copy p {\n margin: 0;\n}\n\n.zGbnIqw_copy p + p {\n margin-top: 12px;\n}\n\n.zGbnIqw_error {\n margin: 16px 0 0;\n font-size: 14px;\n line-height: 22px;\n color: var(--dsw-alias-state-error-primary);\n}\n\n.zGbnIqw_actions {\n display: flex;\n justify-content: flex-end;\n margin-top: 24px;\n}\n\n.zGbnIqw_primary {\n min-width: 120px;\n}\n\n@media (max-width: 560px) {\n .zGbnIqw_primary {\n width: 100%;\n }\n}'
+.zGbnIq_editorHeader {
+ display: flex;
+ align-items: baseline;
+ gap: 8px;
+}
+
+.zGbnIq_editorTitle {
+ font-size: 14px;
+ line-height: 22px;
+ font-weight: 500;
+ color: var(--dsw-alias-label-primary);
+}
+
+.zGbnIq_editorRoute {
+ font-size: 12px;
+ line-height: 18px;
+ color: var(--dsw-alias-label-tertiary);
+}
+
+.zGbnIq_field {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+}
+
+.zGbnIq_fieldLabel {
+ display: inline-flex;
+ align-items: center;
+ gap: 10px;
+ font-size: 12px;
+ line-height: 18px;
+ font-weight: 500;
+ color: var(--dsw-alias-label-secondary);
+}
+
+.zGbnIq_linkButton {
+ box-sizing: border-box;
+ display: inline-flex;
+ align-items: center;
+ height: 28px;
+ padding: 0 10px;
+ border: none;
+ border-radius: 14px;
+ background: transparent;
+ color: var(--dsw-alias-label-tertiary);
+ font: inherit;
+ font-size: 12px;
+ line-height: 18px;
+ cursor: pointer;
+}
+
+.zGbnIq_linkButton:hover:not(:disabled) {
+ background: var(--dsw-alias-interactive-bg-hover);
+ color: var(--dsw-alias-label-secondary);
+}
+
+.zGbnIq_advancedHint {
+ margin: 0;
+ font-size: 12px;
+ line-height: 18px;
+ color: var(--dsw-alias-label-tertiary);
+}
+
+.zGbnIq_editorActions {
+ display: flex;
+ justify-content: flex-end;
+ gap: 8px;
+}
+
+.zGbnIq_addBlock {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+}
+
+.zGbnIq_addActions {
+ display: flex;
+}
+
+.zGbnIq_addButton {
+
+ flex: 1 1 0;
+ min-width: 180px;
+ gap: 6px;
+ height: 44px;
+ border: 1px dashed var(--dsw-alias-border-l3);
+ border-radius: 16px;
+}
+
+.zGbnIq_addModes {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 8px;
+}
+
+.zGbnIq_addPanel {
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+}
+
+.zGbnIq_addPanel[hidden] {
+ display: none;
+}
+
+.zGbnIq_addCard,
+.zGbnIq_setupCard {
+ border-radius: 12px;
+ background: var(--dsw-alias-bg-module-platform);
+ padding: 14px 16px;
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+ list-style: none;
+}
+
+.zGbnIq_addCard .zGbnIq_editor,
+.zGbnIq_setupCard .zGbnIq_editor {
+ background: none;
+ padding: 0;
+}
-const ONBOARDING_CSS = '.zGbnIqo_dialog {\n width: min(600px, 100%);\n padding: 0;\n}\n\n.zGbnIqo_content {\n display: flex;\n flex-direction: column;\n max-height: calc(100vh - 48px);\n padding: 28px;\n box-sizing: border-box;\n overflow-y: auto;\n}\n\n.zGbnIqo_title {\n margin: 0;\n font-size: 20px;\n line-height: 28px;\n font-weight: 500;\n color: var(--dsw-alias-label-primary);\n outline: none;\n}\n\n.zGbnIqo_body {\n margin-top: 20px;\n}\n\n@media (max-width: 560px) {\n .zGbnIqo_content {\n padding: 24px;\n }\n}'
+.zGbnIq_customized {
+ border-top: 0.5px solid var(--dsw-alias-border-l2);
+ padding-top: 10px;
+}
+
+.zGbnIq_customizedSummary {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ width: fit-content;
+ padding: 2px 4px;
+ margin-left: -4px;
+ border-radius: 6px;
+ cursor: pointer;
+ font-size: 12px;
+ line-height: 18px;
+ font-weight: 500;
+ color: var(--dsw-alias-label-secondary);
+ list-style: none;
+}
+
+.zGbnIq_customizedSummary::-webkit-details-marker {
+ display: none;
+}
+
+.zGbnIq_customizedSummary::before {
+ content: '';
+ width: 5px;
+ height: 5px;
+ border-right: 1.5px solid currentcolor;
+ border-bottom: 1.5px solid currentcolor;
+ transform: rotate(-45deg) translate(-1px, -1px);
+ transition: transform 120ms ease;
+}
-const ONBOARDING_DIALOG_CSS = '.zGbnIqd_description {\n margin: 0;\n font-size: 14px;\n line-height: 24px;\n color: var(--dsw-alias-label-secondary);\n}\n\n.zGbnIqd_editor {\n margin-top: 24px;\n}\n\n@media (max-width: 560px) {\n .zGbnIqd_editor {\n margin-top: 20px;\n }\n}'
+.zGbnIq_customized[open] > .zGbnIq_customizedSummary::before {
+ transform: rotate(45deg) translate(-1px, -1px);
+}
+
+.zGbnIq_customizedSummary:hover {
+ color: var(--dsw-alias-label-primary);
+}
+
+.zGbnIq_customizedBody {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ padding-top: 12px;
+}
+
+.zGbnIq_modelCatalog {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ padding-top: 12px;
+ border-top: 0.5px solid var(--dsw-alias-border-l2);
+}
+
+.zGbnIq_modelCatalogHeading {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+}
+
+.zGbnIq_modelCatalogTitle {
+ font-size: 12px;
+ line-height: 18px;
+ font-weight: 500;
+ color: var(--dsw-alias-label-secondary);
+}
+
+.zGbnIq_modelCatalogMeta,
+.zGbnIq_modelEmpty {
+ margin: 0;
+ color: var(--dsw-alias-label-tertiary);
+ font-size: 12px;
+ line-height: 18px;
+}
+
+.zGbnIq_modelList {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+}
+
+.zGbnIq_modelListHead {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 12px;
+}
+
+.zGbnIq_modelEntry {
+ border: 0.5px solid var(--dsw-alias-border-l4);
+ border-radius: 10px;
+ padding: 6px;
+}
+
+.zGbnIq_modelRow {
+ display: grid;
+ grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr) auto auto;
+ align-items: center;
+ gap: 6px;
+}
+
+.zGbnIq_iconButton {
+ box-sizing: border-box;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 28px;
+ height: 28px;
+ border: none;
+ border-radius: 6px;
+ background: transparent;
+ color: var(--dsw-alias-label-tertiary);
+ cursor: pointer;
+}
+
+.zGbnIq_iconButton:hover:not(:disabled) {
+ background: var(--dsw-alias-interactive-bg-hover);
+ color: var(--dsw-alias-label-primary);
+}
+
+.zGbnIq_iconButton:disabled {
+ cursor: default;
+ opacity: 0.4;
+}
+
+.zGbnIq_iconButtonDanger:hover:not(:disabled) {
+ background: var(--dsw-alias-interactive-bg-hover-danger);
+ color: var(--dsw-alias-state-error-primary);
+}
+
+.zGbnIq_modelAdvanced {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 8px;
+ padding: 8px 4px 2px;
+}
+
+.zGbnIq_modelField {
+ display: flex;
+ flex-direction: column;
+ min-width: 0;
+ gap: 4px;
+}
+
+.zGbnIq_modelInputTypes {
+ grid-column: 1 / -1;
+ min-width: 0;
+ margin: 0;
+ padding: 0;
+ border: none;
+}
+
+.zGbnIq_modelInputTypes legend {
+ padding: 0;
+ margin-bottom: 4px;
+}
+
+.zGbnIq_modelInputChoices {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 16px;
+ min-height: 32px;
+ align-items: center;
+}
+
+.zGbnIq_modelFieldLabel {
+ color: var(--dsw-alias-label-tertiary);
+ font-size: 12px;
+ line-height: 18px;
+}
+
+.zGbnIq_modelEmpty {
+ padding: 12px;
+ border: 1px dashed var(--dsw-alias-border-l3);
+ border-radius: 8px;
+ text-align: center;
+}
+
+.zGbnIq_addModelButton {
+ box-sizing: border-box;
+ align-self: flex-start;
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ height: 28px;
+ padding: 0 10px;
+ border: 0.5px solid var(--dsw-alias-border-l3);
+ border-radius: 14px;
+ background: transparent;
+ color: var(--dsw-alias-label-primary);
+ font: inherit;
+ font-size: 12px;
+ line-height: 18px;
+ cursor: pointer;
+}
+
+.zGbnIq_addModelButton:hover:not(:disabled) {
+ background: var(--dsw-alias-interactive-bg-hover);
+}
+
+.zGbnIq_input {
+ box-sizing: border-box;
+ width: 100%;
+ height: 32px;
+ padding: 0 10px;
+ border: 0.5px solid var(--dsw-alias-border-l4);
+ border-radius: 8px;
+ font: inherit;
+ font-size: 14px;
+ line-height: 22px;
+ background: var(--dsw-alias-bg-layer-1);
+ color: var(--dsw-alias-label-primary);
+}
+
+select.zGbnIq_input {
+ max-width: 240px;
+ cursor: pointer;
+}
+
+.zGbnIq_input:focus {
+ outline: none;
+ border-color: var(--dsw-alias-brand-primary);
+}
+
+.zGbnIq_input::placeholder {
+ color: var(--dsw-alias-label-dimmed);
+}
+
+.zGbnIq_input:disabled {
+ opacity: 0.6;
+ cursor: default;
+}
+
+.zGbnIq_selectInput {
+ appearance: none;
+ padding-right: 32px;
+
+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.zGbnIq_w3.zGbnIq_org/2000/svg' width='12' height='12' viewBox='0 0 12 12' fill='none'%3E%3Cpath d='M3 4.5L6 7.5L9 4.5' stroke='%2381858C' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");
+ background-repeat: no-repeat;
+ background-position: right 12px center;
+ background-size: 12px 12px;
+}
+
+.zGbnIq_error {
+ margin: 0;
+ font-size: 12px;
+ line-height: 18px;
+ color: var(--dsw-alias-state-error-primary);
+}
+
+.zGbnIq_deleteDialog {
+ width: min(480px, 100%);
+}
+
+.zGbnIq_deleteConfirm:not(:disabled) {
+ border-color: var(--dsw-alias-state-error-primary);
+ color: var(--dsw-alias-state-error-primary);
+}
+
+.zGbnIq_deleteConfirm:hover:not(:disabled) {
+ background: var(--dsw-alias-interactive-bg-hover-danger);
+}
+
+.zGbnIq_hiddenLabel {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ overflow: hidden;
+ clip: rect(0 0 0 0);
+ white-space: nowrap;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .zGbnIq_customizedSummary::before,
+ .zGbnIq_switchThumb {
+ transition: none;
+ }
+}
+
+.zGbnIq_fetchDialog {
+ max-width: 520px;
+
+ --dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2);
+ --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2);
+}
+
+.zGbnIq_candidateToolbar {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-bottom: 6px;
+}
+
+.zGbnIq_candidateSearch {
+ min-width: 0;
+ flex: 1 1 240px;
+}
+
+.zGbnIq_candidateList {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ max-height: 320px;
+ margin: 0;
+ overflow-y: auto;
+ padding: 0;
+ list-style: none;
+}
+
+.zGbnIq_candidate {
+ border-radius: 6px;
+}
+
+.zGbnIq_candidateLabel {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 6px 8px;
+ cursor: pointer;
+}
+
+.zGbnIq_candidateId {
+ flex: 1 1 auto;
+ font-family: var(--ds-font-family-code);
+ font-size: 13px;
+ overflow-wrap: anywhere;
+}
+
+.zGbnIq_candidateEmpty {
+ margin: 24px 0;
+ color: var(--dsw-alias-label-secondary);
+ font-size: 13px;
+ line-height: 20px;
+ text-align: center;
+}`
+
+const WELCOME_CSS = `.zGbnIqw_copy {
+ font-size: 14px;
+ line-height: 24px;
+ color: var(--dsw-alias-label-secondary);
+}
+
+.zGbnIqw_copy p {
+ margin: 0;
+}
+
+.zGbnIqw_copy p + p {
+ margin-top: 12px;
+}
+
+.zGbnIqw_error {
+ margin: 16px 0 0;
+ font-size: 14px;
+ line-height: 22px;
+ color: var(--dsw-alias-state-error-primary);
+}
+
+.zGbnIqw_actions {
+ display: flex;
+ justify-content: flex-end;
+ margin-top: 24px;
+}
+
+.zGbnIqw_primary {
+ min-width: 120px;
+}
+
+@media (max-width: 560px) {
+ .zGbnIqw_primary {
+ width: 100%;
+ }
+}`
+
+const ONBOARDING_CSS = `.zGbnIqo_dialog {
+ width: min(600px, 100%);
+ max-height: 100%;
+ padding: 0;
+}
+
+.zGbnIqo_content {
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+ padding: 28px;
+ box-sizing: border-box;
+ overflow-y: auto;
+}
+
+.zGbnIqo_title {
+ margin: 0;
+ font-size: 20px;
+ line-height: 28px;
+ font-weight: 500;
+ color: var(--dsw-alias-label-primary);
+ outline: none;
+}
+
+.zGbnIqo_body {
+ margin-top: 20px;
+}
+
+@media (max-width: 560px) {
+ .zGbnIqo_content {
+ padding: 24px;
+ }
+}`
+
+const ONBOARDING_DIALOG_CSS = `.zGbnIqd_description {
+ margin: 0;
+ font-size: 14px;
+ line-height: 24px;
+ color: var(--dsw-alias-label-secondary);
+}
+
+.zGbnIqd_editor {
+ margin-top: 24px;
+}
+
+@media (max-width: 560px) {
+ .zGbnIqd_editor {
+ margin-top: 20px;
+ }
+}`
export const modelStyles: Record<string, string> = {
addActions: 'zGbnIq_addActions',
@@ -16,6 +774,8 @@ export const modelStyles: Record<string, string> = {
addButton: 'zGbnIq_addButton',
addCard: 'zGbnIq_addCard',
addModelButton: 'zGbnIq_addModelButton',
+ addModes: 'zGbnIq_addModes',
+ addPanel: 'zGbnIq_addPanel',
advancedHint: 'zGbnIq_advancedHint',
candidate: 'zGbnIq_candidate',
candidateEmpty: 'zGbnIq_candidateEmpty',
@@ -53,25 +813,25 @@ export const modelStyles: Record<string, string> = {
modelCatalogHeading: 'zGbnIq_modelCatalogHeading',
modelCatalogMeta: 'zGbnIq_modelCatalogMeta',
modelCatalogTitle: 'zGbnIq_modelCatalogTitle',
- modelEffortChip: 'zGbnIq_modelEffortChip',
- modelEfforts: 'zGbnIq_modelEfforts',
modelEmpty: 'zGbnIq_modelEmpty',
modelEntry: 'zGbnIq_modelEntry',
modelField: 'zGbnIq_modelField',
modelFieldLabel: 'zGbnIq_modelFieldLabel',
+ modelInputChoices: 'zGbnIq_modelInputChoices',
+ modelInputTypes: 'zGbnIq_modelInputTypes',
modelList: 'zGbnIq_modelList',
modelListHead: 'zGbnIq_modelListHead',
modelRow: 'zGbnIq_modelRow',
- modelSwitchRow: 'zGbnIq_modelSwitchRow',
notice: 'zGbnIq_notice',
+ org: 'zGbnIq_org',
primaryButton: 'zGbnIq_primaryButton',
rowActions: 'zGbnIq_rowActions',
rowCard: 'zGbnIq_rowCard',
rowHead: 'zGbnIq_rowHead',
rowIdentity: 'zGbnIq_rowIdentity',
rowName: 'zGbnIq_rowName',
- rowTag: 'zGbnIq_rowTag',
rows: 'zGbnIq_rows',
+ rowTag: 'zGbnIq_rowTag',
savedNotice: 'zGbnIq_savedNotice',
secondaryButton: 'zGbnIq_secondaryButton',
section: 'zGbnIq_section',
@@ -79,23 +839,20 @@ export const modelStyles: Record<string, string> = {
setupCard: 'zGbnIq_setupCard',
switchThumb: 'zGbnIq_switchThumb',
title: 'zGbnIq_title',
- titleRow: 'zGbnIq_titleRow',
+ w3: 'zGbnIq_w3',
}
-
export const welcomeStyles: Record<string, string> = {
actions: 'zGbnIqw_actions',
copy: 'zGbnIqw_copy',
error: 'zGbnIqw_error',
primary: 'zGbnIqw_primary',
}
-
export const onboardingStyles: Record<string, string> = {
body: 'zGbnIqo_body',
content: 'zGbnIqo_content',
dialog: 'zGbnIqo_dialog',
title: 'zGbnIqo_title',
}
-
export const onboardingDialogStyles: Record<string, string> = {
description: 'zGbnIqd_description',
editor: 'zGbnIqd_editor',
diff --git a/packages/dsh-tauri-model-config/src/client/models/welcome-store.ts b/packages/dsh-tauri-model-config/src/client/models/welcome-store.ts
index 3c2af7ac..427a2c22 100644
--- a/packages/dsh-tauri-model-config/src/client/models/welcome-store.ts
+++ b/packages/dsh-tauri-model-config/src/client/models/welcome-store.ts
@@ -13,7 +13,6 @@ export interface WelcomeNoticeState {
export type WelcomeSection = Record<string, unknown>
-/** `SettingsScope`(≤0.1.6)与 `ConfigForm`(≥0.1.7)共有的读/写面。 */
export interface WelcomeSettingsForm {
getSnapshot: () => {
status: 'loading' | 'ready' | 'unavailable'
diff --git a/packages/dsh-tauri-model-config/src/client/register/models.ts b/packages/dsh-tauri-model-config/src/client/register/models.ts
index dce77bbc..6297120d 100644
--- a/packages/dsh-tauri-model-config/src/client/register/models.ts
+++ b/packages/dsh-tauri-model-config/src/client/register/models.ts
@@ -5,19 +5,20 @@ import type {} from '@deepseek-ai/dsh-client-ui-renderer/client'
import type {} from '@deepseek-ai/dsh-client-ui-settings/client'
import type { DeepSeekOnboardingInjected } from '../models/DeepSeekOnboardingDialog.tsx'
import type { ModelsSectionInjected } from '../models/ModelsSection.tsx'
+import type {} from '../models/slot-contract.ts'
import type { WelcomeNoticeInjected } from '../models/WelcomeNotice.tsx'
-import type { ClientRemote } from '../types/remotes.ts'
import { defineRegister } from 'dsh-tauri/client'
+import { ONBOARDING_CONFIG_GLOBAL } from '../../shared/onboarding-config.ts'
import { locale } from '../locales'
import { DeepSeekOnboardingDialog } from '../models/DeepSeekOnboardingDialog.tsx'
import { ModelsSection } from '../models/ModelsSection.tsx'
import { createModelsOperations } from '../models/operations.ts'
+import { resolveRemote } from '../models/remote.ts'
import { createSettingsSchemaOperations } from '../models/schema-operations.ts'
import { resolveModelsForms } from '../models/settings-forms.ts'
import { ModelsSettingsStore } from '../models/store.ts'
import { WelcomeNoticeStore } from '../models/welcome-store.ts'
import { WelcomeNotice } from '../models/WelcomeNotice.tsx'
-import { openConfigFile } from '../service/model-config.ts'
function refreshIfLoaded(controller: ModelsSettingsStore): void {
if (controller.store.getSnapshot().status === 'idle')
@@ -25,19 +26,23 @@ function refreshIfLoaded(controller: ModelsSettingsStore): void {
void controller.load()
}
-function remoteOf(ctx: ClientContext): ClientRemote | undefined {
- return ctx.get('remote') as ClientRemote | undefined
+function credentialOnboardingOf(): boolean {
+ const page = globalThis as Partial<Record<typeof ONBOARDING_CONFIG_GLOBAL, unknown>>
+ const payload = page[ONBOARDING_CONFIG_GLOBAL]
+ const value = typeof payload === 'object' && payload !== null
+ ? (payload as { credentialOnboarding?: unknown }).credentialOnboarding
+ : undefined
+ return (value ?? true) === true && !('dshDesktop' in globalThis)
}
-/** 装配 fork 自官方 `ui-settings-models` 的模型设置页与其引导对话框。 */
export const registerModelsPage = defineRegister<ClientContext>((controller, ctx) => {
- const remote = remoteOf(ctx)
- const schema = createSettingsSchemaOperations(ctx.settingsSchema)
- const operations = createModelsOperations(remote as ClientRemote)
+ const remote = resolveRemote(ctx)
const forms = resolveModelsForms(ctx)
- if (forms === undefined)
+ if (remote === undefined || forms === undefined)
return
- const page = new ModelsSettingsStore(remote as ClientRemote, schema, forms.describe)
+ const schema = createSettingsSchemaOperations(ctx.settingsSchema)
+ const operations = createModelsOperations(remote)
+ const page = new ModelsSettingsStore(remote, schema, forms.describe)
const t = locale.text as ModelsSectionInjected['t']
const injected = (): ModelsSectionInjected => ({
controller: page,
@@ -45,9 +50,9 @@ export const registerModelsPage = defineRegister<ClientContext>((controller, ctx
operations,
schema,
t,
- openConfig: openConfigFile,
})
const deepSeekOnboardingInjected = (): DeepSeekOnboardingInjected => ({
+ automatic: credentialOnboardingOf(),
controller: page,
hooks: { models: page.store },
operations,
@@ -61,11 +66,27 @@ export const registerModelsPage = defineRegister<ClientContext>((controller, ctx
t,
})
+ const refreshModels = (): void => {
+ refreshIfLoaded(page)
+ }
+ const disposers = [
+ remote.$on('settings/document-updated', () => {
+ refreshModels()
+ }),
+ remote.$on('credentials/reference-updated', refreshModels),
+ remote.$on('llm/adapters-updated', refreshModels),
+ ctx.on('connection/reset', refreshModels),
+ ]
+ controller.add(() => {
+ welcome.dispose()
+ for (const dispose of disposers) dispose()
+ })
+
controller.add(ctx.slots.inject('settings.section', () => ctx.slots.register({
name: 'settings.section',
id: 'models',
order: 10,
- label: () => locale.text('nav'),
+ label: () => t('nav'),
inject: injected,
children: {
'settings.models.provider-card': { kind: 'keyed', scope: 'root' },
@@ -81,23 +102,8 @@ export const registerModelsPage = defineRegister<ClientContext>((controller, ctx
controller.add(ctx.slots.inject('settings.onboarding', () => ctx.slots.register({
name: 'settings.onboarding',
id: 'deepseek-official',
+ children: { 'settings.models.sign-in': { kind: 'single', scope: 'root' } },
order: 0,
inject: deepSeekOnboardingInjected,
}, DeepSeekOnboardingDialog)))
-
- controller.add(() => welcome.dispose())
- if (remote !== undefined) {
- controller.add(remote.$on('settings/document-updated', () => {
- refreshIfLoaded(page)
- }))
- controller.add(remote.$on('credentials/reference-updated', () => {
- refreshIfLoaded(page)
- }))
- controller.add(remote.$on('llm/adapters-updated', () => {
- refreshIfLoaded(page)
- }))
- }
- controller.add(ctx.on('connection/reset', () => {
- refreshIfLoaded(page)
- }))
})
diff --git a/packages/dsh-tauri-model-config/src/client/types/remotes.ts b/packages/dsh-tauri-model-config/src/client/types/remotes.ts
index 44787517..211dec39 100644
--- a/packages/dsh-tauri-model-config/src/client/types/remotes.ts
+++ b/packages/dsh-tauri-model-config/src/client/types/remotes.ts
@@ -35,12 +35,6 @@ export type SettingsPathOpView
= | { op: 'set', path: string[], value: JsonValue }
| { op: 'unset', path: string[] }
-export interface SettingsDescribeValue {
- writable: boolean
- hasDocument: boolean
- namespaces: SettingsNamespaceView[]
-}
-
export interface LlmProviderInfo {
id: string
name: string
@@ -67,6 +61,7 @@ export interface LlmDiscoveredModel {
name?: string
contextWindow?: number
maxTokens?: number
+ inputModalities?: readonly string[]
}
export interface SettingsRemote {
@@ -85,9 +80,11 @@ export interface LlmRemote {
discoverModels: (settingsNs: string, request: LlmModelDiscoveryRequest) => Promise<RemoteResult<LlmDiscoveredModel[]>>
}
+export type RemoteEventName = 'settings/document-updated' | 'credentials/reference-updated' | 'llm/adapters-updated'
+
export interface ClientRemote {
settings: SettingsRemote
credentials: CredentialsRemote
llm: LlmRemote
- $on: (event: string, listener: () => void) => () => void
+ $on: (event: RemoteEventName, listener: () => void) => () => void
}
diff --git a/packages/dsh-tauri-model-config/src/host/apply.ts b/packages/dsh-tauri-model-config/src/host/apply.ts
index 51cc5878..d29e7894 100644
--- a/packages/dsh-tauri-model-config/src/host/apply.ts
+++ b/packages/dsh-tauri-model-config/src/host/apply.ts
@@ -1,15 +1,16 @@
+import type { Config } from './config/onboarding'
import type { HostContext } from './types'
import { PLUGIN_ID } from '../shared/constants'
-import { setCurrentHostInstance } from './config/runtime'
-import { routes } from './routes'
+import { ONBOARDING_CONFIG_GLOBAL } from '../shared/onboarding-config'
-const ROUTES_EFFECT = `${PLUGIN_ID}: routes`
+const INDEX_EFFECT = `${PLUGIN_ID}: onboarding config global`
-const RUNTIME_EFFECT = `${PLUGIN_ID}: host runtime`
-
-export function apply(ctx: HostContext): void {
- setCurrentHostInstance(ctx)
-
- ctx.effect(() => routes(ctx), ROUTES_EFFECT)
- ctx.effect(() => () => setCurrentHostInstance(undefined), RUNTIME_EFFECT)
+export function apply(ctx: HostContext, config?: Config): void {
+ ctx.effect(() => ctx.on('webserver/index-inject', (table) => {
+ table.push({
+ kind: 'global',
+ name: ONBOARDING_CONFIG_GLOBAL,
+ value: { credentialOnboarding: config?.credentialOnboarding ?? true },
+ })
+ }), INDEX_EFFECT)
}
diff --git a/packages/dsh-tauri-model-config/src/host/config/onboarding.ts b/packages/dsh-tauri-model-config/src/host/config/onboarding.ts
new file mode 100644
index 00000000..87b6db86
--- /dev/null
+++ b/packages/dsh-tauri-model-config/src/host/config/onboarding.ts
@@ -0,0 +1,7 @@
+import { ONBOARDING_CONFIG_GLOBAL } from '../../shared/onboarding-config'
+
+export interface Config {
+ credentialOnboarding?: boolean
+}
+
+export { ONBOARDING_CONFIG_GLOBAL }
diff --git a/packages/dsh-tauri-model-config/src/host/types/index.ts b/packages/dsh-tauri-model-config/src/host/types/index.ts
index b343b811..f2f916ed 100644
--- a/packages/dsh-tauri-model-config/src/host/types/index.ts
+++ b/packages/dsh-tauri-model-config/src/host/types/index.ts
@@ -1 +1,16 @@
-export type HostContext = any
+export interface IndexInjectEntry {
+ kind: 'global'
+ name: string
+ value: unknown
+}
+
+export interface IndexInjectTable {
+ push: (entry: IndexInjectEntry) => void
+}
+
+export type IndexInjectListener = (table: IndexInjectTable) => void
+
+export interface HostContext {
+ on: (event: 'webserver/index-inject', listener: IndexInjectListener) => () => void
+ effect: (callback: () => (() => void) | void, name?: string) => void
+}
diff --git a/packages/dsh-tauri-model-config/src/index.ts b/packages/dsh-tauri-model-config/src/index.ts
index cb1db366..3c6706fc 100644
--- a/packages/dsh-tauri-model-config/src/index.ts
+++ b/packages/dsh-tauri-model-config/src/index.ts
@@ -2,6 +2,8 @@ import { PLUGIN_ID } from './shared/constants'
export const name = PLUGIN_ID
-export const inject = ['webServer', 'connection']
+export const inject = ['webServer']
export { apply } from './host/apply'
+
+export * from './host/config/onboarding'
diff --git a/packages/dsh-tauri-model-config/src/shared/onboarding-config.ts b/packages/dsh-tauri-model-config/src/shared/onboarding-config.ts
new file mode 100644
index 00000000..f2871626
--- /dev/null
+++ b/packages/dsh-tauri-model-config/src/shared/onboarding-config.ts
@@ -0,0 +1 @@
+export const ONBOARDING_CONFIG_GLOBAL = '__DSH_MODELS_ONBOARDING__'
diff --git a/packages/dsh-tauri-ui/src/client/apis/index.ts b/packages/dsh-tauri-ui/src/client/apis/index.ts
index 8097e91a..bc184663 100644
--- a/packages/dsh-tauri-ui/src/client/apis/index.ts
+++ b/packages/dsh-tauri-ui/src/client/apis/index.ts
@@ -10,6 +10,31 @@ import type * as Types from "./index.type";
export const baseURL = "/api/desktop/dsh-tauri-ui";
+/** @method get */
+export function getConfigEditor(options?: FetchOptions) {
+ return ofetch<Types.EditorPreferenceResponse>("/config/editor", { baseURL, method: "get", ...options });
+}
+
+/** @method put */
+export function putConfigEditor(body: Types.EditorPreferenceBody, options?: FetchOptions) {
+ return ofetch<Types.EditorPreferenceResponse>("/config/editor", { baseURL, method: "put", body, ...options });
+}
+
+/** @method post */
+export function postConfigOpen(options?: FetchOptions) {
+ return ofetch<Types.OpenModelsConfigResponse>("/config/open", { baseURL, method: "post", ...options });
+}
+
+/** @method get */
+export function getEndpointModels(params?: Types.GetEndpointModelsQuery, options?: FetchOptions) {
+ return ofetch<Types.EndpointModelsResponse>("/endpoint/models", { baseURL, method: "get", params, ...options });
+}
+
+/** @method get */
+export function getPresets(params?: Types.GetPresetsQuery, options?: FetchOptions) {
+ return ofetch<Types.PresetsResponse>("/presets", { baseURL, method: "get", params, ...options });
+}
+
/** @method post */
export function postSessionResume(body: Types.PostSessionResumeBody, options?: FetchOptions) {
return ofetch<Types.SessionResumeResponse>("/session/resume", { baseURL, method: "post", body, ...options });
diff --git a/packages/dsh-tauri-ui/src/client/apis/index.type.ts b/packages/dsh-tauri-ui/src/client/apis/index.type.ts
index 107f3914..a640bf4d 100644
--- a/packages/dsh-tauri-ui/src/client/apis/index.type.ts
+++ b/packages/dsh-tauri-ui/src/client/apis/index.type.ts
@@ -6,3 +6,53 @@ export type SessionResumeResponse = {
export interface PostSessionResumeBody {
sessionId?: string;
}
+
+export type EditorPreferenceResponse = {
+ preference?: EditorPreference;
+ error?: string;
+};
+export type EditorPreference = {
+ editor: "vscode" | "cursor" | "system" | "custom";
+ command: string;
+};
+export type OpenModelsConfigResponse = {
+ ok?: boolean;
+ path?: string;
+ opened?: "file" | "directory";
+ error?: string;
+};
+export type EndpointModelsResponse = {
+ ok?: boolean;
+ url?: string;
+ models?: EndpointModelCard[];
+ error?: string;
+};
+export type EndpointModelCard = {
+ id: string;
+ name?: string;
+ contextWindow?: number;
+ maxTokens?: number;
+};
+export type PresetsResponse = {
+ ok?: boolean;
+ source?: string;
+ fetchedAt?: string;
+ /** 上游不可达、回退到过期缓存时为 true。 */
+ stale?: boolean;
+ count?: number;
+ presets?: Record<string, readonly number[]>;
+ error?: string;
+};
+
+export interface EditorPreferenceBody {
+ preference: EditorPreference;
+}
+export interface GetEndpointModelsQuery {
+ ns?: string;
+ profilePath?: string;
+ baseURL?: string;
+ apiKey?: string;
+}
+export interface GetPresetsQuery {
+ force?: string;
+}
diff --git a/packages/dsh-tauri-ui/src/client/components/checkbox.cssr.ts b/packages/dsh-tauri-ui/src/client/components/checkbox.cssr.ts
new file mode 100644
index 00000000..2b2bb189
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/client/components/checkbox.cssr.ts
@@ -0,0 +1,45 @@
+import { styles as sharedStyles } from '../constants/theme'
+import { cssr } from '../utils/cssr'
+
+const { c, bem: { b, e } } = cssr
+const { primary, secondary, borderL3 } = sharedStyles
+
+export default b('checkbox', {
+ display: 'inline-flex',
+ alignItems: 'center',
+ gap: '8px',
+ color: primary,
+ cursor: 'pointer',
+ font: 'inherit',
+ fontSize: '14px',
+ lineHeight: '22px',
+}, [
+ e('input', {
+ boxSizing: 'border-box',
+ flex: 'none',
+ width: '16px',
+ height: '16px',
+ margin: '0',
+ accentColor: 'var(--dsw-alias-button-primary-fill)',
+ cursor: 'inherit',
+ }, [
+ c('&:disabled', {
+ cursor: 'not-allowed',
+ }),
+ ]),
+ e('label', {
+ minWidth: 0,
+ color: secondary,
+ }),
+ c('&:has(> .dshp-checkbox__input:disabled)', {
+ cursor: 'not-allowed',
+ opacity: '0.5',
+ }),
+ c('&:has(> .dshp-checkbox__input:disabled) .dshp-checkbox__label', {
+ color: secondary,
+ }),
+ c('.dshp-checkbox__input:focus-visible', {
+ outline: `2px solid ${borderL3}`,
+ outlineOffset: '1px',
+ }),
+])
diff --git a/packages/dsh-tauri-ui/src/client/components/checkbox.tsx b/packages/dsh-tauri-ui/src/client/components/checkbox.tsx
new file mode 100644
index 00000000..a5456539
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/client/components/checkbox.tsx
@@ -0,0 +1,22 @@
+import type { ReactElement } from 'react'
+import type { CheckboxProps } from './checkbox.types'
+import { CHECKBOX_STYLE_ID } from '../constants'
+import { useMountStyle } from '../hooks/use-mount-style'
+import checkboxStyle from './checkbox.cssr'
+
+export function Checkbox({ checked, disabled, onChange, children, 'aria-label': ariaLabel }: CheckboxProps): ReactElement {
+ useMountStyle(checkboxStyle, CHECKBOX_STYLE_ID)
+ return (
+ <label className="dshp-checkbox">
+ <input
+ className="dshp-checkbox__input"
+ type="checkbox"
+ checked={checked}
+ disabled={disabled}
+ aria-label={ariaLabel}
+ onChange={event => onChange(event.target.checked)}
+ />
+ {children === undefined ? null : <span className="dshp-checkbox__label">{children}</span>}
+ </label>
+ )
+}
diff --git a/packages/dsh-tauri-ui/src/client/components/checkbox.types.ts b/packages/dsh-tauri-ui/src/client/components/checkbox.types.ts
new file mode 100644
index 00000000..956470b9
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/client/components/checkbox.types.ts
@@ -0,0 +1,9 @@
+import type { ReactNode } from 'react'
+
+export interface CheckboxProps {
+ 'checked': boolean
+ 'disabled'?: boolean
+ 'onChange': (next: boolean) => void
+ 'children'?: ReactNode
+ 'aria-label'?: string
+}
diff --git a/packages/dsh-tauri-ui/src/client/components/controls.test.tsx b/packages/dsh-tauri-ui/src/client/components/controls.test.tsx
new file mode 100644
index 00000000..485ae034
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/client/components/controls.test.tsx
@@ -0,0 +1,110 @@
+import type { SegmentedControlOption } from './segmented-control.types'
+import { renderToStaticMarkup } from 'react-dom/server'
+import { describe, expect, it, vi } from 'vitest'
+import { Checkbox } from './checkbox'
+import { SegmentedControl, stepSegment } from './segmented-control'
+
+const OPTIONS: SegmentedControlOption[] = [
+ { value: 'a', label: 'A' },
+ { value: 'b', label: 'B' },
+ { value: 'c', label: 'C' },
+]
+
+describe('stepSegment', () => {
+ it('walks forward and backward, wrapping at both ends', () => {
+ expect(stepSegment(OPTIONS, 0, 'ArrowRight')).toBe(1)
+ expect(stepSegment(OPTIONS, 2, 'ArrowRight')).toBe(0)
+ expect(stepSegment(OPTIONS, 0, 'ArrowLeft')).toBe(2)
+ expect(stepSegment(OPTIONS, 1, 'ArrowUp')).toBe(0)
+ expect(stepSegment(OPTIONS, 1, 'ArrowDown')).toBe(2)
+ })
+
+ it('jumps to the ends with Home and End', () => {
+ expect(stepSegment(OPTIONS, 2, 'Home')).toBe(0)
+ expect(stepSegment(OPTIONS, 0, 'End')).toBe(2)
+ })
+
+ it('skips disabled segments instead of stalling on them', () => {
+ const options: SegmentedControlOption[] = [{ value: 'a', label: 'A' }, { value: 'b', label: 'B', disabled: true }, { value: 'c', label: 'C' }]
+ expect(stepSegment(options, 0, 'ArrowRight')).toBe(2)
+ expect(stepSegment(options, 2, 'ArrowLeft')).toBe(0)
+ })
+
+ it('ignores keys it does not own and a fully locked control', () => {
+ expect(stepSegment(OPTIONS, 0, 'Enter')).toBeUndefined()
+ expect(stepSegment(OPTIONS, 0, 'Tab')).toBeUndefined()
+ expect(stepSegment([{ value: 'a', label: 'A', disabled: true }], 0, 'ArrowRight')).toBeUndefined()
+ expect(stepSegment([], 0, 'ArrowRight')).toBeUndefined()
+ })
+})
+
+describe('segmentedControl markup', () => {
+ it('renders a labelled tablist whose segments point at their panels', () => {
+ const html = renderToStaticMarkup(
+ <SegmentedControl id="mode" label="Mode" value="b" options={OPTIONS} onChange={vi.fn()} />,
+ )
+ expect(html).toContain('role="tablist"')
+ expect(html).toContain('aria-label="Mode"')
+ expect(html).toContain('id="mode-a"')
+ expect(html).toContain('id="mode-b"')
+ expect(html).toContain('aria-controls="mode-a-panel"')
+ expect(html).toContain('role="tab"')
+ expect(html).toContain('aria-selected="true"')
+ expect(html).toContain('aria-selected="false"')
+ })
+
+ it('keeps only the selected segment in the tab order', () => {
+ const html = renderToStaticMarkup(
+ <SegmentedControl id="mode" value="b" options={OPTIONS} onChange={vi.fn()} />,
+ )
+ expect(html.match(/tabindex="0"/g)).toHaveLength(1)
+ expect(html.match(/tabindex="-1"/g)).toHaveLength(2)
+ })
+
+ it('falls back to a group without a tab contract when no id is given', () => {
+ const html = renderToStaticMarkup(<SegmentedControl value="a" options={OPTIONS} onChange={vi.fn()} />)
+ expect(html).toContain('role="group"')
+ expect(html).not.toContain('role="tab"')
+ expect(html).not.toContain('aria-selected')
+ expect(html).toContain('aria-pressed="true"')
+ })
+
+ it('locks every segment while disabled and honours per-option locks', () => {
+ const locked = renderToStaticMarkup(
+ <SegmentedControl id="mode" value="a" disabled options={OPTIONS} onChange={vi.fn()} />,
+ )
+ expect(locked.match(/disabled=""/g)).toHaveLength(3)
+ const partial = renderToStaticMarkup(
+ <SegmentedControl
+ id="mode"
+ value="a"
+ options={[{ value: 'a', label: 'A' }, { value: 'b', label: 'B', disabled: true, title: 'no' }]}
+ onChange={vi.fn()}
+ />,
+ )
+ expect(partial.match(/disabled=""/g)).toHaveLength(1)
+ expect(partial).toContain('title="no"')
+ })
+})
+
+describe('checkbox markup', () => {
+ it('renders a real checkbox carrying the checked state', () => {
+ const html = renderToStaticMarkup(<Checkbox checked onChange={vi.fn()} />)
+ expect(html).toContain('type="checkbox"')
+ expect(html).toContain('checked=""')
+ const off = renderToStaticMarkup(<Checkbox checked={false} onChange={vi.fn()} />)
+ expect(off).not.toContain('checked')
+ })
+
+ it('renders children as a visible label next to the input', () => {
+ const html = renderToStaticMarkup(<Checkbox checked={false} onChange={vi.fn()}>Enable thinking</Checkbox>)
+ expect(html).toContain('dshp-checkbox__label')
+ expect(html).toContain('Enable thinking')
+ })
+
+ it('passes the accessible name and the disabled state through', () => {
+ const html = renderToStaticMarkup(<Checkbox checked={false} disabled aria-label="Image input" onChange={vi.fn()} />)
+ expect(html).toContain('aria-label="Image input"')
+ expect(html).toContain('disabled=""')
+ })
+})
diff --git a/packages/dsh-tauri-ui/src/client/components/index.ts b/packages/dsh-tauri-ui/src/client/components/index.ts
index f4a230c1..d3010696 100644
--- a/packages/dsh-tauri-ui/src/client/components/index.ts
+++ b/packages/dsh-tauri-ui/src/client/components/index.ts
@@ -1,6 +1,11 @@
+export * from './checkbox'
+export type * from './checkbox.types'
export * from './icon'
export type * from './icon'
export * from './icons'
export * from './menu-select'
+export * from './model-extras'
export * from './panel-page'
+export * from './segmented-control'
+export type * from './segmented-control.types'
export { circleTreeSvg, clockSvg, FishMark, IconPlaceholder, PanelLeftOutline } from './special-icons'
diff --git a/packages/dsh-tauri-ui/src/client/components/model-extras/auto-config-all-button.tsx b/packages/dsh-tauri-ui/src/client/components/model-extras/auto-config-all-button.tsx
new file mode 100644
index 00000000..7ed665a7
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/client/components/model-extras/auto-config-all-button.tsx
@@ -0,0 +1,28 @@
+import type { ReactElement } from 'react'
+import type { AutoConfigAllButtonProps } from './auto-config-all-button.types'
+import { MODEL_EXTRAS_STYLE_ID } from '../../constants'
+import { useMountStyle } from '../../hooks/use-mount-style'
+import modelExtrasStyle from './model-extras.cssr'
+import { useModelConfigFetch } from './use-model-config-fetch'
+
+export function AutoConfigAllButton({ t, models, probe, disabled, onApply }: AutoConfigAllButtonProps): ReactElement {
+ useMountStyle(modelExtrasStyle, MODEL_EXTRAS_STYLE_ID)
+ const { busy, failure, notice, run } = useModelConfigFetch({ t, models, probe, onApply })
+
+ return (
+ <>
+ <button
+ type="button"
+ className="dshp-model-extras__link"
+ disabled={disabled === true || busy || models.length === 0}
+ title={t('autoConfigureModelsHint')}
+ aria-busy={busy}
+ onClick={() => run()}
+ >
+ {busy ? t('fetchingConfig') : t('autoConfigureModels')}
+ </button>
+ {failure === undefined ? null : <p className="dshp-model-extras__notice dshp-model-extras__notice--failed" role="alert">{failure}</p>}
+ {notice === undefined ? null : <p className="dshp-model-extras__notice dshp-model-extras__notice--done">{notice}</p>}
+ </>
+ )
+}
diff --git a/packages/dsh-tauri-ui/src/client/components/model-extras/auto-config-all-button.types.ts b/packages/dsh-tauri-ui/src/client/components/model-extras/auto-config-all-button.types.ts
new file mode 100644
index 00000000..8c7db194
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/client/components/model-extras/auto-config-all-button.types.ts
@@ -0,0 +1,10 @@
+import type { ModelDraft, ModelProbeTarget } from './model-config-toolbar.types'
+import type { Translate } from './types'
+
+export interface AutoConfigAllButtonProps {
+ t: Translate
+ models: readonly ModelDraft[]
+ probe: ModelProbeTarget
+ disabled?: boolean
+ onApply?: (models: ModelDraft[], applied: number, undisclosed: string[]) => void
+}
diff --git a/packages/dsh-tauri-ui/src/client/components/model-extras/config-editor.cssr.ts b/packages/dsh-tauri-ui/src/client/components/model-extras/config-editor.cssr.ts
new file mode 100644
index 00000000..7403f172
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/client/components/model-extras/config-editor.cssr.ts
@@ -0,0 +1,28 @@
+import { cssr } from '../../utils/cssr'
+
+const { c } = cssr
+const vscode = '<svg width="100" height="100" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg"><mask id="mask0" mask-type="alpha" maskUnits="userSpaceOnUse" x="0" y="0" width="100" height="100"><path fill-rule="evenodd" clip-rule="evenodd" d="M70.9119 99.3171C72.4869 99.9307 74.2828 99.8914 75.8725 99.1264L96.4608 89.2197C98.6242 88.1787 100 85.9892 100 83.5872V16.4133C100 14.0113 98.6243 11.8218 96.4609 10.7808L75.8725 0.873756C73.7862 -0.130129 71.3446 0.11576 69.5135 1.44695C69.252 1.63711 69.0028 1.84943 68.769 2.08341L29.3551 38.0415L12.1872 25.0096C10.589 23.7965 8.35363 23.8959 6.86933 25.2461L1.36303 30.2549C-0.452552 31.9064 -0.454633 34.7627 1.35853 36.417L16.2471 50.0001L1.35853 63.5832C-0.454633 65.2374 -0.452552 68.0938 1.36303 69.7453L6.86933 74.7541C8.35363 76.1043 10.589 76.2037 12.1872 74.9905L29.3551 61.9587L68.769 97.9167C69.3925 98.5406 70.1246 99.0104 70.9119 99.3171ZM75.0152 27.2989L45.1091 50.0001L75.0152 72.7012V27.2989Z" fill="white"/></mask><g mask="url(#mask0)"><path d="M96.4614 10.7962L75.8569 0.875542C73.4719 -0.272773 70.6217 0.211611 68.75 2.08333L1.29858 63.5832C-0.515693 65.2373 -0.513607 68.0937 1.30308 69.7452L6.81272 74.754C8.29793 76.1042 10.5347 76.2036 12.1338 74.9905L93.3609 13.3699C96.086 11.3026 100 13.2462 100 16.6667V16.4275C100 14.0265 98.6246 11.8378 96.4614 10.7962Z" fill="#0065A9"/><g filter="url(#filter0_d)"><path d="M96.4614 89.2038L75.8569 99.1245C73.4719 100.273 70.6217 99.7884 68.75 97.9167L1.29858 36.4169C-0.515693 34.7627 -0.513607 31.9063 1.30308 30.2548L6.81272 25.246C8.29793 23.8958 10.5347 23.7964 12.1338 25.0095L93.3609 86.6301C96.086 88.6974 100 86.7538 100 83.3334V83.5726C100 85.9735 98.6246 88.1622 96.4614 89.2038Z" fill="#007ACC"/></g><g filter="url(#filter1_d)"><path d="M75.8578 99.1263C73.4721 100.274 70.6219 99.7885 68.75 97.9166C71.0564 100.223 75 98.5895 75 95.3278V4.67213C75 1.41039 71.0564 -0.223106 68.75 2.08329C70.6219 0.211402 73.4721 -0.273666 75.8578 0.873633L96.4587 10.7807C98.6234 11.8217 100 14.0112 100 16.4132V83.5871C100 85.9891 98.6234 88.1786 96.4586 89.2196L75.8578 99.1263Z" fill="#1F9CF0"/></g><g style="mix-blend-mode:overlay" opacity="0.25"><path fill-rule="evenodd" clip-rule="evenodd" d="M70.8511 99.3171C72.4261 99.9306 74.2221 99.8913 75.8117 99.1264L96.4 89.2197C98.5634 88.1787 99.9392 85.9892 99.9392 83.5871V16.4133C99.9392 14.0112 98.5635 11.8217 96.4001 10.7807L75.8117 0.873695C73.7255 -0.13019 71.2838 0.115699 69.4527 1.44688C69.1912 1.63705 68.942 1.84937 68.7082 2.08335L29.2943 38.0414L12.1264 25.0096C10.5283 23.7964 8.29285 23.8959 6.80855 25.246L1.30225 30.2548C-0.513334 31.9064 -0.515415 34.7627 1.29775 36.4169L16.1863 50L1.29775 63.5832C-0.515415 65.2374 -0.513334 68.0937 1.30225 69.7452L6.80855 74.754C8.29285 76.1042 10.5283 76.2036 12.1264 74.9905L29.2943 61.9586L68.7082 97.9167C69.3317 98.5405 70.0638 99.0104 70.8511 99.3171ZM74.9544 27.2989L45.0483 50L74.9544 72.7012V27.2989Z" fill="url(#paint0_linear)"/></g></g><defs><filter id="filter0_d" x="-8.39411" y="15.8291" width="116.727" height="92.2456" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"/><feOffset/><feGaussianBlur stdDeviation="4.16667"/><feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0"/><feBlend mode="overlay" in2="BackgroundImageFix" result="effect1_dropShadow"/><feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow" result="shape"/></filter><filter id="filter1_d" x="60.4167" y="-8.07558" width="47.9167" height="116.151" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"/><feOffset/><feGaussianBlur stdDeviation="4.16667"/><feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0"/><feBlend mode="overlay" in2="BackgroundImageFix" result="effect1_dropShadow"/><feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow" result="shape"/></filter><linearGradient id="paint0_linear" x1="49.9392" y1="0.257812" x2="49.9392" y2="99.7423" gradientUnits="userSpaceOnUse"><stop stop-color="white"/><stop offset="1" stop-color="white" stop-opacity="0"/></linearGradient></defs></svg>'
+const cursor = '<svg id="Ebene_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 466.73 532.09"><defs><style>\n .st0 {\n fill: #26251e;\n }\n </style></defs><path class="st0" d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z"/></svg>'
+const system = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="13" rx="2"/><path d="M8 21h8m-4-4v4"/></svg>'
+const custom = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="m15 5 4 4M4 20l5-1L21 7a2.8 2.8 0 0 0-4-4L5 15l-1 5Z"/></svg>'
+
+export const configEditorStyle = c([
+ c('.dshp-model-config-toolbar__trigger', {
+ gap: '5px',
+ whiteSpace: 'nowrap',
+ }),
+ c('.dshp-model-config-toolbar__icon', {
+ display: 'inline-block',
+ flex: 'none',
+ width: '16px',
+ height: '16px',
+ }),
+ c('.dshp-model-config-toolbar__icon--vscode', {
+ background: `url("data:image/svg+xml,${encodeURIComponent(vscode)}") center / contain no-repeat`,
+ }),
+ ...Object.entries({ system, cursor, custom }).map(([name, svg]) => c(`.dshp-model-config-toolbar__icon--${name}`, {
+ backgroundColor: 'currentColor',
+ mask: `url("data:image/svg+xml,${encodeURIComponent(svg)}") center / contain no-repeat`,
+ WebkitMask: `url("data:image/svg+xml,${encodeURIComponent(svg)}") center / contain no-repeat`,
+ })),
+])
diff --git a/packages/dsh-tauri-ui/src/client/components/model-extras/index.ts b/packages/dsh-tauri-ui/src/client/components/model-extras/index.ts
new file mode 100644
index 00000000..4181df3a
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/client/components/model-extras/index.ts
@@ -0,0 +1,10 @@
+export { AutoConfigAllButton } from './auto-config-all-button'
+export type { AutoConfigAllButtonProps } from './auto-config-all-button.types'
+export { ModelConfigToolbar } from './model-config-toolbar'
+export type { ModelConfigToolbarProps, ModelDraft, ModelProbeTarget } from './model-config-toolbar.types'
+export { ModelFetchConfigButton } from './model-fetch-config-button'
+export type { ModelFetchConfigButtonProps } from './model-fetch-config-button.types'
+export { MODEL_EXTRAS_KEYS, modelExtrasTranslate } from './translate'
+export type { Translate } from './types'
+export { EDITOR_LABEL_KEYS, useModelConfigFetch } from './use-model-config-fetch'
+export type { UseModelConfigFetchOptions, UseModelConfigFetchResult } from './use-model-config-fetch'
diff --git a/packages/dsh-tauri-ui/src/client/components/model-extras/model-config-toolbar.tsx b/packages/dsh-tauri-ui/src/client/components/model-extras/model-config-toolbar.tsx
new file mode 100644
index 00000000..98ebbb3a
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/client/components/model-extras/model-config-toolbar.tsx
@@ -0,0 +1,185 @@
+import type { MenuEntry } from '@deepseek-ai/dsh-client-ui-primitives'
+import type { ReactElement } from 'react'
+import type { ModelConfigToolbarProps } from './model-config-toolbar.types'
+import { Button, Menu, Modal } from '@deepseek-ai/dsh-client-ui-primitives'
+import { useState } from 'react'
+import { MODEL_CONFIG_TOOLBAR_STYLE_ID, MODEL_EXTRAS_STYLE_ID } from '../../constants'
+import { useMountStyle } from '../../hooks/use-mount-style'
+import { loadEditor, saveEditor } from '../../service/editor'
+import { withDetail } from '../../service/model-config.utils'
+import { ChevronDown } from '../icons'
+import { configEditorStyle } from './config-editor.cssr'
+import modelExtrasStyle from './model-extras.cssr'
+
+const SEPARATOR: MenuEntry = { id: 'separator', type: 'separator' }
+
+export function ModelConfigToolbar({
+ t,
+ editor,
+ onEditorChange,
+ onOpenConfig,
+ openConfigLabel,
+ openConfigHint,
+ disabled,
+}: ModelConfigToolbarProps): ReactElement {
+ useMountStyle(modelExtrasStyle, MODEL_EXTRAS_STYLE_ID)
+ useMountStyle(configEditorStyle, MODEL_CONFIG_TOOLBAR_STYLE_ID)
+ const [menuOpen, setMenuOpen] = useState(false)
+ const [customOpen, setCustomOpen] = useState(false)
+ const [loaded, setLoaded] = useState(editor)
+ const [command, setCommand] = useState('')
+ const [busy, setBusy] = useState(false)
+ const [failure, setFailure] = useState<string>()
+ const current = editor ?? loaded
+ const locked = disabled === true || busy
+
+ const items: MenuEntry[] = [
+ { id: 'system', label: t('editorSystem'), icon: <span className="dshp-model-config-toolbar__icon dshp-model-config-toolbar__icon--system" aria-hidden="true" /> },
+ { id: 'vscode', label: t('editorVSCode'), icon: <span className="dshp-model-config-toolbar__icon dshp-model-config-toolbar__icon--vscode" aria-hidden="true" /> },
+ { id: 'cursor', label: t('editorCursor'), icon: <span className="dshp-model-config-toolbar__icon dshp-model-config-toolbar__icon--cursor" aria-hidden="true" /> },
+ SEPARATOR,
+ { id: 'custom', label: t('editorCustom'), icon: <span className="dshp-model-config-toolbar__icon dshp-model-config-toolbar__icon--custom" aria-hidden="true" /> },
+ ]
+
+ async function openMenu(): Promise<void> {
+ if (locked)
+ return
+ if (menuOpen) {
+ setMenuOpen(false)
+ return
+ }
+ if (current !== undefined) {
+ setMenuOpen(true)
+ return
+ }
+ setBusy(true)
+ setFailure(undefined)
+ try {
+ setLoaded(await loadEditor())
+ setMenuOpen(true)
+ }
+ catch (error) {
+ setFailure(withDetail(t('editorLoadFailed'), String(error)))
+ }
+ finally {
+ setBusy(false)
+ }
+ }
+
+ function closeDialog(): void {
+ if (busy)
+ return
+ setCustomOpen(false)
+ setFailure(undefined)
+ }
+
+ async function save(next: NonNullable<typeof current>): Promise<void> {
+ if (busy)
+ return
+ setBusy(true)
+ setFailure(undefined)
+ const result = await saveEditor(next)
+ setBusy(false)
+ if (result.ok) {
+ if (editor === undefined)
+ setLoaded(next)
+ onEditorChange?.(next)
+ setCustomOpen(false)
+ }
+ else {
+ setFailure(withDetail(t('editorSaveFailed'), result.error ?? ''))
+ }
+ }
+
+ function selectEditor(id: string): void {
+ if (current === undefined || busy)
+ return
+ setMenuOpen(false)
+ if (id === 'custom') {
+ setCommand(current.command)
+ setCustomOpen(true)
+ return
+ }
+ if (id === 'vscode' || id === 'cursor' || id === 'system')
+ void save({ ...current, editor: id })
+ }
+
+ return (
+ <div className="dshp-model-extras__row">
+ <Menu
+ open={menuOpen}
+ align="end"
+ autoFocus
+ items={items}
+ selectedId={current?.editor}
+ onSelect={selectEditor}
+ onClose={() => setMenuOpen(false)}
+ anchor={(
+ <button
+ type="button"
+ className="dshp-model-extras__link dshp-model-config-toolbar__trigger"
+ onClick={() => { void openMenu() }}
+ disabled={locked}
+ aria-haspopup="menu"
+ aria-expanded={menuOpen}
+ aria-busy={busy}
+ >
+ {t('textEditor')}
+ <ChevronDown aria-hidden="true" />
+ </button>
+ )}
+ />
+ {onOpenConfig === undefined
+ ? null
+ : (
+ <button
+ type="button"
+ className="dshp-model-extras__link"
+ disabled={locked}
+ title={openConfigHint}
+ onClick={onOpenConfig}
+ >
+ {openConfigLabel ?? t('openConfigFile')}
+ </button>
+ )}
+ <Modal
+ open={customOpen || failure !== undefined}
+ onClose={closeDialog}
+ title={customOpen ? t('editorCustom') : t('textEditor')}
+ closeLabel={t('close')}
+ description={t('textEditorHint')}
+ footer={(
+ <>
+ <Button variant="outline" disabled={busy} onClick={closeDialog}>{customOpen ? t('cancel') : t('close')}</Button>
+ {customOpen
+ ? (
+ <Button disabled={busy || !command.trim()} onClick={() => { void save({ editor: 'custom', command: command.trim() }) }}>
+ {t('apply')}
+ </Button>
+ )
+ : null}
+ </>
+ )}
+ >
+ <div className="dshp-model-extras__dialog-field">
+ {customOpen
+ ? (
+ <label className="dshp-model-extras__dialog-field">
+ <span className="dshp-model-extras__dialog-label">{t('editorCommand')}</span>
+ <input
+ className="dshp-model-extras__input"
+ value={command}
+ disabled={busy}
+ placeholder={t('editorCommandPlaceholder')}
+ onChange={event => setCommand(event.target.value)}
+ />
+ <span className="dshp-model-extras__dialog-hint">{t('editorCommandHint')}</span>
+ </label>
+ )
+ : null}
+ {failure === undefined ? null : <p className="dshp-model-extras__dialog-error" role="alert">{failure}</p>}
+ </div>
+ </Modal>
+ </div>
+ )
+}
diff --git a/packages/dsh-tauri-ui/src/client/components/model-extras/model-config-toolbar.types.ts b/packages/dsh-tauri-ui/src/client/components/model-extras/model-config-toolbar.types.ts
new file mode 100644
index 00000000..bd5e4306
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/client/components/model-extras/model-config-toolbar.types.ts
@@ -0,0 +1,23 @@
+import type { EditorPreference } from '../../../shared/editor.types'
+import type { Translate } from './types'
+
+export type ModelDraft = Record<string, unknown>
+
+export interface ModelProbeTarget {
+ settingsNs: string
+ profilePath: readonly string[]
+ provider?: string
+ baseURL?: string
+ api?: string
+ apiKey?: string
+}
+
+export interface ModelConfigToolbarProps {
+ t: Translate
+ editor?: EditorPreference
+ onEditorChange?: (next: EditorPreference) => void
+ onOpenConfig?: () => void
+ openConfigLabel?: string
+ openConfigHint?: string
+ disabled?: boolean
+}
diff --git a/packages/dsh-tauri-ui/src/client/components/model-extras/model-extras.cssr.ts b/packages/dsh-tauri-ui/src/client/components/model-extras/model-extras.cssr.ts
new file mode 100644
index 00000000..983a89b9
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/client/components/model-extras/model-extras.cssr.ts
@@ -0,0 +1,94 @@
+import { styles as sharedStyles } from '../../constants/theme'
+import { cssr } from '../../utils/cssr'
+
+const { c, bem: { b, e, m } } = cssr
+const { primary, secondary, tertiary, error, success, hover, borderL4, layer1, modulePlatform, focusRing } = sharedStyles
+
+export default b('model-extras', [
+ e('row', {
+ display: 'flex',
+ alignItems: 'center',
+ flexWrap: 'wrap',
+ gap: '8px',
+ }),
+ e('link', {
+ display: 'inline-flex',
+ alignItems: 'center',
+ gap: '5px',
+ padding: '0',
+ border: 'none',
+ background: 'none',
+ color: secondary,
+ cursor: 'pointer',
+ font: 'inherit',
+ fontSize: '13px',
+ lineHeight: '20px',
+ whiteSpace: 'nowrap',
+ }, [
+ c('&:hover:not(:disabled)', { color: primary }),
+ c('&:focus-visible', focusRing),
+ c('&:disabled', {
+ cursor: 'not-allowed',
+ opacity: '0.5',
+ }),
+ m('open', {
+ color: secondary,
+ }),
+ ]),
+ e('notice', {
+ margin: '0',
+ fontSize: '12px',
+ lineHeight: '18px',
+ color: tertiary,
+ }, [
+ m('failed', { color: error }),
+ m('done', { color: success }),
+ ]),
+ e('dialog-field', {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '6px',
+ }),
+ e('dialog-label', {
+ fontSize: '12px',
+ lineHeight: '18px',
+ color: secondary,
+ }),
+ e('input', {
+ boxSizing: 'border-box',
+ width: '100%',
+ height: '32px',
+ padding: '0 10px',
+ border: `0.5px solid ${borderL4}`,
+ borderRadius: '8px',
+ background: layer1,
+ color: primary,
+ font: 'inherit',
+ fontSize: '14px',
+ lineHeight: '22px',
+ outline: 'none',
+ }, [
+ c('&:focus-visible', focusRing),
+ c('&:disabled', {
+ cursor: 'not-allowed',
+ opacity: '0.5',
+ }),
+ ]),
+ e('dialog-hint', {
+ fontSize: '12px',
+ lineHeight: '18px',
+ color: tertiary,
+ }),
+ e('dialog-error', {
+ margin: '0',
+ fontSize: '13px',
+ lineHeight: '20px',
+ color: error,
+ }),
+ e('busy', {
+ background: modulePlatform,
+ color: tertiary,
+ }),
+ c('&:hover .dshp-model-extras__link:not(:disabled)', { color: primary }),
+ c('.dshp-model-extras__link:hover', { background: hover }),
+])
diff --git a/packages/dsh-tauri-ui/src/client/components/model-extras/model-extras.test.tsx b/packages/dsh-tauri-ui/src/client/components/model-extras/model-extras.test.tsx
new file mode 100644
index 00000000..784499cf
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/client/components/model-extras/model-extras.test.tsx
@@ -0,0 +1,153 @@
+import type { ReactNode } from 'react'
+import type { Translate } from './types'
+import { renderToStaticMarkup } from 'react-dom/server'
+import { describe, expect, it, vi } from 'vitest'
+import { AutoConfigAllButton } from './auto-config-all-button'
+import { ModelConfigToolbar } from './model-config-toolbar'
+import { ModelFetchConfigButton } from './model-fetch-config-button'
+import { MODEL_EXTRAS_KEYS } from './translate'
+
+const mocks = vi.hoisted(() => ({
+ dicts: undefined as { zh: Record<string, string>, en: Record<string, string> } | undefined,
+ ofetch: vi.fn(),
+}))
+
+vi.mock('dsh-tauri/client', () => ({
+ ofetch: mocks.ofetch,
+ defineLocale: (_namespace: string, dicts: { zh: Record<string, string>, en: Record<string, string> }) => {
+ mocks.dicts = dicts
+ return {
+ NS: _namespace,
+ text: (key: string) => dicts.zh[key] ?? key,
+ activeLocale: () => 'zh',
+ isEnglishLocale: () => false,
+ useLocale: () => 'zh',
+ registerLocale: () => () => {},
+ }
+ },
+}))
+
+vi.mock('@deepseek-ai/dsh-client-ui-primitives', () => ({
+ Menu: ({ anchor, open }: { anchor?: ReactNode, open?: boolean }) => (
+ <>
+ {anchor}
+ {open === true ? null : null}
+ </>
+ ),
+ Modal: ({ open, title, children }: { open?: boolean, title?: ReactNode, children?: ReactNode }) =>
+ open === true ? <div role="dialog" aria-label={typeof title === 'string' ? title : undefined}>{children}</div> : null,
+ Button: ({ children, ...rest }: { children?: ReactNode } & Record<string, unknown>) => <button type="button" {...rest}>{children}</button>,
+}))
+
+const t: Translate = (key, params) => {
+ const dict: Record<string, string> = {
+ textEditor: 'Text editor',
+ openConfigFile: 'Open config file',
+ autoConfigureModels: 'Configure all models',
+ autoConfigureModelsHint: 'Fill in limits',
+ fetchModelConfig: 'Fetch config',
+ fetchModelConfigHint: 'Fill in this model',
+ fetchingConfig: 'Fetching…',
+ }
+ const template = dict[key] ?? key
+ if (params === undefined)
+ return template
+ return template.replace(/\{(\w+)\}/g, (match, name: string) => name in params ? String(params[name]) : match)
+}
+
+describe('mODEL_EXTRAS_KEYS', () => {
+ it('names only keys the dsh-tauri-ui dictionary actually carries, in both languages', async () => {
+ await import('../../locales')
+ const dicts = mocks.dicts
+ if (dicts === undefined)
+ throw new Error('the locale dictionary was never declared')
+ expect(MODEL_EXTRAS_KEYS.length).toBeGreaterThan(0)
+ for (const key of MODEL_EXTRAS_KEYS) {
+ expect(dicts.zh[key], `zh:${key}`).toBeTypeOf('string')
+ expect(dicts.en[key], `en:${key}`).toBeTypeOf('string')
+ }
+ })
+
+ it('keeps the zh and en key sets identical', async () => {
+ await import('../../locales')
+ const dicts = mocks.dicts
+ if (dicts === undefined)
+ throw new Error('the locale dictionary was never declared')
+ expect(Object.keys(dicts.en).sort()).toEqual(Object.keys(dicts.zh).sort())
+ })
+})
+
+describe('modelFetchConfigButton', () => {
+ it('renders the fetch action for a row that carries no configuration yet', () => {
+ const html = renderToStaticMarkup(
+ <ModelFetchConfigButton
+ t={t}
+ modelId="gpt-4o"
+ models={[{ id: 'gpt-4o', name: 'GPT-4o' }]}
+ probe={{ settingsNs: 'llm-pi-ai', profilePath: ['providers', 'acme'] }}
+ />,
+ )
+ expect(html).toContain('Fetch config')
+ expect(html).toContain('Fill in this model')
+ })
+
+ it('renders nothing once the row already declares a capability', () => {
+ const html = renderToStaticMarkup(
+ <ModelFetchConfigButton
+ t={t}
+ modelId="gpt-4o"
+ models={[{ id: 'gpt-4o', contextWindow: 128000 }]}
+ probe={{ settingsNs: 'llm-pi-ai', profilePath: [] }}
+ />,
+ )
+ expect(html).toBe('')
+ })
+
+ it('honours the disabled prop', () => {
+ const html = renderToStaticMarkup(
+ <ModelFetchConfigButton
+ t={t}
+ modelId="m"
+ models={[{ id: 'm' }]}
+ probe={{ settingsNs: 'ns', profilePath: [] }}
+ disabled
+ />,
+ )
+ expect(html).toContain('disabled=""')
+ })
+})
+
+describe('autoConfigAllButton', () => {
+ it('locks itself while the draft carries no model', () => {
+ const html = renderToStaticMarkup(
+ <AutoConfigAllButton t={t} models={[]} probe={{ settingsNs: 'ns', profilePath: [] }} />,
+ )
+ expect(html).toContain('Configure all models')
+ expect(html).toContain('disabled=""')
+ })
+
+ it('stays available once the draft lists a model', () => {
+ const html = renderToStaticMarkup(
+ <AutoConfigAllButton t={t} models={[{ id: 'm' }]} probe={{ settingsNs: 'ns', profilePath: [] }} />,
+ )
+ expect(html).not.toContain('disabled')
+ })
+})
+
+describe('modelConfigToolbar', () => {
+ it('renders the editor trigger and the open-config action', () => {
+ const html = renderToStaticMarkup(
+ <ModelConfigToolbar t={t} onOpenConfig={vi.fn()} editor={{ editor: 'system', command: '' }} />,
+ )
+ expect(html).toContain('Text editor')
+ expect(html).toContain('Open config file')
+ expect(html).toContain('dshp-model-config-toolbar__trigger')
+ })
+
+ it('omits the open-config action when the caller owns it elsewhere', () => {
+ const html = renderToStaticMarkup(
+ <ModelConfigToolbar t={t} editor={{ editor: 'vscode', command: '' }} />,
+ )
+ expect(html).not.toContain('Open config file')
+ })
+})
diff --git a/packages/dsh-tauri-ui/src/client/components/model-extras/model-fetch-config-button.tsx b/packages/dsh-tauri-ui/src/client/components/model-extras/model-fetch-config-button.tsx
new file mode 100644
index 00000000..679c1a77
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/client/components/model-extras/model-fetch-config-button.tsx
@@ -0,0 +1,38 @@
+import type { ReactElement } from 'react'
+import type { ModelFetchConfigButtonProps } from './model-fetch-config-button.types'
+import { MODEL_EXTRAS_STYLE_ID } from '../../constants'
+import { useMountStyle } from '../../hooks/use-mount-style'
+import { hasModelConfig } from '../../service/model-config.utils'
+import modelExtrasStyle from './model-extras.cssr'
+import { useModelConfigFetch } from './use-model-config-fetch'
+
+export function ModelFetchConfigButton({
+ t,
+ modelId,
+ models,
+ probe,
+ disabled,
+ onApply,
+}: ModelFetchConfigButtonProps): ReactElement | null {
+ useMountStyle(modelExtrasStyle, MODEL_EXTRAS_STYLE_ID)
+ const { busy, failure, run } = useModelConfigFetch({ t, models, probe, onApply })
+ const row = models.find(model => model.id === modelId)
+ if (row !== undefined && hasModelConfig(row))
+ return null
+
+ return (
+ <>
+ <button
+ type="button"
+ className="dshp-model-extras__link"
+ disabled={disabled === true || busy}
+ title={t('fetchModelConfigHint')}
+ aria-busy={busy}
+ onClick={() => run([modelId])}
+ >
+ {busy ? t('fetchingConfig') : t('fetchModelConfig')}
+ </button>
+ {failure === undefined ? null : <p className="dshp-model-extras__notice dshp-model-extras__notice--failed" role="alert">{failure}</p>}
+ </>
+ )
+}
diff --git a/packages/dsh-tauri-ui/src/client/components/model-extras/model-fetch-config-button.types.ts b/packages/dsh-tauri-ui/src/client/components/model-extras/model-fetch-config-button.types.ts
new file mode 100644
index 00000000..5fc559b3
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/client/components/model-extras/model-fetch-config-button.types.ts
@@ -0,0 +1,11 @@
+import type { ModelDraft, ModelProbeTarget } from './model-config-toolbar.types'
+import type { Translate } from './types'
+
+export interface ModelFetchConfigButtonProps {
+ t: Translate
+ modelId: string
+ models: readonly ModelDraft[]
+ probe: ModelProbeTarget
+ disabled?: boolean
+ onApply?: (models: ModelDraft[], applied: number, undisclosed: string[]) => void
+}
diff --git a/packages/dsh-tauri-ui/src/client/components/model-extras/translate.ts b/packages/dsh-tauri-ui/src/client/components/model-extras/translate.ts
new file mode 100644
index 00000000..b3651037
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/client/components/model-extras/translate.ts
@@ -0,0 +1,33 @@
+import type { Translate } from './types'
+import { locale } from '../../locales'
+
+export const MODEL_EXTRAS_KEYS = [
+ 'apply',
+ 'textEditor',
+ 'textEditorHint',
+ 'editorSystem',
+ 'editorVSCode',
+ 'editorCursor',
+ 'editorCustom',
+ 'editorCommand',
+ 'editorCommandPlaceholder',
+ 'editorCommandHint',
+ 'editorLoadFailed',
+ 'editorSaveFailed',
+ 'openConfigFile',
+ 'openConfigFileHint',
+ 'openConfigFileLanded',
+ 'openConfigFileDirectory',
+ 'openConfigFileFailed',
+ 'autoConfigureModels',
+ 'autoConfigureModelsHint',
+ 'fetchModelConfig',
+ 'fetchModelConfigHint',
+ 'fetchingConfig',
+ 'configUnreachable',
+ 'configNoneApplied',
+ 'configApplied',
+ 'configUndisclosed',
+] as const
+
+export const modelExtrasTranslate: Translate = (key, params) => (locale.text as Translate)(key, params)
diff --git a/packages/dsh-tauri-ui/src/client/components/model-extras/types.ts b/packages/dsh-tauri-ui/src/client/components/model-extras/types.ts
new file mode 100644
index 00000000..368f2157
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/client/components/model-extras/types.ts
@@ -0,0 +1 @@
+export type Translate = (key: string, params?: Record<string, unknown>) => string
diff --git a/packages/dsh-tauri-ui/src/client/components/model-extras/use-model-config-fetch.ts b/packages/dsh-tauri-ui/src/client/components/model-extras/use-model-config-fetch.ts
new file mode 100644
index 00000000..ba1eef58
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/client/components/model-extras/use-model-config-fetch.ts
@@ -0,0 +1,70 @@
+import type { ModelDraft, ModelProbeTarget } from './model-config-toolbar.types'
+import type { Translate } from './types'
+import { useCallback, useState } from 'react'
+import { loadModelCapacities } from '../../service/model-config'
+import { mergeModelCards, modelConfigNotice, withDetail } from '../../service/model-config.utils'
+import { ensurePresets } from '../../service/presets'
+
+export const EDITOR_LABEL_KEYS = {
+ system: 'editorSystem',
+ vscode: 'editorVSCode',
+ cursor: 'editorCursor',
+ custom: 'editorCustom',
+} as const
+
+export interface UseModelConfigFetchResult {
+ busy: boolean
+ failure?: string
+ notice?: string
+ run: (targets?: readonly string[]) => void
+}
+
+export interface UseModelConfigFetchOptions {
+ t: Translate
+ models: readonly ModelDraft[]
+ probe: ModelProbeTarget
+ onApply?: (models: ModelDraft[], applied: number, undisclosed: string[]) => void
+}
+
+export function useModelConfigFetch(options: UseModelConfigFetchOptions): UseModelConfigFetchResult {
+ const [busy, setBusy] = useState(false)
+ const [failure, setFailure] = useState<string>()
+ const [notice, setNotice] = useState<string>()
+
+ const run = useCallback((targets?: readonly string[]) => {
+ void (async () => {
+ setBusy(true)
+ setFailure(undefined)
+ const [found] = await Promise.all([
+ loadModelCapacities({
+ settingsNs: options.probe.settingsNs,
+ profilePath: options.probe.profilePath,
+ ...options.probe.provider === undefined ? {} : { provider: options.probe.provider },
+ ...options.probe.baseURL === undefined ? {} : { baseURL: options.probe.baseURL },
+ ...options.probe.api === undefined ? {} : { api: options.probe.api },
+ ...options.probe.apiKey === undefined ? {} : { apiKey: options.probe.apiKey },
+ }),
+ ensurePresets(),
+ ])
+ setBusy(false)
+ if (!found.ok) {
+ setNotice(undefined)
+ setFailure(withDetail(options.t('configUnreachable'), found.error))
+ return
+ }
+ const merged = mergeModelCards(options.models, found.models, {
+ ...targets === undefined ? {} : { targets },
+ overwrite: targets === undefined,
+ })
+ if (merged.applied > 0)
+ options.onApply?.(merged.models, merged.applied, merged.undisclosed)
+ setNotice(modelConfigNotice(merged, {
+ applied: options.t('configApplied'),
+ none: options.t('configNoneApplied'),
+ undisclosed: options.t('configUndisclosed'),
+ }))
+ })()
+ }, [options])
+
+ return { busy, failure, notice, run }
+}
diff --git a/packages/dsh-tauri-ui/src/client/components/segmented-control.cssr.ts b/packages/dsh-tauri-ui/src/client/components/segmented-control.cssr.ts
new file mode 100644
index 00000000..b80adbec
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/client/components/segmented-control.cssr.ts
@@ -0,0 +1,56 @@
+import { styles as sharedStyles } from '../constants/theme'
+import { cssr } from '../utils/cssr'
+
+const { c, bem: { b, e } } = cssr
+const { primary, secondary, hover, modulePlatform, layer1, borderL3, focusRing } = sharedStyles
+
+export default b('segmented-control', {
+ boxSizing: 'border-box',
+ display: 'inline-flex',
+ alignItems: 'center',
+ gap: '2px',
+ padding: '2px',
+ border: 'none',
+ borderRadius: '10px',
+ background: modulePlatform,
+}, [
+ e('option', {
+ boxSizing: 'border-box',
+ display: 'inline-flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '6px',
+ minHeight: '28px',
+ padding: '0 12px',
+ border: 'none',
+ borderRadius: '8px',
+ background: 'transparent',
+ color: secondary,
+ cursor: 'pointer',
+ font: 'inherit',
+ fontSize: '13px',
+ lineHeight: '20px',
+ whiteSpace: 'nowrap',
+ }, [
+ c('&:hover:not(:disabled)', {
+ background: hover,
+ color: primary,
+ }),
+ c('&:focus-visible', focusRing),
+ c('&:disabled', {
+ cursor: 'not-allowed',
+ opacity: '0.5',
+ }),
+ ]),
+ e('option--selected', {
+ background: layer1,
+ color: primary,
+ fontWeight: '500',
+ boxShadow: `inset 0 0 0 0.5px ${borderL3}`,
+ }, [
+ c('&:hover:not(:disabled)', {
+ background: layer1,
+ color: primary,
+ }),
+ ]),
+])
diff --git a/packages/dsh-tauri-ui/src/client/components/segmented-control.tsx b/packages/dsh-tauri-ui/src/client/components/segmented-control.tsx
new file mode 100644
index 00000000..e29fee96
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/client/components/segmented-control.tsx
@@ -0,0 +1,98 @@
+import type { ReactElement } from 'react'
+import type { SegmentedControlProps } from './segmented-control.types'
+import { useRef } from 'react'
+import { SEGMENTED_CONTROL_STYLE_ID } from '../constants'
+import { useMountStyle } from '../hooks/use-mount-style'
+import segmentedControlStyle from './segmented-control.cssr'
+
+const FORWARD_KEYS = ['ArrowRight', 'ArrowDown']
+const BACKWARD_KEYS = ['ArrowLeft', 'ArrowUp']
+
+export function stepSegment<T extends { disabled?: boolean }>(
+ options: readonly T[],
+ current: number,
+ key: string,
+): number | undefined {
+ const count = options.length
+ if (count === 0)
+ return undefined
+ if (key === 'Home' || key === 'End') {
+ const index = key === 'Home' ? 0 : count - 1
+ return options[index]?.disabled === true ? undefined : index
+ }
+ const forward = FORWARD_KEYS.includes(key)
+ if (!forward && !BACKWARD_KEYS.includes(key))
+ return undefined
+ const step = forward ? 1 : -1
+ for (let offset = 1; offset <= count; offset++) {
+ const index = ((current + step * offset) % count + count) % count
+ if (options[index]?.disabled !== true)
+ return index
+ }
+ return undefined
+}
+
+export function SegmentedControl({ id, label, value, disabled, options, onChange }: SegmentedControlProps): ReactElement {
+ useMountStyle(segmentedControlStyle, SEGMENTED_CONTROL_STYLE_ID)
+ const refs = useRef<(HTMLButtonElement | null)[]>([])
+ const tabbed = id !== undefined
+ const selected = options.findIndex(option => option.value === value)
+
+ const move = (key: string): void => {
+ if (disabled === true)
+ return
+ const index = stepSegment(options, selected < 0 ? 0 : selected, key)
+ if (index === undefined)
+ return
+ const option = options[index]
+ if (option === undefined)
+ return
+ refs.current[index]?.focus()
+ if (option.value !== value)
+ onChange(option.value)
+ }
+
+ const segmentId = (index: number): string | undefined => {
+ if (id === undefined)
+ return undefined
+ return `${id}-${options[index]?.value ?? index}`
+ }
+
+ return (
+ <div
+ className="dshp-segmented-control"
+ role={tabbed ? 'tablist' : 'group'}
+ aria-label={label}
+ onKeyDown={(event) => {
+ move(event.key)
+ }}
+ >
+ {options.map((option, index) => {
+ const active = option.value === value
+ const locked = disabled === true || option.disabled === true
+ return (
+ <button
+ key={option.value}
+ ref={(node) => { refs.current[index] = node }}
+ type="button"
+ id={segmentId(index)}
+ role={tabbed ? 'tab' : undefined}
+ className={`dshp-segmented-control__option${active ? ' dshp-segmented-control__option--selected' : ''}`}
+ aria-selected={tabbed ? active : undefined}
+ aria-controls={tabbed && id !== undefined ? `${id}-${option.value}-panel` : undefined}
+ aria-pressed={tabbed ? undefined : active}
+ tabIndex={tabbed ? (active || (selected < 0 && index === 0) ? 0 : -1) : undefined}
+ title={option.title}
+ disabled={locked}
+ onClick={() => {
+ if (!locked && !active)
+ onChange(option.value)
+ }}
+ >
+ {option.label}
+ </button>
+ )
+ })}
+ </div>
+ )
+}
diff --git a/packages/dsh-tauri-ui/src/client/components/segmented-control.types.ts b/packages/dsh-tauri-ui/src/client/components/segmented-control.types.ts
new file mode 100644
index 00000000..36ed83e1
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/client/components/segmented-control.types.ts
@@ -0,0 +1,15 @@
+export interface SegmentedControlOption {
+ value: string
+ label: string
+ disabled?: boolean
+ title?: string
+}
+
+export interface SegmentedControlProps {
+ id?: string
+ label?: string
+ value: string
+ disabled?: boolean
+ options: readonly SegmentedControlOption[]
+ onChange: (next: string) => void
+}
diff --git a/packages/dsh-tauri-ui/src/client/index.ts b/packages/dsh-tauri-ui/src/client/index.ts
index 27b59240..e2df9185 100644
--- a/packages/dsh-tauri-ui/src/client/index.ts
+++ b/packages/dsh-tauri-ui/src/client/index.ts
@@ -19,8 +19,15 @@ export type * from './components/sidebar.types'
export type * from './components/trigger.types'
export * from './constants/theme'
export * from './hooks/use-mount-style'
+export * from './service/editor'
+export * from './service/model-config'
+export { hasModelConfig, mergeModelCards, modelConfigNotice, withCount, withDetail, withPath } from './service/model-config.utils'
+export type { ModelConfigMerge, ModelConfigMergeOptions } from './service/model-config.utils'
+export * from './service/model-presets'
+export * from './service/presets'
export type * from './store/modules/sections.types'
export type * from './store/modules/settings.types'
+export * from './types/remotes'
export type * from './types/sections'
export type * from './types/selector'
export * from './utils/cssr'
diff --git a/packages/dsh-tauri-ui/src/client/locales/index.ts b/packages/dsh-tauri-ui/src/client/locales/index.ts
index 8c9e2ce9..ba106360 100644
--- a/packages/dsh-tauri-ui/src/client/locales/index.ts
+++ b/packages/dsh-tauri-ui/src/client/locales/index.ts
@@ -17,6 +17,32 @@ export const locale = defineLocale(PLUGIN_ID, {
loading: '正在加载工作区…',
folderErrorTitle: '无法打开文件夹',
folderErrorRetry: '重新选择',
+ apply: '保存',
+ textEditor: '文本编辑器',
+ textEditorHint: '此设置仅用于模型页面的“打开配置文件”。',
+ editorSystem: '系统默认(推荐)',
+ editorVSCode: 'VS Code',
+ editorCursor: 'Cursor',
+ editorCustom: '自定义编辑器',
+ editorCommand: '应用名称或可执行文件路径',
+ editorCommandPlaceholder: '应用名称、.app 路径或可执行文件路径',
+ editorCommandHint: 'macOS 可填写应用名称或 .app 路径;Windows 请填写 .exe 完整路径;Linux 可填写程序名称或路径。无需引号,请勿附加启动参数。',
+ editorLoadFailed: '无法读取编辑器设置:{detail}',
+ editorSaveFailed: '无法保存编辑器设置:{detail}',
+ openConfigFile: '打开配置文件',
+ openConfigFileHint: '打开承载全部模型定义的设置文件',
+ openConfigFileLanded: '已打开 {path}',
+ openConfigFileDirectory: '配置文件尚未创建,已改为打开 {path}',
+ openConfigFileFailed: '无法打开配置文件,请确认编辑器已安装,或在“文本编辑器”中更换:{detail}',
+ autoConfigureModels: '自动配置所有模型',
+ autoConfigureModelsHint: '为列表中每个模型从端点读取上限,并按模型能力表补齐图片与思考档位',
+ fetchModelConfig: '获取配置',
+ fetchModelConfigHint: '从提供方端点读取该模型的上下文与输出上限,并按模型能力表补齐图片与思考档位',
+ fetchingConfig: '获取中…',
+ configUnreachable: '无法读取模型列表:{detail}',
+ configNoneApplied: '端点与模型能力表都没有为这些模型提供可写入的配置。',
+ configApplied: '已配置 {n} 个模型。',
+ configUndisclosed: '{n} 个模型未被端点披露。',
},
en: {
back: 'Back to app',
@@ -33,5 +59,31 @@ export const locale = defineLocale(PLUGIN_ID, {
loading: 'Loading workspaces…',
folderErrorTitle: 'Couldn’t open folder',
folderErrorRetry: 'Choose again',
+ apply: 'Apply',
+ textEditor: 'Text editor',
+ textEditorHint: 'This preference applies only to opening config files in the Models page.',
+ editorSystem: 'System default (recommended)',
+ editorVSCode: 'VS Code',
+ editorCursor: 'Cursor',
+ editorCustom: 'Custom editor',
+ editorCommand: 'Application name or executable path',
+ editorCommandPlaceholder: 'App name or executable path',
+ editorCommandHint: 'On macOS, enter an app name or .app path. On Windows, use the full .exe path. On Linux, use an executable name or path. Do not add quotes or arguments.',
+ editorLoadFailed: 'Could not load the editor preference: {detail}',
+ editorSaveFailed: 'Could not save the editor preference: {detail}',
+ openConfigFile: 'Open config file',
+ openConfigFileHint: 'Open the settings file that holds every model definition',
+ openConfigFileLanded: 'Opened {path}',
+ openConfigFileDirectory: 'The config file does not exist yet; opened {path} instead',
+ openConfigFileFailed: 'Could not open the config file. Check that your editor is installed, or change it in Text editor: {detail}',
+ autoConfigureModels: 'Configure all models',
+ autoConfigureModelsHint: 'Fill in limits from the endpoint and image/thinking capabilities from the model capability table for every listed model',
+ fetchModelConfig: 'Fetch config',
+ fetchModelConfigHint: 'Fill in this model\'s limits from the endpoint and its image/thinking capabilities from the model capability table',
+ fetchingConfig: 'Fetching…',
+ configUnreachable: 'Could not read the model list: {detail}',
+ configNoneApplied: 'Neither the endpoint nor the capability table had anything to write for these models.',
+ configApplied: 'Configured {n} model(s).',
+ configUndisclosed: '{n} model(s) were not disclosed by the endpoint.',
},
})
diff --git a/packages/dsh-tauri-ui/src/client/service/editor.ts b/packages/dsh-tauri-ui/src/client/service/editor.ts
new file mode 100644
index 00000000..19eb0a9c
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/client/service/editor.ts
@@ -0,0 +1,23 @@
+import type { EditorPreference } from '../../shared/editor.types'
+import { parseEditorPreference } from '../../shared/editor'
+import { getConfigEditor, putConfigEditor } from '../apis'
+
+export async function loadEditor(): Promise<EditorPreference> {
+ const response = await getConfigEditor({ ignoreResponseError: true })
+ if (response.error)
+ throw new Error(response.error)
+ return parseEditorPreference(response.preference)
+}
+
+export async function saveEditor(preference: EditorPreference): Promise<{ ok: boolean, error?: string }> {
+ try {
+ const response = await putConfigEditor({ preference: parseEditorPreference(preference) }, { ignoreResponseError: true })
+ if (response.error)
+ return { ok: false, error: response.error }
+ parseEditorPreference(response.preference)
+ return { ok: true }
+ }
+ catch (error) {
+ return { ok: false, error: error instanceof Error ? error.message : String(error) }
+ }
+}
diff --git a/packages/dsh-tauri-ui/src/client/service/model-config.ts b/packages/dsh-tauri-ui/src/client/service/model-config.ts
new file mode 100644
index 00000000..261f0a32
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/client/service/model-config.ts
@@ -0,0 +1,81 @@
+import type { LlmDiscoveredModel } from '../types/remotes.ts'
+import { getEndpointModels, postConfigOpen } from '../apis'
+
+export interface EndpointProbe {
+ settingsNs: string
+ profilePath: readonly string[]
+ provider?: string
+ baseURL?: string
+ api?: string
+ apiKey?: string
+}
+
+export type ModelCapacityFetch
+ = | { ok: true, models: readonly LlmDiscoveredModel[] }
+ | { ok: false, error: string }
+
+export type ConfigFileOpen
+ = | { ok: true, path: string, opened: 'file' | 'directory' }
+ | { ok: false, error: string }
+
+export type ModelDiscoveryOutcome
+ = | { readonly kind: 'found', readonly models: readonly LlmDiscoveredModel[] }
+ | { readonly kind: 'refused', readonly message: string }
+
+export interface ModelDiscoveryChannel {
+ discoverModels: (settingsNs: string, request: { provider?: string, baseURL?: string, api?: string, apiKey?: string }) => Promise<ModelDiscoveryOutcome>
+}
+
+async function fetchEndpointModels(probe: EndpointProbe): Promise<ModelCapacityFetch> {
+ try {
+ const response = await getEndpointModels({
+ ns: probe.settingsNs,
+ profilePath: JSON.stringify([...probe.profilePath]),
+ ...probe.baseURL === undefined || probe.baseURL.length === 0 ? {} : { baseURL: probe.baseURL },
+ ...probe.apiKey === undefined || probe.apiKey.length === 0 ? {} : { apiKey: probe.apiKey },
+ })
+ if (response.error !== undefined)
+ return { ok: false, error: response.error }
+ return { ok: true, models: response.models ?? [] }
+ }
+ catch (error) {
+ return { ok: false, error: error instanceof Error ? error.message : String(error) }
+ }
+}
+
+export async function loadModelCapacities(
+ probe: EndpointProbe,
+ operations?: ModelDiscoveryChannel,
+): Promise<ModelCapacityFetch> {
+ const direct = await fetchEndpointModels(probe)
+ if (direct.ok && direct.models.length > 0)
+ return direct
+ if (operations === undefined)
+ return direct
+ const official = await operations.discoverModels(probe.settingsNs, {
+ ...probe.provider === undefined ? {} : { provider: probe.provider },
+ ...probe.baseURL === undefined || probe.baseURL.length === 0 ? {} : { baseURL: probe.baseURL },
+ ...probe.api === undefined ? {} : { api: probe.api },
+ ...probe.apiKey === undefined ? {} : { apiKey: probe.apiKey },
+ })
+ if (official.kind === 'found' && official.models.length > 0)
+ return { ok: true, models: official.models }
+ if (!direct.ok)
+ return { ok: false, error: direct.error }
+ return {
+ ok: false,
+ error: official.kind === 'refused' ? official.message : 'the endpoint disclosed no models',
+ }
+}
+
+export async function openConfigFile(): Promise<ConfigFileOpen> {
+ try {
+ const response = await postConfigOpen({ ignoreResponseError: true })
+ if (response.error !== undefined)
+ return { ok: false, error: response.error }
+ return { ok: true, path: response.path ?? '', opened: response.opened ?? 'file' }
+ }
+ catch (error) {
+ return { ok: false, error: error instanceof Error ? error.message : String(error) }
+ }
+}
diff --git a/packages/dsh-tauri-ui/src/client/service/model-config.utils.test.ts b/packages/dsh-tauri-ui/src/client/service/model-config.utils.test.ts
new file mode 100644
index 00000000..40bc395e
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/client/service/model-config.utils.test.ts
@@ -0,0 +1,189 @@
+import type { LlmDiscoveredModel } from '../types/remotes.ts'
+import { beforeEach, describe, expect, it } from 'vitest'
+import {
+ hasModelConfig,
+ mergeModelCards,
+ modelConfigNotice,
+ withCount,
+ withDetail,
+ withPath,
+} from './model-config.utils'
+import { PRESET_FIXTURE } from './model-preset-fixtures'
+import { setPresetTable } from './model-presets'
+
+const found = (id: string, extra: Partial<LlmDiscoveredModel> = {}): LlmDiscoveredModel => ({ id, ...extra })
+
+describe('hasModelConfig', () => {
+ it('treats an identity-only row as unconfigured', () => {
+ expect(hasModelConfig({ id: 'm', name: 'M', description: 'd' })).toBe(false)
+ })
+
+ it('reports every capability field as configuration', () => {
+ expect(hasModelConfig({ id: 'm', contextWindow: 1024 })).toBe(true)
+ expect(hasModelConfig({ id: 'm', maxTokens: 128 })).toBe(true)
+ expect(hasModelConfig({ id: 'm', input: ['text'] })).toBe(true)
+ expect(hasModelConfig({ id: 'm', reasoningEfforts: false })).toBe(true)
+ })
+})
+
+describe('mergeModelCards', () => {
+ it('fills only the fields the row leaves empty', () => {
+ const merged = mergeModelCards(
+ [{ id: 'm', contextWindow: 4096 }],
+ [found('m', { contextWindow: 262144, maxTokens: 8192 })],
+ )
+ expect(merged.models).toEqual([{ id: 'm', contextWindow: 4096, maxTokens: 8192 }])
+ expect(merged.applied).toBe(1)
+ })
+
+ it('never rewrites a value the user already holds when filling', () => {
+ const merged = mergeModelCards([{ id: 'm', maxTokens: 512 }], [found('m', { maxTokens: 8192 })])
+ expect(merged.models[0]?.maxTokens).toBe(512)
+ expect(merged.applied).toBe(0)
+ })
+
+ it('rewrites the disclosed capacities when the caller asks to reconfigure', () => {
+ const merged = mergeModelCards(
+ [{ id: 'm', contextWindow: 4096, maxTokens: 512 }],
+ [found('m', { contextWindow: 262144, maxTokens: 8192 })],
+ { overwrite: true },
+ )
+ expect(merged.models[0]).toEqual({ id: 'm', contextWindow: 262144, maxTokens: 8192 })
+ expect(merged.applied).toBe(1)
+ })
+
+ it('keeps a field the endpoint did not disclose even when overwriting', () => {
+ const merged = mergeModelCards([{ id: 'm', maxTokens: 512 }], [found('m', { contextWindow: 262144 })], { overwrite: true })
+ expect(merged.models[0]).toEqual({ id: 'm', maxTokens: 512, contextWindow: 262144 })
+ })
+
+ it('limits the merge to the requested targets', () => {
+ const merged = mergeModelCards(
+ [{ id: 'a' }, { id: 'b' }],
+ [found('a', { contextWindow: 1 }), found('b', { contextWindow: 2 })],
+ { targets: ['b'] },
+ )
+ expect(merged.models).toEqual([{ id: 'a' }, { id: 'b', contextWindow: 2 }])
+ expect(merged.applied).toBe(1)
+ })
+
+ it('reports rows the endpoint did not disclose', () => {
+ const merged = mergeModelCards([{ id: 'a' }, { id: 'missing' }], [found('a', { contextWindow: 1 })])
+ expect(merged.undisclosed).toEqual(['missing'])
+ expect(merged.models[1]).toEqual({ id: 'missing' })
+ })
+
+ it('ignores a row whose id is still blank', () => {
+ const merged = mergeModelCards([{ id: '' }], [found('a', { contextWindow: 1 })])
+ expect(merged.applied).toBe(0)
+ expect(merged.undisclosed).toEqual([])
+ })
+
+ it('carries every listed row when no target is named', () => {
+ const merged = mergeModelCards([{ id: 'a' }, { id: 'b' }], [found('a', { maxTokens: 4 })])
+ expect(merged.models).toEqual([{ id: 'a', maxTokens: 4 }, { id: 'b' }])
+ expect(merged.applied).toBe(1)
+ })
+
+ it('leaves a row untouched when the endpoint disclosed no capacity', () => {
+ const merged = mergeModelCards([{ id: 'a' }], [found('a')])
+ expect(merged.applied).toBe(0)
+ expect(merged.models[0]).toEqual({ id: 'a' })
+ })
+})
+
+describe('mergeModelCards with presets', () => {
+ beforeEach(() => setPresetTable(PRESET_FIXTURE))
+
+ it('adds the capability facts the endpoint cannot disclose', () => {
+ const merged = mergeModelCards([{ id: 'gpt-4o' }], [found('gpt-4o', { contextWindow: 200000 })])
+ expect(merged.models[0]).toEqual({
+ id: 'gpt-4o',
+ contextWindow: 200000,
+ maxTokens: 16384,
+ input: ['text', 'image'],
+ })
+ })
+
+ it('prefers the endpoint capacity over the preset one', () => {
+ const merged = mergeModelCards([{ id: 'gpt-4o' }], [found('gpt-4o', { contextWindow: 1 })])
+ expect(merged.models[0]?.contextWindow).toBe(1)
+ })
+
+ it('falls back to the preset capacity only when the endpoint said nothing', () => {
+ const merged = mergeModelCards([{ id: 'gpt-4o' }], [])
+ expect(merged.models[0]).toEqual({
+ id: 'gpt-4o',
+ contextWindow: 128000,
+ maxTokens: 16384,
+ input: ['text', 'image'],
+ })
+ expect(merged.undisclosed).toEqual([])
+ })
+
+ it('never lets a preset capacity overwrite a value the row already holds', () => {
+ const merged = mergeModelCards([{ id: 'gpt-4o', contextWindow: 4096 }], [], { overwrite: true })
+ expect(merged.models[0]?.contextWindow).toBe(4096)
+ expect(merged.models[0]?.input).toEqual(['text', 'image'])
+ })
+
+ it('leaves rows the preset does not know to the endpoint alone', () => {
+ const merged = mergeModelCards([{ id: 'acme-inhouse-7b' }], [])
+ expect(merged.applied).toBe(0)
+ expect(merged.undisclosed).toEqual(['acme-inhouse-7b'])
+ expect(merged.models[0]).toEqual({ id: 'acme-inhouse-7b' })
+ })
+
+ it('writes the graded levels for a reasoning model', () => {
+ const merged = mergeModelCards([{ id: 'o3' }], [found('o3', { contextWindow: 200000 })])
+ expect(merged.models[0]?.reasoningEfforts).toEqual({ off: null, low: 'low', medium: 'medium', high: 'high' })
+ })
+
+ it('keeps the capabilities a row already declares on a single-row fill', () => {
+ const row = { id: 'gpt-4o', input: ['text'], reasoningEfforts: { off: null, low: 'low' } }
+ const filled = mergeModelCards([row], [], { targets: ['gpt-4o'] }).models[0]
+ expect(filled?.input).toEqual(['text'])
+ expect(filled?.reasoningEfforts).toEqual({ off: null, low: 'low' })
+ })
+
+ it('replaces the declared capabilities on a reconfigure', () => {
+ const row = { id: 'o3', input: ['text'], reasoningEfforts: { off: null, low: 'low' } }
+ const reconfigured = mergeModelCards([row], [], { targets: ['o3'], overwrite: true }).models[0]
+ expect(reconfigured?.input).toEqual(['text', 'image'])
+ expect(reconfigured?.reasoningEfforts).toEqual({ off: null, low: 'low', medium: 'medium', high: 'high' })
+ })
+
+ it('never rewrites a capability the table did not state as unsupported', () => {
+ const row = { id: 'gpt-4o', reasoningEfforts: { off: null, low: 'low' } }
+ const reconfigured = mergeModelCards([row], [], { targets: ['gpt-4o'], overwrite: true }).models[0]
+ expect(reconfigured?.reasoningEfforts).toEqual({ off: null, low: 'low' })
+ })
+})
+
+describe('copy placeholders', () => {
+ it('substitutes one placeholder without treating the rest as patterns', () => {
+ expect(withDetail('failed: {detail}', '$&')).toBe('failed: $&')
+ expect(withPath('opened {path}', 'C:\\a\\b')).toBe('opened C:\\a\\b')
+ expect(withCount('applied to {n} models', 3)).toBe('applied to 3 models')
+ })
+})
+
+describe('modelConfigNotice', () => {
+ const templates = { applied: 'filled {n}', none: 'nothing', undisclosed: 'missing {n}' }
+
+ it('reports the fill count', () => {
+ expect(modelConfigNotice({ applied: 2, undisclosed: [] }, templates)).toBe('filled 2')
+ })
+
+ it('reports both halves when some rows were not disclosed', () => {
+ expect(modelConfigNotice({ applied: 1, undisclosed: ['a', 'b'] }, templates)).toBe('filled 1 missing 2')
+ })
+
+ it('reports only the undisclosed half when nothing could be filled', () => {
+ expect(modelConfigNotice({ applied: 0, undisclosed: ['a'] }, templates)).toBe('missing 1')
+ })
+
+ it('falls back to the empty-result copy', () => {
+ expect(modelConfigNotice({ applied: 0, undisclosed: [] }, templates)).toBe('nothing')
+ })
+})
diff --git a/packages/dsh-tauri-ui/src/client/service/model-config.utils.ts b/packages/dsh-tauri-ui/src/client/service/model-config.utils.ts
new file mode 100644
index 00000000..12a0c073
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/client/service/model-config.utils.ts
@@ -0,0 +1,89 @@
+import type { LlmDiscoveredModel } from '../types/remotes.ts'
+import { presetFor } from './model-presets.ts'
+
+export type ModelDraft = Record<string, unknown>
+
+const CONFIG_FIELDS = ['contextWindow', 'maxTokens', 'input', 'reasoningEfforts'] as const
+
+export function hasModelConfig(model: ModelDraft): boolean {
+ return CONFIG_FIELDS.some(field => model[field] !== undefined)
+}
+
+export interface ModelConfigMerge {
+ models: ModelDraft[]
+ applied: number
+ undisclosed: string[]
+}
+
+export interface ModelConfigMergeOptions {
+ targets?: readonly string[]
+ overwrite?: boolean
+}
+
+export function mergeModelCards(
+ models: readonly ModelDraft[],
+ discovered: readonly LlmDiscoveredModel[],
+ options: ModelConfigMergeOptions = {},
+): ModelConfigMerge {
+ const byId = new Map(discovered.map(model => [model.id, model]))
+ const selected = options.targets === undefined ? undefined : new Set(options.targets)
+ const overwrite = options.overwrite === true
+ let applied = 0
+ const undisclosed: string[] = []
+ const next = models.map((model) => {
+ const id = typeof model.id === 'string' ? model.id : ''
+ if (selected !== undefined && !selected.has(id))
+ return model
+ const found = byId.get(id)
+ const preset = presetFor(id)
+ const patch: Record<string, unknown> = {}
+ if (found !== undefined) {
+ if (found.contextWindow !== undefined && (overwrite || model.contextWindow === undefined))
+ patch.contextWindow = found.contextWindow
+ if (found.maxTokens !== undefined && (overwrite || model.maxTokens === undefined))
+ patch.maxTokens = found.maxTokens
+ }
+ if (patch.contextWindow === undefined && model.contextWindow === undefined && preset?.contextWindow !== undefined)
+ patch.contextWindow = preset.contextWindow
+ if (patch.maxTokens === undefined && model.maxTokens === undefined && preset?.maxTokens !== undefined)
+ patch.maxTokens = preset.maxTokens
+ if (preset?.input !== undefined && (overwrite || model.input === undefined))
+ patch.input = [...preset.input]
+ if (preset?.efforts !== undefined && (overwrite || model.reasoningEfforts === undefined))
+ patch.reasoningEfforts = { ...preset.efforts }
+ if (Object.keys(patch).length === 0) {
+ if (found === undefined && id.length > 0)
+ undisclosed.push(id)
+ return model
+ }
+ applied += 1
+ return { ...model, ...patch }
+ })
+ return { models: next, applied, undisclosed }
+}
+
+export function withDetail(template: string, detail: string): string {
+ return template.replace('{detail}', () => detail)
+}
+
+export function withPath(template: string, path: string): string {
+ return template.replace('{path}', () => path)
+}
+
+export function withCount(template: string, count: number): string {
+ return template.replace('{n}', () => String(count))
+}
+
+export function modelConfigNotice(
+ merge: Pick<ModelConfigMerge, 'applied' | 'undisclosed'>,
+ templates: { applied: string, none: string, undisclosed: string },
+): string {
+ if (merge.applied === 0 && merge.undisclosed.length === 0)
+ return templates.none
+ const parts: string[] = []
+ if (merge.applied > 0)
+ parts.push(withCount(templates.applied, merge.applied))
+ if (merge.undisclosed.length > 0)
+ parts.push(withCount(templates.undisclosed, merge.undisclosed.length))
+ return parts.join(' ')
+}
diff --git a/packages/dsh-tauri-ui/src/client/service/model-preset-fixtures.ts b/packages/dsh-tauri-ui/src/client/service/model-preset-fixtures.ts
new file mode 100644
index 00000000..9449aa38
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/client/service/model-preset-fixtures.ts
@@ -0,0 +1,12 @@
+import type { PresetTable } from '../../shared/model-presets'
+
+export const PRESET_FIXTURE: PresetTable = {
+ 'claude-3-5-sonnet': [1, 0, 200000, 8192],
+ 'deepseek-reasoner': [0, 1, 131072, 65536],
+ 'gemini-2.5-flash': [1, 1, 1048576, 65535],
+ 'gpt-4o': [1, 0, 128000, 16384],
+ 'kimi-k2-thinking': [0, 1, 262144, 262144],
+ 'mimo-v2-flash': [0, 1, 131072, 32768],
+ 'o3': [1, 1, 200000, 100000],
+ 'qwen3-32b': [0, 1, 40960, 40960],
+}
diff --git a/packages/dsh-tauri-ui/src/client/service/model-presets.test.ts b/packages/dsh-tauri-ui/src/client/service/model-presets.test.ts
new file mode 100644
index 00000000..41dea2cf
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/client/service/model-presets.test.ts
@@ -0,0 +1,97 @@
+import { beforeEach, describe, expect, it } from 'vitest'
+import { PRESET_FIXTURE } from './model-preset-fixtures'
+import { presetFor, presetTableSize, setPresetTable } from './model-presets'
+
+const GRADED = { off: null, low: 'low', medium: 'medium', high: 'high' }
+const VISION = ['text', 'image']
+
+describe('presetFor with the downloaded table', () => {
+ beforeEach(() => setPresetTable(PRESET_FIXTURE))
+
+ it('reads vision and thinking off the table', () => {
+ expect(presetFor('gpt-4o')?.input).toEqual(VISION)
+ expect(presetFor('o3')?.input).toEqual(VISION)
+ expect(presetFor('o3')?.efforts).toEqual(GRADED)
+ expect(presetFor('deepseek-reasoner')?.efforts).toEqual(GRADED)
+ expect(presetFor('mimo-v2-flash')?.efforts).toEqual(GRADED)
+ })
+
+ it('leaves a fact the table does not state undeclared instead of writing it off', () => {
+ expect(presetFor('gpt-4o')).toEqual({ input: VISION, contextWindow: 128000, maxTokens: 16384 })
+ expect(presetFor('deepseek-reasoner')).toEqual({
+ efforts: GRADED,
+ contextWindow: 131072,
+ maxTokens: 65536,
+ })
+ })
+
+ it('carries the table capacities', () => {
+ expect(presetFor('gpt-4o')?.contextWindow).toBe(128000)
+ expect(presetFor('gpt-4o')?.maxTokens).toBe(16384)
+ })
+
+ it('resolves provider prefixes', () => {
+ expect(presetFor('openai/gpt-4o')?.input).toEqual(VISION)
+ expect(presetFor('Qwen/Qwen3-32B')?.efforts).toEqual(GRADED)
+ expect(presetFor('openrouter/moonshotai/kimi-k2-thinking')?.efforts).toEqual(GRADED)
+ })
+
+ it('resolves dated and versioned spellings through prefix fallback', () => {
+ expect(presetFor('gpt-4o-2024-08-06')?.contextWindow).toBe(128000)
+ expect(presetFor('claude-3-5-sonnet-20241022')?.input).toEqual(VISION)
+ expect(presetFor('gemini-2.5-flash-preview-09-2025')?.efforts).toEqual(GRADED)
+ })
+
+ it('adds the family rule on top of a table that has no row', () => {
+ expect(presetFor('doubao-seed-1.6')?.input).toEqual(VISION)
+ expect(presetFor('doubao-seed-1.6')?.efforts).toEqual(GRADED)
+ expect(presetFor('minimax-m2')?.efforts).toEqual(GRADED)
+ })
+
+ it('hands out a fresh effort map so one row cannot mutate another', () => {
+ expect(presetFor('o3')?.efforts).not.toBe(presetFor('o3')?.efforts)
+ })
+
+ it('reports how many rows are loaded', () => {
+ expect(presetTableSize()).toBe(Object.keys(PRESET_FIXTURE).length)
+ })
+})
+
+describe('presetFor without the table', () => {
+ beforeEach(() => setPresetTable({}))
+
+ it('still answers for families the model name already declares', () => {
+ expect(presetFor('gemini-1.5-pro')?.input).toEqual(VISION)
+ expect(presetFor('claude-3-haiku')?.input).toEqual(VISION)
+ expect(presetFor('glm-4v')?.input).toEqual(VISION)
+ expect(presetFor('grok-2-vision')?.input).toEqual(VISION)
+ expect(presetFor('glm-4.6')?.efforts).toEqual(GRADED)
+ expect(presetFor('glm-z1-air')?.efforts).toEqual(GRADED)
+ expect(presetFor('minimax-m1')?.efforts).toEqual(GRADED)
+ expect(presetFor('gpt-5-mini')?.efforts).toEqual(GRADED)
+ expect(presetFor('gpt-5-mini')?.input).toEqual(VISION)
+ expect(presetFor('o3')?.efforts).toEqual(GRADED)
+ })
+
+ it('reads generic modality and thinking markers', () => {
+ expect(presetFor('acme-vl-72b')?.input).toEqual(VISION)
+ expect(presetFor('acme-vision-large')?.input).toEqual(VISION)
+ expect(presetFor('acme-omni-mini')?.input).toEqual(VISION)
+ expect(presetFor('acme-thinking-32b')?.efforts).toEqual(GRADED)
+ expect(presetFor('some-qwq-32b')?.efforts).toEqual(GRADED)
+ })
+
+ it('offers no capacities of its own', () => {
+ expect(presetFor('gemini-1.5-pro')?.contextWindow).toBeUndefined()
+ expect(presetFor('gemini-1.5-pro')?.maxTokens).toBeUndefined()
+ })
+
+ it('leaves models it cannot place unconfigured', () => {
+ expect(presetFor('glm-4-plus')).toBeUndefined()
+ expect(presetFor('doubao-pro-32k')).toBeUndefined()
+ expect(presetFor('abab6.5s-chat')).toBeUndefined()
+ expect(presetFor('acme-inhouse-7b')).toBeUndefined()
+ expect(presetFor('m')).toBeUndefined()
+ expect(presetFor(' ')).toBeUndefined()
+ })
+})
diff --git a/packages/dsh-tauri-ui/src/client/service/model-presets.ts b/packages/dsh-tauri-ui/src/client/service/model-presets.ts
new file mode 100644
index 00000000..bef830ed
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/client/service/model-presets.ts
@@ -0,0 +1,109 @@
+import type { PresetRow, PresetTable } from '../../shared/model-presets'
+
+export interface ModelCapabilityPreset {
+ input?: readonly string[]
+ efforts?: Readonly<Record<string, string | null>>
+ contextWindow?: number
+ maxTokens?: number
+}
+
+interface FamilyRule {
+ pattern: RegExp
+ vision?: boolean
+ reasoning?: boolean
+}
+
+const GRADED = { off: null, low: 'low', medium: 'medium', high: 'high' } as const
+
+const MIN_PREFIX_LENGTH = 3
+
+const FAMILY_RULES: readonly FamilyRule[] = [
+ { pattern: /\bclaude/, vision: true },
+ { pattern: /\bgemini/, vision: true },
+ { pattern: /\bgrok-[2-9]/, vision: true },
+ { pattern: /[-.]vl(?:-|$)|[-.]vision(?:-|$)|[-.]omni(?:-|$)/, vision: true },
+ { pattern: /\bglm-[\d.]+v/, vision: true },
+ { pattern: /(?:^|[/-])seed-1\.[6-9]|\bdoubao-seed|\bseed-[2-9]/, vision: true, reasoning: true },
+ { pattern: /\bgpt-5/, vision: true, reasoning: true },
+ { pattern: /\bglm-(?:4\.[5-9]|5|z)/, reasoning: true },
+ { pattern: /[-.]thinking(?:-|$)|[-.]reasoning(?:-|$)/, reasoning: true },
+ { pattern: /(?:^|[/-])(?:r1|qwq|reasoner)(?:-|$)/, reasoning: true },
+ { pattern: /\bminimax-m[12]/, reasoning: true },
+ { pattern: /\bqwen3/, reasoning: true },
+ { pattern: /\bo[1-9](?:-|$)/, reasoning: true },
+]
+
+let table: PresetTable = {}
+
+export function setPresetTable(next: PresetTable): void {
+ table = next
+}
+
+export function presetTableSize(): number {
+ return Object.keys(table).length
+}
+
+function ruleFacts(id: string): { vision: boolean, reasoning: boolean } | undefined {
+ let vision = false
+ let reasoning = false
+ let matched = false
+ for (const rule of FAMILY_RULES) {
+ if (!rule.pattern.test(id))
+ continue
+ matched = true
+ vision = vision || rule.vision === true
+ reasoning = reasoning || rule.reasoning === true
+ }
+ return matched ? { vision, reasoning } : undefined
+}
+
+function combine(row: PresetRow | undefined, rule: { vision: boolean, reasoning: boolean } | undefined): ModelCapabilityPreset {
+ const vision = row?.[0] === 1 || rule?.vision === true
+ const reasoning = row?.[1] === 1 || rule?.reasoning === true
+ const maxInput = row?.[2] ?? 0
+ const maxOutput = row?.[3] ?? 0
+ return {
+ ...vision ? { input: ['text', 'image'] } : {},
+ ...reasoning ? { efforts: { ...GRADED } } : {},
+ ...maxInput === 0 ? {} : { contextWindow: maxInput },
+ ...maxOutput === 0 ? {} : { maxTokens: maxOutput },
+ }
+}
+
+function candidateKeys(id: string): string[] {
+ const keys: string[] = []
+ const push = (value: string): void => {
+ if (value.length > 0 && !keys.includes(value))
+ keys.push(value)
+ }
+ const slash = id.lastIndexOf('/')
+ const bare = slash >= 0 ? id.slice(slash + 1) : id
+ push(id)
+ push(bare)
+ const segments = bare.split('-')
+ for (let end = segments.length - 1; end > 0; end--) {
+ const prefix = segments.slice(0, end).join('-')
+ if (prefix.length < MIN_PREFIX_LENGTH)
+ break
+ push(prefix)
+ }
+ return keys
+}
+
+export function presetFor(id: string): ModelCapabilityPreset | undefined {
+ const normalized = id.trim().toLowerCase()
+ if (normalized.length === 0)
+ return undefined
+ let row: PresetRow | undefined
+ for (const key of candidateKeys(normalized)) {
+ const hit = table[key]
+ if (hit !== undefined) {
+ row = hit
+ break
+ }
+ }
+ const rule = ruleFacts(normalized)
+ if (row === undefined && rule === undefined)
+ return undefined
+ return combine(row, rule)
+}
diff --git a/packages/dsh-tauri-ui/src/client/service/presets.ts b/packages/dsh-tauri-ui/src/client/service/presets.ts
new file mode 100644
index 00000000..64ce9aca
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/client/service/presets.ts
@@ -0,0 +1,50 @@
+import type { PresetRow } from '../../shared/model-presets'
+import { getPresets } from '../apis'
+import { setPresetTable } from './model-presets'
+
+export type PresetsLoad
+ = | { ok: true, count: number, stale: boolean }
+ | { ok: false, error: string }
+
+let pending: Promise<PresetsLoad> | undefined
+
+function toRows(input: Record<string, readonly number[]> | undefined): Record<string, PresetRow> {
+ const rows: Record<string, PresetRow> = {}
+ for (const [key, value] of Object.entries(input ?? {})) {
+ const [vision, reasoning, maxInput, maxOutput] = value
+ if (typeof vision !== 'number' || typeof reasoning !== 'number')
+ continue
+ if (typeof maxInput !== 'number' || typeof maxOutput !== 'number')
+ continue
+ rows[key] = [vision, reasoning, maxInput, maxOutput]
+ }
+ return rows
+}
+
+async function load(): Promise<PresetsLoad> {
+ try {
+ const response = await getPresets()
+ if (response.error !== undefined)
+ return { ok: false, error: response.error }
+ const rows = toRows(response.presets)
+ const count = Object.keys(rows).length
+ if (count === 0)
+ return { ok: false, error: 'the preset dataset carried no chat models' }
+ setPresetTable(rows)
+ return { ok: true, count, stale: response.stale === true }
+ }
+ catch (error) {
+ return { ok: false, error: error instanceof Error ? error.message : String(error) }
+ }
+}
+
+export async function ensurePresets(): Promise<PresetsLoad> {
+ if (pending !== undefined)
+ return pending
+ const attempt = load()
+ pending = attempt
+ const result = await attempt
+ if (!result.ok)
+ pending = undefined
+ return result
+}
diff --git a/packages/dsh-tauri-ui/src/client/types/remotes.ts b/packages/dsh-tauri-ui/src/client/types/remotes.ts
new file mode 100644
index 00000000..a1d5b9de
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/client/types/remotes.ts
@@ -0,0 +1,24 @@
+export type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }
+
+export interface RemoteFailure {
+ code: string
+ message: string
+}
+
+export type RemoteResult<T>
+ = | { ok: true, value: T }
+ | { ok: false, error: RemoteFailure }
+
+export interface LlmModelDiscoveryRequest {
+ provider?: string
+ baseURL?: string
+ api?: string
+ apiKey?: string
+}
+
+export interface LlmDiscoveredModel {
+ id: string
+ name?: string
+ contextWindow?: number
+ maxTokens?: number
+}
diff --git a/packages/dsh-tauri-ui/src/host/routes/config/editor/get.ts b/packages/dsh-tauri-ui/src/host/routes/config/editor/get.ts
new file mode 100644
index 00000000..38e4745d
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/host/routes/config/editor/get.ts
@@ -0,0 +1,14 @@
+import type { EventHandlerRequest } from 'dsh-tauri'
+import type { EditorPreferenceResponse } from '../../index.types'
+import { defineEventHandler } from 'dsh-tauri'
+import { configFile } from '../../../service/config-file'
+
+export default defineEventHandler<EventHandlerRequest, Promise<EditorPreferenceResponse>>(async (event) => {
+ try {
+ return { preference: await configFile.load() }
+ }
+ catch (error) {
+ event.res.status = 500
+ return { error: error instanceof Error ? error.message : String(error) }
+ }
+})
diff --git a/packages/dsh-tauri-ui/src/host/routes/config/editor/put.ts b/packages/dsh-tauri-ui/src/host/routes/config/editor/put.ts
new file mode 100644
index 00000000..a8a579af
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/host/routes/config/editor/put.ts
@@ -0,0 +1,25 @@
+import type { EventHandlerRequest } from 'dsh-tauri'
+import type { EditorPreference } from '../../../../shared/editor.types'
+import type { EditorPreferenceBody, EditorPreferenceResponse } from '../../index.types'
+import { defineEventHandler, readBody } from 'dsh-tauri'
+import { parseEditorPreference } from '../../../../shared/editor'
+import { configFile } from '../../../service/config-file'
+
+export default defineEventHandler<EventHandlerRequest, Promise<EditorPreferenceResponse>>(async (event) => {
+ let preference: EditorPreference
+ try {
+ const body = await readBody<EditorPreferenceBody>(event, { type: 'json' })
+ preference = parseEditorPreference(body?.preference)
+ }
+ catch (error) {
+ event.res.status = 400
+ return { error: error instanceof Error ? error.message : String(error) }
+ }
+ try {
+ return { preference: await configFile.save(preference) }
+ }
+ catch (error) {
+ event.res.status = 500
+ return { error: error instanceof Error ? error.message : String(error) }
+ }
+})
diff --git a/packages/dsh-tauri-ui/src/host/routes/config/open/post.ts b/packages/dsh-tauri-ui/src/host/routes/config/open/post.ts
new file mode 100644
index 00000000..eaa69dc3
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/host/routes/config/open/post.ts
@@ -0,0 +1,13 @@
+import type { EventHandlerRequest } from 'dsh-tauri'
+import type { OpenModelsConfigResponse } from '../../index.types'
+import { defineEventHandler } from 'dsh-tauri'
+import { configFile } from '../../../service/config-file'
+
+export default defineEventHandler<EventHandlerRequest, Promise<OpenModelsConfigResponse>>(async (event) => {
+ const result = await configFile.open()
+ if (!result.ok) {
+ event.res.status = 500
+ return { ok: false, path: result.path, error: result.error }
+ }
+ return { ok: true, path: result.path, opened: result.opened }
+})
diff --git a/packages/dsh-tauri-ui/src/host/routes/endpoint/models/get.ts b/packages/dsh-tauri-ui/src/host/routes/endpoint/models/get.ts
new file mode 100644
index 00000000..05a9b487
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/host/routes/endpoint/models/get.ts
@@ -0,0 +1,19 @@
+import type { EventHandlerRequest } from 'dsh-tauri'
+import type { EndpointModelsResponse, GetEndpointModelsQuery } from '../../index.types'
+import { defineEventHandler, getQuery } from 'dsh-tauri'
+import { endpointModels } from '../../../service/endpoint-models'
+
+export default defineEventHandler<EventHandlerRequest, Promise<EndpointModelsResponse>>(async (event) => {
+ const query = getQuery<GetEndpointModelsQuery>(event)
+ const result = await endpointModels.list({
+ ns: typeof query.ns === 'string' ? query.ns : '',
+ profilePath: typeof query.profilePath === 'string' ? query.profilePath : undefined,
+ baseURL: typeof query.baseURL === 'string' ? query.baseURL : undefined,
+ apiKey: typeof query.apiKey === 'string' ? query.apiKey : undefined,
+ })
+ if (!result.ok) {
+ event.res.status = 502
+ return { ok: false, error: result.error }
+ }
+ return { ok: true, url: result.url, models: result.models }
+})
diff --git a/packages/dsh-tauri-ui/src/host/routes/index.ts b/packages/dsh-tauri-ui/src/host/routes/index.ts
index cfe69fdd..990c3352 100644
--- a/packages/dsh-tauri-ui/src/host/routes/index.ts
+++ b/packages/dsh-tauri-ui/src/host/routes/index.ts
@@ -1,6 +1,16 @@
import { defineRoutes } from 'dsh-tauri'
+import getEditor from './config/editor/get'
+import putEditor from './config/editor/put'
+import openConfig from './config/open/post'
+import endpointModels from './endpoint/models/get'
+import presets from './presets/get'
import resume from './session/resume/post'
export const routes = defineRoutes((disposer) => {
disposer.post({ kind: 'exact', path: '/api/desktop/dsh-tauri-ui/session/resume' }, resume)
+ disposer.get({ kind: 'exact', path: '/api/desktop/dsh-tauri-ui/config/editor' }, getEditor)
+ disposer.put({ kind: 'exact', path: '/api/desktop/dsh-tauri-ui/config/editor' }, putEditor)
+ disposer.post({ kind: 'exact', path: '/api/desktop/dsh-tauri-ui/config/open' }, openConfig)
+ disposer.get({ kind: 'exact', path: '/api/desktop/dsh-tauri-ui/endpoint/models' }, endpointModels)
+ disposer.get({ kind: 'exact', path: '/api/desktop/dsh-tauri-ui/presets' }, presets)
})
diff --git a/packages/dsh-tauri-ui/src/host/routes/index.types.ts b/packages/dsh-tauri-ui/src/host/routes/index.types.ts
new file mode 100644
index 00000000..9d1617fc
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/host/routes/index.types.ts
@@ -0,0 +1,52 @@
+import type { EditorPreference } from '../../shared/editor.types'
+
+export interface EditorPreferenceBody {
+ preference: EditorPreference
+}
+
+export interface EditorPreferenceResponse {
+ preference?: EditorPreference
+ error?: string
+}
+
+export interface EndpointModelCard {
+ id: string
+ name?: string
+ contextWindow?: number
+ maxTokens?: number
+}
+
+export interface GetEndpointModelsQuery {
+ ns?: string
+ profilePath?: string
+ baseURL?: string
+ apiKey?: string
+}
+
+export interface EndpointModelsResponse {
+ ok?: boolean
+ url?: string
+ models?: EndpointModelCard[]
+ error?: string
+}
+
+export interface OpenModelsConfigResponse {
+ ok?: boolean
+ path?: string
+ opened?: 'file' | 'directory'
+ error?: string
+}
+
+export interface GetPresetsQuery {
+ force?: string
+}
+
+export interface PresetsResponse {
+ ok?: boolean
+ source?: string
+ fetchedAt?: string
+ stale?: boolean
+ count?: number
+ presets?: Record<string, readonly number[]>
+ error?: string
+}
diff --git a/packages/dsh-tauri-ui/src/host/routes/presets/get.ts b/packages/dsh-tauri-ui/src/host/routes/presets/get.ts
new file mode 100644
index 00000000..e7f95104
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/host/routes/presets/get.ts
@@ -0,0 +1,21 @@
+import type { EventHandlerRequest } from 'dsh-tauri'
+import type { GetPresetsQuery, PresetsResponse } from '../index.types'
+import { defineEventHandler, getQuery } from 'dsh-tauri'
+import { modelPresets } from '../../service/model-presets'
+
+export default defineEventHandler<EventHandlerRequest, Promise<PresetsResponse>>(async (event) => {
+ const query = getQuery<GetPresetsQuery>(event)
+ const result = await modelPresets.resolve(query.force === 'true')
+ if (!result.ok) {
+ event.res.status = 502
+ return { ok: false, error: result.error }
+ }
+ return {
+ ok: true,
+ source: result.source,
+ fetchedAt: result.fetchedAt,
+ stale: result.stale,
+ count: Object.keys(result.presets).length,
+ presets: result.presets,
+ }
+})
diff --git a/packages/dsh-tauri-ui/src/host/service/config-file.test.ts b/packages/dsh-tauri-ui/src/host/service/config-file.test.ts
new file mode 100644
index 00000000..e5401f20
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/host/service/config-file.test.ts
@@ -0,0 +1,135 @@
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { openDirectory, writeAtomic } from 'dsh-tauri'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { configFile } from './config-file'
+import { openInEditor } from './config-file.utils'
+
+vi.mock('node:fs/promises', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('node:fs/promises')>()
+ return { ...actual, readFile: vi.fn(actual.readFile) }
+})
+vi.mock('dsh-tauri', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('dsh-tauri')>()
+ return { ...actual, openDirectory: vi.fn(), writeAtomic: vi.fn(actual.writeAtomic) }
+})
+vi.mock('./config-file.utils', () => ({ openInEditor: vi.fn() }))
+
+describe('config file editor preference', () => {
+ let home: string
+
+ beforeEach(async () => {
+ home = await mkdtemp(join(tmpdir(), 'dsh-editor-'))
+ vi.stubEnv('DSH_HOME', home)
+ vi.mocked(openInEditor).mockResolvedValue(undefined)
+ })
+
+ afterEach(async () => {
+ vi.unstubAllEnvs()
+ vi.clearAllMocks()
+ await rm(home, { recursive: true, force: true })
+ })
+
+ it('keeps the system default for existing users without a preference', async () => {
+ await writeFile(join(home, 'settings.yaml'), 'models: {}\n')
+ expect(await configFile.load()).toEqual({ editor: 'system', command: '' })
+ expect(await configFile.open()).toEqual({ ok: true, path: join(home, 'settings.yaml'), opened: 'file' })
+ expect(openInEditor).toHaveBeenCalledWith(join(home, 'settings.yaml'), { editor: 'system', command: '' })
+ })
+
+ it.each([
+ ['malformed JSON', '{'],
+ ['invalid shape', 'null'],
+ ['unknown editor', '{"editor":"unknown","command":""}'],
+ ['empty custom command', '{"editor":"custom","command":" "}'],
+ ])('recovers from %s and allows saving a new preference', async (_, content) => {
+ const path = join(home, 'dsh-tauri-ui', 'editor.json')
+ await mkdir(join(home, 'dsh-tauri-ui'))
+ await writeFile(path, content)
+ await writeFile(join(home, 'settings.yaml'), 'models: {}\n')
+
+ expect(await configFile.load()).toEqual({ editor: 'system', command: '' })
+ expect(await configFile.open()).toEqual({ ok: true, path: join(home, 'settings.yaml'), opened: 'file' })
+ expect(openInEditor).toHaveBeenCalledWith(join(home, 'settings.yaml'), { editor: 'system', command: '' })
+ expect(await readFile(path, 'utf8')).toBe(content)
+
+ await configFile.save({ editor: 'vscode', command: '' })
+ expect(await configFile.load()).toEqual({ editor: 'vscode', command: '' })
+ })
+
+ it.each(['EACCES', 'EIO'])('reports %s instead of falling back to the system editor', async (code) => {
+ await writeFile(join(home, 'settings.yaml'), 'models: {}\n')
+ const error = Object.assign(new Error(code), { code })
+ vi.mocked(readFile).mockRejectedValueOnce(error)
+ await expect(configFile.load()).rejects.toBe(error)
+
+ vi.mocked(readFile).mockRejectedValueOnce(error)
+ expect(await configFile.open()).toEqual({ ok: false, path: join(home, 'settings.yaml'), error: code })
+ expect(openInEditor).not.toHaveBeenCalled()
+ expect(openDirectory).not.toHaveBeenCalled()
+ })
+
+ it('persists a custom editor and uses it on the next open', async () => {
+ await writeFile(join(home, 'settings.yaml'), 'models: {}\n')
+ await configFile.save({ editor: 'custom', command: ' /Applications/My Editor.app ' })
+ const preference = { editor: 'custom', command: '/Applications/My Editor.app' }
+ expect(JSON.parse(await readFile(join(home, 'dsh-tauri-ui', 'editor.json'), 'utf8'))).toEqual(preference)
+ expect(await configFile.load()).toEqual(preference)
+ await configFile.open()
+ expect(openInEditor).toHaveBeenCalledWith(join(home, 'settings.yaml'), preference)
+ await configFile.save({ editor: 'system', command: '' })
+ expect(await configFile.load()).toEqual({ editor: 'system', command: '' })
+ })
+
+ it('rejects an empty custom editor without replacing the saved preference', async () => {
+ await configFile.save({ editor: 'vscode', command: '' })
+ await expect(configFile.save({ editor: 'custom', command: ' ' })).rejects.toThrow('EDITOR_COMMAND_REQUIRED')
+ expect(await configFile.load()).toEqual({ editor: 'vscode', command: '' })
+ })
+
+ it('persists and opens with the Cursor preset', async () => {
+ await writeFile(join(home, 'settings.yaml'), 'models: {}\n')
+ const preference = { editor: 'cursor', command: '' } as const
+ await configFile.save(preference)
+ expect(await configFile.load()).toEqual(preference)
+ await configFile.open()
+ expect(openInEditor).toHaveBeenCalledWith(join(home, 'settings.yaml'), preference)
+ })
+
+ it('reports launcher failure instead of silently opening a different app', async () => {
+ await writeFile(join(home, 'settings.yaml'), 'models: {}\n')
+ vi.mocked(openInEditor).mockRejectedValueOnce(new Error('Editor not found'))
+ expect(await configFile.open()).toEqual({ ok: false, path: join(home, 'settings.yaml'), error: 'Editor not found' })
+ expect(openDirectory).not.toHaveBeenCalled()
+ })
+
+ it('opens and reports the containing directory when settings do not exist', async () => {
+ expect(await configFile.open()).toEqual({ ok: true, path: home, opened: 'directory' })
+ expect(openDirectory).toHaveBeenCalledWith(home)
+ expect(openInEditor).not.toHaveBeenCalled()
+ })
+
+ it('treats a directory named settings.yaml as no settings file and opens the containing directory', async () => {
+ await mkdir(join(home, 'settings.yaml'))
+
+ expect(await configFile.open()).toEqual({ ok: true, path: home, opened: 'directory' })
+ expect(openDirectory).toHaveBeenCalledWith(home)
+ expect(openInEditor).not.toHaveBeenCalled()
+ })
+
+ it('surfaces an atomic write failure without replacing the stored preference', async () => {
+ const path = join(home, 'dsh-tauri-ui', 'editor.json')
+ await configFile.save({ editor: 'vscode', command: '' })
+
+ const failure = Object.assign(new Error('ENOSPC: no space left on device'), { code: 'ENOSPC' })
+ vi.mocked(writeAtomic).mockRejectedValueOnce(failure)
+
+ await expect(configFile.save({ editor: 'cursor', command: '' })).rejects.toBe(failure)
+ expect(writeAtomic).toHaveBeenCalledTimes(2)
+ const [target, serialized] = vi.mocked(writeAtomic).mock.calls[1]!
+ expect(target).toBe(path)
+ expect(JSON.parse(String(serialized))).toEqual({ editor: 'cursor', command: '' })
+ expect(await configFile.load()).toEqual({ editor: 'vscode', command: '' })
+ })
+})
diff --git a/packages/dsh-tauri-ui/src/host/service/config-file.ts b/packages/dsh-tauri-ui/src/host/service/config-file.ts
new file mode 100644
index 00000000..173ec049
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/host/service/config-file.ts
@@ -0,0 +1,65 @@
+import type { EditorPreference } from '../../shared/editor.types'
+import type { ConfigOpenResult } from './config-file.types'
+import { readFile, stat } from 'node:fs/promises'
+import { dirname, join } from 'node:path'
+import { defineService, openDirectory, writeAtomic } from 'dsh-tauri'
+import { PLUGIN_ID } from '../../shared/constants'
+import { parseEditorPreference } from '../../shared/editor'
+import { resolveSettingsFilePath } from '../utils/paths'
+import { openInEditor } from './config-file.utils'
+
+export const configFile = defineService({
+ async load(): Promise<EditorPreference> {
+ let content: string
+ try {
+ content = await readFile(preferencePath(), 'utf8')
+ }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT')
+ return { editor: 'system', command: '' }
+ throw error
+ }
+ try {
+ return parseEditorPreference(JSON.parse(content))
+ }
+ catch {
+ return { editor: 'system', command: '' }
+ }
+ },
+
+ async save(preference: EditorPreference): Promise<EditorPreference> {
+ const normalized = parseEditorPreference(preference)
+ await writeAtomic(preferencePath(), JSON.stringify(normalized))
+ return normalized
+ },
+
+ async open(): Promise<ConfigOpenResult> {
+ const path = resolveSettingsFilePath()
+ try {
+ const servesFile = await isFile(path)
+ if (servesFile)
+ await openInEditor(path, await configFile.load())
+ else
+ await openDirectory(dirname(path))
+ return { ok: true, path: servesFile ? path : dirname(path), opened: servesFile ? 'file' : 'directory' }
+ }
+ catch (error) {
+ return { ok: false, path, error: error instanceof Error ? error.message : String(error) }
+ }
+ },
+})
+
+function preferencePath(): string {
+ return join(dirname(resolveSettingsFilePath()), PLUGIN_ID, 'editor.json')
+}
+
+async function isFile(path: string): Promise<boolean> {
+ try {
+ return (await stat(path)).isFile()
+ }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT')
+ return false
+ throw error
+ }
+}
diff --git a/packages/dsh-tauri-ui/src/host/service/config-file.types.ts b/packages/dsh-tauri-ui/src/host/service/config-file.types.ts
new file mode 100644
index 00000000..dcea8d97
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/host/service/config-file.types.ts
@@ -0,0 +1,3 @@
+export type ConfigOpenResult
+ = | { ok: true, path: string, opened: 'file' | 'directory' }
+ | { ok: false, path: string, error: string }
diff --git a/packages/dsh-tauri-ui/src/host/service/config-file.utils.test.ts b/packages/dsh-tauri-ui/src/host/service/config-file.utils.test.ts
new file mode 100644
index 00000000..5cceae25
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/host/service/config-file.utils.test.ts
@@ -0,0 +1,94 @@
+import { execFile } from 'node:child_process'
+import { existsSync } from 'node:fs'
+import { openUrl, spawnDetached } from 'dsh-tauri'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { openInEditor } from './config-file.utils'
+
+const runtime = vi.hoisted(() => ({ platform: 'darwin', env: {} as NodeJS.ProcessEnv }))
+vi.mock('node:process', () => ({ default: runtime }))
+vi.mock('node:fs', () => ({ existsSync: vi.fn() }))
+vi.mock('node:child_process', () => ({
+ execFile: vi.fn((_command, _args, _options, callback) => callback(null, '', '')),
+}))
+vi.mock('dsh-tauri', () => ({ openUrl: vi.fn(), spawnDetached: vi.fn() }))
+
+describe('opening files in an editor', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ runtime.platform = 'darwin'
+ runtime.env = {}
+ vi.mocked(existsSync).mockReturnValue(false)
+ })
+
+ it('uses the existing system association when requested', async () => {
+ await openInEditor('/tmp/settings.yaml', { editor: 'system', command: '' })
+ expect(openUrl).toHaveBeenCalledWith('/tmp/settings.yaml')
+ expect(execFile).not.toHaveBeenCalled()
+ expect(spawnDetached).not.toHaveBeenCalled()
+ })
+
+ it('opens VS Code on macOS without depending on the code CLI', async () => {
+ await openInEditor('/tmp/my config/settings.yaml', { editor: 'vscode', command: '' })
+ expect(execFile).toHaveBeenCalledWith('/usr/bin/open', ['-a', 'Visual Studio Code', '/tmp/my config/settings.yaml'], { timeout: 10_000 }, expect.any(Function))
+ })
+
+ it('opens Cursor on macOS without depending on its CLI', async () => {
+ await openInEditor('/tmp/settings.yaml', { editor: 'cursor', command: '' })
+ expect(execFile).toHaveBeenCalledWith('/usr/bin/open', ['-a', 'Cursor', '/tmp/settings.yaml'], { timeout: 10_000 }, expect.any(Function))
+ })
+
+ it('passes custom application and file paths as literal arguments', async () => {
+ const path = '/tmp/settings $(touch injected).yaml'
+ await openInEditor(path, { editor: 'custom', command: '/Applications/My Editor.app' })
+ expect(execFile).toHaveBeenCalledWith('/usr/bin/open', ['-a', '/Applications/My Editor.app', path], { timeout: 10_000 }, expect.any(Function))
+ })
+
+ it('propagates a failed macOS open command', async () => {
+ vi.mocked(execFile).mockImplementationOnce((_command: any, _args: any, _options: any, callback: any): any => callback(new Error('Unable to find application')))
+ await expect(openInEditor('/tmp/settings.yaml', { editor: 'vscode', command: '' })).rejects.toThrow('Unable to find application')
+ })
+
+ it('finds a Windows user installation without launching a cmd shim', async () => {
+ runtime.platform = 'win32'
+ runtime.env = { LOCALAPPDATA: 'C:\\Users\\Test User\\AppData\\Local' }
+ const exe = 'C:\\Users\\Test User\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe'
+ vi.mocked(existsSync).mockImplementation(path => path === exe)
+ await openInEditor('C:\\My Config\\settings.yaml', { editor: 'vscode', command: '' })
+ expect(spawnDetached).toHaveBeenCalledWith(exe, ['C:\\My Config\\settings.yaml'])
+ })
+
+ it('finds a portable Windows installation from its bin entry in PATH', async () => {
+ runtime.platform = 'win32'
+ runtime.env = { PATH: 'D:\\Tools\\VS Code\\bin' }
+ vi.mocked(existsSync).mockImplementation(path => path === 'D:\\Tools\\VS Code\\Code.exe')
+ await openInEditor('C:\\settings.yaml', { editor: 'vscode', command: '' })
+ expect(spawnDetached).toHaveBeenCalledWith('D:\\Tools\\VS Code\\Code.exe', ['C:\\settings.yaml'])
+ })
+
+ it('finds a Windows Cursor user installation', async () => {
+ runtime.platform = 'win32'
+ runtime.env = { LOCALAPPDATA: 'C:\\Users\\Test User\\AppData\\Local' }
+ const exe = 'C:\\Users\\Test User\\AppData\\Local\\Programs\\Cursor\\Cursor.exe'
+ vi.mocked(existsSync).mockImplementation(path => path === exe)
+ await openInEditor('C:\\My Config\\settings.yaml', { editor: 'cursor', command: '' })
+ expect(spawnDetached).toHaveBeenCalledWith(exe, ['C:\\My Config\\settings.yaml'])
+ })
+
+ it('launches the code executable on Linux', async () => {
+ runtime.platform = 'linux'
+ await openInEditor('/tmp/settings.yaml', { editor: 'vscode', command: '' })
+ expect(spawnDetached).toHaveBeenCalledWith('code', ['/tmp/settings.yaml'])
+ })
+
+ it('launches the cursor executable on Linux', async () => {
+ runtime.platform = 'linux'
+ await openInEditor('/tmp/settings.yaml', { editor: 'cursor', command: '' })
+ expect(spawnDetached).toHaveBeenCalledWith('cursor', ['/tmp/settings.yaml'])
+ })
+
+ it('launches a custom executable without shell evaluation', async () => {
+ runtime.platform = 'linux'
+ await openInEditor('/tmp/settings.yaml', { editor: 'custom', command: '/opt/My Editor/editor' })
+ expect(spawnDetached).toHaveBeenCalledWith('/opt/My Editor/editor', ['/tmp/settings.yaml'])
+ })
+})
diff --git a/packages/dsh-tauri-ui/src/host/service/config-file.utils.ts b/packages/dsh-tauri-ui/src/host/service/config-file.utils.ts
new file mode 100644
index 00000000..c420ae0c
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/host/service/config-file.utils.ts
@@ -0,0 +1,50 @@
+import type { EditorPreference } from '../../shared/editor.types'
+import { execFile } from 'node:child_process'
+import { existsSync } from 'node:fs'
+import { homedir } from 'node:os'
+import { isAbsolute, join, win32 } from 'node:path'
+import process from 'node:process'
+import { promisify } from 'node:util'
+import { openUrl, spawnDetached } from 'dsh-tauri'
+
+const run = promisify(execFile)
+
+export async function openInEditor(path: string, preference: EditorPreference): Promise<void> {
+ if (preference.editor === 'system') {
+ await openUrl(path)
+ return
+ }
+ let command = preference.command
+ if (preference.editor === 'vscode' || preference.editor === 'cursor') {
+ if (process.platform === 'darwin')
+ command = preference.editor === 'vscode' ? 'Visual Studio Code' : 'Cursor'
+ else if (process.platform === 'win32')
+ command = resolveWindowsEditor(preference.editor)
+ else
+ command = preference.editor === 'vscode' ? 'code' : 'cursor'
+ }
+ if (command.startsWith('~/'))
+ command = join(homedir(), command.slice(2))
+ if (process.platform === 'darwin' && (command.endsWith('.app') || !isAbsolute(command))) {
+ await run('/usr/bin/open', ['-a', command, path], { timeout: 10_000 })
+ return
+ }
+ await spawnDetached(command, [path])
+}
+
+function resolveWindowsEditor(editor: 'vscode' | 'cursor'): string {
+ const directoryName = editor === 'vscode' ? 'Microsoft VS Code' : 'Cursor'
+ const executable = editor === 'vscode' ? 'Code.exe' : 'Cursor.exe'
+ const candidates: string[] = []
+ if (process.env.LOCALAPPDATA)
+ candidates.push(win32.join(process.env.LOCALAPPDATA, 'Programs', directoryName, executable))
+ for (const root of [process.env.ProgramFiles, process.env['ProgramFiles(x86)']]) {
+ if (root)
+ candidates.push(win32.join(root, directoryName, executable))
+ }
+ for (const directory of (process.env.PATH ?? '').split(';').filter(Boolean)) {
+ candidates.push(win32.join(directory, executable))
+ candidates.push(win32.resolve(directory, '..', executable))
+ }
+ return candidates.find(candidate => existsSync(candidate)) ?? executable
+}
diff --git a/packages/dsh-tauri-ui/src/host/service/endpoint-models.ts b/packages/dsh-tauri-ui/src/host/service/endpoint-models.ts
new file mode 100644
index 00000000..81ead080
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/host/service/endpoint-models.ts
@@ -0,0 +1,86 @@
+import type { EndpointModelCard } from '../routes/index.types'
+import { defineService } from 'dsh-tauri'
+import { getCurrentHostInstance } from '../config/runtime'
+import {
+ apiKeyRefOf,
+ endpointOf,
+ getPath,
+ modelsListingUrl,
+ normalizeEndpointModels,
+ parseProfilePath,
+} from './endpoint-models.utils'
+
+export interface EndpointModelsInput {
+ ns: string
+ profilePath?: string
+ baseURL?: string
+ apiKey?: string
+}
+
+export type EndpointModelsResult
+ = | { ok: true, url: string, models: EndpointModelCard[] }
+ | { ok: false, error: string }
+
+const FETCH_TIMEOUT_MS = 15_000
+
+interface SettingsService {
+ get: (ns: string) => unknown
+}
+
+interface CredentialsService {
+ resolve: (ref: string) => Promise<{ value?: string } | undefined>
+}
+
+async function resolveApiKey(ref: string | undefined, typed: string | undefined): Promise<string | undefined> {
+ const trimmed = typed?.trim()
+ if (trimmed !== undefined && trimmed.length > 0)
+ return trimmed
+ if (ref === undefined)
+ return undefined
+ try {
+ const credentials = getCurrentHostInstance().get('credentials') as CredentialsService | undefined
+ if (credentials === undefined)
+ return undefined
+ const hit = await credentials.resolve(ref)
+ return typeof hit?.value === 'string' && hit.value.length > 0 ? hit.value : undefined
+ }
+ catch {
+ return undefined
+ }
+}
+
+export const endpointModels = defineService({
+ async list(input: EndpointModelsInput): Promise<EndpointModelsResult> {
+ const settings = getCurrentHostInstance().get('settings') as SettingsService | undefined
+ const section = settings?.get(input.ns)
+ const path = parseProfilePath(input.profilePath)
+ const profile = path.length === 0 ? section : getPath(section, path)
+ const baseURL = endpointOf(profile, input.baseURL)
+ if (baseURL === undefined) {
+ return { ok: false, error: `settings namespace "${input.ns}" names no endpoint to read` }
+ }
+ const url = modelsListingUrl(baseURL)
+ const apiKey = await resolveApiKey(apiKeyRefOf(profile), input.apiKey)
+ try {
+ const response = await fetch(url, {
+ method: 'GET',
+ headers: {
+ accept: 'application/json',
+ ...apiKey === undefined ? {} : { authorization: `Bearer ${apiKey}` },
+ },
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
+ })
+ if (!response.ok) {
+ const hint = response.status === 401 || response.status === 403 ? '; check the API key' : ''
+ return { ok: false, error: `${url} answered ${response.status}${hint}` }
+ }
+ const models = normalizeEndpointModels(await response.json())
+ if (models === undefined)
+ return { ok: false, error: `${url} model listing has no "data" array` }
+ return { ok: true, url, models }
+ }
+ catch (error) {
+ return { ok: false, error: `could not reach ${url}: ${error instanceof Error ? error.message : String(error)}` }
+ }
+ },
+})
diff --git a/packages/dsh-tauri-ui/src/host/service/endpoint-models.utils.test.ts b/packages/dsh-tauri-ui/src/host/service/endpoint-models.utils.test.ts
new file mode 100644
index 00000000..cc2415f5
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/host/service/endpoint-models.utils.test.ts
@@ -0,0 +1,94 @@
+import { describe, expect, it } from 'vitest'
+import {
+ apiKeyRefOf,
+ endpointOf,
+ getPath,
+ modelsListingUrl,
+ normalizeEndpointModel,
+ normalizeEndpointModels,
+ parseProfilePath,
+} from './endpoint-models.utils'
+
+describe('normalizeEndpointModel', () => {
+ it('reads the aliases OpenAI-compatible endpoints publish', () => {
+ expect(normalizeEndpointModel({ id: 'm', context_length: 131072, max_output_tokens: 8192 }))
+ .toEqual({ id: 'm', contextWindow: 131072, maxTokens: 8192 })
+ expect(normalizeEndpointModel({ id: 'm', context_window: 32768, max_tokens: 4096 }))
+ .toEqual({ id: 'm', contextWindow: 32768, maxTokens: 4096 })
+ expect(normalizeEndpointModel({ id: 'm', max_model_len: 262144 }))
+ .toEqual({ id: 'm', contextWindow: 262144 })
+ })
+
+ it('reads the nested capacity objects', () => {
+ expect(normalizeEndpointModel({ id: 'm', limit: { context: 200000, output: 8192 } }))
+ .toEqual({ id: 'm', contextWindow: 200000, maxTokens: 8192 })
+ expect(normalizeEndpointModel({ id: 'm', top_provider: { max_completion_tokens: 1024 } }))
+ .toEqual({ id: 'm', maxTokens: 1024 })
+ })
+
+ it('prefers the first disclosed alias in order', () => {
+ expect(normalizeEndpointModel({ id: 'm', contextWindow: 1, context_window: 2 }))
+ .toEqual({ id: 'm', contextWindow: 1 })
+ })
+
+ it('leaves undisclosed capacity empty rather than guessing', () => {
+ expect(normalizeEndpointModel({ id: 'm', name: 'M' })).toEqual({ id: 'm', name: 'M' })
+ expect(normalizeEndpointModel({ id: 'm', context_window: 0, max_tokens: -1 })).toEqual({ id: 'm' })
+ })
+
+ it('rejects entries without a usable id', () => {
+ expect(normalizeEndpointModel({ id: ' ' })).toBeUndefined()
+ expect(normalizeEndpointModel('m')).toBeUndefined()
+ expect(normalizeEndpointModel(undefined)).toBeUndefined()
+ })
+})
+
+describe('normalizeEndpointModels', () => {
+ it('reads the data envelope and drops unusable rows', () => {
+ expect(normalizeEndpointModels({ data: [{ id: 'a' }, { name: 'no id' }, { id: 'b', max_tokens: 4 }] }))
+ .toEqual([{ id: 'a' }, { id: 'b', maxTokens: 4 }])
+ })
+
+ it('reports a listing without a data array as unknown', () => {
+ expect(normalizeEndpointModels({ error: 'nope' })).toBeUndefined()
+ expect(normalizeEndpointModels(undefined)).toBeUndefined()
+ })
+})
+
+describe('profile resolution', () => {
+ const section = { providers: { local: { baseURL: 'http://127.0.0.1:8000/v1', apiKeyEnv: 'LOCAL_API_KEY' } } }
+
+ it('reads a nested profile by path', () => {
+ expect(getPath(section, ['providers', 'local'])).toEqual(section.providers.local)
+ })
+
+ it('returns undefined when any segment is missing', () => {
+ expect(getPath(section, ['providers', 'absent'])).toBeUndefined()
+ expect(getPath(undefined, ['providers'])).toBeUndefined()
+ })
+
+ it('parses the query spelling of a profile path', () => {
+ expect(parseProfilePath('["providers","local"]')).toEqual(['providers', 'local'])
+ expect(parseProfilePath('[]')).toEqual([])
+ expect(parseProfilePath(undefined)).toEqual([])
+ expect(parseProfilePath('{"not":"an array"}')).toEqual([])
+ expect(parseProfilePath('[')).toEqual([])
+ })
+
+ it('prefers the base URL the form shows over the stored one', () => {
+ expect(endpointOf(section.providers.local, ' http://localhost:9000/v1 ')).toBe('http://localhost:9000/v1')
+ expect(endpointOf(section.providers.local, ' ')).toBe('http://127.0.0.1:8000/v1')
+ expect(endpointOf(undefined, undefined)).toBeUndefined()
+ })
+
+ it('reads the credential reference the profile names', () => {
+ expect(apiKeyRefOf(section.providers.local)).toBe('LOCAL_API_KEY')
+ expect(apiKeyRefOf({ apiKeyEnv: ' ' })).toBeUndefined()
+ expect(apiKeyRefOf(undefined)).toBeUndefined()
+ })
+
+ it('appends the listing segment without doubling slashes', () => {
+ expect(modelsListingUrl('http://127.0.0.1:8000/v1/')).toBe('http://127.0.0.1:8000/v1/models')
+ expect(modelsListingUrl('http://127.0.0.1:8000/v1')).toBe('http://127.0.0.1:8000/v1/models')
+ })
+})
diff --git a/packages/dsh-tauri-ui/src/host/service/endpoint-models.utils.ts b/packages/dsh-tauri-ui/src/host/service/endpoint-models.utils.ts
new file mode 100644
index 00000000..ce2779cf
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/host/service/endpoint-models.utils.ts
@@ -0,0 +1,110 @@
+import type { EndpointModelCard } from '../routes/index.types'
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
+}
+
+function positiveInteger(...values: unknown[]): number | undefined {
+ for (const value of values) {
+ if (typeof value === 'number' && Number.isInteger(value) && value > 0)
+ return value
+ }
+ return undefined
+}
+
+function nonEmptyText(...values: unknown[]): string | undefined {
+ for (const value of values) {
+ if (typeof value === 'string' && value.trim().length > 0)
+ return value
+ }
+ return undefined
+}
+
+function nested(source: Record<string, unknown> | undefined, key: string): unknown {
+ return isRecord(source) ? source[key] : undefined
+}
+
+export function normalizeEndpointModel(value: unknown): EndpointModelCard | undefined {
+ if (!isRecord(value))
+ return undefined
+ const id = nonEmptyText(value.id)
+ if (id === undefined)
+ return undefined
+ const limit = isRecord(value.limit) ? value.limit : undefined
+ const topProvider = isRecord(value.top_provider) ? value.top_provider : undefined
+ const contextWindow = positiveInteger(
+ value.contextWindow,
+ value.context_window,
+ value.context_length,
+ value.max_input_tokens,
+ value.max_model_len,
+ nested(limit, 'context'),
+ )
+ const maxTokens = positiveInteger(
+ value.maxOutputTokens,
+ value.max_output_tokens,
+ value.maxTokens,
+ value.max_tokens,
+ value.max_output_length,
+ nested(limit, 'output'),
+ nested(topProvider, 'max_completion_tokens'),
+ )
+ const name = nonEmptyText(value.name)
+ return {
+ id,
+ ...name === undefined ? {} : { name },
+ ...contextWindow === undefined ? {} : { contextWindow },
+ ...maxTokens === undefined ? {} : { maxTokens },
+ }
+}
+
+export function normalizeEndpointModels(payload: unknown): EndpointModelCard[] | undefined {
+ if (!isRecord(payload) || !Array.isArray(payload.data))
+ return undefined
+ const cards: EndpointModelCard[] = []
+ for (const entry of payload.data) {
+ const card = normalizeEndpointModel(entry)
+ if (card !== undefined)
+ cards.push(card)
+ }
+ return cards
+}
+
+export function getPath(source: unknown, path: readonly string[]): unknown {
+ let current: unknown = source
+ for (const segment of path) {
+ if (!isRecord(current))
+ return undefined
+ current = current[segment]
+ }
+ return current
+}
+
+export function parseProfilePath(raw: string | undefined): string[] {
+ if (raw === undefined || raw.trim().length === 0)
+ return []
+ try {
+ const parsed: unknown = JSON.parse(raw)
+ if (!Array.isArray(parsed))
+ return []
+ return parsed.filter((segment): segment is string => typeof segment === 'string' && segment.length > 0)
+ }
+ catch {
+ return []
+ }
+}
+
+export function apiKeyRefOf(profile: unknown): string | undefined {
+ return nonEmptyText(isRecord(profile) ? profile.apiKeyEnv : undefined)
+}
+
+export function endpointOf(profile: unknown, override: string | undefined): string | undefined {
+ const trimmedOverride = override?.trim()
+ if (trimmedOverride !== undefined && trimmedOverride.length > 0)
+ return trimmedOverride
+ return nonEmptyText(isRecord(profile) ? profile.baseURL : undefined)
+}
+
+export function modelsListingUrl(baseURL: string): string {
+ return `${baseURL.replace(/\/+$/, '')}/models`
+}
diff --git a/packages/dsh-tauri-ui/src/host/service/model-presets.test.ts b/packages/dsh-tauri-ui/src/host/service/model-presets.test.ts
new file mode 100644
index 00000000..f52875d4
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/host/service/model-presets.test.ts
@@ -0,0 +1,128 @@
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
+import process from 'node:process'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { PRESET_SOURCE_URL } from '../../shared/model-presets'
+
+const UPSTREAM = {
+ 'openai/gpt-4o': { mode: 'chat', supports_vision: true, max_input_tokens: 128000 },
+ 'openai/text-embedding-3-small': { mode: 'embedding', max_input_tokens: 8191 },
+}
+
+const CACHE_DIR = 'dsh-tauri-ui'
+
+function jsonResponse(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })
+}
+
+async function loadService(): Promise<(typeof import('./model-presets'))['modelPresets']> {
+ vi.resetModules()
+ return (await import('./model-presets')).modelPresets
+}
+
+describe('modelPresets.resolve', () => {
+ let home: string
+
+ beforeEach(() => {
+ home = mkdtempSync(join(tmpdir(), 'dsh-model-presets-'))
+ process.env.DSH_HOME = home
+ })
+
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ delete process.env.DSH_HOME
+ rmSync(home, { recursive: true, force: true })
+ })
+
+ it('downloads once, then serves the next call from memory', async () => {
+ const fetchMock = vi.fn(async () => jsonResponse(UPSTREAM))
+ vi.stubGlobal('fetch', fetchMock)
+ const modelPresets = await loadService()
+ const first = await modelPresets.resolve()
+ if (!first.ok)
+ throw new Error(first.error)
+ expect(first.stale).toBe(false)
+ expect(first.source).toBe(PRESET_SOURCE_URL)
+ expect(first.presets).toEqual({ 'gpt-4o': [1, 0, 128000, 0] })
+ const cached = JSON.parse(readFileSync(join(home, CACHE_DIR, 'model-presets.json'), 'utf8'))
+ expect(cached.presets).toEqual(first.presets)
+ const second = await modelPresets.resolve()
+ expect(second.ok).toBe(true)
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ })
+
+ it('serves a fresh disk cache without touching the network', async () => {
+ const path = join(home, CACHE_DIR, 'model-presets.json')
+ mkdirSync(dirname(path), { recursive: true })
+ writeFileSync(path, JSON.stringify({
+ source: 'https://example.test/cost-map.json',
+ fetchedAt: new Date().toISOString(),
+ presets: { 'gpt-4o': [1, 0, 128000, 0] },
+ }))
+ const fetchMock = vi.fn(async () => jsonResponse(UPSTREAM))
+ vi.stubGlobal('fetch', fetchMock)
+ const modelPresets = await loadService()
+ const result = await modelPresets.resolve()
+ if (!result.ok)
+ throw new Error(result.error)
+ expect(result.source).toBe('https://example.test/cost-map.json')
+ expect(result.presets).toEqual({ 'gpt-4o': [1, 0, 128000, 0] })
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
+
+ it('refreshes an expired cache and ignores the cache when forced', async () => {
+ const path = join(home, CACHE_DIR, 'model-presets.json')
+ mkdirSync(dirname(path), { recursive: true })
+ writeFileSync(path, JSON.stringify({
+ source: 'stale',
+ fetchedAt: new Date(Date.now() - 48 * 60 * 60 * 1000).toISOString(),
+ presets: { 'gpt-4o': [0, 0, 1, 0] },
+ }))
+ const fetchMock = vi.fn(async () => jsonResponse(UPSTREAM))
+ vi.stubGlobal('fetch', fetchMock)
+ const modelPresets = await loadService()
+ const result = await modelPresets.resolve()
+ if (!result.ok)
+ throw new Error(result.error)
+ expect(result.stale).toBe(false)
+ expect(result.presets).toEqual({ 'gpt-4o': [1, 0, 128000, 0] })
+ await modelPresets.resolve(true)
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ })
+
+ it('falls back to the expired cache when upstream is unreachable', async () => {
+ const path = join(home, CACHE_DIR, 'model-presets.json')
+ mkdirSync(dirname(path), { recursive: true })
+ writeFileSync(path, JSON.stringify({
+ source: 'stale',
+ fetchedAt: new Date(Date.now() - 48 * 60 * 60 * 1000).toISOString(),
+ presets: { 'gpt-4o': [0, 0, 1, 0] },
+ }))
+ vi.stubGlobal('fetch', vi.fn(() => Promise.reject(new Error('offline'))))
+ const modelPresets = await loadService()
+ const result = await modelPresets.resolve()
+ if (!result.ok)
+ throw new Error(result.error)
+ expect(result.stale).toBe(true)
+ expect(result.presets).toEqual({ 'gpt-4o': [0, 0, 1, 0] })
+ })
+
+ it('reports the upstream failure when there is nothing cached', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({}, 500)))
+ const modelPresets = await loadService()
+ const result = await modelPresets.resolve()
+ expect(result.ok).toBe(false)
+ if (result.ok)
+ throw new Error('expected a failure')
+ expect(result.error).toContain(PRESET_SOURCE_URL)
+ expect(result.error).toContain('500')
+ })
+
+ it('treats a dataset without chat rows as unusable', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ 'bge-m3': { mode: 'embedding', max_input_tokens: 8192 } })))
+ const modelPresets = await loadService()
+ const result = await modelPresets.resolve()
+ expect(result.ok).toBe(false)
+ })
+})
diff --git a/packages/dsh-tauri-ui/src/host/service/model-presets.ts b/packages/dsh-tauri-ui/src/host/service/model-presets.ts
new file mode 100644
index 00000000..5aaa66c9
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/host/service/model-presets.ts
@@ -0,0 +1,110 @@
+import type { PresetRow, PresetTable } from '../../shared/model-presets'
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
+import { dirname } from 'node:path'
+import { defineService } from 'dsh-tauri'
+import { buildPresetTable, PRESET_CACHE_TTL_MS, PRESET_SOURCE_URL } from '../../shared/model-presets'
+import { resolvePresetCachePath } from '../utils/paths'
+
+export interface PresetTablePayload {
+ source: string
+ fetchedAt: string
+ presets: PresetTable
+}
+
+export type PresetResolveResult
+ = | (PresetTablePayload & { ok: true, stale: boolean })
+ | { ok: false, error: string }
+
+const FETCH_TIMEOUT_MS = 20_000
+
+interface CachedPayload {
+ source: string
+ fetchedAt: string
+ presets: PresetTable
+}
+
+let memory: CachedPayload | undefined
+
+function isPresetRow(value: unknown): value is PresetRow {
+ return Array.isArray(value)
+ && value.length === 4
+ && value.every(fact => typeof fact === 'number' && Number.isFinite(fact))
+}
+
+function readPayload(input: unknown): CachedPayload | undefined {
+ if (input === null || typeof input !== 'object')
+ return undefined
+ const candidate = input as Partial<CachedPayload>
+ if (typeof candidate.source !== 'string' || typeof candidate.fetchedAt !== 'string')
+ return undefined
+ if (candidate.presets === null || typeof candidate.presets !== 'object')
+ return undefined
+ const presets: PresetTable = {}
+ for (const [key, row] of Object.entries(candidate.presets)) {
+ if (isPresetRow(row))
+ presets[key] = row
+ }
+ if (Object.keys(presets).length === 0)
+ return undefined
+ return { source: candidate.source, fetchedAt: candidate.fetchedAt, presets }
+}
+
+function readDiskPayload(): CachedPayload | undefined {
+ try {
+ return readPayload(JSON.parse(readFileSync(resolvePresetCachePath(), 'utf8')))
+ }
+ catch {
+ return undefined
+ }
+}
+
+function writeDiskPayload(payload: CachedPayload): void {
+ const path = resolvePresetCachePath()
+ try {
+ mkdirSync(dirname(path), { recursive: true })
+ writeFileSync(path, JSON.stringify(payload))
+ }
+ catch {
+ }
+}
+
+function isFresh(payload: CachedPayload): boolean {
+ const fetchedAt = Date.parse(payload.fetchedAt)
+ return Number.isFinite(fetchedAt) && Date.now() - fetchedAt < PRESET_CACHE_TTL_MS
+}
+
+async function download(): Promise<CachedPayload> {
+ const response = await fetch(PRESET_SOURCE_URL, {
+ method: 'GET',
+ headers: { accept: 'application/json' },
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
+ })
+ if (!response.ok)
+ throw new Error(`${PRESET_SOURCE_URL} answered ${response.status}`)
+ const presets = buildPresetTable(await response.json())
+ if (Object.keys(presets).length === 0)
+ throw new Error(`${PRESET_SOURCE_URL} carried no chat models`)
+ return { source: PRESET_SOURCE_URL, fetchedAt: new Date().toISOString(), presets }
+}
+
+export const modelPresets = defineService({
+ async resolve(force = false): Promise<PresetResolveResult> {
+ const cached = memory ?? readDiskPayload()
+ if (cached !== undefined)
+ memory = cached
+ if (!force && cached !== undefined && isFresh(cached))
+ return { ok: true, ...cached, stale: false }
+ try {
+ const fresh = await download()
+ memory = fresh
+ writeDiskPayload(fresh)
+ return { ok: true, ...fresh, stale: false }
+ }
+ catch (error) {
+ const message = error instanceof Error ? error.message : String(error)
+ if (cached !== undefined)
+ return { ok: true, ...cached, stale: true }
+ return { ok: false, error: message }
+ }
+ },
+})
diff --git a/packages/dsh-tauri-ui/src/host/utils/paths.test.ts b/packages/dsh-tauri-ui/src/host/utils/paths.test.ts
new file mode 100644
index 00000000..4d4fa764
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/host/utils/paths.test.ts
@@ -0,0 +1,29 @@
+import { homedir } from 'node:os'
+import { join, resolve } from 'node:path'
+import { describe, expect, it } from 'vitest'
+import { resolvePresetCachePath, resolveSettingsFilePath } from './paths'
+
+describe('resolveSettingsFilePath', () => {
+ it('uses a non-blank DSH_HOME', () => {
+ expect(resolveSettingsFilePath({ DSH_HOME: 'D:\\harness' } as NodeJS.ProcessEnv))
+ .toBe(resolve('D:\\harness', 'settings.yaml'))
+ })
+
+ it('falls back to ~/.dsh when DSH_HOME is unset or blank', () => {
+ const expected = join(homedir(), '.dsh', 'settings.yaml')
+ expect(resolveSettingsFilePath({} as NodeJS.ProcessEnv)).toBe(expected)
+ expect(resolveSettingsFilePath({ DSH_HOME: ' ' } as NodeJS.ProcessEnv)).toBe(expected)
+ })
+
+ it('expands a leading tilde', () => {
+ expect(resolveSettingsFilePath({ DSH_HOME: '~/custom' } as NodeJS.ProcessEnv))
+ .toBe(join(homedir(), 'custom', 'settings.yaml'))
+ })
+})
+
+describe('resolvePresetCachePath', () => {
+ it('keeps the cache under the plugin directory in DSH_HOME', () => {
+ expect(resolvePresetCachePath({ DSH_HOME: 'D:\\harness' } as NodeJS.ProcessEnv))
+ .toBe(resolve('D:\\harness', 'dsh-tauri-ui', 'model-presets.json'))
+ })
+})
diff --git a/packages/dsh-tauri-ui/src/host/utils/paths.ts b/packages/dsh-tauri-ui/src/host/utils/paths.ts
new file mode 100644
index 00000000..657454f5
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/host/utils/paths.ts
@@ -0,0 +1,30 @@
+import { homedir } from 'node:os'
+import { join, resolve } from 'node:path'
+import process from 'node:process'
+import { PLUGIN_ID, SETTINGS_FILE_NAME } from '../../shared/constants'
+
+const PRESET_CACHE_FILE_NAME = 'model-presets.json'
+
+function expandHome(path: string): string {
+ if (path === '~')
+ return homedir()
+ if (path.startsWith('~/') || path.startsWith('~\\'))
+ return join(homedir(), path.slice(2))
+ return path
+}
+
+function resolveDshHome(env: NodeJS.ProcessEnv): string {
+ const configured = env.DSH_HOME
+ const home = configured !== undefined && configured.trim().length > 0
+ ? expandHome(configured)
+ : join(homedir(), '.dsh')
+ return resolve(home)
+}
+
+export function resolveSettingsFilePath(env: NodeJS.ProcessEnv = process.env): string {
+ return join(resolveDshHome(env), SETTINGS_FILE_NAME)
+}
+
+export function resolvePresetCachePath(env: NodeJS.ProcessEnv = process.env): string {
+ return join(resolveDshHome(env), PLUGIN_ID, PRESET_CACHE_FILE_NAME)
+}
diff --git a/packages/dsh-tauri-ui/src/shared/constants.ts b/packages/dsh-tauri-ui/src/shared/constants.ts
index 2a971335..d1bf64e1 100644
--- a/packages/dsh-tauri-ui/src/shared/constants.ts
+++ b/packages/dsh-tauri-ui/src/shared/constants.ts
@@ -1 +1,3 @@
export const PLUGIN_ID = 'dsh-tauri-ui'
+
+export const SETTINGS_FILE_NAME = 'settings.yaml'
diff --git a/packages/dsh-tauri-ui/src/shared/editor.ts b/packages/dsh-tauri-ui/src/shared/editor.ts
new file mode 100644
index 00000000..7610ceb1
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/shared/editor.ts
@@ -0,0 +1,14 @@
+import type { EditorPreference } from './editor.types'
+
+export function parseEditorPreference(value: unknown): EditorPreference {
+ if (typeof value !== 'object' || value === null)
+ throw new Error('EDITOR_INVALID')
+ const { editor, command } = value as Partial<EditorPreference>
+ if (editor !== 'vscode' && editor !== 'cursor' && editor !== 'system' && editor !== 'custom')
+ throw new Error('EDITOR_INVALID')
+ if (typeof command !== 'string' || /[\r\n\0]/.test(command))
+ throw new Error('EDITOR_INVALID')
+ if (editor === 'custom' && !command.trim())
+ throw new Error('EDITOR_COMMAND_REQUIRED')
+ return { editor, command: command.trim() }
+}
diff --git a/packages/dsh-tauri-ui/src/shared/editor.types.ts b/packages/dsh-tauri-ui/src/shared/editor.types.ts
new file mode 100644
index 00000000..4e44380f
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/shared/editor.types.ts
@@ -0,0 +1,4 @@
+export interface EditorPreference {
+ editor: 'vscode' | 'cursor' | 'system' | 'custom'
+ command: string
+}
diff --git a/packages/dsh-tauri-ui/src/shared/model-presets.test.ts b/packages/dsh-tauri-ui/src/shared/model-presets.test.ts
new file mode 100644
index 00000000..13e469e8
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/shared/model-presets.test.ts
@@ -0,0 +1,63 @@
+import { describe, expect, it } from 'vitest'
+import { buildPresetTable } from './model-presets'
+
+const entry = (input: Record<string, unknown>): Record<string, unknown> => ({ mode: 'chat', ...input })
+
+describe('buildPresetTable', () => {
+ it('keeps only chat models and the four documented facts', () => {
+ const table = buildPresetTable({
+ 'gpt-4o': entry({ supports_vision: true, max_input_tokens: 128000, max_output_tokens: 16384 }),
+ 'bge-m3': { mode: 'embedding', max_input_tokens: 8192 },
+ 'dall-e-3': { mode: 'image_generation' },
+ })
+ expect(table).toEqual({ 'gpt-4o': [1, 0, 128000, 16384] })
+ })
+
+ it('drops entries that carry no fact at all', () => {
+ expect(buildPresetTable({ 'mystery-model': entry({}) })).toEqual({})
+ })
+
+ it('ignores non-positive or non-integer capacities', () => {
+ const table = buildPresetTable({
+ a: entry({ supports_vision: true, max_input_tokens: 0, max_output_tokens: -1 }),
+ b: entry({ supports_reasoning: true, max_input_tokens: 1.5, max_output_tokens: '8192' }),
+ })
+ expect(table).toEqual({ a: [1, 0, 0, 0], b: [0, 1, 0, 0] })
+ })
+
+ it('unions the same model across providers', () => {
+ const table = buildPresetTable({
+ 'openai/gpt-4o': entry({ supports_vision: true, max_input_tokens: 128000 }),
+ 'azure/gpt-4o': entry({ supports_reasoning: true, max_output_tokens: 16384 }),
+ 'openrouter/openai/gpt-4o': entry({ max_input_tokens: 200000 }),
+ })
+ expect(table).toEqual({ 'gpt-4o': [1, 1, 200000, 16384] })
+ })
+
+ it('keys rows by the last path segment, lower-cased', () => {
+ expect(buildPresetTable({ 'Bedrock/MoonshotAI.Kimi-K2': entry({ supports_reasoning: true }) }))
+ .toEqual({ 'moonshotai.kimi-k2': [0, 1, 0, 0] })
+ })
+
+ it('prunes dated variants whose facts a shorter prefix already states', () => {
+ const table = buildPresetTable({
+ 'gpt-4o': entry({ supports_vision: true, max_input_tokens: 128000 }),
+ 'gpt-4o-2024-08-06': entry({ supports_vision: true, max_input_tokens: 128000 }),
+ })
+ expect(Object.keys(table)).toEqual(['gpt-4o'])
+ })
+
+ it('keeps a variant that states something the shorter prefix does not', () => {
+ const table = buildPresetTable({
+ 'o3': entry({ supports_reasoning: true }),
+ 'o3-mini': entry({ supports_reasoning: true, max_output_tokens: 65536 }),
+ })
+ expect(Object.keys(table).sort()).toEqual(['o3', 'o3-mini'])
+ })
+
+ it('rejects a payload that is not an object map', () => {
+ expect(buildPresetTable(undefined)).toEqual({})
+ expect(buildPresetTable('nope')).toEqual({})
+ expect(buildPresetTable({ sample: null })).toEqual({})
+ })
+})
diff --git a/packages/dsh-tauri-ui/src/shared/model-presets.ts b/packages/dsh-tauri-ui/src/shared/model-presets.ts
new file mode 100644
index 00000000..e4efe294
--- /dev/null
+++ b/packages/dsh-tauri-ui/src/shared/model-presets.ts
@@ -0,0 +1,67 @@
+export type PresetRow = readonly [number, number, number, number]
+
+export type PresetTable = Record<string, PresetRow>
+
+export const PRESET_SOURCE_URL
+ = 'https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json'
+
+export const PRESET_CACHE_TTL_MS = 24 * 60 * 60 * 1000
+
+function positiveInteger(value: unknown): number {
+ return typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : 0
+}
+
+function factsOf(entry: Record<string, unknown>): PresetRow {
+ return [
+ entry.supports_vision === true ? 1 : 0,
+ entry.supports_reasoning === true ? 1 : 0,
+ positiveInteger(entry.max_input_tokens),
+ positiveInteger(entry.max_output_tokens),
+ ]
+}
+
+function bareKey(key: string): string {
+ const normalized = key.trim().toLowerCase()
+ const slash = normalized.lastIndexOf('/')
+ return slash < 0 ? normalized : normalized.slice(slash + 1)
+}
+
+function unionRow(current: PresetRow | undefined, row: PresetRow): PresetRow {
+ if (current === undefined)
+ return row
+ return [current[0] || row[0], current[1] || row[1], Math.max(current[2], row[2]), Math.max(current[3], row[3])]
+}
+
+export function buildPresetTable(payload: unknown): PresetTable {
+ const merged = new Map<string, PresetRow>()
+ if (payload === null || typeof payload !== 'object')
+ return {}
+ for (const [key, value] of Object.entries(payload as Record<string, unknown>)) {
+ if (value === null || typeof value !== 'object')
+ continue
+ const entry = value as Record<string, unknown>
+ if (entry.mode !== 'chat')
+ continue
+ const bare = bareKey(key)
+ if (bare.length === 0 || bare === 'sample_spec')
+ continue
+ const row = factsOf(entry)
+ if (row.every(fact => fact === 0))
+ continue
+ merged.set(bare, unionRow(merged.get(bare), row))
+ }
+ const pruned: PresetTable = {}
+ for (const key of [...merged.keys()].sort((left, right) => left.length - right.length)) {
+ const row = merged.get(key) as PresetRow
+ const segments = key.split('-')
+ let covered = false
+ for (let end = segments.length - 1; end > 0 && !covered; end--) {
+ const prefix = merged.get(segments.slice(0, end).join('-'))
+ if (prefix !== undefined && prefix.every((fact, index) => fact === row[index]))
+ covered = true
+ }
+ if (!covered)
+ pruned[key] = row
+ }
+ return pruned
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c8ae3be6..8b2a763a 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -138,6 +138,9 @@ catalogs:
'@deepseek-ai/dsh-user-approval':
specifier: 0.1.7-alpha.1
version: 0.1.7-alpha.1
+ '@deepseek-ai/dsh-util-values':
+ specifier: 0.1.7-alpha.1
+ version: 0.1.7-alpha.1
'@deepseek-ai/dsh-workspace':
specifier: 0.1.7-alpha.1
version: 0.1.7-alpha.1
@@ -689,6 +692,9 @@ importers:
'@deepseek-ai/dsh-client-ui-slots':
specifier: catalog:dsh
version: 0.1.7-alpha.1(@deepseek-ai/[email protected])
+ '@deepseek-ai/dsh-util-values':
+ specifier: catalog:dsh
+ version: 0.1.7-alpha.1(@deepseek-ai/[email protected])
'@types/node':
specifier: catalog:types
version: 22.20.1
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index a68e8011..108c1859 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -113,6 +113,7 @@ catalogs:
'@deepseek-ai/dsh-storage-domain': 0.1.7-alpha.1
'@deepseek-ai/dsh-tools': 0.1.7-alpha.1
'@deepseek-ai/dsh-user-approval': 0.1.7-alpha.1
+ '@deepseek-ai/dsh-util-values': 0.1.7-alpha.1
'@deepseek-ai/dsh-workspace': 0.1.7-alpha.1
lint:
'@antfu/eslint-config': ^9.3.0
diff --git a/test/e2e/plugins/dsh-tauri-model-config.e2e.ts b/test/e2e/plugins/dsh-tauri-model-config.e2e.ts
index 9847cf25..f368d8df 100644
--- a/test/e2e/plugins/dsh-tauri-model-config.e2e.ts
+++ b/test/e2e/plugins/dsh-tauri-model-config.e2e.ts
@@ -1,15 +1,17 @@
/**
- * 批次 10 · `dsh-tauri-model-config` 的宿主路由(L1/L2 契约见 `docs/specs/plugin.test.md`)。
+ * 批次 10 · `dsh-tauri-model-config` 的模型设置页 + `dsh-tauri-ui` 承载的自有宿主路由
+ * (L1/L2 契约见 `docs/specs/plugin.test.md`)。
*
- * 插件顶替官方模型设置页:宿主侧只有 5 条路由,本批覆盖其中 4 条的无会话分支——预设表结构、
- * 端点探测无 endpoint、打开配置文件、设置文件缺失时退回目录。`settings.yaml` 的真实解析与
- * `POST /presets?force=true` 的上游下载由 `packages/dsh-tauri-model-config/src/host/service/`
- * 下的 unit 用例覆盖,不在 L2 重复。
+ * 插件是官方 `ui-settings-models` 的原样 fork(宿主半区只有 `webserver/index-inject`
+ * 的页面全局注入,没有 HTTP 路由)。本仓库自有的 5 条路由随自动配置 / 打开配置文件
+ * 能力迁到 `dsh-tauri-ui`,因此宿主契约在这里按 `dsh-tauri-ui` 的 base 断言。
+ * `settings.yaml` 的真实解析与 `POST /presets?force=true` 的上游下载由
+ * `packages/dsh-tauri-ui/src/host/service/` 下的 unit 用例覆盖,不在 L2 重复。
*
* 断言对象是外部世界(HTTP 状态码、响应字节、scratch `DSH_HOME` 的文件状态、真实 DOM 结构),
* 不采信插件自报。
*
- * 宿主复用 globalSetup 的共享实例(已挂载 dsh-tauri-model-config),不另起进程。
+ * 宿主复用 globalSetup 的共享实例,不另起进程。
*/
import type { Browser } from 'playwright'
@@ -28,11 +30,11 @@ import {
waitForCredentialModal,
} from '../support/browser'
-const PRESETS_PATH = '/api/desktop/dsh-tauri-model-config/presets'
-const ENDPOINT_MODELS_PATH = '/api/desktop/dsh-tauri-model-config/endpoint/models'
-const CONFIG_OPEN_PATH = '/api/desktop/dsh-tauri-model-config/config/open'
+const PRESETS_PATH = '/api/desktop/dsh-tauri-ui/presets'
+const ENDPOINT_MODELS_PATH = '/api/desktop/dsh-tauri-ui/endpoint/models'
+const CONFIG_OPEN_PATH = '/api/desktop/dsh-tauri-ui/config/open'
-/** 设置文件名(`packages/dsh-tauri-model-config/src/shared/constants.ts:4`)。 */
+/** 设置文件名(`packages/dsh-tauri-ui/src/shared/constants.ts`)。 */
const SETTINGS_FILE = 'settings.yaml'
/** 成功响应必须**恰为**这六个字段——多一个都说明契约变了。 */
@@ -42,15 +44,16 @@ const PRESETS_FIELDS = ['ok', 'source', 'fetchedAt', 'stale', 'count', 'presets'
const SECRET_FIELDS = ['apiKey', 'api_key', 'key', 'token'] as const
/**
- * 模型页的结构锚点:CSS Module 运行期类名保留原语义
- * (`packages/dsh-tauri-model-config/src/client/models/styles.ts:69,79,82,14`)。
+ * 模型页的结构锚点:cssr 运行期类名保留官方语义
+ * (`packages/dsh-tauri-model-config/src/client/models/styles.ts`)。
+ * 官方模型页没有标题行类名,标题是 `<h2 class="…title">`。
*/
-const MODELS_TITLE_ROW = '[class*="titleRow"]'
+const MODELS_TITLE = '[class*="title"]'
const MODELS_PROVIDER_CARD = '[class*="rowCard"],[class*="setupCard"]'
const MODELS_ADD_ACTIONS = '[class*="addActions"]'
-/** 空态下页脚操作区的按钮文案(`models/locales.ts:151,212`),不含任何宽泛词。 */
-const MODELS_ADD_LABELS = ['添加提供方', '添加自定义提供方'] as const
+/** 空态下页脚操作区的按钮文案(官方 0.1.7 文案),不含任何宽泛词。 */
+const MODELS_ADD_LABELS = ['添加模型提供商', '自定义模型 API'] as const
interface PresetsBody {
ok?: boolean
@@ -89,9 +92,9 @@ function secretFieldsIn(body: unknown): string[] {
describe('宿主路由:预设表', () => {
it('验证预设端点返回六个字段且 count 与 presets 长度一致', async () => {
// 预设表来自公网上游:不种缓存就会在离线机器上退化成 502(实测),断言随机器漂移。
- // 这里按被测实现自己的缓存格式(`$DSH_HOME/dsh-tauri-model-config/model-presets.json`,
+ // 这里按被测实现自己的缓存格式(`$DSH_HOME/dsh-tauri-ui/model-presets.json`,
// 24h TTL 内命中即返回)种一份新鲜载荷,让「200 + 六字段契约」确定性可验、与外网解耦。
- const cachePath = join(inject('dshHome'), 'dsh-tauri-model-config', 'model-presets.json')
+ const cachePath = join(inject('dshHome'), 'dsh-tauri-ui', 'model-presets.json')
mkdirSync(dirname(cachePath), { recursive: true })
writeFileSync(cachePath, JSON.stringify({
source: 'https://e2e.invalid/presets.json',
@@ -253,23 +256,23 @@ describe('L2 客户端', () => {
await openSettings(app.page, app.frame, app.syntheticFallbacks)
await selectSettingsSection(app.page, app.frame, '模型', app.syntheticFallbacks)
- const state = await app.frame.evaluate(({ titleRow, providerCard, addActions }) => {
+ const state = await app.frame.evaluate(({ title, providerCard, addActions }) => {
const content = document.querySelector('[class*="content-inner"]')
const footer = content?.querySelector(addActions)
return {
- titleRows: content?.querySelectorAll(titleRow).length ?? 0,
+ titles: content?.querySelectorAll(title).length ?? 0,
providerCards: content?.querySelectorAll(providerCard).length ?? 0,
footerButtons: Array.from(footer?.querySelectorAll('button') ?? []).map(button => button.textContent?.trim() ?? ''),
buttons: content?.querySelectorAll('button').length ?? 0,
alerts: Array.from(content?.querySelectorAll('[role="alert"]') ?? []).map(alert => alert.textContent?.trim()),
navLabels: Array.from(document.querySelectorAll('nav[aria-label] button')).map(button => button.textContent?.trim()),
}
- }, { titleRow: MODELS_TITLE_ROW, providerCard: MODELS_PROVIDER_CARD, addActions: MODELS_ADD_ACTIONS })
+ }, { title: MODELS_TITLE, providerCard: MODELS_PROVIDER_CARD, addActions: MODELS_ADD_ACTIONS })
- expect(state.titleRows, '模型页必须渲染标题行(证明走的是正常分支而非加载失败分支)').toBeGreaterThan(0)
+ expect(state.titles, '模型页必须渲染标题行(证明走的是正常分支而非加载失败分支)').toBeGreaterThan(0)
expect(
state.providerCards > 0 || MODELS_ADD_LABELS.some(label => state.footerButtons.includes(label)),
- `模型页必须为提供商渲染卡片 ${MODELS_PROVIDER_CARD},或渲染带「添加提供方」按钮的明确空态`
+ `模型页必须为提供商渲染卡片 ${MODELS_PROVIDER_CARD},或渲染带「添加模型提供商」按钮的明确空态`
+ `(实际页脚按钮:${JSON.stringify(state.footerButtons)})`,
).toBe(true)
expect(state.buttons, '模型页必须渲染可交互的页脚操作区').toBeGreaterThan(0)
@@ -283,7 +286,7 @@ describe('L2 客户端', () => {
}
})
- it('[反向] 验证预设上游不可用时模型页仍可交互', async () => {
+ it('[反向] 验证模型页不依赖预设上游(预设只在显式触发时拉取)', async () => {
const app = await newDshPage(browser)
let stubbedCalls = 0
try {
@@ -310,7 +313,7 @@ describe('L2 客户端', () => {
}
})
- expect(stubbedCalls, '夹具必须真的拦到预设请求,否则这条断言是空转').toBeGreaterThan(0)
+ expect(stubbedCalls, '模型页不得在加载时拉取预设上游:预设只由「自动配置所有模型」显式触发(该能力已迁到 dsh-tauri-ui)').toBe(0)
expect(state.text, '预设上游不可用时页面其余部分仍必须渲染(不是整页崩溃)').not.toBe('')
expect(state.buttons, '失败时仍必须保留可交互入口').toBeGreaterThan(0)
expect(state.inputs, '失败时仍必须保留可编辑字段').toBeGreaterThan(0)