tavern-harness 0.2.3 → 0.2.5

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.5] - 2026-11-23
7
+
8
+ ### 中文
9
+
10
+ #### 新增
11
+
12
+ - 新增首次进入的交互式新手引导:聚光灯依次指向「设置 → API 配置 → 添加供应商 → 填写名称 / Base URL / API Key → 测试连接 → 保存 → 新建对话 → 选择酒馆老板 → 选择模型 → 发送第一条消息」,并在最后自动填入一句开场提问;支持简体中文、繁体中文和英文,可随时跳过,跳过后不再自动出现
13
+ - 仪表盘新增「酒馆说明书」区域,第一章可随时重新开始新手引导
14
+ - 仪表盘顶部新增「打开介绍页」入口
15
+
16
+ #### 改进
17
+
18
+ - 仪表盘移除「与角色继续对话」列表,顶部操作精简为 GitHub、介绍页和 WIKI,页面更聚焦于角色卡片与新手引导
19
+ - WIKI 入口文案缩短为「打开 WIKI」
20
+
21
+ #### 修复
22
+
23
+ - 修复窄屏下从侧边栏新建对话成功后,抽屉和遮罩仍盖在主区域上方、挡住后续操作的问题;现在创建成功会自动收起侧边栏,编辑已有会话不触发
24
+ - 修复侧边栏、弹窗等滚动容器在收起、隐藏或播放切换动画后残留悬浮滚动条的问题;容器不可见时会立即清理滚动条浮层
25
+
26
+ #### 内部
27
+
28
+ - 滚动条模块新增 ResizeObserver、MutationObserver 以及过渡和动画监听,统一回收不可见容器的浮层
29
+ - 新手引导通过事件与 `data-opening-target` 标记驱动,完成状态写入 localStorage
30
+ - 移除仪表盘不再使用的会话预览、相对时间格式化代码及对应 i18n 文案
31
+
32
+ ### English
33
+
34
+ #### Added
35
+
36
+ - Added an interactive first-run guide: a spotlight walks through Settings → API Configuration → add a provider → enter name / Base URL / API key → test the connection → save → create a chat → pick the Tavern Keeper → choose a model → send the first message, with a starter question pre-filled at the end. Available in Simplified Chinese, Traditional Chinese, and English, skippable at any time, and it won't reappear once skipped
37
+ - Added a Tavern Manual section on the dashboard; Chapter 1 restarts the guide at any time
38
+ - Added an "Open introduction page" action to the dashboard hero
39
+
40
+ #### Changed
41
+
42
+ - Removed the "Continue character conversations" list from the dashboard and trimmed the hero actions to GitHub, the introduction page, and the WIKI, focusing the page on character cards and onboarding
43
+ - Shortened the WIKI action label to "Open WIKI"
44
+
45
+ #### Fixed
46
+
47
+ - Fixed the sidebar drawer and overlay staying over the main area after creating a chat on narrow screens and blocking the next step; the drawer now closes after a successful create and stays open when editing an existing chat
48
+ - Fixed stale floating scrollbars left behind when scroll containers collapse, hide, or run transition animations; overlay thumbs are now removed as soon as the container is not visible
49
+
50
+ #### Internal
51
+
52
+ - The scrollbar module now uses ResizeObserver, MutationObserver, and transition/animation listeners to reclaim overlays for hidden containers
53
+ - The opening guide is driven by events and `data-opening-target` markers, with completion persisted in localStorage
54
+ - Removed unused dashboard session-preview and relative-time formatting code and their i18n strings
55
+
56
+ ## [0.2.4] - 2026-11-22
57
+
58
+ ### 中文
59
+
60
+ #### 修复
61
+
62
+ - 修复通过 `/nsfw` 或长按发送键注入破甲指令后,重新生成该回复时不再注入破甲指令的问题;现在重新生成会读取当前会话最新的破甲指令并临时注入
63
+
64
+ ### English
65
+
66
+ #### Fixed
67
+
68
+ - Fixed regenerating a reply that was sent with `/nsfw` or hold-to-charge losing the armor-breaking injection; regeneration now applies the latest armor-breaking instruction configured for the conversation
69
+
6
70
  ## [0.2.3] - 2026-11-21
