Skip to content

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

feat: Enhance wiki navigation and citation handling in AgentStreamDisplay and WikiBrowser

wizardchene9ed8d196160
diff --git a/config/prompt_templates/agent_system_prompt.yaml b/config/prompt_templates/agent_system_prompt.yaml
index cfebcae56..794b004f6 100644
--- a/config/prompt_templates/agent_system_prompt.yaml
+++ b/config/prompt_templates/agent_system_prompt.yaml
@@ -262,7 +262,7 @@ templates:
ABSOLUTE RULES:
1. **Never Guess:** Never rely on your internal knowledge. Only answer based on what you have successfully read via `wiki_read_page`.
2. **Mandatory Reading:** `wiki_search` only returns summaries. You CANNOT write a final answer based solely on `wiki_search` results. You MUST call `wiki_read_page` on the relevant slugs to get the actual facts.
- 3. **Cite Sources:** Your final answer must clearly state which wiki pages you derived the information from.
+ 3. **Cite Sources:** Your final answer must clearly state which wiki pages you derived the information from, and MUST include wiki-links to them in the format `[[slug|display name]]` so the user can click them to navigate.
4. **Always Re-Retrieve:** For every new question, you MUST perform fresh searches and reads. Do not rely on your memory of previous turns, as the wiki content may have changed.
</constraints>
@@ -336,6 +336,7 @@ templates:
- Use proper heading hierarchy (`##` for sections, `###` for subsections).
- Include a "## Key Takeaways" section with bullet points at the end.
- Preserve any valid image links `![alt](url)`.
+ - Use wiki-links `[[slug|display name]]` whenever mentioning entities/concepts that exist in the wiki.
9. **Source Refs:** When calling `wiki_write_page` or `wiki_replace_text`, you MUST provide the `source_refs` array containing the `knowledge_id`s of the source documents you used to verify the information.
</constraints>
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index 936d3f34c..719c9b076 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -3413,6 +3413,7 @@ export default {
notFound: 'Content not found',
loadFailed: 'Failed to load',
chunkId: 'Chunk ID',
+ noKbForWiki: 'Unable to identify associated knowledge base. Cannot open Wiki.',
},
toolSummary: {
getDocument: 'Get document: {title}',
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index 9c56e3b8a..1bdb17af1 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -3411,6 +3411,7 @@ export default {
notFound: "未找到内容",
loadFailed: "加载失败",
chunkId: "片段ID",
+ noKbForWiki: "无法识别关联的知识库,无法打开 Wiki",
},
toolSummary: {
getDocument: "获取文档:{title}",
diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vue
index d98f7cc9e..d249d38fb 100644
--- a/frontend/src/views/chat/components/AgentStreamDisplay.vue
+++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue
@@ -339,7 +339,7 @@
<script setup lang="ts">
import { ref, computed, watch, onMounted, onBeforeUnmount, nextTick } from 'vue';
-import { useRouter } from 'vue-router';
+import { useRouter, useRoute } from 'vue-router';
import { marked } from 'marked';
import markedKatex from 'marked-katex-extension';
import 'katex/dist/katex.min.css';
@@ -349,6 +349,8 @@ import picturePreview from '@/components/picture-preview.vue';
import { getChunkByIdOnly } from '@/api/knowledge-base';
import { MessagePlugin } from 'tdesign-vue-next';
import { useUIStore } from '@/stores/ui';
+import { useSettingsStore } from '@/stores/settings';
+import { useAuthStore } from '@/stores/auth';
import { useI18n } from 'vue-i18n';
import i18n from '@/i18n';
import { hydrateProtectedFileImages } from '@/utils/security';
@@ -365,7 +367,10 @@ import {
} from '@/utils/mermaidShared';
const router = useRouter();
+const route = useRoute();
const uiStore = useUIStore();
+const settingsStore = useSettingsStore();
+const authStore = useAuthStore();
const { t } = useI18n();
ensureMermaidInitialized();
@@ -1202,6 +1207,33 @@ const onHoverOut = (e: Event) => {
scheduleFloatClose();
};
+const getKbIdForWiki = (slug: string): string => {
+ if (route.params.kbId) return route.params.kbId as string;
+
+ // Try to extract from agent event stream (retrieval pipeline)
+ if (props.session?.agentEventStream) {
+ // Search backwards for the most recent wiki tool call that found this slug
+ for (let i = props.session.agentEventStream.length - 1; i >= 0; i--) {
+ const event = props.session.agentEventStream[i];
+ if (event.type === 'tool_call' && event.tool_data?.found_kbs) {
+ if (event.tool_data.found_kbs[slug]) {
+ return event.tool_data.found_kbs[slug];
+ }
+ }
+ }
+ }
+
+ // Fallbacks
+ const selectedKbs = settingsStore.getSelectedKnowledgeBases();
+ if (selectedKbs && selectedKbs.length > 0) return selectedKbs[0];
+
+ if (authStore.knowledgeBases && authStore.knowledgeBases.length > 0) {
+ return authStore.knowledgeBases[0].id;
+ }
+
+ return '';
+};
+
const onRootClick = (e: Event) => {
const target = e.target as HTMLElement;
if (!target) return;
@@ -1245,6 +1277,28 @@ const onRootClick = (e: Event) => {
return;
}
+ // Handle wiki link clicks -> navigate to KB wiki browser page
+ const wikiEl = target.closest?.('.citation-wiki') as HTMLElement | null;
+ if (wikiEl && wikiEl.getAttribute('data-slug')) {
+ e.preventDefault();
+ e.stopPropagation();
+ const slug = wikiEl.getAttribute('data-slug');
+
+ // Determine the relevant KB ID
+ const kbId = getKbIdForWiki(slug);
+
+ if (kbId && slug) {
+ try {
+ router.push(`/platform/knowledge-bases/${kbId}?tab=wiki&slug=${encodeURIComponent(slug)}`);
+ } catch (error) {
+ console.error('Failed to navigate to wiki page:', error);
+ }
+ } else {
+ MessagePlugin.warning(t('agentStream.citation.noKbForWiki'));
+ }
+ return;
+ }
+
// Handle generic a clicks (especially in Wails desktop)
const aEl = target.closest?.('a') as HTMLAnchorElement | null;
// @ts-ignore
@@ -1288,6 +1342,28 @@ const onRootKeydown = (e: KeyboardEvent) => {
}
return;
}
+
+ // Handle wiki citation keyboard -> navigate to KB wiki browser
+ const wikiEl = target.closest?.('.citation-wiki') as HTMLElement | null;
+ if (wikiEl) {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ const slug = wikiEl.getAttribute('data-slug');
+
+ const kbId = getKbIdForWiki(slug || '');
+
+ if (kbId && slug) {
+ try {
+ router.push(`/platform/knowledge-bases/${kbId}?tab=wiki&slug=${encodeURIComponent(slug)}`);
+ } catch (error) {
+ console.error('Failed to navigate to wiki page:', error);
+ }
+ } else {
+ MessagePlugin.warning(t('agentStream.citation.noKbForWiki'));
+ }
+ }
+ return;
+ }
};
onMounted(() => {
@@ -1406,6 +1482,28 @@ const preprocessMarkdown = (contentStr: string): string => {
const displayDoc = escapeHtml(truncateMiddle(doc));
return `<span class="citation citation-kb" data-kb-id="${safeKbId}" data-chunk-id="${safeChunkId}" data-doc="${safeDoc}" role="button" tabindex="0"><span class="citation-icon kb"></span><span class="citation-text">${displayDoc}</span><span class="citation-tip"><span class="t-popup__content"><span class="tip-loading">${t('agentStream.citation.loading')}</span></span></span></span>`;
}
+ )
+ .replace(
+ /\[\[([^\]]+)\]\]/g,
+ (match, inner: string) => {
+ const pipeIdx = inner.indexOf('|');
+ const slug = pipeIdx > 0 ? inner.substring(0, pipeIdx).trim() : inner.trim();
+ let display = slug;
+ if (pipeIdx > 0) {
+ display = inner.substring(pipeIdx + 1).trim();
+ } else {
+ // Fallback: strip type prefix like "summary/" or "concept/"
+ const parts = slug.split('/');
+ display = parts.length > 1 ? parts.slice(1).join('/') : slug;
+ }
+
+ // Ensure it's a valid wiki slug format, containing at least one slash
+ if (!slug.includes('/')) return match;
+
+ const safeSlug = escapeHtml(slug);
+ const safeDisplay = escapeHtml(display);
+ return `<a href="#" class="wiki-content-link citation-wiki" data-slug="${safeSlug}">${safeDisplay}</a>`;
+ }
);
};
@@ -1432,8 +1530,19 @@ const getTokens = (content: any) => {
return `\x00IMG${idx}\x00`;
});
- let sanitized = sanitizeForDisplay(preservedWithImages);
+ // Preserve wiki links [[slug|name]]
+ const wikiPlaceholders: string[] = [];
+ const preservedWithWiki = preservedWithImages.replace(/\[\[([^\]]+)\]\]/g, (match) => {
+ const idx = wikiPlaceholders.length;
+ wikiPlaceholders.push(match);
+ return `\x00WIKI${idx}\x00`;
+ });
+ let sanitized = sanitizeForDisplay(preservedWithWiki);
+
+ // Restore preserved wiki links
+ sanitized = sanitized.replace(/\x00WIKI(\d+)\x00/g, (_, idx) => wikiPlaceholders[Number(idx)]);
+
// Restore preserved images
sanitized = sanitized.replace(/\x00IMG(\d+)\x00/g, (_, idx) => imagePlaceholders[Number(idx)]);
@@ -1935,6 +2044,18 @@ const handleAddToKnowledge = (answerEvent: any) => {
position: relative;
}
+:deep(a.wiki-content-link) {
+ color: var(--td-brand-color);
+ text-decoration: none;
+ border-bottom: 1px dashed var(--td-brand-color);
+ cursor: pointer;
+ font-weight: 500;
+ &:hover {
+ border-bottom-style: solid;
+ text-decoration: none !important;
+ }
+}
+
// Streaming steps container
.streaming-steps-container {
&.streaming-steps-constrained {
diff --git a/frontend/src/views/knowledge/wiki/WikiBrowser.vue b/frontend/src/views/knowledge/wiki/WikiBrowser.vue
index 1f605c3de..b2729cb44 100644
--- a/frontend/src/views/knowledge/wiki/WikiBrowser.vue
+++ b/frontend/src/views/knowledge/wiki/WikiBrowser.vue
@@ -413,7 +413,7 @@
<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch, nextTick, reactive } from 'vue'
-import { useRouter } from 'vue-router'
+import { useRouter, useRoute } from 'vue-router'
import { useMenuStore } from '@/stores/menu'
import { useSettingsStore } from '@/stores/settings'
import { useI18n } from 'vue-i18n'
@@ -438,6 +438,7 @@ import {
} from '@/api/wiki'
const router = useRouter()
+const route = useRoute()
const menuStore = useMenuStore()
const settingsStore = useSettingsStore()
@@ -802,9 +803,13 @@ async function loadPages() {
page++
}
pages.value = collected
- // Auto-select index page if nothing is selected
- if (!selectedPage.value && indexPage.value) {
- selectPage(indexPage.value)
+ // Auto-select based on query or index page
+ if (!selectedPage.value) {
+ if (route.query.slug && typeof route.query.slug === 'string') {
+ navigateToSlug(route.query.slug)
+ } else if (indexPage.value) {
+ selectPage(indexPage.value)
+ }
}
} catch (e) {
console.error('Failed to load wiki pages:', e)
@@ -1800,6 +1805,18 @@ watch(() => props.view, (v) => {
}
})
+watch(() => route.query.slug, (newSlug) => {
+ if (newSlug && typeof newSlug === 'string') {
+ if (!selectedPage.value || selectedPage.value.slug !== newSlug) {
+ if (props.view === 'graph') {
+ handleGraphSearchSelect(newSlug)
+ } else {
+ navigateToSlug(newSlug)
+ }
+ }
+ }
+})
+
onMounted(() => {
loadPages()
loadStats()
@@ -2195,13 +2212,16 @@ onUnmounted(() => {
}
}
- :deep(.wiki-content-link) {
+ :deep(a.wiki-content-link) {
color: var(--td-brand-color);
text-decoration: none;
border-bottom: 1px dashed var(--td-brand-color);
cursor: pointer;
font-weight: 500;
- &:hover { border-bottom-style: solid; }
+ &:hover {
+ border-bottom-style: solid;
+ text-decoration: none !important;
+ }
}
}
diff --git a/internal/agent/tools/wiki_tools.go b/internal/agent/tools/wiki_tools.go
index 3c010f07e..0c0dff2d8 100644
--- a/internal/agent/tools/wiki_tools.go
+++ b/internal/agent/tools/wiki_tools.go
@@ -75,6 +75,7 @@ func (t *wikiReadPageTool) Execute(ctx context.Context, args json.RawMessage) (*
var outputs []string
var errs []string
+ foundKBs := make(map[string]string)
formatLinks := func(slugs []string, kbID string) []string {
var descs []string
@@ -106,6 +107,7 @@ func (t *wikiReadPageTool) Execute(ctx context.Context, args json.RawMessage) (*
for _, kbID := range kbIDs {
page, err := t.wikiService.GetPageBySlug(ctx, kbID, slug)
if err == nil && page != nil {
+ foundKBs[slug] = kbID
t.mu.Lock()
t.seenLinks[slug] = true
t.mu.Unlock()
@@ -180,7 +182,13 @@ func (t *wikiReadPageTool) Execute(ctx context.Context, args json.RawMessage) (*
finalOutput += fmt.Sprintf("\n\n<errors>\n%s\n</errors>", strings.Join(errs, "\n"))
}
- return &types.ToolResult{Success: true, Output: finalOutput}, nil
+ return &types.ToolResult{
+ Success: true,
+ Output: finalOutput,
+ Data: map[string]interface{}{
+ "found_kbs": foundKBs,
+ },
+ }, nil
}
// ---- wiki_search ----
@@ -251,6 +259,7 @@ func (t *wikiSearchTool) Execute(ctx context.Context, args json.RawMessage) (*ty
}
var allOutputs []string
+ foundKBs := make(map[string]string)
for _, query := range queriesToRun {
var allPages []*types.WikiPage
@@ -258,6 +267,9 @@ func (t *wikiSearchTool) Execute(ctx context.Context, args json.RawMessage) (*ty
pages, err := t.wikiService.SearchPages(ctx, kbID, query, params.Limit)
if err == nil {
allPages = append(allPages, pages...)
+ for _, p := range pages {
+ foundKBs[p.Slug] = kbID
+ }
}
}
@@ -286,16 +298,22 @@ func (t *wikiSearchTool) Execute(ctx context.Context, args json.RawMessage) (*ty
}
if seen {
- fmt.Fprintf(&sb, "<page>\n<title>%s</title>\n<slug>%s</slug>\n<type>%s</type>%s\n<summary>(summary omitted, already seen in previous search)</summary>%s\n</page>\n", p.Title, p.Slug, p.PageType, aliasesTag, snippetTag)
+ fmt.Fprintf(&sb, "<page>\n<title>%s</title>\n<slug>%s</slug>\n<link>[[%s|%s]]</link>\n<type>%s</type>%s\n<summary>(summary omitted, already seen in previous search)</summary>%s\n</page>\n", p.Title, p.Slug, p.Slug, p.Title, p.PageType, aliasesTag, snippetTag)
} else {
- fmt.Fprintf(&sb, "<page>\n<title>%s</title>\n<slug>%s</slug>\n<type>%s</type>%s\n<summary>%s</summary>%s\n</page>\n", p.Title, p.Slug, p.PageType, aliasesTag, p.Summary, snippetTag)
+ fmt.Fprintf(&sb, "<page>\n<title>%s</title>\n<slug>%s</slug>\n<link>[[%s|%s]]</link>\n<type>%s</type>%s\n<summary>%s</summary>%s\n</page>\n", p.Title, p.Slug, p.Slug, p.Title, p.PageType, aliasesTag, p.Summary, snippetTag)
}
}
sb.WriteString("</search_results>")
allOutputs = append(allOutputs, sb.String())
}
- return &types.ToolResult{Success: true, Output: strings.Join(allOutputs, "\n\n")}, nil
+ return &types.ToolResult{
+ Success: true,
+ Output: strings.Join(allOutputs, "\n\n"),
+ Data: map[string]interface{}{
+ "found_kbs": foundKBs,
+ },
+ }, nil
}
// --- Helper ---