tavern-harness 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,70 @@
3
3
  > 本文件由 `scripts/changelog.mjs` 从 `changelog/v*.md` 生成,请勿手动编辑。
4
4
  > 版本对比链接见文末;源文件位于仓库 `changelog/` 目录。
5
5
 
6
+ ## [0.2.2] - 2026-11-21
7
+
8
+ ### 中文
9
+
10
+ #### 修复
11
+
12
+ - 设置页的 API Key 输入框不再被浏览器或密码管理器自动填入已保存的账号密码
13
+ - 服务商卡片上的「文本服务 / 语音服务」状态标签不再折行,服务商名称再长也能保持单行显示
14
+
15
+ ### English
16
+
17
+ #### Fixed
18
+
19
+ - The API Key field in Settings is no longer autofilled with saved credentials by browsers or password managers
20
+ - The "Text / Voice" status tag on provider cards no longer wraps, so it stays on one line even with long provider names
21
+
22
+ ## [0.2.1] - 2026-11-21
23
+
24
+ ### 中文
25
+
26
+ #### 新增
27
+
28
+ - 新增内置「生成图片」技能:在设置中添加「百炼 Token Plan」生图供应商并选定默认模型(qwen-image-3.0-pro / qwen-image-2.0-pro / qwen-image-2.0 / wan2.7-image / wan2.7-image-pro)后,角色即可按提示词生成图片,图片保存到工作区 `images/` 目录并自动打开预览
29
+ - 角色创建与更新技能支持 `avatar_path`:酒馆助手可以从工作区的 PNG / JPEG / WebP / BMP / AVIF 图片生成或清空角色头像,保存前会校验图片真实格式并压缩到存储上限
30
+ - 对话中的图片附件改为缩略图卡片,点击即可放大查看
31
+
32
+ #### 改进
33
+
34
+ - 生成的图片文件名改为根据提示词或指定文件名生成的可读名称,并自动追加时间戳与正确的扩展名,不再是一串 `generated-数字`
35
+
36
+ #### 修复
37
+
38
+ - 修复图片预览弹窗缩放后无法平移、大图看不全的问题;图片现在按窗口自适应缩放,超出窗口时可在横向与纵向滚动,并保持居中
39
+ - 修复输入框内边距在不同屏幕宽度下不一致的问题
40
+
41
+ #### 内部
42
+
43
+ - 新增 `imageGeneration`、`imageFilename` 模块,并为生成图片文件名补充测试
44
+ - 持久化服务新增 `/image/generate` 端点,代理百炼 Token Plan 生图请求并下载结果;数据库升级至 v14,新增 `imageProviders` 表
45
+ - 沙箱服务新增二进制文件写入端点(上限 8MB),图片预览与 base64 写入端点纳入同源代理
46
+
47
+ ### English
48
+
49
+ #### Added
50
+
51
+ - Built-in Generate Image skill: after adding a Bailian Token Plan image provider in Settings and choosing a default model (qwen-image-3.0-pro, qwen-image-2.0-pro, qwen-image-2.0, wan2.7-image, wan2.7-image-pro), characters can generate images from prompts; images are saved to the workspace `images/` folder and opened in a preview automatically
52
+ - Character create/update skills accept `avatar_path`: the Tavern Keeper can set or clear a character avatar from a PNG, JPEG, WebP, BMP, or AVIF file in the workspace, with real format validation and compression before saving
53
+ - Image attachments in conversations are now thumbnail cards that open a larger preview on click
54
+
55
+ #### Changed
56
+
57
+ - Generated images now get readable file names derived from the prompt or a requested filename, with a timestamp and the correct extension, instead of `generated-<number>`
58
+
59
+ #### Fixed
60
+
61
+ - Fixed the image preview being impossible to pan after zooming; images now fit the window, scroll horizontally and vertically when larger, and stay centered
62
+ - Fixed inconsistent composer padding across screen widths
63
+
64
+ #### Internal
65
+
66
+ - Added the `imageGeneration` and `imageFilename` modules, with tests for generated image filenames
67
+ - The persistence service gained an `/image/generate` endpoint that proxies Bailian Token Plan requests and downloads the result; the database moved to v14 with a new `imageProviders` table
68
+ - The sandbox service gained a binary file-write endpoint (8MB limit), and the preview/base64 write endpoints are covered by the same-origin proxy
69
+
6
70
  ## [0.2.0] - 2026-11-20
7
71
 
8
72
  ### 中文
@@ -1031,6 +1095,8 @@
1031
1095
  - Vite + React + Zustand + Dexie stack with browser-side local persistence
1032
1096
 
1033
1097
  <!-- 链接定义 -->
