Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

fix: harden agent export, timeout, and artifact handling (#22037)

buua436303776e89c64
diff --git a/internal/agent/tool/registry.go b/internal/agent/tool/registry.go
index 12410e9d15..fee987bf1a 100644
--- a/internal/agent/tool/registry.go
+++ b/internal/agent/tool/registry.go
@@ -747,6 +747,7 @@ func buildQueritTool(params map[string]any) (einotool.BaseTool, error) {
return newQueritTool(nil, nil, defaults, nil), nil
}
+// buildQueritContentsTool constructs the Querit Contents tool from canvas params.
func buildQueritContentsTool(params map[string]any) (einotool.BaseTool, error) {
defaults := queritContentsParams{}
if value, exists := params["api_key"]; exists {
@@ -767,11 +768,15 @@ func buildQueritContentsTool(params map[string]any) (einotool.BaseTool, error) {
defaults.Format = format
}
if value, exists := params["crawl_timeout"]; exists {
- crawlTimeout, valid := strictInt(value)
- if !valid || crawlTimeout < 1 || crawlTimeout > 60 {
- return nil, fmt.Errorf("agent tool: tool %q requires integer node-level param crawl_timeout within [1, 60]", queritContentsToolName)
+ // A cleared numeric form field may be stored as an empty string. Treat it
+ // as omitted so the tool constructor applies the documented default.
+ if empty, ok := value.(string); !ok || strings.TrimSpace(empty) != "" {
+ crawlTimeout, valid := strictInt(value)
+ if !valid || crawlTimeout < 1 || crawlTimeout > 60 {
+ return nil, fmt.Errorf("agent tool: tool %q requires integer node-level param crawl_timeout within [1, 60]", queritContentsToolName)
+ }
+ defaults.CrawlTimeout = crawlTimeout
}
- defaults.CrawlTimeout = crawlTimeout
}
if value, exists := params["extras_meta"]; exists {
extrasMeta, valid := value.(bool)
diff --git a/internal/agent/tool/registry_test.go b/internal/agent/tool/registry_test.go
index 36c04d24e9..d043f54276 100644
--- a/internal/agent/tool/registry_test.go
+++ b/internal/agent/tool/registry_test.go
@@ -181,6 +181,24 @@ func TestBuildByName_QueritContentsAliases(t *testing.T) {
}
}
+func TestBuildByName_QueritContentsEmptyTimeoutUsesDefault(t *testing.T) {
+ for _, value := range []string{"", " "} {
+ built, err := BuildByName("querit_contents", map[string]any{
+ "crawl_timeout": value,
+ })
+ if err != nil {
+ t.Fatalf("BuildByName with empty crawl_timeout %q: %v", value, err)
+ }
+ contents, ok := built.(*QueritContentsTool)
+ if !ok {
+ t.Fatalf("BuildByName returned %T, want *QueritContentsTool", built)
+ }
+ if contents.defaults.CrawlTimeout != 10 {
+ t.Fatalf("crawl timeout = %d, want default 10", contents.defaults.CrawlTimeout)
+ }
+ }
+}
+
func TestBuildByName_YouComReadsCanvasParams(t *testing.T) {
// The canvas stores tool params under the lower-cased component name, and
// the node form also carries query/outputs keys the tool must ignore.
diff --git a/web/src/components/next-markdown-content/__tests__/index.test.tsx b/web/src/components/next-markdown-content/__tests__/index.test.tsx
index 1c95420ee0..62c94b7d6e 100644
--- a/web/src/components/next-markdown-content/__tests__/index.test.tsx
+++ b/web/src/components/next-markdown-content/__tests__/index.test.tsx
@@ -1,4 +1,4 @@
-import { render, screen } from '@testing-library/react';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import MarkdownContent from '..';
@@ -47,6 +47,15 @@ jest.mock('react-markdown', () => ({
__esModule: true,
default: ({ children, components }: any) => {
const ReactLib = jest.requireActual('react');
+ const linkMatch = String(children).match(/^\[([^\]]+)\]\(([^)]+)\)$/);
+ if (linkMatch) {
+ const Anchor = components.a;
+ return ReactLib.createElement(
+ Anchor,
+ { href: linkMatch[2] },
+ linkMatch[1],
+ );
+ }
const CustomTypography = components['custom-typography'];
return ReactLib.createElement(CustomTypography, null, String(children));
},
@@ -217,4 +226,39 @@ describe('MarkdownContent citations', () => {
expect(chipTexts()).toEqual(['[1]']);
expect(screen.queryByTestId('popover')).toBeNull();
});
+
+ it('downloads artifacts marked as attachments instead of opening their blob', async () => {
+ const request = jest.requireMock('@/utils/request').default as jest.Mock;
+ const { downloadFileFromBlob } = jest.requireMock('@/utils/file-util');
+ request.mockResolvedValue({
+ data: new Blob(['<script>window.pwned = true</script>'], {
+ type: 'text/html',
+ }),
+ response: {
+ headers: {
+ get: (name: string) =>
+ name === 'content-disposition' ? 'attachment' : null,
+ },
+ },
+ });
+ const open = jest.spyOn(window, 'open').mockImplementation(() => null);
+
+ render(
+ <MarkdownContent
+ content={'[Download report](/api/v1/documents/artifact/report.html)'}
+ loading={false}
+ reference={undefined}
+ />,
+ );
+ fireEvent.click(screen.getByRole('link', { name: 'Download report' }));
+
+ await waitFor(() =>
+ expect(downloadFileFromBlob).toHaveBeenCalledWith(
+ expect.any(Blob),
+ 'report.html',
+ ),
+ );
+ expect(request).toHaveBeenCalled();
+ expect(open).not.toHaveBeenCalled();
+ });
});
diff --git a/web/src/components/next-markdown-content/index.tsx b/web/src/components/next-markdown-content/index.tsx
index bf09adf24c..d843af124e 100644
--- a/web/src/components/next-markdown-content/index.tsx
+++ b/web/src/components/next-markdown-content/index.tsx
@@ -81,18 +81,19 @@ const getChunkKey = (match: string) => parseCitationIndex(match);
const isArtifactUrl = (url?: string) =>
Boolean(url && url.includes('/api/v1/documents/artifact/'));
-const fetchArtifactBlob = async (url: string): Promise<Blob> => {
- const response = await request(url, {
+const fetchArtifactResponse = (url: string) =>
+ request(url, {
method: 'GET',
responseType: 'blob',
});
- return response.data as Blob;
-};
+const fetchArtifactBlob = async (url: string): Promise<Blob> =>
+ (await fetchArtifactResponse(url)).data as Blob;
const getArtifactName = (url?: string, fallback?: string) =>
fallback || url?.split('/').pop()?.split('?')[0] || 'artifact';
+/** Downloads attachment responses and previews other artifact blobs. */
function ArtifactLink({
href,
className,
@@ -106,7 +107,19 @@ function ArtifactLink({
async (e: React.MouseEvent<HTMLAnchorElement>) => {
e.preventDefault();
try {
- const blob = await fetchArtifactBlob(href);
+ const response = await fetchArtifactResponse(href);
+ const blob = response.data as Blob;
+ const contentDisposition = response.response.headers.get(
+ 'content-disposition',
+ );
+ if (
+ typeof contentDisposition === 'string' &&
+ /^\s*attachment(?:;|$)/i.test(contentDisposition)
+ ) {
+ downloadFileFromBlob(blob, getArtifactName(href));
+ return;
+ }
+
const objectUrl = URL.createObjectURL(blob);
window.open(objectUrl, '_blank', 'noopener,noreferrer');
window.setTimeout(() => URL.revokeObjectURL(objectUrl), 60 * 1000);
diff --git a/web/src/pages/agent/form/querit-contents-form/index.test.tsx b/web/src/pages/agent/form/querit-contents-form/index.test.tsx
new file mode 100644
index 0000000000..c97f23e63d
--- /dev/null
+++ b/web/src/pages/agent/form/querit-contents-form/index.test.tsx
@@ -0,0 +1,146 @@
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import useGraphStore from '../../store';
+import QueritContentsForm from '.';
+
+jest.mock('@/hooks/common-hooks', () => ({
+ useTranslate: () => ({ t: (key: string) => key }),
+}));
+
+jest.mock('@/components/ui/tooltip', () => ({
+ TooltipProvider: ({ children }: { children: React.ReactNode }) => children,
+ FormTooltip: () => null,
+}));
+
+jest.mock('@/components/originui/select-with-search', () => ({
+ SelectWithSearch: () => null,
+}));
+
+jest.mock('@/components/ui/switch', () => ({
+ Switch: () => null,
+}));
+
+jest.mock('../components/api-key-field', () => ({
+ ApiKeyField: () => null,
+}));
+
+jest.mock('../components/form-wrapper', () => ({
+ FormWrapper: ({ children }: { children: React.ReactNode }) => children,
+}));
+
+jest.mock('../components/output', () => ({
+ Output: () => null,
+}));
+
+jest.mock('../components/prompt-editor', () => ({
+ PromptEditor: () => null,
+}));
+
+describe('QueritContentsForm', () => {
+ afterEach(() => {
+ useGraphStore.setState({ nodes: [] });
+ });
+
+ it('keeps the last valid timeout while the field is cleared and can be replaced', async () => {
+ const node = {
+ id: 'querit-node',
+ data: {
+ form: {
+ api_key: '',
+ urls: 'https://example.com',
+ format: 'markdown',
+ crawl_timeout: 10,
+ extras_meta: false,
+ },
+ },
+ } as any;
+ useGraphStore.setState({ nodes: [node] });
+
+ render(
+ <TooltipProvider>
+ <QueritContentsForm node={node} />
+ </TooltipProvider>,
+ );
+ const timeoutInput = screen.getByRole('spinbutton');
+ fireEvent.change(timeoutInput, {
+ target: { value: '' },
+ });
+
+ await waitFor(() => {
+ expect(useGraphStore.getState().nodes[0].data.form.crawl_timeout).toBe(
+ 10,
+ );
+ });
+ expect((timeoutInput as HTMLInputElement).value).toBe('');
+
+ fireEvent.change(timeoutInput, { target: { value: '25' } });
+
+ await waitFor(() => {
+ expect(useGraphStore.getState().nodes[0].data.form.crawl_timeout).toBe(
+ 25,
+ );
+ });
+ expect(timeoutInput).toHaveValue(25);
+ });
+
+ it('restores the last valid timeout if the cleared field is left empty', async () => {
+ const node = {
+ id: 'querit-node',
+ data: {
+ form: {
+ api_key: '',
+ urls: 'https://example.com',
+ format: 'markdown',
+ crawl_timeout: 25,
+ extras_meta: false,
+ },
+ },
+ } as any;
+ useGraphStore.setState({ nodes: [node] });
+
+ render(
+ <TooltipProvider>
+ <QueritContentsForm node={node} />
+ </TooltipProvider>,
+ );
+ const timeoutInput = screen.getByRole('spinbutton');
+ fireEvent.change(timeoutInput, { target: { value: '' } });
+ fireEvent.blur(timeoutInput);
+
+ await waitFor(() => {
+ expect(useGraphStore.getState().nodes[0].data.form.crawl_timeout).toBe(
+ 25,
+ );
+ });
+ expect(timeoutInput).toHaveValue(25);
+ });
+
+ it('normalizes a previously saved empty crawl timeout to its default', async () => {
+ const node = {
+ id: 'querit-node',
+ data: {
+ form: {
+ api_key: '',
+ urls: 'https://example.com',
+ format: 'markdown',
+ crawl_timeout: '',
+ extras_meta: false,
+ },
+ },
+ } as any;
+ useGraphStore.setState({ nodes: [node] });
+
+ render(
+ <TooltipProvider>
+ <QueritContentsForm node={node} />
+ </TooltipProvider>,
+ );
+
+ await waitFor(() => {
+ expect(useGraphStore.getState().nodes[0].data.form.crawl_timeout).toBe(
+ 10,
+ );
+ });
+ expect(screen.getByRole('spinbutton')).toHaveValue(10);
+ });
+});
diff --git a/web/src/pages/agent/form/querit-contents-form/index.tsx b/web/src/pages/agent/form/querit-contents-form/index.tsx
index d69c6de90c..eaebe161eb 100644
--- a/web/src/pages/agent/form/querit-contents-form/index.tsx
+++ b/web/src/pages/agent/form/querit-contents-form/index.tsx
@@ -13,7 +13,7 @@ import { Switch } from '@/components/ui/switch';
import { useTranslate } from '@/hooks/common-hooks';
import { buildOptions } from '@/utils/form';
import { zodResolver } from '@hookform/resolvers/zod';
-import { memo } from 'react';
+import { memo, useEffect, useMemo, useState } from 'react';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import {
@@ -43,15 +43,48 @@ const FormSchema = z.object({
extras_meta: z.boolean(),
});
+/** Parses a crawl timeout only when it is an integer in the supported range. */
+const parseCrawlTimeout = (value: unknown) => {
+ const numberValue =
+ typeof value === 'number'
+ ? value
+ : typeof value === 'string' && value.trim() !== ''
+ ? Number(value)
+ : Number.NaN;
+
+ return Number.isInteger(numberValue) && numberValue >= 1 && numberValue <= 60
+ ? numberValue
+ : undefined;
+};
+
+/** Replaces a missing or invalid saved timeout with the tool's default. */
+const normalizeCrawlTimeout = (value: unknown) =>
+ parseCrawlTimeout(value) ?? initialQueritContentsValues.crawl_timeout;
+
+/** Renders the Querit Contents form and keeps its timeout valid while editing. */
function QueritContentsForm({ node }: INextOperatorForm) {
const { t } = useTranslate('flow');
const values = useFormValues(initialQueritContentsValues, node);
+ const defaultValues = useMemo(
+ () => ({
+ ...values,
+ crawl_timeout: normalizeCrawlTimeout(values.crawl_timeout),
+ }),
+ [values],
+ );
+ const [crawlTimeoutDraft, setCrawlTimeoutDraft] = useState(() =>
+ String(defaultValues.crawl_timeout),
+ );
const form = useForm<z.infer<typeof FormSchema>>({
- defaultValues: values,
+ defaultValues,
resolver: zodResolver(FormSchema),
mode: 'onChange',
});
+ useEffect(() => {
+ setCrawlTimeoutDraft(String(normalizeCrawlTimeout(values.crawl_timeout)));
+ }, [node?.id, values.crawl_timeout]);
+
useWatchFormChange(node?.id, form);
return (
@@ -97,17 +130,46 @@ function QueritContentsForm({ node }: INextOperatorForm) {
<FormField
control={form.control}
name="crawl_timeout"
- render={({ field }) => (
- <FormItem>
- <FormLabel tooltip={t('queritContentsTimeoutTip')}>
- {t('queritContentsTimeout')}
- </FormLabel>
- <FormControl>
- <Input type="number" min={1} max={60} step={1} {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
+ render={({ field }) => {
+ const handleTimeoutChange = (
+ event: React.ChangeEvent<HTMLInputElement>,
+ ) => {
+ const value = String(event.target.value);
+ setCrawlTimeoutDraft(value);
+
+ const timeout = parseCrawlTimeout(value);
+ if (timeout !== undefined) {
+ field.onChange(timeout);
+ }
+ };
+ const handleTimeoutBlur = () => {
+ field.onBlur();
+ setCrawlTimeoutDraft(
+ String(normalizeCrawlTimeout(field.value)),
+ );
+ };
+
+ return (
+ <FormItem>
+ <FormLabel tooltip={t('queritContentsTimeoutTip')}>
+ {t('queritContentsTimeout')}
+ </FormLabel>
+ <FormControl>
+ <Input
+ type="number"
+ min={1}
+ max={60}
+ step={1}
+ {...field}
+ value={crawlTimeoutDraft}
+ onChange={handleTimeoutChange}
+ onBlur={handleTimeoutBlur}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ );
+ }}
/>
<FormField
control={form.control}
diff --git a/web/src/pages/agent/utils/clear-sensitive-fields.test.ts b/web/src/pages/agent/utils/clear-sensitive-fields.test.ts
index 35d5670220..90ccdff040 100644
--- a/web/src/pages/agent/utils/clear-sensitive-fields.test.ts
+++ b/web/src/pages/agent/utils/clear-sensitive-fields.test.ts
@@ -11,10 +11,12 @@ jest.mock('@/constants/agent', () => ({
QueritSearch: 'QueritSearch',
Search1APISearch: 'Search1APISearch',
Search1APICrawl: 'Search1APICrawl',
+ Begin: 'Begin',
},
+ AgentDialogueMode: { Webhook: 'Webhook' },
}));
-import { Operator } from '@/constants/agent';
+import { AgentDialogueMode, Operator } from '@/constants/agent';
import { clearSensitiveFields } from './clear-sensitive-fields';
describe('clearSensitiveFields', () => {
@@ -251,4 +253,64 @@ describe('clearSensitiveFields', () => {
expect(clearSensitiveFields(dsl)).toEqual(dsl);
});
+
+ it('clears webhook authentication secrets from a begin node', () => {
+ const dsl = {
+ graph: {
+ nodes: [
+ {
+ data: {
+ label: Operator.Begin,
+ form: {
+ mode: AgentDialogueMode.Webhook,
+ security: {
+ auth_type: 'basic',
+ token: {
+ token_header: 'X-Token',
+ token_value: 'token-secret',
+ },
+ basic_auth: { username: 'service', password: 'basic-secret' },
+ jwt: { secret: 'jwt-secret', issuer: 'ragflow' },
+ hmac: { header: 'X-Signature', secret: 'hmac-secret' },
+ },
+ },
+ },
+ },
+ ],
+ },
+ components: {
+ begin: {
+ obj: {
+ component_name: Operator.Begin,
+ params: {
+ mode: AgentDialogueMode.Webhook,
+ security: {
+ auth_type: 'token',
+ token: { token_value: 'component-token-secret' },
+ },
+ },
+ },
+ },
+ },
+ };
+
+ const sanitized = clearSensitiveFields(dsl);
+ const security = sanitized.graph.nodes[0].data.form.security;
+
+ expect(security.token.token_value).toBe('');
+ expect(security.basic_auth.password).toBe('');
+ expect(security.jwt.secret).toBe('');
+ expect(security.hmac.secret).toBe('');
+ expect(security.basic_auth.username).toBe('service');
+ expect(security.token.token_header).toBe('X-Token');
+ expect(
+ sanitized.components.begin.obj.params.security.token.token_value,
+ ).toBe('');
+ expect(dsl.graph.nodes[0].data.form.security.token.token_value).toBe(
+ 'token-secret',
+ );
+ expect(dsl.components.begin.obj.params.security.token.token_value).toBe(
+ 'component-token-secret',
+ );
+ });
});
diff --git a/web/src/pages/agent/utils/clear-sensitive-fields.ts b/web/src/pages/agent/utils/clear-sensitive-fields.ts
index 1b35fd6881..35ea6d52de 100644
--- a/web/src/pages/agent/utils/clear-sensitive-fields.ts
+++ b/web/src/pages/agent/utils/clear-sensitive-fields.ts
@@ -21,6 +21,13 @@ const nodeLabelApiKeyOperators: string[] = [
Operator.SofyaSearch,
];
+const WebhookSecretFields = {
+ token: 'token_value',
+ basic_auth: 'password',
+ jwt: 'secret',
+ hmac: 'secret',
+} as const;
+
function isQueritOperator(value: unknown) {
if (typeof value !== 'string') {
return false;
@@ -53,6 +60,29 @@ function isNodeLabelApiKeyOperator(value: unknown) {
);
}
+/** Returns a copy with recognized webhook credentials blanked. */
+function clearWebhookSecrets(value: Record<string, any>) {
+ const security = value.security;
+ if (!isPlainObject(security)) {
+ return;
+ }
+
+ let changed = false;
+ const sanitizedSecurity = { ...security };
+ for (const [section, field] of Object.entries(WebhookSecretFields)) {
+ const auth = sanitizedSecurity[section];
+ if (isPlainObject(auth) && auth[field]) {
+ sanitizedSecurity[section] = { ...auth, [field]: '' };
+ changed = true;
+ }
+ }
+
+ if (changed) {
+ return { ...value, security: sanitizedSecurity };
+ }
+}
+
+/** Returns a copy of the DSL with recognized credentials removed. */
export function clearSensitiveFields<T>(obj: T): T {
return cloneDeepWith(obj, (value) => {
if (!isPlainObject(value)) {
@@ -83,5 +113,10 @@ export function clearSensitiveFields<T>(obj: T): T {
},
};
}
+
+ const sanitizedWebhookForm = clearWebhookSecrets(value);
+ if (sanitizedWebhookForm) {
+ return sanitizedWebhookForm;
+ }
});
}
diff --git a/web/src/pages/agent/utils/download-dsl.ts b/web/src/pages/agent/utils/download-dsl.ts
index 587452d89c..095a8e881b 100644
--- a/web/src/pages/agent/utils/download-dsl.ts
+++ b/web/src/pages/agent/utils/download-dsl.ts
@@ -3,7 +3,7 @@ import { downloadJsonFile } from '@/utils/file-util';
import { clearSensitiveFields } from './clear-sensitive-fields';
/**
- * Shared agent-DSL download path: strips sensitive fields (api_key)
+ * Shared agent-DSL download path: strips sensitive credentials
* and writes the canonical wire shape to `<title>.json`. Used by the
* canvas export button and the version-history dialog so both emit
* the same structure.