@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,85 @@
1
+ /**
2
+ * 布局 / 运行时探针结果合并器(checks.json 的 source=experience + phase=probe)。
3
+ *
4
+ * 探针本身在 scripts/shell-probe.mjs;这里只按 checks.json 的 id 取结果、处理档位/过期/协议。
5
+ * 新增探针检查 = checks.json 一行 + PROBE_CHECKS 一段 + shell-probe 一条断言。
6
+ */
7
+ export const PROBE_CHECKS = {
8
+ 'shell.hit-target': { lane: 'layout', title: '命中区 ≥44×44' },
9
+ 'shell.quick-visible': { lane: 'layout', title: '空态快捷问题可见' },
10
+ 'shell.icon-render': { lane: 'layout', title: '快捷问题图标可见' },
11
+ 'shell.controls-semantic': { lane: 'layout', title: '控件为语义按钮' },
12
+ 'shell.control-present': { lane: 'layout', title: '能力开启时控件在场' },
13
+ 'shell.a11y-name': { lane: 'layout', title: '控件有可访问名' },
14
+ 'shell.blank': { lane: 'layout', title: '首屏块间空白 ≤35%' },
15
+ 'shell.turn-visible': { lane: 'runtime', title: '新回合问题在视口内' },
16
+ 'shell.console-clean': { lane: 'runtime', title: '控制台无告警' },
17
+ };
18
+
19
+ /**
20
+ * 故事板检查(storyboard.json):帧级几何问题的聚合。
21
+ *
22
+ * 与探针的区别:探针的每条检查在浏览器里各自判定;故事板的判定在渲染时就写进帧的 problems,
23
+ * 这里只按 id 取第一条即可——判据留在内核一处,门禁不重算几何。
24
+ */
25
+ export const STORYBOARD_CHECKS = {
26
+ 'storyboard.render': { lane: 'layout', title: '故事板渲染完成' },
27
+ 'card.overflow-x': { lane: 'layout', title: '卡片无横向溢出' },
28
+ 'card.text-clip': { lane: 'layout', title: '文本截断带省略号' },
29
+ 'card.tap-target': { lane: 'layout', title: '卡片点击区 ≥44px' },
30
+ 'card.min-font': { lane: 'layout', title: '卡片最小字号 ≥12px' },
31
+ };
32
+
33
+ export function mergeStoryboardChecks({ storyboard, ids, policy, stale = '', cardCount = 0 }) {
34
+ const frames = Array.isArray(storyboard?.frames) ? storyboard.frames : [];
35
+ const notRun = (meta, reason) => ({ status: 'deferred', detail: '未运行 ' + meta.title + ':' + reason });
36
+ return ids.map((id) => {
37
+ const meta = STORYBOARD_CHECKS[id] ?? { lane: 'layout', title: id };
38
+ if (policy === 'static') return { id, lane: meta.lane, ...notRun(meta, '档位 static 不要求布局车道') };
39
+ if (!storyboard) return { id, lane: meta.lane, ...notRun(meta, stale || 'pnpm storyboard 未产出结果') };
40
+ if (storyboard.status === 'not-run') return { id, lane: meta.lane, ...notRun(meta, storyboard.reason || 'storyboard 记 not-run') };
41
+ if (frames.length === 0) return { id, lane: meta.lane, ...notRun(meta, '没有生成任何帧') };
42
+
43
+ if (id === 'storyboard.render') {
44
+ const failed = frames.filter((frame) => frame.error);
45
+ if (failed.length > 0) {
46
+ return { id, lane: meta.lane, status: 'fail', detail: failed.length + '/' + frames.length + ' 帧未渲染:' + failed.slice(0, 2).map((frame) => frame.id + '(' + frame.error + ')').join(';') };
47
+ }
48
+ if (storyboard.status === 'partial') return { id, lane: meta.lane, status: 'fail', detail: '故事板未跑完:' + (storyboard.reason || '超过预算') };
49
+ const planned = Number(storyboard.planned ?? frames.length);
50
+ const scope = planned > frames.length ? frames.length + '/' + planned + ' 帧(预算/页数截断,已渲染帧全部通过)' : frames.length + ' 帧';
51
+ return { id, lane: meta.lane, status: 'pass', detail: scope + '(' + [...new Set(frames.map((frame) => frame.width))].sort((a, b) => a - b).join('/') + ' 宽)' };
52
+ }
53
+
54
+ const cardFrames = frames.filter((frame) => frame.source === 'card-samples');
55
+ if (id !== 'storyboard.render' && cardCount === 0) return { id, lane: meta.lane, ...notRun(meta, '应用没有卡片') };
56
+ const hits = [];
57
+ for (const frame of frames) {
58
+ for (const problem of frame.problems ?? []) if (problem.id === id) hits.push(problem.detail);
59
+ }
60
+ if (hits.length > 0) return { id, lane: meta.lane, status: 'fail', detail: hits.length + ' 处:' + hits.slice(0, 3).join(';') };
61
+ return { id, lane: meta.lane, status: 'pass', detail: (cardFrames.length > 0 ? cardFrames.length + ' 个卡片帧' : frames.length + ' 个壳帧') + '无问题' };
62
+ });
63
+ }
64
+
65
+ export function mergeProbeChecks({ probe, ids, policy, stale = '' }) {
66
+ const skipped = String(stale).includes('协议版本');
67
+ return ids.map((id) => {
68
+ const meta = PROBE_CHECKS[id] ?? { lane: 'layout', title: id };
69
+ if (policy === 'static') {
70
+ return { id, lane: meta.lane, status: 'deferred', detail: '未运行 ' + meta.title + ':档位 static 不要求布局/运行时' };
71
+ }
72
+ const found = Array.isArray(probe?.items) ? probe.items.find((item) => item.id === id) : undefined;
73
+ if (found) {
74
+ return { id, lane: found.lane ?? meta.lane, status: found.status === 'not-run' ? 'deferred' : found.status, detail: found.detail };
75
+ }
76
+ return {
77
+ id,
78
+ lane: meta.lane,
79
+ status: skipped ? 'skip' : 'deferred',
80
+ detail: skipped
81
+ ? meta.title + ':' + stale
82
+ : (stale ? '未运行 ' + meta.title + ':' + stale : '未运行 ' + meta.title + ':pnpm probe:shell 未产出结果'),
83
+ };
84
+ });
85
+ }
@@ -3,9 +3,9 @@
3
3
  * render-card — 用真实客户端组件渲染一张卡(F9)。
