dsh-image-lite 0.0.0-stage → 0.1.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/client.js ADDED
@@ -0,0 +1,1807 @@
1
+ /**
2
+ * dsh-image-lite — Client half.
3
+ *
4
+ * - the dsh-image-lite card on the Plugins page (`plugins.bundle.config`, key
5
+ * `dsh-image-lite`): a self-contained model library (providers + models
6
+ * CRUD, stored in this entry's volatile `providers` field) next to the
7
+ * quick config (default model + default image spec → `active` /
8
+ * `activeAspect`). The UI is entirely its own (a compact provider row +
9
+ * inline form + quick-config pickers), with no other plugin required.
10
+ * - Right sidebar tab 「生图工作台」: two-stage registration
11
+ * (sidebarRightTabs.register type + keyed `sidebar.right.pane.tab` body),
12
+ * corner entry in `conversation.session.header.corner`, and the panel
13
+ * closed loop: model pick / 7-stop aspect (both live from the entry),
14
+ * reference images (recent results / upload / paste), generate, result
15
+ * gallery + lightbox + "keep editing".
16
+ * - `tool.call.toolview` for image_generate_lite: inline result cards,
17
+ * lightbox, and a "use this one" button that shares refs with the panel.
18
+ *
19
+ * Everything reads and writes one entry (`image-gen-lite`); no cross-plugin
20
+ * configuration reads. The 出图/attachment/credential plumbing lives on the
21
+ * host half.
22
+ */
23
+ window.__ModuleLoader__.load({
24
+ id: 'dsh-image-lite',
25
+ factory: (require) => {
26
+ var module = { exports: {} }
27
+ var exports = module.exports
28
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
29
+
30
+ const React = require('react')
31
+ // Icons are a cosmetic concern: if this runtime's module registry does
32
+ // not resolve the primitives package for third-party clients, the module
33
+ // must still activate (every icon use site degrades to text labels).
34
+ let primitives = {}
35
+ try {
36
+ primitives = require('@deepseek-ai/dsh-client-ui-primitives') ?? {}
37
+ } catch {
38
+ primitives = {}
39
+ }
40
+ // A `position: fixed` overlay is still clipped when an ancestor creates a
41
+ // containing block (`transform` / `filter` / `contain`) — the right sidebar
42
+ // does. A portal into document.body keeps the lightbox on the real viewport,
43
+ // full-window, like the viewer the conversation uses for its own images.
44
+ let portalFactory = null
45
+ try {
46
+ const reactDom = require('react-dom')
47
+ if (typeof reactDom?.createPortal === 'function') portalFactory = reactDom.createPortal
48
+ } catch {
49
+ portalFactory = null
50
+ }
51
+ const pickIcon = (...names) => names.map((n) => primitives[n]).find((v) => typeof v === 'function')
52
+ const IconClose = pickIcon('IconCloseOutline16', 'IconCloseOutlineRegular', 'IconCloseOutlineMedium')
53
+ const IconTrash = pickIcon('IconTrashOutline16', 'IconTrashOutlineRegular', 'IconTrashOutlineMedium')
54
+ const IconPlus = pickIcon('IconPlusOutline16', 'IconPlusOutlineRegular', 'IconPlusOutlineMedium')
55
+ const IconSparkle = pickIcon('IconSparkle16', 'IconSparkleRegular', 'IconSparkleMedium')
56
+
57
+ const ENTRY_NS = 'image-gen-lite'
58
+ const LOCALE_NS = 'image-gen-lite'
59
+ const RPC_CHANNEL = '/image-gen-lite'
60
+ const TAB_ID = 'dsh-image-lite'
61
+ const TAB_KIND = 'image-gen-lite'
62
+ const TOOL_NAME = 'image_generate_lite'
63
+ const ASPECTS = ['1:1', '3:2', '2:3', '3:4', '4:3', '16:9', '9:16', 'auto']
64
+ const SUPPORTED_FORMAT = 'openai-images'
65
+ const MAX_REFS = 5
66
+ const SHARE_EVENT = 'dsh-image-lite-updated'
67
+ const API_FORMATS = [
68
+ { id: 'openai-images', note: '/images/generations · /images/edits' },
69
+ { id: 'xai-images', note: 'aspect_ratio' },
70
+ { id: 'gemini-image', note: 'generateContent' },
71
+ { id: 'openai-chat-image', note: 'chat completions' },
72
+ ]
73
+
74
+ const en = {
75
+ title: 'Image studio',
76
+ cornerTooltip: 'Open the image studio',
77
+ guideTitle: 'Image studio',
78
+ guideDescription: 'Generate and iteratively edit images with the configured model.',
79
+ model: 'Image model',
80
+ modelPlaceholder: 'Pick a model',
81
+ libEmpty: 'The model library is empty. Add a provider on the Plugins page (open the dsh-image-lite card).',
82
+ aspect: 'Aspect ratio',
83
+ refs: 'Reference images',
84
+ refsEmpty: 'No references yet. Upload, paste, or click "keep editing" on a result below.',
85
+ refsFull: 'Up to 5 reference images.',
86
+ upload: 'Upload',
87
+ clear: 'Clear',
88
+ clearHint: 'Clear references, prompt and results to start a new picture.',
89
+ paste: 'Paste an image here to add it as a reference.',
90
+ refsSelected: 'Selected — press Ctrl+V to paste an image into this box.',
91
+ removeRef: 'Remove reference',
92
+ uploadFailed: 'Upload failed.',
93
+ prompt: 'Describe the image (or the change).',
94
+ promptPlaceholder: 'e.g. a red rabbit with headphones, studio light…',
95
+ generate: 'Generate',
96
+ generating: 'Generating…',
97
+ keyConfigured: 'API key set',
98
+ keyUnset: 'API key missing — set it on the Plugins page under dsh-image-lite.',
99
+ noActive: 'Pick an image model to start.',
100
+ noCwd: 'Session working directory is unavailable; generation is disabled.',
101
+ results: 'Results',
102
+ resultsEmpty: 'Generated images appear here.',
103
+ useThis: 'Keep editing',
104
+ useThisHint: 'Uses this image as the reference for the next generation.',
105
+ errorPrefix: 'Generation failed',
106
+ tvGenerating: 'Generating…',
107
+ tvImage: 'Image',
108
+ tvView: 'View image',
109
+ tvLoading: 'Loading image…',
110
+ tvLoadFailed: 'Could not load image. Click to retry.',
111
+ tvDialog: 'Image preview',
112
+ tvClose: 'Close',
113
+ // settings card
114
+ cardTitle: 'Image studio',
115
+ cardIntro: 'Model library and quick defaults. Everything is stored in this plugin and takes effect on the next generation.',
116
+ lib: 'Model library',
117
+ libEmptyCard: 'No providers yet. Add one below.',
118
+ addProvider: 'Add provider',
119
+ editProvider: 'Edit provider',
120
+ providerName: 'Name',
121
+ providerId: 'ID',
122
+ providerBase: 'Base URL',
123
+ providerFormat: 'API format',
124
+ providerKey: 'API key',
125
+ providerKeyEnv: 'Credential name',
126
+ keyModeEnv: 'Use an env var name',
127
+ keyModeKey: 'Paste the key instead',
128
+ keyPlaceholder: 'sk-… paste the API key',
129
+ keyHint: 'Stored in the DSH credentials service — the config keeps only a masked preview.',
130
+ keyStoredHint: 'Already stored: {hint}. Leave empty to keep it.',
131
+ keyEnvHint: 'Read from the environment (or an existing credential) under this name.',
132
+ keyReplaceHint: 'The old value here is not a credential name — paste the API key to replace it.',
133
+ keyWriteFailed: 'Could not store the API key: {reason}',
134
+ providerModels: 'Models',
135
+ modelsHint: 'One model per line: `id` or `id display name`.',
136
+ save: 'Save',
137
+ cancel: 'Cancel',
138
+ deleteProvider: 'Delete',
139
+ modelsCount: '{n} models',
140
+ keySet: 'key set',
141
+ keyMissing: 'key missing',
142
+ idTaken: 'This ID is already in use — pick another one.',
143
+ nameTaken: 'A provider with this name already exists — pick another name.',
144
+ nameRequired: 'Give the provider a name or an ID first.',
145
+ saveFailed: 'The configuration form rejected the write — nothing was saved.',
146
+ unsupportedNote: 'only openai-images can generate in this version',
147
+ quick: 'Quick config',
148
+ defaultModel: 'Default model',
149
+ defaultAspect: 'Default image spec',
150
+ quickReady: 'Ready — this is what image_generate_lite uses.',
151
+ sidebar: 'Sidebar',
152
+ sidebarStudio: 'Use the image studio from the sidebar',
153
+ sidebarStudioHint: 'Off applies at once; turning it back on restores the tab and header button after a window refresh. The image_generate_lite tool always works.',
154
+ sidebarSaveFailed: 'Could not save the switch',
155
+ browse: 'Open folder…',
156
+ pickFailed: 'Could not open the folder picker',
157
+ storage: 'Image folder',
158
+ storagePlaceholder: 'Default: <session workspace> / generate/image',
159
+ storageHint: 'Leave empty to store images under generate/image in the session workspace; a relative path is resolved against the workspace.',
160
+ quickUnset: 'Pick a default model and it takes effect on the next call.',
161
+ quickStale: 'The default model no longer exists in the library; pick one again.',
162
+ }
163
+ const zh = {
164
+ title: '生图工作台',
165
+ cornerTooltip: '打开生图工作台',
166
+ guideTitle: '生图工作台',
167
+ guideDescription: '用已配置的模型生成并迭代修改图片。',
168
+ model: '生图模型',
169
+ modelPlaceholder: '选择模型',
170
+ libEmpty: '模型库为空。请到 插件 页面打开 dsh-image-lite 添加供应商。',
171
+ aspect: '图片比例',
172
+ refs: '参考图',
173
+ refsEmpty: '暂无参考图。可上传、粘贴,或在下方结果里点「用这张继续」。',
174
+ refsFull: '最多 5 张参考图。',
175
+ upload: '上传',
176
+ clear: '清空',
177
+ clearHint: '清空参考图、描述和结果,开始新的生成。',
178
+ paste: '粘贴图片即可添加为参考图。',
179
+ refsSelected: '已选中这张参考图框,按 Ctrl+V 粘贴图片。',
180
+ removeRef: '移除参考图',
181
+ uploadFailed: '上传失败。',
182
+ prompt: '描述图片(或要做的改动)。',
183
+ promptPlaceholder: '例如:戴耳机的红色小兔,影棚光…',
184
+ generate: '生成',
185
+ generating: '生成中…',
186
+ keyConfigured: '密钥已配置',
187
+ keyUnset: '密钥缺失 — 请到 插件 页面的 dsh-image-lite 卡片里配置。',
188
+ noActive: '请先选择一个生图模型。',
189
+ noCwd: '会话工作目录不可用,无法生成。',
190
+ results: '结果',
191
+ resultsEmpty: '生成的图片会出现在这里。',
192
+ useThis: '用这张继续',
193
+ useThisHint: '把这张图作为下次生成的参考图。',
194
+ errorPrefix: '生成失败',
195
+ tvGenerating: '正在生成…',
196
+ tvImage: '图片',
197
+ tvView: '查看图片',
198
+ tvLoading: '正在加载图片…',
199
+ tvLoadFailed: '图片加载失败,点击重试。',
200
+ tvDialog: '图片预览',
201
+ tvClose: '关闭',
202
+ cardTitle: '生图工作台',
203
+ cardIntro: '模型库与快速配置。全部存于本插件,下一次生图即刻生效。',
204
+ lib: '模型库',
205
+ libEmptyCard: '还没有供应商。在下方添加一个。',
206
+ addProvider: '添加供应商',
207
+ editProvider: '编辑供应商',
208
+ providerName: '名称',
209
+ providerId: 'ID',
210
+ providerBase: 'Base URL',
211
+ providerFormat: '接口格式',
212
+ providerKey: 'API 密钥',
213
+ providerKeyEnv: '凭据名(环境变量)',
214
+ keyModeEnv: '改用环境变量名',
215
+ keyModeKey: '改回直接填密钥',
216
+ keyPlaceholder: 'sk-… 粘贴 API 密钥',
217
+ keyHint: '保存到 DSH 凭据服务,配置里只留加密预览。',
218
+ keyStoredHint: '已保存:{hint}。留空则保持不变。',
219
+ keyEnvHint: '从这个名字的环境变量(或已有凭据)读取。',
220
+ keyReplaceHint: '原来那串不是凭据名,粘贴 API 密钥即可替换。',
221
+ keyWriteFailed: '密钥保存失败:{reason}',
222
+ providerModels: '模型',
223
+ modelsHint: '每行一个模型:`id` 或 `id 显示名`。',
224
+ save: '保存',
225
+ cancel: '取消',
226
+ deleteProvider: '删除',
227
+ modelsCount: '{n} 个模型',
228
+ keySet: '密钥已配',
229
+ keyMissing: '密钥未配',
230
+ idTaken: '该 ID 已被占用,请换一个。',
231
+ nameTaken: '同名供应商已存在,请换一个名称。',
232
+ nameRequired: '请先填写名称或 ID。',
233
+ saveFailed: '配置表单拒绝了这次写入,没有保存成功。',
234
+ unsupportedNote: '本版本仅 openai-images 可出图',
235
+ quick: '快速配置',
236
+ defaultModel: '默认模型',
237
+ defaultAspect: '默认图片规格',
238
+ quickReady: '已就绪 — image_generate_lite 将使用它。',
239
+ sidebar: '侧边栏',
240
+ sidebarStudio: '在侧边栏中使用生图工作台',
241
+ sidebarStudioHint: '关闭立即生效;重新开启后刷新窗口即可恢复标签与按钮。image_generate_lite 工具始终可用。',
242
+ sidebarSaveFailed: '开关保存失败',
243
+ browse: '打开文件夹',
244
+ pickFailed: '无法打开文件夹选择器',
245
+ storage: '图片存放位置',
246
+ storagePlaceholder: '留空则用:会话工作区 / generate/image',
247
+ storageHint: '留空就用会话工作区的 generate/image/ 文件夹;相对路径按工作区解析。',
248
+ quickUnset: '选好默认模型后,下一次调用即生效。',
249
+ quickStale: '默认模型已不在模型库中,请重新选择。',
250
+ }
251
+
252
+ function translateFactory(dict) {
253
+ return (key, params) => {
254
+ let text = dict[key] ?? en[key] ?? key
255
+ for (const [name, value] of Object.entries(params ?? {})) {
256
+ text = String(text).replaceAll(`{${name}}`, String(value))
257
+ }
258
+ return text
259
+ }
260
+ }
261
+
262
+ const css = {
263
+ panel: { display: 'flex', flexDirection: 'column', gap: 14, padding: 16, color: 'var(--dsw-alias-label-primary)', fontSize: 14 },
264
+ topbar: { display: 'flex', alignItems: 'center', justifyContent: 'flex-end', marginBottom: -6 },
265
+ switch: { position: 'relative', flex: '0 0 auto', width: 40, height: 22, borderRadius: 11, border: 'none', padding: 0, cursor: 'pointer', transition: 'background .15s' },
266
+ switchKnob: { position: 'absolute', top: 3, width: 16, height: 16, borderRadius: 8, background: '#fff', transition: 'left .15s' },
267
+ idle: { opacity: 0.45, cursor: 'not-allowed' },
268
+ section: { display: 'flex', flexDirection: 'column', gap: 8 },
269
+ row: { display: 'flex', alignItems: 'center', gap: 8 },
270
+ heading: { margin: 0, fontSize: 12, lineHeight: '18px', color: 'var(--dsw-alias-label-tertiary)', letterSpacing: '.04em' },
271
+ label: { fontSize: 13, lineHeight: '20px', color: 'var(--dsw-alias-label-secondary)', flex: 'none' },
272
+ hint: { margin: 0, fontSize: 12, lineHeight: '18px', color: 'var(--dsw-alias-label-tertiary)' },
273
+ error: { margin: 0, fontSize: 12, lineHeight: '18px', color: 'var(--dsw-alias-state-error-primary)' },
274
+ danger: { color: 'var(--dsw-alias-state-error-primary)', borderColor: 'var(--dsw-alias-state-error-primary)' },
275
+ drop: { border: '1px dashed var(--dsw-alias-border-l2)', borderRadius: 8, padding: 8, outline: 'none', transition: 'border-color .12s, background .12s' },
276
+ dropActive: { borderColor: 'var(--dsw-alias-state-focus-border, #4c8dff)', background: 'var(--dsw-alias-interactive-bg-hover)' },
277
+ hintActive: { color: 'var(--dsw-alias-label-primary)' },
278
+ grid: { display: 'flex', flexWrap: 'wrap', gap: 8 },
279
+ resultCard: {
280
+ border: '1px solid var(--dsw-alias-border-l2)', borderRadius: 10, padding: 10,
281
+ background: 'var(--dsw-alias-bg-layer-3)', display: 'flex', flexDirection: 'column', gap: 8,
282
+ },
283
+ chipImg: { width: '100%', height: '100%', objectFit: 'cover', display: 'block' },
284
+ card: { display: 'flex', flexDirection: 'column', gap: 16, padding: 4, color: 'var(--dsw-alias-label-primary)', fontSize: 14 },
285
+ libRow: {
286
+ display: 'flex', alignItems: 'center', gap: 10, border: '1px solid var(--dsw-alias-border-l2)',
287
+ borderRadius: 10, padding: '10px 12px', background: 'var(--dsw-alias-bg-layer-3)',
288
+ },
289
+ libMeta: { fontSize: 12, lineHeight: '18px', color: 'var(--dsw-alias-label-tertiary)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
290
+ formGrid: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, alignItems: 'start' },
291
+ }
292
+
293
+ function ensurePanelCss() {
294
+ if (typeof document === 'undefined') return
295
+ if (document.querySelector('style[data-plugin-css="dsh-image-lite-panel"]')) return
296
+ const tag = document.createElement('style')
297
+ tag.dataset.plugin = 'dsh-image-lite'
298
+ tag.dataset.pluginCss = 'dsh-image-lite-panel'
299
+ tag.textContent = [
300
+ '.dsh-igl-select{box-sizing:border-box;height:36px;padding:0 12px;font:inherit;font-size:14px;line-height:22px;border:1px solid var(--dsw-alias-border-l2);border-radius:18px;background:var(--dsw-alias-bg-module-platform);color:var(--dsw-alias-label-primary);cursor:pointer}',
301
+ '.dsh-igl-select:disabled{opacity:.5;cursor:default}',
302
+ '.dsh-igl-input{box-sizing:border-box;height:32px;width:100%;border:1px solid var(--dsw-alias-border-l2);border-radius:8px;padding:0 10px;font:inherit;font-size:14px;line-height:22px;background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary)}',
303
+ '.dsh-igl-input:focus{outline:none;border-color:var(--dsw-alias-interactive-bg-selected,var(--dsw-alias-border-l3))}',
304
+ '.dsh-igl-textarea{box-sizing:border-box;width:100%;min-height:64px;border:1px solid var(--dsw-alias-border-l2);border-radius:8px;padding:8px 10px;font:inherit;font-size:13px;line-height:20px;background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);resize:vertical}',
305
+ '.dsh-igl-textarea:focus{outline:none;border-color:var(--dsw-alias-interactive-bg-selected,var(--dsw-alias-border-l3))}',
306
+ '.dsh-igl-btn{box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;gap:4px;height:28px;padding:0 10px;border-radius:14px;border:1px solid var(--dsw-alias-border-l2);background:transparent;color:var(--dsw-alias-label-primary);font:inherit;font-size:12px;line-height:18px;cursor:pointer}',
307
+ '.dsh-igl-btn:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover)}',
308
+ '.dsh-igl-btn:disabled{opacity:.5;cursor:default}',
309
+ '.dsh-igl-primary{box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;height:32px;padding:0 14px;border-radius:16px;border:none;background:var(--dsw-alias-button-primary-fill,#3b82f6);color:var(--dsw-alias-label-primary-foreground,#fff);font:inherit;font-size:13px;cursor:pointer}',
310
+ '.dsh-igl-primary:hover:not(:disabled){filter:brightness(1.08)}',
311
+ '.dsh-igl-primary:disabled{opacity:.5;cursor:default}',
312
+ '.dsh-igl-icon{box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;border:none;background:transparent;cursor:pointer;color:var(--dsw-alias-label-tertiary);border-radius:6px;padding:0}',
313
+ '.dsh-igl-icon:hover{color:var(--dsw-alias-label-primary);background:var(--dsw-alias-interactive-bg-hover)}',
314
+ '.dsh-igl-corner{box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;width:32px;height:32px;border:none;border-radius:8px;background:transparent;color:var(--dsw-alias-label-secondary);cursor:pointer}',
315
+ '.dsh-igl-corner:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}',
316
+ '.dsh-igl-chip{position:relative;width:56px;height:56px;border-radius:8px;overflow:hidden;flex:none;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-1)}',
317
+ '.dsh-igl-chip img{width:100%;height:100%;object-fit:cover;display:block}',
318
+ '.dsh-igl-empty{margin:0;font-size:13px;line-height:20px;color:var(--dsw-alias-label-tertiary);border:1px dashed var(--dsw-alias-border-l2);border-radius:8px;padding:10px 12px}',
319
+ '.dsh-igl-badge{box-sizing:border-box;display:inline-flex;align-items:center;height:20px;padding:0 8px;border-radius:10px;background:var(--dsw-alias-bg-layer-2,var(--dsw-alias-bg-layer-1));border:1px solid var(--dsw-alias-border-l2);color:var(--dsw-alias-label-tertiary);font:inherit;font-size:11px;line-height:18px;flex:none}',
320
+ '.dsh-igl-badgeset{box-sizing:border-box;display:inline-flex;align-items:center;height:20px;padding:0 8px;border-radius:10px;font:inherit;font-size:11px;line-height:18px;flex:none;color:var(--dsw-alias-state-success-primary,var(--dsw-alias-label-tertiary))}',
321
+ '.dsh-igl-badgeset.off{color:var(--dsw-alias-state-error-primary,var(--dsw-alias-label-tertiary))}',
322
+ '.dsh-igl-mchip{box-sizing:border-box;display:inline-flex;align-items:center;gap:4px;height:24px;padding:0 8px 0 10px;border-radius:12px;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-2,var(--dsw-alias-bg-layer-1));color:var(--dsw-alias-label-primary);font:inherit;font-size:12px}',
323
+ ].join('')
324
+ document.head.appendChild(tag)
325
+ }
326
+
327
+ // ------------------------------------------------------------ storage + share
328
+
329
+ function storageKeyFor(sessionId) {
330
+ return `dsh.image-gen-lite.v1.${typeof sessionId === 'string' && sessionId ? sessionId : 'global'}`
331
+ }
332
+
333
+ function normalizeSessionStore(parsed) {
334
+ const store = { refs: [], prompt: '', recent: [] }
335
+ if (parsed && typeof parsed === 'object') {
336
+ if (Array.isArray(parsed.refs)) {
337
+ store.refs = parsed.refs
338
+ .filter((ref) => ref && typeof ref === 'object' && typeof ref.attachmentId === 'string')
339
+ .slice(0, MAX_REFS)
340
+ }
341
+ if (typeof parsed.prompt === 'string') store.prompt = parsed.prompt
342
+ if (Array.isArray(parsed.recent)) {
343
+ store.recent = parsed.recent
344
+ .filter((row) => row && typeof row === 'object')
345
+ .slice(0, 12)
346
+ .map((row) => ({
347
+ images: Array.isArray(row.images) ? row.images : [],
348
+ paths: Array.isArray(row.paths) ? row.paths : [],
349
+ provider: String(row.provider ?? ''),
350
+ model: String(row.model ?? ''),
351
+ aspect: String(row.aspect ?? ''),
352
+ at: Number(row.at) || 0,
353
+ }))
354
+ }
355
+ }
356
+ return store
357
+ }
358
+
359
+ function readSessionStore(sessionId) {
360
+ try {
361
+ const raw = localStorage.getItem(storageKeyFor(sessionId))
362
+ return normalizeSessionStore(raw ? JSON.parse(raw) : null)
363
+ } catch {
364
+ return normalizeSessionStore(null)
365
+ }
366
+ }
367
+
368
+ function writeSessionStore(sessionId, store) {
369
+ try {
370
+ localStorage.setItem(storageKeyFor(sessionId), JSON.stringify(store))
371
+ } catch {
372
+ // storage unavailable: the session-scoped state simply does not persist
373
+ }
374
+ }
375
+
376
+ /** Share refs from the toolview into the panel's reference list. */
377
+ function shareRefsWithPanel(sessionId, refs) {
378
+ if (!sessionId || !Array.isArray(refs) || refs.length === 0) return
379
+ const store = readSessionStore(sessionId)
380
+ const seen = new Set(store.refs.map((r) => r && r.attachmentId))
381
+ const merged = []
382
+ for (const ref of refs) {
383
+ if (!ref || seen.has(ref.attachmentId)) continue
384
+ seen.add(ref.attachmentId)
385
+ merged.push(ref)
386
+ if (merged.length === MAX_REFS) break
387
+ }
388
+ if (merged.length === 0) return
389
+ store.refs = merged
390
+ writeSessionStore(sessionId, store)
391
+ if (typeof window !== 'undefined') window.dispatchEvent(new CustomEvent(SHARE_EVENT, { detail: { sessionId } }))
392
+ }
393
+
394
+ // ------------------------------------------------------------ model library (pure)
395
+
396
+ function emptyActiveValue() {
397
+ return { providerId: '', modelId: '', baseUrl: '', model: '', apiKeyEnv: '', apiFormat: '' }
398
+ }
399
+
400
+ /** Mirrors the host's `activeComplete`: every field the 出图 call needs. */
401
+ function activeLooksComplete(active) {
402
+ return !!(active && active.providerId && active.modelId && active.baseUrl
403
+ && active.model && active.apiKeyEnv && active.apiFormat === SUPPORTED_FORMAT)
404
+ }
405
+
406
+ /** One provider+model option for the pickers. */
407
+ function providerOptions(providers) {
408
+ const options = []
409
+ for (const provider of Array.isArray(providers) ? providers : []) {
410
+ if (!provider || typeof provider !== 'object') continue
411
+ for (const model of provider.models ?? []) {
412
+ if (!model?.id) continue
413
+ options.push({
414
+ value: `${provider.id}::${model.id}`,
415
+ label: `${provider.name || provider.id} / ${model.name || model.id}`,
416
+ providerId: provider.id,
417
+ modelId: model.id,
418
+ apiFormat: provider.apiFormat,
419
+ })
420
+ }
421
+ }
422
+ return options
423
+ }
424
+
425
+ /** Options usable by this version's 出图 layer. */
426
+ function modelOptionsFrom(providers) {
427
+ return providerOptions(providers).filter((o) => o.apiFormat === SUPPORTED_FORMAT)
428
+ }
429
+
430
+ /** The six-field `active` value for a chosen option. */
431
+ function buildActiveFromOption(option) {
432
+ if (!option) return emptyActiveValue()
433
+ return {
434
+ providerId: option.providerId,
435
+ modelId: option.modelId,
436
+ baseUrl: option.baseUrl ?? '',
437
+ model: option.modelId,
438
+ apiKeyEnv: option.apiKeyEnv ?? '',
439
+ apiFormat: option.apiFormat,
440
+ }
441
+ }
442
+
443
+ /** The currently selected `providerId::modelId`, when it exists in the options. */
444
+ function activeChoiceFor(active, options) {
445
+ if (!active?.providerId || !active?.modelId) return ''
446
+ const choice = `${active.providerId}::${active.modelId}`
447
+ return options.some((o) => o.value === choice) ? choice : ''
448
+ }
449
+
450
+ /**
451
+ * Keep `active` consistent with the library after an edit: refresh
452
+ * mutable fields from the (possibly edited) provider, and clear the
453
+ * selection when its provider or model disappeared.
454
+ */
455
+ function syncActiveWithProviders(active, providers) {
456
+ if (!activeLooksComplete(active)) return emptyActiveValue()
457
+ const provider = (providers ?? []).find((p) => p && p.id === active.providerId)
458
+ const model = (provider?.models ?? []).find((m) => m?.id === active.modelId)
459
+ if (!provider || !model) return emptyActiveValue()
460
+ return {
461
+ providerId: provider.id,
462
+ modelId: model.id,
463
+ baseUrl: provider.baseUrl,
464
+ model: model.id,
465
+ apiKeyEnv: provider.apiKeyEnv,
466
+ apiFormat: provider.apiFormat,
467
+ }
468
+ }
469
+
470
+ /** Parse the models textarea: `id` or `id display name` per line. */
471
+ function parseModelLines(text) {
472
+ const models = []
473
+ const seen = new Set()
474
+ for (const rawLine of String(text ?? '').split(/\r?\n/)) {
475
+ const line = rawLine.trim()
476
+ if (line.length === 0 || line.startsWith('#')) continue
477
+ const parts = line.split(/[\t ]{1,}/)
478
+ const id = (parts.shift() ?? '').trim()
479
+ if (id.length === 0 || seen.has(id)) continue
480
+ seen.add(id)
481
+ models.push({ id, name: parts.join(' ').trim() || id })
482
+ }
483
+ return models
484
+ }
485
+
486
+ /** A fresh, unique-enough provider id from a display name. */
487
+ function slugForProvider(name, taken) {
488
+ const base = String(name ?? '').trim()
489
+ .toLowerCase()
490
+ .replace(/[^a-z0-9]+/g, '-')
491
+ .replace(/^-+|-+$/g, '')
492
+ .slice(0, 32)
493
+ let id = base || 'provider'
494
+ let n = 2
495
+ while (taken.has(id)) id = `${base || 'provider'}-${n++}`
496
+ return id
497
+ }
498
+
499
+ // ---------------------------------------------------------------- RPC
500
+
501
+ async function rpcCall(rpc, endpoint, payload) {
502
+ const result = await rpc.call(RPC_CHANNEL, endpoint, payload)
503
+ if (!result.ok) throw new Error(result.error?.message ?? String(result.error))
504
+ return result.value
505
+ }
506
+
507
+ /**
508
+ * Session-authorized loader first, then our own RPC. The core helper only
509
+ * answers for attachments bound to the session, so a rejection there must
510
+ * fall through instead of killing the tile.
511
+ */
512
+ function createImageLoader(ctx, rpc, sessionId) {
513
+ return async (image, cwd) => {
514
+ const ref = image?.attachment
515
+ const file = image?.path
516
+ if (ref) {
517
+ if (typeof ctx?.uiConversation?.imageUrl === 'function') {
518
+ try {
519
+ const url = await ctx.uiConversation.imageUrl(sessionId, ref)
520
+ if (typeof url === 'string' && url !== '') return url
521
+ } catch {
522
+ // fall through to the plugin channel
523
+ }
524
+ }
525
+ const result = await rpcCall(rpc, 'image', ref)
526
+ return `data:${result.mediaType};base64,${result.dataBase64}`
527
+ }
528
+ if (file) {
529
+ const result = await rpcCall(rpc, 'file', { path: file, cwd: cwd || '' })
530
+ return `data:${result.mediaType};base64,${result.dataBase64}`
531
+ }
532
+ throw new Error('no image to load')
533
+ }
534
+ }
535
+
536
+ // ---------------------------------------------------------------- hooks
537
+
538
+ function useSnapshot(scope) {
539
+ const [snap, setSnap] = React.useState(() => scope.getSnapshot())
540
+ React.useEffect(() => {
541
+ setSnap(scope.getSnapshot())
542
+ return scope.subscribe(() => setSnap(scope.getSnapshot()))
543
+ }, [scope])
544
+ return snap
545
+ }
546
+
547
+ function useSessionStore(sessionId) {
548
+ const [store, setStore] = React.useState(() => readSessionStore(sessionId))
549
+ React.useEffect(() => {
550
+ setStore(readSessionStore(sessionId))
551
+ const onChange = (event) => {
552
+ const detail = event.detail ?? {}
553
+ if (detail.sessionId === undefined || detail.sessionId === sessionId) {
554
+ setStore(readSessionStore(sessionId))
555
+ }
556
+ }
557
+ window.addEventListener(SHARE_EVENT, onChange)
558
+ return () => window.removeEventListener(SHARE_EVENT, onChange)
559
+ }, [sessionId])
560
+ const update = React.useCallback((mutate) => {
561
+ setStore((prev) => {
562
+ const next = typeof mutate === 'function' ? mutate(prev) : { ...prev, ...mutate }
563
+ writeSessionStore(sessionId, next)
564
+ return next
565
+ })
566
+ }, [sessionId])
567
+ return [store, update]
568
+ }
569
+
570
+ /** Whether the sidebar studio should be offered (default on). */
571
+ function sidebarStudioEnabled(lite) {
572
+ const value = lite?.getSnapshot?.()?.value
573
+ return value?.sidebarEnabled !== false
574
+ }
575
+
576
+ /** The credentials Remote, however this runtime exposes it. */
577
+ function credentialsOf(ctx) {
578
+ return ctx?.remote?.credentials ?? ctx?.get?.('remote')?.credentials
579
+ }
580
+
581
+ /** Key-state for a list of credential names, from the credentials Remote. */
582
+ function useKeyStates(ctx, envs, revision) {
583
+ const [states, setStates] = React.useState({})
584
+ const key = envs.filter((e) => typeof e === 'string' && e.length > 0).join('|')
585
+ React.useEffect(() => {
586
+ const list = key ? key.split('|') : []
587
+ const credentials = credentialsOf(ctx)
588
+ if (list.length === 0 || !credentials?.describe) return undefined
589
+ let cancelled = false
590
+ credentials.describe(list).then((response) => {
591
+ if (cancelled) return
592
+ const next = {}
593
+ for (const env of list) next[env] = response?.ok ? response.value?.[env]?.configured === true : false
594
+ setStates(next)
595
+ }).catch(() => {})
596
+ return () => { cancelled = true }
597
+ }, [key, ctx?.remote, revision])
598
+ return states
599
+ }
600
+
601
+ /**
602
+ * Store one API key in the credentials service under `name`. The write is
603
+ * what makes the provider usable; the config itself never holds the secret.
604
+ */
605
+ async function writeCredential(ctx, name, secret) {
606
+ const credentials = credentialsOf(ctx)
607
+ if (typeof credentials?.set !== 'function') {
608
+ throw new Error('this DSH build has no writable credentials service')
609
+ }
610
+ const result = await credentials.set(name, secret)
611
+ if (result && result.ok === false) {
612
+ throw new Error(result.error?.message ?? 'credentials.set was rejected')
613
+ }
614
+ }
615
+
616
+ /** The credential name a provider's key is stored under. */
617
+ function credentialNameFor(providerId) {
618
+ const slug = String(providerId ?? '').toUpperCase().replace(/[^A-Z0-9]+/g, '_').replace(/^_+|_+$/g, '')
619
+ return `IMAGE_GEN_${slug || 'PROVIDER'}_API_KEY`
620
+ }
621
+
622
+ /** `MY_IMAGE_API_KEY` — a name a credential can be resolved by. */
623
+ function looksLikeCredentialName(value) {
624
+ return /^[A-Z][A-Z0-9_]*$/.test(String(value ?? '').trim())
625
+ }
626
+
627
+ /** `sk-0****32d`: how a stored key is shown back, never the key itself. */
628
+ function maskSecret(value) {
629
+ const text = String(value ?? '')
630
+ if (text.length < 12) return text ? '*'.repeat(Math.min(text.length, 8)) : ''
631
+ return `${text.slice(0, 4)}****${text.slice(-4)}`
632
+ }
633
+
634
+ // ------------------------------------------------------------ image tile
635
+
636
+ function ImageTile({ image, load, t, onUse }) {
637
+ const [src, setSrc] = React.useState(null)
638
+ const [failed, setFailed] = React.useState(false)
639
+ const [open, setOpen] = React.useState(false)
640
+ const [tick, setTick] = React.useState(0)
641
+ const key = image?.attachment?.attachmentId ?? image?.path ?? ''
642
+ React.useEffect(() => {
643
+ let cancelled = false
644
+ setFailed(false)
645
+ setSrc(null)
646
+ Promise.resolve()
647
+ .then(() => load(image, undefined))
648
+ .then((url) => { if (!cancelled) setSrc(url) })
649
+ .catch(() => { if (!cancelled) setFailed(true) })
650
+ return () => { cancelled = true }
651
+ }, [key, tick])
652
+
653
+ if (failed) {
654
+ return React.createElement('button', {
655
+ type: 'button', className: 'dsh-igl-icon',
656
+ style: { width: 'auto', height: 'auto', padding: 4 },
657
+ 'aria-label': t('tvLoadFailed'),
658
+ onClick: () => { setFailed(false); setTick((n) => n + 1) },
659
+ }, t('tvLoadFailed'))
660
+ }
661
+ if (!src) return React.createElement('div', { className: 'dsh-igl-chip' })
662
+ return React.createElement(React.Fragment, null,
663
+ React.createElement('button', {
664
+ type: 'button', className: 'dsh-igl-chip', style: { border: 'none', padding: 0, cursor: 'zoom-in' },
665
+ 'aria-label': t('tvView'),
666
+ onClick: () => setOpen(true),
667
+ }, React.createElement('img', { src, alt: t('tvImage'), style: css.chipImg })),
668
+ open ? React.createElement(ImageLightbox, { src, t, onClose: () => setOpen(false) }) : null,
669
+ onUse ? React.createElement('button', {
670
+ type: 'button', className: 'dsh-igl-btn',
671
+ title: t('useThisHint'),
672
+ onClick: onUse,
673
+ }, t('useThis')) : null,
674
+ )
675
+ }
676
+
677
+ function ImageLightbox({ src, t, onClose }) {
678
+ React.useEffect(() => {
679
+ const onKey = (event) => { if (event.key === 'Escape') onClose() }
680
+ window.addEventListener('keydown', onKey)
681
+ // While the viewer is open the page behind it must not scroll, otherwise
682
+ // a trackpad gesture scrolls the studio panel under the overlay.
683
+ const previousOverflow = document.body.style.overflow
684
+ document.body.style.overflow = 'hidden'
685
+ return () => {
686
+ window.removeEventListener('keydown', onKey)
687
+ document.body.style.overflow = previousOverflow
688
+ }
689
+ }, [onClose])
690
+
691
+ const overlay = React.createElement('div', {
692
+ role: 'dialog', 'aria-modal': 'true', 'aria-label': t('tvDialog'), className: 'dsh-igl-lightbox',
693
+ style: {
694
+ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, zIndex: 2147483000,
695
+ display: 'flex', alignItems: 'center', justifyContent: 'center',
696
+ background: 'rgba(0,0,0,.82)', padding: 24,
697
+ },
698
+ onClick: onClose,
699
+ },
700
+ React.createElement('img', {
701
+ src, alt: t('tvImage'),
702
+ style: { maxWidth: '96vw', maxHeight: '92vh', width: 'auto', height: 'auto', objectFit: 'contain', borderRadius: 4, boxShadow: '0 18px 60px rgba(0,0,0,.55)' },
703
+ onClick: (event) => event.stopPropagation(),
704
+ }),
705
+ React.createElement('button', {
706
+ type: 'button', 'aria-label': t('tvClose'),
707
+ style: {
708
+ position: 'fixed', top: 16, right: 16, width: 36, height: 36, border: 'none',
709
+ borderRadius: '50%', cursor: 'pointer', background: 'rgba(255,255,255,.18)', color: '#fff',
710
+ display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
711
+ },
712
+ onClick: onClose,
713
+ }, IconClose ? React.createElement(IconClose, { size: 16 }) : t('tvClose')),
714
+ )
715
+
716
+ // No portal runtime (older bundle): still better than a clipped overlay.
717
+ if (!portalFactory || typeof document === 'undefined') return overlay
718
+ return portalFactory(overlay, document.body)
719
+ }
720
+
721
+ // ---------------------------------------------------------------- toolview
722
+
723
+ function derivePrompt(argsRaw) {
724
+ let parsed
725
+ try { parsed = JSON.parse(argsRaw) } catch { parsed = undefined }
726
+ let prompt
727
+ if (typeof parsed === 'object' && parsed !== null && typeof parsed.prompt === 'string') prompt = parsed.prompt
728
+ const line = String(prompt ?? argsRaw).split('\n', 1)[0] ?? ''
729
+ return line.length > 48 ? `${line.slice(0, 47)}…` : line
730
+ }
731
+
732
+ function blockImages(block) {
733
+ const images = []
734
+ for (const part of block?.content ?? []) {
735
+ if (part?.type === 'image' && part.attachment) images.push({ attachment: part.attachment })
736
+ }
737
+ if (images.length > 0) return images
738
+ const text = (block?.content ?? []).filter((p) => p?.type === 'text').map((p) => p.text).join('\n')
739
+ const match = text.match(/Image references \(for image_generate_lite\.referenceImages\): (\[[\s\S]*\])\s*$/)
740
+ if (match) {
741
+ try {
742
+ const refs = JSON.parse(match[1])
743
+ for (const ref of refs) images.push({ attachment: ref })
744
+ } catch { /* fall through to paths */ }
745
+ }
746
+ if (images.length === 0) {
747
+ for (const line of text.split('\n')) {
748
+ const m = line.match(/^\s*-\s+(\S+\.(?:png|jpe?g|webp|gif))\s*$/i)
749
+ if (m) images.push({ path: m[1] })
750
+ }
751
+ }
752
+ return images
753
+ }
754
+
755
+ function LiteToolview(props) {
756
+ const { block } = props
757
+ const t = props.t ?? translateFactory(en)
758
+ if (block === undefined) return null
759
+ const phase = typeof props.phase === 'string' ? props.phase : ('kind' in block ? 'result' : 'start')
760
+ const settled = phase === 'result'
761
+ const argsRaw = (settled ? block.call?.argsRaw : block.argsRaw) ?? ''
762
+ const images = settled ? blockImages(block) : []
763
+ // Plain closures: this component owns no hooks, so the early return
764
+ // above stays safe (ImageTile owns its own hook effects).
765
+ const selfLoad = (image, cwd) => createImageLoader(props.ctx, props.rpc, props.sessionId)(image, cwd)
766
+ const load = (image, cwd) => {
767
+ if (image?.attachment && typeof props.loadImage === 'function') {
768
+ return Promise.resolve(props.loadImage(image.attachment))
769
+ }
770
+ return selfLoad(image, cwd ?? props.cwd)
771
+ }
772
+ const textParts = (block?.content ?? []).filter((p) => p?.type === 'text').map((p) => p.text)
773
+ if (textParts.length === 0 && block.error) textParts.push(`${block.error.name ?? 'error'}: ${block.error.code ?? 'failed'}`)
774
+ const text = textParts.join('\n')
775
+ return React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 6, padding: '4px 0' } },
776
+ React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 6 } },
777
+ IconSparkle ? React.createElement(IconSparkle, { size: 14 }) : null,
778
+ React.createElement('span', {
779
+ style: { fontSize: 13, lineHeight: '20px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
780
+ }, `${TOOL_NAME}: ${derivePrompt(argsRaw)}`)),
781
+ !settled ? React.createElement('p', { style: css.hint }, t('tvGenerating')) : null,
782
+ settled && block.isError && text ? React.createElement('p', { style: css.error }, text.split('\n', 1)[0]) : null,
783
+ settled && !block.isError && images.length > 0
784
+ ? React.createElement('div', { style: css.grid },
785
+ images.map((image, index) => React.createElement(ImageTile, {
786
+ key: image.attachment?.attachmentId ?? image.path ?? index,
787
+ image,
788
+ load,
789
+ t,
790
+ onUse: image.attachment && props.sessionId
791
+ ? () => shareRefsWithPanel(props.sessionId, [image.attachment])
792
+ : undefined,
793
+ })))
794
+ : null,
795
+ settled && !block.isError && images.length === 0 && text
796
+ ? React.createElement('p', { style: { ...css.hint, whiteSpace: 'pre-wrap' } }, text)
797
+ : null,
798
+ )
799
+ }
800
+
801
+ // ------------------------------------------------------- settings card
802
+
803
+ /**
804
+ * The 插件配置 card: model library (provider CRUD) + quick config
805
+ * (default model + default image spec). All writes go to this entry's
806
+ * volatile fields through one atomic `mutate`.
807
+ */
808
+ function LiteBundleCard(props) {
809
+ // The seat supplies `t` from the registration's locale; fall back for
810
+ // runtimes that do not (so a missing translator degrades to English
811
+ // instead of throwing during render).
812
+ const t = props.t ?? translateFactory(en)
813
+ const { ctx, liteForm } = props
814
+ const snap = useSnapshot(liteForm)
815
+ const providers = Array.isArray(snap.value?.providers) ? snap.value.providers : []
816
+ const active = snap.value?.active
817
+ const activeAspect = typeof snap.value?.activeAspect === 'string' && snap.value.activeAspect
818
+ ? snap.value.activeAspect : ASPECTS[0]
819
+
820
+ const [editing, setEditing] = React.useState(null) // provider draft or null
821
+ const [saving, setSaving] = React.useState(false)
822
+ const [providerError, setProviderError] = React.useState('')
823
+ // Bumped after a credential write so the key badges re-read the service.
824
+ const [keyRevision, setKeyRevision] = React.useState(0)
825
+ const [storageError, setStorageError] = React.useState('')
826
+ const [sidebarError, setSidebarError] = React.useState('')
827
+
828
+ const keyStates = useKeyStates(ctx, [active?.apiKeyEnv, ...providers.map((p) => p.apiKeyEnv)], keyRevision)
829
+
830
+ const options = React.useMemo(() => modelOptionsFrom(providers), [providers])
831
+ const choice = activeChoiceFor(active, options)
832
+
833
+ async function writeProviders(nextProviders, nextActive) {
834
+ setSaving(true)
835
+ let saved = true
836
+ try {
837
+ const result = await liteForm.mutate([
838
+ { op: 'set', path: ['providers'], value: nextProviders },
839
+ { op: 'set', path: ['active'], value: nextActive },
840
+ ])
841
+ // A rejected write (stale revision, read-only form) must say so
842
+ // instead of silently leaving the card unchanged.
843
+ saved = result !== false
844
+ } catch {
845
+ saved = false
846
+ }
847
+ setSaving(false)
848
+ if (!saved) {
849
+ setProviderError(t('saveFailed'))
850
+ return false
851
+ }
852
+ setProviderError('')
853
+ // The stored key changes what `credentials.describe` reports, so the
854
+ // badges have to re-read it even when the credential name stays put.
855
+ setKeyRevision((n) => n + 1)
856
+ return true
857
+ }
858
+
859
+ function saveProvider(draft) {
860
+ setProviderError('')
861
+ const outcome = providerFromDraft(draft, providers)
862
+ if (outcome.error) {
863
+ setProviderError(t(outcome.error))
864
+ return
865
+ }
866
+ const provider = outcome.provider
867
+ const secret = String(draft.apiKey ?? '').trim()
868
+ const persist = async () => {
869
+ if (draft.apiKeyMode === 'env') {
870
+ // A plain credential reference: nothing is stored here, the key is
871
+ // read from the environment (or an existing stored credential).
872
+ provider.apiKeyHint = ''
873
+ }
874
+ if (secret) {
875
+ // The secret goes to the credentials service; the config only
876
+ // keeps its name plus a masked preview. The name is derived from
877
+ // the provider id, so a key pasted into a row that used to hold an
878
+ // env-var name replaces that reference instead of overriding it.
879
+ provider.apiKeyEnv = credentialNameFor(provider.id)
880
+ provider.apiKeyHint = maskSecret(secret)
881
+ await writeCredential(ctx, provider.apiKeyEnv, secret)
882
+ }
883
+ const ok = await writeProviders(outcome.nextProviders, syncActiveWithProviders(active, outcome.nextProviders))
884
+ if (ok) setEditing(null)
885
+ }
886
+ void persist().catch((error) => {
887
+ setSaving(false)
888
+ setProviderError(t('keyWriteFailed', { reason: error?.message ?? String(error) }))
889
+ })
890
+ }
891
+
892
+ function deleteProvider(id) {
893
+ const nextProviders = providers.filter((p) => p.id !== id)
894
+ void writeProviders(nextProviders, syncActiveWithProviders(active, nextProviders))
895
+ .then((ok) => { if (ok) setEditing(null) })
896
+ }
897
+
898
+ function pickModel(value) {
899
+ const option = options.find((o) => o.value === value)
900
+ const provider = providers.find((p) => p.id === option?.providerId)
901
+ const nextActive = option
902
+ ? {
903
+ ...buildActiveFromOption({ ...option, baseUrl: provider?.baseUrl, apiKeyEnv: provider?.apiKeyEnv }),
904
+ }
905
+ : emptyActiveValue()
906
+ void liteForm.mutate([{ op: 'set', path: ['active'], value: nextActive }]).catch(() => {})
907
+ }
908
+
909
+ function pickAspect(value) {
910
+ void liteForm.mutate([{ op: 'set', path: ['activeAspect'], value }]).catch(() => {})
911
+ }
912
+
913
+ function saveSidebarEnabled(next) {
914
+ setSidebarError('')
915
+ liteForm.mutate([{ op: 'set', path: ['sidebarEnabled'], value: next }])
916
+ .then((result) => { if (result === false) setSidebarError(t('sidebarSaveFailed')) })
917
+ .catch((error) => setSidebarError(t('sidebarSaveFailed') + ' ' + (error?.message ?? String(error))))
918
+ }
919
+
920
+ function saveOutputDir(value) {
921
+ setStorageError('')
922
+ liteForm.mutate([{ op: 'set', path: ['outputDir'], value }])
923
+ .then((result) => {
924
+ if (result === false) setStorageError(t('saveFailed'))
925
+ })
926
+ .catch((error) => setStorageError(`${t('saveFailed')} ${error?.message ?? String(error)}`))
927
+ }
928
+
929
+ const outputDir = typeof snap.value?.outputDir === 'string' ? snap.value.outputDir : ''
930
+ const sidebarOn = snap.value?.sidebarEnabled !== false
931
+
932
+ const activeComplete = activeLooksComplete(active)
933
+ // Stale: the selection names a provider/model the library no longer has.
934
+ const activeProvider = active?.providerId ? providers.find((p) => p.id === active.providerId) : undefined
935
+ const activeStale = !!active?.providerId && !(activeProvider?.models ?? []).some((m) => m?.id === active?.modelId)
936
+
937
+ return React.createElement('div', { style: css.card },
938
+ React.createElement('p', { style: css.heading }, t('cardTitle')),
939
+ React.createElement('p', { style: css.hint }, t('cardIntro')),
940
+ // model library
941
+ React.createElement('section', { style: css.section },
942
+ React.createElement('h4', { style: css.heading }, t('lib')),
943
+ providers.length === 0
944
+ ? React.createElement('p', { className: 'dsh-igl-empty' }, t('libEmptyCard'))
945
+ : providers.map((provider) => React.createElement(ProviderRow, {
946
+ key: provider.id,
947
+ provider,
948
+ t,
949
+ keySet: keyStates[provider.apiKeyEnv] === true,
950
+ onEdit: () => setEditing(draftFromProvider(provider)),
951
+ onDelete: () => deleteProvider(provider.id),
952
+ })),
953
+ React.createElement('div', { style: { ...css.row, justifyContent: 'flex-start' } },
954
+ editing === null
955
+ ? React.createElement('button', {
956
+ type: 'button', className: 'dsh-igl-btn',
957
+ onClick: () => setEditing(draftFromProvider(null, providers)),
958
+ }, IconPlus ? React.createElement(IconPlus, { size: 12 }) : '+', t('addProvider'))
959
+ : null,
960
+ ),
961
+ editing !== null
962
+ ? React.createElement(ProviderForm, {
963
+ key: editing.id || 'new', // remount so the draft resets when switching providers
964
+ draft: editing,
965
+ t,
966
+ formats: API_FORMATS,
967
+ busy: saving,
968
+ onCancel: () => { setEditing(null); setProviderError('') },
969
+ // The form owns the typed values; the outer draft never sees them.
970
+ onSave: (values) => saveProvider(values ?? editing),
971
+ })
972
+ : null,
973
+ providerError ? React.createElement('p', { style: css.error }, providerError) : null,
974
+ ),
975
+ // quick config
976
+ React.createElement('section', { style: css.section },
977
+ React.createElement('h4', { style: css.heading }, t('quick')),
978
+ React.createElement('div', { style: css.row },
979
+ React.createElement('span', { style: css.label }, t('defaultModel')),
980
+ React.createElement('select', {
981
+ className: 'dsh-igl-select', style: { flex: 1, minWidth: 0 },
982
+ value: choice,
983
+ disabled: snap.status !== 'ready',
984
+ 'aria-label': t('defaultModel'),
985
+ onChange: (event) => pickModel(event.target.value),
986
+ },
987
+ options.length > 0 ? React.createElement('option', { value: '', disabled: true }, t('modelPlaceholder')) : null,
988
+ options.map((o) => React.createElement('option', { key: o.value, value: o.value }, o.label))),
989
+ ),
990
+ React.createElement('div', { style: css.row },
991
+ React.createElement('span', { style: css.label }, t('defaultAspect')),
992
+ React.createElement('select', {
993
+ className: 'dsh-igl-select', style: { flex: 1, minWidth: 0 },
994
+ value: activeAspect,
995
+ disabled: snap.status !== 'ready',
996
+ 'aria-label': t('defaultAspect'),
997
+ onChange: (event) => pickAspect(event.target.value),
998
+ }, ASPECTS.map((a) => React.createElement('option', { key: a, value: a }, a))),
999
+ ),
1000
+ activeStale
1001
+ ? React.createElement('p', { style: css.error }, t('quickStale'))
1002
+ : !activeComplete
1003
+ ? React.createElement('p', { style: css.hint }, t('quickUnset'))
1004
+ : keyStates[active?.apiKeyEnv] === false
1005
+ ? React.createElement('p', { style: css.error }, t('keyUnset'))
1006
+ : React.createElement('p', { style: css.hint }, t('quickReady')),
1007
+ ),
1008
+ // sidebar studio switch
1009
+ React.createElement('section', { style: css.section },
1010
+ React.createElement('h4', { style: css.heading }, t('sidebar')),
1011
+ React.createElement(ToggleRow, {
1012
+ label: t('sidebarStudio'),
1013
+ hint: t('sidebarStudioHint'),
1014
+ checked: sidebarOn,
1015
+ disabled: snap.status !== 'ready',
1016
+ onChange: (next) => saveSidebarEnabled(next),
1017
+ }),
1018
+ sidebarError ? React.createElement('p', { style: css.error }, sidebarError) : null,
1019
+ ),
1020
+ // where the files land
1021
+ React.createElement('section', { style: css.section },
1022
+ React.createElement('h4', { style: css.heading }, t('storage')),
1023
+ React.createElement(OutputDirField, {
1024
+ t,
1025
+ ctx,
1026
+ value: outputDir,
1027
+ disabled: snap.status !== 'ready',
1028
+ onCommit: saveOutputDir,
1029
+ onError: setStorageError,
1030
+ }),
1031
+ storageError ? React.createElement('p', { style: css.error }, storageError) : null,
1032
+ React.createElement('p', { style: css.hint }, t('storageHint')),
1033
+ ),
1034
+ )
1035
+ }
1036
+
1037
+ /**
1038
+ * Text field for the image folder. The two buttons only show while the
1039
+ * field is being edited (it was just clicked), so the card stays quiet.
1040
+ * An empty value means the default directory.
1041
+ */
1042
+ /** One boolean row: a pill switch plus its label and hint. */
1043
+ function ToggleRow({ label, hint, checked, disabled, onChange }) {
1044
+ const onColor = 'var(--dsw-alias-state-focus-border, #4c8dff)'
1045
+ const offColor = 'var(--dsw-alias-border-l2, #555)'
1046
+ return React.createElement('div', {
1047
+ style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 },
1048
+ },
1049
+ React.createElement('div', { style: { minWidth: 0 } },
1050
+ React.createElement('span', { style: css.label }, label),
1051
+ hint ? React.createElement('p', { style: css.hint }, hint) : null,
1052
+ ),
1053
+ React.createElement('button', {
1054
+ type: 'button',
1055
+ role: 'switch',
1056
+ 'aria-checked': checked,
1057
+ 'aria-label': label,
1058
+ disabled,
1059
+ className: 'dsh-igl-switch',
1060
+ style: { ...css.switch, background: checked ? onColor : offColor, ...(disabled ? css.idle : null) },
1061
+ onClick: () => onChange(!checked),
1062
+ }, React.createElement('span', { style: { ...css.switchKnob, left: checked ? 21 : 3 } })),
1063
+ )
1064
+ }
1065
+
1066
+ /**
1067
+ * Native folder chooser. The desktop shell injects
1068
+ * `__DSH_DIRECTORY_PICKER__`; other runtimes expose the same picker on the
1069
+ * workspace UI service. Resolves the chosen absolute path, or null when the
1070
+ * user cancels.
1071
+ */
1072
+ async function pickFolderPath(ctx) {
1073
+ const bridge = globalThis.__DSH_DIRECTORY_PICKER__
1074
+ if (bridge !== undefined && typeof bridge.pick === 'function') return await bridge.pick()
1075
+ const ui = ctx?.uiWorkspace ?? ctx?.get?.('uiWorkspace')
1076
+ if (ui !== undefined && typeof ui.pickDirectory === 'function') return await ui.pickDirectory()
1077
+ throw new Error('image_generate_lite: this runtime exposes no directory picker')
1078
+ }
1079
+
1080
+ function OutputDirField({ t, value, disabled, onCommit, onError, ctx }) {
1081
+
1082
+ const [text, setText] = React.useState(value)
1083
+ const [editing, setEditing] = React.useState(false)
1084
+ const inputRef = React.useRef(null)
1085
+ React.useEffect(() => { setText(value) }, [value])
1086
+ // Drop the focus too, so clicking the field again re-opens the buttons.
1087
+ const cancel = () => { setText(value); setEditing(false); inputRef.current?.blur() }
1088
+ const save = () => {
1089
+ const trimmed = String(text ?? '').trim()
1090
+ setText(trimmed)
1091
+ setEditing(false)
1092
+ inputRef.current?.blur()
1093
+ if (trimmed !== value) onCommit(trimmed)
1094
+ }
1095
+ // Keep the focus (and thus the buttons) alive while a button is pressed.
1096
+ const hold = (event) => event.preventDefault()
1097
+ const browse = async () => {
1098
+ if (disabled) return
1099
+ try {
1100
+ const picked = await pickFolderPath(ctx)
1101
+ if (typeof picked !== 'string' || picked.trim().length === 0) return // cancelled
1102
+ const next = picked.trim()
1103
+ setText(next)
1104
+ setEditing(false)
1105
+ inputRef.current?.blur()
1106
+ if (next !== value) onCommit(next)
1107
+ } catch (error) {
1108
+ onError?.(t('pickFailed') + ': ' + (error?.message ?? String(error)))
1109
+ }
1110
+ }
1111
+ return React.createElement('div', { style: { ...css.row, alignItems: 'flex-start' } },
1112
+ React.createElement('input', {
1113
+ ref: inputRef,
1114
+ className: 'dsh-igl-input',
1115
+ style: { flex: 1, minWidth: 0 },
1116
+ value: text,
1117
+ disabled,
1118
+ spellCheck: false,
1119
+ placeholder: t('storagePlaceholder'),
1120
+ 'aria-label': t('storage'),
1121
+ onFocus: () => setEditing(true),
1122
+ onChange: (event) => setText(event.target.value),
1123
+ onKeyDown: (event) => {
1124
+ if (event.key === 'Enter') { event.preventDefault(); save() }
1125
+ else if (event.key === 'Escape') { event.preventDefault(); cancel() }
1126
+ },
1127
+ }),
1128
+ React.createElement('button', {
1129
+ type: 'button',
1130
+ className: 'dsh-igl-btn',
1131
+ style: { whiteSpace: 'nowrap' },
1132
+ disabled,
1133
+ title: t('browse'),
1134
+ 'aria-label': t('browse'),
1135
+ onMouseDown: hold,
1136
+ onClick: () => { void browse() },
1137
+ }, t('browse')),
1138
+ editing
1139
+ ? React.createElement('button', {
1140
+ type: 'button', className: 'dsh-igl-btn', style: css.danger, disabled,
1141
+ onMouseDown: hold, onClick: cancel,
1142
+ }, t('cancel'))
1143
+ : null,
1144
+ editing
1145
+ ? React.createElement('button', {
1146
+ type: 'button', className: 'dsh-igl-primary', disabled,
1147
+ onMouseDown: hold, onClick: save,
1148
+ }, t('save'))
1149
+ : null,
1150
+ )
1151
+ }
1152
+
1153
+ /**
1154
+ * The editor draft for one provider (or a blank one for a new provider).
1155
+ * `apiKey` starts empty on purpose: a stored secret is never read back, and
1156
+ * an empty field means "keep the key that is already there".
1157
+ */
1158
+ function draftFromProvider(provider, providers) {
1159
+ if (provider === null) {
1160
+ void providers
1161
+ return {
1162
+ isNew: true, id: '', name: '', baseUrl: '', apiFormat: SUPPORTED_FORMAT,
1163
+ apiKeyEnv: '', apiKeyHint: '', apiKeyMode: 'key', apiKey: '', modelsText: '',
1164
+ }
1165
+ }
1166
+ const hasStoredKey = typeof provider.apiKeyHint === 'string' && provider.apiKeyHint.length > 0
1167
+ const pointsAtName = looksLikeCredentialName(provider.apiKeyEnv)
1168
+ return {
1169
+ isNew: false,
1170
+ id: provider.id,
1171
+ name: provider.name ?? '',
1172
+ baseUrl: provider.baseUrl ?? '',
1173
+ apiFormat: provider.apiFormat ?? SUPPORTED_FORMAT,
1174
+ apiKeyEnv: provider.apiKeyEnv ?? '',
1175
+ apiKeyHint: provider.apiKeyHint ?? '',
1176
+ // A provider that points at a credential name (no stored key) keeps
1177
+ // that mode; anything else is a key the user has to paste again.
1178
+ apiKeyMode: !hasStoredKey && pointsAtName ? 'env' : 'key',
1179
+ apiKey: '',
1180
+ modelsText: (provider.models ?? []).map((m) => (m.name && m.name !== m.id ? `${m.id} ${m.name}` : m.id)).join('\n'),
1181
+ }
1182
+ }
1183
+
1184
+ /**
1185
+ * Turn one editor draft into a library write. The editor keeps its typed
1186
+ * values in local state, so this is the single place those values become a
1187
+ * provider row — pure, so the save path is testable without a DOM.
1188
+ * @param draft - the editor's current values (`isNew` marks a fresh row).
1189
+ * @param providers - the library to write into.
1190
+ * @returns `{error}` when the draft is unusable, else the new row and library.
1191
+ */
1192
+ function providerFromDraft(draft, providers) {
1193
+ const name = String(draft?.name ?? '').trim()
1194
+ const id = String(draft?.id ?? '').trim()
1195
+ if (!name && !id) return { error: 'nameRequired' }
1196
+ // The ID is typed or derived from the name, and it is final: a collision
1197
+ // is reported, never silently renamed to `agnes-2`.
1198
+ const providerId = id || slugForProvider(name, new Set())
1199
+ const provider = {
1200
+ id: providerId,
1201
+ name: name || id,
1202
+ baseUrl: String(draft.baseUrl ?? '').trim(),
1203
+ apiFormat: draft.apiFormat || SUPPORTED_FORMAT,
1204
+ apiKeyEnv: String(draft.apiKeyEnv ?? '').trim(),
1205
+ apiKeyHint: String(draft.apiKeyHint ?? '').trim(),
1206
+ models: parseModelLines(draft.modelsText),
1207
+ }
1208
+ if (!provider.id) return { error: 'nameRequired' }
1209
+ // The edited row keeps its own id (the field is locked), so only a new
1210
+ // row can clash on the id.
1211
+ const exists = providers.some((p) => p.id === provider.id)
1212
+ if (draft.isNew !== false && exists) {
1213
+ // With no typed ID the collision is really the name's, so name it.
1214
+ return { error: id ? 'idTaken' : 'nameTaken' }
1215
+ }
1216
+ const others = providers.filter((p) => p.id !== provider.id)
1217
+ const lowerName = provider.name.toLowerCase()
1218
+ // A row keeps its own name even when a legacy duplicate carries it too,
1219
+ // so pre-existing duplicates stay editable; renaming onto another name
1220
+ // is always refused.
1221
+ const stored = providers.find((p) => p.id === provider.id)
1222
+ const nameUnchanged = !!stored && String(stored.name ?? '').trim().toLowerCase() === lowerName
1223
+ if (!nameUnchanged && others.some((p) => String(p.name ?? '').trim().toLowerCase() === lowerName)) {
1224
+ return { error: 'nameTaken' }
1225
+ }
1226
+ return {
1227
+ provider,
1228
+ nextProviders: exists
1229
+ ? providers.map((p) => (p.id === provider.id ? provider : p))
1230
+ : [...providers, provider],
1231
+ }
1232
+ }
1233
+
1234
+ function ProviderRow({ provider, t, keySet, onEdit, onDelete }) {
1235
+ const models = provider.models ?? []
1236
+ const format = provider.apiFormat || SUPPORTED_FORMAT
1237
+ return React.createElement('div', { style: css.libRow },
1238
+ React.createElement('div', { style: { minWidth: 0, flex: 1, display: 'flex', flexDirection: 'column', gap: 2 } },
1239
+ React.createElement('div', { style: css.row },
1240
+ React.createElement('span', { style: { fontSize: 13, fontWeight: 600 } }, provider.name || provider.id),
1241
+ React.createElement('span', { className: 'dsh-igl-badge' }, format),
1242
+ format !== SUPPORTED_FORMAT
1243
+ ? React.createElement('span', { className: 'dsh-igl-badge', title: t('unsupportedNote') }, t('unsupportedNote'))
1244
+ : null,
1245
+ React.createElement('span', {
1246
+ className: `dsh-igl-badgeset${keySet ? '' : ' off'}`,
1247
+ }, keySet ? t('keySet') : t('keyMissing')),
1248
+ ),
1249
+ React.createElement('div', { style: { ...css.libMeta, overflow: 'hidden' } },
1250
+ `${provider.baseUrl || '—'} · ${t('modelsCount', { n: models.length })}`
1251
+ + (provider.apiKeyHint ? ` · ${provider.apiKeyHint}` : '')),
1252
+ models.length > 0
1253
+ ? React.createElement('div', { style: { ...css.grid, marginTop: 4 } },
1254
+ models.map((m) => React.createElement('span', { key: m.id, className: 'dsh-igl-mchip' },
1255
+ m.name || m.id)))
1256
+ : null,
1257
+ ),
1258
+ React.createElement('div', { style: { display: 'flex', gap: 6, flex: 'none' } },
1259
+ React.createElement('button', { type: 'button', className: 'dsh-igl-btn', onClick: onEdit }, t('editProvider')),
1260
+ React.createElement('button', { type: 'button', className: 'dsh-igl-btn', onClick: onDelete, 'aria-label': t('deleteProvider') },
1261
+ IconTrash ? React.createElement(IconTrash, { size: 12 }) : t('deleteProvider')),
1262
+ ),
1263
+ )
1264
+ }
1265
+
1266
+ function ProviderForm({ draft, t, formats, busy, onCancel, onSave }) {
1267
+ const [value, setValue] = React.useState(draft)
1268
+ const set = (key) => (event) => setValue((v) => ({ ...v, [key]: event.target.value }))
1269
+ return React.createElement('div', {
1270
+ style: {
1271
+ display: 'flex', flexDirection: 'column', gap: 10, padding: 12,
1272
+ border: '1px solid var(--dsw-alias-border-l2)', borderRadius: 10,
1273
+ background: 'var(--dsw-alias-bg-layer-2, var(--dsw-alias-bg-layer-1))',
1274
+ },
1275
+ },
1276
+ React.createElement('p', { style: { ...css.heading, fontSize: 13 } }, value.isNew ? t('addProvider') : t('editProvider')),
1277
+ React.createElement('div', { style: css.formGrid },
1278
+ React.createElement('label', { style: css.row },
1279
+ React.createElement('span', { style: css.label }, t('providerName')),
1280
+ React.createElement('input', { className: 'dsh-igl-input', value: value.name, onChange: set('name'), 'aria-label': t('providerName') })),
1281
+ React.createElement('label', { style: css.row },
1282
+ React.createElement('span', { style: css.label }, t('providerId')),
1283
+ React.createElement('input', {
1284
+ className: 'dsh-igl-input', value: value.id, disabled: !value.isNew,
1285
+ placeholder: value.isNew ? 'auto (from name)' : '', onChange: set('id'), 'aria-label': t('providerId'),
1286
+ })),
1287
+ React.createElement('label', { style: { ...css.row, gridColumn: '1 / -1' } },
1288
+ React.createElement('span', { style: css.label }, t('providerBase')),
1289
+ React.createElement('input', {
1290
+ className: 'dsh-igl-input', value: value.baseUrl, onChange: set('baseUrl'),
1291
+ placeholder: 'https://…/v1', 'aria-label': t('providerBase'),
1292
+ })),
1293
+ React.createElement('label', { style: css.row },
1294
+ React.createElement('span', { style: css.label }, t('providerFormat')),
1295
+ React.createElement('select', {
1296
+ className: 'dsh-igl-select', value: value.apiFormat, onChange: set('apiFormat'),
1297
+ style: { flex: 1, minWidth: 0, maxWidth: 220 }, 'aria-label': t('providerFormat'),
1298
+ }, formats.map((f) => React.createElement('option', { key: f.id, value: f.id }, `${f.id} — ${f.note}`)))),
1299
+ React.createElement('div', { style: { gridColumn: '1 / -1', display: 'flex', flexDirection: 'column', gap: 4 } },
1300
+ React.createElement('div', { style: { ...css.row, justifyContent: 'space-between' } },
1301
+ React.createElement('label', { style: css.label }, value.apiKeyMode === 'env' ? t('providerKeyEnv') : t('providerKey')),
1302
+ React.createElement('button', {
1303
+ type: 'button', className: 'dsh-igl-btn',
1304
+ onClick: () => setValue((v) => ({ ...v, apiKeyMode: v.apiKeyMode === 'env' ? 'key' : 'env' })),
1305
+ }, value.apiKeyMode === 'env' ? t('keyModeKey') : t('keyModeEnv'))),
1306
+ value.apiKeyMode === 'env'
1307
+ ? React.createElement('input', {
1308
+ className: 'dsh-igl-input', value: value.apiKeyEnv, onChange: set('apiKeyEnv'),
1309
+ placeholder: 'MY_IMAGE_API_KEY', 'aria-label': t('providerKeyEnv'),
1310
+ })
1311
+ : React.createElement('input', {
1312
+ className: 'dsh-igl-input', type: 'password', autoComplete: 'off', spellCheck: false,
1313
+ value: value.apiKey, onChange: set('apiKey'),
1314
+ placeholder: value.apiKeyHint ? t('keySaved', { hint: value.apiKeyHint }) : t('keyPlaceholder'),
1315
+ 'aria-label': t('providerKey'),
1316
+ }),
1317
+ value.apiKeyMode === 'env'
1318
+ ? React.createElement('span', { style: css.hint }, t('keyEnvHint'))
1319
+ : value.apiKeyHint
1320
+ ? React.createElement('span', { style: css.hint }, t('keyStoredHint', { hint: value.apiKeyHint }))
1321
+ : value.apiKeyEnv && !looksLikeCredentialName(value.apiKeyEnv)
1322
+ ? React.createElement('span', { style: css.hint }, t('keyReplaceHint'))
1323
+ : React.createElement('span', { style: css.hint }, t('keyHint')),
1324
+ ),
1325
+ React.createElement('div', { style: { gridColumn: '1 / -1', display: 'flex', flexDirection: 'column', gap: 4 } },
1326
+ React.createElement('label', { style: css.label }, t('providerModels')),
1327
+ React.createElement('textarea', {
1328
+ className: 'dsh-igl-textarea', value: value.modelsText, onChange: set('modelsText'),
1329
+ placeholder: 'gpt-image-1\ngpt-image-2 GPT Image 2', 'aria-label': t('providerModels'),
1330
+ }),
1331
+ React.createElement('span', { style: css.hint }, t('modelsHint')),
1332
+ ),
1333
+ ),
1334
+ React.createElement('div', { style: { ...css.row, justifyContent: 'flex-end' } },
1335
+ React.createElement('button', { type: 'button', className: 'dsh-igl-btn', onClick: onCancel }, t('cancel')),
1336
+ React.createElement('button', {
1337
+ type: 'button', className: 'dsh-igl-primary', disabled: busy,
1338
+ onClick: () => onSave(value),
1339
+ }, t('save')),
1340
+ ),
1341
+ )
1342
+ }
1343
+
1344
+ // ---------------------------------------------------------------- studio panel
1345
+
1346
+ function StudioBody(props) {
1347
+ const t = props.t ?? translateFactory(en)
1348
+ const { ctx, rpc, sessionId, liteForm, useSessions } = props
1349
+ const [store, updateStore] = useSessionStore(sessionId)
1350
+ const [busy, setBusy] = React.useState(false)
1351
+ const [error, setError] = React.useState('')
1352
+ const [prompt, setPrompt] = React.useState(store.prompt)
1353
+ const [refsFocus, setRefsFocus] = React.useState(false)
1354
+
1355
+ const liteSnap = useSnapshot(liteForm)
1356
+
1357
+ React.useEffect(() => { setPrompt(store.prompt) }, [store.prompt])
1358
+
1359
+ const sessionsUse = typeof useSessions === 'function' ? useSessions : undefined
1360
+ const cwd = sessionsUse ? sessionsUse((all) => all.byId?.[sessionId]?.cwd) : undefined
1361
+
1362
+ const providers = Array.isArray(liteSnap.value?.providers) ? liteSnap.value.providers : []
1363
+ const options = React.useMemo(() => modelOptionsFrom(providers), [providers])
1364
+ const active = liteSnap.value?.active
1365
+ const activeAspect = typeof liteSnap.value?.activeAspect === 'string' && liteSnap.value.activeAspect
1366
+ ? liteSnap.value.activeAspect : ASPECTS[0]
1367
+ const hasActive = activeLooksComplete(active)
1368
+ const choice = activeChoiceFor(active, options)
1369
+
1370
+ const keyStates = useKeyStates(ctx, [active?.apiKeyEnv])
1371
+
1372
+ const load = React.useCallback(
1373
+ (image) => createImageLoader(ctx, rpc, sessionId)(image, cwd),
1374
+ [ctx, rpc, sessionId, cwd],
1375
+ )
1376
+
1377
+ async function pickModel(value) {
1378
+ const option = options.find((row) => row.value === value)
1379
+ if (!option) return
1380
+ const provider = providers.find((p) => p.id === option.providerId)
1381
+ try {
1382
+ await liteForm.mutate([{
1383
+ op: 'set',
1384
+ path: ['active'],
1385
+ value: {
1386
+ ...buildActiveFromOption({ ...option, baseUrl: provider?.baseUrl, apiKeyEnv: provider?.apiKeyEnv }),
1387
+ },
1388
+ }])
1389
+ } catch { /* the form's recovery read re-syncs the snapshot */ }
1390
+ }
1391
+
1392
+ async function pickAspect(value) {
1393
+ try {
1394
+ await liteForm.mutate([{ op: 'set', path: ['activeAspect'], value }])
1395
+ } catch { /* snapshot resyncs */ }
1396
+ }
1397
+
1398
+ async function addFiles(fileList) {
1399
+ const files = Array.from(fileList ?? []).filter((f) => /^image\/(png|jpe?g|webp|gif)$/i.test(f.type))
1400
+ if (files.length === 0) return
1401
+ const room = MAX_REFS - store.refs.length
1402
+ if (room <= 0) { setError(t('refsFull')); return }
1403
+ const items = []
1404
+ for (const file of files.slice(0, room)) {
1405
+ const data = await new Promise((resolveData, rejectData) => {
1406
+ const reader = new FileReader()
1407
+ reader.onload = () => resolveData(String(reader.result).split(',', 2)[1] ?? '')
1408
+ reader.onerror = () => rejectData(reader.error)
1409
+ reader.readAsDataURL(file)
1410
+ })
1411
+ items.push({ data, mediaType: file.type === 'image/jpg' ? 'image/jpeg' : file.type, name: file.name })
1412
+ }
1413
+ try {
1414
+ const value = await rpcCall(rpc, 'admitImages', { items })
1415
+ const fresh = value.refs.filter((ref) => !store.refs.some((r) => r.attachmentId === ref.attachmentId))
1416
+ if (fresh.length > 0) updateStore((prev) => ({ ...prev, refs: [...prev.refs, ...fresh].slice(0, MAX_REFS) }))
1417
+ setError('')
1418
+ } catch (err) {
1419
+ setError(`${t('uploadFailed')} ${err?.message ?? ''}`)
1420
+ }
1421
+ }
1422
+
1423
+ function useThis(ref) {
1424
+ updateStore((prev) => {
1425
+ const rest = prev.refs.filter((r) => r.attachmentId !== ref.attachmentId)
1426
+ return { ...prev, refs: [ref, ...rest].slice(0, MAX_REFS) }
1427
+ })
1428
+ setError('')
1429
+ }
1430
+
1431
+ function removeRef(ref) {
1432
+ updateStore((prev) => ({ ...prev, refs: prev.refs.filter((r) => r.attachmentId !== ref.attachmentId) }))
1433
+ }
1434
+
1435
+ async function generate() {
1436
+ const text = prompt.trim()
1437
+ if (!text || busy) return
1438
+ setBusy(true)
1439
+ setError('')
1440
+ try {
1441
+ const value = await rpcCall(rpc, 'generate', {
1442
+ cwd,
1443
+ aspect: activeAspect,
1444
+ prompt: text,
1445
+ ...store.refs.length > 0 ? { refs: store.refs } : {},
1446
+ })
1447
+ updateStore((prev) => ({
1448
+ ...prev,
1449
+ prompt: text,
1450
+ recent: [{
1451
+ images: value.images ?? [],
1452
+ paths: value.paths ?? [],
1453
+ provider: value.provider,
1454
+ model: value.model,
1455
+ aspect: value.aspect,
1456
+ at: Date.now(),
1457
+ }, ...prev.recent].slice(0, 12),
1458
+ }))
1459
+ } catch (err) {
1460
+ setError(`${t('errorPrefix')}: ${err?.message ?? err}`)
1461
+ } finally {
1462
+ setBusy(false)
1463
+ }
1464
+ }
1465
+
1466
+ const canGenerate = hasActive && !!cwd && prompt.trim().length > 0 && !busy
1467
+ const nothingToClear = store.refs.length === 0 && prompt.trim().length === 0 && store.recent.length === 0
1468
+ // Start over: references, prompt, results — the model and aspect stay.
1469
+ const clearPanel = () => {
1470
+ updateStore({ refs: [], prompt: '', recent: [] })
1471
+ setPrompt('')
1472
+ setError('')
1473
+ }
1474
+
1475
+ return React.createElement('div', { style: css.panel, onPaste: (event) => {
1476
+ const files = Array.from(event.clipboardData?.items ?? [])
1477
+ .map((item) => item.getAsFile())
1478
+ .filter((f) => f !== null)
1479
+ if (files.length > 0) { event.preventDefault(); addFiles(files) }
1480
+ } },
1481
+ // Clear — top-right, red, disabled while a generation runs or when idle.
1482
+ React.createElement('div', { style: css.topbar },
1483
+ React.createElement('button', {
1484
+ type: 'button',
1485
+ className: 'dsh-igl-btn',
1486
+ style: { ...css.danger, ...(busy || nothingToClear ? css.idle : null) },
1487
+ 'aria-label': t('clear'),
1488
+ title: t('clearHint'),
1489
+ disabled: busy || nothingToClear,
1490
+ onClick: clearPanel,
1491
+ }, t('clear')),
1492
+ ),
1493
+ // Model
1494
+ React.createElement('div', { style: css.section },
1495
+ React.createElement('p', { style: css.heading }, t('model')),
1496
+ options.length === 0
1497
+ ? React.createElement('p', { className: 'dsh-igl-empty' }, t('libEmpty'))
1498
+ : React.createElement('select', {
1499
+ className: 'dsh-igl-select', style: { maxWidth: '100%' },
1500
+ value: choice,
1501
+ disabled: liteSnap.status !== 'ready',
1502
+ 'aria-label': t('model'),
1503
+ onChange: (event) => pickModel(event.target.value),
1504
+ },
1505
+ React.createElement('option', { value: '', disabled: true }, t('modelPlaceholder')),
1506
+ options.map((o) => React.createElement('option', { key: o.value, value: o.value }, o.label))),
1507
+ !hasActive ? React.createElement('p', { style: css.hint }, t('noActive')) : null,
1508
+ hasActive && keyStates[active?.apiKeyEnv] === false ? React.createElement('p', { style: css.error }, t('keyUnset')) : null,
1509
+ hasActive && keyStates[active?.apiKeyEnv] === true ? React.createElement('span', { style: { ...css.hint, alignSelf: 'flex-start' } }, t('keyConfigured')) : null,
1510
+ ),
1511
+ // Aspect
1512
+ React.createElement('div', { style: css.row },
1513
+ React.createElement('span', { style: css.label }, t('aspect')),
1514
+ React.createElement('select', {
1515
+ className: 'dsh-igl-select', style: { flex: 1, minWidth: 0 },
1516
+ value: activeAspect,
1517
+ disabled: liteSnap.status !== 'ready',
1518
+ 'aria-label': t('aspect'),
1519
+ onChange: (event) => pickAspect(event.target.value),
1520
+ }, ASPECTS.map((a) => React.createElement('option', { key: a, value: a }, a))),
1521
+ ),
1522
+ // References — clicking this box selects it, so paste has a visible target.
1523
+ React.createElement('div', { style: css.section },
1524
+ React.createElement('p', { style: css.heading }, `${t('refs')} (${store.refs.length}/${MAX_REFS})`),
1525
+ React.createElement('div', {
1526
+ className: 'dsh-igl-drop',
1527
+ tabIndex: 0,
1528
+ role: 'group',
1529
+ 'aria-label': t('refs'),
1530
+ 'aria-describedby': 'dsh-igl-refs-hint',
1531
+ style: { ...css.drop, ...(refsFocus ? css.dropActive : null) },
1532
+ onFocus: () => setRefsFocus(true),
1533
+ onBlur: () => setRefsFocus(false),
1534
+ onClick: () => setRefsFocus(true),
1535
+ onPaste: (event) => {
1536
+ const files = Array.from(event.clipboardData?.items ?? [])
1537
+ .map((item) => item.getAsFile())
1538
+ .filter((f) => f !== null)
1539
+ if (files.length > 0) { event.preventDefault(); addFiles(files) }
1540
+ },
1541
+ },
1542
+ store.refs.length === 0
1543
+ ? React.createElement('p', { className: 'dsh-igl-empty', style: { margin: 0 } }, t('refsEmpty'))
1544
+ : React.createElement('div', { style: css.grid },
1545
+ store.refs.map((ref) => React.createElement('div', { key: ref.attachmentId, style: { position: 'relative' } },
1546
+ React.createElement(ImageTile, { image: { attachment: ref }, load, t }),
1547
+ React.createElement('button', {
1548
+ type: 'button', className: 'dsh-igl-icon',
1549
+ style: {
1550
+ position: 'absolute', top: 2, right: 2,
1551
+ background: 'var(--dsw-alias-bg-module-platform)',
1552
+ },
1553
+ 'aria-label': t('removeRef'),
1554
+ onClick: () => removeRef(ref),
1555
+ }, IconTrash ? React.createElement(IconTrash, { size: 12 }) : '×'),
1556
+ ))),
1557
+ ),
1558
+ React.createElement('div', { style: css.row },
1559
+ React.createElement('label', { className: 'dsh-igl-btn', style: { cursor: 'pointer' } },
1560
+ t('upload'),
1561
+ React.createElement('input', {
1562
+ type: 'file', accept: 'image/png,image/jpeg,image/webp,image/gif', multiple: true,
1563
+ style: { display: 'none' },
1564
+ onChange: (event) => { addFiles(event.target.files); event.target.value = '' },
1565
+ })),
1566
+ React.createElement('span', { id: 'dsh-igl-refs-hint', style: { ...css.hint, ...(refsFocus ? css.hintActive : null) } },
1567
+ refsFocus ? t('refsSelected') : t('paste')),
1568
+ ),
1569
+ ),
1570
+ // Prompt + generate
1571
+ React.createElement('div', { style: css.section },
1572
+ React.createElement('label', { style: { ...css.label, display: 'block' } }, t('prompt')),
1573
+ React.createElement('input', {
1574
+ className: 'dsh-igl-input', value: prompt, placeholder: t('promptPlaceholder'),
1575
+ onChange: (event) => setPrompt(event.target.value),
1576
+ 'aria-label': t('prompt'),
1577
+ }),
1578
+ error ? React.createElement('p', { style: css.error, role: 'alert' }, error) : null,
1579
+ !cwd ? React.createElement('p', { style: css.hint }, t('noCwd')) : null,
1580
+ React.createElement('button', {
1581
+ type: 'button', className: 'dsh-igl-primary', disabled: !canGenerate, onClick: generate,
1582
+ }, busy ? t('generating') : t('generate')),
1583
+ ),
1584
+ // Results
1585
+ React.createElement('div', { style: css.section },
1586
+ React.createElement('p', { style: css.heading }, t('results')),
1587
+ store.recent.length === 0
1588
+ ? React.createElement('p', { className: 'dsh-igl-empty' }, t('resultsEmpty'))
1589
+ : store.recent.map((result, index) => React.createElement('div', { key: index, style: css.resultCard },
1590
+ result.images.length > 0
1591
+ ? React.createElement('div', { style: css.grid },
1592
+ result.images.map((ref, i) => React.createElement(ImageTile, {
1593
+ key: ref.attachmentId ?? i,
1594
+ image: { attachment: ref },
1595
+ load,
1596
+ t,
1597
+ onUse: () => useThis(ref),
1598
+ })))
1599
+ : React.createElement('p', { style: css.hint }, (result.paths ?? []).join(', ')),
1600
+ React.createElement('span', { style: css.hint },
1601
+ `${result.provider ?? '—'} / ${result.model ?? '—'} · ${result.aspect ?? '—'}`),
1602
+ )),
1603
+ ),
1604
+ )
1605
+ }
1606
+
1607
+ function StudioTitle(props) {
1608
+ const t = props.t ?? translateFactory(en)
1609
+ return React.createElement(React.Fragment, null,
1610
+ IconSparkle ? React.createElement(IconSparkle, { size: 16 }) : null,
1611
+ React.createElement('span', { style: { fontSize: 13, lineHeight: '20px' } }, t('title')),
1612
+ )
1613
+ }
1614
+
1615
+ function CornerButton(props) {
1616
+ const t = props.t ?? translateFactory(en)
1617
+ return React.createElement('button', {
1618
+ type: 'button',
1619
+ className: 'dsh-igl-corner',
1620
+ title: t('cornerTooltip'),
1621
+ 'aria-label': t('cornerTooltip'),
1622
+ onClick: props.openStudio,
1623
+ }, IconSparkle ? React.createElement(IconSparkle, { size: 16 }) : t('title'))
1624
+ }
1625
+
1626
+ // ---------------------------------------------------------------- configForms
1627
+
1628
+ /**
1629
+ * Guard against runtimes without the configuration forms service:
1630
+ * an inert scope keeps the panel mounted (read-only, nothing to pick).
1631
+ */
1632
+ function formScope(form) {
1633
+ if (!form || typeof form.getSnapshot !== 'function' || typeof form.mutate !== 'function') {
1634
+ return {
1635
+ getSnapshot: () => ({ status: 'unavailable', value: undefined, writable: false, revision: undefined }),
1636
+ subscribe: () => () => {},
1637
+ mutate: () => Promise.resolve(false),
1638
+ }
1639
+ }
1640
+ return form
1641
+ }
1642
+
1643
+ // ---------------------------------------------------------------- inject + apply
1644
+
1645
+ // 'settingsScope' was removed in DSH 0.1.7 (replaced by 'configForms').
1646
+ const inject = [
1647
+ 'slots',
1648
+ 'locale',
1649
+ 'sidebarRight',
1650
+ 'sidebarRightTabs',
1651
+ 'connection',
1652
+ 'remote',
1653
+ 'remote.credentials',
1654
+ 'configForms',
1655
+ 'uiConversation',
1656
+ 'sessions',
1657
+ ]
1658
+
1659
+ /**
1660
+ * Run one registration on its own. The web shell turns any throw inside a
1661
+ * client entry into "entry did not activate" and refuses to boot the whole
1662
+ * UI, so a seat another plugin already owns (or one this DSH build no
1663
+ * longer declares) must only cost that one capability, never the entry.
1664
+ */
1665
+ const softly = (label, run) => {
1666
+ try {
1667
+ return run()
1668
+ } catch (error) {
1669
+ try {
1670
+ console.warn(`dsh-image-lite: ${label} unavailable`, error)
1671
+ } catch {}
1672
+ return undefined
1673
+ }
1674
+ }
1675
+
1676
+ function apply(ctx) {
1677
+ softly('studio styles', ensurePanelCss)
1678
+ const t = ctx.locale.bind(LOCALE_NS)
1679
+ const lite = formScope(ctx.get('configForms')?.get?.(ENTRY_NS) ?? ctx.configForms?.get?.(ENTRY_NS))
1680
+
1681
+ softly('copy dictionaries', () => ctx.effect(
1682
+ () => ctx.locale.register(LOCALE_NS, { zh, en }),
1683
+ 'dsh-image-lite: copy dictionaries',
1684
+ ))
1685
+
1686
+ // 1-4. The sidebar studio, behind one reactive gate: the switch in the
1687
+ // settings card hides (and restores) the tab type, its guide entry,
1688
+ // the pane body and the header button without a window reload.
1689
+ softly('sidebar studio', () => ctx.effect(() => {
1690
+ let disposers = []
1691
+ const release = () => {
1692
+ for (const dispose of disposers) { try { dispose() } catch {} }
1693
+ disposers = []
1694
+ }
1695
+ const mount = () => {
1696
+ if (!sidebarStudioEnabled(lite)) return
1697
+ const register = (run) => {
1698
+ try { disposers.push(run()) } catch (error) {
1699
+ try { console.warn('dsh-image-lite: a studio seat failed to register', error) } catch {}
1700
+ }
1701
+ }
1702
+ // The tab type.
1703
+ register(() => ctx.sidebarRightTabs.register({
1704
+ id: TAB_ID,
1705
+ kind: TAB_KIND,
1706
+ title: () => t('title'),
1707
+ guide: [{
1708
+ id: TAB_ID,
1709
+ order: 30,
1710
+ title: () => t('guideTitle'),
1711
+ description: () => t('guideDescription'),
1712
+ }],
1713
+ keepMounted: true,
1714
+ }))
1715
+ // The pane body (owner props come from the framework).
1716
+ register(() => ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({
1717
+ name: 'sidebar.right.pane.tab',
1718
+ key: TAB_ID,
1719
+ locale: LOCALE_NS,
1720
+ inject: (sessionId) => ({
1721
+ sessionId,
1722
+ ctx,
1723
+ rpc: ctx.get('connection')?.rpc ?? ctx.connection?.rpc,
1724
+ liteForm: lite,
1725
+ }),
1726
+ }, StudioBody)))
1727
+ // The chip title.
1728
+ register(() => ctx.slots.inject('sidebar.right.pane.tab.title', () => ctx.slots.register({
1729
+ name: 'sidebar.right.pane.tab.title',
1730
+ key: TAB_ID,
1731
+ locale: LOCALE_NS,
1732
+ }, StudioTitle)))
1733
+ // The header entry. `conversation.session.header.corner` is a single slot
1734
+ // already claimed by the sidebar's expand button, so ours lives in the
1735
+ // neighbouring list seat, which accepts any number of buttons.
1736
+ register(() => ctx.slots.inject('conversation.session.header.utilities', () => ctx.slots.register({
1737
+ name: 'conversation.session.header.utilities',
1738
+ id: TAB_ID,
1739
+ order: 40,
1740
+ locale: LOCALE_NS,
1741
+ inject: () => ({
1742
+ openStudio: () => {
1743
+ const controller = ctx.get('sidebarRight') ?? ctx.sidebarRight
1744
+ controller?.openTab?.(TAB_KIND)
1745
+ },
1746
+ }),
1747
+ }, CornerButton)))
1748
+ }
1749
+ const sync = () => { release(); mount() }
1750
+ mount()
1751
+ const stop = typeof lite.subscribe === 'function' ? lite.subscribe(sync) : undefined
1752
+ return () => { try { stop?.() } catch {} release() }
1753
+ }, 'dsh-image-lite: sidebar studio'))
1754
+
1755
+ // 5. The settings card (model library + quick config, our entry only).
1756
+ softly('settings card', () => ctx.effect(() => ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({
1757
+ name: 'plugins.bundle.config',
1758
+ key: TAB_ID,
1759
+ locale: LOCALE_NS,
1760
+ inject: () => ({
1761
+ ctx,
1762
+ liteForm: lite,
1763
+ }),
1764
+ }, LiteBundleCard)), 'dsh-image-lite: settings card'))
1765
+
1766
+ // 6. The toolview for image_generate_lite.
1767
+ const rpc = ctx.get('connection')?.rpc ?? ctx.connection?.rpc
1768
+ if (rpc) {
1769
+ softly('toolview', () => ctx.effect(() => ctx.slots.inject('tool.call.toolview', () => ctx.slots.register({
1770
+ name: 'tool.call.toolview',
1771
+ key: TOOL_NAME,
1772
+ locale: LOCALE_NS,
1773
+ inject: (sessionId) => ({
1774
+ sessionId,
1775
+ ctx,
1776
+ rpc,
1777
+ }),
1778
+ }, LiteToolview)), 'dsh-image-lite: toolview'))
1779
+ }
1780
+ }
1781
+
1782
+ exports.apply = apply
1783
+ exports.inject = inject
1784
+ // Pure helpers exposed for the Node-side wiring tests.
1785
+ exports.lib = {
1786
+ emptyActiveValue,
1787
+ activeLooksComplete,
1788
+ providerOptions,
1789
+ modelOptionsFrom,
1790
+ buildActiveFromOption,
1791
+ activeChoiceFor,
1792
+ syncActiveWithProviders,
1793
+ parseModelLines,
1794
+ slugForProvider,
1795
+ draftFromProvider,
1796
+ providerFromDraft,
1797
+ maskSecret,
1798
+ credentialNameFor,
1799
+ looksLikeCredentialName,
1800
+ API_FORMATS,
1801
+ ASPECTS,
1802
+ SUPPORTED_FORMAT,
1803
+ MAX_REFS,
1804
+ }
1805
+ return module.exports
1806
+ },
1807
+ })