@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.
- package/LICENSE +21 -0
- package/README.md +69 -2
- package/assets/keyboard-circle.svg +12 -0
- package/assets/more-circle.svg +3 -0
- package/assets/new-chat.svg +3 -0
- package/assets/quick-command-star.svg +3 -0
- package/assets/send-gradient.svg +14 -0
- package/assets/stop@2x.png +0 -0
- package/assets/voice-circle.svg +3 -0
- package/package.json +70 -3
- package/src/ChatPage.tsx +400 -0
- package/src/card/action-list-pending.test.tsx +91 -0
- package/src/card/define-card.test.ts +25 -0
- package/src/card/define-card.ts +47 -0
- package/src/card/primitives.test.tsx +157 -0
- package/src/card/primitives.tsx +717 -0
- package/src/card/use-card-actions.ts +86 -0
- package/src/card/view-card-inline.test.tsx +42 -0
- package/src/card/view-card.test.tsx +79 -0
- package/src/card/view-card.tsx +250 -0
- package/src/chat-config.test.ts +46 -0
- package/src/chat-config.ts +84 -0
- package/src/components/ActionBar/DebugButton.test.tsx +87 -0
- package/src/components/ActionBar/DebugButton.tsx +48 -0
- package/src/components/ActionBar/index.test.tsx +83 -0
- package/src/components/ActionBar/index.tsx +158 -0
- package/src/components/BottomSheet/index.test.tsx +97 -0
- package/src/components/BottomSheet/index.tsx +49 -0
- package/src/components/CardRenderer.tsx +36 -0
- package/src/components/ChatHeader/index.test.tsx +74 -0
- package/src/components/ChatHeader/index.tsx +77 -0
- package/src/components/ChatInput/index.test.tsx +156 -0
- package/src/components/ChatInput/index.tsx +295 -0
- package/src/components/ChatInput/voice/VoicePressField.tsx +43 -0
- package/src/components/ChatInput/voice/VoiceRecordingOverlay.tsx +51 -0
- package/src/components/ChatInput/voice/machine.ts +27 -0
- package/src/components/ChatInput/voice/useVoicePress.ts +207 -0
- package/src/components/HistoryEntry/index.tsx +42 -0
- package/src/components/MediaList/index.tsx +270 -0
- package/src/components/MessageBubble/index.test.tsx +134 -0
- package/src/components/MessageBubble/index.tsx +208 -0
- package/src/components/PullDownIndicator/index.tsx +31 -0
- package/src/components/QuickCommands/index.test.tsx +101 -0
- package/src/components/QuickCommands/index.tsx +75 -0
- package/src/components/ReasoningBlock/index.tsx +61 -0
- package/src/components/ScrollToBottomButton/index.tsx +12 -0
- package/src/components/ToolCallBlock/detail.test.ts +346 -0
- package/src/components/ToolCallBlock/detail.ts +204 -0
- package/src/components/ToolCallBlock/index.test.tsx +261 -0
- package/src/components/ToolCallBlock/index.tsx +232 -0
- package/src/components/ToolCallBlock/titles.ts +102 -0
- package/src/hooks/use-drag-gesture.test.ts +66 -0
- package/src/hooks/use-drag-gesture.ts +129 -0
- package/src/hooks/use-pull-down-history.ts +241 -0
- package/src/hooks/use-pull-down-wheel-native.test.ts +64 -0
- package/src/hooks/useMediaUpload.ts +242 -0
- package/src/hooks/useTTSAutoPlay.ts +82 -0
- package/src/icons.ts +39 -0
- package/src/index.ts +143 -0
- package/src/overlay/Overlay.tsx +154 -0
- package/src/overlay/focus.ts +53 -0
- package/src/overlay/index.ts +16 -0
- package/src/overlay/inert.ts +27 -0
- package/src/overlay/layers.ts +21 -0
- package/src/overlay/overlay.ssr.test.tsx +27 -0
- package/src/overlay/overlay.test.tsx +209 -0
- package/src/overlay/presence.ts +86 -0
- package/src/overlay/scroll-lock.ts +62 -0
- package/src/overlay/stack.ts +111 -0
- package/src/overlay/use-overlay.ts +80 -0
- package/src/preview-provider.tsx +47 -0
- package/src/shell.contract.json +75 -0
- package/src/shell.test.ts +72 -0
- package/src/shell.ts +60 -0
- package/src/store-context.tsx +92 -0
- package/src/surface.test.tsx +35 -0
- package/src/surface.tsx +44 -0
- package/src/test/setup.ts +7 -0
- package/src/theme/base.css +167 -0
- package/src/theme/contract.json +193 -0
- package/src/theme/motion.css +19 -0
- package/src/theme/theme-contract.test.ts +85 -0
- package/src/theme/theme.ts +17 -0
- package/src/theme/tokens.css +78 -0
- package/src/types.ts +29 -0
- package/src/utils/copyText.ts +11 -0
- package/src/utils/haptics.test.ts +51 -0
- package/src/utils/haptics.ts +44 -0
- package/src/utils/image-preview-host.tsx +95 -0
- package/src/utils/imagePreview.test.ts +32 -0
- package/src/utils/imagePreview.ts +19 -0
- package/src/utils/pull-down-machine.test.ts +188 -0
- package/src/utils/pull-down-machine.ts +157 -0
- package/src/utils/session-error.ts +5 -0
- package/src/utils/toast.test.ts +64 -0
- package/src/utils/toast.ts +108 -0
- package/src/utils/tool-call-display.test.ts +240 -0
- package/src/utils/tool-call-display.ts +146 -0
- 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,42 @@
|
|
|
1
|
+
// @vitest-environment happy-dom
|
|
2
|
+
import { act } from 'react';
|
|
3
|
+
import { createRoot } from 'react-dom/client';
|
|
4
|
+
import { afterEach, describe, expect, it } from 'vitest';
|
|
5
|
+
import type { CardView } from '@tbox.cn/app-contracts';
|
|
6
|
+
import { createSurfaceHarness } from '../surface';
|
|
7
|
+
import { ViewCard } from './view-card';
|
|
8
|
+
|
|
9
|
+
const view: CardView = {
|
|
10
|
+
header: { title: '活动' },
|
|
11
|
+
blocks: [
|
|
12
|
+
{
|
|
13
|
+
kind: 'list',
|
|
14
|
+
items: [{ title: '亲子手作', action: { label: '报名', invoke: { id: 'register' } } }],
|
|
15
|
+
},
|
|
16
|
+
],
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
const roots: ReturnType<typeof createRoot>[] = [];
|
|
20
|
+
afterEach(async () => {
|
|
21
|
+
await act(async () => {
|
|
22
|
+
for (const root of roots) root.unmount();
|
|
23
|
+
});
|
|
24
|
+
roots.length = 0;
|
|
25
|
+
document.body.innerHTML = '';
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
describe('ViewCard 列表内联动作', () => {
|
|
29
|
+
it('点击后进入单飞状态,按钮禁用', async () => {
|
|
30
|
+
const harness = createSurfaceHarness({});
|
|
31
|
+
const el = document.createElement('div');
|
|
32
|
+
document.body.appendChild(el);
|
|
33
|
+
const root = createRoot(el);
|
|
34
|
+
roots.push(root);
|
|
35
|
+
act(() => root.render(harness.wrap(<ViewCard view={view} cardId="c1" actionTokens={{ register: 'token' }} />)));
|
|
36
|
+
const button = [...el.querySelectorAll('button')].find((item) => item.textContent?.includes('报名'))!;
|
|
37
|
+
await act(async () => {
|
|
38
|
+
button.click();
|
|
39
|
+
});
|
|
40
|
+
expect(el.querySelector('button')!.disabled).toBe(true);
|
|
41
|
+
});
|
|
42
|
+
});
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { createElement } from 'react';
|
|
3
|
+
import { renderToStaticMarkup } from 'react-dom/server';
|
|
4
|
+
import type { CardView } from '@tbox.cn/app-contracts';
|
|
5
|
+
import { createSurfaceHarness } from '../surface';
|
|
6
|
+
import { ViewCard } from './view-card';
|
|
7
|
+
|
|
8
|
+
const parking: CardView = {
|
|
9
|
+
header: { title: '停车订单', eyebrow: 'PARKING', status: { text: '待支付', tone: 'warning' } },
|
|
10
|
+
blocks: [
|
|
11
|
+
{ kind: 'facts', items: [['车牌', '浙A·12345'], ['停车时长', '2 小时 20 分钟']] },
|
|
12
|
+
{ kind: 'bill', lines: [['停车费', '¥15'], ['停车券', '-¥10', true]], total: ['应付', '¥5'] },
|
|
13
|
+
{ kind: 'notice', text: '已为你选好停车券', tone: 'info' },
|
|
14
|
+
],
|
|
15
|
+
actions: [
|
|
16
|
+
{ label: '确认支付 ¥5', invoke: { id: 'pay-parking', input: { plate: '浙A·12345' } }, confirm: { title: '确认支付?' } },
|
|
17
|
+
{ label: '用积分换停车券', send: '用积分兑换停车券' },
|
|
18
|
+
],
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
const activity: CardView = {
|
|
22
|
+
header: { title: '近期活动', status: { text: '2 个推荐', tone: 'info' } },
|
|
23
|
+
blocks: [
|
|
24
|
+
{
|
|
25
|
+
kind: 'list',
|
|
26
|
+
items: [
|
|
27
|
+
{ title: '亲子手作', meta: '今天 15:00 · L2 连廊', tags: ['亲子'], description: '剩 8 组名额', action: { label: '报名', invoke: { id: 'register' } } },
|
|
28
|
+
{ title: '积分加倍', meta: '今天 10:00 · L1 中庭' },
|
|
29
|
+
],
|
|
30
|
+
},
|
|
31
|
+
],
|
|
32
|
+
actions: [{ label: '看第一个详情', send: '第一个活动的详情', style: 'secondary' }],
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
const harness = createSurfaceHarness({});
|
|
36
|
+
const render = (view: CardView, isHistory = false) =>
|
|
37
|
+
renderToStaticMarkup(harness.wrap(createElement(ViewCard, { view, cardId: 'c1', isHistory })));
|
|
38
|
+
|
|
39
|
+
describe('ViewCard', () => {
|
|
40
|
+
it('积木与动作渲染一次,标题/明细/提示都在', () => {
|
|
41
|
+
const html = render(parking);
|
|
42
|
+
expect(html).toContain('停车订单');
|
|
43
|
+
expect(html).toContain('浙A·12345');
|
|
44
|
+
expect(html).toContain('应付');
|
|
45
|
+
expect(html).toContain('已为你选好停车券');
|
|
46
|
+
expect(html.match(/确认支付 ¥5/g)?.length).toBe(1);
|
|
47
|
+
expect(html.match(/用积分换停车券/g)?.length).toBe(1);
|
|
48
|
+
expect(html).toContain('tbox-btn');
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it('列表积木渲染实体与内联动作', () => {
|
|
52
|
+
const html = render(activity);
|
|
53
|
+
expect(html).toContain('亲子手作');
|
|
54
|
+
expect(html).toContain('报名');
|
|
55
|
+
expect(html).toContain('2 个推荐');
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('渲染前归一化:超预算积木只渲染前 4 个', () => {
|
|
59
|
+
const over = {
|
|
60
|
+
header: { title: '超预算' },
|
|
61
|
+
blocks: Array.from({ length: 5 }, (_, index) => ({ kind: 'tags' as const, tags: ['tag-' + index] })),
|
|
62
|
+
} as unknown as CardView;
|
|
63
|
+
const html = render(over);
|
|
64
|
+
expect(html).toContain('tag-0');
|
|
65
|
+
expect(html).toContain('tag-3');
|
|
66
|
+
expect(html).not.toContain('tag-4');
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it('坏数据回退为可读提示,不抛错', () => {
|
|
70
|
+
const broken = { header: { title: '坏卡' }, blocks: null } as unknown as CardView;
|
|
71
|
+
const html = render(broken);
|
|
72
|
+
expect(html).toContain('卡片数据不可用');
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it('历史态禁用动作', () => {
|
|
76
|
+
const html = render(parking, true);
|
|
77
|
+
expect(html).toContain('disabled');
|
|
78
|
+
});
|
|
79
|
+
});
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ViewCard:视图卡的通用渲染器(L1)。
|
|
3
|
+
*
|
|
4
|
+
* 一张卡 = 一份 CardView JSON;版式、动作路径、确认弹层、历史禁用都由平台实现一次。
|
|
5
|
+
* 应用只写 view(data) 函数(服务端),客户端不再有手写 tsx。
|
|
6
|
+
*/
|
|
7
|
+
import { useEffect, useRef, useState, type ReactNode } from 'react';
|
|
8
|
+
import { normalizeCardView } from '@tbox.cn/app-contracts';
|
|
9
|
+
import type { CardView, CardViewAction, CardViewBlock } from '@tbox.cn/app-contracts';
|
|
10
|
+
import {
|
|
11
|
+
ActionList,
|
|
12
|
+
Bill,
|
|
13
|
+
Card,
|
|
14
|
+
CardButton,
|
|
15
|
+
CardHeader,
|
|
16
|
+
ConfirmSheet,
|
|
17
|
+
EmptyState,
|
|
18
|
+
EntityRow,
|
|
19
|
+
Hero,
|
|
20
|
+
KeyValueList,
|
|
21
|
+
Notice,
|
|
22
|
+
StatusTag,
|
|
23
|
+
Steps,
|
|
24
|
+
TagList,
|
|
25
|
+
Ticket,
|
|
26
|
+
Timeline,
|
|
27
|
+
} from './primitives';
|
|
28
|
+
import type { CardActionSpec } from './primitives';
|
|
29
|
+
import { useCardActions } from './use-card-actions';
|
|
30
|
+
|
|
31
|
+
type Api = ReturnType<typeof useCardActions>;
|
|
32
|
+
|
|
33
|
+
function toSpec(action: CardViewAction): CardActionSpec {
|
|
34
|
+
return {
|
|
35
|
+
label: action.label,
|
|
36
|
+
...(action.send !== undefined ? { send: action.send } : {}),
|
|
37
|
+
...(action.invoke ? { invoke: action.invoke } : {}),
|
|
38
|
+
...(action.confirm ? { confirm: action.confirm } : {}),
|
|
39
|
+
...(action.style ? { style: action.style } : {}),
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** 列表项内联动作:与卡级动作共用确认弹层语义,但不占整行。 */
|
|
44
|
+
function useInlineRunner(api: Api) {
|
|
45
|
+
const [pending, setPending] = useState<CardViewAction | null>(null);
|
|
46
|
+
const [running, setRunning] = useState(false);
|
|
47
|
+
const runningRef = useRef(false);
|
|
48
|
+
const wasGenerating = useRef(false);
|
|
49
|
+
useEffect(() => {
|
|
50
|
+
if (!running) return undefined;
|
|
51
|
+
const timer = setTimeout(() => {
|
|
52
|
+
runningRef.current = false;
|
|
53
|
+
setRunning(false);
|
|
54
|
+
}, 20000);
|
|
55
|
+
return () => clearTimeout(timer);
|
|
56
|
+
}, [running]);
|
|
57
|
+
useEffect(() => {
|
|
58
|
+
if (api.isGenerating) {
|
|
59
|
+
wasGenerating.current = true;
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
if (!wasGenerating.current) return;
|
|
63
|
+
wasGenerating.current = false;
|
|
64
|
+
if (runningRef.current) {
|
|
65
|
+
runningRef.current = false;
|
|
66
|
+
setRunning(false);
|
|
67
|
+
}
|
|
68
|
+
}, [api.isGenerating]);
|
|
69
|
+
const run = (action: CardViewAction) => {
|
|
70
|
+
if (!action.invoke && !action.send) return;
|
|
71
|
+
runningRef.current = true;
|
|
72
|
+
setRunning(true);
|
|
73
|
+
if (action.invoke) {
|
|
74
|
+
api.invoke(action.invoke.id, action.invoke.input);
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
if (action.send) {
|
|
78
|
+
if (typeof action.send === 'string') api.send(action.send);
|
|
79
|
+
else api.send(action.send.text, { displayText: action.send.displayText });
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
const trigger = (action: CardViewAction) => {
|
|
83
|
+
if (api.disabled || runningRef.current || pending !== null) return;
|
|
84
|
+
if (action.confirm) {
|
|
85
|
+
setPending(action);
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
run(action);
|
|
89
|
+
};
|
|
90
|
+
const sheet =
|
|
91
|
+
pending && pending.confirm ? (
|
|
92
|
+
<ConfirmSheet
|
|
93
|
+
open
|
|
94
|
+
title={pending.confirm.title}
|
|
95
|
+
{...(pending.confirm.description ? { description: pending.confirm.description } : {})}
|
|
96
|
+
{...(pending.confirm.confirmText ? { confirmText: pending.confirm.confirmText } : {})}
|
|
97
|
+
{...(pending.confirm.cancelText ? { cancelText: pending.confirm.cancelText } : {})}
|
|
98
|
+
onConfirm={() => {
|
|
99
|
+
const action = pending;
|
|
100
|
+
setPending(null);
|
|
101
|
+
run(action);
|
|
102
|
+
}}
|
|
103
|
+
onCancel={() => setPending(null)}
|
|
104
|
+
/>
|
|
105
|
+
) : null;
|
|
106
|
+
return { trigger, sheet, busy: api.disabled || running || pending !== null };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function renderBlock(
|
|
110
|
+
block: CardViewBlock,
|
|
111
|
+
trigger: (action: CardViewAction) => void,
|
|
112
|
+
disabled: boolean,
|
|
113
|
+
): ReactNode {
|
|
114
|
+
switch (block.kind) {
|
|
115
|
+
case 'hero':
|
|
116
|
+
return (
|
|
117
|
+
<Hero
|
|
118
|
+
{...(block.eyebrow ? { eyebrow: block.eyebrow } : {})}
|
|
119
|
+
title={block.title}
|
|
120
|
+
{...(block.value ? { value: block.value } : {})}
|
|
121
|
+
{...(block.unit ? { unit: block.unit } : {})}
|
|
122
|
+
{...(block.footnote ? { footnote: block.footnote } : {})}
|
|
123
|
+
{...(block.tone ? { tone: block.tone } : {})}
|
|
124
|
+
/>
|
|
125
|
+
);
|
|
126
|
+
case 'facts':
|
|
127
|
+
return <KeyValueList items={block.items.map(([label, value]) => ({ label, value }))} />;
|
|
128
|
+
case 'bill':
|
|
129
|
+
return (
|
|
130
|
+
<Bill
|
|
131
|
+
lines={block.lines.map(([label, value, muted]) => ({ label, value, ...(muted ? { muted: true } : {}) }))}
|
|
132
|
+
{...(block.total ? { total: { label: block.total[0], value: block.total[1] } } : {})}
|
|
133
|
+
/>
|
|
134
|
+
);
|
|
135
|
+
case 'notice':
|
|
136
|
+
return <Notice {...(block.tone ? { tone: block.tone } : {})}>{block.text}</Notice>;
|
|
137
|
+
case 'tags':
|
|
138
|
+
return <TagList tags={block.tags} {...(block.tone ? { tone: block.tone } : {})} />;
|
|
139
|
+
case 'steps':
|
|
140
|
+
return <Steps steps={block.steps} />;
|
|
141
|
+
case 'ticket':
|
|
142
|
+
return (
|
|
143
|
+
<Ticket
|
|
144
|
+
amount={block.amount}
|
|
145
|
+
{...(block.condition ? { condition: block.condition } : {})}
|
|
146
|
+
{...(block.meta ? { meta: block.meta } : {})}
|
|
147
|
+
{...(block.status ? { status: block.status } : {})}
|
|
148
|
+
{...(block.tone ? { tone: block.tone } : {})}
|
|
149
|
+
/>
|
|
150
|
+
);
|
|
151
|
+
case 'timeline':
|
|
152
|
+
return (
|
|
153
|
+
<Timeline
|
|
154
|
+
items={block.items.map((item) => ({
|
|
155
|
+
label: item.label,
|
|
156
|
+
...(item.amount ? { amount: item.amount } : {}),
|
|
157
|
+
...(item.time ? { time: item.time } : {}),
|
|
158
|
+
...(item.tone ? { tone: item.tone } : {}),
|
|
159
|
+
}))}
|
|
160
|
+
/>
|
|
161
|
+
);
|
|
162
|
+
case 'empty':
|
|
163
|
+
return <EmptyState title={block.title} {...(block.description ? { description: block.description } : {})} />;
|
|
164
|
+
case 'list':
|
|
165
|
+
return (
|
|
166
|
+
<div className="tbox-view-list flex flex-col gap-2.5">
|
|
167
|
+
{block.items.map((item, index) => (
|
|
168
|
+
<EntityRow
|
|
169
|
+
key={item.title + '-' + index}
|
|
170
|
+
title={item.title}
|
|
171
|
+
{...(item.meta ? { meta: item.meta } : {})}
|
|
172
|
+
{...(item.price ? { price: item.price } : {})}
|
|
173
|
+
{...(item.description ? { description: item.description } : {})}
|
|
174
|
+
{...(item.tags && item.tags.length > 0 ? { tags: <TagList tags={item.tags} /> } : {})}
|
|
175
|
+
{...(item.action
|
|
176
|
+
? {
|
|
177
|
+
action: (
|
|
178
|
+
<CardButton
|
|
179
|
+
variant={item.action.style === 'primary' ? 'primary' : 'secondary'}
|
|
180
|
+
disabled={disabled}
|
|
181
|
+
onClick={() => trigger(item.action as CardViewAction)}
|
|
182
|
+
>
|
|
183
|
+
{item.action.label}
|
|
184
|
+
</CardButton>
|
|
185
|
+
),
|
|
186
|
+
}
|
|
187
|
+
: {})}
|
|
188
|
+
/>
|
|
189
|
+
))}
|
|
190
|
+
</div>
|
|
191
|
+
);
|
|
192
|
+
default: {
|
|
193
|
+
const unknown = block as { kind?: string };
|
|
194
|
+
console.warn('[ViewCard] 未知积木,已跳过:' + String(unknown.kind));
|
|
195
|
+
return null;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
export function ViewCard({
|
|
201
|
+
view,
|
|
202
|
+
cardId,
|
|
203
|
+
isHistory,
|
|
204
|
+
actionTokens,
|
|
205
|
+
}: {
|
|
206
|
+
view: CardView;
|
|
207
|
+
cardId: string;
|
|
208
|
+
isHistory?: boolean;
|
|
209
|
+
actionTokens?: Record<string, string>;
|
|
210
|
+
}) {
|
|
211
|
+
let safeView: CardView;
|
|
212
|
+
try {
|
|
213
|
+
safeView = normalizeCardView(view);
|
|
214
|
+
} catch {
|
|
215
|
+
return (
|
|
216
|
+
<Card>
|
|
217
|
+
<Notice tone="error">卡片数据不可用,请重新触发一次</Notice>
|
|
218
|
+
</Card>
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
const api = useCardActions({
|
|
222
|
+
cardId,
|
|
223
|
+
isHistory: isHistory === true,
|
|
224
|
+
...(actionTokens ? { actionTokens } : {}),
|
|
225
|
+
});
|
|
226
|
+
const inline = useInlineRunner(api);
|
|
227
|
+
return (
|
|
228
|
+
<Card>
|
|
229
|
+
<CardHeader
|
|
230
|
+
title={safeView.header.title}
|
|
231
|
+
{...(safeView.header.eyebrow ? { eyebrow: safeView.header.eyebrow } : {})}
|
|
232
|
+
{...(safeView.header.status
|
|
233
|
+
? { status: <StatusTag tone={safeView.header.status.tone ?? 'neutral'}>{safeView.header.status.text}</StatusTag> }
|
|
234
|
+
: {})}
|
|
235
|
+
/>
|
|
236
|
+
{safeView.blocks.map((block, index) => (
|
|
237
|
+
<div key={block.kind + '-' + index}>{renderBlock(block, inline.trigger, inline.busy)}</div>
|
|
238
|
+
))}
|
|
239
|
+
{safeView.actions && safeView.actions.length > 0 ? (
|
|
240
|
+
<ActionList
|
|
241
|
+
api={api}
|
|
242
|
+
actions={safeView.actions.map((action, index) =>
|
|
243
|
+
toSpec(index === 0 ? { ...action, style: action.style ?? 'primary' } : { ...action, style: 'secondary' }),
|
|
244
|
+
)}
|
|
245
|
+
/>
|
|
246
|
+
) : null}
|
|
247
|
+
{inline.sheet}
|
|
248
|
+
</Card>
|
|
249
|
+
);
|
|
250
|
+
}
|
|
@@ -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,84 @@
|
|
|
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
|
+
// SSR / 探针注入点:浏览器生产环境不设置,零影响(探针看不到配置会误判)。
|
|
44
|
+
const ssrSnapshot = ((globalThis as { __TBOX_CHAT_CONFIG__?: Record<string, unknown> }).__TBOX_CHAT_CONFIG__ ?? {});
|
|
45
|
+
export const useChatConfigStore = create<ChatConfigStore>()((set) => ({
|
|
46
|
+
// kit 内建缺省(应用快照经 configureChatConfigDefaults 覆盖;SSR 探针经 globalThis 注入)
|
|
47
|
+
enableImageUpload: (ssrSnapshot['enableImageUpload'] as boolean | undefined) ?? true,
|
|
48
|
+
enableVideoUpload: (ssrSnapshot['enableVideoUpload'] as boolean | undefined) ?? true,
|
|
49
|
+
enableTTS: (ssrSnapshot['enableTTS'] as boolean | undefined) ?? true,
|
|
50
|
+
enableVoiceInput: (ssrSnapshot['enableVoiceInput'] as boolean | undefined) ?? true,
|
|
51
|
+
defaultInputMode: (ssrSnapshot['defaultInputMode'] as 'TEXT' | 'VOICE' | undefined) ?? 'TEXT',
|
|
52
|
+
quickCommands: (ssrSnapshot['quickCommands'] as QuickCommand[] | undefined) ?? [],
|
|
53
|
+
identity: ssrSnapshot['identity'] as ChatIdentity | undefined,
|
|
54
|
+
welcome: ssrSnapshot['welcome'] as ChatWelcome | undefined,
|
|
55
|
+
retryOnError: true,
|
|
56
|
+
applyServerSettings: (settings) =>
|
|
57
|
+
set((cur) => ({
|
|
58
|
+
enableImageUpload: settings?.enableImageUpload ?? cur.enableImageUpload,
|
|
59
|
+
enableVideoUpload: settings?.enableVideoUpload ?? cur.enableVideoUpload,
|
|
60
|
+
enableTTS: settings?.enableTTS ?? cur.enableTTS,
|
|
61
|
+
enableVoiceInput: settings?.enableVoiceInput ?? cur.enableVoiceInput,
|
|
62
|
+
defaultInputMode: settings?.defaultInputMode ?? cur.defaultInputMode,
|
|
63
|
+
})),
|
|
64
|
+
}));
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* 构建期快照注入(应用 boot 时调用一次;createRoot 前调用保证首帧即快照值)。
|
|
68
|
+
* 键缺席保留内建缺省;键在场以快照为准。
|
|
69
|
+
*/
|
|
70
|
+
export function configureChatConfigDefaults(snapshot: Record<string, unknown> | undefined): void {
|
|
71
|
+
if (!snapshot) return;
|
|
72
|
+
useChatConfigStore.setState((cur) => ({
|
|
73
|
+
enableImageUpload: (snapshot['enableImageUpload'] as boolean | undefined) ?? cur.enableImageUpload,
|
|
74
|
+
enableVideoUpload: (snapshot['enableVideoUpload'] as boolean | undefined) ?? cur.enableVideoUpload,
|
|
75
|
+
enableTTS: (snapshot['enableTTS'] as boolean | undefined) ?? cur.enableTTS,
|
|
76
|
+
enableVoiceInput: (snapshot['enableVoiceInput'] as boolean | undefined) ?? cur.enableVoiceInput,
|
|
77
|
+
defaultInputMode:
|
|
78
|
+
(snapshot['defaultInputMode'] as 'TEXT' | 'VOICE' | undefined) ?? cur.defaultInputMode,
|
|
79
|
+
quickCommands: (snapshot['quickCommands'] as QuickCommand[] | undefined) ?? cur.quickCommands,
|
|
80
|
+
identity: (snapshot['identity'] as ChatIdentity | undefined) ?? cur.identity,
|
|
81
|
+
welcome: (snapshot['welcome'] as ChatWelcome | undefined) ?? cur.welcome,
|
|
82
|
+
retryOnError: (snapshot['retryOnError'] as boolean | undefined) ?? cur.retryOnError,
|
|
83
|
+
}));
|
|
84
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
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
|
+
// 调试入口只在显式 ?debug=1 下渲染(B5:dev 构建与 iframe 预览不再触发)
|
|
26
|
+
window.history.replaceState({}, '', '/?debug=1');
|
|
27
|
+
host = document.createElement('div');
|
|
28
|
+
document.body.appendChild(host);
|
|
29
|
+
root = createRoot(host);
|
|
30
|
+
// happy-dom 下 window.parent === window:同一函数引用
|
|
31
|
+
postSpy = vi.fn();
|
|
32
|
+
window.parent.postMessage = postSpy as unknown as typeof window.postMessage;
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
afterEach(() => {
|
|
36
|
+
act(() => root.unmount());
|
|
37
|
+
host.remove();
|
|
38
|
+
window.history.replaceState({}, '', '/');
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
const clickDebug = () => {
|
|
42
|
+
act(() => {
|
|
43
|
+
host.querySelector('.tbox-debug-btn')!.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
|
44
|
+
});
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
it('D1 点击 → 载荷全键精确(type/requestId/conversationId/messageId/messageCreatedAt)', () => {
|
|
48
|
+
act(() => {
|
|
49
|
+
root.render(<DebugButton requestId="req_1" conversationId="conv_1" messageId="m1" messageCreatedAt={123} />);
|
|
50
|
+
});
|
|
51
|
+
clickDebug();
|
|
52
|
+
expect(postSpy).toHaveBeenCalledTimes(1);
|
|
53
|
+
expect(postSpy.mock.calls[0]![0]).toEqual({
|
|
54
|
+
type: 'tbox:debug-trace',
|
|
55
|
+
requestId: 'req_1',
|
|
56
|
+
conversationId: 'conv_1',
|
|
57
|
+
messageId: 'm1',
|
|
58
|
+
messageCreatedAt: 123,
|
|
59
|
+
});
|
|
60
|
+
expect(postSpy.mock.calls[0]![1]).toBe('*');
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it('D2 conversationId 缺席 → 载荷键恒在场、值为 undefined(现状降级形态锁定)', () => {
|
|
64
|
+
act(() => {
|
|
65
|
+
root.render(<DebugButton requestId="req_1" messageId="m2" messageCreatedAt={456} />);
|
|
66
|
+
});
|
|
67
|
+
clickDebug();
|
|
68
|
+
const payload = postSpy.mock.calls[0]![0] as Record<string, unknown>;
|
|
69
|
+
// 键恒在场(严格区分键存在性——toEqual 对 undefined 键与缺失等价,故断言键集)
|
|
70
|
+
expect(Object.keys(payload).sort()).toEqual([
|
|
71
|
+
'conversationId',
|
|
72
|
+
'messageCreatedAt',
|
|
73
|
+
'messageId',
|
|
74
|
+
'requestId',
|
|
75
|
+
'type',
|
|
76
|
+
]);
|
|
77
|
+
expect(payload.conversationId).toBeUndefined();
|
|
78
|
+
expect(payload.requestId).toBe('req_1');
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it('D3 requestId 缺席 → 不渲染(渲染守卫不变)', () => {
|
|
82
|
+
act(() => {
|
|
83
|
+
root.render(<DebugButton messageId="m3" />);
|
|
84
|
+
});
|
|
85
|
+
expect(host.querySelector('.tbox-debug-btn')).toBeNull();
|
|
86
|
+
});
|
|
87
|
+
});
|