@qzsy/dsh-image-generation 0.1.3 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.js CHANGED
@@ -1,313 +1,468 @@
1
1
  /**
2
- * dsh-image-generation — Client half.
2
+ * Client half of `@qzsy/dsh-image-generation`.
3
3
  *
4
- * - Settings → 生图配置: add/edit image providers and their models
5
- * - Settings → 插件 → 插件配置 → 图形生成: pick the single model the tool uses
6
- * - tool.call.toolview for image_generate: inline gallery
4
+ * Three surfaces share this one bundle:
5
+ *
6
+ * - Settings → Image generation: the provider catalog. A provider is a Base
7
+ * URL, one API format, a credential reference and a list of models. The key
8
+ * itself never enters the config file; it is written through the credentials
9
+ * service under the provider's reference.
10
+ * - Settings → Plugins → Plugin configuration → Image generation: the single
11
+ * active model plus the tool's default size and quality. This card is keyed
12
+ * by the bundle package name, because that is what the Plugins page
13
+ * dispatches.
14
+ * - the `image_generate` tool view: generated images inline at 240px with a
15
+ * full-screen lightbox.
16
+ *
17
+ * The Host half is the only part that talks to a provider or writes bytes. This
18
+ * half asks it for image data over the package-private `/image-gen` RPC channel
19
+ * and renders a data URL. That split is why the settings card can run in the
20
+ * browser while the API key stays on the host.
21
+ *
22
+ * Configuration is read from whichever settings surface the running DSH has:
23
+ * `configForms` on 0.1.6+, `settingsScope` on 0.1.5 and older. Both adapters
24
+ * expose the same `getSnapshot/subscribe/mutate` shape, so the cards below do
25
+ * not carry version branches.
7
26
  */
