🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(chat): keep reloaded image tool cards expanded and still (#21626)
YuTengjing53192d1b0d35
diff --git a/packages/builtin-tool-image-generation/src/client/components/ImageCanvas.tsx b/packages/builtin-tool-image-generation/src/client/components/ImageCanvas.tsxindex c34aef6b6f6..9f9dabc51cf 100644--- a/packages/builtin-tool-image-generation/src/client/components/ImageCanvas.tsx+++ b/packages/builtin-tool-image-generation/src/client/components/ImageCanvas.tsx@@ -1,11 +1,12 @@'use client';-import { Image } from '@lobehub/ui';-import { createStaticStyles, cssVar, cx, keyframes } from '@lobehub/ui';+import { createStaticStyles, cssVar, cx, Image, keyframes } from '@lobehub/ui';import type { CSSProperties, ReactNode } from 'react';import { memo, useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';+import { useDevelopsOnMount } from './useDevelopsOnMount';+// Three colour blobs wander on independent, co-prime loops so the aura never// visibly repeats.const wanderA = keyframes`@@ -183,6 +184,9 @@ const styles = createStaticStyles(({ css, cssVar }) => ({`,revealed: css`opacity: 1;+ `,+ revealedDevelop: css`+ opacity: 1;animation: ${develop} 1100ms cubic-bezier(0.2, 0, 0, 1) both;@media (prefers-reduced-motion: reduce) {@@ -257,6 +261,7 @@ export const ImageCanvas = memo<ImageCanvasProps>(const { t } = useTranslation('plugin');const [loadedUrl, setLoadedUrl] = useState<string>();const loaded = !!url && loadedUrl === url;+ const develops = useDevelopsOnMount(url, startedAt);const generating = !url && !children;const elapsed = useElapsedSeconds(generating ? startedAt : undefined);// Computed once per mount: recomputing on every re-render would restart the loops.@@ -272,21 +277,28 @@ export const ImageCanvas = memo<ImageCanvasProps>(return (<div className={styles.canvas} style={{ aspectRatio: ratio }}>- <div- aria-hidden- className={cx(styles.aura, loaded && styles.auraHidden, !!children && styles.auraStill)}- >- <div className={styles.layer} style={auraLayerStyle}>- <div className={styles.auraFocus}>- <span className={styles.blobA} />- <span className={styles.blobB} />- <span className={styles.blobC} />+ {develops && (+ <div+ aria-hidden+ className={cx(styles.aura, loaded && styles.auraHidden, !!children && styles.auraStill)}+ >+ <div className={styles.layer} style={auraLayerStyle}>+ <div className={styles.auraFocus}>+ <span className={styles.blobA} />+ <span className={styles.blobB} />+ <span className={styles.blobC} />+ </div></div>+ <div className={styles.grain} /></div>- <div className={styles.grain} />- </div>+ )}{url && (- <div className={cx(styles.reveal, loaded && styles.revealed)}>+ <div+ className={cx(+ styles.reveal,+ develops ? loaded && styles.revealedDevelop : styles.revealed,+ )}+ ><Imagealt={alt}className={styles.image}diff --git a/packages/builtin-tool-image-generation/src/client/components/useDevelopsOnMount.test.ts b/packages/builtin-tool-image-generation/src/client/components/useDevelopsOnMount.test.tsnew file mode 100644index 00000000000..518423ab2fd--- /dev/null+++ b/packages/builtin-tool-image-generation/src/client/components/useDevelopsOnMount.test.ts@@ -0,0 +1,30 @@+import { renderHook } from '@testing-library/react';+import { describe, expect, it } from 'vitest';++import { useDevelopsOnMount } from './useDevelopsOnMount';++const URL = 'https://example.com/image.png';++describe('useDevelopsOnMount', () => {+ it('skips the develop motion for a history image known at mount', () => {+ const { result } = renderHook(() => useDevelopsOnMount(URL));++ expect(result.current).toBe(false);+ });++ it('keeps the develop motion when the image lands after mount', () => {+ const { rerender, result } = renderHook(({ url }) => useDevelopsOnMount(url), {+ initialProps: { url: undefined as string | undefined },+ });++ rerender({ url: URL });++ expect(result.current).toBe(true);+ });++ it('keeps the develop motion when this session watched the generation start', () => {+ const { result } = renderHook(() => useDevelopsOnMount(URL, Date.now() - 1000));++ expect(result.current).toBe(true);+ });+});diff --git a/packages/builtin-tool-image-generation/src/client/components/useDevelopsOnMount.ts b/packages/builtin-tool-image-generation/src/client/components/useDevelopsOnMount.tsnew file mode 100644index 00000000000..06f6437f4f5--- /dev/null+++ b/packages/builtin-tool-image-generation/src/client/components/useDevelopsOnMount.ts@@ -0,0 +1,14 @@+import { useState } from 'react';++/**+ * Whether a canvas should develop its image out of the generating aura.+ *+ * Decided once at mount: only a canvas that saw the generation happen (no image+ * yet, or a generation clock started in this session) plays the motion. A+ * history card mounts with its image already known; replaying the motion on+ * every reload reads as the image being generated again.+ */+export const useDevelopsOnMount = (url?: string, startedAt?: number) => {+ const [develops] = useState(() => !url || !!startedAt);+ return develops;+};diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsxindex 508c2915f44..c0e690d3828 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx@@ -2,7 +2,7 @@ import { getBuiltinRender } from '@lobechat/builtin-tools/renders';import { getBuiltinStreaming } from '@lobechat/builtin-tools/streamings';import { Accordion, Divider, Flexbox, Skeleton } from '@lobehub/ui';import isEqual from 'fast-deep-equal';-import { memo, useEffect, useState } from 'react';+import { memo, useState } from 'react';import SafeBoundary from '@/components/ErrorBoundary';import dynamic from '@/libs/next/dynamic';@@ -13,19 +13,16 @@ import { toolSelectors } from '@/store/tool/selectors';import { dataSelectors, useConversationStore } from '../../../store';import Actions from './Actions';+import Detail from './Detail';import Inspectors from './Inspector';import { hasToolResultBody } from './toolResultBody';+import { useToolExpandState } from './useToolExpandState';const Debug = dynamic(() => import('./Debug'), {loading: () => <Skeleton height={300} width={'100%'} />,ssr: false,});-const Detail = dynamic(() => import('./Detail'), {- loading: () => <Skeleton height={120} width={'100%'} />,- ssr: false,-});-export interface GroupToolProps {assistantMessageId: string;disableEditing?: boolean;@@ -53,17 +50,19 @@ const Tool = memo<GroupToolProps>(({ assistantMessageId, disableEditing, id }) =const renderDisplayControl = useToolStore(toolSelectors.getRenderDisplayControl(identifier, apiName, result?.state),);- const [showDebug, setShowDebug] = useState(false);- const [showToolRender, setShowToolRender] = useState(false);- // Controls switching between custom render and fallback ArgumentRender- const [showCustomToolRender, setShowCustomToolRender] = useState(true);-const isPending = intervention?.status === 'pending';const isReject = intervention?.status === 'rejected';const isAbort = intervention?.status === 'aborted';const needExpand = renderDisplayControl !== 'collapsed' || isPending;const isAlwaysExpand = renderDisplayControl === 'alwaysExpand';+ const { handleExpand, setShowDebug, showDebug, showToolRender } = useToolExpandState({+ isAlwaysExpand,+ needExpand,+ });+ // Controls switching between custom render and fallback ArgumentRender+ const [showCustomToolRender, setShowCustomToolRender] = useState(true);+let isArgumentsStreaming = false;try {JSON.parse(requestArgs || '{}');@@ -102,25 +101,6 @@ const Tool = memo<GroupToolProps>(({ assistantMessageId, disableEditing, id }) =// Only allow toggle when has custom render and not in pending/reject/abort stateconst canToggleCustomToolRender = hasCustomRender && !isPending && !isReject && !isAbort;- // Handle expand state changes- const handleExpand = (expand?: boolean) => {- // Block collapse action when alwaysExpand is set- if (isAlwaysExpand && expand === false) {- return;- }- // When collapsing, also turn off debug mode so the accordion can actually collapse- if (expand === false) {- setShowDebug(false);- }- setShowToolRender(!!expand);- };-- useEffect(() => {- if (needExpand) {- setTimeout(() => handleExpand(true), 100);- }- }, [needExpand]);-if (!tool) return null;const isToolDetailExpand = forceShowStreamingRender || showToolRender || showDebug;diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/useToolExpandState.test.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/useToolExpandState.test.tsnew file mode 100644index 00000000000..b04cd1f44a8--- /dev/null+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/useToolExpandState.test.ts@@ -0,0 +1,80 @@+/**+ * @vitest-environment happy-dom+ */+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { useToolExpandState } from './useToolExpandState';++describe('useToolExpandState', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('starts open on the first render when the card needs expanding', () => {+ const { result } = renderHook(() =>+ useToolExpandState({ isAlwaysExpand: false, needExpand: true }),+ );++ expect(result.current.showToolRender).toBe(true);+ });++ it('stays closed when the card is collapsed by default', () => {+ const { result } = renderHook(() =>+ useToolExpandState({ isAlwaysExpand: false, needExpand: false }),+ );++ act(() => {+ vi.runAllTimers();+ });++ expect(result.current.showToolRender).toBe(false);+ });++ it('opens after a delay when the card starts needing expansion later', () => {+ const { rerender, result } = renderHook(+ ({ needExpand }) => useToolExpandState({ isAlwaysExpand: false, needExpand }),+ { initialProps: { needExpand: false } },+ );++ rerender({ needExpand: true });+ expect(result.current.showToolRender).toBe(false);++ act(() => {+ vi.advanceTimersByTime(100);+ });+ expect(result.current.showToolRender).toBe(true);+ });++ it('ignores collapse requests on an always-expanded card', () => {+ const { result } = renderHook(() =>+ useToolExpandState({ isAlwaysExpand: true, needExpand: true }),+ );++ act(() => {+ result.current.handleExpand(false);+ });++ expect(result.current.showToolRender).toBe(true);+ });++ it('turns debug off when collapsing', () => {+ const { result } = renderHook(() =>+ useToolExpandState({ isAlwaysExpand: false, needExpand: true }),+ );++ act(() => {+ result.current.setShowDebug(true);+ });+ act(() => {+ result.current.handleExpand(false);+ });++ expect(result.current.showDebug).toBe(false);+ expect(result.current.showToolRender).toBe(false);+ });+});diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/useToolExpandState.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/useToolExpandState.tsnew file mode 100644index 00000000000..f4661cce12c--- /dev/null+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/useToolExpandState.ts@@ -0,0 +1,42 @@+import { useCallback, useEffect, useState } from 'react';++const AUTO_EXPAND_DELAY = 100;++interface ToolExpandStateOptions {+ /** The manifest forbids collapsing this card. */+ isAlwaysExpand: boolean;+ /** The card should show its detail without a click (manifest default or pending intervention). */+ needExpand: boolean;+}++/**+ * Expand state of one tool card.+ *+ * A card that needs expanding at mount starts open, so a reloaded history card+ * renders expanded right away instead of flashing collapsed and animating open.+ * A card that only starts needing it later (e.g. an intervention turns pending)+ * still opens after a short delay.+ */+export const useToolExpandState = ({ isAlwaysExpand, needExpand }: ToolExpandStateOptions) => {+ const [showDebug, setShowDebug] = useState(false);+ const [showToolRender, setShowToolRender] = useState(needExpand);++ const handleExpand = useCallback(+ (expand?: boolean) => {+ // Block collapse action when alwaysExpand is set+ if (isAlwaysExpand && expand === false) return;+ // When collapsing, also turn off debug mode so the accordion can actually collapse+ if (expand === false) setShowDebug(false);+ setShowToolRender(!!expand);+ },+ [isAlwaysExpand],+ );++ useEffect(() => {+ if (!needExpand) return;+ const timer = setTimeout(() => setShowToolRender(true), AUTO_EXPAND_DELAY);+ return () => clearTimeout(timer);+ }, [needExpand]);++ return { handleExpand, setShowDebug, showDebug, showToolRender };+};