AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
perf(frontend/copilot): keep pending-answer contexts and actions stable (#15679)
Abhimanyu Yadav0452d1f32c24
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/stable-onsend.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/stable-onsend.test.tsxnew file mode 100644index 0000000000..074ff4028c--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/stable-onsend.test.tsx@@ -0,0 +1,221 @@+import { renderHook, waitFor } from "@/tests/integrations/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++// The page's send handler is one function for the chat host's lifetime, so+// the chat actions context and the composer keep their props while a reply+// streams in; it still runs with the state of the latest render.++const streamState = vi.hoisted(() => ({+ status: "ready" as "ready" | "submitted" | "streaming" | "error",+}));+const flags = vi.hoisted(() => ({ brainDump: false }));++const sendNewMessage = vi.hoisted(() => vi.fn());+const completeGreeting = vi.hoisted(() => vi.fn());+const queueFollowUpMessage = vi.hoisted(() => vi.fn());+const queueMessage = vi.hoisted(() => vi.fn());+const setPendingFileParts = vi.hoisted(() => vi.fn());++vi.mock("@/services/feature-flags/use-get-flag", () => ({+ Flag: {+ CHAT_MODE_OPTION: "chat-mode-option",+ HIRE_EXPERTS: "hire-experts",+ ONBOARDING_BRAIN_DUMP: "onboarding-brain-dump",+ },+ useGetFlag: (flag: string) =>+ flag === "onboarding-brain-dump" ? flags.brainDump : false,+}));++vi.mock("nuqs", () => ({+ parseAsString: {},+ useQueryState: () => [null, vi.fn()],+}));++vi.mock("@/lib/auth/hooks/useAuth", () => ({+ useAuth: () => ({+ user: { id: "user-1" },+ isUserLoading: false,+ isLoggedIn: true,+ }),+}));++vi.mock("@/app/api/__generated__/endpoints/brain-dump/brain-dump", () => ({+ useCompleteBrainDumpGreeting: () => ({ mutate: completeGreeting }),+}));++vi.mock("../useExpertMap", async (importOriginal) => {+ const actual = await importOriginal<typeof import("../useExpertMap")>();+ return {+ ...actual,+ useExpertMap: () => ({+ expertsById: new Map(),+ isLoadingExperts: false,+ hasExpertsSettled: true,+ hasExpertsErrored: false,+ }),+ };+});++vi.mock("../useChatSession", () => ({+ useChatSession: () => ({+ sessionId: "session-1",+ setSessionId: vi.fn(),+ sessionLlmAuthProvider: "platform",+ sessionExpertId: null,+ isAdoptingExpertSession: false,+ hydratedMessages: [],+ rawSessionMessages: [],+ historicalTurnStats: new Map(),+ hasActiveStream: false,+ activeStreamStartedAt: null,+ hasMoreMessages: false,+ oldestSequence: null,+ isLoadingSession: false,+ isSessionError: false,+ createSession: vi.fn(),+ isCreatingSession: false,+ refetchSession: vi.fn(),+ sessionDryRun: false,+ sessionChatStatus: "idle",+ }),+}));++vi.mock("../useCopilotStream", () => ({+ useCopilotStream: () => ({+ messages: [],+ setMessages: vi.fn(),+ sendMessage: vi.fn(),+ stop: vi.fn(),+ status: streamState.status,+ error: undefined,+ isReconnecting: false,+ isFinishProbing: false,+ isRestoringActiveSession: false,+ isSyncing: false,+ isUserStoppingRef: { current: false },+ isUserStopping: false,+ rateLimitMessage: null,+ dismissRateLimit: vi.fn(),+ }),+}));++vi.mock("../useSendMessage", async (importOriginal) => {+ const actual = await importOriginal<typeof import("../useSendMessage")>();+ return {+ ...actual,+ useSendMessage: () => ({+ onSend: sendNewMessage,+ isUploadingFiles: false,+ setPendingFileParts,+ }),+ };+});++vi.mock("../useLoadMoreMessages", () => ({+ useLoadMoreMessages: () => ({+ pagedMessages: [],+ pagedTurnStats: new Map(),+ hasMore: false,+ isLoadingMore: false,+ loadMore: vi.fn(),+ }),+}));++vi.mock("../useCopilotPendingChips", () => ({+ useCopilotPendingChips: () => ({ queuedMessages: [], queueMessage }),+}));++vi.mock("../useCopilotNotifications", () => ({+ useCopilotNotifications: () => undefined,+}));+vi.mock("../useSessionTitlePoll", () => ({+ useSessionTitlePoll: () => undefined,+}));+vi.mock("../useExpertKickoff", () => ({+ useExpertKickoff: () => ({ isKickoffStarting: false }),+}));+vi.mock("../helpers/queueFollowUpMessage", () => ({ queueFollowUpMessage }));++import { useCopilotUIStore } from "../store";+import { useCopilotPage } from "../useCopilotPage";++beforeEach(() => {+ streamState.status = "ready";+ flags.brainDump = false;+ sendNewMessage.mockResolvedValue(undefined);+ queueFollowUpMessage.mockResolvedValue(undefined);+ useCopilotUIStore.getState().setInitialPrompt(null);+});++afterEach(() => {+ vi.clearAllMocks();+ window.sessionStorage.clear();+ window.localStorage.clear();+});++describe("useCopilotPage — stable onSend", () => {+ it("keeps one onSend and onEnqueue across re-renders", () => {+ const { result, rerender } = renderHook(() => useCopilotPage());+ const { onSend, onEnqueue } = result.current;+ expect(onEnqueue).toBe(onSend);++ streamState.status = "streaming";+ rerender();+ streamState.status = "ready";+ rerender();++ expect(result.current.onSend).toBe(onSend);+ expect(result.current.onEnqueue).toBe(onSend);+ });++ it("sends with the latest render's state from a handler kept since mount", async () => {+ const { result, rerender } = renderHook(() => useCopilotPage());+ const keptOnSend = result.current.onSend;++ flags.brainDump = true;+ rerender();+ await keptOnSend("hello");++ expect(completeGreeting).toHaveBeenCalledTimes(1);+ expect(sendNewMessage).toHaveBeenCalledWith(+ "hello",+ undefined,+ undefined,+ undefined,+ );+ });++ it("queues a follow-up through the kept handler once a turn is running", async () => {+ const { result, rerender } = renderHook(() => useCopilotPage());+ const keptOnSend = result.current.onSend;++ streamState.status = "streaming";+ rerender();+ await keptOnSend("and also this");++ expect(queueFollowUpMessage).toHaveBeenCalledWith(+ "session-1",+ "and also this",+ );+ expect(queueMessage).toHaveBeenCalledWith("and also this");+ expect(sendNewMessage).not.toHaveBeenCalled();+ });++ it("still auto-submits a workflow import prompt that lands after mount", async () => {+ const { rerender } = renderHook(() => useCopilotPage());+ expect(sendNewMessage).not.toHaveBeenCalled();++ window.sessionStorage.setItem("importWorkflowPrompt", "Import this");+ window.sessionStorage.setItem("importWorkflowAutosubmit", "true");+ rerender();++ await waitFor(() =>+ expect(sendNewMessage).toHaveBeenCalledWith(+ "Import this",+ undefined,+ undefined,+ undefined,+ ),+ );+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/PendingAnswerContexts.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/PendingAnswerContexts.tsxindex a37ffd258f..38d3890470 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/PendingAnswerContexts.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/PendingAnswerContexts.tsx@@ -1,7 +1,9 @@"use client";import type { UIDataTypes, UIMessage, UITools } from "ai";-import { getHeldOutcomes } from "../heldCallRows";+import isEqual from "lodash/isEqual";+import { useMemo, useState } from "react";+import { getHeldOutcomes, type HeldOutcome } from "../heldCallRows";import { HeldOutcomesContext } from "../HeldOutcomesContext";import { getPendingOnboardingCallId } from "../../ExpertOnboardingCard/helpers";import { PendingOnboardingContext } from "../../ExpertOnboardingCard/PendingOnboardingContext";@@ -15,17 +17,34 @@ interface Props {children: React.ReactNode;}+const NO_HELD_OUTCOMES: ReadonlyMap<string, HeldOutcome> = new Map();+/** What the session is still waiting on the user for: the clarifying-question* dock, the hire's onboarding card, a held call's row and a Paused card each* decide from here whether they are live or already history, rather than* from local state a reload would lose. */export function PendingAnswerContexts({ messages, children }: Props) {+ // The questions and held outcomes are rebuilt as new objects on every call,+ // and `messages` changes on every streamed flush, so each one keeps the+ // object it last published while its content is the same; otherwise every+ // consumer re-renders on every flush. The onboarding call id is a string+ // and the pause is the part's own `data` object (cards compare it by+ // reference), so both are passed through as they are.+ const pendingQuestions = useEqualValue(+ useMemo(() => getPendingQuestions(messages), [messages]),+ );+ const heldOutcomes = useEqualValue(+ useMemo(() => {+ const outcomes = getHeldOutcomes(messages);+ return outcomes.size === 0 ? NO_HELD_OUTCOMES : outcomes;+ }, [messages]),+ );return (- <PendingQuestionsContext.Provider value={getPendingQuestions(messages)}>+ <PendingQuestionsContext.Provider value={pendingQuestions}><PendingOnboardingContext.Providervalue={getPendingOnboardingCallId(messages)}>- <HeldOutcomesContext.Provider value={getHeldOutcomes(messages)}>+ <HeldOutcomesContext.Provider value={heldOutcomes}><CurrentPauseContext.Provider value={getCurrentPause(messages)}>{children}</CurrentPauseContext.Provider>@@ -34,3 +53,12 @@ export function PendingAnswerContexts({ messages, children }: Props) {</PendingQuestionsContext.Provider>);}++// Kept in state, not a ref: a render React throws away cannot change it.+// Setting state while rendering re-runs this component before it commits.+function useEqualValue<T>(value: T): T {+ const [kept, setKept] = useState(() => value);+ if (kept === value || isEqual(kept, value)) return kept;+ setKept(() => value);+ return value;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/PendingAnswerContexts.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/PendingAnswerContexts.test.tsxnew file mode 100644index 0000000000..da84b81e4e--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/PendingAnswerContexts.test.tsx@@ -0,0 +1,200 @@+import { render } from "@testing-library/react";+import type { UIDataTypes, UIMessage, UITools } from "ai";+import { memo, useContext } from "react";+import { describe, expect, it } from "vitest";+import { PendingOnboardingContext } from "../../../ExpertOnboardingCard/PendingOnboardingContext";+import { PendingQuestionsContext } from "../../../QuestionDock/PendingQuestionsContext";+import { CurrentPauseContext } from "../../../TurnPausedCard/CurrentPauseContext";+import { HeldOutcomesContext } from "../../HeldOutcomesContext";+import { PendingAnswerContexts } from "../PendingAnswerContexts";++type Message = UIMessage<unknown, UIDataTypes, UITools>;+type Part = Message["parts"][number];++interface Seen {+ questions: unknown;+ onboarding: unknown;+ held: ReadonlyMap<string, unknown>;+ pause: unknown;+}++function heldResult(toolCallId: string, body: string): Message {+ return {+ id: `held-${toolCallId}`,+ role: "user",+ metadata: { held_call: { tool_call_id: toolCallId, outcome: "approved" } },+ parts: [+ {+ type: "text",+ text: `<held_call_result tool="create_folder" tool_call_id="${toolCallId}" review_id="r">\n${body}\n</held_call_result>`,+ },+ ],+ };+}++const askPart = {+ type: "tool-ask_question",+ toolCallId: "ask-1",+ state: "output-available",+ input: {},+ output: {+ type: "agent_builder_clarification_needed",+ questions: [{ question: "Which region?", keyword: "region" }],+ },+} as unknown as Part;++function assistant(text: string, extra: Part[] = []): Message {+ return {+ id: "a1",+ role: "assistant",+ parts: [askPart, ...extra, { type: "text", text }],+ };+}++function setup(initial: Message[]) {+ const seen: Seen[] = [];+ const Consumer = memo(function Consumer() {+ seen.push({+ questions: useContext(PendingQuestionsContext),+ onboarding: useContext(PendingOnboardingContext),+ held: useContext(HeldOutcomesContext),+ pause: useContext(CurrentPauseContext),+ });+ return null;+ });+ const consumer = <Consumer />;+ const view = render(+ <PendingAnswerContexts messages={initial}>+ {consumer}+ </PendingAnswerContexts>,+ );+ function rerender(messages: Message[]) {+ view.rerender(+ <PendingAnswerContexts messages={messages}>+ {consumer}+ </PendingAnswerContexts>,+ );+ }+ return { seen, rerender };+}++describe("PendingAnswerContexts", () => {+ it("publishes identical values when rendered again with the same messages", () => {+ const messages = [heldResult("call-7", '{"ok":true}'), assistant("Hi")];+ const { seen, rerender } = setup(messages);+ const first = seen[0];+ expect(first.questions).not.toBeNull();+ expect(first.held.size).toBe(1);++ rerender(messages);++ // The memoised consumer did not render again: no value changed.+ expect(seen).toHaveLength(1);+ });++ it("keeps every value's identity while a token streams into the last message", () => {+ const held = heldResult("call-7", '{"ok":true}');+ const { seen, rerender } = setup([held, assistant("Hel")]);++ rerender([held, assistant("Hello")]);+ rerender([held, assistant("Hello there")]);++ expect(seen).toHaveLength(1);+ expect(seen[0].held.get("call-7")).toEqual({+ outcome: "approved",+ output: { ok: true },+ });+ });++ it("keeps the held outcomes when the result message is rebuilt with the same content", () => {+ const { seen, rerender } = setup([+ heldResult("call-7", '{"ok":true}'),+ assistant("Hi"),+ ]);++ rerender([heldResult("call-7", '{"ok":true}'), assistant("Hi")]);++ expect(seen).toHaveLength(1);+ });++ it("publishes a new map once a held call is answered", () => {+ const first = heldResult("call-7", '{"ok":true}');+ const { seen, rerender } = setup([first, assistant("Hi")]);++ rerender([first, heldResult("call-8", "posted"), assistant("Hi")]);++ expect(seen).toHaveLength(2);+ expect(seen[1].held).not.toBe(seen[0].held);+ expect([...seen[1].held.keys()]).toEqual(["call-7", "call-8"]);+ expect(seen[1].questions).toBe(seen[0].questions);+ });++ it("publishes new questions when the asking call changes", () => {+ const { seen, rerender } = setup([assistant("Hi")]);+ const otherAsk = {+ ...askPart,+ toolCallId: "ask-2",+ output: {+ type: "agent_builder_clarification_needed",+ questions: [{ question: "Which team?", keyword: "team" }],+ },+ } as unknown as Part;++ rerender([assistant("Hi", [otherAsk])]);++ expect(seen).toHaveLength(2);+ expect(seen[1].questions).toMatchObject({+ callIds: ["ask-1", "ask-2"],+ });+ });++ it("clears the questions once the user replies", () => {+ const { seen, rerender } = setup([assistant("Hi")]);++ rerender([+ assistant("Hi"),+ { id: "u1", role: "user", parts: [{ type: "text", text: "Europe" }] },+ ]);++ expect(seen).toHaveLength(2);+ expect(seen[1].questions).toBeNull();+ });++ it("shares one empty map across different messages when nothing is held", () => {+ const { seen, rerender } = setup([+ { id: "u1", role: "user", parts: [{ type: "text", text: "Hi" }] },+ ]);+ expect(seen[0].held.size).toBe(0);++ rerender([+ { id: "u1", role: "user", parts: [{ type: "text", text: "Hi" }] },+ { id: "a1", role: "assistant", parts: [{ type: "text", text: "Yo" }] },+ ]);++ expect(seen).toHaveLength(1);+ });++ it("passes the paused part's own data object through by reference", () => {+ const data = { reason: "daily", resets_at: null };+ const paused = {+ id: "a1",+ role: "assistant",+ parts: [{ type: "data-turn-paused", data }],+ } as unknown as Message;+ const { seen, rerender } = setup([paused]);+ expect(seen[0].pause).toBe(data);++ const equalData = { reason: "daily", resets_at: null };+ rerender([+ {+ id: "a1",+ role: "assistant",+ parts: [{ type: "data-turn-paused", data: equalData }],+ } as unknown as Message,+ ]);++ // Cards match their pause by reference, so an equal copy is a new pause.+ expect(seen).toHaveLength(2);+ expect(seen[1].pause).toBe(equalData);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotChatActionsProvider/CopilotChatActionsProvider.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotChatActionsProvider/CopilotChatActionsProvider.tsxindex 9a353a45f2..bff334d0c2 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotChatActionsProvider/CopilotChatActionsProvider.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotChatActionsProvider/CopilotChatActionsProvider.tsx@@ -1,5 +1,7 @@"use client";+import { useStableCallback } from "@/hooks/useStableCallback";+import { useMemo } from "react";import {CopilotChatActionsContext,type CopilotChatSurface,@@ -25,17 +27,32 @@ export function CopilotChatActionsProvider({assistantName,children,}: Props) {+ // The copilot page hands a new `onBackendTurn` every render (it only reads+ // refs), which would change the actions on every streamed flush. Cards get+ // one function that calls the latest; absent stays absent.+ const followBackendTurn = useStableCallback(() => onBackendTurn?.());+ const hasBackendTurn = Boolean(onBackendTurn);+ const actions = useMemo(+ () => ({+ onSend,+ onBackendTurn: hasBackendTurn ? followBackendTurn : undefined,+ chatSurface,+ getExecutionShareToken,+ sessionId,+ assistantName,+ }),+ [+ onSend,+ hasBackendTurn,+ followBackendTurn,+ chatSurface,+ getExecutionShareToken,+ sessionId,+ assistantName,+ ],+ );return (- <CopilotChatActionsContext.Provider- value={{- onSend,- onBackendTurn,- chatSurface,- getExecutionShareToken,- sessionId,- assistantName,- }}- >+ <CopilotChatActionsContext.Provider value={actions}>{children}</CopilotChatActionsContext.Provider>);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotChatActionsProvider/__tests__/CopilotChatActionsProvider.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotChatActionsProvider/__tests__/CopilotChatActionsProvider.test.tsxnew file mode 100644index 0000000000..9f6977dc3b--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotChatActionsProvider/__tests__/CopilotChatActionsProvider.test.tsx@@ -0,0 +1,85 @@+import { render } from "@testing-library/react";+import { memo } from "react";+import { describe, expect, it, vi } from "vitest";+import { CopilotChatActionsProvider } from "../CopilotChatActionsProvider";+import { useCopilotChatActions } from "../useCopilotChatActions";++type Actions = ReturnType<typeof useCopilotChatActions>;++function setup() {+ const seen: Actions[] = [];+ const Card = memo(function Card() {+ seen.push(useCopilotChatActions());+ return null;+ });+ return { seen, card: <Card /> };+}++describe("CopilotChatActionsProvider", () => {+ it("keeps the actions when the page re-renders with a new onBackendTurn", () => {+ const onSend = vi.fn();+ const { seen, card } = setup();+ const view = render(+ <CopilotChatActionsProvider+ onSend={onSend}+ onBackendTurn={() => undefined}+ sessionId="s1"+ assistantName="Otto"+ >+ {card}+ </CopilotChatActionsProvider>,+ );++ const latest = vi.fn();+ view.rerender(+ <CopilotChatActionsProvider+ onSend={onSend}+ onBackendTurn={latest}+ sessionId="s1"+ assistantName="Otto"+ >+ {card}+ </CopilotChatActionsProvider>,+ );++ expect(seen).toHaveLength(1);+ seen[0].onBackendTurn?.();+ expect(latest).toHaveBeenCalledTimes(1);+ });++ it("publishes new actions when a field changes", () => {+ const { seen, card } = setup();+ const firstSend = vi.fn();+ const view = render(+ <CopilotChatActionsProvider onSend={firstSend} sessionId="s1">+ {card}+ </CopilotChatActionsProvider>,+ );++ const nextSend = vi.fn();+ view.rerender(+ <CopilotChatActionsProvider onSend={nextSend} sessionId="s2">+ {card}+ </CopilotChatActionsProvider>,+ );++ expect(seen).toHaveLength(2);+ expect(seen[1]).toMatchObject({+ onSend: nextSend,+ sessionId: "s2",+ chatSurface: "copilot",+ });+ });++ it("leaves onBackendTurn absent when the surface has none", () => {+ const { seen, card } = setup();+ render(+ <CopilotChatActionsProvider onSend={vi.fn()} chatSurface="share">+ {card}+ </CopilotChatActionsProvider>,+ );++ expect(seen[0].onBackendTurn).toBeUndefined();+ expect(seen[0].chatSurface).toBe("share");+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.tsindex 42ded51a2a..6845c53c71 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts@@ -1,4 +1,5 @@import { toast } from "@/components/molecules/Toast/use-toast";+import { useStableCallback } from "@/hooks/useStableCallback";import { useAuth } from "@/lib/auth/hooks/useAuth";import { isValidUUID } from "@/lib/utils";import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";@@ -361,7 +362,7 @@ export function useCopilotPage({// Wrap sendNewMessage with queue-in-flight routing: if a session is active// and a turn is already running, POST the follow-up text to the pending// endpoint so the backend buffers it; otherwise fall through to normal send.- async function onSend(+ async function sendOrQueue(message: string,files?: File[],workspaceFiles?: WorkspaceAttachment[],@@ -453,9 +454,14 @@ export function useCopilotPage({}await sendNewMessage(message, files, workspaceFiles, metadata);}+ // One function for the host's lifetime that runs the latest `sendOrQueue`,+ // so the chat actions and the composer keep their props across flushes.+ const onSend = useStableCallback(sendOrQueue);useWorkflowImportAutoSubmit({- onSend,+ // This render's function on purpose: its effect lists `onSend` as a+ // dependency and re-checks the URL for a prompt every time it changes.+ onSend: sendOrQueue,setPendingFileParts,isSendLocked: isExpertSendLocked,});diff --git a/autogpt_platform/frontend/src/hooks/__tests__/useStableCallback.test.ts b/autogpt_platform/frontend/src/hooks/__tests__/useStableCallback.test.tsnew file mode 100644index 0000000000..7d6bfdefc5--- /dev/null+++ b/autogpt_platform/frontend/src/hooks/__tests__/useStableCallback.test.ts@@ -0,0 +1,64 @@+import { render, renderHook } from "@testing-library/react";+import { createElement, useLayoutEffect } from "react";+import { describe, expect, it, vi } from "vitest";++import { useStableCallback } from "../useStableCallback";++describe("useStableCallback", () => {+ it("returns the same function across renders", () => {+ const { result, rerender } = renderHook(({ fn }) => useStableCallback(fn), {+ initialProps: { fn: () => "a" },+ });+ const first = result.current;++ rerender({ fn: () => "b" });+ rerender({ fn: () => "c" });++ expect(result.current).toBe(first);+ });++ it("calls the latest implementation with the arguments and returns its result", () => {+ const first = vi.fn((a: number, b: number) => a + b);+ const latest = vi.fn((a: number, b: number) => a * b);+ const { result, rerender } = renderHook(({ fn }) => useStableCallback(fn), {+ initialProps: { fn: first },+ });+ const stable = result.current;++ expect(stable(2, 3)).toBe(5);+ rerender({ fn: latest });++ expect(stable(2, 3)).toBe(6);+ expect(first).toHaveBeenCalledTimes(1);+ expect(latest).toHaveBeenCalledWith(2, 3);+ });++ it("passes a rejected promise through to the caller", async () => {+ const { result } = renderHook(() =>+ useStableCallback(async () => {+ throw new Error("send failed");+ }),+ );++ await expect(result.current()).rejects.toThrow("send failed");+ });++ it("is already the latest in a child's layout effect of the same commit", () => {+ const seen: string[] = [];+ function Child({ run }: { run: () => string }) {+ useLayoutEffect(() => {+ seen.push(run());+ });+ return null;+ }+ function Parent({ label }: { label: string }) {+ const run = useStableCallback(() => label);+ return createElement(Child, { run });+ }++ const view = render(createElement(Parent, { label: "first" }));+ view.rerender(createElement(Parent, { label: "second" }));++ expect(seen).toEqual(["first", "second"]);+ });+});diff --git a/autogpt_platform/frontend/src/hooks/useStableCallback.ts b/autogpt_platform/frontend/src/hooks/useStableCallback.tsnew file mode 100644index 0000000000..1a2d82914c--- /dev/null+++ b/autogpt_platform/frontend/src/hooks/useStableCallback.ts@@ -0,0 +1,28 @@+"use client";++import { useInsertionEffect, useRef, useState } from "react";++/**+ * Returns one function, created once, that always calls the latest `fn`.+ * Passing it down or through a context no longer changes identity on every+ * render, so memoised consumers can skip their render.+ *+ * The latest `fn` is stored in an insertion effect, never during render. That+ * runs before every layout effect of the same commit, so handlers and effects+ * (layout ones in children included) already see it; calling it during render+ * is not supported.+ */+export function useStableCallback<Args extends unknown[], Result>(+ fn: (...args: Args) => Result,+): (...args: Args) => Result {+ const latest = useRef(fn);+ useInsertionEffect(() => {+ latest.current = fn;+ });+ const [stable] = useState(+ () =>+ (...args: Args) =>+ latest.current(...args),+ );+ return stable;+}