8
27
  window.__ModuleLoader__.load({
9
28
  id: '@qzsy/dsh-image-generation',
10
- factory: (require) => {
11
- var module = { exports: {} }
12
- var exports = module.exports
13
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
14
-
15
- const React = require('react')
16
- const primitives = require('@deepseek-ai/dsh-client-ui-primitives')
17
- // Icon exports were renamed in DSH 0.1.7 (size suffix dropped in favor of
18
- // Regular/Medium weights); resolve whichever name this runtime exports.
19
- const pickIcon = (...names) => names.map((n) => primitives[n]).find((v) => typeof v === 'function')
20
- const IconTrash = pickIcon('IconTrashOutline16', 'IconTrashOutlineRegular', 'IconTrashOutlineMedium')
21
- const IconClose = pickIcon('IconCloseOutline16', 'IconCloseOutlineRegular', 'IconCloseOutlineMedium')
22
- const IconPlus = pickIcon('IconPlusOutline16', 'IconPlusOutlineRegular', 'IconPlusOutlineMedium')
23
- const IconChevronDown = pickIcon('IconChevronDownOutline14', 'IconChevronDownOutlineRegular', 'IconChevronDownOutlineMedium')
24
- const IconChevronUp = pickIcon('IconChevronUpOutline14', 'IconChevronUpOutlineRegular', 'IconChevronUpOutlineMedium')
25
- const IconSparkle = pickIcon('IconSparkle16', 'IconSparkleRegular', 'IconSparkleMedium')
26
- const Menu = primitives.Menu
27
-
28
- const SELECT_CSS = '.dsh-ig-select{box-sizing:border-box;background:var(--dsw-alias-bg-module-platform);height:36px;font:inherit;color:var(--dsw-alias-label-primary);cursor:pointer;border:none;border-radius:18px;align-items:center;gap:12px;padding:0 14px;font-size:14px;line-height:22px;display:inline-flex;max-width:min(100%,280px)}.dsh-ig-select:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover)}.dsh-ig-select:disabled{opacity:.5;cursor:default}.dsh-ig-select-label{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}'
29
+ factory(require) {
30
+ const React = require('react');
31
+ const primitives = require('@deepseek-ai/dsh-client-ui-primitives');
32
+ const h = React.createElement;
33
+ const { useCallback, useEffect, useMemo, useRef, useState } = React;
29
34
 
30
- function ensureSelectCss() {
31
- if (typeof document === 'undefined') return
32
- if (document.querySelector('style[data-plugin-css="dsh-image-generation-select"]')) return
33
- const tag = document.createElement('style')
34
- tag.dataset.plugin = 'dsh-image-generation'
35
- tag.dataset.pluginCss = 'dsh-image-generation-select'
36
- tag.textContent = SELECT_CSS
37
- document.head.appendChild(tag)
38
- }
35
+ /** Locale namespace owned by this plugin. */
36
+ const NS = 'imageGen';
37
+ /** Config entry id shared with the Host half. */
38
+ const CATALOG_NS = 'image-gen';
39
+ /** Legacy (DSH <= 0.1.5) namespace that held only the picker. */
40
+ const RUNTIME_NS = 'image-gen-runtime';
41
+ /** Package-private Host channel. */
42
+ const RPC_CHANNEL = '/image-gen';
43
+ const TOOL_NAME = 'image_generate';
44
+ const STYLE_ATTR = 'data-plugin-css';
45
+ const STYLE_ID = 'dsh-image-generation';
46
+ const DEFAULT_SIZE = '1024x1024';
47
+ const DEFAULT_QUALITY = 'auto';
48
+ const SIZES = ['1024x1024', '1024x1536', '1536x1024', 'auto'];
49
+ const QUALITIES = ['low', 'medium', 'high', 'auto'];
50
+ const MAX_REFERENCES = 5;
39
51
 
40
- const CATALOG_NS = 'image-gen'
41
- const RUNTIME_NS = 'image-gen-runtime'
42
- const LOCALE_NS = 'settings.image-gen'
43
- const RPC_CHANNEL = '/image-gen'
52
+ /**
53
+ * Icon exports were renamed across DSH releases (size suffix vs.
54
+ * Regular/Medium weight). Resolve whichever name this runtime ships, and
55
+ * degrade to text if none of them exist.
56
+ */
57
+ const pickIcon = (...names) => names.map((name) => primitives[name]).find((value) => typeof value === 'function');
58
+ const IconTrash = pickIcon('IconTrashOutline16', 'IconTrashOutlineRegular', 'IconTrashOutlineMedium');
59
+ const IconClose = pickIcon('IconCloseOutline16', 'IconCloseOutlineRegular', 'IconCloseOutlineMedium');
60
+ const IconPlus = pickIcon('IconPlusOutline16', 'IconPlusOutlineRegular', 'IconPlusOutlineMedium');
61
+ const IconChevronDown = pickIcon('IconChevronDownOutline14', 'IconChevronDownOutlineRegular', 'IconChevronDownOutlineMedium');
62
+ const IconChevronUp = pickIcon('IconChevronUpOutline14', 'IconChevronUpOutlineRegular', 'IconChevronUpOutlineMedium');
63
+ const IconSparkle = pickIcon('IconSparkle16', 'IconSparkleRegular', 'IconSparkleMedium');
64
+ const Menu = primitives.Menu;
44
65
 
45
66
  const API_FORMATS = [
46
- { id: 'openai-images', label: 'OpenAI Images (/v1/images/generations)', hint: 'gpt-image-2、DALL·E、以及兼容 OpenAI Images 的网关' },
47
- { id: 'xai-images', label: 'xAI Images (/v1/images/generations)', hint: 'grok-imagine-image-2.0,使用 aspect_ratio' },
48
- { id: 'gemini-image', label: 'Gemini / Imagen (generateContent / predict)', hint: 'gemini-*-image、imagen-*;官方需 generativelanguage.googleapis.com' },
49
- { id: 'openai-chat-image', label: 'OpenAI Chat Completions (/v1/chat/completions)', hint: '在对话响应中返回图片的模型(部分聚合网关)' },
50
- ]
51
-
52
- const en = {
53
- nav: 'Image generation',
54
- title: 'Image generation',
55
- intro: 'Add image providers and models here. Then pick one model under Settings → Plugins → Plugin configuration → Image generation. Conversations call image_generate with that model.',
56
- addProvider: 'Add provider',
57
- providerName: 'Name',
58
- baseUrl: 'Base URL',
59
- apiFormat: 'API format',
60
- apiKey: 'API Key',
61
- apiKeyPlaceholder: 'Enter an API key, or leave blank to keep the stored one',
62
- apiKeySet: 'Configured',
63
- apiKeyUnset: 'Not configured',
64
- models: 'Models',
65
- addModel: 'Add model',
66
- modelId: 'Model ID',
67
- modelName: 'Display name',
68
- save: 'Save',
69
- saving: 'Saving…',
70
- saved: 'Saved.',
71
- cancel: 'Cancel',
72
- delete: 'Delete',
73
- edit: 'Edit',
74
- empty: 'No image providers yet. Add one to get started.',
75
- loadFailed: 'Could not load image-generation settings.',
76
- retry: 'Retry',
77
- readOnly: 'Settings are read-only in this deployment.',
78
- nameRequired: 'Provider name is required.',
79
- baseUrlRequired: 'Base URL is required.',
80
- modelRequired: 'Add at least one model, or delete unused rows.',
81
- modelIdRequired: 'Model ID is required.',
82
- modelIdDuplicate: 'Model IDs must be unique.',
83
- conflict: 'Settings changed elsewhere. Reopen this card and try again.',
84
- saveFailed: 'The deployment did not accept these values.',
85
- cardTitle: 'Image generation',
86
- cardDescription: 'Choose the single model conversations use for image_generate.',
87
- enabled: 'Enable image_generate',
88
- enabledHint: 'When off, the tool refuses until you turn it back on.',
89
- pickModel: 'Active model',
90
- pickHint: 'Only one model can be active. Configure providers under Image generation in the sidebar.',
91
- noModels: 'No models yet. Add providers under Settings → Image generation first.',
92
- expand: 'Expand',
93
- collapse: 'Collapse',
94
- discard: 'Discard',
95
- unsaved: 'Unsaved',
96
- generating: 'Generating…',
97
- image: 'Image',
98
- viewImage: 'View image',
99
- viewImageNamed: 'View {name}',
100
- imageLoading: 'Loading image…',
101
- imageLoadFailed: 'Could not load image. Click to retry.',
102
- imagePreview: 'Image preview',
103
- imageClose: 'Close',
104
- defaultSize: 'Default size',
105
- defaultQuality: 'Default quality',
106
- }
67
+ {
68
+ id: 'openai-images',
69
+ label: 'OpenAI Images',
70
+ hint: '/v1/images/generations · gpt-image, DALL·E and compatible gateways',
71
+ },
72
+ {
73
+ id: 'xai-images',
74
+ label: 'xAI Images',
75
+ hint: '/v1/images/generations with aspect_ratio · grok-imagine',
76
+ },
77
+ {
78
+ id: 'gemini-image',
79
+ label: 'Gemini / Imagen',
80
+ hint: 'generateContent or predict · gemini-*-image and imagen-*',
81
+ },
82
+ {
83
+ id: 'openai-chat-image',
84
+ label: 'OpenAI Chat Completions',
85
+ hint: '/v1/chat/completions · gateways that return images in a chat reply',
86
+ },
87
+ ];
107
88
 
108
89
  const zh = {
109
- nav: '生图配置',
110
- title: '生图配置',
111
- intro: '在这里添加生图供应商和模型。然后到 设置 → 插件 → 插件配置 → 图形生成 中选择一个模型。对话需要生图时,会调用 image_generate 使用该模型。',
112
- addProvider: '添加供应商',
113
- providerName: '名称',
114
- baseUrl: 'Base URL',
115
- apiFormat: 'API 格式',
116
- apiKey: 'API Key',
117
- apiKeyPlaceholder: '输入 API Key,留空则保留已保存的密钥',
118
- apiKeySet: '已配置',
119
- apiKeyUnset: '未配置',
120
- models: '模型列表',
121
- addModel: '添加模型',
122
- modelId: '模型 ID',
123
- modelName: '显示名称',
124
- save: '保存',
125
- saving: '保存中…',
126
- saved: '已保存。',
127
- cancel: '取消',
128
- delete: '删除',
129
- edit: '编辑',
130
- empty: '还没有生图供应商,点击下方按钮添加。',
131
- loadFailed: '无法加载生图配置。',
132
- retry: '重试',
133
- readOnly: '当前部署的设置为只读。',
134
- nameRequired: '请填写供应商名称。',
135
- baseUrlRequired: '请填写 Base URL。',
136
- modelRequired: '请至少添加一个模型,或删掉空行。',
137
- modelIdRequired: '模型 ID 不能为空。',
138
- modelIdDuplicate: '模型 ID 不能重复。',
139
- conflict: '设置已在其他位置更新,请关闭后重试。',
140
- saveFailed: '保存失败,已保留你的修改。',
141
- cardTitle: '图形生成',
142
- cardDescription: '选择对话里 image_generate 实际使用的那一个模型。',
143
- enabled: '启用 image_generate',
144
- enabledHint: '关闭后工具会拒绝生图,直到重新打开。',
145
- pickModel: '当前模型',
146
- pickHint: '只能选择一个模型。供应商和模型在左侧「生图配置」中维护。',
147
- noModels: '还没有可用模型。请先到 设置 → 生图配置 添加供应商。',
148
- expand: '展开设置',
149
- collapse: '收起设置',
150
- discard: '放弃修改',
151
- unsaved: '未保存',
152
- generating: '正在生成…',
153
- image: '图片',
154
- viewImage: '查看图片',
155
- viewImageNamed: '查看 {name}',
156
- imageLoading: '正在加载图片…',
157
- imageLoadFailed: '图片加载失败,点击重试。',
158
- imagePreview: '图片预览',
159
- imageClose: '关闭',
160
- defaultSize: '默认尺寸',
161
- defaultQuality: '默认质量',
162
- }
90
+ 'nav': '生图配置',
91
+ 'title': '生图配置',
92
+ 'intro': '在这里维护生图供应商和模型。密钥交给凭据服务保存,不会写进设置文件。',
93
+ 'addProvider': '添加供应商',
94
+ 'providerName': '名称',
95
+ 'baseUrl': 'Base URL',
96
+ 'apiFormat': 'API 格式',
97
+ 'apiKey': 'API Key',
98
+ 'apiKeyPlaceholder': '输入新的 API Key;留空则保留已保存的密钥',
99
+ 'apiKeyConfigured': '密钥已配置',
100
+ 'apiKeyMissing': '密钥未配置',
101
+ 'models': '模型列表',
102
+ 'addModel': '添加模型',
103
+ 'modelId': '模型 ID',
104
+ 'modelName': '显示名称',
105
+ 'save': '保存',
106
+ 'saving': '保存中…',
107
+ 'cancel': '取消',
108
+ 'delete': '删除',
109
+ 'confirmDelete': '再次点击删除',
110
+ 'edit': '编辑',
111
+ 'empty': '还没有生图供应商。添加一个供应商和至少一个模型后即可使用。',
112
+ 'loadFailed': '无法读取生图配置。',
113
+ 'readOnly': '当前部署的设置是只读的。',
114
+ 'nameRequired': '请填写供应商名称。',
115
+ 'baseUrlRequired': '请填写 Base URL。',
116
+ 'modelRequired': '请至少添加一个模型。',
117
+ 'modelIdRequired': '模型 ID 不能为空。',
118
+ 'modelIdDuplicate': '同一供应商下的模型 ID 不能重复。',
119
+ 'saveFailed': '保存失败,修改仍保留在表单里。',
120
+ 'cardTitle': '图形生成',
121
+ 'cardDescription': '选择对话里 image_generate 使用的模型,并设置默认尺寸和质量。',
122
+ 'enabled': '启用 image_generate',
123
+ 'enabledHint': '关闭后工具会拒绝生图,直到重新打开。',
124
+ 'activeModel': '当前模型',
125
+ 'pickHint': '供应商和模型在 设置 → 生图配置 中维护。',
126
+ 'noModels': '还没有可用模型。请先在 设置 → 生图配置 添加供应商。',
127
+ 'expand': '展开设置',
128
+ 'collapse': '收起设置',
129
+ 'discard': '放弃修改',
130
+ 'unsaved': '未保存',
131
+ 'defaultSize': '默认尺寸',
132
+ 'defaultQuality': '默认质量',
133
+ 'generating': '正在生成图片…',
134
+ 'image': '图片',
135
+ 'viewImage': '查看大图',
136
+ 'imageLoading': '正在加载图片…',
137
+ 'imageLoadFailed': '图片加载失败,点击重试。',
138
+ 'imagePreview': '图片预览',
139
+ 'close': '关闭',
140
+ 'configured': '已配置',
141
+ 'notConfigured': '未配置',
142
+ 'modelsCount': '{count} 个模型',
143
+ 'formatUnknown': '未知格式',
144
+ 'saveConflict': '设置已在别处更新。请关闭后重新打开再试。',
145
+ };
146
+
147
+ const en = {
148
+ 'nav': 'Image generation',
149
+ 'title': 'Image generation',
150
+ 'intro': 'Maintain image providers and models here. Keys are stored by the credentials service, never in the settings file.',
151
+ 'addProvider': 'Add provider',
152
+ 'providerName': 'Name',
153
+ 'baseUrl': 'Base URL',
154
+ 'apiFormat': 'API format',
155
+ 'apiKey': 'API key',
156
+ 'apiKeyPlaceholder': 'Enter a new API key; leave blank to keep the stored one',
157
+ 'apiKeyConfigured': 'Key configured',
158
+ 'apiKeyMissing': 'Key missing',
159
+ 'models': 'Models',
160
+ 'addModel': 'Add model',
161
+ 'modelId': 'Model ID',
162
+ 'modelName': 'Display name',
163
+ 'save': 'Save',
164
+ 'saving': 'Saving…',
165
+ 'cancel': 'Cancel',
166
+ 'delete': 'Delete',
167
+ 'confirmDelete': 'Click again to delete',
168
+ 'edit': 'Edit',
169
+ 'empty': 'No image providers yet. Add one with at least one model to start.',
170
+ 'loadFailed': 'Could not read the image-generation settings.',
171
+ 'readOnly': 'Settings are read-only in this deployment.',
172
+ 'nameRequired': 'Provider name is required.',
173
+ 'baseUrlRequired': 'Base URL is required.',
174
+ 'modelRequired': 'Add at least one model.',
175
+ 'modelIdRequired': 'Model ID is required.',
176
+ 'modelIdDuplicate': 'Model IDs must be unique inside one provider.',
177
+ 'saveFailed': 'The save failed; your edits are still in the form.',
178
+ 'cardTitle': 'Image generation',
179
+ 'cardDescription': 'Choose the model conversations use for image_generate, plus its default size and quality.',
180
+ 'enabled': 'Enable image_generate',
181
+ 'enabledHint': 'When off, the tool refuses until you turn it back on.',
182
+ 'activeModel': 'Active model',
183
+ 'pickHint': 'Providers and models are maintained under Settings → Image generation.',
184
+ 'noModels': 'No models yet. Add a provider under Settings → Image generation first.',
185
+ 'expand': 'Expand settings',
186
+ 'collapse': 'Collapse settings',
187
+ 'discard': 'Discard changes',
188
+ 'unsaved': 'Unsaved',
189
+ 'defaultSize': 'Default size',
190
+ 'defaultQuality': 'Default quality',
191
+ 'generating': 'Generating image…',
192
+ 'image': 'Image',
193
+ 'viewImage': 'View image',
194
+ 'imageLoading': 'Loading image…',
195
+ 'imageLoadFailed': 'Could not load the image. Click to retry.',
196
+ 'imagePreview': 'Image preview',
197
+ 'close': 'Close',
198
+ 'configured': 'Configured',
199
+ 'notConfigured': 'Not configured',
200
+ 'modelsCount': '{count} models',
201
+ 'formatUnknown': 'Unknown format',
202
+ 'saveConflict': 'These settings changed elsewhere. Close and reopen this page.',
203
+ };
163
204
 
164
- function translateFactory(dict) {
205
+ function translate(dict) {
165
206
  return (key, params) => {
166
- let text = dict[key] ?? en[key] ?? key
207
+ let text = dict[key] ?? en[key] ?? key;
167
208
  for (const [name, value] of Object.entries(params ?? {})) {
168
- text = String(text).replaceAll(`{${name}}`, String(value))
209
+ text = String(text).replaceAll(`{${name}}`, String(value));
169
210
  }
170
- return text
171
- }
211
+ return text;
212
+ };
172
213
  }
173
214
 
174
- function slugify(name) {
175
- const slug = String(name ?? '').trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')
176
- return slug || 'provider'
177
- }
178
-
179
- function apiKeyEnvFor(id) {
180
- return `IMAGE_GEN_${String(id).toUpperCase().replace(/[^A-Z0-9]+/g, '_')}_API_KEY`
181
- }
182
-
183
- function uniqueId(name, taken) {
184
- const base = slugify(name)
185
- if (!taken.has(base)) return base
186
- let n = 2
187
- while (taken.has(`${base}-${n}`)) n += 1
188
- return `${base}-${n}`
189
- }
190
-
191
- function newModel() {
192
- return { id: '', name: '' }
193
- }
215
+ /**
216
+ * Shared stylesheet for controls that cannot be expressed faithfully with
217
+ * inline styles (the rounded select trigger and its hover state). Card
218
+ * layout stays inline so it follows the theme without a second source.
219
+ */
220
+ const STYLE_TEXT = `
221
+ .dsh-ig-select {
222
+ box-sizing: border-box;
223
+ display: inline-flex;
224
+ align-items: center;
225
+ gap: 8px;
226
+ height: 32px;
227
+ max-width: min(100%, 320px);
228
+ padding: 0 12px;
229
+ border: 1px solid var(--dsw-alias-border-l2);
230
+ border-radius: 16px;
231
+ background: var(--dsw-alias-bg-layer-1);
232
+ color: var(--dsw-alias-label-primary);
233
+ font: inherit;
234
+ font-size: 13px;
235
+ line-height: 20px;
236
+ cursor: pointer;
237
+ }
238
+ .dsh-ig-select:hover:not(:disabled) {
239
+ border-color: var(--dsw-alias-brand-primary);
240
+ }
241
+ .dsh-ig-select:disabled {
242
+ opacity: .55;
243
+ cursor: default;
244
+ }
245
+ .dsh-ig-select-label {
246
+ min-width: 0;
247
+ overflow: hidden;
248
+ text-overflow: ellipsis;
249
+ white-space: nowrap;
250
+ }
251
+ .dsh-ig-native {
252
+ box-sizing: border-box;
253
+ height: 32px;
254
+ max-width: 100%;
255
+ padding: 0 8px;
256
+ border: 1px solid var(--dsw-alias-border-l2);
257
+ border-radius: 8px;
258
+ background: var(--dsw-alias-bg-layer-1);
259
+ color: var(--dsw-alias-label-primary);
260
+ font: inherit;
261
+ font-size: 13px;
262
+ }
263
+ .dsh-ig-focus:focus-visible {
264
+ outline: 2px solid var(--dsw-alias-brand-primary);
265
+ outline-offset: 1px;
266
+ }
267
+ `;
194
268
 
195
- function cloneProviders(value) {
196
- const list = Array.isArray(value?.providers) ? value.providers : []
197
- return list.map((row) => ({
198
- id: String(row.id ?? ''),
199
- name: String(row.name ?? ''),
200
- baseUrl: String(row.baseUrl ?? ''),
201
- apiFormat: String(row.apiFormat ?? 'openai-images'),
202
- apiKeyEnv: String(row.apiKeyEnv ?? ''),
203
- models: Array.isArray(row.models)
204
- ? row.models.map((model) => ({ id: String(model.id ?? ''), name: String(model.name ?? '') }))
205
- : [],
206
- }))
269
+ function ensureStyles() {
270
+ if (typeof document === 'undefined') return;
271
+ if (document.querySelector(`style[${STYLE_ATTR}="${STYLE_ID}"]`)) return;
272
+ const tag = document.createElement('style');
273
+ tag.setAttribute(STYLE_ATTR, STYLE_ID);
274
+ tag.textContent = STYLE_TEXT;
275
+ document.head.appendChild(tag);
207
276
  }
208
277
 
209
278
  const css = {
210
- section: { display: 'flex', flexDirection: 'column', gap: 12, maxWidth: 640, color: 'var(--dsw-alias-label-primary)' },
279
+ section: {
280
+ display: 'flex',
281
+ flexDirection: 'column',
282
+ gap: 14,
283
+ maxWidth: 720,
284
+ color: 'var(--dsw-alias-label-primary)',
285
+ },
211
286
  title: { margin: 0, fontSize: 18, fontWeight: 600, lineHeight: '26px' },
212
- intro: { margin: 0, color: 'var(--dsw-alias-label-tertiary)', fontSize: 14, lineHeight: '22px' },
287
+ intro: { margin: 0, color: 'var(--dsw-alias-label-secondary)', fontSize: 14, lineHeight: '22px' },
213
288
  card: {
214
- border: '1px solid var(--dsw-alias-border-l2)', borderRadius: 12,
215
- padding: '12px 14px', display: 'flex', flexDirection: 'column', gap: 10,
216
- background: 'var(--dsw-alias-bg-layer-3)',
289
+ display: 'flex',
290
+ flexDirection: 'column',
291
+ gap: 10,
292
+ padding: '14px 16px',
293
+ border: '1px solid var(--dsw-alias-border-l2)',
294
+ borderRadius: 12,
295
+ background: 'var(--dsw-alias-bg-layer-1)',
217
296
  },
218
297
  row: { display: 'flex', alignItems: 'center', gap: 8 },
219
- name: { fontWeight: 500, fontSize: 14, lineHeight: '22px', flex: 1, minWidth: 0 },
220
- meta: { margin: 0, fontSize: 12, lineHeight: '18px', color: 'var(--dsw-alias-label-tertiary)' },
221
- field: { display: 'flex', flexDirection: 'column', gap: 4 },
298
+ name: { flex: 1, minWidth: 0, fontWeight: 500, fontSize: 14, lineHeight: '22px' },
299
+ meta: { margin: 0, fontSize: 12, lineHeight: '18px', color: 'var(--dsw-alias-label-secondary)' },
300
+ field: { display: 'flex', flexDirection: 'column', gap: 5 },
222
301
  label: { fontSize: 12, lineHeight: '18px', color: 'var(--dsw-alias-label-secondary)' },
223
302
  input: {
224
- height: 32, width: '100%', boxSizing: 'border-box',
225
- border: '1px solid var(--dsw-alias-border-l2)', borderRadius: 8,
226
- padding: '0 10px', font: 'inherit', fontSize: 14, lineHeight: '22px',
227
- background: 'var(--dsw-alias-bg-layer-1)', color: 'var(--dsw-alias-label-primary)',
303
+ boxSizing: 'border-box',
304
+ width: '100%',
305
+ height: 32,
306
+ padding: '0 10px',
307
+ border: '1px solid var(--dsw-alias-border-l2)',
308
+ borderRadius: 8,
309
+ background: 'var(--dsw-alias-bg-base)',
310
+ color: 'var(--dsw-alias-label-primary)',
311
+ font: 'inherit',
312
+ fontSize: 14,
313
+ lineHeight: '22px',
228
314
  },
229
315
  modelRow: {
230
- display: 'flex', alignItems: 'center', gap: 8,
231
- border: '1px solid var(--dsw-alias-border-l2)', borderRadius: 10,
232
- padding: '8px 10px',
316
+ display: 'flex',
317
+ alignItems: 'center',
318
+ gap: 8,
319
+ padding: '6px 8px',
320
+ border: '1px solid var(--dsw-alias-border-l2)',
321
+ borderRadius: 10,
233
322
  },
234
323
  button: {
235
- boxSizing: 'border-box', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
236
- height: 28, padding: '0 10px', borderRadius: 14,
237
- border: '1px solid var(--dsw-alias-border-l2)', background: 'transparent',
238
- color: 'var(--dsw-alias-label-primary)', font: 'inherit', fontSize: 12, lineHeight: '18px',
324
+ boxSizing: 'border-box',
325
+ display: 'inline-flex',
326
+ alignItems: 'center',
327
+ justifyContent: 'center',
328
+ gap: 4,
329
+ height: 28,
330
+ padding: '0 10px',
331
+ border: '1px solid var(--dsw-alias-border-l2)',
332
+ borderRadius: 14,
333
+ background: 'transparent',
334
+ color: 'var(--dsw-alias-label-primary)',
335
+ font: 'inherit',
336
+ fontSize: 12,
337
+ lineHeight: '18px',
239
338
  cursor: 'pointer',
240
339
  },
241
340
  primary: {
242
- boxSizing: 'border-box', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
243
- height: 32, padding: '0 14px', borderRadius: 16, border: 'none',
244
- background: 'var(--dsw-alias-button-primary-fill, #3b82f6)',
245
- color: 'var(--dsw-alias-label-primary-foreground, #fff)',
246
- font: 'inherit', fontSize: 13, cursor: 'pointer',
341
+ boxSizing: 'border-box',
342
+ display: 'inline-flex',
343
+ alignItems: 'center',
344
+ justifyContent: 'center',
345
+ height: 32,
346
+ padding: '0 14px',
347
+ border: 'none',
348
+ borderRadius: 16,
349
+ background: 'var(--dsw-alias-brand-primary)',
350
+ color: '#fff',
351
+ font: 'inherit',
352
+ fontSize: 13,
353
+ cursor: 'pointer',
247
354
  },
248
- iconBtn: {
249
- boxSizing: 'border-box', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
250
- width: 28, height: 28, border: 'none', background: 'transparent', cursor: 'pointer',
251
- color: 'var(--dsw-alias-label-tertiary)', borderRadius: 8, padding: 0, flex: 'none',
355
+ iconButton: {
356
+ boxSizing: 'border-box',
357
+ display: 'inline-flex',
358
+ alignItems: 'center',
359
+ justifyContent: 'center',
360
+ width: 28,
361
+ height: 28,
362
+ padding: 0,
363
+ border: 'none',
364
+ borderRadius: 8,
365
+ background: 'transparent',
366
+ color: 'var(--dsw-alias-label-secondary)',
367
+ cursor: 'pointer',
368
+ flex: 'none',
252
369
  },
253
370
  error: { margin: 0, fontSize: 12, lineHeight: '18px', color: 'var(--dsw-alias-state-error-primary)' },
254
- ok: { margin: 0, fontSize: 12, lineHeight: '18px', color: 'var(--dsw-alias-state-success-primary)' },
255
- actions: { display: 'flex', gap: 8, justifyContent: 'flex-end', alignItems: 'center', flexWrap: 'wrap' },
256
- pluginCard: {
257
- border: '0.5px solid var(--dsw-alias-border-l4)', background: 'var(--dsw-alias-bg-layer-3)',
258
- borderRadius: 16, listStyle: 'none',
371
+ success: { margin: 0, fontSize: 12, lineHeight: '18px', color: 'var(--dsw-alias-state-success-primary)' },
372
+ actions: { display: 'flex', flexWrap: 'wrap', alignItems: 'center', justifyContent: 'flex-end', gap: 8 },
373
+ bundleCard: {
374
+ border: '1px solid var(--dsw-alias-border-l1)',
375
+ borderRadius: 16,
376
+ background: 'var(--dsw-alias-bg-layer-1)',
377
+ listStyle: 'none',
378
+ margin: 0,
379
+ padding: 0,
259
380
  },
260
- pluginHeader: {
261
- appearance: 'none', width: '100%', font: 'inherit', color: 'inherit', textAlign: 'left',
262
- cursor: 'pointer', background: 'transparent', border: 0, borderRadius: 12,
263
- display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px',
381
+ bundleHeader: {
382
+ appearance: 'none',
383
+ display: 'flex',
384
+ alignItems: 'center',
385
+ gap: 12,
386
+ width: '100%',
387
+ padding: '14px 16px',
388
+ border: 0,
389
+ borderRadius: 12,
390
+ background: 'transparent',
391
+ color: 'inherit',
392
+ font: 'inherit',
393
+ textAlign: 'left',
394
+ cursor: 'pointer',
264
395
  },
265
- pluginName: { color: 'var(--dsw-alias-label-primary)', fontSize: 15, fontWeight: 600, lineHeight: 1.4 },
266
- pluginDesc: { color: 'var(--dsw-alias-label-tertiary)', fontSize: 13, lineHeight: 1.5 },
267
- pluginBody: { borderTop: '0.5px solid var(--dsw-alias-border-l2)', margin: '0 16px', paddingBottom: 8 },
396
+ bundleName: { color: 'var(--dsw-alias-label-primary)', fontSize: 15, fontWeight: 600, lineHeight: 1.4 },
397
+ bundleDesc: { color: 'var(--dsw-alias-label-secondary)', fontSize: 13, lineHeight: 1.5 },
398
+ bundleBody: { borderTop: '1px solid var(--dsw-alias-border-l1)', margin: '0 16px', padding: '2px 0 12px' },
268
399
  switch: {
269
- boxSizing: 'border-box', background: 'var(--dsw-alias-border-l3)', cursor: 'pointer',
270
- border: 0, borderRadius: 10, flex: 'none', width: 36, height: 20, padding: 2, position: 'relative',
400
+ boxSizing: 'border-box',
401
+ position: 'relative',
402
+ width: 36,
403
+ height: 20,
404
+ padding: 2,
405
+ border: 0,
406
+ borderRadius: 10,
407
+ background: 'var(--dsw-alias-border-l2)',
408
+ cursor: 'pointer',
409
+ flex: 'none',
271
410
  },
272
- prefRow: { display: 'flex', alignItems: 'center', gap: 8, padding: '8px 0' },
273
- prefLabel: { minWidth: 0, flex: 1, color: 'var(--dsw-alias-label-primary)', fontSize: 14, lineHeight: '22px' },
274
- }
411
+ switchKnob: {
412
+ display: 'block',
413
+ width: 16,
414
+ height: 16,
415
+ borderRadius: '50%',
416
+ background: '#fff',
417
+ transition: 'transform .15s ease',
418
+ },
419
+ prefRow: { display: 'flex', alignItems: 'center', gap: 12, padding: '8px 0' },
420
+ prefLabel: { flex: 1, minWidth: 0, fontSize: 14, lineHeight: '22px' },
421
+ };
275
422
 
276
- function SelectMenu(props) {
277
- const [open, setOpen] = React.useState(false)
278
- const active = props.options.find((row) => row.id === props.value)?.label ?? props.placeholder ?? props.value ?? ''
279
- if (typeof Menu !== 'function') return null
280
- return React.createElement(Menu, {
423
+ function Select(props) {
424
+ const [open, setOpen] = useState(false);
425
+ const active = props.options.find((row) => row.id === props.value)?.label ?? props.placeholder ?? props.value ?? '';
426
+ if (typeof Menu !== 'function') {
427
+ return h('select', {
428
+ className: 'dsh-ig-native',
429
+ value: props.value,
430
+ disabled: props.disabled,
431
+ 'aria-label': props.label,
432
+ onChange: (event) => props.onPick(event.target.value),
433
+ }, props.options.map((row) => h('option', { key: row.id, value: row.id }, row.label)));
434
+ }
435
+ return h(Menu, {
281
436
  open,
282
437
  onClose: () => setOpen(false),
283
438
  items: props.options,
284
439
  selectedId: props.value,
285
440
  onSelect: (id) => {
286
- setOpen(false)
287
- props.onPick(id)
441
+ setOpen(false);
442
+ props.onPick(id);
288
443
  },
289
444
  align: 'end',
290
445
  portal: true,
291
446
  dense: true,
292
- anchor: React.createElement('button', {
447
+ anchor: h('button', {
293
448
  type: 'button',
294
- className: 'dsh-ig-select',
449
+ className: 'dsh-ig-select dsh-ig-focus',
295
450
  disabled: props.disabled || props.options.length === 0,
296
451
  'aria-haspopup': 'menu',
297
452
  'aria-expanded': open,
298
453
  'aria-label': props.label,
299
454
  onClick: () => setOpen((value) => !value),
300
455
  },
301
- React.createElement('span', { className: 'dsh-ig-select-label' }, active),
302
- IconChevronDown ? React.createElement(IconChevronDown, { size: 14 }) : null,
456
+ h('span', { className: 'dsh-ig-select-label' }, active),
457
+ IconChevronDown ? h(IconChevronDown, { size: 14 }) : null,
303
458
  ),
304
- })
459
+ });
305
460
  }
306
461
 
307
462
  function PrefRow(props) {
308
- return React.createElement('div', { style: css.prefRow },
309
- React.createElement('span', { style: css.prefLabel }, props.label),
310
- React.createElement(SelectMenu, {
463
+ return h('div', { style: css.prefRow },
464
+ h('span', { style: css.prefLabel }, props.label),
465
+ h(Select, {
311
466
  label: props.label,
312
467
  value: props.value,
313
468
  options: props.options,
@@ -315,41 +470,107 @@ window.__ModuleLoader__.load({
315
470
  placeholder: props.placeholder,
316
471
  onPick: props.onPick,
317
472
  }),
318
- )
473
+ );
319
474
  }
320
475
 
321
476
  function IconButton(props) {
322
- return React.createElement('button', {
477
+ return h('button', {
323
478
  type: 'button',
324
- style: { ...css.iconBtn, ...props.style },
479
+ style: { ...css.iconButton, ...props.style },
325
480
  disabled: props.disabled,
326
481
  'aria-label': props.label,
482
+ title: props.label,
327
483
  onClick: props.onClick,
328
- }, props.children)
484
+ }, props.children);
329
485
  }
330
486
 
331
- function formatLabel(id) {
332
- return API_FORMATS.find((row) => row.id === id)?.label ?? id
487
+ /**
488
+ * Deletion is irreversible, and this card is one click away from a working
489
+ * provider. The first click only arms the button; a second click inside
490
+ * three seconds commits. No modal, no native confirm dialog.
491
+ */
492
+ function DeleteButton(props) {
493
+ const [armed, setArmed] = useState(false);
494
+ useEffect(() => {
495
+ if (!armed) return undefined;
496
+ const timer = setTimeout(() => setArmed(false), 3000);
497
+ return () => clearTimeout(timer);
498
+ }, [armed]);
499
+ return h('button', {
500
+ type: 'button',
501
+ style: { ...css.button, ...(armed ? { borderColor: 'var(--dsw-alias-state-error-primary)', color: 'var(--dsw-alias-state-error-primary)' } : {}), ...props.style },
502
+ disabled: props.disabled,
503
+ 'aria-label': props.label,
504
+ onClick: () => {
505
+ if (!armed) {
506
+ setArmed(true);
507
+ return;
508
+ }
509
+ setArmed(false);
510
+ props.onDelete();
511
+ },
512
+ }, props.label && armed ? props.confirmLabel : (props.children ?? props.label));
333
513
  }
334
514
 
335
- function formatHint(id) {
336
- return API_FORMATS.find((row) => row.id === id)?.hint ?? ''
515
+ function useSnapshot(scope) {
516
+ const [snapshot, setSnapshot] = useState(() => scope.getSnapshot());
517
+ useEffect(() => {
518
+ setSnapshot(scope.getSnapshot());
519
+ return scope.subscribe(() => setSnapshot(scope.getSnapshot()));
520
+ }, [scope]);
521
+ return snapshot;
337
522
  }
338
523
 
339
- function useSnapshot(scope) {
340
- const [snap, setSnap] = React.useState(() => scope.getSnapshot())
341
- React.useEffect(() => {
342
- setSnap(scope.getSnapshot())
343
- return scope.subscribe(() => setSnap(scope.getSnapshot()))
344
- }, [scope])
345
- return snap
524
+ function cloneProviders(value) {
525
+ const list = Array.isArray(value?.providers) ? value.providers : [];
526
+ return list.map((row) => ({
527
+ id: String(row?.id ?? ''),
528
+ name: String(row?.name ?? ''),
529
+ baseUrl: String(row?.baseUrl ?? ''),
530
+ apiFormat: String(row?.apiFormat ?? 'openai-images'),
531
+ apiKeyEnv: String(row?.apiKeyEnv ?? ''),
532
+ models: Array.isArray(row?.models)
533
+ ? row.models.map((model) => ({ id: String(model?.id ?? ''), name: String(model?.name ?? '') }))
534
+ : [],
535
+ }));
536
+ }
537
+
538
+ function slugify(value) {
539
+ const slug = String(value ?? '').trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
540
+ return slug || 'provider';
541
+ }
542
+
543
+ function apiKeyEnvFor(providerId) {
544
+ return `IMAGE_GEN_${String(providerId).toUpperCase().replace(/[^A-Z0-9]+/g, '_')}_API_KEY`;
545
+ }
546
+
547
+ function uniqueProviderId(name, taken) {
548
+ const base = slugify(name);
549
+ if (!taken.has(base)) return base;
550
+ let index = 2;
551
+ while (taken.has(`${base}-${index}`)) index += 1;
552
+ return `${base}-${index}`;
553
+ }
554
+
555
+ function formatLabel(id) {
556
+ return API_FORMATS.find((row) => row.id === id)?.label ?? id ?? '';
557
+ }
558
+
559
+ function formatHint(id) {
560
+ return API_FORMATS.find((row) => row.id === id)?.hint ?? '';
346
561
  }
347
562
 
348
563
  function ProviderEditor(props) {
349
- const { t, draft, setDraft, keyDraft, setKeyDraft, keyState, busy, error, saved, writable, onSave, onCancel, onDelete } = props
350
- return React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
351
- React.createElement('div', { style: css.row },
352
- React.createElement('input', {
564
+ const { t, draft, setDraft, keyDraft, setKeyDraft, keyConfigured, busy, error, writable, onSave, onCancel, onDelete } = props;
565
+ const updateModel = (index, patch) => {
566
+ const models = draft.models.slice();
567
+ models[index] = { ...models[index], ...patch };
568
+ setDraft({ ...draft, models });
569
+ };
570
+ return h('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
571
+ h('div', { style: css.row },
572
+ h('input', {
573
+ className: 'dsh-ig-focus',
353
574
  style: { ...css.input, fontWeight: 600 },
354
575
  value: draft.name,
355
576
  placeholder: t('providerName'),
@@ -357,330 +578,362 @@ window.__ModuleLoader__.load({
357
578
  disabled: !writable || busy,
358
579
  onChange: (event) => setDraft({ ...draft, name: event.target.value }),
359
580
  }),
360
- React.createElement(IconButton, {
361
- label: t('delete'), disabled: !writable || busy, onClick: onDelete,
362
- }, IconTrash ? React.createElement(IconTrash, { size: 16 }) : t('delete')),
581
+ h(DeleteButton, {
582
+ label: t('delete'),
583
+ confirmLabel: t('confirmDelete'),
584
+ disabled: !writable || busy,
585
+ onDelete,
586
+ }, IconTrash ? h(IconTrash, { size: 16 }) : t('delete')),
363
587
  ),
364
- React.createElement('div', { style: css.field },
365
- React.createElement('span', { style: css.label }, t('baseUrl')),
366
- React.createElement('input', {
367
- style: css.input, value: draft.baseUrl, placeholder: 'https://api.example.com/v1',
368
- 'aria-label': t('baseUrl'), disabled: !writable || busy,
588
+ h('div', { style: css.field },
589
+ h('span', { style: css.label }, t('baseUrl')),
590
+ h('input', {
591
+ className: 'dsh-ig-focus',
592
+ style: css.input,
593
+ value: draft.baseUrl,
594
+ placeholder: 'https://api.example.com/v1',
595
+ 'aria-label': t('baseUrl'),
596
+ disabled: !writable || busy,
369
597
  onChange: (event) => setDraft({ ...draft, baseUrl: event.target.value }),
370
598
  }),
371
599
  ),
372
- React.createElement('div', { style: css.field },
373
- React.createElement(PrefRow, {
600
+ h('div', { style: css.field },
601
+ h(PrefRow, {
374
602
  label: t('apiFormat'),
375
603
  value: draft.apiFormat,
376
604
  disabled: !writable || busy,
377
605
  options: API_FORMATS.map((row) => ({ id: row.id, label: row.label })),
378
606
  onPick: (id) => setDraft({ ...draft, apiFormat: id }),
379
607
  }),
380
- React.createElement('p', { style: css.meta }, formatHint(draft.apiFormat)),
608
+ h('p', { style: css.meta }, formatHint(draft.apiFormat)),
381
609
  ),
382
- React.createElement('div', { style: css.field },
383
- React.createElement('span', { style: css.label }, `${t('apiKey')} · ${keyState ? t('apiKeySet') : t('apiKeyUnset')}`),
384
- React.createElement('input', {
385
- style: css.input, type: 'password', autoComplete: 'off', value: keyDraft,
386
- placeholder: t('apiKeyPlaceholder'), 'aria-label': t('apiKey'),
610
+ h('div', { style: css.field },
611
+ h('span', { style: css.label },
612
+ `${t('apiKey')} · ${keyConfigured ? t('apiKeyConfigured') : t('apiKeyMissing')}`),
613
+ h('input', {
614
+ className: 'dsh-ig-focus',
615
+ style: css.input,
616
+ type: 'password',
617
+ autoComplete: 'off',
618
+ value: keyDraft,
619
+ placeholder: t('apiKeyPlaceholder'),
620
+ 'aria-label': t('apiKey'),
387
621
  disabled: !writable || busy,
388
622
  onChange: (event) => setKeyDraft(event.target.value),
389
623
  }),
390
624
  ),
391
- React.createElement('div', { style: css.field },
392
- React.createElement('span', { style: css.label }, t('models')),
393
- (draft.models ?? []).map((model, index) => React.createElement('div', { key: index, style: css.modelRow },
394
- React.createElement('input', {
625
+ h('div', { style: css.field },
626
+ h('span', { style: css.label }, t('models')),
627
+ draft.models.map((model, index) => h('div', { key: index, style: css.modelRow },
628
+ h('input', {
629
+ className: 'dsh-ig-focus',
395
630
  style: { ...css.input, flex: 1 },
396
631
  value: model.id,
397
632
  placeholder: t('modelId'),
398
633
  'aria-label': t('modelId'),
399
634
  disabled: !writable || busy,
400
- onChange: (event) => {
401
- const models = draft.models.slice()
402
- models[index] = { ...models[index], id: event.target.value }
403
- setDraft({ ...draft, models })
404
- },
635
+ onChange: (event) => updateModel(index, { id: event.target.value }),
405
636
  }),
406
- React.createElement('input', {
637
+ h('input', {
638
+ className: 'dsh-ig-focus',
407
639
  style: { ...css.input, flex: 1 },
408
640
  value: model.name,
409
641
  placeholder: t('modelName'),
410
642
  'aria-label': t('modelName'),
411
643
  disabled: !writable || busy,
412
- onChange: (event) => {
413
- const models = draft.models.slice()
414
- models[index] = { ...models[index], name: event.target.value }
415
- setDraft({ ...draft, models })
416
- },
644
+ onChange: (event) => updateModel(index, { name: event.target.value }),
417
645
  }),
418
- React.createElement(IconButton, {
419
- label: t('delete'), disabled: !writable || busy,
420
- onClick: () => setDraft({ ...draft, models: draft.models.filter((_, i) => i !== index) }),
421
- }, IconTrash ? React.createElement(IconTrash, { size: 16 }) : t('delete')),
646
+ h(IconButton, {
647
+ label: t('delete'),
648
+ disabled: !writable || busy,
649
+ onClick: () => setDraft({ ...draft, models: draft.models.filter((_, position) => position !== index) }),
650
+ }, IconTrash ? h(IconTrash, { size: 16 }) : t('delete')),
422
651
  )),
423
- React.createElement('button', {
424
- type: 'button', style: { ...css.button, alignSelf: 'flex-start', marginTop: 4, gap: 4 },
652
+ h('button', {
653
+ type: 'button',
654
+ style: { ...css.button, alignSelf: 'flex-start', marginTop: 2 },
425
655
  disabled: !writable || busy,
426
- onClick: () => setDraft({ ...draft, models: [...draft.models, newModel()] }),
427
- },
428
- IconPlus ? React.createElement(IconPlus, { size: 14 }) : null,
429
- t('addModel'),
430
- ),
656
+ onClick: () => setDraft({ ...draft, models: [...draft.models, { id: '', name: '' }] }),
657
+ }, IconPlus ? h(IconPlus, { size: 14 }) : null, t('addModel')),
431
658
  ),
432
- error ? React.createElement('p', { style: css.error, role: 'alert' }, error) : null,
433
- saved ? React.createElement('p', { style: css.ok, role: 'status' }, t('saved')) : null,
434
- React.createElement('div', { style: css.actions },
435
- React.createElement('button', { type: 'button', style: css.button, disabled: busy, onClick: onCancel }, t('cancel')),
436
- React.createElement('button', {
437
- type: 'button', style: css.primary, disabled: !writable || busy, onClick: onSave,
659
+ error ? h('p', { style: css.error, role: 'alert' }, error) : null,
660
+ h('div', { style: css.actions },
661
+ h('button', { type: 'button', style: css.button, disabled: busy, onClick: onCancel }, t('cancel')),
662
+ h('button', {
663
+ type: 'button',
664
+ style: css.primary,
665
+ disabled: !writable || busy,
666
+ onClick: onSave,
438
667
  }, busy ? t('saving') : t('save')),
439
668
  ),
440
- )
669
+ );
441
670
  }
442
671
 
443
672
  function CatalogSection(props) {
444
- const t = props.t ?? translateFactory(en)
445
- const scope = props.catalog
446
- const credentials = props.credentials
447
- const snap = useSnapshot(scope)
448
- const [openId, setOpenId] = React.useState(null)
449
- const [draft, setDraft] = React.useState(null)
450
- const [keyDraft, setKeyDraft] = React.useState('')
451
- const [keyMap, setKeyMap] = React.useState({})
452
- const [busy, setBusy] = React.useState(false)
453
- const [error, setError] = React.useState('')
454
- const [saved, setSaved] = React.useState(false)
455
- const [creating, setCreating] = React.useState(false)
456
-
457
- const providers = cloneProviders(snap.value)
458
- const writable = snap.writable !== false && snap.status === 'ready'
673
+ const t = props.t ?? translate(en);
674
+ const scope = props.catalog;
675
+ const credentials = props.credentials;
676
+ const snapshot = useSnapshot(scope);
677
+ const [editingId, setEditingId] = useState(null);
678
+ const [creating, setCreating] = useState(false);
679
+ const [draft, setDraft] = useState(null);
680
+ const [keyDraft, setKeyDraft] = useState('');
681
+ const [keyState, setKeyState] = useState({});
682
+ const [busy, setBusy] = useState(false);
683
+ const [error, setError] = useState('');
459
684
 
460
- const refreshKeys = React.useCallback(async (list) => {
461
- const refs = list.map((row) => row.apiKeyEnv).filter(Boolean)
462
- if (refs.length === 0 || !credentials) return
463
- const response = await credentials.describe(refs)
464
- if (!response?.ok) return
465
- const next = {}
466
- for (const ref of refs) next[ref] = response.value?.[ref]?.configured === true
467
- setKeyMap(next)
468
- }, [credentials])
685
+ const providers = cloneProviders(snapshot.value);
686
+ const writable = snapshot.writable !== false && snapshot.status === 'ready';
469
687
 
470
- React.useEffect(() => {
471
- if (snap.status === 'ready') void refreshKeys(providers)
472
- }, [snap.status, snap.revision])
688
+ const refreshKeys = useCallback(async (list) => {
689
+ if (!credentials || typeof credentials.describe !== 'function') return;
690
+ const refs = [...new Set(list.map((row) => row.apiKeyEnv).filter(Boolean))];
691
+ if (refs.length === 0) return;
692
+ try {
693
+ const response = await credentials.describe(refs);
694
+ if (!response || response.ok === false) return;
695
+ const next = {};
696
+ for (const ref of refs) next[ref] = response.value?.[ref]?.configured === true;
697
+ setKeyState(next);
698
+ } catch {
699
+ // Key status is decoration. A broken credentials read must not take
700
+ // the whole settings page down.
701
+ }
702
+ }, [credentials]);
473
703
 
474
- function startEdit(row) {
475
- setCreating(false)
476
- setOpenId(row.id)
477
- setDraft({ ...row, models: row.models.length ? row.models.map((m) => ({ ...m })) : [newModel()] })
478
- setKeyDraft('')
479
- setError('')
480
- setSaved(false)
481
- }
704
+ useEffect(() => {
705
+ if (snapshot.status === 'ready') void refreshKeys(providers);
706
+ }, [snapshot.status, snapshot.revision]);
482
707
 
483
708
  function startCreate() {
484
- setCreating(true)
485
- setOpenId('__new__')
709
+ setCreating(true);
710
+ setEditingId('__new__');
486
711
  setDraft({
487
712
  id: '',
488
713
  name: '',
489
714
  baseUrl: '',
490
715
  apiFormat: 'openai-images',
491
716
  apiKeyEnv: '',
492
- models: [newModel()],
493
- })
494
- setKeyDraft('')
495
- setError('')
496
- setSaved(false)
717
+ models: [{ id: '', name: '' }],
718
+ });
719
+ setKeyDraft('');
720
+ setError('');
721
+ }
722
+
723
+ function startEdit(row) {
724
+ setCreating(false);
725
+ setEditingId(row.id);
726
+ setDraft({
727
+ ...row,
728
+ models: row.models.length > 0 ? row.models.map((model) => ({ ...model })) : [{ id: '', name: '' }],
729
+ });
730
+ setKeyDraft('');
731
+ setError('');
732
+ }
733
+
734
+ function stopEdit() {
735
+ setCreating(false);
736
+ setEditingId(null);
737
+ setDraft(null);
738
+ setKeyDraft('');
739
+ setError('');
497
740
  }
498
741
 
499
742
  function validate(next) {
500
- if (!String(next.name ?? '').trim()) return t('nameRequired')
501
- if (!String(next.baseUrl ?? '').trim()) return t('baseUrlRequired')
502
- const models = (next.models ?? []).map((m) => ({ id: String(m.id).trim(), name: String(m.name ?? '').trim() }))
503
- .filter((m) => m.id || m.name)
504
- if (models.length === 0) return t('modelRequired')
505
- const ids = new Set()
743
+ if (!String(next.name ?? '').trim()) return t('nameRequired');
744
+ if (!String(next.baseUrl ?? '').trim()) return t('baseUrlRequired');
745
+ const models = (next.models ?? [])
746
+ .map((model) => ({ id: String(model.id ?? '').trim(), name: String(model.name ?? '').trim() }))
747
+ .filter((model) => model.id || model.name);
748
+ if (models.length === 0) return t('modelRequired');
749
+ const seen = new Set();
506
750
  for (const model of models) {
507
- if (!model.id) return t('modelIdRequired')
508
- if (ids.has(model.id)) return t('modelIdDuplicate')
509
- ids.add(model.id)
751
+ if (!model.id) return t('modelIdRequired');
752
+ if (seen.has(model.id)) return t('modelIdDuplicate');
753
+ seen.add(model.id);
510
754
  }
511
- return ''
755
+ return '';
512
756
  }
513
757
 
514
758
  async function save() {
515
- const next = draft
516
- const message = validate(next)
759
+ const message = validate(draft);
517
760
  if (message) {
518
- setError(message)
519
- return
761
+ setError(message);
762
+ return;
520
763
  }
521
- const models = next.models
522
- .map((m) => ({ id: String(m.id).trim(), name: String(m.name ?? '').trim() || String(m.id).trim() }))
523
- .filter((m) => m.id)
524
- const taken = new Set(providers.map((row) => row.id))
525
- const id = creating ? uniqueId(next.name, taken) : next.id
526
- const apiKeyEnv = next.apiKeyEnv || apiKeyEnvFor(id)
764
+ const models = draft.models
765
+ .map((model) => ({
766
+ id: String(model.id ?? '').trim(),
767
+ name: String(model.name ?? '').trim() || String(model.id ?? '').trim(),
768
+ }))
769
+ .filter((model) => model.id);
770
+ const taken = new Set(providers.map((row) => row.id));
771
+ const id = creating ? uniqueProviderId(draft.name, taken) : draft.id;
527
772
  const record = {
528
773
  id,
529
- name: String(next.name).trim(),
530
- baseUrl: String(next.baseUrl).trim(),
531
- apiFormat: next.apiFormat || 'openai-images',
532
- apiKeyEnv,
774
+ name: String(draft.name).trim(),
775
+ baseUrl: String(draft.baseUrl).trim(),
776
+ apiFormat: draft.apiFormat || 'openai-images',
777
+ apiKeyEnv: draft.apiKeyEnv || apiKeyEnvFor(id),
533
778
  models,
534
- }
535
- const list = creating
779
+ };
780
+ const next = creating
536
781
  ? [...providers, record]
537
- : providers.map((row) => row.id === id ? record : row)
538
- setBusy(true)
539
- setError('')
540
- setSaved(false)
782
+ : providers.map((row) => (row.id === id ? record : row));
783
+ setBusy(true);
784
+ setError('');
541
785
  try {
542
- await scope.set('providers', list)
543
- const landed = cloneProviders(scope.getSnapshot().value)
786
+ await scope.set('providers', next);
787
+ const landed = cloneProviders(scope.getSnapshot().value);
544
788
  if (!landed.some((row) => row.id === id && row.baseUrl === record.baseUrl)) {
545
- throw new Error(t('saveFailed'))
789
+ throw new Error(t('saveFailed'));
546
790
  }
547
- const key = keyDraft.trim()
548
- if (key && credentials) {
549
- const result = await credentials.set(apiKeyEnv, key)
550
- if (result && result.ok === false) throw new Error(result.error?.message || t('saveFailed'))
551
- setKeyDraft('')
791
+ const key = keyDraft.trim();
792
+ if (key) {
793
+ if (!credentials || typeof credentials.set !== 'function') {
794
+ throw new Error(t('saveFailed'));
795
+ }
796
+ const result = await credentials.set(record.apiKeyEnv, key);
797
+ if (result && result.ok === false) throw new Error(result.error?.message || t('saveFailed'));
798
+ setKeyDraft('');
552
799
  }
553
- await refreshKeys(list)
554
- setCreating(false)
555
- setOpenId(null)
556
- setDraft(null)
557
- setKeyDraft('')
558
- setSaved(false)
559
- } catch (err) {
560
- setError(String(err?.message || t('saveFailed')))
800
+ await refreshKeys(next);
801
+ stopEdit();
802
+ } catch (failure) {
803
+ setError(String(failure?.message || t('saveFailed')));
561
804
  } finally {
562
- setBusy(false)
805
+ setBusy(false);
563
806
  }
564
807
  }
565
808
 
566
809
  async function remove(id) {
567
- setBusy(true)
568
- setError('')
810
+ setBusy(true);
811
+ setError('');
569
812
  try {
570
- await scope.set('providers', providers.filter((row) => row.id !== id))
571
- setOpenId(null)
572
- setDraft(null)
573
- setCreating(false)
574
- } catch (err) {
575
- setError(String(err?.message || t('saveFailed')))
813
+ await scope.set('providers', providers.filter((row) => row.id !== id));
814
+ if (editingId === id) stopEdit();
815
+ await refreshKeys(providers.filter((row) => row.id !== id));
816
+ } catch (failure) {
817
+ setError(String(failure?.message || t('saveFailed')));
576
818
  } finally {
577
- setBusy(false)
819
+ setBusy(false);
578
820
  }
579
821
  }
580
822
 
581
- if (snap.status === 'loading' || snap.status === 'idle') {
582
- return React.createElement('div', { style: css.section },
583
- React.createElement('h2', { style: css.title }, t('title')),
584
- React.createElement('p', { style: css.intro }, t('intro')),
585
- )
823
+ if (snapshot.status === 'idle' || snapshot.status === 'loading') {
824
+ return h('div', { style: css.section },
825
+ h('h2', { style: css.title }, t('title')),
826
+ h('p', { style: css.intro }, t('intro')),
827
+ );
586
828
  }
587
- if (snap.status === 'unavailable') {
588
- return React.createElement('div', { style: css.section },
589
- React.createElement('h2', { style: css.title }, t('title')),
590
- React.createElement('p', { style: css.error }, t('loadFailed')),
591
- )
829
+ if (snapshot.status === 'unavailable') {
830
+ return h('div', { style: css.section },
831
+ h('h2', { style: css.title }, t('title')),
832
+ h('p', { style: css.error }, t('loadFailed')),
833
+ );
592
834
  }
593
835
 
594
- return React.createElement('div', { style: css.section },
595
- React.createElement('h2', { style: css.title }, t('title')),
596
- React.createElement('p', { style: css.intro }, t('intro')),
597
- !writable ? React.createElement('p', { style: css.meta }, t('readOnly')) : null,
598
- providers.length === 0 && !creating ? React.createElement('p', { style: css.meta }, t('empty')) : null,
599
- providers.map((row) => React.createElement('div', { key: row.id, style: css.card },
600
- openId === row.id && !creating && draft
601
- ? React.createElement(ProviderEditor, {
602
- t, draft, setDraft, keyDraft, setKeyDraft,
603
- keyState: keyMap[draft.apiKeyEnv] === true,
604
- busy, error, saved, writable, onSave: save,
605
- onCancel: () => { setOpenId(null); setDraft(null); setError(''); setSaved(false) },
606
- onDelete: () => remove(row.id),
607
- })
608
- : React.createElement(React.Fragment, null,
609
- React.createElement('div', { style: css.row },
610
- React.createElement('div', { style: css.name }, row.name || row.id),
611
- React.createElement('button', {
612
- type: 'button', style: css.button, disabled: busy, onClick: () => startEdit(row),
836
+ const editor = (row) => h(ProviderEditor, {
837
+ t,
838
+ draft,
839
+ setDraft,
840
+ keyDraft,
841
+ setKeyDraft,
842
+ keyConfigured: row ? keyState[row.apiKeyEnv] === true : false,
843
+ busy,
844
+ error,
845
+ writable,
846
+ onSave: save,
847
+ onCancel: stopEdit,
848
+ onDelete: () => (creating ? stopEdit() : remove(row.id)),
849
+ });
850
+
851
+ return h('div', { style: css.section },
852
+ h('h2', { style: css.title }, t('title')),
853
+ h('p', { style: css.intro }, t('intro')),
854
+ !writable ? h('p', { style: css.meta }, t('readOnly')) : null,
855
+ error && !draft ? h('p', { style: css.error, role: 'alert' }, error) : null,
856
+ providers.length === 0 && !creating ? h('p', { style: css.meta }, t('empty')) : null,
857
+ providers.map((row) => h('div', { key: row.id, style: css.card },
858
+ editingId === row.id && draft
859
+ ? editor(row)
860
+ : h(React.Fragment, null,
861
+ h('div', { style: css.row },
862
+ h('div', { style: css.name }, row.name || row.id),
863
+ h('button', {
864
+ type: 'button',
865
+ style: css.button,
866
+ disabled: busy,
867
+ onClick: () => startEdit(row),
613
868
  }, t('edit')),
614
- React.createElement(IconButton, {
615
- label: t('delete'), disabled: !writable || busy, onClick: () => remove(row.id),
616
- }, IconTrash ? React.createElement(IconTrash, { size: 16 }) : t('delete')),
617
- ),
618
- React.createElement('p', { style: css.meta },
619
- `${row.baseUrl || '—'} · ${formatLabel(row.apiFormat)} · ${row.models.length} models`
620
- + (keyMap[row.apiKeyEnv] ? ` · ${t('apiKeySet')}` : ` · ${t('apiKeyUnset')}`),
869
+ h(DeleteButton, {
870
+ label: t('delete'),
871
+ confirmLabel: t('confirmDelete'),
872
+ disabled: !writable || busy,
873
+ onDelete: () => remove(row.id),
874
+ }, IconTrash ? h(IconTrash, { size: 16 }) : t('delete')),
621
875
  ),
876
+ h('p', { style: css.meta },
877
+ `${row.baseUrl || '—'} · ${formatLabel(row.apiFormat) || t('formatUnknown')} · `
878
+ + `${t('modelsCount', { count: row.models.length })} · `
879
+ + (keyState[row.apiKeyEnv] ? t('apiKeyConfigured') : t('apiKeyMissing'))),
622
880
  ),
623
881
  )),
624
- creating && draft ? React.createElement('div', { style: css.card },
625
- React.createElement(ProviderEditor, {
626
- t, draft, setDraft, keyDraft, setKeyDraft,
627
- keyState: false, busy, error, saved, writable, onSave: save,
628
- onCancel: () => { setCreating(false); setOpenId(null); setDraft(null); setError('') },
629
- onDelete: () => { setCreating(false); setOpenId(null); setDraft(null) },
630
- }),
631
- ) : null,
632
- React.createElement('button', {
633
- type: 'button', style: { ...css.button, alignSelf: 'flex-start', gap: 4 },
634
- disabled: !writable || creating, onClick: startCreate,
635
- },
636
- IconPlus ? React.createElement(IconPlus, { size: 14 }) : null,
637
- t('addProvider'),
638
- ),
639
- )
882
+ creating && draft ? h('div', { style: css.card }, editor(null)) : null,
883
+ h('button', {
884
+ type: 'button',
885
+ style: { ...css.button, alignSelf: 'flex-start' },
886
+ disabled: !writable || busy || creating,
887
+ onClick: startCreate,
888
+ }, IconPlus ? h(IconPlus, { size: 14 }) : null, t('addProvider')),
889
+ );
640
890
  }
641
891
 
642
892
  function RuntimeCard(props) {
643
- const t = props.t ?? translateFactory(en)
644
- const runtime = props.runtime
645
- const catalog = props.catalog
646
- const runtimeSnap = useSnapshot(runtime)
647
- const catalogSnap = useSnapshot(catalog)
648
- const [open, setOpen] = React.useState(false)
649
- const [enabled, setEnabled] = React.useState(true)
650
- const [choice, setChoice] = React.useState('')
651
- const [size, setSize] = React.useState('1024x1024')
652
- const [quality, setQuality] = React.useState('auto')
653
- const [busy, setBusy] = React.useState(false)
654
- const [failed, setFailed] = React.useState(false)
655
- const [dirty, setDirty] = React.useState(false)
893
+ const t = props.t ?? translate(en);
894
+ const runtime = props.runtime;
895
+ const catalog = props.catalog;
896
+ const runtimeSnapshot = useSnapshot(runtime);
897
+ const catalogSnapshot = useSnapshot(catalog);
898
+ const [open, setOpen] = useState(false);
899
+ const [enabled, setEnabled] = useState(true);
900
+ const [choice, setChoice] = useState('');
901
+ const [size, setSize] = useState(DEFAULT_SIZE);
902
+ const [quality, setQuality] = useState(DEFAULT_QUALITY);
903
+ const [busy, setBusy] = useState(false);
904
+ const [failed, setFailed] = useState(false);
905
+ const [dirty, setDirty] = useState(false);
656
906
 
657
- const providers = cloneProviders(catalogSnap.value)
658
- const options = []
659
- for (const provider of providers) {
660
- for (const model of provider.models) {
661
- options.push({
662
- value: `${provider.id}::${model.id}`,
663
- label: `${provider.name} / ${model.name || model.id}`,
664
- })
907
+ const providers = cloneProviders(catalogSnapshot.value);
908
+ const choices = useMemo(() => {
909
+ const rows = [];
910
+ for (const provider of providers) {
911
+ for (const model of provider.models) {
912
+ rows.push({
913
+ id: `${provider.id}::${model.id}`,
914
+ label: `${provider.name} / ${model.name || model.id}`,
915
+ });
916
+ }
665
917
  }
666
- }
918
+ return rows;
919
+ }, [catalogSnapshot.revision]);
667
920
 
668
- React.useEffect(() => {
669
- if (dirty) return
670
- const value = runtimeSnap.value ?? {}
671
- setEnabled(value.enabled !== false)
672
- setChoice(value.providerId && value.modelId ? `${value.providerId}::${value.modelId}` : '')
673
- setSize(value.defaultSize || '1024x1024')
674
- setQuality(value.defaultQuality || 'auto')
675
- }, [runtimeSnap.revision, dirty])
921
+ useEffect(() => {
922
+ if (dirty) return;
923
+ const value = runtimeSnapshot.value ?? {};
924
+ setEnabled(value.enabled !== false);
925
+ setChoice(value.providerId && value.modelId ? `${value.providerId}::${value.modelId}` : '');
926
+ setSize(value.defaultSize || DEFAULT_SIZE);
927
+ setQuality(value.defaultQuality || DEFAULT_QUALITY);
928
+ }, [runtimeSnapshot.revision, dirty]);
676
929
 
677
- if (runtimeSnap.status !== 'ready') return null
678
- const writable = runtimeSnap.writable !== false
930
+ if (runtimeSnapshot.status !== 'ready') return null;
931
+ const writable = runtimeSnapshot.writable !== false;
679
932
 
680
933
  async function save() {
681
- const [providerId, modelId] = choice.includes('::') ? choice.split('::') : ['', '']
682
- setBusy(true)
683
- setFailed(false)
934
+ const [providerId, modelId] = choice.includes('::') ? choice.split('::') : ['', ''];
935
+ setBusy(true);
936
+ setFailed(false);
684
937
  try {
685
938
  await runtime.mutate([
686
939
  { op: 'set', path: ['enabled'], value: enabled },
@@ -688,241 +941,335 @@ window.__ModuleLoader__.load({
688
941
  { op: 'set', path: ['modelId'], value: modelId || '' },
689
942
  { op: 'set', path: ['defaultSize'], value: size },
690
943
  { op: 'set', path: ['defaultQuality'], value: quality },
691
- ])
692
- const landed = runtime.getSnapshot().value
693
- if (landed?.enabled !== enabled || (landed?.providerId || '') !== (providerId || '') || (landed?.modelId || '') !== (modelId || '')) {
694
- setFailed(true)
695
- return
944
+ ]);
945
+ const landed = runtime.getSnapshot().value ?? {};
946
+ if (landed.enabled !== enabled
947
+ || (landed.providerId || '') !== (providerId || '')
948
+ || (landed.modelId || '') !== (modelId || '')) {
949
+ setFailed(true);
950
+ return;
696
951
  }
697
- setDirty(false)
698
- setOpen(false)
952
+ setDirty(false);
953
+ setOpen(false);
699
954
  } catch {
700
- setFailed(true)
955
+ setFailed(true);
701
956
  } finally {
702
- setBusy(false)
957
+ setBusy(false);
703
958
  }
704
959
  }
705
960
 
706
961
  function discard() {
707
- setDirty(false)
708
- setFailed(false)
709
- const value = runtimeSnap.value ?? {}
710
- setEnabled(value.enabled !== false)
711
- setChoice(value.providerId && value.modelId ? `${value.providerId}::${value.modelId}` : '')
712
- setSize(value.defaultSize || '1024x1024')
713
- setQuality(value.defaultQuality || 'auto')
962
+ const value = runtimeSnapshot.value ?? {};
963
+ setEnabled(value.enabled !== false);
964
+ setChoice(value.providerId && value.modelId ? `${value.providerId}::${value.modelId}` : '');
965
+ setSize(value.defaultSize || DEFAULT_SIZE);
966
+ setQuality(value.defaultQuality || DEFAULT_QUALITY);
967
+ setDirty(false);
968
+ setFailed(false);
714
969
  }
715
970
 
716
- return React.createElement('li', { style: css.pluginCard },
717
- React.createElement('button', {
718
- type: 'button', style: css.pluginHeader, 'aria-expanded': open,
971
+ return h('li', { style: css.bundleCard },
972
+ h('button', {
973
+ type: 'button',
974
+ style: css.bundleHeader,
975
+ 'aria-expanded': open,
719
976
  'aria-label': `${t(open ? 'collapse' : 'expand')}: ${t('cardTitle')}`,
720
- onClick: () => setOpen(!open),
977
+ onClick: () => setOpen((value) => !value),
721
978
  },
722
- React.createElement('span', { style: { display: 'flex', flexDirection: 'column', gap: 4, flex: 1, minWidth: 0 } },
723
- React.createElement('span', { style: css.pluginName }, t('cardTitle')),
724
- React.createElement('span', { style: css.pluginDesc }, t('cardDescription')),
979
+ h('span', { style: { display: 'flex', flexDirection: 'column', gap: 4, flex: 1, minWidth: 0 } },
980
+ h('span', { style: css.bundleName }, t('cardTitle')),
981
+ h('span', { style: css.bundleDesc }, t('cardDescription')),
725
982
  ),
726
- dirty ? React.createElement('span', { style: { ...css.meta, padding: '1px 8px', borderRadius: 999, background: 'var(--dsw-alias-bg-module-platform)' } }, t('unsaved')) : null,
727
- React.createElement('span', { style: { color: 'var(--dsw-alias-label-tertiary)', display: 'inline-flex' } },
983
+ dirty ? h('span', {
984
+ style: {
985
+ padding: '1px 8px',
986
+ borderRadius: 999,
987
+ background: 'var(--dsw-alias-bg-layer-2)',
988
+ color: 'var(--dsw-alias-state-warn-primary)',
989
+ fontSize: 12,
990
+ lineHeight: '18px',
991
+ },
992
+ }, t('unsaved')) : null,
993
+ h('span', { style: { color: 'var(--dsw-alias-label-secondary)', display: 'inline-flex' } },
728
994
  open
729
- ? (IconChevronUp ? React.createElement(IconChevronUp, { size: 14 }) : t('collapse'))
730
- : (IconChevronDown ? React.createElement(IconChevronDown, { size: 14 }) : t('expand')),
995
+ ? (IconChevronUp ? h(IconChevronUp, { size: 14 }) : t('collapse'))
996
+ : (IconChevronDown ? h(IconChevronDown, { size: 14 }) : t('expand')),
731
997
  ),
732
998
  ),
733
- open ? React.createElement('div', { style: css.pluginBody },
734
- React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 0', gap: 16 } },
735
- React.createElement('span', { style: { fontSize: 13 } }, t('enabled')),
736
- React.createElement('button', {
737
- type: 'button', role: 'switch', 'aria-checked': enabled,
738
- style: { ...css.switch, background: enabled ? 'var(--dsw-alias-brand-primary)' : 'var(--dsw-alias-border-l3)' },
739
- disabled: !writable || busy,
740
- onClick: () => { setEnabled(!enabled); setDirty(true) },
741
- }, React.createElement('span', {
999
+ open ? h('div', { style: css.bundleBody },
1000
+ h('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, padding: '8px 0' } },
1001
+ h('span', { style: { fontSize: 13 } }, t('enabled')),
1002
+ h('button', {
1003
+ type: 'button',
1004
+ role: 'switch',
1005
+ 'aria-checked': enabled,
742
1006
  style: {
743
- display: 'block', width: 16, height: 16, borderRadius: '50%',
744
- background: 'var(--dsw-alias-label-primary-foreground, #fff)',
745
- transform: enabled ? 'translateX(16px)' : 'none',
1007
+ ...css.switch,
1008
+ background: enabled ? 'var(--dsw-alias-brand-primary)' : 'var(--dsw-alias-border-l2)',
746
1009
  },
1010
+ disabled: !writable || busy,
1011
+ onClick: () => {
1012
+ setEnabled((value) => !value);
1013
+ setDirty(true);
1014
+ },
1015
+ }, h('span', {
1016
+ style: { ...css.switchKnob, transform: enabled ? 'translateX(16px)' : 'none' },
747
1017
  })),
748
1018
  ),
749
- React.createElement('p', { style: css.meta }, t('enabledHint')),
750
- options.length === 0
751
- ? React.createElement('p', { style: { ...css.meta, padding: '8px 0' } }, t('noModels'))
752
- : React.createElement(PrefRow, {
753
- label: t('pickModel'),
1019
+ h('p', { style: css.meta }, t('enabledHint')),
1020
+ choices.length === 0
1021
+ ? h('p', { style: { ...css.meta, padding: '8px 0' } }, t('noModels'))
1022
+ : h(PrefRow, {
1023
+ label: t('activeModel'),
754
1024
  value: choice,
755
1025
  disabled: !writable || busy,
756
1026
  placeholder: '—',
757
- options: [{ id: '', label: '—' }, ...options.map((row) => ({ id: row.value, label: row.label }))],
758
- onPick: (id) => { setChoice(id); setDirty(true) },
1027
+ options: [{ id: '', label: '—' }, ...choices],
1028
+ onPick: (id) => {
1029
+ setChoice(id);
1030
+ setDirty(true);
1031
+ },
759
1032
  }),
760
- options.length === 0 ? null : React.createElement('p', { style: css.meta }, t('pickHint')),
761
- React.createElement(PrefRow, {
1033
+ choices.length === 0 ? null : h('p', { style: css.meta }, t('pickHint')),
1034
+ h(PrefRow, {
762
1035
  label: t('defaultSize'),
763
1036
  value: size,
764
1037
  disabled: !writable || busy,
765
- options: ['1024x1024', '1024x1536', '1536x1024', 'auto'].map((value) => ({ id: value, label: value })),
766
- onPick: (id) => { setSize(id); setDirty(true) },
1038
+ options: SIZES.map((value) => ({ id: value, label: value })),
1039
+ onPick: (id) => {
1040
+ setSize(id);
1041
+ setDirty(true);
1042
+ },
767
1043
  }),
768
- React.createElement(PrefRow, {
1044
+ h(PrefRow, {
769
1045
  label: t('defaultQuality'),
770
1046
  value: quality,
771
1047
  disabled: !writable || busy,
772
- options: ['low', 'medium', 'high', 'auto'].map((value) => ({ id: value, label: value })),
773
- onPick: (id) => { setQuality(id); setDirty(true) },
1048
+ options: QUALITIES.map((value) => ({ id: value, label: value })),
1049
+ onPick: (id) => {
1050
+ setQuality(id);
1051
+ setDirty(true);
1052
+ },
774
1053
  }),
775
- failed ? React.createElement('p', { style: css.error }, t('saveFailed')) : null,
776
- React.createElement('div', { style: { ...css.actions, padding: '12px 0 4px' } },
777
- React.createElement('button', { type: 'button', style: css.button, disabled: !dirty || busy, onClick: discard }, t('discard')),
778
- React.createElement('button', {
779
- type: 'button', style: css.primary, disabled: !dirty || busy, onClick: save,
780
- }, busy ? t('saving') : t('save')),
1054
+ failed ? h('p', { style: css.error }, t('saveFailed')) : null,
1055
+ h('div', { style: { ...css.actions, padding: '10px 0 2px' } },
1056
+ h('button', { type: 'button', style: css.button, disabled: !dirty || busy, onClick: discard }, t('discard')),
1057
+ h('button', { type: 'button', style: css.primary, disabled: !dirty || busy, onClick: save },
1058
+ busy ? t('saving') : t('save')),
781
1059
  ),
782
1060
  ) : null,
783
- )
1061
+ );
1062
+ }
1063
+
1064
+ function RuntimeBundlePage(props) {
1065
+ if (props.view === 'summary') return null;
1066
+ return h('ul', { style: { listStyle: 'none', margin: 0, padding: 0 } },
1067
+ h(RuntimeCard, props),
1068
+ );
1069
+ }
1070
+
1071
+ function usePortal() {
1072
+ return useMemo(() => {
1073
+ if (typeof document === 'undefined') return null;
1074
+ try {
1075
+ const reactDom = require('react-dom');
1076
+ if (reactDom && typeof reactDom.createPortal === 'function') {
1077
+ return (child) => reactDom.createPortal(child, document.body);
1078
+ }
1079
+ } catch {
1080
+ // Inline positioning still works when react-dom is not exposed.
1081
+ }
1082
+ return null;
1083
+ }, []);
784
1084
  }
785
1085
 
786
- function ImageLightbox({ src, alt, labels, onClose }) {
787
- React.useEffect(() => {
788
- const onKey = (event) => { if (event.key === 'Escape') onClose() }
789
- window.addEventListener('keydown', onKey)
790
- return () => window.removeEventListener('keydown', onKey)
791
- }, [onClose])
792
- return React.createElement('div', {
793
- role: 'dialog', 'aria-label': labels.dialog,
1086
+ function Lightbox({ src, alt, labels, onClose }) {
1087
+ const portal = usePortal();
1088
+ useEffect(() => {
1089
+ const onKey = (event) => {
1090
+ if (event.key === 'Escape') onClose();
1091
+ };
1092
+ window.addEventListener('keydown', onKey);
1093
+ return () => window.removeEventListener('keydown', onKey);
1094
+ }, [onClose]);
1095
+ const node = h('div', {
1096
+ role: 'dialog',
1097
+ 'aria-label': labels.dialog,
794
1098
  style: {
795
- position: 'fixed', inset: 0, zIndex: 10000, display: 'grid', placeItems: 'center',
796
- background: 'rgba(0,0,0,.72)', padding: 24,
1099
+ position: 'fixed',
1100
+ inset: 0,
1101
+ zIndex: 10000,
1102
+ display: 'grid',
1103
+ placeItems: 'center',
1104
+ padding: 24,
1105
+ background: 'rgba(0, 0, 0, .72)',
797
1106
  },
798
1107
  onClick: onClose,
799
1108
  },
800
- React.createElement('img', {
801
- src, alt, style: { maxWidth: '92vw', maxHeight: '92vh', objectFit: 'contain', borderRadius: 4 },
1109
+ h('img', {
1110
+ src,
1111
+ alt,
1112
+ style: { maxWidth: '92vw', maxHeight: '92vh', objectFit: 'contain', borderRadius: 6 },
802
1113
  onClick: (event) => event.stopPropagation(),
803
1114
  }),
804
- React.createElement('button', {
805
- type: 'button', 'aria-label': labels.close,
1115
+ h('button', {
1116
+ type: 'button',
1117
+ 'aria-label': labels.close,
806
1118
  style: {
807
- position: 'absolute', top: 12, right: 12, width: 32, height: 32, border: 'none',
808
- borderRadius: '50%', cursor: 'pointer', background: 'rgba(255,255,255,.16)', color: '#fff',
809
- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
1119
+ position: 'absolute',
1120
+ top: 12,
1121
+ right: 12,
1122
+ display: 'inline-flex',
1123
+ alignItems: 'center',
1124
+ justifyContent: 'center',
1125
+ width: 32,
1126
+ height: 32,
1127
+ border: 'none',
1128
+ borderRadius: '50%',
1129
+ background: 'rgba(255, 255, 255, .16)',
1130
+ color: '#fff',
1131
+ cursor: 'pointer',
810
1132
  },
811
1133
  onClick: onClose,
812
- }, IconClose ? React.createElement(IconClose, { size: 16 }) : labels.close),
813
- )
1134
+ }, IconClose ? h(IconClose, { size: 16 }) : labels.close),
1135
+ );
1136
+ return portal ? portal(node) : node;
814
1137
  }
815
1138
 
816
1139
  function MessageImage({ image, load, cwd, labels }) {
817
- const [src, setSrc] = React.useState(null)
818
- const [error, setError] = React.useState(false)
819
- const [open, setOpen] = React.useState(false)
820
- const [tick, setTick] = React.useState(0)
821
- const key = image?.attachment?.attachmentId ?? image?.path ?? ''
822
- React.useEffect(() => {
823
- let cancelled = false
824
- setError(false)
825
- setSrc(null)
826
- Promise.resolve(load(image, cwd)).then((url) => {
827
- if (!cancelled) setSrc(url)
828
- }, () => {
829
- if (!cancelled) setError(true)
830
- })
831
- return () => { cancelled = true }
832
- }, [key, load, cwd, tick])
833
- if (error) {
834
- return React.createElement('button', {
835
- type: 'button', style: { fontSize: 12, color: 'var(--dsw-alias-state-error-primary)' },
836
- onClick: () => { setError(false); setTick((n) => n + 1) },
837
- }, labels.loadFailed)
1140
+ const [src, setSrc] = useState(null);
1141
+ const [failed, setFailed] = useState(false);
1142
+ const [open, setOpen] = useState(false);
1143
+ const [attempt, setAttempt] = useState(0);
1144
+ const key = image?.attachment?.attachmentId ?? image?.path ?? '';
1145
+ useEffect(() => {
1146
+ let cancelled = false;
1147
+ setFailed(false);
1148
+ setSrc(null);
1149
+ Promise.resolve()
1150
+ .then(() => load(image, cwd))
1151
+ .then((url) => {
1152
+ if (!cancelled) setSrc(url);
1153
+ }, () => {
1154
+ if (!cancelled) setFailed(true);
1155
+ });
1156
+ return () => {
1157
+ cancelled = true;
1158
+ };
1159
+ }, [key, load, cwd, attempt]);
1160
+ if (failed) {
1161
+ return h('button', {
1162
+ type: 'button',
1163
+ style: { ...css.button, borderColor: 'var(--dsw-alias-state-error-primary)', color: 'var(--dsw-alias-state-error-primary)' },
1164
+ onClick: () => {
1165
+ setFailed(false);
1166
+ setAttempt((value) => value + 1);
1167
+ },
1168
+ }, labels.loadFailed);
838
1169
  }
839
- if (!src) return React.createElement('span', { style: { fontSize: 12, color: 'var(--dsw-alias-label-tertiary)' } }, labels.loading)
840
- return React.createElement(React.Fragment, null,
841
- React.createElement('button', {
1170
+ if (!src) return h('span', { style: css.meta }, labels.loading);
1171
+ return h(React.Fragment, null,
1172
+ h('button', {
842
1173
  type: 'button',
843
1174
  style: {
844
- display: 'grid', placeItems: 'center', overflow: 'hidden', padding: 0, borderRadius: 8,
845
- border: '1px solid var(--dsw-alias-border-l2)', cursor: 'zoom-in', width: 240, maxWidth: '100%',
1175
+ display: 'grid',
1176
+ placeItems: 'center',
1177
+ width: 240,
1178
+ maxWidth: '100%',
1179
+ padding: 0,
1180
+ overflow: 'hidden',
1181
+ border: '1px solid var(--dsw-alias-border-l2)',
1182
+ borderRadius: 8,
1183
+ background: 'var(--dsw-alias-bg-layer-2)',
1184
+ cursor: 'zoom-in',
846
1185
  },
847
- onClick: () => setOpen(true), 'aria-label': labels.open,
848
- }, React.createElement('img', { src, alt: labels.image, style: { width: '100%', display: 'block' } })),
849
- open ? React.createElement(ImageLightbox, { src, alt: labels.image, labels, onClose: () => setOpen(false) }) : null,
850
- )
1186
+ 'aria-label': labels.open,
1187
+ onClick: () => setOpen(true),
1188
+ }, h('img', { src, alt: labels.image, style: { display: 'block', width: '100%' } })),
1189
+ open ? h(Lightbox, { src, alt: labels.image, labels, onClose: () => setOpen(false) }) : null,
1190
+ );
851
1191
  }
852
1192
 
853
- function derivePrompt(argsRaw) {
854
- let parsed
855
- try { parsed = JSON.parse(argsRaw) } catch { parsed = undefined }
856
- let prompt
857
- if (typeof parsed === 'object' && parsed !== null && typeof parsed.prompt === 'string') prompt = parsed.prompt
858
- const line = String(prompt ?? argsRaw).split('\n', 1)[0] ?? ''
859
- return line.length > 60 ? `${line.slice(0, 59)}…` : line
1193
+ function promptFromArgs(argsRaw) {
1194
+ let parsed;
1195
+ try {
1196
+ parsed = JSON.parse(argsRaw);
1197
+ } catch {
1198
+ parsed = undefined;
1199
+ }
1200
+ const prompt = typeof parsed?.prompt === 'string' ? parsed.prompt : String(argsRaw ?? '');
1201
+ const line = prompt.split('\n', 1)[0] ?? '';
1202
+ return line.length > 60 ? `${line.slice(0, 59)}…` : line;
860
1203
  }
861
1204
 
862
- function resultImages(block) {
863
- if (!block || !('kind' in block)) return []
864
- const images = []
1205
+ function resultText(block) {
1206
+ if (!block || typeof block !== 'object' || !('kind' in block)) return '';
1207
+ const parts = [];
865
1208
  for (const part of block.content ?? []) {
866
- if (part.type === 'image' && part.attachment) images.push({ attachment: part.attachment })
867
- }
868
- if (images.length > 0) return images
869
- const text = resultText(block)
870
- for (const line of text.split('\n')) {
871
- const match = line.match(/^\s*-\s+(\S+\.(?:png|jpe?g|webp|gif))\s*$/i)
872
- if (match) images.push({ path: match[1] })
1209
+ if (part.type === 'text') parts.push(part.text);
873
1210
  }
874
- return images
1211
+ if (parts.length === 0 && block.error) parts.push(`${block.error.name}: ${block.error.code}`);
1212
+ return parts.join('\n');
875
1213
  }
876
1214
 
877
- function resultText(block) {
878
- if (!block || !('kind' in block)) return ''
879
- const parts = []
880
- for (const part of block.content ?? []) if (part.type === 'text') parts.push(part.text)
881
- if (parts.length === 0 && block.error) parts.push(`${block.error.name}: ${block.error.code}`)
882
- return parts.join('\n')
1215
+ function resultImages(block) {
1216
+ if (!block || typeof block !== 'object' || !('kind' in block)) return [];
1217
+ const images = [];
1218
+ for (const part of block.content ?? []) {
1219
+ if (part.type === 'image' && part.attachment) images.push({ attachment: part.attachment });
1220
+ }
1221
+ if (images.length > 0) return images;
1222
+ // Older Hosts rendered paths into the text block only. Keep those
1223
+ // sessions viewable by recovering the same paths the tool printed.
1224
+ for (const line of resultText(block).split('\n')) {
1225
+ const match = line.match(/^\s*-\s+(\S+\.(?:png|jpe?g|webp|gif))\s*$/i);
1226
+ if (match) images.push({ path: match[1] });
1227
+ }
1228
+ return images;
883
1229
  }
884
1230
 
885
1231
  function ImageGenerateToolview(props) {
886
- const { block } = props
887
- const t = props.t ?? translateFactory(en)
888
- if (block === undefined) return null
889
- // DSH >= 0.1.7 hands explicit phases (preparing/start/result) and an
890
- // owner-provided session-authorized image loader; older runtimes
891
- // discriminate the node by its `kind` field and use the injected loader.
892
- const phase = typeof props.phase === 'string' ? props.phase : ('kind' in block ? 'result' : 'start')
893
- const settled = phase === 'result'
894
- const argsRaw = (settled ? block.call?.argsRaw : block.argsRaw) ?? ''
895
- const title = `image_generate: ${derivePrompt(argsRaw)}`
896
- const images = resultImages(block)
897
- const text = settled ? resultText(block) : ''
898
- const load = (image, cwd) => {
899
- if (image?.attachment && typeof props.loadImage === 'function') {
900
- return Promise.resolve(props.loadImage(image.attachment))
901
- }
902
- if (typeof props.load === 'function') return props.load(image, cwd)
903
- return Promise.reject(new Error('no image loader'))
904
- }
905
- const Sparkle = IconSparkle
1232
+ const t = props.t ?? translate(en);
1233
+ const block = props.block;
1234
+ if (block === undefined || block === null) return null;
1235
+ const phase = typeof props.phase === 'string' ? props.phase : ('kind' in block ? 'result' : 'start');
1236
+ const settled = phase === 'result';
1237
+ const argsRaw = (settled ? block.call?.argsRaw : block.argsRaw) ?? '';
1238
+ const images = resultImages(block);
1239
+ const text = settled ? resultText(block) : '';
906
1240
  const labels = {
907
1241
  image: t('image'),
908
1242
  open: t('viewImage'),
909
1243
  loading: t('imageLoading'),
910
1244
  loadFailed: t('imageLoadFailed'),
911
1245
  dialog: t('imagePreview'),
912
- close: t('imageClose'),
913
- }
914
- return React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 6, padding: '4px 0' } },
915
- React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 6 } },
916
- Sparkle ? React.createElement(Sparkle, { size: 14 }) : null,
917
- React.createElement('span', {
918
- style: { fontSize: 13, lineHeight: '20px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
919
- }, title),
1246
+ close: t('close'),
1247
+ };
1248
+ const load = (image, cwd) => {
1249
+ if (image?.attachment && typeof props.loadImage === 'function') {
1250
+ return Promise.resolve(props.loadImage(image.attachment));
1251
+ }
1252
+ if (typeof props.load === 'function') return props.load(image, cwd);
1253
+ return Promise.reject(new Error('no image loader'));
1254
+ };
1255
+ return h('div', { style: { display: 'flex', flexDirection: 'column', gap: 6, padding: '4px 0' } },
1256
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 6 } },
1257
+ IconSparkle ? h(IconSparkle, { size: 14 }) : null,
1258
+ h('span', {
1259
+ style: {
1260
+ fontSize: 13,
1261
+ lineHeight: '20px',
1262
+ overflow: 'hidden',
1263
+ textOverflow: 'ellipsis',
1264
+ whiteSpace: 'nowrap',
1265
+ },
1266
+ }, `${TOOL_NAME}: ${promptFromArgs(argsRaw)}`),
920
1267
  ),
921
- !settled ? React.createElement('p', { style: css.meta }, t('generating')) : null,
922
- settled && block.isError && text ? React.createElement('p', { style: css.error }, text.split('\n', 1)[0]) : null,
923
- settled && !block.isError && images.length > 0 && load
924
- ? React.createElement('div', { style: { display: 'flex', flexWrap: 'wrap', gap: 8 } },
925
- images.map((image, index) => React.createElement(MessageImage, {
1268
+ !settled ? h('p', { style: css.meta }, t('generating')) : null,
1269
+ settled && block.isError && text ? h('p', { style: css.error }, text.split('\n', 1)[0]) : null,
1270
+ settled && !block.isError && images.length > 0
1271
+ ? h('div', { style: { display: 'flex', flexWrap: 'wrap', gap: 8 } },
1272
+ images.map((image, index) => h(MessageImage, {
926
1273
  key: image.attachment?.attachmentId ?? image.path ?? index,
927
1274
  image,
928
1275
  load,
@@ -931,160 +1278,148 @@ window.__ModuleLoader__.load({
931
1278
  })))
932
1279
  : null,
933
1280
  settled && !block.isError && images.length === 0 && text
934
- ? React.createElement('p', { style: { ...css.meta, whiteSpace: 'pre-wrap' } }, text)
1281
+ ? h('p', { style: { ...css.meta, whiteSpace: 'pre-wrap' } }, text)
935
1282
  : null,
936
- )
1283
+ );
937
1284
  }
938
1285
 
939
1286
  async function callImageGen(rpc, endpoint, payload) {
940
- const result = await rpc.call(RPC_CHANNEL, endpoint, payload)
941
- if (!result.ok) throw new Error(result.error.message)
942
- return result.value
1287
+ const result = await rpc.call(RPC_CHANNEL, endpoint, payload);
1288
+ if (!result || result.ok !== true) throw new Error(result?.error?.message ?? 'image request failed');
1289
+ return result.value;
943
1290
  }
944
1291
 
945
1292
  function createImageLoader(rpc) {
946
1293
  return (image, cwd) => {
947
1294
  const request = image?.attachment
948
1295
  ? callImageGen(rpc, 'image', { ...image.attachment })
949
- : callImageGen(rpc, 'file', { path: image?.path, cwd: cwd || '' })
950
- return request.then((result) => `data:${result.mediaType};base64,${result.dataBase64}`)
951
- }
1296
+ : callImageGen(rpc, 'file', { path: image?.path, cwd: cwd || '' });
1297
+ return request.then((value) => `data:${value.mediaType};base64,${value.dataBase64}`);
1298
+ };
952
1299
  }
953
1300
 
954
1301
  /**
955
- * Adapt a DSH >= 0.1.6 `configForms` entry form to the settingsScope shape
956
- * the cards were written against (set(key, value) + mutate(ops)).
957
- * `pick` projects the merged entry config into one card's section view.
1302
+ * Project the merged entry form into one card's slice. The Host stores the
1303
+ * catalog and the picker in the same entry; each card only sees the fields
1304
+ * it owns, so a save from one card cannot blank the other's values.
958
1305
  */
959
1306
  function adaptConfigForm(form, pick) {
960
1307
  return {
961
1308
  getSnapshot() {
962
- const snap = form.getSnapshot()
1309
+ const snapshot = form.getSnapshot();
963
1310
  return {
964
- status: snap.status,
965
- value: snap.value === undefined ? undefined : pick(snap.value),
966
- writable: snap.writable,
967
- revision: snap.revision,
968
- }
1311
+ status: snapshot.status,
1312
+ value: snapshot.value === undefined ? undefined : pick(snapshot.value),
1313
+ writable: snapshot.writable,
1314
+ revision: snapshot.revision,
1315
+ };
969
1316
  },
970
1317
  subscribe: (callback) => form.subscribe(callback),
971
1318
  set(key, value) {
972
- return form.mutate([{ op: 'set', path: [key], value }])
1319
+ return form.mutate([{ op: 'set', path: [key], value }]);
973
1320
  },
974
1321
  mutate(ops, expectedRevision) {
975
- return form.mutate(ops, expectedRevision)
1322
+ return form.mutate(ops, expectedRevision);
976
1323
  },
977
- }
1324
+ };
978
1325
  }
979
1326
 
980
- /** Inert scope for runtimes with no settings surface at all. */
981
1327
  function unavailableScope() {
982
1328
  return {
983
1329
  getSnapshot: () => ({ status: 'unavailable', value: undefined, writable: false, revision: undefined }),
984
1330
  subscribe: () => () => {},
985
1331
  set: () => Promise.resolve(false),
986
1332
  mutate: () => Promise.resolve(false),
987
- }
1333
+ };
988
1334
  }
989
1335
 
990
- /**
991
- * Bind the catalog/runtime scopes on whichever settings surface this
992
- * runtime has: DSH <= 0.1.5 serves two `settingsScope` namespaces;
993
- * DSH >= 0.1.6 serves one merged `configForms` entry (`image-gen`) whose
994
- * volatile fields carry both.
995
- */
996
1336
  function bindScopes(ctx) {
997
- const settingsScope = ctx.get('settingsScope')
1337
+ const settingsScope = ctx.get('settingsScope');
998
1338
  if (settingsScope && typeof settingsScope.bind === 'function') {
999
1339
  return {
1000
1340
  legacy: true,
1001
1341
  catalog: settingsScope.bind({ namespace: CATALOG_NS }),
1002
1342
  runtime: settingsScope.bind({ namespace: RUNTIME_NS }),
1003
- }
1343
+ };
1004
1344
  }
1005
- const configForms = ctx.get('configForms')
1345
+ const configForms = ctx.get('configForms');
1006
1346
  if (configForms && typeof configForms.get === 'function') {
1007
- const form = configForms.get(CATALOG_NS)
1008
- return {
1009
- legacy: false,
1010
- configForms,
1011
- catalog: adaptConfigForm(form, (value) => ({
1012
- providers: Array.isArray(value?.providers) ? value.providers : [],
1013
- })),
1014
- runtime: adaptConfigForm(form, (value) => ({
1015
- enabled: value?.enabled !== false,
1016
- providerId: value?.providerId ?? '',
1017
- modelId: value?.modelId ?? '',
1018
- defaultSize: value?.defaultSize ?? '1024x1024',
1019
- defaultQuality: value?.defaultQuality ?? 'auto',
1020
- })),
1347
+ const form = configForms.get(CATALOG_NS);
1348
+ if (form && typeof form.getSnapshot === 'function') {
1349
+ return {
1350
+ legacy: false,
1351
+ configForms,
1352
+ catalog: adaptConfigForm(form, (value) => ({
1353
+ providers: Array.isArray(value?.providers) ? value.providers : [],
1354
+ })),
1355
+ runtime: adaptConfigForm(form, (value) => ({
1356
+ enabled: value?.enabled !== false,
1357
+ providerId: value?.providerId ?? '',
1358
+ modelId: value?.modelId ?? '',
1359
+ defaultSize: value?.defaultSize ?? DEFAULT_SIZE,
1360
+ defaultQuality: value?.defaultQuality ?? DEFAULT_QUALITY,
1361
+ })),
1362
+ };
1021
1363
  }
1022
1364
  }
1023
- return { legacy: true, catalog: unavailableScope(), runtime: unavailableScope() }
1365
+ return { legacy: true, catalog: unavailableScope(), runtime: unavailableScope() };
1024
1366
  }
1025
1367
 
1026
- /** plugins.bundle.config page (DSH >= 0.1.6): the runtime picker card. */
1027
- function RuntimeBundlePage(props) {
1028
- if (props.view === 'summary') return null
1029
- return React.createElement('ul', { style: { listStyle: 'none', margin: 0, padding: 0 } },
1030
- React.createElement(RuntimeCard, props))
1031
- }
1032
-
1033
- // 'settingsScope' was removed in DSH 0.1.7 (replaced by 'configForms') and
1034
- // must not be a hard inject, or this client half never activates there.
1035
- const inject = ['slots', 'locale', 'remote', 'remote.credentials', 'connection']
1368
+ const inject = ['slots', 'locale', 'remote', 'remote.credentials', 'connection'];
1036
1369
 
1037
1370
  function apply(ctx) {
1038
- ensureSelectCss()
1039
- ctx.effect(() => ctx.locale.register(LOCALE_NS, { zh, en }), 'dsh-image-generation: copy dictionaries')
1040
- const t = ctx.locale.bind(LOCALE_NS)
1041
- const { legacy, configForms, catalog, runtime } = bindScopes(ctx)
1042
- const connection = ctx.get('connection')
1371
+ ensureStyles();
1372
+ ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'dsh-image-generation: copy dictionaries');
1373
+ const t = ctx.locale.bind(NS);
1374
+ const scopes = bindScopes(ctx);
1375
+ const connection = ctx.get('connection');
1376
+ const credentials = ctx.remote?.credentials;
1043
1377
 
1044
1378
  ctx.slots.inject('settings.section', () => ctx.slots.register({
1045
1379
  name: 'settings.section',
1046
1380
  id: 'image-gen',
1047
1381
  order: 85,
1048
1382
  label: () => t('nav'),
1049
- locale: LOCALE_NS,
1050
- inject: () => ({
1051
- catalog,
1052
- credentials: ctx.remote.credentials,
1053
- }),
1054
- }, CatalogSection))
1383
+ locale: NS,
1384
+ inject: () => ({ catalog: scopes.catalog, credentials, t }),
1385
+ }, CatalogSection));
1055
1386
 
1056
- if (legacy) {
1057
- // DSH <= 0.1.5: the model picker is a card on the Settings plugins page.
1387
+ if (scopes.legacy) {
1388
+ // DSH <= 0.1.5: the model picker lives on the Settings plugins page.
1058
1389
  ctx.slots.inject('settings.plugin.item', () => ctx.slots.register({
1059
1390
  name: 'settings.plugin.item',
1060
1391
  key: RUNTIME_NS,
1061
1392
  priority: 1000,
1062
- locale: LOCALE_NS,
1063
- inject: () => ({ catalog, runtime }),
1064
- }, RuntimeCard))
1065
- } else if (configForms) {
1066
- // DSH >= 0.1.6: the picker lives on this bundle's Plugins page instead.
1067
- ctx.effect(() => configForms.whileServed([CATALOG_NS], () =>
1068
- ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({
1069
- name: 'plugins.bundle.config',
1070
- key: 'dsh-image-generation',
1071
- locale: LOCALE_NS,
1072
- inject: () => ({ catalog, runtime }),
1073
- }, RuntimeBundlePage))), 'dsh-image-generation: plugins page')
1393
+ locale: NS,
1394
+ inject: () => ({ catalog: scopes.catalog, runtime: scopes.runtime, t }),
1395
+ }, RuntimeCard));
1396
+ } else if (scopes.configForms) {
1397
+ // DSH >= 0.1.6: the picker is the bundle's own configuration page.
1398
+ // `whileServed` keeps the registration mounted only while the entry is
1399
+ // actually served by this settings backend.
1400
+ const registerPage = () => ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({
1401
+ name: 'plugins.bundle.config',
1402
+ key: '@qzsy/dsh-image-generation',
1403
+ locale: NS,
1404
+ inject: () => ({ catalog: scopes.catalog, runtime: scopes.runtime, t }),
1405
+ }, RuntimeBundlePage));
1406
+ if (typeof scopes.configForms.whileServed === 'function') {
1407
+ ctx.effect(() => scopes.configForms.whileServed([CATALOG_NS], registerPage), 'dsh-image-generation: plugins page');
1408
+ } else {
1409
+ registerPage();
1410
+ }
1074
1411
  }
1075
1412
 
1076
1413
  if (connection?.rpc) {
1077
1414
  ctx.slots.inject('tool.call.toolview', () => ctx.slots.register({
1078
1415
  name: 'tool.call.toolview',
1079
- key: 'image_generate',
1080
- locale: LOCALE_NS,
1081
- inject: () => ({ load: createImageLoader(connection.rpc) }),
1082
- }, ImageGenerateToolview))
1416
+ key: TOOL_NAME,
1417
+ locale: NS,
1418
+ inject: () => ({ load: createImageLoader(connection.rpc), t }),
1419
+ }, ImageGenerateToolview));
1083
1420
  }
1084
1421
  }
1085
1422
 
1086
- exports.apply = apply
1087
- exports.inject = inject
1088
- return module.exports
1423
+ return { inject, apply };
1089
1424
  },
1090
- })
1425
+ });