@tbox.cn/app-agent-ui-kit 1.0.0-alpha.13 → 1.0.0-alpha.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 (35) hide show
  1. package/package.json +3 -3
  2. package/src/ChatPage.tsx +77 -151
  3. package/src/card/action-list-pending.test.tsx +96 -31
  4. package/src/card/primitives.test.tsx +20 -7
  5. package/src/card/primitives.tsx +54 -41
  6. package/src/card/use-card-actions.ts +23 -14
  7. package/src/card/view-card-inline.test.tsx +34 -2
  8. package/src/card/view-card.test.tsx +3 -3
  9. package/src/card/view-card.tsx +24 -29
  10. package/src/chat-config.test.ts +13 -8
  11. package/src/chat-config.ts +29 -8
  12. package/src/components/ChatInput/index.test.tsx +37 -0
  13. package/src/components/ChatInput/index.tsx +19 -6
  14. package/src/components/ChatInput/use-auto-rows.test.tsx +78 -0
  15. package/src/components/ChatInput/use-auto-rows.ts +68 -0
  16. package/src/components/HistoryEntry/index.tsx +3 -1
  17. package/src/components/HistoryList.tsx +52 -0
  18. package/src/components/MessageBubble/index.tsx +2 -3
  19. package/src/components/QuickCommands/index.test.tsx +25 -5
  20. package/src/components/QuickCommands/index.tsx +30 -27
  21. package/src/hooks/use-pull-down-history.ts +3 -4
  22. package/src/hooks/use-pull-down-wheel-native.test.ts +4 -8
  23. package/src/hooks/use-stick-to-bottom.test.tsx +142 -0
  24. package/src/hooks/use-stick-to-bottom.ts +218 -0
  25. package/src/index.ts +1 -2
  26. package/src/preview-provider.tsx +2 -1
  27. package/src/shell.contract.json +12 -13
  28. package/src/shell.test.ts +107 -11
  29. package/src/shell.ts +13 -10
  30. package/src/test/setup.ts +31 -0
  31. package/src/theme/base.css +5 -0
  32. package/src/theme/contract.json +1 -0
  33. package/src/theme/tokens.css +1 -0
  34. package/src/components/ChatHeader/index.test.tsx +0 -74
  35. package/src/components/ChatHeader/index.tsx +0 -77
