@tbox.cn/app-template-agent 1.0.0-alpha.7 → 1.0.0-alpha.9

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 (161) hide show
  1. package/.gitignore +7 -0
  2. package/.tbox/app.json +1 -1
  3. package/.tbox/default-modules.json +1 -1
  4. package/.tbox/factory/chat.json +9 -0
  5. package/.tbox/miniapp-containers.json +1 -1
  6. package/AGENTS.md +11 -8
  7. package/apps/client/index.html +0 -43
  8. package/apps/client/package.json +1 -0
  9. package/apps/client/scripts/acceptance-changes.test.mjs +97 -0
  10. package/apps/client/scripts/check-evidence.mjs +625 -108
  11. package/apps/client/scripts/color-scan.mjs +66 -0
  12. package/apps/client/scripts/color-scan.test.mjs +25 -0
  13. package/apps/client/scripts/evidence-gate.mjs +337 -0
  14. package/apps/client/scripts/evidence-gate.test.mjs +135 -0
  15. package/apps/client/scripts/experience-checks.mjs +163 -0
  16. package/apps/client/scripts/geometry-kernel.test.mjs +92 -0
  17. package/apps/client/scripts/in-process-checks.mjs +51 -0
  18. package/apps/client/scripts/lib/card-registry.mjs +81 -0
  19. package/apps/client/scripts/lib/card-registry.test.mjs +59 -0
  20. package/apps/client/scripts/lib/evidence-inputs.mjs +91 -0
  21. package/apps/client/scripts/lib/evidence-inputs.test.mjs +27 -0
  22. package/apps/client/scripts/lib/static-render.mjs +35 -0
  23. package/apps/client/scripts/lib/static-render.test.mjs +21 -0
  24. package/apps/client/scripts/probe-checks.mjs +85 -0
  25. package/apps/client/scripts/render-card.mjs +95 -126
  26. package/apps/client/scripts/sample-entries.test.mjs +31 -0
  27. package/apps/client/scripts/storyboard.test.mjs +149 -0
  28. package/apps/client/scripts/surface-css.mjs +54 -0
  29. package/apps/client/scripts/theme-kernel.mjs +236 -0
  30. package/apps/client/scripts/theme-kernel.test.mjs +136 -0
  31. package/apps/client/src/app.config.ts +4 -1
  32. package/apps/client/src/styles/brand.css +13 -14
  33. package/apps/client/src/styles/tailwind.css +20 -21
  34. package/apps/client/vite.config.ts +2 -1
  35. package/apps/server/scripts/probe.mjs +6 -1
  36. package/apps/server/scripts/scenario-lib.mjs +56 -8
  37. package/apps/server/scripts/scenario.mjs +41 -7
  38. package/config/AGENTS.md +1 -0
  39. package/config/chat.json +21 -9
  40. package/docs/agent/agent-prompt.md +1 -1
  41. package/docs/agent/card-action.md +5 -0
  42. package/docs/agent/card.md +45 -2
  43. package/docs/agent/kit.md +3 -3
  44. package/docs/agent/shell.md +1 -0
  45. package/docs/agent/style.md +11 -3
  46. package/docs/agent/tool-emits-card.md +7 -2
  47. package/docs/agent/tool.md +2 -0
  48. package/docs/agent/verify.md +59 -16
  49. package/package.json +21 -7
  50. package/packages/agent-ui-kit/AGENTS.md +1 -1
  51. package/packages/agent-ui-kit/README.md +21 -1
  52. package/packages/agent-ui-kit/catalog.json +8 -4
  53. package/packages/agent-ui-kit/package.json +9 -1
  54. package/packages/agent-ui-kit/src/._surface.tsx +0 -0
  55. package/packages/agent-ui-kit/src/ChatPage.tsx +70 -17
  56. package/packages/agent-ui-kit/src/card/._action-list-pending.test.tsx +0 -0
  57. package/packages/agent-ui-kit/src/card/._define-card.test.ts +0 -0
  58. package/packages/agent-ui-kit/src/card/._view-card-inline.test.tsx +0 -0
  59. package/packages/agent-ui-kit/src/card/._view-card.test.tsx +0 -0
  60. package/packages/agent-ui-kit/src/card/._view-card.tsx +0 -0
  61. package/packages/agent-ui-kit/src/card/action-list-pending.test.tsx +91 -0
  62. package/packages/agent-ui-kit/src/card/define-card.test.ts +25 -0
  63. package/packages/agent-ui-kit/src/card/define-card.ts +18 -5
  64. package/packages/agent-ui-kit/src/card/primitives.test.tsx +10 -0
  65. package/packages/agent-ui-kit/src/card/primitives.tsx +136 -37
  66. package/packages/agent-ui-kit/src/card/view-card-inline.test.tsx +42 -0
  67. package/packages/agent-ui-kit/src/card/view-card.test.tsx +79 -0
  68. package/packages/agent-ui-kit/src/card/view-card.tsx +250 -0
  69. package/packages/agent-ui-kit/src/chat-config.ts +11 -7
  70. package/packages/agent-ui-kit/src/components/ActionBar/DebugButton.test.tsx +3 -0
  71. package/packages/agent-ui-kit/src/components/ActionBar/DebugButton.tsx +2 -7
  72. package/packages/agent-ui-kit/src/components/BottomSheet/._index.test.tsx +0 -0
  73. package/packages/agent-ui-kit/src/components/BottomSheet/._index.tsx +0 -0
  74. package/packages/agent-ui-kit/src/components/BottomSheet/index.test.tsx +90 -0
  75. package/packages/agent-ui-kit/src/components/BottomSheet/index.tsx +129 -0
  76. package/packages/agent-ui-kit/src/components/ChatInput/index.test.tsx +2 -2
  77. package/packages/agent-ui-kit/src/components/ChatInput/index.tsx +22 -17
  78. package/packages/agent-ui-kit/src/components/HistoryEntry/index.tsx +3 -2
  79. package/packages/agent-ui-kit/src/components/MessageBubble/index.tsx +11 -5
  80. package/packages/agent-ui-kit/src/components/QuickCommands/index.test.tsx +3 -1
  81. package/packages/agent-ui-kit/src/components/QuickCommands/index.tsx +31 -8
  82. package/packages/agent-ui-kit/src/components/ScrollToBottomButton/index.tsx +7 -3
  83. package/packages/agent-ui-kit/src/components/ToolCallBlock/index.tsx +4 -2
  84. package/packages/agent-ui-kit/src/index.ts +8 -0
  85. package/packages/agent-ui-kit/src/preview-provider.tsx +47 -0
  86. package/packages/agent-ui-kit/src/shell.contract.json +9 -0
  87. package/packages/agent-ui-kit/src/shell.test.ts +10 -0
  88. package/packages/agent-ui-kit/src/shell.ts +15 -0
  89. package/packages/agent-ui-kit/src/surface.test.tsx +35 -0
  90. package/packages/agent-ui-kit/src/surface.tsx +44 -0
  91. package/packages/agent-ui-kit/src/theme/base.css +9 -11
  92. package/packages/agent-ui-kit/src/theme/contract.json +123 -2
  93. package/packages/agent-ui-kit/src/theme/theme-contract.test.ts +16 -0
  94. package/packages/agent-ui-kit/src/theme/tokens.css +9 -12
  95. package/pnpm-lock.template.yaml +97 -91
  96. package/pnpm-workspace.template.yaml +10 -10
  97. package/profiles/mall/._chat.overrides.json +0 -0
  98. package/profiles/mall/chat.overrides.json +12 -0
  99. package/profiles/mall/config/chat.json +14 -6
  100. package/profiles/mall.json +1 -1
  101. package/scripts/._assert-pack.mjs +0 -0
  102. package/scripts/._deliver.mjs +0 -0
  103. package/scripts/._shell-probe.mjs +0 -0
  104. package/scripts/._storyboard.mjs +0 -0
  105. package/scripts/assert-pack.mjs +48 -0
  106. package/scripts/check-css-target.mjs +6 -3
  107. package/scripts/check-fast.mjs +1 -0
  108. package/scripts/checks.json +400 -26
  109. package/scripts/deliver.mjs +183 -0
  110. package/scripts/lib/._chrome-pipe.mjs +0 -0
  111. package/scripts/lib/._geometry-kernel.mjs +0 -0
  112. package/scripts/lib/chrome-pipe.mjs +95 -0
  113. package/scripts/lib/geometry-kernel.mjs +137 -0
  114. package/scripts/shell-probe.mjs +283 -0
  115. package/scripts/storyboard.mjs +350 -0
  116. package/.tbox/card-render/baseline/demo.png +0 -0
  117. package/.tbox/card-render/demo.html +0 -342
  118. package/.tbox/card-render/demo.png +0 -0
  119. package/.tbox/card-render/scale-demo.audit.html +0 -984
  120. package/.tbox/card-render/scale-demo.html +0 -939
  121. package/.tbox/evidence/cards.txt +0 -1
  122. package/.tbox/evidence/gate.json +0 -1
  123. package/.tbox/evidence/last-gate.json +0 -1
  124. package/.tbox/evidence/scenarios.json +0 -1
  125. package/apps/client/.tbox-gen/app-registry.ts +0 -3
  126. package/apps/client/.tbox-gen/documents/_tbox/card-preview.html +0 -62
  127. package/apps/client/.tbox-gen/documents/index.html +0 -63
  128. package/apps/client/.tbox-gen/entries/card-preview.tsx +0 -6
  129. package/apps/client/.tbox-gen/entries/index.tsx +0 -11
  130. package/apps/client/.tbox-gen/manifest.json +0 -17
  131. package/apps/client/.tbox-gen/registry.client.ts +0 -6
  132. package/apps/client/.tbox-gen/registry.server.ts +0 -15
  133. package/apps/client/STYLE_GUIDE.md +0 -48
  134. package/apps/client/VISUAL_RESTORE.md +0 -90
  135. package/profiles/mall/config/llm_provider.json +0 -5
  136. package/profiles/mall/config/plugins.json +0 -3
  137. package/scripts/compat-probe.mjs +0 -108
  138. package/scripts/gen-tailwind-sources.mjs +0 -55
  139. /package/.tbox/{card-render/._demo.html → factory/._chat.json} +0 -0
  140. /package/{.tbox/card-render/._demo.png → apps/client/scripts/._acceptance-changes.test.mjs} +0 -0
  141. /package/{.tbox/card-render/._scale-demo.audit.html → apps/client/scripts/._color-scan.mjs} +0 -0
  142. /package/{.tbox/card-render/._scale-demo.html → apps/client/scripts/._color-scan.test.mjs} +0 -0
  143. /package/{.tbox/card-render/baseline/._demo.png → apps/client/scripts/._evidence-gate.mjs} +0 -0
  144. /package/{.tbox/evidence/._cards.txt → apps/client/scripts/._evidence-gate.test.mjs} +0 -0
  145. /package/{.tbox/evidence/._gate.json → apps/client/scripts/._experience-checks.mjs} +0 -0
  146. /package/{.tbox/evidence/._last-gate.json → apps/client/scripts/._geometry-kernel.test.mjs} +0 -0
  147. /package/{.tbox/evidence/._scenarios.json → apps/client/scripts/._in-process-checks.mjs} +0 -0
  148. /package/apps/client/{._STYLE_GUIDE.md → scripts/._probe-checks.mjs} +0 -0
  149. /package/apps/client/{._VISUAL_RESTORE.md → scripts/._sample-entries.test.mjs} +0 -0
  150. /package/apps/client/{.tbox-gen/._app-registry.ts → scripts/._storyboard.test.mjs} +0 -0
  151. /package/apps/client/{.tbox-gen/._manifest.json → scripts/._surface-css.mjs} +0 -0
  152. /package/apps/client/{.tbox-gen/._registry.client.ts → scripts/._theme-kernel.mjs} +0 -0
  153. /package/apps/client/{.tbox-gen/._registry.server.ts → scripts/._theme-kernel.test.mjs} +0 -0
  154. /package/apps/client/{.tbox-gen/documents/._index.html → scripts/lib/._card-registry.mjs} +0 -0
  155. /package/apps/client/{.tbox-gen/documents/_tbox/._card-preview.html → scripts/lib/._card-registry.test.mjs} +0 -0
  156. /package/apps/client/{.tbox-gen/entries/._card-preview.tsx → scripts/lib/._evidence-inputs.mjs} +0 -0
  157. /package/apps/client/{.tbox-gen/entries/._index.tsx → scripts/lib/._evidence-inputs.test.mjs} +0 -0
  158. /package/{profiles/mall/config/._llm_provider.json → apps/client/scripts/lib/._static-render.mjs} +0 -0
  159. /package/{profiles/mall/config/._plugins.json → apps/client/scripts/lib/._static-render.test.mjs} +0 -0
  160. /package/{scripts/._compat-probe.mjs → packages/agent-ui-kit/src/._preview-provider.tsx} +0 -0
  161. /package/{scripts/._gen-tailwind-sources.mjs → packages/agent-ui-kit/src/._surface.test.tsx} +0 -0
