This is an automated email from the ASF dual-hosted git repository.

lizhimins pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/rocketmq-dashboard.git


The following commit(s) were added to refs/heads/master by this push:
     new 827d459a2 fix(ai): bind playground results to their execution context 
(#6950)
827d459a2 is described below

commit 827d459a22e2c333ce024363a2bf53eb4717a037
Author: aias00 <[email protected]>
AuthorDate: Fri Nov 27 12:06:57 2026 +0800

    fix(ai): bind playground results to their execution context (#6950)
---
 .../pages/ai/components/ToolPlaygroundModal.tsx    |  41 ++++++-
 .../__tests__/ToolPlaygroundExecution.test.tsx     | 129 +++++++++++++++++++++
 2 files changed, 165 insertions(+), 5 deletions(-)

diff --git a/web/src/pages/ai/components/ToolPlaygroundModal.tsx 
b/web/src/pages/ai/components/ToolPlaygroundModal.tsx
index 20a7d5dea..e19fe7877 100644
--- a/web/src/pages/ai/components/ToolPlaygroundModal.tsx
+++ b/web/src/pages/ai/components/ToolPlaygroundModal.tsx
@@ -121,11 +121,30 @@ const ToolPlaygroundModal = ({
   const [toolResult, setToolResult] = useState<unknown>(undefined);
   const [toolExecuting, setToolExecuting] = useState(false);
   const toolLoadRequestRef = useRef(0);
+  const executionGenerationRef = useRef(0);
+  const executionPendingRef = useRef(false);
+  const mountedRef = useRef(false);
   /** The catalog is loaded once per mount: reopening the modal must not 
re-hit the endpoint. */
   const bootstrappedRef = useRef(false);
 
+  useEffect(() => {
+    mountedRef.current = true;
+    return () => {
+      mountedRef.current = false;
+      executionGenerationRef.current += 1;
+    };
+  }, []);
+
+  useEffect(
+    () => () => {
+      executionGenerationRef.current += 1;
+    },
+    [open, disabled],
+  );
+
   const selectTool = useCallback(
     (name: string, availableTools: McpTool[] = tools, instanceId: string = 
selectedInstanceId) => {
+      executionGenerationRef.current += 1;
       const tool = availableTools.find((item) => item.name === name);
       setSelectedToolName(name);
       setToolInput(tool ? buildToolInputTemplate(tool, instanceId) : '{}');
@@ -136,6 +155,7 @@ const ToolPlaygroundModal = ({
 
   const loadTools = useCallback(
     async (instanceId: string) => {
+      executionGenerationRef.current += 1;
       const requestId = ++toolLoadRequestRef.current;
       setSelectedToolName('');
       setToolResult(undefined);
@@ -201,7 +221,7 @@ const ToolPlaygroundModal = ({
   );
 
   const handleExecuteTool = useCallback(async () => {
-    if (!selectedToolName || toolExecuting) return;
+    if (!open || disabled || !selectedToolName || executionPendingRef.current) 
return;
 
     let parsedInput: unknown;
     try {
@@ -215,22 +235,29 @@ const ToolPlaygroundModal = ({
       return;
     }
 
+    const generation = ++executionGenerationRef.current;
+    executionPendingRef.current = true;
     setToolExecuting(true);
     setToolResult(undefined);
     try {
-      setToolResult(await executeTool(selectedToolName, parsedInput, 
selectedInstanceId));
+      const result = await executeTool(selectedToolName, parsedInput, 
selectedInstanceId);
+      if (generation !== executionGenerationRef.current) return;
+      setToolResult(result);
       message.success(t('ai.tools.executeSuccess'));
     } catch (error) {
+      if (generation !== executionGenerationRef.current) return;
       message.error(error instanceof Error ? error.message : 
t('ai.tools.executeFailed'));
     } finally {
-      setToolExecuting(false);
+      executionPendingRef.current = false;
+      if (mountedRef.current) setToolExecuting(false);
     }
-  }, [selectedInstanceId, selectedToolName, t, toolExecuting, toolInput]);
+  }, [disabled, open, selectedInstanceId, selectedToolName, t, toolInput]);
 
   const handleClose = useCallback(() => {
     // Invalidate an in-flight catalog load: its response would otherwise land 
on a closed modal and
     // re-select a tool nobody is looking at.
     toolLoadRequestRef.current += 1;
+    executionGenerationRef.current += 1;
     setToolsLoading(false);
     onClose();
   }, [onClose]);
@@ -312,7 +339,11 @@ const ToolPlaygroundModal = ({
             aria-label={t('ai.tools.inputAria')}
             value={toolInput}
             disabled={disabled}
-            onChange={(event) => setToolInput(event.target.value)}
+            onChange={(event) => {
+              executionGenerationRef.current += 1;
+              setToolResult(undefined);
+              setToolInput(event.target.value);
+            }}
             autoSize={{ minRows: 6, maxRows: 12 }}
             spellCheck={false}
           />
diff --git 
a/web/src/pages/ai/components/__tests__/ToolPlaygroundExecution.test.tsx 
b/web/src/pages/ai/components/__tests__/ToolPlaygroundExecution.test.tsx
new file mode 100644
index 000000000..547851869
--- /dev/null
+++ b/web/src/pages/ai/components/__tests__/ToolPlaygroundExecution.test.tsx
@@ -0,0 +1,129 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+import { act, fireEvent, render, screen, waitFor } from 
'@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { message } from 'antd';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { executeTool, listTools } from '../../../../api/ai';
+import { listInstances } from '../../../../services/instanceService';
+import ToolPlaygroundModal from '../ToolPlaygroundModal';
+
+vi.mock('../../../../api/ai', () => ({ executeTool: vi.fn(), listTools: 
vi.fn() }));
+vi.mock('../../../../services/instanceService', () => ({ listInstances: 
vi.fn() }));
+vi.mock('../../../../i18n/LangContext', () => ({ useLang: () => ({ t: (key: 
string) => key }) }));
+
+describe('ToolPlayground execution ownership', () => {
+  beforeEach(() => {
+    vi.resetAllMocks();
+    const completion = Promise.resolve(true);
+    const dismiss = Object.assign(() => undefined, { then: 
completion.then.bind(completion) });
+    vi.spyOn(message, 'success').mockReturnValue(dismiss);
+    vi.spyOn(message, 'error').mockReturnValue(dismiss);
+    vi.mocked(listInstances).mockResolvedValue(
+      ['instance-x', 'instance-y'].map((name, id) => ({
+        id,
+        name,
+        remark: null,
+        type: 'DIRECT',
+        endpoint: `${name}:9876`,
+        topicCount: 0,
+        consumerGroupCount: 0,
+        gmtCreate: '',
+        gmtModified: '',
+      })),
+    );
+    vi.mocked(listTools).mockResolvedValue([
+      { name: 'tool-a', description: 'A', parameters: {} },
+      { name: 'tool-b', description: 'B', parameters: {} },
+    ]);
+  });
+
+  it.each(
+    ['tool', 'scope', 'input', 'close', 'external-close', 
'unmount'].flatMap((change) =>
+      ['success', 'failure'].map((outcome) => [change, outcome]),
+    ),
+  )('discardsLateExecutionAfterContextChangesTest: %s %s', async (change, 
outcome) => {
+    const user = userEvent.setup();
+    let resolve!: (value: unknown) => void;
+    let reject!: (error: Error) => void;
+    vi.mocked(executeTool).mockReturnValue(
+      new Promise((release, fail) => {
+        resolve = release;
+        reject = fail;
+      }),
+    );
+    const onClose = vi.fn();
+    const { rerender, unmount } = render(<ToolPlaygroundModal open 
onClose={onClose} />);
+    await waitFor(() => expect(listTools).toHaveBeenCalledTimes(1));
+    await waitFor(() =>
+      expect(screen.getByRole('button', { name: 'ai.tools.execute' 
})).toBeEnabled(),
+    );
+    await user.click(screen.getByRole('button', { name: 'ai.tools.execute' }));
+    expect(executeTool).toHaveBeenCalledTimes(1);
+
+    if (change === 'tool') {
+      await user.click(screen.getByRole('combobox', { name: 
'ai.tools.selectTool' }));
+      await user.click(
+        await screen.findByText('tool-b', { selector: 
'.ant-select-item-option-content' }),
+      );
+    } else if (change === 'scope') {
+      await user.click(screen.getByRole('combobox', { name: 
'ai.tools.selectInstance' }));
+      await user.click(
+        await screen.findByText('instance-y', { selector: 
'.ant-select-item-option-content' }),
+      );
+    } else if (change === 'input') {
+      fireEvent.change(screen.getByRole('textbox', { name: 
'ai.tools.inputAria' }), {
+        target: { value: '{"changed":true}' },
+      });
+    } else if (change === 'unmount') {
+      unmount();
+    } else {
+      if (change === 'close')
+        await user.click(screen.getByRole('button', { name: 'common.close' }));
+      rerender(<ToolPlaygroundModal open={false} onClose={onClose} />);
+      rerender(<ToolPlaygroundModal open onClose={onClose} />);
+    }
+
+    await act(async () => {
+      if (outcome === 'success') resolve({ source: 'old execution' });
+      else reject(new Error('old execution failed'));
+    });
+    expect(screen.queryByTestId('tool-result')).not.toBeInTheDocument();
+    expect(message.success).not.toHaveBeenCalled();
+    expect(message.error).not.toHaveBeenCalled();
+  });
+
+  it('reportsCurrentExecutionAndSuppressesDuplicateSubmissionTest', async () 
=> {
+    let resolve!: (value: unknown) => void;
+    vi.mocked(executeTool).mockReturnValue(
+      new Promise((release) => {
+        resolve = release;
+      }),
+    );
+    render(<ToolPlaygroundModal open onClose={vi.fn()} />);
+    const button = screen.getByRole('button', { name: 'ai.tools.execute' });
+    await waitFor(() => expect(button).toBeEnabled());
+    act(() => {
+      fireEvent.click(button);
+      fireEvent.click(button);
+    });
+    expect(executeTool).toHaveBeenCalledTimes(1);
+    await act(async () => resolve({ source: 'current execution' }));
+    expect(screen.getByTestId('tool-result')).toHaveTextContent('current 
execution');
+    expect(message.success).toHaveBeenCalledTimes(1);
+  });
+});

Reply via email to