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

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 (99) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +69 -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 +70 -3
  11. package/src/ChatPage.tsx +400 -0
  12. package/src/card/action-list-pending.test.tsx +91 -0
  13. package/src/card/define-card.test.ts +25 -0
  14. package/src/card/define-card.ts +47 -0
  15. package/src/card/primitives.test.tsx +157 -0
  16. package/src/card/primitives.tsx +717 -0
  17. package/src/card/use-card-actions.ts +86 -0
  18. package/src/card/view-card-inline.test.tsx +42 -0
  19. package/src/card/view-card.test.tsx +79 -0
  20. package/src/card/view-card.tsx +250 -0
  21. package/src/chat-config.test.ts +46 -0
  22. package/src/chat-config.ts +84 -0
  23. package/src/components/ActionBar/DebugButton.test.tsx +87 -0
  24. package/src/components/ActionBar/DebugButton.tsx +48 -0
  25. package/src/components/ActionBar/index.test.tsx +83 -0
  26. package/src/components/ActionBar/index.tsx +158 -0
  27. package/src/components/BottomSheet/index.test.tsx +97 -0
  28. package/src/components/BottomSheet/index.tsx +49 -0
  29. package/src/components/CardRenderer.tsx +36 -0
  30. package/src/components/ChatHeader/index.test.tsx +74 -0
  31. package/src/components/ChatHeader/index.tsx +77 -0
  32. package/src/components/ChatInput/index.test.tsx +156 -0
  33. package/src/components/ChatInput/index.tsx +295 -0
  34. package/src/components/ChatInput/voice/VoicePressField.tsx +43 -0
  35. package/src/components/ChatInput/voice/VoiceRecordingOverlay.tsx +51 -0
  36. package/src/components/ChatInput/voice/machine.ts +27 -0
  37. package/src/components/ChatInput/voice/useVoicePress.ts +207 -0
  38. package/src/components/HistoryEntry/index.tsx +42 -0
  39. package/src/components/MediaList/index.tsx +270 -0
  40. package/src/components/MessageBubble/index.test.tsx +134 -0
  41. package/src/components/MessageBubble/index.tsx +208 -0
  42. package/src/components/PullDownIndicator/index.tsx +31 -0
  43. package/src/components/QuickCommands/index.test.tsx +101 -0
  44. package/src/components/QuickCommands/index.tsx +75 -0
  45. package/src/components/ReasoningBlock/index.tsx +61 -0
  46. package/src/components/ScrollToBottomButton/index.tsx +12 -0
  47. package/src/components/ToolCallBlock/detail.test.ts +346 -0
  48. package/src/components/ToolCallBlock/detail.ts +204 -0
  49. package/src/components/ToolCallBlock/index.test.tsx +261 -0
  50. package/src/components/ToolCallBlock/index.tsx +232 -0
  51. package/src/components/ToolCallBlock/titles.ts +102 -0
  52. package/src/hooks/use-drag-gesture.test.ts +66 -0
  53. package/src/hooks/use-drag-gesture.ts +129 -0
  54. package/src/hooks/use-pull-down-history.ts +241 -0
  55. package/src/hooks/use-pull-down-wheel-native.test.ts +64 -0
  56. package/src/hooks/useMediaUpload.ts +242 -0
  57. package/src/hooks/useTTSAutoPlay.ts +82 -0
  58. package/src/icons.ts +39 -0
  59. package/src/index.ts +143 -0
  60. package/src/overlay/Overlay.tsx +154 -0
  61. package/src/overlay/focus.ts +53 -0
  62. package/src/overlay/index.ts +16 -0
  63. package/src/overlay/inert.ts +27 -0
  64. package/src/overlay/layers.ts +21 -0
  65. package/src/overlay/overlay.ssr.test.tsx +27 -0
  66. package/src/overlay/overlay.test.tsx +209 -0
  67. package/src/overlay/presence.ts +86 -0
  68. package/src/overlay/scroll-lock.ts +62 -0
  69. package/src/overlay/stack.ts +111 -0
  70. package/src/overlay/use-overlay.ts +80 -0
  71. package/src/preview-provider.tsx +47 -0
  72. package/src/shell.contract.json +75 -0
  73. package/src/shell.test.ts +72 -0
  74. package/src/shell.ts +60 -0
  75. package/src/store-context.tsx +92 -0
  76. package/src/surface.test.tsx +35 -0
  77. package/src/surface.tsx +44 -0
  78. package/src/test/setup.ts +7 -0
  79. package/src/theme/base.css +167 -0
  80. package/src/theme/contract.json +193 -0
  81. package/src/theme/motion.css +19 -0
  82. package/src/theme/theme-contract.test.ts +85 -0
  83. package/src/theme/theme.ts +17 -0
  84. package/src/theme/tokens.css +78 -0
  85. package/src/types.ts +29 -0
  86. package/src/utils/copyText.ts +11 -0
  87. package/src/utils/haptics.test.ts +51 -0
  88. package/src/utils/haptics.ts +44 -0
  89. package/src/utils/image-preview-host.tsx +95 -0
  90. package/src/utils/imagePreview.test.ts +32 -0
  91. package/src/utils/imagePreview.ts +19 -0
  92. package/src/utils/pull-down-machine.test.ts +188 -0
  93. package/src/utils/pull-down-machine.ts +157 -0
  94. package/src/utils/session-error.ts +5 -0
  95. package/src/utils/toast.test.ts +64 -0
  96. package/src/utils/toast.ts +108 -0
  97. package/src/utils/tool-call-display.test.ts +240 -0
  98. package/src/utils/tool-call-display.ts +146 -0
  99. package/src/vite-env.d.ts +1 -0
