@dickpy/dsh-imagegen 1.2.3 → 1.4.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.
Files changed (45) hide show
  1. package/LICENSE +201 -201
  2. package/README.md +203 -181
  3. package/cordis.patch.yml +8 -8
  4. package/docs/images/multi-model-comparison.png +0 -0
  5. package/lib/client.js +2711 -1318
  6. package/lib/client.js.map +1 -1
  7. package/lib/index.js +830 -155
  8. package/package.json +70 -68
  9. package/src/agent-image-tools.ts +418 -316
  10. package/src/client/ImageGenPanel.tsx +1703 -1476
  11. package/src/client/SettingsCard.tsx +936 -648
  12. package/src/client/TemplateLibrary.tsx +336 -336
  13. package/src/client/api.ts +193 -193
  14. package/src/client/channels-form.ts +263 -0
  15. package/src/client/controller.ts +46 -46
  16. package/src/client/conversation-sync.ts +14 -0
  17. package/src/client/css-modules.d.ts +5 -5
  18. package/src/client/helpers.ts +33 -33
  19. package/src/client/image-toolview.module.css +73 -73
  20. package/src/client/image-toolview.tsx +170 -152
  21. package/src/client/index.ts +32 -22
  22. package/src/client/locales.ts +610 -484
  23. package/src/client/mount.tsx +185 -96
  24. package/src/client/panel.module.css +1713 -1445
  25. package/src/client/settings-card.module.css +1023 -536
  26. package/src/client/settings-form.ts +336 -336
  27. package/src/client/settings-scope.ts +298 -250
  28. package/src/client/sidebar-entry.ts +148 -102
  29. package/src/client/templates.module.css +453 -453
  30. package/src/engine.ts +520 -464
  31. package/src/gallery-store.ts +286 -280
  32. package/src/generation-runtime.ts +79 -48
  33. package/src/history-store.ts +250 -238
  34. package/src/image-format.ts +11 -0
  35. package/src/image-models.ts +19 -19
  36. package/src/index.ts +318 -212
  37. package/src/model-catalog.ts +115 -0
  38. package/src/presets.ts +71 -0
  39. package/src/prompt-enhancer.ts +137 -79
  40. package/src/protocol.ts +338 -253
  41. package/src/routes.ts +916 -738
  42. package/src/task-queue.ts +113 -103
  43. package/src/templates/cases.json +10196 -10196
  44. package/src/templates-store.ts +278 -278
  45. package/src/updater.ts +117 -117
@@ -1,1558 +1,1785 @@
1
- /**
2
- * The AI 生图 studio: a three-column layout — left, a card-grouped
3
- * configuration sidebar (mode tabs, prompt with counter, rounded parameter
4
- * selectors, model dropdown + generate button); center, the result canvas;
5
- * right, a persistent generation history column.
6
- *
7
- * Controls ride the system UI primitives (@deepseek-ai/dsh-client-ui-primitives,
8
- * a platform module) so the studio matches the dsh shell look by construction.
9
- */
10
-
11
- import { useEffect, useRef, useState } from 'react'
12
- import { createPortal } from 'react-dom'
1
+ /**
2
+ * The AI 生图 studio: a three-column layout — left, a card-grouped
3
+ * configuration sidebar (mode tabs, prompt with counter, rounded parameter
4
+ * selectors, model dropdown + generate button); center, the result canvas;
5
+ * right, a persistent generation history column.
6
+ *
7
+ * Controls ride the system UI primitives (@deepseek-ai/dsh-client-ui-primitives,
8
+ * a platform module) so the studio matches the dsh shell look by construction.
9
+ */
10
+
11
+ import { useEffect, useRef, useState } from 'react'
12
+ import { createPortal } from 'react-dom'
13
13
  import { Button, Pill } from '@deepseek-ai/dsh-client-ui-primitives'
14
+ import type { ISessions, SessionId } from '@deepseek-ai/dsh-client-runtime/client'
15
+ import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment'
14
16
  import type { ImageGenApi } from './api.ts'
15
17
  import { errorMessage, tt } from './helpers.ts'
16
18
  import { TemplateLibrary } from './TemplateLibrary.tsx'
17
19
  import type { GeneratedImage, GenerateMode, GenerateRequest, GenerationTask, HistoryEntry, HistoryImageRef, UpdateInfo } from '../protocol.ts'
20
+ import { AGENT_IMAGE_API } from '../protocol.ts'
18
21
  import type { ImageGenConfig, ImageGenScope } from './settings-scope.ts'
