@tbox.cn/app-agent-ui-kit 0.0.0-stage → 1.0.0-alpha.6

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 (75) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +16 -2
  3. package/assets/keyboard-circle.svg +12 -0
  4. package/assets/more-circle.svg +3 -0
  5. package/assets/new-chat.svg +3 -0
  6. package/assets/quick-command-star.svg +3 -0
  7. package/assets/send-gradient.svg +14 -0
  8. package/assets/stop@2x.png +0 -0
  9. package/assets/voice-circle.svg +3 -0
  10. package/package.json +58 -3
  11. package/src/ChatPage.tsx +332 -0
  12. package/src/card/define-card.ts +34 -0
  13. package/src/card/primitives.test.tsx +147 -0
  14. package/src/card/primitives.tsx +627 -0
  15. package/src/card/use-card-actions.ts +86 -0
  16. package/src/chat-config.test.ts +46 -0
  17. package/src/chat-config.ts +80 -0
  18. package/src/components/ActionBar/DebugButton.test.tsx +84 -0
  19. package/src/components/ActionBar/DebugButton.tsx +53 -0
  20. package/src/components/ActionBar/index.test.tsx +83 -0
  21. package/src/components/ActionBar/index.tsx +158 -0
  22. package/src/components/CardRenderer.tsx +36 -0
  23. package/src/components/ChatHeader/index.test.tsx +74 -0
  24. package/src/components/ChatHeader/index.tsx +77 -0
  25. package/src/components/ChatInput/index.test.tsx +156 -0
  26. package/src/components/ChatInput/index.tsx +290 -0
  27. package/src/components/ChatInput/voice/VoicePressField.tsx +43 -0
  28. package/src/components/ChatInput/voice/VoiceRecordingOverlay.tsx +51 -0
  29. package/src/components/ChatInput/voice/machine.ts +27 -0
  30. package/src/components/ChatInput/voice/useVoicePress.ts +207 -0
  31. package/src/components/HistoryEntry/index.tsx +41 -0
  32. package/src/components/MediaList/index.tsx +270 -0
  33. package/src/components/MessageBubble/index.test.tsx +134 -0
  34. package/src/components/MessageBubble/index.tsx +202 -0
  35. package/src/components/PullDownIndicator/index.tsx +31 -0
  36. package/src/components/QuickCommands/index.test.tsx +99 -0
  37. package/src/components/QuickCommands/index.tsx +52 -0
  38. package/src/components/ReasoningBlock/index.tsx +61 -0
  39. package/src/components/ScrollToBottomButton/index.tsx +8 -0
  40. package/src/components/ToolCallBlock/detail.test.ts +346 -0
  41. package/src/components/ToolCallBlock/detail.ts +204 -0
  42. package/src/components/ToolCallBlock/index.test.tsx +261 -0
  43. package/src/components/ToolCallBlock/index.tsx +230 -0
  44. package/src/components/ToolCallBlock/titles.ts +102 -0
  45. package/src/hooks/use-drag-gesture.test.ts +66 -0
  46. package/src/hooks/use-drag-gesture.ts +129 -0
  47. package/src/hooks/use-pull-down-history.ts +241 -0
  48. package/src/hooks/use-pull-down-wheel-native.test.ts +64 -0
  49. package/src/hooks/useMediaUpload.ts +242 -0
  50. package/src/hooks/useTTSAutoPlay.ts +82 -0
  51. package/src/icons.ts +39 -0
  52. package/src/index.ts +122 -0
  53. package/src/shell.contract.json +59 -0
  54. package/src/shell.test.ts +61 -0
  55. package/src/shell.ts +45 -0
  56. package/src/store-context.tsx +92 -0
  57. package/src/test/setup.ts +7 -0
  58. package/src/theme/base.css +132 -0
  59. package/src/theme/contract.json +72 -0
  60. package/src/theme/motion.css +19 -0
  61. package/src/theme/theme-contract.test.ts +69 -0
  62. package/src/theme/theme.ts +17 -0
  63. package/src/theme/tokens.css +81 -0
  64. package/src/types.ts +29 -0
  65. package/src/utils/copyText.ts +11 -0
  66. package/src/utils/haptics.test.ts +51 -0
  67. package/src/utils/haptics.ts +44 -0
  68. package/src/utils/imagePreview.ts +10 -0
  69. package/src/utils/pull-down-machine.test.ts +188 -0
  70. package/src/utils/pull-down-machine.ts +157 -0
  71. package/src/utils/session-error.ts +5 -0
  72. package/src/utils/toast.ts +15 -0
  73. package/src/utils/tool-call-display.test.ts +240 -0
  74. package/src/utils/tool-call-display.ts +146 -0
  75. package/src/vite-env.d.ts +1 -0
