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

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 (79) 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 +55 -3
  11. package/src/ChatPage.less +62 -0
  12. package/src/ChatPage.tsx +305 -0
  13. package/src/chat-config.test.ts +82 -0
  14. package/src/chat-config.ts +62 -0
  15. package/src/components/ActionBar/DebugButton.test.tsx +84 -0
  16. package/src/components/ActionBar/DebugButton.tsx +53 -0
  17. package/src/components/ActionBar/index.less +123 -0
  18. package/src/components/ActionBar/index.test.tsx +83 -0
  19. package/src/components/ActionBar/index.tsx +159 -0
  20. package/src/components/CardRenderer.tsx +36 -0
  21. package/src/components/ChatHeader/index.less +148 -0
  22. package/src/components/ChatHeader/index.test.tsx +74 -0
  23. package/src/components/ChatHeader/index.tsx +75 -0
  24. package/src/components/ChatInput/index.less +394 -0
  25. package/src/components/ChatInput/index.test.tsx +156 -0
  26. package/src/components/ChatInput/index.tsx +284 -0
  27. package/src/components/ChatInput/voice/VoicePressField.tsx +34 -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.less +49 -0
  32. package/src/components/HistoryEntry/index.tsx +42 -0
  33. package/src/components/MediaList/index.less +241 -0
  34. package/src/components/MediaList/index.tsx +256 -0
  35. package/src/components/MessageBubble/index.less +325 -0
  36. package/src/components/MessageBubble/index.test.tsx +134 -0
  37. package/src/components/MessageBubble/index.tsx +177 -0
  38. package/src/components/PullDownIndicator/index.less +32 -0
  39. package/src/components/PullDownIndicator/index.tsx +32 -0
  40. package/src/components/QuickCommands/index.less +63 -0
  41. package/src/components/QuickCommands/index.test.tsx +99 -0
  42. package/src/components/QuickCommands/index.tsx +52 -0
  43. package/src/components/ReasoningBlock/index.less +90 -0
  44. package/src/components/ReasoningBlock/index.tsx +56 -0
  45. package/src/components/ScrollToBottomButton/index.less +32 -0
  46. package/src/components/ScrollToBottomButton/index.tsx +10 -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.less +312 -0
  50. package/src/components/ToolCallBlock/index.test.tsx +261 -0
  51. package/src/components/ToolCallBlock/index.tsx +212 -0
  52. package/src/components/ToolCallBlock/titles.ts +102 -0
  53. package/src/hooks/use-drag-gesture.test.ts +66 -0
  54. package/src/hooks/use-drag-gesture.ts +129 -0
  55. package/src/hooks/use-pull-down-history.ts +241 -0
  56. package/src/hooks/use-pull-down-wheel-native.test.ts +64 -0
  57. package/src/hooks/useMediaUpload.ts +242 -0
  58. package/src/hooks/useTTSAutoPlay.ts +82 -0
  59. package/src/index.ts +69 -0
  60. package/src/store-context.tsx +92 -0
  61. package/src/test/setup.ts +7 -0
  62. package/src/theme/contract.json +72 -0
  63. package/src/theme/global.less +99 -0
  64. package/src/theme/motion.less +19 -0
  65. package/src/theme/theme-contract.test.ts +69 -0
  66. package/src/theme/theme.ts +17 -0
  67. package/src/theme/tokens.less +79 -0
  68. package/src/types.ts +29 -0
  69. package/src/utils/copyText.ts +11 -0
  70. package/src/utils/haptics.test.ts +51 -0
  71. package/src/utils/haptics.ts +44 -0
  72. package/src/utils/imagePreview.ts +10 -0
  73. package/src/utils/pull-down-machine.test.ts +188 -0
  74. package/src/utils/pull-down-machine.ts +157 -0
  75. package/src/utils/session-error.ts +5 -0
  76. package/src/utils/toast.ts +15 -0
  77. package/src/utils/tool-call-display.test.ts +240 -0
  78. package/src/utils/tool-call-display.ts +146 -0
  79. package/src/vite-env.d.ts +1 -0
