π€― 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(agent-builder): prevent suggestion refresh on autosave (#16554)
Arvin Xud4e7cb34973a
diff --git a/src/features/AgentBuilder/SuggestionChips/index.tsx b/src/features/AgentBuilder/SuggestionChips/index.tsxindex 03a356d1c19..de0daa67843 100644--- a/src/features/AgentBuilder/SuggestionChips/index.tsx+++ b/src/features/AgentBuilder/SuggestionChips/index.tsx@@ -104,7 +104,7 @@ interface SuggestionChipsProps {const SuggestionChips = memo<SuggestionChipsProps>(({ mode, builderAgentId, count = 3, disabled }) => {const { t: tCommon } = useTranslation('common');- const { contextSummary, generationMode, locale } = useBuilderContext(mode);+ const { contextSummary, generationMode, locale, targetId } = useBuilderContext(mode);const builderConfig = useAgentStore((s) =>agentByIdSelectors.getAgentConfigById(builderAgentId)(s),@@ -120,6 +120,7 @@ const SuggestionChips = memo<SuggestionChipsProps>(mode: generationMode,model: model ?? '',provider: provider ?? '',+ targetId,});// First load with nothing to show yet β card-shaped skeleton that keeps thediff --git a/src/features/AgentBuilder/SuggestionChips/useBuilderContext.ts b/src/features/AgentBuilder/SuggestionChips/useBuilderContext.tsindex c7a5e06479a..0fb2e120997 100644--- a/src/features/AgentBuilder/SuggestionChips/useBuilderContext.ts+++ b/src/features/AgentBuilder/SuggestionChips/useBuilderContext.ts@@ -61,6 +61,7 @@ export interface BuilderContext {contextSummary: string;generationMode: BuilderSuggestionMode;locale: string;+ targetId?: string;}/**@@ -88,5 +89,10 @@ export const useBuilderContext = (mode: SuggestMode): BuilderContext => {[isGroup, agentItem, group],);- return { contextSummary, generationMode: isGroup ? 'group' : 'agent', locale: i18n.language };+ return {+ contextSummary,+ generationMode: isGroup ? 'group' : 'agent',+ locale: i18n.language,+ targetId: isGroup ? activeGroupId : activeAgentId,+ };};diff --git a/src/features/AgentBuilder/SuggestionChips/useBuilderSuggestions.test.tsx b/src/features/AgentBuilder/SuggestionChips/useBuilderSuggestions.test.tsxnew file mode 100644index 00000000000..c5a94aaa012--- /dev/null+++ b/src/features/AgentBuilder/SuggestionChips/useBuilderSuggestions.test.tsx@@ -0,0 +1,140 @@+import { act, renderHook, waitFor } from '@testing-library/react';+import type { PropsWithChildren } from 'react';+import { createElement } from 'react';+import { SWRConfig } from 'swr';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { aiChatService } from '@/services/aiChat';++import { useBuilderSuggestions } from './useBuilderSuggestions';++type GenerateJSONResult = Awaited<ReturnType<typeof aiChatService.generateJSON>>;+type RecordTracingFeedbackResult = Awaited<ReturnType<typeof aiChatService.recordTracingFeedback>>;++const makeEnvelope = (label: string) =>+ ({+ data: {+ suggestions: [+ {+ prompt: `${label} prompt`,+ title: `${label} title`,+ },+ ],+ },+ tracingId: `trace-${label}`,+ }) as GenerateJSONResult;++const baseParams = {+ builderAgentId: 'builder-agent',+ contextSummary: 'initial context',+ enabled: true,+ locale: 'zh-CN',+ mode: 'agent',+ model: 'model-a',+ provider: 'provider-a',+ targetId: 'target-agent',+} satisfies Parameters<typeof useBuilderSuggestions>[0];++const createSWRWrapper = () => {+ const value = { provider: () => new Map() };++ return function SWRTestWrapper({ children }: PropsWithChildren) {+ return createElement(SWRConfig, { value }, children);+ };+};++const waitForNextTick = async () => {+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 0));+ });+};++const getGeneratedUserContent = (callIndex: number) => {+ const [params] = vi.mocked(aiChatService.generateJSON).mock.calls[callIndex];+ const userMessage = params.messages.find((message) => message.role === 'user');++ return String(userMessage?.content ?? '');+};++describe('useBuilderSuggestions', () => {+ beforeEach(() => {+ vi.restoreAllMocks();+ vi.spyOn(aiChatService, 'generateJSON').mockResolvedValue(makeEnvelope('first'));+ vi.spyOn(aiChatService, 'recordTracingFeedback').mockResolvedValue({+ ok: true,+ } as RecordTracingFeedbackResult);+ });++ it('does not regenerate when autosave updates context for the same target', async () => {+ const { rerender, result } = renderHook((props) => useBuilderSuggestions(props), {+ initialProps: baseParams,+ wrapper: createSWRWrapper(),+ });++ await waitFor(() => {+ expect(result.current.suggestions[0]?.title).toBe('first title');+ });+ expect(aiChatService.generateJSON).toHaveBeenCalledTimes(1);++ rerender({ ...baseParams, contextSummary: 'autosaved updated context' });+ await waitForNextTick();++ expect(aiChatService.generateJSON).toHaveBeenCalledTimes(1);+ expect(result.current.suggestions[0]?.title).toBe('first title');+ });++ it('uses the latest context when the user manually refreshes suggestions', async () => {+ vi.mocked(aiChatService.generateJSON)+ .mockResolvedValueOnce(makeEnvelope('first'))+ .mockResolvedValueOnce(makeEnvelope('second'));++ const { rerender, result } = renderHook((props) => useBuilderSuggestions(props), {+ initialProps: baseParams,+ wrapper: createSWRWrapper(),+ });++ await waitFor(() => {+ expect(result.current.suggestions[0]?.title).toBe('first title');+ });++ rerender({ ...baseParams, contextSummary: 'manual refresh context' });++ act(() => {+ result.current.refresh();+ });++ await waitFor(() => {+ expect(aiChatService.generateJSON).toHaveBeenCalledTimes(2);+ });++ expect(getGeneratedUserContent(1)).toContain('manual refresh context');+ expect(result.current.suggestions[0]?.title).toBe('second title');+ });++ it('regenerates when the edited target changes', async () => {+ vi.mocked(aiChatService.generateJSON)+ .mockResolvedValueOnce(makeEnvelope('first'))+ .mockResolvedValueOnce(makeEnvelope('second'));++ const { rerender, result } = renderHook((props) => useBuilderSuggestions(props), {+ initialProps: baseParams,+ wrapper: createSWRWrapper(),+ });++ await waitFor(() => {+ expect(result.current.suggestions[0]?.title).toBe('first title');+ });++ rerender({+ ...baseParams,+ contextSummary: 'new target context',+ targetId: 'target-agent-2',+ });++ await waitFor(() => {+ expect(aiChatService.generateJSON).toHaveBeenCalledTimes(2);+ });++ expect(getGeneratedUserContent(1)).toContain('new target context');+ });+});diff --git a/src/features/AgentBuilder/SuggestionChips/useBuilderSuggestions.ts b/src/features/AgentBuilder/SuggestionChips/useBuilderSuggestions.tsindex 2066d7a0657..a0a55b72ed6 100644--- a/src/features/AgentBuilder/SuggestionChips/useBuilderSuggestions.ts+++ b/src/features/AgentBuilder/SuggestionChips/useBuilderSuggestions.ts@@ -9,6 +9,7 @@ import {import { useCallback, useState } from 'react';import useSWR from 'swr';+import { swrKeys } from '@/libs/swr/keys';import { aiChatService } from '@/services/aiChat';import { useBuilderSuggestionFeedbackStore } from './feedbackStore';@@ -22,6 +23,8 @@ interface UseBuilderSuggestionsParams {mode: BuilderSuggestionMode;model: string;provider: string;+ /** Agent/group currently being edited. Config autosaves for the same target must not regenerate. */+ targetId?: string;}interface BuilderSuggestionsResult {@@ -46,19 +49,27 @@ export const useBuilderSuggestions = ({provider,locale,enabled,+ targetId,}: UseBuilderSuggestionsParams): BuilderSuggestionsResult => {- // Bumping the nonce forces a fresh generation (SWR key change) on refresh.+ // Bumping the nonce forces a fresh generation (SWR key change) on manual refresh.const [nonce, setNonce] = useState(0);const markRegenerated = useBuilderSuggestionFeedbackStore((s) => s.markRegenerated);+ // Key on target identity only β the context summary is deliberately kept out of+ // the key so config autosaves (which stream in new summaries for the same target)+ // don't refetch. Only a target switch or a nonce bump regenerates; the fetcher+ // closure reads the current summary, which is always the latest value on the+ // render that changes the key.const key =enabled && contextSummary && model && provider- ? (['builder-suggestion', mode, builderAgentId, contextSummary, nonce] as const)+ ? swrKeys.agentBuilder.suggestions(mode, builderAgentId, targetId, nonce): null;const { data, isLoading, error } = useSWR(key,async () => {+ // Read mode/context/agent from the closure: SWR runs the fetcher from the+ // render that changed the key, so these already hold the latest values.const { messages, schema } = chainBuilderSuggestion({ contextSummary, locale, mode });const abortController = new AbortController();const envelope = (await aiChatService.generateJSON(diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 46e9aeed3d5..f26c4ee2d04 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -90,6 +90,23 @@ export const agentKeys = {list: def('agent:list', (isLogin: boolean) => ['agent:list', isLogin]),};+// ---- agent builder (opening-suggestion chips) ---------------------------+// Kept off `CACHE_TIERS` on purpose β these are ephemeral LLM-generated chips.+// `contextSummary` is intentionally NOT part of the key so config autosaves for+// the same target don't refetch; `nonce` bumps on manual refresh.+export const agentBuilderKeys = {+ suggestions: def(+ 'agentBuilder:suggestions',+ (mode: string, builderAgentId: string, targetId: string | undefined, nonce: number) => [+ 'agentBuilder:suggestions',+ mode,+ builderAgentId,+ targetId,+ nonce,+ ],+ ),+};+// ---- group --------------------------------------------------------------export const groupKeys = {detail: def('group:detail', (groupId: string) => ['group:detail', groupId]),@@ -845,6 +862,7 @@ export const matchDomain =export const swrKeys = {agent: { ...agentKeys, ...agentConfigKeys },agentBot: agentBotKeys,+ agentBuilder: agentBuilderKeys,agentDocument: agentDocumentSWRKeys,agentHome: agentHomeKeys,agentKnowledge: agentKnowledgeKeys,