代码提交

This commit is contained in:
董宏凯 committed 2026-07-24 10:33:28 +08:00
1 parent f49def09ea
commit 45df500a9c
55 files changed
+3390 -461

No files matched your search

@@ -11,7 +11,7 @@
* **不要**在这里再 fetch / 建 thread / 跑 SSE —— 这些逻辑都在 `useStep1Intent`,
* 本组件保持纯展示 + 透传事件。
*/
import { useRef, useState } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import {
CheckCircle,
FileText,
@@ -128,6 +128,10 @@ export interface Step1PanelProps {
* 统一管理,因此岗位会商定制样式时不会分叉或复制 Step 1 的业务逻辑。
*/
inputArea?: (props: Step1InputAreaProps) => React.ReactNode;
/** Optional database-backed composer state used by the position workspace. */
inputDraftKey?: string;
initialInputText?: string;
onInputTextChange?: (value: string) => void;
onManualSave: () => void;
onTriggerToast: (msg: string) => void;
submitIntentClarifications: (
@@ -157,14 +161,20 @@ export function Step1Panel(props: Step1PanelProps) {
footerAction,
hideEnterRoundtable = false,
inputArea,
inputDraftKey,
initialInputText = "",
onInputTextChange,
onManualSave,
onTriggerToast,
submitIntentClarifications,
} = props;
const step1ScrollRef = useRef<HTMLDivElement>(null);
const step1ContentRef = useRef<HTMLDivElement>(null);
const { atBottom: step1AtBottom, scrollToBottom: scrollStep1ToBottom } =
useAutoScroll(step1ScrollRef, [interactiveMessages]);
useAutoScroll(step1ScrollRef, [interactiveMessages], {
contentRef: step1ContentRef,
});
// 「回答速度指示器」—— 与主页面共用全局开关 streamSpeedMeterEnabled。
const [localSettings] = useLocalSettings();
@@ -173,6 +183,16 @@ export function Step1Panel(props: Step1PanelProps) {
// 输入框完全是本地状态 —— 提到 Page 层会导致每次打字都重渲整页。
const [inputText, setInputText] = useState<string>("");
useEffect(() => {
setInputText(initialInputText);
}, [inputDraftKey, initialInputText]);
const handleInputTextChange = useCallback(
(value: string) => {
setInputText(value);
onInputTextChange?.(value);
},
[onInputTextChange],
);
// 待发送的本地附件(点发送时连同文本一起上传)。
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
const fileInputRef = useRef<HTMLInputElement>(null);
@@ -202,7 +222,7 @@ export function Step1Panel(props: Step1PanelProps) {
const handleSend = () => {
if (!inputText.trim() && attachedFiles.length === 0) return;
onSendMessage(inputText, attachedFiles.length > 0 ? attachedFiles : undefined);
setInputText("");
handleInputTextChange("");
setAttachedFiles([]);
};
@@ -234,21 +254,23 @@ export function Step1Panel(props: Step1PanelProps) {
<div
ref={step1ScrollRef}
// overflow-x-hidden:消息列表只竖向滚(见 Step2Panel 同处注释),避免误触横向拖动抢滑块。
className="flex-1 min-h-0 overflow-y-auto overflow-x-hidden p-6 space-y-4 bg-white"
className="flex-1 min-h-0 overflow-y-auto overflow-x-hidden bg-white"
>
{interactiveMessages.map((msg) => (
<Step1Message
key={msg.id}
msg={msg}
metric={speedMeterEnabled ? messageMetrics.get(msg.id) : undefined}
intentReady={intentReady}
pendingIntentClarificationMsgId={pendingIntentClarificationMsgId}
intentClarificationSelections={intentClarificationSelections}
setIntentClarificationSelections={setIntentClarificationSelections}
isIntentSending={isIntentSending}
submitIntentClarifications={submitIntentClarifications}
/>
))}
<div ref={step1ContentRef} className="space-y-4 p-6">
{interactiveMessages.map((msg) => (
<Step1Message
key={msg.id}
msg={msg}
metric={speedMeterEnabled ? messageMetrics.get(msg.id) : undefined}
intentReady={intentReady}
pendingIntentClarificationMsgId={pendingIntentClarificationMsgId}
intentClarificationSelections={intentClarificationSelections}
setIntentClarificationSelections={setIntentClarificationSelections}
isIntentSending={isIntentSending}
submitIntentClarifications={submitIntentClarifications}
/>
))}
</div>
</div>
{!step1AtBottom && <ScrollToBottomButton onClick={scrollStep1ToBottom} />}
</div>
@@ -257,7 +279,7 @@ export function Step1Panel(props: Step1PanelProps) {
{inputArea ? (
inputArea({
value: inputText,
onValueChange: setInputText,
onValueChange: handleInputTextChange,
attachedFiles,
onAddFiles: addAttachedFiles,
onRemoveFile: removeAttachedFile,
@@ -16,6 +16,12 @@ export function useAutoScroll<T extends HTMLElement>(
options: {
/** How close to the bottom (px) still counts as "at bottom". */
threshold?: number;
/**
* Optional inner content element. Streamed Markdown, clarification cards
* and expandable tool steps can change height without replacing the outer
* message array; observing this node keeps bottom-following reliable.
*/
contentRef?: RefObject<HTMLElement | null>;
} = {},
): {
/** True when the user is at the bottom — drives the button's visibility. */
@@ -24,6 +30,7 @@ export function useAutoScroll<T extends HTMLElement>(
scrollToBottom: () => void;
} {
const threshold = options.threshold ?? 32;
const contentRef = options.contentRef;
// Ref mirrors state so the deps-effect can read the latest value without
// re-subscribing when atBottom flips. State is for the button's render.
const atBottomRef = useRef(true);
@@ -35,7 +42,10 @@ export function useAutoScroll<T extends HTMLElement>(
// - 任何其它 scroll 事件视为用户主动滚动,按位置判定 atBottom。
// 这是修「鼠标拖滚动条没出现按钮」的关键:之前依赖 wheel/touchmove,
// 但鼠标拖滚动条**只触发 scroll 事件**,wheel/touchmove 完全不会触发。
const programmaticScrollRef = useRef(false);
// Keep the expected destination rather than a boolean. Setting scrollTop to
// its current value emits no event; a boolean would remain set and swallow
// the user's next real upward scroll.
const programmaticScrollTargetRef = useRef<number | null>(null);
// 自动跟随 effect 和 onScroll 共享的"上次观察到的 scrollTop"。
// 用来在 effect 里区分两种 distance 暴涨的情况:
// - currentScrollTop < lastObservedScrollTopRef → 用户主动向上滚 → 退出跟随
@@ -52,9 +62,13 @@ export function useAutoScroll<T extends HTMLElement>(
const distanceFromBottom = el.scrollHeight - currentScrollTop - el.clientHeight;
const isAtBottom = distanceFromBottom <= threshold;
if (programmaticScrollRef.current) {
const programmaticTarget = programmaticScrollTargetRef.current;
if (
programmaticTarget !== null &&
Math.abs(currentScrollTop - programmaticTarget) <= 1
) {
// 这是我们刚 scrollTop=scrollHeight 触发的回调,跳过,但仍刷新 prev 用于下次比较。
programmaticScrollRef.current = false;
programmaticScrollTargetRef.current = null;
prevScrollTop = currentScrollTop;
lastObservedScrollTopRef.current = currentScrollTop;
// 程序滚动后通常落在底部,把 atBottom 维持 true。
@@ -64,6 +78,9 @@ export function useAutoScroll<T extends HTMLElement>(
}
return;
}
if (programmaticTarget !== null) {
programmaticScrollTargetRef.current = null;
}
// 用户主动滚动:**任何向上滚的 scrollTop 减少都立刻退出自动跟随**,
// 不等位置算到底部 32px 之外才翻。这是按钮"滚动一点点就显示"的核心。
@@ -115,19 +132,56 @@ export function useAutoScroll<T extends HTMLElement>(
return;
}
// 在底部 (或仅是内容刚增长) → 同步拉到新底部。
programmaticScrollRef.current = true;
programmaticScrollTargetRef.current = Math.max(
0,
el.scrollHeight - el.clientHeight,
);
el.scrollTop = el.scrollHeight;
lastObservedScrollTopRef.current = el.scrollTop;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
// Some message UI grows after the React state update that triggered the
// dependency effect (Markdown layout, clarification cards, collapsed step
// details). Follow the actual content height as well, but only while the
// user has not intentionally scrolled upward.
useEffect(() => {
const el = ref.current;
const content = contentRef?.current;
if (!el || !content || typeof ResizeObserver === "undefined") return;
let frameId: number | null = null;
const observer = new ResizeObserver(() => {
if (!atBottomRef.current) return;
if (frameId !== null) window.cancelAnimationFrame(frameId);
frameId = window.requestAnimationFrame(() => {
frameId = null;
if (!atBottomRef.current) return;
programmaticScrollTargetRef.current = Math.max(
0,
el.scrollHeight - el.clientHeight,
);
el.scrollTop = el.scrollHeight;
lastObservedScrollTopRef.current = el.scrollTop;
});
});
observer.observe(content);
return () => {
observer.disconnect();
if (frameId !== null) window.cancelAnimationFrame(frameId);
};
}, [contentRef, ref]);
// 按钮点击是用户主动行为,保留 smooth 给视觉反馈;期间用户若立刻又拖动,
// onScroll 的方向检测仍会把 atBottom 翻回 false,不会卡住。
const scrollToBottom = useCallback(() => {
const el = ref.current;
if (!el) return;
// 标记程序滚动:smooth 动画过程中浏览器派发的 scroll 事件不应被误判为用户主动滚动。
programmaticScrollRef.current = true;
programmaticScrollTargetRef.current = Math.max(
0,
el.scrollHeight - el.clientHeight,
);
el.scrollTo({ top: el.scrollHeight, behavior: "smooth" });
atBottomRef.current = true;
setAtBottom(true);
@@ -647,17 +647,27 @@ export function useStep1Intent(options: UseStep1IntentOptions): UseStep1IntentRe
[intentClarificationSelections, sendIntentMessage, triggerToast],
);
const hydrateFromDraft = useCallback((snapshot: Step1Snapshot) => {
setIntentThreadId(snapshot.intentThreadId);
setIntentReady(snapshot.intentReady);
setIntentInitError(null);
setIntentInitErrorDetail(null);
setInteractiveMessages(snapshot.interactiveMessages);
setTimelineEntries(snapshot.timelineEntries);
step1InitRef.current = true;
// 让任何在途的旧 init 在 resolve 时被识别为过期,丢弃 setState。
step1InitGenRef.current += 1;
}, []);
const hydrateFromDraft = useCallback(
(snapshot: Step1Snapshot) => {
// 切换历史会话时,旧 thread 可能仍在流式回复。先终止它并清掉仅属于
// 上一个会话的“发送中/待澄清”瞬时状态,避免新会话输入框被锁住,
// 或继续显示旧会话的澄清选择。
stopIntentStream();
setIsIntentSending(false);
setPendingIntentClarificationMsgId(null);
setIntentClarificationSelections(new Map());
setIntentThreadId(snapshot.intentThreadId);
setIntentReady(snapshot.intentReady);
setIntentInitError(null);
setIntentInitErrorDetail(null);
setInteractiveMessages(snapshot.interactiveMessages);
setTimelineEntries(snapshot.timelineEntries);
step1InitRef.current = true;
// 让任何在途的旧 init 在 resolve 时被识别为过期,丢弃 setState。
step1InitGenRef.current += 1;
},
[stopIntentStream],
);
const appendLocalMessage = useCallback((msg: InteractiveMessage) => {
setInteractiveMessages((prev) => [...prev, msg]);