Skip to content

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

Fix: Add a checklist to the agent canvas to display errors found on the canvas. (#20000)

balibabuc6ac9851b9e6
diff --git a/web/jest-setup.ts b/web/jest-setup.ts
index 4016e2403a..8a86e2eb0c 100644
--- a/web/jest-setup.ts
+++ b/web/jest-setup.ts
@@ -13,6 +13,14 @@ if (typeof globalThis.TextEncoder === 'undefined') {
Object.assign(globalThis, { TextDecoder, TextEncoder });
}
+// jsdom does not expose web streams; eventsource-parser reads TransformStream
+// at module scope (via hooks/logic-hooks.ts)
+if (typeof globalThis.TransformStream === 'undefined') {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const { TransformStream } = require('node:stream/web');
+ Object.assign(globalThis, { TransformStream });
+}
+
// Vite's import.meta.glob is rewritten to this stub by jest-esbuild-transformer.cjs
(globalThis as Record<string, unknown>).jestImportMetaGlob = () => ({});
diff --git a/web/jest.config.ts b/web/jest.config.ts
index 68add22c54..e2680bf234 100644
--- a/web/jest.config.ts
+++ b/web/jest.config.ts
@@ -8,13 +8,15 @@ const config: Config = {
'^.+\\.(ts|tsx|js|jsx)$': '<rootDir>/jest-esbuild-transformer.cjs',
},
moduleNameMapper: {
+ // Asset/style stubs must precede the `@/` alias — the alias rewrites
+ // `@/assets/x.png` to a real path and only the first matching mapper runs.
+ '\\.(css|less|scss|sass)$': '<rootDir>/__mocks__/styleMock.js',
+ '\\.(jpg|jpeg|png|gif|svg|webp)$': '<rootDir>/__mocks__/fileMock.js',
// Drags the app shell (routes/react-router) into jsdom; see __mocks__
'^@/components/layout-recognize-form-field$':
'<rootDir>/__mocks__/layout-recognize-form-field.js',
'^@/(.*)$': '<rootDir>/src/$1',
'^human-id$': '<rootDir>/__mocks__/human-id.js',
- '\\.(css|less|scss|sass)$': '<rootDir>/__mocks__/styleMock.js',
- '\\.(jpg|jpeg|png|gif|svg|webp)$': '<rootDir>/__mocks__/fileMock.js',
},
setupFilesAfterEnv: ['<rootDir>/jest-setup.ts'],
collectCoverageFrom: [
diff --git a/web/src/components/compilation-template-form-field.test.tsx b/web/src/components/compilation-template-form-field.test.tsx
new file mode 100644
index 0000000000..aadad00f9b
--- /dev/null
+++ b/web/src/components/compilation-template-form-field.test.tsx
@@ -0,0 +1,130 @@
+/*
+ * Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+ *
+ * Licensed 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 { Form } from '@/components/ui/form';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import { render, screen, within } from '@testing-library/react';
+import { useForm } from 'react-hook-form';
+import { CompilationTemplateFormField } from './compilation-template-form-field';
+
+// jsdom does not provide ResizeObserver or scrollIntoView, which cmdk
+// (inside SelectWithSearch's popover) relies on.
+beforeAll(() => {
+ global.ResizeObserver = class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ };
+ Element.prototype.scrollIntoView = () => {};
+});
+
+const mockUseCompilationTemplateGroupOptions = jest.fn();
+
+jest.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+jest.mock('@/hooks/use-compilation-template-group-request', () => ({
+ useCompilationTemplateGroupOptions: (...args: unknown[]) =>
+ mockUseCompilationTemplateGroupOptions(...args),
+}));
+
+jest.mock('@/hooks/logic-hooks/navigate-hooks', () => ({
+ useNavigatePage: () => ({ navigateToAgents: jest.fn() }),
+}));
+
+function Harness({
+ groupId,
+ ownerTenantId,
+}: {
+ groupId: string;
+ ownerTenantId?: string;
+}) {
+ const form = useForm({
+ defaultValues: { compilation_template_group_id: groupId },
+ });
+
+ return (
+ <TooltipProvider>
+ <Form {...form}>
+ <CompilationTemplateFormField
+ name="compilation_template_group_id"
+ ownerTenantId={ownerTenantId}
+ />
+ </Form>
+ </TooltipProvider>
+ );
+}
+
+describe('CompilationTemplateFormField', () => {
+ it('shows a warning marker for a group the current user cannot resolve', () => {
+ mockUseCompilationTemplateGroupOptions.mockReturnValue({
+ options: [{ label: 'Group A', value: 'g1' }],
+ isFetched: true,
+ isError: false,
+ });
+
+ render(<Harness groupId="gone" />);
+
+ const trigger = screen.getByRole('combobox');
+ expect(within(trigger).getByText('gone')).toBeInTheDocument();
+ expect(trigger.querySelector('svg.size-4')).not.toBeNull();
+ });
+
+ it('suppresses the warning while the group list is loading', () => {
+ mockUseCompilationTemplateGroupOptions.mockReturnValue({
+ options: [],
+ isFetched: false,
+ isError: false,
+ });
+
+ render(<Harness groupId="gone" />);
+
+ const trigger = screen.getByRole('combobox');
+ expect(within(trigger).getByText('gone')).toBeInTheDocument();
+ expect(trigger.querySelector('svg.size-4')).toBeNull();
+ });
+
+ it('shows the option label for a resolvable group', () => {
+ mockUseCompilationTemplateGroupOptions.mockReturnValue({
+ options: [{ label: 'Group A', value: 'g1' }],
+ isFetched: true,
+ isError: false,
+ });
+
+ render(<Harness groupId="g1" />);
+
+ const trigger = screen.getByRole('combobox');
+ expect(within(trigger).getByText('Group A')).toBeInTheDocument();
+ expect(trigger.querySelector('svg.size-4')).toBeNull();
+ });
+
+ it('requests the options of the canvas owner tenant', () => {
+ mockUseCompilationTemplateGroupOptions.mockReturnValue({
+ options: [],
+ isFetched: true,
+ isError: false,
+ });
+
+ render(<Harness groupId="g1" ownerTenantId="owner-1" />);
+
+ expect(mockUseCompilationTemplateGroupOptions).toHaveBeenCalledWith(
+ 'owner-1',
+ );
+ });
+});
diff --git a/web/src/components/compilation-template-form-field.tsx b/web/src/components/compilation-template-form-field.tsx
index 63fe75cf64..7b938bc048 100644
--- a/web/src/components/compilation-template-form-field.tsx
+++ b/web/src/components/compilation-template-form-field.tsx
@@ -17,21 +17,39 @@
import { RAGFlowFormItem } from '@/components/ragflow-form';
import { useCompilationTemplateGroupOptions } from '@/hooks/use-compilation-template-group-request';
import { useNavigatePage } from '@/hooks/logic-hooks/navigate-hooks';
+import { TriangleAlert } from 'lucide-react';
+import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { SelectWithSearch } from './originui/select-with-search';
type CompilationTemplateFormFieldProps = {
horizontal?: boolean;
name?: string;
+ ownerTenantId?: string;
};
export function CompilationTemplateFormField({
horizontal,
name = 'parser_config.compilation_template_group_id',
+ ownerTenantId,
}: CompilationTemplateFormFieldProps) {
const { t } = useTranslation();
const { navigateToAgents } = useNavigatePage();
- const options = useCompilationTemplateGroupOptions();
+ const { options, isFetched, isError } =
+ useCompilationTemplateGroupOptions(ownerTenantId);
+
+ // No owner-scoped name lookup exists for template groups (strictly
+ // owner-tenant, no sharing mechanism) — the raw id is all the missing
+ // display can show. Styled like MissingModelLabel.
+ const renderMissingGroup = useCallback(
+ (missingValue: string) => (
+ <span className="flex items-center gap-1.5 text-text-disabled">
+ <TriangleAlert className="size-4 flex-shrink-0" />
+ <span className="truncate">{missingValue}</span>
+ </span>
+ ),
+ [],
+ );
return (
<RAGFlowFormItem
@@ -50,6 +68,8 @@ export function CompilationTemplateFormField({
value={field.value}
onChange={field.onChange}
options={options}
+ loading={!isFetched || isError}
+ renderMissingValue={renderMissingGroup}
/>
)}
</RAGFlowFormItem>
diff --git a/web/src/components/knowledge-base-item.tsx b/web/src/components/knowledge-base-item.tsx
index 6c6e7230ee..735661b509 100644
--- a/web/src/components/knowledge-base-item.tsx
+++ b/web/src/components/knowledge-base-item.tsx
@@ -43,7 +43,10 @@ function DatasetLabel({ text }: { text: string }) {
);
}
-export function useDisableDifferenceEmbeddingDataset(name: string) {
+export function useDisableDifferenceEmbeddingDataset(
+ name: string,
+ ownerTenantId?: string,
+) {
const form = useFormContext();
const datasetId = useWatch({ name, control: form.control });
const [searchString, setSearchString] = useState('');
@@ -53,7 +56,12 @@ export function useDisableDifferenceEmbeddingDataset(name: string) {
loading,
handleScroll,
hasNextPage,
- } = useFetchKnowledgeList(false, debouncedSearchString);
+ } = useFetchKnowledgeList(
+ false,
+ debouncedSearchString,
+ undefined,
+ ownerTenantId,
+ );
const selectedDatasetIds = useMemo(
() => (Array.isArray(datasetId) ? datasetId : []),
[datasetId],
@@ -63,7 +71,10 @@ export function useDisableDifferenceEmbeddingDataset(name: string) {
// pages, filtered out by the search box), so resolve them by ID to echo
// their names back in the form field. A dataset that has been deleted
// comes back missing and its badge falls back to the raw id.
- const { data: selectedDatasets } = useFetchDatasetsByIds(selectedDatasetIds);
+ const { data: selectedDatasets } = useFetchDatasetsByIds(
+ selectedDatasetIds,
+ ownerTenantId,
+ );
const datasetList = useMemo(() => {
return Array.from(
@@ -139,10 +150,12 @@ export function KnowledgeBaseFormField({
showVariable = false,
name = 'dataset_ids',
required = false,
+ ownerTenantId,
}: {
showVariable?: boolean;
name?: string;
required?: boolean;
+ ownerTenantId?: string;
}) {
const { t } = useTranslation();
@@ -153,7 +166,7 @@ export function KnowledgeBaseFormField({
searchString,
handleScroll,
hasNextPage,
- } = useDisableDifferenceEmbeddingDataset(name);
+ } = useDisableDifferenceEmbeddingDataset(name, ownerTenantId);
const nextOptions = buildQueryVariableOptionsByShowVariable(showVariable)();
diff --git a/web/src/components/llm-select/llm-label.test.tsx b/web/src/components/llm-select/llm-label.test.tsx
new file mode 100644
index 0000000000..0d94298c0b
--- /dev/null
+++ b/web/src/components/llm-select/llm-label.test.tsx
@@ -0,0 +1,57 @@
+/*
+ * Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+ *
+ * Licensed 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 { render, screen } from '@testing-library/react';
+import { MissingModelLabel } from './llm-label';
+
+// Untyped on purpose: files with jest.mock are transformed by esbuild-jest's
+// babel pass, which cannot strip type-only import usages.
+const mockModels = [
+ {
+ model_id: 'm1',
+ model_type: ['chat'],
+ name: 'deepseek-v4-flash',
+ provider_id: 'p1',
+ provider_name: 'OpenAI',
+ instance_id: 'i1',
+ instance_name: 'geek',
+ },
+];
+
+jest.mock('@/hooks/use-llm-request', () => ({
+ useFetchAllAddedModels: () => ({ data: mockModels }),
+}));
+
+describe('MissingModelLabel', () => {
+ it('shows the parsed name for a composite value', () => {
+ render(<MissingModelLabel value="deepseek-r1@geek@OpenAI" />);
+
+ expect(screen.getByText('deepseek-r1')).toBeInTheDocument();
+ });
+
+ it('resolves a plain model_id against the added-model list', () => {
+ render(<MissingModelLabel value="m1" />);
+
+ expect(screen.getByText('deepseek-v4-flash')).toBeInTheDocument();
+ });
+
+ it('falls back to the raw value when nothing resolves', () => {
+ const { container } = render(<MissingModelLabel value="gone" />);
+
+ expect(screen.getByText('gone')).toBeInTheDocument();
+ expect(container.querySelector('svg')).toBeInTheDocument();
+ });
+});
diff --git a/web/src/components/llm-select/llm-label.tsx b/web/src/components/llm-select/llm-label.tsx
index 8276282102..ad1d156da5 100644
--- a/web/src/components/llm-select/llm-label.tsx
+++ b/web/src/components/llm-select/llm-label.tsx
@@ -16,6 +16,7 @@
import { useFetchAllAddedModels } from '@/hooks/use-llm-request';
import { parseModelValue } from '@/utils/llm-util';
+import { TriangleAlert } from 'lucide-react';
import { memo } from 'react';
import { LlmIcon } from '../svg-icon';
@@ -24,42 +25,66 @@ interface IProps {
ownerTenantId?: string;
}
-export const LLMLabel = ({ value, ownerTenantId }: IProps) => {
+/**
+ * Resolve the display name for a persisted model value without judging its
+ * availability: composite values yield their parsed name, plain model_id
+ * values are looked up in the (optionally owner-scoped) added-model list.
+ */
+function useModelDisplayName({ value, ownerTenantId }: IProps) {
const { data: models } = useFetchAllAddedModels(undefined, ownerTenantId);
const parsed = value ? parseModelValue(value) : null;
-
- let modelName = parsed?.model_name;
- let instanceName = parsed?.model_instance;
- let iconName = parsed ? parsed.model_provider : '';
-
- if (!modelName && value) {
- const model = models.find((m) => m.model_id === value);
- if (model) {
- modelName = model.name;
- instanceName = model.instance_name;
- iconName = model.provider_name;
- }
+ if (parsed?.model_name) {
+ return parsed;
}
+ const model = value ? models.find((m) => m.model_id === value) : undefined;
+ return model
+ ? {
+ model_name: model.name,
+ model_instance: model.instance_name,
+ model_provider: model.provider_name,
+ }
+ : null;
+}
+
+export const LLMLabel = ({ value, ownerTenantId }: IProps) => {
+ const display = useModelDisplayName({ value, ownerTenantId });
- if (!modelName) return null;
+ if (!display?.model_name) return null;
return (
<div className="flex items-center gap-1.5 min-w-0">
<LlmIcon
- name={iconName}
+ name={display.model_provider}
width={22}
height={22}
imgClass="size-[22px] flex-shrink-0"
/>
- <span className="font-medium truncate">{modelName}</span>
- {instanceName && (
+ <span className="font-medium truncate">{display.model_name}</span>
+ {display.model_instance && (
<span className="text-text-secondary truncate flex-shrink-0">
- {instanceName}
+ {display.model_instance}
</span>
)}
</div>
);
};
+/**
+ * Warning marker for a persisted model value that resolves against no usable
+ * model — mirrors the retrieval node's stale-dataset row. Best-effort name:
+ * parsed composite name, else a model_id lookup in the (optionally
+ * owner-scoped) added-model list, else the raw value.
+ */
+export const MissingModelLabel = ({ value, ownerTenantId }: IProps) => {
+ const display = useModelDisplayName({ value, ownerTenantId });
+
+ return (
+ <span className="flex items-center gap-1.5 text-text-disabled">
+ <TriangleAlert className="size-4 flex-shrink-0" />
+ <span className="truncate">{display?.model_name ?? value}</span>
+ </span>
+ );
+};
+
export default memo(LLMLabel);
diff --git a/web/src/components/llm-select/next.tsx b/web/src/components/llm-select/next.tsx
index b43766d5a3..4e9cbdff29 100644
--- a/web/src/components/llm-select/next.tsx
+++ b/web/src/components/llm-select/next.tsx
@@ -15,13 +15,15 @@
*/
import { LlmModelType } from '@/constants/knowledge';
+import { useModelValidIds } from '@/hooks/use-llm-request';
import * as SelectPrimitive from '@radix-ui/react-select';
import { forwardRef, memo, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { LlmSettingFieldItems } from '../llm-setting-items/next';
+import { ModelTypeMap } from '../model-tree-select';
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
import { Select, SelectTrigger, SelectValue } from '../ui/select';
-import LLMLabel from './llm-label';
+import LLMLabel, { MissingModelLabel } from './llm-label';
export interface NextInnerLLMSelectProps {
id?: string;
@@ -63,6 +65,17 @@ const NextInnerLLMSelect = forwardRef<
}
}, [filter]);
+ // Validity is checked against the canvas owner's models: a shared canvas
+ // runs with the owner's models, while an imported dsl.json makes the
+ // importer the owner. Gated on isFetched so a slow list never flashes a
+ // false missing state. The filter-derived modelTypes only narrow the
+ // dropdown display, not validity.
+ const { validIds, isFetched: ownModelsFetched } = useModelValidIds(
+ ModelTypeMap.llm_id,
+ ownerTenantId,
+ );
+ const isModelMissing = !!value && ownModelsFetched && !validIds.has(value);
+
return (
<Select disabled={disabled} value={value}>
<Popover open={isPopoverOpen} onOpenChange={setIsPopoverOpen}>
@@ -76,7 +89,14 @@ const NextInnerLLMSelect = forwardRef<
data-testid={triggerTestId}
>
<SelectValue placeholder={t('common.pleaseSelect')}>
- <LLMLabel value={value} ownerTenantId={ownerTenantId} />
+ {isModelMissing ? (
+ <MissingModelLabel
+ value={value}
+ ownerTenantId={ownerTenantId}
+ />
+ ) : (
+ <LLMLabel value={value} ownerTenantId={ownerTenantId} />
+ )}
</SelectValue>
</SelectTrigger>
</PopoverTrigger>
diff --git a/web/src/components/memories-form-field.tsx b/web/src/components/memories-form-field.tsx
index a3406c21e4..8deed86c56 100644
--- a/web/src/components/memories-form-field.tsx
+++ b/web/src/components/memories-form-field.tsx
@@ -27,6 +27,7 @@ type MemoriesFormFieldProps = {
label: string;
name?: string;
required?: boolean;
+ ownerTenantId?: string;
};
function MemoryLabel({ text }: { text: string }) {
@@ -37,10 +38,13 @@ function MemoryLabel({ text }: { text: string }) {
);
}
-export function useDisableDifferenceEmbeddingMemory(name: string) {
+export function useDisableDifferenceEmbeddingMemory(
+ name: string,
+ ownerTenantId?: string,
+) {
const form = useFormContext();
const memoryIds = useWatch({ name, control: form.control });
- const { data: memoryListOrigin } = useFetchAllMemoryList();
+ const { data: memoryListOrigin } = useFetchAllMemoryList(ownerTenantId);
const memoryCacheRef = useRef(new Map<string, IMemory>());
const memoryList = useMemo(() => {
@@ -95,9 +99,10 @@ export function MemoriesFormField({
label,
name = 'memory_ids',
required = false,
+ ownerTenantId,
}: MemoriesFormFieldProps) {
const { t } = useTranslation();
- const { options } = useDisableDifferenceEmbeddingMemory(name);
+ const { options } = useDisableDifferenceEmbeddingMemory(name, ownerTenantId);
return (
<RAGFlowFormItem name={name} label={label} required={required}>
diff --git a/web/src/components/model-tree-select.tsx b/web/src/components/model-tree-select.tsx
index bf73f1abc4..976ace6fee 100644
--- a/web/src/components/model-tree-select.tsx
+++ b/web/src/components/model-tree-select.tsx
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import LLMLabel from '@/components/llm-select/llm-label';
+import LLMLabel, { MissingModelLabel } from '@/components/llm-select/llm-label';
import { LlmIcon } from '@/components/svg-icon';
import {
FormControl,
@@ -25,12 +25,7 @@ import {
} from '@/components/ui/form';
import { useFetchAllAddedModels } from '@/hooks/use-llm-request';
import { IAddedModel } from '@/interfaces/database/llm';
-import {
- buildModelValue,
- getRealModelName,
- parseModelValue,
-} from '@/utils/llm-util';
-import { TriangleAlert } from 'lucide-react';
+import { buildModelValue, getRealModelName } from '@/utils/llm-util';
import { forwardRef, useCallback, useEffect, useMemo } from 'react';
import { useFormContext, useWatch } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
@@ -215,16 +210,12 @@ export const ModelTreeSelect = forwardRef<
// deleted from the provider) — keep it visible with a warning marker
// instead of rendering a blank select. Prefer the readable model name over
// the raw composite id.
- const renderMissingModel = useCallback((missingValue: string) => {
- return (
- <span className="flex items-center gap-1.5 text-text-disabled">
- <TriangleAlert className="size-4 flex-shrink-0" />
- <span className="truncate">
- {parseModelValue(missingValue)?.model_name ?? missingValue}
- </span>
- </span>
- );
- }, []);
+ const renderMissingModel = useCallback(
+ (missingValue: string) => (
+ <MissingModelLabel value={missingValue} ownerTenantId={ownerTenantId} />
+ ),
+ [ownerTenantId],
+ );
return (
<TreeSelect
@@ -246,7 +237,6 @@ export const ModelTreeSelect = forwardRef<
);
});
-
export interface ModelTreeSelectFormFieldProps extends ModelTreeSelectProps {
name?: string;
label?: string;
diff --git a/web/src/components/originui/select-with-search.tsx b/web/src/components/originui/select-with-search.tsx
index e16077c101..afa2ad889f 100644
--- a/web/src/components/originui/select-with-search.tsx
+++ b/web/src/components/originui/select-with-search.tsx
@@ -66,6 +66,12 @@ export type SelectWithSearchFlagProps = {
// Return false to veto selecting the custom value on Enter
onNoMatchEnter?(searchValue: string): boolean | void;
disableAutoSelectOnEnter?: boolean;
+ // Custom display for a value matching no option (e.g. the referenced entity
+ // was deleted or is inaccessible). Opt-in: without it the raw value shows.
+ renderMissingValue?: (value: string) => ReactNode;
+ // While true, an unmatched value is treated as not-yet-loaded instead of
+ // missing, so the missing-value display doesn't flash before options arrive.
+ loading?: boolean;
testId?: string;
optionTestIdPrefix?: string;
};
@@ -142,6 +148,8 @@ export const SelectWithSearch = forwardRef<
onlyShowSelectedIcon = false,
onNoMatchEnter,
disableAutoSelectOnEnter = false,
+ renderMissingValue,
+ loading = false,
testId,
optionTestIdPrefix,
},
@@ -179,6 +187,11 @@ export const SelectWithSearch = forwardRef<
const selectLabel = selectedOption?.label;
+ // Mirrors TreeSelect: an unmatched value means the referenced option is
+ // gone — unless options may simply not have loaded yet.
+ const missingValue =
+ value && !selectedOption && !loading ? value : undefined;
+
const showSearch = useMemo(() => {
if (allowCustomValue || alwaysShowSearch) {
return true;
@@ -267,7 +280,11 @@ export const SelectWithSearch = forwardRef<
triggerClassName,
)}
>
- {selectLabel || value ? (
+ {missingValue && renderMissingValue ? (
+ <span className="flex min-w-0 items-center gap-2 truncate text-text-primary">
+ {renderMissingValue(missingValue)}
+ </span>
+ ) : selectLabel || value ? (
<span className="flex min-w-0 options-center gap-2 truncate text-text-primary">
{onlyShowSelectedIcon && selectedOption?.icon
? selectedOption.icon
diff --git a/web/src/hooks/use-compilation-template-group-request.ts b/web/src/hooks/use-compilation-template-group-request.ts
index 3d63a12d65..c112f01d2a 100644
--- a/web/src/hooks/use-compilation-template-group-request.ts
+++ b/web/src/hooks/use-compilation-template-group-request.ts
@@ -206,15 +206,35 @@ export const useDeleteCompilationTemplateGroup = () => {
return { data, loading, deleteGroup };
};
-export const useFetchAllCompilationTemplateGroups = () => {
- const { data, isFetching: loading } = useQuery<ICompilationTemplateGroup[]>({
- queryKey: CompilationTemplateGroupKeys.all(),
+export const useFetchAllCompilationTemplateGroups = (
+ ownerTenantId?: string,
+) => {
+ const {
+ data,
+ isFetching: loading,
+ isFetched,
+ isError,
+ } = useQuery<ICompilationTemplateGroup[]>({
+ queryKey: [...CompilationTemplateGroupKeys.all(), ownerTenantId],
initialData: [],
gcTime: 0,
queryFn: async () => {
+ const params: {
+ keywords: string;
+ page: number;
+ page_size: number;
+ tenant_id?: string;
+ } = {
+ keywords: '',
+ page: 1,
+ page_size: 100,
+ };
+ // Viewing a shared canvas: fetch the canvas owner's groups instead.
const { data } = await compilationTemplateGroupService.listGroups(
{
- params: { keywords: '', page: 1, page_size: 100 },
+ params: ownerTenantId
+ ? { ...params, tenant_id: ownerTenantId }
+ : params,
},
true,
);
@@ -222,14 +242,38 @@ export const useFetchAllCompilationTemplateGroups = () => {
},
});
- return { groups: data ?? [], loading };
+ // `initialData: []` keeps `isLoading` from ever firing and can't tell a real
+ // empty result apart from "fetch hasn't completed yet" — gate on `isFetched`.
+ return { groups: data ?? [], loading, isFetched, isError };
};
-export const useCompilationTemplateGroupOptions = () => {
- const { groups } = useFetchAllCompilationTemplateGroups();
+export const useCompilationTemplateGroupOptions = (ownerTenantId?: string) => {
+ const { groups, isFetched, isError } =
+ useFetchAllCompilationTemplateGroups(ownerTenantId);
- return useMemo(
+ const options = useMemo(
() => groups.map((group) => ({ label: group.name, value: group.id })),
[groups],
);
+
+ return { options, isFetched, isError };
+};
+
+/**
+ * Ids of template groups visible under the given owner tenant (the current
+ * user's own when omitted). Groups resolve per tenant at run time, so a group
+ * referenced by a shared pipeline only exists under the canvas owner's
+ * tenant. `isFetched` must be checked before trusting `validIds` — the query
+ * seeds `initialData: []`, so every id looks missing while loading.
+ */
+export const useCompilationTemplateGroupValidIds = (ownerTenantId?: string) => {
+ const { groups, isFetched } =
+ useFetchAllCompilationTemplateGroups(ownerTenantId);
+
+ const validIds = useMemo(
+ () => new Set(groups.map((group) => group.id)),
+ [groups],
+ );
+
+ return { validIds, isFetched };
};
diff --git a/web/src/hooks/use-knowledge-request-datasets.test.tsx b/web/src/hooks/use-knowledge-request-datasets.test.tsx
new file mode 100644
index 0000000000..6e1adb2a87
--- /dev/null
+++ b/web/src/hooks/use-knowledge-request-datasets.test.tsx
@@ -0,0 +1,105 @@
+/*
+ * Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+ *
+ * Licensed 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 { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { renderHook, waitFor } from '@testing-library/react';
+import {
+ useFetchDatasetsByIds,
+ useFetchKnowledgeList,
+} from './use-knowledge-request';
+
+const mockListDataset = jest.fn();
+const mockListDatasetByIds = jest.fn();
+
+jest.mock('@/services/knowledge-service', () => ({
+ listDataset: (...args: unknown[]) => mockListDataset(...args),
+ listDatasetByIds: (...args: unknown[]) => mockListDatasetByIds(...args),
+}));
+
+// route-hook (imported by the hook chain) pulls in the app shell — routes
+// constructs a browser router at module scope, which jsdom cannot survive.
+jest.mock('@/routes', () => ({ Routes: {} }));
+
+const DatasetId = '0cb944c66320448aaae827ba8009ef68';
+
+function createWrapper() {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ // `any` on purpose: files with jest.mock go through esbuild-jest's babel
+ // pass, which cannot strip imported bindings used as type annotations.
+ return function Wrapper({ children }: { children?: any }) {
+ return (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ );
+ };
+}
+
+describe('useFetchDatasetsByIds', () => {
+ beforeEach(() => {
+ mockListDatasetByIds.mockClear();
+ mockListDatasetByIds.mockResolvedValue({ data: { data: [] } });
+ });
+
+ it('passes the owner tenant through to the by-ids lookup', async () => {
+ renderHook(() => useFetchDatasetsByIds([DatasetId], 'owner-1'), {
+ wrapper: createWrapper(),
+ });
+
+ await waitFor(() => expect(mockListDatasetByIds).toHaveBeenCalled());
+ expect(mockListDatasetByIds).toHaveBeenCalledWith([DatasetId], 'owner-1');
+ });
+
+ it('leaves the owner tenant undefined for own-canvas lookups', async () => {
+ renderHook(() => useFetchDatasetsByIds([DatasetId]), {
+ wrapper: createWrapper(),
+ });
+
+ await waitFor(() => expect(mockListDatasetByIds).toHaveBeenCalled());
+ expect(mockListDatasetByIds).toHaveBeenCalledWith([DatasetId], undefined);
+ });
+});
+
+describe('useFetchKnowledgeList', () => {
+ beforeEach(() => {
+ mockListDataset.mockClear();
+ mockListDataset.mockResolvedValue({
+ data: { data: [], total_datasets: 0 },
+ });
+ });
+
+ it('adds tenant_id to the list params when an owner tenant is given', async () => {
+ renderHook(() => useFetchKnowledgeList(false, '', 30, 'owner-1'), {
+ wrapper: createWrapper(),
+ });
+
+ await waitFor(() => expect(mockListDataset).toHaveBeenCalled());
+ expect(mockListDataset).toHaveBeenCalledWith(
+ expect.objectContaining({ page: 1, page_size: 30, tenant_id: 'owner-1' }),
+ );
+ });
+
+ it('omits tenant_id without an owner tenant', async () => {
+ renderHook(() => useFetchKnowledgeList(false, 'kw'), {
+ wrapper: createWrapper(),
+ });
+
+ await waitFor(() => expect(mockListDataset).toHaveBeenCalled());
+ const params = mockListDataset.mock.calls[0][0];
+ expect(params).not.toHaveProperty('tenant_id');
+ expect(params).toMatchObject({ page: 1, keywords: 'kw' });
+ });
+});
diff --git a/web/src/hooks/use-knowledge-request.ts b/web/src/hooks/use-knowledge-request.ts
index 32046b1e4c..0b830111f0 100644
--- a/web/src/hooks/use-knowledge-request.ts
+++ b/web/src/hooks/use-knowledge-request.ts
@@ -1050,21 +1050,29 @@ export const KnowledgeListKeys = {
shouldFilterListWithoutDocument: boolean,
keywords: string,
pageSize: number,
+ ownerTenantId?: string,
) =>
[
KnowledgeApiAction.FetchKnowledgeList,
shouldFilterListWithoutDocument,
keywords,
pageSize,
+ ownerTenantId,
+ ] as const,
+ byIds: (ids: string[], ownerTenantId?: string) =>
+ [
+ KnowledgeApiAction.FetchKnowledgeList,
+ 'byIds',
+ ids,
+ ownerTenantId,
] as const,
- byIds: (ids: string[]) =>
- [KnowledgeApiAction.FetchKnowledgeList, 'byIds', ids] as const,
};
export const useFetchKnowledgeList = (
shouldFilterListWithoutDocument: boolean = false,
keywords = '',
pageSize: number = KNOWLEDGE_LIST_PAGE_SIZE,
+ ownerTenantId?: string,
): {
list: IDataset[];
loading: boolean;
@@ -1079,6 +1087,7 @@ export const useFetchKnowledgeList = (
shouldFilterListWithoutDocument,
keywords,
pageSize,
+ // ownerTenantId,
),
gcTime: 0,
initialPageParam: 1,
@@ -1088,6 +1097,8 @@ export const useFetchKnowledgeList = (
page,
page_size: pageSize,
...(keywords ? { keywords } : {}),
+ // Viewing a shared canvas: list the canvas owner's datasets.
+ // ...(ownerTenantId ? { tenant_id: ownerTenantId } : {}),
});
return {
items: (data?.data ?? []) as IDataset[],
@@ -1144,7 +1155,10 @@ export const useFetchKnowledgeList = (
* users pick variables alongside datasets); those are not resolvable ids and
* are dropped before the request is built.
*/
-export const useFetchDatasetsByIds = (ids: string[]) => {
+export const useFetchDatasetsByIds = (
+ ids: string[],
+ ownerTenantId?: string,
+) => {
const sortedIds = useMemo(() => ids.filter(isDatasetId).sort(), [ids]);
const { data, isFetching: loading } = useQuery<IDataset[]>({
queryKey: KnowledgeListKeys.byIds(sortedIds),
@@ -1169,7 +1183,10 @@ export const useFetchDatasetsByIds = (ids: string[]) => {
* empty while the lookup is in flight so consumers can hold off validation
* until it settles; `settled` flips true once the lookup has finished.
*/
-export const useStaleDatasetIds = (datasetIds?: string[]) => {
+export const useStaleDatasetIds = (
+ datasetIds?: string[],
+ ownerTenantId?: string,
+) => {
// Variable references (e.g. `sys.query`) never resolve to datasets, so
// exclude them up front instead of letting them fall out of the lookup
// below and get misreported as stale.
@@ -1177,7 +1194,10 @@ export const useStaleDatasetIds = (datasetIds?: string[]) => {
() => (datasetIds ?? []).filter(isDatasetId),
[datasetIds],
);
- const { data: datasets, loading } = useFetchDatasetsByIds(persistedIds);
+ const { data: datasets, loading } = useFetchDatasetsByIds(
+ persistedIds,
+ ownerTenantId,
+ );
const staleDatasetIds = useMemo(() => {
if (loading) {
diff --git a/web/src/hooks/use-memory-request.test.tsx b/web/src/hooks/use-memory-request.test.tsx
new file mode 100644
index 0000000000..6d1601bdf9
--- /dev/null
+++ b/web/src/hooks/use-memory-request.test.tsx
@@ -0,0 +1,88 @@
+/*
+ * Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+ *
+ * Licensed 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 { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { renderHook, waitFor } from '@testing-library/react';
+import { useFetchAllMemoryList } from './use-memory-request';
+
+const mockGetMemoryList = jest.fn();
+
+jest.mock('@/services/memory-service', () => ({
+ __esModule: true,
+ default: {
+ getMemoryList: (...args: unknown[]) => mockGetMemoryList(...args),
+ },
+}));
+
+function createWrapper() {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ // `any` on purpose: files with jest.mock go through esbuild-jest's babel
+ // pass, which cannot strip imported bindings used as type annotations.
+ return function Wrapper({ children }: { children?: any }) {
+ return (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ );
+ };
+}
+
+describe('useFetchAllMemoryList', () => {
+ beforeEach(() => {
+ mockGetMemoryList.mockClear();
+ mockGetMemoryList.mockResolvedValue({
+ data: { data: { memory_list: [] } },
+ });
+ });
+
+ it('passes tenant_id when an owner tenant is given', async () => {
+ renderHook(() => useFetchAllMemoryList('owner-1'), {
+ wrapper: createWrapper(),
+ });
+
+ await waitFor(() => expect(mockGetMemoryList).toHaveBeenCalled());
+ expect(mockGetMemoryList).toHaveBeenCalledWith(
+ {
+ params: { page_size: 100, page: 1, tenant_id: 'owner-1' },
+ data: {},
+ },
+ true,
+ );
+ });
+
+ it('omits tenant_id without an owner tenant', async () => {
+ renderHook(() => useFetchAllMemoryList(), {
+ wrapper: createWrapper(),
+ });
+
+ await waitFor(() => expect(mockGetMemoryList).toHaveBeenCalled());
+ expect(mockGetMemoryList).toHaveBeenCalledWith(
+ {
+ params: { page_size: 100, page: 1 },
+ data: {},
+ },
+ true,
+ );
+ });
+
+ it('caches owner-scoped lists separately', async () => {
+ const wrapper = createWrapper();
+ renderHook(() => useFetchAllMemoryList('owner-1'), { wrapper });
+ renderHook(() => useFetchAllMemoryList('owner-2'), { wrapper });
+
+ await waitFor(() => expect(mockGetMemoryList).toHaveBeenCalledTimes(2));
+ });
+});
diff --git a/web/src/hooks/use-memory-request.ts b/web/src/hooks/use-memory-request.ts
index 256b089215..aa32c7ea02 100644
--- a/web/src/hooks/use-memory-request.ts
+++ b/web/src/hooks/use-memory-request.ts
@@ -22,13 +22,16 @@ export const enum MemoryApiAction {
FetchMemoryList = 'fetchMemoryList',
}
-export const useFetchAllMemoryList = () => {
+export const useFetchAllMemoryList = (ownerTenantId?: string) => {
const { data, isLoading, isError, refetch } = useQuery<IMemory[], Error>({
- queryKey: [MemoryApiAction.FetchMemoryList],
+ queryKey: [MemoryApiAction.FetchMemoryList, ownerTenantId],
queryFn: async () => {
+ // Viewing a shared canvas: fetch the canvas owner's memories instead.
const { data: response } = await memoryService.getMemoryList(
{
- params: { page_size: 100, page: 1 },
+ params: ownerTenantId
+ ? { page_size: 100, page: 1, tenant_id: ownerTenantId }
+ : { page_size: 100, page: 1 },
data: {},
},
true,
diff --git a/web/src/hooks/use-stale-dataset-validation.ts b/web/src/hooks/use-stale-dataset-validation.ts
index 4fe1892894..b47c547486 100644
--- a/web/src/hooks/use-stale-dataset-validation.ts
+++ b/web/src/hooks/use-stale-dataset-validation.ts
@@ -27,15 +27,22 @@ import { useStaleDatasetIds } from './use-knowledge-request';
* persisted ids are looked up: ids picked from the dataset select are valid
* by construction, while a persisted id may reference a dataset that has
* since been deleted or emptied of chunks — those stale ids are flagged here.
+ * `ownerTenantId` scopes the lookup to the canvas owner's tenant when viewing
+ * a shared canvas.
*/
export function useStaleDatasetFormSchema<T extends z.ZodTypeAny>(
schema: T,
persistedDatasetIds?: string[],
- fieldName = 'dataset_ids',
+ {
+ fieldName = 'dataset_ids',
+ ownerTenantId,
+ }: { fieldName?: string; ownerTenantId?: string } = {},
) {
const { t } = useTranslation();
- const { staleDatasetIds, settled: datasetsFetched } =
- useStaleDatasetIds(persistedDatasetIds);
+ const { staleDatasetIds, settled: datasetsFetched } = useStaleDatasetIds(
+ persistedDatasetIds,
+ ownerTenantId,
+ );
const formSchema = useMemo(() => {
const path = fieldName.split('.');
diff --git a/web/src/hooks/use-unavailable-value-validation.test.tsx b/web/src/hooks/use-unavailable-value-validation.test.tsx
new file mode 100644
index 0000000000..9f18e64502
--- /dev/null
+++ b/web/src/hooks/use-unavailable-value-validation.test.tsx
@@ -0,0 +1,216 @@
+/*
+ * Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+ *
+ * Licensed 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 { renderHook } from '@testing-library/react';
+import { z } from 'zod';
+import {
+ useUnavailableCompilationTemplateGroupFormSchema,
+ useUnavailableModelFormSchema,
+ useUnavailableValueFormSchema,
+} from './use-unavailable-value-validation';
+
+const mockUseModelValidIds = jest.fn();
+const mockUseCompilationTemplateGroupValidIds = jest.fn();
+
+jest.mock('@/hooks/use-llm-request', () => ({
+ useModelValidIds: (...args: unknown[]) => mockUseModelValidIds(...args),
+}));
+
+jest.mock('@/hooks/use-compilation-template-group-request', () => ({
+ useCompilationTemplateGroupValidIds: (...args: unknown[]) =>
+ mockUseCompilationTemplateGroupValidIds(...args),
+}));
+
+const Schema = z.object({ llm_id: z.string() });
+
+describe('useUnavailableValueFormSchema', () => {
+ const renderValueHook = (isFetched: boolean) =>
+ renderHook(() =>
+ useUnavailableValueFormSchema(Schema, {
+ fieldName: 'llm_id',
+ validIds: new Set(['m1']),
+ isFetched,
+ message: 'custom.unavailable',
+ }),
+ );
+
+ it('flags a persisted value missing from the valid ids', () => {
+ const { result } = renderValueHook(true);
+
+ const parsed = result.current.formSchema.safeParse({ llm_id: 'gone' });
+
+ expect(parsed.success).toBe(false);
+ if (!parsed.success) {
+ expect(parsed.error.issues[0].path).toEqual(['llm_id']);
+ expect(parsed.error.issues[0].message).toBe('custom.unavailable');
+ }
+ });
+
+ it('accepts a valid id', () => {
+ const { result } = renderValueHook(true);
+
+ expect(result.current.formSchema.safeParse({ llm_id: 'm1' }).success).toBe(
+ true,
+ );
+ });
+
+ it('stays quiet while the list is loading', () => {
+ const { result } = renderValueHook(false);
+
+ expect(
+ result.current.formSchema.safeParse({ llm_id: 'gone' }).success,
+ ).toBe(true);
+ });
+
+ it('does not flag an empty value', () => {
+ const { result } = renderValueHook(true);
+
+ expect(result.current.formSchema.safeParse({ llm_id: '' }).success).toBe(
+ true,
+ );
+ });
+});
+
+describe('useUnavailableModelFormSchema', () => {
+ it('flags a persisted model missing from the current user models', () => {
+ mockUseModelValidIds.mockReturnValue({
+ validIds: new Set(['m1']),
+ isFetched: true,
+ });
+ const { result } = renderHook(() => useUnavailableModelFormSchema(Schema));
+
+ const parsed = result.current.formSchema.safeParse({ llm_id: 'gone' });
+
+ expect(parsed.success).toBe(false);
+ if (!parsed.success) {
+ expect(parsed.error.issues[0].path).toEqual(['llm_id']);
+ expect(parsed.error.issues[0].message).toBe('common.modelUnavailable');
+ }
+ });
+
+ it('accepts a usable model', () => {
+ mockUseModelValidIds.mockReturnValue({
+ validIds: new Set(['m1']),
+ isFetched: true,
+ });
+ const { result } = renderHook(() => useUnavailableModelFormSchema(Schema));
+
+ expect(result.current.formSchema.safeParse({ llm_id: 'm1' }).success).toBe(
+ true,
+ );
+ });
+
+ it('stays quiet while the model list is loading', () => {
+ mockUseModelValidIds.mockReturnValue({
+ validIds: new Set(),
+ isFetched: false,
+ });
+ const { result } = renderHook(() => useUnavailableModelFormSchema(Schema));
+
+ expect(
+ result.current.formSchema.safeParse({ llm_id: 'gone' }).success,
+ ).toBe(true);
+ });
+
+ it('validates against the given owner tenant', () => {
+ mockUseModelValidIds.mockReturnValue({
+ validIds: new Set(['m1']),
+ isFetched: true,
+ });
+ renderHook(() =>
+ useUnavailableModelFormSchema(Schema, { ownerTenantId: 'owner-1' }),
+ );
+
+ expect(mockUseModelValidIds).toHaveBeenCalledWith(
+ ['chat', 'vision'],
+ 'owner-1',
+ );
+ });
+});
+
+describe('useUnavailableCompilationTemplateGroupFormSchema', () => {
+ const TemplateSchema = z.object({
+ compilation_template_group_id: z.string(),
+ });
+
+ it('flags a template group the current user cannot resolve', () => {
+ mockUseCompilationTemplateGroupValidIds.mockReturnValue({
+ validIds: new Set(['g1']),
+ isFetched: true,
+ });
+ const { result } = renderHook(() =>
+ useUnavailableCompilationTemplateGroupFormSchema(TemplateSchema),
+ );
+
+ const parsed = result.current.formSchema.safeParse({
+ compilation_template_group_id: 'gone',
+ });
+
+ expect(parsed.success).toBe(false);
+ if (!parsed.success) {
+ expect(parsed.error.issues[0].path).toEqual([
+ 'compilation_template_group_id',
+ ]);
+ expect(parsed.error.issues[0].message).toBe(
+ 'knowledgeConfiguration.compilationTemplateUnavailable',
+ );
+ }
+ });
+
+ it('accepts a resolvable template group and stays quiet while loading', () => {
+ mockUseCompilationTemplateGroupValidIds.mockReturnValue({
+ validIds: new Set(['g1']),
+ isFetched: true,
+ });
+ const { result, rerender } = renderHook(() =>
+ useUnavailableCompilationTemplateGroupFormSchema(TemplateSchema),
+ );
+
+ expect(
+ result.current.formSchema.safeParse({
+ compilation_template_group_id: 'g1',
+ }).success,
+ ).toBe(true);
+
+ mockUseCompilationTemplateGroupValidIds.mockReturnValue({
+ validIds: new Set(),
+ isFetched: false,
+ });
+ rerender();
+
+ expect(
+ result.current.formSchema.safeParse({
+ compilation_template_group_id: 'gone',
+ }).success,
+ ).toBe(true);
+ });
+
+ it('validates against the given owner tenant', () => {
+ mockUseCompilationTemplateGroupValidIds.mockReturnValue({
+ validIds: new Set(['g1']),
+ isFetched: true,
+ });
+ renderHook(() =>
+ useUnavailableCompilationTemplateGroupFormSchema(TemplateSchema, {
+ ownerTenantId: 'owner-1',
+ }),
+ );
+
+ expect(mockUseCompilationTemplateGroupValidIds).toHaveBeenCalledWith(
+ 'owner-1',
+ );
+ });
+});
diff --git a/web/src/hooks/use-unavailable-value-validation.ts b/web/src/hooks/use-unavailable-value-validation.ts
new file mode 100644
index 0000000000..b3e9e6a17d
--- /dev/null
+++ b/web/src/hooks/use-unavailable-value-validation.ts
@@ -0,0 +1,143 @@
+/*
+ * Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+ *
+ * Licensed 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 { ModelTypeMap } from '@/components/model-tree-select';
+import { get } from 'lodash';
+import { useEffect, useMemo } from 'react';
+import { UseFormReturn, useWatch } from 'react-hook-form';
+import { useTranslation } from 'react-i18next';
+import { z } from 'zod';
+import { useCompilationTemplateGroupValidIds } from './use-compilation-template-group-request';
+import { useModelValidIds } from './use-llm-request';
+
+type UnavailableValueCheck = {
+ fieldName: string;
+ validIds: Set<string>;
+ isFetched: boolean;
+ message: string;
+};
+
+/**
+ * Extend a form schema with an availability check on one of its fields
+ * (`fieldName`, a dotted path such as `llm_id`): once the referenced-option
+ * list has loaded, a persisted value pointing at nothing the current user
+ * can use gets flagged. Mirrors use-stale-dataset-validation.
+ */
+export function useUnavailableValueFormSchema<T extends z.ZodTypeAny>(
+ schema: T,
+ { fieldName, validIds, isFetched, message }: UnavailableValueCheck,
+) {
+ const formSchema = useMemo(() => {
+ const path = fieldName.split('.');
+ return schema.superRefine((data: any, ctx) => {
+ const value = get(data, path) as string | undefined;
+ if (isFetched && value && !validIds.has(value)) {
+ ctx.addIssue({
+ path,
+ message,
+ code: z.ZodIssueCode.custom,
+ });
+ }
+ });
+ }, [schema, validIds, isFetched, fieldName, message]);
+
+ return { formSchema };
+}
+
+/**
+ * Availability check for a model field (default `llm_id`), validated against
+ * the models visible under `ownerTenantId` (the current user's own when
+ * omitted): a shared canvas runs with the owner's models, while an imported
+ * dsl.json makes the importer the owner — references pointing anywhere else
+ * get flagged.
+ */
+export function useUnavailableModelFormSchema<T extends z.ZodTypeAny>(
+ schema: T,
+ {
+ fieldName = 'llm_id',
+ modelTypes = ModelTypeMap.llm_id,
+ ownerTenantId,
+ }: { fieldName?: string; modelTypes?: string[]; ownerTenantId?: string } = {},
+) {
+ const { t } = useTranslation();
+ const { validIds, isFetched: modelsFetched } = useModelValidIds(
+ modelTypes,
+ ownerTenantId,
+ );
+
+ const { formSchema } = useUnavailableValueFormSchema(schema, {
+ fieldName,
+ validIds,
+ isFetched: modelsFetched,
+ message: t('common.modelUnavailable'),
+ });
+
+ return { formSchema, modelsFetched };
+}
+
+/**
+ * Availability check for a compilation template group field (default
+ * `compilation_template_group_id`), validated against the groups visible
+ * under `ownerTenantId`. Groups resolve per tenant at run time, so a group
+ * referenced by an imported dsl.json only exists under its original author's
+ * tenant and gets flagged.
+ */
+export function useUnavailableCompilationTemplateGroupFormSchema<
+ T extends z.ZodTypeAny,
+>(
+ schema: T,
+ {
+ fieldName = 'compilation_template_group_id',
+ ownerTenantId,
+ }: { fieldName?: string; ownerTenantId?: string } = {},
+) {
+ const { t } = useTranslation();
+ const { validIds, isFetched: templateGroupsFetched } =
+ useCompilationTemplateGroupValidIds(ownerTenantId);
+
+ const { formSchema } = useUnavailableValueFormSchema(schema, {
+ fieldName,
+ validIds,
+ isFetched: templateGroupsFetched,
+ message: t('knowledgeConfiguration.compilationTemplateUnavailable'),
+ });
+
+ return { formSchema, templateGroupsFetched };
+}
+
+/**
+ * A persisted value never fires onChange validation, so once the referenced
+ * list has loaded, revalidate explicitly — the error should be visible before
+ * submit. `form` must stay out of the effect deps (the provider recreates it
+ * on every render, which loops a failing field); `trigger` is the stable
+ * control method.
+ */
+export function useRevalidateUnavailableValue(
+ form: UseFormReturn<any>,
+ isFetched: boolean,
+ fieldName: string,
+) {
+ const value = useWatch({ control: form.control, name: fieldName });
+ const trigger = form.trigger;
+
+ useEffect(() => {
+ if (!isFetched || !value) {
+ return;
+ }
+
+ trigger(fieldName);
+ }, [trigger, isFetched, value, fieldName]);
+}
diff --git a/web/src/interfaces/request/knowledge.ts b/web/src/interfaces/request/knowledge.ts
index 1d8c09db59..b8b02b0df0 100644
--- a/web/src/interfaces/request/knowledge.ts
+++ b/web/src/interfaces/request/knowledge.ts
@@ -31,6 +31,8 @@ export interface IFetchKnowledgeListRequestParams {
keywords?: string;
owner_ids?: string[];
parser_id?: string;
+ // Viewing a shared canvas: fetch the canvas owner's datasets instead.
+ tenant_id?: string;
}
export interface IFetchDocumentListRequestBody {
diff --git a/web/src/locales/en.ts b/web/src/locales/en.ts
index 53ff9004b3..b08430686e 100644
--- a/web/src/locales/en.ts
+++ b/web/src/locales/en.ts
@@ -65,7 +65,7 @@ export default {
pleaseSelect: 'Please select',
pleaseInput: 'Please input',
modelUnavailable:
- 'The previously selected model has been deleted, please select another one',
+ 'The selected model is unavailable (deleted or no permission), please select another one',
submit: 'Submit',
clear: 'Clear',
embedIntoSite: 'Embed into webpage',
@@ -947,6 +947,8 @@ Paragraphs:
entityTypes: 'Entity types',
compilationTemplate: 'Operator',
compilationTemplateRequired: 'Please select an operator',
+ compilationTemplateUnavailable:
+ 'The selected operator is unavailable (deleted or no permission), please select another one',
createTemplate: 'Create template',
scopeFile: 'File',
vietnamese: 'Vietnamese',
@@ -2800,6 +2802,7 @@ Best for: Documents with flowing, contextually connected content — such as boo
stringTransformDescription:
'Modifies text content. Currently supports: Splitting or concatenating text.',
foundation: 'Foundation',
+ tool: 'Tool',
tools: 'Tools',
dataManipulation: 'Data manipulation',
flow: 'Flow',
@@ -2817,7 +2820,7 @@ Best for: Documents with flowing, contextually connected content — such as boo
msgTip:
'Output the variable content of the upstream component or the text entered by yourself.',
messagePlaceholder: `Please enter your message content, use '/' to quickly insert variables.`,
- messageMsg: 'Please input message or delete this field.',
+ messageMsg: 'Message cannot be empty',
addField: 'Add option',
addMessage: 'Add message',
loop: 'Loop',
@@ -3495,14 +3498,20 @@ This process aggregates variables from multiple branches into a single variable
'Extracts raw text and structure from files for downstream processing.',
tokenizer: 'Indexer',
tokenizerRequired: 'Please add the Indexer node first',
- nodeFormInvalid:
- 'Cannot save: "{{name}}" has invalid settings. Please fix them first',
- agentModelMissing:
- 'Cannot save: "{{name}}" has no model selected. Please choose one first',
- retrievalDatasetMissing:
- 'Cannot save: "{{name}}" has no dataset selected. Please choose one first',
- retrievalMemoryMissing:
- 'Cannot save: "{{name}}" has no memories selected. Please choose them first',
+ nodeFormInvalid: 'Invalid settings, please fix them first',
+ agentModelMissing: 'No model selected, please choose one first',
+ retrievalDatasetMissing: 'No dataset selected, please choose one first',
+ retrievalMemoryMissing: 'No memories selected, please choose them first',
+ checklist: 'Checklist',
+ checklistEmpty: 'No issues found',
+ checklistTitle:
+ 'Resolve the following issues before running or publishing',
+ checklistResolveBefore:
+ 'Please resolve the issues in the checklist first',
+ issueNotConnected: 'This step is not connected to anything',
+ issueVariableInvalid: 'Invalid variable: {{variable}}',
+ memoryUnavailable:
+ 'The selected memory is unavailable (deleted), please re-select',
retrievalTemplateDatasetHint:
'This template contains {{num}} retrieval step(s) without a bound dataset. Pick one below and it will be applied to all of them; you can still adjust each retrieval on the canvas after creation.',
retrievalTemplateMemoryHint:
diff --git a/web/src/locales/zh.ts b/web/src/locales/zh.ts
index 6489519ce2..ead7cd21c0 100644
--- a/web/src/locales/zh.ts
+++ b/web/src/locales/zh.ts
@@ -53,7 +53,7 @@ export default {
s: '秒',
pleaseSelect: '请选择',
pleaseInput: '请输入',
- modelUnavailable: '之前选择的模型已被删除,请重新选择',
+ modelUnavailable: '所选模型不可用(已删除或无权限),请重新选择',
submit: '提交',
clear: '清空',
embedIntoSite: '嵌入网站',
@@ -860,6 +860,8 @@ export default {
entityTypes: 'Entity 类型',
compilationTemplate: '算子',
compilationTemplateRequired: '请选择算子',
+ compilationTemplateUnavailable:
+ '所选算子不可用(已删除或无权限),请重新选择',
createTemplate: '创建模板',
scopeFile: '文件',
pageRank: '页面排名',
@@ -2418,6 +2420,7 @@ NER:使用 spaCy NER 和基于规则的关键词提取来抽取 Entities 和 R
stringTransformDescription:
'修改文本内容,目前支持文本分割、文本拼接操作',
foundation: '基础',
+ tool: '工具',
tools: '工具',
dataManipulation: '数据操控',
dialog: '对话',
@@ -2440,7 +2443,7 @@ NER:使用 spaCy NER 和基于规则的关键词提取来抽取 Entities 和 R
msg: '消息',
msgTip: '输出上游组件的变量内容或者自己输入的文本。',
messagePlaceholder: '请输入您的消息内容,使用‘/’快速插入变量。',
- messageMsg: '请输入消息或删除此字段。',
+ messageMsg: '消息不能为空',
addField: '新增字段',
addMessage: '新增消息',
loop: '循环',
@@ -3045,10 +3048,17 @@ NER:使用 spaCy NER 和基于规则的关键词提取来抽取 Entities 和 R
parserDescription: '从文件中提取原始文本和结构以供下游处理。',
tokenizer: '索引器',
tokenizerRequired: '请先添加索引器节点',
- nodeFormInvalid: '无法保存:“{{name}}” 配置有误,请先修正',
- agentModelMissing: '无法保存:“{{name}}” 未选择模型,请先选择',
- retrievalDatasetMissing: '无法保存:“{{name}}” 未选择知识库,请先选择',
- retrievalMemoryMissing: '无法保存:“{{name}}” 未选择记忆,请先选择',
+ nodeFormInvalid: '配置有误,请先修正',
+ agentModelMissing: '未选择模型,请先选择',
+ retrievalDatasetMissing: '未选择知识库,请先选择',
+ retrievalMemoryMissing: '未选择记忆,请先选择',
+ checklist: '检查清单',
+ checklistEmpty: '未发现问题',
+ checklistTitle: '请先解决以下问题再运行或发布',
+ checklistResolveBefore: '请先解决检查清单中的问题',
+ issueNotConnected: '该步骤未与任何算子连接',
+ issueVariableInvalid: '变量失效:{{variable}}',
+ memoryUnavailable: '所选记忆不可用(已删除),请重新选择',
retrievalTemplateDatasetHint:
'该模板包含 {{num}} 处未绑定知识库的检索,请在下方选择一个知识库,将应用到全部检索;创建后仍可在画布中逐处调整。',
retrievalTemplateMemoryHint:
diff --git a/web/src/pages/agent/canvas/index.tsx b/web/src/pages/agent/canvas/index.tsx
index 89401f1ce9..562a6c6d11 100644
--- a/web/src/pages/agent/canvas/index.tsx
+++ b/web/src/pages/agent/canvas/index.tsx
@@ -40,6 +40,7 @@ import { useDropdownManager } from './context';
import { AgentBackground } from '@/components/canvas/background';
import Spotlight from '@/components/spotlight';
+import { useNodeFocusRequest } from '../hooks/use-node-focus-request';
import { useNodeLoading } from '../hooks/use-node-loading';
import {
useHideFormSheetOnNodeDeletion,
@@ -156,6 +157,7 @@ function AgentCanvas({ drawerVisible, hideDrawer }: IProps) {
hideRunOrChatDrawer,
showChatModal,
showFormDrawer,
+ showFormDrawerById,
logSheetVisible,
showLogSheet,
hideLogSheet,
@@ -208,6 +210,11 @@ function AgentCanvas({ drawerVisible, hideDrawer }: IProps) {
useHideFormSheetOnNodeDeletion({ hideFormDrawer });
+ // Focus requests posted through the store (e.g. by the canvas checklist in
+ // the page header): select + center the node, and open its form sheet unless
+ // the caller only wants the highlight (orphan-step issues).
+ useNodeFocusRequest({ reactFlowInstance, showFormDrawerById });
+
const { visible, hideModal, showModal } = useSetModalState();
const [dropdownPosition, setDropdownPosition] = useState({ x: 0, y: 0 });
diff --git a/web/src/pages/agent/canvas/node/card.test.tsx b/web/src/pages/agent/canvas/node/card.test.tsx
new file mode 100644
index 0000000000..47d0df8edc
--- /dev/null
+++ b/web/src/pages/agent/canvas/node/card.test.tsx
@@ -0,0 +1,234 @@
+/*
+ * Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+ *
+ * Licensed 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 { render, screen } from '@testing-library/react';
+import { OwnerTenantIdContext } from '../../context';
+import { CompilationTemplateLabelCard, LLMLabelCard } from './card';
+
+const mockUseModelValidIds = jest.fn();
+const mockUseCompilationTemplateGroupOptions = jest.fn();
+const mockUseCompilationTemplateGroupValidIds = jest.fn();
+
+// Untyped on purpose: files with jest.mock are transformed by esbuild-jest's
+// babel pass, which cannot strip type-only import usages.
+const mockOwnerModels = [
+ {
+ model_id: 'owner-model',
+ model_type: ['chat'],
+ name: 'deepseek-v4-flash',
+ provider_id: 'p1',
+ provider_name: 'OpenAI',
+ instance_id: 'i1',
+ instance_name: 'geek',
+ },
+];
+
+jest.mock('@/hooks/use-llm-request', () => ({
+ useModelValidIds: (...args: unknown[]) => mockUseModelValidIds(...args),
+ // The display name resolves through the owner's list; validity does not.
+ useFetchAllAddedModels: () => ({ data: mockOwnerModels }),
+}));
+
+jest.mock('@/hooks/use-compilation-template-group-request', () => ({
+ useCompilationTemplateGroupOptions: (...args: unknown[]) =>
+ mockUseCompilationTemplateGroupOptions(...args),
+ useCompilationTemplateGroupValidIds: (...args: unknown[]) =>
+ mockUseCompilationTemplateGroupValidIds(...args),
+}));
+
+// LlmIcon relies on theme hooks that jsdom cannot satisfy.
+jest.mock('@/components/svg-icon', () => ({
+ LlmIcon: () => null,
+}));
+
+function renderCard(llmId?: string) {
+ return render(
+ <OwnerTenantIdContext.Provider value="owner-tenant">
+ <LLMLabelCard llmId={llmId} />
+ </OwnerTenantIdContext.Provider>,
+ );
+}
+
+function renderGroupCard(groupId?: string) {
+ return render(
+ <OwnerTenantIdContext.Provider value="owner-tenant">
+ <CompilationTemplateLabelCard groupId={groupId} />
+ </OwnerTenantIdContext.Provider>,
+ );
+}
+
+describe('LLMLabelCard', () => {
+ it('flags a model missing from the current user list, keeping the owner-resolved name', () => {
+ mockUseModelValidIds.mockReturnValue({
+ validIds: new Set(['m1']),
+ isFetched: true,
+ });
+
+ const { container } = renderCard('owner-model');
+
+ expect(screen.getByText('deepseek-v4-flash')).toBeInTheDocument();
+ expect(screen.getByTitle('common.modelUnavailable')).toBeInTheDocument();
+ expect(container.querySelector('.border-state-error')).not.toBeNull();
+ expect(container.querySelector('svg.text-state-error')).not.toBeNull();
+ });
+
+ it('shows no error state for a usable model', () => {
+ mockUseModelValidIds.mockReturnValue({
+ validIds: new Set(['owner-model']),
+ isFetched: true,
+ });
+
+ const { container } = renderCard('owner-model');
+
+ expect(screen.queryByTitle('common.modelUnavailable')).toBeNull();
+ expect(container.querySelector('.border-state-error')).toBeNull();
+ expect(container.querySelector('svg.text-state-error')).toBeNull();
+ });
+
+ it('stays neutral while the model list is loading', () => {
+ mockUseModelValidIds.mockReturnValue({
+ validIds: new Set(),
+ isFetched: false,
+ });
+
+ const { container } = renderCard('owner-model');
+
+ expect(screen.queryByTitle('common.modelUnavailable')).toBeNull();
+ expect(container.querySelector('.border-state-error')).toBeNull();
+ });
+
+ it('keeps the historical red state for an empty model', () => {
+ mockUseModelValidIds.mockReturnValue({
+ validIds: new Set(['m1']),
+ isFetched: true,
+ });
+
+ const { container } = renderCard(undefined);
+
+ expect(container.querySelector('.border-state-error')).not.toBeNull();
+ expect(screen.queryByTitle('common.modelUnavailable')).toBeNull();
+ expect(container.querySelector('svg.text-state-error')).toBeNull();
+ });
+
+ it('validates against the canvas owner tenant', () => {
+ mockUseModelValidIds.mockReturnValue({
+ validIds: new Set(['m1']),
+ isFetched: true,
+ });
+
+ renderCard('m1');
+
+ expect(mockUseModelValidIds).toHaveBeenCalledWith(
+ ['chat', 'vision'],
+ 'owner-tenant',
+ );
+ });
+});
+
+describe('CompilationTemplateLabelCard', () => {
+ beforeEach(() => {
+ mockUseCompilationTemplateGroupOptions.mockReturnValue({
+ options: [{ label: 'Group A', value: 'g1' }],
+ isFetched: true,
+ isError: false,
+ });
+ });
+
+ it('flags a group the current user cannot resolve', () => {
+ mockUseCompilationTemplateGroupValidIds.mockReturnValue({
+ validIds: new Set(['g1']),
+ isFetched: true,
+ });
+
+ const { container } = renderGroupCard('gone');
+
+ expect(screen.getByText('gone')).toBeInTheDocument();
+ expect(
+ screen.getByTitle(
+ 'knowledgeConfiguration.compilationTemplateUnavailable',
+ ),
+ ).toBeInTheDocument();
+ expect(container.querySelector('.border-state-error')).not.toBeNull();
+ expect(container.querySelector('svg.text-state-error')).not.toBeNull();
+ });
+
+ it('shows no error state for a resolvable group', () => {
+ mockUseCompilationTemplateGroupValidIds.mockReturnValue({
+ validIds: new Set(['g1']),
+ isFetched: true,
+ });
+
+ const { container } = renderGroupCard('g1');
+
+ expect(screen.getByText('Group A')).toBeInTheDocument();
+ expect(
+ screen.queryByTitle(
+ 'knowledgeConfiguration.compilationTemplateUnavailable',
+ ),
+ ).toBeNull();
+ expect(container.querySelector('.border-state-error')).toBeNull();
+ expect(container.querySelector('svg.text-state-error')).toBeNull();
+ });
+
+ it('stays neutral while the group list is loading', () => {
+ mockUseCompilationTemplateGroupValidIds.mockReturnValue({
+ validIds: new Set(),
+ isFetched: false,
+ });
+
+ const { container } = renderGroupCard('gone');
+
+ expect(
+ screen.queryByTitle(
+ 'knowledgeConfiguration.compilationTemplateUnavailable',
+ ),
+ ).toBeNull();
+ expect(container.querySelector('.border-state-error')).toBeNull();
+ });
+
+ it('stays neutral for an empty group — the checklist covers unconfigured nodes', () => {
+ mockUseCompilationTemplateGroupValidIds.mockReturnValue({
+ validIds: new Set(['g1']),
+ isFetched: true,
+ });
+
+ const { container } = renderGroupCard(undefined);
+
+ expect(container.querySelector('.border-state-error')).toBeNull();
+ expect(
+ screen.queryByTitle(
+ 'knowledgeConfiguration.compilationTemplateUnavailable',
+ ),
+ ).toBeNull();
+ expect(container.querySelector('svg.text-state-error')).toBeNull();
+ });
+
+ it('resolves names and validity against the canvas owner tenant', () => {
+ mockUseCompilationTemplateGroupValidIds.mockReturnValue({
+ validIds: new Set(['g1']),
+ isFetched: true,
+ });
+
+ renderGroupCard('g1');
+
+ expect(mockUseCompilationTemplateGroupOptions).toHaveBeenCalledWith(
+ 'owner-tenant',
+ );
+ expect(mockUseCompilationTemplateGroupValidIds).toHaveBeenCalledWith(
+ 'owner-tenant',
+ );
+ });
+});
diff --git a/web/src/pages/agent/canvas/node/card.tsx b/web/src/pages/agent/canvas/node/card.tsx
index 180d95f6c7..6b00787f61 100644
--- a/web/src/pages/agent/canvas/node/card.tsx
+++ b/web/src/pages/agent/canvas/node/card.tsx
@@ -1,4 +1,5 @@
import LLMLabel from '@/components/llm-select/llm-label';
+import { ModelTypeMap } from '@/components/model-tree-select';
import { Button } from '@/components/ui/button';
import {
Card,
@@ -17,10 +18,15 @@ import {
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
-import { useFetchAllAddedModels } from '@/hooks/use-llm-request';
+import {
+ useCompilationTemplateGroupOptions,
+ useCompilationTemplateGroupValidIds,
+} from '@/hooks/use-compilation-template-group-request';
+import { useModelValidIds } from '@/hooks/use-llm-request';
import { cn } from '@/lib/utils';
-import { parseModelValue } from '@/utils/llm-util';
-import { PropsWithChildren, useMemo } from 'react';
+import { TriangleAlert } from 'lucide-react';
+import { PropsWithChildren } from 'react';
+import { useTranslation } from 'react-i18next';
import { useOwnerTenantId } from '../../context';
export function CardWithForm() {
@@ -83,33 +89,76 @@ export function LabelCard({ children, className, ...props }: LabelCardProps) {
export function LLMLabelCard({ llmId }: { llmId?: string }) {
const ownerTenantId = useOwnerTenantId();
- const { data: allAddedModels } = useFetchAllAddedModels(
- undefined,
+ const { t } = useTranslation();
+ // Validity is checked against the canvas owner's models: a shared canvas
+ // runs with the owner's models, while an imported dsl.json makes the
+ // importer the owner — anything else is flagged. Gated on isFetched so a
+ // slow list never flashes a false error state. The display name likewise
+ // resolves through the owner's list.
+ const { validIds, isFetched } = useModelValidIds(
+ ModelTypeMap.llm_id,
ownerTenantId,
);
- const isValidLlm = useMemo(() => {
- if (!llmId) return false;
+ const isUnavailable = !!llmId && isFetched && !validIds.has(llmId);
+ // An empty model keeps the historical red state; a loading list shows nothing.
+ const isInvalid = llmId ? isUnavailable : true;
- const parsed = parseModelValue(llmId);
- if (parsed) {
- return allAddedModels.some(
- (m) =>
- m.name === parsed.model_name &&
- m.instance_name === parsed.model_instance &&
- m.provider_name === parsed.model_provider,
- );
- }
+ return (
+ <LabelCard
+ className={isInvalid ? 'bg-state-error-5 border-state-error border' : ''}
+ title={isUnavailable ? t('common.modelUnavailable') : undefined}
+ >
+ <span className="flex items-center gap-1.5">
+ {isUnavailable && (
+ <TriangleAlert className="size-4 shrink-0 text-state-error" />
+ )}
+ <LLMLabel value={llmId} ownerTenantId={ownerTenantId}></LLMLabel>
+ </span>
+ </LabelCard>
+ );
+}
+
+export function CompilationTemplateLabelCard({
+ groupId,
+}: {
+ groupId?: string;
+}) {
+ const { t } = useTranslation();
+ const ownerTenantId = useOwnerTenantId();
+ const { options } = useCompilationTemplateGroupOptions(ownerTenantId);
+ // Validity is checked against the canvas owner's groups: a shared canvas
+ // runs with the owner's groups, while an imported dsl.json makes the
+ // importer the owner — anything else is flagged. Gated on isFetched so a
+ // slow list never flashes a false error state.
+ const { validIds, isFetched } =
+ useCompilationTemplateGroupValidIds(ownerTenantId);
- // value is a plain model_id rather than the composite string
- return allAddedModels.some((m) => m.model_id === llmId);
- }, [allAddedModels, llmId]);
+ const isUnavailable = !!groupId && isFetched && !validIds.has(groupId);
+ const groupName =
+ options.find((option) => option.value === groupId)?.label ?? groupId;
return (
<LabelCard
- className={isValidLlm ? '' : 'bg-state-error-5 border-state-error border'}
+ className={cn(
+ 'text-text-primary flex justify-between flex-col gap-1',
+ isUnavailable && 'bg-state-error-5 border-state-error border',
+ )}
+ title={
+ isUnavailable
+ ? t('knowledgeConfiguration.compilationTemplateUnavailable')
+ : undefined
+ }
>
- <LLMLabel value={llmId} ownerTenantId={ownerTenantId}></LLMLabel>
+ <span className="text-text-secondary">
+ {t('knowledgeConfiguration.compilationTemplate')}
+ </span>
+ <span className="flex items-center gap-1.5">
+ {isUnavailable && (
+ <TriangleAlert className="size-4 shrink-0 text-state-error" />
+ )}
+ <span className="truncate">{groupName}</span>
+ </span>
</LabelCard>
);
}
diff --git a/web/src/pages/agent/canvas/node/compilation-node.tsx b/web/src/pages/agent/canvas/node/compilation-node.tsx
index bb5f0aaf2e..ba6d4f63ff 100644
--- a/web/src/pages/agent/canvas/node/compilation-node.tsx
+++ b/web/src/pages/agent/canvas/node/compilation-node.tsx
@@ -1,30 +1,21 @@
-import { useCompilationTemplateGroupOptions } from '@/hooks/use-compilation-template-group-request';
import { IRagNode } from '@/interfaces/database/agent';
import { NodeProps } from '@xyflow/react';
import { get } from 'lodash';
-import { LabelCard, LLMLabelCard } from './card';
+import { CompilationTemplateLabelCard, LLMLabelCard } from './card';
import { RagNode } from './index';
-import { useTranslation } from 'react-i18next';
export function CompilationNode({ ...props }: NodeProps<IRagNode>) {
const { data } = props;
- const { t } = useTranslation();
- const options = useCompilationTemplateGroupOptions();
const groupId = get(data, 'form.compilation_template_group_id');
const llmId = get(data, 'form.llm_id');
- const groupName =
- options.find((option) => option.value === groupId)?.label ?? groupId;
return (
<RagNode {...props}>
<section className="flex flex-col gap-2">
<LLMLabelCard llmId={llmId}></LLMLabelCard>
- <LabelCard className="text-text-primary flex justify-between flex-col gap-1">
- <span className="text-text-secondary">
- {t('knowledgeConfiguration.compilationTemplate')}
- </span>
- <div className="truncate">{groupName}</div>
- </LabelCard>
+ <CompilationTemplateLabelCard
+ groupId={groupId}
+ ></CompilationTemplateLabelCard>
</section>
</RagNode>
);
diff --git a/web/src/pages/agent/canvas/node/note-node/index.tsx b/web/src/pages/agent/canvas/node/note-node/index.tsx
index a9fa7a94e9..f91eb24deb 100644
--- a/web/src/pages/agent/canvas/node/note-node/index.tsx
+++ b/web/src/pages/agent/canvas/node/note-node/index.tsx
@@ -66,13 +66,13 @@ function NoteNode({
showCopy={false}
>
<NodeWrapper
- className="p-0 w-full h-full flex flex-col bg-bg-component border border-state-warning rounded-lg shadow-md pb-1"
+ className="p-0 w-full h-full flex flex-col bg-bg-component border border-accent-primary rounded-lg shadow-md pb-1"
selected={selected}
>
<NodeResizeControl minWidth={190} minHeight={128} style={controlStyle}>
<ResizeIcon />
</NodeResizeControl>
- <section className="px-2 py-1 flex gap-2 items-center note-drag-handle rounded-t border-t-2 border-state-warning">
+ <section className="px-2 py-1 flex gap-2 items-center note-drag-handle rounded-t border-t-2 border-accent-primary">
<NotebookPen className="size-4" />
<Form {...nameForm}>
<form onSubmit={nameForm.handleSubmit(() => {})} className="flex-1">
diff --git a/web/src/pages/agent/canvas/node/retrieval-node.tsx b/web/src/pages/agent/canvas/node/retrieval-node.tsx
index c3217a56eb..d75ee706a1 100644
--- a/web/src/pages/agent/canvas/node/retrieval-node.tsx
+++ b/web/src/pages/agent/canvas/node/retrieval-node.tsx
@@ -13,6 +13,7 @@ import { TriangleAlert } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { NodeHandleId, RetrievalFrom } from '../../constant';
+import { useOwnerTenantId } from '../../context';
import { RetrievalFormSchemaType } from '../../form/retrieval-form/next';
import { useGetVariableLabelOrTypeByValue } from '../../hooks/use-get-begin-query';
import { LabelCard } from './card';
@@ -38,17 +39,28 @@ function InnerRetrievalNode({
const persistedDatasetIds = isMemory ? [] : knowledgeBaseIds;
+ // Names resolve through the canvas owner's datasets/memories — a shared
+ // canvas references the owner's resources, while an imported dsl.json makes
+ // the importer the owner.
+ const ownerTenantId = useOwnerTenantId();
+
// Resolve names/avatars for the persisted ids directly: the paginated
// knowledge list can miss them (unloaded pages, emptied datasets filtered
// out). Shares the byIds query with the staleness check below.
- const { data: datasets } = useFetchDatasetsByIds(persistedDatasetIds);
+ const { data: datasets } = useFetchDatasetsByIds(
+ persistedDatasetIds,
+ ownerTenantId,
+ );
// Mirror the form's stale-dataset validation: a persisted id referencing a
// dataset that has since been deleted or emptied of chunks is flagged on
// the node as well. Stays empty while the lookup is in flight.
- const { staleDatasetIds } = useStaleDatasetIds(persistedDatasetIds);
+ const { staleDatasetIds } = useStaleDatasetIds(
+ persistedDatasetIds,
+ ownerTenantId,
+ );
- const memoryList = useFetchAllMemoryList();
+ const memoryList = useFetchAllMemoryList(ownerTenantId);
return (
<ToolBar selected={selected} id={id} label={data.label}>
diff --git a/web/src/pages/agent/components/canvas-checklist.test.tsx b/web/src/pages/agent/components/canvas-checklist.test.tsx
new file mode 100644
index 0000000000..619e50013c
--- /dev/null
+++ b/web/src/pages/agent/components/canvas-checklist.test.tsx
@@ -0,0 +1,80 @@
+import { fireEvent, render, screen } from '@testing-library/react';
+import useGraphStore from '../store';
+import { CanvasIssue, CanvasIssueType } from '../utils/canvas-checklist';
+import { CanvasChecklist } from './canvas-checklist';
+
+// Radix Popover measures via ResizeObserver, which jsdom does not provide.
+class ResizeObserverMock {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+(globalThis as Record<string, unknown>).ResizeObserver = ResizeObserverMock;
+
+const issue: CanvasIssue = {
+ nodeId: 'Message:m1',
+ nodeName: 'Message',
+ operatorLabel: 'Message',
+ type: CanvasIssueType.MissingRequired,
+ messageKey: 'flow.messageMsg',
+};
+
+describe('CanvasChecklist', () => {
+ beforeEach(() => {
+ useGraphStore.setState({ nodeFocusRequest: null });
+ });
+
+ it('posts a node focus request with the form opened for variable issues', () => {
+ render(<CanvasChecklist issues={[issue]} />);
+
+ fireEvent.click(screen.getByTestId('canvas-checklist'));
+ fireEvent.click(screen.getByTestId('canvas-checklist-issue'));
+
+ expect(useGraphStore.getState().nodeFocusRequest).toEqual({
+ nodeId: 'Message:m1',
+ toolId: undefined,
+ openForm: true,
+ nonce: expect.any(Number),
+ });
+ });
+
+ it('only highlights the node for orphan issues', () => {
+ render(
+ <CanvasChecklist issues={[{ ...issue, type: CanvasIssueType.Orphan }]} />,
+ );
+
+ fireEvent.click(screen.getByTestId('canvas-checklist'));
+ fireEvent.click(screen.getByTestId('canvas-checklist-issue'));
+
+ expect(useGraphStore.getState().nodeFocusRequest).toEqual({
+ nodeId: 'Message:m1',
+ toolId: undefined,
+ openForm: false,
+ nonce: expect.any(Number),
+ });
+ });
+
+ it('groups issues from different tools of the same agent separately', () => {
+ const toolIssue = (toolId: string, nodeName: string): CanvasIssue => ({
+ nodeId: 'Tool:t1',
+ toolId,
+ nodeName,
+ operatorLabel: 'Retrieval',
+ type: CanvasIssueType.MissingRequired,
+ messageKey: 'flow.retrievalDatasetMissing',
+ });
+ render(
+ <CanvasChecklist
+ issues={[
+ toolIssue('tool-1', 'Agent / DocsA'),
+ toolIssue('tool-2', 'Agent / DocsB'),
+ ]}
+ />,
+ );
+
+ fireEvent.click(screen.getByTestId('canvas-checklist'));
+
+ expect(screen.getByText('Agent / DocsA')).toBeInTheDocument();
+ expect(screen.getByText('Agent / DocsB')).toBeInTheDocument();
+ });
+});
diff --git a/web/src/pages/agent/components/canvas-checklist.tsx b/web/src/pages/agent/components/canvas-checklist.tsx
new file mode 100644
index 0000000000..8a4a97bed5
--- /dev/null
+++ b/web/src/pages/agent/components/canvas-checklist.tsx
@@ -0,0 +1,172 @@
+/*
+ * Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+ *
+ * Licensed 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 OperatorIcon from '@/components/operator-icon';
+import { Button } from '@/components/ui/button';
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from '@/components/ui/popover';
+import { ListChecks, MoveRight } from 'lucide-react';
+import { useCallback, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Operator } from '../constant';
+import useGraphStore from '../store';
+import { CanvasIssue, CanvasIssueType } from '../utils/canvas-checklist';
+
+type IssueGroup = {
+ key: string;
+ nodeName: string;
+ operatorLabel: string;
+ items: CanvasIssue[];
+};
+
+function groupIssuesByNode(issues: CanvasIssue[]): IssueGroup[] {
+ const groups = new Map<string, IssueGroup>();
+ for (const issue of issues) {
+ // Composite key: multiple embedded tools of one agent share the Tool
+ // canvas node (nodeId) but must each get their own group; the agent-form
+ // fallback (no toolId) distinguishes them by display name.
+ const key = `${issue.nodeId}::${issue.toolId ?? issue.nodeName}`;
+ const group = groups.get(key);
+ if (group) {
+ group.items.push(issue);
+ } else {
+ groups.set(key, {
+ key,
+ nodeName: issue.nodeName,
+ operatorLabel: issue.operatorLabel,
+ items: [issue],
+ });
+ }
+ }
+ return [...groups.values()];
+}
+
+function IssueCountBadge({ count }: { count: number }) {
+ if (count <= 0) {
+ return null;
+ }
+ return (
+ <span className="shrink-0 rounded-full bg-state-warning px-1.5 py-0.5 text-[10px] leading-none">
+ {count}
+ </span>
+ );
+}
+
+function ChecklistIssueItem({
+ issue,
+ onLocate,
+}: {
+ issue: CanvasIssue;
+ onLocate: (issue: CanvasIssue) => void;
+}) {
+ const { t } = useTranslation();
+ const handleClick = useCallback(() => {
+ onLocate(issue);
+ }, [issue, onLocate]);
+
+ return (
+ <li>
+ <button
+ type="button"
+ data-testid="canvas-checklist-issue"
+ onClick={handleClick}
+ className="group flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left hover:bg-bg-base-hover"
+ >
+ <span className="size-1.5 shrink-0 rounded-full bg-state-warning" />
+ <span className="flex-1 text-sm text-state-warning">
+ {t(issue.messageKey, issue.messageParams)}
+ </span>
+ <MoveRight className="size-4 shrink-0 text-text-disabled opacity-0 group-hover:opacity-100" />
+ </button>
+ </li>
+ );
+}
+
+/**
+ * Top-right canvas checklist: a live count of canvas issues (dangling
+ * variables, missing required fields, orphan steps) grouped by node. Variable
+ * issues locate the node and open its form; orphan issues only highlight it.
+ */
+export function CanvasChecklist({ issues }: { issues: CanvasIssue[] }) {
+ const { t } = useTranslation();
+ const [open, setOpen] = useState(false);
+ const requestNodeFocus = useGraphStore((state) => state.requestNodeFocus);
+
+ const groups = useMemo(() => groupIssuesByNode(issues), [issues]);
+
+ const handleLocate = useCallback(
+ (issue: CanvasIssue) => {
+ requestNodeFocus(issue.nodeId, {
+ toolId: issue.toolId,
+ openForm: issue.type !== CanvasIssueType.Orphan,
+ });
+ setOpen(false);
+ },
+ [requestNodeFocus],
+ );
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <Button variant={'secondary'} data-testid="canvas-checklist">
+ <ListChecks />
+ {t('flow.checklist')}
+ <IssueCountBadge count={issues.length} />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="end" className="w-96 p-0">
+ <div className="border-b border-border-default px-4 py-3">
+ <div className="flex items-center gap-2 text-sm font-medium text-text-primary">
+ <ListChecks className="size-4" />
+ {t('flow.checklist')}
+ <IssueCountBadge count={issues.length} />
+ </div>
+ <p className="mt-1 text-xs text-text-secondary">
+ {t('flow.checklistTitle')}
+ </p>
+ </div>
+ {issues.length === 0 ? (
+ <div className="px-4 py-6 text-center text-sm text-text-secondary">
+ {t('flow.checklistEmpty')}
+ </div>
+ ) : (
+ <div className="max-h-80 space-y-2 overflow-y-auto p-2">
+ {groups.map((group) => (
+ <section key={group.key} className="rounded-lg bg-bg-card p-1.5">
+ <header className="flex items-center gap-2 px-1.5 py-1 text-sm font-medium text-text-primary">
+ <OperatorIcon name={group.operatorLabel as Operator} />
+ <span className="truncate">{group.nodeName}</span>
+ </header>
+ <ul>
+ {group.items.map((issue, index) => (
+ <ChecklistIssueItem
+ key={`${issue.messageKey}-${issue.messageParams?.variable ?? index}`}
+ issue={issue}
+ onLocate={handleLocate}
+ />
+ ))}
+ </ul>
+ </section>
+ ))}
+ </div>
+ )}
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/web/src/pages/agent/components/publish-confirm-dialog.tsx b/web/src/pages/agent/components/publish-confirm-dialog.tsx
index 208c551af0..0254fefcf8 100644
--- a/web/src/pages/agent/components/publish-confirm-dialog.tsx
+++ b/web/src/pages/agent/components/publish-confirm-dialog.tsx
@@ -7,7 +7,6 @@ import {
DialogFooter,
DialogHeader,
DialogTitle,
- DialogTrigger,
} from '@/components/ui/dialog';
import { IFlow } from '@/interfaces/database/agent';
import { IDataset } from '@/interfaces/database/dataset';
@@ -21,6 +20,9 @@ interface PublishConfirmDialogProps {
agentDetail: IFlow;
loading: boolean;
onPublish: () => void;
+ // Returning true blocks the dialog from opening (e.g. unresolved canvas
+ // checklist issues) — the caller is responsible for the user-facing notice.
+ onBeforeOpen?: () => boolean;
}
function AssociatedDataset({
@@ -64,6 +66,7 @@ export function PublishConfirmDialog({
agentDetail,
loading,
onPublish,
+ onBeforeOpen,
}: PublishConfirmDialogProps) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
@@ -86,17 +89,28 @@ export function PublishConfirmDialog({
setOpen(false);
}, [onPublish]);
+ // A plain button instead of DialogTrigger: Radix opens the dialog on click
+ // regardless of preventDefault, so the guard has to own `setOpen`.
+ const handleTriggerClick = useCallback(() => {
+ if (onBeforeOpen?.()) {
+ return;
+ }
+ setOpen(true);
+ }, [onBeforeOpen]);
+
if (isPipeline) {
return null;
}
return (
<Dialog open={open} onOpenChange={setOpen}>
- <DialogTrigger asChild>
- <ButtonLoading variant={'secondary'} loading={loading}>
- <BookPlus /> {t('flow.release')}
- </ButtonLoading>
- </DialogTrigger>
+ <ButtonLoading
+ variant={'secondary'}
+ loading={loading}
+ onClick={handleTriggerClick}
+ >
+ <BookPlus /> {t('flow.release')}
+ </ButtonLoading>
<DialogContent>
<DialogHeader>
<DialogTitle>{t('flow.confirmPublish')}</DialogTitle>
diff --git a/web/src/pages/agent/form/agent-form/index.tsx b/web/src/pages/agent/form/agent-form/index.tsx
index 26efd8f29c..43e24a6e0f 100644
--- a/web/src/pages/agent/form/agent-form/index.tsx
+++ b/web/src/pages/agent/form/agent-form/index.tsx
@@ -22,6 +22,10 @@ import { Separator } from '@/components/ui/separator';
import { Switch } from '@/components/ui/switch';
import NumberInputStepper from '@/components/originui/number-input';
import { useFindLlmByUuid } from '@/hooks/use-llm-request';
+import {
+ useRevalidateUnavailableValue,
+ useUnavailableModelFormSchema,
+} from '@/hooks/use-unavailable-value-validation';
import { zodResolver } from '@hookform/resolvers/zod';
import { get } from 'lodash';
import { memo, useEffect, useMemo } from 'react';
@@ -34,6 +38,7 @@ import {
NodeHandleId,
VariableType,
} from '../../constant';
+import { useOwnerTenantId } from '../../context';
import { INextOperatorForm } from '../../interface';
import useGraphStore from '../../store';
import { hasSubAgentOrTool, isBottomSubAgent } from '../../utils';
@@ -96,6 +101,12 @@ function AgentForm({ node }: INextOperatorForm) {
const defaultValues = useValues(node);
+ const ownerTenantId = useOwnerTenantId();
+ const { formSchema, modelsFetched } = useUnavailableModelFormSchema(
+ FormSchema,
+ { ownerTenantId },
+ );
+
const { extraOptions } = useBuildPromptExtraPromptOptions(edges, node?.id);
const ExceptionMethodOptions = Object.values(AgentExceptionMethod).map(
@@ -111,7 +122,7 @@ function AgentForm({ node }: INextOperatorForm) {
const form = useForm<AgentFormSchemaType>({
defaultValues: defaultValues,
- resolver: zodResolver(FormSchema),
+ resolver: zodResolver(formSchema),
});
const llmId = useWatch({ control: form.control, name: 'llm_id' });
@@ -159,12 +170,16 @@ function AgentForm({ node }: INextOperatorForm) {
useWatchFormChange(node?.id, form);
+ // A persisted model from a shared canvas may be unusable to the current
+ // user — surface the error once the model list has loaded.
+ useRevalidateUnavailableValue(form, modelsFetched, 'llm_id');
+
return (
<>
<Form {...form}>
<FormWrapper>
{isSubAgent && <DescriptionField></DescriptionField>}
- <LargeModelFormField></LargeModelFormField>
+ <LargeModelFormField ownerTenantId={ownerTenantId} />
{(mcpIds.length > 0 || hasSubAgentOrTool(edges, node?.id)) && (
<FormField
control={form.control}
diff --git a/web/src/pages/agent/form/compilation-form/index.tsx b/web/src/pages/agent/form/compilation-form/index.tsx
index 90829e7dab..fcdebc19a3 100644
--- a/web/src/pages/agent/form/compilation-form/index.tsx
+++ b/web/src/pages/agent/form/compilation-form/index.tsx
@@ -5,6 +5,11 @@ import {
} from '@/components/llm-setting-items/next';
import { useSyncExternalFormErrors } from '@/components/pipeline-operator-tabs/use-sync-external-form-errors';
import { Form } from '@/components/ui/form';
+import {
+ useRevalidateUnavailableValue,
+ useUnavailableCompilationTemplateGroupFormSchema,
+ useUnavailableModelFormSchema,
+} from '@/hooks/use-unavailable-value-validation';
import { zodResolver } from '@hookform/resolvers/zod';
import type { TFunction } from 'i18next';
import { memo } from 'react';
@@ -50,10 +55,18 @@ const CompilationForm = ({
const defaultValues = useFormValues(initialCompilationValues, node);
const ownerTenantId = useOwnerTenantId();
const FormSchema = useFormSchema();
+ const { formSchema: groupFormSchema, templateGroupsFetched } =
+ useUnavailableCompilationTemplateGroupFormSchema(FormSchema, {
+ ownerTenantId,
+ });
+ const { formSchema, modelsFetched } = useUnavailableModelFormSchema(
+ groupFormSchema,
+ { ownerTenantId },
+ );
const form = useForm<CompilationFormSchemaType>({
defaultValues,
- resolver: zodResolver(FormSchema),
+ resolver: zodResolver(formSchema),
mode: 'onChange',
});
@@ -62,10 +75,22 @@ const CompilationForm = ({
useWatchFormChange(node?.id, form);
useFormChangeCallback(form, onValuesChange);
+ // Persisted model/group references from an imported dsl.json do not exist
+ // under the importer's tenant — surface the errors once the lists load.
+ useRevalidateUnavailableValue(
+ form,
+ templateGroupsFetched,
+ 'compilation_template_group_id',
+ );
+ useRevalidateUnavailableValue(form, modelsFetched, 'llm_id');
+
return (
<Form {...form}>
<FormWrapper>
- <CompilationTemplateFormField name="compilation_template_group_id"></CompilationTemplateFormField>
+ <CompilationTemplateFormField
+ name="compilation_template_group_id"
+ ownerTenantId={ownerTenantId}
+ ></CompilationTemplateFormField>
<LlmSettingFieldItems
ownerTenantId={ownerTenantId}
></LlmSettingFieldItems>
diff --git a/web/src/pages/agent/form/message-form/index.tsx b/web/src/pages/agent/form/message-form/index.tsx
index 5e3d73e1c3..42cfbd12fb 100644
--- a/web/src/pages/agent/form/message-form/index.tsx
+++ b/web/src/pages/agent/form/message-form/index.tsx
@@ -18,6 +18,7 @@ import { useFieldArray, useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { z } from 'zod';
import { ExportFileType } from '../../constant';
+import { useOwnerTenantId } from '../../context';
import { INextOperatorForm } from '../../interface';
import { FormWrapper } from '../components/form-wrapper';
import { PromptEditor } from '../components/prompt-editor';
@@ -28,6 +29,7 @@ import { useWatchFormChange } from './use-watch-change';
function MessageForm({ node }: INextOperatorForm) {
const { t } = useTranslation();
+ const ownerTenantId = useOwnerTenantId();
const values = useValues(node);
@@ -163,7 +165,10 @@ function MessageForm({ node }: INextOperatorForm) {
</FormItem>
</>
)}
- <MemoriesFormField label={t('flow.saveToMemory')}></MemoriesFormField>
+ <MemoriesFormField
+ label={t('flow.saveToMemory')}
+ ownerTenantId={ownerTenantId}
+ ></MemoriesFormField>
<UserIdFormField></UserIdFormField>
</FormWrapper>
</Form>
diff --git a/web/src/pages/agent/form/retrieval-form/next.tsx b/web/src/pages/agent/form/retrieval-form/next.tsx
index 481886d855..f26e1b2ccd 100644
--- a/web/src/pages/agent/form/retrieval-form/next.tsx
+++ b/web/src/pages/agent/form/retrieval-form/next.tsx
@@ -94,6 +94,7 @@ export type RetrievalFormSchemaType = z.infer<typeof FormSchema>;
export function MemoryDatasetForm() {
const { t } = useTranslation();
const form = useFormContext();
+ const ownerTenantId = useOwnerTenantId();
const retrievalFrom = useWatch({
control: form.control,
name: 'retrieval_from',
@@ -114,11 +115,16 @@ export function MemoryDatasetForm() {
<MemoriesFormField
label={t('header.memories')}
required
+ ownerTenantId={ownerTenantId}
></MemoriesFormField>
<UserIdFormField></UserIdFormField>
</>
) : (
- <KnowledgeBaseFormField showVariable required></KnowledgeBaseFormField>
+ <KnowledgeBaseFormField
+ showVariable
+ required
+ ownerTenantId={ownerTenantId}
+ ></KnowledgeBaseFormField>
)}
</>
);
@@ -155,6 +161,7 @@ function RetrievalForm({ node }: INextOperatorForm) {
const { formSchema, datasetsFetched } = useStaleDatasetFormSchema(
FormSchema,
defaultValues?.dataset_ids,
+ { ownerTenantId },
);
const form = useForm({
diff --git a/web/src/pages/agent/form/tool-form/retrieval-form/index.tsx b/web/src/pages/agent/form/tool-form/retrieval-form/index.tsx
index 624102ec6d..7d622a936f 100644
--- a/web/src/pages/agent/form/tool-form/retrieval-form/index.tsx
+++ b/web/src/pages/agent/form/tool-form/retrieval-form/index.tsx
@@ -37,9 +37,11 @@ export const FormSchema = z.object({
const RetrievalForm = () => {
const defaultValues = omit(useValues(), 'top_k');
+ const ownerTenantId = useOwnerTenantId();
const { formSchema, datasetsFetched } = useStaleDatasetFormSchema(
FormSchema,
defaultValues?.dataset_ids,
+ { ownerTenantId },
);
const form = useForm({
@@ -54,8 +56,6 @@ const RetrievalForm = () => {
useRevalidateStaleDatasetIds(form, datasetsFetched);
- const ownerTenantId = useOwnerTenantId();
-
return (
<Form {...form}>
<FormWrapper>
diff --git a/web/src/pages/agent/hooks/use-canvas-checklist.ts b/web/src/pages/agent/hooks/use-canvas-checklist.ts
new file mode 100644
index 0000000000..9a701f5bd5
--- /dev/null
+++ b/web/src/pages/agent/hooks/use-canvas-checklist.ts
@@ -0,0 +1,164 @@
+/*
+ * Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+ *
+ * Licensed 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 { ModelTypeMap } from '@/components/model-tree-select';
+import { useFetchAgent } from '@/hooks/use-agent-request';
+import { useFetchAllCompilationTemplateGroups } from '@/hooks/use-compilation-template-group-request';
+import { useStaleDatasetIds } from '@/hooks/use-knowledge-request';
+import { useModelValidIds } from '@/hooks/use-llm-request';
+import { useFetchAllMemoryList } from '@/hooks/use-memory-request';
+import { RAGFlowNodeType } from '@/interfaces/database/agent';
+import { useDebounce } from 'ahooks';
+import { useCallback, useEffect, useMemo, useRef } from 'react';
+import { Operator } from '../constant';
+import useGraphStore from '../store';
+import {
+ CanvasChecklistInputs,
+ collectCanvasIssues,
+} from '../utils/canvas-checklist';
+
+// Every dataset binding on the canvas, including Agent-embedded Retrieval
+// tools, so a single lookup settles staleness for all of them. Variable
+// references mixed into the arrays are dropped inside useStaleDatasetIds.
+function collectAllDatasetIds(nodes: RAGFlowNodeType[]): string[] {
+ const ids: string[] = [];
+ for (const node of nodes) {
+ const form = node.data?.form;
+ if (
+ node.data?.label === Operator.Retrieval &&
+ Array.isArray(form?.dataset_ids)
+ ) {
+ ids.push(...form.dataset_ids);
+ }
+ if (node.data?.label === Operator.Agent && Array.isArray(form?.tools)) {
+ for (const tool of form.tools) {
+ if (
+ tool?.component_name === Operator.Retrieval &&
+ Array.isArray(tool?.params?.dataset_ids)
+ ) {
+ ids.push(...tool.params.dataset_ids);
+ }
+ }
+ }
+ }
+ return ids;
+}
+
+/**
+ * Real-time canvas issues for the checklist panel (`issues`, debounced so
+ * dragging a node does not recompute every frame) plus a synchronous
+ * `getLatestIssues` for gating the Run/Publish/Embed/Explore entry points —
+ * a user who fixes the last issue and immediately clicks Run must not be
+ * blocked by a stale debounced value.
+ */
+export function useCanvasChecklist({
+ ownerTenantId,
+}: { ownerTenantId?: string } = {}) {
+ const nodes = useGraphStore((state) => state.nodes);
+ const edges = useGraphStore((state) => state.edges);
+ const editedNodeFormIds = useGraphStore((state) => state.editedNodeFormIds);
+
+ const { data: agentDetail } = useFetchAgent();
+ const {
+ data: memoryList,
+ isLoading: memoryLoading,
+ isError: memoryError,
+ } = useFetchAllMemoryList(ownerTenantId);
+ // Validate against the canvas owner's resources: a shared canvas runs with
+ // the owner's models/groups/memories, while an imported dsl.json makes the
+ // importer the owner — so references pointing anywhere else surface as
+ // issues.
+ const { validIds: modelValidIds, isFetched: modelsFetched } =
+ useModelValidIds(ModelTypeMap.llm_id, ownerTenantId);
+ const {
+ groups: templateGroups,
+ isFetched: templateGroupsFetched,
+ isError: templateGroupsError,
+ } = useFetchAllCompilationTemplateGroups(ownerTenantId);
+ const datasetIds = useMemo(() => collectAllDatasetIds(nodes), [nodes]);
+ const { staleDatasetIds, settled: datasetsSettled } = useStaleDatasetIds(
+ datasetIds,
+ ownerTenantId,
+ );
+
+ const inputs: CanvasChecklistInputs = useMemo(
+ () => ({
+ nodes,
+ edges,
+ editedNodeFormIds,
+ // useFetchAllMemoryList only fetches the first page (page_size: 100) —
+ // a full page means some memories live beyond it, so hold off instead of
+ // misreporting them as deleted.
+ memoryIds:
+ !memoryLoading && !memoryError && (memoryList?.length ?? 0) < 100
+ ? new Set(memoryList?.map((x) => x.id))
+ : undefined,
+ modelValidIds: modelsFetched ? modelValidIds : undefined,
+ staleDatasetIds: datasetsSettled ? staleDatasetIds : undefined,
+ // The groups query fetches only the first page (page_size: 100) — a
+ // full page means some groups live beyond it, so hold off instead of
+ // misreporting them as inaccessible. Gate on isFetched: initialData
+ // keeps isLoading from ever firing.
+ compilationTemplateGroupIds:
+ templateGroupsFetched &&
+ !templateGroupsError &&
+ templateGroups.length < 100
+ ? new Set(templateGroups.map((x) => x.id))
+ : undefined,
+ variables: agentDetail?.dsl?.variables,
+ }),
+ [
+ nodes,
+ edges,
+ editedNodeFormIds,
+ memoryLoading,
+ memoryError,
+ memoryList,
+ modelsFetched,
+ modelValidIds,
+ datasetsSettled,
+ staleDatasetIds,
+ templateGroups,
+ templateGroupsFetched,
+ templateGroupsError,
+ agentDetail?.dsl?.variables,
+ ],
+ );
+
+ const issues = useMemo(() => collectCanvasIssues(inputs), [inputs]);
+ const debouncedIssues = useDebounce(issues, { wait: 300 });
+
+ const inputsRef = useRef(inputs);
+ useEffect(() => {
+ inputsRef.current = inputs;
+ }, [inputs]);
+
+ const getLatestIssues = useCallback(() => {
+ const {
+ nodes: currentNodes,
+ edges: currentEdges,
+ editedNodeFormIds: currentEditedNodeFormIds,
+ } = useGraphStore.getState();
+ return collectCanvasIssues({
+ ...inputsRef.current,
+ nodes: currentNodes,
+ edges: currentEdges,
+ editedNodeFormIds: currentEditedNodeFormIds,
+ });
+ }, []);
+
+ return { issues: debouncedIssues, getLatestIssues };
+}
diff --git a/web/src/pages/agent/hooks/use-node-focus-request.test.tsx b/web/src/pages/agent/hooks/use-node-focus-request.test.tsx
new file mode 100644
index 0000000000..01139d3fee
--- /dev/null
+++ b/web/src/pages/agent/hooks/use-node-focus-request.test.tsx
@@ -0,0 +1,93 @@
+import { act, renderHook } from '@testing-library/react';
+import useGraphStore from '../store';
+import { useNodeFocusRequest } from './use-node-focus-request';
+
+const createNode = (id: string, label: string) =>
+ ({
+ id,
+ type: 'ragNode',
+ position: { x: 0, y: 0 },
+ data: { label, name: id, form: {} },
+ }) as any;
+
+describe('useNodeFocusRequest', () => {
+ beforeEach(() => {
+ useGraphStore.setState({
+ nodes: [createNode('Message:m1', 'Message')],
+ edges: [],
+ nodeFocusRequest: null,
+ clickedNodeId: '',
+ clickedToolId: '',
+ });
+ });
+
+ it('selects the node, opens its form and centers the viewport on it', () => {
+ const showFormDrawerById = jest.fn();
+ const fitView = jest.fn();
+ renderHook(() =>
+ useNodeFocusRequest({
+ reactFlowInstance: { fitView },
+ showFormDrawerById,
+ }),
+ );
+
+ act(() => {
+ useGraphStore
+ .getState()
+ .requestNodeFocus('Message:m1', { toolId: 'tool-1' });
+ });
+
+ const node = useGraphStore
+ .getState()
+ .nodes.find((x) => x.id === 'Message:m1');
+ expect(node?.selected).toBe(true);
+ expect(showFormDrawerById).toHaveBeenCalledWith('Message:m1', 'tool-1');
+ expect(fitView).toHaveBeenCalledWith({
+ nodes: [{ id: 'Message:m1' }],
+ duration: 300,
+ maxZoom: 1,
+ });
+ expect(useGraphStore.getState().nodeFocusRequest).toBeNull();
+ });
+
+ it('only highlights the node when openForm is false (orphan issues)', () => {
+ const showFormDrawerById = jest.fn();
+ renderHook(() => useNodeFocusRequest({ showFormDrawerById }));
+
+ act(() => {
+ useGraphStore
+ .getState()
+ .requestNodeFocus('Message:m1', { openForm: false });
+ });
+
+ expect(useGraphStore.getState().nodes[0].selected).toBe(true);
+ expect(showFormDrawerById).not.toHaveBeenCalled();
+ expect(useGraphStore.getState().nodeFocusRequest).toBeNull();
+ });
+
+ it('clears requests for nodes that no longer exist', () => {
+ const showFormDrawerById = jest.fn();
+ renderHook(() => useNodeFocusRequest({ showFormDrawerById }));
+
+ act(() => {
+ useGraphStore.getState().requestNodeFocus('Message:gone');
+ });
+
+ expect(showFormDrawerById).not.toHaveBeenCalled();
+ expect(useGraphStore.getState().nodeFocusRequest).toBeNull();
+ });
+
+ it('refires when the same node is focused twice in a row', () => {
+ const showFormDrawerById = jest.fn();
+ renderHook(() => useNodeFocusRequest({ showFormDrawerById }));
+
+ act(() => {
+ useGraphStore.getState().requestNodeFocus('Message:m1');
+ });
+ act(() => {
+ useGraphStore.getState().requestNodeFocus('Message:m1');
+ });
+
+ expect(showFormDrawerById).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/web/src/pages/agent/hooks/use-node-focus-request.ts b/web/src/pages/agent/hooks/use-node-focus-request.ts
new file mode 100644
index 0000000000..95d9b6a32c
--- /dev/null
+++ b/web/src/pages/agent/hooks/use-node-focus-request.ts
@@ -0,0 +1,72 @@
+/*
+ * Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+ *
+ * Licensed 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 { useEffect } from 'react';
+import useGraphStore from '../store';
+
+/**
+ * Consumes node-focus requests posted through the store (e.g. by the canvas
+ * checklist in the page header, which lives outside the canvas context):
+ * selects + centers the node, and opens its form sheet unless the caller only
+ * wants the highlight (orphan-step issues). The request is always cleared
+ * afterwards so the same node can be focused twice in a row.
+ */
+export function useNodeFocusRequest({
+ reactFlowInstance,
+ showFormDrawerById,
+}: {
+ reactFlowInstance?: {
+ fitView: (options: {
+ nodes: { id: string }[];
+ duration: number;
+ maxZoom: number;
+ }) => void;
+ };
+ showFormDrawerById: (nodeId: string, toolId?: string) => void;
+}) {
+ const nodeFocusRequest = useGraphStore((state) => state.nodeFocusRequest);
+ const selectNodeIds = useGraphStore((state) => state.selectNodeIds);
+ const getNode = useGraphStore((state) => state.getNode);
+ const clearNodeFocusRequest = useGraphStore(
+ (state) => state.clearNodeFocusRequest,
+ );
+
+ useEffect(() => {
+ if (!nodeFocusRequest) {
+ return;
+ }
+ const { nodeId, toolId, openForm } = nodeFocusRequest;
+ if (getNode(nodeId)) {
+ selectNodeIds([nodeId]);
+ if (openForm) {
+ showFormDrawerById(nodeId, toolId);
+ }
+ reactFlowInstance?.fitView({
+ nodes: [{ id: nodeId }],
+ duration: 300,
+ maxZoom: 1,
+ });
+ }
+ clearNodeFocusRequest();
+ }, [
+ nodeFocusRequest,
+ getNode,
+ selectNodeIds,
+ showFormDrawerById,
+ reactFlowInstance,
+ clearNodeFocusRequest,
+ ]);
+}
diff --git a/web/src/pages/agent/hooks/use-save-graph.ts b/web/src/pages/agent/hooks/use-save-graph.ts
index fc9ed3a90c..b6188839c9 100644
--- a/web/src/pages/agent/hooks/use-save-graph.ts
+++ b/web/src/pages/agent/hooks/use-save-graph.ts
@@ -1,4 +1,3 @@
-import message from '@/components/ui/message';
import {
useFetchAgent,
useResetAgent,
@@ -10,84 +9,11 @@ import {
} from '@/interfaces/database/agent';
import { formatDate } from '@/utils/date';
import { useDebounceEffect } from 'ahooks';
-import { t } from 'i18next';
import { useCallback, useEffect, useState } from 'react';
-import { useTranslation } from 'react-i18next';
import { useParams } from 'react-router';
-import { Operator } from '../constant';
-import { FormSchema as ParserFormSchema } from '../form/parser-form';
import useGraphStore from '../store';
-import { getEmptyMessageNodeNames } from '../utils';
-import { findAgentNodeWithoutModel } from '../utils/agent-node-model';
-import { findInvalidRetrievalBinding } from '../utils/find-invalid-retrieval';
import { useBuildDslData } from './use-build-dsl';
-/**
- * A node's form only validates while its panel is mounted, so bad values can
- * sit in the store long after the user has moved on. Re-check them against the
- * same schema before persisting, but only for nodes the user actually edited —
- * a node still carrying stale DSL from an older version must not wedge saving.
- */
-function findInvalidNode(
- nodes: RAGFlowNodeType[],
- editedNodeIds: string[],
-): { node: RAGFlowNodeType; messageKey: string } | undefined {
- const invalidParserNode = nodes.find(
- (node) =>
- editedNodeIds.includes(node.id) &&
- node.data?.label === Operator.Parser &&
- !ParserFormSchema.safeParse(node.data?.form).success,
- );
- if (invalidParserNode) {
- return { node: invalidParserNode, messageKey: 'flow.nodeFormInvalid' };
- }
- // Retrieval nodes and Agent-embedded Retrieval tools must carry a dataset
- // or memory binding; see find-invalid-retrieval.ts for why emptiness is
- // asserted directly instead of re-parsing the whole form schema.
- const invalidRetrieval = findInvalidRetrievalBinding(nodes);
- if (invalidRetrieval) {
- return invalidRetrieval;
- }
- // Unlike the schema re-check above, the missing-model check is not gated on
- // editedNodeIds: a canvas loaded from storage with an empty model must warn
- // on the very next save, not only after the node is edited again.
- const agentNode = findAgentNodeWithoutModel(nodes);
- if (agentNode) {
- return { node: agentNode, messageKey: 'flow.agentModelMissing' };
- }
- return undefined;
-}
-
-export const useValidateNodeForms = () => {
- const { t } = useTranslation();
- const nodes = useGraphStore((state) => state.nodes);
- const editedNodeFormIds = useGraphStore((state) => state.editedNodeFormIds);
-
- const getInvalidNode = useCallback(
- (currentNodes?: RAGFlowNodeType[]) =>
- findInvalidNode(currentNodes ?? nodes, editedNodeFormIds),
- [editedNodeFormIds, nodes],
- );
-
- // Only the entry points the user drives explicitly should warn; autosave and
- // publish stay silent and just skip the write.
- const notifyIfInvalid = useCallback(
- (currentNodes?: RAGFlowNodeType[]) => {
- const invalid = getInvalidNode(currentNodes);
- if (invalid) {
- message.warning(
- t(invalid.messageKey, { name: invalid.node.data?.name }),
- );
- return false;
- }
- return true;
- },
- [getInvalidNode, t],
- );
-
- return { getInvalidNode, notifyIfInvalid };
-};
-
export const useSaveGraph = (
showMessage: boolean = true,
skipInvalidation: boolean = false,
@@ -96,8 +22,10 @@ export const useSaveGraph = (
const { setAgent, loading } = useSetAgent(showMessage, skipInvalidation);
const { id } = useParams();
const { buildDslData } = useBuildDslData();
- const { getInvalidNode } = useValidateNodeForms();
+ // Saving is always allowed, even with unresolved canvas issues — those live
+ // in the canvas checklist (useCanvasChecklist) which gates the
+ // publish/run/embed/explore entry points instead.
const saveGraph = useCallback(
async (
currentNodes?: RAGFlowNodeType[],
@@ -110,26 +38,6 @@ export const useSaveGraph = (
return;
}
- if (getInvalidNode(currentNodes)) {
- return;
- }
-
- // Warn about Message components with empty content at save time; the
- // canvas only fails on them when the agent runs otherwise (backend
- // MessageParam.check() rejects empty content). Advisory only — the save
- // itself proceeds. Autosave/publish (showMessage=false) stay silent to
- // avoid nagging toasts.
- if (showMessage) {
- const emptyMessageNodeNames = getEmptyMessageNodeNames(
- currentNodes ?? useGraphStore.getState().nodes,
- );
- if (emptyMessageNodeNames.length > 0) {
- message.warning(
- `${emptyMessageNodeNames.join(', ')}: ${t('flow.messageMsg')}`,
- );
- }
- }
-
const params: Record<string, any> = {
id,
title: data.title,
@@ -142,7 +50,7 @@ export const useSaveGraph = (
return setAgent(params);
},
- [id, getInvalidNode, showMessage, data.title, buildDslData, setAgent],
+ [id, data.title, buildDslData, setAgent],
);
return { saveGraph, loading };
@@ -151,14 +59,9 @@ export const useSaveGraph = (
export const useSaveGraphBeforeOpeningDebugDrawer = (show: () => void) => {
const { saveGraph, loading } = useSaveGraph();
const { resetAgent } = useResetAgent();
- const { notifyIfInvalid } = useValidateNodeForms();
const handleRun = useCallback(
async (nextNodes?: RAGFlowNodeType[]) => {
- if (!notifyIfInvalid(nextNodes)) {
- return;
- }
-
const saveRet = await saveGraph(nextNodes);
if (saveRet?.code === 0) {
// Call the reset api before opening the run drawer each time
@@ -169,7 +72,7 @@ export const useSaveGraphBeforeOpeningDebugDrawer = (show: () => void) => {
}
}
},
- [notifyIfInvalid, saveGraph, resetAgent, show],
+ [saveGraph, resetAgent, show],
);
return { handleRun, loading };
diff --git a/web/src/pages/agent/hooks/use-show-drawer.tsx b/web/src/pages/agent/hooks/use-show-drawer.tsx
index d6d2fa2255..eb08ed9415 100644
--- a/web/src/pages/agent/hooks/use-show-drawer.tsx
+++ b/web/src/pages/agent/hooks/use-show-drawer.tsx
@@ -22,15 +22,14 @@ export const useShowFormDrawer = () => {
showModal: showFormDrawer,
} = useSetModalState();
- const handleShow = useCallback(
- (e: React.MouseEvent<Element>, nodeId: string) => {
- const toolId = (e.target as HTMLElement).dataset.toolId;
- const tool = (e.target as HTMLElement).dataset.tool;
-
- // TODO: Operator type judgment should be used
+ // Event-free variant for programmatic callers (e.g. the canvas checklist):
+ // same guards as handleShow — Tool nodes need a tool id to know which tool
+ // form to render, and LoopStart/ExitLoop have no form at all.
+ const showFormDrawerById = useCallback(
+ (nodeId: string, toolId?: string) => {
const operatorType = getOperatorTypeFromId(nodeId);
if (
- (operatorType === Operator.Tool && !tool) ||
+ (operatorType === Operator.Tool && !toolId) ||
[Operator.LoopStart, Operator.ExitLoop].includes(
operatorType as Operator,
)
@@ -38,17 +37,27 @@ export const useShowFormDrawer = () => {
return;
}
setClickedNodeId(nodeId);
- // Guess this could gracefully handle the case where the tool id is not provided?
- setClickedToolId(toolId || tool);
+ setClickedToolId(toolId);
showFormDrawer();
},
[getOperatorTypeFromId, setClickedNodeId, setClickedToolId, showFormDrawer],
);
+ const handleShow = useCallback(
+ (e: React.MouseEvent<Element>, nodeId: string) => {
+ const toolId = (e.target as HTMLElement).dataset.toolId;
+ const tool = (e.target as HTMLElement).dataset.tool;
+
+ showFormDrawerById(nodeId, toolId || tool);
+ },
+ [showFormDrawerById],
+ );
+
return {
formDrawerVisible,
hideFormDrawer,
showFormDrawer: handleShow,
+ showFormDrawerById,
clickedNode: getNode(clickNodeId),
};
};
@@ -96,8 +105,13 @@ export function useShowDrawer({
showSingleDebugDrawer,
hideSingleDebugDrawer,
} = useShowSingleDebugDrawer();
- const { formDrawerVisible, hideFormDrawer, showFormDrawer, clickedNode } =
- useShowFormDrawer();
+ const {
+ formDrawerVisible,
+ hideFormDrawer,
+ showFormDrawer,
+ showFormDrawerById,
+ clickedNode,
+ } = useShowFormDrawer();
const inputs = useGetBeginNodeDataInputs();
const { showLogSheet, logSheetVisible, hideLogSheet } = useShowLogSheet({
setCurrentMessageId,
@@ -173,6 +187,7 @@ export function useShowDrawer({
hideSingleDebugDrawer,
formDrawerVisible,
showFormDrawer,
+ showFormDrawerById,
clickedNode,
onNodeClick,
hideFormDrawer,
diff --git a/web/src/pages/agent/index.tsx b/web/src/pages/agent/index.tsx
index 7f44722735..46b18ea7d7 100644
--- a/web/src/pages/agent/index.tsx
+++ b/web/src/pages/agent/index.tsx
@@ -44,12 +44,14 @@ import { useTranslation } from 'react-i18next';
import { useParams } from 'react-router';
import AgentCanvas from './canvas';
import { DropdownProvider } from './canvas/context';
+import { CanvasChecklist } from './components/canvas-checklist';
import { PublishConfirmDialog } from './components/publish-confirm-dialog';
import { Operator } from './constant';
import { OwnerTenantIdContext } from './context';
import { GlobalParamSheet } from './gobal-variable-sheet';
import { useBuildDslData } from './hooks/use-build-dsl';
import { useCancelCurrentDataflow } from './hooks/use-cancel-dataflow';
+import { useCanvasChecklist } from './hooks/use-canvas-checklist';
import { useHandleExportJsonFile } from './hooks/use-export-json';
import { useFetchDataOnMount } from './hooks/use-fetch-data';
import { useFetchPipelineLog } from './hooks/use-fetch-pipeline-log';
@@ -62,7 +64,6 @@ import { useRunDataflow } from './hooks/use-run-dataflow';
import {
useSaveGraph,
useSaveGraphBeforeOpeningDebugDrawer,
- useValidateNodeForms,
useWatchAgentChange,
} from './hooks/use-save-graph';
import { PipelineLogSheet } from './pipeline-log-sheet';
@@ -117,13 +118,22 @@ export default function Agent() {
const { handleExportJson } = useHandleExportJsonFile();
const { saveGraph, loading } = useSaveGraph();
- const { notifyIfInvalid } = useValidateNodeForms();
+ // Saving is always allowed — the canvas checklist flags issues and gates
+ // only the publish/run/embed/explore entry points.
const handleSave = useCallback(() => {
- if (notifyIfInvalid()) {
- saveGraph();
- }
- }, [notifyIfInvalid, saveGraph]);
+ saveGraph();
+ }, [saveGraph]);
const { flowDetail: agentDetail } = useFetchDataOnMount();
+ const { issues, getLatestIssues } = useCanvasChecklist({
+ ownerTenantId: agentDetail?.user_id,
+ });
+ const hasBlockingIssues = useCallback(() => {
+ if (getLatestIssues().length > 0) {
+ message.warning(t('flow.checklistResolveBefore'));
+ return true;
+ }
+ return false;
+ }, [getLatestIssues, t]);
const { buildDslData } = useBuildDslData();
const { setAgent, loading: savingWidgetSettings } = useSetAgent(false);
const { handleRun } = useSaveGraphBeforeOpeningDebugDrawer(showChatDrawer);
@@ -214,6 +224,9 @@ export default function Agent() {
});
const handleButtonRunClick = useCallback(async () => {
+ if (hasBlockingIssues()) {
+ return;
+ }
if (isWebhookMode) {
if ((await saveGraph())?.code === 0) showWebhookTestSheet();
} else if (isPipeline) {
@@ -222,6 +235,7 @@ export default function Agent() {
handleRun();
}
}, [
+ hasBlockingIssues,
handleRun,
handleRunPipeline,
isPipeline,
@@ -230,6 +244,20 @@ export default function Agent() {
showWebhookTestSheet,
]);
+ const handleExploreClick = useCallback(() => {
+ if (hasBlockingIssues()) {
+ return;
+ }
+ navigateToAgentExplore(id as string)();
+ }, [hasBlockingIssues, id, navigateToAgentExplore]);
+
+ const handleEmbedClick = useCallback(() => {
+ if (hasBlockingIssues()) {
+ return;
+ }
+ showEmbedModal();
+ }, [hasBlockingIssues, showEmbedModal]);
+
// Single source for the Run button so the tooltip gating in the JSX below
// doesn't duplicate it.
const runButton = (
@@ -316,10 +344,7 @@ export default function Agent() {
runButton
))}
{isConversationMode && (
- <Button
- variant={'secondary'}
- onClick={navigateToAgentExplore(id as string)}
- >
+ <Button variant={'secondary'} onClick={handleExploreClick}>
<Compass />
{t('explore.title')}
</Button>
@@ -328,7 +353,9 @@ export default function Agent() {
agentDetail={agentDetail}
loading={loading}
onPublish={() => saveGraph(undefined, undefined, true)}
+ onBeforeOpen={hasBlockingIssues}
/>
+ <CanvasChecklist issues={issues} />
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant={'secondary'}>
@@ -368,7 +395,7 @@ export default function Agent() {
(location.hostname !== 'cloud.ragflow.io' && (
<>
<DropdownMenuSeparator />
- <AgentDropdownMenuItem onClick={showEmbedModal}>
+ <AgentDropdownMenuItem onClick={handleEmbedClick}>
<ScreenShare />
{t('common.embedIntoSite')}
</AgentDropdownMenuItem>
diff --git a/web/src/pages/agent/store.ts b/web/src/pages/agent/store.ts
index 5297fb9f15..a37c0b2d9c 100644
--- a/web/src/pages/agent/store.ts
+++ b/web/src/pages/agent/store.ts
@@ -152,6 +152,21 @@ export type RFState = {
collapsedBottomHandles: CollapsedBottomHandles;
clickedNodeId: string; // currently selected node
clickedToolId: string; // currently selected tool id
+ // Set by the canvas checklist to focus a node from outside the canvas
+ // (select + center, and open its form unless the issue is an orphan step);
+ // consumed and cleared by AgentCanvas. The nonce retriggers the effect when
+ // the same node is focused twice in a row.
+ nodeFocusRequest: {
+ nodeId: string;
+ toolId?: string;
+ openForm: boolean;
+ nonce: number;
+ } | null;
+ requestNodeFocus: (
+ nodeId: string,
+ options?: { toolId?: string; openForm?: boolean },
+ ) => void;
+ clearNodeFocusRequest: () => void;
onNodesChange: OnNodesChange<RAGFlowNodeType>;
onEdgesChange: OnEdgesChange;
onEdgeMouseEnter?: EdgeMouseHandler<Edge>;
@@ -635,6 +650,20 @@ const useGraphStore = create<RFState>()(
setClickedNodeId: (id?: string) => {
set({ clickedNodeId: id });
},
+ nodeFocusRequest: null,
+ requestNodeFocus: (nodeId, options) => {
+ set({
+ nodeFocusRequest: {
+ nodeId,
+ toolId: options?.toolId,
+ openForm: options?.openForm ?? true,
+ nonce: Date.now(),
+ },
+ });
+ },
+ clearNodeFocusRequest: () => {
+ set({ nodeFocusRequest: null });
+ },
generateNodeName: (name: string) => {
const { nodes } = get();
diff --git a/web/src/pages/agent/utils.test.ts b/web/src/pages/agent/utils.test.ts
index 7805896dbb..d9953034be 100644
--- a/web/src/pages/agent/utils.test.ts
+++ b/web/src/pages/agent/utils.test.ts
@@ -2,19 +2,11 @@ import { RAGFlowNodeType } from '@/interfaces/database/agent';
import { Operator } from './constant';
import {
generateNodeNamesWithIncreasingIndex,
- getEmptyMessageNodeNames,
isEmptyMessageContent,
receiveMessageError,
transformTokenChunkerParams,
} from './utils';
-const createMessageNode = (name: string, content: unknown) => ({
- id: `${Operator.Message}:${name}`,
- type: 'ragNode',
- position: { x: 0, y: 0 },
- data: { label: Operator.Message, name, form: { content } },
-});
-
describe('transformTokenChunkerParams', () => {
it('keeps overlapped_percent and delimiters when delimiter_mode is one', () => {
// Regression: saving with delimiter_mode='one' used to zero these fields,
@@ -90,23 +82,6 @@ describe('Message component content validation', () => {
expect(isEmptyMessageContent([' text '])).toBe(false);
});
});
-
- describe('getEmptyMessageNodeNames', () => {
- it('flags only Message nodes whose content is empty', () => {
- const nodes = [
- createMessageNode('回复消息_0', ['']),
- createMessageNode('回复消息_1', ['ok']),
- {
- id: `${Operator.Agent}:x`,
- type: 'ragNode',
- position: { x: 0, y: 0 },
- data: { label: Operator.Agent, name: '智能体_0', form: {} },
- },
- ];
-
- expect(getEmptyMessageNodeNames(nodes as any)).toEqual(['回复消息_0']);
- });
- });
});
describe('generateNodeNamesWithIncreasingIndex', () => {
diff --git a/web/src/pages/agent/utils.ts b/web/src/pages/agent/utils.ts
index 57e3f61b90..01523539a5 100644
--- a/web/src/pages/agent/utils.ts
+++ b/web/src/pages/agent/utils.ts
@@ -1007,21 +1007,6 @@ export function isEmptyMessageContent(content?: unknown): boolean {
);
}
-/**
- * Returns the display names of Message nodes whose content is empty, so the
- * save flow can warn about them up front instead of surfacing the runtime
- * error only when the user runs the agent.
- */
-export function getEmptyMessageNodeNames(nodes: RAGFlowNodeType[]): string[] {
- return nodes
- .filter(
- (node) =>
- node.data?.label === Operator.Message &&
- isEmptyMessageContent(node.data?.form?.content),
- )
- .map((node) => node.data?.name ?? node.id);
-}
-
/**
* convert the following object into a list
*
diff --git a/web/src/pages/agent/utils/__tests__/canvas-checklist.test.ts b/web/src/pages/agent/utils/__tests__/canvas-checklist.test.ts
new file mode 100644
index 0000000000..e2645eca8a
--- /dev/null
+++ b/web/src/pages/agent/utils/__tests__/canvas-checklist.test.ts
@@ -0,0 +1,722 @@
+import { Edge } from '@xyflow/react';
+import {
+ CanvasChecklistInputs,
+ CanvasIssueType,
+ collectCanvasIssues,
+} from '../canvas-checklist';
+
+const makeNode = (
+ id: string,
+ label: string,
+ form: Record<string, any> = {},
+ extra: Record<string, any> = {},
+) =>
+ ({
+ id,
+ data: { label, name: id, form },
+ ...extra,
+ }) as any;
+
+const makeEdge = (source: string, target: string, sourceHandle?: string) =>
+ ({ id: `${source}->${target}`, source, target, sourceHandle }) as Edge;
+
+const collect = (
+ overrides: Partial<CanvasChecklistInputs> & {
+ nodes: CanvasChecklistInputs['nodes'];
+ },
+) =>
+ collectCanvasIssues({
+ edges: [],
+ editedNodeFormIds: [],
+ ...overrides,
+ });
+
+describe('collectCanvasIssues: orphan steps', () => {
+ it('flags a node with no incident edges', () => {
+ const issues = collect({
+ nodes: [makeNode('Parser:p1', 'Parser', { setups: [{}] })],
+ });
+
+ expect(issues).toContainEqual(
+ expect.objectContaining({
+ nodeId: 'Parser:p1',
+ type: CanvasIssueType.Orphan,
+ messageKey: 'flow.issueNotConnected',
+ }),
+ );
+ });
+
+ it('treats any edge — including tool edges — as a connection', () => {
+ const issues = collect({
+ nodes: [
+ makeNode('Agent:a1', 'Agent', { llm_id: 'model-1', tools: [] }),
+ makeNode('Tool:t1', 'Tool'),
+ ],
+ edges: [makeEdge('Agent:a1', 'Tool:t1', 'tool')],
+ });
+
+ expect(
+ issues.filter((x) => x.type === CanvasIssueType.Orphan),
+ ).toHaveLength(0);
+ });
+
+ it.each([
+ ['begin', 'Begin'],
+ ['Note:n1', 'Note'],
+ ['Placeholder:p1', 'Placeholder'],
+ ['IterationItem:i1', 'IterationItem'],
+ ['LoopItem:l1', 'LoopItem'],
+ ['ExitLoop:e1', 'ExitLoop'],
+ ])('exempts structural node %s', (id, label) => {
+ const issues = collect({ nodes: [makeNode(id, label)] });
+
+ expect(
+ issues.some((x) => x.nodeId === id && x.type === CanvasIssueType.Orphan),
+ ).toBe(false);
+ });
+
+ it('flags a pipeline File node without downstream', () => {
+ const issues = collect({ nodes: [makeNode('File', 'File', {})] });
+
+ expect(issues).toContainEqual(
+ expect.objectContaining({ nodeId: 'File', type: CanvasIssueType.Orphan }),
+ );
+ });
+});
+
+describe('collectCanvasIssues: dangling variable references', () => {
+ const retrievalNode = () =>
+ makeNode('Retrieval:r1', 'Retrieval', {
+ retrieval_from: 'dataset',
+ dataset_ids: ['kb-1'],
+ outputs: { formalized_content: { type: 'string' } },
+ });
+
+ it('accepts a reference to a connected upstream output', () => {
+ const issues = collect({
+ nodes: [
+ retrievalNode(),
+ makeNode('Message:m1', 'Message', {
+ content: ['{Retrieval:r1@formalized_content}'],
+ }),
+ ],
+ edges: [makeEdge('Retrieval:r1', 'Message:m1')],
+ });
+
+ expect(
+ issues.filter((x) => x.type === CanvasIssueType.InvalidVariable),
+ ).toHaveLength(0);
+ });
+
+ it('flags the reference once the connecting edge is removed', () => {
+ const issues = collect({
+ nodes: [
+ retrievalNode(),
+ makeNode('Message:m1', 'Message', {
+ content: ['{Retrieval:r1@formalized_content}'],
+ }),
+ ],
+ });
+
+ expect(issues).toContainEqual(
+ expect.objectContaining({
+ nodeId: 'Message:m1',
+ type: CanvasIssueType.InvalidVariable,
+ messageKey: 'flow.issueVariableInvalid',
+ messageParams: { variable: 'Retrieval:r1@formalized_content' },
+ }),
+ );
+ });
+
+ it('flags a reference whose target node was deleted', () => {
+ const issues = collect({
+ nodes: [
+ makeNode('Message:m1', 'Message', {
+ content: ['{Retrieval:gone@formalized_content}'],
+ }),
+ ],
+ });
+
+ expect(issues).toContainEqual(
+ expect.objectContaining({
+ nodeId: 'Message:m1',
+ type: CanvasIssueType.InvalidVariable,
+ messageParams: { variable: 'Retrieval:gone@formalized_content' },
+ }),
+ );
+ });
+
+ it('flags a reference whose output key no longer exists', () => {
+ const renamed = retrievalNode();
+ renamed.data.form.outputs = { json: { type: 'object' } };
+ const issues = collect({
+ nodes: [
+ renamed,
+ makeNode('Message:m1', 'Message', {
+ content: ['{Retrieval:r1@formalized_content}'],
+ }),
+ ],
+ edges: [makeEdge('Retrieval:r1', 'Message:m1')],
+ });
+
+ expect(issues).toContainEqual(
+ expect.objectContaining({
+ nodeId: 'Message:m1',
+ type: CanvasIssueType.InvalidVariable,
+ }),
+ );
+ });
+
+ it('skips the output-key check for nodes declaring no outputs (Message)', () => {
+ const issues = collect({
+ nodes: [
+ makeNode('Message:m1', 'Message', { content: ['hello'] }),
+ makeNode('Message:m2', 'Message', {
+ content: ['{Message:m1@content}'],
+ }),
+ ],
+ edges: [makeEdge('Message:m1', 'Message:m2')],
+ });
+
+ expect(
+ issues.filter((x) => x.type === CanvasIssueType.InvalidVariable),
+ ).toHaveLength(0);
+ });
+
+ it('reports a duplicated dangling reference only once per node', () => {
+ const issues = collect({
+ nodes: [
+ makeNode('Message:m1', 'Message', {
+ content: ['{Retrieval:gone@x}', 'again {Retrieval:gone@x}'],
+ }),
+ ],
+ });
+
+ expect(
+ issues.filter(
+ (x) =>
+ x.type === CanvasIssueType.InvalidVariable &&
+ x.messageParams?.variable === 'Retrieval:gone@x',
+ ),
+ ).toHaveLength(1);
+ });
+
+ it('detects bare whole-string references such as switch cpn_id', () => {
+ const issues = collect({
+ nodes: [
+ retrievalNode(),
+ makeNode('Switch:s1', 'Switch', {
+ conditions: [{ cpn_id: 'Retrieval:r1@formalized_content' }],
+ }),
+ ],
+ });
+
+ expect(issues).toContainEqual(
+ expect.objectContaining({
+ nodeId: 'Switch:s1',
+ type: CanvasIssueType.InvalidVariable,
+ messageParams: { variable: 'Retrieval:r1@formalized_content' },
+ }),
+ );
+ });
+
+ it('ignores brace-like text inside the Code code field', () => {
+ const issues = collect({
+ nodes: [
+ makeNode('CodeExec:c1', 'CodeExec', {
+ code: 'print("{Retrieval:gone@x}")',
+ outputs: { result: { type: 'string' } },
+ }),
+ ],
+ });
+
+ expect(
+ issues.filter((x) => x.type === CanvasIssueType.InvalidVariable),
+ ).toHaveLength(0);
+ });
+
+ it('never scans password fields for references', () => {
+ const issues = collect({
+ nodes: [
+ makeNode('ExeSQL:e1', 'ExeSQL', { password: 'user:p@ss' }),
+ makeNode('Message:m1', 'Message', { content: ['hi'] }),
+ ],
+ edges: [makeEdge('ExeSQL:e1', 'Message:m1')],
+ });
+
+ expect(
+ issues.filter((x) => x.type === CanvasIssueType.InvalidVariable),
+ ).toHaveLength(0);
+ });
+});
+
+describe('collectCanvasIssues: begin/sys/env references', () => {
+ const beginNode = () =>
+ makeNode('begin', 'Begin', { inputs: { query: { type: 'line' } } });
+
+ it('accepts an existing begin input and flags a deleted one', () => {
+ const issues = collect({
+ nodes: [
+ beginNode(),
+ makeNode('Message:m1', 'Message', {
+ content: ['{begin@query} {begin@removed}'],
+ }),
+ ],
+ edges: [makeEdge('begin', 'Message:m1')],
+ });
+
+ const invalidVariables = issues
+ .filter((x) => x.type === CanvasIssueType.InvalidVariable)
+ .map((x) => x.messageParams?.variable);
+ expect(invalidVariables).toEqual(['begin@removed']);
+ });
+
+ it('treats sys.* globals as always resolvable', () => {
+ const issues = collect({
+ nodes: [makeNode('Message:m1', 'Message', { content: ['{sys.query}'] })],
+ });
+
+ expect(
+ issues.filter((x) => x.type === CanvasIssueType.InvalidVariable),
+ ).toHaveLength(0);
+ });
+
+ it('flags a deleted conversation variable, but only once variables loaded', () => {
+ const messageNode = makeNode('Message:m1', 'Message', {
+ content: ['{env.token}'],
+ });
+
+ const valid = collect({ nodes: [messageNode], variables: { token: {} } });
+ const invalid = collect({ nodes: [messageNode], variables: {} });
+ const unsettled = collect({ nodes: [messageNode] });
+
+ expect(
+ valid.filter((x) => x.type === CanvasIssueType.InvalidVariable),
+ ).toHaveLength(0);
+ expect(invalid).toContainEqual(
+ expect.objectContaining({
+ type: CanvasIssueType.InvalidVariable,
+ messageParams: { variable: 'env.token' },
+ }),
+ );
+ expect(
+ unsettled.filter((x) => x.type === CanvasIssueType.InvalidVariable),
+ ).toHaveLength(0);
+ });
+});
+
+describe('collectCanvasIssues: iteration/loop children references', () => {
+ it('lets a Loop child reference the parent outputs', () => {
+ const issues = collect({
+ nodes: [
+ makeNode('Loop:p1', 'Loop', { outputs: { content: {} } }),
+ makeNode('LoopItem:s1', 'LoopItem', {}, { parentId: 'Loop:p1' }),
+ makeNode(
+ 'Message:m1',
+ 'Message',
+ { content: ['{Loop:p1@content}'] },
+ { parentId: 'Loop:p1' },
+ ),
+ ],
+ edges: [makeEdge('LoopItem:s1', 'Message:m1')],
+ });
+
+ expect(
+ issues.filter((x) => x.type === CanvasIssueType.InvalidVariable),
+ ).toHaveLength(0);
+ });
+
+ it('lets an Iteration child reference the parent upstream', () => {
+ const issues = collect({
+ nodes: [
+ makeNode('File', 'File', {}),
+ makeNode('Iteration:p1', 'Iteration', { outputs: {} }),
+ makeNode(
+ 'IterationItem:s1',
+ 'IterationItem',
+ {},
+ { parentId: 'Iteration:p1' },
+ ),
+ makeNode(
+ 'Message:m1',
+ 'Message',
+ { content: ['{File@result}'] },
+ { parentId: 'Iteration:p1' },
+ ),
+ ],
+ edges: [
+ makeEdge('File', 'Iteration:p1'),
+ makeEdge('IterationItem:s1', 'Message:m1'),
+ ],
+ });
+
+ expect(
+ issues.filter((x) => x.type === CanvasIssueType.InvalidVariable),
+ ).toHaveLength(0);
+ });
+});
+
+describe('collectCanvasIssues: missing required fields', () => {
+ it('flags an empty Message', () => {
+ const issues = collect({
+ nodes: [makeNode('Message:m1', 'Message', { content: [''] })],
+ });
+
+ expect(issues).toContainEqual(
+ expect.objectContaining({
+ nodeId: 'Message:m1',
+ type: CanvasIssueType.MissingRequired,
+ messageKey: 'flow.messageMsg',
+ }),
+ );
+ });
+
+ it('flags a Retrieval node without dataset or memory binding', () => {
+ const datasetIssues = collect({
+ nodes: [
+ makeNode('Retrieval:r1', 'Retrieval', {
+ retrieval_from: 'dataset',
+ dataset_ids: [],
+ }),
+ ],
+ });
+ const memoryIssues = collect({
+ nodes: [
+ makeNode('Retrieval:r2', 'Retrieval', {
+ retrieval_from: 'memory',
+ memory_ids: [],
+ }),
+ ],
+ });
+
+ expect(datasetIssues).toContainEqual(
+ expect.objectContaining({ messageKey: 'flow.retrievalDatasetMissing' }),
+ );
+ expect(memoryIssues).toContainEqual(
+ expect.objectContaining({ messageKey: 'flow.retrievalMemoryMissing' }),
+ );
+ });
+
+ it('flags an Agent node without a model', () => {
+ const issues = collect({
+ nodes: [makeNode('Agent:a1', 'Agent', { llm_id: '' })],
+ });
+
+ expect(issues).toContainEqual(
+ expect.objectContaining({
+ nodeId: 'Agent:a1',
+ type: CanvasIssueType.MissingRequired,
+ messageKey: 'flow.agentModelMissing',
+ }),
+ );
+ });
+
+ it('flags an invalid Parser form only after the node was edited', () => {
+ const parserNode = makeNode('Parser:p1', 'Parser', { setups: [] });
+ const connected = [makeEdge('File', 'Parser:p1')];
+ const fileNode = makeNode('File', 'File', {});
+
+ const untouched = collect({
+ nodes: [parserNode, fileNode],
+ edges: connected,
+ });
+ const edited = collect({
+ nodes: [parserNode, fileNode],
+ edges: connected,
+ editedNodeFormIds: ['Parser:p1'],
+ });
+
+ expect(untouched.some((x) => x.messageKey === 'flow.nodeFormInvalid')).toBe(
+ false,
+ );
+ expect(edited).toContainEqual(
+ expect.objectContaining({
+ nodeId: 'Parser:p1',
+ type: CanvasIssueType.MissingRequired,
+ messageKey: 'flow.nodeFormInvalid',
+ }),
+ );
+ });
+});
+
+describe('collectCanvasIssues: stale resources', () => {
+ it('flags a Message memory that no longer exists', () => {
+ const issues = collect({
+ nodes: [
+ makeNode('Message:m1', 'Message', {
+ content: ['hi'],
+ memory_ids: ['mem-gone'],
+ }),
+ ],
+ memoryIds: new Set(['mem-1']),
+ });
+
+ expect(issues).toContainEqual(
+ expect.objectContaining({
+ nodeId: 'Message:m1',
+ type: CanvasIssueType.InvalidVariable,
+ messageKey: 'flow.memoryUnavailable',
+ }),
+ );
+ });
+
+ it('skips the memory check while the memory list is unsettled', () => {
+ const issues = collect({
+ nodes: [
+ makeNode('Message:m1', 'Message', {
+ content: ['hi'],
+ memory_ids: ['mem-gone'],
+ }),
+ ],
+ });
+
+ expect(
+ issues.filter((x) => x.messageKey === 'flow.memoryUnavailable'),
+ ).toHaveLength(0);
+ });
+
+ it('flags a deleted model on any node carrying llm_id', () => {
+ const issues = collect({
+ nodes: [
+ makeNode('Categorize:c1', 'Categorize', { llm_id: 'deleted-model' }),
+ ],
+ modelValidIds: new Set(['other-model']),
+ });
+
+ expect(issues).toContainEqual(
+ expect.objectContaining({
+ nodeId: 'Categorize:c1',
+ type: CanvasIssueType.InvalidVariable,
+ messageKey: 'common.modelUnavailable',
+ }),
+ );
+ });
+
+ it('flags a stale dataset on a Retrieval node', () => {
+ const issues = collect({
+ nodes: [
+ makeNode('Retrieval:r1', 'Retrieval', {
+ retrieval_from: 'dataset',
+ dataset_ids: ['kb-stale'],
+ }),
+ ],
+ staleDatasetIds: new Set(['kb-stale']),
+ });
+
+ expect(issues).toContainEqual(
+ expect.objectContaining({
+ nodeId: 'Retrieval:r1',
+ type: CanvasIssueType.InvalidVariable,
+ messageKey: 'chat.datasetUnavailable',
+ }),
+ );
+ });
+});
+
+describe('collectCanvasIssues: agent-embedded retrieval tools', () => {
+ const agentWithTool = () =>
+ makeNode('Agent:a1', 'Agent', {
+ llm_id: 'model-1',
+ tools: [
+ {
+ component_name: 'Retrieval',
+ id: 'tool-1',
+ name: 'Docs',
+ params: { retrieval_from: 'dataset', dataset_ids: [] },
+ },
+ ],
+ });
+
+ it('attributes the issue to the Tool canvas node when it exists', () => {
+ const issues = collect({
+ nodes: [agentWithTool(), makeNode('Tool:t1', 'Tool')],
+ edges: [makeEdge('Agent:a1', 'Tool:t1', 'tool')],
+ });
+
+ expect(issues).toContainEqual(
+ expect.objectContaining({
+ nodeId: 'Tool:t1',
+ toolId: 'tool-1',
+ // Names the concrete tool under the concrete agent, not the Tool
+ // node's own label ('flow.tool' on legacy canvases).
+ nodeName: 'Agent:a1 / Docs',
+ operatorLabel: 'Retrieval',
+ type: CanvasIssueType.MissingRequired,
+ messageKey: 'flow.retrievalDatasetMissing',
+ }),
+ );
+ });
+
+ it('falls back to the agent node when there is no Tool canvas node', () => {
+ const issues = collect({ nodes: [agentWithTool()] });
+
+ expect(issues).toContainEqual(
+ expect.objectContaining({
+ nodeId: 'Agent:a1',
+ nodeName: 'Agent:a1 / Docs',
+ type: CanvasIssueType.MissingRequired,
+ messageKey: 'flow.retrievalDatasetMissing',
+ }),
+ );
+ });
+
+ it('distinguishes multiple retrieval tools of the same agent', () => {
+ const agent = makeNode('Agent:a1', 'Agent', {
+ llm_id: 'model-1',
+ tools: [
+ {
+ component_name: 'Retrieval',
+ id: 'tool-1',
+ name: 'DocsA',
+ params: { retrieval_from: 'dataset', dataset_ids: [] },
+ },
+ {
+ component_name: 'Retrieval',
+ id: 'tool-2',
+ name: 'DocsB',
+ params: { retrieval_from: 'memory', memory_ids: [] },
+ },
+ ],
+ });
+
+ const issues = collect({
+ nodes: [agent, makeNode('Tool:t1', 'Tool')],
+ edges: [makeEdge('Agent:a1', 'Tool:t1', 'tool')],
+ });
+
+ expect(issues).toContainEqual(
+ expect.objectContaining({
+ toolId: 'tool-1',
+ nodeName: 'Agent:a1 / DocsA',
+ messageKey: 'flow.retrievalDatasetMissing',
+ }),
+ );
+ expect(issues).toContainEqual(
+ expect.objectContaining({
+ toolId: 'tool-2',
+ nodeName: 'Agent:a1 / DocsB',
+ messageKey: 'flow.retrievalMemoryMissing',
+ }),
+ );
+ });
+
+ it('checks stale datasets and memories inside tool params', () => {
+ const agent = makeNode('Agent:a1', 'Agent', {
+ llm_id: 'model-1',
+ tools: [
+ {
+ component_name: 'Retrieval',
+ id: 'tool-1',
+ params: { retrieval_from: 'memory', memory_ids: ['mem-gone'] },
+ },
+ ],
+ });
+
+ const issues = collect({
+ nodes: [agent],
+ memoryIds: new Set(['mem-1']),
+ });
+
+ expect(issues).toContainEqual(
+ expect.objectContaining({
+ nodeId: 'Agent:a1',
+ type: CanvasIssueType.InvalidVariable,
+ messageKey: 'flow.memoryUnavailable',
+ }),
+ );
+ });
+});
+
+describe('collectCanvasIssues: compiler template group', () => {
+ it('flags a Compiler node with an empty template group', () => {
+ const issues = collect({
+ nodes: [
+ makeNode('Compiler:c1', 'Compiler', {
+ compilation_template_group_id: '',
+ }),
+ ],
+ });
+
+ expect(issues).toContainEqual(
+ expect.objectContaining({
+ nodeId: 'Compiler:c1',
+ type: CanvasIssueType.MissingRequired,
+ messageKey: 'knowledgeConfiguration.compilationTemplateRequired',
+ }),
+ );
+ });
+
+ it('flags a template group the current user cannot resolve', () => {
+ const issues = collect({
+ nodes: [
+ makeNode('Compiler:c1', 'Compiler', {
+ compilation_template_group_id: 'g-gone',
+ }),
+ ],
+ compilationTemplateGroupIds: new Set(['g-1']),
+ });
+
+ expect(issues).toContainEqual(
+ expect.objectContaining({
+ nodeId: 'Compiler:c1',
+ type: CanvasIssueType.InvalidVariable,
+ messageKey: 'knowledgeConfiguration.compilationTemplateUnavailable',
+ }),
+ );
+ });
+
+ it('skips the availability check while the group list is unsettled', () => {
+ const issues = collect({
+ nodes: [
+ makeNode('Compiler:c1', 'Compiler', {
+ compilation_template_group_id: 'g-gone',
+ }),
+ ],
+ });
+
+ expect(
+ issues.filter(
+ (x) =>
+ x.messageKey ===
+ 'knowledgeConfiguration.compilationTemplateUnavailable',
+ ),
+ ).toHaveLength(0);
+ });
+
+ it('accepts a resolvable template group', () => {
+ const issues = collect({
+ nodes: [
+ makeNode('Compiler:c1', 'Compiler', {
+ compilation_template_group_id: 'g-1',
+ }),
+ ],
+ compilationTemplateGroupIds: new Set(['g-1']),
+ });
+
+ expect(
+ issues.filter(
+ (x) =>
+ x.messageKey ===
+ 'knowledgeConfiguration.compilationTemplateUnavailable' ||
+ x.messageKey === 'knowledgeConfiguration.compilationTemplateRequired',
+ ),
+ ).toHaveLength(0);
+ });
+
+ it('ignores the same form key on non-Compiler nodes', () => {
+ const issues = collect({
+ nodes: [
+ makeNode('Categorize:c1', 'Categorize', {
+ compilation_template_group_id: '',
+ }),
+ ],
+ });
+
+ expect(
+ issues.filter(
+ (x) =>
+ x.messageKey === 'knowledgeConfiguration.compilationTemplateRequired',
+ ),
+ ).toHaveLength(0);
+ });
+});
diff --git a/web/src/pages/agent/utils/agent-node-model.test.ts b/web/src/pages/agent/utils/agent-node-model.test.ts
deleted file mode 100644
index 079460316a..0000000000
--- a/web/src/pages/agent/utils/agent-node-model.test.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { Operator } from '@/constants/agent';
-import { RAGFlowNodeType } from '@/interfaces/database/agent';
-import { findAgentNodeWithoutModel } from './agent-node-model';
-
-function baseNode(
- id: string,
- label: Operator,
- form: Record<string, any> = {},
-): RAGFlowNodeType {
- return {
- id,
- type: 'ragNode',
- position: { x: 0, y: 0 },
- data: { label, name: id, form },
- } as RAGFlowNodeType;
-}
-
-describe('findAgentNodeWithoutModel', () => {
- it('flags an Agent node whose model is empty', () => {
- const nodes = [
- baseNode('agent-1', Operator.Agent),
- baseNode('agent-2', Operator.Agent, { llm_id: '' }),
- ];
- expect(findAgentNodeWithoutModel(nodes)).toBe(nodes[0]);
- });
-
- it('accepts an Agent node with a model', () => {
- const nodes = [baseNode('agent-1', Operator.Agent, { llm_id: 'gpt-4o' })];
- expect(findAgentNodeWithoutModel(nodes)).toBeUndefined();
- });
-
- it('ignores nodes of other operators without a model', () => {
- const nodes = [
- baseNode('message-1', Operator.Message),
- baseNode('retrieval-1', Operator.Retrieval),
- ];
- expect(findAgentNodeWithoutModel(nodes)).toBeUndefined();
- });
-});
diff --git a/web/src/pages/agent/utils/agent-node-model.ts b/web/src/pages/agent/utils/agent-node-model.ts
deleted file mode 100644
index 8055403c2b..0000000000
--- a/web/src/pages/agent/utils/agent-node-model.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { Operator } from '@/constants/agent';
-import { RAGFlowNodeType } from '@/interfaces/database/agent';
-
-/**
- * An Agent node without a model is unrunnable — the backend only rejects it
- * with `invalid param "model_id": required` once a question is asked. Saving
- * must surface the gap instead of letting it fail at run time.
- */
-export const findAgentNodeWithoutModel = (nodes: RAGFlowNodeType[]) =>
- nodes.find(
- (node) => node.data?.label === Operator.Agent && !node.data?.form?.llm_id,
- );
diff --git a/web/src/pages/agent/utils/canvas-checklist.ts b/web/src/pages/agent/utils/canvas-checklist.ts
new file mode 100644
index 0000000000..e37374596a
--- /dev/null
+++ b/web/src/pages/agent/utils/canvas-checklist.ts
@@ -0,0 +1,528 @@
+/*
+ * Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+ *
+ * Licensed 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 { RAGFlowNodeType } from '@/interfaces/database/agent';
+import { filterAllUpstreamNodeIds, getNodeOutputs } from '@/utils/canvas-util';
+import { Edge } from '@xyflow/react';
+import { isEmpty, isPlainObject } from 'lodash';
+import {
+ BeginId,
+ NodeHandleId,
+ Operator,
+ RetrievalFrom,
+ VariableRegex,
+} from '../constant';
+import { FormSchema as ParserFormSchema } from '../form/parser-form/schema';
+import { isEmptyMessageContent } from '../utils';
+
+/**
+ * Canvas checklist issue collection. Pure functions fed by `useCanvasChecklist`:
+ * everything graph-derived (orphan steps, dangling variable references, missing
+ * required fields) is computed synchronously from nodes/edges, while external
+ * resources (memories, models, datasets, compilation template groups) arrive as
+ * ready-made Sets — `undefined` means "lookup not settled yet" and skips that
+ * check so a slow request never produces false issues.
+ */
+
+export enum CanvasIssueType {
+ InvalidVariable = 'invalidVariable',
+ MissingRequired = 'missingRequired',
+ Orphan = 'orphan',
+}
+
+export type CanvasIssue = {
+ nodeId: string;
+ toolId?: string;
+ nodeName: string;
+ operatorLabel: string;
+ type: CanvasIssueType;
+ messageKey: string;
+ messageParams?: Record<string, string>;
+};
+
+export type CanvasChecklistInputs = {
+ nodes: RAGFlowNodeType[];
+ edges: Edge[];
+ editedNodeFormIds: string[];
+ memoryIds?: Set<string>;
+ modelValidIds?: Set<string>;
+ staleDatasetIds?: Set<string>;
+ compilationTemplateGroupIds?: Set<string>;
+ variables?: Record<string, any>;
+};
+
+type IssueTarget = Pick<
+ CanvasIssue,
+ 'nodeId' | 'toolId' | 'nodeName' | 'operatorLabel'
+>;
+
+// Node ids are `${operator}:${humanId()}` (e.g. `Agent:HipSignsRhyme`); legacy
+// DSLs use numeric suffixes (`answer:0`). The colon is mandatory so llm ids
+// (`model@instance@provider`), e-mail addresses and URLs never parse as node
+// references.
+const BareNodeReferenceRegex =
+ /^([A-Za-z][A-Za-z0-9_]*):([A-Za-z0-9][A-Za-z0-9_-]*)@(\S+)$/;
+
+// Bare begin-input references (`begin@key` as a whole field value); anchored so
+// prose merely starting with `begin@` is not mistaken for a reference.
+const BareBeginReferenceRegex = new RegExp(`^${BeginId}@\\S+$`);
+const ConversationVariablePrefix = 'env.';
+
+// Free-text fields whose content must never be scanned for references.
+const SkippedFormKeys = new Set(['code', 'password']);
+
+// Structural nodes that legitimately have no edges.
+const OrphanExemptOperators: string[] = [
+ Operator.Begin,
+ Operator.Note,
+ Operator.Placeholder,
+ Operator.IterationStart,
+ Operator.LoopStart,
+ Operator.ExitLoop,
+];
+
+function collectStrings(value: unknown): string[] {
+ if (typeof value === 'string') {
+ return [value];
+ }
+ if (Array.isArray(value)) {
+ return value.flatMap(collectStrings);
+ }
+ if (isPlainObject(value)) {
+ return Object.values(value as Record<string, unknown>).flatMap(
+ collectStrings,
+ );
+ }
+ return [];
+}
+
+function collectFormStrings(
+ form: Record<string, any>,
+ skippedKeys: Set<string>,
+): string[] {
+ return Object.entries(form).flatMap(([key, value]) =>
+ skippedKeys.has(key) ? [] : collectStrings(value),
+ );
+}
+
+function extractReferencesFromText(text: string): string[] {
+ const references: string[] = [];
+ for (const match of text.matchAll(VariableRegex)) {
+ if (match[1]) {
+ references.push(match[1]);
+ }
+ }
+ if (BareNodeReferenceRegex.test(text) || BareBeginReferenceRegex.test(text)) {
+ references.push(text);
+ }
+ return references;
+}
+
+type ReferenceValidationContext = {
+ nodeMap: Map<string, RAGFlowNodeType>;
+ edges: Edge[];
+ beginInputKeys: Set<string>;
+ variables?: Record<string, any>;
+ reachableCache: Map<string, Set<string>>;
+};
+
+function buildReachableNodeIds(
+ node: RAGFlowNodeType,
+ nodeMap: Map<string, RAGFlowNodeType>,
+ edges: Edge[],
+) {
+ // Mirrors the variable picker (useBuildVariableOptions): a node may reference
+ // its own upstream, its parent's upstream, and — for Loop parents only — the
+ // parent's own outputs.
+ const reachable = new Set(filterAllUpstreamNodeIds(edges, [node.id]));
+ const parentId = node.parentId;
+ if (parentId) {
+ for (const id of filterAllUpstreamNodeIds(edges, [parentId])) {
+ reachable.add(id);
+ }
+ if (nodeMap.get(parentId)?.data?.label === Operator.Loop) {
+ reachable.add(parentId);
+ }
+ }
+ return reachable;
+}
+
+function isReferenceValid(
+ reference: string,
+ relaxedUpstream: boolean,
+ referencingNode: RAGFlowNodeType,
+ ctx: ReferenceValidationContext,
+): boolean {
+ const atIndex = reference.indexOf('@');
+
+ if (atIndex === -1) {
+ // sys.* globals are backend built-ins and always resolvable; only
+ // conversation variables (env.*) can dangle when the variable is deleted.
+ if (reference.startsWith(ConversationVariablePrefix)) {
+ return ctx.variables
+ ? reference.slice(ConversationVariablePrefix.length) in ctx.variables
+ : true;
+ }
+ return true;
+ }
+
+ const nodeId = reference.slice(0, atIndex);
+ const rootOutputKey = reference.slice(atIndex + 1).split('.')[0];
+
+ if (nodeId === BeginId) {
+ return ctx.beginInputKeys.has(rootOutputKey);
+ }
+
+ const targetNode = ctx.nodeMap.get(nodeId);
+ if (!targetNode) {
+ return false; // the referenced node was deleted
+ }
+
+ if (!relaxedUpstream) {
+ let reachable = ctx.reachableCache.get(referencingNode.id);
+ if (!reachable) {
+ reachable = buildReachableNodeIds(
+ referencingNode,
+ ctx.nodeMap,
+ ctx.edges,
+ );
+ ctx.reachableCache.set(referencingNode.id, reachable);
+ }
+ if (!reachable.has(nodeId)) {
+ return false; // still on the canvas, but no longer connected upstream
+ }
+ }
+
+ // Dotted sub-paths resolve dynamically on the backend — only the root output
+ // key is checked, and only when the node declares outputs at all (e.g.
+ // Message exposes outputs on the backend without declaring them here).
+ const outputs = getNodeOutputs(targetNode);
+ if (!isEmpty(outputs) && !(rootOutputKey in outputs)) {
+ return false;
+ }
+
+ return true;
+}
+
+/**
+ * References inside an Agent node's embedded tools/mcp params run in the
+ * agent's own context, so they skip the upstream-reachability check. Tool
+ * canvas nodes mirror those params and are not scanned at all.
+ */
+function collectNodeReferenceIssues(
+ node: RAGFlowNodeType,
+ target: IssueTarget,
+ ctx: ReferenceValidationContext,
+): CanvasIssue[] {
+ const label = node.data?.label;
+ const form = node.data?.form;
+ if (!isPlainObject(form) || label === Operator.Tool) {
+ return [];
+ }
+
+ const skippedKeys = SkippedFormKeys;
+
+ let strictTexts: string[];
+ let relaxedTexts: string[] = [];
+ if (label === Operator.Agent) {
+ const { tools, mcp, ...ownForm } = form;
+ strictTexts = collectFormStrings(ownForm, skippedKeys);
+ relaxedTexts = collectStrings({ tools, mcp });
+ } else {
+ strictTexts = collectFormStrings(form, skippedKeys);
+ }
+
+ const issues: CanvasIssue[] = [];
+ const reported = new Set<string>();
+ const pushIfInvalid = (reference: string, relaxedUpstream: boolean) => {
+ if (
+ !reported.has(reference) &&
+ !isReferenceValid(reference, relaxedUpstream, node, ctx)
+ ) {
+ reported.add(reference);
+ issues.push({
+ ...target,
+ type: CanvasIssueType.InvalidVariable,
+ messageKey: 'flow.issueVariableInvalid',
+ messageParams: { variable: reference },
+ });
+ }
+ };
+
+ for (const text of strictTexts) {
+ for (const reference of extractReferencesFromText(text)) {
+ pushIfInvalid(reference, false);
+ }
+ }
+ for (const text of relaxedTexts) {
+ for (const reference of extractReferencesFromText(text)) {
+ pushIfInvalid(reference, true);
+ }
+ }
+ return issues;
+}
+
+/**
+ * Shared by Retrieval nodes and Agent-embedded Retrieval tools. Emptiness is
+ * asserted directly instead of re-parsing the form schema so legacy DSLs keyed
+ * on `kb_ids` are never flagged (ported from find-invalid-retrieval.ts).
+ */
+function collectRetrievalBindingIssues(
+ params: Record<string, any> | undefined,
+ target: IssueTarget,
+ inputs: Pick<CanvasChecklistInputs, 'memoryIds' | 'staleDatasetIds'>,
+): CanvasIssue[] {
+ if (!params || !isPlainObject(params)) {
+ return [];
+ }
+ const { memoryIds, staleDatasetIds } = inputs;
+ const issues: CanvasIssue[] = [];
+
+ if (
+ params.retrieval_from === RetrievalFrom.Dataset &&
+ Array.isArray(params.dataset_ids) &&
+ params.dataset_ids.length === 0
+ ) {
+ issues.push({
+ ...target,
+ type: CanvasIssueType.MissingRequired,
+ messageKey: 'flow.retrievalDatasetMissing',
+ });
+ }
+ if (
+ params.retrieval_from === RetrievalFrom.Memory &&
+ Array.isArray(params.memory_ids) &&
+ params.memory_ids.length === 0
+ ) {
+ issues.push({
+ ...target,
+ type: CanvasIssueType.MissingRequired,
+ messageKey: 'flow.retrievalMemoryMissing',
+ });
+ }
+ if (
+ staleDatasetIds &&
+ params.retrieval_from !== RetrievalFrom.Memory &&
+ Array.isArray(params.dataset_ids) &&
+ params.dataset_ids.some((id: string) => staleDatasetIds.has(id))
+ ) {
+ issues.push({
+ ...target,
+ type: CanvasIssueType.InvalidVariable,
+ messageKey: 'chat.datasetUnavailable',
+ });
+ }
+ if (
+ memoryIds &&
+ params.retrieval_from === RetrievalFrom.Memory &&
+ Array.isArray(params.memory_ids) &&
+ params.memory_ids.some((id: string) => !memoryIds.has(id))
+ ) {
+ issues.push({
+ ...target,
+ type: CanvasIssueType.InvalidVariable,
+ messageKey: 'flow.memoryUnavailable',
+ });
+ }
+ return issues;
+}
+
+function findToolCanvasNode(
+ edges: Edge[],
+ nodeMap: Map<string, RAGFlowNodeType>,
+ agentNodeId: string,
+) {
+ const toolNodeId = edges.find(
+ (edge) =>
+ edge.source === agentNodeId && edge.sourceHandle === NodeHandleId.Tool,
+ )?.target;
+ return toolNodeId ? nodeMap.get(toolNodeId) : undefined;
+}
+
+export function collectCanvasIssues({
+ nodes,
+ edges,
+ editedNodeFormIds,
+ memoryIds,
+ modelValidIds,
+ staleDatasetIds,
+ compilationTemplateGroupIds,
+ variables,
+}: CanvasChecklistInputs): CanvasIssue[] {
+ const nodeMap = new Map(nodes.map((x) => [x.id, x]));
+ // References always use `begin@key` even when the Begin node's id is a
+ // legacy one (`begin:0`), so look the node up by label.
+ const beginNode = nodes.find((x) => x.data?.label === Operator.Begin);
+ const beginInputKeys = new Set(
+ Object.keys(beginNode?.data?.form?.inputs ?? {}),
+ );
+ const connectedNodeIds = new Set<string>();
+ for (const edge of edges) {
+ connectedNodeIds.add(edge.source);
+ connectedNodeIds.add(edge.target);
+ }
+
+ const ctx: ReferenceValidationContext = {
+ nodeMap,
+ edges,
+ beginInputKeys,
+ variables,
+ reachableCache: new Map(),
+ };
+
+ const issues: CanvasIssue[] = [];
+
+ for (const node of nodes) {
+ const label = node.data?.label;
+ const form = node.data?.form;
+ const target: IssueTarget = {
+ nodeId: node.id,
+ nodeName: node.data?.name ?? node.id,
+ operatorLabel: label ?? '',
+ };
+
+ if (
+ label &&
+ !OrphanExemptOperators.includes(label) &&
+ !connectedNodeIds.has(node.id)
+ ) {
+ issues.push({
+ ...target,
+ type: CanvasIssueType.Orphan,
+ messageKey: 'flow.issueNotConnected',
+ });
+ }
+
+ if (label === Operator.Message && isEmptyMessageContent(form?.content)) {
+ issues.push({
+ ...target,
+ type: CanvasIssueType.MissingRequired,
+ messageKey: 'flow.messageMsg',
+ });
+ }
+
+ if (label === Operator.Retrieval) {
+ issues.push(
+ ...collectRetrievalBindingIssues(form, target, {
+ memoryIds,
+ staleDatasetIds,
+ }),
+ );
+ }
+
+ if (label === Operator.Agent) {
+ // Not gated on editedNodeFormIds: a canvas loaded from storage with an
+ // empty model must flag on the very next render, not only after edits.
+ if (!form?.llm_id) {
+ issues.push({
+ ...target,
+ type: CanvasIssueType.MissingRequired,
+ messageKey: 'flow.agentModelMissing',
+ });
+ }
+ if (Array.isArray(form?.tools)) {
+ const toolNode = findToolCanvasNode(edges, nodeMap, node.id);
+ for (const tool of form.tools) {
+ if (tool?.component_name !== Operator.Retrieval) {
+ continue;
+ }
+ // Point at the concrete tool under the concrete agent — the Tool
+ // canvas node's own name is just the operator label (legacy canvases
+ // even carry the raw i18n key), which says nothing about which tool
+ // is broken.
+ const toolTarget: IssueTarget = {
+ nodeId: toolNode?.id ?? node.id,
+ toolId: toolNode ? tool.id || tool.component_name : undefined,
+ nodeName: `${node.data?.name ?? node.id} / ${
+ tool.name || tool.component_name
+ }`,
+ operatorLabel: tool.component_name ?? Operator.Tool,
+ };
+ issues.push(
+ ...collectRetrievalBindingIssues(tool?.params, toolTarget, {
+ memoryIds,
+ staleDatasetIds,
+ }),
+ );
+ }
+ }
+ }
+
+ if (label === Operator.Compiler) {
+ // Same always-on policy as the Agent model check: an empty operator
+ // must flag on load, not only after edits.
+ const groupId = form?.compilation_template_group_id;
+ if (!groupId) {
+ issues.push({
+ ...target,
+ type: CanvasIssueType.MissingRequired,
+ messageKey: 'knowledgeConfiguration.compilationTemplateRequired',
+ });
+ } else if (
+ compilationTemplateGroupIds &&
+ !compilationTemplateGroupIds.has(groupId)
+ ) {
+ issues.push({
+ ...target,
+ type: CanvasIssueType.InvalidVariable,
+ messageKey: 'knowledgeConfiguration.compilationTemplateUnavailable',
+ });
+ }
+ }
+
+ if (
+ label === Operator.Parser &&
+ editedNodeFormIds.includes(node.id) &&
+ !ParserFormSchema.safeParse(form).success
+ ) {
+ issues.push({
+ ...target,
+ type: CanvasIssueType.MissingRequired,
+ messageKey: 'flow.nodeFormInvalid',
+ });
+ }
+
+ if (
+ label === Operator.Message &&
+ memoryIds &&
+ Array.isArray(form?.memory_ids) &&
+ form.memory_ids.some((id: string) => !memoryIds.has(id))
+ ) {
+ issues.push({
+ ...target,
+ type: CanvasIssueType.InvalidVariable,
+ messageKey: 'flow.memoryUnavailable',
+ });
+ }
+
+ if (
+ modelValidIds &&
+ typeof form?.llm_id === 'string' &&
+ form.llm_id &&
+ !modelValidIds.has(form.llm_id)
+ ) {
+ issues.push({
+ ...target,
+ type: CanvasIssueType.InvalidVariable,
+ messageKey: 'common.modelUnavailable',
+ });
+ }
+
+ issues.push(...collectNodeReferenceIssues(node, target, ctx));
+ }
+
+ return issues;
+}
diff --git a/web/src/pages/agent/utils/find-invalid-retrieval.test.ts b/web/src/pages/agent/utils/find-invalid-retrieval.test.ts
deleted file mode 100644
index 5a67ccdfb5..0000000000
--- a/web/src/pages/agent/utils/find-invalid-retrieval.test.ts
+++ /dev/null
@@ -1,122 +0,0 @@
-import { findInvalidRetrievalBinding } from './find-invalid-retrieval';
-
-const agentNode = (form: Record<string, any>, id = 'agent-1') => ({
- id,
- data: { label: 'Agent', name: 'Docs QA Agent', form },
-});
-
-describe('findInvalidRetrievalBinding', () => {
- it('does not flag a bound agent retrieval tool with stale template params', () => {
- // Template-era params: the dataset was bound at creation, but the dict
- // predates `rerank_candidates_count`. Saving must not report a missing
- // dataset for it.
- const nodes = [
- agentNode({
- llm_id: 'deepseek-chat',
- tools: [
- {
- component_name: 'Retrieval',
- params: {
- retrieval_from: 'dataset',
- dataset_ids: ['kb-1'],
- top_k: 1024,
- },
- },
- ],
- }),
- ] as any;
-
- expect(findInvalidRetrievalBinding(nodes)).toBeUndefined();
- });
-
- it('flags an agent retrieval tool whose dataset binding is empty', () => {
- const nodes = [
- agentNode({
- llm_id: 'deepseek-chat',
- tools: [
- {
- component_name: 'Retrieval',
- params: {
- retrieval_from: 'dataset',
- dataset_ids: [],
- rerank_candidates_count: 64,
- },
- },
- ],
- }),
- ] as any;
-
- expect(findInvalidRetrievalBinding(nodes)).toMatchObject({
- messageKey: 'flow.retrievalDatasetMissing',
- });
- });
-
- it('flags a retrieval node sourcing from memories without memories', () => {
- const nodes = [
- {
- id: 'retrieval-1',
- data: {
- label: 'Retrieval',
- name: 'Retrieval',
- form: {
- retrieval_from: 'memory',
- memory_ids: [],
- dataset_ids: [],
- },
- },
- },
- ] as any;
-
- expect(findInvalidRetrievalBinding(nodes)).toMatchObject({
- messageKey: 'flow.retrievalMemoryMissing',
- });
- });
-
- it('flags a retrieval node sourcing from datasets without datasets', () => {
- const nodes = [
- {
- id: 'retrieval-1',
- data: {
- label: 'Retrieval',
- name: 'Retrieval',
- form: { retrieval_from: 'dataset', dataset_ids: [] },
- },
- },
- ] as any;
-
- expect(findInvalidRetrievalBinding(nodes)).toMatchObject({
- messageKey: 'flow.retrievalDatasetMissing',
- });
- });
-
- it('keeps legacy kb_ids-only params out of the check', () => {
- const nodes = [
- agentNode({
- llm_id: 'deepseek-chat',
- tools: [
- {
- component_name: 'Retrieval',
- params: { retrieval_from: 'dataset', kb_ids: [], top_k: 1024 },
- },
- ],
- }),
- ] as any;
-
- expect(findInvalidRetrievalBinding(nodes)).toBeUndefined();
- });
-
- it('accepts variable references as a dataset binding', () => {
- const nodes = [
- {
- id: 'retrieval-1',
- data: {
- label: 'Retrieval',
- name: 'Retrieval',
- form: { retrieval_from: 'dataset', dataset_ids: ['{begin@kb}'] },
- },
- },
- ] as any;
-
- expect(findInvalidRetrievalBinding(nodes)).toBeUndefined();
- });
-});
diff --git a/web/src/pages/agent/utils/find-invalid-retrieval.ts b/web/src/pages/agent/utils/find-invalid-retrieval.ts
deleted file mode 100644
index a3c963d846..0000000000
--- a/web/src/pages/agent/utils/find-invalid-retrieval.ts
+++ /dev/null
@@ -1,77 +0,0 @@
-import { RAGFlowNodeType } from '@/interfaces/database/agent';
-import { Operator, RetrievalFrom } from '../constant';
-
-/**
- * A Retrieval node sourcing from datasets must name at least one dataset,
- * and one sourcing from memories must name at least one memory; the backend
- * otherwise rejects the run with a `dataset_ids`/`memory_ids is required`
- * error that only surfaces at runtime. The same applies to Retrieval tools
- * embedded in an Agent node, which is how template-built agents usually
- * bind retrieval. Only forms/tools carrying the canonical `dataset_ids`/
- * `memory_ids` field are checked, so legacy DSLs still keyed on `kb_ids`
- * cannot wedge saving. Binding emptiness is asserted directly instead of
- * re-parsing the whole form schema: template-era params can miss unrelated
- * newer fields (e.g. `rerank_candidates_count`), and zod skips refinements
- * when the base shape fails — such a stale field must never be reported as
- * a missing dataset after the user picked one at creation.
- */
-const toInvalidRetrieval = (
- params: Record<string, any>,
-): { memoryMissing: boolean } | undefined => {
- if (
- params?.retrieval_from === RetrievalFrom.Dataset &&
- Array.isArray(params?.dataset_ids) &&
- params.dataset_ids.length === 0
- ) {
- return { memoryMissing: false };
- }
- if (
- params?.retrieval_from === RetrievalFrom.Memory &&
- Array.isArray(params?.memory_ids) &&
- params.memory_ids.length === 0
- ) {
- return { memoryMissing: true };
- }
- return undefined;
-};
-
-export function findInvalidRetrievalBinding(nodes: RAGFlowNodeType[]):
- | {
- node: RAGFlowNodeType;
- messageKey: string;
- }
- | undefined {
- for (const node of nodes) {
- if (node.data?.label === Operator.Retrieval) {
- const invalid = toInvalidRetrieval(node.data?.form);
- if (invalid) {
- return {
- node,
- messageKey: invalid.memoryMissing
- ? 'flow.retrievalMemoryMissing'
- : 'flow.retrievalDatasetMissing',
- };
- }
- }
- if (node.data?.label === Operator.Agent) {
- const tools = node.data?.form?.tools;
- if (Array.isArray(tools)) {
- for (const tool of tools) {
- if (tool?.component_name !== Operator.Retrieval) {
- continue;
- }
- const invalid = toInvalidRetrieval(tool?.params);
- if (invalid) {
- return {
- node,
- messageKey: invalid.memoryMissing
- ? 'flow.retrievalMemoryMissing'
- : 'flow.retrievalDatasetMissing',
- };
- }
- }
- }
- }
- }
- return undefined;
-}
diff --git a/web/src/pages/next-search/search-setting.tsx b/web/src/pages/next-search/search-setting.tsx
index 7571140dc5..e74b49f1fe 100644
--- a/web/src/pages/next-search/search-setting.tsx
+++ b/web/src/pages/next-search/search-setting.tsx
@@ -82,7 +82,7 @@ function SearchSetting({
const { formSchema, datasetsFetched } = useStaleDatasetFormSchema(
searchSettingSchema,
search_config?.kb_ids,
- 'search_config.kb_ids',
+ { fieldName: 'search_config.kb_ids' },
);
const formMethods = useForm<SearchSettingFormData>({
resolver: zodResolver(formSchema),
diff --git a/web/src/services/knowledge-service.ts b/web/src/services/knowledge-service.ts
index 06ceb7f7a8..78e6e53df9 100644
--- a/web/src/services/knowledge-service.ts
+++ b/web/src/services/knowledge-service.ts
@@ -358,10 +358,15 @@ export const listDataset = (params?: IFetchKnowledgeListRequestParams) =>
// Fetch datasets by a set of IDs via the `ids` query param (comma-joined).
// Used to echo back already-selected datasets whose names are not present
-// in the first page of the paginated list.
-export const listDatasetByIds = (ids: string[]) =>
+// in the first page of the paginated list. `ownerTenantId` scopes the lookup
+// to the canvas owner's tenant when viewing a shared canvas.
+export const listDatasetByIds = (ids: string[], ownerTenantId?: string) =>
request.get(api.kbList, {
- params: { ids: ids.join(','), page_size: ids.length },
+ params: {
+ ids: ids.join(','),
+ page_size: ids.length,
+ ...(ownerTenantId ? { tenant_id: ownerTenantId } : {}),
+ },
});
export const datasetFilter = () => request.get(api.datasetFilter);
diff --git a/web/src/utils/canvas-util.tsx b/web/src/utils/canvas-util.tsx
index 4a9231eb3f..1ae293a287 100644
--- a/web/src/utils/canvas-util.tsx
+++ b/web/src/utils/canvas-util.tsx
@@ -84,7 +84,7 @@ export function buildSecondaryOutputOptions(
}));
}
-function getNodeOutputs(x: BaseNode) {
+export function getNodeOutputs(x: BaseNode) {
const outputs = x.data.form?.outputs ?? {};
if (x.data.label !== Operator.Code) {
return outputs;