19
- import { DEFAULT_IMAGE_MODELS, normalizeImageModels } from '../image-models.ts'
20
- import css from './panel.module.css'
21
-
22
- /** Size options, presented as aspect ratios (auto = let the model decide).
23
- * The host maps each ratio onto the model's own vocabulary: aspect_ratio for
24
- * Grok Imagine, the closest pixel size for OpenAI-compatible endpoints. */
25
- const SIZES = ['auto', '1:1', '3:4', '4:3', '9:16', '2:3', '3:2', '16:9', '21:9'] as const
26
-
27
- /** Size option keys in the locale dictionary. */
28
- const SIZE_KEYS: Record<string, 'size.auto' | 'size.square' | 'size.portrait34' | 'size.landscape43' | 'size.portrait916' | 'size.portrait23' | 'size.landscape32' | 'size.wide169' | 'size.ultrawide21'> = {
29
- auto: 'size.auto',
30
- '1:1': 'size.square',
31
- '3:4': 'size.portrait34',
32
- '4:3': 'size.landscape43',
33
- '9:16': 'size.portrait916',
34
- '2:3': 'size.portrait23',
35
- '3:2': 'size.landscape32',
36
- '16:9': 'size.wide169',
37
- '21:9': 'size.ultrawide21',
38
- }
39
-
40
- /** Quality options, shown as output-resolution tiers (auto = let the model
41
- * decide). The host maps them: resolution for Grok, quality level for
42
- * OpenAI-compatible endpoints (1k→low, 2k→medium, 4k→high). */
43
- const QUALITIES = ['auto', '1k', '2k', '4k'] as const
44
-
45
- /** Detail options ('' = omit the passthrough). */
46
- const DETAILS = ['', 'standard', 'high'] as const
47
-
48
- const REF_IMAGE_MAX_BYTES = 10 * 1024 * 1024
49
- const PREVIEW_SCALE_MIN = 0.5
50
- const PREVIEW_SCALE_MAX = 3
51
- const PREVIEW_SCALE_STEP = 0.25
52
-
53
- /** Legacy pixel sizes saved by older versions, mapped onto the current
54
- * aspect-ratio vocabulary so restoring old history entries still works. */
55
- const LEGACY_SIZE_TO_RATIO: Record<string, string> = {
56
- '512x512': '1:1',
57
- '1024x1024': '1:1',
58
- '1536x1024': '3:2',
59
- '1024x1536': '2:3',
60
- '1792x1024': '16:9',
61
- '1024x1792': '9:16',
62
- }
63
-
64
- /** Legacy quality levels saved by older versions, mapped onto resolution. */
65
- const LEGACY_QUALITY_TO_RES: Record<string, string> = {
66
- low: '1k',
67
- medium: '2k',
68
- high: '4k',
69
- }
70
-
71
- /** Normalize a saved size value into a current dropdown option. */
72
- function normalizeSize(value: string): string {
73
- if ((SIZES as readonly string[]).includes(value)) return value
74
- return LEGACY_SIZE_TO_RATIO[value] ?? 'auto'
75
- }
76
-
77
- /** Normalize a saved quality value into a current dropdown option. */
78
- function normalizeQuality(value: string): string {
79
- if ((QUALITIES as readonly string[]).includes(value)) return value
80
- return LEGACY_QUALITY_TO_RES[value] ?? 'auto'
81
- }
82
-
83
- function clampPreviewScale(scale: number): number {
84
- return Math.min(PREVIEW_SCALE_MAX, Math.max(PREVIEW_SCALE_MIN, scale))
22
+ import { imageModelOptions } from './settings-scope.ts'
23
+ import { normalizeImageModels } from '../image-models.ts'
24
+ import { describeModel } from '../model-catalog.ts'
25
+ import { CHAT_IMAGE_EVENT, type ChatImageEventDetail, type ConversationService } from './conversation-sync.ts'
26
+ import css from './panel.module.css'
27
+
28
+ /** Size options, presented as aspect ratios (auto = let the model decide).
29
+ * The host maps each ratio onto the model's own vocabulary: aspect_ratio for
30
+ * Grok Imagine, the closest pixel size for OpenAI-compatible endpoints. */
31
+ const SIZES = ['auto', '1:1', '3:4', '4:3', '9:16', '2:3', '3:2', '16:9', '21:9'] as const
32
+
33
+ /** Size option keys in the locale dictionary. */
34
+ const SIZE_KEYS: Record<string, 'size.auto' | 'size.square' | 'size.portrait34' | 'size.landscape43' | 'size.portrait916' | 'size.portrait23' | 'size.landscape32' | 'size.wide169' | 'size.ultrawide21'> = {
35
+ auto: 'size.auto',
36
+ '1:1': 'size.square',
37
+ '3:4': 'size.portrait34',
38
+ '4:3': 'size.landscape43',
39
+ '9:16': 'size.portrait916',
40
+ '2:3': 'size.portrait23',
41
+ '3:2': 'size.landscape32',
42
+ '16:9': 'size.wide169',
43
+ '21:9': 'size.ultrawide21',
44
+ }
45
+
46
+ /** Quality options, shown as output-resolution tiers (auto = let the model
47
+ * decide). The host maps them: resolution for Grok, quality level for
48
+ * OpenAI-compatible endpoints (1k→low, 2k→medium, 4k→high). */
49
+ const QUALITIES = ['auto', '1k', '2k', '4k'] as const
50
+
51
+ /** Detail options ('' = omit the passthrough). */
52
+ const DETAILS = ['', 'standard', 'high'] as const
53
+
54
+ const REF_IMAGE_MAX_BYTES = 10 * 1024 * 1024
55
+ const PREVIEW_SCALE_MIN = 0.5
56
+ const PREVIEW_SCALE_MAX = 3
57
+ const PREVIEW_SCALE_STEP = 0.25
58
+
59
+ /** Legacy pixel sizes saved by older versions, mapped onto the current
60
+ * aspect-ratio vocabulary so restoring old history entries still works. */
61
+ const LEGACY_SIZE_TO_RATIO: Record<string, string> = {
62
+ '512x512': '1:1',
63
+ '1024x1024': '1:1',
64
+ '1536x1024': '3:2',
65
+ '1024x1536': '2:3',
66
+ '1792x1024': '16:9',
67
+ '1024x1792': '9:16',
68
+ }
69
+
70
+ /** Legacy quality levels saved by older versions, mapped onto resolution. */
71
+ const LEGACY_QUALITY_TO_RES: Record<string, string> = {
72
+ low: '1k',
73
+ medium: '2k',
74
+ high: '4k',
75
+ }
76
+
77
+ /** Normalize a saved size value into a current dropdown option. */
78
+ function normalizeSize(value: string): string {
79
+ if ((SIZES as readonly string[]).includes(value)) return value
80
+ return LEGACY_SIZE_TO_RATIO[value] ?? 'auto'
81
+ }
82
+
83
+ /** Normalize a saved quality value into a current dropdown option. */
84
+ function normalizeQuality(value: string): string {
85
+ if ((QUALITIES as readonly string[]).includes(value)) return value
86
+ return LEGACY_QUALITY_TO_RES[value] ?? 'auto'
87
+ }
88
+
89
+ function clampPreviewScale(scale: number): number {
90
+ return Math.min(PREVIEW_SCALE_MAX, Math.max(PREVIEW_SCALE_MIN, scale))
91
+ }
92
+
93
+ /** Read the current config from the settings scope snapshot. */
94
+ function useConfig(scope: ImageGenScope): ImageGenConfig | undefined {
95
+ const [value, setValue] = useState(scope.getSnapshot().value)
96
+ useEffect(() => scope.subscribe(() => { setValue(scope.getSnapshot().value) }), [scope])
97
+ return value
98
+ }
99
+
100
+ /** Track one redacted secret field without exposing its value to the panel. */
101
+ function useSecretSet(scope: ImageGenScope, field: string): boolean {
102
+ const [isSet, setIsSet] = useState(scope.getSecretSetSnapshot(field))
103
+ useEffect(() => scope.subscribeSecretSets(() => { setIsSet(scope.getSecretSetSnapshot(field)) }), [field, scope])
104
+ return isSet
105
+ }
106
+
107
+ /** Tick a seconds counter while `running`. */
108
+ function useElapsed(running: boolean, startedAt: number | null): number {
109
+ const [elapsed, setElapsed] = useState(0)
110
+ useEffect(() => {
111
+ if (!running || startedAt === null) {
112
+ setElapsed(0)
113
+ return
114
+ }
115
+ const update = (): void => {
116
+ setElapsed(Math.max(1, Math.round((Date.now() - startedAt) / 1000)))
117
+ }
118
+ update()
119
+ const timer = window.setInterval(update, 1000)
120
+ return () => window.clearInterval(timer)
121
+ }, [running, startedAt])
122
+ return elapsed
123
+ }
124
+
125
+ /** Data URL for a generated image. */
126
+ function srcOf(image: GeneratedImage): string {
127
+ return `data:${image.mime};base64,${image.b64}`
85
128
  }
86
129
 
87
- /** Read the current config from the settings scope snapshot. */
88
- function useConfig(scope: ImageGenScope): ImageGenConfig | undefined {
89
- const [value, setValue] = useState(scope.getSnapshot().value)
90
- useEffect(() => scope.subscribe(() => { setValue(scope.getSnapshot().value) }), [scope])
91
- return value
130
+ /** Decode one durable conversation attachment into the panel's image shape. */
131
+ async function attachmentToGenerated(ref: ImageAttachmentRef): Promise<GeneratedImage> {
132
+ const query = new URLSearchParams({
133
+ attachment_id: String(ref.attachmentId),
134
+ media_type: ref.mediaType,
135
+ bytes: String(ref.bytes),
136
+ width: String(ref.width),
137
+ height: String(ref.height),
138
+ })
139
+ const response = await fetch(`${AGENT_IMAGE_API}?${query.toString()}`)
140
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
141
+ const blob = await response.blob()
142
+ const dataUrl = await new Promise<string>((resolve, reject) => {
143
+ const reader = new FileReader()
144
+ reader.onload = () => resolve(typeof reader.result === 'string' ? reader.result : '')
145
+ reader.onerror = () => reject(new Error('image read failed'))
146
+ reader.readAsDataURL(blob)
147
+ })
148
+ const comma = dataUrl.indexOf(',')
149
+ if (comma < 0) throw new Error('image decode failed')
150
+ return { b64: dataUrl.slice(comma + 1), mime: ref.mediaType }
92
151
  }
93
152
 
94
- /** Track one redacted secret field without exposing its value to the panel. */
95
- function useSecretSet(scope: ImageGenScope, field: string): boolean {
96
- const [isSet, setIsSet] = useState(scope.getSecretSetSnapshot(field))
97
- useEffect(() => scope.subscribeSecretSets(() => { setIsSet(scope.getSecretSetSnapshot(field)) }), [field, scope])
98
- return isSet
153
+ /** Convert a generated image into the browser-owned draft format. */
154
+ function generatedImageToFile(image: GeneratedImage, index: number): File {
155
+ const binary = atob(image.b64)
156
+ const bytes = new Uint8Array(binary.length)
157
+ for (let offset = 0; offset < binary.length; offset += 1) bytes[offset] = binary.charCodeAt(offset)
158
+ return new File([bytes], `dsh-image-${index + 1}.${extensionOf(image.mime)}`, { type: image.mime })
99
159
  }
100
160
 
101
- /** Tick a seconds counter while `running`. */
102
- function useElapsed(running: boolean, startedAt: number | null): number {
103
- const [elapsed, setElapsed] = useState(0)
161
+ /** Follow the native session selection while the image panel stays mounted. */
162
+ function useCurrentSessionId(sessions: ISessions | undefined): SessionId | undefined {
163
+ const [sessionId, setSessionId] = useState<SessionId | undefined>(() => sessions?.list.getSnapshot().current)
104
164
  useEffect(() => {
105
- if (!running || startedAt === null) return
106
- const timer = window.setInterval(() => {
107
- setElapsed(Math.max(1, Math.round((Date.now() - startedAt) / 1000)))
108
- }, 1000)
109
- return () => window.clearInterval(timer)
110
- }, [running, startedAt])
111
- return elapsed
112
- }
113
-
114
- /** Data URL for a generated image. */
115
- function srcOf(image: GeneratedImage): string {
116
- return `data:${image.mime};base64,${image.b64}`
117
- }
118
-
119
- /** Fetch persisted history image refs and decode them back to in-memory
120
- * GeneratedImage[] (base64), so the canvas/preview can reuse the same
121
- * rendering path as a fresh generation. */
122
- async function historyImagesToGenerated(refs: HistoryImageRef[]): Promise<GeneratedImage[]> {
123
- return Promise.all(refs.map(async ref => {
124
- const response = await fetch(ref.url)
125
- if (!response.ok) throw new Error(`HTTP ${response.status}`)
126
- const blob = await response.blob()
127
- const dataUrl = await new Promise<string>((resolve, reject) => {
128
- const reader = new FileReader()
129
- reader.onload = () => resolve(typeof reader.result === 'string' ? reader.result : '')
130
- reader.onerror = () => reject(new Error('image read failed'))
131
- reader.readAsDataURL(blob)
132
- })
133
- const comma = dataUrl.indexOf(',')
134
- return {
135
- b64: comma >= 0 ? dataUrl.slice(comma + 1) : '',
136
- mime: ref.mime,
137
- ...ref.revisedPrompt === undefined ? {} : { revisedPrompt: ref.revisedPrompt },
165
+ if (sessions === undefined) {
166
+ setSessionId(undefined)
167
+ return
138
168
  }
139
- }))
169
+ const sync = (): void => { setSessionId(sessions.list.getSnapshot().current) }
170
+ sync()
171
+ return sessions.list.subscribe(sync)
172
+ }, [sessions])
173
+ return sessionId
140
174
  }
141
175
 
142
- /** Compact, locale-independent timestamp for history entries. */
143
- function formatTime(timestamp: number): string {
144
- const d = new Date(timestamp)
145
- const pad = (n: number): string => String(n).padStart(2, '0')
146
- return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
176
+ /** Find the host mounted in the shell's left navigation region. */
177
+ function useSidebarHistoryHost(): HTMLDivElement | null {
178
+ const [host, setHost] = useState<HTMLDivElement | null>(() => (
179
+ document.querySelector<HTMLDivElement>('[data-dsh-imagegen-history-host]')
180
+ ))
181
+ useEffect(() => {
182
+ const sync = (): void => {
183
+ setHost(document.querySelector<HTMLDivElement>('[data-dsh-imagegen-history-host]'))
184
+ }
185
+ sync()
186
+ const observer = new MutationObserver(sync)
187
+ observer.observe(document.body, { childList: true, subtree: true })
188
+ return () => observer.disconnect()
189
+ }, [])
190
+ return host
147
191
  }
148
-
149
- /** Studio tabs: the two generation modes plus the gallery view. */
150
- type PanelTab = GenerateMode | 'gallery'
151
-
152
- type GalleryFilter = string
153
- type ComparisonSession = { taskIds: string[]; prompt: string }
154
-
155
- /** Render the studio. */
192
+
193
+ /** Fetch persisted history image refs and decode them back to in-memory
194
+ * GeneratedImage[] (base64), so the canvas/preview can reuse the same
195
+ * rendering path as a fresh generation. */
196
+ async function historyImagesToGenerated(refs: HistoryImageRef[]): Promise<GeneratedImage[]> {
197
+ return Promise.all(refs.map(async ref => {
198
+ const response = await fetch(ref.url)
199
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
200
+ const blob = await response.blob()
201
+ const dataUrl = await new Promise<string>((resolve, reject) => {
202
+ const reader = new FileReader()
203
+ reader.onload = () => resolve(typeof reader.result === 'string' ? reader.result : '')
204
+ reader.onerror = () => reject(new Error('image read failed'))
205
+ reader.readAsDataURL(blob)
206
+ })
207
+ const comma = dataUrl.indexOf(',')
208
+ return {
209
+ b64: comma >= 0 ? dataUrl.slice(comma + 1) : '',
210
+ mime: ref.mime,
211
+ ...ref.revisedPrompt === undefined ? {} : { revisedPrompt: ref.revisedPrompt },
212
+ }
213
+ }))
214
+ }
215
+
216
+ /** Compact, locale-independent timestamp for history entries. */
217
+ function formatTime(timestamp: number): string {
218
+ const d = new Date(timestamp)
219
+ const pad = (n: number): string => String(n).padStart(2, '0')
220
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
221
+ }
222
+
223
+ /** Studio tabs: the two generation modes plus the gallery view. */
224
+ type PanelTab = GenerateMode | 'gallery'
225
+
226
+ type GalleryFilter = string
227
+ type ComparisonSession = { taskIds: string[]; prompt: string; comparisonId: string }
228
+ type HistoryGroup = { key: string; entries: HistoryEntry[]; models: string[] }
229
+
230
+ function modelsOfHistoryEntry(entry: HistoryEntry): string[] {
231
+ return entry.comparisonModels?.length !== undefined && entry.comparisonModels.length > 1
232
+ ? entry.comparisonModels
233
+ : [entry.model]
234
+ }
235
+
236
+ /** Collapse the per-model history rows that belong to one comparison run. */
237
+ function groupHistoryEntries(entries: HistoryEntry[]): HistoryGroup[] {
238
+ const groups = new Map<string, HistoryGroup>()
239
+ for (const entry of entries) {
240
+ const key = entry.comparisonId ?? entry.id
241
+ const existing = groups.get(key)
242
+ if (existing === undefined) {
243
+ groups.set(key, { key, entries: [entry], models: modelsOfHistoryEntry(entry) })
244
+ } else {
245
+ existing.entries.push(entry)
246
+ existing.models = [...new Set([...existing.models, ...modelsOfHistoryEntry(entry)])]
247
+ }
248
+ }
249
+ return [...groups.values()]
250
+ }
251
+
252
+ function newComparisonId(): string {
253
+ const cryptoApi = globalThis.crypto
254
+ if (typeof cryptoApi?.randomUUID === 'function') return cryptoApi.randomUUID()
255
+ return `comparison-${Date.now()}-${Math.random().toString(36).slice(2)}`
256
+ }
257
+
258
+ /** Render the studio. */
156
259
  export function ImageGenPanel(props: {
157
260
  api: ImageGenApi
158
261
  scope: ImageGenScope
262
+ sessions?: ISessions
263
+ conversation?: ConversationService
159
264
  }) {
160
- const { api, scope } = props
161
- const config = useConfig(scope)
162
- const enabled = config?.enabled ?? true
163
- const apiUrl = config?.apiUrl ?? ''
164
- const configured = apiUrl.trim() !== ''
165
- const apiKeySet = useSecretSet(scope, 'apiKey')
166
- const promptKeySet = useSecretSet(scope, 'promptApiKey')
167
- const connected = enabled && configured && apiKeySet
168
- const imageModels = normalizeImageModels(config?.imageModels)
169
-
170
- const [tab, setTab] = useState<PanelTab>('text')
171
- const [prompt, setPrompt] = useState('')
172
- const [size, setSize] = useState<string>('auto')
173
- const [quality, setQuality] = useState<string>('auto')
174
- const [count, setCount] = useState(1)
175
- const [detail, setDetail] = useState('')
176
- const [model, setModel] = useState<string>(DEFAULT_IMAGE_MODELS[0])
177
- const [compareEnabled, setCompareEnabled] = useState(false)
178
- const [compareModels, setCompareModels] = useState<string[]>([...DEFAULT_IMAGE_MODELS])
179
- const [modelOpen, setModelOpen] = useState(false)
180
- const [refImage, setRefImage] = useState<{ dataUrl: string; name: string } | null>(null)
265
+ const { api, scope, sessions, conversation } = props
266
+ const config = useConfig(scope)
267
+ const enabled = config?.enabled ?? true
268
+ // Channel-aware model options: the panel lists every configured alias
269
+ // (default channel first); legacy flat fields remain the upgrade fallback.
270
+ const modelOptions = imageModelOptions(config)
271
+ const hasChannels = (config?.channels ?? []).length > 0
272
+ // With channels configured, the model list is exactly the configured aliases
273
+ // (possibly empty — never fall back to the hardcoded legacy defaults).
274
+ const imageModels = hasChannels ? modelOptions.models : normalizeImageModels(config?.imageModels)
275
+ const defaultChannelId = modelOptions.defaultChannelId
276
+ const apiUrl = defaultChannelId !== undefined && (config?.channels ?? []).length > 0
277
+ ? (config!.channels!.find(channel => channel.id === defaultChannelId)?.apiUrl ?? '')
278
+ : (config?.apiUrl ?? '')
279
+ const configured = apiUrl.trim() !== ''
280
+ const legacyKeySet = useSecretSet(scope, 'apiKey')
281
+ const promptKeySet = useSecretSet(scope, 'promptApiKey')
282
+ const channelKeySet = (config?.channels ?? []).some(channel => scope.getSecretSetSnapshot(`channelSecrets.${channel.id}`))
283
+ const apiKeySet = (config?.channels ?? []).length > 0 ? channelKeySet : legacyKeySet
284
+ const connected = enabled && configured && apiKeySet
285
+
286
+ const [tab, setTab] = useState<PanelTab>('text')
287
+ const [prompt, setPrompt] = useState('')
288
+ const [size, setSize] = useState<string>('auto')
289
+ const [quality, setQuality] = useState<string>('auto')
290
+ const [count, setCount] = useState(1)
291
+ const [detail, setDetail] = useState('')
292
+ const [model, setModel] = useState<string>('')
293
+ const [compareEnabled, setCompareEnabled] = useState(false)
294
+ const [compareModels, setCompareModels] = useState<string[]>([])
295
+ const [modelOpen, setModelOpen] = useState(false)
296
+ const [refImage, setRefImage] = useState<{ dataUrl: string; name: string } | null>(null)
181
297
  const [images, setImages] = useState<GeneratedImage[]>([])
182
- const [error, setError] = useState<string | null>(null)
183
- const [generating, setGenerating] = useState(false)
184
- const [enhancing, setEnhancing] = useState(false)
185
- const [configGuide, setConfigGuide] = useState<'generation' | 'enhancement' | 'disabled' | null>(null)
186
- const [startedAt, setStartedAt] = useState<number | null>(null)
187
- const [history, setHistory] = useState<HistoryEntry[]>([])
188
- const [viewingHistoryId, setViewingHistoryId] = useState<string | null>(null)
189
- const [gallery, setGallery] = useState<HistoryEntry[]>([])
190
- const [galleryViewingId, setGalleryViewingId] = useState<string | null>(null)
191
- const [galleryAdding, setGalleryAdding] = useState(false)
192
- const [galleryMessage, setGalleryMessage] = useState<string | null>(null)
193
- const [galleryFilter, setGalleryFilter] = useState<GalleryFilter>('all')
194
- const [galleryRatio, setGalleryRatio] = useState('all')
195
- const [galleryTagFilter, setGalleryTagFilter] = useState<string | null>(null)
196
- const [galleryView, setGalleryView] = useState<'masonry' | 'grid'>('masonry')
197
- const [gallerySort, setGallerySort] = useState<'newest' | 'oldest'>('newest')
198
- const [galleryQuery, setGalleryQuery] = useState('')
199
- const [galleryTagInput, setGalleryTagInput] = useState('')
200
- const [editingGalleryTagsId, setEditingGalleryTagsId] = useState<string | null>(null)
201
- const [galleryTagEditInput, setGalleryTagEditInput] = useState('')
202
- const [selectedGalleryIds, setSelectedGalleryIds] = useState<Set<string>>(new Set())
203
- const [gallerySelecting, setGallerySelecting] = useState(false)
204
- const [historyQuery, setHistoryQuery] = useState('')
205
- const [historyModelFilter, setHistoryModelFilter] = useState('all')
206
- const [historyRatioFilter, setHistoryRatioFilter] = useState('all')
207
- const [preview, setPreview] = useState<{ images: GeneratedImage[]; index: number } | null>(null)
208
- const [previewScale, setPreviewScale] = useState(1)
209
- const [promptCopied, setPromptCopied] = useState(false)
210
- const [update, setUpdate] = useState<UpdateInfo | null>(null)
211
- const [updating, setUpdating] = useState(false)
212
- const [updateMessage, setUpdateMessage] = useState<string | null>(null)
213
- const [updateResult, setUpdateResult] = useState<'success' | 'failed' | null>(null)
214
- const [libraryOpen, setLibraryOpen] = useState(false)
215
- const [tasks, setTasks] = useState<GenerationTask[]>([])
216
- const [taskTrayOpen, setTaskTrayOpen] = useState(false)
217
- const [comparison, setComparison] = useState<ComparisonSession | null>(null)
298
+ const [addingToConversation, setAddingToConversation] = useState<number | null>(null)
299
+ const [conversationMessage, setConversationMessage] = useState<string | null>(null)
300
+ const [error, setError] = useState<string | null>(null)
301
+ // Submission is brief; actual generation stays visible until the host
302
+ // queue reports that every queued/running task has finished.
303
+ const [submitting, setSubmitting] = useState(false)
304
+ const [enhancing, setEnhancing] = useState(false)
305
+ const [configGuide, setConfigGuide] = useState<'generation' | 'enhancement' | 'disabled' | null>(null)
306
+ const [history, setHistory] = useState<HistoryEntry[]>([])
307
+ const [viewingHistoryId, setViewingHistoryId] = useState<string | null>(null)
308
+ const [gallery, setGallery] = useState<HistoryEntry[]>([])
309
+ const [galleryViewingId, setGalleryViewingId] = useState<string | null>(null)
310
+ const [galleryAdding, setGalleryAdding] = useState(false)
311
+ const [galleryMessage, setGalleryMessage] = useState<string | null>(null)
312
+ const [galleryFilter, setGalleryFilter] = useState<GalleryFilter>('all')
313
+ const [galleryRatio, setGalleryRatio] = useState('all')
314
+ const [galleryTagFilter, setGalleryTagFilter] = useState<string | null>(null)
315
+ const [galleryView, setGalleryView] = useState<'masonry' | 'grid'>('masonry')
316
+ const [gallerySort, setGallerySort] = useState<'newest' | 'oldest'>('newest')
317
+ const [galleryQuery, setGalleryQuery] = useState('')
318
+ const [galleryTagInput, setGalleryTagInput] = useState('')
319
+ const [editingGalleryTagsId, setEditingGalleryTagsId] = useState<string | null>(null)
320
+ const [galleryTagEditInput, setGalleryTagEditInput] = useState('')
321
+ const [selectedGalleryIds, setSelectedGalleryIds] = useState<Set<string>>(new Set())
322
+ const [gallerySelecting, setGallerySelecting] = useState(false)
323
+ const [historyQuery, setHistoryQuery] = useState('')
324
+ const [historyModelFilter, setHistoryModelFilter] = useState('all')
325
+ const [historyRatioFilter, setHistoryRatioFilter] = useState('all')
326
+ const [preview, setPreview] = useState<{ images: GeneratedImage[]; index: number } | null>(null)
327
+ const [previewScale, setPreviewScale] = useState(1)
328
+ const [promptCopied, setPromptCopied] = useState(false)
329
+ const [update, setUpdate] = useState<UpdateInfo | null>(null)
330
+ const [updating, setUpdating] = useState(false)
331
+ const [updateMessage, setUpdateMessage] = useState<string | null>(null)
332
+ const [updateResult, setUpdateResult] = useState<'success' | 'failed' | null>(null)
333
+ const [libraryOpen, setLibraryOpen] = useState(false)
334
+ const [tasks, setTasks] = useState<GenerationTask[]>([])
335
+ const tasksRef = useRef<GenerationTask[]>([])
336
+ const [taskTrayOpen, setTaskTrayOpen] = useState(false)
337
+ const [comparison, setComparison] = useState<ComparisonSession | null>(null)
218
338
  const [comparisonFullscreen, setComparisonFullscreen] = useState(false)
219
- const fileInput = useRef<HTMLInputElement>(null)
220
- const previewStage = useRef<HTMLDivElement>(null)
221
- const elapsed = useElapsed(generating, startedAt)
222
-
223
- // A saved settings change is authoritative. Keep the active selection and
224
- // comparison choices in that allow-list without disturbing valid choices.
225
- const imageModelKey = imageModels.join('\u0000')
226
- useEffect(() => {
227
- setModel(previous => imageModels.includes(previous) ? previous : imageModels[0])
228
- setCompareModels(previous => {
229
- const retained = previous.filter(candidate => imageModels.includes(candidate))
230
- return retained.length > 0 ? retained : [imageModels[0]]
231
- })
232
- }, [imageModelKey])
233
-
234
- const filteredGallery = gallery
235
- .filter(entry => {
236
- if (galleryFilter === 'all') return true
237
- if (galleryFilter === 'text' || galleryFilter === 'edit') return entry.mode === galleryFilter
238
- return entry.model === galleryFilter
239
- })
240
- .filter(entry => galleryRatio === 'all' || normalizeSize(entry.size) === galleryRatio)
241
- .filter(entry => galleryTagFilter === null || (entry.tags ?? []).includes(galleryTagFilter))
242
- .filter(entry => galleryQuery.trim() === '' || `${entry.prompt} ${entry.model} ${(entry.tags ?? []).join(' ')}`.toLocaleLowerCase().includes(galleryQuery.trim().toLocaleLowerCase()))
243
- .slice()
244
- .sort((a, b) => gallerySort === 'newest' ? b.createdAt - a.createdAt : a.createdAt - b.createdAt)
245
-
246
- const galleryTagOptions = [...new Set(gallery.flatMap(entry => entry.tags ?? []))].sort((a, b) => a.localeCompare(b))
247
- const galleryModels = [...new Set([...imageModels, ...gallery.map(entry => entry.model)])]
248
-
249
- const filteredHistory = history.filter(entry => {
250
- const query = historyQuery.trim().toLocaleLowerCase()
251
- return (query === '' || `${entry.prompt} ${entry.model}`.toLocaleLowerCase().includes(query))
252
- && (historyModelFilter === 'all' || entry.model === historyModelFilter)
253
- && (historyRatioFilter === 'all' || normalizeSize(entry.size) === historyRatioFilter)
254
- })
255
-
256
- // Load the host-persisted history and gallery once on mount (they live in
257
- // ~/.dsh on the DSH host, so every browser/device sees the same lists).
339
+ const currentSessionId = useCurrentSessionId(sessions)
340
+ const sidebarHistoryHost = useSidebarHistoryHost()
341
+ const modeModels = tab === 'edit'
342
+ ? imageModels.filter(candidate => describeModel(candidate).supportsEdit)
343
+ : imageModels
344
+ const fileInput = useRef<HTMLInputElement>(null)
345
+ const previewStage = useRef<HTMLDivElement>(null)
346
+ const activeTasks = tasks.filter(task => task.status === 'queued' || task.status === 'running')
347
+ const activeTask = activeTasks.find(task => task.status === 'running') ?? activeTasks[0]
348
+ const generating = submitting || activeTasks.length > 0
349
+ const generationStartedAt = activeTask?.startedAt ?? activeTask?.createdAt ?? null
350
+ const elapsed = useElapsed(generating, generationStartedAt)
351
+
352
+ // A saved settings change is authoritative. Keep the active selection and
353
+ // comparison choices in that allow-list without disturbing valid choices.
354
+ const imageModelKey = modeModels.join('\u0000')
258
355
  useEffect(() => {
259
- let disposed = false
260
- api.historyList()
261
- .then(entries => { if (!disposed) setHistory(entries) })
262
- .catch(() => { /* history unavailable leave the list empty */ })
263
- api.galleryList()
264
- .then(entries => { if (!disposed) setGallery(entries) })
265
- .catch(() => { /* gallery unavailable — leave the list empty */ })
266
- return () => { disposed = true }
356
+ setModel(previous => modeModels.includes(previous) ? previous : modeModels[0] ?? '')
357
+ setCompareModels(previous => {
358
+ const retained = previous.filter(candidate => modeModels.includes(candidate))
359
+ return retained.length > 0 ? retained : modeModels[0] === undefined ? [] : [modeModels[0]]
360
+ })
361
+ }, [imageModelKey])
362
+
363
+ const filteredGallery = gallery
364
+ .filter(entry => {
365
+ if (galleryFilter === 'all') return true
366
+ if (galleryFilter === 'text' || galleryFilter === 'edit') return entry.mode === galleryFilter
367
+ return entry.model === galleryFilter
368
+ })
369
+ .filter(entry => galleryRatio === 'all' || normalizeSize(entry.size) === galleryRatio)
370
+ .filter(entry => galleryTagFilter === null || (entry.tags ?? []).includes(galleryTagFilter))
371
+ .filter(entry => galleryQuery.trim() === '' || `${entry.prompt} ${entry.model} ${(entry.tags ?? []).join(' ')}`.toLocaleLowerCase().includes(galleryQuery.trim().toLocaleLowerCase()))
372
+ .slice()
373
+ .sort((a, b) => gallerySort === 'newest' ? b.createdAt - a.createdAt : a.createdAt - b.createdAt)
374
+
375
+ const galleryTagOptions = [...new Set(gallery.flatMap(entry => entry.tags ?? []))].sort((a, b) => a.localeCompare(b))
376
+ const galleryModels = [...new Set([...imageModels, ...gallery.map(entry => entry.model)])]
377
+
378
+ const filteredHistory = groupHistoryEntries(history).filter(group => group.entries.some(entry => {
379
+ const query = historyQuery.trim().toLocaleLowerCase()
380
+ const models = modelsOfHistoryEntry(entry)
381
+ return (query === '' || `${entry.prompt} ${models.join(' ')}`.toLocaleLowerCase().includes(query))
382
+ && (historyModelFilter === 'all' || models.includes(historyModelFilter))
383
+ && (historyRatioFilter === 'all' || normalizeSize(entry.size) === historyRatioFilter)
384
+ }))
385
+
386
+ // Load the host-persisted history and gallery once on mount (they live in
387
+ // ~/.dsh on the DSH host, so every browser/device sees the same lists).
388
+ useEffect(() => {
389
+ let disposed = false
390
+ api.historyList()
391
+ .then(entries => { if (!disposed) setHistory(entries) })
392
+ .catch(() => { /* history unavailable — leave the list empty */ })
393
+ api.galleryList()
394
+ .then(entries => { if (!disposed) setGallery(entries) })
395
+ .catch(() => { /* gallery unavailable — leave the list empty */ })
396
+ return () => { disposed = true }
267
397
  }, [api])
268
398
 
399
+ // Chat toolviews publish durable refs after they finish loading. Decode the
400
+ // refs through the same host-authorized route and make them the current
401
+ // canvas result for the selected session.
269
402
  useEffect(() => {
270
- let disposed = false
271
- const refresh = (): void => {
272
- void api.taskList().then(next => {
273
- if (disposed) return
274
- setTasks(previous => {
275
- const completed = next.find(task => task.status === 'completed'
276
- && !previous.some(old => old.id === task.id && old.status === 'completed')
277
- && !comparison?.taskIds.includes(task.id))
278
- if (completed?.result !== undefined) {
279
- setImages(completed.result.images)
280
- if (completed.result.history !== undefined) setHistory(completed.result.history)
281
- setError(completed.result.historyError ?? null)
282
- }
283
- return next
403
+ const onChatImages = (event: Event): void => {
404
+ const detail = (event as CustomEvent<ChatImageEventDetail>).detail
405
+ if (detail === undefined || currentSessionId === undefined || detail.sessionId !== currentSessionId) return
406
+ void Promise.all(detail.refs.map(attachmentToGenerated))
407
+ .then(next => {
408
+ setTab('text')
409
+ setImages(next)
410
+ setComparison(null)
411
+ setViewingHistoryId(null)
412
+ setGalleryViewingId(null)
413
+ setError(null)
284
414
  })
285
- }).catch(() => {})
286
- }
287
- refresh()
288
- const timer = window.setInterval(refresh, 1500)
289
- return () => { disposed = true; window.clearInterval(timer) }
290
- }, [api, comparison])
291
-
292
- // Close the model dropdown when clicking anywhere outside it.
293
- const modelMenuRef = useRef<HTMLDivElement>(null)
294
- useEffect(() => {
295
- if (!modelOpen) return
296
- const onPointer = (event: MouseEvent | FocusEvent): void => {
297
- const target = event.target
298
- if (target instanceof Node && modelMenuRef.current?.contains(target)) return
299
- setModelOpen(false)
300
- }
301
- document.addEventListener('mousedown', onPointer)
302
- document.addEventListener('focusin', onPointer)
303
- return () => {
304
- document.removeEventListener('mousedown', onPointer)
305
- document.removeEventListener('focusin', onPointer)
306
- }
307
- }, [modelOpen])
308
-
309
- // Release checks are host-mediated and intentionally best-effort: a GitHub
310
- // outage must never make the image-generation studio unavailable.
311
- useEffect(() => {
312
- let disposed = false
313
- api.updateCheck()
314
- .then(info => {
315
- if (!disposed && info.updateAvailable) setUpdate(info)
316
- })
317
- .catch(() => { /* update discovery is optional */ })
318
- return () => { disposed = true }
319
- }, [api])
320
-
321
- const applyUpdate = async (): Promise<void> => {
322
- if (update === null || updating) return
323
- setUpdating(true)
324
- setUpdateMessage(null)
325
- setUpdateResult(null)
326
- try {
327
- const result = await api.updateApply(update.latestVersion)
328
- setUpdateMessage(tt('update.success', { version: result.updatedVersion }))
329
- setUpdateResult('success')
330
- } catch {
331
- setUpdateMessage(tt('update.failed'))
332
- setUpdateResult('failed')
333
- } finally {
334
- setUpdating(false)
335
- }
336
- }
337
-
338
- const openSettingsGuide = (kind: 'generation' | 'enhancement' | 'disabled'): void => {
339
- setConfigGuide(kind)
340
- const openPluginSettings = (): void => {
341
- const pluginButton = Array.from(document.querySelectorAll<HTMLButtonElement>('button')).find(button => /^(插件|Plugins)$/.test(button.textContent?.trim() ?? ''))
342
- pluginButton?.click()
343
- window.setTimeout(() => {
344
- const imageGenButton = Array.from(document.querySelectorAll<HTMLButtonElement>('button')).find(button => /dsh-imagegen/i.test(button.textContent ?? ''))
345
- if (imageGenButton?.getAttribute('aria-expanded') !== 'true') imageGenButton?.click()
346
- }, 0)
347
- }
348
- const settingsButton = Array.from(document.querySelectorAll<HTMLButtonElement>('button')).find(button => /^(设置|Settings)$/.test(button.textContent?.trim() ?? ''))
349
- if (settingsButton?.getAttribute('aria-expanded') !== 'true') settingsButton?.click()
350
- window.setTimeout(openPluginSettings, 0)
351
- }
352
-
353
- const enhanceCurrentPrompt = async (): Promise<void> => {
354
- if (prompt.trim() === '' || enhancing) return
355
- const promptEndpointConfigured = (config?.promptApiUrl ?? '').trim() !== '' || configured
356
- if ((config?.promptModel ?? '').trim() === '' || !promptEndpointConfigured || (!promptKeySet && !apiKeySet)) {
357
- openSettingsGuide('enhancement')
358
- return
415
+ .catch(caught => { setError(errorMessage(caught)) })
359
416
  }
360
- setEnhancing(true)
361
- setError(null)
417
+ document.addEventListener(CHAT_IMAGE_EVENT, onChatImages)
418
+ return () => document.removeEventListener(CHAT_IMAGE_EVENT, onChatImages)
419
+ }, [currentSessionId])
420
+
421
+ useEffect(() => {
422
+ let disposed = false
423
+ const refresh = (): void => {
424
+ void api.taskList().then(next => {
425
+ if (disposed) return
426
+ const newlyCompleted = next.filter(task => task.status === 'completed'
427
+ && task.result !== undefined
428
+ && !tasksRef.current.some(old => old.id === task.id && old.status === 'completed'))
429
+ tasksRef.current = next
430
+ setTasks(previous => {
431
+ const completed = next.find(task => task.status === 'completed'
432
+ && !previous.some(old => old.id === task.id && old.status === 'completed')
433
+ && !comparison?.taskIds.includes(task.id))
434
+ if (completed?.result !== undefined) {
435
+ setImages(completed.result.images)
436
+ if (completed.result.history !== undefined) setHistory(completed.result.history)
437
+ setError(completed.result.historyError ?? null)
438
+ }
439
+ return next
440
+ })
441
+ if (newlyCompleted.length > 0) {
442
+ void api.historyList().then(entries => {
443
+ if (!disposed) setHistory(entries)
444
+ }).catch(() => {})
445
+ }
446
+ }).catch(() => {})
447
+ }
448
+ refresh()
449
+ const timer = window.setInterval(refresh, 1500)
450
+ return () => { disposed = true; window.clearInterval(timer) }
451
+ }, [api, comparison])
452
+
453
+ // Close the model dropdown when clicking anywhere outside it.
454
+ const modelMenuRef = useRef<HTMLDivElement>(null)
455
+ useEffect(() => {
456
+ if (!modelOpen) return
457
+ const onPointer = (event: MouseEvent | FocusEvent): void => {
458
+ const target = event.target
459
+ if (target instanceof Node && modelMenuRef.current?.contains(target)) return
460
+ setModelOpen(false)
461
+ }
462
+ document.addEventListener('mousedown', onPointer)
463
+ document.addEventListener('focusin', onPointer)
464
+ return () => {
465
+ document.removeEventListener('mousedown', onPointer)
466
+ document.removeEventListener('focusin', onPointer)
467
+ }
468
+ }, [modelOpen])
469
+
470
+ // Release checks are host-mediated and intentionally best-effort: a GitHub
471
+ // outage must never make the image-generation studio unavailable.
472
+ useEffect(() => {
473
+ let disposed = false
474
+ api.updateCheck()
475
+ .then(info => {
476
+ if (!disposed && info.updateAvailable) setUpdate(info)
477
+ })
478
+ .catch(() => { /* update discovery is optional */ })
479
+ return () => { disposed = true }
480
+ }, [api])
481
+
482
+ const applyUpdate = async (): Promise<void> => {
483
+ if (update === null || updating) return
484
+ setUpdating(true)
485
+ setUpdateMessage(null)
486
+ setUpdateResult(null)
487
+ try {
488
+ const result = await api.updateApply(update.latestVersion)
489
+ setUpdateMessage(tt('update.success', { version: result.updatedVersion }))
490
+ setUpdateResult('success')
491
+ } catch {
492
+ setUpdateMessage(tt('update.failed'))
493
+ setUpdateResult('failed')
494
+ } finally {
495
+ setUpdating(false)
496
+ }
497
+ }
498
+
499
+ const openSettingsGuide = (kind: 'generation' | 'enhancement' | 'disabled'): void => {
500
+ setConfigGuide(kind)
501
+ const openPluginSettings = (): void => {
502
+ const pluginButton = Array.from(document.querySelectorAll<HTMLButtonElement>('button')).find(button => /^(插件|Plugins)$/.test(button.textContent?.trim() ?? ''))
503
+ pluginButton?.click()
504
+ window.setTimeout(() => {
505
+ const imageGenButton = Array.from(document.querySelectorAll<HTMLButtonElement>('button')).find(button => /dsh-imagegen/i.test(button.textContent ?? ''))
506
+ if (imageGenButton?.getAttribute('aria-expanded') !== 'true') imageGenButton?.click()
507
+ }, 0)
508
+ }
509
+ const settingsButton = Array.from(document.querySelectorAll<HTMLButtonElement>('button')).find(button => /^(设置|Settings)$/.test(button.textContent?.trim() ?? ''))
510
+ if (settingsButton?.getAttribute('aria-expanded') !== 'true') settingsButton?.click()
511
+ window.setTimeout(openPluginSettings, 0)
512
+ }
513
+
514
+ const enhanceCurrentPrompt = async (): Promise<void> => {
515
+ if (prompt.trim() === '' || enhancing) return
516
+ const promptEndpointConfigured = (config?.promptApiUrl ?? '').trim() !== '' || configured
517
+ if ((config?.promptModel ?? '').trim() === '' || !promptEndpointConfigured || (!promptKeySet && !apiKeySet)) {
518
+ openSettingsGuide('enhancement')
519
+ return
520
+ }
521
+ setEnhancing(true)
522
+ setError(null)
523
+ try {
524
+ setPrompt(await api.enhancePrompt(prompt))
525
+ } catch (caught) {
526
+ setError(errorMessage(caught))
527
+ } finally {
528
+ setEnhancing(false)
529
+ }
530
+ }
531
+
532
+ /** Read an uploaded reference image into a data URL. */
533
+ const acceptFile = (file: File | undefined): void => {
534
+ if (file === undefined) return
535
+ if (!file.type.startsWith('image/')) {
536
+ setError(tt('edit.uploadHint'))
537
+ return
538
+ }
539
+ if (file.size > REF_IMAGE_MAX_BYTES) {
540
+ setError(tt('edit.uploadHint'))
541
+ return
542
+ }
543
+ const reader = new FileReader()
544
+ reader.onload = () => {
545
+ if (typeof reader.result === 'string') setRefImage({ dataUrl: reader.result, name: file.name })
546
+ }
547
+ reader.onerror = () => { setError(tt('edit.uploadHint')) }
548
+ reader.readAsDataURL(file)
549
+ }
550
+
551
+ /** Run one generation. */
552
+ const handleGenerate = async (): Promise<void> => {
553
+ if (submitting) return
554
+ if (!enabled) {
555
+ openSettingsGuide('disabled')
556
+ return
557
+ }
558
+ if (!configured || !apiKeySet) {
559
+ openSettingsGuide('generation')
560
+ return
561
+ }
562
+ const promptText = prompt.trim()
563
+ if (promptText === '') {
564
+ setError(tt('prompt.required'))
565
+ return
566
+ }
567
+ if (tab === 'edit' && refImage === null) {
568
+ setError(tt('edit.required'))
569
+ return
570
+ }
571
+ const request: GenerateRequest = {
572
+ mode: tab === 'gallery' ? 'text' : tab,
573
+ model: modeModels.includes(model) ? model : modeModels[0] ?? '',
574
+ prompt: promptText,
575
+ size,
576
+ quality,
577
+ n: count,
578
+ detail,
579
+ ...defaultChannelId !== undefined ? { channelId: defaultChannelId } : {},
580
+ ...tab === 'edit' && refImage !== null ? { image: refImage.dataUrl } : {},
581
+ ...tab === 'edit' && refImage !== null ? { refName: refImage.name } : {},
582
+ }
583
+ setError(null)
584
+ setSubmitting(true)
585
+ try {
586
+ const targetModels = (compareEnabled ? compareModels : [request.model]).filter(candidate => modeModels.includes(candidate))
587
+ if (targetModels.length === 0) {
588
+ setError(tt('compare.selectRequired'))
589
+ return
590
+ }
591
+ const comparisonId = targetModels.length > 1 ? newComparisonId() : undefined
592
+ const comparisonFields = comparisonId === undefined ? {} : { comparisonId, comparisonModels: targetModels }
593
+ const submitted = await Promise.all(targetModels.map(targetModel => api.taskSubmit({ ...request, model: targetModel, ...comparisonFields })))
594
+ setTasks(previous => [...submitted, ...previous.filter(item => !submitted.some(task => task.id === item.id))])
595
+ setComparison(comparisonId === undefined ? null : { taskIds: submitted.map(task => task.id), prompt: promptText, comparisonId })
596
+ } catch (caught) {
597
+ setError(errorMessage(caught))
598
+ } finally {
599
+ setSubmitting(false)
600
+ }
601
+ }
602
+
603
+ /** Open the full-screen image preview at a given index. */
604
+ const openPreview = (previewImages: GeneratedImage[], index: number): void => {
605
+ setPreview({ images: previewImages, index })
606
+ setPreviewScale(1)
607
+ setPromptCopied(false)
608
+ }
609
+
610
+ const closePreview = (): void => {
611
+ setPreview(null)
612
+ setPreviewScale(1)
613
+ setPromptCopied(false)
614
+ }
615
+
616
+ /** Step the preview by ±1, wrapping around. */
617
+ const stepPreview = (delta: number): void => {
618
+ setPreviewScale(1)
619
+ setPromptCopied(false)
620
+ setPreview(current => {
621
+ if (current === null) return null
622
+ const total = current.images.length
623
+ return { images: current.images, index: (current.index + delta + total) % total }
624
+ })
625
+ }
626
+
627
+ // Keyboard navigation for the preview overlay.
628
+ useEffect(() => {
629
+ if (preview === null) return
630
+ const onKey = (event: KeyboardEvent): void => {
631
+ if (event.key === 'Escape') closePreview()
632
+ else if (event.key === 'ArrowLeft') stepPreview(-1)
633
+ else if (event.key === 'ArrowRight') stepPreview(1)
634
+ else if (event.key === '+' || event.key === '=') setPreviewScale(current => clampPreviewScale(current + PREVIEW_SCALE_STEP))
635
+ else if (event.key === '-') setPreviewScale(current => clampPreviewScale(current - PREVIEW_SCALE_STEP))
636
+ else if (event.key === '0') setPreviewScale(1)
637
+ }
638
+ window.addEventListener('keydown', onKey)
639
+ return () => window.removeEventListener('keydown', onKey)
640
+ }, [preview])
641
+
642
+ // A scaled image owns real scrollable space, rather than being visually
643
+ // transformed and clipped. Recenter the viewport after every zoom or slide.
644
+ useEffect(() => {
645
+ if (preview === null) return
646
+ const frame = window.requestAnimationFrame(() => {
647
+ const stage = previewStage.current
648
+ if (stage === null) return
649
+ stage.scrollLeft = Math.max(0, (stage.scrollWidth - stage.clientWidth) / 2)
650
+ stage.scrollTop = Math.max(0, (stage.scrollHeight - stage.clientHeight) / 2)
651
+ })
652
+ return () => window.cancelAnimationFrame(frame)
653
+ }, [preview, previewScale])
654
+
655
+ const loadHistoryGroup = async (group: HistoryGroup): Promise<GeneratedImage[]> => {
656
+ const loaded = await Promise.all(group.entries.map(entry => historyImagesToGenerated(entry.images)))
657
+ return loaded.flat()
658
+ }
659
+
660
+ /** View every model result from one comparison as one canvas result set. */
661
+ const viewHistoryGroup = async (group: HistoryGroup): Promise<void> => {
662
+ const entry = group.entries[0]
663
+ if (entry === undefined) return
664
+ // History is also the bridge out of the gallery: show the image workspace
665
+ // immediately, then hydrate the selected result into its canvas.
666
+ setTab('text')
362
667
  try {
363
- setPrompt(await api.enhancePrompt(prompt))
364
- } catch (caught) {
365
- setError(errorMessage(caught))
366
- } finally {
367
- setEnhancing(false)
368
- }
369
- }
370
-
371
- /** Read an uploaded reference image into a data URL. */
372
- const acceptFile = (file: File | undefined): void => {
373
- if (file === undefined) return
374
- if (!file.type.startsWith('image/')) {
375
- setError(tt('edit.uploadHint'))
376
- return
377
- }
378
- if (file.size > REF_IMAGE_MAX_BYTES) {
379
- setError(tt('edit.uploadHint'))
380
- return
381
- }
382
- const reader = new FileReader()
383
- reader.onload = () => {
384
- if (typeof reader.result === 'string') setRefImage({ dataUrl: reader.result, name: file.name })
385
- }
386
- reader.onerror = () => { setError(tt('edit.uploadHint')) }
387
- reader.readAsDataURL(file)
668
+ setImages(await loadHistoryGroup(group))
669
+ setComparison(null)
670
+ setError(null)
671
+ setViewingHistoryId(entry.id)
672
+ setGalleryViewingId(null)
673
+ } catch (caught) {
674
+ setError(errorMessage(caught))
675
+ }
676
+ }
677
+
678
+ /** Restore one comparison group, including its selected model set. */
679
+ const restoreHistoryGroup = async (group: HistoryGroup): Promise<void> => {
680
+ const entry = group.entries[0]
681
+ if (entry === undefined) return
682
+ try {
683
+ const restored = await loadHistoryGroup(group)
684
+ setTab(entry.mode)
685
+ setPrompt(entry.prompt)
686
+ setSize(normalizeSize(entry.size))
687
+ setQuality(normalizeQuality(entry.quality))
688
+ setDetail((DETAILS as readonly string[]).includes(entry.detail) ? entry.detail : '')
689
+ setCount(entry.n >= 1 && entry.n <= 4 ? entry.n : 1)
690
+ setModel(imageModels.includes(entry.model) ? entry.model : imageModels[0])
691
+ setCompareModels(group.models.filter(candidate => imageModels.includes(candidate)))
692
+ setCompareEnabled(group.models.filter(candidate => imageModels.includes(candidate)).length > 1)
693
+ setRefImage(null)
694
+ setImages(restored)
695
+ setComparison(null)
696
+ setError(null)
697
+ setViewingHistoryId(entry.id)
698
+ setGalleryViewingId(null)
699
+ } catch (caught) {
700
+ setError(errorMessage(caught))
701
+ }
702
+ }
703
+
704
+ /** Remove every persisted row belonging to one comparison group. */
705
+ const deleteHistoryGroup = async (group: HistoryGroup): Promise<void> => {
706
+ const ids = new Set(group.entries.map(entry => entry.id))
707
+ setHistory(previous => previous.filter(entry => !ids.has(entry.id)))
708
+ if (viewingHistoryId !== null && ids.has(viewingHistoryId)) setViewingHistoryId(null)
709
+ try {
710
+ let next = history
711
+ for (const id of ids) next = await api.historyRemove(id)
712
+ setHistory(next)
713
+ } catch {
714
+ // Keep the optimistic local removal.
715
+ }
716
+ }
717
+
718
+ /** Remove all history entries. */
719
+ const clearHistory = async (): Promise<void> => {
720
+ setHistory([])
721
+ setViewingHistoryId(null)
722
+ try {
723
+ setHistory(await api.historyClear())
724
+ } catch {
725
+ // Keep the cleared local state.
726
+ }
727
+ }
728
+
729
+ /** Add one generated image to the gallery (host deduplicates by content).
730
+ * `entry` makes the action available from a history/gallery list item (its
731
+ * metadata + first image are saved); otherwise the current form state is
732
+ * used. */
733
+ const addToGallery = async (image: GeneratedImage, entry?: HistoryEntry): Promise<void> => {
734
+ if (galleryAdding || tab === 'gallery') return
735
+ const source = entry ?? viewingEntry ?? {
736
+ mode: tab === 'edit' ? 'edit' as GenerateMode : 'text' as GenerateMode,
737
+ model,
738
+ prompt: prompt.trim(),
739
+ size,
740
+ quality,
741
+ detail,
742
+ ...refImage !== null ? { refName: refImage.name } : {},
743
+ }
744
+ setGalleryAdding(true)
745
+ try {
746
+ const result = await api.galleryAppend({
747
+ id: '', // the host assigns a fresh id
748
+ createdAt: Date.now(),
749
+ mode: source.mode,
750
+ model: source.model,
751
+ prompt: source.prompt,
752
+ size: source.size,
753
+ quality: source.quality,
754
+ detail: source.detail,
755
+ n: 1,
756
+ images: [image],
757
+ ...source.refName === undefined ? {} : { refName: source.refName },
758
+ })
759
+ setGallery(result.entries)
760
+ setGalleryMessage(result.added ? tt('gallery.added') : tt('gallery.already'))
761
+ window.setTimeout(() => { setGalleryMessage(null) }, 2200)
762
+ } catch (caught) {
763
+ setError(errorMessage(caught))
764
+ } finally {
765
+ setGalleryAdding(false)
766
+ }
388
767
  }
389
768
 
390
- /** Run one generation. */
391
- const handleGenerate = async (): Promise<void> => {
392
- if (generating) return
393
- if (!enabled) {
394
- openSettingsGuide('disabled')
769
+ /** Put a generated image into the native conversation composer. */
770
+ const addImageToConversation = async (image: GeneratedImage, index: number): Promise<void> => {
771
+ if (addingToConversation !== null) return
772
+ if (conversation === undefined || sessions === undefined || currentSessionId === undefined) {
773
+ setError(tt('conversation.noSession'))
395
774
  return
396
775
  }
397
- if (!configured || !apiKeySet) {
398
- openSettingsGuide('generation')
776
+ const sessionScope = sessions.scope(currentSessionId)
777
+ if (sessionScope === undefined) {
778
+ setError(tt('conversation.unavailable'))
399
779
  return
400
780
  }
401
- const promptText = prompt.trim()
402
- if (promptText === '') {
403
- setError(tt('prompt.required'))
404
- return
405
- }
406
- if (tab === 'edit' && refImage === null) {
407
- setError(tt('edit.required'))
408
- return
409
- }
410
- const request: GenerateRequest = {
411
- mode: tab === 'gallery' ? 'text' : tab,
412
- model: imageModels.includes(model) ? model : imageModels[0],
413
- prompt: promptText,
414
- size,
415
- quality,
416
- n: count,
417
- detail,
418
- ...tab === 'edit' && refImage !== null ? { image: refImage.dataUrl } : {},
419
- ...tab === 'edit' && refImage !== null ? { refName: refImage.name } : {},
420
- }
421
- setError(null)
781
+ setAddingToConversation(index)
782
+ let attachments: ReturnType<ConversationService['createDraftImages']> = []
783
+ let added = false
422
784
  try {
423
- const targetModels = (compareEnabled ? compareModels : [request.model]).filter(candidate => imageModels.includes(candidate))
424
- if (targetModels.length === 0) {
425
- setError(tt('compare.selectRequired'))
426
- return
785
+ const file = generatedImageToFile(image, index)
786
+ attachments = conversation.createDraftImages([file])
787
+ const input = conversation.input.for(sessionScope)
788
+ if (!input.addImages(attachments.map(attachment => attachment.id))) {
789
+ throw new Error(tt('conversation.busy'))
427
790
  }
428
- const submitted = await Promise.all(targetModels.map(targetModel => api.taskSubmit({ ...request, model: targetModel })))
429
- setTasks(previous => [...submitted, ...previous.filter(item => !submitted.some(task => task.id === item.id))])
430
- setComparison(targetModels.length > 1 ? { taskIds: submitted.map(task => task.id), prompt: promptText } : null)
431
- } catch (caught) {
432
- setError(errorMessage(caught))
433
- }
434
- }
435
-
436
- /** Open the full-screen image preview at a given index. */
437
- const openPreview = (previewImages: GeneratedImage[], index: number): void => {
438
- setPreview({ images: previewImages, index })
439
- setPreviewScale(1)
440
- setPromptCopied(false)
441
- }
442
-
443
- const closePreview = (): void => {
444
- setPreview(null)
445
- setPreviewScale(1)
446
- setPromptCopied(false)
447
- }
448
-
449
- /** Step the preview by ±1, wrapping around. */
450
- const stepPreview = (delta: number): void => {
451
- setPreviewScale(1)
452
- setPromptCopied(false)
453
- setPreview(current => {
454
- if (current === null) return null
455
- const total = current.images.length
456
- return { images: current.images, index: (current.index + delta + total) % total }
457
- })
458
- }
459
-
460
- // Keyboard navigation for the preview overlay.
461
- useEffect(() => {
462
- if (preview === null) return
463
- const onKey = (event: KeyboardEvent): void => {
464
- if (event.key === 'Escape') closePreview()
465
- else if (event.key === 'ArrowLeft') stepPreview(-1)
466
- else if (event.key === 'ArrowRight') stepPreview(1)
467
- else if (event.key === '+' || event.key === '=') setPreviewScale(current => clampPreviewScale(current + PREVIEW_SCALE_STEP))
468
- else if (event.key === '-') setPreviewScale(current => clampPreviewScale(current - PREVIEW_SCALE_STEP))
469
- else if (event.key === '0') setPreviewScale(1)
470
- }
471
- window.addEventListener('keydown', onKey)
472
- return () => window.removeEventListener('keydown', onKey)
473
- }, [preview])
474
-
475
- // A scaled image owns real scrollable space, rather than being visually
476
- // transformed and clipped. Recenter the viewport after every zoom or slide.
477
- useEffect(() => {
478
- if (preview === null) return
479
- const frame = window.requestAnimationFrame(() => {
480
- const stage = previewStage.current
481
- if (stage === null) return
482
- stage.scrollLeft = Math.max(0, (stage.scrollWidth - stage.clientWidth) / 2)
483
- stage.scrollTop = Math.max(0, (stage.scrollHeight - stage.clientHeight) / 2)
484
- })
485
- return () => window.cancelAnimationFrame(frame)
486
- }, [preview, previewScale])
487
-
488
- /** Load a past generation's images into the canvas. */
489
- const viewHistoryEntry = async (entry: HistoryEntry): Promise<void> => {
490
- try {
491
- setImages(await historyImagesToGenerated(entry.images))
492
- setError(null)
493
- setViewingHistoryId(entry.id)
494
- setGalleryViewingId(null)
495
- } catch (caught) {
496
- setError(errorMessage(caught))
497
- }
498
- }
499
-
500
- /** Restore a past generation's parameters (and its images) into the form. */
501
- const restoreHistoryEntry = async (entry: HistoryEntry): Promise<void> => {
502
- try {
503
- const restored = await historyImagesToGenerated(entry.images)
504
- setTab(entry.mode)
505
- setPrompt(entry.prompt)
506
- setSize(normalizeSize(entry.size))
507
- setQuality(normalizeQuality(entry.quality))
508
- setDetail((DETAILS as readonly string[]).includes(entry.detail) ? entry.detail : '')
509
- setCount(entry.n >= 1 && entry.n <= 4 ? entry.n : 1)
510
- setModel(imageModels.includes(entry.model) ? entry.model : imageModels[0])
511
- setRefImage(null)
512
- setImages(restored)
513
- setError(null)
514
- setViewingHistoryId(entry.id)
515
- setGalleryViewingId(null)
516
- } catch (caught) {
517
- setError(errorMessage(caught))
518
- }
519
- }
520
-
521
- /** Remove one history entry. */
522
- const deleteHistoryEntry = async (id: string): Promise<void> => {
523
- setHistory(history.filter(entry => entry.id !== id))
524
- if (viewingHistoryId === id) setViewingHistoryId(null)
525
- try {
526
- setHistory(await api.historyRemove(id))
527
- } catch {
528
- // Keep the optimistic local removal.
529
- }
530
- }
531
-
532
- /** Remove all history entries. */
533
- const clearHistory = async (): Promise<void> => {
534
- setHistory([])
535
- setViewingHistoryId(null)
536
- try {
537
- setHistory(await api.historyClear())
538
- } catch {
539
- // Keep the cleared local state.
540
- }
541
- }
542
-
543
- /** Add one generated image to the gallery (host deduplicates by content).
544
- * `entry` makes the action available from a history/gallery list item (its
545
- * metadata + first image are saved); otherwise the current form state is
546
- * used. */
547
- const addToGallery = async (image: GeneratedImage, entry?: HistoryEntry): Promise<void> => {
548
- if (galleryAdding || tab === 'gallery') return
549
- const source = entry ?? viewingEntry ?? {
550
- mode: tab === 'edit' ? 'edit' as GenerateMode : 'text' as GenerateMode,
551
- model,
552
- prompt: prompt.trim(),
553
- size,
554
- quality,
555
- detail,
556
- ...refImage !== null ? { refName: refImage.name } : {},
557
- }
558
- setGalleryAdding(true)
559
- try {
560
- const result = await api.galleryAppend({
561
- id: '', // the host assigns a fresh id
562
- createdAt: Date.now(),
563
- mode: source.mode,
564
- model: source.model,
565
- prompt: source.prompt,
566
- size: source.size,
567
- quality: source.quality,
568
- detail: source.detail,
569
- n: 1,
570
- images: [image],
571
- ...source.refName === undefined ? {} : { refName: source.refName },
572
- })
573
- setGallery(result.entries)
574
- setGalleryMessage(result.added ? tt('gallery.added') : tt('gallery.already'))
575
- window.setTimeout(() => { setGalleryMessage(null) }, 2200)
791
+ added = true
792
+ if (input.state.getSnapshot().draft.trim() === '' && prompt.trim() !== '') input.setDraft(prompt.trim())
793
+ setConversationMessage(tt('conversation.added'))
794
+ window.setTimeout(() => { setConversationMessage(null) }, 2200)
576
795
  } catch (caught) {
796
+ if (!added) conversation.releaseDraftImages(attachments)
577
797
  setError(errorMessage(caught))
578
798
  } finally {
579
- setGalleryAdding(false)
580
- }
581
- }
582
-
583
- /** Add one history entry's first image to the gallery (fetches it from the
584
- * history image route, then delegates to addToGallery). */
585
- const addHistoryEntryToGallery = async (entry: HistoryEntry): Promise<void> => {
586
- if (galleryAdding || entry.images.length === 0) return
587
- try {
588
- const [image] = await historyImagesToGenerated(entry.images.slice(0, 1))
589
- if (image === undefined) return
590
- await addToGallery(image, entry)
591
- } catch (caught) {
592
- setError(errorMessage(caught))
593
- }
594
- }
595
-
596
- /** View a gallery image in the canvas. */
597
- const viewGalleryEntry = async (entry: HistoryEntry): Promise<void> => {
598
- try {
599
- const restored = await historyImagesToGenerated(entry.images)
600
- setImages(restored)
601
- setError(null)
602
- setViewingHistoryId(null)
603
- setGalleryViewingId(entry.id)
604
- if (restored.length > 0) openPreview(restored, 0)
605
- } catch (caught) {
606
- setError(errorMessage(caught))
607
- }
608
- }
609
-
610
- /** Restore a gallery entry's parameters (and its images) into the form. */
611
- const restoreGalleryEntry = async (entry: HistoryEntry): Promise<void> => {
612
- try {
613
- const restored = await historyImagesToGenerated(entry.images)
614
- setTab(entry.mode)
615
- setPrompt(entry.prompt)
616
- setSize(normalizeSize(entry.size))
617
- setQuality(normalizeQuality(entry.quality))
618
- setDetail((DETAILS as readonly string[]).includes(entry.detail) ? entry.detail : '')
619
- setCount(entry.n >= 1 && entry.n <= 4 ? entry.n : 1)
620
- setModel(imageModels.includes(entry.model) ? entry.model : imageModels[0])
621
- setRefImage(null)
622
- setImages(restored)
623
- setError(null)
624
- setViewingHistoryId(null)
625
- setGalleryViewingId(null)
626
- } catch (caught) {
627
- setError(errorMessage(caught))
628
- }
629
- }
630
-
631
- /** Remove one gallery entry. */
632
- const deleteGalleryEntry = async (id: string): Promise<void> => {
633
- setGallery(gallery.filter(entry => entry.id !== id))
634
- if (galleryViewingId === id) setGalleryViewingId(null)
635
- try {
636
- setGallery(await api.galleryRemove(id))
637
- } catch {
638
- // Keep the optimistic local removal.
799
+ setAddingToConversation(null)
639
800
  }
640
801
  }
641
-
642
- /** Remove every gallery entry. */
643
- const clearGalleryAll = async (): Promise<void> => {
644
- setGallery([])
645
- setGalleryViewingId(null)
646
- try {
647
- setGallery(await api.galleryClear())
648
- } catch {
649
- // Keep the cleared local state.
650
- }
651
- }
652
-
653
- const applyGalleryTags = async (): Promise<void> => {
654
- const tags = galleryTagInput.split(',').map(tag => tag.trim()).filter(Boolean)
655
- if (tags.length === 0 || selectedGalleryIds.size === 0) return
656
- try {
657
- let next = gallery
658
- for (const id of selectedGalleryIds) {
659
- const existing = next.find(entry => entry.id === id)?.tags ?? []
660
- next = await api.gallerySetTags(id, [...existing, ...tags])
661
- }
662
- setGallery(next)
663
- setGalleryTagInput('')
664
- } catch (caught) { setError(errorMessage(caught)) }
665
- }
666
-
667
- const startEditingGalleryTags = (entry: HistoryEntry): void => {
668
- setEditingGalleryTagsId(entry.id)
669
- setGalleryTagEditInput((entry.tags ?? []).join(', '))
670
- }
671
-
672
- const saveGalleryTags = async (id: string): Promise<void> => {
673
- const tags = galleryTagEditInput.split(',').map(tag => tag.trim()).filter(Boolean)
674
- try {
675
- setGallery(await api.gallerySetTags(id, tags))
676
- setEditingGalleryTagsId(null)
677
- setGalleryTagEditInput('')
678
- } catch (caught) { setError(errorMessage(caught)) }
679
- }
680
-
681
- const toggleGallerySelection = (id: string): void => {
682
- setSelectedGalleryIds(previous => {
683
- const next = new Set(previous)
684
- if (next.has(id)) next.delete(id)
685
- else next.add(id)
686
- return next
687
- })
688
- }
689
-
690
- const clearGallerySelection = (): void => {
691
- setSelectedGalleryIds(new Set())
692
- setGallerySelecting(false)
693
- }
694
-
695
- const exportGalleryJson = (): void => {
696
- const entries = gallery.filter(entry => selectedGalleryIds.has(entry.id))
697
- const blob = new Blob([JSON.stringify(entries, null, 2)], { type: 'application/json' })
698
- const url = URL.createObjectURL(blob)
699
- const anchor = document.createElement('a')
700
- anchor.href = url
701
- anchor.download = `dsh-imagegen-gallery-${new Date().toISOString().slice(0, 10)}.json`
702
- anchor.click()
703
- URL.revokeObjectURL(url)
704
- }
705
-
706
- const downloadGalleryImages = (): void => {
707
- gallery.filter(entry => selectedGalleryIds.has(entry.id)).forEach((entry, index) => {
708
- const image = entry.images[0]
709
- if (image === undefined) return
710
- const anchor = document.createElement('a')
711
- anchor.href = image.url
712
- anchor.download = `dsh-gallery-${index + 1}.${extensionOf(image.mime)}`
713
- anchor.click()
714
- })
715
- }
716
-
717
- const generateDisabled = generating
718
- const viewingEntry = viewingHistoryId === null ? null : history.find(entry => entry.id === viewingHistoryId) ?? null
719
- const viewingGalleryEntry = galleryViewingId === null ? null : gallery.find(entry => entry.id === galleryViewingId) ?? null
720
- const previewImage = preview === null ? null : preview.images[preview.index] ?? null
721
- const comparisonTasks = comparison === null ? [] : comparison.taskIds.map(id => tasks.find(task => task.id === id)).filter((task): task is GenerationTask => task !== undefined)
722
- const comparisonResults = comparisonTasks.filter(task => task.status === 'completed' && task.result !== undefined)
723
- const previewFrameScale = Math.max(1, previewScale)
724
- const previewImageScale = previewScale / previewFrameScale
725
-
726
- const copyPreviewPrompt = async (text: string): Promise<void> => {
727
- try {
728
- if (navigator.clipboard?.writeText !== undefined) {
729
- await navigator.clipboard.writeText(text)
730
- } else {
731
- const textarea = document.createElement('textarea')
732
- textarea.value = text
733
- textarea.style.position = 'fixed'
734
- textarea.style.opacity = '0'
735
- document.body.appendChild(textarea)
736
- textarea.select()
737
- const copied = document.execCommand('copy')
738
- textarea.remove()
739
- if (!copied) throw new Error('copy failed')
740
- }
741
- setPromptCopied(true)
742
- window.setTimeout(() => { setPromptCopied(false) }, 1800)
743
- } catch {
744
- setPromptCopied(false)
745
- }
746
- }
747
-
802
+
803
+ /** Add one history entry's first image to the gallery (fetches it from the
804
+ * history image route, then delegates to addToGallery). */
805
+ const addHistoryEntryToGallery = async (entry: HistoryEntry): Promise<void> => {
806
+ if (galleryAdding || entry.images.length === 0) return
807
+ try {
808
+ const [image] = await historyImagesToGenerated(entry.images.slice(0, 1))
809
+ if (image === undefined) return
810
+ await addToGallery(image, entry)
811
+ } catch (caught) {
812
+ setError(errorMessage(caught))
813
+ }
814
+ }
815
+
816
+ /** View a gallery image in the canvas. */
817
+ const viewGalleryEntry = async (entry: HistoryEntry): Promise<void> => {
818
+ try {
819
+ const restored = await historyImagesToGenerated(entry.images)
820
+ setImages(restored)
821
+ setError(null)
822
+ setViewingHistoryId(null)
823
+ setGalleryViewingId(entry.id)
824
+ if (restored.length > 0) openPreview(restored, 0)
825
+ } catch (caught) {
826
+ setError(errorMessage(caught))
827
+ }
828
+ }
829
+
830
+ /** Restore a gallery entry's parameters (and its images) into the form. */
831
+ const restoreGalleryEntry = async (entry: HistoryEntry): Promise<void> => {
832
+ try {
833
+ const restored = await historyImagesToGenerated(entry.images)
834
+ setTab(entry.mode)
835
+ setPrompt(entry.prompt)
836
+ setSize(normalizeSize(entry.size))
837
+ setQuality(normalizeQuality(entry.quality))
838
+ setDetail((DETAILS as readonly string[]).includes(entry.detail) ? entry.detail : '')
839
+ setCount(entry.n >= 1 && entry.n <= 4 ? entry.n : 1)
840
+ setModel(imageModels.includes(entry.model) ? entry.model : imageModels[0])
841
+ setRefImage(null)
842
+ setImages(restored)
843
+ setError(null)
844
+ setViewingHistoryId(null)
845
+ setGalleryViewingId(null)
846
+ } catch (caught) {
847
+ setError(errorMessage(caught))
848
+ }
849
+ }
850
+
851
+ /** Remove one gallery entry. */
852
+ const deleteGalleryEntry = async (id: string): Promise<void> => {
853
+ setGallery(gallery.filter(entry => entry.id !== id))
854
+ if (galleryViewingId === id) setGalleryViewingId(null)
855
+ try {
856
+ setGallery(await api.galleryRemove(id))
857
+ } catch {
858
+ // Keep the optimistic local removal.
859
+ }
860
+ }
861
+
862
+ /** Remove every gallery entry. */
863
+ const clearGalleryAll = async (): Promise<void> => {
864
+ setGallery([])
865
+ setGalleryViewingId(null)
866
+ try {
867
+ setGallery(await api.galleryClear())
868
+ } catch {
869
+ // Keep the cleared local state.
870
+ }
871
+ }
872
+
873
+ const applyGalleryTags = async (): Promise<void> => {
874
+ const tags = galleryTagInput.split(',').map(tag => tag.trim()).filter(Boolean)
875
+ if (tags.length === 0 || selectedGalleryIds.size === 0) return
876
+ try {
877
+ let next = gallery
878
+ for (const id of selectedGalleryIds) {
879
+ const existing = next.find(entry => entry.id === id)?.tags ?? []
880
+ next = await api.gallerySetTags(id, [...existing, ...tags])
881
+ }
882
+ setGallery(next)
883
+ setGalleryTagInput('')
884
+ } catch (caught) { setError(errorMessage(caught)) }
885
+ }
886
+
887
+ const startEditingGalleryTags = (entry: HistoryEntry): void => {
888
+ setEditingGalleryTagsId(entry.id)
889
+ setGalleryTagEditInput((entry.tags ?? []).join(', '))
890
+ }
891
+
892
+ const saveGalleryTags = async (id: string): Promise<void> => {
893
+ const tags = galleryTagEditInput.split(',').map(tag => tag.trim()).filter(Boolean)
894
+ try {
895
+ setGallery(await api.gallerySetTags(id, tags))
896
+ setEditingGalleryTagsId(null)
897
+ setGalleryTagEditInput('')
898
+ } catch (caught) { setError(errorMessage(caught)) }
899
+ }
900
+
901
+ const toggleGallerySelection = (id: string): void => {
902
+ setSelectedGalleryIds(previous => {
903
+ const next = new Set(previous)
904
+ if (next.has(id)) next.delete(id)
905
+ else next.add(id)
906
+ return next
907
+ })
908
+ }
909
+
910
+ const clearGallerySelection = (): void => {
911
+ setSelectedGalleryIds(new Set())
912
+ setGallerySelecting(false)
913
+ }
914
+
915
+ const exportGalleryJson = (): void => {
916
+ const entries = gallery.filter(entry => selectedGalleryIds.has(entry.id))
917
+ const blob = new Blob([JSON.stringify(entries, null, 2)], { type: 'application/json' })
918
+ const url = URL.createObjectURL(blob)
919
+ const anchor = document.createElement('a')
920
+ anchor.href = url
921
+ anchor.download = `dsh-imagegen-gallery-${new Date().toISOString().slice(0, 10)}.json`
922
+ anchor.click()
923
+ URL.revokeObjectURL(url)
924
+ }
925
+
926
+ const downloadGalleryImages = (): void => {
927
+ gallery.filter(entry => selectedGalleryIds.has(entry.id)).forEach((entry, index) => {
928
+ const image = entry.images[0]
929
+ if (image === undefined) return
930
+ const anchor = document.createElement('a')
931
+ anchor.href = image.url
932
+ anchor.download = `dsh-gallery-${index + 1}.${extensionOf(image.mime)}`
933
+ anchor.click()
934
+ })
935
+ }
936
+
937
+ const generateDisabled = submitting || modeModels.length === 0
938
+ const viewingEntry = viewingHistoryId === null ? null : history.find(entry => entry.id === viewingHistoryId) ?? null
939
+ const viewingGalleryEntry = galleryViewingId === null ? null : gallery.find(entry => entry.id === galleryViewingId) ?? null
940
+ const previewImage = preview === null ? null : preview.images[preview.index] ?? null
941
+ const comparisonTasks = comparison === null ? [] : comparison.taskIds.map(id => tasks.find(task => task.id === id)).filter((task): task is GenerationTask => task !== undefined)
942
+ const comparisonResults = comparisonTasks.filter(task => task.status === 'completed' && task.result !== undefined)
943
+ const previewFrameScale = Math.max(1, previewScale)
944
+ const previewImageScale = previewScale / previewFrameScale
945
+
946
+ const copyPreviewPrompt = async (text: string): Promise<void> => {
947
+ try {
948
+ if (navigator.clipboard?.writeText !== undefined) {
949
+ await navigator.clipboard.writeText(text)
950
+ } else {
951
+ const textarea = document.createElement('textarea')
952
+ textarea.value = text
953
+ textarea.style.position = 'fixed'
954
+ textarea.style.opacity = '0'
955
+ document.body.appendChild(textarea)
956
+ textarea.select()
957
+ const copied = document.execCommand('copy')
958
+ textarea.remove()
959
+ if (!copied) throw new Error('copy failed')
960
+ }
961
+ setPromptCopied(true)
962
+ window.setTimeout(() => { setPromptCopied(false) }, 1800)
963
+ } catch {
964
+ setPromptCopied(false)
965
+ }
966
+ }
967
+
748
968
  const addPreviewToEdit = (): void => {
749
- if (previewImage === null || preview === null) return
750
- setTab('edit')
751
- setRefImage({
752
- dataUrl: srcOf(previewImage),
753
- name: `dsh-image-${preview.index + 1}.${extensionOf(previewImage.mime)}`,
754
- })
755
- if (prompt.trim() === '' && previewImage.revisedPrompt !== undefined) setPrompt(previewImage.revisedPrompt)
756
- setError(null)
969
+ if (previewImage === null || preview === null) return
970
+ setTab('edit')
971
+ setRefImage({
972
+ dataUrl: srcOf(previewImage),
973
+ name: `dsh-image-${preview.index + 1}.${extensionOf(previewImage.mime)}`,
974
+ })
975
+ if (prompt.trim() === '' && previewImage.revisedPrompt !== undefined) setPrompt(previewImage.revisedPrompt)
976
+ setError(null)
757
977
  closePreview()
758
978
  }
759
979
 
760
- return (
761
- <div className={css.panel}>
762
- <header className={css.panelHeader}>
763
- <span className={css.panelHeading}>
764
- <h2 className={css.panelTitle}>{tt('panel.title')}</h2>
765
- <a
766
- className={css.githubLink}
767
- href="https://github.com/dickpy/dsh-imagegen"
768
- target="_blank"
769
- rel="noreferrer"
770
- title={tt('panel.githubTip')}
771
- aria-label={tt('panel.githubTip')}
772
- >
773
- <svg viewBox="0 0 16 16" width="15" height="15" fill="currentColor" aria-hidden="true"><path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.01 8.01 0 0 0 16 8c0-4.42-3.58-8-8-8z"/></svg>
774
- </a>
775
- </span>
776
- <button
777
- type="button"
778
- className={css.connectionStatus}
779
- data-connected={connected ? 'true' : 'false'}
780
- aria-label={tt(connected ? 'connection.connected' : 'connection.disconnected')}
781
- >
782
- <span className={css.connectionDot} aria-hidden="true" />
783
- {tt(connected ? 'connection.connected' : 'connection.disconnected')}
784
- </button>
980
+ // Render history into the shell sidebar so it remains a separate navigation
981
+ // surface from both the image workspace and the native conversation.
982
+ const historyPanel = (
983
+ <aside className={css.history} data-dsh-imagegen-history>
984
+ <header className={css.historyHeader}>
985
+ <span className={css.historyTitle}>{tt('history.title')}</span>
986
+ {history.length > 0 ? (
987
+ <button type="button" className={css.historyClear} onClick={() => { void clearHistory() }}>
988
+ {tt('history.clear')}
989
+ </button>
990
+ ) : null}
785
991
  </header>
786
992
 
787
- {update !== null ? (
788
- <div className={css.updateBanner} data-kind={updateResult === 'success' ? 'ok' : 'warn'}>
789
- <span className={css.updateText}>
790
- {updateMessage ?? tt('update.available', { version: update.latestVersion })}
791
- </span>
792
- <span className={css.updateActions}>
793
- <a className={css.updateRelease} href={update.releaseUrl} target="_blank" rel="noreferrer">{tt('update.release')}</a>
794
- <Button variant="primary" size="sm" disabled={updating || updateMessage !== null} onClick={() => { void applyUpdate() }}>
795
- {updating ? tt('update.installing') : tt('update.install')}
796
- </Button>
797
- </span>
798
- </div>
799
- ) : null}
993
+ <div className={css.historyFilters}>
994
+ <input className={css.historySearch} value={historyQuery} onChange={event => { setHistoryQuery(event.target.value) }} placeholder={tt('history.search')} aria-label={tt('history.search')} />
995
+ <select value={historyModelFilter} onChange={event => { setHistoryModelFilter(event.target.value) }} aria-label={tt('history.model')}>
996
+ <option value="all">{tt('history.allModels')}</option>
997
+ {[...new Set(history.flatMap(entry => modelsOfHistoryEntry(entry)))].map(option => <option key={option} value={option}>{option}</option>)}
998
+ </select>
999
+ <select value={historyRatioFilter} onChange={event => { setHistoryRatioFilter(event.target.value) }} aria-label={tt('history.ratio')}>
1000
+ <option value="all">{tt('history.allRatios')}</option>
1001
+ {[...new Set(history.map(entry => normalizeSize(entry.size)))].map(option => <option key={option} value={option}>{option}</option>)}
1002
+ </select>
1003
+ </div>
800
1004
 
801
- <div className={css.studio}>
802
- {/* ---------------------------------------------------- config sidebar */}
803
- <aside className={css.config} data-gallery={tab === 'gallery' ? 'true' : undefined}>
804
- {tab === 'gallery' ? (
805
- <div className={css.galleryFilters}>
806
- <div className={css.galleryFilterHeading}>{tt('gallery.categories')}</div>
807
- {[
808
- ['all', tt('gallery.all')],
809
- ['text', tt('mode.text')],
810
- ['edit', tt('mode.edit')],
811
- ...galleryModels.map(value => [value, value]),
812
- ].map(([value, label]) => (
1005
+ {filteredHistory.length === 0 ? (
1006
+ <div className={css.historyEmpty}>{tt('history.empty')}</div>
1007
+ ) : (
1008
+ <div className={css.historyList}>
1009
+ {filteredHistory.map(group => {
1010
+ const entry = group.entries[0]!
1011
+ const isComparison = group.models.length > 1
1012
+ const imageCount = group.entries.reduce((total, item) => total + item.images.length, 0)
1013
+ return (
1014
+ <div
1015
+ key={group.key}
1016
+ className={css.historyItem}
1017
+ data-active={group.entries.some(item => item.id === viewingHistoryId) ? '' : undefined}
1018
+ data-comparison={isComparison ? '' : undefined}
1019
+ >
813
1020
  <button
814
- key={value}
815
1021
  type="button"
816
- className={css.galleryFilter}
817
- data-active={galleryFilter === value ? '' : undefined}
818
- onClick={() => { setGalleryFilter(value) }}
1022
+ className={css.historyMain}
1023
+ data-dsh-imagegen-history-main=""
1024
+ onClick={() => { void viewHistoryGroup(group) }}
819
1025
  >
820
- <span>{label}</span>
821
- <span className={css.galleryFilterCount}>{gallery.filter(entry => value === 'all' || value === 'text' || value === 'edit' ? (value === 'all' ? true : entry.mode === value) : entry.model === value).length}</span>
1026
+ {entry.images.length > 0 ? (
1027
+ <img className={css.historyThumb} src={entry.images[0]!.url} alt="" />
1028
+ ) : (
1029
+ <span className={css.historyThumbPlaceholder} />
1030
+ )}
1031
+ <span className={css.historyInfo}>
1032
+ <span className={css.historyPrompt}>{entry.prompt}</span>
1033
+ <span className={css.historyMeta}>
1034
+ {isComparison ? tt('compare.title') : tt(`mode.${entry.mode === 'edit' ? 'edit' : 'text'}` as const)}
1035
+ {' · '}{isComparison ? group.models.join(' · ') : entry.model}
1036
+ {' · '}{formatTime(entry.createdAt)}
1037
+ {' · '}{imageCount} {tt('history.images')}
1038
+ </span>
1039
+ </span>
822
1040
  </button>
823
- ))}
824
- <div className={css.galleryFilterDivider} />
825
- <div className={css.galleryFilterHeading}>{tt('gallery.ratio')}</div>
826
- <div className={css.galleryRatioList}>
827
- {(['all', '1:1', '3:4', '4:3', '16:9'] as const).map(ratio => (
828
- <button key={ratio} type="button" className={css.galleryRatio} data-active={galleryRatio === ratio ? '' : undefined} onClick={() => { setGalleryRatio(ratio) }}>
829
- {ratio === 'all' ? tt('gallery.all') : ratio}
830
- </button>
831
- ))}
832
- </div>
833
- {galleryTagOptions.length > 0 ? (
834
- <>
835
- <div className={css.galleryFilterDivider} />
836
- <div className={css.galleryFilterHeading}>{tt('gallery.tags')}</div>
837
- <div className={css.galleryTagFilterList}>
838
- {galleryTagOptions.map(tag => (
839
- <button key={tag} type="button" className={css.galleryTagFilter} data-active={galleryTagFilter === tag ? '' : undefined} onClick={() => { setGalleryTagFilter(previous => previous === tag ? null : tag) }}>
840
- <span>{tag}</span>
841
- <span>{gallery.filter(entry => (entry.tags ?? []).includes(tag)).length}</span>
842
- </button>
843
- ))}
844
- </div>
845
- </>
846
- ) : null}
847
- <div className={css.galleryFilterNote}>{tt('gallery.filterHint')}</div>
848
- </div>
849
- ) : null}
850
- <div className={css.configScroll}>
851
- {/* mode / gallery tabs */}
852
- <section className={css.card}>
853
- <div className={css.modeRow} role="tablist" aria-label={tt('panel.title')}>
854
- <Pill active={tab === 'text'} onClick={() => { setTab('text') }} className={css.modePill}>{tt('mode.text')}</Pill>
855
- <Pill active={tab === 'edit'} onClick={() => { setTab('edit') }} className={css.modePill}>{tt('mode.edit')}</Pill>
856
- <Pill active={tab === 'gallery'} onClick={() => { setTab('gallery') }} className={css.modePill}>{tt('gallery.title')}</Pill>
857
- </div>
858
- </section>
859
-
860
- {/* reference image (edit mode) */}
861
- {tab === 'edit' ? (
862
- <section className={css.card}>
863
- {refImage === null
864
- ? (
1041
+ <span className={css.historyActions}>
1042
+ {entry.images.length > 0 ? (
865
1043
  <button
866
1044
  type="button"
867
- className={css.uploadBox}
868
- onClick={() => { fileInput.current?.click() }}
869
- onDragOver={(event) => { event.preventDefault() }}
870
- onDrop={(event) => {
871
- event.preventDefault()
872
- acceptFile(event.dataTransfer.files?.[0])
873
- }}
1045
+ className={css.historyAction}
1046
+ disabled={galleryAdding}
1047
+ title={tt('gallery.add')}
1048
+ onClick={() => { void addHistoryEntryToGallery(entry) }}
874
1049
  >
875
- <span className={css.uploadIcon}>
876
- <svg viewBox="0 0 16 16" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M8 10.5V3"/><path d="M5 5.5l3-3 3 3"/><path d="M2.5 9v3.5h11V9"/></svg>
877
- </span>
878
- <span>{tt('edit.upload')}</span>
879
- <span className={css.uploadHint}>{tt('edit.uploadHint')}</span>
1050
+ {tt('gallery.add')}
880
1051
  </button>
881
- )
882
- : (
883
- <div className={css.reference}>
884
- <img className={css.referenceImage} src={refImage.dataUrl} alt={refImage.name} />
885
- <div className={css.referenceActions}>
886
- <Button variant="outline" size="sm" onClick={() => { fileInput.current?.click() }}>
887
- {tt('edit.change')}
888
- </Button>
889
- <Button variant="outline" size="sm" onClick={() => { setRefImage(null) }}>
890
- {tt('edit.remove')}
891
- </Button>
892
- </div>
893
- </div>
894
- )}
895
- <input
896
- ref={fileInput}
897
- type="file"
898
- accept="image/png,image/jpeg,image/webp,image/gif"
899
- className={css.hiddenFile}
900
- onChange={(event) => {
901
- acceptFile(event.target.files?.[0])
902
- event.target.value = ''
903
- }}
904
- />
905
- </section>
906
- ) : null}
907
-
908
- {/* prompt */}
909
- <section className={css.card}>
910
- <textarea
911
- className={css.prompt}
912
- value={prompt}
913
- placeholder={tt('prompt.placeholder')}
914
- onChange={(event) => { setPrompt(event.target.value) }}
915
- />
916
- <div className={css.promptFooter}>
917
- <button
918
- type="button"
919
- className={css.templatesButton}
920
- title={tt('templates.title')}
921
- onClick={() => { setLibraryOpen(true) }}
922
- >
923
- <svg viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M2.5 3.5h11M2.5 8h11M2.5 12.5h7"/></svg>
924
- {tt('templates.open')}
925
- </button>
926
- <button
927
- type="button"
928
- className={css.enhanceButton}
929
- disabled={prompt.trim() === '' || enhancing}
930
- title={tt('prompt.enhanceHint')}
931
- onClick={() => { void enhanceCurrentPrompt() }}
932
- >
933
- {enhancing ? tt('prompt.enhancing') : tt('prompt.enhance')}
934
- </button>
935
- <span className={css.promptCount}>{tt('prompt.count', { count: prompt.length })}</span>
936
- </div>
937
- </section>
938
-
939
- {/* parameters */}
940
- <section className={css.card}>
941
- <div className={css.paramGroup}>
942
- <span className={css.paramLabel}>{tt('params.size')}</span>
943
- <div className={css.optionGrid}>
944
- {SIZES.map(option => (
945
- <Pill
946
- key={option}
947
- active={size === option}
948
- onClick={() => { setSize(option) }}
949
- className={css.optionPill}
950
- >
951
- {tt(SIZE_KEYS[option] ?? 'size.auto')}
952
- </Pill>
953
- ))}
954
- </div>
955
- </div>
956
- <div className={css.paramGroup}>
957
- <span className={css.paramLabel}>{tt('params.quality')}</span>
958
- <div className={css.optionRow}>
959
- {QUALITIES.map(option => (
960
- <Pill
961
- key={option}
962
- active={quality === option}
963
- onClick={() => { setQuality(option) }}
964
- className={css.optionPill}
965
- >
966
- {tt(`quality.${option}` as const)}
967
- </Pill>
968
- ))}
969
- </div>
970
- </div>
971
- <div className={css.paramGroup}>
972
- <span className={css.paramLabel}>{tt('params.count')}</span>
973
- <div className={css.optionRow}>
974
- {[1, 2, 3, 4].map(option => (
975
- <Pill
976
- key={option}
977
- active={count === option}
978
- onClick={() => { setCount(option) }}
979
- className={css.optionPill}
980
- >
981
- {tt(`count.${option === 1 ? 'one' : option === 2 ? 'two' : option === 3 ? 'three' : 'four'}` as const)}
982
- </Pill>
983
- ))}
984
- </div>
985
- </div>
986
- <div className={css.paramGroup}>
987
- <span className={css.paramLabel}>{tt('params.detail')}</span>
988
- <div className={css.optionRow}>
989
- {DETAILS.map(option => (
990
- <Pill
991
- key={option === '' ? 'auto' : option}
992
- active={detail === option}
993
- onClick={() => { setDetail(option) }}
994
- className={css.optionPill}
995
- >
996
- {tt(option === '' ? 'detail.auto' : option === 'standard' ? 'detail.standard' : 'detail.high')}
997
- </Pill>
998
- ))}
999
- </div>
1000
- <span className={css.paramHint}>{tt('detail.hint')}</span>
1001
- </div>
1002
- </section>
1003
- </div>
1004
-
1005
- {/* footer: model + generate — a fixed sibling of the scroll area, so
1006
- it never overlaps the cards scrolling above it. */}
1007
- <section className={css.footer}>
1008
- <label className={css.modelWrap}>
1009
- <span className={css.modelLabel}>{tt('model.label')}</span>
1010
- <span ref={modelMenuRef} className={css.modelMenu} data-open={modelOpen ? 'true' : 'false'}>
1011
- <button
1012
- type="button"
1013
- className={css.modelSelect}
1014
- disabled={generating}
1015
- aria-haspopup="listbox"
1016
- aria-expanded={modelOpen}
1017
- onClick={() => { setModelOpen(open => !open) }}
1018
- >
1019
- <span>{model}</span>
1020
- <svg viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M8 10.5L4 6h8z"/></svg>
1021
- </button>
1022
- {modelOpen ? (
1023
- <div className={css.modelMenuList} role="listbox" aria-label={tt('model.label')}>
1024
- {imageModels.map(option => (
1025
- <button
1026
- key={option}
1027
- type="button"
1028
- role="option"
1029
- aria-selected={model === option}
1030
- className={css.modelMenuItem}
1031
- data-selected={model === option ? '' : undefined}
1032
- onClick={() => { setModel(option); setModelOpen(false) }}
1033
- >
1034
- {option}
1035
- </button>
1036
- ))}
1037
- </div>
1038
- ) : null}
1039
- </span>
1040
- </label>
1041
- <div className={css.compareControl}>
1042
- <label className={css.compareToggle}>
1043
- <input type="checkbox" checked={compareEnabled} onChange={event => { setCompareEnabled(event.target.checked) }} />
1044
- <span>{tt('compare.enable')}</span>
1045
- </label>
1046
- {compareEnabled ? (
1047
- <div className={css.compareModelChoices} role="group" aria-label={tt('compare.models')}>
1048
- {imageModels.map(option => (
1049
- <label key={option}>
1050
- <input type="checkbox" checked={compareModels.includes(option)} onChange={() => { setCompareModels(previous => previous.includes(option) ? previous.filter(value => value !== option) : [...previous, option]) }} />
1051
- <span>{option}</span>
1052
- </label>
1053
- ))}
1054
- </div>
1055
- ) : null}
1056
- </div>
1057
- <Button
1058
- variant="primary"
1059
- size="md"
1060
- className={css.generateButton}
1061
- disabled={generateDisabled}
1062
- onClick={() => { void handleGenerate() }}
1063
- >
1064
- {generating ? (
1065
- <span className={css.generateInner}>
1066
- <span className={css.spinner} />
1067
- {tt('generating')}
1068
- </span>
1069
- ) : tt('generate')}
1070
- </Button>
1071
- </section>
1072
- </aside>
1073
-
1074
- {/* --------------------------------------------------------- canvas */}
1075
- <section className={css.canvas} data-gallery={tab === 'gallery' ? 'true' : undefined}>
1076
- {tab === 'gallery' ? (
1077
- <div className={css.galleryWorkspace}>
1078
- <header className={css.galleryToolbar}>
1079
- <div>
1080
- <h3 className={css.galleryHeading}>{tt('gallery.all')}</h3>
1081
- <span className={css.galleryCount}>{tt('gallery.count', { count: filteredGallery.length })}</span>
1082
- </div>
1083
- <div className={css.galleryToolbarActions}>
1084
- <input className={css.gallerySearch} value={galleryQuery} onChange={event => { setGalleryQuery(event.target.value) }} placeholder={tt('gallery.search')} aria-label={tt('gallery.search')} />
1085
- <button type="button" className={css.gallerySelectMode} data-active={gallerySelecting ? '' : undefined} aria-pressed={gallerySelecting} onClick={() => { setGallerySelecting(previous => !previous) }}>
1086
- {gallerySelecting ? tt('gallery.selectionDone') : tt('gallery.select')}
1052
+ ) : null}
1053
+ <button type="button" className={css.historyAction} onClick={() => { void restoreHistoryGroup(group) }}>
1054
+ {tt('history.restore')}
1087
1055
  </button>
1088
- <div className={css.galleryViewToggle} role="group" aria-label={tt('gallery.viewMode')}>
1089
- <button type="button" data-active={galleryView === 'masonry' ? '' : undefined} onClick={() => { setGalleryView('masonry') }} title={tt('gallery.masonry')}>
1090
- <span aria-hidden="true">▦</span> {tt('gallery.masonry')}
1091
- </button>
1092
- <button type="button" data-active={galleryView === 'grid' ? '' : undefined} onClick={() => { setGalleryView('grid') }} title={tt('gallery.grid')}>
1093
- <span aria-hidden="true">▤</span> {tt('gallery.grid')}
1094
- </button>
1095
- </div>
1096
- <select className={css.gallerySort} value={gallerySort} onChange={event => { setGallerySort(event.target.value as 'newest' | 'oldest') }} aria-label={tt('gallery.sort')}>
1097
- <option value="newest">{tt('gallery.newest')}</option>
1098
- <option value="oldest">{tt('gallery.oldest')}</option>
1099
- </select>
1100
- {gallery.length > 0 ? <button type="button" className={css.galleryClear} onClick={() => { void clearGalleryAll() }}>{tt('gallery.clear')}</button> : null}
1101
- </div>
1102
- </header>
1103
- {selectedGalleryIds.size > 0 ? (
1104
- <section className={css.gallerySelectionBar} aria-label={tt('gallery.selected', { count: selectedGalleryIds.size })}>
1105
- <strong>{tt('gallery.selected', { count: selectedGalleryIds.size })}</strong>
1106
- <input className={css.galleryTagInput} value={galleryTagInput} onChange={event => { setGalleryTagInput(event.target.value) }} placeholder={tt('gallery.tagsPlaceholder')} aria-label={tt('gallery.tagsPlaceholder')} />
1107
- <button type="button" className={css.galleryBulkButton} disabled={galleryTagInput.trim() === ''} onClick={() => { void applyGalleryTags() }}>{tt('gallery.tagsApply')}</button>
1108
- <button type="button" className={css.galleryBulkButton} onClick={downloadGalleryImages}>{tt('gallery.downloadSelected')}</button>
1109
- <button type="button" className={css.galleryBulkButton} onClick={exportGalleryJson}>{tt('gallery.exportJson')}</button>
1110
- <button type="button" className={css.gallerySelectionClear} onClick={clearGallerySelection}>{tt('gallery.selectionClear')}</button>
1111
- </section>
1112
- ) : null}
1113
- {filteredGallery.length === 0 ? (
1114
- <div className={css.historyEmpty}>{tt('gallery.empty')}</div>
1115
- ) : (
1116
- <div className={css.galleryMasonry} data-view={galleryView}>
1117
- {filteredGallery.map(entry => {
1118
- const image = entry.images[0]
1119
- if (image === undefined) return null
1120
- return (
1121
- <article key={entry.id} className={css.galleryCard} data-selected={selectedGalleryIds.has(entry.id) ? '' : undefined}>
1122
- <label className={css.gallerySelect} title={tt('gallery.select')}>
1123
- <input type="checkbox" checked={selectedGalleryIds.has(entry.id)} onChange={() => { setGallerySelecting(true); toggleGallerySelection(entry.id) }} />
1124
- </label>
1125
- <button type="button" className={css.galleryImageButton} data-selecting={gallerySelecting ? '' : undefined} onClick={() => { if (gallerySelecting) toggleGallerySelection(entry.id); else void viewGalleryEntry(entry) }} title={gallerySelecting ? tt('gallery.select') : tt('preview.open')}>
1126
- <img className={css.galleryImage} src={image.url} alt={entry.prompt} />
1127
- <span className={css.galleryBadge}>{entry.mode === 'edit' ? tt('mode.edit') : tt('mode.text')}</span>
1128
- </button>
1129
- <div className={css.galleryCardFooter}>
1130
- <span className={css.galleryAvatar}>{entry.model.toLowerCase().startsWith('nanobanana') ? 'N' : entry.model.toLowerCase().startsWith('seedream') ? 'S' : entry.model.startsWith('grok') ? 'G' : 'D'}</span>
1131
- <span className={css.galleryCardInfo}>
1132
- <strong>{entry.prompt || tt('gallery.untitled')}</strong>
1133
- <small>{entry.model} · {normalizeSize(entry.size)} · {formatTime(entry.createdAt)}</small>
1134
- <span className={css.galleryTags}>
1135
- {(entry.tags ?? []).map(tag => <button key={tag} type="button" onClick={() => { setGalleryTagFilter(tag) }}>{tag}</button>)}
1136
- <button type="button" className={css.galleryTagEdit} onClick={() => { startEditingGalleryTags(entry) }} title={tt('gallery.editTags')}>{tt('gallery.tagsEditShort')}</button>
1137
- </span>
1138
- </span>
1139
- <button type="button" className={css.galleryRemove} onClick={() => { void deleteGalleryEntry(entry.id) }} title={tt('gallery.delete')}>×</button>
1140
- </div>
1141
- {editingGalleryTagsId === entry.id ? (
1142
- <form className={css.galleryTagEditor} onSubmit={event => { event.preventDefault(); void saveGalleryTags(entry.id) }}>
1143
- <input value={galleryTagEditInput} onChange={event => { setGalleryTagEditInput(event.target.value) }} placeholder={tt('gallery.tagsPlaceholder')} aria-label={tt('gallery.tagsPlaceholder')} autoFocus />
1144
- <button type="submit">{tt('gallery.tagsSave')}</button>
1145
- <button type="button" onClick={() => { setEditingGalleryTagsId(null); setGalleryTagEditInput('') }}>{tt('gallery.tagsCancel')}</button>
1146
- </form>
1147
- ) : null}
1148
- </article>
1149
- )
1150
- })}
1151
- </div>
1152
- )}
1153
- </div>
1154
- ) : null}
1155
- {tab !== 'gallery' && tasks.length > 0 ? (
1156
- <section className={css.taskTray} data-open={taskTrayOpen ? 'true' : 'false'} aria-label={tt('tasks.title')}>
1157
- <header className={css.taskTrayHeader}>
1158
- <button type="button" className={css.taskTrayToggle} aria-expanded={taskTrayOpen} onClick={() => { setTaskTrayOpen(open => !open) }}>
1159
- <span>{tt('tasks.title')}</span>
1160
- <span className={css.taskTrayCount}>{tasks.filter(task => task.status === 'queued' || task.status === 'running').length}</span>
1161
- <span className={css.taskTrayChevron} aria-hidden="true">{taskTrayOpen ? '⌃' : '⌄'}</span>
1162
- </button>
1163
- {taskTrayOpen ? <button type="button" className={css.taskTrayClose} aria-label={tt('preview.close')} onClick={() => { setTaskTrayOpen(false) }}>×</button> : null}
1164
- </header>
1165
- <div className={css.taskRows}>
1166
- {tasks.slice(0, 5).map(task => (
1167
- <div key={task.id} className={css.taskRow} data-status={task.status}>
1168
- <span className={css.taskStatus}>{tt(`tasks.${task.status}` as never)}</span>
1169
- <span className={css.taskPrompt}>{task.request.prompt}</span>
1170
- {(task.status === 'queued' || task.status === 'running') ? <button type="button" onClick={() => { void api.taskCancel(task.id) }}>{tt('tasks.cancel')}</button> : null}
1171
- {task.status === 'failed' || task.status === 'cancelled' ? <button type="button" onClick={() => { void api.taskRetry(task.id) }}>{tt('tasks.retry')}</button> : null}
1172
- </div>
1173
- ))}
1174
- </div>
1175
- </section>
1176
- ) : null}
1177
- {tab !== 'gallery' && comparison !== null ? (
1178
- <section className={css.comparisonBoard} aria-label={tt('compare.title')}>
1179
- <header><div><strong>{tt('compare.title')}</strong><span>{comparisonResults.length} / {comparisonTasks.length}</span></div><button type="button" disabled={comparisonResults.length === 0} onClick={() => { setComparisonFullscreen(true) }}>{tt('compare.fullscreen')}</button></header>
1180
- <div className={css.comparisonGrid}>
1181
- {comparisonTasks.map(task => (
1182
- <article key={task.id}>
1183
- <strong>{task.request.model}</strong>
1184
- {task.result?.images[0] !== undefined ? <img src={srcOf(task.result.images[0])} alt={task.request.model} /> : <span>{tt(`tasks.${task.status}` as never)}</span>}
1185
- </article>
1186
- ))}
1056
+ <button type="button" className={css.historyAction} data-danger onClick={() => { void deleteHistoryGroup(group) }}>
1057
+ {tt('history.delete')}
1058
+ </button>
1059
+ </span>
1187
1060
  </div>
1188
- </section>
1189
- ) : null}
1190
- {generating ? (
1191
- <div className={css.canvasState} role="status">
1192
- <span className={css.bigSpinner} />
1193
- <span className={css.canvasStateTitle}>{tt('canvas.generating')}</span>
1194
- <span className={css.canvasStateHint}>{tt('canvas.elapsed', { seconds: elapsed })}</span>
1195
- </div>
1196
- ) : null}
1197
-
1198
- {!generating && error !== null ? (
1199
- <div className={css.canvasError} role="alert">{tt('canvas.error', { error })}</div>
1200
- ) : null}
1061
+ )
1062
+ })}
1063
+ </div>
1064
+ )}
1065
+ </aside>
1066
+ )
1201
1067
 
1202
- {!generating && !error && images.length === 0 ? (
1203
- <div className={css.canvasState}>
1204
- <span className={css.canvasEmptyIcon}>
1205
- <svg viewBox="0 0 24 24" width="34" height="34" fill="none" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><rect x="3" y="3" width="18" height="18" rx="3"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="M21 15l-5-5L5 21"/></svg>
1206
- </span>
1207
- <span className={css.canvasStateTitle}>{tt('canvas.emptyTitle')}</span>
1208
- <span className={css.canvasStateHint}>{tt('canvas.emptyHint')}</span>
1209
- </div>
1210
- ) : null}
1068
+ return (
1069
+ <div className={css.panel}>
1070
+ <header className={css.panelHeader}>
1071
+ <span className={css.panelHeading}>
1072
+ <h2 className={css.panelTitle}>{tt('panel.title')}</h2>
1073
+ <a
1074
+ className={css.githubLink}
1075
+ href="https://github.com/dickpy/dsh-imagegen"
1076
+ target="_blank"
1077
+ rel="noreferrer"
1078
+ title={tt('panel.githubTip')}
1079
+ aria-label={tt('panel.githubTip')}
1080
+ >
1081
+ <svg viewBox="0 0 16 16" width="15" height="15" fill="currentColor" aria-hidden="true"><path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.01 8.01 0 0 0 16 8c0-4.42-3.58-8-8-8z"/></svg>
1082
+ </a>
1083
+ </span>
1084
+ <button
1085
+ type="button"
1086
+ className={css.connectionStatus}
1087
+ data-connected={connected ? 'true' : 'false'}
1088
+ aria-label={tt(connected ? 'connection.connected' : 'connection.disconnected')}
1089
+ >
1090
+ <span className={css.connectionDot} aria-hidden="true" />
1091
+ {tt(connected ? 'connection.connected' : 'connection.disconnected')}
1092
+ </button>
1093
+ </header>
1094
+
1095
+ {update !== null ? (
1096
+ <div className={css.updateBanner} data-kind={updateResult === 'success' ? 'ok' : 'warn'}>
1097
+ <span className={css.updateText}>
1098
+ {updateMessage ?? tt('update.available', { version: update.latestVersion })}
1099
+ </span>
1100
+ <span className={css.updateActions}>
1101
+ <a className={css.updateRelease} href={update.releaseUrl} target="_blank" rel="noreferrer">{tt('update.release')}</a>
1102
+ <Button variant="primary" size="sm" disabled={updating || updateMessage !== null} onClick={() => { void applyUpdate() }}>
1103
+ {updating ? tt('update.installing') : tt('update.install')}
1104
+ </Button>
1105
+ </span>
1106
+ </div>
1107
+ ) : null}
1108
+
1109
+ <div className={css.studio}>
1110
+ {/* ------------------------------- left history + generation workspace */}
1111
+ <div className={css.generation}>
1112
+ {/* ------------------------------------------------ config sidebar */}
1113
+ <aside className={css.config} data-gallery={tab === 'gallery' ? 'true' : undefined}>
1114
+ {tab === 'gallery' ? (
1115
+ <div className={css.galleryFilters}>
1116
+ <div className={css.galleryFilterHeading}>{tt('gallery.categories')}</div>
1117
+ {[
1118
+ ['all', tt('gallery.all')],
1119
+ ['text', tt('mode.text')],
1120
+ ['edit', tt('mode.edit')],
1121
+ ...galleryModels.map(value => [value, value]),
1122
+ ].map(([value, label]) => (
1123
+ <button
1124
+ key={value}
1125
+ type="button"
1126
+ className={css.galleryFilter}
1127
+ data-active={galleryFilter === value ? '' : undefined}
1128
+ onClick={() => { setGalleryFilter(value) }}
1129
+ >
1130
+ <span>{label}</span>
1131
+ <span className={css.galleryFilterCount}>{gallery.filter(entry => value === 'all' || value === 'text' || value === 'edit' ? (value === 'all' ? true : entry.mode === value) : entry.model === value).length}</span>
1132
+ </button>
1133
+ ))}
1134
+ <div className={css.galleryFilterDivider} />
1135
+ <div className={css.galleryFilterHeading}>{tt('gallery.ratio')}</div>
1136
+ <div className={css.galleryRatioList}>
1137
+ {(['all', '1:1', '3:4', '4:3', '16:9'] as const).map(ratio => (
1138
+ <button key={ratio} type="button" className={css.galleryRatio} data-active={galleryRatio === ratio ? '' : undefined} onClick={() => { setGalleryRatio(ratio) }}>
1139
+ {ratio === 'all' ? tt('gallery.all') : ratio}
1140
+ </button>
1141
+ ))}
1142
+ </div>
1143
+ {galleryTagOptions.length > 0 ? (
1144
+ <>
1145
+ <div className={css.galleryFilterDivider} />
1146
+ <div className={css.galleryFilterHeading}>{tt('gallery.tags')}</div>
1147
+ <div className={css.galleryTagFilterList}>
1148
+ {galleryTagOptions.map(tag => (
1149
+ <button key={tag} type="button" className={css.galleryTagFilter} data-active={galleryTagFilter === tag ? '' : undefined} onClick={() => { setGalleryTagFilter(previous => previous === tag ? null : tag) }}>
1150
+ <span>{tag}</span>
1151
+ <span>{gallery.filter(entry => (entry.tags ?? []).includes(tag)).length}</span>
1152
+ </button>
1153
+ ))}
1154
+ </div>
1155
+ </>
1156
+ ) : null}
1157
+ <div className={css.galleryFilterNote}>{tt('gallery.filterHint')}</div>
1158
+ </div>
1159
+ ) : null}
1160
+ <div className={css.configScroll}>
1161
+ {/* mode / gallery tabs */}
1162
+ <section className={css.card}>
1163
+ <div className={css.modeRow} role="tablist" aria-label={tt('panel.title')}>
1164
+ <Pill active={tab === 'text'} onClick={() => { setTab('text') }} className={css.modePill}>{tt('mode.text')}</Pill>
1165
+ <Pill active={tab === 'edit'} onClick={() => { setTab('edit') }} className={css.modePill}>{tt('mode.edit')}</Pill>
1166
+ <Pill active={tab === 'gallery'} onClick={() => { setTab('gallery') }} className={css.modePill}>{tt('gallery.title')}</Pill>
1167
+ </div>
1168
+ </section>
1169
+
1170
+ {/* reference image (edit mode) */}
1171
+ {tab === 'edit' ? (
1172
+ <section className={css.card}>
1173
+ {refImage === null
1174
+ ? (
1175
+ <button
1176
+ type="button"
1177
+ className={css.uploadBox}
1178
+ onClick={() => { fileInput.current?.click() }}
1179
+ onDragOver={(event) => { event.preventDefault() }}
1180
+ onDrop={(event) => {
1181
+ event.preventDefault()
1182
+ acceptFile(event.dataTransfer.files?.[0])
1183
+ }}
1184
+ >
1185
+ <span className={css.uploadIcon}>
1186
+ <svg viewBox="0 0 16 16" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M8 10.5V3"/><path d="M5 5.5l3-3 3 3"/><path d="M2.5 9v3.5h11V9"/></svg>
1187
+ </span>
1188
+ <span>{tt('edit.upload')}</span>
1189
+ <span className={css.uploadHint}>{tt('edit.uploadHint')}</span>
1190
+ </button>
1191
+ )
1192
+ : (
1193
+ <div className={css.reference}>
1194
+ <img className={css.referenceImage} src={refImage.dataUrl} alt={refImage.name} />
1195
+ <div className={css.referenceActions}>
1196
+ <Button variant="outline" size="sm" onClick={() => { fileInput.current?.click() }}>
1197
+ {tt('edit.change')}
1198
+ </Button>
1199
+ <Button variant="outline" size="sm" onClick={() => { setRefImage(null) }}>
1200
+ {tt('edit.remove')}
1201
+ </Button>
1202
+ </div>
1203
+ </div>
1204
+ )}
1205
+ <input
1206
+ ref={fileInput}
1207
+ type="file"
1208
+ accept="image/png,image/jpeg,image/webp,image/gif"
1209
+ className={css.hiddenFile}
1210
+ onChange={(event) => {
1211
+ acceptFile(event.target.files?.[0])
1212
+ event.target.value = ''
1213
+ }}
1214
+ />
1215
+ </section>
1216
+ ) : null}
1217
+
1218
+ {/* prompt */}
1219
+ <section className={css.card}>
1220
+ <textarea
1221
+ className={css.prompt}
1222
+ value={prompt}
1223
+ placeholder={tt('prompt.placeholder')}
1224
+ onChange={(event) => { setPrompt(event.target.value) }}
1225
+ />
1226
+ <div className={css.promptFooter}>
1227
+ <button
1228
+ type="button"
1229
+ className={css.templatesButton}
1230
+ title={tt('templates.title')}
1231
+ onClick={() => { setLibraryOpen(true) }}
1232
+ >
1233
+ <svg viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M2.5 3.5h11M2.5 8h11M2.5 12.5h7"/></svg>
1234
+ {tt('templates.open')}
1235
+ </button>
1236
+ <button
1237
+ type="button"
1238
+ className={css.enhanceButton}
1239
+ disabled={prompt.trim() === '' || enhancing}
1240
+ title={tt('prompt.enhanceHint')}
1241
+ onClick={() => { void enhanceCurrentPrompt() }}
1242
+ >
1243
+ {enhancing ? tt('prompt.enhancing') : tt('prompt.enhance')}
1244
+ </button>
1245
+ <span className={css.promptCount}>{tt('prompt.count', { count: prompt.length })}</span>
1246
+ </div>
1247
+ </section>
1248
+
1249
+ {/* parameters */}
1250
+ <section className={css.card}>
1251
+ <div className={css.paramGroup}>
1252
+ <span className={css.paramLabel}>{tt('params.size')}</span>
1253
+ <div className={css.optionGrid}>
1254
+ {SIZES.map(option => (
1255
+ <Pill
1256
+ key={option}
1257
+ active={size === option}
1258
+ onClick={() => { setSize(option) }}
1259
+ className={css.optionPill}
1260
+ >
1261
+ {tt(SIZE_KEYS[option] ?? 'size.auto')}
1262
+ </Pill>
1263
+ ))}
1264
+ </div>
1265
+ </div>
1266
+ <div className={css.paramGroup}>
1267
+ <span className={css.paramLabel}>{tt('params.quality')}</span>
1268
+ <div className={css.optionRow}>
1269
+ {QUALITIES.map(option => (
1270
+ <Pill
1271
+ key={option}
1272
+ active={quality === option}
1273
+ onClick={() => { setQuality(option) }}
1274
+ className={css.optionPill}
1275
+ >
1276
+ {tt(`quality.${option}` as const)}
1277
+ </Pill>
1278
+ ))}
1279
+ </div>
1280
+ </div>
1281
+ <div className={css.paramGroup}>
1282
+ <span className={css.paramLabel}>{tt('params.count')}</span>
1283
+ <div className={css.optionRow}>
1284
+ {[1, 2, 3, 4].map(option => (
1285
+ <Pill
1286
+ key={option}
1287
+ active={count === option}
1288
+ onClick={() => { setCount(option) }}
1289
+ className={css.optionPill}
1290
+ >
1291
+ {tt(`count.${option === 1 ? 'one' : option === 2 ? 'two' : option === 3 ? 'three' : 'four'}` as const)}
1292
+ </Pill>
1293
+ ))}
1294
+ </div>
1295
+ </div>
1296
+ <div className={css.paramGroup}>
1297
+ <span className={css.paramLabel}>{tt('params.detail')}</span>
1298
+ <div className={css.optionRow}>
1299
+ {DETAILS.map(option => (
1300
+ <Pill
1301
+ key={option === '' ? 'auto' : option}
1302
+ active={detail === option}
1303
+ onClick={() => { setDetail(option) }}
1304
+ className={css.optionPill}
1305
+ >
1306
+ {tt(option === '' ? 'detail.auto' : option === 'standard' ? 'detail.standard' : 'detail.high')}
1307
+ </Pill>
1308
+ ))}
1309
+ </div>
1310
+ <span className={css.paramHint}>{tt('detail.hint')}</span>
1311
+ </div>
1312
+ </section>
1313
+ </div>
1314
+
1315
+ {/* footer: model + generate — a fixed sibling of the scroll area, so
1316
+ it never overlaps the cards scrolling above it. */}
1317
+ <section className={css.footer}>
1318
+ <label className={css.modelWrap}>
1319
+ <span className={css.modelLabel}>{tt('model.label')}</span>
1320
+ <span ref={modelMenuRef} className={css.modelMenu} data-open={modelOpen ? 'true' : 'false'}>
1321
+ <button
1322
+ type="button"
1323
+ className={css.modelSelect}
1324
+ disabled={submitting}
1325
+ aria-haspopup="listbox"
1326
+ aria-expanded={modelOpen}
1327
+ onClick={() => { setModelOpen(open => !open) }}
1328
+ >
1329
+ <span>{model || tt('model.noEditModels')}</span>
1330
+ <svg viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M8 10.5L4 6h8z"/></svg>
1331
+ </button>
1332
+ {modelOpen ? (
1333
+ <div className={css.modelMenuList} role="listbox" aria-label={tt('model.label')}>
1334
+ {modeModels.map(option => (
1335
+ <button
1336
+ key={option}
1337
+ type="button"
1338
+ role="option"
1339
+ aria-selected={model === option}
1340
+ className={css.modelMenuItem}
1341
+ data-selected={model === option ? '' : undefined}
1342
+ onClick={() => { setModel(option); setModelOpen(false) }}
1343
+ >
1344
+ {option}
1345
+ </button>
1346
+ ))}
1347
+ </div>
1348
+ ) : null}
1349
+ </span>
1350
+ </label>
1351
+ <div className={css.compareControl}>
1352
+ <label className={css.compareToggle}>
1353
+ <input type="checkbox" checked={compareEnabled} onChange={event => { setCompareEnabled(event.target.checked) }} />
1354
+ <span>{tt('compare.enable')}</span>
1355
+ </label>
1356
+ {compareEnabled ? (
1357
+ <div className={css.compareModelChoices} role="group" aria-label={tt('compare.models')}>
1358
+ {modeModels.map(option => (
1359
+ <label key={option}>
1360
+ <input type="checkbox" checked={compareModels.includes(option)} onChange={() => { setCompareModels(previous => previous.includes(option) ? previous.filter(value => value !== option) : [...previous, option]) }} />
1361
+ <span>{option}</span>
1362
+ </label>
1363
+ ))}
1364
+ </div>
1365
+ ) : null}
1366
+ </div>
1367
+ <Button
1368
+ variant="primary"
1369
+ size="md"
1370
+ className={css.generateButton}
1371
+ disabled={generateDisabled}
1372
+ onClick={() => { void handleGenerate() }}
1373
+ >
1374
+ {generating ? (
1375
+ <span className={css.generateInner}>
1376
+ <span className={css.spinner} />
1377
+ {tt('generating')}
1378
+ </span>
1379
+ ) : tt('generate')}
1380
+ </Button>
1381
+ </section>
1382
+ </aside>
1211
1383
 
1212
- {!generating && images.length > 0 ? (
1213
- <div className={css.canvasBody}>
1214
- <div className={css.canvasMeta}>
1215
- <span>{tt('canvas.images', { count: images.length })}</span>
1216
- {viewingEntry !== null || viewingGalleryEntry !== null ? (
1217
- <span className={css.canvasHistoryTag}>
1218
- {viewingEntry !== null
1219
- ? tt('history.viewing', { time: formatTime(viewingEntry.createdAt) })
1220
- : tt('gallery.viewing', { time: formatTime(viewingGalleryEntry!.createdAt) })}
1221
- </span>
1222
- ) : null}
1223
- </div>
1224
- <div className={css.grid} data-count={images.length}>
1225
- {images.map((image, index) => (
1226
- <figure
1227
- key={index}
1228
- className={css.imageCard}
1229
- role="button"
1230
- tabIndex={0}
1231
- title={tt('preview.open')}
1232
- onClick={() => { openPreview(images, index) }}
1233
- onKeyDown={(event) => {
1234
- if (event.key === 'Enter' || event.key === ' ') {
1235
- event.preventDefault()
1236
- openPreview(images, index)
1237
- }
1238
- }}
1239
- >
1240
- <img
1241
- className={css.image}
1242
- src={srcOf(image)}
1243
- alt={image.revisedPrompt ?? `${tt('panel.title')} ${index + 1}`}
1244
- />
1245
- {image.revisedPrompt !== undefined ? (
1246
- <figcaption className={css.imageCaption} title={image.revisedPrompt}>
1247
- {tt('revisedPrompt', { prompt: image.revisedPrompt })}
1248
- </figcaption>
1249
- ) : null}
1250
- <span className={css.zoomHint}>
1251
- <svg viewBox="0 0 16 16" width="13" height="13" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><circle cx="7" cy="7" r="4"/><path d="M13 13l-3.2-3.2"/><path d="M7 5.4v3.2M5.4 7h3.2"/></svg>
1252
- {tt('preview.open')}
1253
- </span>
1384
+ {/* ------------------------------------------------------- canvas */}
1385
+ <section className={css.canvas} data-gallery={tab === 'gallery' ? 'true' : undefined}>
1386
+ {tab === 'gallery' ? (
1387
+ <div className={css.galleryWorkspace}>
1388
+ <header className={css.galleryToolbar}>
1389
+ <div>
1390
+ <h3 className={css.galleryHeading}>{tt('gallery.all')}</h3>
1391
+ <span className={css.galleryCount}>{tt('gallery.count', { count: filteredGallery.length })}</span>
1392
+ </div>
1393
+ <div className={css.galleryToolbarActions}>
1394
+ <input className={css.gallerySearch} value={galleryQuery} onChange={event => { setGalleryQuery(event.target.value) }} placeholder={tt('gallery.search')} aria-label={tt('gallery.search')} />
1395
+ <button type="button" className={css.gallerySelectMode} data-active={gallerySelecting ? '' : undefined} aria-pressed={gallerySelecting} onClick={() => { setGallerySelecting(previous => !previous) }}>
1396
+ {gallerySelecting ? tt('gallery.selectionDone') : tt('gallery.select')}
1397
+ </button>
1398
+ <div className={css.galleryViewToggle} role="group" aria-label={tt('gallery.viewMode')}>
1399
+ <button type="button" data-active={galleryView === 'masonry' ? '' : undefined} onClick={() => { setGalleryView('masonry') }} title={tt('gallery.masonry')}>
1400
+ <span aria-hidden="true">▦</span> {tt('gallery.masonry')}
1401
+ </button>
1402
+ <button type="button" data-active={galleryView === 'grid' ? '' : undefined} onClick={() => { setGalleryView('grid') }} title={tt('gallery.grid')}>
1403
+ <span aria-hidden="true">▤</span> {tt('gallery.grid')}
1404
+ </button>
1405
+ </div>
1406
+ <select className={css.gallerySort} value={gallerySort} onChange={event => { setGallerySort(event.target.value as 'newest' | 'oldest') }} aria-label={tt('gallery.sort')}>
1407
+ <option value="newest">{tt('gallery.newest')}</option>
1408
+ <option value="oldest">{tt('gallery.oldest')}</option>
1409
+ </select>
1410
+ {gallery.length > 0 ? <button type="button" className={css.galleryClear} onClick={() => { void clearGalleryAll() }}>{tt('gallery.clear')}</button> : null}
1411
+ </div>
1412
+ </header>
1413
+ {selectedGalleryIds.size > 0 ? (
1414
+ <section className={css.gallerySelectionBar} aria-label={tt('gallery.selected', { count: selectedGalleryIds.size })}>
1415
+ <strong>{tt('gallery.selected', { count: selectedGalleryIds.size })}</strong>
1416
+ <input className={css.galleryTagInput} value={galleryTagInput} onChange={event => { setGalleryTagInput(event.target.value) }} placeholder={tt('gallery.tagsPlaceholder')} aria-label={tt('gallery.tagsPlaceholder')} />
1417
+ <button type="button" className={css.galleryBulkButton} disabled={galleryTagInput.trim() === ''} onClick={() => { void applyGalleryTags() }}>{tt('gallery.tagsApply')}</button>
1418
+ <button type="button" className={css.galleryBulkButton} onClick={downloadGalleryImages}>{tt('gallery.downloadSelected')}</button>
1419
+ <button type="button" className={css.galleryBulkButton} onClick={exportGalleryJson}>{tt('gallery.exportJson')}</button>
1420
+ <button type="button" className={css.gallerySelectionClear} onClick={clearGallerySelection}>{tt('gallery.selectionClear')}</button>
1421
+ </section>
1422
+ ) : null}
1423
+ {filteredGallery.length === 0 ? (
1424
+ <div className={css.historyEmpty}>{tt('gallery.empty')}</div>
1425
+ ) : (
1426
+ <div className={css.galleryMasonry} data-view={galleryView}>
1427
+ {filteredGallery.map(entry => {
1428
+ const image = entry.images[0]
1429
+ if (image === undefined) return null
1430
+ return (
1431
+ <article key={entry.id} className={css.galleryCard} data-selected={selectedGalleryIds.has(entry.id) ? '' : undefined}>
1432
+ <label className={css.gallerySelect} title={tt('gallery.select')}>
1433
+ <input type="checkbox" checked={selectedGalleryIds.has(entry.id)} onChange={() => { setGallerySelecting(true); toggleGallerySelection(entry.id) }} />
1434
+ </label>
1435
+ <button type="button" className={css.galleryImageButton} data-selecting={gallerySelecting ? '' : undefined} onClick={() => { if (gallerySelecting) toggleGallerySelection(entry.id); else void viewGalleryEntry(entry) }} title={gallerySelecting ? tt('gallery.select') : tt('preview.open')}>
1436
+ <img className={css.galleryImage} src={image.url} alt={entry.prompt} />
1437
+ <span className={css.galleryBadge}>{entry.mode === 'edit' ? tt('mode.edit') : tt('mode.text')}</span>
1438
+ </button>
1439
+ <div className={css.galleryCardFooter}>
1440
+ <span className={css.galleryAvatar}>{entry.model.toLowerCase().startsWith('nanobanana') ? 'N' : entry.model.toLowerCase().startsWith('seedream') ? 'S' : entry.model.startsWith('grok') ? 'G' : 'D'}</span>
1441
+ <span className={css.galleryCardInfo}>
1442
+ <strong>{entry.prompt || tt('gallery.untitled')}</strong>
1443
+ <small>{entry.model} · {normalizeSize(entry.size)} · {formatTime(entry.createdAt)}</small>
1444
+ <span className={css.galleryTags}>
1445
+ {(entry.tags ?? []).map(tag => <button key={tag} type="button" onClick={() => { setGalleryTagFilter(tag) }}>{tag}</button>)}
1446
+ <button type="button" className={css.galleryTagEdit} onClick={() => { startEditingGalleryTags(entry) }} title={tt('gallery.editTags')}>{tt('gallery.tagsEditShort')}</button>
1447
+ </span>
1448
+ </span>
1449
+ <button type="button" className={css.galleryRemove} onClick={() => { void deleteGalleryEntry(entry.id) }} title={tt('gallery.delete')}>×</button>
1450
+ </div>
1451
+ {editingGalleryTagsId === entry.id ? (
1452
+ <form className={css.galleryTagEditor} onSubmit={event => { event.preventDefault(); void saveGalleryTags(entry.id) }}>
1453
+ <input value={galleryTagEditInput} onChange={event => { setGalleryTagEditInput(event.target.value) }} placeholder={tt('gallery.tagsPlaceholder')} aria-label={tt('gallery.tagsPlaceholder')} autoFocus />
1454
+ <button type="submit">{tt('gallery.tagsSave')}</button>
1455
+ <button type="button" onClick={() => { setEditingGalleryTagsId(null); setGalleryTagEditInput('') }}>{tt('gallery.tagsCancel')}</button>
1456
+ </form>
1457
+ ) : null}
1458
+ </article>
1459
+ )
1460
+ })}
1461
+ </div>
1462
+ )}
1463
+ </div>
1464
+ ) : null}
1465
+ {tab !== 'gallery' && tasks.length > 0 ? (
1466
+ <section className={css.taskTray} data-open={taskTrayOpen ? 'true' : 'false'} aria-label={tt('tasks.title')}>
1467
+ <header className={css.taskTrayHeader}>
1468
+ <button type="button" className={css.taskTrayToggle} aria-expanded={taskTrayOpen} onClick={() => { setTaskTrayOpen(open => !open) }}>
1469
+ <span>{tt('tasks.title')}</span>
1470
+ <span className={css.taskTrayCount}>{activeTasks.length}</span>
1471
+ <span className={css.taskTrayChevron} aria-hidden="true">{taskTrayOpen ? '⌃' : '⌄'}</span>
1472
+ </button>
1473
+ {taskTrayOpen ? <button type="button" className={css.taskTrayClose} aria-label={tt('preview.close')} onClick={() => { setTaskTrayOpen(false) }}>×</button> : null}
1474
+ </header>
1475
+ <div className={css.taskRows}>
1476
+ {tasks.slice(0, 5).map(task => (
1477
+ <div key={task.id} className={css.taskRow} data-status={task.status}>
1478
+ <span className={css.taskStatus}>{tt(`tasks.${task.status}` as never)}</span>
1479
+ <span className={css.taskPrompt}>{task.request.prompt}</span>
1480
+ {(task.status === 'queued' || task.status === 'running') ? <button type="button" onClick={() => { void api.taskCancel(task.id) }}>{tt('tasks.cancel')}</button> : null}
1481
+ {task.status === 'failed' || task.status === 'cancelled' ? <button type="button" onClick={() => { void api.taskRetry(task.id) }}>{tt('tasks.retry')}</button> : null}
1482
+ </div>
1483
+ ))}
1484
+ </div>
1485
+ </section>
1486
+ ) : null}
1487
+ {tab !== 'gallery' && comparison !== null ? (
1488
+ <section className={css.comparisonBoard} aria-label={tt('compare.title')}>
1489
+ <header><div><strong>{tt('compare.title')}</strong><span>{comparisonResults.length} / {comparisonTasks.length}{generating ? ` · ${tt('canvas.elapsed', { seconds: elapsed })}` : ''}</span></div><button type="button" disabled={comparisonResults.length === 0} onClick={() => { setComparisonFullscreen(true) }}>{tt('compare.fullscreen')}</button></header>
1490
+ <div className={css.comparisonGrid}>
1491
+ {comparisonTasks.map(task => {
1492
+ const taskImages = task.result?.images ?? []
1493
+ const image = taskImages[0]
1494
+ return (
1495
+ <article key={task.id}>
1496
+ <strong>{task.request.model}</strong>
1497
+ {image !== undefined ? (
1498
+ <button
1499
+ type="button"
1500
+ className={css.comparisonImageButton}
1501
+ title={tt('preview.open')}
1502
+ onClick={() => { openPreview(taskImages, 0) }}
1503
+ >
1504
+ <img src={srcOf(image)} alt={task.request.model} />
1505
+ </button>
1506
+ ) : <span>{tt(`tasks.${task.status}` as never)}</span>}
1507
+ </article>
1508
+ )
1509
+ })}
1510
+ </div>
1511
+ </section>
1512
+ ) : null}
1513
+ {generating && comparison === null ? (
1514
+ <div className={css.canvasState} data-generation-state={activeTask?.status ?? 'submitting'} role="status">
1515
+ <span className={css.bigSpinner} />
1516
+ <span className={css.canvasStateTitle}>
1517
+ {submitting && activeTask === undefined
1518
+ ? tt('canvas.submitting')
1519
+ : activeTask?.status === 'queued'
1520
+ ? tt('canvas.queued')
1521
+ : tt('canvas.generating')}
1522
+ </span>
1523
+ <span className={css.canvasStateHint}>
1524
+ {activeTask?.status === 'queued'
1525
+ ? tt('canvas.queueHint', { count: activeTasks.length })
1526
+ : tt('canvas.elapsed', { seconds: elapsed })}
1527
+ </span>
1528
+ </div>
1529
+ ) : null}
1530
+
1531
+ {!generating && error !== null ? (
1532
+ <div className={css.canvasError} role="alert">{tt('canvas.error', { error })}</div>
1533
+ ) : null}
1534
+
1535
+ {!generating && !error && images.length === 0 ? (
1536
+ <div className={css.canvasState}>
1537
+ <span className={css.canvasEmptyIcon}>
1538
+ <svg viewBox="0 0 24 24" width="34" height="34" fill="none" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><rect x="3" y="3" width="18" height="18" rx="3"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="M21 15l-5-5L5 21"/></svg>
1539
+ </span>
1540
+ <span className={css.canvasStateTitle}>{tt('canvas.emptyTitle')}</span>
1541
+ <span className={css.canvasStateHint}>{tt('canvas.emptyHint')}</span>
1542
+ </div>
1543
+ ) : null}
1544
+
1545
+ {!generating && images.length > 0 ? (
1546
+ <div className={css.canvasBody}>
1547
+ <div className={css.canvasMeta}>
1548
+ <span>{tt('canvas.images', { count: images.length })}</span>
1549
+ {viewingEntry !== null || viewingGalleryEntry !== null ? (
1550
+ <span className={css.canvasHistoryTag}>
1551
+ {viewingEntry !== null
1552
+ ? tt('history.viewing', { time: formatTime(viewingEntry.createdAt) })
1553
+ : tt('gallery.viewing', { time: formatTime(viewingGalleryEntry!.createdAt) })}
1554
+ </span>
1555
+ ) : null}
1556
+ </div>
1557
+ <div className={css.grid} data-count={images.length}>
1558
+ {images.map((image, index) => (
1559
+ <figure
1560
+ key={index}
1561
+ className={css.imageCard}
1562
+ role="button"
1563
+ tabIndex={0}
1564
+ title={tt('preview.open')}
1565
+ onClick={() => { openPreview(images, index) }}
1566
+ onKeyDown={(event) => {
1567
+ if (event.key === 'Enter' || event.key === ' ') {
1568
+ event.preventDefault()
1569
+ openPreview(images, index)
1570
+ }
1571
+ }}
1572
+ >
1573
+ <img
1574
+ className={css.image}
1575
+ src={srcOf(image)}
1576
+ alt={image.revisedPrompt ?? `${tt('panel.title')} ${index + 1}`}
1577
+ />
1578
+ {image.revisedPrompt !== undefined ? (
1579
+ <figcaption className={css.imageCaption} title={image.revisedPrompt}>
1580
+ {tt('revisedPrompt', { prompt: image.revisedPrompt })}
1581
+ </figcaption>
1582
+ ) : null}
1583
+ <span className={css.zoomHint}>
1584
+ <svg viewBox="0 0 16 16" width="13" height="13" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><circle cx="7" cy="7" r="4"/><path d="M13 13l-3.2-3.2"/><path d="M7 5.4v3.2M5.4 7h3.2"/></svg>
1585
+ {tt('preview.open')}
1586
+ </span>
1254
1587
  <button
1255
1588
  type="button"
1256
1589
  className={css.galleryAdd}
1257
- title={tt('gallery.add')}
1258
- disabled={galleryAdding}
1259
- onClick={(event) => { event.stopPropagation(); void addToGallery(image) }}
1260
- >
1261
- <svg viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><rect x="2.5" y="3" width="11" height="10" rx="1.5"/><path d="M8 5.8v4.4M5.8 8h4.4"/></svg>
1590
+ title={tt('gallery.add')}
1591
+ disabled={galleryAdding}
1592
+ onClick={(event) => { event.stopPropagation(); void addToGallery(image) }}
1593
+ >
1594
+ <svg viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><rect x="2.5" y="3" width="11" height="10" rx="1.5"/><path d="M8 5.8v4.4M5.8 8h4.4"/></svg>
1262
1595
  {tt('gallery.add')}
1263
1596
  </button>
1264
- <a
1265
- className={css.download}
1266
- href={srcOf(image)}
1267
- download={`dsh-image-${index + 1}.${extensionOf(image.mime)}`}
1268
- onClick={(event) => { event.stopPropagation() }}
1269
- >
1270
- {tt('download')}
1271
- </a>
1272
- </figure>
1273
- ))}
1274
- </div>
1275
- </div>
1276
- ) : null}
1277
- </section>
1278
-
1279
- {/* ------------------------ right column: gallery (tab) or history */}
1280
- {tab === 'gallery' ? (
1281
- <aside className={css.history}>
1282
- <header className={css.historyHeader}>
1283
- <span className={css.historyTitle}>{tt('gallery.title')}</span>
1284
- {gallery.length > 0 ? (
1285
- <button type="button" className={css.historyClear} onClick={() => { void clearGalleryAll() }}>
1286
- {tt('gallery.clear')}
1287
- </button>
1288
- ) : null}
1289
- </header>
1290
-
1291
- {gallery.length === 0 ? (
1292
- <div className={css.historyEmpty}>{tt('gallery.empty')}</div>
1293
- ) : (
1294
- <div className={css.historyList}>
1295
- {gallery.map(entry => (
1296
- <div
1297
- key={entry.id}
1298
- className={css.historyItem}
1299
- data-active={entry.id === galleryViewingId ? '' : undefined}
1300
- >
1301
- <button
1302
- type="button"
1303
- className={css.historyMain}
1304
- onClick={() => { void viewGalleryEntry(entry) }}
1305
- >
1306
- {entry.images.length > 0 ? (
1307
- <img className={css.historyThumb} src={entry.images[0]!.url} alt="" />
1308
- ) : (
1309
- <span className={css.historyThumbPlaceholder} />
1310
- )}
1311
- <span className={css.historyInfo}>
1312
- <span className={css.historyPrompt}>{entry.prompt}</span>
1313
- <span className={css.historyMeta}>
1314
- {tt(`mode.${entry.mode === 'edit' ? 'edit' : 'text'}` as const)}
1315
- {' · '}{formatTime(entry.createdAt)}
1316
- </span>
1317
- </span>
1318
- </button>
1319
- <span className={css.historyActions}>
1320
- <button type="button" className={css.historyAction} onClick={() => { void restoreGalleryEntry(entry) }}>
1321
- {tt('history.restore')}
1322
- </button>
1323
- <button type="button" className={css.historyAction} data-danger onClick={() => { void deleteGalleryEntry(entry.id) }}>
1324
- {tt('gallery.delete')}
1325
- </button>
1326
- </span>
1327
- </div>
1328
- ))}
1329
- </div>
1330
- )}
1331
- </aside>
1332
- ) : (
1333
- <aside className={css.history}>
1334
- <header className={css.historyHeader}>
1335
- <span className={css.historyTitle}>{tt('history.title')}</span>
1336
- {history.length > 0 ? (
1337
- <button type="button" className={css.historyClear} onClick={() => { void clearHistory() }}>
1338
- {tt('history.clear')}
1339
- </button>
1340
- ) : null}
1341
- </header>
1342
-
1343
- <div className={css.historyFilters}>
1344
- <input className={css.historySearch} value={historyQuery} onChange={event => { setHistoryQuery(event.target.value) }} placeholder={tt('history.search')} aria-label={tt('history.search')} />
1345
- <select value={historyModelFilter} onChange={event => { setHistoryModelFilter(event.target.value) }} aria-label={tt('history.model')}>
1346
- <option value="all">{tt('history.allModels')}</option>
1347
- {[...new Set(history.map(entry => entry.model))].map(option => <option key={option} value={option}>{option}</option>)}
1348
- </select>
1349
- <select value={historyRatioFilter} onChange={event => { setHistoryRatioFilter(event.target.value) }} aria-label={tt('history.ratio')}>
1350
- <option value="all">{tt('history.allRatios')}</option>
1351
- {[...new Set(history.map(entry => normalizeSize(entry.size)))].map(option => <option key={option} value={option}>{option}</option>)}
1352
- </select>
1353
- </div>
1354
-
1355
- {filteredHistory.length === 0 ? (
1356
- <div className={css.historyEmpty}>{tt('history.empty')}</div>
1357
- ) : (
1358
- <div className={css.historyList}>
1359
- {filteredHistory.map(entry => (
1360
- <div
1361
- key={entry.id}
1362
- className={css.historyItem}
1363
- data-active={entry.id === viewingHistoryId ? '' : undefined}
1364
- >
1365
- <button
1366
- type="button"
1367
- className={css.historyMain}
1368
- onClick={() => { void viewHistoryEntry(entry) }}
1369
- >
1370
- {entry.images.length > 0 ? (
1371
- <img className={css.historyThumb} src={entry.images[0]!.url} alt="" />
1372
- ) : (
1373
- <span className={css.historyThumbPlaceholder} />
1374
- )}
1375
- <span className={css.historyInfo}>
1376
- <span className={css.historyPrompt}>{entry.prompt}</span>
1377
- <span className={css.historyMeta}>
1378
- {tt(`mode.${entry.mode === 'edit' ? 'edit' : 'text'}` as const)}
1379
- {' · '}{formatTime(entry.createdAt)}
1380
- {' · '}{entry.images.length} {tt('history.images')}
1381
- </span>
1382
- </span>
1383
- </button>
1384
- <span className={css.historyActions}>
1385
- {entry.images.length > 0 ? (
1386
1597
  <button
1387
1598
  type="button"
1388
- className={css.historyAction}
1389
- disabled={galleryAdding}
1390
- title={tt('gallery.add')}
1391
- onClick={() => { void addHistoryEntryToGallery(entry) }}
1599
+ className={css.conversationAdd}
1600
+ title={tt('conversation.add')}
1601
+ disabled={addingToConversation !== null}
1602
+ onClick={(event) => { event.stopPropagation(); void addImageToConversation(image, index) }}
1392
1603
  >
1393
- {tt('gallery.add')}
1604
+ <svg viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M3 4.5h10v7H3z"/><path d="M5.5 2.5h5M8 6v4M6 8h4"/></svg>
1605
+ {addingToConversation === index ? tt('conversation.adding') : tt('conversation.add')}
1394
1606
  </button>
1395
- ) : null}
1396
- <button type="button" className={css.historyAction} onClick={() => { void restoreHistoryEntry(entry) }}>
1397
- {tt('history.restore')}
1398
- </button>
1399
- <button type="button" className={css.historyAction} data-danger onClick={() => { void deleteHistoryEntry(entry.id) }}>
1400
- {tt('history.delete')}
1401
- </button>
1402
- </span>
1403
- </div>
1404
- ))}
1405
- </div>
1406
- )}
1407
- </aside>
1408
- )}
1409
- </div>
1410
-
1411
- {/* ------------------------------------------------ template library */}
1412
- {libraryOpen ? (
1413
- <TemplateLibrary
1414
- api={api}
1415
- onClose={() => { setLibraryOpen(false) }}
1416
- onUse={(text) => {
1417
- setTab('text')
1418
- setPrompt(text)
1419
- setError(null)
1420
- setLibraryOpen(false)
1421
- }}
1422
- />
1423
- ) : null}
1424
-
1425
- {configGuide !== null ? (
1426
- <div className={css.configGuide} role="dialog" aria-modal="true" aria-label={tt(`config.${configGuide}Title` as never)}>
1427
- <div className={css.configGuideBody}>
1428
- <strong>{tt(`config.${configGuide}Title` as never)}</strong>
1429
- <span>{tt(`config.${configGuide}Hint` as never)}</span>
1430
- <button type="button" onClick={() => { setConfigGuide(null) }}>{tt('preview.close')}</button>
1431
- </div>
1607
+ <a
1608
+ className={css.download}
1609
+ href={srcOf(image)}
1610
+ download={`dsh-image-${index + 1}.${extensionOf(image.mime)}`}
1611
+ onClick={(event) => { event.stopPropagation() }}
1612
+ >
1613
+ {tt('download')}
1614
+ </a>
1615
+ </figure>
1616
+ ))}
1617
+ </div>
1618
+ </div>
1619
+ ) : null}
1620
+ </section>
1432
1621
  </div>
1433
- ) : null}
1434
1622
 
1435
- {comparisonFullscreen && comparison !== null ? createPortal(
1436
- <div className={css.comparisonFullscreen} role="dialog" aria-modal="true" aria-label={tt('compare.title')} onClick={() => { setComparisonFullscreen(false) }}>
1437
- <button type="button" className={css.lightboxClose} aria-label={tt('preview.close')} onClick={() => { setComparisonFullscreen(false) }}>×</button>
1438
- <div className={css.comparisonFullscreenGrid} onClick={event => { event.stopPropagation() }}>
1439
- {comparisonResults.map(task => (
1440
- <figure key={task.id}><figcaption>{task.request.model}</figcaption>{task.result!.images.map((image, index) => <img key={index} src={srcOf(image)} alt={task.request.model} />)}</figure>
1441
- ))}
1442
- </div>
1443
- </div>, document.body) : null}
1623
+ </div>
1444
1624
 
1445
- {/* -------------------------------------------------- preview overlay */}
1446
- {preview !== null && previewImage !== null
1447
- ? createPortal(
1448
- <div
1449
- className={css.lightbox}
1450
- role="dialog"
1451
- aria-modal="true"
1452
- aria-label={tt('preview.title')}
1453
- onClick={closePreview}
1454
- >
1455
- <button type="button" className={css.lightboxClose} aria-label={tt('preview.close')} title={tt('preview.close')} onClick={closePreview}>
1456
- <svg viewBox="0 0 16 16" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" aria-hidden="true"><path d="M4 4l8 8M12 4l-8 8"/></svg>
1457
- </button>
1458
- {preview.images.length > 1 ? (
1459
- <>
1460
- <button type="button" className={css.lightboxNav} data-dir="prev" aria-label={tt('preview.prev')} onClick={(event) => { event.stopPropagation(); stepPreview(-1) }}>
1461
- <svg viewBox="0 0 16 16" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M10 3l-5 5 5 5"/></svg>
1462
- </button>
1463
- <button type="button" className={css.lightboxNav} data-dir="next" aria-label={tt('preview.next')} onClick={(event) => { event.stopPropagation(); stepPreview(1) }}>
1464
- <svg viewBox="0 0 16 16" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M6 3l5 5-5 5"/></svg>
1465
- </button>
1466
- </>
1467
- ) : null}
1468
- <figure className={css.lightboxFigure} onClick={(event) => { event.stopPropagation() }}>
1469
- <div
1470
- ref={previewStage}
1471
- className={css.lightboxStage}
1472
- onWheel={(event) => {
1473
- event.preventDefault()
1474
- setPreviewScale(current => clampPreviewScale(current + (event.deltaY < 0 ? PREVIEW_SCALE_STEP : -PREVIEW_SCALE_STEP)))
1475
- }}
1476
- >
1477
- <div
1478
- className={css.lightboxScaleFrame}
1479
- style={{ width: `${previewFrameScale * 100}%`, height: `${previewFrameScale * 100}%` }}
1480
- >
1481
- <img
1482
- className={css.lightboxImage}
1483
- style={{ width: `${previewImageScale * 100}%`, height: `${previewImageScale * 100}%` }}
1484
- src={srcOf(previewImage)}
1485
- alt={previewImage.revisedPrompt ?? tt('preview.title')}
1486
- />
1487
- </div>
1488
- </div>
1489
- <div className={css.lightboxTools} role="group" aria-label={tt('preview.zoomControls')}>
1490
- <button type="button" className={css.lightboxTool} aria-label={tt('preview.zoomOut')} title={tt('preview.zoomOut')} onClick={() => { setPreviewScale(current => clampPreviewScale(current - PREVIEW_SCALE_STEP)) }}>
1491
- <svg viewBox="0 0 16 16" width="17" height="17" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" aria-hidden="true"><circle cx="7" cy="7" r="4.2"/><path d="M4.8 7h4.4M13 13l-2.8-2.8"/></svg>
1492
- </button>
1493
- <button type="button" className={css.lightboxZoomLevel} aria-label={tt('preview.zoomReset')} title={tt('preview.zoomReset')} onClick={() => { setPreviewScale(1) }}>
1494
- {tt('preview.zoomLevel', { percent: Math.round(previewScale * 100) })}
1495
- </button>
1496
- <button type="button" className={css.lightboxTool} aria-label={tt('preview.zoomIn')} title={tt('preview.zoomIn')} onClick={() => { setPreviewScale(current => clampPreviewScale(current + PREVIEW_SCALE_STEP)) }}>
1497
- <svg viewBox="0 0 16 16" width="17" height="17" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" aria-hidden="true"><circle cx="7" cy="7" r="4.2"/><path d="M7 4.8v4.4M4.8 7h4.4M13 13l-2.8-2.8"/></svg>
1498
- </button>
1499
- </div>
1500
- {previewImage.revisedPrompt !== undefined ? (
1501
- <div className={css.lightboxCaptionRow}>
1502
- <figcaption className={css.lightboxCaption} title={previewImage.revisedPrompt}>
1503
- {tt('revisedPrompt', { prompt: previewImage.revisedPrompt })}
1504
- </figcaption>
1505
- <button type="button" className={css.lightboxCopy} aria-label={tt(promptCopied ? 'preview.copied' : 'preview.copyPrompt')} title={tt(promptCopied ? 'preview.copied' : 'preview.copyPrompt')} onClick={() => { void copyPreviewPrompt(previewImage.revisedPrompt!) }}>
1506
- {promptCopied ? (
1507
- <svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M3 8l3 3 7-7"/></svg>
1508
- ) : (
1509
- <svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><rect x="5" y="5" width="7" height="8" rx="1"/><path d="M3 10V3.8c0-.44.36-.8.8-.8H9"/></svg>
1510
- )}
1511
- <span>{tt(promptCopied ? 'preview.copied' : 'preview.copyPrompt')}</span>
1512
- </button>
1513
- </div>
1514
- ) : null}
1515
- <div className={css.lightboxMeta}>
1516
- <span className={css.lightboxIndex}>{tt('preview.index', { index: preview.index + 1, total: preview.images.length })}</span>
1517
- <span className={css.lightboxActions}>
1518
- <button type="button" className={css.lightboxEdit} disabled={galleryAdding} onClick={() => { void addToGallery(previewImage) }}>
1519
- {tt('gallery.add')}
1520
- </button>
1521
- <button type="button" className={css.lightboxEdit} onClick={addPreviewToEdit}>
1522
- {tt('preview.addToEdit')}
1523
- </button>
1524
- <a
1525
- className={css.lightboxDownload}
1526
- href={srcOf(previewImage)}
1527
- download={`dsh-image-${preview.index + 1}.${extensionOf(previewImage.mime)}`}
1528
- >
1529
- {tt('download')}
1530
- </a>
1531
- </span>
1532
- </div>
1533
- </figure>
1534
- </div>,
1535
- document.body,
1536
- )
1625
+ {sidebarHistoryHost !== null && historyPanel !== null
1626
+ ? createPortal(historyPanel, sidebarHistoryHost)
1537
1627
  : null}
1538
1628
 
1539
- {/* ------------------------------------------------- gallery toast */}
1629
+ {/* ------------------------------------------------ template library */}
1630
+ {libraryOpen ? (
1631
+ <TemplateLibrary
1632
+ api={api}
1633
+ onClose={() => { setLibraryOpen(false) }}
1634
+ onUse={(text) => {
1635
+ setTab('text')
1636
+ setPrompt(text)
1637
+ setError(null)
1638
+ setLibraryOpen(false)
1639
+ }}
1640
+ />
1641
+ ) : null}
1642
+
1643
+ {configGuide !== null ? (
1644
+ <div className={css.configGuide} role="dialog" aria-modal="true" aria-label={tt(`config.${configGuide}Title` as never)}>
1645
+ <div className={css.configGuideBody}>
1646
+ <strong>{tt(`config.${configGuide}Title` as never)}</strong>
1647
+ <span>{tt(`config.${configGuide}Hint` as never)}</span>
1648
+ <button type="button" onClick={() => { setConfigGuide(null) }}>{tt('preview.close')}</button>
1649
+ </div>
1650
+ </div>
1651
+ ) : null}
1652
+
1653
+ {comparisonFullscreen && comparison !== null ? createPortal(
1654
+ <div className={css.comparisonFullscreen} role="dialog" aria-modal="true" aria-label={tt('compare.title')} onClick={() => { setComparisonFullscreen(false) }}>
1655
+ <button type="button" className={css.lightboxClose} aria-label={tt('preview.close')} onClick={() => { setComparisonFullscreen(false) }}>×</button>
1656
+ <div className={css.comparisonFullscreenGrid} onClick={event => { event.stopPropagation() }}>
1657
+ {comparisonResults.map(task => (
1658
+ <figure key={task.id}><figcaption>{task.request.model}</figcaption>{task.result!.images.map((image, index) => <img key={index} src={srcOf(image)} alt={task.request.model} />)}</figure>
1659
+ ))}
1660
+ </div>
1661
+ </div>, document.body) : null}
1662
+
1663
+ {/* -------------------------------------------------- preview overlay */}
1664
+ {preview !== null && previewImage !== null
1665
+ ? createPortal(
1666
+ <div
1667
+ className={css.lightbox}
1668
+ role="dialog"
1669
+ aria-modal="true"
1670
+ aria-label={tt('preview.title')}
1671
+ onClick={closePreview}
1672
+ >
1673
+ <button type="button" className={css.lightboxClose} aria-label={tt('preview.close')} title={tt('preview.close')} onClick={closePreview}>
1674
+ <svg viewBox="0 0 16 16" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" aria-hidden="true"><path d="M4 4l8 8M12 4l-8 8"/></svg>
1675
+ </button>
1676
+ {preview.images.length > 1 ? (
1677
+ <>
1678
+ <button type="button" className={css.lightboxNav} data-dir="prev" aria-label={tt('preview.prev')} onClick={(event) => { event.stopPropagation(); stepPreview(-1) }}>
1679
+ <svg viewBox="0 0 16 16" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M10 3l-5 5 5 5"/></svg>
1680
+ </button>
1681
+ <button type="button" className={css.lightboxNav} data-dir="next" aria-label={tt('preview.next')} onClick={(event) => { event.stopPropagation(); stepPreview(1) }}>
1682
+ <svg viewBox="0 0 16 16" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M6 3l5 5-5 5"/></svg>
1683
+ </button>
1684
+ </>
1685
+ ) : null}
1686
+ <figure className={css.lightboxFigure} onClick={(event) => { event.stopPropagation() }}>
1687
+ <div
1688
+ ref={previewStage}
1689
+ className={css.lightboxStage}
1690
+ onWheel={(event) => {
1691
+ event.preventDefault()
1692
+ setPreviewScale(current => clampPreviewScale(current + (event.deltaY < 0 ? PREVIEW_SCALE_STEP : -PREVIEW_SCALE_STEP)))
1693
+ }}
1694
+ >
1695
+ <div
1696
+ className={css.lightboxScaleFrame}
1697
+ style={{ width: `${previewFrameScale * 100}%`, height: `${previewFrameScale * 100}%` }}
1698
+ >
1699
+ <img
1700
+ className={css.lightboxImage}
1701
+ style={{ width: `${previewImageScale * 100}%`, height: `${previewImageScale * 100}%` }}
1702
+ src={srcOf(previewImage)}
1703
+ alt={previewImage.revisedPrompt ?? tt('preview.title')}
1704
+ />
1705
+ </div>
1706
+ </div>
1707
+ <div className={css.lightboxTools} role="group" aria-label={tt('preview.zoomControls')}>
1708
+ <button type="button" className={css.lightboxTool} aria-label={tt('preview.zoomOut')} title={tt('preview.zoomOut')} onClick={() => { setPreviewScale(current => clampPreviewScale(current - PREVIEW_SCALE_STEP)) }}>
1709
+ <svg viewBox="0 0 16 16" width="17" height="17" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" aria-hidden="true"><circle cx="7" cy="7" r="4.2"/><path d="M4.8 7h4.4M13 13l-2.8-2.8"/></svg>
1710
+ </button>
1711
+ <button type="button" className={css.lightboxZoomLevel} aria-label={tt('preview.zoomReset')} title={tt('preview.zoomReset')} onClick={() => { setPreviewScale(1) }}>
1712
+ {tt('preview.zoomLevel', { percent: Math.round(previewScale * 100) })}
1713
+ </button>
1714
+ <button type="button" className={css.lightboxTool} aria-label={tt('preview.zoomIn')} title={tt('preview.zoomIn')} onClick={() => { setPreviewScale(current => clampPreviewScale(current + PREVIEW_SCALE_STEP)) }}>
1715
+ <svg viewBox="0 0 16 16" width="17" height="17" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" aria-hidden="true"><circle cx="7" cy="7" r="4.2"/><path d="M7 4.8v4.4M4.8 7h4.4M13 13l-2.8-2.8"/></svg>
1716
+ </button>
1717
+ </div>
1718
+ {previewImage.revisedPrompt !== undefined ? (
1719
+ <div className={css.lightboxCaptionRow}>
1720
+ <figcaption className={css.lightboxCaption} title={previewImage.revisedPrompt}>
1721
+ {tt('revisedPrompt', { prompt: previewImage.revisedPrompt })}
1722
+ </figcaption>
1723
+ <button type="button" className={css.lightboxCopy} aria-label={tt(promptCopied ? 'preview.copied' : 'preview.copyPrompt')} title={tt(promptCopied ? 'preview.copied' : 'preview.copyPrompt')} onClick={() => { void copyPreviewPrompt(previewImage.revisedPrompt!) }}>
1724
+ {promptCopied ? (
1725
+ <svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M3 8l3 3 7-7"/></svg>
1726
+ ) : (
1727
+ <svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><rect x="5" y="5" width="7" height="8" rx="1"/><path d="M3 10V3.8c0-.44.36-.8.8-.8H9"/></svg>
1728
+ )}
1729
+ <span>{tt(promptCopied ? 'preview.copied' : 'preview.copyPrompt')}</span>
1730
+ </button>
1731
+ </div>
1732
+ ) : null}
1733
+ <div className={css.lightboxMeta}>
1734
+ <span className={css.lightboxIndex}>{tt('preview.index', { index: preview.index + 1, total: preview.images.length })}</span>
1735
+ <span className={css.lightboxActions}>
1736
+ <button type="button" className={css.lightboxEdit} disabled={addingToConversation !== null} onClick={() => { void addImageToConversation(previewImage, preview.index) }}>
1737
+ {addingToConversation === preview.index ? tt('conversation.adding') : tt('conversation.add')}
1738
+ </button>
1739
+ <button type="button" className={css.lightboxEdit} disabled={galleryAdding} onClick={() => { void addToGallery(previewImage) }}>
1740
+ {tt('gallery.add')}
1741
+ </button>
1742
+ <button type="button" className={css.lightboxEdit} onClick={addPreviewToEdit}>
1743
+ {tt('preview.addToEdit')}
1744
+ </button>
1745
+ <a
1746
+ className={css.lightboxDownload}
1747
+ href={srcOf(previewImage)}
1748
+ download={`dsh-image-${preview.index + 1}.${extensionOf(previewImage.mime)}`}
1749
+ >
1750
+ {tt('download')}
1751
+ </a>
1752
+ </span>
1753
+ </div>
1754
+ </figure>
1755
+ </div>,
1756
+ document.body,
1757
+ )
1758
+ : null}
1759
+
1760
+ {/* ------------------------------------------------- gallery toast */}
1540
1761
  {galleryMessage !== null ? (
1541
1762
  <div className={css.galleryToast} role="status">
1542
- <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><rect x="2.5" y="3" width="11" height="10" rx="1.5"/><path d="M8 5.8v4.4M5.8 8h4.4"/></svg>
1763
+ <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><rect x="2.5" y="3" width="11" height="10" rx="1.5"/><path d="M8 5.8v4.4M5.8 8h4.4"/></svg>
1543
1764
  {galleryMessage}
1544
1765
  </div>
1545
1766
  ) : null}
1767
+ {conversationMessage !== null ? (
1768
+ <div className={css.conversationToast} role="status">
1769
+ <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M3 4.5h10v7H3z"/><path d="M5.5 2.5h5M8 6v4M6 8h4"/></svg>
1770
+ {conversationMessage}
1771
+ </div>
1772
+ ) : null}
1546
1773
  </div>
1547
- )
1548
- }
1549
-
1550
- /** File extension for a MIME type (download filenames). */
1551
- function extensionOf(mime: string): string {
1552
- switch (mime.split(';')[0]!.trim()) {
1553
- case 'image/jpeg': return 'jpg'
1554
- case 'image/webp': return 'webp'
1555
- case 'image/gif': return 'gif'
1556
- default: return 'png'
1557
- }
1558
- }
1774
+ )
1775
+ }
1776
+
1777
+ /** File extension for a MIME type (download filenames). */
1778
+ function extensionOf(mime: string): string {
1779
+ switch (mime.split(';')[0]!.trim()) {
1780
+ case 'image/jpeg': return 'jpg'
1781
+ case 'image/webp': return 'webp'
1782
+ case 'image/gif': return 'gif'
1783
+ default: return 'png'
1784
+ }
1785
+ }