@@ -0,0 +1,208 @@
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
+ // 发送者名取应用身份(chat.json identity.name),没有配置才回落通用名。
31
+ const identity = useChatConfigStore((s) => s.identity);
32
+ const roleName = isUser ? '你' : (identity?.name ?? 'AI 助手');
33
+ const timeLabel = new Date(message.createdAt).toLocaleTimeString('zh-CN', {
34
+ hour: '2-digit',
35
+ minute: '2-digit',
36
+ hour12: false,
37
+ });
38
+
39
+ const isThinking = message.status === 'thinking';
40
+ const isStreaming = message.status === 'streaming';
41
+ const hasReasoning = !!message.reasoning;
42
+ // 018:formSubmit 伪工具 prod 过滤不变;dev 放行(防御性——若事件到达则可见)
43
+ const visibleToolCalls = useMemo(
44
+ () => (message.toolCalls || []).filter((tc) => toolDebug || tc.name !== '__a2uiFormSubmit'),
45
+ [message.toolCalls, toolDebug],
46
+ );
47
+ const hasToolCalls = visibleToolCalls.length > 0;
48
+
49
+ const filterInlineCards = useInlineCardFilter();
50
+ const messageCards = useMemo(
51
+ () => (isUser ? [] : filterInlineCards(cardsByMessageId[message.id] || [])),
52
+ [cardsByMessageId, message.id, isUser, filterInlineCards],
53
+ );
54
+ const imageItems = isUser
55
+ ? message.mediaItems?.filter((i) => i.type === 'image' && (i.src || i.fileId))
56
+ : undefined;
57
+
58
+ const isPureThinking = isThinking && !hasReasoning && !message.content && !hasToolCalls;
59
+ const isReasoningActive = isThinking || (isStreaming && !message.content);
60
+ const showBubble = isUser || !!message.content || !!message.error || isStreaming;
61
+
62
+ const copy = async () => {
63
+ const copied = await copyText(message.content);
64
+ void toast(copied ? '复制成功' : '复制失败,请重试', copied ? 'success' : 'error');
65
+ };
66
+
67
+ const imageUrls = (imageItems || []).map((it) => it.src || `${TBOX_FILE_URL}${it.fileId}`);
68
+
69
+ // 登录入口由页面级半屏浮层承载;仅含登录卡的空 assistant 行不进入聊天流。
70
+ if (!isUser && !isPureThinking && !hasReasoning && !hasToolCalls && !showBubble && messageCards.length === 0) {
71
+ return null;
72
+ }
73
+
74
+ return (
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
+ >
80
+ <div className={isUser ? 'msg-main min-w-0' : 'msg-main min-w-0 flex-1'}>
81
+ <div
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]'}`}
83
+ >
84
+ <span className="msg-meta__role mr-1 text-xs leading-[normal] text-secondary-foreground">{roleName}</span>
85
+ <span className="msg-meta__time text-xs leading-[normal] text-muted-foreground">{timeLabel}</span>
86
+ </div>
87
+
88
+ {isPureThinking && (
89
+ <div className="msg-thinking ml-1.5 flex items-center justify-start gap-1 py-[5px]">
90
+ <div className="msg-thinking__dot h-[5px] w-[5px] animate-[dot-fade_1.4s_ease-in-out_infinite] rounded-full bg-[#aab3c2]" />
91
+ <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]" />
92
+ <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]" />
93
+ </div>
94
+ )}
95
+
96
+ {hasReasoning && <ReasoningBlock reasoning={message.reasoning!} isActive={isReasoningActive} />}
97
+
98
+ {hasToolCalls && <ToolCallBlock toolCalls={visibleToolCalls} debug={toolDebug} />}
99
+
100
+ {isThinking && hasToolCalls && !message.content && (
101
+ <div className="msg-thinking-inline ml-1.5 flex items-center justify-start gap-1 py-[5px]">
102
+ <div className="msg-thinking-inline__dot h-[5px] w-[5px] animate-[dot-fade_1.4s_ease-in-out_infinite] rounded-full bg-[#aab3c2]" />
103
+ <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]" />
104
+ <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]" />
105
+ </div>
106
+ )}
107
+
108
+ {showBubble && (
109
+ <div
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)]'}`}
111
+ >
112
+ {isUser ? (
113
+ <span className="msg-bubble__text text-base leading-[1.6] font-medium text-foreground [overflow-wrap:break-word]">{message.content}</span>
114
+ ) : (
115
+ <>
116
+ {message.content && (
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]">
118
+ <ReactMarkdown remarkPlugins={[remarkGfm]}>{message.content}</ReactMarkdown>
119
+ </div>
120
+ )}
121
+ {message.error && (
122
+ <div
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]' : ''}`}
124
+ role="alert"
125
+ >
126
+ {message.error}
127
+ </div>
128
+ )}
129
+ {isStreaming && <span className="msg-cursor ml-0.5 inline-block h-3 w-[2px] animate-[blink_1s_step-end_infinite] align-middle bg-[#5874ff]" />}
130
+ </>
131
+ )}
132
+ </div>
133
+ )}
134
+
135
+ {/* 卡片在对话气泡之后显示(决策出卡多张/意图卡/历史卡统一经 cardsByMessageId 挂载,多卡纵向铺开) */}
136
+ <CardCarousel
137
+ className="msg-cards mt-1"
138
+ cards={messageCards}
139
+ renderItem={(card) => <CardRenderer key={card.id} card={card} />}
140
+ />
141
+
142
+ {imageItems && imageItems.length > 0 && (
143
+ <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">
144
+ {imageItems.map((item, idx) => (
145
+ <img
146
+ key={item.id}
147
+ 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]"
148
+ src={item.src || `${TBOX_FILE_URL}${item.fileId}`}
149
+ alt=""
150
+ onClick={() => previewImages(imageUrls, idx)}
151
+ />
152
+ ))}
153
+ </div>
154
+ )}
155
+
156
+ {isUser && !!message.content && (
157
+ <div className="msg-toolbar msg-toolbar--user mt-1 flex items-center justify-end pr-1.5 opacity-40">
158
+ <div className="msg-toolbar__action flex h-[14px] w-[17px] items-center justify-center" onClick={copy}>
159
+ <Copy size={12} color="#535b6c" />
160
+ </div>
161
+ </div>
162
+ )}
163
+
164
+ {!isUser && message.status === 'done' && !!message.content && (
165
+ <div className="msg-toolbar-row flex flex-wrap items-center gap-1.5">
166
+ <ActionBar message={message} />
167
+ </div>
168
+ )}
169
+
170
+ {/* 出错消息不提供朗读/反馈;支持重试(重发上一条用户消息)、复制错误详情与拉 trace 排查。 */}
171
+ {!isUser && message.status === 'error' && (
172
+ <div className="msg-toolbar-row flex flex-wrap items-center gap-1.5">
173
+ <div className="tbox-action-bar">
174
+ {retryOnError ? (
175
+ <button
176
+ type="button"
177
+ 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"
178
+ disabled={generating}
179
+ onClick={() => {
180
+ const index = messages.findIndex((item) => item.id === message.id);
181
+ const scope = index >= 0 ? messages.slice(0, index) : messages;
182
+ const lastUser = [...scope].reverse().find((item) => item.role === 'user');
183
+ if (!lastUser?.content) {
184
+ void toast('没有可重发的消息', 'info');
185
+ return;
186
+ }
187
+ sendMessage(lastUser.content);
188
+ }}
189
+ >
190
+ 重试
191
+ </button>
192
+ ) : null}
193
+ <CopyButton text={getMessageCopyText(message)} />
194
+ {message.requestId && (
195
+ <DebugButton
196
+ requestId={message.requestId}
197
+ conversationId={message.conversationId}
198
+ messageId={message.id}
199
+ messageCreatedAt={new Date(message.createdAt).getTime()}
200
+ />
201
+ )}
202
+ </div>
203
+ </div>
204
+ )}
205
+ </div>
206
+ </div>
207
+ );
208
+ }
@@ -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,101 @@
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
+ // 图标走 CSS mask + currentColor(换品牌色不再残留固定蓝),断言 mask 的图片地址。
80
+ const iconUrl = buttons[1]?.querySelector<HTMLElement>('.quick-commands__icon')?.getAttribute('data-icon') ?? '';
81
+ expect(iconUrl).toContain('6-OCR5kWFa');
82
+ flushSync(() => buttons[1]!.click());
83
+ expect(onCommand).toHaveBeenCalledWith('服务端品牌导览');
84
+ });
85
+
86
+ it('隐藏时保留胶囊容器,但禁止交互', () => {
87
+ const onCommand = vi.fn();
88
+ const container = document.createElement('div');
89
+ document.body.appendChild(container);
90
+ renderWithKit(container, <QuickCommands hidden onCommand={onCommand} />);
91
+
92
+ const commands = container.querySelector('.quick-commands');
93
+ const button = container.querySelector<HTMLButtonElement>('.quick-commands__item');
94
+ expect(commands).not.toBeNull();
95
+ expect(commands?.classList.contains('quick-commands--hidden')).toBe(true);
96
+ expect(commands?.getAttribute('aria-hidden')).toBe('true');
97
+ expect(button?.disabled).toBe(true);
98
+ flushSync(() => button?.click());
99
+ expect(onCommand).not.toHaveBeenCalled();
100
+ });
101
+ });
@@ -0,0 +1,75 @@
1
+ // 输入框上方的快捷指令;文案由 chatConfig 驱动,服务端下发不含 icon 时按 label 合并本地配置。
2
+ // 011 I2:服务端 HelloAck.chatConfig.quickCommands 优先(单一真源),本地 chat.json 为 fallback。
3
+ // label 只写纯文字;前面的星标由本组件渲染(icon 字段或默认 ✦),不要把 ✦/emoji 写进 label。
4
+ //
5
+ // 两种排布:空会话用 grid(两列、全可见、每个 44px 命中区),对话态用 row(底部单行、可横滚)。
6
+ // 颜色只用语义令牌:换品牌色后不残留固定蓝。
7
+ import { useChatConfigStore } from '../../chat-config';
8
+ import { useChatStore } from '../../store-context';
9
+ import starIcon from '../../../assets/quick-command-star.svg';
10
+
11
+ export function QuickCommands({
12
+ onCommand,
13
+ hidden = false,
14
+ variant = 'row',
15
+ }: {
16
+ onCommand: (query: string) => void;
17
+ hidden?: boolean;
18
+ variant?: 'row' | 'grid';
19
+ }) {
20
+ const staticCommands = useChatConfigStore((s) => s.quickCommands);
21
+ // chatConfig 可选链:旧 server 的 HELLO_ACK 可能不带该段(与「ack 缺席回落静态」同语义)
22
+ const serverCommands = useChatStore((s) => s.helloAck?.chatConfig?.quickCommands);
23
+ // 服务端下发优先;未收到 HELLO_ACK(非 mall 部署)回落本地静态
24
+ const staticByLabel = new Map(staticCommands.map((command) => [command.label, command]));
25
+ const commands = serverCommands && serverCommands.length > 0
26
+ ? serverCommands.map((command) => ({
27
+ label: command.label,
28
+ query: command.prompt,
29
+ icon: staticByLabel.get(command.label)?.icon,
30
+ }))
31
+ : staticCommands;
32
+ if (!commands.length) return null;
33
+
34
+ const grid = variant === 'grid';
35
+ return (
36
+ <div
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
+ }
42
+ aria-hidden={hidden || undefined}
43
+ >
44
+ {commands.map((cmd) => (
45
+ <button
46
+ key={cmd.label}
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
+ }
52
+ disabled={hidden}
53
+ onClick={() => onCommand(cmd.query)}
54
+ >
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
+ }}
69
+ />
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>
71
+ </button>
72
+ ))}
73
+ </div>
74
+ );
75
+ }
@@ -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,12 @@
1
+ /** 生成时出现的“回到底部”悬浮按钮。 */
2
+ export default function ScrollToBottomButton({ visible, onClick }: { visible: boolean; onClick: () => void }) {
3
+ return (
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>
11
+ );
12
+ }