dsh-aperture 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,20 +1,22 @@
1
1
  /**
2
- * `dsh-aperture` 浏览器半边:**设置 → 插件 → Aperture** 标签页。
2
+ * `dsh-aperture` 浏览器半边:**「插件」页里本插件那个包页上的配置页**。
3
3
  *
4
- * 扩展点与接线方式对齐参考实现 `@xiaoyuyu6420/dsh-backup`(`backupPanel` + 插件标签页):
4
+ * 注册在包级配置槽位 `plugins.bundle.config` 上,键是包名 `dsh-aperture`:点开插件列表里的本
5
+ * 插件就是这一页。页面只交内容,控件用官方原语,**没有卡片**,标题与面包屑由页主画。
5
6
  *
6
- * - 用 `settings.plugins.tab` 注册一个**列表槽位**标签页,而不是往「插件配置」里塞卡片;
7
- * - 注入面只有 `slots` / `locale` / `remote` 三个服务,**不注入设置传输**——配置读写与
8
- * 发现结果一样,都经自己的 `aperturePanel` Remote 命名空间往返,标签页因此不关心设置
9
- * 文档长什么样;
10
- * - 标签页只拿两个 prop:`panel`(端点集合)与 `t`(字典,因为注册时声明了 `locale`)。
7
+ * 地址与同步开关交给官方设置表单(`SettingsForm` / `SettingsValueField` / `SettingsFormModel`):
8
+ * 草稿与生效值的差分、`revision` 围栏写入、保存失败保留草稿、只读与「命名空间没在服务」都归它
9
+ * 管,本模块只声明每个字段怎么在「存下来的值」与「输入框文本」之间换算。
11
10
  *
12
- * **这个文件就是构建产物。** DSH 的客户端模块系统只要求一个经典脚本,用
13
- * `window.__ModuleLoader__.load({ id, factory })` 的握手把自己报上去;它不要求这份脚本
14
- * 经过打包器,也不检查它是否被压缩过。因此这里直接写 CJS 工厂体,用 `createElement`
15
- * 而不是 JSX:仓库不必为此引入打包器,也不必把一个编译产物提交进版本库。
11
+ * 注入面是 `slots` / `locale` / `remote` / `configForms`:报告与「立刻刷新」经自己的
12
+ * `aperturePanel` Remote 往返;设置的读写面向 `configForms` 要——**包级**配置页页主只递
13
+ * `view: 'page'`、不递 `form`(递 `form` 的是行级与条目级),所以得按设置命名空间自己取。状态走
14
+ * 注入面里的 `hooks`(渲染器把它变成 `useApertureCard` 选择器钩子),动作走普通函数。
16
15
  *
17
- * 运行时只 `require('react')`(DSH 平台基线模块),不需要 `dsh.client.external`。
16
+ * 客户端模块系统把 `dsh.client.inject` 里列出的包注册成可 `require` 的模块,因此这里能直接
17
+ * require 官方客户端包,不必引入打包器。**这个文件就是构建产物**:模块系统只要求一个经典脚本,
18
+ * 用 `window.__ModuleLoader__.load({ id, factory })` 的握手报名,不要求打包器,因此这里直接写
19
+ * CJS 工厂体,用 `createElement` 而不是 JSX。
18
20
  *
19
21
  * @module dsh-aperture/client
20
22
  */
