DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
chore: 删除 archiving 归档目录,并在插件客户端规范里加入组件资源化条款
hairyff74165f00e91
diff --git a/archiving/dsh-tauri-model-config/README.md b/archiving/dsh-tauri-model-config/README.mddeleted file mode 100644index d1ea7f64..00000000--- a/archiving/dsh-tauri-model-config/README.md+++ /dev/null@@ -1,130 +0,0 @@-# dsh-tauri-model-config--本仓库维护的内置扩展,并非 DeepSeek 官方插件:接管 DSH 的「模型」设置页,在官方页面的基础上补齐官方不支持的配置项(上下文、图片输入、思考模式),并让模型上限可以从提供方端点直接读取。--## 为什么是 fork--官方没有为模型配置页提供任何插槽,页内也没有可扩展点;在复杂表单上打 DOM 补丁会随官方改版直接失效。-因此本插件**完整 fork 官方模型配置页**,注册同一个 `settings.section/models` 声明,并在-`cordis.patch.yml` 里关掉官方入口 `ui-settings-models`——两者声明的槽位互斥,不能同时开启。--- 上游:`@deepseek-ai/dsh-client-ui-settings-models`(`deepseek-ai/deepseek-harness`,`packages/client/ui-settings-models`,tag `dsh-v0.1.5-rc.1`)-- 落点:`src/client/models/`(逐文件对应上游 `src/client/`,行为保持一致)-- 本地改动:`ModelListEditor` / `DeepSeekModelsEditor`(新增能力)、`ModelsSection`(打开配置文件)、`styles.ts`(样式覆盖)、`locales.ts`(新增文案键)-- 上游注释已按仓库规范精简;`styles.ts` 是 `ModelsSection.module.css` 等的哈希化产物,类名前缀与官方一致(`zGbnIq_*` 等)--同步上游时的步骤:以同一 tag 重新取源 → 覆盖 `src/client/models/` 中未被本地改动的文件 → 重放上述改动。--编辑器选择位于独立的 `src/client/components/config-editor.tsx`,模型页面只负责挂载入口;偏好存储和跨平台启动逻辑在本插件宿主端。当前仅服务模型配置文件,无需拆成独立插件或桌面全局能力。若上游提供统一编辑器接口或出现跨插件复用需求,再评估迁移;插件内隔离仍需配合模型页面 fork 的上游同步维护。--## 新增能力--| 位置 | 能力 |-| --- | --- |-| 面板标题右侧(`.zGbnIq_title`) | **文本编辑器**:下拉菜单默认跟随系统,可选择 VS Code、Cursor 或自定义编辑器;预设点选即保存,自定义路径确认后保存。**打开配置文件**:使用所选编辑器打开 `$DSH_HOME/settings.yaml`(`DSH_HOME` 未设置或为空白时为 `~/.dsh/settings.yaml`);文件尚未创建时改为打开它所在目录 |-| 单个模型行(`.zGbnIq_modelRow`) | **获取配置**:仅在该条目只有 `id`/`name`/`description` 时出现,按 `id` 从提供方端点读取该模型的上下文与输出上限 |-| 模型目录标题(`.zGbnIq_modelCatalogHeading`) | 追加 `flex: 1`(按钮集中到右侧),并在右侧加入 **自动配置所有模型**;pi-ai 提供方与官方 DeepSeek 模型目录都有这个入口 |-| 单个模型高级区(`.zGbnIq_modelAdvanced`) | **图片输入** 开关 → `input` 声明;**思考模式** 开关 → `reasoningEfforts` 声明,打开后可按档位勾选;**关闭 Developer 角色** 开关 → `compat` 声明(仅路由显式声明 `openai-completions` 时出现) |--高级区里的开关统一由 `.zGbnIq_modelSwitchRow` 包裹(`display: flex` + `height: 32px` + 垂直居中),与相邻的 32px 文本输入框对齐。--高级区首行横跨整个栅格:左半边是两个容量输入(彼此等宽,整组按内容宽度),右半边是三个开关(开关组吃掉剩余宽度)——开关按内容宽度排布、不做拉伸,容器带 4px 左外边距,行内与开关组内的间距都是 6px;档位勾选仍独占下一行。高级区自身去掉上游那 4px 左右内边距,首行因此与上面的模型行同宽、同起止。--VS Code 和 Cursor 菜单图标随插件内嵌,以 CSS background / mask 显示,无运行时外部请求。图形分别来自 [VS Code 官方品牌资源](https://code.visualstudio.com/brand) 和 [Cursor 官方品牌资源](https://cursor.com/brand)。--## 配置从哪里来--三条通道,先直连再回退(前两条与参考实现 `dsh-llm-capabilities` 的顺序一致):--1. **宿主直连** `GET /endpoint/models`:宿主按 `settings` 服务里的 profile 解析端点与凭据,请求- `{baseURL}/models` 并归一化容量。官方发现通道会把清单收窄,容量字段只有端点原始清单里才有。-2. **官方发现通道** `remote.llm.discoverModels(settingsNs, probe)`:覆盖端点地址不在用户设置里的提供方- (例如内置 DeepSeek 官方路由,它的地址只有适配器自己知道)。-3. **模型能力表** `GET /presets`:端点清单只说容量,不说模态与档位,图片与思考能力来自 LiteLLM 的- 模型价目/容量表(`model_prices_and_context_window.json`,MIT,与 <https://models.litellm.ai/> 同源)。- 表**不进仓库**:宿主在第一次需要时下载,压成 `模型 id → [支持图片, 支持思考, 最大输入, 最大输出]`- 后缓存在 `$DSH_HOME/dsh-tauri-model-config/model-presets.json`,一天内直接用缓存;上游不可达时先用- 过期缓存,完全没有缓存时退回家族规则(`claude` / `gemini` / `grok-N` / `-vl` / `-vision` / `-omni` /- `glm-Nv` / `glm-4.5+` / `seed-1.6+` / `-thinking` / `r1` / `qwq` / `minimax-m1|m2` / `qwen3` / `o1-o9`)。-- 为什么不走 LiteLLM 代理的公开接口(`GET /public/litellm_model_cost_map`):那是 demo 代理,- 固定在自己那份 LiteLLM 版本上(实测 1.82.6),表比主干旧一截(1020 vs 1424 条 chat 模型),- 新模型会缺席;该接口也只提供全量,`/models/{model_id}` 之类还需要密钥、且只回答「这个代理自己- 部署了哪些模型」(公开实例上任何厂商 id 都是 404)。--请求事实全部来自表单当前显示的值(`provider` / `baseURL` / `api`,以及已输入未保存的 `apiKey`),-插件不认识任何具体部署;凭据只在宿主侧解析,响应里从不回显,也不进 URL。--并入草稿时的优先级:--- 容量以端点披露为准;端点什么都没说时用能力表的值,已有值永不被能力表覆盖。-- 图片与思考先看能力表,表没给出「能」的结论时由家族规则按命名补一条(只做加法,不做减法:- 把模型误判成只能读文字会让用户发不出图片,代价比多勾一个开关大)。-- 能力表的 `0` 是「数据集没有给出这项事实」,不是「不支持」:没表态的模态与档位不写进条目,- 该字段保持「继承默认」。因此「自动配置所有模型」不会把部署真实具备、或用户已经声明的思考与- 图片能力改写成显式的 `reasoningEfforts: false` / `input: ['text']`——本地端点上的模型常常比- 数据集新,写死的否定声明会直接关掉它。-- **单行「获取配置」**:只补空缺字段,不覆盖已有值。-- **「自动配置所有模型」**:按按钮语义重新配置,端点披露的容量会覆盖行内旧值;端点没披露的字段保持不动。--两条路径都会给出「已写入 N 个 / M 个未被端点披露」的结果行。--## 宿主路由--| 方法 | 路径 | 作用 |-| --- | --- | --- |-| GET | `/api/desktop/dsh-tauri-model-config/endpoint/models` | 读取提供方端点的 `/models` 清单并归一化容量 |-| GET | `/api/desktop/dsh-tauri-model-config/presets` | 取模型能力表(`force=true` 忽略缓存有效期) |-| GET / PUT | `/api/desktop/dsh-tauri-model-config/config/editor` | 读取 / 保存文本编辑器偏好 |-| POST | `/api/desktop/dsh-tauri-model-config/config/open` | 用所选编辑器打开模型配置文件,未设置时跟随系统 |--已接入 `genapi.config.ts`,客户端 `apis/` 为生成产物。--## 思考模式--**思考模式** 开关打开时保留该行已有档位,没有则给默认的 `{ off: null, low: 'low', medium: 'medium', high: 'high' }`-(与官方 pi-ai 目录给自建路由的默认档位、参考实现 `dsh-llm-capabilities` 的 `DEFAULT_REASONING_EFFORTS` 一致);-打开后出现 `off` 到 `max` 的**档位勾选项**(`off, minimal, low, medium, high, xhigh, max`),-勾上即写入该档位、取消即移除;取消到空表时写 `false`(显式「不支持思考」),因为空表会被 schema 判为非法声明。--键是档位,值是分发给端点时使用的线值(只有 `off` 允许为空)。需要为某个模型改线值时,直接在设置文档里改这一项。--开关只表达两种**显式声明**:`false`(不支持)与档位对象(支持)。`reasoningEfforts` 缺席表示「继承默认」,-此时开关读为关,与图片开关同一口径。--### 关闭 Developer 角色--声明了档位不等于档位能到端点。pi-ai 默认把档位放进顶层的 `reasoning_effort`,并在模型有思考能力时-把系统提示的角色从 `system` 换成 `developer`;而 vLLM 这类 OpenAI 兼容端点从 `chat_template_kwargs`-读思考参数、也不认 `developer`,于是出现「档位选了没反应」与「整轮 400 `Unexpected message role.`」。--**关闭 Developer 角色** 开关把这类端点需要的三项事实一次写进该模型的 `compat`:--```yaml-compat:- supportsDeveloperRole: false- thinkingFormat: chat-template- chatTemplateKwargs:- reasoning_effort:- $var: thinking.effort-```--前两项分别解决角色与下发格式,第三项用 pi-ai 的请求态占位符把下拉框选中的档位动态填进参数,-不需要重述端点的 chat template。开关读为开的条件是 `thinkingFormat: chat-template` 与-`supportsDeveloperRole: false` 同时成立,因此只写了一半的手写条目在开关上仍读为关,打开时会补齐。-关闭只摘掉这三项,条目里其它 `compat` 键与 chat template 参数原样保留。--`compat` 在 pi-ai 里是逐协议校验的,`thinkingFormat` 与 `chatTemplateKwargs` 只有-`openai-completions` 收,写到 Responses / Anthropic 路由的模型上会让整段配置解析失败,所以这个开关-只在路由显式声明 `openai-completions` 时出现;目录路由(协议由内置目录决定,插件看不到)不提供。--## 已知约束--- 模型配置文件按 `$DSH_HOME`(非空白)→ `~/.dsh` 解析后取 `settings.yaml`,与官方 `resolveDshHome` 及桌面壳一致;如果 profile 的 `cordis.yml` 为 `settings-file` 配了自定义 `path`,这里无法感知。-- 编辑器设置仅作用于本插件模型页面的“打开配置文件”;偏好保存于 `$DSH_HOME/dsh-tauri-model-config/editor.json`,不修改系统文件关联。自定义编辑器在 macOS 上支持应用名称、`.app` 路径或可执行文件路径;Windows 使用 `.exe` 完整路径;Linux 支持可执行程序名称或路径。无需引号,不支持附加参数。编辑器启动失败会显示错误,不自动切换应用。-- 编辑器偏好文件内容无效时跟随系统默认,读取时保留原文件,可重新选择编辑器并保存;权限或其他读取错误仍会报错。-- 文件不存在时打开的是它所在的目录,而不是替用户创建一个空文档。-- 图片能力既不在官方发现通道的返回里,也没有跨厂商的端点字段:它来自模型能力表,表里没有的靠家族规则。两者都是社区口径的近似值,用户随时可以在高级区改;单行「获取配置」也不会覆盖手写值。-- 能力表需要一次网络请求(约 2.6 MB 的原始数据集,压成 72 KB 落盘,一天内不再请求)。离线且从未下载过时,只剩家族规则能补图片/思考,容量仍由端点清单提供。-- 档位只提供官方词表内的勾选,线值固定等于档位名;端点要求特殊线值时改设置文档即可。-- 「关闭 Developer 角色」写的是一组固定的 `compat`:参数名 `reasoning_effort`、下发格式 `chat-template`。端点要求别的参数名(例如 `enable_thinking`)或别的下发格式时,改设置文档即可;开关只表达它写入的这一组。diff --git a/archiving/dsh-tauri-model-config/cordis.patch.yml b/archiving/dsh-tauri-model-config/cordis.patch.ymldeleted file mode 100644index f21f25a3..00000000--- a/archiving/dsh-tauri-model-config/cordis.patch.yml+++ /dev/null@@ -1,9 +0,0 @@-# 官方「模型」设置页:本插件是它的完整 fork(新增「支持图片输入」开关、打开配置文件、-# 从提供方端点补全模型上限)。两者在 `settings.section/models` 上互斥,同开会在-# 加载期报槽位重复声明,因此必须关掉官方入口。-- id: ui-settings-models- disabled: true--- insert:- - id: dsh-tauri-model-config- name: dsh-tauri-model-configdiff --git a/archiving/dsh-tauri-model-config/package.json b/archiving/dsh-tauri-model-config/package.jsondeleted file mode 100644index 6ff90fb9..00000000--- a/archiving/dsh-tauri-model-config/package.json+++ /dev/null@@ -1,89 +0,0 @@-{- "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/archiving/dsh-tauri-model-config/src/client/apis/index.ts b/archiving/dsh-tauri-model-config/src/client/apis/index.tsdeleted file mode 100644index b3967fea..00000000--- a/archiving/dsh-tauri-model-config/src/client/apis/index.ts+++ /dev/null@@ -1,36 +0,0 @@-/*- * @title dsh-tauri-model-config- * @swagger 2.0- * @version 0.0.0- */--import type { FetchOptions } from "dsh-tauri/client";-import { ofetch } from "dsh-tauri/client";-import type * as Types from "./index.type";--export const baseURL = "/api/desktop/dsh-tauri-model-config";--/** @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 });-}diff --git a/archiving/dsh-tauri-model-config/src/client/apis/index.type.ts b/archiving/dsh-tauri-model-config/src/client/apis/index.type.tsdeleted file mode 100644index 2c815750..00000000--- a/archiving/dsh-tauri-model-config/src/client/apis/index.type.ts+++ /dev/null@@ -1,49 +0,0 @@-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/archiving/dsh-tauri-model-config/src/client/components/config-editor.cssr.ts b/archiving/dsh-tauri-model-config/src/client/components/config-editor.cssr.tsdeleted file mode 100644index 552a7612..00000000--- a/archiving/dsh-tauri-model-config/src/client/components/config-editor.cssr.ts+++ /dev/null@@ -1,28 +0,0 @@-import { cssr } from 'dsh-tauri-ui/client'--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-editor__trigger', {- gap: '5px',- whiteSpace: 'nowrap',- }),- c('.dshp-model-config-editor__icon', {- display: 'inline-block',- flex: 'none',- width: '16px',- height: '16px',- }),- c('.dshp-model-config-editor__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-editor__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/archiving/dsh-tauri-model-config/src/client/components/config-editor.tsx b/archiving/dsh-tauri-model-config/src/client/components/config-editor.tsxdeleted file mode 100644index 6be375e4..00000000--- a/archiving/dsh-tauri-model-config/src/client/components/config-editor.tsx+++ /dev/null@@ -1,150 +0,0 @@-import type { MenuEntry } from '@deepseek-ai/dsh-client-ui-primitives'-import type { EditorPreference } from '../../shared/editor.types'-import type { en } from '../models/locales'-import { Button, Menu, Modal } from '@deepseek-ai/dsh-client-ui-primitives'-import { ChevronDown, useMountStyle } from 'dsh-tauri-ui/client'-import { useState } from 'react'-import { If } from 'react-if-lite'-import { modelStyles as styles } from '../models/styles'-import { loadEditor, saveEditor } from '../service/editor'-import { withDetail } from '../service/model-config.utils'-import { configEditorStyle } from './config-editor.cssr'--export function ConfigEditor({ t }: { t: (key: keyof typeof en) => string }) {- useMountStyle(configEditorStyle, 'dshp-model-config-editor')- const [menuOpen, setMenuOpen] = useState(false)- const [customOpen, setCustomOpen] = useState(false)- const [preference, setPreference] = useState<EditorPreference>()- const [command, setCommand] = useState('')- const [busy, setBusy] = useState(false)- const [failure, setFailure] = useState<string>()- const items: MenuEntry[] = [- { id: 'system', label: t('editorSystem'), icon: <span className="dshp-model-config-editor__icon dshp-model-config-editor__icon--system" aria-hidden="true" /> },- { id: 'vscode', label: t('editorVSCode'), icon: <span className="dshp-model-config-editor__icon dshp-model-config-editor__icon--vscode" aria-hidden="true" /> },- { id: 'cursor', label: t('editorCursor'), icon: <span className="dshp-model-config-editor__icon dshp-model-config-editor__icon--cursor" aria-hidden="true" /> },- { id: 'separator', type: 'separator' },- { id: 'custom', label: t('editorCustom'), icon: <span className="dshp-model-config-editor__icon dshp-model-config-editor__icon--custom" aria-hidden="true" /> },- ]-- async function openMenu() {- if (busy)- return- if (menuOpen) {- setMenuOpen(false)- return- }- setBusy(true)- setFailure(undefined)- try {- setPreference(await loadEditor())- setMenuOpen(true)- }- catch (error) {- setFailure(withDetail(t('editorLoadFailed'), String(error)))- }- finally {- setBusy(false)- }- }-- function closeDialog() {- if (busy)- return- setCustomOpen(false)- setFailure(undefined)- }-- async function save(next: EditorPreference) {- if (busy)- return- setBusy(true)- setFailure(undefined)- const result = await saveEditor(next)- setBusy(false)- if (result.ok) {- setPreference(next)- setCustomOpen(false)- }- else {- setFailure(withDetail(t('editorSaveFailed'), result.error ?? ''))- }- }-- function selectEditor(editor: string) {- if (!preference || busy)- return- setMenuOpen(false)- if (editor === 'custom') {- setCommand(preference.command)- setCustomOpen(true)- }- else if (editor === 'vscode' || editor === 'cursor' || editor === 'system') {- void save({ ...preference, editor })- }- }-- return (- <>- <Menu- open={menuOpen}- align="end"- autoFocus- items={items}- selectedId={preference?.editor}- onSelect={selectEditor}- onClose={() => setMenuOpen(false)}- anchor={(- <button- type="button"- className={`${styles.linkButton} dshp-model-config-editor__trigger`}- onClick={() => { void openMenu() }}- disabled={busy}- aria-haspopup="menu"- aria-expanded={menuOpen}- aria-busy={busy}- >- {t('textEditor')}- <ChevronDown aria-hidden="true" />- </button>- )}- />- <Modal- open={customOpen || failure !== undefined}- onClose={closeDialog}- title={customOpen ? t('editorCustom') : t('textEditor')}- closeLabel={t('close')}- description={t('textEditorHint')}- className={styles.fetchDialog}- footer={(- <>- <Button variant="outline" disabled={busy} onClick={closeDialog}>{customOpen ? t('cancel') : t('close')}</Button>- <If cond={customOpen}>- <Button disabled={busy || !command.trim()} onClick={() => { void save({ editor: 'custom', command: command.trim() }) }}>- {t('apply')}- </Button>- </If>- </>- )}- >- <div className={styles.editor}>- <If cond={customOpen}>- <label className={styles.field}>- <span className={styles.fieldLabel}>{t('editorCommand')}</span>- <input- className={styles.input}- value={command}- disabled={busy}- placeholder={t('editorCommandPlaceholder')}- onChange={event => setCommand(event.target.value)}- />- <span className={styles.advancedHint}>{t('editorCommandHint')}</span>- </label>- </If>- <If cond={failure !== undefined}>- <p className={styles.error} role="alert">{failure}</p>- </If>- </div>- </Modal>- </>- )-}diff --git a/archiving/dsh-tauri-model-config/src/client/constants/index.ts b/archiving/dsh-tauri-model-config/src/client/constants/index.tsdeleted file mode 100644index 2b05d310..00000000--- a/archiving/dsh-tauri-model-config/src/client/constants/index.ts+++ /dev/null@@ -1,10 +0,0 @@-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.tsdeleted file mode 100644index b55aed34..00000000--- a/archiving/dsh-tauri-model-config/src/client/index.ts+++ /dev/null@@ -1,37 +0,0 @@-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.tsdeleted file mode 100644index 72df8342..00000000--- a/archiving/dsh-tauri-model-config/src/client/locales/index.ts+++ /dev/null@@ -1,6 +0,0 @@-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.tsxdeleted file mode 100644index cb0af9f9..00000000--- a/archiving/dsh-tauri-model-config/src/client/models/CustomProviderCard.tsx+++ /dev/null@@ -1,284 +0,0 @@-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.tsxdeleted file mode 100644index 5e9106b6..00000000--- a/archiving/dsh-tauri-model-config/src/client/models/DeepSeekModelsEditor.tsx+++ /dev/null@@ -1,319 +0,0 @@-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.tsxdeleted file mode 100644index 15973ce7..00000000--- a/archiving/dsh-tauri-model-config/src/client/models/DeepSeekOnboardingDialog.tsx+++ /dev/null@@ -1,111 +0,0 @@-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.tsxdeleted file mode 100644index ca8ddffd..00000000--- a/archiving/dsh-tauri-model-config/src/client/models/EditorFooter.tsx+++ /dev/null@@ -1,46 +0,0 @@-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.tsxdeleted file mode 100644index c8828262..00000000--- a/archiving/dsh-tauri-model-config/src/client/models/ModelListEditor.tsx+++ /dev/null@@ -1,596 +0,0 @@-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.tsxdeleted file mode 100644index 47f4ed47..00000000--- a/archiving/dsh-tauri-model-config/src/client/models/ModelsSection.tsx+++ /dev/null@@ -1,561 +0,0 @@-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.tsxdeleted file mode 100644index 893c5c2b..00000000--- a/archiving/dsh-tauri-model-config/src/client/models/OnboardingModal.tsx+++ /dev/null@@ -1,49 +0,0 @@-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.tsxdeleted file mode 100644index 45e39545..00000000--- a/archiving/dsh-tauri-model-config/src/client/models/ProviderEditor.tsx+++ /dev/null@@ -1,474 +0,0 @@-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.tsxdeleted file mode 100644index e89c4555..00000000--- a/archiving/dsh-tauri-model-config/src/client/models/WelcomeNotice.tsx+++ /dev/null@@ -1,73 +0,0 @@-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.tsdeleted file mode 100644index 5c959ae3..00000000--- a/archiving/dsh-tauri-model-config/src/client/models/apiKey.ts+++ /dev/null@@ -1,25 +0,0 @@-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.tsdeleted file mode 100644index 73831e11..00000000--- a/archiving/dsh-tauri-model-config/src/client/models/locales.ts+++ /dev/null@@ -1,271 +0,0 @@-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.tsdeleted file mode 100644index aafc30d3..00000000--- a/archiving/dsh-tauri-model-config/src/client/models/operations.ts+++ /dev/null@@ -1,69 +0,0 @@-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.tsdeleted file mode 100644index 8aeb4019..00000000--- a/archiving/dsh-tauri-model-config/src/client/models/schema-operations.ts+++ /dev/null@@ -1,20 +0,0 @@-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.tsdeleted file mode 100644index 721c4e29..00000000--- a/archiving/dsh-tauri-model-config/src/client/models/settings-forms.ts+++ /dev/null@@ -1,54 +0,0 @@-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.tsdeleted file mode 100644index 41d691ec..00000000--- a/archiving/dsh-tauri-model-config/src/client/models/slot-contract.ts+++ /dev/null@@ -1,25 +0,0 @@-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.tsdeleted file mode 100644index 2babb02a..00000000--- a/archiving/dsh-tauri-model-config/src/client/models/store.ts+++ /dev/null@@ -1,283 +0,0 @@-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.tsdeleted file mode 100644index 3ae825f3..00000000--- a/archiving/dsh-tauri-model-config/src/client/models/styles.ts+++ /dev/null@@ -1,104 +0,0 @@-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.tsdeleted file mode 100644index 3c2af7ac..00000000--- a/archiving/dsh-tauri-model-config/src/client/models/welcome-store.ts+++ /dev/null@@ -1,130 +0,0 @@-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.tsdeleted file mode 100644index dce77bbc..00000000--- a/archiving/dsh-tauri-model-config/src/client/register/models.ts+++ /dev/null@@ -1,103 +0,0 @@-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.tsdeleted file mode 100644index 4e61f84a..00000000--- a/archiving/dsh-tauri-model-config/src/client/register/styles.ts+++ /dev/null@@ -1,8 +0,0 @@-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/archiving/dsh-tauri-model-config/src/client/service/editor.ts b/archiving/dsh-tauri-model-config/src/client/service/editor.tsdeleted file mode 100644index 19eb0a9c..00000000--- a/archiving/dsh-tauri-model-config/src/client/service/editor.ts+++ /dev/null@@ -1,23 +0,0 @@-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/archiving/dsh-tauri-model-config/src/client/service/model-config.ts b/archiving/dsh-tauri-model-config/src/client/service/model-config.tsdeleted file mode 100644index 1336532a..00000000--- a/archiving/dsh-tauri-model-config/src/client/service/model-config.ts+++ /dev/null@@ -1,84 +0,0 @@-import type { ModelsOperations } from '../models/operations.ts'-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 }--/** 直接读提供方端点公布的清单;能带回官方通道裁掉的容量字段。 */-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) }- }-}--/**- * 读取端点公布的模型容量:先宿主直连原始清单,失败再退回官方发现通道。- *- * 两条通道各有覆盖不到的地方——自建端点的容量只在端点自己写下的原始字段里,而官方通道认识- * 端点地址不在用户设置里的提供方(例如内置的 DeepSeek 官方路由)。先直连再回退,与参考实现- * dsh-llm-capabilities 的顺序一致。- * @param probe - 表单当前显示的端点事实。- * @param operations - 官方发现通道。- * @returns 归一化条目,或两条通道都没成功时的失败文案。- */-export async function loadModelCapacities(- probe: EndpointProbe,- operations: ModelsOperations,-): Promise<ModelCapacityFetch> {- const direct = await fetchEndpointModels(probe)- if (direct.ok && direct.models.length > 0)- 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/archiving/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.tsdeleted file mode 100644index 12d216f9..00000000--- a/archiving/dsh-tauri-model-config/src/client/service/model-config.utils.test.ts+++ /dev/null@@ -1,342 +0,0 @@-import type { LlmDiscoveredModel } from '../types/remotes.ts'-import { beforeEach, describe, expect, it } from 'vitest'-import {- declaredThinkingLevels,- enableThinking,- hasModelConfig,- imageInputValue,- mergeModelCards,- modelConfigNotice,- supportsImageInput,- supportsTemplateThinking,- supportsThinking,- templateThinkingCompat,- THINKING_LEVELS,- thinkingEffortsOf,- toggleThinkingLevel,- 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('supportsImageInput', () => {- it('reads an explicit image declaration as on', () => {- expect(supportsImageInput({ id: 'm', input: ['text', 'image'] })).toBe(true)- })-- it('reads inheritance and a text-only declaration as off', () => {- expect(supportsImageInput({ id: 'm' })).toBe(false)- expect(supportsImageInput({ id: 'm', input: ['text'] })).toBe(false)- expect(supportsImageInput({ id: 'm', input: 'image' })).toBe(false)- })-- it('encodes both switch positions as explicit declarations', () => {- expect(imageInputValue(true)).toEqual(['text', 'image'])- expect(imageInputValue(false)).toEqual(['text'])- })-})--describe('supportsThinking', () => {- it('reads a graded declaration as on', () => {- expect(supportsThinking({ id: 'm', reasoningEfforts: { off: null, low: 'low' } })).toBe(true)- })-- it('reads an explicit refusal and inheritance as off', () => {- expect(supportsThinking({ id: 'm', reasoningEfforts: false })).toBe(false)- expect(supportsThinking({ id: 'm' })).toBe(false)- expect(supportsThinking({ id: 'm', reasoningEfforts: 'low' })).toBe(false)- expect(supportsThinking({ id: 'm', reasoningEfforts: ['low'] })).toBe(false)- })-- it('reads an off-only declaration as off', () => {- expect(supportsThinking({ id: 'm', reasoningEfforts: { off: null } })).toBe(false)- })-})--describe('thinking levels', () => {- it('offers the whole official vocabulary, off through max', () => {- expect([...THINKING_LEVELS]).toEqual(['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'])- })-- it('seeds a default graded set when enabling an unconfigured row', () => {- expect(enableThinking({ id: 'm' })).toEqual({ off: null, low: 'low', medium: 'medium', high: 'high' })- })-- it('replaces an off-only declaration, which offers nothing to turn on', () => {- expect(enableThinking({ id: 'm', reasoningEfforts: { off: null } }))- .toEqual({ off: null, low: 'low', medium: 'medium', high: 'high' })- })-- it('keeps the levels a row already declares', () => {- const declared = { off: null, minimal: 'minimal', max: 'max' }- expect(enableThinking({ id: 'm', reasoningEfforts: declared })).toBe(declared)- })-- it('reads the declared levels in vocabulary order for the checkboxes', () => {- expect(declaredThinkingLevels({ id: 'm', reasoningEfforts: { max: 'max', off: null } })).toEqual(['max', 'off'])- expect(declaredThinkingLevels({ id: 'm', reasoningEfforts: false })).toEqual([])- })-- it('adds a level with its wire value and drops it again', () => {- const added = toggleThinkingLevel({ off: null }, 'low', true)- expect(added).toEqual({ off: null, low: 'low' })- const removed = toggleThinkingLevel({ off: null, low: 'low' }, 'low', false)- expect(removed).toEqual({ off: null })- })-- it('leaves off without a wire value', () => {- expect(toggleThinkingLevel({}, 'off', true)).toEqual({ off: null })- })-- it('falls back to an explicit refusal when the last level is cleared', () => {- expect(toggleThinkingLevel({ low: 'low' }, 'low', false)).toBe(false)- })-- it('does not mutate the declaration it was handed', () => {- const current = { off: null }- toggleThinkingLevel(current, 'high', true)- expect(current).toEqual({ off: null })- })-- it('reads a foreign declaration as an empty map', () => {- expect(thinkingEffortsOf({ id: 'm', reasoningEfforts: ['low'] })).toEqual({})- expect(thinkingEffortsOf({ id: 'm', reasoningEfforts: null })).toEqual({})- })-})--describe('template thinking compat', () => {- it('reads the switch as on only when the effort travels through the chat template', () => {- expect(supportsTemplateThinking({ id: 'm' })).toBe(false)- expect(supportsTemplateThinking({ id: 'm', compat: { thinkingFormat: 'chat-template' } })).toBe(false)- expect(supportsTemplateThinking({- id: 'm',- compat: { thinkingFormat: 'chat-template', supportsDeveloperRole: false },- })).toBe(true)- expect(supportsTemplateThinking({ id: 'm', compat: 'chat-template' })).toBe(false)- })-- it('writes the three switches a vLLM-style endpoint needs', () => {- expect(templateThinkingCompat({ id: 'm' }, true)).toEqual({- supportsDeveloperRole: false,- thinkingFormat: 'chat-template',- chatTemplateKwargs: { reasoning_effort: { $var: 'thinking.effort' } },- })- })-- it('keeps the compat entries it does not own', () => {- const model = {- id: 'm',- compat: {- supportsStore: false,- chatTemplateKwargs: { enable_thinking: true },- chatTemplateArgs: {},- },- }- expect(templateThinkingCompat(model, true)).toEqual({- supportsStore: false,- chatTemplateArgs: {},- supportsDeveloperRole: false,- thinkingFormat: 'chat-template',- chatTemplateKwargs: { enable_thinking: true, reasoning_effort: { $var: 'thinking.effort' } },- })- })-- it('removes only the switches it wrote, dropping emptied containers', () => {- const written = {- id: 'm',- compat: {- supportsDeveloperRole: false,- thinkingFormat: 'chat-template',- chatTemplateKwargs: { reasoning_effort: { $var: 'thinking.effort' } },- },- }- expect(templateThinkingCompat(written, false)).toBeUndefined()- expect(templateThinkingCompat({ id: 'm', compat: { supportsStore: false } }, false))- .toEqual({ supportsStore: false })- })-- it('does not mutate the compat it was handed', () => {- const model = { id: 'm', compat: { chatTemplateKwargs: { enable_thinking: true } } }- templateThinkingCompat(model, true)- expect(model.compat).toEqual({ chatTemplateKwargs: { enable_thinking: 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/archiving/dsh-tauri-model-config/src/client/service/model-config.utils.ts b/archiving/dsh-tauri-model-config/src/client/service/model-config.utils.tsdeleted file mode 100644index 9acdf747..00000000--- a/archiving/dsh-tauri-model-config/src/client/service/model-config.utils.ts+++ /dev/null@@ -1,269 +0,0 @@-import type { DeepSeekModelDraft } from '../models/DeepSeekModelsEditor.tsx'-import type { LlmDiscoveredModel } from '../types/remotes.ts'-import { presetFor } from './model-presets.ts'--/** 一个模型条目除身份字段外还带有的配置字段。 */-const CONFIG_FIELDS = ['contextWindow', 'maxTokens', 'input', 'reasoningEfforts'] as const--/** 官方 pi-ai 档位词表;`off` 之外的每个档位都必须带上分发用的线值。 */-export const THINKING_LEVELS = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'] as const--/** 打开「思考模式」时的初始档位,与官方 pi-ai 目录给自建路由的默认档位一致。 */-export const DEFAULT_THINKING_EFFORTS: Readonly<Record<string, string | null>> = {- off: null,- low: 'low',- medium: 'medium',- high: 'high',-}--/**- * vLLM 这类 OpenAI 兼容端点读取思考档位的方式:参数走 chat template,而不是顶层的- * `reasoning_effort`。档位本身用 pi-ai 的请求态占位符动态填入,因此不必重述模板。- */-const TEMPLATE_THINKING_FORMAT = 'chat-template'-const TEMPLATE_THINKING_KWARG = 'reasoning_effort'-const TEMPLATE_THINKING_EFFORT_VAR = 'thinking.effort'--/** 任意值读成普通对象;缺席、数组与标量都读作空表。 */-function recordOf(value: unknown): Record<string, unknown> {- if (typeof value !== 'object' || value === null || Array.isArray(value))- return {}- return value as Record<string, unknown>-}--/** 该条目当前的 compat 声明;缺席或非对象读作空表。 */-function compatOf(model: DeepSeekModelDraft): Record<string, unknown> {- return recordOf(model.compat)-}--/**- * 该条目是否还只是「身份」——只有 id/name/description,没有任何能力配置。- * 「获取配置」按钮只在这种条目上出现:已经配置过的行不提供一个会把用户手写值- * 覆盖掉的入口。- */-export function hasModelConfig(model: DeepSeekModelDraft): boolean {- return CONFIG_FIELDS.some(field => model[field] !== undefined)-}--/**- * 该条目是否已声明接受图片。- *- * `input` 缺席表示「继承默认」,此时开关读为关:显式写入 `['text']` 才是「只收文本」,- * 这两种状态在设置文档里是不同的事实,开关只表达显式声明的那一种。- */-export function supportsImageInput(model: DeepSeekModelDraft): boolean {- const input = model.input- return Array.isArray(input) && input.includes('image')-}--/** 开关状态对应的 `input` 声明值。 */-export function imageInputValue(next: boolean): string[] {- return next ? ['text', 'image'] : ['text']-}--/** 该条目当前的档位声明;缺席、`false` 或非对象都读作空表。 */-export function thinkingEffortsOf(model: DeepSeekModelDraft): Record<string, string | null> {- const efforts = model.reasoningEfforts- if (typeof efforts !== 'object' || efforts === null || Array.isArray(efforts))- return {}- return efforts as Record<string, string | null>-}--/** 该条目已声明的档位名,用于渲染勾选态。 */-export function declaredThinkingLevels(model: DeepSeekModelDraft): string[] {- return Object.keys(thinkingEffortsOf(model))-}--/**- * 该条目是否已声明提供思考档位。- *- * `reasoningEfforts` 为 `false` 表示显式「不支持思考」,缺席表示「继承默认」,两者在- * 开关上都读为关;只有含 `off` 以外档位的对象才算打开——只声明 `off` 的条目在 schema- * 校验里本就不合法,等于没有可用的思考档位。- */-export function supportsThinking(model: DeepSeekModelDraft): boolean {- return Object.keys(thinkingEffortsOf(model)).some(level => level !== 'off')-}--/** 打开思考模式:保留已有的可用档位(含自定义档位),一个都没有时给默认四档。 */-export function enableThinking(model: DeepSeekModelDraft): Record<string, string | null> {- const current = thinkingEffortsOf(model)- const graded = Object.keys(current).filter(level => level !== 'off')- return graded.length === 0 ? { ...DEFAULT_THINKING_EFFORTS } : current-}--/**- * 勾选/取消一个档位的声明。- *- * 取消到空表时写 `false`(显式「不支持思考」)而不是空对象:空表会被 schema 判为非法声明。- * @param efforts - 当前的档位声明。- * @param level - 被切换的档位。- * @param enabled - 勾选为添加,取消为删除。- * @returns 新的声明值。- */-export function toggleThinkingLevel(- efforts: Readonly<Record<string, string | null>>,- level: string,- enabled: boolean,-): Record<string, string | null> | false {- const next = { ...efforts }- if (enabled)- next[level] = level === 'off' ? null : level- else- delete next[level]- return Object.keys(next).length === 0 ? false : next-}--/**- * 该条目是否已声明按 chat template 下发思考。- *- * 两个键一起读:只写 `thinkingFormat` 的条目(例如手写的)在开关上仍读为关,打开时会把端点- * 不认 `developer` 角色所必需的 `supportsDeveloperRole: false` 一并补上。- */-export function supportsTemplateThinking(model: DeepSeekModelDraft): boolean {- const compat = compatOf(model)- return compat.thinkingFormat === TEMPLATE_THINKING_FORMAT && compat.supportsDeveloperRole === false-}--/**- * 开关状态对应的 `compat` 声明值。- *- * 打开时写入 vLLM 这类 OpenAI 兼容端点需要的三项事实:思考参数走 `chat_template_kwargs`、档位- * 由下拉框动态填入、系统提示保持 `system` 角色(这类端点不认 `developer`,否则整轮请求 400)。- * 关闭只摘掉这三项,条目里其它 compat 键与 chat template 参数原样保留;compat 被摘空时返回- * undefined,让调用方删掉整个字段。- * @param model - 该条目当前的声明。- * @param next - 打开为写入,关闭为摘除。- * @returns 新的 compat 值,或 undefined(整个字段都不该存在)。- */-export function templateThinkingCompat(- model: DeepSeekModelDraft,- next: boolean,-): Record<string, unknown> | undefined {- const compat = { ...compatOf(model) }- const kwargs = { ...recordOf(compat.chatTemplateKwargs) }- delete kwargs[TEMPLATE_THINKING_KWARG]- if (next) {- compat.chatTemplateKwargs = { ...kwargs, [TEMPLATE_THINKING_KWARG]: { $var: TEMPLATE_THINKING_EFFORT_VAR } }- compat.thinkingFormat = TEMPLATE_THINKING_FORMAT- compat.supportsDeveloperRole = false- }- else {- delete compat.thinkingFormat- delete compat.supportsDeveloperRole- if (Object.keys(kwargs).length === 0)- delete compat.chatTemplateKwargs- else- compat.chatTemplateKwargs = kwargs- }- return Object.keys(compat).length === 0 ? undefined : compat-}--export interface ModelConfigMerge {- models: DeepSeekModelDraft[]- /** 至少写入了一个字段的条目数。 */- applied: number- /** 端点没有披露、因此没被补上的条目 id。 */- undisclosed: string[]-}--export interface ModelConfigMergeOptions {- /** 参与并入的条目 id;缺省为列表里的全部。 */- targets?: readonly string[]- /**- * 是否改写已有值。批量「自动配置所有模型」为 true(按钮的语义就是重新配置),- * 单行的「获取配置」为 false(它只出现在没有任何配置的条目上)。- */- overwrite?: boolean-}--/**- * 把端点披露的模型容量与家族预设的能力并入草稿。- *- * 容量只能来自端点,能力只能来自预设——端点清单不含模态与档位。端点没披露的条目,- * 只要预设认得,也一样配置得上。- * @param models - 当前草稿条目。- * @param discovered - 端点披露的模型条目。- * @param options - 参与并入的目标与是否改写已有值。- * @returns 并入后的条目、写入计数与既没被端点披露、预设也不认得的 id。- */-export function mergeModelCards(- models: readonly DeepSeekModelDraft[],- 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 }-}--/** 填入文案里 `{detail}` 占位符。 */-export function withDetail(template: string, detail: string): string {- return template.replace('{detail}', () => detail)-}--/** 填入文案里 `{path}` 占位符。 */-export function withPath(template: string, path: string): string {- return template.replace('{path}', () => path)-}--/** 填入文案里 `{n}` 占位符。 */-export function withCount(template: string, count: number): string {- return template.replace('{n}', () => String(count))-}--/**- * 组合一次端点读取的结果文案:写了多少、有多少条目端点没披露。- * @param merge - {@link mergeModelCards} 的结果。- * @param templates - 三段的文案模板(已本地化)。- * @param templates.applied - 已写入若干条目时的模板。- * @param templates.none - 一个字段都没写时的模板。- * @param templates.undisclosed - 端点未披露若干条目时的模板。- * @returns 可直接渲染的一行结果。- */-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/archiving/dsh-tauri-model-config/src/client/service/model-preset-fixtures.ts b/archiving/dsh-tauri-model-config/src/client/service/model-preset-fixtures.tsdeleted file mode 100644index 9888383b..00000000--- a/archiving/dsh-tauri-model-config/src/client/service/model-preset-fixtures.ts+++ /dev/null@@ -1,17 +0,0 @@-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/archiving/dsh-tauri-model-config/src/client/service/model-presets.test.ts b/archiving/dsh-tauri-model-config/src/client/service/model-presets.test.tsdeleted file mode 100644index 41dea2cf..00000000--- a/archiving/dsh-tauri-model-config/src/client/service/model-presets.test.ts+++ /dev/null@@ -1,97 +0,0 @@-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/archiving/dsh-tauri-model-config/src/client/service/model-presets.ts b/archiving/dsh-tauri-model-config/src/client/service/model-presets.tsdeleted file mode 100644index 2fe9ab24..00000000--- a/archiving/dsh-tauri-model-config/src/client/service/model-presets.ts+++ /dev/null@@ -1,158 +0,0 @@-import type { PresetRow, PresetTable } from '../../shared/model-presets'--/**- * 模型能力预设。- *- * 表由宿主侧从 LiteLLM 的模型价目/容量表现取(见 `src/host/service/model-presets.ts`),给出- * 「支持图片 / 支持思考 / 上下文上限 / 输出上限」四项事实;表里没收录的型号再由家族规则补一条- * 结论。预设只是起步值:端点披露的容量优先,用户可以随时在高级区改;两项能力只写「能」的结论,- * 数据集没表态的那一项留空,不会被写成显式的「不支持」。- */--/**- * 预设给出的能力;缺席的字段表示预设没有结论。- *- * `input` 只可能声明「收图片」,`efforts` 只可能声明「有档位」——预设不做减法:数据集没表态- * 的模态与档位不写进模型条目,让它们保持「继承默认」,而不是被写成显式的「不支持」。- */-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--/**- * 家族规则:只在表没给出结论时补一条「能」。- *- * 规则只做加法——上游数据集说不能、或没收录,都不妨碍这里按命名标记补上图片与思考能力- * (`glm-4v`、`kimi-k2-thinking`、`seed-1.6` 这类名字本身就是声明)。反过来不做减法:- * 把模型判成只能读文字会让用户发不出图片,代价比多勾一个开关大得多。- */-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-}--/** 当前预设表的条目数(0 表示只剩家族规则)。 */-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-}--/**- * 把数据集的一行与家族规则合成一条预设。- *- * 只写「能」的结论:数据集把 0 用作「没有给出这项事实」,家族规则也只按命名补「能」,所以两者- * 都没给出结论时该字段缺席。把「未知」写成 `input: ['text']` / `reasoningEfforts: false` 会替用户- * 否决掉部署真实具备的能力——本地端点上的模型往往比数据集新,自动配置又会覆盖行内旧值,代价是把- * 已经声明的思考与图片能力直接关掉。- * @param row - 数据集里该模型的一行事实。- * @param rule - 家族规则给出的结论,没有规则命中时为 undefined。- * @returns 只含正向结论的预设。- */-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 },- }-}--/**- * 查表用的候选键,自具体到宽泛:原样 → provider 前缀之后 → 逐段去掉尾部。- *- * 逐段回退覆盖端点上常见的日期与发布后缀(`gpt-4o-2024-08-06` → `gpt-4o`、- * `claude-3-5-sonnet-20241022` → `claude-3-5-sonnet`)。- * @param id - 已小写化的模型 id。- * @returns 按优先级排列的候选键。- */-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-}--/**- * 按模型 id 取能力预设。- * @param id - 端点上的模型 id(可带 provider 前缀、日期后缀),大小写不敏感。- * @returns 命中的预设,或 undefined(预设也不认识这个模型)。- */-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/archiving/dsh-tauri-model-config/src/client/service/presets.ts b/archiving/dsh-tauri-model-config/src/client/service/presets.tsdeleted file mode 100644index fb490abd..00000000--- a/archiving/dsh-tauri-model-config/src/client/service/presets.ts+++ /dev/null@@ -1,57 +0,0 @@-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) }- }-}--/**- * 确保能力预设表已装入。- *- * 表是自动配置填入图片与思考档位的唯一来源:进模型设置页时预取一次,之后同一会话复用同一个- * Promise。失败后不缓存结果,下一次调用会重新尝试(宿主侧还有自己的缓存与降级)。- * @returns 装入的条目数,或失败文案(此时家族规则仍然生效)。- */-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/archiving/dsh-tauri-model-config/src/client/types/remotes.ts b/archiving/dsh-tauri-model-config/src/client/types/remotes.tsdeleted file mode 100644index 44787517..00000000--- a/archiving/dsh-tauri-model-config/src/client/types/remotes.ts+++ /dev/null@@ -1,93 +0,0 @@-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.tsdeleted file mode 100644index 51cc5878..00000000--- a/archiving/dsh-tauri-model-config/src/host/apply.ts+++ /dev/null@@ -1,15 +0,0 @@-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/archiving/dsh-tauri-model-config/src/host/config/runtime.ts b/archiving/dsh-tauri-model-config/src/host/config/runtime.tsdeleted file mode 100644index 40e150b7..00000000--- a/archiving/dsh-tauri-model-config/src/host/config/runtime.ts+++ /dev/null@@ -1,4 +0,0 @@-import type { HostContext } from '../types'-import { defineHostRuntime } from 'dsh-tauri'--export const { setCurrentHostInstance, getCurrentHostInstance } = defineHostRuntime<HostContext>()diff --git a/archiving/dsh-tauri-model-config/src/host/routes/config/editor/get.ts b/archiving/dsh-tauri-model-config/src/host/routes/config/editor/get.tsdeleted file mode 100644index 38e4745d..00000000--- a/archiving/dsh-tauri-model-config/src/host/routes/config/editor/get.ts+++ /dev/null@@ -1,14 +0,0 @@-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/archiving/dsh-tauri-model-config/src/host/routes/config/editor/put.ts b/archiving/dsh-tauri-model-config/src/host/routes/config/editor/put.tsdeleted file mode 100644index a8a579af..00000000--- a/archiving/dsh-tauri-model-config/src/host/routes/config/editor/put.ts+++ /dev/null@@ -1,25 +0,0 @@-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/archiving/dsh-tauri-model-config/src/host/routes/config/open/post.ts b/archiving/dsh-tauri-model-config/src/host/routes/config/open/post.tsdeleted file mode 100644index eaa69dc3..00000000--- a/archiving/dsh-tauri-model-config/src/host/routes/config/open/post.ts+++ /dev/null@@ -1,13 +0,0 @@-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/archiving/dsh-tauri-model-config/src/host/routes/endpoint/models/get.ts b/archiving/dsh-tauri-model-config/src/host/routes/endpoint/models/get.tsdeleted file mode 100644index 05a9b487..00000000--- a/archiving/dsh-tauri-model-config/src/host/routes/endpoint/models/get.ts+++ /dev/null@@ -1,19 +0,0 @@-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/archiving/dsh-tauri-model-config/src/host/routes/index.ts b/archiving/dsh-tauri-model-config/src/host/routes/index.tsdeleted file mode 100644index f1bb8215..00000000--- a/archiving/dsh-tauri-model-config/src/host/routes/index.ts+++ /dev/null@@ -1,14 +0,0 @@-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'--export const routes = defineRoutes((disposer) => {- disposer.get({ kind: 'exact', path: '/api/desktop/dsh-tauri-model-config/config/editor' }, getEditor)- disposer.put({ kind: 'exact', path: '/api/desktop/dsh-tauri-model-config/config/editor' }, putEditor)- disposer.get({ kind: 'exact', path: '/api/desktop/dsh-tauri-model-config/endpoint/models' }, endpointModels)- disposer.get({ kind: 'exact', path: '/api/desktop/dsh-tauri-model-config/presets' }, presets)- disposer.post({ kind: 'exact', path: '/api/desktop/dsh-tauri-model-config/config/open' }, openConfig)-})diff --git a/archiving/dsh-tauri-model-config/src/host/routes/index.types.ts b/archiving/dsh-tauri-model-config/src/host/routes/index.types.tsdeleted file mode 100644index 684db961..00000000--- a/archiving/dsh-tauri-model-config/src/host/routes/index.types.ts+++ /dev/null@@ -1,61 +0,0 @@-import type { EditorPreference } from '../../shared/editor.types'--export interface EditorPreferenceBody {- preference: EditorPreference-}--export interface EditorPreferenceResponse {- preference?: EditorPreference- error?: string-}--export type HostContext = any--/** 一条归一化后的端点模型条目;缺席字段表示端点没有披露。 */-export interface EndpointModelCard {- id: string- name?: string- contextWindow?: number- maxTokens?: number-}--export interface GetEndpointModelsQuery {- /** 承载该提供方配置的设置命名空间(`llm-pi-ai` / `llm-deepseek` …)。 */- ns?: string- /** 从命名空间节根到该提供方 profile 的路径(JSON 数组;空数组表示整节即 profile)。 */- profilePath?: string- /** 表单当前显示的 API 地址;为空时用 profile 里已保存的值。 */- baseURL?: string- /** 已输入但尚未保存的密钥;为空时用 profile 指向的已存凭证。 */- 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 {- /** `'true'` 表示忽略缓存有效期,重新下载预设表。 */- force?: string-}--export interface PresetsResponse {- ok?: boolean- source?: string- fetchedAt?: string- /** 上游不可达、回退到过期缓存时为 true。 */- stale?: boolean- count?: number- presets?: Record<string, readonly number[]>- error?: string-}diff --git a/archiving/dsh-tauri-model-config/src/host/routes/presets/get.ts b/archiving/dsh-tauri-model-config/src/host/routes/presets/get.tsdeleted file mode 100644index e7f95104..00000000--- a/archiving/dsh-tauri-model-config/src/host/routes/presets/get.ts+++ /dev/null@@ -1,21 +0,0 @@-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/archiving/dsh-tauri-model-config/src/host/service/config-file.test.ts b/archiving/dsh-tauri-model-config/src/host/service/config-file.test.tsdeleted file mode 100644index 71ab36fb..00000000--- a/archiving/dsh-tauri-model-config/src/host/service/config-file.test.ts+++ /dev/null@@ -1,135 +0,0 @@-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-model-config', 'editor.json')- await mkdir(join(home, 'dsh-tauri-model-config'))- 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-model-config', '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-model-config', '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/archiving/dsh-tauri-model-config/src/host/service/config-file.ts b/archiving/dsh-tauri-model-config/src/host/service/config-file.tsdeleted file mode 100644index 173ec049..00000000--- a/archiving/dsh-tauri-model-config/src/host/service/config-file.ts+++ /dev/null@@ -1,65 +0,0 @@-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/archiving/dsh-tauri-model-config/src/host/service/config-file.types.ts b/archiving/dsh-tauri-model-config/src/host/service/config-file.types.tsdeleted file mode 100644index dcea8d97..00000000--- a/archiving/dsh-tauri-model-config/src/host/service/config-file.types.ts+++ /dev/null@@ -1,3 +0,0 @@-export type ConfigOpenResult- = | { ok: true, path: string, opened: 'file' | 'directory' }- | { ok: false, path: string, error: string }diff --git a/archiving/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.tsdeleted file mode 100644index 5cceae25..00000000--- a/archiving/dsh-tauri-model-config/src/host/service/config-file.utils.test.ts+++ /dev/null@@ -1,94 +0,0 @@-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/archiving/dsh-tauri-model-config/src/host/service/config-file.utils.ts b/archiving/dsh-tauri-model-config/src/host/service/config-file.utils.tsdeleted file mode 100644index c420ae0c..00000000--- a/archiving/dsh-tauri-model-config/src/host/service/config-file.utils.ts+++ /dev/null@@ -1,50 +0,0 @@-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/archiving/dsh-tauri-model-config/src/host/service/endpoint-models.ts b/archiving/dsh-tauri-model-config/src/host/service/endpoint-models.tsdeleted file mode 100644index 3b1ac76d..00000000--- a/archiving/dsh-tauri-model-config/src/host/service/endpoint-models.ts+++ /dev/null@@ -1,103 +0,0 @@-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- /** 从命名空间节根到 profile 的路径,JSON 数组字符串(空/缺省表示整节即 profile)。 */- profilePath?: string- /** 表单当前显示的 API 地址;为空时用 profile 里已保存的值。 */- baseURL?: string- /** 已输入但尚未保存的密钥;为空时用 profile 指向的已存凭证。 */- 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- }-}--/**- * 直接读取提供方端点公布的模型清单。- *- * 官方发现通道会把清单收窄成它自己的模型模型,而宿主直连能拿到端点写下的原始容量字段- * (`context_length` / `max_output_tokens` 等一批别名)——这是本服务存在的唯一理由,- * 与参考实现 dsh-llm-capabilities 的 `raw-models` 路由同理。- */-export const endpointModels = defineService({- /**- * 读取 `{baseURL}/models` 并归一化。- * @param input - 设置命名空间、profile 路径,以及表单当前显示的可选覆盖值。- * @returns 归一化条目与清单地址,或宿主侧自己的失败文案。- */- 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/archiving/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.tsdeleted file mode 100644index cc2415f5..00000000--- a/archiving/dsh-tauri-model-config/src/host/service/endpoint-models.utils.test.ts+++ /dev/null@@ -1,94 +0,0 @@-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/archiving/dsh-tauri-model-config/src/host/service/endpoint-models.utils.ts b/archiving/dsh-tauri-model-config/src/host/service/endpoint-models.utils.tsdeleted file mode 100644index 15759c6d..00000000--- a/archiving/dsh-tauri-model-config/src/host/service/endpoint-models.utils.ts+++ /dev/null@@ -1,125 +0,0 @@-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-}--/**- * 把一条端点清单纪录收敛成模型条目。- *- * 容量字段取自各家 OpenAI 兼容实现的常见别名(官方发现通道读的是同一批),- * 端点没披露就留空,绝不臆测。- * @param value - 清单里的一条纪录。- * @returns 归一化条目;没有可用 id 时返回 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 },- }-}--/** 读取 `{ data: [...] }` 清单信封里的每一条纪录。 */-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-}--/** 按路径读取设置节里的一个节点;任一段缺失即返回 undefined。 */-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-}--/** 解析查询里的 profile 路径:非法 JSON 或非字符串数组都按「整节即 profile」处理。 */-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 []- }-}--/** profile 里指向凭据的引用名。 */-export function apiKeyRefOf(profile: unknown): string | undefined {- return nonEmptyText(isRecord(profile) ? profile.apiKeyEnv : undefined)-}--/** profile 里已保存的 API 地址,或表单当前显示的那个。 */-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)-}--/** 清单地址:`{baseURL}/models`。 */-export function modelsListingUrl(baseURL: string): string {- return `${baseURL.replace(/\/+$/, '')}/models`-}diff --git a/archiving/dsh-tauri-model-config/src/host/service/model-presets.test.ts b/archiving/dsh-tauri-model-config/src/host/service/model-presets.test.tsdeleted file mode 100644index a9ae2eb1..00000000--- a/archiving/dsh-tauri-model-config/src/host/service/model-presets.test.ts+++ /dev/null@@ -1,129 +0,0 @@-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-model-config'--function jsonResponse(body: unknown, status = 200): Response {- return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })-}--/** 每个用例都在全新的模块实例与全新的 `$DSH_HOME` 下跑,内存缓存不会串场。 */-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/archiving/dsh-tauri-model-config/src/host/service/model-presets.ts b/archiving/dsh-tauri-model-config/src/host/service/model-presets.tsdeleted file mode 100644index 0e988955..00000000--- a/archiving/dsh-tauri-model-config/src/host/service/model-presets.ts+++ /dev/null@@ -1,123 +0,0 @@-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 }-}--/**- * 模型能力预设表的宿主侧来源。- *- * 表本身不进仓库:首次需要时从上游取一份,落在 `$DSH_HOME/dsh-tauri-model-config/` 下做缓存,- * 一天内直接用缓存。上游不可达时宁可用过期缓存也不用空表——端点的容量字段仍然能补上,- * 缺的只是图片与思考档位。- */-export const modelPresets = defineService({- /**- * 取预设表。- * @param force - 忽略缓存有效期,强制重新下载。- * @returns 预设表、来源、抓取时间与是否已过期,或宿主侧自己的失败文案。- */- 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/archiving/dsh-tauri-model-config/src/host/types/index.ts b/archiving/dsh-tauri-model-config/src/host/types/index.tsdeleted file mode 100644index b343b811..00000000--- a/archiving/dsh-tauri-model-config/src/host/types/index.ts+++ /dev/null@@ -1 +0,0 @@-export type HostContext = anydiff --git a/archiving/dsh-tauri-model-config/src/host/utils/paths.test.ts b/archiving/dsh-tauri-model-config/src/host/utils/paths.test.tsdeleted file mode 100644index f2840a30..00000000--- a/archiving/dsh-tauri-model-config/src/host/utils/paths.test.ts+++ /dev/null@@ -1,29 +0,0 @@-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-model-config', 'model-presets.json'))- })-})diff --git a/archiving/dsh-tauri-model-config/src/host/utils/paths.ts b/archiving/dsh-tauri-model-config/src/host/utils/paths.tsdeleted file mode 100644index 95f525b5..00000000--- a/archiving/dsh-tauri-model-config/src/host/utils/paths.ts+++ /dev/null@@ -1,32 +0,0 @@-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)-}--/** `$DSH_HOME`(非空白)优先,否则 `~/.dsh`:与官方 `resolveDshHome` 及桌面壳保持一致。 */-export function resolveSettingsFilePath(env: NodeJS.ProcessEnv = process.env): string {- return join(resolveDshHome(env), SETTINGS_FILE_NAME)-}--/** 模型能力预设的磁盘缓存:`$DSH_HOME/dsh-tauri-model-config/model-presets.json`。 */-export function resolvePresetCachePath(env: NodeJS.ProcessEnv = process.env): string {- return join(resolveDshHome(env), PLUGIN_ID, PRESET_CACHE_FILE_NAME)-}diff --git a/archiving/dsh-tauri-model-config/src/index.ts b/archiving/dsh-tauri-model-config/src/index.tsdeleted file mode 100644index cb1db366..00000000--- a/archiving/dsh-tauri-model-config/src/index.ts+++ /dev/null@@ -1,7 +0,0 @@-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.tsdeleted file mode 100644index 364e63c2..00000000--- a/archiving/dsh-tauri-model-config/src/shared/constants.ts+++ /dev/null@@ -1,4 +0,0 @@-export const PLUGIN_ID = 'dsh-tauri-model-config'--/** 承载全部模型配置的 DSH 设置文档文件名(位于 `$DSH_HOME` 之下)。 */-export const SETTINGS_FILE_NAME = 'settings.yaml'diff --git a/archiving/dsh-tauri-model-config/src/shared/editor.ts b/archiving/dsh-tauri-model-config/src/shared/editor.tsdeleted file mode 100644index 7610ceb1..00000000--- a/archiving/dsh-tauri-model-config/src/shared/editor.ts+++ /dev/null@@ -1,14 +0,0 @@-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/archiving/dsh-tauri-model-config/src/shared/editor.types.ts b/archiving/dsh-tauri-model-config/src/shared/editor.types.tsdeleted file mode 100644index 4e44380f..00000000--- a/archiving/dsh-tauri-model-config/src/shared/editor.types.ts+++ /dev/null@@ -1,4 +0,0 @@-export interface EditorPreference {- editor: 'vscode' | 'cursor' | 'system' | 'custom'- command: string-}diff --git a/archiving/dsh-tauri-model-config/src/shared/model-presets.test.ts b/archiving/dsh-tauri-model-config/src/shared/model-presets.test.tsdeleted file mode 100644index 13e469e8..00000000--- a/archiving/dsh-tauri-model-config/src/shared/model-presets.test.ts+++ /dev/null@@ -1,63 +0,0 @@-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/archiving/dsh-tauri-model-config/src/shared/model-presets.ts b/archiving/dsh-tauri-model-config/src/shared/model-presets.tsdeleted file mode 100644index 1dfd788f..00000000--- a/archiving/dsh-tauri-model-config/src/shared/model-presets.ts+++ /dev/null@@ -1,90 +0,0 @@-/**- * 模型能力预设的取数口径。- *- * 数据来自 LiteLLM 维护的模型价目/容量表,它给出「支持图片 / 支持思考 / 最大输入 / 最大输出」- * 四项事实。取数在宿主侧完成,插件本身不内嵌数据集。- */--export type PresetRow = readonly [number, number, number, number]--export type PresetTable = Record<string, PresetRow>--/**- * 上游数据集:LiteLLM 维护的模型价目/容量表(MIT),与 <https://models.litellm.ai/> 同源。- *- * 没有走 `litellm-api.up.railway.app` 的公开接口:那是 LiteLLM 的 demo 代理,固定在自己那份- * LiteLLM 版本上(实测 1.82.6),表比主干旧一截(1020 vs 1424 条 chat 模型),新模型会缺席。- * 该接口只提供全量,`/models/{model_id}` 之类又需要密钥、且只回答「代理自己部署了哪些模型」。- */-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),- ]-}--/** 键取 provider 前缀之后的末段并小写:同一模型被多家 provider 收录时只留一份。 */-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])]-}--/**- * 把上游数据集压成预设表。- *- * 口径:只保留 `mode === "chat"` 且至少带一项事实的条目;事实与更短前缀完全一致的日期/发布- * 后缀变体被剪掉,交给查询期的前缀匹配覆盖(`gpt-4o-2024-08-06` → `gpt-4o`)。- * @param payload - 上游数据集解析后的内容。- * @returns 模型 id → `[支持图片, 支持思考, 最大输入, 最大输出]`,0 表示数据集没有给出这项事实。- */-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/archiving/dsh-tauri-model-config/src/shared/onboarding-copy.ts b/archiving/dsh-tauri-model-config/src/shared/onboarding-copy.tsdeleted file mode 100644index 1e15894b..00000000--- a/archiving/dsh-tauri-model-config/src/shared/onboarding-copy.ts+++ /dev/null@@ -1,7 +0,0 @@-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.tsdeleted file mode 100644index b889e553..00000000--- a/archiving/dsh-tauri-model-config/tsdown.config.ts+++ /dev/null@@ -1,8 +0,0 @@-import { defineDshConfig } from '../dsh-tauri-tsdown/src/index.ts'--export default defineDshConfig({- client: {- dts: true,- noExternal: ['react-if-lite'],- },-})