@@ -0,0 +1,134 @@
1
+ // @vitest-environment happy-dom
2
+ import { act } from 'react';
3
+ import { createRoot } from 'react-dom/client';
4
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
5
+ import type { TboxCardPayload } from '@tbox.cn/app-contracts';
6
+
7
+ const mocks = vi.hoisted(() => ({
8
+ state: {
9
+ cardsByMessageId: {} as Record<string, TboxCardPayload[]>,
10
+ },
11
+ debugProps: null as Record<string, unknown> | null,
12
+ }));
13
+
14
+ vi.mock('../../store-context', () => ({
15
+ useChatStore: (selector: (state: typeof mocks.state) => unknown) => selector(mocks.state),
16
+ // W2-1:内联卡过滤经 context 注入(域语义保持原 witness:会员门禁卡系剥离,
17
+ // 原直连 '@/components/MemberGateSheet/model' 的 MEMBER_GATE_CARD_TYPES 语义)
18
+ useInlineCardFilter: () =>
19
+ (cards: Array<{ cardType: string }>) =>
20
+ cards.filter((c) => !['member-login-cta', 'member-enrollment-cta'].includes(c.cardType)),
21
+ }));
22
+ vi.mock('../CardRenderer', () => ({
23
+ CardRenderer: ({ card }: { card: TboxCardPayload }) => <div data-card-id={card.id} />,
24
+ }));
25
+ vi.mock('../../components/ReasoningBlock', () => ({ default: () => null }));
26
+ vi.mock('../../components/ToolCallBlock', () => ({ default: () => null }));
27
+ vi.mock('../../components/ActionBar', () => ({
28
+ ActionBar: () => null,
29
+ CopyButton: () => null,
30
+ getMessageCopyText: () => '',
31
+ }));
32
+ vi.mock('../../components/ActionBar/DebugButton', () => ({
33
+ DebugButton: (props: Record<string, unknown>) => {
34
+ mocks.debugProps = props;
35
+ return null;
36
+ },
37
+ }));
38
+
39
+ import { MessageBubble } from './index';
40
+
41
+ function card(id: string, cardType: string): TboxCardPayload {
42
+ return { id, cardType, data: {}, status: 'ready', meta: { createdAt: 1 } };
43
+ }
44
+
45
+ const emptyAssistantMessage = {
46
+ id: 'assistant-1',
47
+ role: 'assistant' as const,
48
+ content: '',
49
+ status: 'done' as const,
50
+ createdAt: 1,
51
+ };
52
+
53
+ describe('MessageBubble member gate card partition', () => {
54
+ let host: HTMLDivElement;
55
+ let root: ReturnType<typeof createRoot>;
56
+
57
+ beforeEach(() => {
58
+ host = document.createElement('div');
59
+ document.body.appendChild(host);
60
+ root = createRoot(host);
61
+ });
62
+
63
+ afterEach(() => {
64
+ act(() => root.unmount());
65
+ host.remove();
66
+ });
67
+
68
+ it('does not leave an empty message row for a login-only card', () => {
69
+ mocks.state.cardsByMessageId = {
70
+ 'assistant-1': [card('login-1', 'member-login-cta')],
71
+ };
72
+ act(() => root.render(<MessageBubble message={emptyAssistantMessage} />));
73
+ expect(host.innerHTML).toBe('');
74
+ });
75
+
76
+ it('keeps ordinary cards while removing the login card from a mixed carousel', () => {
77
+ mocks.state.cardsByMessageId = {
78
+ 'assistant-1': [
79
+ card('login-1', 'member-login-cta'),
80
+ card('coupon-1', 'coupon-detail'),
81
+ ],
82
+ };
83
+ act(() => root.render(<MessageBubble message={emptyAssistantMessage} />));
84
+ expect(host.querySelector('[data-card-id="login-1"]')).toBeNull();
85
+ expect(host.querySelector('[data-card-id="coupon-1"]')).not.toBeNull();
86
+ expect(host.querySelector('[aria-label^="第 "]')).toBeNull();
87
+ });
88
+
89
+ it('strips enrollment-cta from inline carousel (module button is a bypassing openLink jump)', () => {
90
+ mocks.state.cardsByMessageId = {
91
+ 'assistant-1': [
92
+ card('enroll-1', 'member-enrollment-cta'),
93
+ card('member-card-1', 'member-card-summary'),
94
+ ],
95
+ };
96
+ act(() => root.render(<MessageBubble message={emptyAssistantMessage} />));
97
+ // 入会卡内联渲染会旁路 gate 闭环(openLink 裸外跳)——必须剥离,由 MemberGateSheet 投影
98
+ expect(host.querySelector('[data-card-id="enroll-1"]')).toBeNull();
99
+ expect(host.querySelector('[data-card-id="member-card-1"]')).not.toBeNull();
100
+ });
101
+
102
+ it('多卡决策出卡 → 纵向按序渲染,无轮播圆点', () => {
103
+ mocks.state.cardsByMessageId = {
104
+ 'assistant-1': [
105
+ card('coupon-1', 'coupon-detail'),
106
+ card('member-1', 'member-card-summary'),
107
+ ],
108
+ };
109
+ act(() => root.render(<MessageBubble message={emptyAssistantMessage} />));
110
+ const all = host.querySelectorAll('[data-card-id]');
111
+ expect(all.length).toBe(2);
112
+ expect(all[0].getAttribute('data-card-id')).toBe('coupon-1');
113
+ expect(all[1].getAttribute('data-card-id')).toBe('member-1');
114
+ // 纵向铺开:不再有轮播圆点指示器
115
+ expect(host.querySelector('[aria-label^="第 "]')).toBeNull();
116
+ });
117
+
118
+ it('error 消息接线:DebugButton 透传 requestId + conversationId(error 分支守卫——不经 ActionBar 的独立渲染路径)', () => {
119
+ mocks.state.cardsByMessageId = {}; // 用例间隔离:清除前序用例的卡片桶残留
120
+ mocks.debugProps = null;
121
+ act(() => {
122
+ root.render(
123
+ <MessageBubble
124
+ message={{ ...emptyAssistantMessage, status: 'error' as const, error: '失败', requestId: 'req_e', conversationId: 'conv_e' }}
125
+ />,
126
+ );
127
+ });
128
+ expect(mocks.debugProps).toMatchObject({
129
+ requestId: 'req_e',
130
+ conversationId: 'conv_e',
131
+ messageId: 'assistant-1',
132
+ });
133
+ });
134
+ });
@@ -0,0 +1,202 @@
1
+ import { useMemo } from 'react';
2
+ import ReactMarkdown from 'react-markdown';
3
+ import remarkGfm from 'remark-gfm';
4
+ import { Copy } from '@phosphor-icons/react';
5
+ import { previewImages } from '../../utils/imagePreview';
6
+ import type { ChatMessage } from '../../types';
7
+ import ReasoningBlock from '../../components/ReasoningBlock';
8
+ import ToolCallBlock from '../../components/ToolCallBlock';
9
+ import { ActionBar, CopyButton, getMessageCopyText } from '../../components/ActionBar';
10
+ import { DebugButton } from '../../components/ActionBar/DebugButton';
11
+ import { CardRenderer } from '../CardRenderer';
12
+ import { CardCarousel } from '@tbox.cn/app-agent-sdk-client';
13
+ import { useChatStore, useInlineCardFilter } from '../../store-context';
14
+ import { useChatConfigStore } from '../../chat-config';
15
+ import { copyText } from '../../utils/copyText';
16
+ import { toast } from '../../utils/toast';
17
+
18
+ const TBOX_FILE_URL = 'https://mdn.alipayobjects.com/tcmarket/afts/file/';
19
+
20
+ /** 消息气泡(对齐原模板):meta + 思考/工具/卡片 + 气泡 + 媒体 + 操作栏。 */
21
+ export function MessageBubble({ message }: { message: ChatMessage }) {
22
+ const cardsByMessageId = useChatStore((s) => s.cardsByMessageId);
23
+ // 018 tool-debug:服务端旗标单源(HELLO_ACK;无 URL 逃逸——数据面信任锚点在服务端)
24
+ const toolDebug = useChatStore((s) => s.helloAck?.toolDebug === true);
25
+ const retryOnError = useChatConfigStore((s) => s.retryOnError);
26
+ const messages = useChatStore((s) => s.messages);
27
+ const sendMessage = useChatStore((s) => s.sendMessage);
28
+ const generating = useChatStore((s) => s.isGenerating);
29
+ const isUser = message.role === 'user';
30
+ const roleName = isUser ? '你' : 'AI 助手';
31
+ const timeLabel = new Date(message.createdAt).toLocaleTimeString('zh-CN', {
32
+ hour: '2-digit',
33
+ minute: '2-digit',
34
+ hour12: false,
35
+ });
36
+
37
+ const isThinking = message.status === 'thinking';
38
+ const isStreaming = message.status === 'streaming';
39
+ const hasReasoning = !!message.reasoning;
40
+ // 018:formSubmit 伪工具 prod 过滤不变;dev 放行(防御性——若事件到达则可见)
41
+ const visibleToolCalls = useMemo(
42
+ () => (message.toolCalls || []).filter((tc) => toolDebug || tc.name !== '__a2uiFormSubmit'),
43
+ [message.toolCalls, toolDebug],
44
+ );
45
+ const hasToolCalls = visibleToolCalls.length > 0;
46
+
47
+ const filterInlineCards = useInlineCardFilter();
48
+ const messageCards = useMemo(
49
+ () => (isUser ? [] : filterInlineCards(cardsByMessageId[message.id] || [])),
50
+ [cardsByMessageId, message.id, isUser, filterInlineCards],
51
+ );
52
+ const imageItems = isUser
53
+ ? message.mediaItems?.filter((i) => i.type === 'image' && (i.src || i.fileId))
54
+ : undefined;
55
+
56
+ const isPureThinking = isThinking && !hasReasoning && !message.content && !hasToolCalls;
57
+ const isReasoningActive = isThinking || (isStreaming && !message.content);
58
+ const showBubble = isUser || !!message.content || !!message.error || isStreaming;
59
+
60
+ const copy = async () => {
61
+ const copied = await copyText(message.content);
62
+ void toast(copied ? '复制成功' : '复制失败,请重试', copied ? 'success' : 'error');
63
+ };
64
+
65
+ const imageUrls = (imageItems || []).map((it) => it.src || `${TBOX_FILE_URL}${it.fileId}`);
66
+
67
+ // 登录入口由页面级半屏浮层承载;仅含登录卡的空 assistant 行不进入聊天流。
68
+ if (!isUser && !isPureThinking && !hasReasoning && !hasToolCalls && !showBubble && messageCards.length === 0) {
69
+ return null;
70
+ }
71
+
72
+ 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'}`}>
74
+ <div className={isUser ? 'msg-main min-w-0' : 'msg-main min-w-0 flex-1'}>
75
+ <div
76
+ 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]'}`}
77
+ >
78
+ <span className="msg-meta__role mr-1 text-xs leading-[normal] text-secondary-foreground">{roleName}</span>
79
+ <span className="msg-meta__time text-xs leading-[normal] text-muted-foreground">{timeLabel}</span>
80
+ </div>
81
+
82
+ {isPureThinking && (
83
+ <div className="msg-thinking ml-1.5 flex items-center justify-start gap-1 py-[5px]">
84
+ <div className="msg-thinking__dot h-[5px] w-[5px] animate-[dot-fade_1.4s_ease-in-out_infinite] rounded-full bg-[#aab3c2]" />
85
+ <div className="msg-thinking__dot msg-thinking__dot--2 h-[5px] w-[5px] animate-[dot-fade_1.4s_ease-in-out_infinite] rounded-full bg-[#aab3c2] [animation-delay:0.2s]" />
86
+ <div className="msg-thinking__dot msg-thinking__dot--3 h-[5px] w-[5px] animate-[dot-fade_1.4s_ease-in-out_infinite] rounded-full bg-[#aab3c2] [animation-delay:0.4s]" />
87
+ </div>
88
+ )}
89
+
90
+ {hasReasoning && <ReasoningBlock reasoning={message.reasoning!} isActive={isReasoningActive} />}
91
+
92
+ {hasToolCalls && <ToolCallBlock toolCalls={visibleToolCalls} debug={toolDebug} />}
93
+
94
+ {isThinking && hasToolCalls && !message.content && (
95
+ <div className="msg-thinking-inline ml-1.5 flex items-center justify-start gap-1 py-[5px]">
96
+ <div className="msg-thinking-inline__dot h-[5px] w-[5px] animate-[dot-fade_1.4s_ease-in-out_infinite] rounded-full bg-[#aab3c2]" />
97
+ <div className="msg-thinking-inline__dot msg-thinking-inline__dot--2 h-[5px] w-[5px] animate-[dot-fade_1.4s_ease-in-out_infinite] rounded-full bg-[#aab3c2] [animation-delay:0.2s]" />
98
+ <div className="msg-thinking-inline__dot msg-thinking-inline__dot--3 h-[5px] w-[5px] animate-[dot-fade_1.4s_ease-in-out_infinite] rounded-full bg-[#aab3c2] [animation-delay:0.4s]" />
99
+ </div>
100
+ )}
101
+
102
+ {showBubble && (
103
+ <div
104
+ 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
+ >
106
+ {isUser ? (
107
+ <span className="msg-bubble__text text-xs leading-[1.6] font-medium text-foreground [overflow-wrap:break-word]">{message.content}</span>
108
+ ) : (
109
+ <>
110
+ {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]">
112
+ <ReactMarkdown remarkPlugins={[remarkGfm]}>{message.content}</ReactMarkdown>
113
+ </div>
114
+ )}
115
+ {message.error && (
116
+ <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]' : ''}`}
118
+ role="alert"
119
+ >
120
+ {message.error}
121
+ </div>
122
+ )}
123
+ {isStreaming && <span className="msg-cursor ml-0.5 inline-block h-3 w-[2px] animate-[blink_1s_step-end_infinite] align-middle bg-[#5874ff]" />}
124
+ </>
125
+ )}
126
+ </div>
127
+ )}
128
+
129
+ {/* 卡片在对话气泡之后显示(决策出卡多张/意图卡/历史卡统一经 cardsByMessageId 挂载,多卡纵向铺开) */}
130
+ <CardCarousel
131
+ className="msg-cards mt-1"
132
+ cards={messageCards}
133
+ renderItem={(card) => <CardRenderer key={card.id} card={card} />}
134
+ />
135
+
136
+ {imageItems && imageItems.length > 0 && (
137
+ <div className="msg-media mt-0.5 mr-1.5 flex flex-nowrap gap-2 overflow-x-auto [direction:rtl] [-webkit-overflow-scrolling:touch] [&::-webkit-scrollbar]:hidden">
138
+ {imageItems.map((item, idx) => (
139
+ <img
140
+ key={item.id}
141
+ className="msg-media__thumb h-[var(--tbox-media-item-size)] w-[var(--tbox-media-item-size)] min-w-[var(--tbox-media-item-size)] shrink-0 rounded-[var(--tbox-media-item-radius)] object-cover [direction:ltr]"
142
+ src={item.src || `${TBOX_FILE_URL}${item.fileId}`}
143
+ alt=""
144
+ onClick={() => previewImages(imageUrls, idx)}
145
+ />
146
+ ))}
147
+ </div>
148
+ )}
149
+
150
+ {isUser && !!message.content && (
151
+ <div className="msg-toolbar msg-toolbar--user mt-1 flex items-center justify-end pr-1.5 opacity-40">
152
+ <div className="msg-toolbar__action flex h-[14px] w-[17px] items-center justify-center" onClick={copy}>
153
+ <Copy size={12} color="#535b6c" />
154
+ </div>
155
+ </div>
156
+ )}
157
+
158
+ {!isUser && message.status === 'done' && !!message.content && (
159
+ <div className="msg-toolbar-row flex flex-wrap items-center gap-1.5">
160
+ <ActionBar message={message} />
161
+ </div>
162
+ )}
163
+
164
+ {/* 出错消息不提供朗读/反馈;支持重试(重发上一条用户消息)、复制错误详情与拉 trace 排查。 */}
165
+ {!isUser && message.status === 'error' && (
166
+ <div className="msg-toolbar-row flex flex-wrap items-center gap-1.5">
167
+ <div className="tbox-action-bar">
168
+ {retryOnError ? (
169
+ <button
170
+ type="button"
171
+ className="msg-retry cursor-pointer border-0 bg-transparent px-1 py-0.5 text-xs leading-[normal] text-primary [font-family:inherit] disabled:cursor-not-allowed disabled:text-muted-foreground"
172
+ disabled={generating}
173
+ onClick={() => {
174
+ const index = messages.findIndex((item) => item.id === message.id);
175
+ const scope = index >= 0 ? messages.slice(0, index) : messages;
176
+ const lastUser = [...scope].reverse().find((item) => item.role === 'user');
177
+ if (!lastUser?.content) {
178
+ void toast('没有可重发的消息', 'info');
179
+ return;
180
+ }
181
+ sendMessage(lastUser.content);
182
+ }}
183
+ >
184
+ 重试
185
+ </button>
186
+ ) : null}
187
+ <CopyButton text={getMessageCopyText(message)} />
188
+ {message.requestId && (
189
+ <DebugButton
190
+ requestId={message.requestId}
191
+ conversationId={message.conversationId}
192
+ messageId={message.id}
193
+ messageCreatedAt={new Date(message.createdAt).getTime()}
194
+ />
195
+ )}
196
+ </div>
197
+ </div>
198
+ )}
199
+ </div>
200
+ </div>
201
+ );
202
+ }
@@ -0,0 +1,31 @@
1
+ import type { PullStatus } from '../../utils/pull-down-machine';
2
+ import { PULL_DOWN_THRESHOLD } from '../../utils/pull-down-machine';
3
+
4
+ /** 下拉加载历史的顶部指示器。 */
5
+ export default function PullDownIndicator({ status, distance }: { status: PullStatus; distance: number }) {
6
+ if (status === 'idle') return null;
7
+
8
+ const marginTop = status === 'loading' ? 0 : -PULL_DOWN_THRESHOLD + Math.min(distance, PULL_DOWN_THRESHOLD);
9
+ const showTransition = status === 'loading' || status === 'noMore';
10
+
11
+ const content =
12
+ status === 'pulling'
13
+ ? '↓ 下拉加载更多'
14
+ : status === 'ready'
15
+ ? '↑ 释放加载历史'
16
+ : status === 'loading'
17
+ ? '加载中...'
18
+ : status === 'noMore'
19
+ ? '没有更多历史记录'
20
+ : '';
21
+
22
+ return (
23
+ <div
24
+ className={`pull-indicator flex h-[30px] items-center justify-center gap-[6px] ${showTransition ? ' pull-indicator--animated transition-[margin-top] duration-[var(--tbox-motion-duration-base)] ease-out' : ''}`}
25
+ style={{ marginTop: `${marginTop}px` }}
26
+ >
27
+ {status === 'loading' && <div className="pull-indicator__spinner size-4 rounded-full border-[1.5px] border-border-strong border-t-primary animate-[pull-spin_0.6s_linear_infinite]" />}
28
+ <span className="pull-indicator__text text-sm leading-none text-[#8c8c8c]">{content}</span>
29
+ </div>
30
+ );
31
+ }
@@ -0,0 +1,99 @@
1
+ // @vitest-environment happy-dom
2
+ /**
3
+ * QuickCommands 快捷胶囊(W2-1 自 mall 随迁):断言原样——harness 改 kit context 注入形式
4
+ * (原 mock 应用 store → 现最小测试 store + KitChatProvider;本地图文合并经 config store 快照注入)。
5
+ */
6
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
7
+ import { createRoot } from 'react-dom/client';
8
+ import { flushSync } from 'react-dom';
9
+ import type { ReactNode } from 'react';
10
+ import { create } from 'zustand';
11
+ import type { CoreChatStore } from '@tbox.cn/app-agent-sdk-client';
12
+ import { configureChatConfigDefaults, useChatConfigStore } from '../../chat-config';
13
+ import { KitChatProvider } from '../../store-context';
14
+ import { QuickCommands } from './index';
15
+
16
+ /** 最小测试 store(仅 helloAck 消费面);注入形式经 KitChatProvider。 */
17
+ const testStore = create<{ helloAck: unknown }>(() => ({ helloAck: null })) as unknown as CoreChatStore;
18
+
19
+ /** 构建期快照(对齐 mall config/chat.json 三条——本地图标合并真源) */
20
+ const STATIC_COMMANDS = [
21
+ {
22
+ label: '今日优惠',
23
+ query: '现在有什么优惠?',
24
+ icon: 'https://mdn.alipayobjects.com/agt_content/afts/img/yirAQ7obEFcAAAAAAAAAAAAAehe3AQBr/original',
25
+ },
26
+ {
27
+ label: '品牌导览',
28
+ query: '品牌导览',
29
+ icon: 'https://mdn.alipayobjects.com/agt_content/afts/img/6-OCR5kWFaAAAAAAAAAAAAAAehe3AQBr/original',
30
+ },
31
+ {
32
+ label: '活动中心',
33
+ query: '活动中心',
34
+ icon: 'https://mdn.alipayobjects.com/agt_content/afts/img/yirAQ7obEFcAAAAAAAAAAAAAehe3AQBr/original',
35
+ },
36
+ ];
37
+
38
+ function renderWithKit(container: HTMLElement, node: ReactNode): void {
39
+ flushSync(() =>
40
+ createRoot(container).render(
41
+ <KitChatProvider store={testStore} cards={{}} rawCards={{}}>
42
+ {node}
43
+ </KitChatProvider>,
44
+ ),
45
+ );
46
+ }
47
+
48
+ beforeEach(() => {
49
+ configureChatConfigDefaults({ quickCommands: STATIC_COMMANDS });
50
+ });
51
+
52
+ afterEach(() => {
53
+ testStore.setState({ helloAck: null } as never);
54
+ useChatConfigStore.setState({ quickCommands: [] });
55
+ document.body.innerHTML = '';
56
+ });
57
+
58
+ describe('QuickCommands 快捷胶囊', () => {
59
+ it('按服务端顺序渲染三项、合并本地图标并发送服务端 prompt', () => {
60
+ testStore.setState({
61
+ helloAck: {
62
+ chatConfig: {
63
+ quickCommands: [
64
+ { label: '今日优惠', prompt: '服务端优惠查询' },
65
+ { label: '品牌导览', prompt: '服务端品牌导览' },
66
+ { label: '活动中心', prompt: '服务端活动查询' },
67
+ ],
68
+ },
69
+ },
70
+ } as never);
71
+ const onCommand = vi.fn();
72
+ const container = document.createElement('div');
73
+ document.body.appendChild(container);
74
+ renderWithKit(container, <QuickCommands onCommand={onCommand} />);
75
+
76
+ const buttons = [...container.querySelectorAll<HTMLButtonElement>('.quick-commands__item')];
77
+ expect(buttons.map((button) => button.textContent)).toEqual(['今日优惠', '品牌导览', '活动中心']);
78
+ expect(container.textContent).not.toContain('找门店');
79
+ expect(buttons[1]?.querySelector('img')?.src).toContain('6-OCR5kWFa');
80
+ flushSync(() => buttons[1]!.click());
81
+ expect(onCommand).toHaveBeenCalledWith('服务端品牌导览');
82
+ });
83
+
84
+ it('隐藏时保留胶囊容器,但禁止交互', () => {
85
+ const onCommand = vi.fn();
86
+ const container = document.createElement('div');
87
+ document.body.appendChild(container);
88
+ renderWithKit(container, <QuickCommands hidden onCommand={onCommand} />);
89
+
90
+ const commands = container.querySelector('.quick-commands');
91
+ const button = container.querySelector<HTMLButtonElement>('.quick-commands__item');
92
+ expect(commands).not.toBeNull();
93
+ expect(commands?.classList.contains('quick-commands--hidden')).toBe(true);
94
+ expect(commands?.getAttribute('aria-hidden')).toBe('true');
95
+ expect(button?.disabled).toBe(true);
96
+ flushSync(() => button?.click());
97
+ expect(onCommand).not.toHaveBeenCalled();
98
+ });
99
+ });
@@ -0,0 +1,52 @@
1
+ // 输入框上方的快捷指令;文案由 chatConfig 驱动,服务端下发不含 icon 时按 label 合并本地配置。
2
+ // 011 I2:服务端 HelloAck.chatConfig.quickCommands 优先(单一真源),本地 chat.json 为 fallback。
3
+ // label 只写纯文字;前面的星标由本组件渲染(icon 字段或默认 ✦),不要把 ✦/emoji 写进 label。
4
+ import { useChatConfigStore } from '../../chat-config';
5
+ import { useChatStore } from '../../store-context';
6
+ import starIcon from '../../../assets/quick-command-star.svg';
7
+
8
+ export function QuickCommands({
9
+ onCommand,
10
+ hidden = false,
11
+ }: {
12
+ onCommand: (query: string) => void;
13
+ hidden?: boolean;
14
+ }) {
15
+ const staticCommands = useChatConfigStore((s) => s.quickCommands);
16
+ // chatConfig 可选链:旧 server 的 HELLO_ACK 可能不带该段(与「ack 缺席回落静态」同语义)
17
+ const serverCommands = useChatStore((s) => s.helloAck?.chatConfig?.quickCommands);
18
+ // 服务端下发优先;未收到 HELLO_ACK(非 mall 部署)回落本地静态
19
+ const staticByLabel = new Map(staticCommands.map((command) => [command.label, command]));
20
+ const commands = serverCommands && serverCommands.length > 0
21
+ ? serverCommands.map((command) => ({
22
+ label: command.label,
23
+ query: command.prompt,
24
+ icon: staticByLabel.get(command.label)?.icon,
25
+ }))
26
+ : staticCommands;
27
+ if (!commands.length) return null;
28
+
29
+ return (
30
+ <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' : ''}`}
32
+ aria-hidden={hidden || undefined}
33
+ >
34
+ {commands.map((cmd) => (
35
+ <button
36
+ 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"
38
+ disabled={hidden}
39
+ onClick={() => onCommand(cmd.query)}
40
+ >
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; }}
46
+ />
47
+ <span className="quick-commands__label whitespace-nowrap text-sm font-medium leading-[18px] text-foreground">{cmd.label}</span>
48
+ </button>
49
+ ))}
50
+ </div>
51
+ );
52
+ }
@@ -0,0 +1,61 @@
1
+ import { useEffect, useRef, useState } from 'react';
2
+ import ReactMarkdown from 'react-markdown';
3
+ import remarkGfm from 'remark-gfm';
4
+
5
+ interface Props {
6
+ reasoning: string;
7
+ /** 是否正在思考中(自动展开 + 计时) */
8
+ isActive?: boolean;
9
+ }
10
+
11
+ /** 思考过程折叠块(思考中自动展开并计时,结束后自动收起)。 */
12
+ export default function ReasoningBlock({ reasoning, isActive }: Props) {
13
+ const [expanded, setExpanded] = useState(!!isActive);
14
+ const startTime = useRef(Date.now());
15
+ const [elapsed, setElapsed] = useState(0);
16
+ const wasActive = useRef(isActive);
17
+
18
+ useEffect(() => {
19
+ if (isActive) {
20
+ wasActive.current = true;
21
+ setExpanded(true);
22
+ startTime.current = Date.now();
23
+ const timer = setInterval(() => {
24
+ setElapsed(Math.floor((Date.now() - startTime.current) / 1000));
25
+ }, 1000);
26
+ return () => clearInterval(timer);
27
+ }
28
+ if (wasActive.current) {
29
+ setExpanded(false);
30
+ wasActive.current = false;
31
+ }
32
+ }, [isActive]);
33
+
34
+ const durationLabel = elapsed > 0 ? `${elapsed}s` : '';
35
+
36
+ return (
37
+ <div
38
+ className={`reasoning mb-2 max-w-full min-w-0 overflow-hidden rounded-[7px] ${isActive ? 'reasoning--active bg-[linear-gradient(135deg,rgba(102,126,234,0.08)_0%,rgba(118,75,162,0.06)_100%)]' : 'reasoning--done bg-[rgba(0,0,0,0.03)]'}`}
39
+ >
40
+ <div className="reasoning__header flex items-center justify-between px-[9px] py-[7px]" onClick={() => setExpanded(!expanded)}>
41
+ <div className="reasoning__left flex items-center gap-1">
42
+ <div
43
+ className={`reasoning__indicator size-[5px] shrink-0 rounded-full ${isActive ? 'reasoning__indicator--pulse animate-[reasoning-pulse_1.5s_ease-in-out_infinite] bg-[#667eea]' : 'bg-[#b0bec5]'}`}
44
+ />
45
+ <span className={`reasoning__title text-xs leading-[normal] font-semibold ${isActive ? 'text-[#667eea]' : 'text-[#6b7a99]'}`}>{isActive ? '思考中...' : '思考过程'}</span>
46
+ {durationLabel && <span className="reasoning__duration text-xs leading-[normal] text-[#9ba7c3]">({durationLabel})</span>}
47
+ </div>
48
+ <span className={`reasoning__toggle text-xs leading-[normal] text-[#8b95b0] ${expanded ? 'reasoning__toggle--up' : ''}`}>
49
+ {expanded ? '收起' : '展开'}
50
+ </span>
51
+ </div>
52
+ {expanded && (
53
+ <div
54
+ className={`reasoning__content mx-[9px] mb-2 overflow-hidden border-l-[1.5px] pl-[21px] text-xs leading-[1.7] text-[#8b95b0] [overflow-wrap:break-word] [&_p]:my-[3px]! ${isActive ? 'border-l-[#667eea]' : 'border-l-[#d6dce8]'}`}
55
+ >
56
+ <ReactMarkdown remarkPlugins={[remarkGfm]}>{reasoning}</ReactMarkdown>
57
+ </div>
58
+ )}
59
+ </div>
60
+ );
61
+ }
@@ -0,0 +1,8 @@
1
+ /** 生成时出现的“回到底部”悬浮按钮。 */
2
+ export default function ScrollToBottomButton({ visible, onClick }: { visible: boolean; onClick: () => void }) {
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>
7
+ );
8
+ }