dsh-better-chat/src/client/ChoreographedFlow.tsx

317 lines
17 KiB
TypeScript

import { createContext, useContext, useEffect, useLayoutEffect, useRef, useState } from 'react';
import type { ReactNode } from 'react';
import type { ChatSnapshot } from '@deepseek-ai/dsh-client-ui-chat/client';
import type { ReaderProps } from './types.js';
import type { LiveStep, LiveTurnItem } from './live-turn.js';
import { collapseRows, containsNewUser, flowRows, FOLD_TIMING, groupProcessRows, retiringKeys } from './fold-choreography.js';
import type { FlowRow, FoldPhase } from './fold-choreography.js';
import { Disclosure } from './motion.js';
import { FoldSummaryText } from './LiveFold.js';
import { DiffStat } from './DiffPanel.js';
import { StreamMotionContext } from './streaming.js';
import css from './Reader.module.css';
import { useSummaryLane } from './StickyLane.js';
const FLOW_CELLS = ':scope > [data-flow-key], :scope > [data-reader-process-frame] > [data-reader-process-scroll] > [data-flow-key]';
const FlowSnapshot = createContext<ChatSnapshot | null>(null);
/** Public projection only. Descendants cannot leak live data through a frozen frame. */
export const useFlowChat: ReaderProps['useChat'] = selector => {
const snapshot = useContext(FlowSnapshot);
if (!snapshot) throw new Error('Flow snapshot provider missing');
return selector(snapshot);
};
export type PresentationFrame = { items: readonly LiveTurnItem[]; snapshot: ChatSnapshot };
type Transaction = {
phase: FoldPhase; shown: PresentationFrame; target: PresentationFrame;
retiring: readonly string[]; beforeKeys: ReadonlySet<string>;
};
const idle = (frame: PresentationFrame): Transaction => ({ phase: 'idle', shown: frame, target: frame, retiring: [], beforeKeys: new Set() });
function Summary({ item, open, onChange, motion }: {
item: Extract<LiveTurnItem, { kind: 'fold' }>; open: boolean; onChange: (open: boolean) => void; motion: boolean;
}) {
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={`执行记录,${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>;
}
/** Manual disclosure shares the measured-size path; children survive until finish. */
function FlowCell({ hidden, instant, motion, rowKey, children, summary = false, process }: {
hidden: boolean; instant: boolean; motion: boolean; rowKey: string; children: ReactNode; summary?: boolean; process?: boolean;
}) {
const ref = useRef<HTMLDivElement>(null);
useSummaryLane(ref, summary);
const [present, setPresent] = useState(!hidden);
const previous = useRef(hidden);
if (!hidden && !present) setPresent(true);
useLayoutEffect(() => {
const el = ref.current;
const changed = previous.current !== hidden;
previous.current = hidden;
if (!el) return;
if (!changed || instant || !motion) { setPresent(!hidden); return; }
const height = el.scrollHeight;
const animation = el.animate([
{ height: `${hidden ? height : 0}px`, opacity: hidden ? 1 : 0 },
{ height: `${hidden ? 0 : height}px`, opacity: hidden ? 0 : 1 },
], { duration: 220, easing: 'cubic-bezier(.4,0,.2,1)', fill: 'both' });
el.dispatchEvent(new CustomEvent('reader-layout-start', { bubbles: true }));
let released = false;
const release = () => { if (!released) { released = true; el.dispatchEvent(new CustomEvent('reader-layout-end', { bubbles: true })); } };
// Do NOT cancel here. `fill: 'both'` is what currently holds the cell at its
// collapsed size; cancelling on finish drops that fill before React has
// committed the removal, so the cell snaps back to full height for one frame
// — the flash before it disappears. The state change alone retires it; the
// cleanup below cancels the animation once that has actually rendered.
let settled = false;
const settle = () => {
if (settled) return;
settled = true;
// Expanding retires nothing: the fill only pins the measured height. Drop it
// now — if the cell's content later shrinks, the stale fill would hold the
// empty space open. Collapsing still keeps the fill until React commits
// the removal (see the comment above), then the cleanup cancels it.
if (!hidden) animation.cancel();
setPresent(!hidden);
release();
};
animation.onfinish = settle;
// \`fill: 'both'\` pins the opening keyframe for the whole run, so if this
// animation never advances the cell stays at height 0 and opacity 0: the row is
// in the DOM but reads as "clicked it and nothing happened". A cancelled
// animation, or one inside a subtree the compositor skips, never fires
// onfinish. Fall back to the state change on a deadline; the cleanup then
// cancels the animation and drops the fill.
const deadline = window.setTimeout(settle, 220 + 240);
return () => { window.clearTimeout(deadline); animation.cancel(); release(); };
// `present` is a dependency so that committing it re-runs this effect: the
// cleanup then cancels the finished animation *after* the removal has been
// applied, which is the only moment the fill can be dropped safely. Without
// it the animation was never cancelled at all and every folded cell kept one.
}, [hidden, instant, motion, present]);
return <div ref={ref} className={css.flowCell} data-flow-key={rowKey} data-flow-summary={summary || undefined} data-flow-process={process || undefined}
hidden={hidden && !present} aria-hidden={hidden || undefined} {...(hidden ? { inert: '' } : {})}>
{present && <div className={css.flowCellInner}>{children}</div>}
</div>;
}
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; running: boolean; renderStep: (step: LiveStep, folded: boolean) => ReactNode; id: string; status?: ReactNode;
}) {
const root = useRef<HTMLDivElement>(null);
const stream = useContext(StreamMotionContext);
const latest = useRef(frame); latest.current = frame;
const [visible, setVisible] = useState(() => !document.hidden);
const [state, setState] = useState<Transaction>(() => idle(frame));
const bypass = !motion || !enabled || urgent || !visible || !processOpen || (state.phase !== 'idle' && Object.values(open).some(Boolean));
const shownKeys = state.shown !== frame ? new Set(state.shown.items.map(item => item.key)) : undefined;
const outputArrived = shownKeys !== undefined && frame.items.some(item =>
item.kind === 'open' && item.step.kind === 'body' && !shownKeys.has(item.key));
// Publish new prose with its folded process rather than buffering the first words.
// Render-time adjustment prevents even one paint of the stale layout.
if ((bypass || outputArrived || containsNewUser(state.shown.items, frame.items)) && (state.phase !== 'idle' || state.shown !== frame)) {
setState(idle(frame));
} else if (state.phase === 'idle' && state.shown !== frame) {
const retiring = retiringKeys(state.shown.items, frame.items, open);
setState(retiring.length ? { ...state, phase: 'collapse', target: frame, retiring,
beforeKeys: new Set(flowRows(state.shown.items).map(row => row.key)) } : idle(frame));
}
useEffect(() => {
const update = () => setVisible(!document.hidden);
document.addEventListener('visibilitychange', update);
return () => document.removeEventListener('visibilitychange', update);
}, []);
useLayoutEffect(() => {
if (state.phase !== 'collapse') return;
const el = root.current;
if (!el) return;
const retiring = new Set(state.retiring);
const animations: Animation[] = [];
el.dispatchEvent(new CustomEvent('reader-layout-start', { bubbles: true }));
for (const cell of el.querySelectorAll<HTMLElement>(FLOW_CELLS)) {
const key = cell.dataset.flowKey!;
const isHeader = cell.dataset.flowSummary && !state.beforeKeys.has(key);
if (!retiring.has(key) && !isHeader) continue;
const height = cell.getBoundingClientRect().height;
animations.push(cell.animate(isHeader ? [
{ height: '0px', opacity: 0 }, { height: `${height}px`, opacity: 1 },
] : [
{ height: `${height}px`, opacity: 1 },
{ height: `${height * .5}px`, opacity: .85, offset: .5 },
{ height: '0px', opacity: 0 },
], { duration: FOLD_TIMING.collapse, easing: 'cubic-bezier(.4,0,.2,1)', fill: 'both' }));
}
let cancelled = false;
// Coalesce everything received during shrink, once. No animation restarts.
// Idempotent and phase-checked: the promise and the deadline race, and
// whichever arrives first wins while the other becomes a no-op.
let advanced = false;
const advance = () => {
if (cancelled || advanced) return;
advanced = true;
setState(current => current.phase === 'collapse' ? { ...current, phase: 'count', target: latest.current } : current);
};
// `finished` rejects when an animation is cancelled and can stay pending when a
// compositor never runs it to completion, so the promise alone cannot be the only
// way out of this phase. Without a deadline a stalled phase would hold the frame
// source at `shown` and keep the reveal paused, which reads as a frozen turn
// until the view remounts.
const deadline = window.setTimeout(advance, FOLD_TIMING.collapse + FOLD_TIMING.watchdogSlack);
Promise.all(animations.map(animation => animation.finished)).then(advance, advance);
return () => {
cancelled = true;
window.clearTimeout(deadline);
animations.forEach(animation => animation.cancel());
el.dispatchEvent(new CustomEvent('reader-layout-end', { bubbles: true }));
};
}, [state.phase]);
useEffect(() => {
if (state.phase !== 'count' && state.phase !== 'settle' && state.phase !== 'reveal') return;
const phase = state.phase;
let done = false;
const finish = () => {
if (done) return;
done = true;
setState(current => {
if (current.phase !== phase) return current;
if (phase === 'count') return { ...current, phase: 'settle' };
if (phase === 'settle') return { ...current, phase: 'reveal' };
return idle(current.target);
});
};
// Count visible presentation time, not a timer that can expire before a
// busy browser paints. Each attention phase must get actual rendered frames.
let elapsed = 0;
let previous: number | undefined;
let raf = 0;
const tick = (now: number) => {
if (previous !== undefined) elapsed += Math.min(40, now - previous);
previous = now;
if (elapsed < FOLD_TIMING[phase]) { raf = requestAnimationFrame(tick); return; }
finish();
};
raf = requestAnimationFrame(tick);
// A hidden tab gets no frames at all, so the frame counter above would never
// reach its budget and the phase would hold forever. The wall-clock deadline
// advances it anyway; a non-idle phase is what freezes the turn.
const deadline = window.setTimeout(finish, FOLD_TIMING[phase] + FOLD_TIMING.watchdogSlack);
return () => { window.clearTimeout(deadline); cancelAnimationFrame(raf); };
}, [state.phase]);
useLayoutEffect(() => {
if (state.phase !== 'reveal' || !root.current) return;
const el = root.current;
el.dispatchEvent(new CustomEvent('reader-layout-start', { bubbles: true }));
// Opacity alone still inserts the new layout in one frame. Open real space
// first; text stays paused until this entry finishes, then catches up.
const animations = Array.from(el.querySelectorAll<HTMLElement>(FLOW_CELLS))
.filter(child => !child.hidden && !state.beforeKeys.has(child.dataset.flowKey!))
.map(child => child.animate([
{ height: '0px', opacity: 0 },
{ height: `${child.getBoundingClientRect().height}px`, opacity: 1 },
], { duration: FOLD_TIMING.reveal, easing: 'cubic-bezier(.4,0,.2,1)', fill: 'both' }));
return () => {
animations.forEach(animation => animation.cancel());
el.dispatchEvent(new CustomEvent('reader-layout-end', { bubbles: true }));
};
}, [state.phase]);
const blocked = state.phase === 'collapse' || state.phase === 'count' || state.phase === 'settle';
const source = state.phase === 'idle' || state.phase === 'collapse' ? state.shown : state.target;
const rows = state.phase === 'collapse' ? collapseRows(state.shown.items, state.target.items) : flowRows(source.items);
const cells = rows.map(row => {
if (row.kind === 'summary') return { row, key: row.key, hidden: false, process: true };
const node = row.step.kind === 'other' ? source.snapshot.nodes.get(row.step.nodeKey) : undefined;
const trigger = !!status && node?.kind === 'turn-trigger';
const process = row.step.kind === 'reasoning' || row.step.kind === 'tool' || trigger
|| (row.step.kind === 'other' && row.step.process === true && node?.kind !== 'turn-trigger');
const hidden = (trigger && !processOpen) || !!row.foldKey && (!processOpen || !open[row.foldKey])
|| (blocked && state.phase !== 'collapse' && !state.beforeKeys.has(row.key));
return { row, key: row.key, hidden, process: processOpen && process };
});
const header = { row: null, key: 'process-status', hidden: false, process: true };
const groups = groupProcessRows(status ? [header, ...cells] : cells);
const renderCell = ({ row, hidden, process }: { row: FlowRow; hidden: boolean; process: boolean }) => {
if (row.kind === 'summary') return <FlowCell key={row.key} rowKey={row.key} hidden={false} instant motion={motion} summary process={process}>
<Summary item={row.item} open={processOpen && !!open[row.key]} onChange={value => onOpenChange(row.key, value)} motion={motion && state.phase !== 'collapse'} />
</FlowCell>;
return <FlowCell key={row.key} rowKey={row.key} hidden={hidden} instant={state.phase !== 'idle'} motion={motion} process={process}>
{renderStep(row.step, !!row.foldKey)}
</FlowCell>;
};
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, 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>}
<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 }))}
</ProcessScroll>
</div>;
})}
</div>
</StreamMotionContext.Provider>
</FlowSnapshot.Provider>;
}