@tbox.cn/app-agent-ui-kit 1.0.0-alpha.7 → 1.0.0-alpha.9

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/README.md +21 -1
  2. package/package.json +11 -3
  3. package/src/ChatPage.tsx +70 -17
  4. package/src/card/action-list-pending.test.tsx +91 -0
  5. package/src/card/define-card.test.ts +25 -0
  6. package/src/card/define-card.ts +18 -5
  7. package/src/card/primitives.test.tsx +10 -0
  8. package/src/card/primitives.tsx +136 -37
  9. package/src/card/view-card-inline.test.tsx +42 -0
  10. package/src/card/view-card.test.tsx +79 -0
  11. package/src/card/view-card.tsx +250 -0
  12. package/src/chat-config.ts +11 -7
  13. package/src/components/ActionBar/DebugButton.test.tsx +3 -0
  14. package/src/components/ActionBar/DebugButton.tsx +2 -7
  15. package/src/components/BottomSheet/index.test.tsx +90 -0
  16. package/src/components/BottomSheet/index.tsx +129 -0
  17. package/src/components/ChatInput/index.test.tsx +2 -2
  18. package/src/components/ChatInput/index.tsx +22 -17
  19. package/src/components/HistoryEntry/index.tsx +3 -2
  20. package/src/components/MessageBubble/index.tsx +11 -5
  21. package/src/components/QuickCommands/index.test.tsx +3 -1
  22. package/src/components/QuickCommands/index.tsx +31 -8
  23. package/src/components/ScrollToBottomButton/index.tsx +7 -3
  24. package/src/components/ToolCallBlock/index.tsx +4 -2
  25. package/src/index.ts +8 -0
  26. package/src/preview-provider.tsx +47 -0
  27. package/src/shell.contract.json +9 -0
  28. package/src/shell.test.ts +10 -0
  29. package/src/shell.ts +15 -0
  30. package/src/surface.test.tsx +35 -0
  31. package/src/surface.tsx +44 -0
  32. package/src/theme/base.css +9 -11
  33. package/src/theme/contract.json +123 -2
  34. package/src/theme/theme-contract.test.ts +16 -0
  35. package/src/theme/tokens.css +9 -12