7
71
 
8
72
  ### 中文
@@ -1141,6 +1205,8 @@
1141
1205
  - Vite + React + Zustand + Dexie stack with browser-side local persistence
1142
1206
 
1143
1207
  <!-- 链接定义 -->
1208
+ [0.2.5]: https://github.com/Rannichan/Tavern-Harness/compare/v0.2.4...v0.2.5
1209
+ [0.2.4]: https://github.com/Rannichan/Tavern-Harness/compare/v0.2.3...v0.2.4
1144
1210
  [0.2.3]: https://github.com/Rannichan/Tavern-Harness/compare/v0.2.2...v0.2.3
1145
1211
  [0.2.2]: https://github.com/Rannichan/Tavern-Harness/compare/v0.2.1...v0.2.2
1146
1212
  [0.2.1]: https://github.com/Rannichan/Tavern-Harness/compare/v0.2.0...v0.2.1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tavern-harness",
3
- "version": "0.2.3",
3
+ "version": "0.2.5",
4
4
  "description": "Tavern Harness — 酒馆模式下的本地 AI Agent 助手(MyAgent-Android 的 Web 复刻)",
5
5
  "private": false,
6
6
  "type": "module",
package/src/App.tsx CHANGED
@@ -13,6 +13,7 @@ import { WorkspaceFileManagerModal } from './components/WorkspaceFileManagerModa
13
13
  import { Toasts } from './components/Toasts';
14
14
  import { AchievementModal, showAchievementUnlock } from './components/AchievementModal';
15
15
  import { GameplayExportModal, GameplayImportModal } from './components/GameplayDialogs';
16
+ import { OpeningGuide } from './components/OpeningGuide';
16
17
  import { Icon, SessionVisual, Modal } from './components/shared';
17
18
  import type { NpcCharacter } from './types/models';
18
19
  import { registerUnlockDispatcher } from './core/achievements';
@@ -225,6 +226,7 @@ export default function App() {
225
226
  <Toasts />
226
227
  <AchievementModal />
227
228
  <FileDisplayModal />
229
+ <OpeningGuide />
228
230
  {/* 游戏导出 / 导入的全局入口(会话右键菜单 / 侧边栏导入按钮共用) */}
229
231
  <GameplayEntryDialogs />
230
232
  </>
@@ -856,6 +856,7 @@ export function ChatInput({ sessionId }: { sessionId: number }) {
856
856
  sendingAttachments.map((a) => a.dataUrl),
857
857
  sendingAttachments.map((a) => a.name)
858
858
  );
859
+ window.dispatchEvent(new CustomEvent('th-opening-message-sent'));
859
860
  };
