tavern-harness 0.1.31 → 0.1.33

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,74 @@
3
3
  > 本文件由 `scripts/changelog.mjs` 从 `changelog/v*.md` 生成,请勿手动编辑。
4
4
  > 版本对比链接见文末;源文件位于仓库 `changelog/` 目录。
5
5
 
6
+ ## [0.1.33] - 2026-11-18
7
+
8
+ ### 中文
9
+
10
+ #### 修复
11
+
12
+ - 修复 0.1.32 的 npm 包遗漏 `voice-server.mjs`、导致本地持久化服务无法启动、对话数据无法加载与保存的问题
13
+ - 持久化与沙箱子进程反复拉起时不再重复注册进程退出监听,消除启动时的 `MaxListenersExceededWarning`
14
+ - 子进程的错误输出会显示在终端,本地服务启动失败时不再静默
15
+
16
+ #### 内部
17
+
18
+ - 新增发布内容校验:`npm pack` / `npm publish` 前会检查 `files` 白名单是否覆盖所有运行时相对导入
19
+
20
+ ### English
21
+
22
+ #### Fixed
23
+
24
+ - Fixed the 0.1.32 npm package missing `voice-server.mjs`, which prevented the local persistence service from starting and blocked loading or saving conversations
25
+ - Stopped re-registering process exit listeners whenever the persistence or sandbox child process is relaunched, removing the startup `MaxListenersExceededWarning`
26
+ - Child-process errors now appear in the terminal instead of failing silently
27
+
28
+ #### Internal
29
+
30
+ - Added a publish-content check that verifies the `files` allowlist covers every runtime relative import before `npm pack` / `npm publish`
31
+
32
+ ## [0.1.32] - 2026-11-18
33
+
34
+ ### 中文
35
+
36
+ #### 新增
37
+
38
+ - 语音服务供应商:设置页新增「🔊 语音服务供应商」分区,支持 DeepSeek(海星 · 女声、暗潮 · 男声)与百炼 Token Plan(龙安灵心、龙安陆风)。填写 API Key 即可保存,保存前还能在表单里试听音色;可以添加多个供应商,并随时启用、停用、编辑或删除
39
+ - 朗读助手消息:在助手消息的「更多」菜单中选择「朗读消息」,就会用默认音色朗读这条回复
40
+ - 自动朗读:对话标题栏新增朗读开关,开启后每条助手回复生成完毕会自动朗读,关闭后恢复静音
41
+ - 默认音色:在「语音服务供应商」下方选择默认的供应商与音色,手动朗读和自动朗读都会使用它;没有配置时会提示先选择
42
+
43
+ #### 改进
44
+
45
+ - 设置页的供应商列表改为按添加时间倒序排列,新添加的供应商显示在最上方;「添加供应商」按钮移到分区标题右侧,列表为空时也始终可见
46
+ - 文本供应商与语音供应商的卡片分别显示「文本」「语音」标签,并统一了两类标签的配色,一眼就能区分服务类型
47
+ - 文本与语音供应商的 API Key 输入框都增加了显示 / 隐藏按钮,方便核对已填写的密钥
48
+ - 语音合成请求由本地持久化服务代理转发,API Key 只保存在本地数据库,不会直接出现在发往第三方的浏览器请求里
49
+
50
+ #### 内部
51
+
52
+ - 新增 `voice-server.mjs`,对百炼返回的音频地址做 HTTPS 与域名校验;补充语音、持久化与供应商相关的测试
53
+
54
+ ### English
55
+
56
+ #### Added
57
+
58
+ - **Voice service providers**: Settings now has a **🔊 Voice Service Providers** section supporting DeepSeek (Stella · female, Tide · male) and Bailian Token Plan (Longan Lingxin, Longan Lufeng). Enter an API key to save a provider, and preview each voice right in the form before saving. You can add several providers and enable, disable, edit, or delete them at any time
59
+ - **Read message aloud**: choose **Read message aloud** from an assistant message's More menu to hear that reply in the default voice
60
+ - **Automatic reading**: the conversation header has a new reading toggle. When it is on, every completed assistant reply is read aloud automatically; turn it off to go silent
61
+ - **Default voice**: pick the default provider and voice below the voice providers section; both manual and automatic reading use it. If nothing is configured, the app prompts you to choose one first
62
+
63
+ #### Changed
64
+
65
+ - The provider list in Settings is now sorted newest first, so freshly added providers appear at the top; the **Add provider** button moved next to the section heading and is always visible, even when the list is empty
66
+ - Text and voice provider cards now carry **Text** and **Voice** tags with a unified color scheme, making the service type obvious at a glance
67
+ - API key fields for both text and voice providers gained a show/hide button so you can check what you entered
68
+ - Voice synthesis requests are proxied through the local persistence service, so the API key stays in the local database and never appears in browser requests to third parties
69
+
70
+ #### Internal
71
+
72
+ - Added `voice-server.mjs` to validate Bailian audio URLs against HTTPS and an allowlisted domain pattern, plus tests for voice, persistence, and provider behavior
73
+
6
74
  ## [0.1.31] - 2026-11-05
