@tbox.cn/app-agent-ui-kit 1.0.0-alpha.12 → 1.0.0-alpha.14

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 (35) hide show
  1. package/package.json +3 -3
  2. package/src/ChatPage.tsx +77 -151
  3. package/src/card/action-list-pending.test.tsx +96 -31
  4. package/src/card/primitives.test.tsx +20 -7
  5. package/src/card/primitives.tsx +54 -41
  6. package/src/card/use-card-actions.ts +23 -14
  7. package/src/card/view-card-inline.test.tsx +34 -2
  8. package/src/card/view-card.test.tsx +3 -3
  9. package/src/card/view-card.tsx +24 -29
  10. package/src/chat-config.test.ts +13 -8
  11. package/src/chat-config.ts +29 -8
  12. package/src/components/ChatInput/index.test.tsx +37 -0
  13. package/src/components/ChatInput/index.tsx +19 -6
  14. package/src/components/ChatInput/use-auto-rows.test.tsx +78 -0
  15. package/src/components/ChatInput/use-auto-rows.ts +68 -0
  16. package/src/components/HistoryEntry/index.tsx +3 -1
  17. package/src/components/HistoryList.tsx +52 -0
  18. package/src/components/MessageBubble/index.tsx +2 -3
  19. package/src/components/QuickCommands/index.test.tsx +25 -5
  20. package/src/components/QuickCommands/index.tsx +30 -27
  21. package/src/hooks/use-pull-down-history.ts +3 -4
  22. package/src/hooks/use-pull-down-wheel-native.test.ts +4 -8
  23. package/src/hooks/use-stick-to-bottom.test.tsx +142 -0
  24. package/src/hooks/use-stick-to-bottom.ts +218 -0
  25. package/src/index.ts +1 -2
  26. package/src/preview-provider.tsx +2 -1
  27. package/src/shell.contract.json +12 -13
  28. package/src/shell.test.ts +107 -11
  29. package/src/shell.ts +13 -10
  30. package/src/test/setup.ts +31 -0
  31. package/src/theme/base.css +5 -0
  32. package/src/theme/contract.json +1 -0
  33. package/src/theme/tokens.css +1 -0
  34. package/src/components/ChatHeader/index.test.tsx +0 -74
  35. package/src/components/ChatHeader/index.tsx +0 -77
@@ -280,7 +280,7 @@ const HERO_TONE = {
280
280
  warm: 'bg-linear-to-br from-warm to-card',
281
281
  jade: 'bg-linear-to-br from-jade to-card',
282
282
  // 深色底:只用契约里的令牌(primary-dark / primary-light),不引入字面量色值。
283
- inverse: 'bg-primary-dark text-primary-foreground [&_.tbox-hero__eyebrow]:text-primary-foreground [&_.tbox-hero__footnote]:text-primary-foreground [&_.tbox-hero__value_small]:text-primary-foreground',
283
+ inverse: String.raw`bg-primary-dark text-primary-foreground [&_.tbox-hero\_\_eyebrow]:text-primary-foreground [&_.tbox-hero\_\_footnote]:text-primary-foreground [&_.tbox-hero\_\_value_small]:text-primary-foreground`,
284
284
  neutral: 'bg-muted',
285
285
  } as const;
286
286
 
