tavern-harness 0.1.13 → 0.1.15

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 (44) hide show
  1. package/CHANGELOG.md +116 -0
  2. package/index.html +1 -1
  3. package/package.json +1 -1
  4. package/persistence-server.mjs +54 -2
  5. package/sandbox-server.mjs +341 -90
  6. package/src/App.tsx +91 -25
  7. package/src/components/AchievementModal.tsx +4 -2
  8. package/src/components/CharactersView.tsx +53 -25
  9. package/src/components/ChatView.tsx +264 -135
  10. package/src/components/Dashboard.tsx +12 -8
  11. package/src/components/DeleteConfirmDialog.tsx +1 -1
  12. package/src/components/FileDisplayModal.tsx +90 -102
  13. package/src/components/GameplayDialogs.tsx +2 -2
  14. package/src/components/NewSessionMenu.tsx +1 -1
  15. package/src/components/SettingsView.tsx +46 -29
  16. package/src/components/Sidebar.tsx +30 -3
  17. package/src/components/StatsView.tsx +55 -45
  18. package/src/components/VersionHistoryModal.tsx +1 -1
  19. package/src/components/WorkspaceFileManagerModal.tsx +28 -3
  20. package/src/components/shared.tsx +84 -24
  21. package/src/core/achievements.ts +22 -4
  22. package/src/core/avatarThumbnail.ts +245 -0
  23. package/src/core/characterBook.ts +2 -1
  24. package/src/core/i18n.ts +51 -9
  25. package/src/core/markdown.ts +3 -2
  26. package/src/core/mobileViewport.ts +18 -3
  27. package/src/core/openai.ts +44 -22
  28. package/src/core/randomId.ts +19 -0
  29. package/src/core/rowFingerprint.ts +75 -0
  30. package/src/core/stats.ts +50 -5
  31. package/src/core/stickyBottom.ts +10 -1
  32. package/src/core/textPreview.ts +16 -0
  33. package/src/core/toolDefinitions.ts +9 -9
  34. package/src/core/tools/generatedSkillExecutor.ts +52 -32
  35. package/src/db/database.ts +101 -13
  36. package/src/generated/changelog.json +159 -1
  37. package/src/main.tsx +12 -21
  38. package/src/store/store.ts +213 -65
  39. package/src/theme/chat.css +62 -71
  40. package/src/theme/global.css +85 -21
  41. package/src/theme/theme.ts +13 -10
  42. package/src/theme/views.css +108 -8
  43. package/src/types/models.ts +2 -0
  44. package/vite.config.ts +128 -4
package/src/App.tsx CHANGED
@@ -1,5 +1,5 @@
1
- import { useEffect, useState } from 'react';
2
- import { useStore } from './store/store';
1
+ import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
2
+ import { useStore, type ActiveView } from './store/store';
3
3
  import { Sidebar } from './components/Sidebar';
4
4
  import { ChatView, ChatInput, MessageMenu, TurnQueuePanel } from './components/ChatView';
5
5
  import { CharactersView } from './components/CharactersView';