@@ -23,335 +25,107 @@ window.__ModuleLoader__.load({
23
25
  id: 'dsh-aperture',
24
26
  factory: (require) => {
25
27
  const React = require('react');
28
+ const {
29
+ SettingsForm,
30
+ SettingsValueField,
31
+ SettingsFormModel,
32
+ settingsTextField,
33
+ Button,
34
+ Checkbox,
35
+ IconChevronRightOutlineRegular,
36
+ IconRefreshOutlineRegular,
37
+ SegmentedControl,
38
+ StateDot,
39
+ Switch,
40
+ Tag,
41
+ } = require('@deepseek-ai/dsh-client-ui-primitives');
42
+
26
43
  const h = React.createElement;
27
44
 
28
- /** 字典命名空间(本插件拥有)。标签页的 `locale` 声明与 `ctx.locale.bind` 都用它。 */
45
+ /** 字典命名空间(本插件拥有);配置页的 `locale` 声明与 `ctx.locale.bind` 都用它。 */
29
46
  const NS = 'settings.aperturePanel';
30
47
  /** 宿主半边的 Remote 命名空间(`src/remote.ts`)。 */
31
48
  const PANEL = 'aperturePanel';
32
- /** 包名,取自 package.json,同时是端点 id 的前缀。 */
49
+ /** 包名,取自 package.json;它同时是包级配置页的键。 */
33
50
  const PACKAGE = 'dsh-aperture';
34
- /** 样式表归属标记;卸载与热替换时按它回收。 */
35
- const STYLE_MARK = 'data-dsh-aperture';
36
-
37
- // ---------------------------------------------------------------- 端点契约
38
-
51
+ /** 样式表的归属标记;卸载与热替换时按它回收。 */
52
+ const STYLE_OWNER = 'aperture/client.js';
39
53
  /**
40
- * 一个 strict 结果编解码器。
41
- *
42
- * 浏览器半边挂载贡献时强制要求每个参数与结果的编解码器都是 `strict`、带非空类型符号
43
- * 与可用的 `parse`。生成器会塞进 zod schema;本插件的形状很小,手写校验就够了——手写
44
- * 反而能在宿主与界面漂移时报出具体字段名(`…status.models[3].contextWindow:期望 number`)。
45
- *
46
- * 字段类型是一行小文法:
47
- * - `'string'` / `'number'` / `'boolean'`:基本类型;
48
- * - 末尾 `?`:可省略(宿主没给这个字段);
49
- * - 末尾 `|null`:允许 `null`(参数里表示「撤销这一条覆盖」);
50
- * - 末尾 `[]`:数组;
51
- * - 直接给另一个 codec:嵌套对象;`opt(...)` 表示它可省略;`list(...)` 表示对象数组。
52
- *
53
- * @param {string} typeSymbol - 类型符号,注册表要求非空。
54
- * @param {Record<string, string|object>} fields - 字段与类型。
55
- * @returns {object} 编解码器。
54
+ * 设置命名空间(宿主 `src/config.ts` 的 `APERTURE_NAMESPACE`,也是 `cordis.patch.yml` 里那一行
55
+ * 的 id)。包级配置页页主不递 `form`,这一份表单就是按它向 `configForms` 要来的。
56
56
  */
57
- function codec(typeSymbol, fields) {
58
- return Object.freeze({
59
- mode: 'strict',
60
- typeSymbol,
61
- schema: {
62
- parse(value, at) {
63
- if (value === null || typeof value !== 'object' || Array.isArray(value)) {
64
- throw new TypeError(`${at ?? typeSymbol}:期望一个对象`);
65
- }
66
- const parsed = {};
67
- for (const [name, kind] of Object.entries(fields)) {
68
- // 嵌套时报错带完整路径(`…status.models[0].contextWindow`);顶层就是类型符号。
69
- const path = at === undefined ? `${typeSymbol}.${name}` : `${at}.${name}`;
70
- const field = value[name];
71
- if (field === undefined) {
72
- if (isOptional(kind)) continue;
73
- throw new TypeError(`${path}:缺字段`);
74
- }
75
- parsed[name] = parseKind(path, kind, field);
76
- }
77
- return parsed;
78
- },
79
- },
80
- });
81
- }
82
-
83
- /** 一个字段是否可省略。 */
84
- function isOptional(kind) {
85
- return typeof kind === 'string' ? kind.endsWith('?') : kind.optional === true;
86
- }
57
+ const SETTINGS_NS = 'aperture';
58
+ /** 这一页自己编辑的两个字段;其余配置键(`models` 除外)留给配置文件。 */
59
+ const FIELDS = Object.freeze(['baseUrl', 'sync']);
87
60
 
88
- /** 可省略的嵌套对象字段。 */
89
- function opt(inner) {
90
- return Object.freeze({ codec: inner, optional: true });
91
- }
92
-
93
- /** 由另一个 codec 描述的对象数组字段。 */
94
- function list(inner) {
95
- return Object.freeze({ list: inner });
96
- }
97
-
98
- /** 允许 `null` 的嵌套字段(`null` 与「缺字段」是两件事,因此不能靠 `?`)。 */
99
- function nullable(inner) {
100
- return Object.freeze({ nullable: inner });
101
- }
102
-
103
- /**
104
- * 按类型说明校验一个值。
105
- *
106
- * @param {string} path - 出错信息里的字段路径。
107
- * @param {string|object} kind - 类型说明。
108
- * @param {*} value - 待校验的值。
109
- * @returns {*} 校验过的值。
110
- */
111
- function parseKind(path, kind, value) {
112
- if (typeof kind === 'object' && kind !== null) {
113
- if (kind.list !== undefined) {
114
- if (!Array.isArray(value)) throw new TypeError(`${path}:期望数组`);
115
- return value.map((item, index) => parseKind(`${path}[${index}]`, kind.list, item));
116
- }
117
- if (kind.codec !== undefined) return kind.codec.schema.parse(value, path);
118
- if (kind.nullable !== undefined) {
119
- return value === null ? null : parseKind(path, kind.nullable, value);
120
- }
121
- // 直接给了另一个 codec,就是「这里是它描述的那个嵌套对象」。
122
- if (typeof kind.schema?.parse === 'function') return kind.schema.parse(value, path);
123
- throw new TypeError(`${path}:类型说明写错了`);
124
- }
125
-
126
- let spec = kind;
127
- if (spec.endsWith('?')) spec = spec.slice(0, -1);
128
- const nullable = spec.endsWith('|null');
129
- if (nullable) spec = spec.slice(0, -'|null'.length);
130
- const items = spec.endsWith('[]');
131
- const type = items ? spec.slice(0, -2) : spec;
132
-
133
- if (value === null) {
134
- if (nullable) return null;
135
- throw new TypeError(`${path}:期望 ${type},收到 null`);
136
- }
137
- if (items) {
138
- if (!Array.isArray(value)) throw new TypeError(`${path}:期望数组`);
139
- return value.map((item, index) => {
140
- if (typeof item !== type) {
141
- throw new TypeError(`${path}[${index}]:期望 ${type},收到 ${typeof item}`);
142
- }
143
- return item;
144
- });
145
- }
146
- if (typeof value !== type) throw new TypeError(`${path}:期望 ${type},收到 ${typeof value}`);
147
- return value;
148
- }
149
-
150
- /** 一个参数编解码器。
151
- *
152
- * `acceptsUndefined` 与「可省略」是一回事:`save` 的调用方常常只想改其中一个字段,
153
- * 没提到的那个必须原样传过去。
154
- *
155
- * @param {string} typeSymbol - 类型符号。
156
- * @param {'string' | 'boolean'} type - 允许的类型;`string` 另外允许 `null`(撤销覆盖)。
157
- * @returns {object} 参数编解码器。
158
- */
159
- function optionalParam(typeSymbol, type) {
160
- return Object.freeze({
161
- mode: 'strict',
162
- typeSymbol,
163
- acceptsUndefined: true,
164
- schema: {
165
- parse(value) {
166
- if (value === undefined) return undefined;
167
- if (type === 'string' && value === null) return null;
168
- if (typeof value !== type) throw new TypeError(`${typeSymbol}:期望 ${type},收到 ${typeof value}`);
169
- return value;
170
- },
171
- },
172
- });
173
- }
61
+ // ---------------------------------------------------------------- 端点契约
174
62
 
175
63
  /**
176
- * 一个参数编解码器。
64
+ * 浏览器半边与宿主半边之间的线格式。
177
65
  *
178
- * 类型说明用与字段同一套文法(数组、嵌套对象、`null` 都在其中),因此参数与结果只有一份规则。
179
- * 可省略表示「这一项不碰」:省略编号会让同一个端点少传一个参数,而不是传一个空值。
66
+ * 只有一个直通编解码器,因为浏览器侧从不解析这些值:注册表(`@deepseek-ai/dsh-typert-registry`)
67
+ * 只检查 `mode` 是 `strict`、`typeSymbol` 非空、`create` 是个函数,网关客户端只读参数上的
68
+ * `mode` 与结果上可选的 `decode`/`encode`,**没有一处调用 `create()`**,逐字段手写的 wire 校验
69
+ * 因此永远不会执行。曾经那 300 行文法还埋了个雷:注册表要的是 `create` 工厂,`schema` 字段不被
70
+ * 承认,于是 `$mount` 抛 `strict codec has no create() factory`,整份贡献被拒,界面安静地什么
71
+ * 都不出现。
180
72
  *
181
- * @param {string} typeSymbol - 类型符号。
182
- * @param {string|object} kind - 类型说明。
183
- * @returns {object} 参数编解码器。
73
+ * 端点名不能与命名空间服务自己的成员重名:api-gateway 为每个命名空间建的
74
+ * `RemoteNamespaceService` 会把端点收成自己的属性,撞上 `remove` / `has` / `install` / `name` /
75
+ * `ctx` 这类预置名字时校验会拒绝**整份**贡献。
184
76
  */
185
- function param(typeSymbol, kind) {
186
- return Object.freeze({
187
- mode: 'strict',
188
- typeSymbol,
189
- schema: {
190
- parse(value) {
191
- if (value === undefined) return undefined;
192
- return parseKind(typeSymbol, kind, value);
193
- },
194
- },
195
- });
196
- }
197
-
198
- /** 动作结果。 */
199
- const ACTION = codec(`${PACKAGE}/types#action`, { ok: 'boolean', summary: 'string' });
200
- /** 表单要显示的配置。 */
201
- const CONFIGURATION = codec(`${PACKAGE}/types#configuration`, {
202
- baseUrl: 'string',
203
- sync: 'boolean',
204
- baseUrlOverridden: 'boolean',
205
- syncOverridden: 'boolean',
206
- writable: 'boolean',
207
- });
208
-
209
- /** 一个模型的覆盖(`aperture.models` 里那一条)。 */
210
- const OVERRIDE = codec(`${PACKAGE}/types#modelOverride`, {
211
- name: 'string?',
212
- api: 'string?',
213
- contextWindow: 'number?',
214
- maxTokens: 'number?',
215
- input: 'string[]?',
216
- thinking: 'boolean?',
217
- });
218
-
219
- /** 一条事实的来源;未知来源原样显示。 */
220
- const PROVENANCE = codec(`${PACKAGE}/types#provenance`, {
221
- limits: 'string',
222
- reasoning: 'string',
223
- input: 'string',
224
- name: 'string',
225
- });
226
-
227
- /** 报告里的一个模型。 */
228
- const MODEL = codec(`${PACKAGE}/types#model`, {
229
- id: 'string',
230
- name: 'string',
231
- route: 'string?',
232
- protocol: 'string?',
233
- endpoints: 'string[]',
234
- contextWindow: 'number?',
235
- maxTokens: 'number?',
236
- input: 'string[]',
237
- reasoning: 'boolean',
238
- provenance: PROVENANCE,
239
- override: opt(OVERRIDE),
240
- alias: 'string?',
241
- });
242
-
243
- /** 报告里的一条路由。 */
244
- const ROUTE = codec(`${PACKAGE}/types#route`, {
245
- provider: 'string',
246
- api: 'string?',
247
- baseURL: 'string?',
248
- models: 'number',
249
- });
250
-
251
- /** 最近一次刷新的状态。 */
252
- const REFRESH = codec(`${PACKAGE}/types#refresh`, {
253
- trigger: 'string',
254
- at: 'string',
255
- durationMs: 'number',
256
- ok: 'boolean',
257
- error: 'string?',
258
- catalog: codec(`${PACKAGE}/types#catalog`, {
259
- available: 'boolean',
260
- entries: 'number',
261
- reason: 'string?',
262
- }),
263
- endpoint: opt(codec(`${PACKAGE}/types#endpoint`, { url: 'string', listed: 'number' })),
264
- sync: opt(codec(`${PACKAGE}/types#sync`, {
265
- applied: 'boolean',
266
- ops: 'number',
267
- routes: 'string[]',
268
- reason: 'string?',
269
- })),
270
- });
271
-
272
- /** 标签页要显示的整份报告。 */
273
- const STATUS = codec(`${PACKAGE}/types#status`, {
274
- place: 'string',
275
- refresh: opt(REFRESH),
276
- routes: list(ROUTE),
277
- models: list(MODEL),
278
- });
279
-
280
- /**
281
- * `edit` 的补丁:只带界面改动过的字段,缺字段表示不碰,`null` 表示这一条覆盖不要了。
282
- */
283
- const PATCH = codec(`${PACKAGE}/types#modelPatch`, {
284
- name: 'string|null?',
285
- api: 'string|null?',
286
- contextWindow: 'number|null?',
287
- maxTokens: 'number|null?',
288
- input: 'string[]|null?',
289
- thinking: 'boolean|null?',
290
- alias: 'string|null?',
77
+ const SCHEMA = Object.freeze({ parse: (value) => value });
78
+ const CODEC = Object.freeze({
79
+ mode: 'strict',
80
+ typeSymbol: `${PACKAGE}/types#any`,
81
+ create: () => SCHEMA,
291
82
  });
292
83
 
293
84
  /**
294
- * 一个端点的浏览器侧调用描述符。
85
+ * 一个端点的浏览器侧描述符。
295
86
  *
296
- * `acceptsUndefined` 由参数自己的编解码器决定,而不是一律为真:只有「可省略」的参数
297
- * (`save` 的地址与开关,没提到就原样不碰)才接受 `undefined`。`edit` 的补丁必须显式给出,
298
- * 因为 `null` 是有含义的(撤销覆盖),缺省不能顺便也当成撤销。
87
+ * 参数按宿主方法的形参顺序给出;调用点按位置传参,网关按 `wire` 映射,并且**自动省掉
88
+ * `undefined` 实参**(`if (value !== void 0) args[parameter.wire] = value`),所以「没提到的
89
+ * 参数」天然就是「不碰」。
299
90
  *
300
- * @param {string} method - 端点方法名(也是宿主服务上的方法名)。
301
- * @param {Array} parameters - `[参数名, 编解码器]` 对,顺序与宿主方法一致。
302
- * @param {object} result - 结果编解码器。
303
- * @returns {object} 描述符。
91
+ * @param {Array<string>} parameters - 参数名,顺序与宿主方法一致。
304
92
  */
305
- function descriptor(method, parameters, result) {
93
+ function descriptor(method, parameters = []) {
306
94
  return Object.freeze({
307
95
  id: `${PACKAGE}#${PANEL}/${method}`,
308
96
  service: PANEL,
309
97
  namespace: PANEL,
310
98
  method,
311
99
  invocation: Object.freeze({ kind: 'direct' }),
312
- parameters: Object.freeze(parameters.map(([name, param]) => Object.freeze({
100
+ parameters: Object.freeze(parameters.map((name) => Object.freeze({
313
101
  name,
314
102
  wire: name,
315
103
  source: 'json',
316
- codec: param,
317
- acceptsUndefined: param.acceptsUndefined === true,
104
+ codec: CODEC,
318
105
  }))),
319
- result,
106
+ result: CODEC,
320
107
  });
321
108
  }
322
109
 
323
- /**
324
- * 与宿主半边 `PANEL_INVOCATIONS` 一一对应的贡献。
325
- *
326
- * 端点名不能与命名空间服务自己的成员重名:api-gateway 为每个命名空间建一个
327
- * `RemoteNamespaceService`,端点会成为它的属性,撞上 `remove` / `has` / `install` /
328
- * `name` / `ctx` 这类预置名字时 `validateContribution` 会拒绝**整份**贡献,界面因此
329
- * 安静地什么都不出现。「撤下路由」叫 `withdraw` 就是这个原因。
330
- */
110
+ /** 与宿主半边 `PANEL_INVOCATIONS` 一一对应的贡献。 */
331
111
  const REMOTE = Object.freeze({
332
112
  package: PACKAGE,
333
113
  descriptors: Object.freeze([
334
- descriptor('status', [], STATUS),
335
- descriptor('refresh', [], ACTION),
336
- descriptor('withdraw', [], ACTION),
337
- descriptor('configuration', [], CONFIGURATION),
338
- descriptor('save', [
339
- ['baseUrl', optionalParam(`${PACKAGE}/types#baseUrl`, 'string')],
340
- ['sync', optionalParam(`${PACKAGE}/types#sync`, 'boolean')],
341
- ], ACTION),
342
- descriptor('edit', [
343
- ['id', param(`${PACKAGE}/types#modelId`, 'string')],
344
- ['patch', param(`${PACKAGE}/types#modelPatch`, nullable(PATCH))],
345
- ], ACTION),
114
+ descriptor('status'),
115
+ descriptor('refresh'),
116
+ descriptor('edit', ['id', 'patch']),
346
117
  ]),
347
118
  });
348
119
 
349
120
  /**
350
- * 把 `RemoteResult` 拆成值,失败则抛人话。
121
+ * 界面能编辑的覆盖键。
351
122
  *
352
- * @param {{ok: boolean}} result - 端点应答。
353
- * @returns {object} 端点值。
123
+ * 列表以外的键(例如 `reasoningEfforts`)一旦出现在用户层里,这一行就只能整条撤:只清认得
124
+ * 的那几项,它在报告里仍然是「已覆盖」,那颗标签会按不下去。
354
125
  */
126
+ const EDITABLE_KEYS = Object.freeze(['name', 'api', 'contextWindow', 'maxTokens', 'input', 'thinking', 'alias']);
127
+
128
+ /** 把 `RemoteResult` 拆成值,失败则抛人话。 */
355
129
  function unwrap(result) {
356
130
  if (result.ok) return result.value;
357
131
  const detail = result.error && result.error.message ? result.error.message : '未知原因';
@@ -361,292 +135,515 @@ window.__ModuleLoader__.load({
361
135
  // -------------------------------------------------------------------- 样式
362
136
 
363
137
  /**
364
- * 注入标签页样式。
138
+ * 配置页样式。
139
+ *
140
+ * 页面在独立 bundle 里,用不了仓库的 CSS module 管线,因此样式随包分发、按 effect 生命周期注入,
141
+ * 卸载时移除;元素按 `data-plugin-css` 认领,与自己重名的那份先删掉(热替换)。
142
+ *
143
+ * 选择器全部收在根节点的 `[data-dsh-aperture]` 之下,颜色只引用 dsh web 的主题 token
144
+ * (`--dsw-alias-*`,各带回落值),深浅色自动跟随。
365
145
  *
366
- * 标签页在独立 bundle 里,用不了仓库的 CSS module 管线,因此样式随包分发、按 effect
367
- * 生命周期注入,并在卸载时移除。选择器全部收在 `[data-dsh-aperture]` 之下;颜色只引用
368
- * dsh web 的主题 token(`--dsw-alias-*`,各带回落值),深浅色自动跟随。
146
+ * 排版照官方「模型」页:一个模型一张卡片(发丝描边 + 大圆角),展开的编辑器是卡片里一块内嵌面,
147
+ * 字段用官方 `SettingsValueField`,因此徽章、重置、提示这些细活与官方设置页逐像素一致。官方那些
148
+ * 类名是打包器哈希出来的私有产物,抄不到,能抄的只有配方(描边、圆角、内边距、字号)。
369
149
  *
370
- * 尺寸与形状照抄官方设置页的「模型」卡片(`@deepseek-ai/dsh-client-ui-settings-models`):
371
- * 输入框 32px / 8px 圆角 / `.5px` 边框,卡片与编辑区 12px 圆角、14px 16px 内边距,参数
372
- * 用 `minmax(160px, 1fr)` 的栅格加 12px 小标签,行内动作按钮 28px,正文按钮 36px 胶囊。
373
- * 那份 CSS 是构建产物里的字面量,可以逐条对照,因此界面不必赌一个没有类型声明的组件
374
- * API 也能与官方标签页长得一样。
150
+ * 颜色只许用「这一页真的定义过」的 token:官方原语自己用的那几个(`bg-layer-3`、`border-l4`、
151
+ * `interactive-bg-hover`)与 Theme 检查面列出的那十几个。像 `--dsw-alias-settings-card-stroke`
152
+ * 这种只活在官方「模型」页自己那份组件 CSS 里的名字,在插件页上根本没定义——引用它等于引用一个
153
+ * 空值,回落值又是白色,于是亮色主题下卡片连边都看不见(暗色主题反而正常,因为回落值是白 16%)。
154
+ * 亮色主题下 `bg-layer-*` 全是白色(层与层靠阴影分开),所以卡片只能靠描边立住,底色只是给暗色
155
+ * 主题加一点抬起感。
375
156
  *
376
157
  * @returns {Function} 卸载时移除样式表的 disposer。
377
158
  */
378
159
  function installStyles() {
379
- if (document.querySelector(`style[${STYLE_MARK}]`) !== null) return () => {};
160
+ const stale = document.querySelector(`style[data-plugin-css="${STYLE_OWNER}"]`);
161
+ if (stale !== null && stale.parentNode !== null) stale.parentNode.removeChild(stale);
162
+
380
163
  const element = document.createElement('style');
381
- element.setAttribute(STYLE_MARK, '');
164
+ element.dataset.plugin = PACKAGE;
165
+ element.dataset.pluginCss = STYLE_OWNER;
382
166
  element.textContent = `
383
- [${STYLE_MARK}] { display: flex; flex-direction: column; gap: 12px; max-width: 720px; min-width: 0; color: var(--dsw-alias-label-primary, inherit); }
384
- [${STYLE_MARK}] .dap-title { font-size: 16px; font-weight: 500; line-height: 24px; }
385
- [${STYLE_MARK}] .dap-subtitle { margin: 0; font-size: 14px; line-height: 22px; color: var(--dsw-alias-label-tertiary, rgba(127,127,127,.9)); }
386
- [${STYLE_MARK}] .dap-section { display: flex; flex-direction: column; gap: 12px; padding: 14px 16px; border: .5px solid var(--dsw-alias-border-l2, rgba(127,127,127,.3)); border-radius: 12px; background: var(--dsw-alias-bg-layer-2, transparent); }
387
- [${STYLE_MARK}] .dap-head { display: flex; flex-direction: column; gap: 2px; flex: 1 1 auto; min-width: 0; }
388
- [${STYLE_MARK}] .dap-row { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
389
- [${STYLE_MARK}] .dap-label { font-size: 12px; font-weight: 500; line-height: 18px; color: var(--dsw-alias-label-secondary, inherit); }
390
- [${STYLE_MARK}] .dap-hint { margin: 0; font-size: 12px; line-height: 18px; color: var(--dsw-alias-label-tertiary, rgba(127,127,127,.9)); }
391
-
392
- /* 输入控件照抄官方:32px 高、8px 圆角、.5px 的 l4 边框、bg-layer-1 底、聚焦只换边框色。
393
- select 的箭头是官方那段内联 SVG(颜色写死,深浅色下都够用)。 */
394
- [${STYLE_MARK}] .dap-input { box-sizing: border-box; width: 100%; min-width: 0; height: 32px; font: inherit; font-size: 14px; line-height: 22px; padding: 0 10px; border: .5px solid var(--dsw-alias-border-l4, rgba(127,127,127,.4)); border-radius: 8px; background: var(--dsw-alias-bg-layer-1, transparent); color: var(--dsw-alias-label-primary, inherit); }
395
- [${STYLE_MARK}] .dap-input:focus { border-color: var(--dsw-alias-brand-primary, rgba(127,127,127,.6)); outline: none; }
396
- [${STYLE_MARK}] .dap-input::placeholder { color: var(--dsw-alias-label-dimmed, rgba(127,127,127,.6)); }
397
- [${STYLE_MARK}] .dap-input:disabled { opacity: .6; cursor: default; }
398
- [${STYLE_MARK}] select.dap-input { max-width: 240px; cursor: pointer; appearance: none; padding-right: 32px; 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"); background-position: right 12px center; background-repeat: no-repeat; background-size: 12px 12px; }
399
-
400
- [${STYLE_MARK}] .dap-tag { flex: none; padding: 1px 6px; border: .5px solid var(--dsw-alias-border-l3, rgba(127,127,127,.4)); border-radius: 4px; font-size: 11px; line-height: 16px; color: var(--dsw-alias-label-secondary, inherit); }
401
- [${STYLE_MARK}] .dap-check { display: inline-flex; gap: 6px; align-items: center; font-size: 14px; line-height: 22px; }
402
- [${STYLE_MARK}] .dap-check > input { accent-color: var(--dsw-alias-brand-primary, rgba(127,127,127,.6)); }
403
- [${STYLE_MARK}] .dap-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
404
- [${STYLE_MARK}] .dap-actions[data-align="end"] { justify-content: flex-end; }
405
- [${STYLE_MARK}] .dap-button { box-sizing: border-box; display: inline-flex; justify-content: center; align-items: center; gap: 4px; height: 36px; padding: 0 14px; border: none; border-radius: 18px; background: none; color: var(--dsw-alias-label-primary, inherit); font: inherit; font-size: 14px; line-height: 22px; cursor: pointer; }
406
- [${STYLE_MARK}] .dap-button:not([data-primary="true"]) { border: .5px solid var(--dsw-alias-border-l3, rgba(127,127,127,.4)); }
407
- [${STYLE_MARK}] .dap-button:not([data-primary="true"]):hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover-solid, var(--dsw-alias-interactive-bg-hover, rgba(127,127,127,.12))); }
408
- [${STYLE_MARK}] .dap-button[data-danger="true"] { border: none; color: var(--dsw-alias-state-error-primary, #d9534f); }
409
- [${STYLE_MARK}] .dap-button[data-danger="true"]:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover-danger, rgba(217,83,79,.12)); }
410
- [${STYLE_MARK}] .dap-button:focus-visible { outline: none; box-shadow: 0 0 0 2px var(--dsw-alias-border-l3, rgba(127,127,127,.4)); }
411
- /* 主按钮的底色与文字是一对 token,不能只换底色。--dsw-alias-brand-primary 在浅色主题里是
412
- 近黑、在深色主题里是近白,而继承来的正文色恰好与它同色——只写 background 就是「深底深字」。
413
- --dsw-alias-label-primary-foreground 就是为这种底色准备的对比色。禁用态用主题自己的
414
- dimmed 填充 + label-secondary:官方的整颗 opacity: .4 会把底色与文字一起压向页面底色,
415
- 两个都变浅之后反而谁也看不清(浅色主题下大约 1.4:1)。 */
416
- [${STYLE_MARK}] .dap-button[data-primary="true"] { background: var(--dsw-alias-button-primary-fill, var(--dsw-alias-brand-primary, rgba(127,127,127,.5))); color: var(--dsw-alias-label-primary-foreground, #fff); }
417
- [${STYLE_MARK}] .dap-button[data-primary="true"]:hover:not(:disabled) { background: var(--dsw-alias-button-primary-hover, var(--dsw-alias-brand-primary, rgba(127,127,127,.5))); }
418
- [${STYLE_MARK}] .dap-button[data-primary="true"]:disabled { opacity: 1; background: var(--dsw-alias-button-primary-dimmed, rgba(127,127,127,.18)); color: var(--dsw-alias-label-secondary, rgba(127,127,127,.9)); }
419
- [${STYLE_MARK}] .dap-button:disabled { cursor: default; }
420
-
421
- [${STYLE_MARK}] .dap-banner { margin: 0; font-size: 12px; line-height: 18px; white-space: pre-wrap; }
422
- [${STYLE_MARK}] .dap-banner[data-ok="false"] { color: var(--dsw-alias-state-error-primary, #d9534f); }
423
- [${STYLE_MARK}] .dap-banner[data-ok="true"] { color: var(--dsw-alias-state-success-primary, inherit); }
424
- /* 状态段是一串「标签 + 值」,不用表格:值本身可能是地址或一列路由名,会很长。 */
425
- [${STYLE_MARK}] .dap-facts { margin: 0; padding: 0; list-style: none; display: flex; flex-direction: column; }
426
- [${STYLE_MARK}] .dap-fact { display: flex; gap: 12px; padding: 5px 0; border-top: .5px solid var(--dsw-alias-border-l2, rgba(127,127,127,.18)); }
427
- [${STYLE_MARK}] .dap-fact:first-child { border-top: none; padding-top: 0; }
428
- [${STYLE_MARK}] .dap-fact > dt { flex: 0 0 84px; font-size: 12px; line-height: 22px; color: var(--dsw-alias-label-tertiary, rgba(127,127,127,.9)); }
429
- [${STYLE_MARK}] .dap-fact > dd { margin: 0; min-width: 0; font-size: 14px; line-height: 22px; word-break: break-word; }
430
-
431
- [${STYLE_MARK}] .dap-group { display: flex; flex-direction: column; gap: 8px; }
432
- [${STYLE_MARK}] .dap-group-head { display: flex; flex-direction: column; gap: 2px; }
433
- [${STYLE_MARK}] .dap-group-title { font-size: 12px; font-weight: 500; line-height: 18px; color: var(--dsw-alias-label-secondary, inherit); }
434
- [${STYLE_MARK}] .dap-group-meta { font-size: 12px; line-height: 18px; color: var(--dsw-alias-label-tertiary, rgba(127,127,127,.9)); }
435
- [${STYLE_MARK}] .dap-models { margin: 0; padding: 0; list-style: none; display: flex; flex-direction: column; gap: 8px; }
436
- [${STYLE_MARK}] .dap-model { display: flex; flex-direction: column; gap: 8px; padding: 10px 12px; border: .5px solid var(--dsw-alias-border-l4, rgba(127,127,127,.3)); border-radius: 10px; }
437
- [${STYLE_MARK}] .dap-model-head { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; }
438
- [${STYLE_MARK}] .dap-model-identity { display: inline-flex; gap: 6px; align-items: center; min-width: 0; }
439
- [${STYLE_MARK}] .dap-model-id { font-family: var(--ds-font-family-code, monospace); font-size: 13px; line-height: 20px; overflow-wrap: anywhere; }
440
- [${STYLE_MARK}] .dap-model-name { font-size: 14px; font-weight: 500; line-height: 22px; }
441
- [${STYLE_MARK}] .dap-model-actions { display: inline-flex; gap: 4px; align-items: center; margin-left: auto; }
442
- [${STYLE_MARK}] .dap-model-actions .dap-button { height: 28px; padding: 0 10px; border-radius: 14px; font-size: 12px; line-height: 18px; }
443
- [${STYLE_MARK}] .dap-model-facts { font-size: 12px; line-height: 18px; color: var(--dsw-alias-label-secondary, inherit); }
444
- [${STYLE_MARK}] .dap-model-meta { margin: 0; font-size: 12px; line-height: 18px; color: var(--dsw-alias-label-tertiary, rgba(127,127,127,.9)); }
445
-
446
- /* 编辑区与官方一样是卡片里的一块浅色面:12px 圆角、14px 16px 内边距,参数排成
447
- minmax(160px, 1fr) 的栅格,标签 12px 在上,动作右对齐。 */
448
- [${STYLE_MARK}] .dap-editor { display: flex; flex-direction: column; gap: 14px; padding: 14px 16px; border-radius: 12px; background: var(--dsw-alias-bg-module-platform, var(--dsw-alias-bg-layer-1, transparent)); }
449
- [${STYLE_MARK}] .dap-editor-head { display: flex; gap: 8px; align-items: baseline; }
450
- [${STYLE_MARK}] .dap-editor-title { font-size: 14px; font-weight: 500; line-height: 22px; }
451
- [${STYLE_MARK}] .dap-editor-route { font-size: 12px; line-height: 18px; color: var(--dsw-alias-label-tertiary, rgba(127,127,127,.9)); }
452
- [${STYLE_MARK}] .dap-fields { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 8px; }
453
- [${STYLE_MARK}] .dap-field { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
454
- [${STYLE_MARK}] .dap-field > label { font-size: 12px; line-height: 18px; color: var(--dsw-alias-label-tertiary, rgba(127,127,127,.9)); }
455
- [${STYLE_MARK}] .dap-field-note { font-size: 12px; line-height: 18px; color: var(--dsw-alias-label-tertiary, rgba(127,127,127,.9)); }
456
- [${STYLE_MARK}] .dap-error { margin: 0; font-size: 12px; line-height: 18px; color: var(--dsw-alias-state-error-primary, #d9534f); }
457
- [${STYLE_MARK}] .dap-chevron { display: inline-flex; transition: transform 120ms ease; }
458
- [${STYLE_MARK}] .dap-chevron[data-open="true"] { transform: rotate(90deg); }
167
+ [data-dsh-aperture] {
168
+ display: flex;
169
+ flex-direction: column;
170
+ gap: 20px;
171
+ font-size: 13px;
172
+ color: var(--dsw-alias-label-primary, #e6e6e6);
173
+ }
174
+ [data-dsh-aperture] .dap-group {
175
+ display: flex;
176
+ flex-direction: column;
177
+ gap: 12px;
178
+ }
179
+ [data-dsh-aperture] .dap-groupHead {
180
+ display: flex;
181
+ align-items: center;
182
+ justify-content: space-between;
183
+ gap: 12px;
184
+ }
185
+ [data-dsh-aperture] .dap-titleWrap {
186
+ display: inline-flex;
187
+ align-items: baseline;
188
+ gap: 8px;
189
+ min-width: 0;
190
+ }
191
+ [data-dsh-aperture] .dap-groupTitle {
192
+ margin: 0;
193
+ font-size: 14px;
194
+ font-weight: 500;
195
+ line-height: 22px;
196
+ }
197
+ /* 数目跟在标题后面,用等宽数字,免得一轮刷新改写时宽度乱跳。 */
198
+ [data-dsh-aperture] .dap-count {
199
+ font-size: 14px;
200
+ line-height: 22px;
201
+ font-variant-numeric: tabular-nums;
202
+ color: var(--dsw-alias-label-tertiary, #8b8b8b);
203
+ }
204
+ /* 空状态是官方「模型」页那条虚线盒子:没有内容时给个形状,不留白。 */
205
+ [data-dsh-aperture] .dap-empty {
206
+ margin: 0;
207
+ padding: 12px;
208
+ border: 0.5px dashed var(--dsw-alias-border-l2, rgba(128, 128, 128, 0.28));
209
+ border-radius: var(--dsw-radius-lg, 16px);
210
+ text-align: center;
211
+ font-size: 12px;
212
+ line-height: 18px;
213
+ color: var(--dsw-alias-label-tertiary, #8b8b8b);
214
+ }
215
+ [data-dsh-aperture] .dap-hint {
216
+ margin: 0;
217
+ font-size: 12px;
218
+ line-height: 1.6;
219
+ color: var(--dsw-alias-label-tertiary, #8b8b8b);
220
+ }
221
+ [data-dsh-aperture] .dap-banner {
222
+ margin: 0;
223
+ font-size: 12px;
224
+ line-height: 1.6;
225
+ color: var(--dsw-alias-label-secondary, #c9c9c9);
226
+ }
227
+ [data-dsh-aperture] .dap-banner[data-ok='false'] {
228
+ color: var(--dsw-alias-state-error-primary, #e06c75);
229
+ }
230
+ [data-dsh-aperture] .dap-toggleRow {
231
+ display: flex;
232
+ align-items: flex-start;
233
+ justify-content: space-between;
234
+ gap: 16px;
235
+ font-size: 13px;
236
+ line-height: 1.5;
237
+ }
238
+ [data-dsh-aperture] .dap-toggleText {
239
+ display: flex;
240
+ flex-direction: column;
241
+ gap: 2px;
242
+ min-width: 0;
243
+ }
244
+ /* 一个模型一张卡片:发丝描边立形状(官方输入框用的就是这一档描边),底色只在暗色主题下抬起一层。 */
245
+ [data-dsh-aperture] .dap-rows {
246
+ display: flex;
247
+ flex-direction: column;
248
+ gap: 8px;
249
+ margin: 0;
250
+ padding: 0;
251
+ list-style: none;
252
+ }
253
+ [data-dsh-aperture] .dap-card {
254
+ display: flex;
255
+ flex-direction: column;
256
+ border: 0.5px solid var(--dsw-alias-border-l4, rgba(128, 128, 128, 0.36));
257
+ border-radius: var(--dsw-radius-xl, 20px);
258
+ background: var(--dsw-alias-bg-layer-2, transparent);
259
+ }
260
+ /* 行首是一条盖满整行的按钮:点哪儿都能展开这一行。 */
261
+ [data-dsh-aperture] .dap-cardHead {
262
+ display: flex;
263
+ /* 顶着第一行走,不居中:这一行有两行身份(名字 + 事实),居中的话状态点会落在两行中间。 */
264
+ align-items: flex-start;
265
+ gap: 10px;
266
+ width: 100%;
267
+ padding: 12px 14px;
268
+ border: 0;
269
+ border-radius: inherit;
270
+ background: none;
271
+ color: inherit;
272
+ font: inherit;
273
+ text-align: left;
274
+ cursor: pointer;
275
+ }
276
+ [data-dsh-aperture] .dap-cardHead:hover {
277
+ background: var(--dsw-alias-interactive-bg-hover, rgba(255, 255, 255, 0.06));
278
+ }
279
+ [data-dsh-aperture] .dap-cardHead[aria-expanded='true'] {
280
+ border-bottom: 0.5px solid var(--dsw-alias-border-l2, rgba(255, 255, 255, 0.12));
281
+ border-radius: var(--dsw-radius-xl, 20px) var(--dsw-radius-xl, 20px) 0 0;
282
+ }
283
+ [data-dsh-aperture] .dap-cardHead:focus-visible {
284
+ outline: 2px solid var(--dsw-alias-brand-primary, #7aaaff);
285
+ outline-offset: 1px;
286
+ }
287
+ /* 状态点:写入与否这一列永远在同一处,扫一眼就能比。22px 就是名字那一行的高度,点因此落在名字中间。 */
288
+ [data-dsh-aperture] .dap-status {
289
+ display: inline-flex;
290
+ align-items: center;
291
+ flex: none;
292
+ height: 22px;
293
+ }
294
+ [data-dsh-aperture] .dap-identity {
295
+ display: flex;
296
+ flex-direction: column;
297
+ gap: 2px;
298
+ flex: 1;
299
+ min-width: 0;
300
+ }
301
+ [data-dsh-aperture] .dap-identityTop {
302
+ display: flex;
303
+ align-items: center;
304
+ flex-wrap: wrap;
305
+ gap: 6px;
306
+ min-width: 0;
307
+ }
308
+ [data-dsh-aperture] .dap-name {
309
+ overflow: hidden;
310
+ font-size: 14px;
311
+ font-weight: 500;
312
+ line-height: 22px;
313
+ text-overflow: ellipsis;
314
+ white-space: nowrap;
315
+ }
316
+ /* 事实一项一句(「路由 x」「上下文 1M」),之间用小圆点分开:比一串空格好认,也不抢字号。
317
+ 名字必须是 .dap-factRow 而不是 .dap-facts:报告那张 dl 已经占了 .dap-facts,而且它的规则在后面,
318
+ 同名的话会把这里压成竖排(一条一行)。 */
319
+ [data-dsh-aperture] .dap-factRow {
320
+ display: flex;
321
+ align-items: baseline;
322
+ flex-wrap: wrap;
323
+ column-gap: 6px;
324
+ min-width: 0;
325
+ font-size: 12px;
326
+ line-height: 18px;
327
+ font-variant-numeric: tabular-nums;
328
+ color: var(--dsw-alias-label-tertiary, #8b8b8b);
329
+ }
330
+ [data-dsh-aperture] .dap-factItem + .dap-factItem::before {
331
+ content: '·';
332
+ margin-right: 6px;
333
+ color: var(--dsw-alias-label-tertiary, #8b8b8b);
334
+ }
335
+ [data-dsh-aperture] .dap-chevron {
336
+ display: inline-flex;
337
+ align-items: center;
338
+ flex: none;
339
+ height: 22px;
340
+ color: var(--dsw-alias-label-tertiary, #8b8b8b);
341
+ transition: transform 160ms ease;
342
+ }
343
+ [data-dsh-aperture] .dap-chevron[data-open='true'] {
344
+ transform: rotate(90deg);
345
+ }
346
+ /* 展开区是卡片里的一块内嵌面:暗色主题下比卡片再亮一层,亮色主题下靠这圈描边立住(底色也是白的)。 */
347
+ [data-dsh-aperture] .dap-editor {
348
+ display: flex;
349
+ flex-direction: column;
350
+ gap: 14px;
351
+ margin: 0 14px 14px;
352
+ padding: 14px 16px;
353
+ border: 0.5px solid var(--dsw-alias-border-l2, rgba(128, 128, 128, 0.28));
354
+ border-radius: var(--dsw-radius-lg, 16px);
355
+ background: var(--dsw-alias-bg-layer-3, transparent);
356
+ }
357
+ [data-dsh-aperture] .dap-editorHead {
358
+ display: flex;
359
+ align-items: center;
360
+ gap: 8px;
361
+ min-width: 0;
362
+ }
363
+ [data-dsh-aperture] .dap-editorId {
364
+ overflow: hidden;
365
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
366
+ font-size: 12px;
367
+ line-height: 18px;
368
+ color: var(--dsw-alias-label-tertiary, #8b8b8b);
369
+ text-overflow: ellipsis;
370
+ white-space: nowrap;
371
+ }
372
+ [data-dsh-aperture] .dap-editorDirty {
373
+ margin-left: auto;
374
+ }
375
+ [data-dsh-aperture] .dap-warnNote {
376
+ font-size: 12px;
377
+ line-height: 18px;
378
+ color: var(--dsw-alias-state-warn-primary, #dd8629);
379
+ }
380
+ [data-dsh-aperture] .dap-editGroup {
381
+ display: flex;
382
+ flex-direction: column;
383
+ gap: 4px;
384
+ }
385
+ [data-dsh-aperture] .dap-editGroupTitle {
386
+ font-size: 12px;
387
+ font-weight: 500;
388
+ line-height: 18px;
389
+ color: var(--dsw-alias-label-secondary, #c9c9c9);
390
+ }
391
+ /* 字段用网格排,格子自带一层壳:官方那条「相邻字段加一条上边框」在网格里会错开半格。 */
392
+ [data-dsh-aperture] .dap-fields {
393
+ display: grid;
394
+ grid-template-columns: repeat(auto-fit, minmax(210px, 1fr));
395
+ gap: 2px 16px;
396
+ }
397
+ [data-dsh-aperture] .dap-fieldCell {
398
+ min-width: 0;
399
+ }
400
+ [data-dsh-aperture] .dap-grid2 {
401
+ display: grid;
402
+ grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
403
+ gap: 14px 16px;
404
+ align-items: start;
405
+ }
406
+ [data-dsh-aperture] .dap-endpoints {
407
+ display: flex;
408
+ flex-direction: column;
409
+ gap: 4px;
410
+ }
411
+ [data-dsh-aperture] .dap-endpointList {
412
+ display: flex;
413
+ flex-direction: column;
414
+ gap: 2px;
415
+ margin: 0;
416
+ padding: 0;
417
+ list-style: none;
418
+ }
419
+ [data-dsh-aperture] .dap-endpoint {
420
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
421
+ font-size: 12px;
422
+ line-height: 18px;
423
+ color: var(--dsw-alias-label-secondary, #c9c9c9);
424
+ overflow-wrap: anywhere;
425
+ }
426
+ [data-dsh-aperture] .dap-inline {
427
+ display: flex;
428
+ align-items: center;
429
+ flex-wrap: wrap;
430
+ gap: 16px;
431
+ }
432
+ [data-dsh-aperture] .dap-control {
433
+ display: flex;
434
+ align-items: center;
435
+ gap: 8px;
436
+ font-size: 13px;
437
+ line-height: 1.5;
438
+ }
439
+ [data-dsh-aperture] .dap-actions {
440
+ display: flex;
441
+ align-items: center;
442
+ gap: 8px;
443
+ padding-top: 2px;
444
+ }
445
+ /* 左边那句「还有几项没写下去」,按钮一律靠右,主按钮在最右。 */
446
+ [data-dsh-aperture] .dap-actionsNote {
447
+ margin-right: auto;
448
+ font-size: 12px;
449
+ line-height: 18px;
450
+ color: var(--dsw-alias-label-tertiary, #8b8b8b);
451
+ }
459
452
  `;
460
- document.head.append(element);
461
- return () => element.remove();
453
+ document.head.appendChild(element);
454
+ return () => {
455
+ if (element.parentNode !== null) element.parentNode.removeChild(element);
456
+ };
462
457
  }
463
458
 
464
459
  // -------------------------------------------------------------------- 字典
465
460
 
466
- /**
467
- * 中英文字典。
468
- *
469
- * 注册时必须一次交齐所有内置语言,缺一个都会在注册处被拒绝;中文是本插件的主语言,
470
- * 英文只求达意。`{name}` 是插值占位符(由 locale 服务替换)。
471
- */
472
461
  const zh = {
473
- tab: 'Aperture',
474
- title: 'Aperture 模型发现',
475
- subtitle: '把实例通告的模型发布成 llm-pi-ai 的 provider 路由。',
476
- loading: '正在读取状态…',
477
- addressLabel: '实例地址',
478
- addressPlaceholder: 'https://ai.example.ts.net',
479
- addressDormant: '没有实例地址:发现处于休眠,插件不探测,也不会写入 llm-pi-ai。',
480
- syncLabel: '同步到 llm-pi-ai',
481
- syncOn: '写入 provider 字典',
482
- syncOff: '只探测,不写入',
483
- overridden: '已覆盖',
484
- reset: '撤销覆盖',
485
462
  save: '保存',
486
463
  saving: '保存中…',
487
- cancel: '取消',
488
- refresh: '立即刷新',
489
- refreshing: '正在发现…',
490
- withdraw: '撤掉已发布的路由',
491
- withdrawing: '正在撤下…',
492
- readOnly: '当前设置文档不接受写入,表单只读。',
493
-
494
- statusHeading: '最近一次刷新',
495
- noAddress: '未配置地址',
496
- neverRefreshed: '尚未完成任何刷新:稍后会自动重试,也可以按「立即刷新」。',
497
- refreshOk: '成功',
498
- refreshFailed: '失败',
499
- factTrigger: '触发',
500
- factTime: '时间',
501
- factDuration: '耗时',
502
- factResult: '结果',
503
- factCatalog: '清单',
504
- catalogEntries: '{count} 个条目',
505
- catalogUnavailable: '不可用({reason})',
506
- factEndpoint: '端点',
507
- endpointListed: '{url} 列出了 {count} 行',
508
- factSync: '设置',
509
- syncApplied: '向 llm-pi-ai 写入 {count} 个操作({routes})',
510
- syncOnlyRemoval: '仅移除',
511
- syncSkipped: '未写入({reason})',
512
-
513
- modelsHeading: '模型与路由',
514
- modelsCount: '{count} 个模型',
515
- modelsMetaOverride: '已覆盖 {count} 个模型,其余沿用发现值与清单',
516
- modelsMetaInherit: '全部沿用发现值与清单',
517
- noModels: '未发现任何模型。',
518
- modelsError: '未发现任何内容:{error}',
519
- unservedHeading: '未服务:没有本插件可发布的端点',
520
- unservedHint: '填上协议可以让它在对应路由上发布。',
521
- unservedEndpoints: '通告的端点:{list}',
522
- noEndpoints: '未通告任何端点',
523
- pendingTag: '待保存',
464
+ saveFailed: '没被接受:文档可能只读,或刚被别处改过',
465
+ readOnly: '这份设置是只读的,改不动。',
466
+ unavailable: '这一份设置现在读不到:宿主没有把 aperture 段服务给这个页面。',
467
+
468
+ addressLabel: '实例地址',
469
+ addressHint: '填 Aperture 的地址;留空即休眠,不再发现模型。',
470
+ addressPlaceholder: 'http://127.0.0.1:54117',
471
+ syncLabel: '自动同步',
472
+ syncHint: '每轮发现之后,把模型与参数写进 dsh 的 llm-pi-ai 路由。',
473
+
474
+ overridden: '已覆盖',
475
+ overriddenCount: '已覆盖 {count} 项',
476
+ resetField: '恢复默认',
477
+ invalidField: '要填不小于 1 的整数,或留空',
478
+
479
+ refresh: '立刻刷新',
480
+ refreshHint: '立刻重新发现并发布一次,清单与每一行的状态都按这一轮刷新。',
481
+ refreshing: '刷新中…',
482
+ loading: '读取中…',
483
+
484
+ configRefused: '设置已被别处改过,这次改动没有写入:刷新页面后再改一遍。',
485
+ savedResult: '已保存:{result}',
486
+ noChanges: '没有改动,因此没有写入。',
487
+ invalidNumber: '{field} 只能填不小于 1 的整数。',
488
+
489
+ // 「发现报告」那一块删掉之后留下的三句:没有地址时的空状态,以及这一轮两处可能出问题的地方。
490
+ dormantHint: '还没有实例地址:填上并保存之后才会去发现模型。',
491
+ catalogUnavailable: '清单不可用({reason})',
492
+ syncSkipped: '没写({reason})',
493
+
494
+ modelsTitle: '模型',
495
+ modelsHint: '一行一个模型;展开改这一行的覆盖,「保存」只写这一行。顺序来自发现顺序,没有路由可服务的排在最后。',
496
+ modelsCount: '{count} 个',
497
+ noModels: '还没有发现任何模型。',
524
498
  unservedTag: '未服务',
525
- advancedHide: '收起',
499
+ dirtyTag: '有未保存的改动',
500
+ statusUnserved: '没有路由能服务这个模型',
501
+ statusUnknown: '这一轮没有同步,写没写进去看不出来',
502
+ statusPublished: '已写入 dsh 的路由',
503
+ statusNotPublished: '还没写进 dsh 的路由',
504
+
505
+ factContextWindow: '上下文 {count}',
506
+ factMaxTokens: '输出 {count}',
507
+ factRoute: '路由 {route}',
508
+ factProtocol: '协议 {protocol}',
509
+ factInput: '模态 {value}',
510
+ factReasoning: '推理 {value}',
511
+ factAlias: '别名 {alias}',
512
+ factEndpoints: '网关通告的端点:',
513
+ factSource: '来源:{source}',
526
514
 
527
- factContextWindow: '{count} 上下文窗口',
528
- factMaxTokens: '{count} 输出',
529
515
  modalityText: '文本',
530
- modalityImage: '图像',
531
- modalityNone: '无模态',
532
- factReasoningOn: '推理',
533
- factReasoningOff: '无推理',
534
- factAlias: '清单别名 {alias}',
535
- sourceAperture: 'aperture',
536
- sourceNote: '来自 {source}',
516
+ modalityImage: '图片',
517
+ modalityNone: '无',
518
+ reasoningFollow: '跟随发现',
519
+ reasoningOn: '开',
520
+ reasoningOff: '关',
521
+
522
+ sourceAperture: 'Aperture',
537
523
  sourceModelsDev: 'models.dev',
538
524
  sourceConfig: '配置',
539
- sourceDefault: '默认',
525
+ sourceDefault: '默认值',
540
526
 
541
- edit: '编辑',
542
- noAlias: '未收录',
543
- noChanges: '没有要保存的改动。',
544
527
  editName: '显示名',
545
- editAlias: '清单别名',
546
- editContextWindow: '上下文',
528
+ editApi: '协议',
529
+ editContextWindow: '上下文容量',
547
530
  editMaxTokens: '最大输出',
548
- editInput: '输入模态',
531
+ editInput: '请求模态',
549
532
  editReasoning: '推理',
550
- editApi: '协议',
551
- editHint: '显示名、容量与模态留空表示这一项不覆盖,回落到发现值;协议与推理的「跟随发现」同理。',
552
- effectiveHint: '生效 {value}',
553
- effectiveSource: '生效 {value} · 来自 {source}',
554
- optionAuto: '跟随发现',
555
- optionOn: '开',
556
- optionOff: '关',
557
- invalidNumber: '{field} 必须是不小于 1 的整数。',
533
+ editAlias: '清单别名',
534
+ editNameHint: '留空即用发现到的名字。',
535
+ editApiHint: '未服务的模型只有这里能救:填上协议它才有路由;留空即用网关通告的协议。',
536
+ editCapacityHint: '可以写 1M、384K;留空即用发现到的容量。',
537
+ editAliasHint: '写进 llm-pi-ai 清单的别名。',
538
+ editInputHint: '这里能覆盖报告说它接收的模态。',
539
+ editReasoningHint: '「跟随发现」就是这一项不写。',
540
+ fieldHelp: '{field}的说明',
541
+ editGroupIdentity: '名称与协议',
542
+ editGroupCapacity: '容量',
543
+ editUnknownOverrides: '这一行还有界面改不动的覆盖({keys}):清空覆盖会整条删掉。',
544
+ pendingChanges: '有 {count} 项改动还没写下去',
545
+ noPendingChanges: '和已保存的值相同',
546
+ saveRow: '保存',
547
+ clearOverrides: '清空覆盖',
548
+ cancelRow: '取消',
549
+ keyReasoningEfforts: '推理档位',
550
+ listSeparator: '、',
558
551
  };
559
552
 
560
553
  const en = {
561
- tab: 'Aperture',
562
- title: 'Aperture model discovery',
563
- subtitle: 'Publish the models your instance advertises as llm-pi-ai provider routes.',
564
- loading: 'Reading state…',
565
- addressLabel: 'Instance address',
566
- addressPlaceholder: 'https://ai.example.ts.net',
567
- addressDormant: 'No instance address: discovery is dormant, so nothing is probed and nothing is written to llm-pi-ai.',
568
- syncLabel: 'Sync into llm-pi-ai',
569
- syncOn: 'writes the provider dictionary',
570
- syncOff: 'probe only, write nothing',
571
- overridden: 'overridden',
572
- reset: 'Reset',
573
554
  save: 'Save',
574
555
  saving: 'Saving…',
575
- cancel: 'Cancel',
556
+ saveFailed: 'not accepted: the document may be read-only, or just changed elsewhere',
557
+ readOnly: 'These settings are read-only, so nothing can be changed here.',
558
+ unavailable: 'These settings cannot be read right now: the Host does not serve the aperture section to this page.',
559
+
560
+ addressLabel: 'Instance address',
561
+ addressHint: 'Where Aperture listens; leave it empty to go dormant and stop discovering models.',
562
+ addressPlaceholder: 'http://127.0.0.1:54117',
563
+ syncLabel: 'Sync automatically',
564
+ syncHint: 'After each discovery round, write the models and their parameters into dsh\u2019s llm-pi-ai routes.',
565
+
566
+ overridden: 'overridden',
567
+ overriddenCount: '{count} overridden',
568
+ resetField: 'Reset to default',
569
+ invalidField: 'Enter an integer of at least 1, or leave it empty',
570
+
576
571
  refresh: 'Refresh now',
577
- refreshing: 'Discovering…',
578
- withdraw: 'Withdraw published routes',
579
- withdrawing: 'Withdrawing…',
580
- readOnly: 'This deployment does not accept settings writes, so the form is read-only.',
581
-
582
- statusHeading: 'Last refresh',
583
- noAddress: 'no address configured',
584
- neverRefreshed: 'No refresh has finished yet: one is retried shortly, or press “Refresh now”.',
585
- refreshOk: 'succeeded',
586
- refreshFailed: 'failed',
587
- factTrigger: 'Trigger',
588
- factTime: 'Time',
589
- factDuration: 'Took',
590
- factResult: 'Result',
591
- factCatalog: 'Catalog',
592
- catalogEntries: '{count} entries',
593
- catalogUnavailable: 'unavailable ({reason})',
594
- factEndpoint: 'Endpoint',
595
- endpointListed: '{url} listed {count} rows',
596
- factSync: 'Settings',
597
- syncApplied: 'wrote {count} operations to llm-pi-ai ({routes})',
598
- syncOnlyRemoval: 'removals only',
599
- syncSkipped: 'not written ({reason})',
600
-
601
- modelsHeading: 'Models and routes',
572
+ refreshHint: 'Discover and republish once; the list and every row’s status follow this round.',
573
+ refreshing: 'Refreshing…',
574
+ loading: 'Loading…',
575
+
576
+ configRefused: 'These settings changed elsewhere, so this edit was not written. Reload the page and try again.',
577
+ savedResult: 'Saved: {result}',
578
+ noChanges: 'Nothing changed, so nothing was written.',
579
+ invalidNumber: '{field} takes an integer of at least 1.',
580
+
581
+ // What is left of the deleted discovery report: the empty state without an address, plus the two
582
+ // things that can go wrong in a round.
583
+ dormantHint: 'No instance address yet: models are discovered once you set and save one.',
584
+ catalogUnavailable: 'catalog unavailable ({reason})',
585
+ syncSkipped: 'skipped ({reason})',
586
+
587
+ modelsTitle: 'Models',
588
+ modelsHint: 'One model per row; expand a row to edit its overrides, and Save writes only that row. The order comes from discovery, with anything no route can serve last.',
602
589
  modelsCount: '{count} models',
603
- modelsMetaOverride: '{count} models overridden, the rest inherit discovery and the catalog',
604
- modelsMetaInherit: 'everything inherits discovery and the catalog',
605
- noModels: 'No models discovered.',
606
- modelsError: 'Nothing discovered: {error}',
607
- unservedHeading: 'Unserved: no endpoint this plugin can publish',
608
- unservedHint: 'Filling in a protocol publishes it on the matching route.',
609
- unservedEndpoints: 'Advertised endpoints: {list}',
610
- noEndpoints: 'no endpoints advertised',
611
- pendingTag: 'unsaved',
590
+ noModels: 'No models discovered yet.',
612
591
  unservedTag: 'unserved',
613
- advancedHide: 'Collapse',
592
+ dirtyTag: 'unsaved edits',
593
+ statusUnserved: 'No route can serve this model',
594
+ statusUnknown: 'This round synced nothing, so whether it was written is unknown',
595
+ statusPublished: 'Written into the dsh routes',
596
+ statusNotPublished: 'Not written into the dsh routes yet',
597
+
598
+ factContextWindow: '{count} context',
599
+ factMaxTokens: 'output {count}',
600
+ factRoute: 'route {route}',
601
+ factProtocol: 'protocol {protocol}',
602
+ factInput: 'modalities {value}',
603
+ factReasoning: 'reasoning {value}',
604
+ factAlias: 'alias {alias}',
605
+ factEndpoints: 'Endpoints the gateway advertises:',
606
+ factSource: 'Source: {source}',
614
607
 
615
- factContextWindow: '{count} context window',
616
- factMaxTokens: '{count} output',
617
608
  modalityText: 'text',
618
609
  modalityImage: 'image',
619
- modalityNone: 'no modality',
620
- factReasoningOn: 'reasoning',
621
- factReasoningOff: 'no reasoning',
622
- factAlias: 'catalog alias {alias}',
623
- sourceAperture: 'aperture',
624
- sourceNote: '来自 {source}',
610
+ modalityNone: 'none',
611
+ reasoningFollow: 'Follow discovery',
612
+ reasoningOn: 'On',
613
+ reasoningOff: 'Off',
614
+
615
+ sourceAperture: 'Aperture',
625
616
  sourceModelsDev: 'models.dev',
626
617
  sourceConfig: 'config',
627
618
  sourceDefault: 'default',
628
619
 
629
- edit: 'Edit',
630
- noAlias: 'not in the catalog',
631
- noChanges: 'Nothing to save.',
632
620
  editName: 'Display name',
633
- editAlias: 'Catalog alias',
634
- editContextWindow: 'Context',
621
+ editApi: 'Protocol',
622
+ editContextWindow: 'Context window',
635
623
  editMaxTokens: 'Max output',
636
- editInput: 'Input modalities',
624
+ editInput: 'Request modalities',
637
625
  editReasoning: 'Reasoning',
638
- editApi: 'Protocol',
639
- editHint: 'An empty display name, capacity or modality drops that override and falls back to discovery; the same goes for “follow discovery” on protocol and reasoning.',
640
- effectiveHint: 'in effect: {value}',
641
- effectiveSource: 'in effect: {value} · from {source}',
642
- optionAuto: 'follow discovery',
643
- optionOn: 'on',
644
- optionOff: 'off',
645
- invalidNumber: '{field} must be an integer of at least 1.',
626
+ editAlias: 'Catalog alias',
627
+ editNameHint: 'Leave it empty to use the discovered name.',
628
+ editApiHint: 'The only way an unserved model gets a route is a protocol here; leave it empty to use the advertised one.',
629
+ editCapacityHint: 'Write 1M or 384K; leave it empty to use the discovered capacity.',
630
+ editAliasHint: 'The alias written into the llm-pi-ai catalog.',
631
+ editInputHint: 'This overrides the modalities the report says it accepts.',
632
+ editReasoningHint: '\u201cFollow discovery\u201d leaves this key unwritten.',
633
+ fieldHelp: 'About {field}',
634
+ editGroupIdentity: 'Name and protocol',
635
+ editGroupCapacity: 'Capacity',
636
+ editUnknownOverrides: 'This row also carries overrides this page cannot edit ({keys}); clearing overrides removes the whole entry.',
637
+ pendingChanges: '{count} edits not written yet',
638
+ noPendingChanges: 'Matches the saved values',
639
+ saveRow: 'Save',
640
+ clearOverrides: 'Clear overrides',
641
+ cancelRow: 'Cancel',
642
+ keyReasoningEfforts: 'reasoning efforts',
643
+ listSeparator: ', ',
646
644
  };
647
645
 
648
-
649
- // ------------------------------------------------------------------ 标签页
646
+ // ------------------------------------------------------------------ 小工具
650
647
 
651
648
  /** 一个错误的人话形式。 */
652
649
  function textOf(error) {
@@ -658,10 +655,43 @@ window.__ModuleLoader__.load({
658
655
  return value.toLocaleString();
659
656
  }
660
657
 
661
- /** ISO 时间戳 → 本地时间;宿主只报 ISO,时区是浏览器的事。 */
662
- function formatTime(iso) {
663
- const at = new Date(iso);
664
- return Number.isNaN(at.getTime()) ? iso : at.toLocaleString();
658
+ /** 容量能写成的样子:十进制数加一个可选的 K/M 后缀。 */
659
+ const CAPACITY_PATTERN = /^(\d+(?:\.\d+)?)([km])?$/i;
660
+ /** 后缀是十进制的:`1M` 就是 1000K,跟容量平时的说法一致。 */
661
+ const CAPACITY_SCALE = { k: 1e3, m: 1e6 };
662
+
663
+ /**
664
+ * 读输入框里的容量,好让人写 `1M`、`100K` 而不必去数零。与官方「模型」页同一套写法(它的
665
+ * `parseCapacity`):空串是「这一项不覆盖」,读不出来的返回 `NaN`,由调用方在本地挡下来。
666
+ *
667
+ * @returns {number|undefined} token 数;空串给 `undefined`,读不出来给 `NaN`。
668
+ */
669
+ function parseCapacity(text) {
670
+ const trimmed = text.trim();
671
+ if (trimmed.length === 0) return undefined;
672
+ const match = CAPACITY_PATTERN.exec(trimmed);
673
+ if (match === null) return NaN;
674
+ const suffix = match[2] === undefined ? '' : match[2].toLowerCase();
675
+ const scale = suffix === 'k' || suffix === 'm' ? CAPACITY_SCALE[suffix] : 1;
676
+ const scaled = Number(match[1]) * scale;
677
+ const rounded = Math.round(scaled);
678
+ // 浮点误差落在整数边上的(`1.0000001M`)吃掉;真不是整数的(`0.5`)原样返回,交给
679
+ // 调用方按「必须是不小于 1 的整数」拒绝。
680
+ return Math.abs(scaled - rounded) < 1e-6 ? rounded : scaled;
681
+ }
682
+
683
+ /**
684
+ * 把存下来的 token 数写回输入框,取能原样读回来的最短写法:`1000000` 写成 `1M`、`384000`
685
+ * 写成 `384K`,`1048576` 不是整千就照原样写——官方 `formatCapacity` 同此,两边是一套词汇。
686
+ *
687
+ * @returns {string} 输入框文本;没有值时是空串。
688
+ */
689
+ function formatCapacity(value) {
690
+ if (value === undefined) return '';
691
+ if (!Number.isInteger(value) || value <= 0) return String(value);
692
+ if (value % CAPACITY_SCALE.m === 0) return `${String(value / CAPACITY_SCALE.m)}M`;
693
+ if (value % CAPACITY_SCALE.k === 0) return `${String(value / CAPACITY_SCALE.k)}K`;
694
+ return String(value);
665
695
  }
666
696
 
667
697
  /** 事实来源 → 字典键;未知来源原样显示。 */
@@ -672,14 +702,15 @@ window.__ModuleLoader__.load({
672
702
  default: 'sourceDefault',
673
703
  };
674
704
 
705
+ /** 一个键在不在用户层里——这就是「有没有被覆盖」的判据:写了与默认值相同的值也算覆盖。 */
706
+ function hasKey(layer, key) {
707
+ return typeof layer === 'object' && layer !== null && Object.prototype.hasOwnProperty.call(layer, key);
708
+ }
709
+
675
710
  /**
676
- * 把 `{name}` 占位符换成实参。
677
- *
678
- * locale 服务自己做这件事;这里只是为了在没有注入 `t` 时(测试、以及渲染器还没绑定字典时)
679
- * 用同一套规则兜底——否则字典里的模板会原样漏到界面上。
711
+ * 把 `{name}` 占位符换成实参。locale 服务自己做这件事,这里只是没有注入 `t` 时(测试、以及
712
+ * 渲染器还没绑定字典时)用同一套规则兜底——否则字典里的模板会原样漏到界面上。
680
713
  *
681
- * @param {string} template - 字典里的模板。
682
- * @param {Record<string, *>} params - 实参。
683
714
  * @returns {string} 填好的字符串。
684
715
  */
685
716
  function interpolate(template, params) {
@@ -689,50 +720,121 @@ window.__ModuleLoader__.load({
689
720
  ));
690
721
  }
691
722
 
723
+ // ------------------------------------------------------------ 设置表单模型
724
+
725
+ /**
726
+ * 布尔字段的换算规格。
727
+ *
728
+ * 官方设置表单按「草稿文本」组织,规格只要求两个方向:值怎么写进文本、文本怎么变成一次写入。
729
+ * 开关用 `'true'` / `'false'` 当草稿,空串是「这一项不写」,值回落到组合层与 schema 默认。
730
+ *
731
+ * @returns {object} 字段规格。
732
+ */
733
+ function booleanField(field) {
734
+ return {
735
+ field,
736
+ format: (value) => (value === true ? 'true' : value === false ? 'false' : ''),
737
+ parse: (text) => {
738
+ if (text === '') return { kind: 'clear' };
739
+ if (text === 'true') return { kind: 'set', value: true };
740
+ if (text === 'false') return { kind: 'set', value: false };
741
+ return undefined;
742
+ },
743
+ };
744
+ }
745
+
746
+ /**
747
+ * 这份设置没有服务时用的替身:`configForms` 缺席时(注入表保证不会,但这一页不该因此整页消失)
748
+ * 让 `SettingsFormModel` 读到 `unavailable` 快照,官方表单自己会画那句「读不到」,模型那一段
749
+ * 照旧。写入一律回绝——没有服务时没有任何东西能接受它。
750
+ */
751
+ const UNSERVED = Object.freeze({
752
+ getSnapshot: () => ({
753
+ status: 'unavailable',
754
+ value: undefined,
755
+ base: undefined,
756
+ user: undefined,
757
+ writable: false,
758
+ revision: undefined,
759
+ }),
760
+ subscribe: () => () => {},
761
+ mutate: async () => false,
762
+ });
763
+
764
+ // ------------------------------------------------------------------ 配置页
765
+
766
+ /**
767
+ * 一个模型此刻在表单里长什么样。
768
+ *
769
+ * 取的都是**生效值**,输入框里显示的永远是此刻真正在用的东西;提交时逐字段与这份快照比较,
770
+ * 只有改动过的字段才会发出去,因此界面不编辑的 `reasoningEfforts` 之类不会被顺手抹掉。
771
+ */
772
+ function initialOf(model) {
773
+ return {
774
+ name: model.name,
775
+ alias: model.alias ?? '',
776
+ // 容量回写成能原样读回来的最短写法(`1M`、`384K`),与官方「模型」页同一套词汇。
777
+ contextWindow: formatCapacity(model.contextWindow),
778
+ maxTokens: formatCapacity(model.maxTokens),
779
+ text: model.input.includes('text'),
780
+ image: model.input.includes('image'),
781
+ // 「跟随发现」= 用户层里没写过这个键。写过了,生效值就是用户写的那个值。
782
+ reasoning: declaredIn(model, 'thinking') ? (model.reasoning ? 'on' : 'off') : 'auto',
783
+ api: declaredIn(model, 'api') ? (model.protocol ?? '') : '',
784
+ };
785
+ }
786
+
692
787
  /**
693
- * 「Aperture」标签页。
788
+ * 用户层里写没写过这个键——这就是「覆盖」的判据。
694
789
  *
695
- * 只持有视图状态:配置与报告分别由一个 effect 拉取,动作按下后再拉一次。**effect 的
696
- * 依赖里刻意不放注入面**——`inject` 面由渲染器每次渲染重新组装,把它的身份放进依赖会
697
- * 让 effect 每渲染一次就重跑一次,进而无限循环。因此这里用自增计数器当刷新信号。
790
+ * 报告里的 `overrideKeys` 直接来自用户层,不必拿生效值和默认值比:比出来的答案既会漏(写了与
791
+ * 默认相同的值),也会多(schema 补出来的空值)。
792
+ */
793
+ function declaredIn(model, key) {
794
+ return (model.overrideKeys ?? []).includes(key);
795
+ }
796
+
797
+ /** 覆盖键在界面上的名字;界面不编辑的键(`reasoningEfforts`)另给一个词条。 */
798
+ const OVERRIDE_NAMES = {
799
+ name: 'editName',
800
+ api: 'editApi',
801
+ contextWindow: 'editContextWindow',
802
+ maxTokens: 'editMaxTokens',
803
+ input: 'editInput',
804
+ thinking: 'editReasoning',
805
+ alias: 'editAlias',
806
+ reasoningEfforts: 'keyReasoningEfforts',
807
+ };
808
+
809
+ /**
810
+ * 配置页:实例(地址、同步开关)与模型清单。
811
+ *
812
+ * 表单状态读注入面里的 `useApertureCard`(官方 SettingsFormModel 的投影),报告、提示语与每行
813
+ * 草稿是局部状态——它们是这一页的视图状态,不是设置文档的一部分。报告本身(`panel.status` 那一份
814
+ * 结构化数据)仍然要读:每一行的事实、覆盖与状态点都长在它上面,只是不再整块摊开给用户看。
815
+ *
816
+ * **effect 的依赖里刻意不放注入面**:`inject` 面由渲染器每次渲染重新组装,把它的身份放进依赖会
817
+ * 让 effect 每渲染一次就重跑一次。因此报告用一个自增计数器当重读信号(依赖里只有那个数),注入
818
+ * 面里的函数只在事件处理里调用,拿到的永远是当轮的那份。
698
819
  *
699
- * @param {object} props - 渲染器交过来的 `panel` 与 `t`。
700
- * @returns {object} 标签页元素。
820
+ * @param {object} props - 注入面:`useApertureCard`、`panel`(报告端点)、`save` / `edit` /
821
+ * `resetField` / `discard` / `failed`(设置表单)与 `t`(字典,注册时声明了 `locale`)。
822
+ * @returns {object} 页面元素。
701
823
  */
702
- function ApertureTab(props) {
703
- const panel = props.panel;
824
+ function AperturePanel(props) {
704
825
  const t = typeof props.t === 'function' ? props.t : (key, params) => interpolate(zh[key] ?? key, params);
826
+ const state = props.useApertureCard((snapshot) => snapshot);
705
827
 
706
- const [configuration, setConfiguration] = React.useState(null);
707
- const [draft, setDraft] = React.useState(null);
708
828
  const [report, setReport] = React.useState(null);
709
829
  const [banner, setBanner] = React.useState(null);
710
830
  const [busy, setBusy] = React.useState('');
711
831
  const [drafts, setDrafts] = React.useState({});
712
832
  const [opened, setOpened] = React.useState({});
713
- const [configRevision, setConfigRevision] = React.useState(0);
714
- const [reportRevision, setReportRevision] = React.useState(0);
715
-
716
- React.useEffect(() => {
717
- let cancelled = false;
718
- panel.configuration().then(
719
- (next) => {
720
- if (cancelled) return;
721
- setConfiguration(next);
722
- setDraft({ baseUrl: next.baseUrl, sync: next.sync });
723
- },
724
- (error) => {
725
- if (!cancelled) setBanner({ ok: false, text: textOf(error) });
726
- },
727
- );
728
- return () => {
729
- cancelled = true;
730
- };
731
- }, [configRevision]);
833
+ const [revision, setRevision] = React.useState(0);
732
834
 
733
835
  React.useEffect(() => {
734
836
  let cancelled = false;
735
- panel.status().then(
837
+ props.panel.status().then(
736
838
  (next) => {
737
839
  if (!cancelled) setReport(next);
738
840
  },
@@ -743,9 +845,9 @@ window.__ModuleLoader__.load({
743
845
  return () => {
744
846
  cancelled = true;
745
847
  };
746
- }, [reportRevision]);
848
+ }, [revision]);
747
849
 
748
- /** 跑一个动作:期间禁用按钮,结束后把结果贴出来并按需重读。 */
850
+ /** 跑一个动作:期间禁用控件,结束后把结果贴出来并按需重读报告。 */
749
851
  const run = (key, action, after) => {
750
852
  setBusy(key);
751
853
  setBanner(null);
@@ -757,63 +859,61 @@ window.__ModuleLoader__.load({
757
859
  setBanner({ ok: false, text: textOf(error) });
758
860
  } finally {
759
861
  setBusy('');
760
- after();
862
+ if (after !== undefined) after();
761
863
  }
762
864
  })();
763
865
  };
764
866
 
765
867
  /**
766
- * 一个模型此刻在表单里长什么样。
767
- *
768
- * 取的都是**生效值**,这样输入框里显示的永远是此刻真正在用的东西;提交时逐字段与这份
769
- * 快照比较,只有改动过的字段才会被发出去(没提到的字段保持原样,因此界面不编辑的
770
- * `reasoningEfforts` 之类不会被顺手抹掉)。
868
+ * 保存设置里那两个字段,然后等一轮重新发现落地再说话。
771
869
  *
772
- * @param {object} model - 报告里的一个模型。
773
- * @returns {object} 八个字段的初值。
870
+ * 写入走官方表单模型的 `save()`:它自带 `revision` 围栏(期间别处改过就拒绝,而不是覆盖别人的
871
+ * 改动)并从宿主接受的那份重新播种,因此写完不重读设置——投影会自己变新。报告里的模型事实
872
+ * 与状态点来自最近一次刷新,写完必须等一轮,否则就是「保存了却没变」。设置变更自己也会唤起同一轮
873
+ * 刷新(单飞判定按配置版本合并),因此这里通常并进那一轮。
774
874
  */
775
- const initialOf = (model) => ({
776
- name: model.name,
777
- alias: model.alias ?? '',
778
- contextWindow: model.contextWindow === undefined ? '' : String(model.contextWindow),
779
- maxTokens: model.maxTokens === undefined ? '' : String(model.maxTokens),
780
- text: model.input.includes('text'),
781
- image: model.input.includes('image'),
782
- reasoning: model.override !== undefined && model.override.thinking !== undefined
783
- ? (model.override.thinking ? 'on' : 'off')
784
- : 'auto',
785
- api: (model.override !== undefined && model.override.api) || '',
786
- });
787
-
788
- /** 一个模型的当前草稿;没改过就是生效值本身。 */
875
+ const saveSettings = () => run('save', async () => {
876
+ await props.save();
877
+ if (props.failed()) return { ok: false, summary: t('configRefused') };
878
+ const round = await props.panel.refresh();
879
+ // 写入成功了,但重新发现可能失败——两件事不能混成一句话说,因此后半句照抄那一轮的说法。
880
+ return { ok: round.ok, summary: t('savedResult', { result: round.summary }) };
881
+ }, () => setRevision((value) => value + 1));
882
+
883
+ /** 一个模型此刻的草稿;没改过就是生效值本身。 */
789
884
  const draftOf = (model) => drafts[model.id] ?? initialOf(model);
790
885
 
791
- /** 改一个字段;用函数式更新,同一个 tick 里连着改几个字段也不会互相覆盖。 */
792
- const edit = (model, field, value) => {
886
+ /** 改这一行的几个字段;用函数式更新,同一个 tick 里连着改几项也不会互相覆盖。 */
887
+ const stage = (model, changes) => {
793
888
  setDrafts((current) => ({
794
889
  ...current,
795
- [model.id]: { ...(current[model.id] ?? initialOf(model)), [field]: value },
890
+ [model.id]: { ...(current[model.id] ?? initialOf(model)), ...changes },
796
891
  }));
797
892
  };
798
893
 
799
- /** 改动的字段 → 补丁;没变的不进补丁,非法值只报字段名。 */
894
+ /**
895
+ * 改动的字段 → 补丁;没变的不进补丁,非法值只报字段名。补丁里的空值就是「这一项不覆盖」:
896
+ * 文本字段用空串或 `null`(别名用空串),模态用 `null`,推理用 `null` 表示回落到发现。
897
+ */
800
898
  const patchOf = (draft, initial) => {
801
899
  const patch = {};
802
900
  const bad = [];
803
901
 
804
- if (draft.name !== initial.name) patch.name = draft.name.trim() === '' ? null : draft.name.trim();
805
- if (draft.alias !== initial.alias) patch.alias = draft.alias.trim();
902
+ // 前后空白不算改动:只把 ` 名字 ` 的空格去掉不算换过值,否则会凭空写下一笔覆盖。
903
+ const name = draft.name.trim();
904
+ if (name !== initial.name) patch.name = name === '' ? null : name;
905
+
906
+ const alias = draft.alias.trim();
907
+ if (alias !== initial.alias) patch.alias = alias;
806
908
 
807
909
  for (const [field, label] of [['contextWindow', 'editContextWindow'], ['maxTokens', 'editMaxTokens']]) {
808
910
  if (draft[field] === initial[field]) continue;
809
- const raw = draft[field].trim();
810
- if (raw === '') {
811
- patch[field] = null;
812
- continue;
813
- }
814
- const value = Number(raw);
815
- if (!Number.isInteger(value) || value < 1) bad.push(t(label));
816
- else patch[field] = value;
911
+ // 容量认 `1M`、`100K` 这种写法(官方「模型」页同一套);空串是「这一项不覆盖」。
912
+ const value = parseCapacity(draft[field]);
913
+ if (capacityBad(draft[field])) bad.push(t(label));
914
+ else if (value === undefined) patch[field] = null;
915
+ // 换一种写法写同一个数(`100k` 对 `100K`)不是改动:写下去只会多一笔没人改过的覆盖。
916
+ else if (value !== parseCapacity(initial[field])) patch[field] = value;
817
917
  }
818
918
 
819
919
  if (draft.api !== initial.api) patch.api = draft.api === '' ? null : draft.api;
@@ -829,615 +929,536 @@ window.__ModuleLoader__.load({
829
929
  };
830
930
 
831
931
  /**
832
- * 保存这一行的改动。
932
+ * 容量那一项的本地判定,输入框与保存走同一条规矩:空串不是非法,是「这一项不覆盖」;其余必须
933
+ * 是不小于 1 的整数——面板只收这种值,放过去只会换来一次没必要的往返。`1G`、`1.5`、`0` 都在
934
+ * 这里被挡下。
935
+ */
936
+ const capacityBad = (text) => {
937
+ const value = parseCapacity(text);
938
+ return value !== undefined && (!Number.isInteger(value) || value < 1);
939
+ };
940
+
941
+ /** 这一行有没有还没写下去的改动。 */
942
+ const dirtyOf = (model) => Object.keys(patchOf(draftOf(model), initialOf(model)).patch).length > 0;
943
+
944
+ /** 丢掉一行的草稿:输入框回到生效值。 */
945
+ const dropDraft = (id) => {
946
+ setDrafts((current) => {
947
+ const { [id]: _dropped, ...kept } = current;
948
+ return kept;
949
+ });
950
+ };
951
+
952
+ /** 展开或收起一行;收起不动草稿——收起来不等于放弃,标签会写着还有未保存的改动。 */
953
+ const toggleRow = (model) => setOpened((current) => ({ ...current, [model.id]: current[model.id] !== true }));
954
+
955
+ /**
956
+ * 写下这一行(一个模型)的改动。
833
957
  *
834
- * 一行一个保存按钮,写下去的就只有这一行——多行同时开着也不会互相牵连,版本校验也只
835
- * 管这一次写入。保存成功后收起面板:这一行的覆盖标签与事实都会跟着变,收起才看得见。
958
+ * 一行一个保存按钮,写下去的就只有这一行,宿主那边的版本校验也只管这一次写入。成功后收起面板
959
+ * ——这一行的覆盖标签与事实都会跟着变,收起才看得见。
836
960
  *
837
961
  * @param {object} model - 报告里的一个模型。
838
962
  */
839
- const submit = (model) => {
963
+ const submitRow = (model) => {
840
964
  const { patch, bad } = patchOf(draftOf(model), initialOf(model));
841
965
  if (bad.length > 0) {
842
- setBanner({ ok: false, text: t('invalidNumber', { field: bad.join('、') }) });
966
+ setBanner({ ok: false, text: t('invalidNumber', { field: bad.join(t('listSeparator')) }) });
843
967
  return;
844
968
  }
845
969
  if (Object.keys(patch).length === 0) {
846
970
  setBanner({ ok: true, text: t('noChanges') });
847
971
  return;
848
972
  }
849
- run('edit', () => panel.edit(model.id, patch), () => {
973
+ run('edit', () => props.panel.writeModel(model.id, patch), () => {
850
974
  dropDraft(model.id);
851
- close(model.id);
852
- setConfigRevision((value) => value + 1);
853
- setReportRevision((value) => value + 1);
975
+ setOpened((current) => ({ ...current, [model.id]: false }));
976
+ setRevision((value) => value + 1);
854
977
  });
855
978
  };
856
979
 
857
- /** 丢掉一行的草稿:输入框回到生效值。 */
858
- const dropDraft = (id) => {
859
- setDrafts((current) => {
860
- const { [id]: _dropped, ...kept } = current;
861
- return kept;
862
- });
863
- };
864
-
865
- /** 收起一行(草稿已经丢掉或写入成功)。 */
866
- const close = (id) => setOpened((state) => ({ ...state, [id]: false }));
867
-
868
980
  /** 取消这一行的编辑:草稿丢掉、面板收起,什么都不写。 */
869
- const cancel = (model) => {
981
+ const cancelRow = (model) => {
870
982
  dropDraft(model.id);
871
- close(model.id);
983
+ setOpened((current) => ({ ...current, [model.id]: false }));
872
984
  setBanner(null);
873
985
  };
874
986
 
875
987
  /**
876
988
  * 撤销这一行的覆盖:只把**报告里写着确实被覆盖过**的字段清掉。
877
989
  *
878
- * 不是整条删掉:`aperture.models` 里那条可能还有界面根本不编辑的键(例如
879
- * `reasoningEfforts`),整条删掉等于把用户手写的东西一起扔掉。因此这里只把已知被覆盖的
880
- * 字段逐个置空——与保存走同一个端点,只是补丁全是 `null`。万一报告的覆盖里出现了界面
881
- * 不认识的键(宿主以后加了字段),整条删掉是唯一能让这一行真的回落到发现值的做法。
990
+ * 不是整条删掉:`aperture.models` 里那条可能还有界面根本不编辑的键(例如 `reasoningEfforts`),
991
+ * 整条删掉等于把用户手写的东西一起扔掉,因此只把已知被覆盖的字段逐个置空。万一报告里出现了
992
+ * 界面不认识的键(宿主以后加了字段),整条删掉是唯一能让这一行真的回落到发现值的做法。
882
993
  *
883
994
  * @param {object} model - 报告里的一个模型。
884
995
  */
885
996
  const clearOverrides = (model) => {
886
- const overrides = model.override ?? {};
887
- const patch = {};
888
- if (overrides.name !== undefined) patch.name = null;
889
- if (overrides.api !== undefined) patch.api = null;
890
- if (overrides.contextWindow !== undefined) patch.contextWindow = null;
891
- if (overrides.maxTokens !== undefined) patch.maxTokens = null;
892
- if (overrides.input !== undefined) patch.input = null;
893
- if (overrides.thinking !== undefined) patch.thinking = null;
894
- // 别名在 `modelAliases` 里,是另一张表;显示的别名可能来自清单,因此这里只是
895
- // 「不要再覆盖」,宿主看到用户层没有这个键就什么都不写。
896
- if (model.alias !== undefined) patch.alias = '';
897
-
898
- const payload = Object.keys(patch).length === 0 ? null : patch;
899
- run('revert', () => panel.edit(model.id, payload), () => {
997
+ const keys = model.overrideKeys ?? [];
998
+ const known = keys.filter((key) => EDITABLE_KEYS.includes(key));
999
+ const unknown = keys.filter((key) => !EDITABLE_KEYS.includes(key));
1000
+ // 别名用空串表示「不要再覆盖」;其余字段 `null` 就是「不覆盖这一项」。
1001
+ const patch = Object.fromEntries(known.map((key) => [key, key === 'alias' ? '' : null]));
1002
+ const payload = unknown.length > 0 || known.length === 0 ? null : patch;
1003
+ run('revert', () => props.panel.writeModel(model.id, payload), () => {
900
1004
  dropDraft(model.id);
901
- close(model.id);
902
- setConfigRevision((value) => value + 1);
903
- setReportRevision((value) => value + 1);
1005
+ setOpened((current) => ({ ...current, [model.id]: false }));
1006
+ setRevision((value) => value + 1);
904
1007
  });
905
1008
  };
906
1009
 
907
- if (configuration === null || draft === null) {
908
- return h(
909
- 'div',
910
- { [STYLE_MARK]: '', 'aria-busy': 'true' },
911
- h('p', { className: 'dap-subtitle' }, banner === null ? t('loading') : banner.text),
912
- );
913
- }
914
-
915
- const disabled = busy !== '' || !configuration.writable;
916
- const dirty = draft.baseUrl !== configuration.baseUrl || draft.sync !== configuration.sync;
917
- const dormant = draft.baseUrl.trim().length === 0;
1010
+ const refreshReport = () => run('refresh', () => props.panel.refresh(), () => setRevision((value) => value + 1));
918
1011
 
919
- /** 「标签 + 值」的一行;没有标签时就是一个整行的值(错误什么的)。 */
920
- const fact = (key, label, value) => h(
921
- 'div',
922
- { className: 'dap-fact', key },
923
- label === null ? null : h('dt', null, label),
924
- h('dd', null, value),
925
- );
1012
+ /** 来源那句:报告里的事实都有出处,界面按语言渲染它。 */
1013
+ const sourceOf = (fact) => t('factSource', {
1014
+ source: SOURCE_KEYS[fact] === undefined ? fact : t(SOURCE_KEYS[fact]),
1015
+ });
926
1016
 
927
- /** 状态段:最近一次刷新决定了什么。 */
928
- const statusFacts = (current) => {
929
- const refresh = current.refresh;
930
- if (refresh === undefined) {
931
- return h('p', { className: 'dap-hint' }, t('neverRefreshed'));
932
- }
933
- return h(
934
- 'dl',
935
- { className: 'dap-facts' },
936
- fact('trigger', t('factTrigger'), refresh.trigger),
937
- fact('time', t('factTime'), formatTime(refresh.at)),
938
- fact('duration', t('factDuration'), `${refresh.durationMs}ms`),
939
- fact('result', t('factResult'), refresh.ok ? t('refreshOk') : t('refreshFailed')),
940
- refresh.error === undefined ? null : fact('error', null, refresh.error),
941
- fact(
942
- 'catalog',
943
- t('factCatalog'),
944
- refresh.catalog.available
945
- ? t('catalogEntries', { count: formatCount(refresh.catalog.entries) })
946
- : t('catalogUnavailable', { reason: refresh.catalog.reason ?? '—' }),
947
- ),
948
- refresh.endpoint === undefined
949
- ? null
950
- : fact('endpoint', t('factEndpoint'), t('endpointListed', {
951
- url: refresh.endpoint.url,
952
- count: refresh.endpoint.listed,
953
- })),
954
- refresh.sync === undefined
955
- ? null
956
- : fact('sync', t('factSync'), refresh.sync.applied
957
- ? t('syncApplied', {
958
- count: refresh.sync.ops,
959
- routes: refresh.sync.routes.join(', ') || t('syncOnlyRemoval'),
960
- })
961
- : t('syncSkipped', { reason: refresh.sync.reason ?? '—' })),
962
- );
963
- };
1017
+ /** 最近一轮写入过的路由名;`undefined` 是「这一轮没同步」,不是「没写」——同步关着的时候报告里
1018
+ * 根本没有这一项,界面不能把「不知道」说成「没写」。
1019
+ */
1020
+ const writtenRoutes = report === null || report.refresh === undefined || report.refresh.sync === undefined
1021
+ ? undefined
1022
+ : report.refresh.sync.routes;
964
1023
 
965
- /** 一个模型那几项生效的事实。 */
966
- const modelFacts = (model) => {
1024
+ /** 一行模型那几项生效的事实,一项一句;缺哪项就不提哪项。 */
1025
+ const factItems = (model) => {
967
1026
  const facts = [];
1027
+ if (model.route !== undefined) facts.push(t('factRoute', { route: model.route }));
1028
+ if (model.protocol !== undefined) facts.push(t('factProtocol', { protocol: model.protocol }));
968
1029
  if (model.contextWindow !== undefined) {
969
1030
  facts.push(t('factContextWindow', { count: formatCount(model.contextWindow) }));
970
1031
  }
971
1032
  if (model.maxTokens !== undefined) facts.push(t('factMaxTokens', { count: formatCount(model.maxTokens) }));
972
- facts.push(model.input.length === 0
973
- ? t('modalityNone')
974
- : model.input.map((item) => t(item === 'image' ? 'modalityImage' : 'modalityText')).join('+'));
975
- facts.push(model.reasoning ? t('factReasoningOn') : t('factReasoningOff'));
1033
+ facts.push(t('factInput', {
1034
+ value: model.input.length === 0
1035
+ ? t('modalityNone')
1036
+ : model.input.map((item) => t(item === 'image' ? 'modalityImage' : 'modalityText')).join('+'),
1037
+ }));
1038
+ facts.push(t('factReasoning', { value: model.reasoning ? t('reasoningOn') : t('reasoningOff') }));
976
1039
  if (model.alias !== undefined && model.alias !== '') facts.push(t('factAlias', { alias: model.alias }));
977
- return facts.join(' · ');
1040
+ return facts;
978
1041
  };
979
1042
 
980
- /** 披露箭头;展开时转 90 度(官方那份也是自己画的内联 SVG)。 */
981
- const chevron = (open) => h(
982
- 'span',
983
- { className: 'dap-chevron', 'data-open': open ? 'true' : 'false' },
984
- h(
985
- 'svg',
986
- { width: '12', height: '12', viewBox: '0 0 16 16', fill: 'none', 'aria-hidden': 'true' },
987
- h('path', {
988
- d: 'M6 3.5L10.5 8L6 12.5',
989
- stroke: 'currentColor',
990
- strokeWidth: '1.5',
991
- strokeLinecap: 'round',
992
- strokeLinejoin: 'round',
993
- }),
994
- ),
995
- );
996
-
997
1043
  /**
998
- * 一个参数格子:标签在上、控件在下(官方的 `modelAdvanced` 栅格就是这样)。
1044
+ * 这一行的状态点:绿是写进去了、灰是没写进去、黄是根本没有路由能服务它。
999
1045
  *
1000
- * @param {string} key - React key 与控件 id。
1001
- * @param {string} label - 12px 的小标签。
1002
- * @param {object} control - 控件元素。
1003
- * @param {string} [note] - 生效值一类的补充说明。
1004
- * @returns {object} 一个栅格单元。
1046
+ * 点旁边那句 `title` 就是它的说法——官方 `StateDot` 自己是 `aria-hidden`,说给谁听得由这里给。
1005
1047
  */
1006
- const field = (key, label, control, note) => h(
1007
- 'div',
1008
- { className: 'dap-field', key },
1009
- h('label', { htmlFor: key }, label),
1010
- control,
1011
- note === undefined ? null : h('span', { className: 'dap-field-note' }, note),
1012
- );
1048
+ const publishState = (model) => {
1049
+ if (model.route === undefined) return { state: 'warning', title: t('statusUnserved') };
1050
+ if (writtenRoutes === undefined) return { state: 'idle', title: t('statusUnknown') };
1051
+ return writtenRoutes.includes(model.route)
1052
+ ? { state: 'done', title: t('statusPublished') }
1053
+ : { state: 'idle', title: t('statusNotPublished') };
1054
+ };
1013
1055
 
1014
- /** 一个 `<select>` 的选项。 */
1015
- const option = (value, label) => h('option', { value, key: value === '' ? 'auto' : value }, label);
1056
+ /** 把覆盖键翻成给人看的一句话:界面认得的键都有字段,认不得的只有这里说得出名字。 */
1057
+ const overrideKeyNames = (keys) => keys
1058
+ .map((key) => (OVERRIDE_NAMES[key] === undefined ? key : t(OVERRIDE_NAMES[key])))
1059
+ .join(t('listSeparator'));
1016
1060
 
1017
1061
  /**
1018
- * 一个字段旁边的注脚:当前生效的值,以及它从哪里来。
1062
+ * 一个文本类覆盖字段。
1019
1063
  *
1020
- * 来源跟着**它描述的那个字段**走:「容量 1,048,576 · 来自 aperture」和输入框摆在一起
1021
- * 才读得懂。把四项来源串成一句话挂在行尾,用户得自己把每一项对回去,而一张十一行模型
1022
- * 的清单每行再挂一串,正文就被诊断信息盖住了。
1064
+ * 官方 `SettingsValueField` 的语义正好对得上:「已覆盖」= 用户层里有这个键(报告给的
1065
+ * `overrideKeys`),「恢复默认」= 把草稿改回「不覆盖」,非法草稿只标出来、由保存拦住。
1023
1066
  *
1024
- * @param {string} value - 当前生效的值。
1025
- * @param {string} [source] - 来源代号;没有来源时(例如协议是推导出来的)只说值。
1026
- * @returns {string} 注脚。
1067
+ * 长解释进 `help`(官方那个「i」按钮),输入框下面只留一句来源;外面再套一层格子,官方字段行
1068
+ * 那条「相邻就加上边框」在网格里会错开半格,隔开一层壳就不碰它了。
1027
1069
  */
1028
- const inEffect = (value, source) => source === undefined
1029
- ? t('effectiveHint', { value })
1030
- : t('effectiveSource', { value, source: t(SOURCE_KEYS[source] ?? source) });
1031
-
1032
- /** 编辑面板里的一个文本输入框。 */
1033
- const textField = (model, name, label, options = {}) => {
1034
- const id = `dap-model-${model.id}-${name}`;
1035
- return field(
1036
- id,
1037
- label,
1038
- h('input', {
1039
- id,
1040
- className: 'dap-input',
1041
- type: 'text',
1042
- inputMode: options.numeric === true ? 'numeric' : undefined,
1043
- spellCheck: false,
1044
- autoComplete: 'off',
1045
- placeholder: options.placeholder,
1046
- value: draftOf(model)[name],
1047
- disabled: !configuration.writable,
1048
- onChange: (event) => edit(model, name, event.target.value),
1049
- }),
1050
- options.note,
1051
- );
1052
- };
1070
+ const textField = (model, key, copy) => h(
1071
+ 'div',
1072
+ { className: 'dap-fieldCell' },
1073
+ h(SettingsValueField, {
1074
+ id: `dap-${model.id}-${key}`,
1075
+ label: t(copy.label),
1076
+ help: { label: t('fieldHelp', { field: t(copy.label) }), content: t(copy.hint) },
1077
+ hint: sourceOf(copy.source(model)),
1078
+ ...(copy.placeholder === undefined ? {} : { placeholder: copy.placeholder(model) }),
1079
+ ...(copy.numeric === true ? { numeric: true } : {}),
1080
+ text: draftOf(model)[key],
1081
+ overridden: declaredIn(model, key),
1082
+ // 只有容量那两项用 `1M`/`384K` 的词汇,因此也只有它们会「读不出来」;文本字段写什么都算数。
1083
+ invalid: copy.numeric === true && capacityBad(draftOf(model)[key]),
1084
+ overriddenLabel: t('overridden'),
1085
+ resetLabel: t('resetField'),
1086
+ invalidLabel: t('invalidField'),
1087
+ disabled: busy !== '',
1088
+ onEdit: (text) => stage(model, { [key]: text }),
1089
+ onReset: () => stage(model, { [key]: copy.cleared }),
1090
+ }),
1091
+ );
1053
1092
 
1054
- /**
1055
- * 一个模型的编辑面板:展开后才出现的全部字段,以及这一行的三个动作。
1056
- *
1057
- * 与官方那张卡片同一套形状——12px 圆角的面、`minmax(160px, 1fr)` 的参数栅格、
1058
- * 12px 的小标签,右对齐的动作行(危险动作在左、主按钮在右)。
1059
- *
1060
- * @param {object} model - 报告里的一个模型。
1061
- * @returns {object} 编辑面板。
1062
- */
1093
+ /** 一行模型的覆盖编辑器:只写这一行。 */
1063
1094
  const editor = (model) => {
1064
- const current = draftOf(model);
1065
- const overridden = model.override !== undefined && Object.keys(model.override).length > 0;
1066
- const { patch } = patchOf(current, initialOf(model));
1067
- const count = (value) => (value === undefined ? '—' : formatCount(value));
1068
- const modalities = model.input.length === 0
1069
- ? t('modalityNone')
1070
- : model.input.map((item) => t(item === 'image' ? 'modalityImage' : 'modalityText')).join('+');
1071
- const toggle = (name, id) => h(
1072
- 'label',
1073
- { className: 'dap-check', htmlFor: id },
1074
- h('input', {
1075
- id,
1076
- type: 'checkbox',
1077
- checked: current[name],
1078
- disabled: !configuration.writable,
1079
- onChange: (event) => edit(model, name, event.target.checked),
1080
- }),
1081
- t(name === 'text' ? 'modalityText' : 'modalityImage'),
1082
- );
1083
-
1095
+ const draft = draftOf(model);
1096
+ const overrides = model.overrideKeys ?? [];
1097
+ const changed = Object.keys(patchOf(draft, initialOf(model)).patch).length;
1098
+ // 界面认不得的键(`reasoningEfforts` 之类)只有「清空覆盖」撤得掉,而那是整条删,得先说清楚。
1099
+ const unknown = overrides.filter((key) => !EDITABLE_KEYS.includes(key));
1084
1100
  return h(
1085
1101
  'div',
1086
1102
  { className: 'dap-editor' },
1087
1103
  h(
1088
1104
  'div',
1089
- { className: 'dap-editor-head' },
1090
- h('code', { className: 'dap-editor-title dap-model-id' }, model.id),
1091
- h('span', { className: 'dap-editor-route' }, [
1092
- model.route === undefined ? t('unservedTag') : model.route,
1093
- model.protocol === undefined ? undefined : ` · ${model.protocol}`,
1094
- ].filter((part) => part !== undefined).join('')),
1105
+ { className: 'dap-editorHead' },
1106
+ h('span', { className: 'dap-editorId', title: model.id }, model.id),
1107
+ unknown.length === 0
1108
+ ? null
1109
+ : h(
1110
+ 'span',
1111
+ { className: 'dap-warnNote' },
1112
+ t('editUnknownOverrides', { keys: overrideKeyNames(unknown) }),
1113
+ ),
1114
+ dirtyOf(model)
1115
+ ? h(Tag, { tone: 'warning', className: 'dap-editorDirty' }, t('dirtyTag'))
1116
+ : null,
1095
1117
  ),
1096
1118
  h(
1097
1119
  'div',
1098
- { className: 'dap-fields' },
1099
- textField(model, 'name', t('editName'), {
1100
- placeholder: model.name,
1101
- // 输入框里显示的就是这个值,注脚只要说它从哪儿来。
1102
- note: t('sourceNote', { source: t(SOURCE_KEYS[model.provenance.name] ?? model.provenance.name) }),
1103
- }),
1104
- textField(model, 'alias', t('editAlias'), { placeholder: t('noAlias') }),
1105
- textField(model, 'contextWindow', t('editContextWindow'), {
1106
- numeric: true,
1107
- note: inEffect(count(model.contextWindow), model.provenance.limits),
1108
- }),
1109
- textField(model, 'maxTokens', t('editMaxTokens'), {
1110
- numeric: true,
1111
- note: inEffect(count(model.maxTokens), model.provenance.limits),
1112
- }),
1113
- field(
1114
- `dap-model-${model.id}-input`,
1115
- t('editInput'),
1116
- h(
1117
- 'div',
1118
- { className: 'dap-row' },
1119
- toggle('text', `dap-model-${model.id}-text`),
1120
- toggle('image', `dap-model-${model.id}-image`),
1121
- ),
1122
- inEffect(modalities, model.provenance.input),
1120
+ { className: 'dap-editGroup' },
1121
+ h('span', { className: 'dap-editGroupTitle' }, t('editGroupIdentity')),
1122
+ h(
1123
+ 'div',
1124
+ { className: 'dap-fields' },
1125
+ textField(model, 'name', {
1126
+ label: 'editName',
1127
+ hint: 'editNameHint',
1128
+ source: (item) => item.provenance.name,
1129
+ cleared: '',
1130
+ }),
1131
+ textField(model, 'alias', {
1132
+ label: 'editAlias',
1133
+ hint: 'editAliasHint',
1134
+ source: () => 'config',
1135
+ cleared: '',
1136
+ }),
1137
+ textField(model, 'api', {
1138
+ label: 'editApi',
1139
+ hint: 'editApiHint',
1140
+ // 协议没有单独一项来源:写过就是配置,没写过就是从通告的端点推导出来的。
1141
+ source: (item) => (declaredIn(item, 'api') ? 'config' : 'aperture'),
1142
+ cleared: '',
1143
+ placeholder: (item) => item.protocol ?? '',
1144
+ }),
1123
1145
  ),
1124
- field(
1125
- `dap-model-${model.id}-reasoning`,
1126
- t('editReasoning'),
1127
- h(
1128
- 'select',
1129
- {
1130
- id: `dap-model-${model.id}-reasoning`,
1131
- className: 'dap-input',
1132
- value: current.reasoning,
1133
- disabled: !configuration.writable,
1134
- onChange: (event) => edit(model, 'reasoning', event.target.value),
1135
- },
1136
- option('auto', t('optionAuto')),
1137
- option('on', t('optionOn')),
1138
- option('off', t('optionOff')),
1139
- ),
1140
- inEffect(model.reasoning ? t('optionOn') : t('optionOff'), model.provenance.reasoning),
1146
+ ),
1147
+ h(
1148
+ 'div',
1149
+ { className: 'dap-editGroup' },
1150
+ h('span', { className: 'dap-editGroupTitle' }, t('editGroupCapacity')),
1151
+ h(
1152
+ 'div',
1153
+ { className: 'dap-fields' },
1154
+ textField(model, 'contextWindow', {
1155
+ label: 'editContextWindow',
1156
+ hint: 'editCapacityHint',
1157
+ source: (item) => item.provenance.limits,
1158
+ cleared: '',
1159
+ numeric: true,
1160
+ // 清空之后回落到的就是发现到的那个数,摆在占位符里最省事。
1161
+ placeholder: (item) => formatCapacity(item.contextWindow),
1162
+ }),
1163
+ textField(model, 'maxTokens', {
1164
+ label: 'editMaxTokens',
1165
+ hint: 'editCapacityHint',
1166
+ source: (item) => item.provenance.limits,
1167
+ cleared: '',
1168
+ numeric: true,
1169
+ placeholder: (item) => formatCapacity(item.maxTokens),
1170
+ }),
1141
1171
  ),
1142
- field(
1143
- `dap-model-${model.id}-api`,
1144
- t('editApi'),
1172
+ ),
1173
+ // 模态与推理并排:它们都是「一个开关加一句话」,横着放比竖着叠省一半高度。
1174
+ h(
1175
+ 'div',
1176
+ { className: 'dap-grid2' },
1177
+ h(
1178
+ 'div',
1179
+ { className: 'dap-editGroup' },
1180
+ h('span', { className: 'dap-editGroupTitle' }, t('editInput')),
1145
1181
  h(
1146
- 'select',
1147
- {
1148
- id: `dap-model-${model.id}-api`,
1149
- className: 'dap-input',
1150
- value: current.api,
1151
- disabled: !configuration.writable,
1152
- onChange: (event) => edit(model, 'api', event.target.value),
1153
- },
1154
- option('', t('optionAuto')),
1155
- option('openai-completions', 'openai-completions'),
1156
- option('anthropic-messages', 'anthropic-messages'),
1182
+ 'div',
1183
+ { className: 'dap-control' },
1184
+ h(Checkbox, {
1185
+ checked: draft.text,
1186
+ onChange: (next) => stage(model, { text: next }),
1187
+ label: t('modalityText'),
1188
+ disabled: busy !== '',
1189
+ }),
1190
+ h(Checkbox, {
1191
+ checked: draft.image,
1192
+ onChange: (next) => stage(model, { image: next }),
1193
+ label: t('modalityImage'),
1194
+ disabled: busy !== '',
1195
+ }),
1196
+ overrides.includes('input') ? h(Tag, { tone: 'neutral' }, t('overridden')) : null,
1157
1197
  ),
1158
- // 协议是从通告的端点上推导出来的,没有来源可报,只说当前是哪一种。
1159
- inEffect(model.protocol ?? '—'),
1198
+ h('span', { className: 'dap-hint' }, sourceOf(model.provenance.input)),
1199
+ ),
1200
+ h(
1201
+ 'div',
1202
+ { className: 'dap-editGroup' },
1203
+ h('span', { className: 'dap-editGroupTitle' }, t('editReasoning')),
1204
+ h(SegmentedControl, {
1205
+ id: `dap-${model.id}-reasoning`,
1206
+ label: t('editReasoning'),
1207
+ value: draft.reasoning,
1208
+ options: [
1209
+ { value: 'auto', label: t('reasoningFollow') },
1210
+ { value: 'on', label: t('reasoningOn') },
1211
+ { value: 'off', label: t('reasoningOff') },
1212
+ ],
1213
+ onChange: (next) => stage(model, { reasoning: next }),
1214
+ disabled: busy !== '',
1215
+ }),
1216
+ h('span', { className: 'dap-hint' }, sourceOf(model.provenance.reasoning)),
1160
1217
  ),
1161
1218
  ),
1162
- h('p', { className: 'dap-field-note' }, t('editHint')),
1163
- model.route === undefined ? h('p', { className: 'dap-field-note' }, t('unservedHint')) : null,
1219
+ model.endpoints.length === 0
1220
+ ? null
1221
+ : h(
1222
+ 'div',
1223
+ { className: 'dap-endpoints' },
1224
+ h('span', { className: 'dap-editGroupTitle' }, t('factEndpoints')),
1225
+ h(
1226
+ 'ul',
1227
+ { className: 'dap-endpointList' },
1228
+ model.endpoints.map((endpoint) => h(
1229
+ 'li',
1230
+ { className: 'dap-endpoint', key: endpoint },
1231
+ endpoint,
1232
+ )),
1233
+ ),
1234
+ ),
1164
1235
  h(
1165
1236
  'div',
1166
- { className: 'dap-actions', 'data-align': 'end' },
1167
- overridden
1168
- ? h('button', {
1169
- id: `dap-model-${model.id}-revert`,
1170
- type: 'button',
1171
- className: 'dap-button',
1172
- 'data-danger': 'true',
1173
- disabled: disabled,
1174
- onClick: () => clearOverrides(model),
1175
- }, busy === 'revert' ? t('saving') : t('reset'))
1176
- : null,
1177
- h('button', {
1178
- id: `dap-model-${model.id}-cancel`,
1179
- type: 'button',
1180
- className: 'dap-button',
1237
+ { className: 'dap-actions' },
1238
+ h('span', { className: 'dap-actionsNote' }, changed === 0
1239
+ ? t('noPendingChanges')
1240
+ : t('pendingChanges', { count: changed })),
1241
+ h(Button, {
1242
+ variant: 'ghost',
1243
+ size: 'sm',
1244
+ onClick: () => cancelRow(model),
1181
1245
  disabled: busy !== '',
1182
- onClick: () => cancel(model),
1183
- }, t('cancel')),
1184
- h('button', {
1185
- id: `dap-model-${model.id}-save`,
1186
- type: 'button',
1187
- className: 'dap-button',
1188
- 'data-primary': 'true',
1189
- // 没改动就没什么可保存的(官方那张卡片的「应用」也是这样)。
1190
- disabled: disabled || Object.keys(patch).length === 0,
1191
- onClick: () => submit(model),
1192
- }, busy === 'edit' ? t('saving') : t('save')),
1246
+ }, t('cancelRow')),
1247
+ overrides.length === 0
1248
+ ? null
1249
+ : h(Button, {
1250
+ variant: 'outline',
1251
+ size: 'sm',
1252
+ onClick: () => clearOverrides(model),
1253
+ disabled: busy !== '',
1254
+ }, t('clearOverrides')),
1255
+ h(Button, {
1256
+ variant: 'primary',
1257
+ size: 'sm',
1258
+ onClick: () => submitRow(model),
1259
+ disabled: busy !== '',
1260
+ }, busy === 'edit' ? t('saving') : t('saveRow')),
1193
1261
  ),
1194
1262
  );
1195
1263
  };
1196
1264
 
1197
- /** 一个模型一行:收起时只有 id、标签与生效的事实,点「编辑」才展开面板。 */
1265
+ /**
1266
+ * 一行模型:折起来是身份与状态,展开是这一行的覆盖编辑器。
1267
+ *
1268
+ * 行首那条按钮盖满整行(官方 `DisclosureRow` 是一根 24px 高、`overflow:hidden` 的横条,标题又
1269
+ * 不许收缩,名字一长就把右边的事实和标签挤没了)。这里名字自己一行、过长省略,事实另起一行随
1270
+ * 宽度换行,标签跟在名字后面。
1271
+ */
1198
1272
  const modelRow = (model) => {
1199
- const { patch } = patchOf(draftOf(model), initialOf(model));
1200
- const overridden = model.override !== undefined && Object.keys(model.override).length > 0;
1201
1273
  const open = opened[model.id] === true;
1202
-
1274
+ const overrides = model.overrideKeys ?? [];
1275
+ const status = publishState(model);
1203
1276
  return h(
1204
1277
  'li',
1205
- { className: 'dap-model', key: model.id },
1278
+ { key: model.id, className: 'dap-card' },
1206
1279
  h(
1207
- 'div',
1208
- { className: 'dap-model-head' },
1280
+ 'button',
1281
+ {
1282
+ type: 'button',
1283
+ className: 'dap-cardHead',
1284
+ 'aria-expanded': open ? 'true' : 'false',
1285
+ onClick: () => toggleRow(model),
1286
+ },
1209
1287
  h(
1210
1288
  'span',
1211
- { className: 'dap-model-identity' },
1212
- h('code', { className: 'dap-model-id' }, model.id),
1213
- model.name === model.id ? null : h('span', { className: 'dap-model-name' }, model.name),
1289
+ { className: 'dap-status', role: 'img', 'aria-label': status.title, title: status.title },
1290
+ h(StateDot, { state: status.state, size: 10 }),
1214
1291
  ),
1215
- overridden ? h('span', { className: 'dap-tag' }, t('overridden')) : null,
1216
- model.route === undefined ? h('span', { className: 'dap-tag' }, t('unservedTag')) : null,
1217
- Object.keys(patch).length > 0 ? h('span', { className: 'dap-tag' }, t('pendingTag')) : null,
1218
1292
  h(
1219
1293
  'span',
1220
- { className: 'dap-model-actions' },
1221
- h('button', {
1222
- id: `dap-model-${model.id}-toggle`,
1223
- type: 'button',
1224
- className: 'dap-button',
1225
- 'aria-label': t('edit'),
1226
- 'aria-expanded': open ? 'true' : 'false',
1227
- disabled: busy !== '',
1228
- onClick: () => setOpened((state) => ({ ...state, [model.id]: !open })),
1229
- }, chevron(open), open ? t('advancedHide') : t('edit')),
1294
+ { className: 'dap-identity' },
1295
+ h(
1296
+ 'span',
1297
+ { className: 'dap-identityTop' },
1298
+ h('span', { className: 'dap-name', title: model.name }, model.name),
1299
+ model.route === undefined ? h(Tag, { tone: 'warning' }, t('unservedTag')) : null,
1300
+ overrides.length === 0
1301
+ ? null
1302
+ : h(
1303
+ // 这一层只为挂 `title`:官方 `Tag` 除了 tone/className/children 什么都不透传,
1304
+ // 想让人 hover 看出「覆盖的是哪几项」就得自己在外面套一层。
1305
+ 'span',
1306
+ { className: 'dap-tagWrap', title: overrideKeyNames(overrides) },
1307
+ h(Tag, { tone: 'neutral' }, t('overriddenCount', { count: overrides.length })),
1308
+ ),
1309
+ dirtyOf(model) ? h(Tag, { tone: 'warning' }, t('dirtyTag')) : null,
1310
+ ),
1311
+ h(
1312
+ 'span',
1313
+ { className: 'dap-factRow' },
1314
+ factItems(model).map((item, index) => h(
1315
+ 'span',
1316
+ { className: 'dap-factItem', key: `${model.id}-fact-${String(index)}` },
1317
+ item,
1318
+ )),
1319
+ ),
1320
+ ),
1321
+ h(
1322
+ 'span',
1323
+ { className: 'dap-chevron', 'data-open': open ? 'true' : 'false' },
1324
+ h(IconChevronRightOutlineRegular, { size: 14 }),
1230
1325
  ),
1231
1326
  ),
1232
- h('div', { className: 'dap-model-facts' }, modelFacts(model)),
1233
- model.route === undefined
1234
- ? h('p', { className: 'dap-model-meta' }, t('unservedEndpoints', {
1235
- list: model.endpoints.length === 0 ? t('noEndpoints') : model.endpoints.join(', '),
1236
- }))
1237
- : null,
1238
1327
  open ? editor(model) : null,
1239
1328
  );
1240
1329
  };
1241
1330
 
1242
- /** 一条路由的分组头:`provider · 协议` 一行,`→ 地址 · N 个模型` 一行。 */
1243
- const groupHead = (title, meta) => h(
1244
- 'div',
1245
- { className: 'dap-group-head' },
1246
- h('span', { className: 'dap-group-title' }, title),
1247
- h('span', { className: 'dap-group-meta' }, meta),
1248
- );
1249
-
1250
1331
  /**
1251
- * 模型清单:先按路由分组,最后是没有任何路由能服务的那些。
1252
- *
1253
- * 头部只说一句「已覆盖几个,其余沿用发现值与清单」(官方「模型」卡片左半边那句);
1254
- * 右边没有官方的「撤销全部覆盖」——这里按行改,撤销也按行做,一次管一整份清单的动作
1255
- * 没有对应场景。
1332
+ * 这一轮哪里不对:清单读不到、或者该写的东西没写进去。
1256
1333
  *
1257
- * 每一行收起时只是一条事实,点「编辑」才展开面板:报告是这张标签页的主要用途,不该被
1258
- * 一地输入框淹掉。
1259
- *
1260
- * @param {object} current - 报告。
1261
- * @returns {object} 模型段。
1334
+ * 「发现报告」那一块删掉之后,这些原本只写在报告事实表里的话得有地方落脚——否则清单挂了的时候,
1335
+ * 用户看到的就只是「还没有发现任何模型」,没有任何理由。刷新整个失败(`ok: false`)不在这里说:
1336
+ * 那句话由 `run()` 贴到提示语上,比这里更显眼。正常的一轮(同步关着 / 同步成功)什么都不说。
1262
1337
  */
1263
- const modelList = (current) => {
1264
- const overridden = current.models.filter(
1265
- (model) => model.override !== undefined && Object.keys(model.override).length > 0,
1266
- );
1267
-
1268
- const head = h(
1269
- 'div',
1270
- { className: 'dap-row' },
1271
- h(
1272
- 'div',
1273
- { className: 'dap-head' },
1274
- h('div', { className: 'dap-title' }, t('modelsHeading')),
1275
- h('p', { className: 'dap-hint' }, overridden.length === 0
1276
- ? t('modelsMetaInherit')
1277
- : t('modelsMetaOverride', { count: overridden.length })),
1278
- ),
1279
- );
1280
-
1281
- if (current.models.length === 0) {
1282
- return [
1283
- head,
1284
- h('p', { className: 'dap-hint' }, current.refresh !== undefined && current.refresh.error !== undefined
1285
- ? t('modelsError', { error: current.refresh.error })
1286
- : t('noModels')),
1287
- ];
1338
+ const roundProblem = (current) => {
1339
+ const refresh = current === null ? undefined : current.refresh;
1340
+ if (refresh === undefined) return null;
1341
+ if (!refresh.catalog.available) {
1342
+ return t('catalogUnavailable', { reason: refresh.catalog.reason ?? '—' });
1288
1343
  }
1289
-
1290
- const groups = [];
1291
- for (const route of current.routes) {
1292
- const models = current.models.filter((model) => model.route === route.provider);
1293
- if (models.length === 0) continue;
1294
- const title = route.api === undefined ? route.provider : `${route.provider} · ${route.api}`;
1295
- const meta = [
1296
- route.baseURL === undefined ? undefined : `→ ${route.baseURL}`,
1297
- t('modelsCount', { count: models.length }),
1298
- ].filter((part) => part !== undefined).join(' · ');
1299
- groups.push(h(
1300
- 'div',
1301
- { className: 'dap-group', key: route.provider },
1302
- groupHead(title, meta),
1303
- h('ul', { className: 'dap-models' }, models.map(modelRow)),
1304
- ));
1305
- }
1306
- const unserved = current.models.filter((model) => model.route === undefined);
1307
- if (unserved.length > 0) {
1308
- groups.push(h(
1309
- 'div',
1310
- { className: 'dap-group', key: 'unserved' },
1311
- groupHead(t('unservedHeading'), t('modelsCount', { count: unserved.length })),
1312
- h('ul', { className: 'dap-models' }, unserved.map(modelRow)),
1313
- ));
1344
+ if (refresh.sync !== undefined && !refresh.sync.applied) {
1345
+ return t('syncSkipped', { reason: refresh.sync.reason ?? '—' });
1314
1346
  }
1315
-
1316
- return [head, groups];
1347
+ return null;
1317
1348
  };
1318
1349
 
1350
+ const controlsDisabled = !state.available || !state.writable;
1351
+ const problem = roundProblem(report);
1352
+
1319
1353
  return h(
1320
1354
  'div',
1321
- { [STYLE_MARK]: '', 'aria-busy': busy !== '' ? 'true' : 'false' },
1322
- h(
1323
- 'div',
1324
- null,
1325
- h('div', { className: 'dap-title' }, t('title')),
1326
- h('p', { className: 'dap-subtitle' }, dormant ? t('addressDormant') : t('subtitle')),
1327
- ),
1328
-
1355
+ { 'data-dsh-aperture': '' },
1329
1356
  h(
1330
- 'div',
1331
- { className: 'dap-section' },
1332
- h(
1333
- 'div',
1334
- { className: 'dap-row' },
1335
- h('label', { className: 'dap-label', htmlFor: 'dap-base-url' }, t('addressLabel')),
1336
- h('input', {
1337
- id: 'dap-base-url',
1338
- className: 'dap-input',
1339
- type: 'text',
1340
- spellCheck: false,
1341
- autoComplete: 'off',
1342
- placeholder: t('addressPlaceholder'),
1343
- value: draft.baseUrl,
1344
- disabled,
1345
- onChange: (event) => setDraft({ baseUrl: event.target.value, sync: draft.sync }),
1346
- }),
1347
- configuration.baseUrlOverridden
1348
- ? h('span', { className: 'dap-tag' }, t('overridden'))
1349
- : null,
1350
- configuration.baseUrlOverridden
1351
- ? h('button', {
1352
- type: 'button',
1353
- className: 'dap-button',
1354
- disabled,
1355
- onClick: () => run('reset', () => panel.save(null, undefined), () => setConfigRevision((value) => value + 1)),
1356
- }, t('reset'))
1357
- : null,
1358
- ),
1357
+ SettingsForm,
1358
+ {
1359
+ labels: {
1360
+ unavailable: t('unavailable'),
1361
+ readOnly: t('readOnly'),
1362
+ saveFailed: t('saveFailed'),
1363
+ save: t('save'),
1364
+ saving: t('saving'),
1365
+ },
1366
+ state,
1367
+ onSave: saveSettings,
1368
+ onDiscard: props.discard,
1369
+ },
1370
+ h(SettingsValueField, {
1371
+ id: 'dap-base-url',
1372
+ label: t('addressLabel'),
1373
+ hint: t('addressHint'),
1374
+ placeholder: t('addressPlaceholder'),
1375
+ text: state.baseUrl.text,
1376
+ overridden: state.baseUrl.overridden,
1377
+ invalid: state.baseUrl.invalid,
1378
+ overriddenLabel: t('overridden'),
1379
+ resetLabel: t('resetField'),
1380
+ invalidLabel: t('invalidField'),
1381
+ disabled: controlsDisabled || state.saving,
1382
+ onEdit: (text) => props.edit('baseUrl', text),
1383
+ onReset: () => props.resetField('baseUrl'),
1384
+ }),
1359
1385
  h(
1360
1386
  'div',
1361
- { className: 'dap-row' },
1387
+ { className: 'dap-toggleRow' },
1362
1388
  h(
1363
- 'label',
1364
- { className: 'dap-check', htmlFor: 'dap-sync' },
1365
- h('input', {
1366
- id: 'dap-sync',
1367
- type: 'checkbox',
1368
- checked: draft.sync,
1369
- disabled,
1370
- onChange: (event) => setDraft({ baseUrl: draft.baseUrl, sync: event.target.checked }),
1371
- }),
1372
- t('syncLabel'),
1389
+ 'div',
1390
+ { className: 'dap-toggleText' },
1391
+ h('span', null, t('syncLabel')),
1392
+ h('span', { className: 'dap-hint' }, t('syncHint')),
1373
1393
  ),
1374
- h('span', { className: 'dap-tag' }, draft.sync ? t('syncOn') : t('syncOff')),
1375
- configuration.syncOverridden
1376
- ? h('span', { className: 'dap-tag' }, t('overridden'))
1377
- : null,
1378
- ),
1379
- configuration.writable ? null : h('p', { className: 'dap-banner', 'data-ok': 'false' }, t('readOnly')),
1380
- h(
1381
- 'div',
1382
- { className: 'dap-actions' },
1383
- h('button', {
1384
- type: 'button',
1385
- className: 'dap-button',
1386
- 'data-primary': 'true',
1387
- disabled: disabled || !dirty,
1388
- onClick: () => run('save', () => panel.save(draft.baseUrl, draft.sync), () => {
1389
- setConfigRevision((value) => value + 1);
1390
- setReportRevision((value) => value + 1);
1394
+ h(
1395
+ 'div',
1396
+ { className: 'dap-inline' },
1397
+ state.sync.overridden
1398
+ ? h(Tag, { tone: 'info' }, t('overridden'))
1399
+ : null,
1400
+ state.sync.overridden
1401
+ ? h(Button, {
1402
+ variant: 'ghost',
1403
+ size: 'sm',
1404
+ onClick: () => props.resetField('sync'),
1405
+ disabled: controlsDisabled || state.saving,
1406
+ }, t('resetField'))
1407
+ : null,
1408
+ h(Switch, {
1409
+ checked: state.sync.text === 'true',
1410
+ onChange: (next) => props.edit('sync', next ? 'true' : 'false'),
1411
+ label: t('syncLabel'),
1412
+ disabled: controlsDisabled || state.saving,
1391
1413
  }),
1392
- }, busy === 'save' ? t('saving') : t('save')),
1393
- h('button', {
1394
- type: 'button',
1395
- className: 'dap-button',
1396
- disabled: busy !== '' || !dirty,
1397
- onClick: () => setDraft({ baseUrl: configuration.baseUrl, sync: configuration.sync }),
1398
- }, t('cancel')),
1414
+ ),
1399
1415
  ),
1400
1416
  ),
1401
-
1417
+ banner === null
1418
+ ? null
1419
+ : h('p', {
1420
+ className: 'dap-banner',
1421
+ 'data-ok': banner.ok ? 'true' : 'false',
1422
+ role: 'status',
1423
+ 'aria-live': 'polite',
1424
+ }, banner.text),
1402
1425
  h(
1403
- 'div',
1404
- { className: 'dap-section' },
1426
+ 'section',
1427
+ { className: 'dap-group' },
1405
1428
  h(
1406
1429
  'div',
1407
- { className: 'dap-actions' },
1408
- h('button', {
1409
- type: 'button',
1410
- className: 'dap-button',
1411
- disabled,
1412
- onClick: () => run('refresh', () => panel.refresh(), () => setReportRevision((value) => value + 1)),
1430
+ { className: 'dap-groupHead' },
1431
+ h(
1432
+ 'span',
1433
+ { className: 'dap-titleWrap' },
1434
+ h('h3', { className: 'dap-groupTitle' }, t('modelsTitle')),
1435
+ report === null
1436
+ ? null
1437
+ : h('span', { className: 'dap-count' }, t('modelsCount', { count: report.models.length })),
1438
+ ),
1439
+ h(Button, {
1440
+ variant: 'ghost',
1441
+ size: 'sm',
1442
+ icon: h(IconRefreshOutlineRegular, { size: 14 }),
1443
+ onClick: refreshReport,
1444
+ disabled: busy !== '',
1445
+ title: t('refreshHint'),
1413
1446
  }, busy === 'refresh' ? t('refreshing') : t('refresh')),
1414
- h('button', {
1415
- type: 'button',
1416
- className: 'dap-button',
1417
- disabled,
1418
- onClick: () => run('withdraw', () => panel.withdraw(), () => setReportRevision((value) => value + 1)),
1419
- }, busy === 'withdraw' ? t('withdrawing') : t('withdraw')),
1420
1447
  ),
1421
- banner === null
1422
- ? null
1423
- : h('p', { className: 'dap-banner', 'data-ok': banner.ok ? 'true' : 'false' }, banner.text),
1448
+ h('p', { className: 'dap-hint' }, t('modelsHint')),
1449
+ problem === null ? null : h('p', { className: 'dap-warnNote' }, problem),
1424
1450
  report === null
1425
- ? null
1426
- : h('p', { className: 'dap-hint' }, `Aperture:${report.place.length === 0 ? t('noAddress') : report.place}`),
1451
+ ? h('p', { className: 'dap-hint' }, t('loading'))
1452
+ : report.models.length === 0
1453
+ // 没有实例地址时发现根本不会跑,这时说「还没发现到模型」等于没说——那句话要说清为什么。
1454
+ // 只在设置读得到的时候这么说:读不到时地址存不存在都不知道,那是另一件事(表单自己会说)。
1455
+ ? h(
1456
+ 'p',
1457
+ { className: 'dap-empty' },
1458
+ state.available && state.baseUrl.text === '' ? t('dormantHint') : t('noModels'),
1459
+ )
1460
+ : h('ul', { className: 'dap-rows' }, report.models.map(modelRow)),
1427
1461
  ),
1428
-
1429
- report === null
1430
- ? null
1431
- : h(
1432
- 'div',
1433
- { className: 'dap-section' },
1434
- h('div', { className: 'dap-title' }, t('statusHeading')),
1435
- statusFacts(report),
1436
- ),
1437
-
1438
- report === null
1439
- ? null
1440
- : h('div', { className: 'dap-section' }, modelList(report)),
1441
1462
  );
1442
1463
  }
1443
1464
 
@@ -1446,9 +1467,8 @@ window.__ModuleLoader__.load({
1446
1467
  /**
1447
1468
  * 把 `aperturePanel` 贡献挂到客户端的 Remote 服务上。
1448
1469
  *
1449
- * `apply` 必须保持同步:宿主 Cordis 会卸载 async apply 里 `await` 之后注册的
1450
- * `ctx.effect`。因此异步的 `$mount` 在一个**同步注册**的 effect 工厂内部完成,失败
1451
- * 落 console.error。
1470
+ * `apply` 必须保持同步:宿主 Cordis 会卸载 async apply 里 `await` 之后注册的 `ctx.effect`。
1471
+ * 因此异步的 `$mount` 在一个**同步注册**的 effect 工厂内部完成,失败落 console.error。
1452
1472
  *
1453
1473
  * @param {object} ctx - 客户端根上下文。
1454
1474
  */
@@ -1474,10 +1494,14 @@ window.__ModuleLoader__.load({
1474
1494
  }
1475
1495
 
1476
1496
  /**
1477
- * 浏览器插件主体:字典、样式、Remote 贡献,以及插件标签页。
1497
+ * 浏览器插件主体:字典、样式、Remote 贡献,以及「插件」页里本插件那个包页的配置页。
1478
1498
  *
1479
- * `ctx.slots.inject` 是必需的,不是可选的:`settings.plugins.tab` 由设置区自己声明,
1480
- * 那个声明完全可能在本插件 `apply` 之后才发生,直接 register 会撞上「槽位尚未声明」。
1499
+ * `ctx.slots.inject` 是必需的,不是可选的:`plugins.bundle.config` 由插件管理页自己声明,那个
1500
+ * 声明完全可能在本插件 `apply` 之后才发生,直接 register 会撞上「槽位尚未声明」。
1501
+ *
1502
+ * 注册的键是**包名**:键控槽位按它找贡献,点开插件列表里的本插件就是这一页。设置那一份表单也
1503
+ * 在这里取——页主只递 `view`,`configForms.get(命名空间)` 才是这一页的配置读写面;服务按命名
1504
+ * 空间缓存控制器,因此它与插件页自己取到的是同一份。
1481
1505
  *
1482
1506
  * @param {object} ctx - 客户端根上下文。
1483
1507
  */
@@ -1492,29 +1516,49 @@ window.__ModuleLoader__.load({
1492
1516
  const panel = {
1493
1517
  status: async () => unwrap(await namespace().status()),
1494
1518
  refresh: async () => unwrap(await namespace().refresh()),
1495
- withdraw: async () => unwrap(await namespace().withdraw()),
1496
- configuration: async () => unwrap(await namespace().configuration()),
1497
- save: async (baseUrl, sync) => unwrap(await namespace().save(baseUrl, sync)),
1498
- edit: async (id, patch) => unwrap(await namespace().edit(id, patch)),
1519
+ writeModel: async (id, patch) => unwrap(await namespace().edit(id, patch)),
1499
1520
  };
1500
- scope.slots.inject('settings.plugins.tab', () => scope.slots.register({
1501
- name: 'settings.plugins.tab',
1502
- id: 'aperture',
1503
- order: 40,
1504
- label: () => t('tab'),
1521
+
1522
+ // 官方设置表单那一套:这一份模型负责草稿、`revision` 围栏与「哪些字段已覆盖」,页面只读
1523
+ // 它的投影。表单自己订阅控制器,因此设置一变,投影就会变新。
1524
+ const controller = ctx.configForms === undefined ? UNSERVED : ctx.configForms.get(SETTINGS_NS);
1525
+ const form = new SettingsFormModel(controller, [settingsTextField('baseUrl'), booleanField('sync')]);
1526
+ const actions = form.actions();
1527
+ const card = form.bind(() => ({
1528
+ ...form.shell(),
1529
+ baseUrl: form.field('baseUrl'),
1530
+ sync: form.field('sync'),
1531
+ }));
1532
+ scope.effect(() => () => form.dispose(), 'dsh-aperture: settings form');
1533
+
1534
+ scope.slots.inject('plugins.bundle.config', () => scope.slots.register({
1535
+ name: 'plugins.bundle.config',
1536
+ key: PACKAGE,
1505
1537
  locale: NS,
1506
- inject: () => ({ panel }),
1507
- }, ApertureTab));
1538
+ inject: () => ({
1539
+ hooks: { apertureCard: card },
1540
+ panel,
1541
+ edit: actions.edit,
1542
+ resetField: actions.resetField,
1543
+ discard: actions.discard,
1544
+ save: () => form.save(),
1545
+ failed: () => form.shell().failed,
1546
+ }),
1547
+ }, AperturePanel));
1508
1548
  });
1509
1549
  }
1510
1550
 
1511
1551
  const module = { exports: {} };
1512
1552
  module.exports.name = PACKAGE;
1513
- /** 本插件依赖的客户端服务:槽位、字典与 Remote 调用面。 */
1514
- module.exports.inject = ['slots', 'locale', 'remote'];
1553
+ /** 本插件依赖的客户端服务:槽位、字典、Remote 调用面,以及设置接缝的配置表单。 */
1554
+ module.exports.inject = ['slots', 'locale', 'remote', 'configForms'];
1515
1555
  module.exports.apply = apply;
1516
1556
  /** 字典命名空间(测试与排查用)。 */
1517
1557
  module.exports.NS = NS;
1558
+ /** 设置命名空间,也是包级配置页这一份表单的键(测试与排查用)。 */
1559
+ module.exports.SETTINGS_NS = SETTINGS_NS;
1560
+ /** 这一页自己编辑的字段(测试与排查用)。 */
1561
+ module.exports.FIELDS = FIELDS;
1518
1562
  /** 上报给 Remote 注册表的贡献(测试与排查用)。 */
1519
1563
  module.exports.REMOTE = REMOTE;
1520
1564
  return module.exports;