@@ -0,0 +1,218 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState, type MutableRefObject, type RefObject } from 'react';
2
+
3
+ /**
4
+ * 贴底跟随:对话区滚动位置的唯一状态机。
5
+ *
6
+ * 两种状态——following(贴底)与 detached(用户主动离开)。
7
+ * 只有**用户手势**能让 following 变 detached:程序写入、内容长高、卡片挂载都不算。
8
+ * 旧实现按「离底 <150px」判定,内容一长高就被误判成用户离开。
9
+ *
10
+ * detached 回到 following 的条件:发送消息、点「回到底部」、新会话、或用户手势结束时已离底 ≤ threshold。
11
+ */
12
+
13
+ export interface StickToBottom {
14
+ /** 是否跟随(ref:流式期间每帧读写,不触发重渲染) */
15
+ followingRef: MutableRefObject<boolean>;
16
+ /** 不跟随且离底超过阈值 → 显示「回到底部」 */
17
+ showJump: boolean;
18
+ /** 回到跟随并立即贴底(发送 / 点浮标) */
19
+ follow: () => void;
20
+ /**
21
+ * 回到跟随但**不写滚动**(新会话):旧内容即将清空,此刻贴底会先把用户拽到旧内容底部。
22
+ * 状态置为 following,随后的内容变化按跟随处理。
23
+ */
24
+ resume: () => void;
25
+ /**
26
+ * 主动离开跟随(程序调用,不是用户手势)。
27
+ * 用于「用户要看历史」这类由应用发起的位移:此时内容会长高,但视线应停在历史条目上。
28
+ */
29
+ hold: () => void;
30
+ }
31
+
32
+ export interface UseStickToBottomOptions {
33
+ /** 滚动容器 */
34
+ scrollRef: RefObject<HTMLElement | null>;
35
+ /** 内容容器(尺寸变化即内容长高:流式文字、卡片挂载、图片加载) */
36
+ contentRef: RefObject<HTMLElement | null>;
37
+ /** 离底容差(px),缺省 80 */
38
+ threshold?: number;
39
+ }
40
+
41
+ const DEFAULT_THRESHOLD = 80;
42
+ /** 惯性滚动判定:最后一次 scroll 事件之后多久算静止 */
43
+ const SCROLL_IDLE_MS = 150;
44
+
45
+ export function useStickToBottom(opts: UseStickToBottomOptions): StickToBottom {
46
+ const threshold = opts.threshold ?? DEFAULT_THRESHOLD;
47
+ const followingRef = useRef(true);
48
+ const [showJump, setShowJump] = useState(false);
49
+ /** 程序写入的目标值:紧随其后的 scroll 事件按此识别并忽略 */
50
+ const programmaticTargetRef = useRef<number | null>(null);
51
+ /** 手指按住中:暂停写入,避免与手势打架 */
52
+ const touchingRef = useRef(false);
53
+ /** 手指起点:下拖判定用 */
54
+ const touchStartYRef = useRef<number | null>(null);
55
+ const scrollIdleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
56
+
57
+ const syncJump = useCallback(() => {
58
+ const el = opts.scrollRef.current;
59
+ if (!el) return;
60
+ const distance = el.scrollHeight - el.scrollTop - el.clientHeight;
61
+ const shouldShow = !followingRef.current && distance > threshold;
62
+ setShowJump((prev) => (prev === shouldShow ? prev : shouldShow));
63
+ }, [opts.scrollRef, threshold]);
64
+
65
+ const writeBottom = useCallback(() => {
66
+ const el = opts.scrollRef.current;
67
+ if (!el || !followingRef.current || touchingRef.current) return;
68
+ const target = el.scrollHeight - el.clientHeight;
69
+ if (target <= el.scrollTop + 1) return;
70
+ programmaticTargetRef.current = target;
71
+ el.scrollTop = target;
72
+ }, [opts.scrollRef]);
73
+
74
+ const follow = useCallback(() => {
75
+ followingRef.current = true;
76
+ writeBottom();
77
+ syncJump();
78
+ }, [writeBottom, syncJump]);
79
+
80
+ const resume = useCallback(() => {
81
+ followingRef.current = true;
82
+ syncJump();
83
+ }, [syncJump]);
84
+
85
+ /** 用户手势触发离开跟随 */
86
+ const detach = useCallback(() => {
87
+ if (!followingRef.current) return;
88
+ followingRef.current = false;
89
+ syncJump();
90
+ }, [syncJump]);
91
+
92
+ /** 程序发起离开跟随:与手势同效,但不受「已在跟随」短路影响(可重复调用)。 */
93
+ const hold = useCallback(() => {
94
+ followingRef.current = false;
95
+ syncJump();
96
+ }, [syncJump]);
97
+
98
+ // 内容或视口尺寸变化 → 跟随时贴底(流式每帧最多一次写入,靠 rAF 合并)
99
+ useEffect(() => {
100
+ const scrollEl = opts.scrollRef.current;
101
+ const contentEl = opts.contentRef.current;
102
+ if (!scrollEl || !contentEl) return undefined;
103
+ let frame = 0;
104
+ const schedule = () => {
105
+ if (frame) return;
106
+ frame = requestAnimationFrame(() => {
107
+ frame = 0;
108
+ writeBottom();
109
+ syncJump();
110
+ });
111
+ };
112
+ const ro = new ResizeObserver(schedule);
113
+ ro.observe(contentEl);
114
+ ro.observe(scrollEl);
115
+ schedule();
116
+ return () => {
117
+ if (frame) cancelAnimationFrame(frame);
118
+ ro.disconnect();
119
+ };
120
+ }, [opts.scrollRef, opts.contentRef, writeBottom, syncJump]);
121
+
122
+ // 手势判定:滚轮向上 / 手指下拖 / PageUp·Home·ArrowUp
123
+ useEffect(() => {
124
+ const scrollEl = opts.scrollRef.current;
125
+ if (!scrollEl) return undefined;
126
+ // 具名常量:函数声明提升会丢掉 opts.scrollRef.current 的窄化
127
+ const el: HTMLElement = scrollEl;
128
+
129
+ const onWheel = (event: WheelEvent) => {
130
+ if (event.deltaY < 0) detach();
131
+ else if (!followingRef.current) {
132
+ // 向下滚到底部附近时自动回到跟随
133
+ scheduleIdleSync();
134
+ }
135
+ };
136
+ const onTouchStart = () => {
137
+ touchingRef.current = true;
138
+ touchStartYRef.current = null;
139
+ };
140
+ const onTouchMove = (event: TouchEvent) => {
141
+ const y = event.touches[0]?.clientY;
142
+ if (typeof y !== 'number') return;
143
+ const prev = touchStartYRef.current;
144
+ if (prev === null) {
145
+ touchStartYRef.current = y;
146
+ return;
147
+ }
148
+ // 手指向下移动 = 内容向上翻 = 用户想往回看
149
+ if (y - prev > 4) detach();
150
+ };
151
+ const onTouchEnd = () => {
152
+ touchingRef.current = false;
153
+ scheduleIdleSync();
154
+ };
155
+ // 卡片表单里的方向键/Home 是编辑操作,不是「往回看」——按事件源排除
156
+ const isEditable = (target: EventTarget | null) => {
157
+ const node = target as HTMLElement | null;
158
+ if (!node || typeof node.closest !== 'function') return false;
159
+ return Boolean(node.closest('input, textarea, select, [contenteditable="true"], [contenteditable=""]'));
160
+ };
161
+ const onKeyDown = (event: KeyboardEvent) => {
162
+ if (event.key !== 'PageUp' && event.key !== 'Home' && event.key !== 'ArrowUp') return;
163
+ if (isEditable(event.target)) return;
164
+ detach();
165
+ };
166
+ const onScroll = () => {
167
+ const target = programmaticTargetRef.current;
168
+ if (target !== null) {
169
+ programmaticTargetRef.current = null;
170
+ if (Math.abs(el.scrollTop - target) <= 1) {
171
+ // 程序写入:不参与状态判断
172
+ return;
173
+ }
174
+ }
175
+ // 手势结束后的静止判定:滚回底部附近即恢复跟随
176
+ scheduleIdleSync();
177
+ };
178
+
179
+ el.addEventListener('wheel', onWheel, { passive: true });
180
+ el.addEventListener('touchstart', onTouchStart, { passive: true });
181
+ el.addEventListener('touchmove', onTouchMove, { passive: true });
182
+ el.addEventListener('touchend', onTouchEnd, { passive: true });
183
+ el.addEventListener('touchcancel', onTouchEnd, { passive: true });
184
+ el.addEventListener('scroll', onScroll, { passive: true });
185
+ el.addEventListener('keydown', onKeyDown);
186
+
187
+ function scheduleIdleSync() {
188
+ if (scrollIdleTimerRef.current) clearTimeout(scrollIdleTimerRef.current);
189
+ scrollIdleTimerRef.current = setTimeout(() => {
190
+ scrollIdleTimerRef.current = null;
191
+ if (programmaticTargetRef.current !== null) return;
192
+ const distance = el.scrollHeight - el.scrollTop - el.clientHeight;
193
+ if (distance <= threshold) {
194
+ followingRef.current = true;
195
+ writeBottom();
196
+ }
197
+ syncJump();
198
+ }, SCROLL_IDLE_MS);
199
+ }
200
+
201
+ return () => {
202
+ el.removeEventListener('wheel', onWheel);
203
+ el.removeEventListener('touchstart', onTouchStart);
204
+ el.removeEventListener('touchmove', onTouchMove);
205
+ el.removeEventListener('touchend', onTouchEnd);
206
+ el.removeEventListener('touchcancel', onTouchEnd);
207
+ el.removeEventListener('scroll', onScroll);
208
+ el.removeEventListener('keydown', onKeyDown);
209
+ if (scrollIdleTimerRef.current) {
210
+ clearTimeout(scrollIdleTimerRef.current);
211
+ scrollIdleTimerRef.current = null;
212
+ }
213
+ };
214
+ }, [opts.scrollRef, detach, follow, writeBottom, syncJump, threshold]);
215
+
216
+ // 返回对象按依赖稳定:否则每次渲染都新建,调用方把它放进 effect 依赖会连带重跑
217
+ return useMemo(() => ({ followingRef, showJump, follow, hold, resume }), [showJump, follow, hold, resume]);
218
+ }
package/src/index.ts CHANGED
@@ -33,7 +33,7 @@ export type { QuickCommand } from './chat-config';
33
33
  export { applyTheme, currentTheme } from './theme/theme';
