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

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 (91) hide show
  1. package/.tbox/app.json +1 -1
  2. package/.tbox/default-modules.json +1 -1
  3. package/.tbox/miniapp-containers.json +1 -1
  4. package/AGENTS.md +8 -7
  5. package/apps/client/index.html +0 -43
  6. package/apps/client/scripts/check-evidence.mjs +327 -77
  7. package/apps/client/scripts/evidence-gate.mjs +135 -0
  8. package/apps/client/scripts/evidence-gate.test.mjs +77 -0
  9. package/apps/client/scripts/render-card.mjs +20 -67
  10. package/apps/client/scripts/surface-css.mjs +51 -0
  11. package/apps/client/src/app.config.ts +4 -1
  12. package/apps/client/src/styles/brand.css +2 -3
  13. package/apps/client/src/styles/tailwind.css +17 -17
  14. package/apps/server/scripts/scenario-lib.mjs +2 -1
  15. package/docs/agent/agent-prompt.md +1 -1
  16. package/docs/agent/card-action.md +5 -0
  17. package/docs/agent/card.md +44 -2
  18. package/docs/agent/kit.md +2 -2
  19. package/docs/agent/style.md +8 -2
  20. package/docs/agent/tool-emits-card.md +7 -2
  21. package/docs/agent/tool.md +2 -0
  22. package/docs/agent/verify.md +23 -9
  23. package/package.json +16 -5
  24. package/packages/agent-ui-kit/AGENTS.md +1 -1
  25. package/packages/agent-ui-kit/catalog.json +7 -3
  26. package/packages/agent-ui-kit/package.json +1 -1
  27. package/packages/agent-ui-kit/src/ChatPage.tsx +40 -16
  28. package/packages/agent-ui-kit/src/card/action-list-pending.test.tsx +91 -0
  29. package/packages/agent-ui-kit/src/card/define-card.test.ts +25 -0
  30. package/packages/agent-ui-kit/src/card/define-card.ts +18 -5
  31. package/packages/agent-ui-kit/src/card/primitives.tsx +122 -27
  32. package/packages/agent-ui-kit/src/card/view-card-inline.test.tsx +42 -0
  33. package/packages/agent-ui-kit/src/card/view-card.test.tsx +79 -0
  34. package/packages/agent-ui-kit/src/card/view-card.tsx +245 -0
  35. package/packages/agent-ui-kit/src/components/ChatInput/index.tsx +1 -1
  36. package/packages/agent-ui-kit/src/components/HistoryEntry/index.tsx +2 -2
  37. package/packages/agent-ui-kit/src/components/MessageBubble/index.tsx +11 -5
  38. package/packages/agent-ui-kit/src/components/QuickCommands/index.test.tsx +3 -1
  39. package/packages/agent-ui-kit/src/components/QuickCommands/index.tsx +31 -8
  40. package/packages/agent-ui-kit/src/index.ts +4 -0
  41. package/packages/agent-ui-kit/src/preview-provider.tsx +47 -0
  42. package/packages/agent-ui-kit/src/surface.test.tsx +35 -0
  43. package/packages/agent-ui-kit/src/surface.tsx +44 -0
  44. package/packages/agent-ui-kit/src/theme/base.css +9 -11
  45. package/packages/agent-ui-kit/src/theme/contract.json +45 -1
  46. package/packages/agent-ui-kit/src/theme/tokens.css +8 -11
  47. package/pnpm-lock.template.yaml +91 -91
  48. package/pnpm-workspace.template.yaml +10 -10
  49. package/scripts/assert-pack.mjs +48 -0
  50. package/scripts/check-css-target.mjs +6 -3
  51. package/scripts/checks.json +123 -26
  52. package/.tbox/card-render/baseline/demo.png +0 -0
  53. package/.tbox/card-render/demo.html +0 -342
  54. package/.tbox/card-render/demo.png +0 -0
  55. package/.tbox/card-render/scale-demo.audit.html +0 -984
  56. package/.tbox/card-render/scale-demo.html +0 -939
  57. package/.tbox/evidence/cards.txt +0 -1
  58. package/.tbox/evidence/gate.json +0 -1
  59. package/.tbox/evidence/last-gate.json +0 -1
  60. package/.tbox/evidence/scenarios.json +0 -1
  61. package/apps/client/.tbox-gen/._manifest.json +0 -0
  62. package/apps/client/.tbox-gen/._registry.client.ts +0 -0
  63. package/apps/client/.tbox-gen/._registry.server.ts +0 -0
  64. package/apps/client/.tbox-gen/app-registry.ts +0 -3
  65. package/apps/client/.tbox-gen/documents/._index.html +0 -0
  66. package/apps/client/.tbox-gen/documents/_tbox/._card-preview.html +0 -0
  67. package/apps/client/.tbox-gen/documents/_tbox/card-preview.html +0 -62
  68. package/apps/client/.tbox-gen/documents/index.html +0 -63
  69. package/apps/client/.tbox-gen/entries/._card-preview.tsx +0 -0
  70. package/apps/client/.tbox-gen/entries/._index.tsx +0 -0
  71. package/apps/client/.tbox-gen/entries/card-preview.tsx +0 -6
  72. package/apps/client/.tbox-gen/entries/index.tsx +0 -11
  73. package/apps/client/.tbox-gen/manifest.json +0 -17
  74. package/apps/client/.tbox-gen/registry.client.ts +0 -6
  75. package/apps/client/.tbox-gen/registry.server.ts +0 -15
  76. package/apps/client/STYLE_GUIDE.md +0 -48
  77. package/apps/client/VISUAL_RESTORE.md +0 -90
  78. package/scripts/._compat-probe.mjs +0 -0
  79. package/scripts/compat-probe.mjs +0 -108
  80. /package/{.tbox/card-render/._demo.html → apps/client/scripts/._evidence-gate.mjs} +0 -0
  81. /package/{.tbox/card-render/._demo.png → apps/client/scripts/._evidence-gate.test.mjs} +0 -0
  82. /package/{.tbox/card-render/._scale-demo.audit.html → apps/client/scripts/._surface-css.mjs} +0 -0
  83. /package/{.tbox/card-render/._scale-demo.html → packages/agent-ui-kit/src/._preview-provider.tsx} +0 -0
  84. /package/{.tbox/card-render/baseline/._demo.png → packages/agent-ui-kit/src/._surface.test.tsx} +0 -0
  85. /package/{.tbox/evidence/._cards.txt → packages/agent-ui-kit/src/._surface.tsx} +0 -0
  86. /package/{.tbox/evidence/._gate.json → packages/agent-ui-kit/src/card/._action-list-pending.test.tsx} +0 -0
  87. /package/{.tbox/evidence/._last-gate.json → packages/agent-ui-kit/src/card/._define-card.test.ts} +0 -0
  88. /package/{.tbox/evidence/._scenarios.json → packages/agent-ui-kit/src/card/._view-card-inline.test.tsx} +0 -0
  89. /package/{apps/client/._STYLE_GUIDE.md → packages/agent-ui-kit/src/card/._view-card.test.tsx} +0 -0
  90. /package/{apps/client/._VISUAL_RESTORE.md → packages/agent-ui-kit/src/card/._view-card.tsx} +0 -0
  91. /package/{apps/client/.tbox-gen/._app-registry.ts → scripts/._assert-pack.mjs} +0 -0
