@qzsy/dsh-image-generation 0.0.0-stage → 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 ADDED
@@ -0,0 +1,1425 @@
1
+ /**
2
+ * Client half of `@qzsy/dsh-image-generation`.
3
+ *
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.
26
+ */
27
+ window.__ModuleLoader__.load({
28
+ id: '@qzsy/dsh-image-generation',
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;
34
+
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;
51
+
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;
65
+
66
+ const API_FORMATS = [
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
+ ];
88
+
89
+ const zh = {
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
+ };
204
+
205
+ function translate(dict) {
206
+ return (key, params) => {
207
+ let text = dict[key] ?? en[key] ?? key;
208
+ for (const [name, value] of Object.entries(params ?? {})) {
209
+ text = String(text).replaceAll(`{${name}}`, String(value));
210
+ }
211
+ return text;
212
+ };
213
+ }
214
+
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
+ `;
268
+
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);
276
+ }
277
+
278
+ const css = {
279
+ section: {
280
+ display: 'flex',
281
+ flexDirection: 'column',
282
+ gap: 14,
283
+ maxWidth: 720,
284
+ color: 'var(--dsw-alias-label-primary)',
285
+ },
286
+ title: { margin: 0, fontSize: 18, fontWeight: 600, lineHeight: '26px' },
287
+ intro: { margin: 0, color: 'var(--dsw-alias-label-secondary)', fontSize: 14, lineHeight: '22px' },
288
+ card: {
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)',
296
+ },
297
+ row: { display: 'flex', alignItems: 'center', gap: 8 },
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 },
301
+ label: { fontSize: 12, lineHeight: '18px', color: 'var(--dsw-alias-label-secondary)' },
302
+ input: {
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',
314
+ },
315
+ modelRow: {
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,
322
+ },
323
+ button: {
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',
338
+ cursor: 'pointer',
339
+ },
340
+ primary: {
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',
354
+ },
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',
369
+ },
370
+ error: { margin: 0, fontSize: 12, lineHeight: '18px', color: 'var(--dsw-alias-state-error-primary)' },
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,
380
+ },
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',
395
+ },
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' },
399
+ switch: {
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',
410
+ },
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
+ };
422
+
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, {
436
+ open,
437
+ onClose: () => setOpen(false),
438
+ items: props.options,
439
+ selectedId: props.value,
440
+ onSelect: (id) => {
441
+ setOpen(false);
442
+ props.onPick(id);
443
+ },
444
+ align: 'end',
445
+ portal: true,
446
+ dense: true,
447
+ anchor: h('button', {
448
+ type: 'button',
449
+ className: 'dsh-ig-select dsh-ig-focus',
450
+ disabled: props.disabled || props.options.length === 0,
451
+ 'aria-haspopup': 'menu',
452
+ 'aria-expanded': open,
453
+ 'aria-label': props.label,
454
+ onClick: () => setOpen((value) => !value),
455
+ },
456
+ h('span', { className: 'dsh-ig-select-label' }, active),
457
+ IconChevronDown ? h(IconChevronDown, { size: 14 }) : null,
458
+ ),
459
+ });
460
+ }
461
+
462
+ function PrefRow(props) {
463
+ return h('div', { style: css.prefRow },
464
+ h('span', { style: css.prefLabel }, props.label),
465
+ h(Select, {
466
+ label: props.label,
467
+ value: props.value,
468
+ options: props.options,
469
+ disabled: props.disabled,
470
+ placeholder: props.placeholder,
471
+ onPick: props.onPick,
472
+ }),
473
+ );
474
+ }
475
+
476
+ function IconButton(props) {
477
+ return h('button', {
478
+ type: 'button',
479
+ style: { ...css.iconButton, ...props.style },
480
+ disabled: props.disabled,
481
+ 'aria-label': props.label,
482
+ title: props.label,
483
+ onClick: props.onClick,
484
+ }, props.children);
485
+ }
486
+
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));
513
+ }
514
+
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;
522
+ }
523
+
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 ?? '';
561
+ }
562
+
563
+ function ProviderEditor(props) {
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',
574
+ style: { ...css.input, fontWeight: 600 },
575
+ value: draft.name,
576
+ placeholder: t('providerName'),
577
+ 'aria-label': t('providerName'),
578
+ disabled: !writable || busy,
579
+ onChange: (event) => setDraft({ ...draft, name: event.target.value }),
580
+ }),
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')),
587
+ ),
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,
597
+ onChange: (event) => setDraft({ ...draft, baseUrl: event.target.value }),
598
+ }),
599
+ ),
600
+ h('div', { style: css.field },
601
+ h(PrefRow, {
602
+ label: t('apiFormat'),
603
+ value: draft.apiFormat,
604
+ disabled: !writable || busy,
605
+ options: API_FORMATS.map((row) => ({ id: row.id, label: row.label })),
606
+ onPick: (id) => setDraft({ ...draft, apiFormat: id }),
607
+ }),
608
+ h('p', { style: css.meta }, formatHint(draft.apiFormat)),
609
+ ),
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'),
621
+ disabled: !writable || busy,
622
+ onChange: (event) => setKeyDraft(event.target.value),
623
+ }),
624
+ ),
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',
630
+ style: { ...css.input, flex: 1 },
631
+ value: model.id,
632
+ placeholder: t('modelId'),
633
+ 'aria-label': t('modelId'),
634
+ disabled: !writable || busy,
635
+ onChange: (event) => updateModel(index, { id: event.target.value }),
636
+ }),
637
+ h('input', {
638
+ className: 'dsh-ig-focus',
639
+ style: { ...css.input, flex: 1 },
640
+ value: model.name,
641
+ placeholder: t('modelName'),
642
+ 'aria-label': t('modelName'),
643
+ disabled: !writable || busy,
644
+ onChange: (event) => updateModel(index, { name: event.target.value }),
645
+ }),
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')),
651
+ )),
652
+ h('button', {
653
+ type: 'button',
654
+ style: { ...css.button, alignSelf: 'flex-start', marginTop: 2 },
655
+ disabled: !writable || busy,
656
+ onClick: () => setDraft({ ...draft, models: [...draft.models, { id: '', name: '' }] }),
657
+ }, IconPlus ? h(IconPlus, { size: 14 }) : null, t('addModel')),
658
+ ),
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,
667
+ }, busy ? t('saving') : t('save')),
668
+ ),
669
+ );
670
+ }
671
+
672
+ function CatalogSection(props) {
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('');
684
+
685
+ const providers = cloneProviders(snapshot.value);
686
+ const writable = snapshot.writable !== false && snapshot.status === 'ready';
687
+
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]);
703
+
704
+ useEffect(() => {
705
+ if (snapshot.status === 'ready') void refreshKeys(providers);
706
+ }, [snapshot.status, snapshot.revision]);
707
+
708
+ function startCreate() {
709
+ setCreating(true);
710
+ setEditingId('__new__');
711
+ setDraft({
712
+ id: '',
713
+ name: '',
714
+ baseUrl: '',
715
+ apiFormat: 'openai-images',
716
+ apiKeyEnv: '',
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('');
740
+ }
741
+
742
+ function validate(next) {
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();
750
+ for (const model of models) {
751
+ if (!model.id) return t('modelIdRequired');
752
+ if (seen.has(model.id)) return t('modelIdDuplicate');
753
+ seen.add(model.id);
754
+ }
755
+ return '';
756
+ }
757
+
758
+ async function save() {
759
+ const message = validate(draft);
760
+ if (message) {
761
+ setError(message);
762
+ return;
763
+ }
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;
772
+ const record = {
773
+ id,
774
+ name: String(draft.name).trim(),
775
+ baseUrl: String(draft.baseUrl).trim(),
776
+ apiFormat: draft.apiFormat || 'openai-images',
777
+ apiKeyEnv: draft.apiKeyEnv || apiKeyEnvFor(id),
778
+ models,
779
+ };
780
+ const next = creating
781
+ ? [...providers, record]
782
+ : providers.map((row) => (row.id === id ? record : row));
783
+ setBusy(true);
784
+ setError('');
785
+ try {
786
+ await scope.set('providers', next);
787
+ const landed = cloneProviders(scope.getSnapshot().value);
788
+ if (!landed.some((row) => row.id === id && row.baseUrl === record.baseUrl)) {
789
+ throw new Error(t('saveFailed'));
790
+ }
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('');
799
+ }
800
+ await refreshKeys(next);
801
+ stopEdit();
802
+ } catch (failure) {
803
+ setError(String(failure?.message || t('saveFailed')));
804
+ } finally {
805
+ setBusy(false);
806
+ }
807
+ }
808
+
809
+ async function remove(id) {
810
+ setBusy(true);
811
+ setError('');
812
+ try {
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')));
818
+ } finally {
819
+ setBusy(false);
820
+ }
821
+ }
822
+
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
+ );
828
+ }
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
+ );
834
+ }
835
+
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),
868
+ }, t('edit')),
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')),
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'))),
880
+ ),
881
+ )),
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
+ );
890
+ }
891
+
892
+ function RuntimeCard(props) {
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);
906
+
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
+ }
917
+ }
918
+ return rows;
919
+ }, [catalogSnapshot.revision]);
920
+
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]);
929
+
930
+ if (runtimeSnapshot.status !== 'ready') return null;
931
+ const writable = runtimeSnapshot.writable !== false;
932
+
933
+ async function save() {
934
+ const [providerId, modelId] = choice.includes('::') ? choice.split('::') : ['', ''];
935
+ setBusy(true);
936
+ setFailed(false);
937
+ try {
938
+ await runtime.mutate([
939
+ { op: 'set', path: ['enabled'], value: enabled },
940
+ { op: 'set', path: ['providerId'], value: providerId || '' },
941
+ { op: 'set', path: ['modelId'], value: modelId || '' },
942
+ { op: 'set', path: ['defaultSize'], value: size },
943
+ { op: 'set', path: ['defaultQuality'], value: quality },
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;
951
+ }
952
+ setDirty(false);
953
+ setOpen(false);
954
+ } catch {
955
+ setFailed(true);
956
+ } finally {
957
+ setBusy(false);
958
+ }
959
+ }
960
+
961
+ function discard() {
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);
969
+ }
970
+
971
+ return h('li', { style: css.bundleCard },
972
+ h('button', {
973
+ type: 'button',
974
+ style: css.bundleHeader,
975
+ 'aria-expanded': open,
976
+ 'aria-label': `${t(open ? 'collapse' : 'expand')}: ${t('cardTitle')}`,
977
+ onClick: () => setOpen((value) => !value),
978
+ },
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')),
982
+ ),
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' } },
994
+ open
995
+ ? (IconChevronUp ? h(IconChevronUp, { size: 14 }) : t('collapse'))
996
+ : (IconChevronDown ? h(IconChevronDown, { size: 14 }) : t('expand')),
997
+ ),
998
+ ),
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,
1006
+ style: {
1007
+ ...css.switch,
1008
+ background: enabled ? 'var(--dsw-alias-brand-primary)' : 'var(--dsw-alias-border-l2)',
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' },
1017
+ })),
1018
+ ),
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'),
1024
+ value: choice,
1025
+ disabled: !writable || busy,
1026
+ placeholder: '—',
1027
+ options: [{ id: '', label: '—' }, ...choices],
1028
+ onPick: (id) => {
1029
+ setChoice(id);
1030
+ setDirty(true);
1031
+ },
1032
+ }),
1033
+ choices.length === 0 ? null : h('p', { style: css.meta }, t('pickHint')),
1034
+ h(PrefRow, {
1035
+ label: t('defaultSize'),
1036
+ value: size,
1037
+ disabled: !writable || busy,
1038
+ options: SIZES.map((value) => ({ id: value, label: value })),
1039
+ onPick: (id) => {
1040
+ setSize(id);
1041
+ setDirty(true);
1042
+ },
1043
+ }),
1044
+ h(PrefRow, {
1045
+ label: t('defaultQuality'),
1046
+ value: quality,
1047
+ disabled: !writable || busy,
1048
+ options: QUALITIES.map((value) => ({ id: value, label: value })),
1049
+ onPick: (id) => {
1050
+ setQuality(id);
1051
+ setDirty(true);
1052
+ },
1053
+ }),
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')),
1059
+ ),
1060
+ ) : null,
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
+ }, []);
1084
+ }
1085
+
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,
1098
+ style: {
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)',
1106
+ },
1107
+ onClick: onClose,
1108
+ },
1109
+ h('img', {
1110
+ src,
1111
+ alt,
1112
+ style: { maxWidth: '92vw', maxHeight: '92vh', objectFit: 'contain', borderRadius: 6 },
1113
+ onClick: (event) => event.stopPropagation(),
1114
+ }),
1115
+ h('button', {
1116
+ type: 'button',
1117
+ 'aria-label': labels.close,
1118
+ style: {
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',
1132
+ },
1133
+ onClick: onClose,
1134
+ }, IconClose ? h(IconClose, { size: 16 }) : labels.close),
1135
+ );
1136
+ return portal ? portal(node) : node;
1137
+ }
1138
+
1139
+ function MessageImage({ image, load, cwd, labels }) {
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);
1169
+ }
1170
+ if (!src) return h('span', { style: css.meta }, labels.loading);
1171
+ return h(React.Fragment, null,
1172
+ h('button', {
1173
+ type: 'button',
1174
+ style: {
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',
1185
+ },
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
+ );
1191
+ }
1192
+
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;
1203
+ }
1204
+
1205
+ function resultText(block) {
1206
+ if (!block || typeof block !== 'object' || !('kind' in block)) return '';
1207
+ const parts = [];
1208
+ for (const part of block.content ?? []) {
1209
+ if (part.type === 'text') parts.push(part.text);
1210
+ }
1211
+ if (parts.length === 0 && block.error) parts.push(`${block.error.name}: ${block.error.code}`);
1212
+ return parts.join('\n');
1213
+ }
1214
+
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;
1229
+ }
1230
+
1231
+ function ImageGenerateToolview(props) {
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) : '';
1240
+ const labels = {
1241
+ image: t('image'),
1242
+ open: t('viewImage'),
1243
+ loading: t('imageLoading'),
1244
+ loadFailed: t('imageLoadFailed'),
1245
+ dialog: t('imagePreview'),
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)}`),
1267
+ ),
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, {
1273
+ key: image.attachment?.attachmentId ?? image.path ?? index,
1274
+ image,
1275
+ load,
1276
+ cwd: props.cwd,
1277
+ labels,
1278
+ })))
1279
+ : null,
1280
+ settled && !block.isError && images.length === 0 && text
1281
+ ? h('p', { style: { ...css.meta, whiteSpace: 'pre-wrap' } }, text)
1282
+ : null,
1283
+ );
1284
+ }
1285
+
1286
+ async function callImageGen(rpc, endpoint, payload) {
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;
1290
+ }
1291
+
1292
+ function createImageLoader(rpc) {
1293
+ return (image, cwd) => {
1294
+ const request = image?.attachment
1295
+ ? callImageGen(rpc, 'image', { ...image.attachment })
1296
+ : callImageGen(rpc, 'file', { path: image?.path, cwd: cwd || '' });
1297
+ return request.then((value) => `data:${value.mediaType};base64,${value.dataBase64}`);
1298
+ };
1299
+ }
1300
+
1301
+ /**
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.
1305
+ */
1306
+ function adaptConfigForm(form, pick) {
1307
+ return {
1308
+ getSnapshot() {
1309
+ const snapshot = form.getSnapshot();
1310
+ return {
1311
+ status: snapshot.status,
1312
+ value: snapshot.value === undefined ? undefined : pick(snapshot.value),
1313
+ writable: snapshot.writable,
1314
+ revision: snapshot.revision,
1315
+ };
1316
+ },
1317
+ subscribe: (callback) => form.subscribe(callback),
1318
+ set(key, value) {
1319
+ return form.mutate([{ op: 'set', path: [key], value }]);
1320
+ },
1321
+ mutate(ops, expectedRevision) {
1322
+ return form.mutate(ops, expectedRevision);
1323
+ },
1324
+ };
1325
+ }
1326
+
1327
+ function unavailableScope() {
1328
+ return {
1329
+ getSnapshot: () => ({ status: 'unavailable', value: undefined, writable: false, revision: undefined }),
1330
+ subscribe: () => () => {},
1331
+ set: () => Promise.resolve(false),
1332
+ mutate: () => Promise.resolve(false),
1333
+ };
1334
+ }
1335
+
1336
+ function bindScopes(ctx) {
1337
+ const settingsScope = ctx.get('settingsScope');
1338
+ if (settingsScope && typeof settingsScope.bind === 'function') {
1339
+ return {
1340
+ legacy: true,
1341
+ catalog: settingsScope.bind({ namespace: CATALOG_NS }),
1342
+ runtime: settingsScope.bind({ namespace: RUNTIME_NS }),
1343
+ };
1344
+ }
1345
+ const configForms = ctx.get('configForms');
1346
+ if (configForms && typeof configForms.get === 'function') {
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
+ };
1363
+ }
1364
+ }
1365
+ return { legacy: true, catalog: unavailableScope(), runtime: unavailableScope() };
1366
+ }
1367
+
1368
+ const inject = ['slots', 'locale', 'remote', 'remote.credentials', 'connection'];
1369
+
1370
+ function apply(ctx) {
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;
1377
+
1378
+ ctx.slots.inject('settings.section', () => ctx.slots.register({
1379
+ name: 'settings.section',
1380
+ id: 'image-gen',
1381
+ order: 85,
1382
+ label: () => t('nav'),
1383
+ locale: NS,
1384
+ inject: () => ({ catalog: scopes.catalog, credentials, t }),
1385
+ }, CatalogSection));
1386
+
1387
+ if (scopes.legacy) {
1388
+ // DSH <= 0.1.5: the model picker lives on the Settings plugins page.
1389
+ ctx.slots.inject('settings.plugin.item', () => ctx.slots.register({
1390
+ name: 'settings.plugin.item',
1391
+ key: RUNTIME_NS,
1392
+ priority: 1000,
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
+ }
1411
+ }
1412
+
1413
+ if (connection?.rpc) {
1414
+ ctx.slots.inject('tool.call.toolview', () => ctx.slots.register({
1415
+ name: 'tool.call.toolview',
1416
+ key: TOOL_NAME,
1417
+ locale: NS,
1418
+ inject: () => ({ load: createImageLoader(connection.rpc), t }),
1419
+ }, ImageGenerateToolview));
1420
+ }
1421
+ }
1422
+
1423
+ return { inject, apply };
1424
+ },
1425
+ });