34
34
 
35
35
  // ── 壳契约(区域、可覆写选择器、品牌名来源) ──
36
- export { SHELL_CONTRACT, resolveBrandName } from './shell';
36
+ export { SHELL_CONTRACT } from './shell';
37
37
  export type { ShellArea, ShellContract, ShellRegion } from './shell';
38
38
 
39
39
  // ── 卡片渲染(context 注册表注入) ──
@@ -96,7 +96,6 @@ export { QuickCommands } from './components/QuickCommands';
96
96
  export { MediaList } from './components/MediaList';
97
97
  export { ActionBar, CopyButton, getMessageCopyText } from './components/ActionBar';
98
98
  export { DebugButton } from './components/ActionBar/DebugButton';
99
- export { default as ChatHeader } from './components/ChatHeader';
100
99
  export { default as HistoryEntry } from './components/HistoryEntry';
101
100
  export { default as PullDownIndicator } from './components/PullDownIndicator';
102
101
  export { default as ReasoningBlock } from './components/ReasoningBlock';
@@ -18,7 +18,8 @@ import { KitChatProvider } from './store-context';
18
18
  /** 预览用 store:只满足壳与卡片的读取(sendUiAction 空实现、不在生成中)。 */
19
19
  export function createPreviewStore(state: Partial<CoreChatState> = {}): CoreChatStore {
20
20
  const vanilla = createStore<CoreChatState>(() => ({
21
- sendUiAction: () => {},
21
+ // 预览没有服务端:动作一律按 rejected 返回,按钮立即恢复(不进入挂起)
22
+ sendUiAction: () => ({ status: 'rejected' as const, reason: 'offline' as const }),
22
23
  isGenerating: false,
23
24
  ...state,
24
25
  } as unknown as CoreChatState));
@@ -1,25 +1,24 @@
1
1
  {
2
- "$comment": "对话壳契约数据(docs/agent/kit.md 与 shell.test.ts 的共同来源;改这里 = 改壳的对外承诺)。regions = ChatPage 渲染的区域;internal = 不承诺稳定的内部结构。",
2
+ "$comment": "对话壳契约数据(docs/agent/kit.md 与 shell.test.ts 的共同来源;改这里 = 改壳的对外承诺)。regions = ChatPage 渲染的区域;invariants = 壳的行为承诺(单测与真浏览器探针按 id 断言);internal = 不承诺稳定的内部结构。",
3
+ "invariants": [
4
+ { "id": "no-fixed-chrome", "text": "滚动区之上不渲染任何常驻元素(没有页头、没有固定标题栏)" },
5
+ { "id": "input-rows", "text": "空输入框高度 = 行高 × chat.json input.minRows;输入框外框命中区 ≥44px" },
6
+ { "id": "follow-latest", "text": "跟随时内容增长后离底 ≤2px;用户手势上滑后停止跟随并显示「回到底部」" },
7
+ { "id": "action-settle", "text": "卡片动作的结束信号到达后同一帧解锁按钮,不靠超时兜底" }
8
+ ],
3
9
  "regions": [
4
- {
5
- "id": "brand",
6
- "area": "brand",
7
- "selector": ".chat-page__brand",
8
- "drivenBy": ["chat.json identity.name", "chat.json identity.tagline", "HELLO_ACK mallScope.mallName(缺省回落)"],
9
- "brandable": true
10
- },
11
10
  {
12
11
  "id": "welcome",
13
12
  "area": "welcome",
14
13
  "selector": ".chat-page__welcome",
15
- "drivenBy": ["chat.json welcome.title", "chat.json welcome.subtitle", "chat.json identity(缺省回落)"],
14
+ "drivenBy": ["chat.json welcome.title", "chat.json welcome.subtitle"],
16
15
  "brandable": true
17
16
  },
18
17
  {
19
18
  "id": "messages",
20
19
  "area": "messages",
21
20
  "selector": ".chat-page__body",
22
- "drivenBy": ["chat store messages / historyMessages"],
21
+ "drivenBy": ["chat store messages / historyMessages,历史分页保留当前阅读位置"],
23
22
  "brandable": false
24
23
  },
25
24
  {
@@ -47,14 +46,14 @@
47
46
  "id": "quick-commands",
48
47
  "area": "quick-commands",
49
48
  "selector": ".quick-commands",
50
- "drivenBy": ["chat.json quickCommands"],
49
+ "drivenBy": ["HELLO_ACK chatConfig.quickCommands(缺省回落 chat.json)", "chat.json quickCommands[].icon(图片或 icon:calendar)"],
51
50
  "brandable": true
52
51
  },
53
52
  {
54
53
  "id": "input",
55
54
  "area": "input",
56
55
  "selector": ".tbox-chat-input",
57
- "drivenBy": ["chat.json(enableTTS 等)", "chat store runtimeStatus / isGenerating"],
56
+ "drivenBy": ["chat.json(enableTTS / input.minRows / input.maxRows)", "chat store runtimeStatus / isGenerating"],
58
57
  "brandable": false
59
58
  }
60
59
  ],
@@ -69,7 +68,7 @@
69
68
  ],
70
69
  "internal": [
71
70
  "MessageBubble 内部结构(.msg-row / .msg-main / .msg-thinking)",
72
- "ChatInput 内部结构(.tbox-media-picker、发送按钮)",
71
+ "ChatInput 内部结构(文本框、.tbox-media-picker、发送按钮)",
73
72
  "卡片渲染器内部结构(.tbox-card-*)"
74
73
  ]
75
74
  }