@@ -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
+ }
@@ -40,14 +40,18 @@ interface ChatConfigStore {
40
40
  applyServerSettings: (settings: ChatUiSettings | undefined) => void;
41
41
  }
42
42
 
43
+ // SSR / 探针注入点:浏览器生产环境不设置,零影响(探针看不到配置会误判)。
44
+ const ssrSnapshot = ((globalThis as { __TBOX_CHAT_CONFIG__?: Record<string, unknown> }).__TBOX_CHAT_CONFIG__ ?? {});
43
45
  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: [],
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,
51
55
  retryOnError: true,
52
56
  applyServerSettings: (settings) =>
53
57
  set((cur) => ({
@@ -22,6 +22,8 @@ describe('DebugButton 平台契约(tbox:debug-trace 载荷锁定)', () => {
22
22
  let postSpy: ReturnType<typeof vi.fn>;
23
23
 
24
24
  beforeEach(() => {
25
+ // 调试入口只在显式 ?debug=1 下渲染(B5:dev 构建与 iframe 预览不再触发)
26
+ window.history.replaceState({}, '', '/?debug=1');
25
27
  host = document.createElement('div');
26
28
  document.body.appendChild(host);
27
29
  root = createRoot(host);
@@ -33,6 +35,7 @@ describe('DebugButton 平台契约(tbox:debug-trace 载荷锁定)', () => {
33
35
  afterEach(() => {
34
36
  act(() => root.unmount());
35
37
  host.remove();
38
+ window.history.replaceState({}, '', '/');
36
39
  });
37
40
 
38
41
  const clickDebug = () => {
@@ -11,13 +11,8 @@ import { Bug } from '@phosphor-icons/react';
11
11
  */
12
12
  function shouldShow(): boolean {
13
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
- }
14
+ // 只在显式调试请求下显示:dev 构建与 iframe 预览都不再触发(B5)。
15
+ return new URLSearchParams(window.location.search).get('debug') === '1';
21
16
  }
22
17
 
23
18
  export function DebugButton({
@@ -0,0 +1,90 @@
1
+ // @vitest-environment happy-dom
2
+ import { afterEach, describe, expect, it, vi } from 'vitest';
3
+ import { act } from 'react';
4
+ import { createRoot } from 'react-dom/client';
5
+ import type { Root } from 'react-dom/client';
6
+ import { BottomSheet } from './index';
7
+
8
+ let root: Root | undefined;
9
+ afterEach(async () => {
10
+ await act(async () => root?.unmount());
11
+ root = undefined;
12
+ document.body.innerHTML = '';
13
+ });
14
+
15
+ async function waitForDialog() {
16
+ for (let attempt = 0; attempt < 50; attempt += 1) {
17
+ const dialog = document.querySelector('[role="dialog"]');
18
+ if (dialog) return dialog;
19
+ await act(async () => {
20
+ await new Promise((resolve) => setTimeout(resolve, 0));
21
+ });
22
+ }
23
+ throw new Error('BottomSheet 懒加载后仍未挂载弹层');
24
+ }
25
+
26
+ async function renderSheet(open: boolean, onClose = vi.fn()) {
27
+ if (!root) {
28
+ const container = document.createElement('div');
29
+ document.body.append(container);
30
+ root = createRoot(container);
31
+ }
32
+ await act(async () => {
33
+ root!.render(<BottomSheet open={open} title="奖品详情" onClose={onClose}>
34
+ <button type="button">内容操作</button>
35
+ </BottomSheet>);
36
+ });
37
+ return onClose;
38
+ }
39
+
40
+ describe('BottomSheet', () => {
41
+ it('关闭态不挂载内容;打开通过 portal 展示命名对话框和业务内容', async () => {
42
+ await renderSheet(false);
43
+ expect(document.querySelector('[role="dialog"]')).toBeNull();
44
+ await renderSheet(true);
45
+ const dialog = await waitForDialog();
46
+ expect(dialog.getAttribute('aria-modal')).toBe('true');
47
+ expect(document.getElementById(dialog.getAttribute('aria-labelledby')!)?.textContent).toBe('奖品详情');
48
+ expect(dialog.textContent).toContain('内容操作');
49
+ });
50
+
51
+ it('关闭按钮与 Escape 请求受控关闭,卸载后恢复触发按钮焦点并清理监听', async () => {
52
+ const trigger = document.createElement('button');
53
+ document.body.append(trigger);
54
+ trigger.focus();
55
+ const onClose = await renderSheet(true);
56
+ await waitForDialog();
57
+ await act(async () => {
58
+ (document.querySelector('[aria-label="关闭奖品详情"]') as HTMLButtonElement).click();
59
+ });
60
+ expect(onClose).toHaveBeenCalledTimes(1);
61
+ await act(async () => document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })));
62
+ expect(onClose).toHaveBeenCalledTimes(2);
63
+ await act(async () => root?.unmount());
64
+ root = undefined;
65
+ expect(document.activeElement).toBe(trigger);
66
+ document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
67
+ expect(onClose).toHaveBeenCalledTimes(2);
68
+ });
69
+
70
+ it('Tab 与 Shift+Tab 在弹层内循环,不落到背景页面', async () => {
71
+ await renderSheet(true);
72
+ await waitForDialog();
73
+ const close = document.querySelector('[aria-label="关闭奖品详情"]') as HTMLButtonElement;
74
+ const last = document.querySelector('.tbox-bottom-sheet__body button') as HTMLButtonElement;
75
+ last.focus();
76
+ document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Tab', cancelable: true }));
77
+ expect(document.activeElement).toBe(close);
78
+ document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Tab', shiftKey: true, cancelable: true }));
79
+ expect(document.activeElement).toBe(last);
80
+ });
81
+
82
+ it('遮罩点击请求关闭,内容点击不关闭', async () => {
83
+ const onClose = await renderSheet(true);
84
+ await waitForDialog();
85
+ await act(async () => (document.querySelector('.tbox-bottom-sheet__body button') as HTMLButtonElement).click());
86
+ expect(onClose).not.toHaveBeenCalled();
87
+ await act(async () => (document.querySelector('.adm-mask') as HTMLElement).click());
88
+ expect(onClose).toHaveBeenCalledTimes(1);
89
+ });
90
+ });
@@ -0,0 +1,129 @@
1
+ import { useEffect, useId, useRef, useState } from 'react';
2
+ import type { ComponentType, ReactNode } from 'react';
3
+ import type { PopupProps } from 'antd-mobile';
4
+
5
+ export interface BottomSheetProps {
6
+ open: boolean;
7
+ title: string;
8
+ onClose: () => void;
9
+ children: ReactNode;
10
+ /** 内容容器的业务样式;弹层外壳由组件统一管理。 */
11
+ className?: string;
12
+ }
13
+
14
+ type PopupComponent = ComponentType<PopupProps>;
15
+
16
+ /**
17
+ * antd-mobile 带 CSS 的运行时依赖只在浏览器按需加载:kit 源码在 Node/Vite SSR 里可直接 import
18
+ * (静态 import 会让 Node 读到 CJS 入口 require 的 global.css,整条证据链/SSR 消费者失败)。
19
+ * 失败时清空缓存,允许下一次交互重试。
20
+ */
21
+ let popupPromise: Promise<PopupComponent> | undefined;
22
+
23
+ export function preloadBottomSheet(): Promise<ComponentType<PopupProps>> {
24
+ popupPromise ??= import('antd-mobile')
25
+ .then((module) => module.Popup as PopupComponent)
26
+ .catch((error: unknown) => {
27
+ popupPromise = undefined;
28
+ throw error;
29
+ });
30
+ return popupPromise;
31
+ }
32
+
33
+ /** 受控底部弹层:业务只提供内容与开关,不自行处理遮罩、滚动和焦点。 */
34
+ export function BottomSheet({ open, title, onClose, children, className }: BottomSheetProps) {
35
+ const titleId = useId();
36
+ const panelRef = useRef<HTMLDivElement>(null);
37
+ const closeRef = useRef<HTMLButtonElement>(null);
38
+ const onCloseRef = useRef(onClose);
39
+ onCloseRef.current = onClose;
40
+ const [Popup, setPopup] = useState<PopupComponent | null>(null);
41
+
42
+ useEffect(() => {
43
+ if (Popup) return;
44
+ let alive = true;
45
+ preloadBottomSheet()
46
+ .then((loaded) => {
47
+ if (alive) setPopup(() => loaded);
48
+ })
49
+ .catch((error: unknown) => {
50
+ // 一次 chunk 失败不应静默:保留可诊断信息;open 变化会再次进入本 effect 重试(promise 已清空)。
51
+ console.warn('BottomSheet: antd-mobile Popup 加载失败', error);
52
+ });
53
+ return () => {
54
+ alive = false;
55
+ };
56
+ }, [open, Popup]);
57
+
58
+ // 懒加载窗口:弹层未就绪时先挡住背景交互(无遮罩会让「模态」破窗)。
59
+ useEffect(() => {
60
+ if (!open || Popup) return;
61
+ const previous = document.body.style.overflow;
62
+ document.body.style.overflow = 'hidden';
63
+ return () => {
64
+ document.body.style.overflow = previous;
65
+ };
66
+ }, [open, Popup]);
67
+
68
+ useEffect(() => {
69
+ if (!open) return;
70
+ const previous = document.activeElement;
71
+ const onKeyDown = (event: KeyboardEvent) => {
72
+ if (event.key === 'Escape') {
73
+ event.preventDefault();
74
+ event.stopPropagation();
75
+ onCloseRef.current();
76
+ }
77
+ if (event.key !== 'Tab' || !panelRef.current) return;
78
+ const focusable = [...panelRef.current.querySelectorAll<HTMLElement>(
79
+ 'button:not(:disabled), a[href], input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex="0"]',
80
+ )].filter((element) => !element.hidden && element.getAttribute('aria-hidden') !== 'true');
81
+ const first = focusable[0];
82
+ const last = focusable[focusable.length - 1];
83
+ if (!first || !last) return;
84
+ const active = document.activeElement;
85
+ if (event.shiftKey && (active === first || !panelRef.current.contains(active))) {
86
+ event.preventDefault();
87
+ last.focus();
88
+ } else if (!event.shiftKey && (active === last || !panelRef.current.contains(active))) {
89
+ event.preventDefault();
90
+ first.focus();
91
+ }
92
+ };
93
+ document.addEventListener('keydown', onKeyDown);
94
+ return () => {
95
+ document.removeEventListener('keydown', onKeyDown);
96
+ if (previous instanceof HTMLElement && previous.isConnected) previous.focus();
97
+ };
98
+ }, [open]);
99
+
100
+ // Popup 晚于 open 就绪时 afterShow 不保证触发,这里补一次显式聚焦。
101
+ useEffect(() => {
102
+ if (!open || !Popup) return;
103
+ const timer = window.setTimeout(() => closeRef.current?.focus(), 0);
104
+ return () => window.clearTimeout(timer);
105
+ }, [open, Popup]);
106
+
107
+ if (!Popup) {
108
+ return open ? <div className="fixed inset-0 z-[1100] bg-scrim" role="presentation" aria-hidden="true" /> : null;
109
+ }
110
+
111
+ return (
112
+ <Popup className="motion-reduce:[&_.adm-popup-body]:transition-none motion-reduce:[&_.adm-mask]:transition-none" visible={open} position="bottom" onClose={onClose} closeOnMaskClick
113
+ destroyOnClose disableBodyScroll bodyClassName="tbox-bottom-sheet mx-auto w-full overflow-hidden rounded-t-[14px] bg-card text-foreground"
114
+ style={{ '--z-index': '1100' }} afterShow={() => closeRef.current?.focus()}>
115
+ <div ref={panelRef} className="tbox-bottom-sheet__panel flex max-h-[65vh] flex-col supports-[height:100dvh]:max-h-[65dvh]" role="dialog"
116
+ aria-modal="true" aria-labelledby={titleId}>
117
+ <header className="tbox-bottom-sheet__header flex shrink-0 items-center justify-between gap-3 px-3.5 py-3">
118
+ <h2 id={titleId} className="m-0 text-base font-semibold leading-[21px]">{title}</h2>
119
+ <button className="flex size-9 shrink-0 cursor-pointer items-center justify-center rounded-full border-0 bg-transparent p-1.5 text-inherit focus-visible:outline-2 focus-visible:outline-primary" ref={closeRef} type="button" aria-label={`关闭${title}`} onClick={onClose}>
120
+ <svg className="size-4.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
121
+ <path d="m6 6 12 12M6 18 18 6" />
122
+ </svg>
123
+ </button>
124
+ </header>
125
+ <div className={['tbox-bottom-sheet__body min-h-0 overflow-y-auto overscroll-contain px-3.5 pt-0 pb-[calc(16px+env(safe-area-inset-bottom))] text-sm leading-[19px]', className].filter(Boolean).join(' ')}>{children}</div>
126
+ </div>
127
+ </Popup>
128
+ );
129
+ }
@@ -83,9 +83,9 @@ describe('ChatInput 语音活动状态', () => {
83
83
  });
84
84
 
85
85
  describe('ChatInput 派生模式(服务端 defaultInputMode 水合)', () => {
86
- /** voice 态投影:录音模式显示"键盘"切换图标;text 态显示"语音"切换图标 */
86
+ /** voice 态投影:录音模式的可访问名为「切换到键盘输入」;text 态为「切换到语音输入」 */
87
87
  const inVoiceMode = (container: HTMLElement) =>
88
- container.querySelector('img[alt="键盘"]') !== null;
88
+ container.querySelector('.tbox-voice-toggle[aria-label="切换到键盘输入"]') !== null;
89
89
 
90
90
  const renderInput = async (root: ReturnType<typeof createRoot>) => {
91
91
  await act(async () => root.render(<ChatInput onSend={vi.fn()} />));
@@ -190,9 +190,9 @@ export function ChatInput({
190
190
 
191
191
  <div className="tbox-chat-input__row flex flex-wrap items-end gap-2">
192
192
  {onNewChat && (
193
- <div className="tbox-new-chat-btn flex size-11 shrink-0 items-center justify-center rounded-full bg-[rgba(255,255,255,0.5)] shadow-[0_1px_10px_rgba(110,139,180,0.24)]" onClick={onNewChat}>
194
- <img className="tbox-new-chat-btn__icon size-[22px]" src={newChatIcon} alt="新对话" />
195
- </div>
193
+ <button type="button" data-tbox-control="new-chat" aria-label="新建对话" className="tbox-new-chat-btn flex size-11 shrink-0 cursor-pointer appearance-none items-center justify-center rounded-full border-0 bg-[rgba(255,255,255,0.5)] p-0 shadow-[0_1px_10px_rgba(110,139,180,0.24)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary" onClick={onNewChat}>
194
+ <img className="tbox-new-chat-btn__icon size-[22px]" src={newChatIcon} alt="" />
195
+ </button>
196
196
  )}
197
197
 
198
198
  <div className="tbox-chat-input__wrapper flex min-w-0 flex-1 items-end gap-[14px] rounded-[var(--tbox-input-radius)] border border-border bg-[var(--tbox-input-bg)] p-[var(--tbox-input-padding)] shadow-[0_1px_10px_rgba(110,139,180,0.24)] transition-[border-color,box-shadow] duration-[var(--tbox-motion-duration-fast)] ease-[var(--tbox-motion-easing-standard)] focus-within:border-primary focus-within:shadow-[0_0_0_1.5px_rgba(9,107,250,0.12)]">
@@ -208,7 +208,7 @@ export function ChatInput({
208
208
  />
209
209
  ) : (
210
210
  <textarea
211
- className="tbox-chat-input__field min-w-0 flex-1 resize-none border-0 bg-transparent p-0 text-base leading-[24px] text-foreground outline-none max-h-[100px] [font-family:inherit] placeholder:text-muted-foreground disabled:opacity-[0.45]"
211
+ className="tbox-chat-input__field min-h-11 min-w-0 flex-1 resize-none border-0 bg-transparent p-0 text-base leading-[24px] text-foreground outline-none max-h-[100px] [font-family:inherit] placeholder:text-muted-foreground disabled:opacity-[0.45]"
212
212
  value={text}
213
213
  placeholder={blocked?.message ?? '有什么需要问我的吗'}
214
214
  rows={1}
@@ -224,31 +224,36 @@ export function ChatInput({
224
224
  )}
225
225
 
226
226
  {enableVoice && (
227
- <div className="tbox-voice-toggle flex size-[22px] shrink-0 items-center justify-center" onClick={toggleMode}>
227
+ <button type="button" data-tbox-control="voice-toggle" aria-label={inputMode === 'voice' ? '切换到键盘输入' : '切换到语音输入'} aria-pressed={inputMode === 'voice'} className="tbox-voice-toggle flex size-11 -m-[11px] shrink-0 cursor-pointer appearance-none items-center justify-center border-0 bg-transparent p-0 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary" onClick={toggleMode}>
228
228
  <img
229
229
  className="tbox-voice-toggle__icon size-[22px]"
230
230
  src={inputMode === 'voice' ? keyboardIcon : voiceIcon}
231
- alt={inputMode === 'voice' ? '键盘' : '语音'}
231
+ alt=""
232
232
  />
233
- </div>
233
+ </button>
234
234
  )}
235
235
 
236
236
  {blocked ? null : generating ? (
237
- <div className="tbox-chat-input__send tbox-chat-input__send--active flex size-[var(--tbox-send-btn-size)] shrink-0 items-center justify-center" onClick={onCancel}>
238
- <img className="tbox-chat-input__send-img block size-[var(--tbox-send-btn-size)]" src={stopIcon} alt="停止" />
239
- </div>
237
+ <button type="button" data-tbox-control="stop" aria-label="停止生成" className="tbox-chat-input__send tbox-chat-input__send--active flex size-11 -m-[11px] shrink-0 cursor-pointer appearance-none items-center justify-center border-0 bg-transparent p-0 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary" onClick={onCancel}>
238
+ <img className="tbox-chat-input__send-img block size-[var(--tbox-send-btn-size)]" src={stopIcon} alt="" />
239
+ </button>
240
240
  ) : canSend ? (
241
- <div className="tbox-chat-input__send tbox-chat-input__send--active flex size-[var(--tbox-send-btn-size)] shrink-0 items-center justify-center" onClick={submit}>
242
- <img className="tbox-chat-input__send-img block size-[var(--tbox-send-btn-size)]" src={sendIcon} alt="发送" />
243
- </div>
241
+ <button type="button" data-tbox-control="send" aria-label="发送" className="tbox-chat-input__send tbox-chat-input__send--active flex size-11 -m-[11px] shrink-0 cursor-pointer appearance-none items-center justify-center border-0 bg-transparent p-0 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary" onClick={submit}>
242
+ <img className="tbox-chat-input__send-img block size-[var(--tbox-send-btn-size)]" src={sendIcon} alt="" />
243
+ </button>
244
244
  ) : menuOptions.length > 0 ? (
245
245
  <div className="tbox-media-picker relative shrink-0">
246
- <div
247
- className={`tbox-media-picker__trigger flex shrink-0 items-center justify-center transition-transform duration-[var(--tbox-motion-duration-base)] ease-[ease] ${menuVisible ? ' tbox-media-picker__trigger--open rotate-45' : ''}`}
246
+ <button
247
+ type="button"
248
+ data-tbox-control="media-add"
249
+ aria-label="添加图片或视频"
250
+ aria-haspopup="menu"
251
+ aria-expanded={menuVisible}
252
+ className={`tbox-media-picker__trigger flex size-11 -m-[11px] shrink-0 cursor-pointer appearance-none items-center justify-center border-0 bg-transparent p-0 transition-transform duration-[var(--tbox-motion-duration-base)] ease-[ease] ${menuVisible ? ' tbox-media-picker__trigger--open rotate-45' : ''}`}
248
253
  onClick={onPlus}
249
254
  >
250
- <img className="tbox-media-picker__trigger-icon size-[var(--tbox-send-btn-size)]" src={moreIcon} alt="更多" />
251
- </div>
255
+ <img className="tbox-media-picker__trigger-icon size-[var(--tbox-send-btn-size)]" src={moreIcon} alt="" />
256
+ </button>
252
257
  </div>
253
258
  ) : null}
254
259
  </div>
@@ -29,11 +29,12 @@ export default function HistoryEntry({
29
29
  <div className="history-entry flex justify-center p-0">
30
30
  <button
31
31
  type="button"
32
- className="history-entry__button inline-flex appearance-none items-center gap-[5px] rounded-[25px] border-0 bg-[rgba(15,64,113,0.06)] px-3 py-[3px] text-xs font-normal leading-[16px] text-muted-foreground transition-[background] duration-[var(--tbox-motion-duration-fast)] ease-[var(--tbox-motion-easing-standard)] [font-family:inherit] active:bg-[rgba(15,64,113,0.1)] disabled:cursor-default"
32
+ data-tbox-control="history"
33
+ className="history-entry__button inline-flex min-h-11 appearance-none items-center gap-[5px] rounded-[25px] border-0 bg-muted px-4 py-1 text-sm font-normal leading-[18px] text-muted-foreground transition-colors duration-[var(--tbox-motion-duration-fast)] ease-[var(--tbox-motion-easing-standard)] [font-family:inherit] active:bg-border disabled:cursor-default"
33
34
  disabled={disabled}
34
35
  onClick={onLoad}
35
36
  >
36
- {(loading || pullStatus === 'loading') && <span className="history-entry__spinner size-[10px] rounded-full border-[1.5px] border-[rgba(15,64,113,0.18)] border-t-primary animate-[history-entry-spin_0.6s_linear_infinite]" />}
37
+ {(loading || pullStatus === 'loading') && <span className="history-entry__spinner size-[10px] rounded-full border-[1.5px] border-border border-t-primary animate-[history-entry-spin_0.6s_linear_infinite]" />}
37
38
  {labelOf(pullStatus, loading)}
38
39
  </button>
39
40
  </div>