7
75
 
8
76
  ### 中文
@@ -914,6 +982,8 @@
914
982
  - Vite + React + Zustand + Dexie stack with browser-side local persistence
915
983
 
916
984
  <!-- 链接定义 -->
985
+ [0.1.33]: https://github.com/Rannichan/Tavern-Harness/compare/v0.1.32...v0.1.33
986
+ [0.1.32]: https://github.com/Rannichan/Tavern-Harness/compare/v0.1.31...v0.1.32
917
987
  [0.1.31]: https://github.com/Rannichan/Tavern-Harness/compare/v0.1.30...v0.1.31
918
988
  [0.1.30]: https://github.com/Rannichan/Tavern-Harness/compare/v0.1.29...v0.1.30
919
989
  [0.1.29]: https://github.com/Rannichan/Tavern-Harness/compare/v0.1.28...v0.1.29
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tavern-harness",
3
- "version": "0.1.31",
3
+ "version": "0.1.33",
4
4
  "description": "Tavern Harness — 酒馆模式下的本地 AI Agent 助手(MyAgent-Android 的 Web 复刻)",
5
5
  "private": false,
6
6
  "type": "module",
@@ -15,6 +15,7 @@
15
15
  "vite.config.ts",
16
16
  "sandbox-server.mjs",
17
17
  "persistence-server.mjs",
18
+ "voice-server.mjs",
18
19
  "tsconfig.json",
19
20
  "README.md",
20
21
  "CHANGELOG.md"
@@ -41,6 +42,8 @@
41
42
  "changelog:build": "node scripts/changelog.mjs build",
42
43
  "changelog:check": "node scripts/changelog.mjs check",
43
44
  "changelog:check:release": "node scripts/changelog.mjs check --release",
45
+ "check:package": "node scripts/check-package-files.mjs",
46
+ "prepack": "npm run check:package",
44
47
  "prepublishOnly": "npm run build && npm run changelog:check:release"
45
48
  },