@@ -30,6 +30,10 @@ export default function App() {
30
30
  const syncControlState = useStore((s) => s.syncControlState);
31
31
  const takeOverControl = useStore((s) => s.takeOverControl);
32
32
  const activeView = useStore((s) => s.activeView);
33
+ const [mountedViews, setMountedViews] = useState<ActiveView[]>([activeView]);
34
+ if (!mountedViews.includes(activeView)) {
35
+ setMountedViews([...mountedViews, activeView]);
36
+ }
33
37
  const activeSessionId = useStore((s) => s.activeSessionId);
34
38
  const sessions = useStore((s) => s.sessions);
35
39
  const messages = useStore((s) => s.messages);
@@ -84,7 +88,11 @@ export default function App() {
84
88
  };
85
89
 
86
90
  if (initStatus === 'loading') {
87
- return <div className="tav-bg" />;
91
+ return (
92
+ <div className="startup-loading" role="status" aria-label={t('init.loading')} aria-busy="true">
93
+ <span className="spinner" aria-hidden="true" />
94
+ </div>
95
+ );
88
96
  }
89
97
 
90
98
  if (initStatus === 'error') {
@@ -132,28 +140,44 @@ export default function App() {
132
140
  <div className="app-shell">
133
141
  <Sidebar />
134
142
  <main className="main-area">
135
- {activeView === 'chat' && activeSession && (
136
- <>
137
- <SessionHeader session={activeSession} participants={sessionParticipants} />
138
- <div className="chat-main-row">
139
- <div className="chat-main-col">
140
- <ChatView
141
- session={activeSession}
142
- messages={sessionMessages}
143
- participants={sessionParticipants}
144
- compressions={contextCompressions[activeSession.id!] ?? []}
145
- streaming={isStreamingSession}
146
- />
147
- <ChatInput sessionId={activeSession.id!} />
143
+ <ViewSlot active={activeView === 'chat'}>
144
+ {activeSession ? (
145
+ <>
146
+ <SessionHeader session={activeSession} participants={sessionParticipants} />
147
+ <div className="chat-main-row">
148
+ <div className="chat-main-col">
149
+ <ChatView
150
+ session={activeSession}
151
+ messages={sessionMessages}
152
+ participants={sessionParticipants}
153
+ compressions={contextCompressions[activeSession.id!] ?? []}
154
+ streaming={isStreamingSession}
155
+ active={activeView === 'chat'}
156
+ />
157
+ <ChatInput sessionId={activeSession.id!} />
158
+ </div>
159
+ <TurnQueuePanel session={activeSession} participants={sessionParticipants} />
148
160
  </div>
149
- <TurnQueuePanel session={activeSession} participants={sessionParticipants} />
150
- </div>
151
- </>
161
+ </>
162
+ ) : (
163
+ <Dashboard />
164
+ )}
165
+ </ViewSlot>
166
+ {mountedViews.includes('characters') && (
167
+ <ViewSlot active={activeView === 'characters'}>
168
+ <CharactersView active={activeView === 'characters'} />
169
+ </ViewSlot>
170
+ )}
171
+ {mountedViews.includes('settings') && (
172
+ <ViewSlot active={activeView === 'settings'}>
173
+ <SettingsView />
174
+ </ViewSlot>
175
+ )}
176
+ {mountedViews.includes('stats') && (
177
+ <ViewSlot active={activeView === 'stats'}>
178
+ <StatsView active={activeView === 'stats'} />
179
+ </ViewSlot>
152
180
  )}
153
- {activeView === 'chat' && !activeSession && <Dashboard />}
154
- {activeView === 'characters' && <CharactersView />}
155
- {activeView === 'settings' && <SettingsView />}
156
- {activeView === 'stats' && <StatsView />}
157
181
  </main>
158
182
  </div>
159
183
  <ConfirmationDialog />
@@ -167,6 +191,48 @@ export default function App() {
167
191
  );
168
192
  }
169
193
 
194
+ /** 保持已访问的视图挂载,并隔离隐藏视图的焦点与辅助功能。 */
195
+ function ViewSlot({ active, children }: { active: boolean; children: ReactNode }) {
196
+ const ref = useRef<HTMLDivElement>(null);
197
+ const lastTheme = useRef<string | undefined>();
198
+ const revealFrame = useRef<number | null>(null);
199
+
200
+ useLayoutEffect(() => {
201
+ const el = ref.current;
202
+ if (!el) return;
203
+ if (active) {
204
+ const theme = document.documentElement.dataset.theme;
205
+ const themeChanged = lastTheme.current !== undefined && lastTheme.current !== theme;
206
+ if (themeChanged) {
207
+ // 隐藏视图在 content-visibility 下会延后解析变量;显示的首帧禁用过渡,
208
+ // 避免旧主题颜色被补绘并动画到新主题。
209
+ el.dataset.themeReveal = 'true';
210
+ revealFrame.current = window.requestAnimationFrame(() => {
211
+ revealFrame.current = window.requestAnimationFrame(() => {
212
+ delete el.dataset.themeReveal;
213
+ revealFrame.current = null;
214
+ });
215
+ });
216
+ }
217
+ lastTheme.current = theme;
218
+ el.removeAttribute('inert');
219
+ el.removeAttribute('aria-hidden');
220
+ return () => {
221
+ if (revealFrame.current != null) window.cancelAnimationFrame(revealFrame.current);
222
+ };
223
+ }
224
+ const focused = document.activeElement;
225
+ if (focused instanceof HTMLElement && el.contains(focused)) focused.blur();
226
+ el.setAttribute('inert', '');
227
+ el.setAttribute('aria-hidden', 'true');
228
+ }, [active]);
229
+ return (
230
+ <div ref={ref} className="view-slot" data-active={active ? 'true' : 'false'}>
231
+ {children}
232
+ </div>
233
+ );
234
+ }
235
+
170
236
  /** 全局注册的游戏导出/导入弹窗(供 Sidebar 与 SessionHeader 之外的入口使用) */
171
237
  function GameplayEntryDialogs() {
172
238
  const [exportTarget, setExportTarget] = useState<{ sessionId: number; includeHistory: boolean } | null>(null);
@@ -278,7 +344,7 @@ function SessionHeader({
278
344
  )}
279
345
 
280
346
  {confirmReset && (
281
- <Modal onClose={() => setConfirmReset(false)} width="min(400px, calc(100vw - 32px))">
347
+ <Modal onClose={() => setConfirmReset(false)} size="compact">
282
348
  <div className="modal-head">
283
349
  <span style={{ fontWeight: 800, fontSize: 15 }}>{t('header.resetSessionTitle')}</span>
284
350
  <button className="icon-btn" onClick={() => setConfirmReset(false)}><Icon name="x" /></button>
@@ -303,7 +369,7 @@ function SessionHeader({
303
369
  )}
304
370
 
305
371
  {confirmDelete && (
306
- <Modal onClose={() => setConfirmDelete(false)} width="min(400px, calc(100vw - 32px))">
372
+ <Modal onClose={() => setConfirmDelete(false)} size="compact">
307
373
  <div className="modal-head">
308
374
  <span style={{ fontWeight: 800, fontSize: 15 }}>{t('header.deleteTitle')}</span>
309
375
  <button className="icon-btn" onClick={() => setConfirmDelete(false)}><Icon name="x" /></button>
@@ -111,7 +111,7 @@ function CelebrationOverlay({ item }: { item: QueueItem }) {
111
111
 
112
112
  return createPortal(
113
113
  <>
114
- <div className="ach-overlay" onClick={() => dismiss(true)} />
114
+ <div className="ach-overlay" />
115
115
  <div className="ach-celebration">
116
116
  <div className={`ach-rain ${leaving ? 'leave' : ''}`}>
117
117
  {confetti.map((c) => (
@@ -132,7 +132,9 @@ function CelebrationOverlay({ item }: { item: QueueItem }) {
132
132
  ))}
133
133
  </div>
134
134
  <div className={`ach-trophy ${leaving ? 'leave' : ''}`}>
135
- <div className="ach-trophy-badge">{item.ach.icon}</div>
135
+ <div className="ach-trophy-badge">
136
+ {item.ach.iconUrl ? <img className="ach-trophy-image" src={item.ach.iconUrl} alt="" /> : item.ach.icon}
137
+ </div>
136
138
  <div className="ach-trophy-glow" />
137
139
  </div>
138
140
  <div className={`ach-caption ${leaving ? 'leave' : ''}`}>
@@ -1,4 +1,4 @@
1
- import { lazy, Suspense, useEffect, useMemo, useRef, useState } from 'react';
1
+ import { lazy, memo, Suspense, useEffect, useMemo, useRef, useState } from 'react';
2
2
  import {
3
3
  DndContext,
4
4
  closestCenter,
@@ -25,11 +25,15 @@ import { DeleteConfirmDialog } from './DeleteConfirmDialog';
25
25
  import { parseSillyTavernCardFile } from '../core/sillyTavernImporter';
26
26
  import { parseSillyTavernWorldInfoFile } from '../core/sillyTavernWorldInfo';
27
27
  import { characterBookEntryStats } from '../core/characterBook';
28
+ import { textPreview } from '../core/textPreview';
29
+ import { AVATAR_STORAGE_SIZE, shrinkAvatarDataUrl } from '../core/avatarThumbnail';
28
30
  import { ALL_BUILTIN_TOOL_NAMES } from '../core/toolDefinitions';
29
31
  import { useT } from '../core/i18n';
30
32
 
31
33
  const CharacterBookEditor = lazy(() => import('./CharacterBookEditor'));
32
34
 
35
+ type WorkshopTab = 'characters' | 'worldbooks' | 'skills';
36
+
33
37
  // 内置角色「酒馆老板」默认启用所有技能
34
38
  const ALL_DEFAULT_SKILLS = [...ALL_BUILTIN_TOOL_NAMES];
35
39
 
@@ -39,12 +43,22 @@ const ALL_DEFAULT_SKILLS = [...ALL_BUILTIN_TOOL_NAMES];
39
43
  // 由用户手动点保存
40
44
  // ============================================================
41
45
 
42
- export function CharactersView() {
46
+ export const CharactersView = memo(function CharactersView({ active = true }: { active?: boolean }) {
43
47
  const npcs = useStore((s) => s.npcs);
44
48
  const worldBooks = useStore((s) => s.worldBooks);
45
49
  const addToast = useStore((s) => s.addToast);
46
50
  const t = useT();
47
- const [tab, setTab] = useState<'characters' | 'worldbooks' | 'skills'>('characters');
51
+ const [tab, setTab] = useState<WorkshopTab>('characters');
52
+ // 懒挂载 + 常驻(与 App.tsx 的 ViewSlot 同一思路):tab 一旦打开过就不再卸载。
53
+ // 角色卡 / 世界书卡片带着大段文本和头像背景图,反复重建会把排版和解码
54
+ // 成本重复付一遍,表现就是每次切换都卡一下。
55
+ const [mountedTabs, setMountedTabs] = useState<ReadonlySet<WorkshopTab>>(
56
+ () => new Set<WorkshopTab>(['characters']),
57
+ );
58
+ const selectTab = (next: WorkshopTab) => {
59
+ setTab(next);
60
+ setMountedTabs((prev) => (prev.has(next) ? prev : new Set(prev).add(next)));
61
+ };
48
62
  const [editing, setEditing] = useState<NpcCharacter | null>(null);
49
63
  const [isNew, setIsNew] = useState(false);
50
64
  const fileRef = useRef<HTMLInputElement>(null);
@@ -55,19 +69,19 @@ export function CharactersView() {
55
69
  const refreshWb = useStore((s) => s.refreshWorldBooks);
56
70
  const refreshTools = useStore((s) => s.refreshTools);
57
71
 
58
- // 每次进入角色工坊都刷新一次,确保聊天中通过技能创建/修改的数据即时可见
72
+ // 视图常驻时按激活状态刷新。
59
73
  useEffect(() => {
60
- refresh();
61
- refreshWb();
62
- refreshTools();
63
- // eslint-disable-next-line react-hooks/exhaustive-deps
64
- }, []);
74
+ if (!active) return;
75
+ void refresh();
76
+ void refreshWb();
77
+ void refreshTools();
78
+ }, [active, refresh, refreshWb, refreshTools]);
65
79
 
66
80
  const handleImport = async (file: File) => {
67
81
  try {
68
82
  const draft = await parseSillyTavernCardFile(file);
69
- // 预填新建角色表单,由用户确认后保存
70
- setEditing({ ...draft.character, id: undefined });
83
+ const avatarDataUrl = await shrinkAvatarDataUrl(draft.character.avatarDataUrl, AVATAR_STORAGE_SIZE);
84
+ setEditing({ ...draft.character, avatarDataUrl, id: undefined });
71
85
  setIsNew(true);
72
86
  addToast(t('toast.importedChar', { name: draft.character.name, version: draft.version }));
73
87
  } catch (e) {
@@ -83,18 +97,18 @@ export function CharactersView() {
83
97
  <p className="view-sub">{t('workshop.sub')}</p>
84
98
  </div>
85
99
  <div className="side-nav" data-hscroll>
86
- <button className={`nav-chip ${tab === 'characters' ? 'active' : ''}`} onClick={() => setTab('characters')}>
100
+ <button className={`nav-chip ${tab === 'characters' ? 'active' : ''}`} onClick={() => selectTab('characters')}>
87
101
  {t('workshop.tabCharacters')}
88
102
  </button>
89
- <button className={`nav-chip ${tab === 'worldbooks' ? 'active' : ''}`} onClick={() => setTab('worldbooks')}>
103
+ <button className={`nav-chip ${tab === 'worldbooks' ? 'active' : ''}`} onClick={() => selectTab('worldbooks')}>
90
104
  {t('workshop.tabWorldbooks')}
91
105
  </button>
92
- <button className={`nav-chip ${tab === 'skills' ? 'active' : ''}`} onClick={() => setTab('skills')}>
106
+ <button className={`nav-chip ${tab === 'skills' ? 'active' : ''}`} onClick={() => selectTab('skills')}>
93
107
  {t('workshop.tabSkills')}
94
108
  </button>
95
109
  </div>
96
110
 
97
- {tab === 'characters' && (
111
+ <div className="workshop-tab-panel" data-active={tab === 'characters' ? 'true' : 'false'}>
98
112
  <CharacterGrid
99
113
  npcs={npcs}
100
114
  onEdit={(n, isNew) => {
@@ -103,9 +117,13 @@ export function CharactersView() {
103
117
  }}
104
118
  onImportPng={openFilePicker}
105
119
  />
106
- )}
107
- {tab === 'worldbooks' && <WorldBookList books={worldBooks} onChanged={refreshWb} />}
108
- {tab === 'skills' && <SkillList />}
120
+ </div>
121
+ <div className="workshop-tab-panel" data-active={tab === 'worldbooks' ? 'true' : 'false'}>
122
+ {mountedTabs.has('worldbooks') && <WorldBookList books={worldBooks} onChanged={refreshWb} />}
123
+ </div>
124
+ <div className="workshop-tab-panel" data-active={tab === 'skills' ? 'true' : 'false'}>
125
+ {mountedTabs.has('skills') && <SkillList />}
126
+ </div>
109
127
  </div>
110
128
  <input
111
129
  ref={fileRef}
@@ -134,7 +152,7 @@ export function CharactersView() {
134
152
  )}
135
153
  </div>
136
154
  );
137
- }
155
+ });
138
156
 
139
157
  // ---------------- 角色网格 ----------------
140
158
 
@@ -188,7 +206,7 @@ function CharacterGrid({ npcs, onEdit, onImportPng }: { npcs: NpcCharacter[]; on
188
206
  <ScrollingCardName name={n.name} />
189
207
  {n.isBuiltIn && <span className="tag">{t('common.builtin')}</span>}
190
208
  </div>
191
- <div className="cgreet">{n.greeting || t('workshop.noGreeting')}</div>
209
+ <div className="cgreet">{textPreview(n.greeting) || t('workshop.noGreeting')}</div>
192
210
  {/* 技能区固定渲染(哪怕无技能),保证所有卡片高度一致 */}
193
211
  <div className="cskil">
194
212
  {n.enabledToolNames.map((s) => (
@@ -328,7 +346,10 @@ function CharacterEditorModal({ npc, isNew, onClose, onSaved }: { npc: NpcCharac
328
346
  const f = e.target.files?.[0];
329
347
  if (f) {
330
348
  const reader = new FileReader();
331
- reader.onload = () => setAvatarDataUrl(reader.result as string);
349
+ reader.onload = () => {
350
+ const raw = reader.result as string;
351
+ void shrinkAvatarDataUrl(raw, AVATAR_STORAGE_SIZE).then((url) => setAvatarDataUrl(url));
352
+ };
332
353
  reader.readAsDataURL(f);
333
354
  }
334
355
  }} />
@@ -451,6 +472,13 @@ function WorldBookList({ books, onChanged }: {
451
472
  const [editorTab, setEditorTab] = useState<'worldbook' | 'knowledge'>('worldbook');
452
473
  const [pendingDelete, setPendingDelete] = useState<WorldBook | null>(null);
453
474
  const jsonFileRef = useRef<HTMLInputElement>(null);
475
+ const statsByBook = useMemo(() => {
476
+ const map = new Map<number, { total: number; enabled: number }>();
477
+ for (const book of books) {
478
+ if (book.id != null) map.set(book.id, characterBookEntryStats(book.characterBook));
479
+ }
480
+ return map;
481
+ }, [books]);
454
482
 
455
483
  const closeEditor = () => {
456
484
  setEditing(null);
@@ -556,7 +584,7 @@ function WorldBookList({ books, onChanged }: {
556
584
  <MasonryGrid>
557
585
  {books.map((b) => {
558
586
  const isBuiltin = isBuiltinTavernHandbook(b);
559
- const knowledge = characterBookEntryStats(b.characterBook);
587
+ const knowledge = (b.id != null ? statsByBook.get(b.id) : undefined) ?? { total: 0, enabled: 0 };
560
588
  const meta = [
561
589
  b.content ? t('workshop.wbChars', { n: b.content.length }) : '',
562
590
  knowledge.total > 0 ? t('workshop.wbKnowledgeMeta', { enabled: knowledge.enabled, total: knowledge.total }) : '',
@@ -568,7 +596,7 @@ function WorldBookList({ books, onChanged }: {
568
596
  <ScrollingCardName name={b.name} />
569
597
  {isBuiltin && <span className="tag">{t('common.builtin')}</span>}
570
598
  </div>
571
- <div className="wcontent">{b.content || t('workshop.wbNoContent')}</div>
599
+ <div className="wcontent">{textPreview(b.content) || t('workshop.wbNoContent')}</div>
572
600
  <div className="cmeta">{meta}</div>
573
601
  <div className="cactions">
574
602
  <button className="btn btn-sm" onClick={() => openEditor(b)}><Icon name="settings" size={12} /> {t('workshop.browseEdit')}</button>
@@ -652,7 +680,7 @@ function WorldBookForm({
652
680
  const [characterBook, setCharacterBook] = useState(initial.characterBook ?? '');
653
681
  const [renderMarkdown, setRenderMarkdown] = useState(false);
654
682
  const isBuiltin = isBuiltinTavernHandbook(initial);
655
- const knowledge = characterBookEntryStats(characterBook);
683
+ const knowledge = useMemo(() => characterBookEntryStats(characterBook), [characterBook]);
656
684
  const isEditing = 'id' in initial && initial.id != null;
657
685
 
658
686
  const resetToDefault = () => {
@@ -1030,7 +1058,7 @@ function SkillDetailModal({ tool, onClose }: { tool: McpTool; onClose: () => voi
1030
1058
  };
1031
1059
 
1032
1060
  return (
1033
- <Modal onClose={onClose} width={620}>
1061
+ <Modal onClose={onClose}>
1034
1062
  <div className="modal-head">
1035
1063
  <span style={{ fontWeight: 800, fontSize: 15 }}>
1036
1064
  {t('workshop.skillDetails')}