@tbox.cn/app-template-agent 1.0.0-alpha.15 → 1.0.0-alpha.17

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 (90) hide show
  1. package/.gitignore +2 -0
  2. package/.tbox/app.json +1 -1
  3. package/.tbox/cache/._apps-client-strict.tsbuildinfo +0 -0
  4. package/.tbox/cache/._apps-client.tsbuildinfo +0 -0
  5. package/.tbox/cache/._apps-server-strict.tsbuildinfo +0 -0
  6. package/.tbox/cache/._apps-server.tsbuildinfo +0 -0
  7. package/.tbox/cache/._packages-agent-ui-kit-strict.tsbuildinfo +0 -0
  8. package/.tbox/cache/._packages-agent-ui-kit.tsbuildinfo +0 -0
  9. package/.tbox/cache/._packages-shared-strict.tsbuildinfo +0 -0
  10. package/.tbox/cache/._packages-shared.tsbuildinfo +0 -0
  11. package/.tbox/cache/apps-client-strict.tsbuildinfo +1 -0
  12. package/.tbox/cache/apps-client.tsbuildinfo +1 -0
  13. package/.tbox/cache/apps-server-strict.tsbuildinfo +1 -0
  14. package/.tbox/cache/apps-server.tsbuildinfo +1 -0
  15. package/.tbox/cache/packages-agent-ui-kit-strict.tsbuildinfo +1 -0
  16. package/.tbox/cache/packages-agent-ui-kit.tsbuildinfo +1 -0
  17. package/.tbox/cache/packages-shared-strict.tsbuildinfo +1 -0
  18. package/.tbox/cache/packages-shared.tsbuildinfo +1 -0
  19. package/.tbox/default-modules.json +1 -1
  20. package/.tbox/miniapp-containers.json +1 -1
  21. package/AGENTS.md +4 -0
  22. package/apps/client/scripts/._home-preset-wiring.test.ts +0 -0
  23. package/apps/client/scripts/._home-preset-wiring.ts +0 -0
  24. package/apps/client/scripts/._static-checks.test.mjs +0 -0
  25. package/apps/client/scripts/acceptance-changes.test.mjs +16 -3
  26. package/apps/client/scripts/check-evidence.mjs +69 -7
  27. package/apps/client/scripts/evidence-gate.mjs +9 -6
  28. package/apps/client/scripts/experience-checks.mjs +139 -0
  29. package/apps/client/scripts/geometry-kernel.test.mjs +3 -1
  30. package/apps/client/scripts/home-preset-wiring.test.ts +61 -0
  31. package/apps/client/scripts/home-preset-wiring.ts +41 -0
  32. package/apps/client/scripts/in-process-checks.mjs +100 -1
  33. package/apps/client/scripts/probe-checks.mjs +1 -0
  34. package/apps/client/scripts/static-checks.test.mjs +219 -0
  35. package/apps/client/src/cards/._home-preset.test.ts +0 -0
  36. package/apps/client/src/cards/._home-preset.ts +0 -0
  37. package/apps/client/src/cards/home-preset.test.ts +40 -0
  38. package/apps/client/src/cards/home-preset.ts +19 -0
  39. package/apps/client/src/cards/registry.ts +10 -3
  40. package/apps/client/src/pages/index/index.tsx +1 -1
  41. package/apps/client/src/styles/tailwind.css +3 -1
  42. package/apps/client/tsconfig.json +1 -0
  43. package/apps/client/vite.config.ts +15 -5
  44. package/apps/server/scripts/scenario-lib.mjs +12 -1
  45. package/config/._agent.jsonc +0 -0
  46. package/config/agent.jsonc +10 -0
  47. package/docs/agent/card-action.md +5 -1
  48. package/docs/agent/card.md +7 -1
  49. package/docs/agent/errors.md +7 -1
  50. package/docs/agent/kit.md +7 -6
  51. package/docs/agent/shell.md +3 -1
  52. package/docs/agent/style.md +37 -0
  53. package/docs/agent/verify.md +5 -2
  54. package/package.json +5 -4
  55. package/packages/agent-ui-kit/catalog.json +134 -5
  56. package/packages/agent-ui-kit/package.json +1 -1
  57. package/packages/agent-ui-kit/src/._contract.test.tsx +0 -0
  58. package/packages/agent-ui-kit/src/ChatPage.tsx +204 -27
  59. package/packages/agent-ui-kit/src/card/._confirm-fields.test.tsx +0 -0
  60. package/packages/agent-ui-kit/src/card/confirm-fields.test.tsx +106 -0
  61. package/packages/agent-ui-kit/src/card/primitives.tsx +270 -59
  62. package/packages/agent-ui-kit/src/card/use-card-actions.ts +5 -1
  63. package/packages/agent-ui-kit/src/card/view-card.tsx +113 -22
  64. package/packages/agent-ui-kit/src/chat-config.ts +2 -0
  65. package/packages/agent-ui-kit/src/components/ActionBar/DebugButton.tsx +12 -4
  66. package/packages/agent-ui-kit/src/components/ActionBar/index.tsx +61 -27
  67. package/packages/agent-ui-kit/src/components/BottomSheet/index.tsx +26 -2
  68. package/packages/agent-ui-kit/src/components/QuickCommands/index.tsx +60 -14
  69. package/packages/agent-ui-kit/src/components/ToolCallBlock/detail.test.ts +2 -0
  70. package/packages/agent-ui-kit/src/components/ToolCallBlock/detail.ts +9 -2
  71. package/packages/agent-ui-kit/src/contract.test.tsx +176 -0
  72. package/packages/agent-ui-kit/src/hooks/use-stick-to-bottom.test.tsx +101 -0
  73. package/packages/agent-ui-kit/src/hooks/use-stick-to-bottom.ts +35 -7
  74. package/packages/agent-ui-kit/src/index.ts +2 -0
  75. package/packages/agent-ui-kit/src/overlay/Overlay.tsx +21 -2
  76. package/packages/agent-ui-kit/src/overlay/overlay.test.tsx +15 -0
  77. package/packages/agent-ui-kit/src/preview-provider.tsx +8 -0
  78. package/packages/agent-ui-kit/src/shell.contract.json +1 -1
  79. package/packages/agent-ui-kit/src/shell.test.ts +105 -2
  80. package/packages/agent-ui-kit/src/theme/base.css +42 -2
  81. package/pnpm-lock.template.yaml +94 -94
  82. package/pnpm-workspace.template.yaml +11 -11
  83. package/scripts/._interaction-probe.mjs +0 -0
  84. package/scripts/check-fast.mjs +11 -2
  85. package/scripts/checks.json +80 -2
  86. package/scripts/deliver.mjs +85 -7
  87. package/scripts/interaction-probe.mjs +222 -0
  88. package/scripts/lib/geometry-kernel.mjs +8 -1
  89. package/scripts/shell-probe.mjs +8 -3
  90. package/scripts/storyboard.mjs +5 -0
