@tbox.cn/app-template-agent 1.0.0-alpha.8 → 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 (109) 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 +4 -2
  7. package/apps/client/package.json +1 -0
  8. package/apps/client/scripts/._color-scan.test.mjs +0 -0
  9. package/apps/client/scripts/._experience-checks.mjs +0 -0
  10. package/apps/client/scripts/._geometry-kernel.test.mjs +0 -0
  11. package/apps/client/scripts/._in-process-checks.mjs +0 -0
  12. package/apps/client/scripts/._probe-checks.mjs +0 -0
  13. package/apps/client/scripts/._sample-entries.test.mjs +0 -0
  14. package/apps/client/scripts/._storyboard.test.mjs +0 -0
  15. package/apps/client/scripts/._theme-kernel.mjs +0 -0
  16. package/apps/client/scripts/._theme-kernel.test.mjs +0 -0
  17. package/apps/client/scripts/acceptance-changes.test.mjs +97 -0
  18. package/apps/client/scripts/check-evidence.mjs +361 -94
  19. package/apps/client/scripts/color-scan.mjs +66 -0
  20. package/apps/client/scripts/color-scan.test.mjs +25 -0
  21. package/apps/client/scripts/evidence-gate.mjs +248 -46
  22. package/apps/client/scripts/evidence-gate.test.mjs +63 -5
  23. package/apps/client/scripts/experience-checks.mjs +163 -0
  24. package/apps/client/scripts/geometry-kernel.test.mjs +92 -0
  25. package/apps/client/scripts/in-process-checks.mjs +51 -0
  26. package/apps/client/scripts/lib/._card-registry.mjs +0 -0
  27. package/apps/client/scripts/lib/._card-registry.test.mjs +0 -0
  28. package/apps/client/scripts/lib/._evidence-inputs.mjs +0 -0
  29. package/apps/client/scripts/lib/._evidence-inputs.test.mjs +0 -0
  30. package/apps/client/scripts/lib/._static-render.mjs +0 -0
  31. package/apps/client/scripts/lib/._static-render.test.mjs +0 -0
  32. package/apps/client/scripts/lib/card-registry.mjs +81 -0
  33. package/apps/client/scripts/lib/card-registry.test.mjs +59 -0
  34. package/apps/client/scripts/lib/evidence-inputs.mjs +91 -0
  35. package/apps/client/scripts/lib/evidence-inputs.test.mjs +27 -0
  36. package/apps/client/scripts/lib/static-render.mjs +35 -0
  37. package/apps/client/scripts/lib/static-render.test.mjs +21 -0
  38. package/apps/client/scripts/probe-checks.mjs +85 -0
  39. package/apps/client/scripts/render-card.mjs +76 -60
  40. package/apps/client/scripts/sample-entries.test.mjs +31 -0
  41. package/apps/client/scripts/storyboard.test.mjs +149 -0
  42. package/apps/client/scripts/surface-css.mjs +5 -2
  43. package/apps/client/scripts/theme-kernel.mjs +236 -0
  44. package/apps/client/scripts/theme-kernel.test.mjs +136 -0
  45. package/apps/client/src/styles/brand.css +11 -11
  46. package/apps/client/src/styles/tailwind.css +3 -4
  47. package/apps/client/vite.config.ts +2 -1
  48. package/apps/server/scripts/probe.mjs +6 -1
  49. package/apps/server/scripts/scenario-lib.mjs +54 -7
  50. package/apps/server/scripts/scenario.mjs +41 -7
  51. package/config/AGENTS.md +1 -0
  52. package/config/chat.json +21 -9
  53. package/docs/agent/card.md +1 -0
  54. package/docs/agent/kit.md +1 -1
  55. package/docs/agent/shell.md +1 -0
  56. package/docs/agent/style.md +3 -1
  57. package/docs/agent/verify.md +37 -8
  58. package/package.json +9 -6
  59. package/packages/agent-ui-kit/README.md +21 -1
  60. package/packages/agent-ui-kit/catalog.json +1 -1
  61. package/packages/agent-ui-kit/package.json +9 -1
  62. package/packages/agent-ui-kit/src/ChatPage.tsx +30 -1
  63. package/packages/agent-ui-kit/src/card/primitives.test.tsx +10 -0
  64. package/packages/agent-ui-kit/src/card/primitives.tsx +14 -10
  65. package/packages/agent-ui-kit/src/card/view-card.tsx +6 -1
  66. package/packages/agent-ui-kit/src/chat-config.ts +11 -7
  67. package/packages/agent-ui-kit/src/components/ActionBar/DebugButton.test.tsx +3 -0
  68. package/packages/agent-ui-kit/src/components/ActionBar/DebugButton.tsx +2 -7
  69. package/packages/agent-ui-kit/src/components/BottomSheet/._index.test.tsx +0 -0
  70. package/packages/agent-ui-kit/src/components/BottomSheet/._index.tsx +0 -0
  71. package/packages/agent-ui-kit/src/components/BottomSheet/index.test.tsx +90 -0
  72. package/packages/agent-ui-kit/src/components/BottomSheet/index.tsx +129 -0
  73. package/packages/agent-ui-kit/src/components/ChatInput/index.test.tsx +2 -2
  74. package/packages/agent-ui-kit/src/components/ChatInput/index.tsx +21 -16
  75. package/packages/agent-ui-kit/src/components/HistoryEntry/index.tsx +1 -0
  76. package/packages/agent-ui-kit/src/components/QuickCommands/index.tsx +2 -2
  77. package/packages/agent-ui-kit/src/components/ScrollToBottomButton/index.tsx +7 -3
  78. package/packages/agent-ui-kit/src/components/ToolCallBlock/index.tsx +4 -2
  79. package/packages/agent-ui-kit/src/index.ts +4 -0
  80. package/packages/agent-ui-kit/src/shell.contract.json +9 -0
  81. package/packages/agent-ui-kit/src/shell.test.ts +10 -0
  82. package/packages/agent-ui-kit/src/shell.ts +15 -0
  83. package/packages/agent-ui-kit/src/theme/contract.json +78 -1
  84. package/packages/agent-ui-kit/src/theme/theme-contract.test.ts +16 -0
  85. package/packages/agent-ui-kit/src/theme/tokens.css +1 -1
  86. package/pnpm-lock.template.yaml +97 -91
  87. package/pnpm-workspace.template.yaml +10 -10
  88. package/profiles/mall/._chat.overrides.json +0 -0
  89. package/profiles/mall/chat.overrides.json +12 -0
  90. package/profiles/mall/config/chat.json +14 -6
  91. package/profiles/mall.json +1 -1
  92. package/scripts/._deliver.mjs +0 -0
  93. package/scripts/._shell-probe.mjs +0 -0
  94. package/scripts/._storyboard.mjs +0 -0
  95. package/scripts/check-fast.mjs +1 -0
  96. package/scripts/checks.json +294 -17
  97. package/scripts/deliver.mjs +183 -0
  98. package/scripts/lib/._chrome-pipe.mjs +0 -0
  99. package/scripts/lib/._geometry-kernel.mjs +0 -0
  100. package/scripts/lib/chrome-pipe.mjs +95 -0
  101. package/scripts/lib/geometry-kernel.mjs +137 -0
  102. package/scripts/shell-probe.mjs +283 -0
  103. package/scripts/storyboard.mjs +350 -0
  104. package/profiles/mall/config/llm_provider.json +0 -5
  105. package/profiles/mall/config/plugins.json +0 -3
  106. package/scripts/gen-tailwind-sources.mjs +0 -55
  107. /package/{profiles/mall/config/._llm_provider.json → .tbox/factory/._chat.json} +0 -0
  108. /package/{profiles/mall/config/._plugins.json → apps/client/scripts/._acceptance-changes.test.mjs} +0 -0
  109. /package/{scripts/._gen-tailwind-sources.mjs → apps/client/scripts/._color-scan.mjs} +0 -0
