@tbox.cn/app-agent-ui-kit 0.0.0-stage → 1.0.0-alpha.10

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 (99) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +69 -2
  3. package/assets/keyboard-circle.svg +12 -0
  4. package/assets/more-circle.svg +3 -0
  5. package/assets/new-chat.svg +3 -0
  6. package/assets/quick-command-star.svg +3 -0
  7. package/assets/send-gradient.svg +14 -0
  8. package/assets/stop@2x.png +0 -0
  9. package/assets/voice-circle.svg +3 -0
  10. package/package.json +70 -3
  11. package/src/ChatPage.tsx +400 -0
  12. package/src/card/action-list-pending.test.tsx +91 -0
  13. package/src/card/define-card.test.ts +25 -0
  14. package/src/card/define-card.ts +47 -0
  15. package/src/card/primitives.test.tsx +157 -0
  16. package/src/card/primitives.tsx +717 -0
  17. package/src/card/use-card-actions.ts +86 -0
  18. package/src/card/view-card-inline.test.tsx +42 -0
  19. package/src/card/view-card.test.tsx +79 -0
  20. package/src/card/view-card.tsx +250 -0
  21. package/src/chat-config.test.ts +46 -0
  22. package/src/chat-config.ts +84 -0
  23. package/src/components/ActionBar/DebugButton.test.tsx +87 -0
  24. package/src/components/ActionBar/DebugButton.tsx +48 -0
  25. package/src/components/ActionBar/index.test.tsx +83 -0
  26. package/src/components/ActionBar/index.tsx +158 -0
  27. package/src/components/BottomSheet/index.test.tsx +97 -0
  28. package/src/components/BottomSheet/index.tsx +49 -0
  29. package/src/components/CardRenderer.tsx +36 -0
  30. package/src/components/ChatHeader/index.test.tsx +74 -0
  31. package/src/components/ChatHeader/index.tsx +77 -0
  32. package/src/components/ChatInput/index.test.tsx +156 -0
  33. package/src/components/ChatInput/index.tsx +295 -0
  34. package/src/components/ChatInput/voice/VoicePressField.tsx +43 -0
  35. package/src/components/ChatInput/voice/VoiceRecordingOverlay.tsx +51 -0
  36. package/src/components/ChatInput/voice/machine.ts +27 -0
  37. package/src/components/ChatInput/voice/useVoicePress.ts +207 -0
  38. package/src/components/HistoryEntry/index.tsx +42 -0
  39. package/src/components/MediaList/index.tsx +270 -0
  40. package/src/components/MessageBubble/index.test.tsx +134 -0
  41. package/src/components/MessageBubble/index.tsx +208 -0
  42. package/src/components/PullDownIndicator/index.tsx +31 -0
  43. package/src/components/QuickCommands/index.test.tsx +101 -0
  44. package/src/components/QuickCommands/index.tsx +75 -0
  45. package/src/components/ReasoningBlock/index.tsx +61 -0
  46. package/src/components/ScrollToBottomButton/index.tsx +12 -0
  47. package/src/components/ToolCallBlock/detail.test.ts +346 -0
  48. package/src/components/ToolCallBlock/detail.ts +204 -0
  49. package/src/components/ToolCallBlock/index.test.tsx +261 -0
  50. package/src/components/ToolCallBlock/index.tsx +232 -0
  51. package/src/components/ToolCallBlock/titles.ts +102 -0
  52. package/src/hooks/use-drag-gesture.test.ts +66 -0
  53. package/src/hooks/use-drag-gesture.ts +129 -0
  54. package/src/hooks/use-pull-down-history.ts +241 -0
  55. package/src/hooks/use-pull-down-wheel-native.test.ts +64 -0
  56. package/src/hooks/useMediaUpload.ts +242 -0
  57. package/src/hooks/useTTSAutoPlay.ts +82 -0
  58. package/src/icons.ts +39 -0
  59. package/src/index.ts +143 -0
  60. package/src/overlay/Overlay.tsx +154 -0
  61. package/src/overlay/focus.ts +53 -0
  62. package/src/overlay/index.ts +16 -0
  63. package/src/overlay/inert.ts +27 -0
  64. package/src/overlay/layers.ts +21 -0
  65. package/src/overlay/overlay.ssr.test.tsx +27 -0
  66. package/src/overlay/overlay.test.tsx +209 -0
  67. package/src/overlay/presence.ts +86 -0
  68. package/src/overlay/scroll-lock.ts +62 -0
  69. package/src/overlay/stack.ts +111 -0
  70. package/src/overlay/use-overlay.ts +80 -0
  71. package/src/preview-provider.tsx +47 -0
  72. package/src/shell.contract.json +75 -0
  73. package/src/shell.test.ts +72 -0
  74. package/src/shell.ts +60 -0
  75. package/src/store-context.tsx +92 -0
  76. package/src/surface.test.tsx +35 -0
  77. package/src/surface.tsx +44 -0
  78. package/src/test/setup.ts +7 -0
  79. package/src/theme/base.css +167 -0
  80. package/src/theme/contract.json +193 -0
  81. package/src/theme/motion.css +19 -0
  82. package/src/theme/theme-contract.test.ts +85 -0
  83. package/src/theme/theme.ts +17 -0
  84. package/src/theme/tokens.css +78 -0
  85. package/src/types.ts +29 -0
  86. package/src/utils/copyText.ts +11 -0
  87. package/src/utils/haptics.test.ts +51 -0
  88. package/src/utils/haptics.ts +44 -0
  89. package/src/utils/image-preview-host.tsx +95 -0
  90. package/src/utils/imagePreview.test.ts +32 -0
  91. package/src/utils/imagePreview.ts +19 -0
  92. package/src/utils/pull-down-machine.test.ts +188 -0
  93. package/src/utils/pull-down-machine.ts +157 -0
  94. package/src/utils/session-error.ts +5 -0
  95. package/src/utils/toast.test.ts +64 -0
  96. package/src/utils/toast.ts +108 -0
  97. package/src/utils/tool-call-display.test.ts +240 -0
  98. package/src/utils/tool-call-display.ts +146 -0
  99. package/src/vite-env.d.ts +1 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 tbox.cn
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,70 @@
1
- # Temporary Holding Version
1
+ # @tbox.cn/app-agent-ui-kit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Agent 对话壳 UI 组件包(源码发布)——单一模板统一化 W2-1 自 mall 模板抽取。
4
+
5
+ - **真源**:本包(`packages/agent-ui-kit`)。模板出厂副本经 `scripts/sync-agent-ui-kit.mjs` 派生
6
+ (name 改写 `@tbox.cn/app-agent-ui-kit` → `@tbox.cn/app-agent-ui-kit`),guard identity 锁定一致。
7
+ - **消费面**:应用 `<ChatPage store={useChatStore} cards={CHAT_REGISTRY} slots={clientCtx.slots}/>`
8
+ 单点装配;应用首页经 home 槽渲染,会话级浮层经 conversationOverlay 槽独立挂载。
9
+ - **主题**:kit 默认 tokens(`src/theme/tokens.css`);品牌资产包经 `html[data-theme]` 级联覆写 +
10
+ 接线三行(`import '<pkg>/index.css'` + `import '<pkg>/brand.js'`[可选] + `applyTheme(id)`;见 docs/reference/templates.md)。
11
+
12
+ ## 弹层(`./overlay`)
13
+
14
+ `Overlay` 是唯一弹层外壳:传送、遮罩、层级、滚动锁、应用根惰性(`inert`)、Escape、焦点循环与恢复、进出场动画都在这里。业务只决定版式(`placement`)与面板样式,不再各写一套。
15
+
16
+ ```tsx
17
+ import { Overlay } from '@tbox.cn/app-agent-ui-kit/overlay';
18
+
19
+ <Overlay
20
+ open={open}
21
+ onDismiss={() => setOpen(false)}
22
+ placement="bottom"
23
+ labelledBy={titleId}
24
+ initialFocus={closeRef}
25
+ rootClassName="my-sheet group"
26
+ panelClassName="my-sheet__panel ..."
27
+ >
28
+ …
29
+ </Overlay>
30
+ ```
31
+
32
+ - **层级三档**:modal `1100` / preview `1200` / toast `1300`(`OVERLAY_LAYER_CLASS`)。同档内按打开先后叠放,嵌套自然成立;不再按组件分配层级。
33
+ - **栈语义**:全实例一个弹层栈,键盘只挂一个 `document` 捕获监听——Escape 与 Tab 只作用于栈顶,嵌套弹层不会一起关;下层根节点自动 `inert`。
34
+ - **滚动锁**:计数式(嵌套按最后关闭者解锁)。滚动宿主由 `ChatPage` 经 `registerScrollHost` 登记,模块不读壳内部类名;无宿主时锁 `body`。
35
+ - **进出场**:根节点 `data-state="open|closed"`;退出动画期间面板不带 `role=dialog`,动画播完才卸载(`motion-reduce` 直接收尾)。自管挂载的宿主用 `onExited` 把 `onClose` 推迟到动画之后。
36
+ - **服务端**:无 `document` 时就地渲染(不 portal),`renderToStaticMarkup` 证据链可直接用。
37
+ - **自管 DOM** 的复杂弹层(如 FLIP 形变详情页)用 `useOverlay` + `usePresence` 组合,行为面与 `Overlay` 相同。
38
+
39
+ ### 半屏弹层
40
+
41
+ `BottomSheet` 是 `Overlay` 之上的受控底部弹层:外壳负责遮罩、滚动锁、安全区、标题、关闭按钮、Escape 与焦点循环/恢复,业务只给内容与开关。
42
+
43
+ ```tsx
44
+ import { BottomSheet } from '@tbox.cn/app-agent-ui-kit/bottom-sheet';
45
+
46
+ <BottomSheet open={open} title="详情" onClose={() => setOpen(false)}>
47
+ <DetailContent />
48
+ </BottomSheet>
49
+ ```
50
+
51
+ 支持 `className` 定制内容区,默认最大高度为视口的 65%,长内容在弹层内部滚动。`preloadBottomSheet()` 保留为已废弃的空操作(弹层不再有第三方运行时需要预热)。
52
+
53
+ ### 大图预览
54
+
55
+ `previewImages(images, index)` 首次调用时按需加载 Yet Another Lightbox(`./utils/image-preview-host`,单独 chunk)。缩放/双击/下拉关闭/点背景关闭由它提供,滚动锁、Escape 与层级走 kit overlay;样式由 `@tbox.cn/app-build` 的 `tboxVendorLayerPlugin` 收进 `@layer vendor`。
56
+
57
+ ### 轻提示
58
+
59
+ `toast(content, tone)` 是纯 DOM 实现(不依赖 React 与组件库):单实例替换、2000ms、视口居中、不拦截点击、`role="status"` 可朗读;Node/SSR 直接空返回。可从 `@tbox.cn/app-agent-ui-kit/toast` 独立导入,避免引入完整聊天壳。
60
+
61
+ ## SSR / Node 边界
62
+
63
+ 弹层与提示都没有第三方 CSS 运行时依赖,`bottom-sheet` / `overlay` / `toast` 子路径在 Vite/Node SSR 里可直接 import。大图预览宿主只经 `import()` 到达(它静态引 Lightbox 与它的 `styles.css`),不会进入 Node 加载图——`scripts/tests/guard-kit-ssr.test.mjs` 按静态可达性守住这条。kit **根入口**仍依赖 SVG/PNG/CSS 资产,只承诺 bundler(Vite 等)消费,不承诺 raw-Node 直跑。
64
+
65
+ ## 验证
66
+
67
+ ```sh
68
+ pnpm --filter @tbox.cn/app-agent-ui-kit typecheck
69
+ pnpm --filter @tbox.cn/app-agent-ui-kit test
70
+ ```
@@ -0,0 +1,12 @@
1
+ <svg width="44px" height="44px" viewBox="0 0 44 44" xmlns="http://www.w3.org/2000/svg">
2
+ <g fill="currentColor" fill-rule="evenodd">
3
+ <path d="M22,0 C34.1502645,0 44,9.8497355 44,22 C44,34.1502645 34.1502645,44 22,44 C9.8497355,44 0,34.1502645 0,22 C0,9.8497355 9.8497355,0 22,0 Z M22,3 C11.5065898,3 3,11.5065898 3,22 C3,32.4934102 11.5065898,41 22,41 C32.4934102,41 41,32.4934102 41,22 C41,11.5065898 32.4934102,3 22,3 Z"/>
4
+ <circle cx="14" cy="15" r="2"/>
5
+ <circle cx="22" cy="15" r="2"/>
6
+ <circle cx="30" cy="15" r="2"/>
7
+ <circle cx="14" cy="22" r="2"/>
8
+ <circle cx="22" cy="22" r="2"/>
9
+ <circle cx="30" cy="22" r="2"/>
10
+ <rect x="12" y="28" width="20" height="4" rx="2"/>
11
+ </g>
12
+ </svg>
@@ -0,0 +1,3 @@
1
+ <svg width="44" height="44" viewBox="0 0 44 44" xmlns="http://www.w3.org/2000/svg">
2
+ <path d="M22,0 C34.15,0 44,9.85 44,22 C44,34.15 34.15,44 22,44 C9.85,44 0,34.15 0,22 C0,9.85 9.85,0 22,0 Z M22,3 C11.507,3 3,11.507 3,22 C3,32.493 11.507,41 22,41 C32.493,41 41,32.493 41,22 C41,11.507 32.493,3 22,3 Z M23.5,11.7 L23.499,20.5 L32.3,20.5 L32.3,23.5 L23.499,23.5 L23.5,32.3 L20.5,32.3 L20.499,23.5 L11.7,23.5 L11.7,20.5 L20.499,20.5 L20.5,11.7 L23.5,11.7 Z" fill="currentColor"/>
3
+ </svg>
@@ -0,0 +1,3 @@
1
+ <svg width="44" height="44" viewBox="0 0 44 44" xmlns="http://www.w3.org/2000/svg">
2
+ <path d="M22,2.75 C26.737,2.74 31.309,4.484 34.837,7.645 L35.002,7.803 C35.259,8.103 35.42,8.488 35.42,8.914 C35.42,9.578 35.019,10.176 34.405,10.428 C33.79,10.68 33.084,10.535 32.619,10.061 L32.674,10.094 C29.981,7.669 26.539,6.239 22.92,6.043 L21.93,6.017 C17.686,6.018 13.619,7.719 10.637,10.74 C5.72,15.726 4.605,23.325 7.883,29.513 L8.078,29.872 L8.078,35.922 L14.128,35.922 L14.491,36.117 C16.493,37.175 18.695,37.799 20.955,37.95 L22,37.987 C25.817,37.987 29.429,36.663 32.303,34.236 L32.736,33.851 C33.335,33.311 34.233,33.271 34.877,33.755 C35.512,34.232 35.699,35.105 35.31,35.798 L35.152,36.08 C31.868,39.164 27.599,40.985 23.1,41.221 L21.912,41.25 C18.928,41.232 15.988,40.527 13.321,39.189 L6.791,39.189 C5.697,39.189 4.811,38.303 4.811,37.209 L4.811,30.683 C1.093,23.283 2.502,14.338 8.316,8.441 C11.638,5.079 16.086,3.065 20.805,2.787 L22,2.75 Z M33.755,13.845 C34.657,13.845 35.387,14.579 35.387,15.477 L35.387,20.368 L40.007,20.368 C40.908,20.368 41.639,21.099 41.639,22 C41.639,22.901 40.908,23.632 40.007,23.632 L35.383,23.632 L35.383,28.424 C35.383,29.325 34.653,30.056 33.752,30.056 C32.851,30.056 32.12,29.325 32.12,28.424 L32.12,23.632 L27.588,23.632 C27.005,23.632 26.466,23.321 26.175,22.816 C25.883,22.311 25.883,21.689 26.175,21.184 C26.466,20.679 27.005,20.368 27.588,20.368 L32.124,20.368 L32.124,15.477 C32.124,14.575 32.857,13.845 33.755,13.845 Z" fill="#4E6688"/>
3
+ </svg>
@@ -0,0 +1,3 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32" fill="none">
2
+ <path d="M16 2C16.8 8.4 23.6 15.2 30 16C23.6 16.8 16.8 23.6 16 30C15.2 23.6 8.4 16.8 2 16C8.4 15.2 15.2 8.4 16 2Z" fill="#4E6688"/>
3
+ </svg>
@@ -0,0 +1,14 @@
1
+ <svg width="56" height="56" viewBox="0 0 56 56" xmlns="http://www.w3.org/2000/svg">
2
+ <defs>
3
+ <linearGradient x1="-22%" y1="14.7%" x2="90.1%" y2="75.2%" id="sendGrad">
4
+ <stop stop-color="#AE94FF" offset="0%"/>
5
+ <stop stop-color="#2388FF" offset="100%"/>
6
+ </linearGradient>
7
+ </defs>
8
+ <circle fill="url(#sendGrad)" cx="28" cy="28" r="28"/>
9
+ <g transform="translate(28,28) rotate(-90) translate(-28,-28) translate(10,10)" fill="#FFF">
10
+ <g transform="translate(16.68,17.1) scale(-1,1) translate(-16.68,-17.1) translate(1.86,4.5)">
11
+ <path d="M27.914,10.908 L5.868,10.908 C5.865,10.908 5.862,10.9 5.865,10.9 L14.18,2.908 C14.615,2.49 14.794,1.871 14.649,1.284 C14.504,0.698 14.057,0.234 13.477,0.066 C12.896,-0.101 12.271,0.054 11.836,0.472 L0.518,11.349 C0.187,11.668 0,12.108 0,12.567 C0,13.027 0.187,13.467 0.518,13.785 L11.898,24.725 C12.22,25.037 12.654,25.208 13.103,25.2 C13.551,25.191 13.978,25.004 14.288,24.679 C14.934,24.005 14.913,22.936 14.241,22.289 L5.927,14.297 C5.923,14.294 5.927,14.289 5.931,14.289 L27.95,14.289 C28.849,14.289 29.583,13.585 29.637,12.702 C29.695,11.723 28.891,10.908 27.913,10.908 L27.914,10.908 Z"/>
12
+ </g>
13
+ </g>
14
+ </svg>
Binary file
@@ -0,0 +1,3 @@
1
+ <svg width="44" height="44" viewBox="0 0 44 44" xmlns="http://www.w3.org/2000/svg">
2
+ <path d="M22,0 C34.15,0 44,9.85 44,22 C44,34.15 34.15,44 22,44 C9.85,44 0,34.15 0,22 C0,9.85 9.85,0 22,0 Z M22,3 C11.507,3 3,11.507 3,22 C3,32.493 11.507,41 22,41 C32.493,41 41,32.493 41,22 C41,11.507 32.493,3 22,3 Z M24.654,8.334 L25.784,9.32 C29.433,12.502 31.568,17.097 31.568,22.034 C31.568,26.932 29.467,31.493 25.87,34.674 L24.746,35.667 L22.759,33.42 L23.883,32.426 C26.843,29.809 28.568,26.063 28.568,22.034 C28.568,17.973 26.814,14.199 23.812,11.58 L22.682,10.594 L24.654,8.334 Z M19.79,13.769 L20.92,14.755 C23.004,16.572 24.224,19.198 24.224,22.018 C24.224,24.815 23.024,27.422 20.969,29.238 L19.845,30.232 L17.858,27.985 L18.982,26.991 C20.399,25.738 21.224,23.946 21.224,22.018 C21.224,20.074 20.385,18.269 18.948,17.016 L17.818,16.03 L19.79,13.769 Z M16.289,19.962 C16.841,19.962 17.289,20.409 17.289,20.962 L17.289,23.038 C17.289,23.591 16.841,24.038 16.289,24.038 L14.212,24.038 C13.66,24.038 13.212,23.591 13.212,23.038 L13.212,20.962 C13.212,20.409 13.66,19.962 14.212,19.962 L16.289,19.962 Z" fill="currentColor"/>
3
+ </svg>
package/package.json CHANGED
@@ -1,6 +1,73 @@
1
1
  {
2
2
  "name": "@tbox.cn/app-agent-ui-kit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0-alpha.10",
4
+ "type": "module",
5
+ "description": "Agent 对话壳 UI 组件包(源码发布,单一模板统一化 W2-1):ChatPage/壳组件族/主题 tokens。",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./src/index.ts",
9
+ "import": "./src/index.ts"
10
+ },
11
+ "./theme": {
12
+ "types": "./src/theme/theme.ts",
13
+ "import": "./src/theme/theme.ts"
14
+ },
15
+ "./package.json": "./package.json",
16
+ "./theme/base.css": "./src/theme/base.css",
17
+ "./theme/contract": "./src/theme/contract.json",
18
+ "./icons": {
19
+ "types": "./src/icons.ts",
20
+ "import": "./src/icons.ts"
21
+ },
22
+ "./toast": {
23
+ "types": "./src/utils/toast.ts",
24
+ "import": "./src/utils/toast.ts"
25
+ },
26
+ "./overlay": {
27
+ "types": "./src/overlay/index.ts",
28
+ "import": "./src/overlay/index.ts"
29
+ },
30
+ "./bottom-sheet": {
31
+ "types": "./src/components/BottomSheet/index.tsx",
32
+ "import": "./src/components/BottomSheet/index.tsx"
33
+ }
34
+ },
35
+ "files": [
36
+ "src",
37
+ "assets",
38
+ "README.md",
39
+ "LICENSE"
40
+ ],
41
+ "dependencies": {
42
+ "@phosphor-icons/react": "2.1.10",
43
+ "react-markdown": "9.1.0",
44
+ "remark-gfm": "4.0.1",
45
+ "yet-another-react-lightbox": "3.33.1",
46
+ "zustand": "4.5.7",
47
+ "@tbox.cn/app-agent-sdk-client": "1.0.0-alpha.10",
48
+ "@tbox.cn/app-contracts": "1.0.0-alpha.10"
49
+ },
50
+ "peerDependencies": {
51
+ "react": "18.3.1",
52
+ "react-dom": "18.3.1"
53
+ },
54
+ "devDependencies": {
55
+ "@types/node": "24.13.3",
56
+ "@types/react": "18.3.31",
57
+ "@types/react-dom": "18.3.7",
58
+ "happy-dom": "20.11.2",
59
+ "react": "18.3.1",
60
+ "react-dom": "18.3.1",
61
+ "typescript": "5.9.3",
62
+ "vite": "6.4.3",
63
+ "vitest": "4.1.10"
64
+ },
65
+ "engines": {
66
+ "node": ">=20.0.0"
67
+ },
68
+ "license": "MIT",
69
+ "scripts": {
70
+ "typecheck": "tsc --noEmit",
71
+ "test": "vitest run"
72
+ }
6
73
  }
