Simplify process disclosures and follow the execution frame

This commit is contained in:
QQ 2026-11-28 21:27:17 +08:00
parent 8ca3b77aed
commit 066935d125
11 changed files with 333 additions and 913 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -5,7 +5,7 @@ import { Blocks, CopyAnswer } from './Blocks.js';
import { ReasoningCard } from './ReasoningCard.js';
import { OfficialActions, OfficialAssistantBody } from './OfficialContent.js';
import { Disclosure, ProcessFragment } from './motion.js';
import { FoldSummaryText } from './LiveFold.js';
import type { ProcessSeam } from './live-turn.js';
import { assistantSegments, forkAnchorSeq, hasVisibleBody, isEarlierNarration } from './projection.js';
import type { TurnBoundary } from './projection.js';
import type { BlockRenderProps, ReaderProps } from './types.js';
@ -22,7 +22,7 @@ type SeatProps = BlockRenderProps & Pick<ReaderProps, 'useChat' | 'sessionId'> &
export const AssistantNode = memo(function AssistantNode({ useChat, nodeKey, boundary, processOpen = false, pinned = false, folded = false, partStart, seamSummary, seamAfter = false, motion, onRead, returnFocusTo, ...render }: SeatProps & {
motion: boolean; onRead: () => void; returnFocusTo: RefObject<HTMLButtonElement>; partStart?: number; folded?: boolean;
seamSummary?: string; seamAfter?: boolean;
seamSummary?: ProcessSeam; seamAfter?: boolean;
}) {
const node = useChat(snapshot => snapshot.nodes.get(nodeKey));
if (!node || node.visibility === 'hidden' || !isNode(node, 'assistant-step')) return null;
@ -38,7 +38,7 @@ export const AssistantNode = memo(function AssistantNode({ useChat, nodeKey, bou
const index = parts.findIndex(item => item.start === part.start);
const last = index === parts.length - 1;
if (part.kind === 'reasoning') return <ProcessFragment key={part.start} open={processOpen} motion={motion} onRead={onRead} returnFocusTo={returnFocusTo} nodeKey={nodeKey} framed>
<ReasoningCard step={data.step} active={processOpen && boundary.status === 'open' && data.step === boundary.latestStep} motion={motion} selected={pinned} onRead={onRead}>
<ReasoningCard step={data.step}>
<Blocks {...render} blocks={part.blocks} streaming={data.status === 'running' && last && data.blocks.at(-1)?.kind === 'reasoning'}
holdFormatting={pinned} startedAt={data.time} interrupted={data.status === 'interrupted'} liveText />
</ReasoningCard>
@ -50,9 +50,9 @@ export const AssistantNode = memo(function AssistantNode({ useChat, nodeKey, bou
// including the text transform, is only the fallback.
const isFinalAnswer = !isProcessStep;
return <Fragment key={part.start}>
{seamSummary && <div className={css.processSeamRow} data-reader-process-seam data-reader-process-seam-summary={seamSummary}>
<Disclosure open={false} onChange={() => onRead()} ariaLabel="被折叠的过程"
label={<FoldSummaryText summary={seamSummary} motion={false} />} />
{seamSummary && <div className={css.processSeamRow} data-reader-process-seam data-reader-process-seam-summary={seamSummary.summary}>
<Disclosure open={false} onChange={() => onRead()} ariaLabel={`执行记录,${seamSummary.summary}`}
label={<span title={seamSummary.summary}>查看 {seamSummary.count} 条执行记录</span>} />
</div>}
<article className={css.answer} data-reader-body data-reader-anchor data-reader-key={nodeKey} data-reader-source-start={part.start}
{...answerRowAttrs(nodeKey, part.start, data.turn)}

View File

@ -34,8 +34,9 @@ function Summary({ item, open, onChange, motion }: {
const button = useRef<HTMLButtonElement>(null);
return <div data-reader-live-fold data-expanded={open} data-reader-live-fold-summary={item.summary}>
<div className={css.summaryRow}>
<Disclosure open={open} onChange={onChange} buttonRef={button} ariaLabel="此前步骤"
label={<FoldSummaryText summary={item.summary} motion={motion} />} />
<Disclosure open={open} onChange={onChange} buttonRef={button} ariaLabel={`执行记录,${item.summary}`}
label={open ? <FoldSummaryText summary={item.summary} motion={motion} />
: <span title={item.summary}>查看 {item.steps.length} 条执行记录</span>} />
<DiffStat steps={item.steps} label={item.summary} />
</div>
</div>;
@ -101,10 +102,58 @@ function FlowCell({ hidden, instant, motion, rowKey, children, summary = false,
</div>;
}
export function ChoreographedFlow({ frame, motion, enabled, urgent, open, onOpenChange, processOpen, renderStep, id, status }: {
function ProcessScroll({ children, live }: { children: ReactNode; live: boolean }) {
const ref = useRef<HTMLDivElement>(null);
const following = useRef(true);
const lastWrittenTop = useRef<number | null>(null);
useLayoutEffect(() => {
const port = ref.current;
if (!port || !live) return;
const follow = () => {
const selection = document.getSelection();
if (!following.current || (selection && !selection.isCollapsed && selection.rangeCount
&& selection.getRangeAt(0).intersectsNode(port))) return;
const end = Math.max(0, port.scrollHeight - port.clientHeight);
if (Math.abs(port.scrollTop - end) <= 1) return;
port.scrollTop = end;
lastWrittenTop.current = port.scrollTop;
};
const resize = new ResizeObserver(follow);
const observeRows = () => {
resize.disconnect();
resize.observe(port);
for (const child of port.children) resize.observe(child);
follow();
};
const rows = new MutationObserver(observeRows);
rows.observe(port, { childList: true });
observeRows();
return () => {
rows.disconnect();
resize.disconnect();
};
}, [live]);
return <div ref={ref} className={css.processScroll} data-reader-process-scroll tabIndex={0} role="region" aria-label="执行过程"
onScroll={event => {
const port = event.currentTarget;
if (event.target !== port) return;
const written = lastWrittenTop.current;
lastWrittenTop.current = null;
if (written !== null && Math.abs(written - port.scrollTop) <= 1) return;
following.current = port.scrollHeight - port.clientHeight - port.scrollTop <= 2;
}}
onWheel={event => {
const port = event.currentTarget;
if (event.deltaY < 0 && port.scrollTop > 0) following.current = false;
}}>
{children}
</div>;
}
export function ChoreographedFlow({ frame, motion, enabled, urgent, open, onOpenChange, processOpen, running, renderStep, id, status }: {
frame: PresentationFrame; motion: boolean; enabled: boolean; urgent: boolean;
open: Readonly<Record<string, boolean>>; onOpenChange: (key: string, value: boolean) => void;
processOpen: boolean; renderStep: (step: LiveStep, folded: boolean) => ReactNode; id: string; status?: ReactNode;
processOpen: boolean; running: boolean; renderStep: (step: LiveStep, folded: boolean) => ReactNode; id: string; status?: ReactNode;
}) {
const root = useRef<HTMLDivElement>(null);
const stream = useContext(StreamMotionContext);
@ -249,15 +298,16 @@ export function ChoreographedFlow({ frame, motion, enabled, urgent, open, onOpen
return <FlowSnapshot.Provider value={source.snapshot}>
<StreamMotionContext.Provider value={{ ...stream, paused: state.phase !== 'idle', resumed: state.phase === 'reveal' }}>
<div id={id} ref={root} className={css.choreographedFlow} data-reader-flow data-reader-transition={state.phase} data-ud-motion="fold-choreography">
{groups.map(group => {
{groups.map((group, index) => {
const first = group[0]!;
if (!first.process && first.row) return renderCell({ ...first, row: first.row });
const key = first.row?.kind === 'summary' ? first.row.item.steps[0]?.key ?? first.key : first.key;
return <div key={`process:${key}`} className={css.processViewport} data-reader-process-frame>
{!first.row && <div className={css.turnStickyLanes} data-flow-process>{status}</div>}
<div className={css.processScroll} data-reader-process-scroll tabIndex={0} role="region" aria-label="执行过程">
<ProcessScroll live={running && visible && state.phase === 'idle' && index === groups.length - 1
&& group.some(({ row, hidden }) => !hidden && row?.kind === 'step' && !row.foldKey)}>
{group.map(cell => cell.row && renderCell({ ...cell, row: cell.row }))}
</div>
</ProcessScroll>
</div>;
})}
</div>

View File

@ -136,19 +136,16 @@
rail width, same gutter, so a column of nested rows reads as one line. */
.processContents { display: flow-root; border-left: 1px solid var(--dsw-alias-border-l2); padding: 3px 0 2px var(--reader-gutter, 16px); margin: 0 0 0 var(--reader-rail, 6px); color: var(--dsw-alias-label-secondary); font-size: 14px; line-height: 24px; }
.processContents > :last-child { margin-bottom: 0; }
/* Narration stays ordinary body text (the `.answer` typography) and carries no
left rule of its own. When collapsed reasoning/tool rows sat between two
narration blocks, the gap carries a compact folded-process summary in the
process-chain language: a 1px left rail plus the familiar `思考×N · 工具×K`
label with its chevron. The preceding narration cell drops its outer bottom
gap so the seam row owns exactly that space. */
.processSeamRow {
display: flex; align-items: center; min-height: 40px;
margin-left: var(--reader-rail, 6px); padding-left: var(--reader-gutter, 16px);
border-left: 1px solid var(--dsw-alias-border-l2); box-sizing: border-box;
/* The inline disclosure supplies the spacing between narration blocks. */
.processSeamRow { display: flex; align-items: center; min-height: 32px; }
.processSeamRow .disclosureButton {
min-height: 24px;
padding-block: 2px;
font-size: 12px;
line-height: 20px;
color: var(--dsw-alias-label-tertiary);
}
.processSeamRow > .disclosure { display: flex; align-items: center; min-height: 24px; }
.processSeamRow .disclosureButton { min-height: 24px; padding-block: 2px; font-size: 12px; line-height: 20px; color: var(--dsw-alias-label-tertiary); }
@media (pointer: coarse) { .processSeamRow .disclosureButton { min-height: 44px; } }
.flowCell:has(> .flowCellInner > [data-reader-seam-after]) > .flowCellInner { padding-bottom: 0; }
.processFrame { min-width: 0; }
.toolActivity { color: var(--dsw-alias-label-secondary); }
@ -359,65 +356,17 @@
@container (max-width: 420px) { .toolHeading { gap: 7px; padding: 11px 10px 6px; grid-template-columns: 16px minmax(0, 1fr) auto; } .toolHeadingState { gap: 4px; } .toolLedger { padding-left: 33px; padding-right: 10px; } .toolPanel { padding: 10px; } /* .toolChildren keeps the shared rail here too: a different left edge under a
narrow container is what made nested rows read as misplaced lines. */ }
@media (pointer: coarse) { .toolTabs > button { min-height: 44px; } }
/* Transitions.dev — Reasoning stream (user-supplied). Transform the one real
transcript; hand the painted offset to native scrolling for manual reading. */
.reasonCard {
--reason-preview-height: 224px;
--reason-hold: 840ms;
--reason-step: 500ms;
--reason-lines: 2;
--reason-fade: 28px;
--reason-ease: cubic-bezier(0.22, 1, 0.36, 1);
position: relative;
min-width: 0;
overflow: hidden;
border: 1px solid var(--dsw-alias-border-l2);
border-radius: 12px;
background: var(--dsw-alias-bg-module-platform);
scroll-margin-block: 16px calc(var(--dsh-composer-height, 152px) + 16px);
}
.reasonHeading { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; padding: 10px 16px 0; color: var(--dsw-alias-label-secondary); font-size: 12px; line-height: 20px; font-variant-numeric: tabular-nums; }
.reasonCard[data-overflow=false][data-expanded=false] .reasonText { padding-bottom: 10px; }
.reasonLabel { font-weight: 500; }
.reasonViewport {
position: relative;
max-height: var(--reason-preview-height);
overflow: auto;
scroll-behavior: auto;
overflow-anchor: none;
overscroll-behavior-y: contain;
scrollbar-width: thin;
scrollbar-color: var(--dsw-alias-border-l1) transparent;
}
.reasonCard[data-expanded=true] .reasonViewport { max-height: min(60vh, 560px, var(--reason-reading-height, 560px)); }
.reasonViewport[data-edges=both], .reasonCard[data-following=true][data-overflow=true] .reasonViewport {
-webkit-mask-image: linear-gradient(transparent 0, black var(--reason-fade), black calc(100% - var(--reason-fade)), transparent 100%);
mask-image: linear-gradient(transparent 0, black var(--reason-fade), black calc(100% - var(--reason-fade)), transparent 100%);
}
.reasonViewport[data-edges=top] {
-webkit-mask-image: linear-gradient(transparent 0, black var(--reason-fade), black 100%);
mask-image: linear-gradient(transparent 0, black var(--reason-fade), black 100%);
}
.reasonViewport[data-edges=bottom] {
-webkit-mask-image: linear-gradient(black 0, black calc(100% - var(--reason-fade)), transparent 100%);
mask-image: linear-gradient(black 0, black calc(100% - var(--reason-fade)), transparent 100%);
}
.reasonCard[data-expanded=true] .reasonViewport { -webkit-mask-image: none; mask-image: none; }
.reasonViewport:focus-visible { outline: 2px solid var(--dsw-alias-state-business-primary); outline-offset: -3px; }
.reasonTrack { position: relative; transform: translateY(0); }
.reasonCard[data-following=true] .reasonTrack { will-change: transform; }
.reasonText { padding: 8px 16px 16px; font-size: 14px; line-height: 24px; color: var(--dsw-alias-label-secondary); overflow-wrap: anywhere; }
.reasonText .readingText > div { font-size: inherit; line-height: inherit; color: inherit; }
.reasonFooter { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 2px 10px 8px; font-size: 12px; line-height: 20px; color: var(--dsw-alias-label-secondary); }
.reasonAction { display: inline-flex; justify-content: center; align-items: center; gap: 5px; min-height: 28px; padding: 4px 6px; border: 0; border-radius: 6px; background: transparent; color: inherit; font: inherit; cursor: pointer; white-space: nowrap; }
.reasonAction:hover { background: var(--dsw-alias-interactive-bg-hover); }
.reasonAction:disabled { cursor: default; opacity: .65; }
.reasonAction svg { flex: none; fill: none; stroke: currentColor; stroke-width: 1.3; stroke-linecap: round; stroke-linejoin: round; }
.reasonCaption { padding-left: 6px; }
@container (max-width: 480px) { .reasonCard { --reason-preview-height: 192px; } }
@media (pointer: coarse) { .reasonAction { min-height: 44px; } }
@media (prefers-reduced-motion: reduce) { .reasonTrack { transition: none !important; transform: none !important; will-change: auto !important; } }
@media (forced-colors: active) { .reasonViewport { -webkit-mask-image: none !important; mask-image: none !important; } }
.processItem, .tool { margin: 0 0 18px; min-width: 0; }
.processLabel { display: flex; align-items: baseline; gap: 12px; margin: 0 0 6px; color: var(--dsw-alias-label-tertiary); font-size: 12px; line-height: 20px; }
.processFootnote { color: var(--dsw-alias-label-tertiary); margin: 14px 0 0; font-size: 12px; line-height: 20px; }
@ -590,6 +539,10 @@
.processScroll:focus-visible { outline: 2px solid var(--dsw-alias-state-business-primary); outline-offset: -2px; }
.processViewport > .turnStickyLanes { position: static; flex: none; padding: 4px 8px; }
.root[data-reader-glass] .processViewport { background: transparent; }
.processViewport:has(.closedProcessSummary, > .processScroll > .flowCell[data-flow-summary]):not(:has(> .processScroll > .flowCell:not([hidden], [data-flow-summary]))) {
border: 0;
background: transparent;
}
.flowCell[data-flow-process] :is(.reasonCard, .toolActivity, .processCard, .toolDetails, :global([data-turn-trigger])) {
border: 0;
background: transparent;

View File

@ -607,6 +607,7 @@ const TurnGroup = memo(function TurnGroup({ group, motion, autoFold, pinnedKeys,
<div className={css.turnStickyRegion} data-reader-sticky-region>
<ChoreographedFlow id={flowId} frame={presentation} motion={motion} enabled={autoFold && boundary.status === 'open' && !holdingSelection}
urgent={hasTurnError || interaction !== undefined || !sessionRunning} open={foldOpenByKey} processOpen={expanded}
running={sessionRunning && boundary.status === 'open' && !holdingSelection}
status={(showStatusLane || showClosedSummary) && <StickyLane kind="status" className={css.turnProcessSticky}>
{showStatusLane && <Disclosure open={expanded} onChange={setExpanded} controls={flowId} buttonRef={processButton}
label={<GroupStatus group={group} useChat={props.useChat} pending={interaction} motion={motion} />} />}

View File

@ -1,306 +1,12 @@
import { useCallback, useContext, useEffect, useId, useLayoutEffect, useRef, useState } from 'react';
import { StreamMotionContext } from './streaming.js';
import type { ReactNode } from 'react';
import { REASON_CHASE_HOLD, REASON_HOLD, REASON_LINES, REASON_STEP, reasoningTarget } from './reasoning-follow.js';
import css from './Reader.module.css';
const EASING = 'cubic-bezier(.22,1,.36,1)';
/** One real transcript: reference transform while following, native scroll while reading. */
export function ReasoningCard({ children, step, active, motion, selected, onRead }: {
children: ReactNode; step: number; active: boolean; motion: boolean; selected: boolean; onRead: () => void;
}) {
const viewport = useRef<HTMLDivElement>(null);
const track = useRef<HTMLDivElement>(null);
const content = useRef<HTMLDivElement>(null);
const controls = useId();
const [expanded, setExpanded] = useState(false);
const [following, setFollowing] = useState(true);
const [overflow, setOverflow] = useState(false);
const [edges, setEdges] = useState('none');
const lastHeight = useRef(0);
const resize = useRef<Animation | null>(null);
const previousExpanded = useRef(expanded);
const stopFollow = useRef<() => void>(() => {});
const { paused = false } = useContext(StreamMotionContext);
const allowed = following && active && motion && !selected && !paused;
const pause = useCallback(() => {
stopFollow.current();
setFollowing(false);
onRead();
}, [onRead]);
useLayoutEffect(() => {
// The parent's selection observer can suspend this card before its own
// listener runs. Clearing a selection must not silently resume following.
if (!selected) return;
stopFollow.current();
setFollowing(false);
}, [selected]);
useLayoutEffect(() => {
if (!expanded) return;
const port = viewport.current;
const host = port?.closest<HTMLElement>('[data-conversation-scroll]');
if (!port || !host) return;
const fit = () => {
// Public DSH layout variable, updated by the native composer's observer.
// Leave room for the permanent identity, footer and reading margin.
const composer = parseFloat(getComputedStyle(host).getPropertyValue('--dsh-composer-height')) || 152;
const heading = port.parentElement?.querySelector<HTMLElement>('[data-reader-reasoning-heading]')?.offsetHeight || 30;
const footer = port.parentElement?.querySelector<HTMLElement>('[data-ud-check=reasoning-controls]')?.offsetHeight || 38;
const available = Math.max(120, host.clientHeight - composer - heading - footer - 32);
port.style.setProperty('--reason-reading-height', `${available}px`);
};
fit();
const observer = new ResizeObserver(fit); observer.observe(host);
return () => { observer.disconnect(); };
}, [expanded]);
useLayoutEffect(() => {
const port = viewport.current;
const text = content.current;
const scrollTrack = track.current;
if (!port || !text || !scrollTrack) return;
let frame = 0;
let timer: ReturnType<typeof setTimeout> | undefined;
let nextAt = performance.now() + REASON_HOLD;
let alive = true;
let automatic = false;
let lastPainted = port.scrollTop;
let targetOffset = lastPainted;
const tail = () => Math.max(0, text.offsetHeight - port.clientHeight);
const clamp = (value: number) => Math.max(0, Math.min(tail(), value));
const paintedOffset = () => {
if (!automatic) return port.scrollTop;
const transform = getComputedStyle(scrollTrack).transform;
// Reduced-motion CSS may win before React receives the media change.
// Retain the last painted position rather than snapping back to the top.
return clamp(transform === 'none' ? lastPainted : port.scrollTop - new DOMMatrixReadOnly(transform).m42);
};
const hasSelection = () => {
const selection = document.getSelection();
return !!selection && !selection.isCollapsed && !!selection.anchorNode && text.contains(selection.anchorNode);
};
const cancel = () => {
cancelAnimationFrame(frame); frame = 0;
clearTimeout(timer); timer = undefined;
delete port.dataset.reasoningMoving;
};
const manual = () => {
if (!automatic) return;
const top = paintedOffset();
automatic = false;
scrollTrack.style.transition = 'none';
scrollTrack.style.transform = 'none';
// Set both in the same layout effect/event, before a frame can paint.
// The first wheel gesture must already have a native scrollable viewport.
port.style.overflow = 'auto';
port.scrollTop = top;
lastPainted = port.scrollTop;
port.dataset.reasoningMode = 'manual';
};
const follow = () => {
if (automatic) return;
targetOffset = lastPainted = clamp(port.scrollTop);
scrollTrack.style.transition = 'none';
scrollTrack.style.transform = `translateY(-${lastPainted}px)`;
port.scrollTop = 0;
port.style.overflow = 'hidden';
automatic = true;
port.dataset.reasoningMode = 'transform';
};
const measure = (recordHeight = true) => {
const previewHeight = parseFloat(getComputedStyle(port).getPropertyValue('--reason-preview-height'));
setOverflow(text.offsetHeight > previewHeight + 1);
lastPainted = paintedOffset();
const top = lastPainted > 1;
const bottom = tail() - lastPainted > 1;
const next = top ? bottom ? 'both' : 'top' : bottom ? 'bottom' : 'none';
setEdges(value => value === next ? value : next);
if (recordHeight && !resize.current) lastHeight.current = port.clientHeight;
};
stopFollow.current = () => { cancel(); manual(); measure(false); };
const canFollow = () => allowed && alive && !document.hidden && !hasSelection();
const schedule = () => {
if (!canFollow() || frame || timer !== undefined) return;
follow();
if (tail() - paintedOffset() < 1) return;
timer = setTimeout(start, Math.max(0, nextAt - performance.now()));
};
const start = () => {
timer = undefined;
if (!canFollow()) return;
const from = paintedOffset();
const lineHeight = parseFloat(getComputedStyle(text).lineHeight) || 24;
// How much unpainted text is waiting. A fast model pushes this far past the
// reference step, and chasing it is what keeps the scroll continuous.
const backlogLines = Math.max(0, (tail() - from) / lineHeight);
const target = reasoningTarget(from, text.offsetHeight, port.clientHeight, lineHeight, backlogLines);
if (target - from < 1) return;
const began = performance.now();
// Still behind after this step: take the next one almost immediately instead
// of holding the reading beat, so motion tracks the text rather than stalling.
nextAt = began + (backlogLines > REASON_LINES ? REASON_CHASE_HOLD : REASON_HOLD);
targetOffset = target;
// The supplied recipe: commit the start pose, then transition the track.
// No per-frame scrollTop writes and no catch-up across unread lines.
scrollTrack.style.transition = 'none';
scrollTrack.style.transform = `translateY(-${from}px)`;
void scrollTrack.offsetHeight;
scrollTrack.style.transition = 'transform var(--reason-step) var(--reason-ease)';
scrollTrack.style.transform = `translateY(-${target}px)`;
port.dataset.reasoningMoving = 'true';
port.dataset.reasoningFrom = String(from);
port.dataset.reasoningTarget = String(target);
port.dataset.reasoningBegan = String(began);
const tick = (now: number) => {
frame = 0;
if (!canFollow()) { cancel(); manual(); return; }
// Observe the browser's actual CSS interpolation for masks and handoff.
measure();
if (now - began < REASON_STEP || Math.abs(lastPainted - target) > .05) frame = requestAnimationFrame(tick);
else { delete port.dataset.reasoningMoving; schedule(); }
};
frame = requestAnimationFrame(tick);
};
const onScroll = () => {
measure();
// Focus/keyboard-induced native scroll wins even while the track moves.
if (automatic && port.scrollTop > 1) pause();
};
const onWheel = (event: WheelEvent) => {
if (!event.deltaY) return;
// The compositor picks a wheel scroller before handlers run. A clipped
// transform viewport would otherwise lose this first gesture or scroll
// the conversation. Consume only this handoff; later wheels stay native.
const handoff = automatic && event.cancelable;
if (handoff) event.preventDefault();
const unit = event.deltaMode === WheelEvent.DOM_DELTA_LINE ? parseFloat(getComputedStyle(text).lineHeight) || 24
: event.deltaMode === WheelEvent.DOM_DELTA_PAGE ? port.clientHeight : 1;
pause();
if (handoff) { port.scrollTop = clamp(port.scrollTop + event.deltaY * unit); measure(); }
};
const onSelection = () => { if (hasSelection()) pause(); };
const onVisibility = () => {
cancel(); manual();
nextAt = performance.now() + REASON_HOLD;
if (!document.hidden) schedule();
};
const observer = new ResizeObserver(() => {
if (automatic && targetOffset > tail() + 1) {
cancel(); manual();
nextAt = performance.now() + REASON_HOLD;
}
measure(); schedule();
});
observer.observe(text); observer.observe(port);
port.addEventListener('scroll', onScroll, { passive: true });
port.addEventListener('wheel', onWheel, { passive: false });
document.addEventListener('selectionchange', onSelection);
document.addEventListener('visibilitychange', onVisibility);
// Keep the previous layout height until the resize effect can sample it.
measure(false); schedule();
return () => {
alive = false; cancel(); manual(); observer.disconnect();
port.removeEventListener('scroll', onScroll); port.removeEventListener('wheel', onWheel);
document.removeEventListener('selectionchange', onSelection);
document.removeEventListener('visibilitychange', onVisibility);
stopFollow.current = () => {};
};
}, [allowed, pause]);
useLayoutEffect(() => {
const port = viewport.current;
if (!port) return;
const changed = expanded !== previousExpanded.current;
previousExpanded.current = expanded;
const from = resize.current ? port.clientHeight : lastHeight.current;
resize.current?.cancel(); resize.current = null;
port.style.maxHeight = ''; port.style.height = '';
const target = port.clientHeight;
// Explicit reading adjusts only the conversation, never the outer app.
// The card is also a reader anchor so resizing cannot pin a later answer
// in place at the expense of this card's visible heading.
if (changed && !selected) {
const card = port.parentElement;
const host = port.closest<HTMLElement>('[data-conversation-scroll]');
if (card && host) {
const composer = parseFloat(getComputedStyle(host).getPropertyValue('--dsh-composer-height')) || 152;
const region = host.getBoundingClientRect();
const box = card.getBoundingClientRect();
const top = region.top + 16;
const bottom = region.bottom - composer - 16;
const delta = box.top < top ? box.top - top : box.bottom > bottom ? Math.min(box.bottom - bottom, box.top - top) : 0;
if (Math.abs(delta) > 1) host.scrollTo({ top: Math.max(0, host.scrollTop + delta), behavior: motion ? 'smooth' : 'instant' });
}
}
if (!changed || !motion || from < 1 || Math.abs(target - from) < 1) {
lastHeight.current = target;
return;
}
// max-height otherwise clamps the very first collapse frame to the new cap.
port.style.maxHeight = 'none';
const animation = port.animate([{ height: `${from}px` }, { height: `${target}px` }], { duration: 300, easing: EASING, fill: 'both' });
resize.current = animation;
const restore = () => {
// `max-height` was cleared so the first frame could exceed the old cap; it has
// to come back even if the animation never reports finishing, or the card keeps
// the inline styles the animation was driving.
port.style.maxHeight = ''; port.style.height = '';
lastHeight.current = port.clientHeight;
};
let settled = false;
const settle = () => {
if (settled) return;
settled = true;
if (resize.current === animation) resize.current = null;
animation.cancel();
restore();
};
animation.onfinish = settle;
// `fill: 'both'` holds whichever keyframe the animation stopped on, so a run that
// never finishes — cancelled by a re-run, unmounted, or skipped by the compositor —
// would leave the card at the previous height with its inline styles still
// overridden. Restore on a deadline too.
const deadline = window.setTimeout(settle, 300 + 240);
return () => { window.clearTimeout(deadline); };
}, [expanded, motion, selected]);
useEffect(() => () => resize.current?.cancel(), []);
const toggleReading = () => {
// Resize the same transcript without changing follow intent or position.
// Wheel, selection and viewport focus still explicitly pause following.
onRead();
setExpanded(value => !value);
};
return <div className={css.reasonCard} data-reader-reasoning-card data-reader-anchor data-expanded={expanded} data-following={allowed} data-overflow={overflow} data-ud-motion="reader-reasoning-size">
export function ReasoningCard({ children, step }: { children: ReactNode; step: number }) {
return <div className={css.reasonCard} data-reader-reasoning-card>
<div className={css.reasonHeading} data-reader-reasoning-heading data-ud-check="reasoning-identity">
<span className={css.reasonLabel} data-reader-reasoning-label>思考</span>
<span>步骤 {step}</span>
</div>
<div ref={viewport} id={controls} className={css.reasonViewport} data-reader-reasoning-scroll data-edges={edges}
data-ud-motion="reader-reasoning-scroll" role="region" aria-label={`步骤 ${step} 的思考${overflow ? ',可滚动阅读' : ''}`}
tabIndex={overflow ? 0 : undefined} onPointerDown={pause} onFocus={pause}>
<div ref={track} className={css.reasonTrack} data-reader-reasoning-track>
<div ref={content} className={css.reasonText} data-reader-reasoning-text>{children}</div>
</div>
</div>
{(overflow || expanded) && <div className={css.reasonFooter} data-ud-check="reasoning-controls">
{active && motion ? <button type="button" className={css.reasonAction} disabled={selected} aria-controls={controls}
aria-label={following ? '暂停自动跟随思考' : '继续跟随最新思考'}
title={selected ? '取消文字选择后可继续跟随' : undefined}
onClick={() => { if (following) pause(); else { onRead(); setFollowing(true); } }}>
<svg width="12" height="12" viewBox="0 0 16 16" aria-hidden="true">{following ? <path d="M5.5 4v8m5-8v8" /> : <path d="M8 3v10m-4-4 4 4 4-4" />}</svg>
{following ? '暂停跟随' : '跟随最新'}
</button> : <span className={css.reasonCaption}>{expanded ? '手动阅读' : '可滚动阅读'}</span>}
<button type="button" className={css.reasonAction} aria-expanded={expanded} aria-controls={controls}
aria-label={expanded ? '收起完整思考' : '展开阅读完整思考'} onClick={toggleReading}>
{expanded ? '收起' : '展开阅读'}
<svg width="12" height="12" viewBox="0 0 16 16" aria-hidden="true">{expanded ? <path d="m4 10 4-4 4 4" /> : <path d="m4 6 4 4 4-4" />}</svg>
</button>
</div>}
<div className={css.reasonText} data-reader-reasoning-text>{children}</div>
</div>;
}

View File

@ -167,12 +167,14 @@ export function presentLiveTurn(steps: readonly LiveStep[], boundary: TurnBounda
* is what marks the previous body with `data-reader-seam-after` and drops its
* bottom padding; skipping the seam must leave that spacing alone.
*/
export type ProcessSeam = { summary: string; count: number };
export function planProcessSeams(
steps: readonly LiveStep[],
liveItems: readonly LiveTurnItem[],
expanded: boolean,
): { before: Map<string, string>; after: Set<string> } {
const before = new Map<string, string>();
): { before: Map<string, ProcessSeam>; after: Set<string> } {
const before = new Map<string, ProcessSeam>();
const after = new Set<string>();
if (expanded) return { before, after };
const liveFolded = new Set(
@ -186,7 +188,7 @@ export function planProcessSeams(
const coveredByLiveFold = folded.length > 0 && folded.every(item => liveFolded.has(item.key));
if (!coveredByLiveFold && previousBody
&& folded.some(item => item.kind === 'reasoning' || item.kind === 'tool' || item.kind === 'other')) {
before.set(step.key, foldSummary(folded));
before.set(step.key, { summary: foldSummary(folded), count: folded.length });
after.add(previousBody.key);
}
previousBody = step;

View File

@ -452,14 +452,19 @@ export function useReadingScroll(root: RefObject<HTMLElement>, motion: boolean):
}
if (!bottom) { following.current = false; setDetached(true); }
};
const fromProcess = (event: Event) => event.target instanceof Element
&& event.target.closest('[data-reader-process-scroll]');
const onWheel = (event: WheelEvent) => {
if (fromProcess(event)) return;
cancelAnimationFrame(followFrame); followFrame = 0; lastWrittenTop = null;
if (event.deltaY < 0) { following.current = false; setDetached(true); pinned.current = false; scheduleCapture(); }
};
const onTouch = () => {
const onTouch = (event: TouchEvent) => {
if (fromProcess(event)) return;
cancelAnimationFrame(followFrame); followFrame = 0; lastWrittenTop = null;
};
const onKey = (event: KeyboardEvent) => {
if (fromProcess(event)) return;
if (event.target instanceof HTMLElement && event.target.closest('textarea,input,[contenteditable=true]')) return;
if (['PageUp', 'Home', 'ArrowUp'].includes(event.key)) {
cancelAnimationFrame(followFrame); followFrame = 0; lastWrittenTop = null;

View File

@ -280,7 +280,7 @@ test('closed turn keeps the seam between narration blocks and the previous body
assert.equal(live.some(item => item.kind === 'fold'), false);
const seams = planProcessSeams(steps, live, false);
assert.equal(seams.before.get('body2'), '思考×2 · 工具×3 · 记录×1');
assert.deepEqual(seams.before.get('body2'), { summary: '思考×2 · 工具×3 · 记录×1', count: 6 });
assert.equal(seams.after.has('body1'), true);
const expanded = planProcessSeams(steps, live, true);

View File

@ -100,6 +100,7 @@ test('the status lane joins the visible process frame and the execution request
assert.match(reader, /status=\{\(showStatusLane \|\| showClosedSummary\) && <StickyLane/u);
assert.match(flow, /groupProcessRows\(status \? \[header, \.\.\.cells\] : cells\)/u);
assert.match(flow, /const hidden = \(trigger && !processOpen\)/u);
assert.match(flow, /data-reader-process-frame>[\s\S]*?\{status\}[\s\S]*?data-reader-process-scroll/u);
assert.match(flow, /data-reader-process-frame>[\s\S]*?\{status\}[\s\S]*?<ProcessScroll/u);
assert.match(flow, /className=\{css\.processScroll\} data-reader-process-scroll/u);
assert.match(readerCss, /\[data-flow-process\]\[data-flow-summary\] \.disclosureButton \{[^}]*border: 0/u);
});