@@ -0,0 +1,135 @@
1
+ /**
2
+ * 证据门禁的纯函数:内容哈希、验收漂移、覆盖集合、软闩判定、颜色对比。
3
+ *
4
+ * 从 check-evidence.mjs 抽出,便于用 vitest 直接测;脚本只做 IO 与编排。
5
+ */
6
+ import { createHash } from 'node:crypto';
7
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
8
+ import path from 'node:path';
9
+
10
+ export const HASH_SOURCE_DIRS = ['apps', 'packages', 'config', 'scenarios'];
11
+ export const HASH_SKIP = new Set(['node_modules', 'dist', 'dist-ssr', '.tbox-gen', '.tbox', '.git', '.vite']);
12
+
13
+ /** 交付内容哈希:路径 + 内容,同一文件改内容也能被软闩捕获。 */
14
+ export function hashSourceTree(root) {
15
+ const hash = createHash('sha256');
16
+ let files = 0;
17
+ const walk = (dir, rel) => {
18
+ let entries;
19
+ try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
20
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
21
+ if (HASH_SKIP.has(entry.name) || entry.name.startsWith('._') || entry.name === '.DS_Store') continue;
22
+ const abs = path.join(dir, entry.name);
23
+ const next = rel + '/' + entry.name;
24
+ if (entry.isDirectory()) { walk(abs, next); continue; }
25
+ if (!entry.isFile()) continue;
26
+ try {
27
+ const stat = statSync(abs);
28
+ hash.update(next + '\0' + stat.size + '\0');
29
+ hash.update(readFileSync(abs));
30
+ files += 1;
31
+ } catch { /* 读失败的条目不影响其他内容 */ }
32
+ }
33
+ };
34
+ for (const name of HASH_SOURCE_DIRS) {
35
+ const abs = path.join(root, name);
36
+ if (existsSync(abs)) walk(abs, name);
37
+ }
38
+ for (const name of ['package.json', 'pnpm-lock.yaml']) {
39
+ const abs = path.join(root, name);
40
+ if (!existsSync(abs)) continue;
41
+ try { hash.update(name + '\0'); hash.update(readFileSync(abs)); files += 1; } catch { /* ignore */ }
42
+ }
43
+ return { hash: hash.digest('hex').slice(0, 16), files };
44
+ }
45
+
46
+ export function acceptanceDrift(prevGate, acceptanceHash, acceptanceIds) {
47
+ if (!prevGate || !prevGate.acceptanceHash || !acceptanceHash || prevGate.acceptanceHash === acceptanceHash) {
48
+ return { added: [], removed: [], drift: [] };
49
+ }
50
+ const prevIds = Array.isArray(prevGate.acceptanceIds) ? prevGate.acceptanceIds : [];
51
+ const added = acceptanceIds.filter((id) => !prevIds.includes(id));
52
+ const removed = prevIds.filter((id) => !acceptanceIds.includes(id));
53
+ const detail = '验收文件哈希变化' + (added.length ? ';新增 ' + added.join('、') : '') + (removed.length ? ';删除 ' + removed.join('、') : '');
54
+ return { added, removed, drift: [{ kind: 'acceptance', detail }] };
55
+ }
56
+
57
+ export function shouldReopen(prevGate, verdict, contentHash) {
58
+ return Boolean(
59
+ verdict === 'deliverable' &&
60
+ prevGate &&
61
+ prevGate.verdict === 'deliverable' &&
62
+ prevGate.contentHash &&
63
+ contentHash &&
64
+ prevGate.contentHash !== contentHash,
65
+ );
66
+ }
67
+
68
+ export function coverageSets(scenarioResults, originByFile) {
69
+ const covered = new Set();
70
+ const declared = new Set();
71
+ for (const result of scenarioResults) {
72
+ if (!result.ok) continue;
73
+ for (const id of result.covers ?? []) {
74
+ declared.add(id);
75
+ if (originByFile.get(result.file) !== 'recorded') covered.add(id);
76
+ }
77
+ }
78
+ return { covered, declared };
79
+ }
80
+
81
+ export function scenarioKey(appDir, file) {
82
+ return path.relative(appDir, file);
83
+ }
84
+
85
+ export function parseColor(value) {
86
+ if (!value) return null;
87
+ const oklch = /^oklch\(\s*([\d.]+)(%?)\s+([\d.]+)\s+([\d.]+)(?:deg|rad|grad|turn)?(?:\s*\/\s*[\d.]+%?)?\s*\)$/i.exec(value);
88
+ if (oklch) {
89
+ const lightness = Number(oklch[1]) / (oklch[2] === '%' ? 100 : 1);
90
+ const chroma = Number(oklch[3]);
91
+ const hue = (Number(oklch[4]) * Math.PI) / 180;
92
+ const a = chroma * Math.cos(hue);
93
+ const b = chroma * Math.sin(hue);
94
+ const lRoot = lightness + 0.3963377774 * a + 0.2158037573 * b;
95
+ const mRoot = lightness - 0.1055613458 * a - 0.0638541728 * b;
96
+ const sRoot = lightness - 0.0894841775 * a - 1.291485548 * b;
97
+ const l = lRoot ** 3;
98
+ const m = mRoot ** 3;
99
+ const sVal = sRoot ** 3;
100
+ const linear = [
101
+ 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * sVal,
102
+ -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * sVal,
103
+ -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * sVal,
104
+ ];
105
+ return linear.map((channel) => {
106
+ const gamma = channel <= 0.0031308 ? 12.92 * channel : 1.055 * Math.pow(Math.max(channel, 0), 1 / 2.4) - 0.055;
107
+ return Math.round(Math.min(1, Math.max(0, gamma)) * 255);
108
+ });
109
+ }
110
+ const hex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(value);
111
+ if (hex) {
112
+ let h = hex[1];
113
+ if (h.length === 3) h = h.split('').map((c) => c + c).join('');
114
+ return [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16));
115
+ }
116
+ const rgb = /^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(value);
117
+ if (rgb) return [Number(rgb[1]), Number(rgb[2]), Number(rgb[3])];
118
+ return null;
119
+ }
120
+
121
+ export function luminance(rgb) {
122
+ const channel = (c) => {
123
+ const x = c / 255;
124
+ return x <= 0.03928 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);
125
+ };
126
+ return 0.2126 * channel(rgb[0]) + 0.7152 * channel(rgb[1]) + 0.0722 * channel(rgb[2]);
127
+ }
128
+
129
+ export function contrastRatio(fg, bg) {
130
+ const a = luminance(fg);
131
+ const b = luminance(bg);
132
+ const hi = Math.max(a, b);
133
+ const lo = Math.min(a, b);
134
+ return (hi + 0.05) / (lo + 0.05);
135
+ }
@@ -0,0 +1,77 @@
1
+ import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import path from 'node:path';
4
+ import { afterEach, describe, expect, it } from 'vitest';
5
+ import {
6
+ acceptanceDrift,
7
+ contrastRatio,
8
+ coverageSets,
9
+ hashSourceTree,
10
+ parseColor,
11
+ shouldReopen,
12
+ } from './evidence-gate.mjs';
13
+
14
+ let root = '';
15
+
16
+ afterEach(() => {
17
+ if (root) rmSync(root, { recursive: true, force: true });
18
+ root = '';
19
+ });
20
+
21
+ describe('hashSourceTree', () => {
22
+ it('同一路径改内容会改变哈希,跳过 node_modules / .tbox', () => {
23
+ root = mkdtempSync(path.join(tmpdir(), 'tbox-hash-'));
24
+ mkdirSync(path.join(root, 'apps'), { recursive: true });
25
+ writeFileSync(path.join(root, 'apps/a.ts'), '// a\n');
26
+ const first = hashSourceTree(root);
27
+ writeFileSync(path.join(root, 'apps/a.ts'), '// b\n');
28
+ const second = hashSourceTree(root);
29
+ expect(second.hash).not.toBe(first.hash);
30
+ expect(second.files).toBe(first.files);
31
+
32
+ mkdirSync(path.join(root, 'node_modules/x'), { recursive: true });
33
+ mkdirSync(path.join(root, '.tbox'), { recursive: true });
34
+ writeFileSync(path.join(root, 'node_modules/x/a.ts'), 'changed\n');
35
+ writeFileSync(path.join(root, '.tbox/a.ts'), 'changed\n');
36
+ expect(hashSourceTree(root).hash).toBe(second.hash);
37
+ });
38
+ });
39
+
40
+ describe('acceptanceDrift / shouldReopen', () => {
41
+ it('列出新增与删除的验收项', () => {
42
+ const prev = { acceptanceHash: 'old', acceptanceIds: ['a', 'b'] };
43
+ const result = acceptanceDrift(prev, 'new', ['a', 'c']);
44
+ expect(result.added).toEqual(['c']);
45
+ expect(result.removed).toEqual(['b']);
46
+ expect(result.drift[0].kind).toBe('acceptance');
47
+ expect(acceptanceDrift(prev, 'old', ['a', 'b']).drift).toEqual([]);
48
+ });
49
+
50
+ it('只有交付后内容变化才 reopen', () => {
51
+ const prev = { verdict: 'deliverable', contentHash: 'h1' };
52
+ expect(shouldReopen(prev, 'deliverable', 'h2')).toBe(true);
53
+ expect(shouldReopen(prev, 'deliverable', 'h1')).toBe(false);
54
+ expect(shouldReopen({ ...prev, verdict: 'reopened' }, 'deliverable', 'h2')).toBe(false);
55
+ expect(shouldReopen(prev, 'failing', 'h2')).toBe(false);
56
+ });
57
+ });
58
+
59
+ describe('coverageSets', () => {
60
+ it('recorded 场景只计入 declared,不覆盖验收', () => {
61
+ const spec = { ok: true, file: '/app/scenarios/spec.json', covers: ['a'] };
62
+ const recorded = { ok: true, file: '/app/scenarios/rec.json', covers: ['b'] };
63
+ const origins = new Map([[spec.file, 'spec'], [recorded.file, 'recorded']]);
64
+ const { covered, declared } = coverageSets([spec, recorded], origins);
65
+ expect([...covered]).toEqual(['a']);
66
+ expect([...declared].sort()).toEqual(['a', 'b']);
67
+ });
68
+ });
69
+
70
+ describe('对比度颜色', () => {
71
+ it('解析 hex / rgb / oklch,并计算黑白对比', () => {
72
+ expect(parseColor('#fff')).toEqual([255, 255, 255]);
73
+ expect(parseColor('rgb(0, 0, 0)')).toEqual([0, 0, 0]);
74
+ expect(parseColor('oklch(0.62796 0.25768 29.23)')).toEqual([255, 0, 0]);
75
+ expect(contrastRatio([0, 0, 0], [255, 255, 255])).toBeCloseTo(21, 0);
76
+ });
77
+ });
@@ -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,6 +19,7 @@
19
19
  */