4
4
  *
5
5
  * 加载方式与 check:fast 的证据包完全一致:不读应用 vite.config.ts,直接
6
- * `createServer({ configFile: false, root: apps/client, plugins: [react()] })`,
6
+ * `createServer({ configFile: false, root: apps/client, plugins: [tailwindcss(), react()] })`,
7
7
  * 再用 `ssrLoadModule` 同时加载客户端卡片注册表与服务端卡片 meta(样例的静态真源)。
8
- * 这样别名、TSX、less 与 store 垫片都与构建态同源,却零端口、零浏览器。
8
+ * 样式与 dev/build 同一条管线(surface-css.mjs):没有 Less、没有 rem 换算、没有固定根字号。
9
9
  *
10
10
  * 用法:
11
11
  * node scripts/render-card.mjs --type <cardType> [--sample <label|序号>] [--all] [--outline] [--audit] [--screenshot] [--baseline] [--json]
@@ -19,8 +19,12 @@
19
19
  */
20
20
  import { createRequire } from 'node:module';
21
21
  import { copyFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
22
+ import { createServer as createHttpServer } from 'node:http';
23
+ import { buildSurfaceCss, SURFACE_CSS_SENTINELS } from './surface-css.mjs';
24
+ import { geometryFunctionSource } from '../../../scripts/lib/geometry-kernel.mjs';
22
25
  import { execFileSync } from 'node:child_process';
23
26
  import path from 'node:path';
27
+ import { fileURLToPath } from 'node:url';
24
28
  import process from 'node:process';
25
29
 
26
30
  const appDir = path.resolve(import.meta.dirname, '..', '..', '..');
@@ -98,7 +102,7 @@ function usageError(message) {
98
102
  }
99
103
 
100
104
  // ── 1. 启动 Vite(与 check-evidence 同一条加载路径) ─────────────────
101
- async function loadVite() {
105
+ export async function loadVite() {
102
106
  let createServer;
103
107
  let react;
104
108
  let tailwindcss;
@@ -122,15 +126,21 @@ async function loadVite() {
122
126
  '@config': path.join(appDir, 'config'),
123
127
  },
124
128
  },
125
- server: { middlewareMode: true, fs: { allow: [appDir] } },
129
+ // 零 socket:给 Vite 一个永不 listen 的 http server 承载 HMR 升级,避免自建 24678 监听。
130
+ server: { middlewareMode: true, hmr: { server: createHttpServer() }, fs: { allow: [appDir] } },
126
131
  optimizeDeps: { noDiscovery: true, include: [] },
132
+ // SSR 加载客户端 registry 时,依赖里带 CSS 的包必须交给 Vite 内联处理:
133
+ // Node 直连 antd-mobile 的 CJS 入口会 require 它自己的 global.css,直接 SyntaxError。
134
+ // 新增同类运行时依赖(带 CSS 副作用)时补进这张名单,否则 registry 步骤会在
135
+ // 模块客户端代码 import 到它时报「Unexpected token ':'」。
136
+ ssr: { noExternal: ['antd-mobile'] },
127
137
  });