@@ -0,0 +1,400 @@
1
+ /**
2
+ * ChatPage(单一模板统一化 W2-1:自 mall 模板 pages/index/index.tsx 抽取通用页)。
3
+ *
4
+ * - 自组 KitChatProvider(store/cards/rawCards/slots 注入位;应用单点装配);
5
+ * - 应用形态由 home 槽存在性派生(D7):注册 home → 空态渲染槽(home-first,会话态与
6
+ * 空态恒挂载——域自持其显隐);缺席 → chat 流(空态为空体,landing 槽已退役);
7
+ * - 域自持段(首屏数据/门禁/详情弹层/活动预热)经槽渲染函数自带——本页零域语义。
8
+ */
9
+ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
10
+
11
+ // SSR(预览/探针)没有 DOM 可量:useLayoutEffect 会打印不可消除的告警,服务端退化为 useEffect。
12
+ const useIsomorphicLayoutEffect = typeof window === 'undefined' ? useEffect : useLayoutEffect;
13
+ import { consumeAutoSendQuery, runAutoSend } from '@tbox.cn/app-agent-sdk-client';
14
+ import { usePullDownHistory } from './hooks/use-pull-down-history';
15
+ import { registerScrollHost } from './overlay';
16
+ import type { TboxCardPayload } from '@tbox.cn/app-contracts';
17
+ import { CardRenderer } from './components/CardRenderer';
18
+ import { ChatInput } from './components/ChatInput';
19
+ import HistoryEntry from './components/HistoryEntry';
20
+ import { MessageBubble } from './components/MessageBubble';
21
+ import { QuickCommands } from './components/QuickCommands';
22
+ import ScrollToBottomButton from './components/ScrollToBottomButton';
23
+ import { useChatConfigStore } from './chat-config';
24
+ import { resolveBrandName } from './shell';
25
+ import {
26
+ KitChatProvider,
27
+ useChatStore,
28
+ useClientSlots,
29
+ useInlineCardFilter,
30
+ type KitChatContextValue,
31
+ } from './store-context';
32
+ import type { ChatInputMessage } from './types';
33
+ import './theme/tokens.css';
34
+
35
+ export interface ChatPageProps {
36
+ /** 应用 chat store(zustand 绑定 hook + API;如 `useChatStore`) */
37
+ store: KitChatContextValue['store'];
38
+ /** 聊天入口卡片注册表(模块注册 + 组合层覆盖) */
39
+ cards: KitChatContextValue['cards'];
40
+ /** 原始形态卡片注册表(缺省 = cards——无覆盖应用零配置) */
41
+ rawCards?: KitChatContextValue['rawCards'];
42
+ /** 客户端槽注册表(home 首期唯一槽;缺席 = chat 流形态) */
43
+ slots?: KitChatContextValue['slots'];
44
+ /**
45
+ * 旁路卡内联流过滤(域注入;缺省恒等):域可声明哪些 orphan 卡不进内联流
46
+ * (由域浮层自持,如 mall 会员门禁卡系)——过滤结果同时参与 home-first 形态判定。
47
+ */
48
+ filterInlineCards?: (cards: readonly TboxCardPayload[]) => TboxCardPayload[];
49
+ }
50
+
51
+ export function ChatPage({ store, cards, rawCards, slots, filterInlineCards }: ChatPageProps) {
52
+ return (
53
+ <KitChatProvider
54
+ store={store}
55
+ cards={cards}
56
+ rawCards={rawCards ?? cards}
57
+ {...(slots ? { slots } : {})}
58
+ {...(filterInlineCards ? { filterInlineCards } : {})}
59
+ >
60
+ <ChatPageInner />
61
+ </KitChatProvider>
62
+ );
63
+ }
64
+
65
+ function ChatPageInner() {
66
+ const messages = useChatStore((s) => s.messages);
67
+ const historyMessages = useChatStore((s) => s.historyMessages);
68
+ const historyHasMore = useChatStore((s) => s.historyHasMore);
69
+ const isLoadingHistory = useChatStore((s) => s.isLoadingHistory);
70
+ const loadMoreHistory = useChatStore((s) => s.loadMoreHistory);
71
+ const isGenerating = useChatStore((s) => s.isGenerating);
72
+ const runtimeStatus = useChatStore((s) => s.runtimeStatus);
73
+ const authBlocked = useChatStore((s) => s.authBlocked);
74
+ const orphanCards = useChatStore((s) => s.orphanCards);
75
+ const cardsByMessageId = useChatStore((s) => s.cardsByMessageId);
76
+ const initConversation = useChatStore((s) => s.initConversation);
77
+ const destroy = useChatStore((s) => s.destroy);
78
+ const sendMessage = useChatStore((s) => s.sendMessage);
79
+ const cancelGeneration = useChatStore((s) => s.cancelGeneration);
80
+ const newConversation = useChatStore((s) => s.newConversation);
81
+ const retryBootstrap = useChatStore((s) => s.retryBootstrap);
82
+ // 品牌名 = HELLO_ACK.mallScope.mallName(服务端 buildScope 回显;存在即可渲染的 kit 同源约定)
83
+ const mallName = useChatStore((s) => s.helloAck?.mallScope?.mallName);
84
+ // chat settings 水合:HELLO_ACK 服务端真源 → 静态 store(ack 未达/键缺席保留构建期快照;
85
+ // 重连/新会话产生新 helloAck 再水合——applyServerSettings 幂等)
86
+ const serverSettings = useChatStore((s) => s.helloAck?.chatConfig?.settings);
87
+ const applyServerSettings = useChatConfigStore((s) => s.applyServerSettings);
88
+ useEffect(() => {
89
+ applyServerSettings(serverSettings);
90
+ }, [serverSettings, applyServerSettings]);
91
+
92
+ const slots = useClientSlots();
93
+ const homeSlot = slots?.resolve('home');
94
+ const conversationOverlay = slots?.resolve('conversationOverlay');
95
+ const identity = useChatConfigStore((s) => s.identity);
96
+ const welcome = useChatConfigStore((s) => s.welcome);
97
+
98
+ // 页面元信息跟身份与主题走:标题、主题色不再停在模板出厂值(B9)。
99
+ useEffect(() => {
100
+ if (typeof document === 'undefined') return;
101
+ const name = identity?.name;
102
+ if (name) document.title = name;
103
+ const bg = getComputedStyle(document.documentElement).getPropertyValue('--tbox-bg-page').trim();
104
+ if (bg) {
105
+ let meta = document.querySelector('meta[name="theme-color"]');
106
+ if (!meta) {
107
+ meta = document.createElement('meta');
108
+ meta.setAttribute('name', 'theme-color');
109
+ document.head.appendChild(meta);
110
+ }
111
+ meta.setAttribute('content', bg);
112
+ }
113
+ }, [identity?.name]);
114
+ // 常驻品牌条:chat.json identity.name → HELLO_ACK 的 mallName → 不渲染(壳契约见 shell.ts)
115
+ const brandName = resolveBrandName(identity, mallName);
116
+
117
+ const [showScrollToBottom, setShowScrollToBottom] = useState(false);
118
+ const [voiceActive, setVoiceActive] = useState(false);
119
+ const bodyRef = useRef<HTMLDivElement>(null);
120
+
121
+ // 弹层滚动锁要锁的是应用自己的滚动宿主(body 在本壳里并不滚动):登记给 kit overlay 内核,
122
+ // 业务弹层因此不再需要读 `.chat-page__body` 这类壳内部类名。
123
+ useEffect(() => {
124
+ const el = bodyRef.current;
125
+ if (!el) return undefined;
126
+ return registerScrollHost(el);
127
+ }, []);
128
+ // 底部输入区(QuickCommands + ChatInput)高度测量:底部避让消费(如半屏 sheet)
129
+ const chatBottomRef = useRef<HTMLDivElement>(null);
130
+ // 历史前插视口锚:home 槽位占位(历史插入发生在其上,保持用户看到的位置)
131
+ const historyAnchorRef = useRef<HTMLDivElement>(null);
132
+ const historyLoadInFlightRef = useRef<Promise<void> | null>(null);
133
+ const pendingHistoryViewportRef = useRef<{ anchorTop: number } | null>(null);
134
+ const isAtTopRef = useRef(true);
135
+ const isNearBottomRef = useRef(true);
136
+
137
+ const startNewConversation = useCallback(() => {
138
+ void newConversation();
139
+ const el = bodyRef.current;
140
+ if (el) el.scrollTop = 0;
141
+ isAtTopRef.current = true;
142
+ isNearBottomRef.current = false;
143
+ setShowScrollToBottom(false);
144
+ }, [newConversation]);
145
+
146
+ const send = useCallback((input: string | ChatInputMessage) => {
147
+ // 主动发送代表用户要回到最新对话;待消息 DOM 提交后由下方 effect 落底。
148
+ // 生成中 store 会拒绝新消息,此时不改变用户正在查看的滚动位置。
149
+ if (isGenerating) return;
150
+ isNearBottomRef.current = true;
151
+ setShowScrollToBottom(false);
152
+ sendMessage(input);
153
+ }, [isGenerating, sendMessage]);
154
+
155
+ // 连接终态阻断(登录失败/scope 拒绝):禁用输入 + 提示条 + 重试。
156
+ // 门控仅 runtimeStatus=failed 或 authBlocked——bootstrapping 等过渡态不闪现横幅
157
+ const blocked =
158
+ runtimeStatus === 'failed' || authBlocked
159
+ ? {
160
+ message: authBlocked ?? '登录失败,暂时无法对话',
161
+ onRetry: () => void retryBootstrap(true),
162
+ }
163
+ : undefined;
164
+
165
+ const scrollToBottom = useCallback(() => {
166
+ const el = bodyRef.current;
167
+ if (el) el.scrollTop = el.scrollHeight;
168
+ isNearBottomRef.current = true;
169
+ setShowScrollToBottom(false);
170
+ }, []);
171
+
172
+ const NEAR_BOTTOM = 150;
173
+ const onScroll = useCallback(() => {
174
+ const el = bodyRef.current;
175
+ if (!el) return;
176
+ isAtTopRef.current = el.scrollTop <= 5;
177
+ const distanceToBottom = el.scrollHeight - el.scrollTop - el.clientHeight;
178
+ isNearBottomRef.current = distanceToBottom < NEAR_BOTTOM;
179
+ setShowScrollToBottom(!isNearBottomRef.current);
180
+ }, []);
181
+
182
+ // 顶部入口与轻量下拉共用同一加载任务;同一周期复用 Promise,避免点击/手势重复请求。
183
+ const onLoadHistory = useCallback(() => {
184
+ if (historyLoadInFlightRef.current) return historyLoadInFlightRef.current;
185
+ const anchor = historyAnchorRef.current;
186
+ if (anchor) {
187
+ pendingHistoryViewportRef.current = {
188
+ anchorTop: anchor.getBoundingClientRect().top,
189
+ };
190
+ }
191
+ const task = loadMoreHistory().finally(() => {
192
+ if (historyLoadInFlightRef.current === task) historyLoadInFlightRef.current = null;
193
+ });
194
+ historyLoadInFlightRef.current = task;
195
+ return task;
196
+ }, [loadMoreHistory]);
197
+
198
+ // 历史插入发生在当前内容上方:绘制前只补一次新增高度,保持用户原本看到的位置。
199
+ // 不设置定时器、不钉住 scrollTop;补偿后下一次滚动立即由用户接管。
200
+ useIsomorphicLayoutEffect(() => {
201
+ const pending = pendingHistoryViewportRef.current;
202
+ const anchor = historyAnchorRef.current;
203
+ if (!pending || !anchor) return;
204
+ pendingHistoryViewportRef.current = null;
205
+ const anchorDelta = anchor.getBoundingClientRect().top - pending.anchorTop;
206
+ if (Math.abs(anchorDelta) > 0.5) {
207
+ const el = bodyRef.current;
208
+ if (el) el.scrollTop += anchorDelta;
209
+ }
210
+ }, [historyMessages]);
211
+
212
+ const filterInlineCards = useInlineCardFilter();
213
+ const inlineOrphanCards = useMemo(
214
+ () => filterInlineCards(orphanCards),
215
+ [orphanCards, filterInlineCards],
216
+ );
217
+
218
+ // 是否仍为空会话(home-first 形态判定);home 槽缺席时始终为对话形态
219
+ const showHome = !!homeSlot
220
+ && historyMessages.length === 0
221
+ && messages.length === 0
222
+ && inlineOrphanCards.length === 0;
223
+
224
+ const liveCardSignature = useMemo(
225
+ () => messages
226
+ .map((message) => `${message.id}:${(cardsByMessageId[message.id] ?? []).map((card) => card.id).join(',')}`)
227
+ .join('|'),
228
+ [messages, cardsByMessageId],
229
+ );
230
+
231
+ const showHistoryEntry = historyHasMore && historyMessages.length === 0;
232
+
233
+ // 空会话欢迎区:没有 home 槽时给首屏一个落点(标题来自 chat.json welcome,缺省「开始对话」)
234
+ const showWelcome = !homeSlot
235
+ && historyMessages.length === 0
236
+ && messages.length === 0
237
+ && inlineOrphanCards.length === 0;
238
+ const welcomeTitle = welcome?.title ?? identity?.name ?? '开始对话';
239
+ const welcomeSubtitle = welcome?.subtitle ?? identity?.tagline ?? '可以直接提问,也可以从下面的问题开始';
240
+ // 空会话(有 home 槽或无 home 槽)共用快捷问题的显示条件。
241
+ const isEmptyState = showHome || showWelcome;
242
+
243
+ const pull = usePullDownHistory({
244
+ isAtTopRef,
245
+ isLoadingHistory,
246
+ hasMore: historyHasMore,
247
+ onLoad: onLoadHistory,
248
+ disabled: runtimeStatus !== 'ready',
249
+ });
250
+
251
+ useEffect(() => {
252
+ // 深链自动发送:同步消费(StrictMode 双挂载/刷新安全),引导完成后等连接就绪发送
253
+ const autoQuery = consumeAutoSendQuery();
254
+ void initConversation().then(async () => {
255
+ if (autoQuery) await runAutoSend(autoQuery, sendMessage);
256
+ });
257
+ return () => {
258
+ destroy();
259
+ };
260
+ // eslint-disable-next-line react-hooks/exhaustive-deps
261
+ }, []);
262
+
263
+ // 底部输入区高度 → CSS 变量 --tbox-chat-bottom-height,供半屏 sheet(portal 到 body)避让消费。
264
+ useEffect(() => {
265
+ const el = chatBottomRef.current;
266
+ if (!el) return;
267
+ const update = () =>
268
+ document.documentElement.style.setProperty('--tbox-chat-bottom-height', `${el.offsetHeight}px`);
269
+ update();
270
+ const ro = new ResizeObserver(update);
271
+ ro.observe(el);
272
+ return () => ro.disconnect();
273
+ }, []);
274
+
275
+ // 回合锚定:新回合把本轮用户消息置顶,流式期间不追底。
276
+ // 贴底滚动会把问题顶出视口(实测卡片 648px 时问题上移 244px),用户看不到自己在问什么。
277
+ const turnAnchorRef = useRef<string | null>(null);
278
+ useEffect(() => {
279
+ const lastUser = [...messages].reverse().find((message) => message.role === 'user');
280
+ if (!lastUser || turnAnchorRef.current === lastUser.id) return;
281
+ turnAnchorRef.current = lastUser.id;
282
+ const body = bodyRef.current;
283
+ const element = body?.querySelector(`[data-message-id="${lastUser.id}"]`);
284
+ if (!body || !element) return;
285
+ const delta = element.getBoundingClientRect().top - body.getBoundingClientRect().top;
286
+ body.scrollTop += delta - 8;
287
+ isNearBottomRef.current = false;
288
+ // 回合锚定后内容通常超出视口:必须让「回到底部」入口出现,否则用户只能靠手势找底。
289
+ if (body.scrollHeight > body.clientHeight + 8) setShowScrollToBottom(true);
290
+ }, [messages]);
291
+
292
+ // 已脱离底部时内容继续变高(流式回复、卡片后挂载):保持浮标可见,不追底。
293
+ useEffect(() => {
294
+ if (isNearBottomRef.current) return;
295
+ const el = bodyRef.current;
296
+ if (el && el.scrollHeight > el.clientHeight + 8) setShowScrollToBottom(true);
297
+ }, [messages, liveCardSignature, orphanCards]);
298
+
299
+ // 没有新回合、但卡片在文字之后挂载时,内容会继续变高:只在用户本来就在底部时补滚,
300
+ // 且不改变「本轮问题已在视口内」的锚点。
301
+ useEffect(() => {
302
+ if (!isNearBottomRef.current) return;
303
+ const el = bodyRef.current;
304
+ if (el && messages.length === 0 && orphanCards.length > 0) el.scrollTop = el.scrollHeight;
305
+ }, [orphanCards, liveCardSignature, messages.length]);
306
+
307
+ return (
308
+ <div className={`chat-page relative flex h-full w-full min-h-0 flex-col overflow-hidden bg-background ${showHome ? '' : ' chat-page--conversation'}`}>
309
+ {/* 整页背景独立于滚动内容,覆盖历史入口、首页与底部输入区;图片按视口居中铺满、不重复。 */}
310
+ <div className="chat-page__bg pointer-events-none absolute inset-0 z-0 bg-background bg-center bg-cover bg-no-repeat" />
311
+
312
+ {brandName ? (
313
+ <div className="chat-page__brand relative z-10 flex items-baseline justify-center gap-3 border-b border-border bg-background px-page pb-3 pt-[calc(16px+env(safe-area-inset-top))]" aria-label={brandName}>
314
+ <span className="chat-page__brand-name text-base font-bold tracking-wide text-foreground">{brandName}</span>
315
+ {identity?.tagline ? <span className="chat-page__brand-tagline text-xs text-muted-foreground">{identity.tagline}</span> : null}
316
+ </div>
317
+ ) : null}
318
+
319
+ <div className="chat-page__body-wrapper relative z-10 flex min-h-0 flex-1 flex-col">
320
+ <div
321
+ className="chat-page__body mx-auto w-full max-w-content flex-1 min-h-0 overflow-y-auto overflow-x-hidden overscroll-contain pb-6 pt-[calc(12px+env(safe-area-inset-top))] [overflow-anchor:none] [scrollbar-width:none] [-webkit-overflow-scrolling:touch] [&::-webkit-scrollbar]:hidden"
322
+ ref={bodyRef}
323
+ onScroll={onScroll}
324
+ onWheel={pull.handleWheel}
325
+ onTouchStart={pull.handleTouchStart}
326
+ onTouchMove={pull.handleTouchMove}
327
+ onTouchEnd={pull.handleTouchEnd}
328
+ onTouchCancel={pull.handleTouchCancel}
329
+ >
330
+ <HistoryEntry
331
+ visible={showHistoryEntry}
332
+ loading={isLoadingHistory}
333
+ disabled={runtimeStatus !== 'ready' || isLoadingHistory}
334
+ pullStatus={pull.pullStatus}
335
+ onLoad={() => void onLoadHistory()}
336
+ />
337
+
338
+ <div className="chat-page__history">
339
+ {historyMessages.map((msg) => (
340
+ <MessageBubble key={msg.id} message={msg} />
341
+ ))}
342
+ </div>
343
+
344
+ {/* 空会话欢迎区:没有 home 槽时的首屏落点(文案来自 chat.json welcome / identity) */}
345
+ {showWelcome ? (
346
+ <div className="chat-page__welcome flex flex-col items-center justify-center gap-2 px-page pb-4 pt-6 text-center">
347
+ <h2 className="chat-page__welcome-title m-0 text-xl font-bold text-foreground">{welcomeTitle}</h2>
348
+ {welcomeSubtitle ? <p className="chat-page__welcome-subtitle m-0 text-sm leading-normal text-muted-foreground">{welcomeSubtitle}</p> : null}
349
+ </div>
350
+ ) : null}
351
+
352
+ {/* 历史前插视口锚 + home 槽渲染位(域自持显隐;缺席则不渲染)。flow-root 让首页子元素
353
+ 的外边距留在槽内,不折叠到历史入口与首页之间。 */}
354
+ <div className="chat-page__home-slot flow-root" ref={historyAnchorRef}>
355
+ {homeSlot?.({ onSend: send, ...(mallName ? { mallName } : {}) })}
356
+ </div>
357
+
358
+ {/* 空会话的服务入口:快捷问题与欢迎区成组居中,两列全可见(不再贴底单行溢出)。 */}
359
+ {!blocked && isEmptyState ? (
360
+ <div className="chat-page__home-actions mt-6 flex w-full flex-col items-center">
361
+ <QuickCommands variant="grid" hidden={voiceActive} onCommand={send} />
362
+ </div>
363
+ ) : null}
364
+
365
+ {/* 业务旁路 emit 的卡片(如欢迎卡) */}
366
+ {inlineOrphanCards.map((card) => (
367
+ <div key={card.id} className="chat-page__orphan-card mx-page">
368
+ <CardRenderer card={card} />
369
+ </div>
370
+ ))}
371
+
372
+ {/* 消息(每条消息下的卡片由 MessageBubble 内部渲染) */}
373
+ {messages.map((msg) => (
374
+ <MessageBubble key={msg.id} message={msg} />
375
+ ))}
376
+ </div>
377
+
378
+ <ScrollToBottomButton visible={showScrollToBottom} onClick={scrollToBottom} />
379
+ </div>
380
+
381
+ {/* 对话态保留底部快捷指令;空会话的快捷问题在正文里成组展示(不重复渲染)。 */}
382
+ <div ref={chatBottomRef}>
383
+ {!blocked && !isEmptyState && <QuickCommands hidden={voiceActive} onCommand={send} />}
384
+ <ChatInput
385
+ generating={isGenerating}
386
+ blocked={blocked}
387
+ onSend={send}
388
+ onCancel={cancelGeneration}
389
+ onNewChat={startNewConversation}
390
+ onVoiceActivityChange={setVoiceActive}
391
+ />
392
+ </div>
393
+ {conversationOverlay && (
394
+ <div className="chat-page__conversation-overlay contents">
395
+ {conversationOverlay({ onSend: send, ...(mallName ? { mallName } : {}) })}
396
+ </div>
397
+ )}
398
+ </div>
399
+ );
400
+ }