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

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 (79) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +16 -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 +55 -3
  11. package/src/ChatPage.less +62 -0
  12. package/src/ChatPage.tsx +305 -0
  13. package/src/chat-config.test.ts +82 -0
  14. package/src/chat-config.ts +62 -0
  15. package/src/components/ActionBar/DebugButton.test.tsx +84 -0
  16. package/src/components/ActionBar/DebugButton.tsx +53 -0
  17. package/src/components/ActionBar/index.less +123 -0
  18. package/src/components/ActionBar/index.test.tsx +83 -0
  19. package/src/components/ActionBar/index.tsx +159 -0
  20. package/src/components/CardRenderer.tsx +36 -0
  21. package/src/components/ChatHeader/index.less +148 -0
  22. package/src/components/ChatHeader/index.test.tsx +74 -0
  23. package/src/components/ChatHeader/index.tsx +75 -0
  24. package/src/components/ChatInput/index.less +394 -0
  25. package/src/components/ChatInput/index.test.tsx +156 -0
  26. package/src/components/ChatInput/index.tsx +284 -0
  27. package/src/components/ChatInput/voice/VoicePressField.tsx +34 -0
  28. package/src/components/ChatInput/voice/VoiceRecordingOverlay.tsx +51 -0
  29. package/src/components/ChatInput/voice/machine.ts +27 -0
  30. package/src/components/ChatInput/voice/useVoicePress.ts +207 -0
  31. package/src/components/HistoryEntry/index.less +49 -0
  32. package/src/components/HistoryEntry/index.tsx +42 -0
  33. package/src/components/MediaList/index.less +241 -0
  34. package/src/components/MediaList/index.tsx +256 -0
  35. package/src/components/MessageBubble/index.less +325 -0
  36. package/src/components/MessageBubble/index.test.tsx +134 -0
  37. package/src/components/MessageBubble/index.tsx +177 -0
  38. package/src/components/PullDownIndicator/index.less +32 -0
  39. package/src/components/PullDownIndicator/index.tsx +32 -0
  40. package/src/components/QuickCommands/index.less +63 -0
  41. package/src/components/QuickCommands/index.test.tsx +99 -0
  42. package/src/components/QuickCommands/index.tsx +52 -0
  43. package/src/components/ReasoningBlock/index.less +90 -0
  44. package/src/components/ReasoningBlock/index.tsx +56 -0
  45. package/src/components/ScrollToBottomButton/index.less +32 -0
  46. package/src/components/ScrollToBottomButton/index.tsx +10 -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.less +312 -0
  50. package/src/components/ToolCallBlock/index.test.tsx +261 -0
  51. package/src/components/ToolCallBlock/index.tsx +212 -0
  52. package/src/components/ToolCallBlock/titles.ts +102 -0
  53. package/src/hooks/use-drag-gesture.test.ts +66 -0
  54. package/src/hooks/use-drag-gesture.ts +129 -0
  55. package/src/hooks/use-pull-down-history.ts +241 -0
  56. package/src/hooks/use-pull-down-wheel-native.test.ts +64 -0
  57. package/src/hooks/useMediaUpload.ts +242 -0
  58. package/src/hooks/useTTSAutoPlay.ts +82 -0
  59. package/src/index.ts +69 -0
  60. package/src/store-context.tsx +92 -0
  61. package/src/test/setup.ts +7 -0
  62. package/src/theme/contract.json +72 -0
  63. package/src/theme/global.less +99 -0
  64. package/src/theme/motion.less +19 -0
  65. package/src/theme/theme-contract.test.ts +69 -0
  66. package/src/theme/theme.ts +17 -0
  67. package/src/theme/tokens.less +79 -0
  68. package/src/types.ts +29 -0
  69. package/src/utils/copyText.ts +11 -0
  70. package/src/utils/haptics.test.ts +51 -0
  71. package/src/utils/haptics.ts +44 -0
  72. package/src/utils/imagePreview.ts +10 -0
  73. package/src/utils/pull-down-machine.test.ts +188 -0
  74. package/src/utils/pull-down-machine.ts +157 -0
  75. package/src/utils/session-error.ts +5 -0
  76. package/src/utils/toast.ts +15 -0
  77. package/src/utils/tool-call-display.test.ts +240 -0
  78. package/src/utils/tool-call-display.ts +146 -0
  79. 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,17 @@
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` → `@app/agent-ui-kit`),guard identity 锁定一致。
7
+ - **消费面**:应用 `<ChatPage store={useChatStore} cards={CHAT_REGISTRY} slots={clientCtx.slots}/>`
8
+ 单点装配;域 UI(如商圈主屏)经 home 槽渲染函数自带。
9
+ - **主题**:kit 默认 tokens(`src/theme/tokens.less`);品牌资产包经 `html[data-theme]` 级联覆写 +
10
+ 接线三行(`import '<pkg>/index.css'` + `import '<pkg>/brand.js'`[可选] + `applyTheme(id)`;见 docs/reference/templates.md)。
11
+
12
+ ## 验证
13
+
14
+ ```sh
15
+ pnpm --filter @tbox.cn/app-agent-ui-kit typecheck
16
+ pnpm --filter @tbox.cn/app-agent-ui-kit test
17
+ ```
@@ -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,58 @@
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.1",
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/global.less": "./src/theme/global.less",
17
+ "./theme/contract": "./src/theme/contract.json"
18
+ },
19
+ "files": [
20
+ "src",
21
+ "assets",
22
+ "README.md",
23
+ "LICENSE"
24
+ ],
25
+ "dependencies": {
26
+ "@tbox.cn/app-contracts": "1.0.0-alpha.1",
27
+ "@phosphor-icons/react": "2.1.10",
28
+ "antd-mobile": "5.42.3",
29
+ "react-markdown": "9.1.0",
30
+ "remark-gfm": "4.0.1",
31
+ "zustand": "4.5.7",
32
+ "@tbox.cn/app-agent-sdk-client": "1.0.0-alpha.1"
33
+ },
34
+ "peerDependencies": {
35
+ "react": "18.3.1",
36
+ "react-dom": "18.3.1"
37
+ },
38
+ "devDependencies": {
39
+ "@types/node": "24.13.3",
40
+ "@types/react": "18.3.31",
41
+ "@types/react-dom": "18.3.7",
42
+ "happy-dom": "20.11.2",
43
+ "less": "4.8.1",
44
+ "react": "18.3.1",
45
+ "react-dom": "18.3.1",
46
+ "typescript": "5.9.3",
47
+ "vite": "6.4.3",
48
+ "vitest": "4.1.10"
49
+ },
50
+ "engines": {
51
+ "node": ">=20.0.0"
52
+ },
53
+ "license": "MIT",
54
+ "scripts": {
55
+ "typecheck": "tsc --noEmit",
56
+ "test": "vitest run"
57
+ }
6
58
  }
@@ -0,0 +1,62 @@
1
+ .chat-page {
2
+ position: relative;
3
+ display: flex;
4
+ flex-direction: column;
5
+ width: 100%;
6
+ height: 100vh;
7
+ height: 100dvh;
8
+ min-height: 0;
9
+ overflow: hidden;
10
+ background: var(--tbox-bg-page);
11
+
12
+ &__bg {
13
+ position: absolute;
14
+ inset: 0;
15
+ z-index: 0;
16
+ background: var(--tbox-bg-page);
17
+ pointer-events: none;
18
+ }
19
+
20
+ &__body-wrapper {
21
+ position: relative;
22
+ z-index: 1;
23
+ display: flex;
24
+ flex: 1;
25
+ flex-direction: column;
26
+ min-height: 0;
27
+ }
28
+
29
+ &__body {
30
+ flex: 1;
31
+ width: 100%;
32
+ max-width: var(--tbox-content-max-width);
33
+ min-height: 0;
34
+ margin: 0 auto;
35
+ padding: calc(12PX + env(safe-area-inset-top, 0PX)) 0 24PX;
36
+ overflow-y: auto;
37
+ overflow-x: hidden;
38
+ overflow-anchor: none;
39
+ overscroll-behavior: contain;
40
+ scrollbar-width: none;
41
+ -webkit-overflow-scrolling: touch;
42
+
43
+ &::-webkit-scrollbar {
44
+ display: none;
45
+ }
46
+ }
47
+
48
+ &__orphan-card {
49
+ margin-right: var(--tbox-page-gutter);
50
+ margin-left: var(--tbox-page-gutter);
51
+ }
52
+
53
+ /* 顶部历史入口在场时欢迎区不再叠加自身顶部留白:胶囊到标题区留 4PX(= 欢迎区自带上边距)。 */
54
+ .history-entry ~ .mall-home {
55
+ padding-top: 0;
56
+ }
57
+
58
+ /* 对话开始后首页仍保留,消息接在联单主卡下方。 */
59
+ &--conversation &__body {
60
+ padding-top: calc(12PX + env(safe-area-inset-top, 0PX));
61
+ }
62
+ }
@@ -0,0 +1,305 @@
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
+ import { consumeAutoSendQuery, runAutoSend } from '@tbox.cn/app-agent-sdk-client';
11
+ import { usePullDownHistory } from './hooks/use-pull-down-history';
12
+ import type { TboxCardPayload } from '@tbox.cn/app-contracts';
13
+ import { CardRenderer } from './components/CardRenderer';
14
+ import { ChatInput } from './components/ChatInput';
15
+ import HistoryEntry from './components/HistoryEntry';
16
+ import { MessageBubble } from './components/MessageBubble';
17
+ import { QuickCommands } from './components/QuickCommands';
18
+ import ScrollToBottomButton from './components/ScrollToBottomButton';
19
+ import { useChatConfigStore } from './chat-config';
20
+ import {
21
+ KitChatProvider,
22
+ useChatStore,
23
+ useClientSlots,
24
+ useInlineCardFilter,
25
+ type KitChatContextValue,
26
+ } from './store-context';
27
+ import type { ChatInputMessage } from './types';
28
+ import './ChatPage.less';
29
+ import './theme/tokens.less';
30
+
31
+ export interface ChatPageProps {
32
+ /** 应用 chat store(zustand 绑定 hook + API;如 `useChatStore`) */
33
+ store: KitChatContextValue['store'];
34
+ /** 聊天入口卡片注册表(模块注册 + 组合层覆盖) */
35
+ cards: KitChatContextValue['cards'];
36
+ /** 原始形态卡片注册表(缺省 = cards——无覆盖应用零配置) */
37
+ rawCards?: KitChatContextValue['rawCards'];
38
+ /** 客户端槽注册表(home 首期唯一槽;缺席 = chat 流形态) */
39
+ slots?: KitChatContextValue['slots'];
40
+ /**
41
+ * 旁路卡内联流过滤(域注入;缺省恒等):域可声明哪些 orphan 卡不进内联流
42
+ * (由域浮层自持,如 mall 会员门禁卡系)——过滤结果同时参与 home-first 形态判定。
43
+ */
44
+ filterInlineCards?: (cards: readonly TboxCardPayload[]) => TboxCardPayload[];
45
+ }
46
+
47
+ export function ChatPage({ store, cards, rawCards, slots, filterInlineCards }: ChatPageProps) {
48
+ return (
49
+ <KitChatProvider
50
+ store={store}
51
+ cards={cards}
52
+ rawCards={rawCards ?? cards}
53
+ {...(slots ? { slots } : {})}
54
+ {...(filterInlineCards ? { filterInlineCards } : {})}
55
+ >
56
+ <ChatPageInner />
57
+ </KitChatProvider>
58
+ );
59
+ }
60
+
61
+ function ChatPageInner() {
62
+ const messages = useChatStore((s) => s.messages);
63
+ const historyMessages = useChatStore((s) => s.historyMessages);
64
+ const historyHasMore = useChatStore((s) => s.historyHasMore);
65
+ const isLoadingHistory = useChatStore((s) => s.isLoadingHistory);
66
+ const loadMoreHistory = useChatStore((s) => s.loadMoreHistory);
67
+ const isGenerating = useChatStore((s) => s.isGenerating);
68
+ const runtimeStatus = useChatStore((s) => s.runtimeStatus);
69
+ const authBlocked = useChatStore((s) => s.authBlocked);
70
+ const orphanCards = useChatStore((s) => s.orphanCards);
71
+ const cardsByMessageId = useChatStore((s) => s.cardsByMessageId);
72
+ const initConversation = useChatStore((s) => s.initConversation);
73
+ const destroy = useChatStore((s) => s.destroy);
74
+ const sendMessage = useChatStore((s) => s.sendMessage);
75
+ const cancelGeneration = useChatStore((s) => s.cancelGeneration);
76
+ const newConversation = useChatStore((s) => s.newConversation);
77
+ const retryBootstrap = useChatStore((s) => s.retryBootstrap);
78
+ // 品牌名 = HELLO_ACK.mallScope.mallName(服务端 buildScope 回显;存在即可渲染的 kit 同源约定)
79
+ const mallName = useChatStore((s) => s.helloAck?.mallScope?.mallName);
80
+ // chat settings 水合:HELLO_ACK 服务端真源 → 静态 store(ack 未达/键缺席保留构建期快照;
81
+ // 重连/新会话产生新 helloAck 再水合——applyServerSettings 幂等)
82
+ const serverSettings = useChatStore((s) => s.helloAck?.chatConfig?.settings);
83
+ const applyServerSettings = useChatConfigStore((s) => s.applyServerSettings);
84
+ useEffect(() => {
85
+ applyServerSettings(serverSettings);
86
+ }, [serverSettings, applyServerSettings]);
87
+
88
+ const slots = useClientSlots();
89
+ const homeSlot = slots?.resolve('home');
90
+
91
+ const [showScrollToBottom, setShowScrollToBottom] = useState(false);
92
+ const [voiceActive, setVoiceActive] = useState(false);
93
+ const bodyRef = useRef<HTMLDivElement>(null);
94
+ // 底部输入区(QuickCommands + ChatInput)高度测量:底部避让消费(如半屏 sheet)
95
+ const chatBottomRef = useRef<HTMLDivElement>(null);
96
+ // 历史前插视口锚:home 槽位占位(历史插入发生在其上,保持用户看到的位置)
97
+ const historyAnchorRef = useRef<HTMLDivElement>(null);
98
+ const historyLoadInFlightRef = useRef<Promise<void> | null>(null);
99
+ const pendingHistoryViewportRef = useRef<{ anchorTop: number } | null>(null);
100
+ const isAtTopRef = useRef(true);
101
+ const isNearBottomRef = useRef(true);
102
+
103
+ const startNewConversation = useCallback(() => {
104
+ void newConversation();
105
+ const el = bodyRef.current;
106
+ if (el) el.scrollTop = 0;
107
+ isAtTopRef.current = true;
108
+ isNearBottomRef.current = false;
109
+ setShowScrollToBottom(false);
110
+ }, [newConversation]);
111
+
112
+ const send = useCallback((input: string | ChatInputMessage) => {
113
+ // 主动发送代表用户要回到最新对话;待消息 DOM 提交后由下方 effect 落底。
114
+ // 生成中 store 会拒绝新消息,此时不改变用户正在查看的滚动位置。
115
+ if (isGenerating) return;
116
+ isNearBottomRef.current = true;
117
+ setShowScrollToBottom(false);
118
+ sendMessage(input);
119
+ }, [isGenerating, sendMessage]);
120
+
121
+ // 连接终态阻断(登录失败/scope 拒绝):禁用输入 + 提示条 + 重试。
122
+ // 门控仅 runtimeStatus=failed 或 authBlocked——bootstrapping 等过渡态不闪现横幅
123
+ const blocked =
124
+ runtimeStatus === 'failed' || authBlocked
125
+ ? {
126
+ message: authBlocked ?? '登录失败,暂时无法对话',
127
+ onRetry: () => void retryBootstrap(true),
128
+ }
129
+ : undefined;
130
+
131
+ const scrollToBottom = useCallback(() => {
132
+ const el = bodyRef.current;
133
+ if (el) el.scrollTop = el.scrollHeight;
134
+ isNearBottomRef.current = true;
135
+ setShowScrollToBottom(false);
136
+ }, []);
137
+
138
+ const NEAR_BOTTOM = 150;
139
+ const onScroll = useCallback(() => {
140
+ const el = bodyRef.current;
141
+ if (!el) return;
142
+ isAtTopRef.current = el.scrollTop <= 5;
143
+ const distanceToBottom = el.scrollHeight - el.scrollTop - el.clientHeight;
144
+ isNearBottomRef.current = distanceToBottom < NEAR_BOTTOM;
145
+ setShowScrollToBottom(!isNearBottomRef.current);
146
+ }, []);
147
+
148
+ // 顶部入口与轻量下拉共用同一加载任务;同一周期复用 Promise,避免点击/手势重复请求。
149
+ const onLoadHistory = useCallback(() => {
150
+ if (historyLoadInFlightRef.current) return historyLoadInFlightRef.current;
151
+ const anchor = historyAnchorRef.current;
152
+ if (anchor) {
153
+ pendingHistoryViewportRef.current = {
154
+ anchorTop: anchor.getBoundingClientRect().top,
155
+ };
156
+ }
157
+ const task = loadMoreHistory().finally(() => {
158
+ if (historyLoadInFlightRef.current === task) historyLoadInFlightRef.current = null;
159
+ });
160
+ historyLoadInFlightRef.current = task;
161
+ return task;
162
+ }, [loadMoreHistory]);
163
+
164
+ // 历史插入发生在当前内容上方:绘制前只补一次新增高度,保持用户原本看到的位置。
165
+ // 不设置定时器、不钉住 scrollTop;补偿后下一次滚动立即由用户接管。
166
+ useLayoutEffect(() => {
167
+ const pending = pendingHistoryViewportRef.current;
168
+ const anchor = historyAnchorRef.current;
169
+ if (!pending || !anchor) return;
170
+ pendingHistoryViewportRef.current = null;
171
+ const anchorDelta = anchor.getBoundingClientRect().top - pending.anchorTop;
172
+ if (Math.abs(anchorDelta) > 0.5) {
173
+ const el = bodyRef.current;
174
+ if (el) el.scrollTop += anchorDelta;
175
+ }
176
+ }, [historyMessages]);
177
+
178
+ const filterInlineCards = useInlineCardFilter();
179
+ const inlineOrphanCards = useMemo(
180
+ () => filterInlineCards(orphanCards),
181
+ [orphanCards, filterInlineCards],
182
+ );
183
+
184
+ // 是否仍为空会话(home-first 形态判定);home 槽缺席时始终为对话形态
185
+ const showHome = !!homeSlot
186
+ && historyMessages.length === 0
187
+ && messages.length === 0
188
+ && inlineOrphanCards.length === 0;
189
+
190
+ const liveCardSignature = useMemo(
191
+ () => messages
192
+ .map((message) => `${message.id}:${(cardsByMessageId[message.id] ?? []).map((card) => card.id).join(',')}`)
193
+ .join('|'),
194
+ [messages, cardsByMessageId],
195
+ );
196
+
197
+ const showHistoryEntry = historyHasMore && historyMessages.length === 0;
198
+
199
+ const pull = usePullDownHistory({
200
+ isAtTopRef,
201
+ isLoadingHistory,
202
+ hasMore: historyHasMore,
203
+ onLoad: onLoadHistory,
204
+ disabled: runtimeStatus !== 'ready',
205
+ });
206
+
207
+ useEffect(() => {
208
+ // 深链自动发送:同步消费(StrictMode 双挂载/刷新安全),引导完成后等连接就绪发送
209
+ const autoQuery = consumeAutoSendQuery();
210
+ void initConversation().then(async () => {
211
+ if (autoQuery) await runAutoSend(autoQuery, sendMessage);
212
+ });
213
+ return () => {
214
+ destroy();
215
+ };
216
+ // eslint-disable-next-line react-hooks/exhaustive-deps
217
+ }, []);
218
+
219
+ // 底部输入区高度 → CSS 变量 --tbox-chat-bottom-height,供半屏 sheet(portal 到 body)避让消费。
220
+ useEffect(() => {
221
+ const el = chatBottomRef.current;
222
+ if (!el) return;
223
+ const update = () =>
224
+ document.documentElement.style.setProperty('--tbox-chat-bottom-height', `${el.offsetHeight}px`);
225
+ update();
226
+ const ro = new ResizeObserver(update);
227
+ ro.observe(el);
228
+ return () => ro.disconnect();
229
+ }, []);
230
+
231
+ // 仅在已有对话内容且贴近底部时自动滚动,避免打断用户上翻查看历史。
232
+ // 依赖含 cardsByMessageId:主卡在文字完成后挂载、消息行增高,需补滚避免卡片截出视口
233
+ useEffect(() => {
234
+ const hasLiveContent = messages.length > 0 || orphanCards.length > 0;
235
+ if (hasLiveContent && isNearBottomRef.current) {
236
+ const el = bodyRef.current;
237
+ if (el) el.scrollTop = el.scrollHeight;
238
+ }
239
+ }, [messages, orphanCards, liveCardSignature]);
240
+
241
+ return (
242
+ <div className={`chat-page${showHome ? '' : ' chat-page--conversation'}`}>
243
+ <div className="chat-page__bg" />
244
+
245
+ <div className="chat-page__body-wrapper">
246
+ <div
247
+ className="chat-page__body"
248
+ ref={bodyRef}
249
+ onScroll={onScroll}
250
+ onWheel={pull.handleWheel}
251
+ onTouchStart={pull.handleTouchStart}
252
+ onTouchMove={pull.handleTouchMove}
253
+ onTouchEnd={pull.handleTouchEnd}
254
+ onTouchCancel={pull.handleTouchCancel}
255
+ >
256
+ <HistoryEntry
257
+ visible={showHistoryEntry}
258
+ loading={isLoadingHistory}
259
+ disabled={runtimeStatus !== 'ready' || isLoadingHistory}
260
+ pullStatus={pull.pullStatus}
261
+ onLoad={() => void onLoadHistory()}
262
+ />
263
+
264
+ <div className="chat-page__history">
265
+ {historyMessages.map((msg) => (
266
+ <MessageBubble key={msg.id} message={msg} />
267
+ ))}
268
+ </div>
269
+
270
+ {/* 历史前插视口锚 + home 槽渲染位(域自持显隐;缺席则不渲染) */}
271
+ <div className="chat-page__home-slot" ref={historyAnchorRef}>
272
+ {homeSlot?.({ onSend: send, ...(mallName ? { mallName } : {}) })}
273
+ </div>
274
+
275
+ {/* 业务旁路 emit 的卡片(如欢迎卡) */}
276
+ {inlineOrphanCards.map((card) => (
277
+ <div key={card.id} className="chat-page__orphan-card">
278
+ <CardRenderer card={card} />
279
+ </div>
280
+ ))}
281
+
282
+ {/* 消息(每条消息下的卡片由 MessageBubble 内部渲染) */}
283
+ {messages.map((msg) => (
284
+ <MessageBubble key={msg.id} message={msg} />
285
+ ))}
286
+ </div>
287
+
288
+ <ScrollToBottomButton visible={showScrollToBottom} onClick={scrollToBottom} />
289
+ </div>
290
+
291
+ {/* 首页与对话态都保留快捷指令;语音活跃时只隐去胶囊并保留灰底占位,阻断时才卸载。 */}
292
+ <div ref={chatBottomRef}>
293
+ {!blocked && <QuickCommands hidden={voiceActive} onCommand={send} />}
294
+ <ChatInput
295
+ generating={isGenerating}
296
+ blocked={blocked}
297
+ onSend={send}
298
+ onCancel={cancelGeneration}
299
+ onNewChat={startNewConversation}
300
+ onVoiceActivityChange={setVoiceActive}
301
+ />
302
+ </div>
303
+ </div>
304
+ );
305
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * chat-config store 水合 action(chat settings 服务端下发真源):
3
+ * applyServerSettings 五键整组语义——undefined 键保留构建期快照,禁部分水合。
4
+ */
5
+ import { describe, it, expect, beforeEach } from 'vitest';
6
+ import { configureChatConfigDefaults, useChatConfigStore } from './chat-config';
7
+
8
+ const snapshot = () => useChatConfigStore.getState();
9
+
10
+ describe('applyServerSettings:HELLO_ACK settings 水合', () => {
11
+ beforeEach(() => {
12
+ // 重置回构建期快照(快照值来自模板 config/chat.json 静态 import)
13
+ useChatConfigStore.setState({
14
+ enableImageUpload: true,
15
+ enableVideoUpload: true,
16
+ enableTTS: true,
17
+ enableVoiceInput: true,
18
+ defaultInputMode: 'TEXT',
19
+ });
20
+ });
21
+
22
+ it('五键全覆盖 → 全部覆盖快照值', () => {
23
+ snapshot().applyServerSettings({
24
+ enableImageUpload: false,
25
+ enableVideoUpload: false,
26
+ enableTTS: false,
27
+ enableVoiceInput: false,
28
+ defaultInputMode: 'VOICE',
29
+ });
30
+ expect(snapshot().enableImageUpload).toBe(false);
31
+ expect(snapshot().enableVideoUpload).toBe(false);
32
+ expect(snapshot().enableTTS).toBe(false);
33
+ expect(snapshot().enableVoiceInput).toBe(false);
34
+ expect(snapshot().defaultInputMode).toBe('VOICE');
35
+ });
36
+
37
+ it('部分键(undefined 保留快照值——禁部分水合导致快照丢失)', () => {
38
+ snapshot().applyServerSettings({ enableTTS: false });
39
+ expect(snapshot().enableTTS).toBe(false);
40
+ expect(snapshot().enableImageUpload).toBe(true);
41
+ expect(snapshot().enableVideoUpload).toBe(true);
42
+ expect(snapshot().enableVoiceInput).toBe(true);
43
+ expect(snapshot().defaultInputMode).toBe('TEXT');
44
+ });
45
+
46
+ it('整包 undefined(旧 server / ack 未达)→ no-op 快照保留', () => {
47
+ snapshot().applyServerSettings(undefined);
48
+ expect(snapshot().enableImageUpload).toBe(true);
49
+ expect(snapshot().enableTTS).toBe(true);
50
+ expect(snapshot().defaultInputMode).toBe('TEXT');
51
+ });
52
+
53
+ it('同值幂等:两次 apply 后五键深等价(防第二次 apply 丢键/翻转)', () => {
54
+ const settings = { enableTTS: false, defaultInputMode: 'VOICE' as const };
55
+ snapshot().applyServerSettings(settings);
56
+ const after1 = snapshot();
57
+ snapshot().applyServerSettings(settings);
58
+ // toEqual 全状态深比较——单键 toBe 对原始值恒真,钉不住实现回归
59
+ expect(snapshot()).toEqual(after1);
60
+ expect(snapshot().enableTTS).toBe(false);
61
+ expect(snapshot().defaultInputMode).toBe('VOICE');
62
+ });
63
+ });
64
+
65
+ describe('configureChatConfigDefaults:构建期快照注入(W2-1 kit 化)', () => {
66
+ it('快照键覆盖内建缺省;缺席键保留;undefined no-op', () => {
67
+ configureChatConfigDefaults({
68
+ enableTTS: false,
69
+ quickCommands: [{ label: 'L', query: 'Q' }],
70
+ });
71
+ expect(snapshot().enableTTS).toBe(false);
72
+ expect(snapshot().quickCommands).toEqual([{ label: 'L', query: 'Q' }]);
73
+ // 缺席键保留
74
+ expect(snapshot().enableImageUpload).toBe(true);
75
+
76
+ configureChatConfigDefaults(undefined);
77
+ expect(snapshot().enableTTS).toBe(false); // no-op:不因 undefined 回翻
78
+
79
+ // 复位(防污染后续用例)
80
+ useChatConfigStore.setState({ enableTTS: true, quickCommands: [] });
81
+ });
82
+ });