128
138
  } catch (error) {
129
139
  throw new Error(`Vite 启动失败:${error?.message ?? error}\n 修复:检查依赖安装与 apps/client/.tbox-gen(pnpm generate)`);
130
140
  }
131
141
  }
132
142
 
133
- async function loadRegistry(vite) {
143
+ export async function loadRegistry(vite) {
134
144
  let client;
135
145
  let server;
136
146
  try {
@@ -146,58 +156,10 @@ async function loadRegistry(vite) {
146
156
  return { client, server };
147
157
  }
148
158
 
149
- // ── 2. 样式(best-effort:编译失败不阻塞渲染,只少视觉样式) ──────────
150
- const pxToRem = (css) =>
151
- css.replace(/(\d+(?:\.\d+)?)px/g, (match, value) => (Number(value) >= 2 ? `${Number(value) / 100}rem` : match));
152
-
153
- function inlineCssImports(css, baseDir, depth = 0) {
154
- if (depth > 4) return css;
155
- return css.replace(/@import\s+(?:url\()?['"]\.\/([^'")]+)['"]\)?\s*;/g, (_match, name) => {
156
- const file = path.join(baseDir, name);
157
- if (!existsSync(file)) return '';
158
- return inlineCssImports(readFileSync(file, 'utf8'), path.dirname(file), depth + 1);
159
- });
160
- }
161
-
162
- async function buildStyleSheet(vite) {
163
- let less;
164
- try {
165
- less = (await import('less')).default;
166
- } catch {
167
- return '';
168
- }
169
- const require = createRequire(path.join(clientDir, 'package.json'));
170
- const resolveOptional = (id) => {
171
- try {
172
- return require.resolve(id);
173
- } catch {
174
- return undefined;
175
- }
176
- };
177
- const compileLess = async (file) => {
178
- if (!file || !existsSync(file)) return '';
179
- try {
180
- const out = await less.render(readFileSync(file, 'utf8'), { filename: file, javascriptEnabled: true });
181
- return pxToRem(out.css);
182
- } catch {
183
- return '';
184
- }
185
- };
186
- const chunks = [];
187
- const kitGlobal = resolveOptional('@tbox.cn/app-agent-ui-kit/theme/base.css');
188
- chunks.push(await compileLess(kitGlobal));
189
- const themeEntry = resolveOptional('@tbox.cn/app-theme-tbox/index.css');
190
- if (themeEntry) chunks.push(pxToRem(inlineCssImports(readFileSync(themeEntry, 'utf8'), path.dirname(themeEntry))));
191
- chunks.push(await compileLess(path.join(clientDir, 'src/styles/brand.less')));
192
- const kitPkg = resolveOptional('@tbox.cn/app-agent-ui-kit/package.json');
193
- if (kitPkg) chunks.push(await compileLess(path.join(path.dirname(kitPkg), 'src/card/primitives.less')));
194
- try {
195
- const tailwind = await vite.ssrLoadModule('/src/styles/tailwind.css?inline');
196
- if (tailwind?.default) chunks.push(tailwind.default);
197
- } catch {
198
- // 旧模板可能没有 Tailwind 入口:保持已有样式
199
- }
200
- return chunks.filter(Boolean).join('\n');
159
+ // ── 2. 样式:与 dev/build 同一条 Vite + Tailwind 管线 ────────────────
160
+ export async function buildStyleSheet(vite) {
161
+ const { cssText, bytes, missing } = await buildSurfaceCss(vite, { clientDir, appDir });
162
+ return { css: cssText, bytes, missing };
201
163
  }
202
164
 
203
165
  function buildHtmlDocument(cardHtml, css) {
@@ -208,7 +170,6 @@ function buildHtmlDocument(cardHtml, css) {
208
170
  <meta name="viewport" content="width=device-width, initial-scale=1">
209
171
  <title>tbox card render</title>
210
172
  <style>
211
- html { font-size: 50px; }
212
173
  body { margin: 0; background: #f5f6f7; color: #1f1f1f; font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif; }
213
174
  /* 左对齐固定 8px:无头 Chrome 有最小窗口宽(约 500),居中会被 420 截图裁掉右缘。 */
214
175
  .tbox-card-render { width: 375px; max-width: calc(100% - 16px); margin: 16px 8px; }
@@ -417,21 +378,37 @@ function buildOutline(cardType, label, cardHtml) {
417
378
  }
418
379
 
419
380
  // ── 4. 渲染 ──────────────────────────────────────────────────────────
420
- function sampleEntries(meta) {
381
+ export function sampleEntries(meta, { includeHidden = true } = {}) {
421
382
  const samples = [];
422
- if (meta.sampleData !== undefined) samples.push({ label: 'sampleData', note: undefined, data: meta.sampleData });
383
+ if (meta.sampleData !== undefined) samples.push({ label: 'sampleData', note: undefined, data: meta.sampleData, isHistory: false, noTokens: false, hidden: false });
423
384
  if (Array.isArray(meta.samples)) {
424
385
  meta.samples.forEach((entry, index) => {
386
+ if (entry?.hidden === true && !includeHidden) return;
425
387
  samples.push({
426
388
  label: typeof entry?.label === 'string' ? entry.label : `samples[${index}]`,
427
389
  note: typeof entry?.note === 'string' ? entry.note : undefined,
390
+ group: typeof entry?.group === 'string' ? entry.group : undefined,
428
391
  data: entry?.data,
392
+ isHistory: entry?.isHistory === true,
393
+ noTokens: entry?.noTokens === true,
394
+ hidden: entry?.hidden === true,
429
395
  });
430
396
  });
431
397
  }
432
398
  return samples;
433
399
  }
434
400
 
401
+ /** 同卡样例 label 重复检测:label 是故事板帧键与渲染文件名的一部分,重复会静默覆盖证据。 */
402
+ export function duplicateSampleLabels(meta, { includeHidden = true } = {}) {
403
+ const seen = new Set();
404
+ const duplicates = new Set();
405
+ for (const sample of sampleEntries(meta, { includeHidden })) {
406
+ if (seen.has(sample.label)) duplicates.add(sample.label);
407
+ seen.add(sample.label);
408
+ }
409
+ return [...duplicates];
410
+ }
411
+
435
412
  function selectSamples(samples, args) {
436
413
  if (samples.length === 0) return [];
437
414
  if (args.all) return samples;
@@ -448,7 +425,7 @@ function selectSamples(samples, args) {
448
425
 
449
426
  const slug = (label) => label.replace(/[^\p{L}\p{N}._-]+/gu, '-').replace(/^-+|-+$/g, '') || 'sample';
450
427
 
451
- async function renderSamples(vite, registries, cardType, samples) {
428
+ export async function renderSamples(vite, registries, cardType, samples) {
452
429
  const meta = registries.server?.cards?.[cardType];
453
430
  const components = registries.client?.cards ?? {};
454
431
  const Component = components[cardType];
@@ -460,16 +437,12 @@ async function renderSamples(vite, registries, cardType, samples) {
460
437
  }
461
438
  const React = (await import('react')).default;
462
439
  const { renderToStaticMarkup } = await import('react-dom/server');
463
- const { createStore } = await import('zustand/vanilla');
464
- const { useStore } = await import('zustand');
440
+ const { createStaticRenderer } = await import('./lib/static-render.mjs');
441
+ const staticRender = createStaticRenderer(renderToStaticMarkup);
465
442
  const kit = await vite.ssrLoadModule('@tbox.cn/app-agent-ui-kit');
466
443
 
467
- // 卡片预览的内存 store(与 check-evidence 同构:动作不落库,isGenerating=false)
468
- const store = createStore(() => ({ sendUiAction() {}, isGenerating: false }));
469
- const hook = (selector) => useStore(store, selector);
470
- hook.getState = store.getState;
471
- hook.setState = store.setState;
472
- hook.subscribe = store.subscribe;
444
+ // 与 check:fast / 预览同一条装配(SurfaceHarness):动作不落库、isGenerating=false。
445
+ const harness = kit.createSurfaceHarness({ cards: components });
473
446
 
474
447
  const rendered = [];
475
448
  for (const sample of samples) {
@@ -477,11 +450,9 @@ async function renderSamples(vite, registries, cardType, samples) {
477
450
  const schemaValid = parsed ? parsed.success : true;
478
451
  let html;
479
452
  try {
480
- html = renderToStaticMarkup(
481
- React.createElement(
482
- kit.KitChatProvider,
483
- { store: hook, cards: components, rawCards: components },
484
- React.createElement(Component, { data: parsed?.success ? parsed.data : sample.data, cardId: `render-${cardType}`, isHistory: false, actionTokens: {} }),
453
+ html = staticRender.render(
454
+ harness.wrap(
455
+ React.createElement(Component, { data: parsed?.success ? parsed.data : sample.data, cardId: `render-${cardType}`, isHistory: sample.isHistory === true, actionTokens: {} }),
485
456
  ),
486
457
  );
487
458
  } catch (error) {
@@ -503,6 +474,9 @@ async function renderSamples(vite, registries, cardType, samples) {
503
474
  // ── 视觉体检(F12,可选层:需要无头浏览器) ──────────────────────
504
475
  const CHROME_CANDIDATES = [
505
476
  process.env.TBOX_CHROME,
477
+ // 平台沙箱:Chrome for Testing 由镜像安装,路径只在 AGENT_BROWSER_EXECUTABLE_PATH 暴露。
478
+ process.env.AGENT_BROWSER_EXECUTABLE_PATH,
479
+ '/home/admin/.agent-browser/chrome/chrome-linux64/chrome',
506
480
  '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
507
481
  '/Applications/Chromium.app/Contents/MacOS/Chromium',
508
482
  '/usr/bin/google-chrome',
@@ -511,6 +485,7 @@ const CHROME_CANDIDATES = [
511
485
  '/usr/bin/chromium-browser',
512
486
  ].filter(Boolean);
513
487
 
488
+ let chromeLookupError = '';
514
489
  function findChrome() {
515
490
  for (const candidate of CHROME_CANDIDATES) if (existsSync(candidate)) return candidate;
516
491
  for (const name of ['chromium', 'google-chrome', 'chrome']) {
@@ -521,48 +496,27 @@ function findChrome() {
521
496
  // 继续找
522
497
  }
523
498
  }
499
+ chromeLookupError = '已尝试:' + CHROME_CANDIDATES.join('、') + ' 与 PATH 中的 chromium/google-chrome/chrome';
524
500
  return undefined;
525
501
  }
526
502
 
527
- const auditScript = (width) => `
503
+ const auditScript = () => `
528
504
  <script>
529
505
  (function () {
530
- // 无头浏览器有最小窗口宽(macOS 上约 500),这里按实际视口量并把宽度写进结果;
531
- // 设计宽(390)的精确核对需要先做 px→rem 转换,属后续增强。
532
- var W = window.innerWidth;
533
- var out = { viewport: W, overflow: 0, overflowRight: 0, minFontPx: null, truncated: 0, smallTargets: [] };
534
- var minFont = 1e9;
535
- var fontCounts = {};
536
- var fontSamples = {};
537
- var nodes = document.body.querySelectorAll('*');
538
- for (var i = 0; i < nodes.length; i += 1) {
539
- var el = nodes[i];
540
- var rect = el.getBoundingClientRect();
541
- if (rect.width > 0 && rect.right > W + 1) out.overflowRight = Math.max(out.overflowRight, Math.round(rect.right - W));
542
- if (el.tagName === 'SCRIPT' || el.tagName === 'STYLE' || el.tagName === 'NOSCRIPT') continue;
543
- if (el.children.length === 0 && (el.textContent || '').trim() !== '') {
544
- var size = parseFloat(getComputedStyle(el).fontSize);
545
- if (size > 0) {
546
- minFont = Math.min(minFont, size);
547
- var key = Math.round(size * 10) / 10;
548
- fontCounts[key] = (fontCounts[key] || 0) + 1;
549
- if (!fontSamples[key]) fontSamples[key] = (el.textContent || '').trim().slice(0, 20);
550
- }
551
- if (el.scrollWidth > el.clientWidth + 1) out.truncated += 1;
552
- }
553
- if ((el.tagName === 'BUTTON' || el.tagName === 'A') && rect.width > 0) {
554
- if (rect.width < 44 || rect.height < 44) out.smallTargets.push({ tag: el.tagName, w: Math.round(rect.width), h: Math.round(rect.height), text: (el.textContent || '').trim().slice(0, 16) });
555
- }
556
- }
557
- out.overflow = Math.max(0, document.documentElement.scrollWidth - W);
558
- out.minFontPx = minFont === 1e9 ? null : Math.round(minFont * 10) / 10;
559
- var ALLOWED = [12, 14, 16, 18, 20];
560
- var offScale = Object.keys(fontCounts)
561
- .map(Number)
562
- .filter(function (px) { return ALLOWED.indexOf(px) < 0; })
563
- .map(function (px) { return { px: px, count: fontCounts[px], sample: fontSamples[px] }; });
564
- out.typeScale = { allowed: ALLOWED, counts: fontCounts, offScale: offScale };
565
- out.smallTargets = out.smallTargets.slice(0, 5);
506
+ // 量法统一在 scripts/lib/geometry-kernel.mjs(与壳探针、故事板同一份);
507
+ // 这里只把内核输出映射回体检原有的字段名,报告与命令行输出不变。
508
+ // 无头浏览器有最小窗口宽(macOS 上约 500),这里按实际视口量并把宽度写进结果。
509
+ ${geometryFunctionSource()}
510
+ var g = tboxGeometry({ targets: 'button, a', thresholds: { minTarget: 44, minFontPx: 12 } });
511
+ var out = {
512
+ viewport: g.viewport.w,
513
+ overflow: g.overflowX,
514
+ overflowRight: g.overflowRight,
515
+ minFontPx: g.minFontPx,
516
+ truncated: g.clipped.length,
517
+ smallTargets: g.smallTargets,
518
+ typeScale: g.typeScale,
519
+ };
566
520
  var pre = document.createElement('pre');
567
521
  pre.id = '__tbox_audit';
568
522
  pre.textContent = JSON.stringify(out);
@@ -573,7 +527,7 @@ const auditScript = (width) => `
573
527
  /** 用无头浏览器量一张卡在 390 宽下的布局风险;找不到浏览器时返回 skipped。 */
574
528
  function auditFile(file, width = 390) {
575
529
  const chrome = findChrome();
576
- if (!chrome) return { skipped: true, reason: '未找到无头浏览器(可设 TBOX_CHROME 指向 Chrome/Chromium)' };
530
+ if (!chrome) return { skipped: true, reason: '未找到无头浏览器(可设 TBOX_CHROME 指向 Chrome/Chromium)' + (chromeLookupError ? ';' + chromeLookupError : '') };
577
531
  const html = readFileSync(file, 'utf8').replace('</body>', `${auditScript(width)}\n</body>`);
578
532
  const probe = file.replace(/\.html$/, '.audit.html');
579
533
  writeFileSync(probe, html, 'utf8');
@@ -604,7 +558,7 @@ function auditLines(audit) {
604
558
 
605
559
  function captureScreenshot(file, outDir, base) {
606
560
  const chrome = findChrome();
607
- if (!chrome) return { skipped: true, reason: '未找到无头浏览器(可设 TBOX_CHROME 指向 Chrome/Chromium)' };
561
+ if (!chrome) return { skipped: true, reason: '未找到无头浏览器(可设 TBOX_CHROME 指向 Chrome/Chromium)' + (chromeLookupError ? ';' + chromeLookupError : '') };
608
562
  const png = path.join(outDir, `${base}.png`);
609
563
  try {
610
564
  execFileSync(
@@ -659,7 +613,7 @@ function compareScreenshot(current, baselineDir, base) {
659
613
  }
660
614
 
661
615
  // ── 5. 输出 ──────────────────────────────────────────────────────────
662
- function writeSample(outDir, cardType, sample, css) {
616
+ export function writeSample(outDir, cardType, sample, css) {
663
617
  mkdirSync(outDir, { recursive: true });
664
618
  const base = sample.label === 'sampleData' ? cardType : `${cardType}-${slug(sample.label)}`;
665
619
  const file = path.join(outDir, `${base}.html`);
@@ -680,8 +634,10 @@ async function main() {
680
634
  const vite = await loadVite();
681
635
  try {
682
636
  const registries = await loadRegistry(vite);
683
- const knownCards = Object.keys(registries.server?.cards ?? {});
684
- const meta = registries.server?.cards?.[args.type];
637
+ const view = (await import('./lib/card-registry.mjs')).collectCards({ server: registries.server, client: registries.client });
638
+ const resolved = { ...registries, server: { ...registries.server, cards: view.metas }, client: { ...registries.client, cards: view.components } };
639
+ const knownCards = Object.keys(view.metas);
640
+ const meta = view.metas[args.type];
685
641
  if (!meta) {
686
642
  throw new Error(
687
643
  `未找到卡片类型 "${args.type}"(已注册:${knownCards.join('、') || '无'})\n` +
@@ -692,12 +648,20 @@ async function main() {
692
648
  if (samples.length === 0) {
693
649
  throw new Error(
694
650
  `卡片 ${args.type} 没有样例。\n` +
695
- ` 修复:在 apps/server/src/cards/${args.type}.card.ts 的 sampleData 或 samples 里补一条静态字面量(card render 依赖它)`,
651
+ ` 修复:在 ${view.provenance?.[args.type]?.kind === 'module' ? `modules/${view.provenance[args.type].moduleId}/src/server/cards/${args.type}/meta.ts` : `apps/server/src/cards/${args.type}.card.ts`} 的 sampleData 或 samples 里补一条静态字面量(card render 依赖它)`,
696
652
  );
697
653
  }
698
654
  const selected = selectSamples(samples, args);
699
- const rendered = await renderSamples(vite, registries, args.type, selected);
700
- const css = await buildStyleSheet(vite);
655
+ const rendered = await renderSamples(vite, resolved, args.type, selected);
656
+ const surface = await buildStyleSheet(vite);
657
+ const css = surface.css;
658
+ // 证据自校验:CSS 为空或哨兵缺失时,截图/HTML 只会说谎——直接失败,不产出「无样式证据」。
659
+ if (surface.missing.length > 0 || surface.bytes < 20000) {
660
+ throw new Error(
661
+ `表面 CSS 不可信:${surface.bytes} 字节,缺哨兵 ${surface.missing.join('、') || '无'}。\n` +
662
+ ` 修复:确认 apps/client/vite.config.ts 的 tboxModuleSourcesPlugin 在 tailwindcss() 之前;本命令与 check:fast 同一管线(surface-css.mjs)。`,
663
+ );
664
+ }
701
665
  const outDir = path.resolve(args.out ?? path.join(appDir, '.tbox/card-render'));
702
666
  const baselineDir = path.join(outDir, 'baseline');
703
667
  const results = rendered.map((sample) => {
@@ -710,7 +674,7 @@ async function main() {
710
674
  });
711
675
  for (const sample of results) if (sample.schemaValid === false) warnings.push(`${args.type} / ${sample.label} 的样例未过 dataSchema:${(sample.issues ?? []).join(';')}`);
712
676
 
713
- const result = { ok: true, cardType: args.type, samples: results, warnings };
677
+ const result = { ok: true, cardType: args.type, cssBytes: surface.bytes, samples: results, warnings };
714
678
  if (args.json) {
715
679
  console.log(JSON.stringify(result));
716
680
  return;
@@ -728,16 +692,21 @@ async function main() {
728
692
  else console.log(` ✅ 视觉差异 ${(sample.visual.ratio * 100).toFixed(3)}%`);
729
693
  }
730
694
  }
695
+ console.log(` 样式:${surface.bytes} 字节(与 dev/build 同一管线)`);
731
696
  if (!args.outline) console.log(' 提示:--outline 看层级与按钮;--all 渲染全部样例;--json 机器可读');
732
697
  } finally {
733
698
  await vite.close();
734
699
  }
735
700
  }
736
701
 
737
- try {
738
- await main();
739
- } catch (error) {
740
- if (process.argv.includes('--json')) console.log(JSON.stringify({ ok: false, error: error?.message ?? String(error) }));
741
- else console.error(`❌ ${error?.message ?? error}`);
742
- process.exitCode = 1;
702
+ // 直接运行才走 CLI;被 scripts/storyboard.mjs 导入时只提供渲染函数(同进程复用一次 vite)。
703
+ const invokedDirectly = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url);
704
+ if (invokedDirectly) {
705
+ try {
706
+ await main();
707
+ } catch (error) {
708
+ if (process.argv.includes('--json')) console.log(JSON.stringify({ ok: false, error: error?.message ?? String(error) }));
709
+ else console.error(`❌ ${error?.message ?? error}`);
710
+ process.exitCode = 1;
711
+ }
743
712
  }
@@ -0,0 +1,31 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { duplicateSampleLabels, sampleEntries } from './render-card.mjs';
3
+
4
+ const meta = {
5
+ sampleData: { title: '基准' },
6
+ samples: [
7
+ { label: '历史', data: { title: '历史' }, isHistory: true },
8
+ { label: '隐藏', data: { title: '隐藏' }, hidden: true },
9
+ { label: '无令牌', data: { title: '无令牌' }, noTokens: true },
10
+ ],
11
+ };
12
+
13
+ describe('样例条目', () => {
14
+ it('贯通 isHistory/noTokens/hidden/group/note,隐藏样例可按需过滤', () => {
15
+ const all = sampleEntries(meta);
16
+ expect(all.map((sample) => sample.label)).toEqual(['sampleData', '历史', '隐藏', '无令牌']);
17
+ expect(all.find((sample) => sample.label === '历史')?.isHistory).toBe(true);
18
+ expect(all.find((sample) => sample.label === '无令牌')?.noTokens).toBe(true);
19
+ expect(all.find((sample) => sample.label === '隐藏')?.hidden).toBe(true);
20
+ expect(sampleEntries(meta, { includeHidden: false }).map((sample) => sample.label)).toEqual(['sampleData', '历史', '无令牌']);
21
+ });
22
+
23
+ it('同卡 label 重复可被检测(帧键/文件名冲突防线)', () => {
24
+ expect(duplicateSampleLabels(meta)).toEqual([]);
25
+ const duplicated = { ...meta, samples: [...meta.samples, { label: '历史', data: {} }] };
26
+ expect(duplicateSampleLabels(duplicated)).toEqual(['历史']);
27
+ // hidden-only 重复不进帧:故事板用 includeHidden:false 检查,不应误伤。
28
+ const hiddenDuplicate = { ...meta, samples: [...meta.samples, { label: '隐藏', data: {}, hidden: true }] };
29
+ expect(duplicateSampleLabels(hiddenDuplicate, { includeHidden: false })).toEqual([]);
30
+ });
31
+ });