@@ -22,6 +22,8 @@ describe('DebugButton 平台契约(tbox:debug-trace 载荷锁定)', () => {
22
22
  let postSpy: ReturnType<typeof vi.fn>;
23
23
 
24
24
  beforeEach(() => {
25
+ // 调试入口只在显式 ?debug=1 下渲染(B5:dev 构建与 iframe 预览不再触发)
26
+ window.history.replaceState({}, '', '/?debug=1');
25
27
  host = document.createElement('div');
26
28
  document.body.appendChild(host);
27
29
  root = createRoot(host);
@@ -33,6 +35,7 @@ describe('DebugButton 平台契约(tbox:debug-trace 载荷锁定)', () => {
33
35
  afterEach(() => {
34
36
  act(() => root.unmount());
35
37
  host.remove();
38
+ window.history.replaceState({}, '', '/');
36
39
  });
37
40
 
38
41
  const clickDebug = () => {
@@ -11,13 +11,8 @@ import { Bug } from '@phosphor-icons/react';
11
11
  */
12
12
  function shouldShow(): boolean {
13
13
  if (typeof window === 'undefined') return false;
14
- if (import.meta.env.DEV) return true;
15
- if (new URLSearchParams(window.location.search).get('debug') === '1') return true;
16
- try {
17
- return window.self !== window.top;
18
- } catch {
19
- return true;
20
- }
14
+ // 只在显式调试请求下显示:dev 构建与 iframe 预览都不再触发(B5)。
15
+ return new URLSearchParams(window.location.search).get('debug') === '1';
21
16
  }
22
17
 
23
18
  export function DebugButton({
@@ -0,0 +1,90 @@
1
+ // @vitest-environment happy-dom
2
+ import { afterEach, describe, expect, it, vi } from 'vitest';
3
+ import { act } from 'react';
4
+ import { createRoot } from 'react-dom/client';
5
+ import type { Root } from 'react-dom/client';
6
+ import { BottomSheet } from './index';
7
+
8
+ let root: Root | undefined;
9
+ afterEach(async () => {
10
+ await act(async () => root?.unmount());
11
+ root = undefined;
12
+ document.body.innerHTML = '';
13
+ });
14
+
15
+ async function waitForDialog() {
16
+ for (let attempt = 0; attempt < 50; attempt += 1) {
17
+ const dialog = document.querySelector('[role="dialog"]');
18
+ if (dialog) return dialog;
19
+ await act(async () => {
20
+ await new Promise((resolve) => setTimeout(resolve, 0));
21
+ });
22
+ }
23
+ throw new Error('BottomSheet 懒加载后仍未挂载弹层');
24
+ }
25
+
26
+ async function renderSheet(open: boolean, onClose = vi.fn()) {
27
+ if (!root) {
28
+ const container = document.createElement('div');
29
+ document.body.append(container);
30
+ root = createRoot(container);
31
+ }
32
+ await act(async () => {
33
+ root!.render(<BottomSheet open={open} title="奖品详情" onClose={onClose}>
34
+ <button type="button">内容操作</button>
35
+ </BottomSheet>);
36
+ });
37
+ return onClose;
38
+ }
39
+
40
+ describe('BottomSheet', () => {
41
+ it('关闭态不挂载内容;打开通过 portal 展示命名对话框和业务内容', async () => {
42
+ await renderSheet(false);
43
+ expect(document.querySelector('[role="dialog"]')).toBeNull();
44
+ await renderSheet(true);
45
+ const dialog = await waitForDialog();
46
+ expect(dialog.getAttribute('aria-modal')).toBe('true');
47
+ expect(document.getElementById(dialog.getAttribute('aria-labelledby')!)?.textContent).toBe('奖品详情');
48
+ expect(dialog.textContent).toContain('内容操作');
49
+ });
50
+
51
+ it('关闭按钮与 Escape 请求受控关闭,卸载后恢复触发按钮焦点并清理监听', async () => {
52
+ const trigger = document.createElement('button');
53
+ document.body.append(trigger);
54
+ trigger.focus();
55
+ const onClose = await renderSheet(true);
56
+ await waitForDialog();
57
+ await act(async () => {
58
+ (document.querySelector('[aria-label="关闭奖品详情"]') as HTMLButtonElement).click();
59
+ });
60
+ expect(onClose).toHaveBeenCalledTimes(1);
61
+ await act(async () => document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })));
62
+ expect(onClose).toHaveBeenCalledTimes(2);
63
+ await act(async () => root?.unmount());
64
+ root = undefined;
65
+ expect(document.activeElement).toBe(trigger);
66
+ document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
67
+ expect(onClose).toHaveBeenCalledTimes(2);
68
+ });
69
+
70
+ it('Tab 与 Shift+Tab 在弹层内循环,不落到背景页面', async () => {
71
+ await renderSheet(true);
72
+ await waitForDialog();
73
+ const close = document.querySelector('[aria-label="关闭奖品详情"]') as HTMLButtonElement;
74
+ const last = document.querySelector('.tbox-bottom-sheet__body button') as HTMLButtonElement;
75
+ last.focus();
76
+ document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Tab', cancelable: true }));
77
+ expect(document.activeElement).toBe(close);
78
+ document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Tab', shiftKey: true, cancelable: true }));
79
+ expect(document.activeElement).toBe(last);
80
+ });
81
+
82
+ it('遮罩点击请求关闭,内容点击不关闭', async () => {
83
+ const onClose = await renderSheet(true);
84
+ await waitForDialog();
85
+ await act(async () => (document.querySelector('.tbox-bottom-sheet__body button') as HTMLButtonElement).click());
86
+ expect(onClose).not.toHaveBeenCalled();
87
+ await act(async () => (document.querySelector('.adm-mask') as HTMLElement).click());
88
+ expect(onClose).toHaveBeenCalledTimes(1);
89
+ });
90
+ });
@@ -0,0 +1,129 @@
1
+ import { useEffect, useId, useRef, useState } from 'react';
2
+ import type { ComponentType, ReactNode } from 'react';
3
+ import type { PopupProps } from 'antd-mobile';
4
+
5
+ export interface BottomSheetProps {
6
+ open: boolean;
7
+ title: string;
8
+ onClose: () => void;
9
+ children: ReactNode;
10
+ /** 内容容器的业务样式;弹层外壳由组件统一管理。 */
11
+ className?: string;
12
+ }
13
+
14
+ type PopupComponent = ComponentType<PopupProps>;
15
+
16
+ /**
17
+ * antd-mobile 带 CSS 的运行时依赖只在浏览器按需加载:kit 源码在 Node/Vite SSR 里可直接 import
18
+ * (静态 import 会让 Node 读到 CJS 入口 require 的 global.css,整条证据链/SSR 消费者失败)。
19
+ * 失败时清空缓存,允许下一次交互重试。
20
+ */
21
+ let popupPromise: Promise<PopupComponent> | undefined;
22
+
23
+ export function preloadBottomSheet(): Promise<ComponentType<PopupProps>> {
24
+ popupPromise ??= import('antd-mobile')
25
+ .then((module) => module.Popup as PopupComponent)
26
+ .catch((error: unknown) => {
27
+ popupPromise = undefined;
28
+ throw error;
29
+ });
30
+ return popupPromise;
31
+ }
32
+
33
+ /** 受控底部弹层:业务只提供内容与开关,不自行处理遮罩、滚动和焦点。 */
34
+ export function BottomSheet({ open, title, onClose, children, className }: BottomSheetProps) {
35
+ const titleId = useId();
36
+ const panelRef = useRef<HTMLDivElement>(null);
37
+ const closeRef = useRef<HTMLButtonElement>(null);
38
+ const onCloseRef = useRef(onClose);
39
+ onCloseRef.current = onClose;
40
+ const [Popup, setPopup] = useState<PopupComponent | null>(null);
41
+
42
+ useEffect(() => {
43
+ if (Popup) return;
44
+ let alive = true;
45
+ preloadBottomSheet()
46
+ .then((loaded) => {
47
+ if (alive) setPopup(() => loaded);
48
+ })
49
+ .catch((error: unknown) => {
50
+ // 一次 chunk 失败不应静默:保留可诊断信息;open 变化会再次进入本 effect 重试(promise 已清空)。
51
+ console.warn('BottomSheet: antd-mobile Popup 加载失败', error);
52
+ });
53
+ return () => {
54
+ alive = false;
55
+ };
56
+ }, [open, Popup]);
57
+
58
+ // 懒加载窗口:弹层未就绪时先挡住背景交互(无遮罩会让「模态」破窗)。
59
+ useEffect(() => {
60
+ if (!open || Popup) return;
61
+ const previous = document.body.style.overflow;
62
+ document.body.style.overflow = 'hidden';
63
+ return () => {
64
+ document.body.style.overflow = previous;
65
+ };
66
+ }, [open, Popup]);
67
+
68
+ useEffect(() => {
69
+ if (!open) return;
70
+ const previous = document.activeElement;
71
+ const onKeyDown = (event: KeyboardEvent) => {
72
+ if (event.key === 'Escape') {
73
+ event.preventDefault();
74
+ event.stopPropagation();
75
+ onCloseRef.current();
76
+ }
77
+ if (event.key !== 'Tab' || !panelRef.current) return;
78
+ const focusable = [...panelRef.current.querySelectorAll<HTMLElement>(
79
+ 'button:not(:disabled), a[href], input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex="0"]',
80
+ )].filter((element) => !element.hidden && element.getAttribute('aria-hidden') !== 'true');
81
+ const first = focusable[0];
82
+ const last = focusable[focusable.length - 1];
83
+ if (!first || !last) return;
84
+ const active = document.activeElement;
85
+ if (event.shiftKey && (active === first || !panelRef.current.contains(active))) {
86
+ event.preventDefault();
87
+ last.focus();
88
+ } else if (!event.shiftKey && (active === last || !panelRef.current.contains(active))) {
89
+ event.preventDefault();
90
+ first.focus();
91
+ }
92
+ };
93
+ document.addEventListener('keydown', onKeyDown);
94
+ return () => {
95
+ document.removeEventListener('keydown', onKeyDown);
96
+ if (previous instanceof HTMLElement && previous.isConnected) previous.focus();
97
+ };
98
+ }, [open]);
99
+
100
+ // Popup 晚于 open 就绪时 afterShow 不保证触发,这里补一次显式聚焦。
101
+ useEffect(() => {
102
+ if (!open || !Popup) return;
103
+ const timer = window.setTimeout(() => closeRef.current?.focus(), 0);
104
+ return () => window.clearTimeout(timer);
105
+ }, [open, Popup]);
106
+
107
+ if (!Popup) {
108
+ return open ? <div className="fixed inset-0 z-[1100] bg-scrim" role="presentation" aria-hidden="true" /> : null;
109
+ }
110
+
111
+ return (
112
+ <Popup className="motion-reduce:[&_.adm-popup-body]:transition-none motion-reduce:[&_.adm-mask]:transition-none" visible={open} position="bottom" onClose={onClose} closeOnMaskClick
113
+ destroyOnClose disableBodyScroll bodyClassName="tbox-bottom-sheet mx-auto w-full overflow-hidden rounded-t-[14px] bg-card text-foreground"
114
+ style={{ '--z-index': '1100' }} afterShow={() => closeRef.current?.focus()}>
115
+ <div ref={panelRef} className="tbox-bottom-sheet__panel flex max-h-[65vh] flex-col supports-[height:100dvh]:max-h-[65dvh]" role="dialog"
116
+ aria-modal="true" aria-labelledby={titleId}>
117
+ <header className="tbox-bottom-sheet__header flex shrink-0 items-center justify-between gap-3 px-3.5 py-3">
118
+ <h2 id={titleId} className="m-0 text-base font-semibold leading-[21px]">{title}</h2>
119
+ <button className="flex size-9 shrink-0 cursor-pointer items-center justify-center rounded-full border-0 bg-transparent p-1.5 text-inherit focus-visible:outline-2 focus-visible:outline-primary" ref={closeRef} type="button" aria-label={`关闭${title}`} onClick={onClose}>
120
+ <svg className="size-4.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
121
+ <path d="m6 6 12 12M6 18 18 6" />
122
+ </svg>
123
+ </button>
124
+ </header>
125
+ <div className={['tbox-bottom-sheet__body min-h-0 overflow-y-auto overscroll-contain px-3.5 pt-0 pb-[calc(16px+env(safe-area-inset-bottom))] text-sm leading-[19px]', className].filter(Boolean).join(' ')}>{children}</div>
126
+ </div>
127
+ </Popup>
128
+ );
129
+ }
@@ -83,9 +83,9 @@ describe('ChatInput 语音活动状态', () => {
83
83
  });
84
84
 
85
85
  describe('ChatInput 派生模式(服务端 defaultInputMode 水合)', () => {
86
- /** voice 态投影:录音模式显示"键盘"切换图标;text 态显示"语音"切换图标 */
86
+ /** voice 态投影:录音模式的可访问名为「切换到键盘输入」;text 态为「切换到语音输入」 */
87
87
  const inVoiceMode = (container: HTMLElement) =>
88
- container.querySelector('img[alt="键盘"]') !== null;
88
+ container.querySelector('.tbox-voice-toggle[aria-label="切换到键盘输入"]') !== null;
89
89
 
90
90
  const renderInput = async (root: ReturnType<typeof createRoot>) => {
91
91
  await act(async () => root.render(<ChatInput onSend={vi.fn()} />));
@@ -190,9 +190,9 @@ export function ChatInput({
190
190
 
191
191
  <div className="tbox-chat-input__row flex flex-wrap items-end gap-2">
192
192
  {onNewChat && (
193
- <div className="tbox-new-chat-btn flex size-11 shrink-0 items-center justify-center rounded-full bg-[rgba(255,255,255,0.5)] shadow-[0_1px_10px_rgba(110,139,180,0.24)]" onClick={onNewChat}>
194
- <img className="tbox-new-chat-btn__icon size-[22px]" src={newChatIcon} alt="新对话" />
195
- </div>
193
+ <button type="button" data-tbox-control="new-chat" aria-label="新建对话" className="tbox-new-chat-btn flex size-11 shrink-0 cursor-pointer appearance-none items-center justify-center rounded-full border-0 bg-[rgba(255,255,255,0.5)] p-0 shadow-[0_1px_10px_rgba(110,139,180,0.24)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary" onClick={onNewChat}>
194
+ <img className="tbox-new-chat-btn__icon size-[22px]" src={newChatIcon} alt="" />
195
+ </button>
196
196
  )}
197
197
 
198
198
  <div className="tbox-chat-input__wrapper flex min-w-0 flex-1 items-end gap-[14px] rounded-[var(--tbox-input-radius)] border border-border bg-[var(--tbox-input-bg)] p-[var(--tbox-input-padding)] shadow-[0_1px_10px_rgba(110,139,180,0.24)] transition-[border-color,box-shadow] duration-[var(--tbox-motion-duration-fast)] ease-[var(--tbox-motion-easing-standard)] focus-within:border-primary focus-within:shadow-[0_0_0_1.5px_rgba(9,107,250,0.12)]">
@@ -208,7 +208,7 @@ export function ChatInput({
208
208
  />
209
209
  ) : (
210
210
  <textarea
211
- className="tbox-chat-input__field min-w-0 flex-1 resize-none border-0 bg-transparent p-0 text-base leading-[24px] text-foreground outline-none max-h-[100px] [font-family:inherit] placeholder:text-muted-foreground disabled:opacity-[0.45]"
211
+ className="tbox-chat-input__field min-h-11 min-w-0 flex-1 resize-none border-0 bg-transparent p-0 text-base leading-[24px] text-foreground outline-none max-h-[100px] [font-family:inherit] placeholder:text-muted-foreground disabled:opacity-[0.45]"
212
212
  value={text}
213
213
  placeholder={blocked?.message ?? '有什么需要问我的吗'}
214
214
  rows={1}
@@ -224,31 +224,36 @@ export function ChatInput({
224
224
  )}
225
225
 
226
226
  {enableVoice && (
227
- <div className="tbox-voice-toggle flex size-[22px] shrink-0 items-center justify-center" onClick={toggleMode}>
227
+ <button type="button" data-tbox-control="voice-toggle" aria-label={inputMode === 'voice' ? '切换到键盘输入' : '切换到语音输入'} aria-pressed={inputMode === 'voice'} className="tbox-voice-toggle flex size-11 -m-[11px] shrink-0 cursor-pointer appearance-none items-center justify-center border-0 bg-transparent p-0 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary" onClick={toggleMode}>
228
228
  <img
229
229
  className="tbox-voice-toggle__icon size-[22px]"
230
230
  src={inputMode === 'voice' ? keyboardIcon : voiceIcon}
231
- alt={inputMode === 'voice' ? '键盘' : '语音'}
231
+ alt=""
232
232
  />
233
- </div>
233
+ </button>
234
234
  )}
235
235
 
236
236
  {blocked ? null : generating ? (
237
- <div className="tbox-chat-input__send tbox-chat-input__send--active flex size-[var(--tbox-send-btn-size)] shrink-0 items-center justify-center" onClick={onCancel}>
238
- <img className="tbox-chat-input__send-img block size-[var(--tbox-send-btn-size)]" src={stopIcon} alt="停止" />
239
- </div>
237
+ <button type="button" data-tbox-control="stop" aria-label="停止生成" className="tbox-chat-input__send tbox-chat-input__send--active flex size-11 -m-[11px] shrink-0 cursor-pointer appearance-none items-center justify-center border-0 bg-transparent p-0 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary" onClick={onCancel}>
238
+ <img className="tbox-chat-input__send-img block size-[var(--tbox-send-btn-size)]" src={stopIcon} alt="" />
239
+ </button>
240
240
  ) : canSend ? (
241
- <div className="tbox-chat-input__send tbox-chat-input__send--active flex size-[var(--tbox-send-btn-size)] shrink-0 items-center justify-center" onClick={submit}>
242
- <img className="tbox-chat-input__send-img block size-[var(--tbox-send-btn-size)]" src={sendIcon} alt="发送" />
243
- </div>
241
+ <button type="button" data-tbox-control="send" aria-label="发送" className="tbox-chat-input__send tbox-chat-input__send--active flex size-11 -m-[11px] shrink-0 cursor-pointer appearance-none items-center justify-center border-0 bg-transparent p-0 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary" onClick={submit}>
242
+ <img className="tbox-chat-input__send-img block size-[var(--tbox-send-btn-size)]" src={sendIcon} alt="" />
243
+ </button>
244
244
  ) : menuOptions.length > 0 ? (
245
245
  <div className="tbox-media-picker relative shrink-0">
246
- <div
247
- className={`tbox-media-picker__trigger flex shrink-0 items-center justify-center transition-transform duration-[var(--tbox-motion-duration-base)] ease-[ease] ${menuVisible ? ' tbox-media-picker__trigger--open rotate-45' : ''}`}
246
+ <button
247
+ type="button"
248
+ data-tbox-control="media-add"
249
+ aria-label="添加图片或视频"
250
+ aria-haspopup="menu"
251
+ aria-expanded={menuVisible}
252
+ className={`tbox-media-picker__trigger flex size-11 -m-[11px] shrink-0 cursor-pointer appearance-none items-center justify-center border-0 bg-transparent p-0 transition-transform duration-[var(--tbox-motion-duration-base)] ease-[ease] ${menuVisible ? ' tbox-media-picker__trigger--open rotate-45' : ''}`}
248
253
  onClick={onPlus}
249
254
  >
250
- <img className="tbox-media-picker__trigger-icon size-[var(--tbox-send-btn-size)]" src={moreIcon} alt="更多" />
251
- </div>
255
+ <img className="tbox-media-picker__trigger-icon size-[var(--tbox-send-btn-size)]" src={moreIcon} alt="" />
256
+ </button>
252
257
  </div>
253
258
  ) : null}
254
259
  </div>
@@ -29,11 +29,12 @@ export default function HistoryEntry({
29
29
  <div className="history-entry flex justify-center p-0">
30
30
  <button
31
31
  type="button"
32
- className="history-entry__button inline-flex appearance-none items-center gap-[5px] rounded-[25px] border-0 bg-[rgba(15,64,113,0.06)] px-3 py-[3px] text-xs font-normal leading-[16px] text-muted-foreground transition-[background] duration-[var(--tbox-motion-duration-fast)] ease-[var(--tbox-motion-easing-standard)] [font-family:inherit] active:bg-[rgba(15,64,113,0.1)] disabled:cursor-default"
32
+ data-tbox-control="history"
33
+ className="history-entry__button inline-flex min-h-11 appearance-none items-center gap-[5px] rounded-[25px] border-0 bg-muted px-4 py-1 text-sm font-normal leading-[18px] text-muted-foreground transition-colors duration-[var(--tbox-motion-duration-fast)] ease-[var(--tbox-motion-easing-standard)] [font-family:inherit] active:bg-border disabled:cursor-default"
33
34
  disabled={disabled}
34
35
  onClick={onLoad}
35
36
  >
36
- {(loading || pullStatus === 'loading') && <span className="history-entry__spinner size-[10px] rounded-full border-[1.5px] border-[rgba(15,64,113,0.18)] border-t-primary animate-[history-entry-spin_0.6s_linear_infinite]" />}
37
+ {(loading || pullStatus === 'loading') && <span className="history-entry__spinner size-[10px] rounded-full border-[1.5px] border-border border-t-primary animate-[history-entry-spin_0.6s_linear_infinite]" />}
37
38
  {labelOf(pullStatus, loading)}
38
39
  </button>
39
40
  </div>
@@ -27,7 +27,9 @@ export function MessageBubble({ message }: { message: ChatMessage }) {
27
27
  const sendMessage = useChatStore((s) => s.sendMessage);
28
28
  const generating = useChatStore((s) => s.isGenerating);
29
29
  const isUser = message.role === 'user';
30
- const roleName = isUser ? '你' : 'AI 助手';
30
+ // 发送者名取应用身份(chat.json identity.name),没有配置才回落通用名。
31
+ const identity = useChatConfigStore((s) => s.identity);
32
+ const roleName = isUser ? '你' : (identity?.name ?? 'AI 助手');
31
33
  const timeLabel = new Date(message.createdAt).toLocaleTimeString('zh-CN', {
32
34
  hour: '2-digit',
33
35
  minute: '2-digit',
@@ -70,7 +72,11 @@ export function MessageBubble({ message }: { message: ChatMessage }) {
70
72
  }
71
73
 
72
74
  return (
73
- <div className={`msg-row mb-2.5 flex items-start px-page ${isUser ? 'msg-row--user flex-row-reverse' : 'msg-row--bot flex-row'}`}>
75
+ <div
76
+ className={`msg-row mb-2.5 flex items-start px-page ${isUser ? 'msg-row--user flex-row-reverse' : 'msg-row--bot flex-row'}`}
77
+ data-message-id={message.id}
78
+ data-message-role={message.role}
79
+ >
74
80
  <div className={isUser ? 'msg-main min-w-0' : 'msg-main min-w-0 flex-1'}>
75
81
  <div
76
82
  className={`msg-meta flex items-center ${isUser ? 'msg-meta--user justify-end' : 'msg-meta--bot justify-start'} ${!showBubble && messageCards.length > 0 ? 'msg-meta--solo-card mb-1.5' : 'mb-[3px]'}`}
@@ -104,17 +110,17 @@ export function MessageBubble({ message }: { message: ChatMessage }) {
104
110
  className={`msg-bubble leading-[1.6] ${isUser ? 'msg-bubble--user mb-1 ml-auto mr-0 flex min-h-6 w-fit max-w-full items-center rounded-[24px_4px_24px_24px] bg-[rgba(255,255,255,0.9)] px-[11px] py-[9px] shadow-[0_2px_8px_rgba(50,65,92,0.08)]' : 'msg-bubble--bot relative mb-1.5 rounded-[4px_24px_24px] border-[0.5px] border-[#edf0f6] bg-[rgba(255,255,255,0.4)] p-[11px] text-base text-foreground shadow-[0_1.5px_4px_2.5px_rgba(1,112,254,0.0392),0_1px_2px_rgba(72,78,86,0.0706)]'}`}
105
111
  >
106
112
  {isUser ? (
107
- <span className="msg-bubble__text text-xs leading-[1.6] font-medium text-foreground [overflow-wrap:break-word]">{message.content}</span>
113
+ <span className="msg-bubble__text text-base leading-[1.6] font-medium text-foreground [overflow-wrap:break-word]">{message.content}</span>
108
114
  ) : (
109
115
  <>
110
116
  {message.content && (
111
- <div className="msg-markdown text-xs leading-[1.6] text-foreground [overflow-wrap:anywhere] [&_h1]:mt-2! [&_h1]:mb-1! [&_h1]:text-lg [&_h1]:font-semibold [&_h1]:leading-[1.4] [&_h2]:mt-2! [&_h2]:mb-1! [&_h2]:text-base [&_h2]:font-semibold [&_h2]:leading-[1.4] [&_h3]:mt-2! [&_h3]:mb-1! [&_h3]:text-base [&_h3]:font-semibold [&_h3]:leading-[1.4] [&_h4]:mt-2! [&_h4]:mb-1! [&_h4]:text-sm [&_h4]:font-semibold [&_h4]:leading-[1.4] [&_h5]:mt-2! [&_h5]:mb-1! [&_h5]:font-semibold [&_h5]:leading-[1.4] [&_h6]:mt-2! [&_h6]:mb-1! [&_h6]:font-semibold [&_h6]:leading-[1.4] [&_p]:my-1! [&_strong]:font-semibold [&_em]:italic [&_a]:text-primary [&_a]:underline [&_ul]:my-1! [&_ul]:pl-4 [&_ol]:my-1! [&_ol]:pl-4 [&_li]:my-0.5 [&_blockquote]:my-1.5 [&_blockquote]:border-l-2 [&_blockquote]:border-l-[#667eea] [&_blockquote]:pl-2 [&_blockquote]:text-secondary-foreground [&_code]:rounded-[3px] [&_code]:bg-[rgba(0,0,0,0.06)] [&_code]:px-1 [&_code]:py-[1px] [&_code]:text-sm [&_code]:leading-[1.6] [&_code]:font-mono [&_pre]:my-1.5 [&_pre]:overflow-x-auto [&_pre]:rounded-[6px] [&_pre]:bg-[#1e1e2e] [&_pre]:p-2.5 [&_pre_code]:bg-transparent [&_pre_code]:p-0 [&_pre_code]:text-xs [&_pre_code]:leading-[1.6] [&_pre_code]:text-[#cdd6f4] [&_table]:my-1.5 [&_table]:w-full [&_table]:border-collapse [&_th]:border-[0.5px] [&_th]:border-border [&_th]:bg-muted [&_th]:px-1.5 [&_th]:py-1 [&_th]:text-left [&_th]:text-sm [&_th]:leading-[1.6] [&_th]:font-semibold [&_td]:border-[0.5px] [&_td]:border-border [&_td]:px-1.5 [&_td]:py-1 [&_td]:text-left [&_td]:text-sm [&_td]:leading-[1.6]">
117
+ <div className="msg-markdown text-base leading-[1.6] text-foreground [overflow-wrap:anywhere] [&_h1]:mt-2! [&_h1]:mb-1! [&_h1]:text-lg [&_h1]:font-semibold [&_h1]:leading-[1.4] [&_h2]:mt-2! [&_h2]:mb-1! [&_h2]:text-base [&_h2]:font-semibold [&_h2]:leading-[1.4] [&_h3]:mt-2! [&_h3]:mb-1! [&_h3]:text-base [&_h3]:font-semibold [&_h3]:leading-[1.4] [&_h4]:mt-2! [&_h4]:mb-1! [&_h4]:text-sm [&_h4]:font-semibold [&_h4]:leading-[1.4] [&_h5]:mt-2! [&_h5]:mb-1! [&_h5]:font-semibold [&_h5]:leading-[1.4] [&_h6]:mt-2! [&_h6]:mb-1! [&_h6]:font-semibold [&_h6]:leading-[1.4] [&_p]:my-1! [&_strong]:font-semibold [&_em]:italic [&_a]:text-primary [&_a]:underline [&_ul]:my-1! [&_ul]:pl-4 [&_ol]:my-1! [&_ol]:pl-4 [&_li]:my-0.5 [&_blockquote]:my-1.5 [&_blockquote]:border-l-2 [&_blockquote]:border-l-primary [&_blockquote]:pl-2 [&_blockquote]:text-secondary-foreground [&_code]:rounded-[3px] [&_code]:bg-[rgba(0,0,0,0.06)] [&_code]:px-1 [&_code]:py-[1px] [&_code]:text-sm [&_code]:leading-[1.6] [&_code]:font-mono [&_pre]:my-1.5 [&_pre]:overflow-x-auto [&_pre]:rounded-[6px] [&_pre]:bg-[#1e1e2e] [&_pre]:p-2.5 [&_pre_code]:bg-transparent [&_pre_code]:p-0 [&_pre_code]:text-xs [&_pre_code]:leading-[1.6] [&_pre_code]:text-[#cdd6f4] [&_table]:my-1.5 [&_table]:w-full [&_table]:border-collapse [&_th]:border-[0.5px] [&_th]:border-border [&_th]:bg-muted [&_th]:px-1.5 [&_th]:py-1 [&_th]:text-left [&_th]:text-sm [&_th]:leading-[1.6] [&_th]:font-semibold [&_td]:border-[0.5px] [&_td]:border-border [&_td]:px-1.5 [&_td]:py-1 [&_td]:text-left [&_td]:text-sm [&_td]:leading-[1.6]">
112
118
  <ReactMarkdown remarkPlugins={[remarkGfm]}>{message.content}</ReactMarkdown>
113
119
  </div>
114
120
  )}
115
121
  {message.error && (
116
122
  <div
117
- className={`msg-bubble__error whitespace-pre-wrap text-xs leading-[1.6] text-destructive [overflow-wrap:anywhere] ${message.content ? 'msg-bubble__error--with-content mt-[7px] border-t-[0.5px] border-t-destructive pt-[7px]' : ''}`}
123
+ className={`msg-bubble__error whitespace-pre-wrap text-sm leading-[1.6] text-destructive [overflow-wrap:anywhere] ${message.content ? 'msg-bubble__error--with-content mt-[7px] border-t-[0.5px] border-t-destructive pt-[7px]' : ''}`}
118
124
  role="alert"
119
125
  >
120
126
  {message.error}
@@ -76,7 +76,9 @@ describe('QuickCommands 快捷胶囊', () => {
76
76
  const buttons = [...container.querySelectorAll<HTMLButtonElement>('.quick-commands__item')];
77
77
  expect(buttons.map((button) => button.textContent)).toEqual(['今日优惠', '品牌导览', '活动中心']);
78
78
  expect(container.textContent).not.toContain('找门店');
79
- expect(buttons[1]?.querySelector('img')?.src).toContain('6-OCR5kWFa');
79
+ // 图标走 CSS mask + currentColor(换品牌色不再残留固定蓝),断言 mask 的图片地址。
80
+ const iconUrl = buttons[1]?.querySelector<HTMLElement>('.quick-commands__icon')?.getAttribute('data-icon') ?? '';
81
+ expect(iconUrl).toContain('6-OCR5kWFa');
80
82
  flushSync(() => buttons[1]!.click());
81
83
  expect(onCommand).toHaveBeenCalledWith('服务端品牌导览');
82
84
  });
@@ -1,6 +1,9 @@
1
1
  // 输入框上方的快捷指令;文案由 chatConfig 驱动,服务端下发不含 icon 时按 label 合并本地配置。
2
2
  // 011 I2:服务端 HelloAck.chatConfig.quickCommands 优先(单一真源),本地 chat.json 为 fallback。
3
3
  // label 只写纯文字;前面的星标由本组件渲染(icon 字段或默认 ✦),不要把 ✦/emoji 写进 label。
4
+ //
5
+ // 两种排布:空会话用 grid(两列、全可见、每个 44px 命中区),对话态用 row(底部单行、可横滚)。
6
+ // 颜色只用语义令牌:换品牌色后不残留固定蓝。
4
7
  import { useChatConfigStore } from '../../chat-config';
5
8
  import { useChatStore } from '../../store-context';
6
9
  import starIcon from '../../../assets/quick-command-star.svg';
@@ -8,9 +11,11 @@ import starIcon from '../../../assets/quick-command-star.svg';
8
11
  export function QuickCommands({
9
12
  onCommand,
10
13
  hidden = false,
14
+ variant = 'row',
11
15
  }: {
12
16
  onCommand: (query: string) => void;
13
17
  hidden?: boolean;
18
+ variant?: 'row' | 'grid';
14
19
  }) {
15
20
  const staticCommands = useChatConfigStore((s) => s.quickCommands);
16
21
  // chatConfig 可选链:旧 server 的 HELLO_ACK 可能不带该段(与「ack 缺席回落静态」同语义)
@@ -26,25 +31,43 @@ export function QuickCommands({
26
31
  : staticCommands;
27
32
  if (!commands.length) return null;
28
33
 
34
+ const grid = variant === 'grid';
29
35
  return (
30
36
  <div
31
- className={`quick-commands relative z-[1] mx-auto flex w-full max-w-content gap-2 overflow-x-auto px-page pb-[9px] [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden ${hidden ? ' quick-commands--hidden invisible pointer-events-none' : ''}`}
37
+ className={
38
+ grid
39
+ ? `quick-commands quick-commands--grid relative z-[1] mx-auto grid w-full max-w-content grid-cols-2 gap-2 px-page ${hidden ? ' quick-commands--hidden invisible pointer-events-none' : ''}`
40
+ : `quick-commands relative z-[1] mx-auto flex w-full max-w-content gap-2 overflow-x-auto px-page pb-[9px] [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden ${hidden ? ' quick-commands--hidden invisible pointer-events-none' : ''}`
41
+ }
32
42
  aria-hidden={hidden || undefined}
33
43
  >
34
44
  {commands.map((cmd) => (
35
45
  <button
36
46
  key={cmd.label}
37
- className="quick-commands__item inline-flex h-[34px] flex-[1_0_auto] appearance-none items-center justify-center gap-[5px] rounded-[25px] border border-[rgba(15,64,113,0.14)] bg-[rgba(255,255,255,0.92)] px-[13px] py-0 shadow-[0_4px_16px_rgba(38,59,92,0.05)] transition-[background,border-color] duration-[var(--tbox-motion-duration-fast)] ease-[var(--tbox-motion-easing-standard)] [font-family:inherit] active:border-primary"
47
+ className={
48
+ grid
49
+ ? 'quick-commands__item inline-flex min-h-11 w-full appearance-none items-center justify-start gap-1.5 rounded-[22px] border border-border bg-card px-3 py-2 text-left text-foreground shadow-sm transition-colors duration-[var(--tbox-motion-duration-fast)] ease-[var(--tbox-motion-easing-standard)] active:border-primary'
50
+ : 'quick-commands__item inline-flex min-h-11 flex-[1_0_auto] appearance-none items-center justify-center gap-1.5 rounded-[22px] border border-border bg-card px-3 py-2 text-foreground shadow-sm transition-colors duration-[var(--tbox-motion-duration-fast)] ease-[var(--tbox-motion-easing-standard)] active:border-primary'
51
+ }
38
52
  disabled={hidden}
39
53
  onClick={() => onCommand(cmd.query)}
40
54
  >
41
- <img
42
- className="quick-commands__icon size-4 object-contain"
43
- src={cmd.icon ?? starIcon}
44
- alt=""
45
- onError={(event) => { event.currentTarget.src = starIcon; }}
55
+ <span
56
+ className="quick-commands__icon size-4 shrink-0 bg-primary"
57
+ aria-hidden="true"
58
+ data-icon={cmd.icon ?? starIcon}
59
+ style={{
60
+ maskImage: `url("${cmd.icon ?? starIcon}")`,
61
+ WebkitMaskImage: `url("${cmd.icon ?? starIcon}")`,
62
+ maskSize: 'contain',
63
+ WebkitMaskSize: 'contain',
64
+ maskRepeat: 'no-repeat',
65
+ WebkitMaskRepeat: 'no-repeat',
66
+ maskPosition: 'center',
67
+ WebkitMaskPosition: 'center',
68
+ }}
46
69
  />
47
- <span className="quick-commands__label whitespace-nowrap text-sm font-medium leading-[18px] text-foreground">{cmd.label}</span>
70
+ <span className={`quick-commands__label text-sm font-medium leading-[18px] text-foreground ${grid ? 'line-clamp-2 text-left' : 'whitespace-nowrap'}`}>{cmd.label}</span>
48
71
  </button>
49
72
  ))}
50
73
  </div>
@@ -1,8 +1,12 @@
1
1
  /** 生成时出现的“回到底部”悬浮按钮。 */
2
2
  export default function ScrollToBottomButton({ visible, onClick }: { visible: boolean; onClick: () => void }) {
3
3
  return (
4
- <div className={`scroll-to-bottom-btn absolute right-4 bottom-4 z-10 flex size-9 items-center justify-center rounded-full bg-white shadow-[0_2px_8px_0_rgba(0,0,0,0.12)] transition-[opacity,transform] duration-[var(--tbox-motion-duration-fast)] ease-[ease] ${visible ? ' scroll-to-bottom-btn--visible pointer-events-auto opacity-100 [transform:scale(1)]' : ' pointer-events-none opacity-0 [transform:scale(0.8)]'}`} onClick={onClick}>
5
- <div className="scroll-to-bottom-btn__arrow h-0 w-0 border-x-[6px] border-t-[7px] border-x-transparent border-t-[#666]" />
6
- </div>
4
+ <button
5
+ type="button"
6
+ data-tbox-control="scroll-bottom"
7
+ aria-label="回到底部"
8
+ className={`scroll-to-bottom-btn absolute right-4 bottom-4 z-10 flex size-11 cursor-pointer appearance-none items-center justify-center rounded-full border-0 bg-white p-0 shadow-[0_2px_8px_0_rgba(0,0,0,0.12)] transition-[opacity,transform] duration-[var(--tbox-motion-duration-fast)] ease-[ease] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary ${visible ? ' scroll-to-bottom-btn--visible pointer-events-auto opacity-100 [transform:scale(1)]' : ' pointer-events-none opacity-0 [transform:scale(0.8)]'}`} onClick={onClick}>
9
+ <span className="scroll-to-bottom-btn__arrow h-0 w-0 border-x-[6px] border-t-[7px] border-x-transparent border-t-[#666]" aria-hidden="true" />
10
+ </button>
7
11
  );
8
12
  }
@@ -54,6 +54,8 @@ export default function ToolCallBlock({
54
54
  const listId = useId();
55
55
  const items = useMemo(() => toolCalls.map(deriveToolCallItem), [toolCalls]);
56
56
  const summary = useMemo(() => deriveSummary(items), [items]);
57
+ // 已恢复的失败不打扰用户:只有整批都失败时才展示失败计数与错误图标(B11)。
58
+ const allFailed = summary.failedCount > 0 && summary.failedCount === items.length;
57
59
 
58
60
  const toggleDetail = (id: string) => {
59
61
  setExpandedDetailIds((current) => {
@@ -79,14 +81,14 @@ export default function ToolCallBlock({
79
81
  className="tool-calls__spinner size-3.5 shrink-0 animate-[tool-spin_0.8s_linear_infinite] rounded-full border-2 border-[rgba(9,107,250,0.2)] border-t-primary motion-reduce:animate-none"
80
82
  aria-hidden="true"
81
83
  />
82
- ) : summary.failedCount > 0 ? (
84
+ ) : allFailed ? (
83
85
  <X className="tool-calls__icon tool-calls__icon--error shrink-0 self-center text-muted-foreground" size={16} strokeWidth={2.5} />
84
86
  ) : (
85
87
  <Check className="tool-calls__icon tool-calls__icon--success shrink-0 self-center text-muted-foreground" size={16} strokeWidth={2.5} />
86
88
  )}
87
89
  <span className="tool-calls__summary-text min-w-0 truncate text-xs font-normal leading-[1.4]">
88
90
  {buildSummaryText(summary).join(' · ')}
89
- {summary.failedCount > 0 && (
91
+ {allFailed && (
90
92
  <span className="tool-calls__failed text-muted-foreground"> · {summary.failedCount} 个失败</span>
91
93
  )}
92
94
  </span>
package/src/index.ts CHANGED
@@ -21,6 +21,9 @@ export {
21
21
  useClientSlots,
22
22
  } from './store-context';
23
23
  export type { KitChatContextValue } from './store-context';
24
+ export { KitPreviewProvider, createPreviewStore } from './preview-provider';
25
+ export { createSurfaceHarness } from './surface';
26
+ export type { SurfaceHarness, SurfaceHarnessOptions } from './surface';
24
27
 
25
28
  // ── chat 设置(构建期快照 + HELLO_ACK 水合) ──
26
29
  export { configureChatConfigDefaults, useChatConfigStore } from './chat-config';
@@ -38,6 +41,7 @@ export { CardRenderer, RawCardRenderer } from './components/CardRenderer';
38
41
 
39
42
  // ── 应用级卡片工厂与卡片内交互 ──
40
43
  export { defineCard } from './card/define-card';
44
+ export { ViewCard } from './card/view-card';
41
45
  export type { CardRenderProps, DefinedCard } from './card/define-card';
42
46
  export { useCardActions } from './card/use-card-actions';
43
47
  export type { CardActions, UseCardActionsOptions } from './card/use-card-actions';
@@ -120,3 +124,7 @@ export type {
120
124
  MessageStatus,
121
125
  ToolCallInfo,
122
126
  } from './types';
127
+
128
+ // ── 通用弹层 ──
129
+ export { BottomSheet, preloadBottomSheet } from './components/BottomSheet';
130
+ export type { BottomSheetProps } from './components/BottomSheet';
@@ -0,0 +1,47 @@
1
+ /**
2
+ * KitPreviewProvider:卡片预览面的最小装配根。
3
+ *
4
+ * 预览页直接渲染 SDK CardRenderer,没有应用 store——kit 卡片的 `useCardActions`
5
+ * 会因「KitChatProvider 缺席」抛错(预览 7/7 全红)。这里给一个只读预览 store:
6
+ * 动作写通道是空实现(预览页自己的动作通道另经 bindCardActionChannel 接管),
7
+ * 卡片能渲染、按钮能显示、历史/禁用态照常。
8
+ *
9
+ * 应用接线:app.config.ts 的 `wrapPreview` 返回 `createElement(KitPreviewProvider, null, node)`。
10
+ */
11
+ import { useMemo, type ReactNode } from 'react';
12
+ import { useStore } from 'zustand';
13
+ import { createStore } from 'zustand/vanilla';
14
+ import type { CardComponent } from '@tbox.cn/app-contracts';
15
+ import type { CoreChatState, CoreChatStore } from '@tbox.cn/app-agent-sdk-client';
16
+ import { KitChatProvider } from './store-context';
17
+
18
+ /** 预览用 store:只满足壳与卡片的读取(sendUiAction 空实现、不在生成中)。 */
19
+ export function createPreviewStore(state: Partial<CoreChatState> = {}): CoreChatStore {
20
+ const vanilla = createStore<CoreChatState>(() => ({
21
+ sendUiAction: () => {},
22
+ isGenerating: false,
23
+ ...state,
24
+ } as unknown as CoreChatState));
25
+ const hook = ((selector: (state: CoreChatState) => unknown) =>
26
+ useStore(vanilla, selector)) as unknown as CoreChatStore;
27
+ hook.getState = vanilla.getState;
28
+ hook.setState = vanilla.setState;
29
+ hook.subscribe = vanilla.subscribe;
30
+ return hook;
31
+ }
32
+
33
+ export function KitPreviewProvider({
34
+ cards = {},
35
+ children,
36
+ }: {
37
+ /** 预览页的卡片注册表(缺省空表;动作由预览页接管) */
38
+ cards?: Record<string, CardComponent>;
39
+ children: ReactNode;
40
+ }) {
41
+ const store = useMemo(() => createPreviewStore(), []);
42
+ return (
43
+ <KitChatProvider store={store} cards={cards} rawCards={cards}>
44
+ {children}
45
+ </KitChatProvider>
46
+ );
47
+ }
@@ -51,6 +51,15 @@
51
51
  "brandable": false
52
52
  }
53
53
  ],
54
+ "controls": [
55
+ { "id": "new-chat", "selector": "[data-tbox-control='new-chat']", "name": "新建对话", "minHit": 44 },
56
+ { "id": "voice-toggle", "selector": "[data-tbox-control='voice-toggle']", "name": "语音输入", "minHit": 44, "capability": "input.voice" },
57
+ { "id": "send", "selector": "[data-tbox-control='send']", "name": "发送", "minHit": 44 },
58
+ { "id": "stop", "selector": "[data-tbox-control='stop']", "name": "停止生成", "minHit": 44 },
59
+ { "id": "media-add", "selector": "[data-tbox-control='media-add']", "name": "添加图片或视频", "minHit": 44, "capability": ["input.image", "input.video"] },
60
+ { "id": "history", "selector": "[data-tbox-control='history']", "name": "历史记录", "minHit": 44 },
61
+ { "id": "scroll-bottom", "selector": "[data-tbox-control='scroll-bottom']", "name": "回到底部", "minHit": 44 }
62
+ ],
54
63
  "internal": [
55
64
  "MessageBubble 内部结构(.msg-row / .msg-main / .msg-thinking)",
56
65
  "ChatInput 内部结构(.tbox-media-picker、发送按钮)",