package/src/shell.test.ts CHANGED
@@ -1,15 +1,21 @@
1
+ // @vitest-environment happy-dom
1
2
  import { readFileSync } from 'node:fs';
2
3
  import path from 'node:path';
3
4
  import { fileURLToPath } from 'node:url';
4
- import { describe, expect, it } from 'vitest';
5
- import { SHELL_CONTRACT, resolveBrandName } from './shell';
5
+ import { describe, expect, it, vi } from 'vitest';
6
+ import { act, createElement } from 'react';
7
+ import { createRoot } from 'react-dom/client';
8
+ import { ClientSlotRegistry } from '@tbox.cn/app-agent-sdk-client';
9
+ import { ChatPage } from './ChatPage';
10
+ import { configureChatConfigDefaults, useChatConfigStore } from './chat-config';
11
+ import { createPreviewStore } from './preview-provider';
12
+ import { SHELL_CONTRACT } from './shell';
6
13
 
7
14
  const here = path.dirname(fileURLToPath(import.meta.url));
8
15
  const read = (rel: string) => readFileSync(path.join(here, rel), 'utf8');
9
16
 
10
17
  /** 契约声明的选择器必须真的出现在源码里——「文档说有、代码没接」在这里失败。 */
11
18
  const SELECTOR_SOURCES: Record<string, string[]> = {
12
- '.chat-page__brand': ['ChatPage.tsx'],
13
19
  '.chat-page__welcome': ['ChatPage.tsx'],
14
20
  '.chat-page__body': ['ChatPage.tsx'],
15
21
  '.history-entry': ['components/HistoryEntry/index.tsx'],
@@ -45,6 +51,13 @@ describe('壳契约', () => {
45
51
  }
46
52
  });