@@ -0,0 +1,137 @@
1
+ /**
2
+ * 几何内核:一次 DOM 遍历回答「有没有溢出、字号够不够、点击区够不够、截断与空白」。
3
+ *
4
+ * 三处消费者(壳探针、卡片渲染体检、故事板)共用这一份实现;新增一处消费 = 调用它,
5
+ * 不再各写一遍量法。阈值可被 checks.json 的 threshold 字段覆盖。
6
+ *
7
+ * 内核只认识 DOM,不认识「商圈」「卡片」「DSH」:它不读配置、不发请求、不写文件。
8
+ */
9
+ export const GEOMETRY_DEFAULTS = {
10
+ /** 可点元素的最小边长(CSS px) */
11
+ minTarget: 44,
12
+ /** 正文最小字号(CSS px) */
13
+ minFontPx: 12,
14
+ /** 横向溢出容差:1px 内的亚像素误差不算溢出 */
15
+ overflowTolerancePx: 1,
16
+ };
17
+
18
+ /** 默认的「可点元素」选择器:只认原生可交互元素,避免把装饰 div 算进去。 */
19
+ export const DEFAULT_TARGETS = 'button, a, [role="button"], input, select, textarea';
20
+
21
+ /**
22
+ * 浏览器内执行的测量函数源码。调用方把它拼进表达式或 <script>,再调用 tboxGeometry(opts)。
23
+ *
24
+ * opts:
25
+ * targets 可点元素选择器(缺省 DEFAULT_TARGETS)
26
+ * blankSelectors 参与「块间空白」的块选择器数组(缺省空 = 不量空白)
27
+ * thresholds { minTarget, minFontPx, overflowTolerancePx }
28
+ * root 遍历起点选择器(缺省 document.body)
29
+ * typeScale 字号标度白名单(缺省 [12,14,16,18,20])
30
+ */
31
+ export function geometryFunctionSource() {
32
+ return [
33
+ 'function tboxGeometry(opts) {',
34
+ ' var o = opts || {};',
35
+ ' var t = o.thresholds || {};',
36
+ ' var minTarget = typeof t.minTarget === "number" ? t.minTarget : 44;',
37
+ ' var minFontAllowed = typeof t.minFontPx === "number" ? t.minFontPx : 12;',
38
+ ' var tolerance = typeof t.overflowTolerancePx === "number" ? t.overflowTolerancePx : 1;',
39
+ ' var scale = o.typeScale || [12, 14, 16, 18, 20];',
40
+ ' var rootSel = o.root || "body";',
41
+ ' var root = (rootSel === "body" ? document.body : document.querySelector(rootSel)) || document.body;',
42
+ ' var W = window.innerWidth;',
43
+ ' var out = { viewport: { w: W, h: window.innerHeight }, overflowX: 0, overflowRight: 0, clipped: [], smallTargets: [], minFontPx: null, typeScale: { allowed: scale, counts: {}, offScale: [] }, blankGap: null, height: 0 };',
44
+ ' var minFont = 1e9;',
45
+ ' var counts = {};',
46
+ ' var samples = {};',
47
+ ' var nodes = root.querySelectorAll("*");',
48
+ ' for (var i = 0; i < nodes.length; i += 1) {',
49
+ ' var el = nodes[i];',
50
+ ' var rect = el.getBoundingClientRect();',
51
+ ' if (rect.width > 0 && rect.right > W + tolerance) out.overflowRight = Math.max(out.overflowRight, Math.round(rect.right - W));',
52
+ ' if (el.tagName === "SCRIPT" || el.tagName === "STYLE" || el.tagName === "NOSCRIPT") continue;',
53
+ ' if (el.children.length === 0 && (el.textContent || "").trim() !== "") {',
54
+ ' var size = parseFloat(getComputedStyle(el).fontSize);',
55
+ ' if (size > 0) {',
56
+ ' minFont = Math.min(minFont, size);',
57
+ ' var key = Math.round(size * 10) / 10;',
58
+ ' counts[key] = (counts[key] || 0) + 1;',
59
+ ' if (!samples[key]) samples[key] = (el.textContent || "").trim().slice(0, 20);',
60
+ ' }',
61
+ ' if (el.scrollWidth > el.clientWidth + tolerance) {',
62
+ ' var style = getComputedStyle(el);',
63
+ ' var ellipsis = (style.textOverflow || "") === "ellipsis";',
64
+ ' out.clipped.push({ text: (el.textContent || "").trim().slice(0, 24), tag: el.tagName, ellipsis: ellipsis });',
65
+ ' }',
66
+ ' }',
67
+ ' if (rect.width > 0 && el.matches(o.targets || ' + JSON.stringify(DEFAULT_TARGETS) + ')) {',
68
+ ' if (Math.round(rect.width) < minTarget || Math.round(rect.height) < minTarget) {',
69
+ ' out.smallTargets.push({ tag: el.tagName, w: Math.round(rect.width), h: Math.round(rect.height), text: (el.textContent || "").trim().slice(0, 16) });',
70
+ ' }',
71
+ ' }',
72
+ ' }',
73
+ ' out.overflowX = Math.max(0, document.documentElement.scrollWidth - W);',
74
+ ' out.minFontPx = minFont === 1e9 ? null : Math.round(minFont * 10) / 10;',
75
+ ' out.typeScale.counts = counts;',
76
+ ' out.typeScale.offScale = Object.keys(counts).map(Number).filter(function (px) { return scale.indexOf(px) < 0; }).map(function (px) { return { px: px, count: counts[px], sample: samples[px] }; });',
77
+ ' out.smallTargets = out.smallTargets.slice(0, 5);',
78
+ ' out.clipped = out.clipped.slice(0, 10);',
79
+ ' out.height = Math.round(document.documentElement.scrollHeight);',
80
+ ' var blankSels = o.blankSelectors || [];',
81
+ ' if (blankSels.length > 0) {',
82
+ ' var blocks = [];',
83
+ ' for (var s = 0; s < blankSels.length; s += 1) {',
84
+ ' var found = document.querySelectorAll(blankSels[s]);',
85
+ ' for (var f = 0; f < found.length; f += 1) {',
86
+ ' var cs = getComputedStyle(found[f]);',
87
+ ' var r = found[f].getBoundingClientRect();',
88
+ ' if (cs.display !== "none" && cs.visibility !== "hidden" && Number(cs.opacity) > 0 && r.width > 0 && r.height > 0) blocks.push(r);',
89
+ ' }',
90
+ ' }',
91
+ ' blocks.sort(function (a, b) { return a.top - b.top; });',
92
+ ' var maxGap = 0;',
93
+ ' for (var b = 1; b < blocks.length; b += 1) maxGap = Math.max(maxGap, Math.round(blocks[b].top - blocks[b - 1].bottom));',
94
+ ' out.blankGap = { maxGap: Math.max(0, maxGap), blocks: blocks.length };',
95
+ ' }',
96
+ ' return out;',
97
+ '}',
98
+ ].join('\n');
99
+ }
100
+
101
+ /** 阈值:checks.json 里对应检查的 threshold 覆盖缺省。 */
102
+ export function loadThresholds(checksJson, ids = []) {
103
+ const merged = { ...GEOMETRY_DEFAULTS };
104
+ const list = Array.isArray(checksJson?.checks) ? checksJson.checks : [];
105
+ for (const id of ids) {
106
+ const check = list.find((item) => item.id === id);
107
+ if (check && check.threshold && typeof check.threshold === 'object') Object.assign(merged, check.threshold);
108
+ }
109
+ return merged;
110
+ }
111
+
112
+ /** CDP Runtime.evaluate 可直接执行的表达式;返回 JSON 字符串。 */
113
+ export function geometryExpression(options = {}) {
114
+ const { thresholds = {}, ...rest } = options;
115
+ return [
116
+ '(() => {',
117
+ geometryFunctionSource(),
118
+ ' return JSON.stringify(tboxGeometry(' + JSON.stringify({ ...rest, thresholds }) + '));',
119
+ '})()',
120
+ ].join('\n');
121
+ }
122
+
123
+ /** 拼进 HTML 的 <script> 内容:量完写进 <pre id="__tbox_audit">,供 --dump-dom 读回。 */
124
+ export function geometryAuditScript(options = {}) {
125
+ return [
126
+ '<script>',
127
+ '(function () {',
128
+ geometryFunctionSource(),
129
+ ' var out = tboxGeometry(' + JSON.stringify(options) + ');',
130
+ ' var pre = document.createElement("pre");',
131
+ ' pre.id = "__tbox_audit";',
132
+ ' pre.textContent = JSON.stringify(out);',
133
+ ' document.body.appendChild(pre);',
134
+ '})();',
135
+ '</script>',
136
+ ].join('\n');
137
+ }
@@ -0,0 +1,283 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * pnpm probe:shell —— 壳体验探针(空态,390×844)。
4
+ *
5
+ * 渲染真实 ChatPage(SSR + 真实配置)→ 静态 HTML → 无头 Chrome(CDP over pipe,零 socket)
6
+ * → 量命中区、控件语义、控件在场、快捷问题可见性、图标与空白。
7
+ * 结果写 .tbox/evidence/shell.json;没有 Chrome 时全部记 not-run,不阻断。
8
+ */
9
+ import { createServer as createHttpServer } from 'node:http';
10
+ import { spawn } from 'node:child_process';
11
+ import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
12
+ import { createRequire } from 'node:module';
13
+ import path from 'node:path';
14
+ import { pathToFileURL } from 'node:url';
15
+ import { geometryFunctionSource } from './lib/geometry-kernel.mjs';
16
+ import { findChrome, openChromeSession } from './lib/chrome-pipe.mjs';
17
+
18
+ const appDir = path.resolve(import.meta.dirname, '..');
19
+ const clientDir = path.join(appDir, 'apps/client');
20
+ const outDir = path.join(appDir, '.tbox/evidence');
21
+ mkdirSync(outDir, { recursive: true });
22
+
23
+ const chromePath = findChrome();
24
+
25
+ const PROBE_IDS = [
26
+ 'shell.hit-target', 'shell.quick-visible', 'shell.icon-render',
27
+ 'shell.controls-semantic', 'shell.control-present', 'shell.a11y-name',
28
+ 'shell.turn-visible', 'shell.console-clean',
29
+ ];
30
+
31
+ const items = [];
32
+ const push = (id, lane, status, detail) => items.push({ id, lane, status, detail });
33
+ const writeResult = (extra) => {
34
+ writeFileSync(path.join(outDir, 'shell.json'), JSON.stringify({
35
+ schemaVersion: 1,
36
+ protocolVersion: 1,
37
+ generatedAt: new Date().toISOString(),
38
+ viewport: { w: 390, h: 844 },
39
+ ...extra,
40
+ items,
41
+ }, null, 2) + '\n', 'utf8');
42
+ console.log('shell probe: ' + items.map((item) => item.id + '=' + item.status).join(' '));
43
+ };
44
+
45
+ if (!chromePath) {
46
+ for (const id of PROBE_IDS) {
47
+ push(id, id.startsWith('shell.turn') || id === 'shell.console-clean' ? 'runtime' : 'layout', 'not-run', '未找到无头浏览器(可设 TBOX_CHROME)');
48
+ }
49
+ writeResult({ chrome: null, reason: 'no-chrome' });
50
+ process.exit(0);
51
+ }
52
+
53
+ let vite;
54
+ let hub;
55
+ try {
56
+ const chatPath = path.join(appDir, 'config/chat.json');
57
+ const chat = existsSync(chatPath) ? JSON.parse(readFileSync(chatPath, 'utf8')) : {};
58
+ globalThis.__TBOX_CHAT_CONFIG__ = chat; // SSR 注入点(kit 读取)
59
+ // 依赖从 apps/client 解析:vite/react 是它的依赖,脚本自身不在依赖树里。
60
+ const clientRequire = createRequire(path.join(clientDir, 'package.json'));
61
+ const load = (specifier) => import(pathToFileURL(clientRequire.resolve(specifier)).href);
62
+ const { createServer, build } = await load('vite');
63
+ const react = (await load('@vitejs/plugin-react')).default;
64
+ const tailwindcss = (await load('@tailwindcss/vite')).default;
65
+ const React = (await load('react')).default;
66
+ const { renderToStaticMarkup } = await load('react-dom/server');
67
+ hub = createHttpServer();
68
+ vite = await createServer({
69
+ configFile: false, root: clientDir, appType: 'custom', logLevel: 'error',
70
+ plugins: [tailwindcss(), react()],
71
+ resolve: { alias: { '@': path.join(clientDir, 'src'), '@config': path.join(appDir, 'config') } },
72
+ server: { middlewareMode: true, hmr: { server: hub }, fs: { allow: [appDir] } },
73
+ optimizeDeps: { noDiscovery: true, include: [] },
74
+ // SSR 加载 kit 时,依赖里带 CSS 的包必须交给 Vite 内联处理:Node 直连 antd-mobile 的
75
+ // CJS 入口会 require 它自己的 global.css(SyntaxError),探针会整体降级为 not-run。
76
+ ssr: { noExternal: ['antd-mobile'] },
77
+ });
78
+ const { buildSurfaceCss } = await import(path.join(clientDir, 'scripts/surface-css.mjs'));
79
+ const surface = await buildSurfaceCss(vite, { clientDir, appDir });
80
+ const kit = await vite.ssrLoadModule('@tbox.cn/app-agent-ui-kit');
81
+ const registry = await vite.ssrLoadModule('/.tbox-gen/registry.client.ts');
82
+ kit.configureChatConfigDefaults(chat);
83
+ const store = kit.createPreviewStore({
84
+ messages: [], historyMessages: [], historyHasMore: false, isLoadingHistory: false,
85
+ isGenerating: false, runtimeStatus: 'ready', authBlocked: null, orphanCards: [], cardsByMessageId: {},
86
+ });
87
+ const markup = renderToStaticMarkup(React.createElement(kit.ChatPage, { store, cards: registry.cards, rawCards: registry.cards }));
88
+ const htmlFile = path.join(outDir, 'shell.html');
89
+ writeFileSync(htmlFile, '<!doctype html><html lang="zh-CN" data-theme="tbox"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>shell probe</title><style>' + surface.cssText + '</style></head><body>' + markup + '</body></html>', 'utf8');
90
+ // 运行时车道:真实水合(IIFE 内联)→ 量回合可见性与控制台噪声。
91
+ let runtimeHtml;
92
+ try {
93
+ const runtimeEntry = path.join(clientDir, '.tbox-probe-runtime.tsx');
94
+ const runtimeSource = [
95
+ "import React from 'react';",
96
+ "import { createRoot } from 'react-dom/client';",
97
+ "import * as kit from '@tbox.cn/app-agent-ui-kit';",
98
+ "const warnings = [];",
99
+ "for (const level of ['warn', 'error']) {",
100
+ " const original = console[level];",
101
+ " console[level] = (...args) => { warnings.push(level + ': ' + args.map((a) => (typeof a === 'string' ? a : String((a && a.message) || a))).join(' ')); original.apply(console, args); };",
102
+ "}",
103
+ "globalThis.__tboxProbeWarnings = warnings;",
104
+ "const errors = [];",
105
+ "globalThis.__tboxProbeErrors = errors;",
106
+ "window.addEventListener('error', (event) => errors.push('error: ' + (event.message || event.error)));",
107
+ "window.addEventListener('unhandledrejection', (event) => errors.push('rejection: ' + (event.reason && event.reason.message ? event.reason.message : event.reason)));",
108
+ "const long = '这一段用于把对话撑出视口。'.repeat(24);",
109
+ "const messages = [];",
110
+ "for (let i = 0; i < 4; i += 1) {",
111
+ " messages.push({ id: 'u' + i, role: 'user', content: '第 ' + (i + 1) + ' 轮问题:我要停车缴费,顺便看看今天有什么活动', status: 'done', createdAt: i * 2 });",
112
+ " messages.push({ id: 'a' + i, role: 'assistant', content: long, status: 'done', createdAt: i * 2 + 1 });",
113
+ "}",
114
+ "const noop = () => {}; const asyncNoop = async () => {}; const store = kit.createPreviewStore({ messages, historyMessages: [], historyHasMore: false, isLoadingHistory: false, isGenerating: false, runtimeStatus: 'ready', authBlocked: null, orphanCards: [], cardsByMessageId: {}, initConversation: asyncNoop, newConversation: asyncNoop, loadMoreHistory: asyncNoop, retryBootstrap: asyncNoop, scheduleSessionUpgrade: asyncNoop, clearChat: noop, destroy: noop, setAuthBlocked: noop, submitFeedback: asyncNoop, cancelGeneration: noop, setGenerating: noop, setUserId: noop });",
115
+ "globalThis.__tboxProbeMount = () => {",
116
+ " createRoot(document.getElementById('root')).render(React.createElement(kit.ChatPage, { store, cards: {}, rawCards: {} }));",
117
+ "};",
118
+ ].join('\n');
119
+ const runtimeDir = path.join(outDir, 'runtime');
120
+ writeFileSync(runtimeEntry, runtimeSource, 'utf8');
121
+ try {
122
+ await build({
123
+ configFile: false, root: clientDir, logLevel: 'error', mode: 'production', plugins: [react()],
124
+ esbuild: { jsx: 'automatic', jsxDev: false },
125
+ build: {
126
+ outDir: runtimeDir, emptyOutDir: true, minify: false, write: true,
127
+ lib: { entry: runtimeEntry, formats: ['iife'], name: 'TboxProbeRuntime', fileName: () => 'probe.js' },
128
+ rollupOptions: { output: { inlineDynamicImports: true } },
129
+ },
130
+ define: { 'process.env.NODE_ENV': JSON.stringify('production') },
131
+ });
132
+ } finally {
133
+ try { unlinkSync(runtimeEntry); } catch { /* 临时入口删不删都不影响产物 */ }
134
+ }
135
+ const bundle = readFileSync(path.join(runtimeDir, 'probe.js'), 'utf8');
136
+ runtimeHtml = path.join(outDir, 'shell-runtime.html');
137
+ writeFileSync(runtimeHtml, '<!doctype html><html lang="zh-CN" data-theme="tbox"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>shell runtime probe</title><style>' + surface.cssText + '</style></head><body><div id="root" style="height:844px"></div><script>' + bundle + '</script><script>window.__tboxProbeMount()</script></body></html>', 'utf8');
138
+ } catch (error) {
139
+ runtimeHtml = undefined;
140
+ push('shell.turn-visible', 'runtime', 'not-run', '运行时构建失败:' + (error && error.message ? error.message : String(error)));
141
+ push('shell.console-clean', 'runtime', 'not-run', '运行时构建失败:' + (error && error.message ? error.message : String(error)));
142
+ }
143
+ await vite.close();
144
+ vite = undefined;
145
+ await new Promise((resolve) => hub.close(resolve));
146
+ hub = undefined;
147
+
148
+ const emptyShot = path.join(outDir, 'shell-empty.png');
149
+ const result = await runChrome(chromePath, htmlFile, staticExpression(), emptyShot);
150
+ applyChecks(result, chat);
151
+ let runtimeShot;
152
+ if (runtimeHtml) {
153
+ runtimeShot = path.join(outDir, 'shell-runtime.png');
154
+ const runtime = await runChrome(chromePath, runtimeHtml, runtimeExpression(), runtimeShot);
155
+ applyRuntimeChecks(runtime);
156
+ }
157
+ writeResult({
158
+ chrome: result.product ?? 'unknown',
159
+ html: path.relative(appDir, htmlFile),
160
+ screenshots: [htmlFile, emptyShot, runtimeShot]
161
+ .filter((file) => file && existsSync(file))
162
+ .map((file) => path.relative(appDir, file)),
163
+ });
164
+ } catch (error) {
165
+ for (const id of PROBE_IDS) {
166
+ push(id, id.startsWith('shell.turn') || id === 'shell.console-clean' ? 'runtime' : 'layout', 'not-run', '探针未完成:' + (error && error.message ? error.message : String(error)));
167
+ }
168
+ writeResult({ reason: 'probe-error' });
169
+ } finally {
170
+ if (vite) await vite.close().catch(() => {});
171
+ if (hub) hub.close();
172
+ }
173
+ process.exit(0);
174
+
175
+ function staticExpression() {
176
+ return [
177
+ '(() => {',
178
+ geometryFunctionSource(),
179
+ ' // 几何量法来自 scripts/lib/geometry-kernel.mjs(与卡片体检、故事板同一份)。',
180
+ ' const geometry = tboxGeometry({ blankSelectors: [".chat-page__welcome", ".quick-commands", ".chat-page__brand", ".tbox-chat-input"] });',
181
+ ' const rect = (el) => { const r = el.getBoundingClientRect(); return [Math.round(r.width), Math.round(r.height)]; };',
182
+ ' const visible = (el) => { const cs = getComputedStyle(el); const r = el.getBoundingClientRect(); return cs.display !== "none" && cs.visibility !== "hidden" && Number(cs.opacity) > 0 && r.width > 0 && r.height > 0; };',
183
+ ' const nodes = [...document.querySelectorAll("[data-tbox-control], button, [role=button], .tbox-btn")].filter(visible);',
184
+ ' const controls = nodes.map((el) => { const r = rect(el); return { tag: el.tagName, id: el.getAttribute("data-tbox-control") || "", cls: String(el.className).slice(0, 40), label: el.getAttribute("aria-label") || "", text: (el.textContent || "").trim().slice(0, 16), w: r[0], h: r[1] }; });',
185
+ ' const quickEl = document.querySelector(".quick-commands");',
186
+ ' const quick = quickEl ? { count: quickEl.children.length, scrollWidth: quickEl.scrollWidth, clientWidth: quickEl.clientWidth } : null;',
187
+ ' const icons = [...document.querySelectorAll(".quick-commands__icon")].map((el) => { const cs = getComputedStyle(el); const mask = cs.maskImage || cs.webkitMaskImage || "none"; return { maskActive: mask !== "none", hasContent: (el.textContent || "").trim().length > 0, visible: visible(el) }; });',
188
+ ' const brand = (document.querySelector(".chat-page__brand") || {}).textContent || "";',
189
+ ' const blank = geometry.blankGap ? { maxGap: geometry.blankGap.maxGap, blocks: geometry.blankGap.blocks, viewport: geometry.viewport.h } : null;',
190
+ ' return JSON.stringify({ controls, quick, icons, brand, blank, geometry });',
191
+ '})()',
192
+ ].join('\n');
193
+ }
194
+
195
+ function runtimeExpression() {
196
+ return [
197
+ '(() => {',
198
+ ' const body = document.querySelector(".chat-page__body");',
199
+ ' const nodes = [...document.querySelectorAll("[data-message-id]")];',
200
+ ' const lastUser = nodes.find((el) => el.getAttribute("data-message-id") === "u3");',
201
+ ' const btn = document.querySelector("[data-tbox-control=scroll-bottom]");',
202
+ ' const b = body ? body.getBoundingClientRect() : null;',
203
+ ' const r = lastUser ? lastUser.getBoundingClientRect() : null;',
204
+ ' const bs = btn ? getComputedStyle(btn) : null;',
205
+ ' return JSON.stringify({ count: nodes.length, scrollTop: body ? Math.round(body.scrollTop) : 0, userTop: r ? Math.round(r.top) : null, bodyTop: b ? Math.round(b.top) : null, bodyBottom: b ? Math.round(b.bottom) : null, buttonVisible: Boolean(btn) && bs.opacity !== "0" && bs.display !== "none", warnings: (globalThis.__tboxProbeWarnings || []).slice(0, 5), errors: (globalThis.__tboxProbeErrors || []).slice(0, 5) });',
206
+ '})()',
207
+ ].join('\n');
208
+ }
209
+
210
+ function applyRuntimeChecks(runtime) {
211
+ const visible = runtime.count >= 8 && runtime.scrollTop > 0 && runtime.userTop !== null && runtime.bodyTop !== null && runtime.userTop >= runtime.bodyTop - 2 && runtime.userTop < runtime.bodyBottom;
212
+ push('shell.turn-visible', 'runtime', visible ? 'pass' : 'fail',
213
+ '消息 ' + runtime.count + ' 条;scrollTop ' + runtime.scrollTop + ';末条用户消息 top ' + runtime.userTop + ' / 视口 ' + runtime.bodyTop + '-' + runtime.bodyBottom + ';浮标 ' + (runtime.buttonVisible ? '可见' : '不可见'));
214
+
215
+ const warnings = [...(runtime.warnings || []), ...(runtime.errors || [])];
216
+ push('shell.console-clean', 'runtime', warnings.length === 0 ? 'pass' : 'fail',
217
+ warnings.length === 0 ? '控制台无告警/错误' : warnings.slice(0, 3).join(';'));
218
+ }
219
+
220
+ function applyChecks(result, chat) {
221
+ const controls = result.controls || [];
222
+ const small = controls.filter((item) => item.w < 44 || item.h < 44);
223
+ push('shell.hit-target', 'layout', small.length ? 'fail' : 'pass',
224
+ small.length ? '命中区不足 44px:' + small.slice(0, 5).map((item) => (item.label || item.id) + ' ' + item.w + '×' + item.h).join('、') : '全部控件 ≥44×44');
225
+
226
+ const nonSemantic = controls.filter((item) => item.tag !== 'BUTTON' && item.tag !== 'A');
227
+ push('shell.controls-semantic', 'layout', nonSemantic.length ? 'fail' : 'pass',
228
+ nonSemantic.length ? '非语义控件:' + nonSemantic.slice(0, 5).map((item) => item.tag + '.' + (item.id || item.cls)).join('、') : '控件均为 button/a');
229
+
230
+ const unnamed = controls.filter((item) => !(item.label || item.text || '').trim());
231
+ push('shell.a11y-name', 'layout', unnamed.length ? 'fail' : 'pass',
232
+ unnamed.length ? '缺可访问名:' + unnamed.slice(0, 5).map((item) => item.id || item.cls).join('、') : '控件均有可访问名');
233
+
234
+ const quick = result.quick;
235
+ const expected = Array.isArray(chat.quickCommands) ? chat.quickCommands.length : 0;
236
+ if (!expected) {
237
+ push('shell.quick-visible', 'layout', 'skip', '应用未配置快捷问题');
238
+ } else if (!quick) {
239
+ push('shell.quick-visible', 'layout', 'fail', '快捷问题容器未渲染(配置 ' + expected + ' 条)');
240
+ } else {
241
+ const visible = quick.count >= expected && quick.scrollWidth <= quick.clientWidth + 1;
242
+ push('shell.quick-visible', 'layout', visible ? 'pass' : 'fail',
243
+ '渲染 ' + quick.count + '/' + expected + ' 条;内容宽 ' + quick.scrollWidth + ' / 容器 ' + quick.clientWidth);
244
+ }
245
+
246
+ const capabilities = [];
247
+ if (chat.enableVoiceInput !== false) capabilities.push(['voice-toggle', '语音输入']);
248
+ if (chat.enableImageUpload !== false || chat.enableVideoUpload !== false) capabilities.push(['media-add', '图片/视频上传']);
249
+ const present = capabilities.map(([id]) => controls.some((item) => item.id === id && item.w > 0));
250
+ if (capabilities.length === 0) {
251
+ push('shell.control-present', 'layout', 'skip', '能力全部关闭');
252
+ } else {
253
+ const missing = capabilities.filter(([id]) => !controls.some((item) => item.id === id && item.w > 0));
254
+ push('shell.control-present', 'layout', missing.length ? 'fail' : 'pass',
255
+ missing.length ? '能力开启但控件缺席:' + missing.map(([, title]) => title).join('、') : '能力与控件一致(' + present.filter(Boolean).length + ' 项)');
256
+ }
257
+
258
+ const icons = result.icons || [];
259
+ const broken = icons.filter((item) => !item.maskActive && !item.hasContent);
260
+ push('shell.icon-render', 'layout', icons.length === 0 ? 'skip' : broken.length ? 'fail' : 'pass',
261
+ icons.length === 0 ? '没有快捷问题图标' : broken.length ? '图标不可见:' + broken.length + ' 个' : '图标可见(遮罩或自绘)');
262
+
263
+ const blank = result.blank;
264
+ if (!blank || blank.blocks < 2) {
265
+ push('shell.blank', 'layout', 'skip', '块数量不足,无法计算空白');
266
+ } else {
267
+ const limit = Math.round(blank.viewport * 0.35);
268
+ push('shell.blank', 'layout', blank.maxGap > limit ? 'fail' : 'pass',
269
+ '最大块间空白 ' + blank.maxGap + 'px(上限 ' + limit + 'px;' + blank.blocks + ' 块)');
270
+ }
271
+ }
272
+
273
+ async function runChrome(chrome, htmlFile, expression, screenshotPath) {
274
+ const session = await openChromeSession({ chrome, url: 'file://' + htmlFile });
275
+ if (!session) throw new Error('无头浏览器未启动');
276
+ try {
277
+ const value = JSON.parse(await session.evaluate(expression));
278
+ if (screenshotPath) writeFileSync(screenshotPath, await session.screenshot());
279
+ return { ...value, product: await session.version(), screenshot: screenshotPath };
280
+ } finally {
281
+ session.close();
282
+ }
283
+ }