@@ -20,6 +20,40 @@ export const IN_PROCESS_CHECKS = {
20
20
  };
21
21
  },
22
22
 
23
+ /**
24
+ * 文案冗余:标题在 eyebrow / header / hero 之间重复,或把内部实现词写进用户可见文案。
25
+ * 视图卡的结构让这类重复很容易发生(hero.title + header.title 都写「会员中心」)。
26
+ */
27
+ 'card.copy-redundant': (ctx) => {
28
+ const problems = [];
29
+ for (const [cardType, meta] of Object.entries(ctx.registryServer?.cards ?? {})) {
30
+ if (!meta || typeof meta.view !== 'function') continue;
31
+ for (const view of derivedViewsOf(meta)) {
32
+ problems.push(...copyProblemsOf(cardType, view));
33
+ }
34
+ }
35
+ return problems.length === 0
36
+ ? { status: 'pass', detail: '卡片文案无重复与内部术语' }
37
+ : { status: 'fail', detail: problems.slice(0, 4).join(';') };
38
+ },
39
+
40
+ /**
41
+ * 按钮文案语义:纯终态词(「已领取」「已过期」)当按钮——用户点了没反应,因为动作早已结束。
42
+ * 只匹配「整串就是终态词」的情形;「已领券 · 查看」这类带后续动作的不算。
43
+ */
44
+ 'card.action-semantics': (ctx) => {
45
+ const problems = [];
46
+ for (const [cardType, meta] of Object.entries(ctx.registryServer?.cards ?? {})) {
47
+ if (!meta || typeof meta.view !== 'function') continue;
48
+ for (const view of derivedViewsOf(meta)) {
49
+ problems.push(...terminalLabelProblemsOf(cardType, view));
50
+ }
51
+ }
52
+ return problems.length === 0
53
+ ? { status: 'pass', detail: '按钮文案都表达了可执行动作' }
54
+ : { status: 'fail', detail: problems.slice(0, 4).join(';') };
55
+ },
56
+
23
57
  'card.height': async (ctx) => {
24
58
  const cardCount = Object.keys(ctx.registryServer?.cards ?? {}).length;
25
59
  if (cardCount === 0) return { status: 'deferred', detail: '没有卡片' };
@@ -30,13 +64,78 @@ export const IN_PROCESS_CHECKS = {
30
64
  if (density.worst > 506 && density.worst <= 633) {
31
65
  ctx.warn('card-height-warn', '视图卡最高 ' + density.worst + 'px(超过一屏 60% 的 506px)', { fix: '优先减积木或拆卡;>633px 会阻断', recipe: 'card' });
32
66
  }
67
+ const sheetNote = (density.sheetCards ?? []).length > 0
68
+ ? ';抽屉卡豁免:' + density.sheetCards.join('、')
69
+ : '';
33
70
  return {
34
71
  status: density.violations.length > 0 ? 'fail' : 'pass',
35
- detail: '最高 ' + density.worst + 'px' + (density.violations.length > 0 ? ';超限:' + density.violations.join('、') : ''),
72
+ detail: '最高 ' + density.worst + 'px' + (density.violations.length > 0 ? ';超限:' + density.violations.join('、') : '') + sheetNote,
36
73
  };
37
74
  },
38
75
  };
39
76
 
