@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,86 @@
1
+ /**
2
+ * 卡片内交互:把「点按钮之后发生什么」收敛成两种意图,避免每张卡重写门控。
3
+ *
4
+ * - `send`:把一句话作为用户消息发回,走模型(信息不足、需要模型再判断时用);
5
+ * - `invoke`:触发卡片上声明的确定性动作(moduleAction),不过模型;
6
+ * - `disabled`:历史卡片与生成中一律禁用,两者文案不同——历史卡只读,生成中提示等待。
7
+ *
8
+ * 门控与 toast 文案集中在实现处;卡片组件只消费 `disabled` 与两个动作函数。
9
+ */
10
+ import { useCallback } from 'react';
11
+ import { toast } from '../utils/toast';
12
+ import { useChatStore } from '../store-context';
13
+
14
+ export interface UseCardActionsOptions {
15
+ /** 卡片实例 id(协议字段名 surfaceId 的历史别名) */
16
+ cardId: string;
17
+ /** 历史消息里的卡片:只读 */
18
+ isHistory?: boolean;
19
+ /** 卡片携带的动作令牌(`payload.actionTokens`,仅 moduleAction 有) */
20
+ actionTokens?: Record<string, string>;
21
+ }
22
+
23
+ export interface CardActions {
24
+ /** 发一句话给模型;`displayText` 是气泡展示文本,缺省同 `text` */
25
+ send(text: string, opts?: { displayText?: string }): void;
26
+ /**
27
+ * 触发卡片上的确定性动作(需该动作已签发令牌)。
28
+ * `input` 作为该次调用的入参(UI_ACTION 的 formData 通道),由服务端 `inputSchema` 校验;
29
+ * 不传时按空对象校验——无参动作写 `z.object({})`。
30
+ */
31
+ invoke(actionId: string, input?: Record<string, unknown>): void;
32
+ /** 历史卡或生成中为 true——按钮应据此置灰 */
33
+ disabled: boolean;
34
+ isHistory: boolean;
35
+ isGenerating: boolean;
36
+ }
37
+
38
+ export function useCardActions(opts: UseCardActionsOptions): CardActions {
39
+ const sendUiAction = useChatStore((s) => s.sendUiAction);
40
+ const isGenerating = useChatStore((s) => s.isGenerating);
41
+ const isHistory = opts.isHistory === true;
42
+ const disabled = isHistory || isGenerating;
43
+
44
+ const send = useCallback(
45
+ (text: string, o?: { displayText?: string }) => {
46
+ if (!text) return;
47
+ if (isHistory) {
48
+ void toast('历史卡片仅供查看', 'info');
49
+ return;
50
+ }
51
+ if (isGenerating) {
52
+ void toast('正在处理上一条消息,请稍候', 'info');
53
+ return;
54
+ }
55
+ sendUiAction(opts.cardId, {
56
+ type: 'sendMessage',
57
+ value: text,
58
+ displayText: o?.displayText ?? text,
59
+ visible: true,
60
+ });
61
+ },
62
+ [opts.cardId, isHistory, isGenerating, sendUiAction],
63
+ );
64
+
65
+ const invoke = useCallback(
66
+ (actionId: string, input?: Record<string, unknown>) => {
67
+ if (isHistory) {
68
+ void toast('历史卡片仅供查看', 'info');
69
+ return;
70
+ }
71
+ if (isGenerating) {
72
+ void toast('正在处理上一条消息,请稍候', 'info');
73
+ return;
74
+ }
75
+ const contextToken = opts.actionTokens?.[actionId];
76
+ if (!contextToken) {
77
+ void toast('该操作不可用', 'info');
78
+ return;
79
+ }
80
+ sendUiAction(opts.cardId, { type: 'moduleAction', actionId, contextToken }, input);
81
+ },
82
+ [opts.cardId, opts.actionTokens, isHistory, isGenerating, sendUiAction],
83
+ );
84
+
85
+ return { send, invoke, disabled, isHistory, isGenerating };
86
+ }
@@ -0,0 +1,46 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { configureChatConfigDefaults, useChatConfigStore } from './chat-config';
3
+
4
+ const reset = () => {
5
+ configureChatConfigDefaults({
6
+ enableImageUpload: true,
7
+ enableVideoUpload: true,
8
+ enableTTS: true,
9
+ enableVoiceInput: true,
10
+ defaultInputMode: 'TEXT',
11
+ quickCommands: [],
12
+ retryOnError: true,
13
+ });
14
+ useChatConfigStore.setState({ identity: undefined, welcome: undefined });
15
+ };
16
+
17
+ describe('chat 设置的构建期快照', () => {
18
+ it('identity / welcome / retryOnError 随快照注入', () => {
19
+ reset();
20
+ configureChatConfigDefaults({
21
+ identity: { name: '悦享里', tagline: '商圈智能助手' },
22
+ welcome: { title: '今天想逛点什么?', subtitle: '会员、停车、优惠都能问我' },
23
+ retryOnError: false,
24
+ });
25
+ const state = useChatConfigStore.getState();
26
+ expect(state.identity?.name).toBe('悦享里');
27
+ expect(state.welcome?.title).toBe('今天想逛点什么?');
28
+ expect(state.retryOnError).toBe(false);
29
+ });
30
+
31
+ it('缺省 retryOnError 为 true,identity 缺省不渲染', () => {
32
+ reset();
33
+ const state = useChatConfigStore.getState();
34
+ expect(state.retryOnError).toBe(true);
35
+ expect(state.identity).toBeUndefined();
36
+ });
37
+
38
+ it('HELLO_ACK 水合不覆盖展示配置', () => {
39
+ reset();
40
+ configureChatConfigDefaults({ identity: { name: '悦享里' } });
41
+ useChatConfigStore.getState().applyServerSettings({ enableTTS: false } as never);
42
+ const state = useChatConfigStore.getState();
43
+ expect(state.enableTTS).toBe(false);
44
+ expect(state.identity?.name).toBe('悦享里');
45
+ });
46
+ });
@@ -0,0 +1,80 @@
1
+ /**
2
+ * chat 设置静态 store(自 mall 模板 store/chat-config.ts 迁入,单一模板统一化 W2-1)。
3
+ *
4
+ * - 构建期快照:应用 boot 时经 `configureChatConfigDefaults(chat.json 内容)` 注入
5
+ * (createRoot 前调用保证首帧即快照值;kit 不 import 应用 config 路径);
6
+ * - HELLO_ACK settings 水合:服务端单一真源(applyServerSettings;五键整组语义,禁部分水合)。
7
+ */
8
+ import { create } from 'zustand';
9
+ import type { ChatUiSettings } from '@tbox.cn/app-agent-sdk-client';
10
+
11
+ export interface QuickCommand {
12
+ /** 纯文案;前导星标/图标由 QuickCommands 组件渲染,不要写进 label */
13
+ label: string;
14
+ query: string;
15
+ icon?: string;
16
+ }
17
+
18
+ export interface ChatIdentity {
19
+ name: string;
20
+ tagline?: string;
21
+ }
22
+
23
+ export interface ChatWelcome {
24
+ title: string;
25
+ subtitle?: string;
26
+ }
27
+
28
+ interface ChatConfigStore {
29
+ enableImageUpload: boolean;
30
+ enableVideoUpload: boolean;
31
+ enableTTS: boolean;
32
+ enableVoiceInput: boolean;
33
+ defaultInputMode: 'TEXT' | 'VOICE';
34
+ quickCommands: QuickCommand[];
35
+ /** 身份与欢迎区是构建期展示配置,不经 HELLO_ACK 水合 */
36
+ identity?: ChatIdentity;
37
+ welcome?: ChatWelcome;
38
+ retryOnError: boolean;
39
+ /** HELLO_ACK settings 水合:服务端单一真源;undefined 键保留构建期快照(五键整组语义,禁部分水合) */
40
+ applyServerSettings: (settings: ChatUiSettings | undefined) => void;
41
+ }
42
+
43
+ export const useChatConfigStore = create<ChatConfigStore>()((set) => ({
44
+ // kit 内建缺省(应用快照经 configureChatConfigDefaults 覆盖)
45
+ enableImageUpload: true,
46
+ enableVideoUpload: true,
47
+ enableTTS: true,
48
+ enableVoiceInput: true,
49
+ defaultInputMode: 'TEXT',
50
+ quickCommands: [],
51
+ retryOnError: true,
52
+ applyServerSettings: (settings) =>
53
+ set((cur) => ({
54
+ enableImageUpload: settings?.enableImageUpload ?? cur.enableImageUpload,
55
+ enableVideoUpload: settings?.enableVideoUpload ?? cur.enableVideoUpload,
56
+ enableTTS: settings?.enableTTS ?? cur.enableTTS,
57
+ enableVoiceInput: settings?.enableVoiceInput ?? cur.enableVoiceInput,
58
+ defaultInputMode: settings?.defaultInputMode ?? cur.defaultInputMode,
59
+ })),
60
+ }));
61
+
62
+ /**
63
+ * 构建期快照注入(应用 boot 时调用一次;createRoot 前调用保证首帧即快照值)。
64
+ * 键缺席保留内建缺省;键在场以快照为准。
65
+ */
66
+ export function configureChatConfigDefaults(snapshot: Record<string, unknown> | undefined): void {
67
+ if (!snapshot) return;
68
+ useChatConfigStore.setState((cur) => ({
69
+ enableImageUpload: (snapshot['enableImageUpload'] as boolean | undefined) ?? cur.enableImageUpload,
70
+ enableVideoUpload: (snapshot['enableVideoUpload'] as boolean | undefined) ?? cur.enableVideoUpload,
71
+ enableTTS: (snapshot['enableTTS'] as boolean | undefined) ?? cur.enableTTS,
72
+ enableVoiceInput: (snapshot['enableVoiceInput'] as boolean | undefined) ?? cur.enableVoiceInput,
73
+ defaultInputMode:
74
+ (snapshot['defaultInputMode'] as 'TEXT' | 'VOICE' | undefined) ?? cur.defaultInputMode,
75
+ quickCommands: (snapshot['quickCommands'] as QuickCommand[] | undefined) ?? cur.quickCommands,
76
+ identity: (snapshot['identity'] as ChatIdentity | undefined) ?? cur.identity,
77
+ welcome: (snapshot['welcome'] as ChatWelcome | undefined) ?? cur.welcome,
78
+ retryOnError: (snapshot['retryOnError'] as boolean | undefined) ?? cur.retryOnError,
79
+ }));
80
+ }
@@ -0,0 +1,84 @@
1
+ // @vitest-environment happy-dom
2
+ /**
3
+ * DebugButton postMessage 载荷契约锁(P0 对齐 trace-exporter 行格式锁定先例):
4
+ * 载荷形状是 H5 → 平台父窗口的跨系统契约——键名漂移 = 平台侧静默断裂。
5
+ * conversationId 语义:会话 β 后由服务端经 run 事件 threadId / 历史行下发,
6
+ * 与 requestId 同点位落位至 message;D2 锁定「缺席 = 键值 undefined 仍发送」
7
+ * 现状降级形态(平台侧 no-conv 回退依赖此形态)。
8
+ */
9
+ import { act } from 'react';
10
+ import { createRoot } from 'react-dom/client';
11
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
12
+
13
+ vi.mock('@tbox.cn/app-agent-sdk-client', () => ({
14
+ createLogger: () => ({ warn: vi.fn() }),
15
+ }));
16
+
17
+ import { DebugButton } from './DebugButton';
18
+
19
+ describe('DebugButton 平台契约(tbox:debug-trace 载荷锁定)', () => {
20
+ let host: HTMLDivElement;
21
+ let root: ReturnType<typeof createRoot>;
22
+ let postSpy: ReturnType<typeof vi.fn>;
23
+
24
+ beforeEach(() => {
25
+ host = document.createElement('div');
26
+ document.body.appendChild(host);
27
+ root = createRoot(host);
28
+ // happy-dom 下 window.parent === window:同一函数引用
29
+ postSpy = vi.fn();
30
+ window.parent.postMessage = postSpy as unknown as typeof window.postMessage;
31
+ });
32
+
33
+ afterEach(() => {
34
+ act(() => root.unmount());
35
+ host.remove();
36
+ });
37
+
38
+ const clickDebug = () => {
39
+ act(() => {
40
+ host.querySelector('.tbox-debug-btn')!.dispatchEvent(new MouseEvent('click', { bubbles: true }));
41
+ });
42
+ };
43
+
44
+ it('D1 点击 → 载荷全键精确(type/requestId/conversationId/messageId/messageCreatedAt)', () => {
45
+ act(() => {
46
+ root.render(<DebugButton requestId="req_1" conversationId="conv_1" messageId="m1" messageCreatedAt={123} />);
47
+ });
48
+ clickDebug();
49
+ expect(postSpy).toHaveBeenCalledTimes(1);
50
+ expect(postSpy.mock.calls[0]![0]).toEqual({
51
+ type: 'tbox:debug-trace',
52
+ requestId: 'req_1',
53
+ conversationId: 'conv_1',
54
+ messageId: 'm1',
55
+ messageCreatedAt: 123,
56
+ });
57
+ expect(postSpy.mock.calls[0]![1]).toBe('*');
58
+ });
59
+
60
+ it('D2 conversationId 缺席 → 载荷键恒在场、值为 undefined(现状降级形态锁定)', () => {
61
+ act(() => {
62
+ root.render(<DebugButton requestId="req_1" messageId="m2" messageCreatedAt={456} />);
63
+ });
64
+ clickDebug();
65
+ const payload = postSpy.mock.calls[0]![0] as Record<string, unknown>;
66
+ // 键恒在场(严格区分键存在性——toEqual 对 undefined 键与缺失等价,故断言键集)
67
+ expect(Object.keys(payload).sort()).toEqual([
68
+ 'conversationId',
69
+ 'messageCreatedAt',
70
+ 'messageId',
71
+ 'requestId',
72
+ 'type',
73
+ ]);
74
+ expect(payload.conversationId).toBeUndefined();
75
+ expect(payload.requestId).toBe('req_1');
76
+ });
77
+
78
+ it('D3 requestId 缺席 → 不渲染(渲染守卫不变)', () => {
79
+ act(() => {
80
+ root.render(<DebugButton messageId="m3" />);
81
+ });
82
+ expect(host.querySelector('.tbox-debug-btn')).toBeNull();
83
+ });
84
+ });
@@ -0,0 +1,53 @@
1
+ import { createLogger } from '@tbox.cn/app-agent-sdk-client';
2
+
3
+ const debugLogger = createLogger('DebugButton');
4
+
5
+ import { Bug } from '@phosphor-icons/react';
6
+
7
+ /**
8
+ * 调试按钮:点击把本轮 requestId / conversationId / messageId / messageCreatedAt
9
+ * 通过 postMessage 发给父窗口,平台据此构造日志时间窗、拉取 trace 日志。
10
+ * 显示条件:dev / URL 带 ?debug=1 / 被 iframe 嵌入。
11
+ */
12
+ function shouldShow(): boolean {
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
+ }
21
+ }
22
+
23
+ export function DebugButton({
24
+ requestId,
25
+ conversationId,
26
+ messageId,
27
+ messageCreatedAt,
28
+ }: {
29
+ requestId?: string;
30
+ conversationId?: string;
31
+ messageId?: string;
32
+ messageCreatedAt?: number;
33
+ }) {
34
+ if (!shouldShow() || !requestId) return null;
35
+
36
+ const onClick = () => {
37
+ try {
38
+ window.parent.postMessage(
39
+ { type: 'tbox:debug-trace', requestId, conversationId, messageId, messageCreatedAt },
40
+ '*',
41
+ );
42
+ } catch (err) {
43
+ debugLogger.warn('postMessage failed:', err);
44
+ }
45
+ };
46
+
47
+ return (
48
+ <div className="tbox-debug-btn inline-flex h-[26px] items-center justify-center gap-1 rounded-full bg-white px-[11px] text-secondary-foreground transition-[background-color,transform] duration-[var(--tbox-motion-duration-fast)] ease-[ease] active:scale-[0.97] active:bg-muted" onClick={onClick}>
49
+ <Bug className="tbox-debug-btn__icon size-[14px] shrink-0" size={22} />
50
+ <span className="tbox-debug-btn__text text-xs leading-none">调试</span>
51
+ </div>
52
+ );
53
+ }
@@ -0,0 +1,83 @@
1
+ // @vitest-environment happy-dom
2
+ /**
3
+ * ActionBar → DebugButton prop 接线守卫(病因学守卫):
4
+ * 会话 β(31de86f3)删除 conversationId prop 行零红灯复发——本测试锁定
5
+ * message.requestId/conversationId 恒透传至 DebugButton(删除任一 prop 行 → 红)。
6
+ * 捕获式 mock(MessageBubble 测试同款模式)。
7
+ */
8
+ import { act } from 'react';
9
+ import { createRoot } from 'react-dom/client';
10
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
11
+ import type { ChatMessage } from '../../types';
12
+
13
+ const { debugPropsRef } = vi.hoisted(() => ({
14
+ debugPropsRef: {} as { current?: Record<string, unknown> },
15
+ }));
16
+
17
+ vi.mock('./DebugButton', () => ({
18
+ DebugButton: (props: Record<string, unknown>) => {
19
+ debugPropsRef.current = props;
20
+ return null;
21
+ },
22
+ }));
23
+ vi.mock('../../store-context', () => ({
24
+ useChatStore: (selector: (s: Record<string, unknown>) => unknown) =>
25
+ selector({ submitFeedback: vi.fn() }),
26
+ }));
27
+ vi.mock('../../chat-config', () => ({
28
+ useChatConfigStore: (selector: (s: Record<string, unknown>) => unknown) => selector({ enableTTS: false }),
29
+ }));
30
+ vi.mock('@tbox.cn/app-agent-sdk-client', () => ({
31
+ createLogger: () => ({ warn: vi.fn() }),
32
+ useFeedbackAdapter: () => undefined,
33
+ useRefreshSession: () => undefined,
34
+ useTTSAdapter: () => undefined,
35
+ }));
36
+ vi.mock('../../utils/copyText', () => ({ copyText: vi.fn(async () => true) }));
37
+ vi.mock('../../utils/toast', () => ({ toast: vi.fn() }));
38
+
39
+ import { ActionBar } from './index';
40
+
41
+ const doneMessage = (over: Partial<ChatMessage> = {}): ChatMessage => ({
42
+ id: 'm1',
43
+ role: 'assistant',
44
+ content: '答案',
45
+ status: 'done',
46
+ createdAt: 1,
47
+ ...over,
48
+ });
49
+
50
+ describe('ActionBar → DebugButton 接线(病因学守卫)', () => {
51
+ let host: HTMLDivElement;
52
+ let root: ReturnType<typeof createRoot>;
53
+
54
+ beforeEach(() => {
55
+ host = document.createElement('div');
56
+ document.body.appendChild(host);
57
+ root = createRoot(host);
58
+ debugPropsRef.current = undefined;
59
+ });
60
+
61
+ afterEach(() => {
62
+ act(() => root.unmount());
63
+ host.remove();
64
+ });
65
+
66
+ it('A1 done 消息:requestId + conversationId 均透传(删除任一 prop 行 → 红)', () => {
67
+ act(() => {
68
+ root.render(<ActionBar message={doneMessage({ requestId: 'req_1', conversationId: 'conv_1' })} />);
69
+ });
70
+ expect(debugPropsRef.current).toMatchObject({
71
+ requestId: 'req_1',
72
+ conversationId: 'conv_1',
73
+ messageId: 'm1',
74
+ });
75
+ });
76
+
77
+ it('A2 字段缺席:prop 透传 undefined(不抛错、按钮层自守卫)', () => {
78
+ act(() => {
79
+ root.render(<ActionBar message={doneMessage({ requestId: 'req_1' })} />);
80
+ });
81
+ expect(debugPropsRef.current).toMatchObject({ requestId: 'req_1', conversationId: undefined });
82
+ });
83
+ });
@@ -0,0 +1,158 @@
1
+ import { useEffect, useState, useSyncExternalStore } from 'react';
2
+ import { createLogger } from '@tbox.cn/app-agent-sdk-client';
3
+
4
+ const ttsActionLogger = createLogger('tts');
5
+ import { Copy, SpeakerHigh, ThumbsDown, ThumbsUp } from '@phosphor-icons/react';
6
+ import { useChatStore } from '../../store-context';
7
+ import { useChatConfigStore } from '../../chat-config';
8
+ import { useFeedbackAdapter, useRefreshSession, useTTSAdapter } from '@tbox.cn/app-agent-sdk-client';
9
+ import type { ChatMessage } from '../../types';
10
+ import { copyText } from '../../utils/copyText';
11
+ import { toast } from '../../utils/toast';
12
+ import { DebugButton } from './DebugButton';
13
+
14
+ /**
15
+ * 跨所有 ActionBar 实例共享的"正在朗读的消息 id"(对齐原模板 useTTS 的 _playingId)。
16
+ * 保证同一时刻只有发起朗读的那条消息按钮显示波纹/暂停态,切到另一条会自动复位前一条。
17
+ */
18
+ let _playingId: string | null = null;
19
+ const _playingIdListeners = new Set<() => void>();
20
+ const getPlayingId = () => _playingId;
21
+ function subscribePlayingId(cb: () => void) {
22
+ _playingIdListeners.add(cb);
23
+ return () => {
24
+ _playingIdListeners.delete(cb);
25
+ };
26
+ }
27
+ function setPlayingId(id: string | null) {
28
+ if (_playingId === id) return;
29
+ _playingId = id;
30
+ _playingIdListeners.forEach((cb) => cb());
31
+ }
32
+ /** play() 同步执行期间为 true,防止切歌瞬间 adapter 的 idle 事件误清 playingId */
33
+ let _isPlaying = false;
34
+
35
+ /** 助手消息操作栏(对齐原模板):朗读(TTS) + 复制 + 赞 + 踩。 */
36
+ export function getMessageCopyText(message: ChatMessage): string {
37
+ return [message.content, message.error].filter(Boolean).join('\n\n');
38
+ }
39
+
40
+ export function CopyButton({ text }: { text: string }) {
41
+ const copy = async () => {
42
+ const copied = await copyText(text);
43
+ void toast(copied ? '复制成功' : '复制失败,请重试', copied ? 'success' : 'error');
44
+ };
45
+
46
+ return (
47
+ <button type="button" className="tbox-action-btn flex size-[26px] shrink-0 cursor-pointer items-center justify-center rounded-full border-0 bg-white p-0 text-muted-foreground transition-[background-color,transform] duration-[var(--tbox-motion-duration-fast)] ease-[ease] [font-family:inherit] active:scale-[0.97] active:bg-muted" onClick={copy} aria-label="复制">
48
+ <span className="tbox-action-btn__icon-wrap flex size-[14px] shrink-0 items-center justify-center">
49
+ <Copy size={22} />
50
+ </span>
51
+ </button>
52
+ );
53
+ }
54
+
55
+ export function ActionBar({ message }: { message: ChatMessage }) {
56
+ const feedback = useFeedbackAdapter();
57
+ const refreshSession = useRefreshSession();
58
+ const tts = useTTSAdapter();
59
+ const enableTTS = useChatConfigStore((s) => s.enableTTS);
60
+ const submitFeedback = useChatStore((s) => s.submitFeedback);
61
+
62
+ const [ttsState, setTtsState] = useState<'idle' | 'loading' | 'playing' | 'paused'>('idle');
63
+ // 是否轮到本条消息:由共享 playingId 决定(而非各自的本地 state),实现跨实例互斥高亮
64
+ const playingId = useSyncExternalStore(subscribePlayingId, getPlayingId);
65
+ const isMine = playingId === message.id;
66
+ useEffect(() => {
67
+ if (!tts) return;
68
+ return (
69
+ tts.onStateChange((s) => {
70
+ setTtsState(s);
71
+ // 播放自然结束 → 清空全局播放态;_isPlaying 守卫避免切歌瞬间的 idle 误清
72
+ if (s === 'idle' && !_isPlaying) setPlayingId(null);
73
+ }) || undefined
74
+ );
75
+ }, [tts]);
76
+
77
+ const onFeedback = (type: 'like' | 'dislike') => {
78
+ if (!feedback) return;
79
+ const next = message.feedbackState === type ? 'cancel' : type;
80
+ submitFeedback(message.id, next, feedback, refreshSession);
81
+ };
82
+
83
+ const wave = isMine && (ttsState === 'loading' || ttsState === 'playing');
84
+ // 对齐原模板 TTSButton:播放/加载中点击→暂停;暂停中点击→恢复;其余→从头播放
85
+ const onTts = () => {
86
+ if (!tts) return;
87
+ if (isMine) {
88
+ if (ttsState === 'playing' || ttsState === 'loading') {
89
+ tts.pause();
90
+ return;
91
+ }
92
+ if (ttsState === 'paused') {
93
+ tts.resume();
94
+ return;
95
+ }
96
+ }
97
+ _isPlaying = true;
98
+ setPlayingId(message.id);
99
+ tts.speak(message.content, message.id).catch((err: unknown) => {
100
+ ttsActionLogger.warn(`tts.speak 失败:err=${(err as Error)?.message ?? String(err)}`);
101
+ setPlayingId(null);
102
+ });
103
+ _isPlaying = false;
104
+ };
105
+
106
+ // 显示依据 requestId(server 下发、不依赖 session);提交时若无 feedback 适配器则 onFeedback 内部 no-op
107
+ const canFeedback = !!message.requestId;
108
+
109
+ return (
110
+ <div className="tbox-action-bar flex items-center gap-2">
111
+ {enableTTS && tts && (
112
+ <div className={`tbox-action-btn flex size-[26px] shrink-0 cursor-pointer items-center justify-center rounded-full border-0 p-0 transition-[background-color,transform] duration-[var(--tbox-motion-duration-fast)] ease-[ease] [font-family:inherit] active:scale-[0.97] active:bg-muted ${wave ? ' tbox-tts-btn--playing bg-primary-foreground text-primary' : ' bg-white text-muted-foreground'}`} onClick={onTts}>
113
+ {wave ? (
114
+ <div className="tbox-tts-wave flex size-[14px] items-center justify-center gap-[1.5px]">
115
+ <div className="tbox-tts-wave__bar tbox-tts-wave__bar--1 h-[7px] w-[1.5px] origin-bottom rounded-full bg-primary animate-[tbox-tts-wave_0.8s_ease-in-out_infinite] [animation-delay:0s]" />
116
+ <div className="tbox-tts-wave__bar tbox-tts-wave__bar--2 h-[9px] w-[1.5px] origin-bottom rounded-full bg-primary animate-[tbox-tts-wave_0.8s_ease-in-out_infinite] [animation-delay:0.15s]" />
117
+ <div className="tbox-tts-wave__bar tbox-tts-wave__bar--3 h-[6px] w-[1.5px] origin-bottom rounded-full bg-primary animate-[tbox-tts-wave_0.8s_ease-in-out_infinite] [animation-delay:0.3s]" />
118
+ </div>
119
+ ) : (
120
+ <div className="tbox-action-btn__icon-wrap flex size-[14px] shrink-0 items-center justify-center">
121
+ <SpeakerHigh size={22} />
122
+ </div>
123
+ )}
124
+ </div>
125
+ )}
126
+
127
+ <CopyButton text={getMessageCopyText(message)} />
128
+
129
+ {canFeedback && (
130
+ <>
131
+ <div
132
+ className={`tbox-action-btn flex size-[26px] shrink-0 cursor-pointer items-center justify-center rounded-full border-0 p-0 transition-[background-color,transform] duration-[var(--tbox-motion-duration-fast)] ease-[ease] [font-family:inherit] active:scale-[0.97] active:bg-muted ${message.feedbackState === 'like' ? ' tbox-action-btn--active bg-primary-foreground text-primary' : ' bg-white text-muted-foreground'}`}
133
+ onClick={() => onFeedback('like')}
134
+ >
135
+ <div className="tbox-action-btn__icon-wrap flex size-[14px] shrink-0 items-center justify-center">
136
+ <ThumbsUp size={22} />
137
+ </div>
138
+ </div>
139
+ <div
140
+ className={`tbox-action-btn flex size-[26px] shrink-0 cursor-pointer items-center justify-center rounded-full border-0 p-0 transition-[background-color,transform] duration-[var(--tbox-motion-duration-fast)] ease-[ease] [font-family:inherit] active:scale-[0.97] active:bg-muted ${message.feedbackState === 'dislike' ? ' tbox-action-btn--active bg-primary-foreground text-primary' : ' bg-white text-muted-foreground'}`}
141
+ onClick={() => onFeedback('dislike')}
142
+ >
143
+ <div className="tbox-action-btn__icon-wrap flex size-[14px] shrink-0 items-center justify-center">
144
+ <ThumbsDown size={22} />
145
+ </div>
146
+ </div>
147
+ </>
148
+ )}
149
+
150
+ <DebugButton
151
+ requestId={message.requestId}
152
+ conversationId={message.conversationId}
153
+ messageId={message.id}
154
+ messageCreatedAt={new Date(message.createdAt).getTime()}
155
+ />
156
+ </div>
157
+ );
158
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * 卡片渲染入口(kit 版,自 mall 模板 cards/CardRenderer.tsx 迁入):
3
+ * 注入 context 提供的注册表后委托 SDK 的 CardRenderer;
4
+ * 动作按钮 → 注入 store 的 sendUiAction(token 来自 payload.actionTokens)。
5
+ *
6
+ * - CardRenderer:聊天入口(组合层覆盖注册表 cards);
7
+ * - RawCardRenderer:原始形态(rawCards,无覆盖)——首页详情弹层 body 等防嵌套入口。
8
+ */
9
+ import { CardRenderer as SdkCardRenderer } from '@tbox.cn/app-agent-sdk-client';
10
+ import type { TboxCardPayload, UiAction } from '@tbox.cn/app-contracts';
11
+ import { useChatCards, useChatRawCards, useChatStore } from '../store-context';
12
+
13
+ export function CardRenderer({ card }: { card: TboxCardPayload }) {
14
+ const sendUiAction = useChatStore((s) => s.sendUiAction);
15
+ const cards = useChatCards();
16
+ return (
17
+ <SdkCardRenderer
18
+ card={card}
19
+ registry={cards}
20
+ onAction={(action: UiAction) => sendUiAction(card.id, action)}
21
+ />
22
+ );
23
+ }
24
+
25
+ /** 原始形态渲染(无组合层覆盖):详情弹层 body 专用——弹层自身已提供 hero+主题容器 */
26
+ export function RawCardRenderer({ card }: { card: TboxCardPayload }) {
27
+ const sendUiAction = useChatStore((s) => s.sendUiAction);
28
+ const rawCards = useChatRawCards();
29
+ return (
30
+ <SdkCardRenderer
31
+ card={card}
32
+ registry={rawCards}
33
+ onAction={(action: UiAction) => sendUiAction(card.id, action)}
34
+ />
35
+ );
36
+ }