47
53
 
54
+ it('快捷胶囊契约包含本地图标配置', () => {
55
+ const quickCommands = SHELL_CONTRACT.regions.find((region) => region.id === 'quick-commands');
56
+ expect(quickCommands?.drivenBy).toEqual(expect.arrayContaining([
57
+ expect.stringContaining('chat.json quickCommands[].icon'),
58
+ ]));
59
+ });
60
+
48
61
  it('控件契约的 data-tbox-control 都在源码里', () => {
49
62
  const sources = ['components/ChatInput/index.tsx', 'components/HistoryEntry/index.tsx', 'components/ScrollToBottomButton/index.tsx'];
50
63
  for (const control of SHELL_CONTRACT.controls ?? []) {
@@ -56,17 +69,100 @@ describe('壳契约', () => {
56
69
  });
57
70
  });
58
71
 
59
- describe('品牌名三级来源', () => {
60
- it('identity.name 优先', () => {
61
- expect(resolveBrandName({ name: '悦享里', tagline: '商圈助手' }, '某商场')).toBe('悦享里');
72
+ describe('壳行为不变式', () => {
73
+ it('不变式四条齐全且 id 唯一', () => {
74
+ const ids = SHELL_CONTRACT.invariants.map((item) => item.id);
75
+ expect(ids).toEqual(expect.arrayContaining(['no-fixed-chrome', 'input-rows', 'follow-latest', 'action-settle']));
76
+ expect(new Set(ids).size).toBe(ids.length);
77
+ for (const item of SHELL_CONTRACT.invariants) expect(item.text.trim().length).toBeGreaterThan(0);
78
+ });
79
+
80
+ it('滚动区之上没有常驻元素(no-fixed-chrome)', async () => {
81
+ const container = document.createElement('div');
82
+ document.body.append(container);
83
+ const root = createRoot(container);
84
+ const store = createPreviewStore({
85
+ messages: [], historyMessages: [], historyHasMore: false, orphanCards: [], cardsByMessageId: {},
86
+ runtimeStatus: 'ready', initConversation: async () => {}, destroy: () => {},
87
+ });
88
+ try {
89
+ await act(async () => root.render(createElement(ChatPage, { store, cards: {} })));
90
+ const page = container.querySelector('.chat-page')!;
91
+ const body = container.querySelector('.chat-page__body')!;
92
+ // 滚动区之前的兄弟节点只允许背景装饰层(pointer-events-none 的 .chat-page__bg)
93
+ const before = Array.from(page.children).slice(0, Array.from(page.children).indexOf(body.parentElement!));
94
+ expect(before.every((el) => el.classList.contains('chat-page__bg'))).toBe(true);
95
+ expect(container.querySelector('.chat-page__brand')).toBeNull();
96
+ } finally {
97
+ await act(async () => root.unmount());
98
+ container.remove();
99
+ }
62
100
  });
101
+ });
102
+
103
+ describe('商场对话壳的主题布局', () => {
104
+ it.each([false, true])('主题启用紧凑布局为 %s 时使用对应的首页和输入栏样式', async (compact) => {
105
+ const rootStyle = document.documentElement.style;
106
+ const previousConfig = useChatConfigStore.getState();
107
+ const container = document.createElement('div');
108
+ document.body.append(container);
109
+ const root = createRoot(container);
110
+ const slots = new ClientSlotRegistry();
111
+ slots.register('home', () => createElement('main', null, '商场首页'));
112
+ const store = createPreviewStore({
113
+ messages: [], historyMessages: [], historyHasMore: true, orphanCards: [], cardsByMessageId: {},
114
+ runtimeStatus: 'ready', initConversation: async () => {}, destroy: () => {},
115
+ });
116
+
117
+ try {
118
+ rootStyle.setProperty('--tbox-compact-chat', compact ? '1' : '0');
119
+ configureChatConfigDefaults({
120
+ identity: { name: '商场助手' },
121
+ quickCommands: [{ label: '优惠', query: '有优惠吗?' }],
122
+ });
123
+ await act(async () => root.render(createElement(ChatPage, { store, cards: {}, slots })));
63
124
 
64
- it('缺 identity 时回落 HELLO_ACK 的 mallName', () => {
65
- expect(resolveBrandName(undefined, '某商场')).toBe('某商场');
125
+ // 壳没有页头:紧凑与非紧凑都不渲染常驻品牌区
126
+ expect(container.querySelector('.chat-page__brand')).toBeNull();
127
+ expect(container.querySelector('.chat-page__body')?.classList.contains('justify-center')).toBe(false);
128
+ expect(Boolean(container.querySelector('.chat-page__body .quick-commands'))).toBe(!compact);
129
+ expect(Boolean(container.querySelector('.quick-commands + .tbox-chat-input'))).toBe(compact);
130
+ expect(container.querySelector('textarea')?.classList.contains('h-6')).toBe(compact);
131
+ expect(container.querySelector('.history-entry__button')?.classList.contains('min-h-11')).toBe(!compact);
132
+ } finally {
133
+ await act(async () => root.unmount());
134
+ container.remove();
135
+ rootStyle.removeProperty('--tbox-compact-chat');
136
+ useChatConfigStore.setState(previousConfig, true);
137
+ }
66
138
  });
139
+ });
67
140
 
68
- it('都没有则不渲染', () => {
69
- expect(resolveBrandName(undefined, undefined)).toBeUndefined();
70
- expect(resolveBrandName({ name: '' }, undefined)).toBeUndefined();
141
+ describe('历史首次打开', () => {
142
+ it('空页保持位置,有消息时从最近的历史问题开始读', async () => {
143
+ const container = document.createElement('div');
144
+ document.body.append(container);
145
+ const root = createRoot(container);
146
+ const store = createPreviewStore({
147
+ messages: [], historyMessages: [], historyHasMore: true, orphanCards: [], cardsByMessageId: {},
148
+ runtimeStatus: 'ready', initConversation: async () => {}, destroy: () => {},
149
+ });
150
+ const geometry = vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) {
151
+ return new DOMRect(0, this.dataset.messageId === 'latest' ? 500 : 0, 360, 600);
152
+ });
153
+ try {
154
+ await act(async () => root.render(createElement(ChatPage, { store, cards: {} })));
155
+ const body = container.querySelector<HTMLElement>('.chat-page__body')!;
156
+ await act(async () => store.setState({ historyMessages: [] }));
157
+ expect(body.scrollTop).toBe(0);
158
+ await act(async () => store.setState({ historyMessages: ['older', 'latest'].map(id => ({
159
+ id, role: 'user', status: 'done', content: id, createdAt: 1,
160
+ })) }));
161
+ expect(body.scrollTop).toBe(492);
162
+ } finally {
163
+ geometry.mockRestore();
164
+ await act(async () => root.unmount());
165
+ container.remove();
166
+ }
71
167
  });
72
168
  });
package/src/shell.ts CHANGED
@@ -10,10 +10,9 @@
10
10
  * 只描述壳层(ChatPage 渲染的区域)。kit 内部组件(MessageBubble、ChatInput 的内部结构)
11
11
  * 不承诺稳定;改样式请用契约里 `brandable: true` 的选择器。
12
12
  */
13
- import type { ChatIdentity } from './chat-config';
14
13
  import contract from './shell.contract.json';
15
14
 
16
- export type ShellArea = 'brand' | 'welcome' | 'messages' | 'history' | 'home' | 'quick-commands' | 'input' | 'conversation-overlay';
15
+ export type ShellArea = 'welcome' | 'messages' | 'history' | 'home' | 'quick-commands' | 'input' | 'conversation-overlay';
17
16
 
18
17
  export interface ShellRegion {
19
18
  /** 稳定 id(文档与测试引用) */
@@ -41,7 +40,19 @@ export interface ShellControl {
41
40
  capability?: string | string[];
42
41
  }
43
42
 
43
+ /**
44
+ * 壳的行为承诺:滚动区之上没有常驻元素、输入框单行且命中区达标、内容增长时跟到底、
45
+ * 卡片动作有结束信号。单测与真浏览器探针按 id 断言,改壳先改这里。
46
+ */
47
+ export interface ShellInvariant {
48
+ /** 稳定 id(探针与文档引用) */
49
+ id: string;
50
+ /** 一句话承诺 */
51
+ text: string;
52
+ }
53
+
44
54
  export interface ShellContract {
55
+ invariants: ShellInvariant[];
45
56
  regions: ShellRegion[];
46
57
  /** 交互控件契约:探针按它查,不按内部类名猜 */
47
58
  controls?: ShellControl[];
@@ -50,11 +61,3 @@ export interface ShellContract {
50
61
  }
51
62
 
52
63
  export const SHELL_CONTRACT: ShellContract = contract as ShellContract;
53
-
54
- /**
55
- * 品牌名三级来源:`chat.json identity.name` → `HELLO_ACK mallScope.mallName` → 无(不渲染品牌条)。
56
- * 智能体身份是配置项,不是代码:应用只改 `config/chat.json`。
57
- */
58
- export function resolveBrandName(identity: ChatIdentity | undefined, mallName: string | undefined): string | undefined {
59
- return identity?.name || mallName || undefined;
60
- }
package/src/test/setup.ts CHANGED
@@ -5,3 +5,34 @@
5
5
  */
6
6
  (globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean })
7
7
  .IS_REACT_ACT_ENVIRONMENT = true;
8
+
9
+ /**
10
+ * ResizeObserver 替身(happy-dom 无实现):壳里「内容长高就贴底」依赖它,
11
+ * 用例需要一个可手动触发的入口——`triggerResizeObservers()` 手工冲刷一轮回调。
12
+ */
13
+ const observers = new Set<{ callback: ResizeObserverCallback }>();
14
+
15
+ // happy-dom 自带一个永不触发的实现,一律替换,保证用例可控
16
+ {
17
+ class TestResizeObserver {
18
+ callback: ResizeObserverCallback;
19
+ constructor(callback: ResizeObserverCallback) {
20
+ this.callback = callback;
21
+ observers.add(this);
22
+ }
23
+ observe() {}
24
+ unobserve() {}
25
+ disconnect() {
26
+ observers.delete(this);
27
+ }
28
+ }
29
+ (globalThis as typeof globalThis & { ResizeObserver: unknown }).ResizeObserver =
30
+ TestResizeObserver as unknown as typeof ResizeObserver;
31
+ }
32
+
33
+ /** 手动触发全部已注册的 ResizeObserver 回调(用例在改尺寸后调用)。 */
34
+ export function triggerResizeObservers(): void {
35
+ for (const observer of [...observers]) {
36
+ observer.callback([], observer as unknown as ResizeObserver);
37
+ }
38
+ }
@@ -72,6 +72,11 @@
72
72
  }
73
73
  }
74
74
 
75
+ /* 翻页前插时,历史卡片应直接占据最终位置,保持当前阅读锚点。 */
76
+ .chat-page__history .tbox-card {
77
+ animation: none;
78
+ }
79
+
75
80
  @media (prefers-reduced-motion: reduce) {
76
81
  .tbox-card {
77
82
  animation: none;
@@ -9,6 +9,7 @@
9
9
  "--tbox-bg-warm",
10
10
  "--tbox-border",
11
11
  "--tbox-border-strong",
12
+ "--tbox-compact-chat",
12
13
  "--tbox-content-max-width",
13
14
  "--tbox-error",
14
15
  "--tbox-fs-body",
@@ -68,6 +68,7 @@
68
68
  --tbox-input-bg: rgba(255, 255, 255, 0.7);
69
69
  /* 输入条高度固定,仅横向伸缩。 */
70
70
  --tbox-input-radius: 25PX;
71
+ --tbox-compact-chat: 0;
71
72
  --tbox-input-padding: 10PX 12PX;
72
73
  --tbox-send-btn-size: 22PX;
73
74
  --tbox-icon-color: #4b6282;
@@ -1,74 +0,0 @@
1
- // @vitest-environment happy-dom
2
- import { beforeEach, describe, expect, it, vi } from 'vitest';
3
- import { createRoot } from 'react-dom/client';
4
- import { flushSync } from 'react-dom';
5
- import ChatHeader from './index';
6
-
7
- interface MockChatState {
8
- helloAck: { mallScope?: Record<string, string> } | null;
9
- }
10
-
11
- let mockHelloAck: MockChatState['helloAck'] = null;
12
-
13
- vi.mock('../../store-context', () => ({
14
- useChatStore: (selector: (s: MockChatState) => unknown) =>
15
- selector({ helloAck: mockHelloAck }),
16
- }));
17
-
18
- vi.mock('../../chat-config', () => ({
19
- useChatConfigStore: (selector: (s: { enableTTS: boolean }) => unknown) =>
20
- selector({ enableTTS: false }),
21
- }));
22
-
23
- function renderHeader(container: HTMLDivElement) {
24
- flushSync(() => {
25
- createRoot(container).render(
26
- <ChatHeader ttsAutoPlay={false} onToggleTTS={() => {}} onClearChat={() => {}} />,
27
- );
28
- });
29
- }
30
-
31
- describe('ChatHeader 品牌区(014 T7:mallScope.mallName 驱动,非 mall 部署降级)', () => {
32
- beforeEach(() => {
33
- mockHelloAck = null;
34
- });
35
-
36
- it('有 mallScope.mallName → 渲染品牌区(mark + mallName)', () => {
37
- mockHelloAck = { mallScope: { mallId: 'mall-demo', mallName: '示例商场' } };
38
- const container = document.createElement('div');
39
- document.body.appendChild(container);
40
- try {
41
- renderHeader(container);
42
- const brand = container.querySelector('.chat-header__brand');
43
- expect(brand).not.toBeNull();
44
- expect(brand?.textContent).toContain('示例商场');
45
- expect(brand?.getAttribute('aria-label')).toBe('示例商场');
46
- } finally {
47
- document.body.removeChild(container);
48
- }
49
- });
50
-
51
- it('无 mallScope(非 mall 部署)→ 不渲染品牌区', () => {
52
- mockHelloAck = null;
53
- const container = document.createElement('div');
54
- document.body.appendChild(container);
55
- try {
56
- renderHeader(container);
57
- expect(container.querySelector('.chat-header__brand')).toBeNull();
58
- } finally {
59
- document.body.removeChild(container);
60
- }
61
- });
62
-
63
- it('mallScope 缺 mallName → 不渲染品牌区(回显不完整降级)', () => {
64
- mockHelloAck = { mallScope: { mallId: 'mall-demo' } };
65
- const container = document.createElement('div');
66
- document.body.appendChild(container);
67
- try {
68
- renderHeader(container);
69
- expect(container.querySelector('.chat-header__brand')).toBeNull();
70
- } finally {
71
- document.body.removeChild(container);
72
- }
73
- });
74
- });