77
+ /** 内部实现词:用户不该在卡片上看到这些。 */
78
+ const INTERNAL_PHRASES = [/状态实时同步/, /状态机/, /\bstate machine\b/i, /轮询/];
79
+
80
+ /** 纯终态词当按钮 = 点了没反应(「已领券 · 查看」这类带后续动作的不算)。 */
81
+ const TERMINAL_LABELS = /^(已领取|已领券|已使用|已完成|不可使用|已过期|已结束|已核销|已支付|失败)$/;
82
+
83
+ /**
84
+ * 一张卡的「已派生视图 JSON」列表(基准态 + 状态样本)。
85
+ *
86
+ * ⚠️ `meta.sampleData` 与 `meta.samples[].data` 都是 defineViewCard 已经跑过 `view(...)` 的
87
+ * **CardView JSON**,绝不能再喂回 `view()`:真实卡片的 view 读的是领域字段,收到视图 JSON 会抛错,
88
+ * 而 try/catch 会把它当成「没数据」静默跳过——两条文案检查曾因此对真实卡 100% 假绿。
89
+ * 三件套的 meta 没有 view 标记,调用方已先行过滤。
90
+ */
91
+ function derivedViewsOf(meta) {
92
+ return [meta.sampleData, ...(Array.isArray(meta.samples) ? meta.samples.map((sample) => sample?.data) : [])]
93
+ .filter((view) => view && typeof view === 'object' && Array.isArray(view.blocks));
94
+ }
95
+
96
+ /** 文案重复与内部术语(纯函数,便于单测)。 */
97
+ function copyProblemsOf(cardType, view) {
98
+ const problems = [];
99
+ const headerTitle = view?.header?.title ?? '';
100
+ const hero = (view?.blocks ?? []).find((block) => block.kind === 'hero');
101
+ if (hero) {
102
+ if (hero.eyebrow && hero.eyebrow === hero.title) problems.push(cardType + ':hero 的 eyebrow 与 title 重复');
103
+ if (headerTitle && hero.title === headerTitle) problems.push(cardType + ':hero.title 与卡标题重复');
104
+ }
105
+ const texts = [
106
+ headerTitle,
107
+ ...(view?.blocks ?? []).flatMap((block) => [
108
+ block.text,
109
+ block.title,
110
+ ...(block.items ?? []).map((item) => item?.title ?? item?.label),
111
+ ]),
112
+ ].filter((text) => typeof text === 'string' && text.length > 0);
113
+ for (const text of texts) {
114
+ if (INTERNAL_PHRASES.some((pattern) => pattern.test(text))) {
115
+ problems.push(cardType + ':用户可见文案含内部实现词(' + text.slice(0, 12) + ')');
116
+ break;
117
+ }
118
+ }
119
+ return problems;
120
+ }
121
+
122
+ /** 终态词按钮(纯函数,便于单测)。 */
123
+ function terminalLabelProblemsOf(cardType, view) {
124
+ const labels = [
125
+ ...(view?.actions ?? []).map((action) => action?.label),
126
+ ...(view?.blocks ?? []).flatMap((block) => [
127
+ ...(block?.action ? [block.action.label] : []),
128
+ ...(block?.actions ?? []).map((action) => action?.label),
129
+ ...(block?.items ?? []).flatMap((item) => [
130
+ ...(item?.action ? [item.action.label] : []),
131
+ ...(item?.actions ?? []).map((action) => action?.label),
132
+ ]),
133
+ ]),
134
+ ].filter((label) => typeof label === 'string');
135
+ const terminal = labels.find((label) => TERMINAL_LABELS.test(label.trim()));
136
+ return terminal ? [cardType + ':按钮用终态词「' + terminal + '」'] : [];
137
+ }
138
+
40
139
  export async function runInProcessChecks(context, ids) {
41
140
  const items = [];
42
141
  for (const id of ids) {
@@ -30,6 +30,7 @@ export const STORYBOARD_CHECKS = {
30
30
  'card.text-clip': { lane: 'layout', title: '文本截断带省略号' },
31
31
  'card.tap-target': { lane: 'layout', title: '卡片点击区 ≥44px' },
32
32
  'card.min-font': { lane: 'layout', title: '卡片最小字号 ≥12px' },
33
+ 'card.button-ua-style': { lane: 'layout', title: '按钮无浏览器默认外观' },
33
34
  };
34
35
 
35
36
  export function mergeStoryboardChecks({ storyboard, ids, policy, stale = '', cardCount = 0 }) {
@@ -0,0 +1,219 @@
1
+ /**
2
+ * 静态检查的误报守卫(`style.class-conflict` / `card.raw-button`)。
3
+ *
4
+ * 为什么专门测误报:这两条是新加的、会出现在每次 check:fast 里的检查。
5
+ * 门禁噪音比漏报更贵——一旦合法写法被标红,用户(和 agent)就会开始忽略整张表。
6
+ * 这里钉死的正是历史上真实踩过的形态:属性里的箭头函数 `=>` 自带 `>`,
7
+ * 旧实现 `/<button(?![^>]*\btype=)/` 会在那里截断,把 `type` 写在后面的按钮判成缺 type。
8
+ */
9
+ import { describe, expect, it } from 'vitest';
10
+ import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
11
+ import path from 'node:path';
12
+ import os from 'node:os';
13
+ import { STATIC_CHECKS } from './experience-checks.mjs';
14
+ import { IN_PROCESS_CHECKS } from './in-process-checks.mjs';
15
+
16
+ const withCard = (source, run) => {
17
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'tbox-static-'));
18
+ const clientDir = path.join(dir, 'client');
19
+ mkdirSync(path.join(clientDir, 'src', 'cards'), { recursive: true });
20
+ writeFileSync(path.join(clientDir, 'src', 'cards', 'x.card.tsx'), source);
21
+ try {
22
+ return run({ clientDir });
23
+ } finally {
24
+ rmSync(dir, { recursive: true, force: true });
25
+ }
26
+ };
27
+
28
+ describe('card.raw-button:语义与热区判定', () => {
29
+ const check = (buttonMarkup) =>
30
+ withCard(`export const X = () => (${buttonMarkup});\n`, (ctx) => STATIC_CHECKS['card.raw-button'](ctx));
31
+
32
+ it('type 在前:通过', () => {
33
+ expect(check('<button type="button" className="min-h-11" onClick={() => x()}>A</button>').status).toBe('pass');
34
+ });
35
+
36
+ it('箭头函数在前、type 在后:不再误报(旧实现会 fail)', () => {
37
+ expect(check('<button onClick={() => setX(1)} type="button" className="min-h-11">B</button>').status).toBe('pass');
38
+ });
39
+
40
+ it('属性里出现比较运算符(a > b):不再误报', () => {
41
+ expect(check('<button onClick={() => setX(a > b)} type="button" className="min-h-11">C</button>').status).toBe('pass');
42
+ });
43
+
44
+ it('多行属性:正常识别 type', () => {
45
+ expect(check('<button\n className="min-h-11 px-3"\n type="button"\n>D</button>').status).toBe('pass');
46
+ });
47
+
48
+ it('确实缺 type:拦截', () => {
49
+ const result = check('<button onClick={go} className="min-h-11">E</button>');
50
+ expect(result.status).toBe('fail');
51
+ expect(result.detail).toContain('type="button"');
52
+ });
53
+
54
+ it('缺最小热区:拦截(热区与语义是两条独立判据)', () => {
55
+ const result = check('<button type="button" className="px-3">F</button>');
56
+ expect(result.status).toBe('fail');
57
+ expect(result.detail).toContain('最小热区');
58
+ });
59
+ });
60
+
61
+ describe('style.class-conflict:只在单个静态字面量内判互斥', () => {
62
+ const check = (className) =>
63
+ withCard(`export const X = () => <div className="${className}" />;\n`, (ctx) =>
64
+ STATIC_CHECKS['style.class-conflict'](ctx),
65
+ );
66
+
67
+ it('同一串里 border-0 与 border 并存:拦截', () => {
68
+ expect(check('border-0 border p-2').status).toBe('fail');
69
+ });
70
+
71
+ it('hidden 与 flex 并存:拦截', () => {
72
+ expect(check('hidden flex items-center').status).toBe('fail');
73
+ });
74
+
75
+ it('响应式前缀不算冲突(md:flex 与 hidden 是常见组合)', () => {
76
+ expect(check('hidden md:flex items-center').status).toBe('pass');
77
+ });
78
+
79
+ it('border 与 border-b 不误判', () => {
80
+ expect(check('border border-b p-2').status).toBe('pass');
81
+ });
82
+ });
83
+
84
+ describe('card.raw-button:热区判据的合法形态', () => {
85
+ const check = (className) =>
86
+ withCard(`export const X = () => <button type="button" className="${className}">A</button>;\n`, (ctx) =>
87
+ STATIC_CHECKS['card.raw-button'](ctx),
88
+ );
89
+
90
+ it.each(['min-h-11', 'h-12', 'size-11', 'min-h-[44px]', 'min-h-[52px]', 'py-3'])('%s 视为达标', (cls) => {
91
+ expect(check(cls).status).toBe('pass');
92
+ });
93
+
94
+ it('只有小内距:拦截', () => {
95
+ expect(check('px-2 py-1 text-xs').status).toBe('fail');
96
+ });
97
+
98
+ it('箭头函数在前时热区仍能被读到(回归:旧实现整段漏检)', () => {
99
+ const result = withCard(
100
+ `export const X = () => <button onClick={() => go()} type="button" className="px-2">A</button>;\n`,
101
+ (ctx) => STATIC_CHECKS['card.raw-button'](ctx),
102
+ );
103
+ expect(result.status).toBe('fail');
104
+ expect(result.detail).toContain('最小热区');
105
+ });
106
+ });
107
+
108
+ describe('action.placement-check:结果卡去重/落点提示', () => {
109
+ const withAction = (source) => {
110
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'tbox-placement-'));
111
+ const clientDir = path.join(dir, 'apps', 'client');
112
+ mkdirSync(path.join(dir, 'apps', 'server', 'src', 'actions'), { recursive: true });
113
+ mkdirSync(clientDir, { recursive: true });
114
+ writeFileSync(path.join(dir, 'apps', 'server', 'src', 'actions', 'x.action.ts'), source);
115
+ try {
116
+ return STATIC_CHECKS['action.placement-check']({ clientDir });
117
+ } finally {
118
+ rmSync(dir, { recursive: true, force: true });
119
+ }
120
+ };
121
+
122
+ it('裸 cardResult:提示补 replaceKey 或 defaultPlacement', () => {
123
+ const result = withAction(`export const action = {\n execute: async () => cardResult(detailCard, { id: '1' }),\n};\n`);
124
+ expect(result.status).toBe('fail');
125
+ expect(result.detail).toContain('defaultPlacement');
126
+ });
127
+
128
+ it('带 replaceKey:通过', () => {
129
+ expect(withAction(`cardResult(detailCard, data, { replaceKey: 'shop:1' })`).status).toBe('pass');
130
+ });
131
+
132
+ it('显式 sheet 落点:通过', () => {
133
+ expect(withAction(`cardResult(detailCard, data, { placement: 'sheet' })`).status).toBe('pass');
134
+ });
135
+ });
136
+
137
+ describe('card.copy-redundant / card.action-semantics:文案质量', () => {
138
+ // 真实形态:defineViewCard 的 meta.sampleData 已经是 view() 的产物(CardView JSON)。
139
+ // 这里的 view 刻意读领域字段——若检查把它当入参再调一次,会抛错并被静默跳过(历史假绿)。
140
+ const ctxOf = (views, domainRead = false) => ({
141
+ registryServer: {
142
+ cards: {
143
+ demo: {
144
+ view: (data) => {
145
+ if (domainRead) return { header: { title: data.title }, blocks: [] };
146
+ return views[0];
147
+ },
148
+ sampleData: views[0],
149
+ ...(views.length > 1 ? { samples: views.slice(1).map((data) => ({ label: 's', data })) } : {}),
150
+ },
151
+ },
152
+ },
153
+ warn: () => {},
154
+ });
155
+ const redundant = {
156
+ header: { title: '会员中心' },
157
+ blocks: [{ kind: 'hero', eyebrow: '会员中心', title: '会员中心', value: '100' }],
158
+ };
159
+
160
+ it('标题三处重复:拦截', () => {
161
+ const result = IN_PROCESS_CHECKS['card.copy-redundant'](ctxOf([redundant]));
162
+ expect(result.status).toBe('fail');
163
+ expect(result.detail).toContain('重复');
164
+ });
165
+
166
+ it('文案含内部实现词:拦截', () => {
167
+ const result = IN_PROCESS_CHECKS['card.copy-redundant'](
168
+ ctxOf([{ header: { title: '会员' }, blocks: [{ kind: 'notice', text: '状态实时同步' }] }]),
169
+ );
170
+ expect(result.status).toBe('fail');
171
+ expect(result.detail).toContain('内部实现词');
172
+ });
173
+
174
+ it('干净文案:通过', () => {
175
+ const result = IN_PROCESS_CHECKS['card.copy-redundant'](
176
+ ctxOf([{ header: { title: '停车订单' }, blocks: [{ kind: 'hero', title: '待支付', value: '¥5' }] }]),
177
+ );
178
+ expect(result.status).toBe('pass');
179
+ });
180
+
181
+ it('状态样本里的重复也要查(不只基准态)', () => {
182
+ const result = IN_PROCESS_CHECKS['card.copy-redundant'](
183
+ ctxOf([
184
+ { header: { title: '停车订单' }, blocks: [{ kind: 'hero', title: '待支付', value: '¥5' }] },
185
+ { header: { title: '停车订单' }, blocks: [{ kind: 'hero', title: '停车订单', value: '¥0' }] },
186
+ ]),
187
+ );
188
+ expect(result.status).toBe('fail');
189
+ expect(result.detail).toContain('重复');
190
+ });
191
+
192
+ it('回归:view 读领域字段(真实形态)时不会被静默跳过', () => {
193
+ // 若实现又去调 meta.view(sampleData),这里会抛 TypeError 被 catch 掉 → pass(假绿)
194
+ const result = IN_PROCESS_CHECKS['card.copy-redundant'](ctxOf([redundant], true));
195
+ expect(result.status).toBe('fail');
196
+ });
197
+
198
+ it('按钮用终态词:拦截', () => {
199
+ const result = IN_PROCESS_CHECKS['card.action-semantics'](
200
+ ctxOf([{ header: { title: 'x' }, blocks: [], actions: [{ label: '已领取' }] }]),
201
+ );
202
+ expect(result.status).toBe('fail');
203
+ expect(result.detail).toContain('终态词');
204
+ });
205
+
206
+ it('「已领券 · 查看」这类带后续动作的不算终态:通过', () => {
207
+ const result = IN_PROCESS_CHECKS['card.action-semantics'](
208
+ ctxOf([{ header: { title: 'x' }, blocks: [], actions: [{ label: '已领券 · 查看' }] }]),
209
+ );
210
+ expect(result.status).toBe('pass');
211
+ });
212
+
213
+ it('条目级按钮同样查终态词', () => {
214
+ const result = IN_PROCESS_CHECKS['card.action-semantics'](
215
+ ctxOf([{ header: { title: 'x' }, blocks: [{ kind: 'list', items: [{ title: 'a', actions: [{ label: '已使用' }] }] }] }]),
216
+ );
217
+ expect(result.status).toBe('fail');
218
+ });
219
+ });
@@ -0,0 +1,40 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import { resolveHomePresetId } from './home-preset';
3
+
4
+ describe('resolveHomePresetId', () => {
5
+ let warn: ReturnType<typeof vi.spyOn>;
6
+ beforeEach(() => {
7
+ warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
8
+ warn.mockClear();
9
+ });
10
+ afterEach(() => {
11
+ warn.mockRestore();
12
+ });
13
+
14
+ it('mall-home 生效;none / 缺席 / 非对象静默不挂载', () => {
15
+ expect(resolveHomePresetId({ homePreset: 'mall-home' })).toBe('mall-home');
16
+ for (const value of [undefined, null, [], {}, { homePreset: 'none' }]) {
17
+ expect(resolveHomePresetId(value)).toBeNull();
18
+ }
19
+ expect(warn).not.toHaveBeenCalled();
20
+ });
21
+
22
+ it('未知值只告警并降级 chat 流', () => {
23
+ expect(resolveHomePresetId({ homePreset: 'mall_home' })).toBeNull();
24
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('未知 homePreset'));
25
+ warn.mockClear();
26
+ expect(resolveHomePresetId({ homePreset: 42 })).toBeNull();
27
+ expect(warn).toHaveBeenCalledTimes(1);
28
+ warn.mockClear();
29
+ expect(resolveHomePresetId({ homePreset: null })).toBeNull();
30
+ expect(warn).toHaveBeenCalledTimes(1);
31
+ });
32
+
33
+ it('告警按 JSON 格式带出原值(空串/对象不塌成空或 [object Object])', () => {
34
+ expect(resolveHomePresetId({ homePreset: '' })).toBeNull();
35
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('homePreset=""'));
36
+ warn.mockClear();
37
+ expect(resolveHomePresetId({ homePreset: { a: 1 } })).toBeNull();
38
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('homePreset={"a":1}'));
39
+ });
40
+ });
@@ -0,0 +1,19 @@
1
+ import { HOME_PRESET_IDS, type HomePresetId } from '@tbox.cn/app-contracts';
2
+
3
+ export type { HomePresetId };
4
+
5
+ /**
6
+ * 生效的预置首页:`mall-home` 复用内置 MallHome;`none`/缺席 = 不注册 home 槽。
7
+ * 未知值只告警并按 chat 流处理——配置面另有 schema/doctor/构建期校验,运行时不因错字白屏。
8
+ */
9
+ export function resolveHomePresetId(chat: unknown): Exclude<HomePresetId, 'none'> | null {
10
+ if (!chat || typeof chat !== 'object' || Array.isArray(chat)) return null;
11
+ const raw = (chat as { homePreset?: unknown }).homePreset;
12
+ if (raw === undefined || raw === 'none') return null;
13
+ if (typeof raw === 'string' && (HOME_PRESET_IDS as readonly string[]).includes(raw)) {
14
+ return raw as Exclude<HomePresetId, 'none'>;
15
+ }
16
+ // JSON.stringify:与服务端 loader 同一格式,空串/数字/对象都能看出原值(String 会丢成空或 [object Object])。
17
+ console.warn(`[home] 未知 homePreset=${JSON.stringify(raw)},按 chat 流处理`);
18
+ return null;
19
+ }
@@ -4,7 +4,9 @@
4
4
  */