46
49
  "dependencies": {
@@ -9,6 +9,7 @@ import { mkdirSync } from 'node:fs';
9
9
  import { homedir } from 'node:os';
10
10
  import { dirname, join, resolve } from 'node:path';
11
11
  import { DatabaseSync } from 'node:sqlite';
12
+ import { normalizeBailianAudioUrl } from './voice-server.mjs';
12
13
 
13
14
  const PORT = Number(process.argv[2] || process.env.PERSISTENCE_PORT || 17892);
14
15
  // 记录读写(图片/附件)走大上限;锁和健康检查的请求体很小,单独收紧。
@@ -194,7 +195,7 @@ const listRecordsByJsonField = database.prepare(`
194
195
  const listStartupRecords = database.prepare(`
195
196
  SELECT collection, record_key, value_json, updated_at
196
197
  FROM app_records
197
- WHERE collection IN ('settings', 'providers', 'npcs', 'sessions', 'worldBooks', 'tools', 'achievementUnlocks')
198
+ WHERE collection IN ('settings', 'providers', 'voiceProviders', 'npcs', 'sessions', 'worldBooks', 'tools', 'achievementUnlocks')
198
199
  ORDER BY collection, record_key
199
200
  `);
200
201
  const deleteRecord = database.prepare('DELETE FROM app_records WHERE collection = ? AND record_key = ?');
@@ -288,6 +289,7 @@ const server = createServer(async (req, res) => {
288
289
  const collections = {
289
290
  settings: [],
290
291
  providers: [],
292
+ voiceProviders: [],
291
293
  npcs: [],
292
294
  sessions: [],
293
295
  worldBooks: [],
@@ -304,6 +306,87 @@ const server = createServer(async (req, res) => {
304
306
  json(res, 200, { ok: true, lock: lockState(clientId), collections });
305
307
  return;
306
308
  }
309
+ if (pathname === '/voice/synthesize' || pathname === '/voice/preview') {
310
+ const voiceId = typeof body.voiceId === 'string' ? body.voiceId : '';
311
+ const text = typeof body.text === 'string' ? body.text.trim() : '';
312
+ let kind;
313
+ let apiKey;
314
+ if (pathname === '/voice/preview') {
315
+ kind = body.kind;
316
+ apiKey = typeof body.apiKey === 'string' ? body.apiKey.trim() : '';
317
+ } else {
318
+ const providerId = Number(body.providerId);
319
+ if (!Number.isInteger(providerId) || providerId <= 0) {
320
+ json(res, 400, { ok: false, message: 'Invalid voice synthesis request' });
321
+ return;
322
+ }
323
+ const record = getRecord.get('voiceProviders', String(providerId));
324
+ if (!record) {
325
+ json(res, 404, { ok: false, message: 'Voice provider not found' });
326
+ return;
327
+ }
328
+ const provider = JSON.parse(record.value_json);
329
+ if (!provider.isEnabled) {
330
+ json(res, 400, { ok: false, message: 'Voice provider or voice is unavailable' });
331
+ return;
332
+ }
333
+ kind = provider.kind;
334
+ apiKey = typeof provider.apiKey === 'string' ? provider.apiKey.trim() : '';
335
+ }
336
+ const allowedVoices = kind === 'deepseek'
337
+ ? new Set(['stella', 'tide'])
338
+ : kind === 'bailian'
339
+ ? new Set(['longanlingxin', 'longanlufeng'])
340
+ : null;
341
+ if (!allowedVoices || !apiKey || !allowedVoices.has(voiceId) || !text || text.length > 10_000) {
342
+ json(res, 400, { ok: false, message: 'Voice provider or voice is unavailable' });
343
+ return;
344
+ }
345
+ const endpoint = kind === 'deepseek'
346
+ ? 'https://api.deepseek.com/v1/tools/tts'
347
+ : 'https://token-plan.cn-beijing.maas.aliyuncs.com/api/v1/services/audio/tts/SpeechSynthesizer';
348
+ const requestBody = kind === 'deepseek'
349
+ ? { text, voice_id: voiceId, format: 'wav', filter_markdown: true }
350
+ : { model: 'qwen-audio-3.0-tts-plus', input: { text, voice: voiceId, format: 'mp3', sample_rate: 22050 } };
351
+ const upstream = await fetch(endpoint, {
352
+ method: 'POST',
353
+ headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
354
+ body: JSON.stringify(requestBody),
355
+ signal: AbortSignal.timeout(120_000),
356
+ });
357
+ if (!upstream.ok) {
358
+ const payload = await upstream.json().catch(() => null);
359
+ upstream.body?.cancel();
360
+ const upstreamMessage = payload?.message ?? payload?.error?.message ?? payload?.code;
361
+ json(res, upstream.status, { ok: false, message: upstreamMessage ? `Voice service error: ${upstreamMessage}` : `Voice service returned HTTP ${upstream.status}` });
362
+ return;
363
+ }
364
+ let audioResponse = upstream;
365
+ if (kind === 'bailian') {
366
+ const payload = await upstream.json();
367
+ const rawAudioUrl = payload?.output?.audio?.url;
368
+ const audioUrl = normalizeBailianAudioUrl(rawAudioUrl);
369
+ if (!audioUrl) {
370
+ const upstreamMessage = payload?.message ?? payload?.error?.message ?? payload?.code;
371
+ json(res, 502, { ok: false, message: upstreamMessage ? `Bailian synthesis failed: ${upstreamMessage}` : 'Bailian did not return a valid audio URL' });
372
+ return;
373
+ }
374
+ audioResponse = await fetch(audioUrl, { signal: AbortSignal.timeout(120_000) });
375
+ if (!audioResponse.ok) {
376
+ audioResponse.body?.cancel();
377
+ json(res, 502, { ok: false, message: `Unable to download generated audio (HTTP ${audioResponse.status})` });
378
+ return;
379
+ }
380
+ }
381
+ const audio = Buffer.from(await audioResponse.arrayBuffer());
382
+ res.writeHead(200, {
383
+ 'Content-Type': audioResponse.headers.get('content-type') || (kind === 'deepseek' ? 'audio/wav' : 'audio/mpeg'),
384
+ 'Content-Length': String(audio.length),
385
+ 'Cache-Control': 'no-store',
386
+ });
387
+ res.end(audio);
388
+ return;
389
+ }
307
390
  if (!pathname.startsWith('/records/')) {
308
391
  json(res, 404, { ok: false, message: `Unknown persistence endpoint: ${pathname}` });
309
392
  return;
package/src/App.tsx CHANGED
@@ -321,6 +321,7 @@ function SessionHeader({
321
321
  const deleteSession = useStore((s) => s.deleteSession);
322
322
  const resetSessionConversation = useStore((s) => s.resetSessionConversation);
323
323
  const themeMode = useStore((s) => s.settings?.themeMode ?? 'system');
324
+ const autoVoiceEnabled = useStore((s) => s.settings?.autoVoiceEnabled ?? false);
324
325
  const setSettings = useStore((s) => s.setSettings);
325
326
  const t = useT();
326
327
  const [showEdit, setShowEdit] = useState(false);
@@ -402,6 +403,16 @@ function SessionHeader({
402
403
  >
403
404
  <Icon name="more" size={18} />
404
405
  </button>
406
+ <button
407
+ className={`btn-ghost icon-tooltip chat-voice-toggle${autoVoiceEnabled ? ' active' : ''}`}
408
+ type="button"
409
+ title={t(autoVoiceEnabled ? 'header.disableAutoVoice' : 'header.enableAutoVoice')}
410
+ aria-label={t(autoVoiceEnabled ? 'header.disableAutoVoice' : 'header.enableAutoVoice')}
411
+ aria-pressed={autoVoiceEnabled}
412
+ onClick={() => void setSettings({ autoVoiceEnabled: !autoVoiceEnabled })}
413
+ >
414
+ <Icon name={autoVoiceEnabled ? 'speaker' : 'speaker-off'} size={17} />
415
+ </button>
405
416
  <button
406
417
  className="btn-ghost icon-tooltip chat-theme-toggle"
407
418
  type="button"
@@ -1321,6 +1321,7 @@ export function MessageMenu() {
1321
1321
  const t = useT();
1322
1322
  const regenerateMessage = useStore((s) => s.regenerateMessage);
1323
1323
  const forkSession = useStore((s) => s.forkSession);
1324
+ const speakMessage = useStore((s) => s.speakMessage);
1324
1325
  const addToast = useStore((s) => s.addToast);
1325
1326
  const messages = useStore((s) => s.messages);
1326
1327
  const npcs = useStore((s) => s.npcs);
@@ -1415,6 +1416,13 @@ export function MessageMenu() {
1415
1416
  });
1416
1417
  },
1417
1418
  });
1419
+ if (msg.role === 'assistant') {
1420
+ actions.push({
1421
+ label: t('chat.readMsg'),
1422
+ icon: 'speaker',
1423
+ onClick: () => { void speakMessage(msg.content); },
1424
+ });
1425
+ }
1418
1426
  }
1419
1427
  if (msg.role === 'user' || msg.role === 'assistant') {
1420
1428
  actions.push({
@@ -2,7 +2,8 @@ import { memo, useRef, useState, type PointerEvent as ReactPointerEvent } from '
2
2
  import { useStore } from '../store/store';
3
3
  import { db, DEFAULT_GENERATION_SETTINGS } from '../db/database';
4
4
  import { type ThemeMode } from '../theme/theme';
5
- import { type ApiProvider, type AppLanguage, type ReasoningEffort, enabledModelIds, modelAliases } from '../types/models';
5
+ import { type ApiProvider, type AppLanguage, type ReasoningEffort, type VoiceProvider, type VoiceProviderKind, type VoiceId, enabledModelIds, modelAliases } from '../types/models';
6
+ import { VOICE_PROVIDER_OPTIONS, previewVoice } from '../core/voice';
6
7
  import { Icon, Modal } from './shared';
7
8
  import { DeleteConfirmDialog } from './DeleteConfirmDialog';
8
9
  import { isNetworkLikeError, toProxyUrl } from '../core/proxy';
@@ -21,6 +22,8 @@ export const SettingsView = memo(function SettingsView() {
21
22
  const resetTavern = useStore((s) => s.resetTavern);
22
23
  const providers = useStore((s) => s.providers);
23
24
  const refreshProviders = useStore((s) => s.refreshProviders);
25
+ const voiceProviders = useStore((s) => s.voiceProviders);
26
+ const refreshVoiceProviders = useStore((s) => s.refreshVoiceProviders);
24
27
  const [showResetConfirm, setShowResetConfirm] = useState(false);
25
28
  const [resetting, setResetting] = useState(false);
26
29
  const [showVersionHistory, setShowVersionHistory] = useState(false);
@@ -113,6 +116,7 @@ export const SettingsView = memo(function SettingsView() {
113
116
 
114
117
  {/* 模型服务 Provider(置顶) */}
115
118
  <ProviderManager providers={providers} onChanged={refreshProviders} />
119
+ <VoiceProviderManager providers={voiceProviders} onChanged={refreshVoiceProviders} />
116
120
 
117
121
  <div className="set-section">
118
122
  <h3>{t('settings.toolExecution')}</h3>
@@ -429,11 +433,164 @@ async function fetchModelsSmart(baseUrl: string, apiKey: string): Promise<Models
429
433
  throw lastErr ?? new Error('unknown-error');
430
434
  }
431
435
 
436
+ function ApiKeyField({ value, onChange, required = false }: { value: string; onChange: (value: string) => void; required?: boolean }) {
437
+ const t = useT();
438
+ const [visible, setVisible] = useState(false);
439
+
440
+ return (
441
+ <div className="field">
442
+ <label>{t('settings.apiKey')}</label>
443
+ <div className="password-input-wrap">
444
+ <input
445
+ className="input mono"
446
+ type={visible ? 'text' : 'password'}
447
+ required={required}
448
+ value={value}
449
+ onChange={(event) => onChange(event.target.value)}
450
+ placeholder={t('settings.apiKeyPh')}
451
+ />
452
+ <button
453
+ type="button"
454
+ className="password-visibility-btn"
455
+ onClick={() => setVisible((current) => !current)}
456
+ aria-label={t(visible ? 'settings.hideApiKey' : 'settings.showApiKey')}
457
+ title={t(visible ? 'settings.hideApiKey' : 'settings.showApiKey')}
458
+ >
459
+ <Icon name={visible ? 'eye-off' : 'eye'} size={16} />
460
+ </button>
461
+ </div>
462
+ </div>
463
+ );
464
+ }
465
+
466
+ function VoiceProviderManager({ providers, onChanged }: { providers: VoiceProvider[]; onChanged: () => void }) {
467
+ const settings = useStore((s) => s.settings)!;
468
+ const setSettings = useStore((s) => s.setSettings);
469
+ const addToast = useStore((s) => s.addToast);
470
+ const t = useT();
471
+ const [editing, setEditing] = useState<VoiceProvider | null>(null);
472
+ const [pendingDelete, setPendingDelete] = useState<VoiceProvider | null>(null);
473
+
474
+ const providerName = (kind: VoiceProviderKind) => t(`settings.voiceProviderKind.${kind}`);
475
+ const voiceLabel = (voiceId: VoiceId) => t(`settings.voiceLabel.${voiceId}`);
476
+
477
+ const saveProvider = async (provider: VoiceProvider) => {
478
+ if (provider.id != null) await db.voiceProviders.update(provider.id, provider);
479
+ else await db.voiceProviders.add(provider);
480
+ setEditing(null);
481
+ await onChanged();
482
+ addToast(t(provider.id != null ? 'toast.voiceProviderUpdated' : 'toast.voiceProviderAdded'));
483
+ };
484
+
485
+ return (
486
+ <div className="set-section">
487
+ <div className="settings-section-head">
488
+ <h3>{t('settings.voiceProviderTitle')}</h3>
489
+ <button className="btn btn-sm settings-gen-reset" onClick={() => setEditing({ kind: 'deepseek', apiKey: '', isEnabled: true, createdAt: Date.now() })}>
490
+ <Icon name="plus" size={13} /> {t('settings.addProvider')}
491
+ </button>
492
+ </div>
493
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
494
+ {providers.length === 0 && <div className="typo-body-sm text-muted">{t('settings.noVoiceProvider')}</div>}
495
+ {[...providers].sort((a, b) => b.createdAt - a.createdAt).map((provider) => {
496
+ const options = VOICE_PROVIDER_OPTIONS[provider.kind];
497
+ return (
498
+ <div key={provider.id} className={`provider-card ${provider.isEnabled ? '' : 'disabled'}`}>
499
+ <div className="p-head">
500
+ <label className="switch" title={provider.isEnabled ? t('settings.disable') : t('settings.enable')}>
501
+ <input type="checkbox" checked={provider.isEnabled} onChange={async () => { await db.voiceProviders.update(provider.id!, { isEnabled: !provider.isEnabled }); await onChanged(); }} />
502
+ <span className="switch-slider" />
503
+ </label>
504
+ <span className="p-name">{providerName(provider.kind)}</span>
505
+ <span className="p-status voice">{t('settings.voiceServiceTag')}</span>
506
+ <div style={{ marginLeft: 'auto', display: 'flex', gap: 6 }}>
507
+ <button className="btn btn-sm" onClick={() => setEditing(provider)}>{t('common.edit')}</button>
508
+ <button className="btn btn-sm btn-danger" onClick={() => setPendingDelete(provider)}><Icon name="trash" size={12} /></button>
509
+ </div>
510
+ </div>
511
+ <div className="provider-inline-detail"><b>{t('settings.voices')}:</b> {options.voices.map((voice) => voiceLabel(voice.id)).join(', ')}</div>
512
+ </div>
513
+ );
514
+ })}
515
+ </div>
516
+ <div className="voice-default-card">
517
+ <div>
518
+ <div className="s-label">{t('settings.defaultVoice')}</div>
519
+ <div className="s-desc">{t('settings.defaultVoiceDesc')}</div>
520
+ </div>
521
+ <select
522
+ className="select voice-default-select"
523
+ value={settings.activeVoiceProviderId != null && settings.activeVoiceId ? `${settings.activeVoiceProviderId}:${settings.activeVoiceId}` : ''}
524
+ onChange={(event) => {
525
+ const [providerId, voiceId] = event.target.value.split(':');
526
+ void setSettings(event.target.value
527
+ ? { activeVoiceProviderId: Number(providerId), activeVoiceId: voiceId as VoiceId }
528
+ : { activeVoiceProviderId: null, activeVoiceId: null });
529
+ }}
530
+ >
531
+ <option value="">{t('settings.noDefaultVoice')}</option>
532
+ {providers.filter((provider) => provider.isEnabled).flatMap((provider) => VOICE_PROVIDER_OPTIONS[provider.kind].voices.map((voice) => (
533
+ <option key={`${provider.id}:${voice.id}`} value={`${provider.id}:${voice.id}`}>
534
+ {providerName(provider.kind)} · {voiceLabel(voice.id)}
535
+ </option>
536
+ )))}
537
+ </select>
538
+ </div>
539
+ {editing && <Modal onClose={() => setEditing(null)}>
540
+ <div className="modal-head">
541
+ <span className="typo-dialog-title">{editing.id != null ? t('settings.editVoiceProvider') : t('settings.addVoiceProvider')}</span>
542
+ <button className="icon-btn" onClick={() => setEditing(null)}><Icon name="x" /></button>
543
+ </div>
544
+ <VoiceProviderForm initial={editing} onSave={saveProvider} />
545
+ </Modal>}
546
+ {pendingDelete && <DeleteConfirmDialog title={t('settings.deleteVoiceProvider')} itemName={providerName(pendingDelete.kind)} onCancel={() => setPendingDelete(null)} onConfirm={async () => {
547
+ await db.voiceProviders.delete(pendingDelete.id!);
548
+ if (settings.activeVoiceProviderId === pendingDelete.id) await setSettings({ activeVoiceProviderId: null, activeVoiceId: null });
549
+ setPendingDelete(null);
550
+ await onChanged();
551
+ }} />}
552
+ </div>
553
+ );
554
+ }
555
+
556
+ function VoiceProviderForm({ initial, onSave }: { initial: VoiceProvider; onSave: (provider: VoiceProvider) => void }) {
557
+ const addToast = useStore((s) => s.addToast);
558
+ const t = useT();
559
+ const [kind, setKind] = useState<VoiceProviderKind>(initial.kind);
560
+ const [apiKey, setApiKey] = useState(initial.apiKey);
561
+ const [previewingVoiceId, setPreviewingVoiceId] = useState<VoiceId | null>(null);
562
+ const voices = VOICE_PROVIDER_OPTIONS[kind].voices;
563
+
564
+ const preview = async (voiceId: VoiceId) => {
565
+ setPreviewingVoiceId(voiceId);
566
+ try {
567
+ await previewVoice(kind, apiKey, voiceId, t('settings.voicePreviewText'));
568
+ addToast(t('toast.voicePreviewPlaying'));
569
+ } catch (error) {
570
+ addToast(t('toast.voiceFailed', { msg: error instanceof Error ? error.message : String(error) }), 'error');
571
+ } finally {
572
+ setPreviewingVoiceId(null);
573
+ }
574
+ };
575
+
576
+ return <>
577
+ <div className="modal-body" style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
578
+ <div className="field"><label>{t('settings.voiceProvider')}</label><select className="select" value={kind} disabled={initial.id != null} onChange={(event) => setKind(event.target.value as VoiceProviderKind)}><option value="deepseek">{t('settings.voiceProviderKind.deepseek')}</option><option value="bailian">{t('settings.voiceProviderKind.bailian')}</option></select></div>
579
+ <ApiKeyField value={apiKey} onChange={setApiKey} required />
580
+ <div className="field"><label>{t('settings.voices')}</label><div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>{voices.map((voice) => <div key={voice.id} className="provider-voice-option"><span><b>{voice.id}</b><br /><span className="text-muted">{t(`settings.voiceLabel.${voice.id}`)}</span></span><button type="button" className="icon-btn provider-voice-preview" disabled={!apiKey.trim() || previewingVoiceId != null} title={t('settings.previewVoice')} aria-label={`${t('settings.previewVoice')}: ${t(`settings.voiceLabel.${voice.id}`)}`} onClick={() => void preview(voice.id)}>{previewingVoiceId === voice.id ? <span className="spinner" /> : <Icon name="speaker" size={17} />}</button></div>)}</div></div>
581
+ </div>
582
+ <div className="modal-foot">
583
+ <button className="btn btn-primary" disabled={!apiKey.trim()} onClick={() => onSave({ ...initial, kind, apiKey: apiKey.trim(), isEnabled: true })}>{t('common.save')}</button>
584
+ </div>
585
+ </>;
586
+ }
587
+
432
588
  function ProviderManager({ providers, onChanged }: { providers: ApiProvider[]; onChanged: () => void }) {
433
589
  const addToast = useStore((s) => s.addToast);
434
590
  const t = useT();
435
591
  const [editing, setEditing] = useState<ApiProvider | null>(null);
436
592
  const [pendingDelete, setPendingDelete] = useState<ApiProvider | null>(null);
593
+ const orderedProviders = [...providers].sort((a, b) => b.createdAt - a.createdAt);
437
594
 
438
595
  const toggleEnabled = async (p: ApiProvider) => {
439
596
  await db.providers.update(p.id!, { isEnabled: !p.isEnabled });
@@ -449,10 +606,18 @@ function ProviderManager({ providers, onChanged }: { providers: ApiProvider[]; o
449
606
 
450
607
  return (
451
608
  <div className="set-section">
452
- <h3>{t('settings.providerTitle')}</h3>
609
+ <div className="settings-section-head">
610
+ <h3>{t('settings.providerTitle')}</h3>
611
+ <button
612
+ className="btn btn-sm settings-gen-reset"
613
+ onClick={() => setEditing({ name: '', baseUrl: '', apiKey: '', isEnabled: true, cachedModelsCsv: '', modelAliasesJson: '{}', createdAt: Date.now() })}
614
+ >
615
+ <Icon name="plus" size={13} /> {t('settings.addProvider')}
616
+ </button>
617
+ </div>
453
618
  <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
454
619
  {providers.length === 0 && <div className="typo-body-sm text-muted">{t('settings.noProvider')}</div>}
455
- {providers.map((p) => {
620
+ {orderedProviders.map((p) => {
456
621
  const aliases = modelAliases(p);
457
622
  const enabledModels = enabledModelIds(p);
458
623
  const visibleModels = p.cachedModelsCsv.split(',').map((model) => model.trim()).filter((model) => enabledModels.has(model));
@@ -466,7 +631,7 @@ function ProviderManager({ providers, onChanged }: { providers: ApiProvider[]; o
466
631
  <span className="switch-slider" />
467
632
  </label>
468
633
  <span className="p-name">{p.name}</span>
469
- <span className={`p-status ${p.isEnabled ? 'on' : 'off'}`}>{p.isEnabled ? t('settings.enable') : t('settings.disable')}</span>
634
+ <span className="p-status text">{t('settings.textServiceTag')}</span>
470
635
  <div style={{ marginLeft: 'auto', display: 'flex', gap: 6 }}>
471
636
  <button className="btn btn-sm" onClick={() => setEditing(p)}>{t('common.edit')}</button>
472
637
  <button className="btn btn-sm btn-danger" onClick={() => setPendingDelete(p)}><Icon name="trash" size={12} /></button>
@@ -483,9 +648,6 @@ function ProviderManager({ providers, onChanged }: { providers: ApiProvider[]; o
483
648
  </div>
484
649
  );
485
650
  })}
486
- <button className="btn" style={{ alignSelf: 'flex-start' }} onClick={() => setEditing({ name: '', baseUrl: '', apiKey: '', isEnabled: true, cachedModelsCsv: '', modelAliasesJson: '{}', createdAt: Date.now() })}>
487
- <Icon name="plus" size={13} /> {t('settings.addProvider')}
488
- </button>
489
651
  </div>
490
652
 
491
653
  {editing && (
@@ -565,10 +727,7 @@ function ProviderForm({ initial, onSave }: { initial: ApiProvider; onSave: (p: A
565
727
  <label>{t('settings.baseUrl')}</label>
566
728
  <input className="input mono" value={baseUrl} onChange={(e) => setBaseUrl(e.target.value)} placeholder={t('settings.baseUrlPh')} />
567
729
  </div>
568
- <div className="field">
569
- <label>{t('settings.apiKey')}</label>
570
- <input className="input mono" type="password" value={apiKey} onChange={(e) => setApiKey(e.target.value)} placeholder={t('settings.apiKeyPh')} />
571
- </div>
730
+ <ApiKeyField value={apiKey} onChange={setApiKey} />
572
731
  {models.length > 0 && (
573
732
  <div className="field">
574
733
  <label>{t('settings.models')}</label>
@@ -418,10 +418,14 @@ const ICONS: Record<string, React.ReactNode> = {
418
418
  'pip-exit': <><rect x="3" y="5" width="18" height="14" rx="2" /><path d="m14 14 5-5M15 9h4v4" /></>,
419
419
  'text-wrap': <><path d="M4 6h13a4 4 0 0 1 0 8H9" /><path d="m12 11-3 3 3 3M4 18h3" /></>,
420
420
  eye: <><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z" /><circle cx="12" cy="12" r="3" /></>,
421
+ 'eye-off': <><path d="m3 3 18 18" /><path d="M10.6 5.2A11.8 11.8 0 0 1 12 5c6.5 0 10 7 10 7a17.7 17.7 0 0 1-2.1 3.1M6.6 6.6C3.7 8.4 2 12 2 12s3.5 7 10 7a10.7 10.7 0 0 0 4.1-.8" /><path d="M9.9 9.9a3 3 0 0 0 4.2 4.2" /></>,
422
+ speaker: <><path d="M11 5 6 9H2v6h4l5 4V5z" /><path d="M15.5 8.5a5 5 0 0 1 0 7M18.5 5.5a9 9 0 0 1 0 13" /></>,
423
+ 'speaker-off': <><path d="M11 5 6 9H2v6h4l5 4V5z" /><path d="m16 9 5 5M21 9l-5 5" /></>,
421
424
  sun: <><circle cx="12" cy="12" r="4" /><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41" /></>,
422
425
  moon: <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />,
423
426
  folder: <><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z" /></>,
424
427
  copy: <><rect x="8" y="8" width="13" height="13" rx="2" /><path d="M5 16V6a2 2 0 0 1 2-2h10" /></>,
428
+ play: <><path d="M6 4l14 8-14 8z" /></>,
425
429
  };
426
430
 
427
431
  export function Icon({ name, size = 15 }: { name: string; size?: number }) {