1098
+ [0.2.2]: https://github.com/Rannichan/Tavern-Harness/compare/v0.2.1...v0.2.2
1099
+ [0.2.1]: https://github.com/Rannichan/Tavern-Harness/compare/v0.2.0...v0.2.1
1034
1100
  [0.2.0]: https://github.com/Rannichan/Tavern-Harness/compare/v0.1.33...v0.2.0
1035
1101
  [0.1.33]: https://github.com/Rannichan/Tavern-Harness/compare/v0.1.32...v0.1.33
1036
1102
  [0.1.32]: https://github.com/Rannichan/Tavern-Harness/compare/v0.1.31...v0.1.32
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tavern-harness",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "Tavern Harness — 酒馆模式下的本地 AI Agent 助手(MyAgent-Android 的 Web 复刻)",
5
5
  "private": false,
6
6
  "type": "module",
@@ -195,7 +195,7 @@ const listRecordsByJsonField = database.prepare(`
195
195
  const listStartupRecords = database.prepare(`
196
196
  SELECT collection, record_key, value_json, updated_at
197
197
  FROM app_records
198
- WHERE collection IN ('settings', 'providers', 'voiceProviders', 'npcs', 'sessions', 'worldBooks', 'tools', 'achievementUnlocks')
198
+ WHERE collection IN ('settings', 'providers', 'voiceProviders', 'imageProviders', 'npcs', 'sessions', 'worldBooks', 'tools', 'achievementUnlocks')
199
199
  ORDER BY collection, record_key
200
200
  `);
201
201
  const deleteRecord = database.prepare('DELETE FROM app_records WHERE collection = ? AND record_key = ?');
@@ -290,6 +290,7 @@ const server = createServer(async (req, res) => {
290
290
  settings: [],
291
291
  providers: [],
292
292
  voiceProviders: [],
293
+ imageProviders: [],
293
294
  npcs: [],
294
295
  sessions: [],
295
296
  worldBooks: [],
@@ -306,6 +307,64 @@ const server = createServer(async (req, res) => {
306
307
  json(res, 200, { ok: true, lock: lockState(clientId), collections });
307
308
  return;
308
309
  }
310
+ if (pathname === '/image/generate') {
311
+ const providerId = Number(body.providerId);
312
+ const prompt = typeof body.prompt === 'string' ? body.prompt.trim() : '';
313
+ const model = typeof body.model === 'string' ? body.model.trim() : '';
314
+ const size = typeof body.size === 'string' ? body.size.trim() : '1024*1024';
315
+ if (!Number.isInteger(providerId) || providerId <= 0 || !prompt || prompt.length > 10_000 || !model || !/^\d{2,5}\*\d{2,5}$/.test(size)) {
316
+ json(res, 400, { ok: false, message: 'Invalid image generation request' });
317
+ return;
318
+ }
319
+ const record = getRecord.get('imageProviders', String(providerId));
320
+ if (!record) {
321
+ json(res, 404, { ok: false, message: 'Image provider not found' });
322
+ return;
323
+ }
324
+ const provider = JSON.parse(record.value_json);
325
+ const apiKey = typeof provider.apiKey === 'string' ? provider.apiKey.trim() : '';
326
+ if (!provider.isEnabled || provider.kind !== 'bailian-token-plan' || !apiKey) {
327
+ json(res, 400, { ok: false, message: 'Image provider is unavailable' });
328
+ return;
329
+ }
330
+ const upstream = await fetch('https://token-plan.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation', {
331
+ method: 'POST',
332
+ headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
333
+ body: JSON.stringify({
334
+ model,
335
+ input: { messages: [{ role: 'user', content: [{ text: prompt }] }] },
336
+ parameters: { size },
337
+ }),
338
+ signal: AbortSignal.timeout(180_000),
339
+ });
340
+ const payload = await upstream.json().catch(() => null);
341
+ if (!upstream.ok) {
342
+ const upstreamMessage = payload?.message ?? payload?.error?.message ?? payload?.code;
343
+ json(res, upstream.status, { ok: false, message: upstreamMessage ? `Image service error: ${upstreamMessage}` : `Image service returned HTTP ${upstream.status}` });
344
+ return;
345
+ }
346
+ const imageUrl = payload?.output?.choices?.[0]?.message?.content?.[0]?.image;
347
+ if (typeof imageUrl !== 'string' || !/^https?:\/\//i.test(imageUrl)) {
348
+ json(res, 502, { ok: false, message: 'Image service did not return a valid image URL' });
349
+ return;
350
+ }
351
+ const imageResponse = await fetch(imageUrl, { signal: AbortSignal.timeout(120_000) });
352
+ if (!imageResponse.ok) {
353
+ imageResponse.body?.cancel();
354
+ json(res, 502, { ok: false, message: `Unable to download generated image (HTTP ${imageResponse.status})` });
355
+ return;
356
+ }
357
+ const image = Buffer.from(await imageResponse.arrayBuffer());
358
+ const mimeType = imageResponse.headers.get('content-type')?.split(';')[0] || 'image/png';
359
+ json(res, 200, {
360
+ ok: true,
361
+ dataUrl: `data:${mimeType};base64,${image.toString('base64')}`,
362
+ mimeType,
363
+ width: payload?.usage?.width ?? null,
364
+ height: payload?.usage?.height ?? null,
365
+ });
366
+ return;
367
+ }
309
368
  if (pathname === '/voice/synthesize' || pathname === '/voice/preview') {
310
369
  const voiceId = typeof body.voiceId === 'string' ? body.voiceId : '';
311
370
  const text = typeof body.text === 'string' ? body.text.trim() : '';
@@ -611,10 +611,10 @@ const server = createServer(async (req, res) => {
611
611
  }
612
612
 
613
613
  // ---- 真实文件工作区端点(file_read / file_write / file_delete / file_list) ----
614
- if (req.url === '/file_read' || req.url === '/file_write' || req.url === '/file_delete' || req.url === '/file_list') {
614
+ if (req.url === '/file_read' || req.url === '/file_write' || req.url === '/file_write_base64' || req.url === '/file_delete' || req.url === '/file_list') {
615
615
  let body = '';
616
616
  for await (const chunk of req) body += chunk;
617
- if (body.length > 512 * 1024) {
617
+ if (body.length > (req.url === '/file_write_base64' ? 12 * 1024 * 1024 : 512 * 1024)) {
618
618
  res.writeHead(413);
619
619
  res.end(JSON.stringify({ ok: false, message: 'body too large' }));
620
620
  return;
@@ -640,10 +640,11 @@ const server = createServer(async (req, res) => {
640
640
  const fp = resolve(base, rel);
641
641
  const text = await readFileAsync(fp);
642
642
  res.end(JSON.stringify({ ok: true, path: rel, content: text.slice(0, MAX_FILE_READ_CHARS) }));
643
- } else if (req.url === '/file_write') {
643
+ } else if (req.url === '/file_write' || req.url === '/file_write_base64') {
644
644
  const rawPath = String(payload?.path ?? '').replace(/\\/g, '/').trim();
645
645
  if (!rawPath) throw new Error('Invalid path');
646
- const mode = payload?.mode === 'append' ? 'append' : 'write';
646
+ const binary = req.url === '/file_write_base64';
647
+ const mode = binary ? 'write' : payload?.mode === 'append' ? 'append' : 'write';
647
648
  const content = String(payload?.content ?? '');
648
649
  ensureSessionBase(base);
649
650
  const rel = sanitizeWorkspaceRelativePath(rawPath);
@@ -655,16 +656,18 @@ const server = createServer(async (req, res) => {
655
656
  mkdirSync(dirname(fp), { recursive: true });
656
657
  assertInside(base, realpathSync(dirname(fp)));
657
658
  if (existsSync(fp)) assertInside(base, realpathSync(fp));
658
- if (Buffer.byteLength(content, 'utf8') > MAX_FILE_WRITE_BYTES) {
659
- throw new Error(`File exceeds the ${MAX_FILE_WRITE_BYTES / 1024}KB limit`);
659
+ const fileContent = binary ? Buffer.from(content, 'base64') : content;
660
+ const bytes = binary ? fileContent.length : Buffer.byteLength(content, 'utf8');
661
+ if (bytes > (binary ? 8 * 1024 * 1024 : MAX_FILE_WRITE_BYTES)) {
662
+ throw new Error(binary ? 'Binary file exceeds the 8MB limit' : `File exceeds the ${MAX_FILE_WRITE_BYTES / 1024}KB limit`);
660
663
  }
661
664
  if (mode === 'append') {
662
665
  const existing = existsSync(fp) ? await readFilePromise(fp, 'utf8') : '';
663
666
  await writeFilePromise(fp, existing + content, 'utf8');
664
667
  } else {
665
- await writeFilePromise(fp, content, 'utf8');
668
+ await writeFilePromise(fp, fileContent, binary ? undefined : 'utf8');
666
669
  }
667
- res.end(JSON.stringify({ ok: true, path: rel, mode, bytes: Buffer.byteLength(content, 'utf8') }));
670
+ res.end(JSON.stringify({ ok: true, path: rel, mode, bytes }));
668
671
  } else if (req.url === '/file_delete') {
669
672
  const rawPath = String(payload?.path ?? '').replace(/\\/g, '/').trim();
670
673
  if (!rawPath) throw new Error('Invalid path');
@@ -559,7 +559,7 @@ function MessageBubble({
559
559
  {msg.attachments.length > 0 && (
560
560
  <div className="attachments">
561
561
  {msg.attachments.map((a, i) => (
562
- <AttachCard key={i} name={msg.attachmentInfos?.[i]?.displayName || attachmentName(a)} />
562
+ <AttachCard key={i} src={a} name={msg.attachmentInfos?.[i]?.displayName || attachmentName(a)} />
563
563
  ))}
564
564
  </div>
565
565
  )}
@@ -656,6 +656,7 @@ function MessageEditorModal({
656
656
  {attachments.map((a, i) => (
657
657
  <AttachCard
658
658
  key={i}
659
+ src={a.dataUrl}
659
660
  name={a.name}
660
661
  onRemove={() => setAttachments(attachments.filter((_, j) => j !== i))}
661
662
  />
@@ -718,7 +719,7 @@ function UserBubble({ msg, session, userPersonaName, loopIndex }: { msg: ChatMes
718
719
  {msg.attachments.length > 0 && (
719
720
  <div className="attachments">
720
721
  {msg.attachments.map((a, i) => (
721
- <AttachCard key={i} name={msg.attachmentInfos?.[i]?.displayName || attachmentName(a)} />
722
+ <AttachCard key={i} src={a} name={msg.attachmentInfos?.[i]?.displayName || attachmentName(a)} />
722
723
  ))}
723
724
  </div>
724
725
  )}
@@ -994,6 +995,7 @@ export function ChatInput({ sessionId }: { sessionId: number }) {
994
995
  {attachments.map((a, i) => (
995
996
  <AttachCard
996
997
  key={i}
998
+ src={a.dataUrl}
997
999
  name={a.name}
998
1000
  onRemove={() => setAttachments(attachments.filter((_, j) => j !== i))}
999
1001
  />
@@ -33,7 +33,7 @@ const PIP_RECT_STORAGE_KEY = 'tav-file-display-pip-rect';
33
33
  const PREVIEW_ZOOMS_STORAGE_KEY = 'tav-file-display-preview-zooms';
34
34
  const PIP_REFRESH_INTERVAL = 1000;
35
35
 
36
- type PreviewZoomKind = 'html';
36
+ type PreviewZoomKind = 'html' | 'image';
37
37
 
38
38
  interface PipRect {
39
39
  x: number;
@@ -151,11 +151,20 @@ export function FileDisplayModal() {
151
151
  const [workspaceDir, setWorkspaceDir] = useState<string | null>(null);
152
152
  const [loadState, setLoadState] = useState<'loading' | 'ok' | 'error'>('loading');
153
153
  const [htmlZoom, setHtmlZoom] = useState(1);
154
+ const [imageZoom, setImageZoom] = useState(1);
155
+ const [imageLoadVersion, setImageLoadVersion] = useState(0);
156
+ const [imageLayout, setImageLayout] = useState<{
157
+ width: number;
158
+ height: number;
159
+ overflowX: boolean;
160
+ overflowY: boolean;
161
+ } | null>(null);
154
162
  const [htmlPreviewVersion, setHtmlPreviewVersion] = useState(0);
155
163
  const [textWrap, setTextWrap] = useState(true);
156
164
  const [isPictureInPicture, setIsPictureInPicture] = useState(true);
157
165
  const [pipRect, setPipRect] = useState<PipRect>(createPipRect);
158
166
  const contentRef = useRef<string | null>(null);
167
+ const imageViewportRef = useRef<HTMLDivElement | null>(null);
159
168
  const wasDisplayOpenRef = useRef(false);
160
169
  const pipGestureRef = useRef<
161
170
  | { type: 'move'; pointerX: number; pointerY: number; startX: number; startY: number }
@@ -195,8 +204,51 @@ export function FileDisplayModal() {
195
204
  setIsPictureInPicture(opensInPictureInPicture);
196
205
  }
197
206
  setHtmlZoom(active.kind === 'html' ? restorePreviewZoom('html', active.path, 1) : 1);
207
+ setImageZoom(active.kind === 'image' ? restorePreviewZoom('image', active.path, 1) : 1);
208
+ setImageLoadVersion(0);
209
+ setImageLayout(null);
198
210
  }, [active]);
199
211
 
212
+ useLayoutEffect(() => {
213
+ if (!active || active.kind !== 'image' || loadState !== 'ok' || !workspaceDir) return;
214
+ const viewport = imageViewportRef.current;
215
+ const image = viewport?.querySelector('img');
216
+ if (!viewport || !image || !image.complete) return;
217
+
218
+ const updateImageViewport = () => {
219
+ const naturalWidth = image.naturalWidth;
220
+ const naturalHeight = image.naturalHeight;
221
+ if (!naturalWidth || !naturalHeight) return;
222
+
223
+ const fitScale = Math.min(1, viewport.clientWidth / naturalWidth, viewport.clientHeight / naturalHeight);
224
+ const width = naturalWidth * fitScale * imageZoom;
225
+ const height = naturalHeight * fitScale * imageZoom;
226
+ const nextLayout = {
227
+ width,
228
+ height,
229
+ overflowX: width > viewport.clientWidth,
230
+ overflowY: height > viewport.clientHeight,
231
+ };
232
+ setImageLayout((current) => current
233
+ && current.width === nextLayout.width
234
+ && current.height === nextLayout.height
235
+ && current.overflowX === nextLayout.overflowX
236
+ && current.overflowY === nextLayout.overflowY
237
+ ? current
238
+ : nextLayout);
239
+ requestAnimationFrame(() => {
240
+ viewport.scrollLeft = Math.max(0, (width - viewport.clientWidth) / 2);
241
+ viewport.scrollTop = Math.max(0, (height - viewport.clientHeight) / 2);
242
+ });
243
+ };
244
+
245
+ updateImageViewport();
246
+ const resizeObserver = new ResizeObserver(updateImageViewport);
247
+ resizeObserver.observe(viewport);
248
+ resizeObserver.observe(image);
249
+ return () => resizeObserver.disconnect();
250
+ }, [active, imageLoadVersion, imageZoom, isPictureInPicture, loadState, workspaceDir]);
251
+
200
252
  useEffect(() => {
201
253
  if (!active || active.kind === 'unsupported' || !isPictureInPicture) return;
202
254
  let cancelled = false;
@@ -374,6 +426,16 @@ export function FileDisplayModal() {
374
426
  const htmlZoomIn = () => updateHtmlZoom((z) => Math.min(2, +(z + 0.1).toFixed(1)));
375
427
  const htmlZoomOut = () => updateHtmlZoom((z) => Math.max(0.5, +(z - 0.1).toFixed(1)));
376
428
  const resetHtmlZoom = () => updateHtmlZoom(() => 1);
429
+ const updateImageZoom = (update: (zoom: number) => number) => {
430
+ setImageZoom((zoom) => {
431
+ const nextZoom = update(zoom);
432
+ persistPreviewZoom('image', active.path, nextZoom);
433
+ return nextZoom;
434
+ });
435
+ };
436
+ const imageZoomIn = () => updateImageZoom((z) => Math.min(3, +(z + 0.1).toFixed(1)));
437
+ const imageZoomOut = () => updateImageZoom((z) => Math.max(0.2, +(z - 0.1).toFixed(1)));
438
+ const resetImageZoom = () => updateImageZoom(() => 1);
377
439
 
378
440
  const renderBody = () => {
379
441
  if (active.kind === 'unsupported') {
@@ -391,6 +453,47 @@ export function FileDisplayModal() {
391
453
  return <div className="display-error">{t('display.fileError', { path: active.path })}</div>;
392
454
  }
393
455
 
456
+ if (active.kind === 'image') {
457
+ if (!workspaceDir) return <div className="display-error">{t('display.fileError', { path: active.path })}</div>;
458
+ return (
459
+ <div className="display-image-wrap">
460
+ <div
461
+ ref={imageViewportRef}
462
+ className="display-image-viewport"
463
+ style={{
464
+ overflowX: imageLayout?.overflowX ? 'auto' : 'hidden',
465
+ overflowY: imageLayout?.overflowY ? 'auto' : 'hidden',
466
+ }}
467
+ >
468
+ <div
469
+ className="display-image-scroll-area"
470
+ style={imageLayout ? { width: imageLayout.width, height: imageLayout.height } : undefined}
471
+ >
472
+ <img
473
+ className="display-image"
474
+ src={previewUrl(active.path, workspaceDir)}
475
+ alt={title}
476
+ style={imageLayout
477
+ ? { width: imageLayout.width, height: imageLayout.height, visibility: 'visible' }
478
+ : { visibility: 'hidden' }}
479
+ onLoad={() => setImageLoadVersion((version) => version + 1)}
480
+ />
481
+ </div>
482
+ </div>
483
+ <div className="display-html-note display-image-note">
484
+ <span />
485
+ {!isPictureInPicture && (
486
+ <span className="display-html-zoom-group">
487
+ <button className="icon-btn" title={t('display.htmlZoomOut')} onClick={imageZoomOut}><Icon name="zoom-out" size={15} /></button>
488
+ <button className="icon-btn" title={t('display.resetHtmlZoom')} onClick={resetImageZoom}>{Math.round(imageZoom * 100)}%</button>
489
+ <button className="icon-btn" title={t('display.htmlZoomIn')} onClick={imageZoomIn}><Icon name="zoom-in" size={15} /></button>
490
+ </span>
491
+ )}
492
+ </div>
493
+ </div>
494
+ );
495
+ }
496
+
394
497
  if (active.kind === 'html') {
395
498
  if (!workspaceDir) return <div className="display-error">{t('display.fileError', { path: active.path })}</div>;
396
499
  return (
@@ -548,7 +651,7 @@ export function parseStoredDisplayRef(json: string | null): DisplayFileRef | nul
548
651
  if (!json) return null;
549
652
  try {
550
653
  const obj = JSON.parse(json) as Partial<DisplayFileRef>;
551
- if (!obj || typeof obj.path !== 'string' || !['text', 'html', 'unsupported'].includes(obj.kind ?? '')) return null;
654
+ if (!obj || typeof obj.path !== 'string' || !['text', 'html', 'image', 'unsupported'].includes(obj.kind ?? '')) return null;
552
655
  return {
553
656
  path: obj.path,
554
657
  kind: obj.kind as DisplayFileRef['kind'],
@@ -2,13 +2,14 @@ import { memo, useEffect, useRef, useState, type PointerEvent as ReactPointerEve
2
2
  import { useStore } from '../store/store';
3
3
  import { db, DEFAULT_GENERATION_SETTINGS } from '../db/database';
4
4
  import { type ThemeMode, type ThemePaletteId } from '../theme/theme';
5
- import { type ApiProvider, type AppLanguage, type ReasoningEffort, type VoiceProvider, type VoiceProviderKind, type VoiceId, enabledModelIds, modelAliases } from '../types/models';
5
+ import { type ApiProvider, type AppLanguage, type ImageProvider, type ImageProviderKind, type ReasoningEffort, type VoiceProvider, type VoiceProviderKind, type VoiceId, enabledModelIds, modelAliases } from '../types/models';
6
6
  import { VOICE_PROVIDER_OPTIONS, previewVoice } from '../core/voice';
7
7
  import { Icon, Modal } from './shared';
8
8
  import { DeleteConfirmDialog } from './DeleteConfirmDialog';
9
9
  import { isNetworkLikeError, toProxyUrl } from '../core/proxy';
10
10
  import { useT } from '../core/i18n';
11
11
  import { APP_VERSION, useHasUnseenVersion } from '../core/version';
12
+ import { IMAGE_MODELS } from '../core/imageGeneration';
12
13
  import { VersionHistoryModal } from './VersionHistoryModal';
13
14
 
14
15
  // ============================================================
@@ -26,6 +27,8 @@ export const SettingsView = memo(function SettingsView() {
26
27
  const refreshProviders = useStore((s) => s.refreshProviders);
27
28
  const voiceProviders = useStore((s) => s.voiceProviders);
28
29
  const refreshVoiceProviders = useStore((s) => s.refreshVoiceProviders);
30
+ const imageProviders = useStore((s) => s.imageProviders);
31
+ const refreshImageProviders = useStore((s) => s.refreshImageProviders);
29
32
  const [tab, setTab] = useState<SettingsTab>('api');
30
33
  const [showResetConfirm, setShowResetConfirm] = useState(false);
31
34
  const [resetting, setResetting] = useState(false);
@@ -132,6 +135,7 @@ export const SettingsView = memo(function SettingsView() {
132
135
  <div className="settings-tab-panel" data-active={tab === 'api' ? 'true' : 'false'} role="tabpanel">
133
136
  <ProviderManager providers={providers} onChanged={refreshProviders} />
134
137
  <VoiceProviderManager providers={voiceProviders} onChanged={refreshVoiceProviders} />
138
+ <ImageProviderManager providers={imageProviders} onChanged={refreshImageProviders} />
135
139
  </div>
136
140
 
137
141
  <div className="settings-tab-panel" data-active={tab === 'model' ? 'true' : 'false'} role="tabpanel">
@@ -486,6 +490,10 @@ function ApiKeyField({ value, onChange, required = false }: { value: string; onC
486
490
  value={value}
487
491
  onChange={(event) => onChange(event.target.value)}
488
492
  placeholder={t('settings.apiKeyPh')}
493
+ autoComplete="new-password"
494
+ spellCheck={false}
495
+ data-1p-ignore
496
+ data-lpignore="true"
489
497
  />
490
498
  <button
491
499
  type="button"
@@ -524,6 +532,113 @@ function ScrollingProviderName({ name }: { name: string }) {
524
532
  );
525
533
  }
526
534
 
535
+ function ImageProviderManager({ providers, onChanged }: { providers: ImageProvider[]; onChanged: () => void }) {
536
+ const settings = useStore((s) => s.settings)!;
537
+ const setSettings = useStore((s) => s.setSettings);
538
+ const addToast = useStore((s) => s.addToast);
539
+ const t = useT();
540
+ const [editing, setEditing] = useState<ImageProvider | null>(null);
541
+ const [pendingDelete, setPendingDelete] = useState<ImageProvider | null>(null);
542
+ const providerName = (kind: ImageProviderKind) => t(`settings.imageProviderKind.${kind === 'bailian-token-plan' ? 'bailianTokenPlan' : kind}`);
543
+
544
+ const saveProvider = async (provider: ImageProvider) => {
545
+ if (provider.id != null) await db.imageProviders.update(provider.id, provider);
546
+ else await db.imageProviders.add(provider);
547
+ setEditing(null);
548
+ await onChanged();
549
+ addToast(t(provider.id != null ? 'toast.imageProviderUpdated' : 'toast.imageProviderAdded'));
550
+ };
551
+
552
+ return (
553
+ <div className="set-section">
554
+ <div className="settings-section-head">
555
+ <h3>{t('settings.imageProviderTitle')}</h3>
556
+ <button className="btn btn-sm settings-gen-reset" onClick={() => setEditing({ kind: 'bailian-token-plan', apiKey: '', isEnabled: true, createdAt: Date.now() })}>
557
+ <Icon name="plus" size={13} /> {t('settings.addProvider')}
558
+ </button>
559
+ </div>
560
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
561
+ {providers.length === 0 && <div className="typo-body-sm text-muted">{t('settings.noImageProvider')}</div>}
562
+ {[...providers].sort((a, b) => b.createdAt - a.createdAt).map((provider) => (
563
+ <div key={provider.id} className={`provider-card ${provider.isEnabled ? '' : 'disabled'}`}>
564
+ <div className="p-head">
565
+ <label className="switch" title={provider.isEnabled ? t('settings.disable') : t('settings.enable')}>
566
+ <input type="checkbox" checked={provider.isEnabled} onChange={async () => { await db.imageProviders.update(provider.id!, { isEnabled: !provider.isEnabled }); await onChanged(); }} />
567
+ <span className="switch-slider" />
568
+ </label>
569
+ <ScrollingProviderName name={providerName(provider.kind)} />
570
+ <span className="p-status voice">{t('settings.imageServiceTag')}</span>
571
+ <div style={{ marginLeft: 'auto', display: 'flex', gap: 6 }}>
572
+ <button className="btn btn-sm" onClick={() => setEditing(provider)}>{t('common.edit')}</button>
573
+ <button className="btn btn-sm btn-danger" onClick={() => setPendingDelete(provider)}><Icon name="trash" size={12} /></button>
574
+ </div>
575
+ </div>
576
+ <div className="provider-inline-detail"><b>{t('settings.models')}:</b> {IMAGE_MODELS.join(', ')}</div>
577
+ </div>
578
+ ))}
579
+ </div>
580
+ <div className="voice-default-card">
581
+ <div>
582
+ <div className="s-label">{t('settings.defaultImageModel')}</div>
583
+ <div className="s-desc">{t('settings.defaultImageModelDesc')}</div>
584
+ </div>
585
+ <select
586
+ className="select voice-default-select"
587
+ value={settings.activeImageProviderId != null && settings.defaultImageModel ? `${settings.activeImageProviderId}:${settings.defaultImageModel}` : ''}
588
+ onChange={(event) => {
589
+ const [providerId, model] = event.target.value.split(':');
590
+ void setSettings(event.target.value
591
+ ? { activeImageProviderId: Number(providerId), defaultImageModel: model }
592
+ : { activeImageProviderId: null });
593
+ }}
594
+ >
595
+ <option value="">{t('settings.noDefaultImageProvider')}</option>
596
+ {providers.filter((provider) => provider.isEnabled).flatMap((provider) => IMAGE_MODELS.map((model) => (
597
+ <option key={`${provider.id}:${model}`} value={`${provider.id}:${model}`}>{providerName(provider.kind)} · {model}</option>
598
+ )))}
599
+ </select>
600
+ </div>
601
+ {editing && <Modal onClose={() => setEditing(null)}>
602
+ <div className="modal-head">
603
+ <span className="typo-dialog-title">{editing.id != null ? t('settings.editImageProvider') : t('settings.addImageProvider')}</span>
604
+ <button className="icon-btn" onClick={() => setEditing(null)}><Icon name="x" /></button>
605
+ </div>
606
+ <ImageProviderForm initial={editing} onSave={saveProvider} />
607
+ </Modal>}
608
+ {pendingDelete && <DeleteConfirmDialog title={t('settings.deleteImageProvider')} itemName={providerName(pendingDelete.kind)} onCancel={() => setPendingDelete(null)} onConfirm={async () => {
609
+ await db.imageProviders.delete(pendingDelete.id!);
610
+ if (settings.activeImageProviderId === pendingDelete.id) await setSettings({ activeImageProviderId: null });
611
+ setPendingDelete(null);
612
+ await onChanged();
613
+ }} />}
614
+ </div>
615
+ );
616
+ }
617
+
618
+ function ImageProviderForm({ initial, onSave }: { initial: ImageProvider; onSave: (provider: ImageProvider) => void }) {
619
+ const t = useT();
620
+ const [kind, setKind] = useState<ImageProviderKind>(initial.kind);
621
+ const [apiKey, setApiKey] = useState(initial.apiKey);
622
+ return <>
623
+ <div className="modal-body" style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
624
+ <div className="field">
625
+ <label>{t('settings.imageProvider')}</label>
626
+ <select className="select" value={kind} disabled={initial.id != null} onChange={(event) => setKind(event.target.value as ImageProviderKind)}>
627
+ <option value="bailian-token-plan">{t('settings.imageProviderKind.bailianTokenPlan')}</option>
628
+ </select>
629
+ </div>
630
+ <ApiKeyField value={apiKey} onChange={setApiKey} required />
631
+ <div className="field">
632
+ <label>{t('settings.models')}</label>
633
+ <div className="provider-inline-detail">{IMAGE_MODELS.join(', ')}</div>
634
+ </div>
635
+ </div>
636
+ <div className="modal-foot">
637
+ <button className="btn btn-primary" disabled={!apiKey.trim()} onClick={() => onSave({ ...initial, kind, apiKey: apiKey.trim(), isEnabled: true })}>{t('common.save')}</button>
638
+ </div>
639
+ </>;
640
+ }
641
+
527
642
  function VoiceProviderManager({ providers, onChanged }: { providers: VoiceProvider[]; onChanged: () => void }) {
528
643
  const settings = useStore((s) => s.settings)!;
529
644
  const setSettings = useStore((s) => s.setSettings);
@@ -19,10 +19,10 @@ function extOf(path: string): string {
19
19
  }
20
20
 
21
21
  /** 与 file_display 相同的「按扩展名推断展示方式」逻辑 */
22
- function kindFromPath(path: string): 'text' | 'html' | 'unsupported' {
22
+ function kindFromPath(path: string): 'text' | 'html' | 'image' | 'unsupported' {
23
23
  const ext = extOf(path);
24
24
  if (/^(html?)$/i.test(ext)) return 'html';
25
- if (/^(png|jpe?g|gif|webp|svg|bmp|ico)$/i.test(ext)) return 'unsupported';
25
+ if (/^(png|jpe?g|gif|webp|svg|bmp|ico)$/i.test(ext)) return 'image';
26
26
  return 'text';
27
27
  }
28
28
 
@@ -232,18 +232,37 @@ export const Avatar = memo(function Avatar({
232
232
  // 附件卡片:仅展示文件名(去掉图片/视频缩略图)
233
233
  // ============================================================
234
234
 
235
- export function AttachCard({ name, onRemove }: { name: string; onRemove?: () => void }) {
235
+ export function AttachCard({ name, src, onRemove }: { name: string; src?: string; onRemove?: () => void }) {
236
236
  const t = useT();
237
+ const [previewing, setPreviewing] = useState(false);
238
+ const isImage = typeof src === 'string' && (src.startsWith('data:image/') || /\.(png|jpe?g|gif|webp|svg|bmp)(?:$|[?#])/i.test(src));
237
239
  return (
238
- <div className="attach-card">
239
- <span className="attach-card-icon">📎</span>
240
- <span className="attach-card-name" title={name}>{name}</span>
241
- {onRemove && (
242
- <button className="attach-rm" onClick={onRemove} title={t('common.removeAttachment')}>
243
- <Icon name="x" size={11} />
244
- </button>
240
+ <>
241
+ <div className={`attach-card ${isImage ? 'attach-card-image' : ''}`}>
242
+ {isImage ? (
243
+ <button type="button" className="attach-thumb-button" onClick={() => setPreviewing(true)} aria-label={name}>
244
+ <img className="attach-thumb" src={src} alt={name} />
245
+ </button>
246
+ ) : <span className="attach-card-icon">📎</span>}
247
+ <span className="attach-card-name" title={name}>{name}</span>
248
+ {onRemove && (
249
+ <button className="attach-rm" onClick={onRemove} title={t('common.removeAttachment')}>
250
+ <Icon name="x" size={11} />
251
+ </button>
252
+ )}
253
+ </div>
254
+ {previewing && isImage && (
255
+ <Modal onClose={() => setPreviewing(false)} size="wide" className="image-preview-modal">
256
+ <div className="modal-head">
257
+ <span>{name}</span>
258
+ <button className="icon-btn" onClick={() => setPreviewing(false)} aria-label={t('common.close')}><Icon name="x" /></button>
259
+ </div>
260
+ <div className="image-preview-body" onClick={() => setPreviewing(false)}>
261
+ <img src={src} alt={name} />
262
+ </div>
263
+ </Modal>
245
264
  )}
246
- </div>
265
+ </>
247
266
  );
248
267
  }
249
268