5
5
  import type { CardComponent, HomeSlotValue, TboxCardPayload } from '@tbox.cn/app-contracts';
6
6
  import deploymentChat from '@config/chat.json';
7
- import { ClientSlotRegistry, getClientContext } from '@tbox.cn/app-agent-sdk-client';
7
+ import { type ClientSlotRegistry, getClientContext } from '@tbox.cn/app-agent-sdk-client';
8
+ import { resolveHomePresetId } from './home-preset';
9
+ export { resolveHomePresetId, type HomePresetId } from './home-preset';
8
10
 
9
11
  const ctx = getClientContext();
10
12
 
@@ -21,8 +23,13 @@ export const CHAT_REGISTRY: Record<string, CardComponent> = {
21
23
  export const INLINE_CARD_FILTER = (cards: readonly TboxCardPayload[]): TboxCardPayload[] =>
22
24
  ctx.cards.applyInlineFilters(cards);
23
25
 
26
+ /** home-first 形态只替换 home 槽;conversationOverlay 由 home-slot 自持门禁,避免双挂。 */
27
+ function slotsWithoutHomeOverlay(): ClientSlotRegistry {
28
+ return ctx.slots.cloneExcept(['home', 'conversationOverlay']);
29
+ }
30
+
24
31
  function pageSlots() {
25
- if (ctx.slots.has('home') || !('homePreset' in deploymentChat) || deploymentChat.homePreset !== 'mall-home') {
32
+ if (ctx.slots.has('home') || resolveHomePresetId(deploymentChat) !== 'mall-home') {
26
33
  return ctx.slots;
27
34
  }
28
35
  // mall 画像才安装此模块。无模块的基础模板也能构建。
@@ -32,7 +39,7 @@ function pageSlots() {
32
39
  const home = Object.values(homes)[0];
33
40
  if (!home) throw new Error('homePreset=mall-home 需要安装 module-mall-core');
34
41
  // 此预置包含完整的会员门禁。使用页面自己的槽表,避免同一门禁再挂载一份。
35
- const slots = new ClientSlotRegistry();
42
+ const slots = slotsWithoutHomeOverlay();
36
43
  slots.register('home', home);
37
44
  return slots;
38
45
  }
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * - store = 应用薄壳 store(会话泳道 deps 注入 SDK 默认实现);
5
5
  * - cards/rawCards = 覆盖通道组装 / 原始形态(registry.ts 经 ctx 读取);
6
- * - slots = 客户端槽注册表(home 槽由 module-mall-core register 注册);
6
+ * - slots = 客户端槽注册表(由应用注册,或 config/chat.json 的 homePreset 装配);
7
7
  * - filterInlineCards = 内联流过滤复合(域模块注册;无注册恒等)。
8
8
  */
9
9
  import { ChatPage } from '@tbox.cn/app-agent-ui-kit';
@@ -66,7 +66,9 @@
66
66
  --radius-3xl: 20px;
67
67
  --radius-4xl: 24px;
68
68
  --radius-media: var(--tbox-media-item-radius);
69
- /* 阴影:契约变量(v4 默认档位本身就是 px,不清理也不会被根字号放大) */
69
+ /* 阴影:契约变量(v4 默认档位本身就是 px,不清理也不会被根字号放大);
70
+ xs 是 v4 默认值(rem),补一条物理 px 让整条阴影阶梯口径一致。 */
71
+ --shadow-xs: 0 1PX 2PX rgba(11, 15, 23, 0.06);
70
72
  --shadow-sm: var(--tbox-shadow-sm);
71
73
  --shadow-md: var(--tbox-shadow-md);
72
74
  --shadow-lg: var(--tbox-shadow-lg);
@@ -14,6 +14,7 @@
14
14
  },
15
15
  "include": [
16
16
  "src",
17
+ "scripts/*.ts",
17
18
  "vite.config.ts"
18
19
  ]
19
20
  }
@@ -9,6 +9,7 @@ import { pathToFileURL } from 'node:url';
9
9
  // 源码位置属性,供 inspector runtime(/__vs_inspector__.js) 点选元素→定位源码。仅 dev 启用(见下)。
10
10
  import codeInspectPlugin from '@tbox.cn/app-agent-sdk-client/platform/code-inspect';
11
11
  import { tboxAppPlugin, tboxModuleSourcesPlugin, tboxVendorLayerPlugin } from '@tbox.cn/app-build';
12
+ import { assertHomePresetWiring } from './scripts/home-preset-wiring';
12
13
 
13
14
  export default defineConfig(async ({ command }) => {
14
15
  // tbox-app-dev dev 探测行(dev 探针常量;构件区在位时启用原地装配改指,缺席零行为变化。
@@ -29,12 +30,22 @@ export default defineConfig(async ({ command }) => {
29
30
  const { default: tboxDevOverride } = await import(pathToFileURL(devOverridePath).href);
30
31
  devPlugins.push(tboxDevOverride());
31
32
  }
32
- const configuredChat = process.env.TBOX_CONFIG_DIR && resolve(process.env.TBOX_CONFIG_DIR, 'chat.json');
33
+ // 配置面锚以应用根(apps/client 的上一级×2)为基准解析:绝对路径不受影响,
34
+ // 相对路径不会因 `pnpm --filter ./apps/client` 把 cwd 切到 apps/client 而静默 miss 目标 chat.json。
35
+ const appRoot = resolve(__dirname, '../..');
36
+ const configuredChat = process.env.TBOX_CONFIG_DIR && resolve(appRoot, process.env.TBOX_CONFIG_DIR, 'chat.json');
37
+ if (!process.env.VITEST) {
38
+ assertHomePresetWiring(
39
+ configuredChat && existsSync(configuredChat) ? configuredChat : resolve(appRoot, 'config/chat.json'),
40
+ // 1.0 应用模块恒在 modules/<id>(@app-module alias 同源);packages/ 旧布局不在 homePreset 支持面内。
41
+ resolve(appRoot, 'modules/module-mall-core/src/client/home-slot.tsx'),
42
+ );
43
+ }
33
44
  return {
34
45
  plugins: [
35
- tboxModuleSourcesPlugin({ appRoot: resolve(__dirname, '../..') }),
46
+ tboxModuleSourcesPlugin({ appRoot }),
36
47
  tboxVendorLayerPlugin(),
37
- tboxAppPlugin({ root: resolve(__dirname, '../..') }),
48
+ tboxAppPlugin({ root: appRoot }),
38
49
  tailwindcss(),
39
50
  react({
40
51
  babel: { plugins: command === 'serve' ? [codeInspectPlugin] : [] },
@@ -59,8 +70,7 @@ export default defineConfig(async ({ command }) => {
59
70
  // environment 保持每文件 @vitest-environment pragma(纯逻辑用例不付 DOM 开销)。
60
71
  test: {
61
72
  setupFiles: ['src/test/setup.ts'],
62
- // W3-2:client 测试随域迁模块包(2026-09-20 并入 module-mall-core;页级集成测试 = 模块 tests/home-slot.test.tsx);
63
- // 模板仅留薄页装配,零测试文件合法(新增客户端测试时移除本旗标)
73
+ // 用户应用可能精简掉测试文件;模板自身已有壳/配置/脚本测试,零用例时允许通过。
64
74
  passWithNoTests: true,
65
75
  },
66
76
  // 构建输入由 tboxAppPlugin 按 .tbox-gen/manifest.json 注入(文档模式唯一真源)
@@ -138,7 +138,18 @@ export async function runScenarios({ appDir, registry, files }) {
138
138
  }
139
139
  const invalid = result.cards.filter((card) => !card.valid);
140
140
  if (invalid.length > 0) {
141
- failures.push(`${label}: 卡片数据不合法 ${invalid.map((c) => `${c.cardType}(${c.issues.join('; ')})`).join('、')}`);
141
+ // 视图卡与三件套的数据形状不同:一个是 CardView JSON,一个是领域数据。
142
+ // 断言写错时最容易在这里绕圈,所以把「哪一类卡、该给什么形状」直接写进失败信息。
143
+ const detail = invalid
144
+ .map((card) => {
145
+ const isView = card.view === true || card.kind === 'view';
146
+ const shape = isView
147
+ ? '视图卡:data 必须是 CardView JSON(header + blocks + 可选 actions),不是领域数据'
148
+ : '自定义卡:data 必须符合该卡 dataSchema 的领域数据';
149
+ return `${card.cardType}(${card.issues.join('; ')}|${shape})`;
150
+ })
151
+ .join('、');
152
+ failures.push(`${label}: 卡片数据不合法 ${detail}`);
142
153
  continue;
143
154
  }
144
155
  if (step.expect?.output !== undefined) {
Binary file
@@ -0,0 +1,10 @@
1
+ {
2
+ // 业务提示词(必填):逐行拼接,追加在平台规则之后;不替代平台规则。
3
+ // 领域中立:这里写「怎么答」的通用准则,具体业务(门店/优惠/订单…)由需求侧决定。
4
+ // 字段真源:pnpm exec tbox-app schema config/agent.jsonc
5
+ "instructions": [
6
+ "先给结论,再给必要细节;信息不足就先追问最关键的一项,不要编造未查到的事实。",
7
+ "涉及实时数据(清单、状态、金额、可用性)时,先调工具拿真实数据再作答,不复述工具原始 JSON;卡片由工具出参交给平台渲染。"
8
+ ]
9
+ // 装配长期记忆时可再加 "memoryInstructions": ["…"](同样逐行拼接)。
10
+ }
@@ -76,7 +76,11 @@ export const action = defineAction({
76
76
  - `id` 全局唯一;`cardType` 决定它挂在哪张卡上(数组表示同一操作出现在多张卡上),出卡时平台按被点卡签发令牌;
77
77
  - `inputSchema` 校验卡片传入的 `input`;无参动作写 `z.object({})`;
78
78
  - `execute(input, ctx)` 的 `ctx` 是 `{ userId, cardId?, cardType? }`——`userId` 来自授权令牌绑定的会话身份,**不要信客户端传上来的 userId**;`cardType` 是被点击那张卡的类型;
79
- - 返回值三选一:`updateResult(card, data)` 原地更新被点的卡、`cardResult(card, data)` 出一张结果卡、`actionResult.notice(text)` 只给一条提示。`update` 与 `card` 互斥;
79
+ - 返回值三选一:`updateResult(card, data, { notice })` 原地更新被点的卡、`cardResult(card, data, { placement, replaceKey, notice })` 出一张结果卡、`actionResult.notice(text)` 只给一条提示。`update` 与 `card` 互斥;
80
+ - **结果卡落点**:`placement` 三选一——`timeline`(缺省,插在对话流末尾并滚入视口)/ `sheet`(半屏抽屉,详情与完整券包用)/ `top`(只给业务旁路欢迎卡)。不写就按卡的 `defaultPlacement`,再缺省 `timeline`。
81
+ - **重复触发必须给 `replaceKey`**(字母/数字/冒号/下划线/中划线,≤128):同键原位替换,连点不会叠出一排一样的卡。没写时 `action.placement-check` 会提醒。
82
+ - **改动了别处的状态**(券包/订单/会员)→ 带上 `invalidateCardTypes: ['parking-order']`:同会话里旧卡顶部出现「相关状态已更新」,不会两张卡互相打架。
83
+ - `text` / `notice` 是伴随轻提示:**有卡也会发**,不会因为出卡就吞掉提示。
80
84
  - `data` 与出卡同口径:视图卡(`defineViewCard`)收**领域数据**,平台内部转成视图 JSON;三件套卡收该卡 schema 的值。传视图 JSON 仍然可用,但不要手写 `card.view(...)`;
81
85
  - 写操作用 `singleUse: true` 防重复提交;幂等判断放在副作用之前;
82
86
  - 动作结果只回给客户端(`tbox:card-update` / `tbox:notice` / 结束回执 `tbox:action-settled`),**不进模型上下文**——需要模型知道的事实,让它在下一轮用工具查。
@@ -34,7 +34,13 @@ export const card = defineViewCard<ParkingOrder>({
34
34
  });
35
35
  ```
36
36
 
37
- - 积木:`hero` / `facts` / `bill` / `notice` / `tags` / `steps` / `list` / `ticket` / `timeline` / `empty`;动作规格与 `ActionList` 同形(label / send / invoke / confirm / style)。
37
+ - 积木:`hero` / `facts` / `bill` / `notice` / `tags` / `steps` / `list` / `stats` / `tickets` / `ticket` / `timeline` / `empty`;动作规格与 `ActionList` 同形(label / send / invoke / confirm / style)。
38
+ - `hero` 的 `title` 可选:积分/余额这类主视觉只写 `value` + `unit` 就够,**不要**为了凑标题跟卡标题重复(`card.copy-redundant` 会点名)。
39
+ - `stats`(2–4 格):一行并列数值,替代「facts 竖排四行」——`items: [{ label: '积分', value: '1,280' }]`。
40
+ - `tickets`(≤3 张):券包/票夹形态,每项 `{ amount, title, condition?, status?, action? }`;完整券包走抽屉(见下)。
41
+ - `list` 条目多了三样:`badge`(标题左短标记)、`status`(状态胶囊)、`actions`(≤3 个按钮,单行等分)。
42
+ - **明细卡默认进抽屉**:卡声明写 `defaultPlacement: 'sheet'`,动作不写 `placement` 时自动进半屏抽屉,
43
+ 且不再受「流内一屏 506px」高度告警约束;抽屉内关闭后原位留「查看详情」胶囊,不会消失。
38
44
  - `hero` 的 `tone`:`primary`(缺省)/ `warm` / `jade` / `inverse`。**要深色主视觉(金额、路线、会员等级)用 `inverse`**——它用 `--tbox-primary-dark` 底 + `--tbox-primary-light` 字,对比度由门禁 `shell.contrast` 兜底;不要为了深色底去写 `bg-[#173F33]` 这类字面量(`style.color-repeat` 会点名)。
39
45
  - 预算写进 schema:积木 ≤4、提示 ≤1、属性 ≤5、列表 ≤3、账单行 ≤8、步骤 ≤5、时间线 ≤6、标签 ≤6、卡级动作 ≤2;作者期 `defineViewCard` 直接报错,生产侧 `cardOfView` 先截断再校验,不整张卡丢弃。
40
46
  - 样例由 `sampleState` 与 `samples` 派生,不用手写大段 `sampleData`。
@@ -41,7 +41,7 @@
41
41
  | `css.sentinel`(错误) | 证据 CSS 为空、缺模块源码或模块类未生成 | 确认 `vite.config.ts` 的 `tboxModuleSourcesPlugin` 在 `tailwindcss()` 之前;证据与 dev/build 共用 app-build 的 `collectModuleSourceDirs`([style](style.md)) |
42
42
  | `card.states`(错误) | 卡片历史态渲染失败或为空 | 用 isHistory 只禁用动作,不隐藏内容([card](card.md)) |
43
43
  | `shell.hit-target`(错误) | 可交互元素命中区小于 44px | 用 kit 按钮与 min-h-11;视觉尺寸可小,命中区要足([shell](shell.md)) |
44
- | `shell.quick-visible`(错误) | 空态快捷问题没有全部可见(横向溢出或贴底) | 空态用两列 grid,对话态才用单行([shell](shell.md)) |
44
+ | `shell.quick-visible`(错误) | 空态快捷问题没有全部可见(横向溢出或贴底) | 无 home 槽的纯对话欢迎态用两列 grid,有 home 槽的首页与对话态共用输入框上方单行([shell](shell.md)) |
45
45
  | `flow.persist`(建议) | 状态没有跨进程重启验证 | 用 createUserState({ persist: "file" }) 并加重启探针([state](state.md)) |
46
46
  | `shell.contrast`(错误) | 令牌对比度低于阈值(文字看不清) | 调 brand.css 的令牌值;color-mix 派生的由浏览器车道补验([style](style.md)) |
47
47
  | `shell.blank`(建议) | 首页内容块之间空白过大(看起来没做完) | 空态成组居中、补服务入口;只算块间空白,不算首尾对称留白;聊天流首屏记 not-run([shell](shell.md)) |
@@ -63,4 +63,10 @@
63
63
  | `shell.no-fixed-chrome`(错误) | 滚动区之上有常驻元素(页头、固定标题栏) | 删掉固定区;品牌/身份写 welcome.title,页面标题写 page.title([shell](shell.md)) |
64
64
  | `shell.input-rows`(错误) | 空输入框不是单行(或不是 chat.json 要求的行数),或外框命中区不足 | 输入框高度交给 kit 的 useAutoRows;不要给 textarea 写死 min-height([shell](shell.md)) |
65
65
  | `shell.follow-latest`(错误) | 流式内容增长时不跟底,或用户上滑后仍被拉回底部 | 滚动位置交给 kit 的 useStickToBottom;不要自己写「离底 <N 就跟随」([shell](shell.md)) |
66
+ | `style.class-conflict`(错误) | 同一个 className 里写了互斥类(如 border-0 与 border、hidden 与 flex) | 删掉其中一个:边框/底色/显隐只留一个来源(变体类或基础类)([style](style.md)) |
67
+ | `card.raw-button`(建议) | 自定义卡片里的 <button> 缺 type="button" 或未写最小热区 | 补 type="button" 与 min-h-11(或直接用 kit 的 CardButton)([card](card.md)) |
68
+ | `card.button-ua-style`(错误) | 卡片按钮仍是浏览器默认外观(outset 边框) | 用 kit 的 CardButton/ActionList;自定义按钮写 `border-0 bg-transparent`(作用域重置已兜底)([style](style.md)) |
69
+ | `card.copy-redundant`(建议) | 卡片标题在 eyebrow/header/hero 之间重复,或用户可见文案含内部实现词 | 标题只在一处写;把「状态实时同步/轮询」这类实现词换成用户关心的事实([card](card.md)) |
70
+ | `card.action-semantics`(建议) | 按钮文案是纯终态词(已领取 / 已过期),点了不会有反应 | 终态不再给按钮(用 status 徽标);仍可操作的写动作短语(已领券 · 查看)([card-action](card-action.md)) |
71
+ | `action.placement-check`(建议) | cardResult 既没写 replaceKey 也没声明 placement: 'sheet' | 明细卡在卡声明写 defaultPlacement: 'sheet';反复触发的卡写 replaceKey(同键原位替换)([card-action](card-action.md)) |
66
72
  <!-- check-docs:errors end -->