Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

Revert "Merge pull request #7278 from makecindy/dash/chat-open-scroll-jump"

MagicLiziadc2626f870b
diff --git a/apps/desktop/scripts/fixtures/message-follow/fixture.tsx b/apps/desktop/scripts/fixtures/message-follow/fixture.tsx
deleted file mode 100644
index d41d1bafec..0000000000
--- a/apps/desktop/scripts/fixtures/message-follow/fixture.tsx
+++ /dev/null
@@ -1,140 +0,0 @@
-import { useLayoutEffect, useRef, useState } from 'react';
-import { mountPage } from '../../ui-page/harness';
-import {
- MessageViewport,
- type MessageViewportApi,
-} from '../../../src/renderer/components/chat/MessageViewport';
-import { useSmoothMessageFollow } from '../../../src/renderer/components/chat/useSmoothMessageFollow';
-import { Button } from '../../../src/renderer/components/ui/button';
-
-const entries = Array.from({ length: 100 }, (_, index) => ({
- key: String(index),
- retain: index === 99,
-}));
-
-function Thread() {
- const scroll = useRef<HTMLDivElement>(null);
- const items = useRef<HTMLDivElement>(null);
- const following = useRef(true);
- const viewport = useRef<MessageViewportApi>(null);
- const follow = useSmoothMessageFollow(scroll, items);
- const [lines, setLines] = useState(1);
- const [bottomPadding, setBottomPadding] = useState(0);
- const [initialMotion, setInitialMotion] = useState<number | null>(null);
- // Like MessageStream's composer reservation, this measurement lands in a
- // second layout commit, after the first pin but before the first paint.
- useLayoutEffect(() => {
- setBottomPadding(120);
- }, []);
- useLayoutEffect(() => {
- viewport.current?.connect();
- });
- useLayoutEffect(() => {
- follow();
- viewport.current?.reconcileViewport();
- }, [follow, lines, bottomPadding]);
- useLayoutEffect(() => {
- const observer = new ResizeObserver(() => {
- if (!following.current) return;
- follow();
- viewport.current?.syncViewport();
- });
- observer.observe(items.current!);
- return () => observer.disconnect();
- }, [follow]);
- useLayoutEffect(() => {
- let count = 0,
- max = 0,
- frame: number;
- const measure = () => {
- const transform = getComputedStyle(items.current!).transform;
- max = Math.max(
- max,
- transform === 'none' ? 0 : Math.abs(new DOMMatrixReadOnly(transform).m42),
- );
- if (++count < 20) frame = requestAnimationFrame(measure);
- else setInitialMotion(max);
- };
- frame = requestAnimationFrame(measure);
- return () => cancelAnimationFrame(frame);
- }, []);
- return (
- <>
- <div className="flex items-center gap-4 px-6 py-3 border-b border-border">
- <span className="text-sm text-muted-foreground">任务消息</span>
- <Button variant="outline" size="sm" onClick={() => setLines((value) => value + 1)}>
- 追加进展
- </Button>
- <output hidden data-initial-motion={initialMotion ?? ''} />
- </div>
- <div
- ref={scroll}
- data-thread-scroll
- className="h-[420px] overflow-y-auto"
- onWheel={() => {
- following.current = false;
- }}
- >
- <MessageViewport
- apiRef={viewport}
- options={{
- entries,
- scrollRef: scroll,
- itemsRef: items,
- followRef: following,
- disabled: false,
- }}
- >
- {(view) => (
- <div
- ref={items}
- data-thread-items
- className="flex flex-col gap-4 p-6"
- style={{ paddingBottom: bottomPadding }}
- >
- {entries.map((entry) =>
- !view.shouldMount(entry) ? (
- <div
- key={entry.key}
- data-render-item-key={entry.key}
- data-message-placeholder
- style={{ height: view.placeholderHeight(entry.key), flexShrink: 0 }}
- />
- ) : (
- <div
- key={entry.key}
- data-render-item-key={entry.key}
- className="text-sm leading-6"
- >
- <div className="text-muted-foreground">工作记录 {Number(entry.key) + 1}</div>
- <p>正在核对任务结果,完成后继续下一步。</p>
- {entry.key === '99' &&
- Array.from({ length: lines }, (_, index) => (
- <p key={index}>已验证第 {index + 1} 项结果。</p>
- ))}
- </div>
- ),
- )}
- </div>
- )}
- </MessageViewport>
- </div>
- </>
- );
-}
-
-function Fixture() {
- const [generation, setGeneration] = useState(0);
- return (
- <div data-ui-page-subject>
- <div className="p-4">
- <Button variant="outline" onClick={() => setGeneration((value) => value + 1)}>
- 重新打开任务
- </Button>
- </div>
- <Thread key={generation} />
- </div>
- );
-}
-
-void mountPage({ render: () => <Fixture /> });
diff --git a/apps/desktop/scripts/fixtures/message-follow/ui-page.mjs b/apps/desktop/scripts/fixtures/message-follow/ui-page.mjs
deleted file mode 100644
index 26957385e4..0000000000
--- a/apps/desktop/scripts/fixtures/message-follow/ui-page.mjs
+++ /dev/null
@@ -1,63 +0,0 @@
-import assert from 'node:assert/strict';
-
-export default {
- name: 'message-follow',
- entry: './fixture.tsx',
- viewport: { width: 800, height: 560 },
- real: 'useSmoothMessageFollow, MessageViewport and native ResizeObserver with 100 variable-height rows',
- notCovered: 'Full MessageStream, remote history loading, rich cards and account data',
- cases: {
- default: {
- about: 'Initial virtualized layout and reopening stay still; later content follows smoothly',
- },
- },
- async ready(page) {
- // The screenshot harness defaults to reduced motion; this regression needs
- // actual compositor animation, including on the first mounted frame.
- await page.emulateMedia({ reducedMotion: 'no-preference' });
- await page.getByRole('button', { name: '重新打开任务', exact: true }).click();
- await page.waitForFunction(
- () =>
- document.querySelector('[data-initial-motion]')?.getAttribute('data-initial-motion') !== '',
- );
- },
- async check(page, ui) {
- const assertInitial = async () => {
- await page.waitForFunction(
- () =>
- document.querySelector('[data-initial-motion]')?.getAttribute('data-initial-motion') !==
- '',
- );
- assert.ok(
- Number(await page.locator('[data-initial-motion]').getAttribute('data-initial-motion')) < 1,
- 'initial layout must not replay as a follow animation',
- );
- };
- await assertInitial();
- await page.getByRole('button', { name: '重新打开任务', exact: true }).click();
- await assertInitial();
- await ui.capture('reopened');
- const didAnimate = await page.evaluate(async () => {
- const content = document.querySelector('[data-thread-items]');
- document.querySelectorAll('button')[1].click();
- for (let frame = 0; frame < 12; frame++) {
- await new Promise(requestAnimationFrame);
- if (content.getAnimations().some((animation) => animation.playState === 'running'))
- return true;
- }
- return false;
- });
- assert.equal(didAnimate, true, 'later content still follows smoothly');
- await page.waitForFunction(() => {
- const el = document.querySelector('[data-thread-scroll]');
- return (
- Math.abs(el.scrollHeight - el.clientHeight - el.scrollTop) < 1 &&
- !document
- .querySelector('[data-thread-items]')
- .getAnimations()
- .some((animation) => animation.playState === 'running')
- );
- });
- await ui.capture('new-content');
- },
-};
diff --git a/apps/desktop/src/renderer/__tests__/smoothMessageFollow.test.tsx b/apps/desktop/src/renderer/__tests__/smoothMessageFollow.test.tsx
deleted file mode 100644
index 96ccf3b0f3..0000000000
--- a/apps/desktop/src/renderer/__tests__/smoothMessageFollow.test.tsx
+++ /dev/null
@@ -1,178 +0,0 @@
-/** @vitest-environment jsdom */
-import { act, useLayoutEffect, useRef } from 'react';
-import { createRoot, type Root } from 'react-dom/client';
-import { afterEach, beforeEach, expect, it, vi } from 'vitest';
-import { useSmoothMessageFollow } from '../components/chat/useSmoothMessageFollow';
-
-// Regression: reopening a long running task animated its initial layout by 452px.
-// The virtualizer tests do not mount the real follow hook. This unit fixture
-// exercises repeated initial pins, later streaming and gesture/lifecycle takeover.
-let host: HTMLDivElement;
-let root: Root;
-let follow: () => void;
-let height: number;
-let top: number;
-let frames: Map<number, FrameRequestCallback>;
-let sequence: number;
-let reduced: boolean;
-const cancel = vi.fn();
-const animate = vi.fn((_frames: Keyframe[], _options: KeyframeAnimationOptions) => ({
- cancel,
- playState: 'running',
- startTime: 0,
-}));
-
-function Fixture({ active = true, loaded = true }: { active?: boolean; loaded?: boolean }) {
- const scrollRef = useRef<HTMLDivElement>(null);
- const contentRef = useRef<HTMLDivElement>(null);
- follow = useSmoothMessageFollow(scrollRef, contentRef, active);
- useLayoutEffect(() => {
- Object.defineProperties(scrollRef.current!, {
- scrollHeight: { configurable: true, get: () => height },
- clientHeight: { configurable: true, get: () => 600 },
- scrollTop: {
- configurable: true,
- get: () => top,
- set: (value: number) => {
- top = Math.max(0, Math.min(value, height - 600));
- },
- },
- });
- contentRef.current!.animate = animate as unknown as HTMLElement['animate'];
- follow();
- }, [active, loaded]);
- return (
- <div ref={scrollRef}>
- <div ref={contentRef}>{loaded ? 'Message' : null}</div>
- </div>
- );
-}
-
-async function frame() {
- const pending = [...frames.values()];
- frames.clear();
- await act(async () => pending.forEach((callback) => callback(performance.now())));
-}
-async function settle() {
- await frame();
- await frame();
-}
-async function grow(value: number) {
- height = value;
- await act(async () => follow());
-}
-
-beforeEach(() => {
- (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
- frames = new Map();
- sequence = 0;
- height = 2000;
- top = 0;
- reduced = false;
- animate.mockClear();
- cancel.mockClear();
- vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
- frames.set(++sequence, callback);
- return sequence;
- });
- vi.stubGlobal('cancelAnimationFrame', (id: number) => frames.delete(id));
- vi.stubGlobal('matchMedia', () => ({
- matches: reduced,
- addEventListener() {},
- removeEventListener() {},
- }));
- vi.spyOn(window, 'getComputedStyle').mockReturnValue({
- getPropertyValue: (key: string) =>
- key === '--motion-base' ? '200ms' : 'cubic-bezier(0.4, 0, 0.2, 1)',
- } as CSSStyleDeclaration);
- host = document.body.appendChild(document.createElement('div'));
- root = createRoot(host);
-});
-afterEach(async () => {
- await act(async () => root.unmount());
- host.remove();
- vi.restoreAllMocks();
- vi.unstubAllGlobals();
-});
-
-it('pins all initial layout corrections directly, then animates later content', async () => {
- await act(async () => root.render(<Fixture />));
- await grow(2452); // virtualized rows mount again before the first paint
- expect(top).toBe(1852);
- expect(animate).not.toHaveBeenCalled();
- await frame();
- await grow(2372); // ResizeObserver corrects the estimate after that frame
- await frame();
- await grow(2587);
- expect(top).toBe(1987);
- expect(animate).not.toHaveBeenCalled();
- await settle();
- await grow(2627);
- expect(top).toBe(2027);
- expect(animate.mock.calls.at(-1)?.[0]).toEqual([
- { transform: 'translateY(40px)' },
- { transform: 'translateY(0)' },
- ]);
-});
-
-it('does not starve settling when observers repeat an unchanged pin', async () => {
- await act(async () => root.render(<Fixture />));
- await frame();
- await act(async () => follow());
- await frame();
- await grow(2040);
- expect(animate).toHaveBeenCalledTimes(1);
-});
-
-it('keeps a delayed first history page in initial positioning', async () => {
- height = 600;
- await act(async () => root.render(<Fixture loaded={false} />));
- await settle();
- height = 2400;
- await act(async () => root.render(<Fixture />));
- await grow(2452);
- expect(top).toBe(1852);
- expect(animate).not.toHaveBeenCalled();
- await settle();
- await grow(2492);
- expect(animate).toHaveBeenCalledTimes(1);
-});
-
-it('restarts initial positioning after deactivation', async () => {
- await act(async () => root.render(<Fixture />));
- await settle();
- await grow(2040);
- await act(async () => root.render(<Fixture active={false} />));
- expect(cancel).toHaveBeenCalled();
- animate.mockClear();
- await act(async () => root.render(<Fixture />));
- await grow(2600);
- expect(top).toBe(2000);
- expect(animate).not.toHaveBeenCalled();
-});
-
-it('hands the displayed offset to a user gesture without keeping an animation', async () => {
- vi.spyOn(performance, 'now').mockReturnValue(100);
- await act(async () => root.render(<Fixture />));
- await settle();
- await grow(2040);
- await act(async () => host.firstElementChild!.dispatchEvent(new Event('wheel')));
- expect(top).toBeCloseTo(1400, 2);
- expect(cancel).toHaveBeenCalled();
-});
-
-it('keeps reduced motion instantaneous after initial positioning', async () => {
- reduced = true;
- await act(async () => root.render(<Fixture />));
- await settle();
- await grow(2040);
- expect(top).toBe(1440);
- expect(animate).not.toHaveBeenCalled();
-});
-
-it('cancels pending initialization when the stream is deactivated', async () => {
- await act(async () => root.render(<Fixture />));
- await frame();
- await act(async () => root.render(<Fixture active={false} />));
- expect(frames.size).toBe(0);
-});
diff --git a/apps/desktop/src/renderer/components/chat/useSmoothMessageFollow.ts b/apps/desktop/src/renderer/components/chat/useSmoothMessageFollow.ts
index 8685e3f381..015caf5505 100644
--- a/apps/desktop/src/renderer/components/chat/useSmoothMessageFollow.ts
+++ b/apps/desktop/src/renderer/components/chat/useSmoothMessageFollow.ts
@@ -13,14 +13,8 @@ export function useSmoothMessageFollow(
) {
const previousTop = useRef<number | null>(null);
const initialized = useRef(false);
- const initialLayoutFrame = useRef<number | null>(null);
const animation = useRef<Animation | null>(null);
- const trajectory = useRef<{
- offset: number;
- start: number;
- duration: number;
- curve: number[];
- } | null>(null);
+ const trajectory = useRef<{ offset: number; start: number; duration: number; curve: number[] } | null>(null);
const currentOffset = useCallback(() => {
const path = trajectory.current;
@@ -30,10 +24,8 @@ export function useSmoothMessageFollow(
// seeking the running animation (seeking would itself reset its start time).
const progress = Math.min(1, Math.max(0, (performance.now() - path.start) / path.duration));
const [x1, y1, x2, y2] = path.curve;
- const bezier = (t: number, a: number, b: number) =>
- 3 * (1 - t) ** 2 * t * a + 3 * (1 - t) * t ** 2 * b + t ** 3;
- let low = 0,
- high = 1;
+ const bezier = (t: number, a: number, b: number) => 3 * (1 - t) ** 2 * t * a + 3 * (1 - t) * t ** 2 * b + t ** 3;
+ let low = 0, high = 1;
for (let i = 0; i < 16; i++) {
const middle = (low + high) / 2;
if (bezier(middle, x1, x2) < progress) low = middle;
@@ -42,38 +34,28 @@ export function useSmoothMessageFollow(
return path.offset * (1 - bezier((low + high) / 2, y1, y2));
}, []);
- const retarget = useCallback(
- (offset: number) => {
- const content = contentRef.current;
- animation.current?.cancel();
- animation.current = null;
- trajectory.current = null;
- if (!content?.animate || window.matchMedia?.('(prefers-reduced-motion: reduce)').matches)
- return;
- const style = getComputedStyle(content);
- const duration = style.getPropertyValue('--motion-base').trim();
- const milliseconds = Number.parseFloat(duration) * (duration.endsWith('ms') ? 1 : 1000);
- const easing = style.getPropertyValue('--motion-ease-move').trim();
- const curve = /^cubic-bezier\(([^)]+)\)$/.exec(easing)?.[1].split(',').map(Number);
- if (
- !Number.isFinite(milliseconds) ||
- milliseconds <= 0 ||
- curve?.length !== 4 ||
- curve.some((n) => !Number.isFinite(n))
- )
- return;
- const start = performance.now();
- trajectory.current = { offset, start, duration: milliseconds, curve };
- animation.current = content.animate(
- [{ transform: `translateY(${offset}px)` }, { transform: 'translateY(0)' }],
- { duration: milliseconds, easing, fill: 'both' },
- );
- // Pending animations otherwise wait for a compositor acknowledgement and
- // can sit on their first frame while another layout update retargets them.
- animation.current.startTime = start;
- },
- [contentRef],
- );
+ const retarget = useCallback((offset: number) => {
+ const content = contentRef.current;
+ animation.current?.cancel();
+ animation.current = null;
+ trajectory.current = null;
+ if (!content?.animate || window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) return;
+ const style = getComputedStyle(content);
+ const duration = style.getPropertyValue('--motion-base').trim();
+ const milliseconds = Number.parseFloat(duration) * (duration.endsWith('ms') ? 1 : 1000);
+ const easing = style.getPropertyValue('--motion-ease-move').trim();
+ const curve = /^cubic-bezier\(([^)]+)\)$/.exec(easing)?.[1].split(',').map(Number);
+ if (!Number.isFinite(milliseconds) || milliseconds <= 0 || curve?.length !== 4 || curve.some(n => !Number.isFinite(n))) return;
+ const start = performance.now();
+ trajectory.current = { offset, start, duration: milliseconds, curve };
+ animation.current = content.animate([
+ { transform: `translateY(${offset}px)` },
+ { transform: 'translateY(0)' },
+ ], { duration: milliseconds, easing, fill: 'both' });
+ // Pending animations otherwise wait for a compositor acknowledgement and
+ // can sit on their first frame while another layout update retargets them.
+ animation.current.startTime = start;
+ }, [contentRef]);
useLayoutEffect(() => {
if (!active) {
@@ -113,13 +95,7 @@ export function useSmoothMessageFollow(
}
reduced?.addEventListener('change', reduce);
return () => {
- if (initialLayoutFrame.current !== null) cancelAnimationFrame(initialLayoutFrame.current);
- initialLayoutFrame.current = null;
- initialized.current = false;
- previousTop.current = null;
animation.current?.cancel();
- animation.current = null;
- trajectory.current = null;
scroll.removeEventListener('scroll', rememberScroll);
for (const event of ['wheel', 'touchstart', 'pointerdown', 'keydown']) {
scroll.removeEventListener(event, takeOver, true);
@@ -137,24 +113,7 @@ export function useSmoothMessageFollow(
scroll.scrollTop = scroll.scrollHeight;
const delta = scroll.scrollTop - before;
previousTop.current = scroll.scrollTop;
- if (!initialized.current) {
- // A cold history load may leave the mounted list empty for many frames.
- // Its first content still needs initial positioning, not an entrance.
- if (!content.hasChildNodes()) return;
- // A mount can pin several times: estimated rows, their real contents and
- // ResizeObserver corrections all belong to initial positioning. Wait for
- // a painted frame without another correction before animating live growth.
- // Repeated no-op observer pins must not keep postponing that boundary.
- if (initialLayoutFrame.current !== null && Math.abs(delta) < 0.25) return;
- if (initialLayoutFrame.current !== null) cancelAnimationFrame(initialLayoutFrame.current);
- initialLayoutFrame.current = requestAnimationFrame(() => {
- initialLayoutFrame.current = requestAnimationFrame(() => {
- initialLayoutFrame.current = null;
- initialized.current = true;
- });
- });
- return;
- }
+ if (!initialized.current) { initialized.current = true; return; }
if (Math.abs(delta) < 0.25) return;
retarget(offset + delta);
}, [scrollRef, contentRef, currentOffset, retarget, active]);