Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix(frontend): distinguish graph availability errors from disabled state (#4172)

mingyik yeung501d04280ebc
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index 6b27f55eb..94a43506a 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -2887,6 +2887,8 @@ export default {
extractFailed: 'Entity-relationship extraction failed',
exampleLoaded: 'Example loaded',
exampleCleared: 'Example cleared',
+ checkingAvailability: 'Checking knowledge graph availability…',
+ checkAvailabilityFailed: 'Unable to check knowledge graph availability. Please retry.',
disabledWarning: 'Knowledge graph database is not enabled, entity-relationship extraction will not be available',
howToEnable: 'How to enable knowledge graph?'
},
diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts
index 48ab96729..afb1296a4 100644
--- a/frontend/src/i18n/locales/ja-JP.ts
+++ b/frontend/src/i18n/locales/ja-JP.ts
@@ -2887,6 +2887,8 @@ export default {
extractFailed: 'エンティティとリレーションの抽出に失敗しました',
exampleLoaded: '例を読み込みました',
exampleCleared: '例をクリアしました',
+ checkingAvailability: 'ナレッジグラフの利用状況を確認中…',
+ checkAvailabilityFailed: 'ナレッジグラフの利用状況を確認できませんでした。再試行してください。',
disabledWarning: 'ナレッジグラフのデータベースが有効になっていないため、エンティティとリレーションの抽出は利用できません',
howToEnable: 'ナレッジグラフを有効にするには?'
},
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index a2cde4580..15bd9c8af 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -6469,6 +6469,8 @@ export default {
extractFailed: '엔티티 관계 추출 실패',
exampleLoaded: '예시가 로드되었습니다',
exampleCleared: '예시가 지워졌습니다',
+ checkingAvailability: '지식 그래프 사용 가능 여부를 확인하는 중…',
+ checkAvailabilityFailed: '지식 그래프 사용 가능 여부를 확인할 수 없습니다. 다시 시도해 주세요.',
disabledWarning: '지식 그래프 데이터베이스가 활성화되지 않아 엔티티 관계 추출 기능을 사용할 수 없습니다',
howToEnable: '지식 그래프를 활성화하는 방법?'
},
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index 40509d217..702d8c049 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -6469,6 +6469,8 @@ export default {
extractFailed: 'Не удалось извлечь сущности и отношения',
exampleLoaded: 'Пример загружен',
exampleCleared: 'Пример очищен',
+ checkingAvailability: 'Проверка доступности графа знаний…',
+ checkAvailabilityFailed: 'Не удалось проверить доступность графа знаний. Повторите попытку.',
disabledWarning: 'База данных графа знаний не включена, извлечение сущностей и отношений будет недоступно',
howToEnable: 'Как включить граф знаний?'
},
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index b3389eea9..f8545507e 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -6470,6 +6470,8 @@ export default {
extractFailed: '实体关系提取失败',
exampleLoaded: '示例已加载',
exampleCleared: '示例已清除',
+ checkingAvailability: '正在检查知识图谱服务…',
+ checkAvailabilityFailed: '无法检查知识图谱服务,请重试。',
disabledWarning: '知识图谱数据库未启用,实体关系提取功能将无法使用',
howToEnable: '如何启用知识图谱?'
},
diff --git a/frontend/src/i18n/locales/zh-TW.ts b/frontend/src/i18n/locales/zh-TW.ts
index 364ca5229..78470f06a 100644
--- a/frontend/src/i18n/locales/zh-TW.ts
+++ b/frontend/src/i18n/locales/zh-TW.ts
@@ -6470,6 +6470,8 @@ export default {
extractFailed: '實體關係提取失敗',
exampleLoaded: '示例已載入',
exampleCleared: '示例已清除',
+ checkingAvailability: '正在檢查知識圖譜服務…',
+ checkAvailabilityFailed: '無法檢查知識圖譜服務,請重試。',
disabledWarning: '知識圖譜資料庫未啟用,實體關係提取功能將無法使用',
howToEnable: '如何啟用知識圖譜?'
},
diff --git a/frontend/src/views/knowledge/settings/GraphSettings.test.ts b/frontend/src/views/knowledge/settings/GraphSettings.test.ts
new file mode 100644
index 000000000..95ef93e76
--- /dev/null
+++ b/frontend/src/views/knowledge/settings/GraphSettings.test.ts
@@ -0,0 +1,240 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test, { type TestContext } from 'node:test'
+import { runInNewContext } from 'node:vm'
+import { compileScript, parse } from '@vue/compiler-sfc'
+import ts from 'typescript'
+import * as vue from 'vue'
+
+const { descriptor } = parse(readFileSync(new URL('./GraphSettings.vue', import.meta.url), 'utf8'))
+const script = compileScript(descriptor, { id: 'graph-settings-test', inlineTemplate: true }).content
+const compiled = ts.transpileModule(script.replace('import.meta.env.VITE_KG_GUIDE_URL', 'undefined'), {
+ compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
+}).outputText
+
+type Host = { type: string; props: Record<string, any>; children: Host[]; text: string; parent?: Host }
+const node = (type: string): Host => ({ type, props: {}, children: [], text: '' })
+const renderer = vue.createRenderer<Host, Host>({
+ createElement: node,
+ createText: text => ({ ...node('#text'), text }),
+ createComment: text => ({ ...node('#comment'), text }),
+ patchProp: (el, key, _old, value) => { el.props[key] = value },
+ setText: (el, text) => { el.text = text },
+ setElementText: (el, text) => { el.children = []; el.text = text },
+ parentNode: el => el.parent || null,
+ nextSibling: el => el.parent?.children[el.parent.children.indexOf(el) + 1] || null,
+ insert(el, parent, anchor) {
+ if (el.parent) el.parent.children.splice(el.parent.children.indexOf(el), 1)
+ el.parent = parent
+ const index = anchor ? parent.children.indexOf(anchor) : -1
+ parent.children.splice(index < 0 ? parent.children.length : index, 0, el)
+ },
+ remove(el) {
+ el.parent?.children.splice(el.parent.children.indexOf(el), 1)
+ el.parent = undefined
+ },
+})
+
+const textOf = (el: Host): string => el.type === '#comment' ? '' : el.text + el.children.map(textOf).join('')
+const all = (el: Host, predicate: (node: Host) => boolean): Host[] => [
+ ...(predicate(el) ? [el] : []), ...el.children.flatMap(child => all(child, predicate)),
+]
+const hasClass = (el: Host, name: string) => String(el.props.class || '').split(' ').includes(name)
+const flush = async () => {
+ await new Promise<void>(resolve => setImmediate(resolve))
+ await vue.nextTick()
+}
+
+type Request = { force: boolean; resolve: (info: unknown) => void; reject: (error: Error) => void }
+
+function fixture(t: TestContext, embedded: boolean) {
+ const requests: Request[] = []
+ const events: unknown[] = []
+ const opened: unknown[][] = []
+ const graphExtract = {
+ enabled: true,
+ text: 'A sample passage',
+ tags: ['Author'],
+ nodes: [{ name: 'Book', attributes: ['Fiction'] }],
+ relations: [{ node1: 'Book', node2: 'Writer', type: 'Author' }],
+ customInstructions: 'Extract authors and their books.',
+ }
+ const snapshot = structuredClone(graphExtract)
+ const store = {
+ systemInfo: null as unknown,
+ ensureSystemInfo(force = false) {
+ return new Promise<unknown>((resolve, reject) => requests.push({ force, resolve, reject }))
+ .then(info => { store.systemInfo = info })
+ },
+ }
+ const exports: { default?: vue.Component } = {}
+ runInNewContext(compiled, {
+ exports,
+ console: { error() {} },
+ window: { open: (...args: unknown[]) => opened.push(args) },
+ require(name: string) {
+ if (name === 'vue') return vue
+ if (name === 'vue-i18n') return { useI18n: () => ({ t: (key: string) => key }) }
+ if (name === '@/stores/editorResources') return { useEditorResourcesStore: () => store }
+ if (name === '@/stores/auth') return { useAuthStore: () => ({ hasRole: () => true }) }
+ if (name === '@/utils/docsUrl') return { docsUrl: () => 'https://example.com/knowledge-graph' }
+ if (name === 'tdesign-vue-next') return { MessagePlugin: {} }
+ if (name === '@/api/initialization') return {
+ extractTextRelations: () => assert.fail('Availability checks must not extract relations'),
+ fabriText: () => assert.fail('Availability checks must not generate text'),
+ fabriTag: () => assert.fail('Availability checks must not generate tags'),
+ }
+ throw new Error(`Unexpected import: ${name}`)
+ },
+ })
+ const app = renderer.createApp(exports.default!, {
+ graphExtract,
+ modelId: 'model',
+ embedded,
+ 'onUpdate:graphExtract': (value: unknown) => events.push(value),
+ })
+ for (const name of ['t-button', 't-icon', 't-input', 't-option', 't-select', 't-switch', 't-textarea']) {
+ app.component(name, vue.defineComponent({
+ inheritAttrs: false,
+ setup: (_props, { attrs, slots }) => () => vue.h(name, attrs, slots.message?.() ?? slots.default?.()),
+ }))
+ }
+ const root = node('root')
+ app.mount(root)
+ t.after(() => {
+ app.unmount()
+ assert.deepEqual(graphExtract, snapshot)
+ assert.deepEqual(events, [])
+ })
+ const elements = (type: string) => all(root, el => el.type === type)
+ const classes = (name: string) => all(root, el => hasClass(el, name))
+ const retry = () => {
+ const button = elements('t-button').find(el => textOf(el).trim() === 'common.retry')
+ assert.ok(button, 'Expected a retry button')
+ assert.equal(button.props.disabled === true, false)
+ return button.props.onClick as () => Promise<void>
+ }
+ const expectState = (state: 'loading' | 'enabled' | 'disabled' | 'error') => {
+ const notices = classes('graph-disabled')
+ assert.equal(notices.length, state === 'enabled' ? 0 : 1)
+ if (state !== 'enabled') assert.equal(notices[0]!.props.role, state === 'loading' ? 'status' : 'alert')
+ assert.equal(classes('graph-disabled--loading').length, state === 'loading' ? 1 : 0)
+ assert.equal(classes('settings-group').length, state === 'enabled' ? 1 : 0)
+ assert.equal(classes('section-header').length, embedded ? 0 : 1)
+ assert.equal(elements('t-button').filter(el => textOf(el).trim() === 'graphSettings.howToEnable').length, state === 'disabled' && !embedded ? 1 : 0)
+ const messages = {
+ loading: 'graphSettings.checkingAvailability',
+ disabled: 'graphSettings.disabledWarning',
+ error: 'graphSettings.checkAvailabilityFailed',
+ }
+ for (const [status, message] of Object.entries(messages)) {
+ assert.equal(textOf(root).includes(message), status === state, `Unexpected ${message} in ${state}`)
+ }
+ assert.equal(elements('t-button').filter(el => textOf(el).trim() === 'common.retry').length, state === 'error' ? 1 : 0)
+ if (state === 'enabled') {
+ assert.equal(elements('t-switch')[0]?.props.modelValue, snapshot.enabled)
+ const inputValue = (type: string, placeholder: string) => elements(type)
+ .find(el => el.props.placeholder === `graphSettings.${placeholder}`)?.props.modelValue
+ assert.equal(inputValue('t-textarea', 'customInstructionsPlaceholder'), snapshot.customInstructions)
+ assert.equal(inputValue('t-textarea', 'sampleTextPlaceholder'), snapshot.text)
+ assert.deepEqual([...inputValue('t-select', 'tagsPlaceholder')], snapshot.tags)
+ assert.deepEqual(classes('node-name-input').map(el => el.props.modelValue), snapshot.nodes.map(value => value.name))
+ assert.deepEqual(classes('attribute-input').map(el => el.props.modelValue), snapshot.nodes.flatMap(value => value.attributes))
+ assert.deepEqual(classes('relation-select').map(el => el.props.modelValue), snapshot.relations.flatMap(value => [value.node1, value.type, value.node2]))
+ }
+ }
+ assert.equal(requests.length, 1)
+ assert.equal(requests[0]!.force, false)
+ return { requests, elements, opened, retry, expectState }
+}
+
+for (const embedded of [false, true]) {
+ const mode = embedded ? 'embedded' : 'standalone'
+
+ test(`${mode}: pending system information does not show a disabled database warning`, async t => {
+ const f = fixture(t, embedded)
+ await vue.nextTick()
+ f.expectState('loading')
+ })
+
+ for (const engine of ['Neo4j', 'Memgraph', ' FutureEngine ']) {
+ test(`${mode}: ${engine.trim()} enables graph settings`, async t => {
+ const f = fixture(t, embedded)
+ f.requests[0]!.resolve({ graph_database_engine: engine })
+ await flush()
+ f.expectState('enabled')
+ })
+ }
+
+ test(`${mode}: only an explicit disabled engine shows the setup warning`, async t => {
+ const f = fixture(t, embedded)
+ f.requests[0]!.resolve({ graph_database_engine: 'Not Enabled' })
+ await flush()
+ f.expectState('disabled')
+ if (!embedded) {
+ f.elements('t-button').find(el => textOf(el).trim() === 'graphSettings.howToEnable')!.props.onClick()
+ assert.deepEqual(f.opened, [['https://example.com/knowledge-graph', '_blank', 'noopener']])
+ }
+ })
+
+ for (const error of [new Error('HTTP 500'), new Error('HTTP 403'), new Error('Request timed out')]) {
+ test(`${mode}: ${error.message} shows a retryable failure instead of disabled`, async t => {
+ const f = fixture(t, embedded)
+ f.requests[0]!.reject(error)
+ await flush()
+ f.expectState('error')
+ })
+ }
+
+ const invalidResponses: Array<[string, unknown]> = [
+ ['null response', null],
+ ['undefined response', undefined],
+ ['missing engine', {}],
+ ['null engine', { graph_database_engine: null }],
+ ['empty engine', { graph_database_engine: '' }],
+ ['whitespace engine', { graph_database_engine: ' ' }],
+ ['boolean engine', { graph_database_engine: true }],
+ ['numeric engine', { graph_database_engine: 42 }],
+ ]
+ for (const [label, info] of invalidResponses) {
+ test(`${mode}: ${label} is a retryable failure`, async t => {
+ const f = fixture(t, embedded)
+ f.requests[0]!.resolve(info)
+ await flush()
+ f.expectState('error')
+ })
+ }
+
+ test(`${mode}: retry forces a refresh and restores settings without changing saved configuration`, async t => {
+ const f = fixture(t, embedded)
+ f.requests[0]!.reject(new Error('HTTP 500'))
+ await flush()
+ f.expectState('error')
+ f.retry()()
+ await vue.nextTick()
+ f.expectState('loading')
+ assert.deepEqual(f.requests.map(request => request.force), [false, true])
+ f.requests[1]!.resolve({ graph_database_engine: 'Neo4j' })
+ await flush()
+ f.expectState('enabled')
+ })
+
+ for (const staleOutcome of ['failure', 'disabled'] as const) {
+ test(`${mode}: an older ${staleOutcome} cannot replace a successful retry`, async t => {
+ const f = fixture(t, embedded)
+ f.requests[0]!.reject(new Error('HTTP 500'))
+ await flush()
+ const retry = f.retry()
+ retry()
+ retry()
+ assert.deepEqual(f.requests.map(request => request.force), [false, true, true])
+ f.requests[2]!.resolve({ graph_database_engine: 'Neo4j' })
+ await flush()
+ f.expectState('enabled')
+ if (staleOutcome === 'failure') f.requests[1]!.reject(new Error('Late HTTP 500'))
+ else f.requests[1]!.resolve({ graph_database_engine: 'Not Enabled' })
+ await flush()
+ f.expectState('enabled')
+ })
+ }
+}
diff --git a/frontend/src/views/knowledge/settings/GraphSettings.vue b/frontend/src/views/knowledge/settings/GraphSettings.vue
index 65bb952db..1e039d69f 100644
--- a/frontend/src/views/knowledge/settings/GraphSettings.vue
+++ b/frontend/src/views/knowledge/settings/GraphSettings.vue
@@ -4,13 +4,29 @@
<h2>{{ t('graphSettings.title') }}</h2>
<p class="section-description">{{ t('graphSettings.description') }}</p>
</div>
- <div v-if="!isGraphDatabaseEnabled" class="graph-disabled">
- <span class="graph-disabled-icon"><t-icon name="chart-bubble" /></span>
+ <div
+ v-if="graphAvailability !== 'enabled'"
+ class="graph-disabled"
+ :class="{ 'graph-disabled--loading': graphAvailability === 'loading' }"
+ :role="graphAvailability === 'loading' ? 'status' : 'alert'"
+ >
+ <span class="graph-disabled-icon">
+ <t-icon :name="graphAvailability === 'loading' ? 'info-circle' : 'chart-bubble'" />
+ </span>
<div class="graph-disabled-text">
- <p>{{ t('graphSettings.disabledWarning') }}</p>
+ <p>{{ graphAvailabilityMessage }}</p>
</div>
<t-button
- v-if="!embedded"
+ v-if="graphAvailability === 'error'"
+ size="small"
+ theme="primary"
+ variant="outline"
+ @click="loadSystemInfo(true)"
+ >
+ {{ t('common.retry') }}
+ </t-button>
+ <t-button
+ v-if="graphAvailability === 'disabled' && !embedded"
size="small"
theme="primary"
variant="outline"
@@ -373,12 +389,12 @@ const tagFabring = ref(false)
const textFabring = ref(false)
const extracting = ref(false)
-// 系统信息
-const systemInfo = ref<any>(null)
-
-// 计算图数据库是否启用
-const isGraphDatabaseEnabled = computed(() => {
- return systemInfo.value?.graph_database_engine && systemInfo.value.graph_database_engine !== 'Not Enabled'
+const graphAvailability = ref<'loading' | 'enabled' | 'disabled' | 'error'>('loading')
+const isGraphDatabaseEnabled = computed(() => graphAvailability.value === 'enabled')
+const graphAvailabilityMessage = computed(() => {
+ if (graphAvailability.value === 'loading') return t('graphSettings.checkingAvailability')
+ if (graphAvailability.value === 'error') return t('graphSettings.checkAvailabilityFailed')
+ return t('graphSettings.disabledWarning')
})
// Watch for prop changes
@@ -571,12 +587,19 @@ const clearExtractExample = () => {
const editorResources = useEditorResourcesStore()
-// 加载系统信息
+let systemInfoRequest = 0
const loadSystemInfo = async (force = false) => {
+ const request = ++systemInfoRequest
+ graphAvailability.value = 'loading'
try {
await editorResources.ensureSystemInfo(force)
- systemInfo.value = editorResources.systemInfo
+ if (request !== systemInfoRequest) return
+ const engine = editorResources.systemInfo?.graph_database_engine
+ const name = typeof engine === 'string' ? engine.trim() : ''
+ graphAvailability.value = !name ? 'error' : name === 'Not Enabled' ? 'disabled' : 'enabled'
} catch (error: any) {
+ if (request !== systemInfoRequest) return
+ graphAvailability.value = 'error'
console.error('Failed to load system info:', error)
}
}
@@ -653,6 +676,11 @@ onMounted(async () => {
}
}
+.graph-disabled--loading .graph-disabled-icon {
+ color: var(--td-brand-color);
+ background: var(--td-brand-color-light);
+}
+
.settings-group {
display: flex;
flex-direction: column;