860
861
  send().catch((error: unknown) => {
861
862
  // 发送链路本身也可能失败(例如另一个浏览器持有了写锁):不能静默丢掉
@@ -918,6 +919,15 @@ export function ChatInput({ sessionId }: { sessionId: number }) {
918
919
  setTimeout(() => setSendChargeState('idle'), 420);
919
920
  };
920
921
 
922
+ useEffect(() => {
923
+ const prefill = (event: Event) => {
924
+ const question = (event as CustomEvent<string>).detail;
925
+ if (question) setText(question);
926
+ };
927
+ window.addEventListener('th-opening-prefill', prefill);
928
+ return () => window.removeEventListener('th-opening-prefill', prefill);
929
+ }, []);
930
+
921
931
  useEffect(() => () => {
922
932
  if (sendChargeTimerRef.current) clearTimeout(sendChargeTimerRef.current);
923
933
  if (navigator.vibrate) navigator.vibrate(0);
@@ -1095,6 +1105,7 @@ export function ChatInput({ sessionId }: { sessionId: number }) {
1095
1105
  {/* 模型选择器:输入框左侧,弹出列表(非弹窗) */}
1096
1106
  <div className="composer-model">
1097
1107
  <button
1108
+ data-opening-target="model-button"
1098
1109
  className={`composer-model-btn ${showModels ? 'open' : ''}`}
1099
1110
  title={t('chat.selectModel')}
1100
1111
  aria-expanded={showModels}
@@ -1253,6 +1264,7 @@ export function ChatInput({ sessionId }: { sessionId: number }) {
1253
1264
  </button>
1254
1265
  ) : (
1255
1266
  <button
1267
+ data-opening-target="message-send"
1256
1268
  className={`btn btn-primary btn-round send-charge${sendChargeState !== 'idle' ? ` ${sendChargeState}` : ''}`}
1257
1269
  disabled={!canSend || typing}
1258
1270
  onClick={() => {
@@ -1331,9 +1343,13 @@ function ModelPickerPanel({ onClose }: { onClose: () => void }) {
1331
1343
  <div className="model-popover-list">
1332
1344
  {models.map((option) => {
1333
1345
  const active = option.providerId === selectedProviderId && option.modelId === selected;
1346
+ const openingProviderValue = document.documentElement.getAttribute('data-opening-provider-id');
1347
+ const openingProviderId = openingProviderValue == null ? null : Number(openingProviderValue);
1348
+ const isOpeningModel = openingProviderId == null || openingProviderId === option.providerId;
1334
1349
  return (
1335
1350
  <button
1336
1351
  key={`${option.providerId}:${option.modelId}`}
1352
+ data-opening-target={isOpeningModel ? 'model-option' : undefined}
1337
1353
  className={`model-option ${active ? 'active' : ''}`}
1338
1354
  onClick={() => pick(option)}
1339
1355
  >
@@ -1,12 +1,9 @@
1
- import { memo, useEffect, useMemo, useState } from 'react';
1
+ import { memo } from 'react';
2
2
  import { createSession, useStore } from '../store/store';
3
- import { db } from '../db/database';
4
- import { Avatar, Icon, MasonryGrid, SessionVisual } from './shared';
5
- import { NewSessionMenu } from './NewSessionMenu';
6
- import { useT, currentLocale } from '../core/i18n';
3
+ import { Avatar, Icon, MasonryGrid } from './shared';
4
+ import { useT } from '../core/i18n';
7
5
  import { textPreview } from '../core/textPreview';
8
- import type { SessionMember } from './shared';
9
- import type { NpcCharacter } from '../types/models';
6
+ import { restartOpeningGuide } from './OpeningGuide';
10
7
 
11
8
  // ============================================================
12
9
  // 仪表盘(无活动会话时的起始页)
@@ -14,9 +11,7 @@ import type { NpcCharacter } from '../types/models';
14
11
 
15
12
  export const Dashboard = memo(function Dashboard() {
16
13
  const npcs = useStore((s) => s.npcs);
17
- const sessions = useStore((s) => s.sessions);
18
14
  const t = useT();
19
- const [showNew, setShowNew] = useState(false);
20
15
 
21
16
  const startNpc = async (id: number) => {
22
17
  const sid = await createSession('NPC', { associatedId: id });
@@ -24,59 +19,6 @@ export const Dashboard = memo(function Dashboard() {
24
19
  useStore.getState().setActiveSession(sid);
25
20
  };
26
21
 
27
- // 群聊会话 → 参与者中的 NPC 角色(用于群头像拼贴,每个会话一次)
28
- const [groupMembers, setGroupMembers] = useState<Record<number, NpcCharacter[]>>({});
29
- useEffect(() => {
30
- const groupSessions = sessions.filter((s) => s.mode === 'GROUP');
31
- if (groupSessions.length === 0) return;
32
- let cancelled = false;
33
- (async () => {
34
- const loaded: Record<number, NpcCharacter[]> = {};
35
- await Promise.all(
36
- groupSessions.map(async (s) => {
37
- const parts = await db.participants.where('sessionId').equals(s.id!).toArray();
38
- const npcs1 = parts
39
- .filter((p) => p.kind === 'NPC' && p.npcId != null)
40
- .map((p) => npcs.find((n) => n.id === p.npcId))
41
- .filter((n): n is NpcCharacter => Boolean(n));
42
- loaded[s.id!] = npcs1;
43
- })
44
- );
45
- if (!cancelled) setGroupMembers(loaded);
46
- })();
47
- return () => {
48
- cancelled = true;
49
- };
50
- }, [sessions, npcs]);
51
-
52
- // 与角色继续对话:最近按 updatedAt 排序的 3 个有实际内容的会话(最新在前)
53
- const recentSessions = useMemo(() => {
54
- return sessions
55
- .filter((s) => s.mode !== 'STANDARD')
56
- .sort((a, b) => b.updatedAt - a.updatedAt)
57
- .slice(0, 3);
58
- }, [sessions]);
59
-
60
- // 会话缩略标题:使用最后一条消息的首行,截断到 42 字符
61
- const sessionPreview = (s: (typeof sessions)[number]) => {
62
- const text = s.lastMessage || (s.mode === 'GROUP' ? t('dash.groupSession') : t('dash.newSession'));
63
- const line = text.trim().split('\n').find(Boolean) ?? '';
64
- return line.length > 42 ? `${line.slice(0, 42)}…` : line;
65
- };
66
-
67
- // 会话相对时间(刚刚 / N 分钟前 / N 小时前 / N 天前),与界面语言一致
68
- const sessionTime = (ts: number) => {
69
- const diff = Date.now() - ts;
70
- const min = Math.floor(diff / 60000);
71
- const hour = Math.floor(diff / 3600000);
72
- const day = Math.floor(diff / 86400000);
73
- if (min < 1) return t('dash.timeJustNow');
74
- if (min < 60) return t('dash.timeMinAgo', { n: min });
75
- if (hour < 24) return t('dash.timeHourAgo', { n: hour });
76
- if (day < 30) return t('dash.timeDayAgo', { n: day });
77
- return new Date(ts).toLocaleDateString(currentLocale());
78
- };
79
-
80
22
  return (
81
23
  <div className="dash-scroll">
82
24
  <div className="dash">
@@ -87,74 +29,29 @@ export const Dashboard = memo(function Dashboard() {
87
29
  <span className="dash-hero-accent">{t('dash.heroAccent')}</span>
88
30
  </p>
89
31
  <div className="actions">
90
- <button className="btn btn-primary" onClick={() => setShowNew(true)}>
91
- <Icon name="plus" size={14} /> {t('dash.newChat')}
92
- </button>
93
- <button
94
- className="btn"
95
- onClick={() => {
96
- useStore.getState().setActiveView('characters');
97
- }}
98
- >
99
- <Icon name="users" size={14} /> {t('dash.goCharacters')}
100
- </button>
32
+ <a className="btn btn-primary" href="https://github.com/Rannichan/Tavern-Harness" target="_blank" rel="noreferrer">
33
+ <span className="github-icon" aria-hidden="true" /> {t('dash.openGitHub')}
34
+ </a>
35
+ <a className="btn" href="https://rannichan.github.io/Tavern-Harness/index.html" target="_blank" rel="noreferrer">
36
+ <Icon name="open-in-new" size={14} /> {t('dash.openIntro')}
37
+ </a>
101
38
  <a className="btn" href="https://rannichan.github.io/Tavern-Harness/wiki.html" target="_blank" rel="noreferrer">
102
39
  <Icon name="book" size={14} /> {t('dash.openWiki')}
103
40
  </a>
104
- <a className="btn" href="https://github.com/Rannichan/Tavern-Harness" target="_blank" rel="noreferrer">
105
- <span className="github-icon" aria-hidden="true" /> {t('dash.openGitHub')}
106
- </a>
107
41
  </div>
108
42
  </div>
109
43
 
110
- <div>
111
- <span className="section-title">{t('dash.continue')}</span>
112
- {recentSessions.length === 0 ? (
113
- <div className="card empty-state">
114
- <div className="big">🍺</div>
115
- <span>{t('dash.noCharConv')}</span>
116
- </div>
117
- ) : (
118
- <div className="recent-list">
119
- {recentSessions.map((s) => {
120
- const npc = npcs.find((n) => n.id === s.associatedId);
121
- const members: SessionMember[] | undefined =
122
- s.mode === 'GROUP'
123
- ? (groupMembers[s.id!] ?? []).slice(0, 4).map((n) => ({
124
- name: n.name,
125
- colorOrdinal: n.avatarColorOrdinal,
126
- imageUrl: n.avatarDataUrl,
127
- }))
128
- : undefined;
129
- return (
130
- <button
131
- key={s.id}
132
- className="recent-item"
133
- onClick={() => useStore.getState().setActiveSession(s.id!)}
134
- >
135
- <SessionVisual
136
- mode={s.mode}
137
- npcName={npc?.name}
138
- hue={npc?.avatarColorOrdinal}
139
- imageUrl={npc?.avatarDataUrl}
140
- members={members}
141
- />
142
- <div className="recent-meta">
143
- <div className="recent-title">
144
- <span className="recent-title-text">{s.title}</span>
145
- <span className="recent-time">{sessionTime(s.updatedAt)}</span>
146
- </div>
147
- <div className="recent-preview">{sessionPreview(s)}</div>
148
- </div>
149
- <span className="recent-go">
150
- <Icon name="send" size={13} />
151
- </span>
152
- </button>
153
- );
154
- })}
155
- </div>
156
- )}
157
- </div>
44
+ <section className="tavern-manual">
45
+ <span className="section-title">{t('dash.manual')}</span>
46
+ <button className="manual-chapter" onClick={restartOpeningGuide}>
47
+ <span className="manual-chapter-icon"><Icon name="book" size={18} /></span>
48
+ <span className="manual-chapter-copy">
49
+ <strong>{t('dash.manualChapterOne')}</strong>
50
+ <span>{t('dash.manualChapterOneDesc')}</span>
51
+ </span>
52
+ <span className="manual-chapter-action">{t('dash.manualStart')} <Icon name="send" size={13} /></span>
53
+ </button>
54
+ </section>
158
55
 
159
56
  <div>
160
57
  <span className="section-title">{t('dash.regulars')}</span>
@@ -180,8 +77,6 @@ export const Dashboard = memo(function Dashboard() {
180
77
  </MasonryGrid>
181
78
  </div>
182
79
  </div>
183
-
184
- {showNew && <NewSessionMenu onClose={() => setShowNew(false)} />}
185
80
  </div>
186
81
  );
187
82
  });
@@ -37,7 +37,12 @@ const restrictToSortList: Modifier = ({ transform, activeNodeRect, containerNode
37
37
  return { ...transform, x, y };
38
38
  };
39
39
 
40
- export function NewSessionMenu({ onClose, editingSession }: { onClose: () => void; editingSession?: ChatSession | null }) {
40
+ export function NewSessionMenu({ onClose, onCreated, editingSession }: {
41
+ onClose: () => void;
42
+ /** 新建成功后回调(编辑已有会话不触发);用于窄屏收起侧边栏等页面级收尾。 */
43
+ onCreated?: () => void;
44
+ editingSession?: ChatSession | null;
45
+ }) {
41
46
  const npcs = useStore((s) => s.npcs);
42
47
  const worldBooks = useStore((s) => s.worldBooks);
43
48
  const addToast = useStore((s) => s.addToast);
@@ -129,7 +134,9 @@ export function NewSessionMenu({ onClose, editingSession }: { onClose: () => voi
129
134
  });
130
135
  await useStore.getState().refreshSessions();
131
136
  useStore.getState().setActiveSession(sid);
137
+ onCreated?.();
132
138
  onClose();
139
+ window.dispatchEvent(new CustomEvent('th-opening-session-created'));
133
140
  } catch (error) {
134
141
  if (isEditing) addToast(t('toast.sessionSaveFailed', { msg: (error as Error).message }), 'error');
135
142
  else addToast(t('toast.genFailed', { msg: (error as Error).message }), 'error');
@@ -297,7 +304,7 @@ export function NewSessionMenu({ onClose, editingSession }: { onClose: () => voi
297
304
  </div>
298
305
  <div className="modal-foot">
299
306
  <button className="btn" onClick={onClose}>{t('common.cancel')}</button>
300
- <button className="btn btn-primary" disabled={!canCreate || saving} onClick={create}>{isEditing ? t('common.save') : t('common.ok')}</button>
307
+ <button data-opening-target="create-chat" className="btn btn-primary" disabled={!canCreate || saving} onClick={create}>{isEditing ? t('common.save') : t('common.ok')}</button>
301
308
  </div>
302
309
  </Modal>
303
310
  );
@@ -358,6 +365,7 @@ function SlotPicker({ excluded, onPick }: { excluded: number[]; onPick: (npcId:
358
365
  return (
359
366
  <div className="slot-picker">
360
367
  <button
368
+ data-opening-target="add-owner"
361
369
  className="npc-slot-add"
362
370
  title={t('newSession.addCharTip')}
363
371
  onClick={(e) => { e.stopPropagation(); setOpen(!open); }}
@@ -367,7 +375,7 @@ function SlotPicker({ excluded, onPick }: { excluded: number[]; onPick: (npcId:
367
375
  {open && (
368
376
  <div className="slot-picker-menu card">
369
377
  {available.map((n) => (
370
- <button key={n.id} className="slot-picker-item" onClick={() => { onPick(n.id!); setOpen(false); }}>
378
+ <button key={n.id} data-opening-target={n.isTavernKeeper ? 'owner-option' : undefined} className="slot-picker-item" onClick={() => { onPick(n.id!); setOpen(false); }}>
371
379
  <Avatar name={n.name} colorOrdinal={n.avatarColorOrdinal} imageUrl={n.avatarDataUrl} size="xs" />
372
380
  <span>{n.name}</span>
373
381
  </button>
@@ -0,0 +1,186 @@
1
+ import { useEffect, useLayoutEffect, useMemo, useState } from 'react';
2
+ import { useStore } from '../store/store';
3
+ import { useT } from '../core/i18n';
4
+
5
+ const STORAGE_KEY = 'th-opening-completed-v1';
6
+ const RESTART_EVENT = 'th-opening-restart';
7
+
8
+ export function restartOpeningGuide() {
9
+ localStorage.removeItem(STORAGE_KEY);
10
+ window.dispatchEvent(new CustomEvent(RESTART_EVENT));
11
+ }
12
+
13
+ type OpeningStep =
14
+ | 'settings'
15
+ | 'api'
16
+ | 'add-provider'
17
+ | 'provider-name'
18
+ | 'provider-base-url'
19
+ | 'provider-api-key'
20
+ | 'provider-test'
21
+ | 'provider-save'
22
+ | 'new-chat'
23
+ | 'add-owner'
24
+ | 'owner-option'
25
+ | 'create-chat'
26
+ | 'model-button'
27
+ | 'model-option'
28
+ | 'message-send';
29
+
30
+ const STEPS: OpeningStep[] = [
31
+ 'settings', 'api', 'add-provider', 'provider-name', 'provider-base-url', 'provider-api-key', 'provider-test', 'provider-save', 'new-chat',
32
+ 'add-owner', 'owner-option', 'create-chat', 'model-button', 'model-option', 'message-send',
33
+ ];
34
+
35
+ const NEXT_ON_CLICK: Partial<Record<OpeningStep, OpeningStep>> = {
36
+ settings: 'api',
37
+ api: 'add-provider',
38
+ 'add-provider': 'provider-name',
39
+ 'new-chat': 'add-owner',
40
+ 'add-owner': 'owner-option',
41
+ 'owner-option': 'create-chat',
42
+ 'model-button': 'model-option',
43
+ 'model-option': 'message-send',
44
+ };
45
+
46
+ export function OpeningGuide() {
47
+ const t = useT();
48
+ const initStatus = useStore((state) => state.initStatus);
49
+ const [step, setStep] = useState<OpeningStep | null>(null);
50
+ const [rect, setRect] = useState<DOMRect | null>(null);
51
+ const [savedProviderId, setSavedProviderId] = useState<number | null>(null);
52
+ const question = t('opening.question');
53
+
54
+ useEffect(() => {
55
+ if (savedProviderId == null) document.documentElement.removeAttribute('data-opening-provider-id');
56
+ else document.documentElement.setAttribute('data-opening-provider-id', String(savedProviderId));
57
+ return () => document.documentElement.removeAttribute('data-opening-provider-id');
58
+ }, [savedProviderId]);
59
+
60
+ useEffect(() => {
61
+ if (initStatus !== 'ready') return;
62
+ const restartFromBeginning = () => {
63
+ setSavedProviderId(null);
64
+ setStep('settings');
65
+ };
66
+ if (!localStorage.getItem(STORAGE_KEY)) {
67
+ const state = useStore.getState();
68
+ setStep(state.providers.length > 0 ? (state.sessions.length > 0 ? 'model-button' : 'new-chat') : 'settings');
69
+ }
70
+ window.addEventListener(RESTART_EVENT, restartFromBeginning);
71
+ return () => window.removeEventListener(RESTART_EVENT, restartFromBeginning);
72
+ }, [initStatus]);
73
+
74
+ useEffect(() => {
75
+ if (!step) return;
76
+ const onClick = (event: MouseEvent) => {
77
+ const target = event.target instanceof Element ? event.target.closest(`[data-opening-target="${step}"]`) : null;
78
+ if (!target || target.hasAttribute('disabled') || target.getClientRects().length === 0) return;
79
+ const next = NEXT_ON_CLICK[step];
80
+ if (next) window.setTimeout(() => setStep(next), 0);
81
+ };
82
+ const onFieldCompleted = (event: Event) => {
83
+ const completed = (event as CustomEvent<OpeningStep>).detail;
84
+ setStep((current) => current === completed
85
+ ? completed === 'provider-name' ? 'provider-base-url'
86
+ : completed === 'provider-base-url' ? 'provider-api-key'
87
+ : completed === 'provider-api-key' ? 'provider-test'
88
+ : current
89
+ : current);
90
+ };
91
+ const onTested = () => setStep((current) => current === 'provider-test' ? 'provider-save' : current);
92
+ const onSaved = (event: Event) => setStep((current) => {
93
+ if (current !== 'provider-save') return current;
94
+ const providerId = (event as CustomEvent<number>).detail;
95
+ if (Number.isFinite(providerId)) setSavedProviderId(providerId);
96
+ window.setTimeout(() => window.dispatchEvent(new CustomEvent('th-opening-show-new-chat')), 0);
97
+ return 'new-chat';
98
+ });
99
+ const onCreated = () => setStep((current) => current === 'create-chat' ? 'model-button' : current);
100
+ const onSent = () => setStep((current) => {
101
+ if (current === 'message-send') {
102
+ localStorage.setItem(STORAGE_KEY, 'true');
103
+ return null;
104
+ }
105
+ return current;
106
+ });
107
+ document.addEventListener('click', onClick, true);
108
+ window.addEventListener('th-opening-field-completed', onFieldCompleted);
109
+ window.addEventListener('th-opening-provider-tested', onTested);
110
+ window.addEventListener('th-opening-provider-saved', onSaved);
111
+ window.addEventListener('th-opening-session-created', onCreated);
112
+ window.addEventListener('th-opening-message-sent', onSent);
113
+ return () => {
114
+ document.removeEventListener('click', onClick, true);
115
+ window.removeEventListener('th-opening-field-completed', onFieldCompleted);
116
+ window.removeEventListener('th-opening-provider-tested', onTested);
117
+ window.removeEventListener('th-opening-provider-saved', onSaved);
118
+ window.removeEventListener('th-opening-session-created', onCreated);
119
+ window.removeEventListener('th-opening-message-sent', onSent);
120
+ };
121
+ }, [step]);
122
+
123
+ useEffect(() => {
124
+ if (step === 'message-send') window.dispatchEvent(new CustomEvent('th-opening-prefill', { detail: question }));
125
+ }, [step, question]);
126
+
127
+ useLayoutEffect(() => {
128
+ if (!step) return;
129
+ let frame = 0;
130
+ const update = () => {
131
+ cancelAnimationFrame(frame);
132
+ frame = requestAnimationFrame(() => {
133
+ const element = [...document.querySelectorAll<HTMLElement>(`[data-opening-target="${step}"]`)]
134
+ .find((candidate) => candidate.getClientRects().length > 0);
135
+ if (element) {
136
+ element.scrollIntoView({ block: 'nearest', inline: 'nearest' });
137
+ setRect(element.getBoundingClientRect());
138
+ } else {
139
+ setRect(null);
140
+ }
141
+ });
142
+ };
143
+ update();
144
+ const observer = new MutationObserver(update);
145
+ observer.observe(document.body, { childList: true, subtree: true, attributes: true });
146
+ window.addEventListener('resize', update);
147
+ window.addEventListener('scroll', update, true);
148
+ return () => {
149
+ cancelAnimationFrame(frame);
150
+ observer.disconnect();
151
+ window.removeEventListener('resize', update);
152
+ window.removeEventListener('scroll', update, true);
153
+ };
154
+ }, [step]);
155
+
156
+ const progress = useMemo(() => step ? Math.max(1, Math.ceil(((STEPS.indexOf(step) + 1) / STEPS.length) * 5)) : 0, [step]);
157
+ if (!step || !rect) return null;
158
+
159
+ const pad = 7;
160
+ const hole = {
161
+ left: Math.max(6, rect.left - pad),
162
+ top: Math.max(6, rect.top - pad),
163
+ width: Math.min(window.innerWidth - 12, rect.width + pad * 2),
164
+ height: Math.min(window.innerHeight - 12, rect.height + pad * 2),
165
+ };
166
+ const cardBelow = hole.top + hole.height + 16;
167
+ const cardTop = cardBelow + 190 < window.innerHeight ? cardBelow : Math.max(12, hole.top - 176);
168
+ const cardLeft = Math.min(Math.max(12, hole.left), window.innerWidth - 332);
169
+
170
+ function finish() {
171
+ localStorage.setItem(STORAGE_KEY, 'true');
172
+ setStep(null);
173
+ }
174
+
175
+ return (
176
+ <div className="opening-guide" aria-live="polite">
177
+ <div className="opening-guide-spotlight" style={hole} />
178
+ <section className="opening-guide-card" style={{ top: cardTop, left: cardLeft }}>
179
+ <div className="opening-guide-progress">{t('opening.progress', { current: progress, total: 5 })}</div>
180
+ <h2>{t(`opening.${step}.title`)}</h2>
181
+ <p>{t(`opening.${step}.body`, { question })}</p>
182
+ <button type="button" onClick={finish}>{t('opening.skip')}</button>
183
+ </section>
184
+ </div>
185
+ );
186
+ }