@@ -594,53 +594,66 @@ export interface CardActionSpec {
594
594
  *
595
595
  * @behavior 首个动作为整行主按钮,其余并排一行;confirm 走挂到 body 的 ConfirmSheet;disabled 自动接 api.disabled。
596
596
  */
597
- const PENDING_TIMEOUT_MS = 20000;
597
+ /**
598
+ * 挂起键:动作 id + 入参的稳定哈希。
599
+ * 按序号记录会在卡片原地刷新后落到新卡的第一个按钮上(用户点的是 A,转圈的是 B)。
600
+ */
601
+ function actionKeyOf(spec: CardActionSpec, index: number): string {
602
+ const send = spec.send;
603
+ const id = spec.invoke?.id
604
+ ?? (typeof send === 'string' ? send : send?.text)
605
+ ?? String(index);
606
+ const input = spec.invoke?.input;
607
+ return input ? id + ':' + stableHash(JSON.stringify(input)) : id;
608
+ }
609
+
610
+ function stableHash(text: string): string {
611
+ let hash = 0;
612
+ for (let i = 0; i < text.length; i += 1) {
613
+ hash = (hash * 31 + text.charCodeAt(i)) | 0;
614
+ }
615
+ return (hash >>> 0).toString(36);
616
+ }
598
617
 
599
618
  export function ActionList({ actions, api }: { actions: CardActionSpec[]; api: CardActions }) {
600
619
  const [confirmIndex, setConfirmIndex] = useState<number | null>(null);
601
- const [running, setRunning] = useState<number | null>(null);
620
+ const [running, setRunning] = useState<string | null>(null);
602
621
  // 单飞用 ref 同步判重:state 要等重渲染,连点两下会都通过。
603
- const runningRef = useRef<number | null>(null);
604
- const wasGenerating = useRef(false);
622
+ const runningRef = useRef<string | null>(null);
623
+ /** 挂起令牌:await 回来时若组件已换了一轮动作,不再改状态 */
624
+ const tokenRef = useRef<symbol | null>(null);
625
+ const mountedRef = useRef(true);
605
626
 
606
- // 兜底解除:没有回执(方案 A 不改协议)时,按钮不能永远转圈。
627
+ // effect 体必须把 ref 置回 true:StrictMode 下是 mount → cleanup → mount,
628
+ // 只在 cleanup 里置 false 会让首次挂载后永久为 false(按钮再也不解锁)。
607
629
  useEffect(() => {
608
- if (running === null) return undefined;
609
- const timer = setTimeout(() => {
610
- runningRef.current = null;
611
- setRunning(null);
612
- }, PENDING_TIMEOUT_MS);
613
- return () => clearTimeout(timer);
614
- }, [running]);
615
-
616
- // 生成态从 true 回到 false = 这一轮有结果,解除 pending。
617
- // 无论点击发生在生成前还是生成后,标记都要在当前这一轮结束时复位。
618
- useEffect(() => {
619
- if (api.isGenerating) {
620
- wasGenerating.current = true;
621
- return;
622
- }
623
- if (!wasGenerating.current) return;
624
- wasGenerating.current = false;
625
- if (runningRef.current !== null) {
626
- runningRef.current = null;
627
- setRunning(null);
628
- }
629
- }, [api.isGenerating]);
630
+ mountedRef.current = true;
631
+ return () => { mountedRef.current = false; };
632
+ }, []);
630
633
 
631
634
  const run = (spec: CardActionSpec, index: number) => {
632
635
  // 没有 send / invoke 的动作不进入 pending,否则只会空转。
633
636
  if (!spec.invoke && !spec.send) return;
634
- runningRef.current = index;
635
- setRunning(index);
636
- if (spec.invoke) {
637
- api.invoke(spec.invoke.id, spec.invoke.input);
638
- return;
639
- }
640
- if (spec.send) {
641
- if (typeof spec.send === 'string') api.send(spec.send);
642
- else api.send(spec.send.text, { displayText: spec.send.displayText });
643
- }
637
+ const key = actionKeyOf(spec, index);
638
+ const token = Symbol(key);
639
+ runningRef.current = key;
640
+ tokenRef.current = token;
641
+ setRunning(key);
642
+ const promise = spec.invoke
643
+ ? api.invoke(spec.invoke.id, spec.invoke.input)
644
+ : typeof spec.send === 'string'
645
+ ? api.send(spec.send)
646
+ : api.send(spec.send!.text, { displayText: spec.send!.displayText });
647
+ // 结束信号到达即解锁;组件已卸载或已开启下一轮时不改状态。
648
+ // 用 then(clear, clear) 而不是 finally:公开类型 CardActions 允许实现方 reject,
649
+ // finally 会把拒绝原样透传成 unhandledrejection(控制台报错 + 踩 console-clean)。
650
+ const clear = () => {
651
+ if (!mountedRef.current) return;
652
+ if (tokenRef.current !== token) return;
653
+ runningRef.current = null;
654
+ setRunning(null);
655
+ };
656
+ void promise.then(clear, clear);
644
657
  };