@@ -0,0 +1,62 @@
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
+ interface ChatConfigStore {
19
+ enableImageUpload: boolean;
20
+ enableVideoUpload: boolean;
21
+ enableTTS: boolean;
22
+ enableVoiceInput: boolean;
23
+ defaultInputMode: 'TEXT' | 'VOICE';
24
+ quickCommands: QuickCommand[];
25
+ /** HELLO_ACK settings 水合:服务端单一真源;undefined 键保留构建期快照(五键整组语义,禁部分水合) */
26
+ applyServerSettings: (settings: ChatUiSettings | undefined) => void;
27
+ }
28
+
29
+ export const useChatConfigStore = create<ChatConfigStore>()((set) => ({
30
+ // kit 内建缺省(应用快照经 configureChatConfigDefaults 覆盖)
31
+ enableImageUpload: true,
32
+ enableVideoUpload: true,
33
+ enableTTS: true,
34
+ enableVoiceInput: true,
35
+ defaultInputMode: 'TEXT',
36
+ quickCommands: [],
37
+ applyServerSettings: (settings) =>
38
+ set((cur) => ({
39
+ enableImageUpload: settings?.enableImageUpload ?? cur.enableImageUpload,
40
+ enableVideoUpload: settings?.enableVideoUpload ?? cur.enableVideoUpload,
41
+ enableTTS: settings?.enableTTS ?? cur.enableTTS,
42
+ enableVoiceInput: settings?.enableVoiceInput ?? cur.enableVoiceInput,
43
+ defaultInputMode: settings?.defaultInputMode ?? cur.defaultInputMode,
44
+ })),
45
+ }));
46
+
47
+ /**
48
+ * 构建期快照注入(应用 boot 时调用一次;createRoot 前调用保证首帧即快照值)。
49
+ * 键缺席保留内建缺省;键在场以快照为准。
50
+ */
51
+ export function configureChatConfigDefaults(snapshot: Record<string, unknown> | undefined): void {
52
+ if (!snapshot) return;
53
+ useChatConfigStore.setState((cur) => ({
54
+ enableImageUpload: (snapshot['enableImageUpload'] as boolean | undefined) ?? cur.enableImageUpload,
55
+ enableVideoUpload: (snapshot['enableVideoUpload'] as boolean | undefined) ?? cur.enableVideoUpload,
56
+ enableTTS: (snapshot['enableTTS'] as boolean | undefined) ?? cur.enableTTS,
57
+ enableVoiceInput: (snapshot['enableVoiceInput'] as boolean | undefined) ?? cur.enableVoiceInput,
58
+ defaultInputMode:
59
+ (snapshot['defaultInputMode'] as 'TEXT' | 'VOICE' | undefined) ?? cur.defaultInputMode,
60
+ quickCommands: (snapshot['quickCommands'] as QuickCommand[] | undefined) ?? cur.quickCommands,
61
+ }));
62
+ }
@@ -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" onClick={onClick}>
49
+ <Bug className="tbox-debug-btn__icon" size={22} />
50
+ <span className="tbox-debug-btn__text">调试</span>
51
+ </div>
52
+ );
53
+ }
@@ -0,0 +1,123 @@
1
+ /**
2
+ * 助手消息操作栏(mall-vis 蓝系 token 化)。
3
+ * - 图标 phosphor 矢量(currentColor):默认灰(--tbox-text-muted)、active 态蓝(--tbox-primary)
4
+ * - active 底 / TTS 播放底:--tbox-primary-light(蓝系浅底)
5
+ * - 调试文字 / 波形条:--tbox-text-secondary
6
+ * - 按压底:--tbox-bg-subtle
7
+ */
8
+ .tbox-action-bar {
9
+ display: flex;
10
+ align-items: center;
11
+ gap: 16px;
12
+ }
13
+
14
+ .tbox-action-btn {
15
+ padding: 0;
16
+ border: 0;
17
+ color: var(--tbox-text-muted);
18
+ font: inherit;
19
+ cursor: pointer;
20
+ width: 52px;
21
+ height: 52px;
22
+ display: flex;
23
+ align-items: center;
24
+ justify-content: center;
25
+ flex-shrink: 0;
26
+ border-radius: 26px;
27
+ background: #fff;
28
+ transition: background-color var(--tbox-motion-duration-fast) ease, transform var(--tbox-motion-duration-fast) ease;
29
+
30
+ &:active {
31
+ background: var(--tbox-bg-subtle);
32
+ transform: scale(0.97);
33
+ }
34
+
35
+ &--active {
36
+ color: var(--tbox-primary);
37
+ background: var(--tbox-primary-light);
38
+ }
39
+
40
+ &__icon-wrap {
41
+ width: 28px;
42
+ height: 28px;
43
+ display: flex;
44
+ align-items: center;
45
+ justify-content: center;
46
+ flex-shrink: 0;
47
+ }
48
+ }
49
+
50
+ /* 调试按钮:独立 pill(icon + “调试” 文字) */
51
+ .tbox-debug-btn {
52
+ display: inline-flex;
53
+ align-items: center;
54
+ justify-content: center;
55
+ gap: 8px;
56
+ height: 52px;
57
+ padding: 0 22px;
58
+ border-radius: 26px;
59
+ background: #fff;
60
+ color: var(--tbox-text-secondary);
61
+ transition: background-color var(--tbox-motion-duration-fast) ease, transform var(--tbox-motion-duration-fast) ease;
62
+
63
+ &:active {
64
+ background: var(--tbox-bg-subtle);
65
+ transform: scale(0.97);
66
+ }
67
+
68
+ &__icon {
69
+ width: 28px;
70
+ height: 28px;
71
+ flex-shrink: 0;
72
+ }
73
+
74
+ &__text {
75
+ font-size: 21px;
76
+ line-height: 1;
77
+ }
78
+ }
79
+
80
+ /* TTS 播放波形(红系主色,随 token 走) */
81
+ .tbox-tts-wave {
82
+ display: flex;
83
+ align-items: center;
84
+ justify-content: center;
85
+ gap: 3px;
86
+ width: 28px;
87
+ height: 28px;
88
+
89
+ &__bar {
90
+ width: 3px;
91
+ border-radius: 999px;
92
+ background: var(--tbox-primary);
93
+ transform-origin: center bottom;
94
+ animation: tbox-tts-wave 0.8s ease-in-out infinite;
95
+ }
96
+ &__bar--1 {
97
+ height: 14px;
98
+ animation-delay: 0s;
99
+ }
100
+ &__bar--2 {
101
+ height: 18px;
102
+ animation-delay: 0.15s;
103
+ }
104
+ &__bar--3 {
105
+ height: 12px;
106
+ animation-delay: 0.3s;
107
+ }
108
+ }
109
+
110
+ .tbox-tts-btn--playing {
111
+ color: var(--tbox-primary);
112
+ background: var(--tbox-primary-light);
113
+ }
114
+
115
+ @keyframes tbox-tts-wave {
116
+ 0%,
117
+ 100% {
118
+ transform: scaleY(0.6);
119
+ }
120
+ 50% {
121
+ transform: scaleY(1);
122
+ }
123
+ }
@@ -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,159 @@
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
+ import './index.less';
14
+
15
+ /**
16
+ * 跨所有 ActionBar 实例共享的"正在朗读的消息 id"(对齐原模板 useTTS 的 _playingId)。
17
+ * 保证同一时刻只有发起朗读的那条消息按钮显示波纹/暂停态,切到另一条会自动复位前一条。
18
+ */
19
+ let _playingId: string | null = null;
20
+ const _playingIdListeners = new Set<() => void>();
21
+ const getPlayingId = () => _playingId;
22
+ function subscribePlayingId(cb: () => void) {
23
+ _playingIdListeners.add(cb);
24
+ return () => {
25
+ _playingIdListeners.delete(cb);
26
+ };
27
+ }
28
+ function setPlayingId(id: string | null) {
29
+ if (_playingId === id) return;
30
+ _playingId = id;
31
+ _playingIdListeners.forEach((cb) => cb());
32
+ }
33
+ /** play() 同步执行期间为 true,防止切歌瞬间 adapter 的 idle 事件误清 playingId */
34
+ let _isPlaying = false;
35
+
36
+ /** 助手消息操作栏(对齐原模板):朗读(TTS) + 复制 + 赞 + 踩。 */
37
+ export function getMessageCopyText(message: ChatMessage): string {
38
+ return [message.content, message.error].filter(Boolean).join('\n\n');
39
+ }
40
+
41
+ export function CopyButton({ text }: { text: string }) {
42
+ const copy = async () => {
43
+ const copied = await copyText(text);
44
+ void toast(copied ? '复制成功' : '复制失败,请重试', copied ? 'success' : 'error');
45
+ };
46
+
47
+ return (
48
+ <button type="button" className="tbox-action-btn" onClick={copy} aria-label="复制">
49
+ <span className="tbox-action-btn__icon-wrap">
50
+ <Copy size={22} />
51
+ </span>
52
+ </button>
53
+ );
54
+ }
55
+
56
+ export function ActionBar({ message }: { message: ChatMessage }) {
57
+ const feedback = useFeedbackAdapter();
58
+ const refreshSession = useRefreshSession();
59
+ const tts = useTTSAdapter();
60
+ const enableTTS = useChatConfigStore((s) => s.enableTTS);
61
+ const submitFeedback = useChatStore((s) => s.submitFeedback);
62
+
63
+ const [ttsState, setTtsState] = useState<'idle' | 'loading' | 'playing' | 'paused'>('idle');
64
+ // 是否轮到本条消息:由共享 playingId 决定(而非各自的本地 state),实现跨实例互斥高亮
65
+ const playingId = useSyncExternalStore(subscribePlayingId, getPlayingId);
66
+ const isMine = playingId === message.id;
67
+ useEffect(() => {
68
+ if (!tts) return;
69
+ return (
70
+ tts.onStateChange((s) => {
71
+ setTtsState(s);
72
+ // 播放自然结束 → 清空全局播放态;_isPlaying 守卫避免切歌瞬间的 idle 误清
73
+ if (s === 'idle' && !_isPlaying) setPlayingId(null);
74
+ }) || undefined
75
+ );
76
+ }, [tts]);
77
+
78
+ const onFeedback = (type: 'like' | 'dislike') => {
79
+ if (!feedback) return;
80
+ const next = message.feedbackState === type ? 'cancel' : type;
81
+ submitFeedback(message.id, next, feedback, refreshSession);
82
+ };
83
+
84
+ const wave = isMine && (ttsState === 'loading' || ttsState === 'playing');
85
+ // 对齐原模板 TTSButton:播放/加载中点击→暂停;暂停中点击→恢复;其余→从头播放
86
+ const onTts = () => {
87
+ if (!tts) return;
88
+ if (isMine) {
89
+ if (ttsState === 'playing' || ttsState === 'loading') {
90
+ tts.pause();
91
+ return;
92
+ }
93
+ if (ttsState === 'paused') {
94
+ tts.resume();
95
+ return;
96
+ }
97
+ }
98
+ _isPlaying = true;
99
+ setPlayingId(message.id);
100
+ tts.speak(message.content, message.id).catch((err: unknown) => {
101
+ ttsActionLogger.warn(`tts.speak 失败:err=${(err as Error)?.message ?? String(err)}`);
102
+ setPlayingId(null);
103
+ });
104
+ _isPlaying = false;
105
+ };
106
+
107
+ // 显示依据 requestId(server 下发、不依赖 session);提交时若无 feedback 适配器则 onFeedback 内部 no-op
108
+ const canFeedback = !!message.requestId;
109
+
110
+ return (
111
+ <div className="tbox-action-bar">
112
+ {enableTTS && tts && (
113
+ <div className={`tbox-action-btn${wave ? ' tbox-tts-btn--playing' : ''}`} onClick={onTts}>
114
+ {wave ? (
115
+ <div className="tbox-tts-wave">
116
+ <div className="tbox-tts-wave__bar tbox-tts-wave__bar--1" />
117
+ <div className="tbox-tts-wave__bar tbox-tts-wave__bar--2" />
118
+ <div className="tbox-tts-wave__bar tbox-tts-wave__bar--3" />
119
+ </div>
120
+ ) : (
121
+ <div className="tbox-action-btn__icon-wrap">
122
+ <SpeakerHigh size={22} />
123
+ </div>
124
+ )}
125
+ </div>
126
+ )}
127
+
128
+ <CopyButton text={getMessageCopyText(message)} />
129
+
130
+ {canFeedback && (
131
+ <>
132
+ <div
133
+ className={`tbox-action-btn${message.feedbackState === 'like' ? ' tbox-action-btn--active' : ''}`}
134
+ onClick={() => onFeedback('like')}
135
+ >
136
+ <div className="tbox-action-btn__icon-wrap">
137
+ <ThumbsUp size={22} />
138
+ </div>
139
+ </div>
140
+ <div
141
+ className={`tbox-action-btn${message.feedbackState === 'dislike' ? ' tbox-action-btn--active' : ''}`}
142
+ onClick={() => onFeedback('dislike')}
143
+ >
144
+ <div className="tbox-action-btn__icon-wrap">
145
+ <ThumbsDown size={22} />
146
+ </div>
147
+ </div>
148
+ </>
149
+ )}
150
+
151
+ <DebugButton
152
+ requestId={message.requestId}
153
+ conversationId={message.conversationId}
154
+ messageId={message.id}
155
+ messageCreatedAt={new Date(message.createdAt).getTime()}
156
+ />
157
+ </div>
158
+ );
159
+ }
@@ -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
+ }