20
20
  import { createRequire } from 'node:module';
21
21
  import { copyFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
22
+ import { buildSurfaceCss, SURFACE_CSS_SENTINELS } from './surface-css.mjs';
22
23
  import { execFileSync } from 'node:child_process';
23
24
  import path from 'node:path';
24
25
  import process from 'node:process';
@@ -146,58 +147,10 @@ async function loadRegistry(vite) {
146
147
  return { client, server };
147
148
  }
148
149
 
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
-
150
+ // ── 2. 样式:与 dev/build 同一条 Vite + Tailwind 管线 ────────────────
162
151
  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');
152
+ const { cssText, bytes, missing } = await buildSurfaceCss(vite, { clientDir, appDir });
153
+ return { css: cssText, bytes, missing };
201
154
  }
202
155
 
203
156
  function buildHtmlDocument(cardHtml, css) {
@@ -208,7 +161,6 @@ function buildHtmlDocument(cardHtml, css) {
208
161
  <meta name="viewport" content="width=device-width, initial-scale=1">
209
162
  <title>tbox card render</title>
210
163
  <style>
211
- html { font-size: 50px; }
212
164
  body { margin: 0; background: #f5f6f7; color: #1f1f1f; font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif; }
213
165
  /* 左对齐固定 8px:无头 Chrome 有最小窗口宽(约 500),居中会被 420 截图裁掉右缘。 */
214
166
  .tbox-card-render { width: 375px; max-width: calc(100% - 16px); margin: 16px 8px; }
@@ -460,16 +412,10 @@ async function renderSamples(vite, registries, cardType, samples) {
460
412
  }
461
413
  const React = (await import('react')).default;
462
414
  const { renderToStaticMarkup } = await import('react-dom/server');
463
- const { createStore } = await import('zustand/vanilla');
464
- const { useStore } = await import('zustand');
465
415
  const kit = await vite.ssrLoadModule('@tbox.cn/app-agent-ui-kit');
466
416
 
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;
417
+ // 与 check:fast / 预览同一条装配(SurfaceHarness):动作不落库、isGenerating=false。
418
+ const harness = kit.createSurfaceHarness({ cards: components });
473
419
 
474
420
  const rendered = [];
475
421
  for (const sample of samples) {
@@ -478,9 +424,7 @@ async function renderSamples(vite, registries, cardType, samples) {
478
424
  let html;
479
425
  try {
480
426
  html = renderToStaticMarkup(
481
- React.createElement(
482
- kit.KitChatProvider,
483
- { store: hook, cards: components, rawCards: components },
427
+ harness.wrap(
484
428
  React.createElement(Component, { data: parsed?.success ? parsed.data : sample.data, cardId: `render-${cardType}`, isHistory: false, actionTokens: {} }),
485
429
  ),
486
430
  );
@@ -697,7 +641,15 @@ async function main() {
697
641
  }
698
642
  const selected = selectSamples(samples, args);
699
643
  const rendered = await renderSamples(vite, registries, args.type, selected);
700
- const css = await buildStyleSheet(vite);
644
+ const surface = await buildStyleSheet(vite);
645
+ const css = surface.css;
646
+ // 证据自校验:CSS 为空或哨兵缺失时,截图/HTML 只会说谎——直接失败,不产出「无样式证据」。
647
+ if (surface.missing.length > 0 || surface.bytes < 20000) {
648
+ throw new Error(
649
+ `表面 CSS 不可信:${surface.bytes} 字节,缺哨兵 ${surface.missing.join('、') || '无'}。\n` +
650
+ ` 修复:确认 apps/client/src/styles/tailwind.css 存在且 @source 覆盖 src 与 kit;本命令与 check:fast 同一管线(surface-css.mjs)。`,
651
+ );
652
+ }
701
653
  const outDir = path.resolve(args.out ?? path.join(appDir, '.tbox/card-render'));
702
654
  const baselineDir = path.join(outDir, 'baseline');
703
655
  const results = rendered.map((sample) => {
@@ -710,7 +662,7 @@ async function main() {
710
662
  });
711
663
  for (const sample of results) if (sample.schemaValid === false) warnings.push(`${args.type} / ${sample.label} 的样例未过 dataSchema:${(sample.issues ?? []).join(';')}`);
712
664
 
713
- const result = { ok: true, cardType: args.type, samples: results, warnings };
665
+ const result = { ok: true, cardType: args.type, cssBytes: surface.bytes, samples: results, warnings };
714
666
  if (args.json) {
715
667
  console.log(JSON.stringify(result));
716
668
  return;
@@ -728,6 +680,7 @@ async function main() {
728
680
  else console.log(` ✅ 视觉差异 ${(sample.visual.ratio * 100).toFixed(3)}%`);
729
681
  }
730
682
  }
683
+ console.log(` 样式:${surface.bytes} 字节(与 dev/build 同一管线)`);
731
684
  if (!args.outline) console.log(' 提示:--outline 看层级与按钮;--all 渲染全部样例;--json 机器可读');
732
685
  } finally {
733
686
  await vite.close();
@@ -0,0 +1,51 @@
1
+ /**
2
+ * surface-css — 证据面与截图共用的一份样式构建。
3
+ *
4
+ * 与 dev/build 同一条 Vite + Tailwind 管线(同一个入口、同一组 @source、同一层序),
5
+ * 所以「证据里看到的样式」就是「运行时拿到的样式」。不再有 Less / pxToRem / 固定根字号。
6
+ *
7
+ * 用法:
8
+ * const css = await buildSurfaceCss(vite, { clientDir, appDir });
9
+ * css.cssText / css.bytes / css.sentinels
10
+ */
11
+ import { mkdirSync, writeFileSync } from 'node:fs';
12
+ import { createRequire } from 'node:module';
13
+ import path from 'node:path';
14
+
15
+ /** 必须出现在产物里的哨兵:少了任何一个,说明样式管线断了,证据不可信。 */
16
+ export const SURFACE_CSS_SENTINELS = ['--tbox-primary', '.tbox-card', '.bg-card'];
17
+
18
+ function resolveOptional(require, id) {
19
+ try {
20
+ return require.resolve(id);
21
+ } catch {
22
+ return undefined;
23
+ }
24
+ }
25
+
26
+ /**
27
+ * 构建整份表面样式(tailwind 工具类 + kit 基座 + 主题包 + 品牌覆写,顺序与 app.config.ts 一致)。
28
+ * @returns {Promise<{ cssText: string, bytes: number, missing: string[], entry: string }>}
29
+ */
30
+ export async function buildSurfaceCss(vite, { clientDir, appDir }) {
31
+ const require = createRequire(path.join(clientDir, 'package.json'));
32
+ const files = [
33
+ path.join(clientDir, 'src/styles/tailwind.css'),
34
+ resolveOptional(require, '@tbox.cn/app-agent-ui-kit/theme/base.css'),
35
+ resolveOptional(require, '@tbox.cn/app-theme-tbox/index.css'),
36
+ path.join(clientDir, 'src/styles/brand.css'),
37
+ ].filter(Boolean);
38
+
39
+ const entryDir = path.join(appDir, '.tbox/evidence');
40
+ mkdirSync(entryDir, { recursive: true });
41
+ const entry = path.join(entryDir, 'surface.css');
42
+ const imports = files
43
+ .map((file) => `@import "${path.relative(entryDir, file).split(path.sep).join('/')}";`)
44
+ .join('\n');
45
+ writeFileSync(entry, `/* 由 surface-css.mjs 生成:证据/截图共用的样式入口 */\n${imports}\n`);
46
+
47
+ const result = await vite.transformRequest(`/@fs${entry}?direct`);
48
+ const cssText = typeof result === 'string' ? result : (result?.code ?? '');
49
+ const missing = SURFACE_CSS_SENTINELS.filter((sentinel) => !cssText.includes(sentinel));
50
+ return { cssText, bytes: Buffer.byteLength(cssText), missing, entry };
51
+ }
@@ -5,9 +5,10 @@
5
5
  * (scopeKey 在首建时捕获,避免 module 顶层 getAuthClient 抢先建缺省实例)。
6
6
  * setup 在 runtime 配置后、页面渲染前执行:主题应用 + chat 配置快照。
7
7
  */
8
+ import { createElement, type ReactNode } from 'react';
8
9
  import { createAuthClient } from '@tbox.cn/app-agent-sdk-client';
9
10
  import type { AgentAppConfig } from '@tbox.cn/app-agent-sdk-client/app';
10
- import { configureChatConfigDefaults } from '@tbox.cn/app-agent-ui-kit';
11
+ import { configureChatConfigDefaults, KitPreviewProvider } from '@tbox.cn/app-agent-ui-kit';
11
12
  import './styles/tailwind.css';
12
13
  import '@tbox.cn/app-agent-ui-kit/theme/base.css';
13
14
  // 品牌主题(出厂接线——theme-tbox 平台品牌资产包:素材/标题经本包承载,模块零品牌资产)。
@@ -29,6 +30,8 @@ createAuthClient({
29
30
 
30
31
  const config = {
31
32
  apiBaseUrl: import.meta.env.VITE_API_URL as string | undefined,
33
+ // 卡片预览面的装配根:预览页只渲染 SDK CardRenderer,kit 卡片需要 provider 才能拿到 store。
34
+ wrapPreview: (node: ReactNode) => createElement(KitPreviewProvider, null, node),
32
35
  setup() {
33
36
  applyTheme('tbox');
34
37
  // chat.json 构建期快照 → kit 静态配置 store(render 前注入,首帧即快照值;
@@ -3,8 +3,8 @@
3
3
  *
4
4
  * - 只覆写平台主题变量(`packages/agent-ui-kit/src/theme/contract.json` 的 platform 段)与壳外观,
5
5
  * 不 fork ChatPage、不改 kit 组件内部结构;
6
- * - 卡片样式优先用 kit 基元(零 less);确有应用级样式时在同目录另建 `cards.less` 并在此 @import;
7
- * - 尺寸统一 750 设计稿 px(构建期由 postcss-pxtorem 转 rem),字号下限 22px(≈11 屏幕像素);
6
+ * - 卡片样式优先用 kit 基元;确有应用级样式时写在卡片组件自己的工具类里,不新建 CSS 文件;
7
+ * - 尺寸与字号一律物理 px(没有 rem 换算,也没有动态根字号);字号只用 12/14/16/18/20/24/30/36 档;
8
8
  * - 变量名逐字取自 contract.json,写错名字不会报错、只会静默不生效——用 `docs/agent/kit.md` 的 token 表核对。
9
9
  *
10
10
  * 换品牌 = 改下面这一节里的值(十来个变量即可覆盖主色、底色、文字与圆角阴影)。
@@ -48,4 +48,3 @@ html[data-theme='tbox'] .chat-page {
48
48
  }
49
49
 
50
50
  /* 应用级卡片样式(没有就把这行删掉) */
51
- /* @import '../cards/cards.less'; */
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * - 主题值经 `@theme inline` 直接投影到 `--tbox-*`:工具类产物是 `var(--tbox-*)`,子树覆写照常生效;
5
5
  * - `source(none)` + 显式 @source:只扫应用源码与 kit,不扫 node_modules;
6
- * - 旧 Less(kit 壳、模块)仍在;迁移一个组件就删一份旧规则,未迁移部分保持原样。
6
+ * - 组件样式全部走工具类与语义令牌,没有 Less,也没有 rem 换算。
7
7
  */
8
8
  /* 显式层序:kit 的 base.css 与模块基座进 base 层,工具类恒在最后 */
9
9
  @layer theme, base, components, utilities;
@@ -37,24 +37,25 @@
37
37
  /* 主色上的文字:契约暂无对应项,先给纯白(E3 语义色) */
38
38
  --color-white: #ffffff;
39
39
  --color-scrim: rgba(0, 0, 0, 0.45);
40
- --color-primary-soft: rgba(22, 119, 255, 0.06);
40
+ /* 浅色底由主色派生:换品牌色后不再残留固定蓝。 */
41
+ --color-primary-soft: color-mix(in srgb, var(--tbox-primary) 8%, var(--tbox-bg-card));
41
42
  --color-warm: var(--tbox-bg-warm);
42
43
  --color-jade: var(--tbox-domain-parking-surface);
43
- --color-success-soft: var(--tbox-success-light, #e6f7f0);
44
- --color-warning-soft: var(--tbox-warning-light, #fff4e0);
45
- --color-neutral-soft: rgba(0, 0, 0, 0.06);
46
- --color-warn-surface: #fff8ea;
47
- --color-warn-border: #f7e2bb;
48
- --color-warn-ink: #a8701b;
44
+ --color-success-soft: color-mix(in srgb, var(--tbox-success) 10%, var(--tbox-bg-card));
45
+ --color-warning-soft: color-mix(in srgb, var(--tbox-warning, #d98a1a) 12%, var(--tbox-bg-card));
46
+ --color-neutral-soft: color-mix(in srgb, var(--tbox-text-primary) 6%, var(--tbox-bg-card));
47
+ --color-warn-surface: color-mix(in srgb, var(--tbox-warning, #d98a1a) 8%, var(--tbox-bg-card));
48
+ --color-warn-border: color-mix(in srgb, var(--tbox-warning, #d98a1a) 28%, var(--tbox-bg-card));
49
+ --color-warn-ink: color-mix(in srgb, var(--tbox-warning, #d98a1a) 72%, var(--tbox-ink));
49
50
  --color-white-soft: rgba(255, 255, 255, 0.04);
50
- --color-danger-soft: #fdf0ee;
51
- --color-danger-border: #fcc9bb;
51
+ --color-danger-soft: color-mix(in srgb, var(--tbox-error) 8%, var(--tbox-bg-card));
52
+ --color-danger-border: color-mix(in srgb, var(--tbox-error) 30%, var(--tbox-bg-card));
52
53
  --color-white-line: rgba(255, 255, 255, 0.35);
53
54
  --color-white-dim: rgba(255, 255, 255, 0.84);
54
55
  --color-member-accent: #91ad60;
55
- --color-focus-ring: rgba(99, 137, 61, 0.24);
56
+ --color-focus-ring: color-mix(in srgb, var(--tbox-primary) 45%, transparent);
56
57
 
57
- /* 圆角:先清空命名空间再用 px 补齐——默认档位是 rem,会被动态根字号放大(rounded-2xl 会变成 50px)。
58
+ /* 圆角:先清空命名空间再用 px 补齐(默认档位是 rem,统一改成物理 px)。
58
59
  sm/md/lg 来自契约(lg = 卡框 24px),其余档位是物理 px 的常规阶梯。 */
59
60
  --radius-*: initial;
60
61
  --radius-xs: 4px;
@@ -71,9 +72,8 @@
71
72
  --shadow-md: var(--tbox-shadow-md);
72
73
  --shadow-lg: var(--tbox-shadow-lg);
73
74
 
74
- /* 间距:1 单位 = 4px。必须用 px:宿主入口按设计稿动态设置根字号(移动端约 50px),
75
- 若用 rem,p-4 会变成 50px,整张卡放大数倍。 */
76
- /* 断点用 px:默认档位是 rem,会被宿主入口的动态根字号放大(40rem 会变成 2000px) */
75
+ /* 间距:1 单位 = 4px,全部物理 px(默认档位是 rem,统一改成 px)。 */
76
+ /* 断点用 px(默认档位是 rem) */
77
77
  --breakpoint-sm: 640px;
78
78
  --breakpoint-md: 768px;
79
79
  --breakpoint-lg: 1024px;
@@ -82,7 +82,7 @@
82
82
 
83
83
  --spacing: 4px;
84
84
 
85
- /* 字号同样先清空命名空间再用 px 补齐(默认档位是 rem,会被根字号放大);档位 12/14/16/18/20/24/30/36。 */
85
+ /* 字号同样先清空命名空间再用 px 补齐(默认档位是 rem);档位 12/14/16/18/20/24/30/36。 */
86
86
  --text-*: initial;
87
87
  --text-xs: 12px;
88
88
  --text-xs--line-height: 1.5;
@@ -220,7 +220,7 @@
220
220
  }
221
221
 
222
222
  /* 模块动效关键帧集中登记(模块迁 Tailwind 后不再随模块 CSS 出货)。
223
- 值为物理 px:原模块 CSS 里的小写 px 是 750 设计稿值(构建期折半),迁入此处时已折半。 */
223
+ 值为物理 px。 */
224
224
  @keyframes member-points-rule-backdrop-in {
225
225
  from { opacity: 0; }
226
226
  to { opacity: 1; }
@@ -190,7 +190,8 @@ export async function recordScenario({ registry, name, steps, user }) {
190
190
  const { createToolHarness } = await import('@tbox.cn/app-agent-sdk-server/testing');
191
191
  const harness = createToolHarness({ registry });
192
192
  const scenarioUser = typeof user === 'string' ? user : `scenario:${name}`;
193
- const out = { name, user: scenarioUser, steps: [] };
193
+ // 录制产物标记来源:验收闩不允许 recorded 场景单独覆盖验收项。
194
+ const out = { name, user: scenarioUser, origin: 'recorded', steps: [] };
194
195
  for (const step of steps) {
195
196
  const kind = step.action ? 'action' : 'tool';
196
197
  const id = step.action ?? step.tool;
@@ -20,7 +20,7 @@ pnpm exec tbox-app schema config/chat.json
20
20
  - 首行写身份句(「你是谁、服务谁」),随后按「服务范围 / 业务规则 / 沟通风格」分段。
21
21
  - 数据类问题一律要求「先调工具拿本轮结果再回答」,不要凭历史结论作答。
22
22
  - 操作类流程写清楚三类动作:什么时候只给信息、什么时候出确认卡、什么时候执行。
23
- - 按钮语义要写明:「卡片按钮会把用户意图作为下一条消息发回来,收到即为确认,直接执行、不要重复追问」——否则模型会反复确认。
23
+ - 按钮语义要写明:「卡片按钮优先走确定性动作(invoke),不需要模型再判断;只有需要模型补充信息时才走发消息(send)。收到动作结果直接执行,不要重复追问」——否则模型会把每个按钮都当成一轮对话。
24
24
 
25
25
  ## 对话配置
26
26
 
@@ -2,6 +2,9 @@
2
2
 
3
3
  > 本页管:卡片按钮的两种语义(发消息 / 触发动作)、确认弹层、禁用规则、动作的入参与返回值。|不管:卡片结构 → [card](card.md);工具出卡 → [tool-emits-card](tool-emits-card.md);基元 props → [kit](kit.md)。
4
4
 
5
+ > 视图卡的动作与三件套同形:`invoke` / `send` / `confirm` 写在 `view()` 的 `actions` 里,确认弹层、禁用与历史态由平台统一处理。
6
+ > 自己渲染动作的卡(`ActionList`)在 `defineCard` 里写 `actions: 'self'`;不写时 SDK 默认按钮条照旧渲染,容易出现两条动作。
7
+
5
8
  ## 两种按钮
6
9
 
7
10
  `useCardActions()` 给两个方法:
@@ -24,6 +27,8 @@
24
27
 
25
28
  按钮的 `disabled` 一定要接这个值,否则用户会在错误时机触发写操作。
26
29
 
30
+ `ActionList` 点击后进入 pending:同一张卡只允许一次在途(连点同 tick 也只执行一次),生成结束自动解除,20 秒兜底。手写按钮时用本地 pending 并把 `disabled` 一并接上。
31
+
27
32
  ## 令牌
28
33
 
29
34
  `invoke` 需要动作令牌:卡片 payload 的 `actionTokens[actionId]`,由服务端在出卡时签发,随卡片数据传给组件(`CardRenderProps.actionTokens`)。没有令牌时 `invoke` 只提示「该操作不可用」——说明这张卡上的该动作没有注册或没有签发。
@@ -1,8 +1,50 @@
1
1
  # 新增一张卡片
2
2
 
3
- > 本页管:卡片的三处落点(数据契约、服务端声明、客户端渲染)与成对规则。|不管:出卡协议 → [tool-emits-card](tool-emits-card.md);按钮 → [card-action](card-action.md)。
3
+ > 本页管:卡片的两种写法(视图卡默认 / 三件套仅富交互)、落点与成对规则。|不管:出卡协议 → [tool-emits-card](tool-emits-card.md);按钮 → [card-action](card-action.md)。
4
4
 
5
- ## 一张卡要有三样东西
5
+ ## 先选写法:默认视图卡
6
+
7
+ 卡片默认写**视图卡**:服务端一个文件,`view(data)` 返回可序列化的视图 JSON(积木 + 动作规格),客户端由 `app-build` 自动派生 `ViewCard`——没有 `apps/client/src/cards/<id>.card.tsx`,也不会报 `CARD_PAIR_MISSING`。
8
+
9
+ 只有需要局部自定义图形或富交互时,才写「数据契约 + 服务端声明 + 客户端渲染」三件套(L3,见本页末节)。
10
+
11
+ ### 视图卡(默认)
12
+
13
+ ```ts
14
+ import { defineViewCard } from '@tbox.cn/app-agent-sdk-server';
15
+
16
+ interface ParkingOrder {
17
+ plate: string;
18
+ payable: number;
19
+ }
20
+
21
+ export const card = defineViewCard<ParkingOrder>({
22
+ cardType: 'parking-order',
23
+ displayName: '停车订单',
24
+ description: '待支付停车订单与支付结果',
25
+ sampleState: { plate: '浙A·12345', payable: 5 },
26
+ view: (order) => ({
27
+ header: { title: '停车订单', status: { text: '待支付', tone: 'warning' } },
28
+ blocks: [
29
+ { kind: 'facts', items: [['车牌', order.plate]] },
30
+ { kind: 'bill', lines: [['停车费', '¥15']], total: ['应付', '¥' + order.payable] },
31
+ ],
32
+ actions: [{ label: '确认支付', invoke: { id: 'pay-parking', input: { plate: order.plate } }, confirm: { title: '确认支付?' } }],
33
+ }),
34
+ });
35
+ ```
36
+
37
+ - 积木:`hero` / `facts` / `bill` / `notice` / `tags` / `steps` / `list` / `ticket` / `timeline` / `empty`;动作规格与 `ActionList` 同形(label / send / invoke / confirm / style)。
38
+ - 预算写进 schema:积木 ≤4、提示 ≤1、属性 ≤5、列表 ≤3、账单行 ≤8、步骤 ≤5、时间线 ≤6、标签 ≤6、卡级动作 ≤2;作者期 `defineViewCard` 直接报错,生产侧 `cardOfView` 先截断再校验,不整张卡丢弃。
39
+ - 样例由 `sampleState` 与 `samples` 派生,不用手写大段 `sampleData`。
40
+ - 出卡用 `cardOfView(card, domainData, note)`:它先跑 `view()`,再走统一的出卡校验。
41
+ - `pnpm exec tbox-app new card <name> --view` 直接生成视图卡单文件;不带 `--view` 才生成三件套(仅富交互卡)。
42
+ - `pnpm exec tbox-app new feature <name> --view` 生成视图卡竖切(工具用 `cardOfView` 出卡);不带 `--view` 才是三件套起手(工具返回 `cards`)。
43
+ - 卡片自己渲染动作(`ActionList` / `ViewCard`)时,`defineCard` 必须写 `actions: 'self'`,否则 SDK 默认按钮条会叠加;不写动作的卡保持默认 `auto`。
44
+
45
+ ### 三件套(仅富交互卡)
46
+
47
+ 一张卡要有三样东西:
6
48
 
7
49
  | 位置 | 文件 | 作用 |
8
50
  |---|---|---|
package/docs/agent/kit.md CHANGED
@@ -23,7 +23,7 @@ import { Card, CardHeader, KeyValueList, StatusTag } from '@tbox.cn/app-agent-ui
23
23
  | `StatusTag` | 状态标签。 * | `children: ReactNode` `tone?: Tone` |
24
24
  | `Notice` | 提示条:说明、限制、下一步指引。 * | `children: ReactNode` `tone?: Tone` `icon?: ReactNode` |
25
25
  | `ActionRow` | 按钮行:主次两级,禁用整行。 * | `primary?: ReactNode` `secondary?: ReactNode` `disabled?: boolean` |
26
- | `CardButton` | — | `children: ReactNode` `onClick?: () => void` `variant?: 'primary' \| 'secondary' \| 'link'` `disabled?: boolean` |
26
+ | `CardButton` | — | `children: ReactNode` `onClick?: () => void` `variant?: 'primary' \| 'secondary' \| 'link'` `disabled?: boolean` `busy?: boolean` |
27
27
  | `ConfirmSheet` | 确认弹层:写操作前的一次确认。 | `open: boolean` `title: ReactNode` `description?: ReactNode` `confirmText?: string` `cancelText?: string` `onConfirm: () => void` `onCancel: () => void` |
28
28
  | `Ticket` | 票券形:券、凭证、卡包条目。 | `amount: ReactNode` `condition?: ReactNode` `meta?: ReactNode` `status?: ReactNode` `tone?: 'primary' \| 'muted'` |
29
29
  | `Steps` | 步骤/路线:取车路线、办理进度。 | `steps: StepItem[]` |
@@ -35,7 +35,7 @@ import { Card, CardHeader, KeyValueList, StatusTag } from '@tbox.cn/app-agent-ui
35
35
  | `Timeline` | 明细时间线:积分收支、停车计费。 * | `items: TimelineItem[]` |
36
36
  | `EmptyState` | 空态:没券、没订单、没记录时给一句解释与一个下一步。 * | `title: ReactNode` `description?: ReactNode` `action?: ReactNode` |
37
37
  | `TagList` | 标签组:口味、距离、适用条件。 * | `tags: ReactNode[]` `tone?: Tone` |
38
- | `ActionList` | 按钮组(描述对象版):把「发消息 / 确定性动作 / 确认弹层 / 禁用」收进一处。 | `actions: CardActionSpec[]` `api: CardActions` |
38
+ | `ActionList` | — | `actions: CardActionSpec[]` `api: CardActions` |
39
39
 
40
40
  ## 图标
41
41