645
658
  const trigger = (spec: CardActionSpec, index: number) => {
646
659
  if (api.disabled || runningRef.current !== null || confirmIndex !== null) return;
@@ -654,7 +667,7 @@ export function ActionList({ actions, api }: { actions: CardActionSpec[]; api: C
654
667
  const busy = api.disabled || running !== null || confirmIndex !== null;
655
668
  const label = (text: string, index: number) => (
656
669
  <span className="inline-flex items-center gap-2">
657
- {running === index ? (
670
+ {running === actionKeyOf(actions[index]!, index) ? (
658
671
  <span
659
672
  className="tbox-btn__spinner inline-block size-4 animate-spin rounded-full border-2 border-current border-t-transparent"
660
673
  aria-hidden="true"
@@ -670,7 +683,7 @@ export function ActionList({ actions, api }: { actions: CardActionSpec[]; api: C
670
683
  <CardButton
671
684
  variant={actions[0].style ?? 'primary'}
672
685
  disabled={busy}
673
- busy={running === 0}
686
+ busy={running === actionKeyOf(actions[0], 0)}
674
687
  onClick={() => trigger(actions[0], 0)}
675
688
  >
676
689
  {label(actions[0].label, 0)}
@@ -685,7 +698,7 @@ export function ActionList({ actions, api }: { actions: CardActionSpec[]; api: C
685
698
  <CardButton
686
699
  variant={spec.style ?? 'secondary'}
687
700
  disabled={busy}
688
- busy={running === actionIndex}
701
+ busy={running === actionKeyOf(spec, actionIndex)}
689
702
  onClick={() => trigger(spec, actionIndex)}
690
703
  >
691
704
  {label(spec.label, actionIndex)}
@@ -5,11 +5,13 @@
5
5
  * - `invoke`:触发卡片上声明的确定性动作(moduleAction),不过模型;
6
6
  * - `disabled`:历史卡片与生成中一律禁用,两者文案不同——历史卡只读,生成中提示等待。
7
7
  *
8
- * 门控与 toast 文案集中在实现处;卡片组件只消费 `disabled` 与两个动作函数。
8
+ * 两个动作都返回 **动作结局的 Promise**:按钮据此解除挂起态,不再靠超时兜底。
9
+ * 门控拒绝(历史卡 / 生成中 / 无令牌)当场返回 rejected,按钮立即恢复。
9
10
  */
10
11
  import { useCallback } from 'react';
11
12
  import { toast } from '../utils/toast';
12
13
  import { useChatStore } from '../store-context';
14
+ import type { ActionOutcome, UiActionDispatch } from '@tbox.cn/app-agent-sdk-client';
13
15
 
14
16
  export interface UseCardActionsOptions {
15
17
  /** 卡片实例 id(协议字段名 surfaceId 的历史别名) */
@@ -22,19 +24,24 @@ export interface UseCardActionsOptions {
22
24
 
23
25
  export interface CardActions {
24
26
  /** 发一句话给模型;`displayText` 是气泡展示文本,缺省同 `text` */
25
- send(text: string, opts?: { displayText?: string }): void;
27
+ send(text: string, opts?: { displayText?: string }): Promise<ActionOutcome>;
26
28
  /**
27
29
  * 触发卡片上的确定性动作(需该动作已签发令牌)。
28
30
  * `input` 作为该次调用的入参(UI_ACTION 的 formData 通道),由服务端 `inputSchema` 校验;
29
31
  * 不传时按空对象校验——无参动作写 `z.object({})`。
30
32
  */
31
- invoke(actionId: string, input?: Record<string, unknown>): void;
33
+ invoke(actionId: string, input?: Record<string, unknown>): Promise<ActionOutcome>;
32
34
  /** 历史卡或生成中为 true——按钮应据此置灰 */
33
35
  disabled: boolean;
34
36
  isHistory: boolean;
35
37
  isGenerating: boolean;
36
38
  }
37
39
 
40
+ /** 派发结果 → 结局 Promise:已上行等结算,本地动作或被拒当场兑现。 */
41
+ export function toOutcome(dispatch: UiActionDispatch): Promise<ActionOutcome> {
42
+ return dispatch.status === 'sent' ? dispatch.settled : Promise.resolve(dispatch);
43
+ }
44
+
38
45
  export function useCardActions(opts: UseCardActionsOptions): CardActions {
39
46
  const sendUiAction = useChatStore((s) => s.sendUiAction);
40
47
  const isGenerating = useChatStore((s) => s.isGenerating);
@@ -42,42 +49,44 @@ export function useCardActions(opts: UseCardActionsOptions): CardActions {
42
49
  const disabled = isHistory || isGenerating;
43
50
 
44
51
  const send = useCallback(
45
- (text: string, o?: { displayText?: string }) => {
46
- if (!text) return;
52
+ (text: string, o?: { displayText?: string }): Promise<ActionOutcome> => {
53
+ if (!text) return Promise.resolve({ status: 'rejected', reason: 'no-token' });
47
54
  if (isHistory) {
48
55
  void toast('历史卡片仅供查看', 'info');
49
- return;
56
+ return Promise.resolve({ status: 'rejected', reason: 'history' });
50
57
  }
51
58
  if (isGenerating) {
52
59
  void toast('正在处理上一条消息,请稍候', 'info');
53
- return;
60
+ return Promise.resolve({ status: 'rejected', reason: 'generating' });
54
61
  }
55
- sendUiAction(opts.cardId, {
62
+ return toOutcome(sendUiAction(opts.cardId, {
56
63
  type: 'sendMessage',
57
64
  value: text,
58
65
  displayText: o?.displayText ?? text,
59
66
  visible: true,
60
- });
67
+ }));
61
68
  },
62
69
  [opts.cardId, isHistory, isGenerating, sendUiAction],
63
70
  );
64
71
 
65
72
  const invoke = useCallback(
66
- (actionId: string, input?: Record<string, unknown>) => {
73
+ (actionId: string, input?: Record<string, unknown>): Promise<ActionOutcome> => {
67
74
  if (isHistory) {
68
75
  void toast('历史卡片仅供查看', 'info');
69
- return;
76
+ return Promise.resolve({ status: 'rejected', reason: 'history' });
70
77
  }
71
78
  if (isGenerating) {
72
79
  void toast('正在处理上一条消息,请稍候', 'info');
73
- return;
80
+ return Promise.resolve({ status: 'rejected', reason: 'generating' });
74
81
  }
75
82
  const contextToken = opts.actionTokens?.[actionId];
76
83
  if (!contextToken) {
77
84
  void toast('该操作不可用', 'info');
78
- return;
85
+ return Promise.resolve({ status: 'rejected', reason: 'no-token' });
79
86
  }
80
- sendUiAction(opts.cardId, { type: 'moduleAction', actionId, contextToken }, input);
87
+ return toOutcome(
88
+ sendUiAction(opts.cardId, { type: 'moduleAction', actionId, contextToken }, input),
89
+ );
81
90
  },
82
91
  [opts.cardId, opts.actionTokens, isHistory, isGenerating, sendUiAction],
83
92
  );
@@ -26,8 +26,19 @@ afterEach(async () => {
26
26
  });
27
27
 
28
28
  describe('ViewCard 列表内联动作', () => {
29
- it('点击后进入单飞状态,按钮禁用', async () => {
29
+ it('派发后进入单飞状态(禁用),结算到达即恢复', async () => {
30
30
  const harness = createSurfaceHarness({});
31
+ // 受控结算:预览 store 的动作在派发后保持挂起,直到测试手动兑现
32
+ let release: (() => void) | undefined;
33
+ harness.store.setState({
34
+ sendUiAction: () => ({
35
+ status: 'sent',
36
+ requestId: 'r1',
37
+ settled: new Promise((resolve) => {
38
+ release = () => resolve({ status: 'settled', outcome: 'updated' });
39
+ }),
40
+ }),
41
+ } as never);
31
42
  const el = document.createElement('div');
32
43
  document.body.appendChild(el);
33
44
  const root = createRoot(el);
@@ -37,6 +48,27 @@ describe('ViewCard 列表内联动作', () => {
37
48
  await act(async () => {
38
49
  button.click();
39
50
  });
40
- expect(el.querySelector('button')!.disabled).toBe(true);
51
+ // 挂起中:按钮禁用
52
+ expect(button.disabled).toBe(true);
53
+ // 结算到达:立即恢复(不等 20 秒兜底)
54
+ await act(async () => {
55
+ release?.();
56
+ });
57
+ const after = [...el.querySelectorAll('button')].find((item) => item.textContent?.includes('报名'))!;
58
+ expect(after.disabled).toBe(false);
59
+ });
60
+
61
+ it('预览没有服务端时动作被拒,按钮不进入挂起', async () => {
62
+ const harness = createSurfaceHarness({});
63
+ const el = document.createElement('div');
64
+ document.body.appendChild(el);
65
+ const root = createRoot(el);
66
+ roots.push(root);
67
+ act(() => root.render(harness.wrap(<ViewCard view={view} cardId="c1" actionTokens={{ register: 'token' }} />)));
68
+ const button = [...el.querySelectorAll('button')].find((item) => item.textContent?.includes('报名'))!;
69
+ await act(async () => {
70
+ button.click();
71
+ });
72
+ expect(button.disabled).toBe(false);
41
73
  });
42
74
  });
@@ -8,12 +8,12 @@ import { ViewCard } from './view-card';
8
8
  const parking: CardView = {
9
9
  header: { title: '停车订单', eyebrow: 'PARKING', status: { text: '待支付', tone: 'warning' } },
10
10
  blocks: [
11
- { kind: 'facts', items: [['车牌', '浙A·12345'], ['停车时长', '2 小时 20 分钟']] },
11
+ { kind: 'facts', items: [['车牌', '京A·00000'], ['停车时长', '2 小时 20 分钟']] },
12
12
  { kind: 'bill', lines: [['停车费', '¥15'], ['停车券', '-¥10', true]], total: ['应付', '¥5'] },
13
13
  { kind: 'notice', text: '已为你选好停车券', tone: 'info' },
14
14
  ],
15
15
  actions: [
16
- { label: '确认支付 ¥5', invoke: { id: 'pay-parking', input: { plate: '浙A·12345' } }, confirm: { title: '确认支付?' } },
16
+ { label: '确认支付 ¥5', invoke: { id: 'pay-parking', input: { plate: '京A·00000' } }, confirm: { title: '确认支付?' } },
17
17
  { label: '用积分换停车券', send: '用积分兑换停车券' },
18
18
  ],
19
19
  };
@@ -40,7 +40,7 @@ describe('ViewCard', () => {
40
40
  it('积木与动作渲染一次,标题/明细/提示都在', () => {
41
41
  const html = render(parking);
42
42
  expect(html).toContain('停车订单');
43
- expect(html).toContain('浙A·12345');
43
+ expect(html).toContain('京A·00000');
44
44
  expect(html).toContain('应付');
45
45
  expect(html).toContain('已为你选好停车券');
46
46
  expect(html.match(/确认支付 ¥5/g)?.length).toBe(1);
@@ -40,44 +40,39 @@ function toSpec(action: CardViewAction): CardActionSpec {
40
40
  };
41
41
  }
42
42
 
43
- /** 列表项内联动作:与卡级动作共用确认弹层语义,但不占整行。 */
43
+ /** 列表项内联动作:与卡级动作共用确认弹层语义与结算语义,但不占整行。 */
44
44
  function useInlineRunner(api: Api) {
45
45
  const [pending, setPending] = useState<CardViewAction | null>(null);
46
46
  const [running, setRunning] = useState(false);
47
47
  const runningRef = useRef(false);
48
- const wasGenerating = useRef(false);
48
+ /** 挂起令牌:动作结束信号到达时若已换轮次,不再改状态 */
49
+ const tokenRef = useRef<symbol | null>(null);
50
+ const mountedRef = useRef(true);
51
+ // StrictMode 双挂载:effect 体置回 true,否则 cleanup 之后永久 false(按钮不再解锁)
49
52
  useEffect(() => {
50
- if (!running) return undefined;
51
- const timer = setTimeout(() => {
52
- runningRef.current = false;
53
- setRunning(false);
54
- }, 20000);
55
- return () => clearTimeout(timer);
56
- }, [running]);
57
- useEffect(() => {
58
- if (api.isGenerating) {
59
- wasGenerating.current = true;
60
- return;
61
- }
62
- if (!wasGenerating.current) return;
63
- wasGenerating.current = false;
64
- if (runningRef.current) {
65
- runningRef.current = false;
66
- setRunning(false);
67
- }
68
- }, [api.isGenerating]);
53
+ mountedRef.current = true;
54
+ return () => { mountedRef.current = false; };
55
+ }, []);
56
+
69
57
  const run = (action: CardViewAction) => {
70
58
  if (!action.invoke && !action.send) return;
59
+ const token = Symbol('inline');
71
60
  runningRef.current = true;
61
+ tokenRef.current = token;
72
62
  setRunning(true);
73
- if (action.invoke) {
74
- api.invoke(action.invoke.id, action.invoke.input);
75
- return;
76
- }
77
- if (action.send) {
78
- if (typeof action.send === 'string') api.send(action.send);
79
- else api.send(action.send.text, { displayText: action.send.displayText });
80
- }
63
+ const promise = action.invoke
64
+ ? api.invoke(action.invoke.id, action.invoke.input)
65
+ : typeof action.send === 'string'
66
+ ? api.send(action.send)
67
+ : api.send(action.send!.text, { displayText: action.send!.displayText });
68
+ // 结束信号到达即解锁(不再等 20 秒兜底);then(clear, clear) 吸收实现方的 reject
69
+ const clear = () => {
70
+ if (!mountedRef.current) return;
71
+ if (tokenRef.current !== token) return;
72
+ runningRef.current = false;
73
+ setRunning(false);
74
+ };
75
+ void promise.then(clear, clear);
81
76
  };
82
77
  const trigger = (action: CardViewAction) => {
83
78
  if (api.disabled || runningRef.current || pending !== null) return;
@@ -11,36 +11,41 @@ const reset = () => {
11
11
  quickCommands: [],
12
12
  retryOnError: true,
13
13
  });
14
- useChatConfigStore.setState({ identity: undefined, welcome: undefined });
14
+ useChatConfigStore.setState({ welcome: undefined });
15
15
  };
16
16
 
17
17
  describe('chat 设置的构建期快照', () => {
18
- it('identity / welcome / retryOnError 随快照注入', () => {
18
+ it('welcome / retryOnError 随快照注入', () => {
19
19
  reset();
20
20
  configureChatConfigDefaults({
21
- identity: { name: '悦享里', tagline: '商圈智能助手' },
22
21
  welcome: { title: '今天想逛点什么?', subtitle: '会员、停车、优惠都能问我' },
23
22
  retryOnError: false,
24
23
  });
25
24
  const state = useChatConfigStore.getState();
26
- expect(state.identity?.name).toBe('悦享里');
27
25
  expect(state.welcome?.title).toBe('今天想逛点什么?');
28
26
  expect(state.retryOnError).toBe(false);
29
27
  });
30
28
 
31
- it('缺省 retryOnError 为 true,identity 缺省不渲染', () => {
29
+ it('缺省 retryOnError 为 true,welcome 缺省不渲染', () => {
32
30
  reset();
33
31
  const state = useChatConfigStore.getState();
34
32
  expect(state.retryOnError).toBe(true);
35
- expect(state.identity).toBeUndefined();
33
+ expect(state.welcome).toBeUndefined();
36
34
  });
37
35
 
38
36
  it('HELLO_ACK 水合不覆盖展示配置', () => {
39
37
  reset();
40
- configureChatConfigDefaults({ identity: { name: '悦享里' } });
38
+ configureChatConfigDefaults({ welcome: { title: '示例应用' } });
41
39
  useChatConfigStore.getState().applyServerSettings({ enableTTS: false } as never);
42
40
  const state = useChatConfigStore.getState();
43
41
  expect(state.enableTTS).toBe(false);
44
- expect(state.identity?.name).toBe('悦享里');
42
+ expect(state.welcome?.title).toBe('示例应用');
43
+ });
44
+
45
+ it('退役的 identity 键不再进入 store(存量 chat.json 带它也不报错)', () => {
46
+ reset();
47
+ configureChatConfigDefaults({ identity: { name: '示例应用', tagline: '商圈智能服务' } } as never);
48
+ const state = useChatConfigStore.getState() as unknown as Record<string, unknown>;
49
+ expect('identity' in state).toBe(false);
45
50
  });
46
51
  });
@@ -15,10 +15,7 @@ export interface QuickCommand {
15
15
  icon?: string;
16
16
  }
17
17
 
18
- export interface ChatIdentity {
19
- name: string;
20
- tagline?: string;
21
- }
18
+
22
19
 
23
20
  export interface ChatWelcome {
24
21
  title: string;
@@ -32,8 +29,11 @@ interface ChatConfigStore {
32
29
  enableVoiceInput: boolean;
33
30
  defaultInputMode: 'TEXT' | 'VOICE';
34
31
  quickCommands: QuickCommand[];
35
- /** 身份与欢迎区是构建期展示配置,不经 HELLO_ACK 水合 */
36
- identity?: ChatIdentity;
32
+ /** 空输入框占几行(chat.json input.minRows,出厂 1) */
33
+ inputMinRows: number;
34
+ /** 输入框自动长高的上限行数(chat.json input.maxRows) */
35
+ inputMaxRows: number;
36
+ /** 欢迎区是构建期展示配置,不经 HELLO_ACK 水合 */
37
37
  welcome?: ChatWelcome;
38
38
  retryOnError: boolean;
39
39
  /** HELLO_ACK settings 水合:服务端单一真源;undefined 键保留构建期快照(五键整组语义,禁部分水合) */
@@ -50,7 +50,8 @@ export const useChatConfigStore = create<ChatConfigStore>()((set) => ({
50
50
  enableVoiceInput: (ssrSnapshot['enableVoiceInput'] as boolean | undefined) ?? true,
51
51
  defaultInputMode: (ssrSnapshot['defaultInputMode'] as 'TEXT' | 'VOICE' | undefined) ?? 'TEXT',
52
52
  quickCommands: (ssrSnapshot['quickCommands'] as QuickCommand[] | undefined) ?? [],
53
- identity: ssrSnapshot['identity'] as ChatIdentity | undefined,
53
+ inputMinRows: 1,
54
+ inputMaxRows: 4,
54
55
  welcome: ssrSnapshot['welcome'] as ChatWelcome | undefined,
55
56
  retryOnError: true,
56
57
  applyServerSettings: (settings) =>
@@ -67,6 +68,25 @@ export const useChatConfigStore = create<ChatConfigStore>()((set) => ({
67
68
  * 构建期快照注入(应用 boot 时调用一次;createRoot 前调用保证首帧即快照值)。
68
69
  * 键缺席保留内建缺省;键在场以快照为准。
69
70
  */
71
+ /**
72
+ * 读 input.minRows / input.maxRows:缺省或非法值返回 undefined(保留内建缺省)。
73
+ * 上限与服务端 schema 同源(minRows 1..4 / maxRows 1..8):客户端先夹住,
74
+ * 免得出现「客户端渲染 5 行、服务端整份配置校验失败回退默认」的分叉。
75
+ */
76
+ const ROW_LIMITS: Record<'minRows' | 'maxRows', { min: number; max: number }> = {
77
+ minRows: { min: 1, max: 4 },
78
+ maxRows: { min: 1, max: 8 },
79
+ };
80
+
81
+ function readRows(input: unknown, key: 'minRows' | 'maxRows'): number | undefined {
82
+ if (typeof input !== 'object' || input === null) return undefined;
83
+ const value = (input as Record<string, unknown>)[key];
84
+ if (typeof value !== 'number' || !Number.isInteger(value)) return undefined;
85
+ const { min, max } = ROW_LIMITS[key];
86
+ if (value < min || value > max) return undefined;
87
+ return value;
88
+ }
89
+
70
90
  export function configureChatConfigDefaults(snapshot: Record<string, unknown> | undefined): void {
71
91
  if (!snapshot) return;
72
92
  useChatConfigStore.setState((cur) => ({
@@ -77,7 +97,8 @@ export function configureChatConfigDefaults(snapshot: Record<string, unknown> |
77
97
  defaultInputMode:
78
98
  (snapshot['defaultInputMode'] as 'TEXT' | 'VOICE' | undefined) ?? cur.defaultInputMode,
79
99
  quickCommands: (snapshot['quickCommands'] as QuickCommand[] | undefined) ?? cur.quickCommands,
80
- identity: (snapshot['identity'] as ChatIdentity | undefined) ?? cur.identity,
100
+ inputMinRows: readRows(snapshot['input'], 'minRows') ?? cur.inputMinRows,
101
+ inputMaxRows: readRows(snapshot['input'], 'maxRows') ?? cur.inputMaxRows,
81
102
  welcome: (snapshot['welcome'] as ChatWelcome | undefined) ?? cur.welcome,
82
103
  retryOnError: (snapshot['retryOnError'] as boolean | undefined) ?? cur.retryOnError,
83
104
  }));
@@ -154,3 +154,40 @@ describe('ChatInput 派生模式(服务端 defaultInputMode 水合)', () =>
154
154
  await act(async () => root.unmount());
155
155
  });
156
156
  });
157
+ describe('ChatInput 回车发送与输入法组词', () => {
158
+ it('组词中的回车是上屏,不发送;compositionend 之后的回车才发送', async () => {
159
+ const sent: string[] = [];
160
+ const container = document.createElement('div');
161
+ document.body.appendChild(container);
162
+ const root = createRoot(container);
163
+ await act(async () => {
164
+ root.render(<ChatInput onSend={(msg) => sent.push(typeof msg === 'string' ? msg : msg.text)} />);
165
+ });
166
+ const textarea = container.querySelector('textarea')!;
167
+ const setValue = async (value: string) => {
168
+ await act(async () => {
169
+ const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!;
170
+ setter.call(textarea, value);
171
+ textarea.dispatchEvent(new Event('input', { bubbles: true }));
172
+ });
173
+ };
174
+ await setValue('杭州');
175
+ // 组词中:compositionstart 之后的 Enter 不发送
176
+ await act(async () => {
177
+ textarea.dispatchEvent(new CompositionEvent('compositionstart', { bubbles: true }));
178
+ });
179
+ await act(async () => {
180
+ textarea.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true, keyCode: 229 } as KeyboardEventInit));
181
+ });
182
+ expect(sent).toEqual([]);
183
+ // 组词结束:回车发送
184
+ await act(async () => {
185
+ textarea.dispatchEvent(new CompositionEvent('compositionend', { bubbles: true }));
186
+ });
187
+ await act(async () => {
188
+ textarea.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }));
189
+ });
190
+ expect(sent).toEqual(['杭州']);
191
+ await act(async () => root.unmount());
192
+ });
193
+ });
@@ -1,4 +1,5 @@
1
1
  import { useEffect, useRef, useState } from 'react';
2
+ import { useAutoRows } from './use-auto-rows';
2
3
  import { useMediaUpload } from '../../hooks/useMediaUpload';
3
4
  import { useASRAdapter, isInAlipayShell } from '@tbox.cn/app-agent-sdk-client';
4
5
  import { useChatConfigStore } from '../../chat-config';
@@ -49,6 +50,7 @@ const MEDIA_MAX_TOTAL = 9;
49
50
 
50
51
  /** 对话输入框(对齐原模板):媒体预览 + 新对话 + 药丸[输入框/按住说话 + 语音切换 + 发送/“+”] + 动画选取菜单 + 免责声明。 */
51
52
  export function ChatInput({
53
+ compact = false,
52
54
  generating,
53
55
  blocked,
54
56
  onSend,
@@ -57,6 +59,7 @@ export function ChatInput({
57
59
  onVoiceActivityChange,
58
60
  disclaimer = '以上内容由AI生成,请谨慎甄别。',
59
61
  }: {
62
+ compact?: boolean;
60
63
  generating?: boolean;
61
64
  blocked?: ChatBlocked;
62
65
  onSend: (msg: ChatInputMessage) => void;
@@ -66,6 +69,9 @@ export function ChatInput({
66
69
  disclaimer?: string;
67
70
  }) {
68
71
  const [text, setText] = useState('');
72
+ const textareaRef = useRef<HTMLTextAreaElement>(null);
73
+ /** 输入法组词中:Enter 是上屏而非发送 */
74
+ const composingRef = useRef(false);
69
75
  const imageRef = useRef<HTMLInputElement>(null);
70
76
  const cameraRef = useRef<HTMLInputElement>(null);
71
77
  const videoRef = useRef<HTMLInputElement>(null);
@@ -80,6 +86,9 @@ export function ChatInput({
80
86
  const enableVideo = useChatConfigStore((s) => s.enableVideoUpload);
81
87
  const enableVoice = useChatConfigStore((s) => s.enableVoiceInput);
82
88
  const defaultInputMode = useChatConfigStore((s) => s.defaultInputMode);
89
+ const minRows = useChatConfigStore((s) => s.inputMinRows);
90
+ const maxRows = useChatConfigStore((s) => s.inputMaxRows);
91
+ useAutoRows(textareaRef, text, { minRows, maxRows });
83
92
  // 派生模式(禁 useState 捕获初值——水合晚到时服务端 defaultInputMode 进不了已捕获 state):
84
93
  // userMode=null 跟随默认(随水合重渲染更新);显式值 = 用户手动切换优先
85
94
  const [userMode, setUserMode] = useState<'text' | 'voice' | null>(null);
@@ -195,7 +204,7 @@ export function ChatInput({
195
204
  </button>
196
205
  )}
197
206
 
198
- <div className="tbox-chat-input__wrapper flex min-w-0 flex-1 items-end gap-[14px] rounded-[var(--tbox-input-radius)] border border-border bg-[var(--tbox-input-bg)] p-[var(--tbox-input-padding)] shadow-[0_1px_10px_rgba(110,139,180,0.24)] transition-[border-color,box-shadow] duration-[var(--tbox-motion-duration-fast)] ease-[var(--tbox-motion-easing-standard)] focus-within:border-primary focus-within:shadow-[0_0_0_1.5px_rgba(9,107,250,0.12)]">
207
+ <div className={`tbox-chat-input__wrapper flex min-w-0 flex-1 gap-[14px] rounded-[var(--tbox-input-radius)] border border-border bg-[var(--tbox-input-bg)] p-[var(--tbox-input-padding)] shadow-[0_1px_10px_rgba(110,139,180,0.24)] transition-[border-color,box-shadow] duration-[var(--tbox-motion-duration-fast)] ease-[var(--tbox-motion-easing-standard)] focus-within:border-primary focus-within:shadow-[0_0_0_1.5px_rgba(9,107,250,0.12)] ${compact ? 'min-h-6 items-center' : 'min-h-11 items-end'}`}>
199
208
  <input ref={imageRef} type="file" accept="image/*" multiple hidden onChange={onPickFiles} />
200
209
  <input ref={cameraRef} type="file" accept="image/*" capture="environment" hidden onChange={onPickFiles} />
201
210
  <input ref={videoRef} type="file" accept="video/*" hidden onChange={onPickFiles} />
@@ -208,17 +217,21 @@ export function ChatInput({
208
217
  />
209
218
  ) : (
210
219
  <textarea
211
- className="tbox-chat-input__field min-h-11 min-w-0 flex-1 resize-none border-0 bg-transparent p-0 text-base leading-[24px] text-foreground outline-none max-h-[100px] [font-family:inherit] placeholder:text-muted-foreground disabled:opacity-[0.45]"
220
+ ref={textareaRef}
221
+ className={`tbox-chat-input__field min-w-0 flex-1 resize-none border-0 bg-transparent p-0 text-base leading-[24px] text-foreground outline-none [font-family:inherit] placeholder:text-muted-foreground disabled:opacity-[0.45] ${compact ? 'h-6' : ''}`}
212
222
  value={text}
213
223
  placeholder={blocked?.message ?? '有什么需要问我的吗'}
214
224
  rows={1}
215
225
  disabled={!!blocked}
216
226
  onChange={(e) => setText(e.target.value)}
227
+ onCompositionStart={() => { composingRef.current = true; }}
228
+ onCompositionEnd={() => { composingRef.current = false; }}
217
229
  onKeyDown={(e) => {
218
- if (e.key === 'Enter' && !e.shiftKey) {
219
- e.preventDefault();
220
- submit();
221
- }
230
+ // 输入法组词中的 Enter 是「上屏」,不是发送(部分 WebView 不带 isComposing)
231
+ if (e.key !== 'Enter' || e.shiftKey) return;
232
+ if (composingRef.current || e.nativeEvent.isComposing || e.keyCode === 229) return;
233
+ e.preventDefault();
234
+ submit();
222
235
  }}
223
236
  />
224
237
  )}