diff --git a/docs/docs.go b/docs/docs.go index 5723f0b2..c29fdffb 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -7938,7 +7938,7 @@ const docTemplate = `{ "Bearer": [] } ], - "description": "Retrieve a wiki page by its slug", + "description": "Retrieve a wiki page by its slug, including titles of existing backlinks", "produces": [ "application/json" ], @@ -7966,7 +7966,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WikiPage" + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WikiPageDetail" } }, "404": { @@ -24042,6 +24042,150 @@ const docTemplate = `{ } } }, + "github_com_Tencent_WeKnora_internal_types.WikiPageDetail": { + "type": "object", + "properties": { + "aliases": { + "description": "Alternate names, abbreviations, acronyms or translated names", + "type": "array", + "items": { + "type": "string" + } + }, + "category_path": { + "description": "CategoryPath is the directory breadcrumb that groups this page in the\nwiki browser, e.g. [\"AI\", \"LLM 应用\", \"RAG\"]. Derived cache of the\nfolder chain identified by FolderID.", + "type": "array", + "items": { + "type": "string" + } + }, + "chunk_refs": { + "description": "ChunkRefs records the specific source-document chunks this page was\nbuilt from — one UUID per cited chunk. Populated during ingest from\nthe chunk-citation pass; refreshed wholesale whenever the page is\nre-materialized. Empty for summary pages (they are document-level\nsynopses and don't carry chunk-level citations). Use this when you\nneed to surface the underlying evidence for a wiki page, or to\nretract citations when a source document is deleted.", + "type": "array", + "items": { + "type": "string" + } + }, + "content": { + "description": "Full markdown content", + "type": "string" + }, + "created_at": { + "description": "Creation time", + "type": "string" + }, + "deleted_at": { + "description": "Soft delete", + "allOf": [ + { + "$ref": "#/definitions/gorm.DeletedAt" + } + ] + }, + "depth": { + "description": "Depth is len(CategoryPath), cached for filtering / display.", + "type": "integer" + }, + "folder_id": { + "description": "FolderID is the single source of truth for where this page sits in the\ndirectory tree — a reference to wiki_folders.id (\"\" = wiki root). The\nCategoryPath / WikiPath / Depth fields below are denormalized caches\nrecomputed from this folder's chain on every write so list/index/search\nqueries don't have to join wiki_folders.", + "type": "string" + }, + "id": { + "description": "Unique identifier (UUID)", + "type": "string" + }, + "in_link_titles": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "in_links": { + "description": "Slugs of pages that link TO this page (backlinks)", + "type": "array", + "items": { + "type": "string" + } + }, + "knowledge_base_id": { + "description": "Knowledge base this page belongs to", + "type": "string" + }, + "last_edit_source": { + "description": "LastEditSource records who authored the CURRENT version: pipeline |\nagent | user | revert. Empty for legacy rows (treated as pipeline).\nWhen the version is superseded this value travels into the revision\nsnapshot, so each historical version keeps its own author kind.", + "type": "string" + }, + "last_editor_id": { + "description": "LastEditorID is the user id of the caller that produced the current\nversion (empty for background pipeline writes).", + "type": "string" + }, + "out_links": { + "description": "Slugs of pages this page links to (outbound links)", + "type": "array", + "items": { + "type": "string" + } + }, + "page_metadata": { + "description": "Arbitrary metadata (tags, categories, dates, etc.)", + "type": "array", + "items": { + "type": "integer" + } + }, + "page_type": { + "description": "Page type: summary, entity, concept, index, synthesis, comparison", + "type": "string" + }, + "parent_slug": { + "description": "ParentSlug optionally points at the wiki page that should act as this\npage's semantic parent in the directory tree. The parent may be empty\nwhen the page is grouped only by FolderID.", + "type": "string" + }, + "slug": { + "description": "URL-friendly slug for addressing, e.g. \"entity/acme-corp\", \"concept/rag\"\nUnique within a knowledge base", + "type": "string" + }, + "sort_order": { + "description": "SortOrder allows generated or manually edited pages to control sibling\nordering before falling back to title.", + "type": "integer" + }, + "source_refs": { + "description": "References to source knowledge IDs that contributed to this page.\nFormat matches the legacy \"\u003cknowledge_id\u003e|\u003cdoc_title\u003e\" convention used\nacross the ingest pipeline, so retract / display code can split on ` + "`" + `|` + "`" + `\nto recover the title. Document-level granularity.", + "type": "array", + "items": { + "type": "string" + } + }, + "status": { + "description": "Page status: draft, published, archived", + "type": "string" + }, + "summary": { + "description": "One-line summary for index listing", + "type": "string" + }, + "tenant_id": { + "description": "Workspace ID for multi-workspace isolation", + "type": "integer" + }, + "title": { + "description": "Human-readable title", + "type": "string" + }, + "updated_at": { + "description": "Last update time", + "type": "string" + }, + "version": { + "description": "Version number. Incremented only when a user-visible content field\n(title, content, summary, page_type, status) actually changes; pure\nbookkeeping writes (link maintenance, same-content re-ingest, status\nsync from background jobs) leave it untouched so it can be used as a\nreal \"the page was edited\" signal.", + "type": "integer" + }, + "wiki_path": { + "description": "WikiPath is a normalized, sortable path derived from page_type,\ncategory_path, and title. It keeps large directory listings cheap to sort.", + "type": "string" + } + } + }, "github_com_Tencent_WeKnora_internal_types.WikiPageIssue": { "type": "object", "properties": { diff --git a/docs/swagger.json b/docs/swagger.json index 2e3fcdcd..7f857e19 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -7931,7 +7931,7 @@ "Bearer": [] } ], - "description": "Retrieve a wiki page by its slug", + "description": "Retrieve a wiki page by its slug, including titles of existing backlinks", "produces": [ "application/json" ], @@ -7959,7 +7959,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WikiPage" + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WikiPageDetail" } }, "404": { @@ -24035,6 +24035,150 @@ } } }, + "github_com_Tencent_WeKnora_internal_types.WikiPageDetail": { + "type": "object", + "properties": { + "aliases": { + "description": "Alternate names, abbreviations, acronyms or translated names", + "type": "array", + "items": { + "type": "string" + } + }, + "category_path": { + "description": "CategoryPath is the directory breadcrumb that groups this page in the\nwiki browser, e.g. [\"AI\", \"LLM 应用\", \"RAG\"]. Derived cache of the\nfolder chain identified by FolderID.", + "type": "array", + "items": { + "type": "string" + } + }, + "chunk_refs": { + "description": "ChunkRefs records the specific source-document chunks this page was\nbuilt from — one UUID per cited chunk. Populated during ingest from\nthe chunk-citation pass; refreshed wholesale whenever the page is\nre-materialized. Empty for summary pages (they are document-level\nsynopses and don't carry chunk-level citations). Use this when you\nneed to surface the underlying evidence for a wiki page, or to\nretract citations when a source document is deleted.", + "type": "array", + "items": { + "type": "string" + } + }, + "content": { + "description": "Full markdown content", + "type": "string" + }, + "created_at": { + "description": "Creation time", + "type": "string" + }, + "deleted_at": { + "description": "Soft delete", + "allOf": [ + { + "$ref": "#/definitions/gorm.DeletedAt" + } + ] + }, + "depth": { + "description": "Depth is len(CategoryPath), cached for filtering / display.", + "type": "integer" + }, + "folder_id": { + "description": "FolderID is the single source of truth for where this page sits in the\ndirectory tree — a reference to wiki_folders.id (\"\" = wiki root). The\nCategoryPath / WikiPath / Depth fields below are denormalized caches\nrecomputed from this folder's chain on every write so list/index/search\nqueries don't have to join wiki_folders.", + "type": "string" + }, + "id": { + "description": "Unique identifier (UUID)", + "type": "string" + }, + "in_link_titles": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "in_links": { + "description": "Slugs of pages that link TO this page (backlinks)", + "type": "array", + "items": { + "type": "string" + } + }, + "knowledge_base_id": { + "description": "Knowledge base this page belongs to", + "type": "string" + }, + "last_edit_source": { + "description": "LastEditSource records who authored the CURRENT version: pipeline |\nagent | user | revert. Empty for legacy rows (treated as pipeline).\nWhen the version is superseded this value travels into the revision\nsnapshot, so each historical version keeps its own author kind.", + "type": "string" + }, + "last_editor_id": { + "description": "LastEditorID is the user id of the caller that produced the current\nversion (empty for background pipeline writes).", + "type": "string" + }, + "out_links": { + "description": "Slugs of pages this page links to (outbound links)", + "type": "array", + "items": { + "type": "string" + } + }, + "page_metadata": { + "description": "Arbitrary metadata (tags, categories, dates, etc.)", + "type": "array", + "items": { + "type": "integer" + } + }, + "page_type": { + "description": "Page type: summary, entity, concept, index, synthesis, comparison", + "type": "string" + }, + "parent_slug": { + "description": "ParentSlug optionally points at the wiki page that should act as this\npage's semantic parent in the directory tree. The parent may be empty\nwhen the page is grouped only by FolderID.", + "type": "string" + }, + "slug": { + "description": "URL-friendly slug for addressing, e.g. \"entity/acme-corp\", \"concept/rag\"\nUnique within a knowledge base", + "type": "string" + }, + "sort_order": { + "description": "SortOrder allows generated or manually edited pages to control sibling\nordering before falling back to title.", + "type": "integer" + }, + "source_refs": { + "description": "References to source knowledge IDs that contributed to this page.\nFormat matches the legacy \"\u003cknowledge_id\u003e|\u003cdoc_title\u003e\" convention used\nacross the ingest pipeline, so retract / display code can split on `|`\nto recover the title. Document-level granularity.", + "type": "array", + "items": { + "type": "string" + } + }, + "status": { + "description": "Page status: draft, published, archived", + "type": "string" + }, + "summary": { + "description": "One-line summary for index listing", + "type": "string" + }, + "tenant_id": { + "description": "Workspace ID for multi-workspace isolation", + "type": "integer" + }, + "title": { + "description": "Human-readable title", + "type": "string" + }, + "updated_at": { + "description": "Last update time", + "type": "string" + }, + "version": { + "description": "Version number. Incremented only when a user-visible content field\n(title, content, summary, page_type, status) actually changes; pure\nbookkeeping writes (link maintenance, same-content re-ingest, status\nsync from background jobs) leave it untouched so it can be used as a\nreal \"the page was edited\" signal.", + "type": "integer" + }, + "wiki_path": { + "description": "WikiPath is a normalized, sortable path derived from page_type,\ncategory_path, and title. It keeps large directory listings cheap to sort.", + "type": "string" + } + } + }, "github_com_Tencent_WeKnora_internal_types.WikiPageIssue": { "type": "object", "properties": { @@ -26438,4 +26582,4 @@ "in": "header" } } -} \ No newline at end of file +} diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 3959aaf4..6e1ebcb3 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -4919,6 +4919,148 @@ definitions: category_path, and title. It keeps large directory listings cheap to sort. type: string type: object + github_com_Tencent_WeKnora_internal_types.WikiPageDetail: + properties: + aliases: + description: Alternate names, abbreviations, acronyms or translated names + items: + type: string + type: array + category_path: + description: |- + CategoryPath is the directory breadcrumb that groups this page in the + wiki browser, e.g. ["AI", "LLM 应用", "RAG"]. Derived cache of the + folder chain identified by FolderID. + items: + type: string + type: array + chunk_refs: + description: |- + ChunkRefs records the specific source-document chunks this page was + built from — one UUID per cited chunk. Populated during ingest from + the chunk-citation pass; refreshed wholesale whenever the page is + re-materialized. Empty for summary pages (they are document-level + synopses and don't carry chunk-level citations). Use this when you + need to surface the underlying evidence for a wiki page, or to + retract citations when a source document is deleted. + items: + type: string + type: array + content: + description: Full markdown content + type: string + created_at: + description: Creation time + type: string + deleted_at: + allOf: + - $ref: '#/definitions/gorm.DeletedAt' + description: Soft delete + depth: + description: Depth is len(CategoryPath), cached for filtering / display. + type: integer + folder_id: + description: |- + FolderID is the single source of truth for where this page sits in the + directory tree — a reference to wiki_folders.id ("" = wiki root). The + CategoryPath / WikiPath / Depth fields below are denormalized caches + recomputed from this folder's chain on every write so list/index/search + queries don't have to join wiki_folders. + type: string + id: + description: Unique identifier (UUID) + type: string + in_link_titles: + additionalProperties: + type: string + type: object + in_links: + description: Slugs of pages that link TO this page (backlinks) + items: + type: string + type: array + knowledge_base_id: + description: Knowledge base this page belongs to + type: string + last_edit_source: + description: |- + LastEditSource records who authored the CURRENT version: pipeline | + agent | user | revert. Empty for legacy rows (treated as pipeline). + When the version is superseded this value travels into the revision + snapshot, so each historical version keeps its own author kind. + type: string + last_editor_id: + description: |- + LastEditorID is the user id of the caller that produced the current + version (empty for background pipeline writes). + type: string + out_links: + description: Slugs of pages this page links to (outbound links) + items: + type: string + type: array + page_metadata: + description: Arbitrary metadata (tags, categories, dates, etc.) + items: + type: integer + type: array + page_type: + description: 'Page type: summary, entity, concept, index, synthesis, comparison' + type: string + parent_slug: + description: |- + ParentSlug optionally points at the wiki page that should act as this + page's semantic parent in the directory tree. The parent may be empty + when the page is grouped only by FolderID. + type: string + slug: + description: |- + URL-friendly slug for addressing, e.g. "entity/acme-corp", "concept/rag" + Unique within a knowledge base + type: string + sort_order: + description: |- + SortOrder allows generated or manually edited pages to control sibling + ordering before falling back to title. + type: integer + source_refs: + description: |- + References to source knowledge IDs that contributed to this page. + Format matches the legacy "|" convention used + across the ingest pipeline, so retract / display code can split on `|` + to recover the title. Document-level granularity. + items: + type: string + type: array + status: + description: 'Page status: draft, published, archived' + type: string + summary: + description: One-line summary for index listing + type: string + tenant_id: + description: Workspace ID for multi-workspace isolation + type: integer + title: + description: Human-readable title + type: string + updated_at: + description: Last update time + type: string + version: + description: |- + Version number. Incremented only when a user-visible content field + (title, content, summary, page_type, status) actually changes; pure + bookkeeping writes (link maintenance, same-content re-ingest, status + sync from background jobs) leave it untouched so it can be used as a + real "the page was edited" signal. + type: integer + wiki_path: + description: |- + WikiPath is a normalized, sortable path derived from page_type, + category_path, and title. It keeps large directory listings cheap to sort. + type: string + type: object github_com_Tencent_WeKnora_internal_types.WikiPageIssue: properties: created_at: @@ -11700,7 +11842,8 @@ paths: tags: - Wiki get: - description: Retrieve a wiki page by its slug + description: Retrieve a wiki page by its slug, including titles of existing + backlinks parameters: - description: Knowledge base ID in: path @@ -11718,7 +11861,7 @@ paths: "200": description: OK schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.WikiPage' + $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.WikiPageDetail' "404": description: Not Found schema: diff --git a/docs/swagger_contract_test.go b/docs/swagger_contract_test.go index 09161fa2..302d9c98 100644 --- a/docs/swagger_contract_test.go +++ b/docs/swagger_contract_test.go @@ -79,6 +79,47 @@ func TestFAQEnabledFilterContract(t *testing.T) { } } +func TestWikiPageBacklinkTitlesContract(t *testing.T) { + for _, tt := range swaggerDocuments() { + t.Run(tt.name, func(t *testing.T) { + var spec struct { + Paths map[string]map[string]struct { + Responses map[string]struct { + Schema struct { + Ref string `json:"$ref" yaml:"$ref"` + } `json:"schema" yaml:"schema"` + } `json:"responses" yaml:"responses"` + } `json:"paths" yaml:"paths"` + Definitions map[string]struct { + Properties map[string]map[string]any `json:"properties" yaml:"properties"` + } `json:"definitions" yaml:"definitions"` + } + if err := tt.parse(tt.loadSpec(t), &spec); err != nil { + t.Fatal(err) + } + const detail = "github_com_Tencent_WeKnora_internal_types.WikiPageDetail" + get := spec.Paths["/knowledgebase/{kb_id}/wiki/pages/{slug}"]["get"] + if get.Responses["200"].Schema.Ref != "#/definitions/"+detail { + t.Fatal("page detail response must expose backlink titles") + } + properties := spec.Definitions[detail].Properties + titles := properties["in_link_titles"] + values, ok := titles["additionalProperties"].(map[string]any) + if titles["type"] != "object" || !ok || values["type"] != "string" { + t.Fatal("in_link_titles must be a string-valued map") + } + for field := range spec.Definitions["github_com_Tencent_WeKnora_internal_types.WikiPage"].Properties { + if _, ok := properties[field]; !ok { + t.Errorf("page detail dropped existing field %s", field) + } + } + if _, ok := spec.Paths["/knowledgebase/{kb_id}/wiki/page-titles"]; ok { + t.Fatal("obsolete standalone title endpoint remains documented") + } + }) + } +} + func readSwaggerFile(t *testing.T, name string) []byte { t.Helper() data, err := os.ReadFile(name) diff --git a/frontend/src/api/wiki/index.ts b/frontend/src/api/wiki/index.ts index ea5f295a..02855898 100644 --- a/frontend/src/api/wiki/index.ts +++ b/frontend/src/api/wiki/index.ts @@ -27,6 +27,8 @@ export interface WikiPage { sort_order?: number; source_refs: string[]; in_links: string[]; + // Present on page detail responses; list and mutation responses omit it. + in_link_titles?: Record; out_links: string[]; page_metadata: Record; version: number; diff --git a/frontend/src/views/knowledge/wiki/WikiBrowser.vue b/frontend/src/views/knowledge/wiki/WikiBrowser.vue index 2b68c6c1..1d0f65b7 100644 --- a/frontend/src/views/knowledge/wiki/WikiBrowser.vue +++ b/frontend/src/views/knowledge/wiki/WikiBrowser.vue @@ -809,6 +809,7 @@ import { expandedWikiDirectoryPaths, expandWikiDirectoryPath, } from './wikiDirectoryState' +import { resolveWikiBacklinkTitle } from './wikiBacklinkTitles' import { getKnowledgeDetails } from '@/api/knowledge-base' import { createSessions } from '@/api/chat' import ChatView from '@/views/chat/index.vue' @@ -2947,7 +2948,8 @@ async function savePageEdit(versionOverride?: number) { version: versionOverride ?? editBaseVersion.value, }) const updated = ((res as any).data || res) as WikiPage - selectedPage.value = updated + // Updates omit the display-only titles; retain the current detail map. + selectedPage.value = { ...selectedPage.value, ...updated } editingPage.value = false editConflictVersion.value = null updateSidebarPageTitle(slug, updated.title) @@ -3699,12 +3701,7 @@ function formatDate(dateStr: string) { // Convert slug like "entity/acme-corp" to a readable label "acme-corp" function slugDisplayName(slug: string): string { - // Find the page title if loaded - const page = pages.value.find(p => p.slug === slug) - if (page) return page.title - // Fallback: strip type prefix, replace hyphens - const parts = slug.split('/') - return parts.length > 1 ? parts.slice(1).join('/') : slug + return resolveWikiBacklinkTitle(slug, selectedPage.value?.in_link_titles ?? {}, pages.value) } // ─── Graph Rendering (interactive SVG force-directed graph) ─── diff --git a/frontend/src/views/knowledge/wiki/wikiBacklinkBrowser.test.ts b/frontend/src/views/knowledge/wiki/wikiBacklinkBrowser.test.ts new file mode 100644 index 00000000..6f6b550e --- /dev/null +++ b/frontend/src/views/knowledge/wiki/wikiBacklinkBrowser.test.ts @@ -0,0 +1,167 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { createRequire } from 'node:module' +import test from 'node:test' +import { fileURLToPath } from 'node:url' +import { runInNewContext } from 'node:vm' +import { compileScript, parse } from '@vue/compiler-sfc' +import ts from 'typescript' +import { createRenderer, nextTick } from 'vue' + +const require = createRequire(import.meta.url) +const filename = fileURLToPath(new URL('./WikiBrowser.vue', import.meta.url)) +const { descriptor } = parse(readFileSync(filename, 'utf8'), { filename }) +const script = compileScript(descriptor, { id: 'wiki-backlink-browser-test' }).content + .replace('__expose();', '') + .replace('return __returned__', '__expose(__returned__); return __returned__') +const compiled = ts.transpileModule(script, { + compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 }, +}).outputText + +function page(slug: string, titles: Record = {}) { + return { id: slug, slug, title: slug, content: '', version: 1, in_links: Object.keys(titles), in_link_titles: titles } +} + +async function fixture() { + const calls: { name: string; args: any[] }[] = [] + const errors: unknown[][] = [] + let response: any = page('first') + let failure: Error | undefined + const api = { + getWikiPage: async (...args: any[]) => { + calls.push({ name: 'getWikiPage', args }) + if (failure) throw failure + return { data: response } + }, + updateWikiPage: async (...args: any[]) => { + calls.push({ name: 'updateWikiPage', args }) + const { in_link_titles, ...updated } = response + return { data: { ...updated, ...args[2], version: updated.version + 1 } } + }, + listWikiIssues: async () => [], + listWikiPages: async () => ({ pages: [], total: 0 }), + listWikiFolders: async () => ({ folders: [] }), + getWikiIndex: async () => ({ groups: [] }), + getWikiStats: async () => ({}), + } + const exports: any = {} + runInNewContext(compiled, { + exports, console: { error: (...args: unknown[]) => errors.push(args) }, + setTimeout, clearTimeout, setInterval, clearInterval, + localStorage: { getItem: () => null, setItem() {} }, + require(name: string) { + if (name === 'vue' || name === 'marked') return require(name) + if (name === 'vue-router') return { useRouter: () => ({}), useRoute: () => ({ query: {} }) } + if (name === 'vue-i18n') return { useI18n: () => ({ t: (key: string) => key }) } + if (name === '@/stores/menu') return { useMenuStore: () => ({}) } + if (name === '@/stores/settings') return { useSettingsStore: () => ({}) } + if (name === '@/api/wiki') return api + if (name === 'tdesign-vue-next') return { MessagePlugin: { success() {}, error() {} } } + // DOM sanitization has separate tests; this fixture exercises the actual + // component's title resolution and Markdown caller before that boundary. + if (name === '@/utils/security') return { sanitizeMarkdownHTML: (html: string) => html, hydrateProtectedFileImages: async () => {} } + if (name.startsWith('./wiki')) return require(`${name}.ts`) + if (name === '@/utils/markedLiteralTilde') return require('../../../utils/markedLiteralTilde.ts') + if (name.endsWith('.vue') || ['vue-virtual-scroller', '@/api/knowledge-base', '@/api/chat'].includes(name)) return { default: {} } + throw new Error(`Unexpected component dependency: ${name}`) + }, + }) + exports.default.render = () => null + const renderer = createRenderer({ + createElement: () => ({}), createText: () => ({}), createComment: () => ({}), + insert() {}, remove() {}, setElementText() {}, setText() {}, patchProp() {}, + parentNode: () => null, nextSibling: () => null, + }) + const app = renderer.createApp(exports.default, { knowledgeBaseId: 'kb-1' }) + const vm: any = app.mount({}) + await new Promise(resolve => setImmediate(resolve)) + await nextTick() + return { + vm, calls, errors, + respond(value: any) { response = value; failure = undefined }, + fail() { failure = new Error('page lookup failed') }, + close: () => app.unmount(), + } +} + +test('page navigation consumes all response titles without a separate title request', async () => { + const f = await fixture() + try { + const titles = Object.fromEntries(Array.from({ length: 2507 }, (_, i) => [`concept/${i}-${'a'.repeat(200)}`, `标题 ${i}`])) + f.respond(page('first', titles)) + await f.vm.selectPage({ id: 'first', slug: 'first' }) + await nextTick() + for (const [slug, title] of Object.entries(titles)) assert.equal(f.vm.slugDisplayName(slug), title) + assert.equal(f.calls.length, 1) + assert.deepEqual(f.calls[0], { name: 'getWikiPage', args: ['kb-1', 'first'] }) + assert.equal(f.errors.length, 0) + } finally { f.close() } +}) + +test('navigation, same-page refresh, history and clearing use the matching page map', async () => { + const f = await fixture() + try { + f.respond(page('first', { 'concept/shared': 'First title' })) + await f.vm.selectPage({ id: 'first', slug: 'first' }) + f.respond(page('second', { 'concept/shared': 'Second title' })) + await f.vm.navigateToSlug('second') + assert.equal(f.vm.slugDisplayName('concept/shared'), 'Second title') + f.respond(page('second', { 'concept/shared': 'Refreshed title' })) + await f.vm.refreshSelectedPage() + assert.equal(f.vm.slugDisplayName('concept/shared'), 'Refreshed title') + f.vm.goBack() + assert.equal(f.vm.selectedPage.slug, 'first') + assert.equal(f.vm.slugDisplayName('concept/shared'), 'First title') + f.vm.selectedPage = null + assert.equal(f.vm.slugDisplayName('concept/shared'), 'shared') + assert.equal(f.errors.length, 0) + } finally { f.close() } +}) + +test('Markdown caller handles prototype names, missing titles and explicit labels', async () => { + const f = await fixture() + try { + f.respond(page('current')) + await f.vm.navigateToSlug('current') + for (const slug of ['constructor', 'toString', '__proto__', 'hasOwnProperty']) { + const html = f.vm.renderMarkdown(`[[${slug}]]`) + assert.ok(html.includes(`data-slug="${slug}"`)) + assert.ok(html.includes(`>${require('marked').marked.parseInline(slug)}`)) + assert.match(f.vm.renderMarkdown(`[[${slug}|Explicit label]]`), />Explicit label<\/a>/) + } + f.vm.pages = [{ slug: 'concept/loaded', title: 'Loaded title' }] + assert.match(f.vm.renderMarkdown('[[concept/loaded]] [[concept/missing]]'), />Loaded title<\/a>.*>missing<\/a>/) + f.respond(page('current', JSON.parse('{"constructor":"构造函数","__proto__":"原型"}'))) + await f.vm.refreshSelectedPage() + assert.match(f.vm.renderMarkdown('[[constructor]] [[__proto__]]'), />构造函数<\/a>.*>原型<\/a>/) + assert.equal(f.errors.length, 0) + } finally { f.close() } +}) + +test('saving page edits retains titles omitted from the mutation response', async () => { + const f = await fixture() + try { + f.respond(page('current', { 'concept/unloaded': 'Unloaded title' })) + await f.vm.navigateToSlug('current') + await nextTick() + f.vm.startEditPage() + f.vm.editForm.title = 'Edited title' + await f.vm.savePageEdit() + assert.equal(f.vm.selectedPage.title, 'Edited title') + assert.equal(f.vm.slugDisplayName('concept/unloaded'), 'Unloaded title') + assert.equal(f.errors.length, 0) + } finally { f.close() } +}) + +test('failed navigation retains the displayed page and reports the failure', async () => { + const f = await fixture() + try { + f.respond(page('first', { 'concept/shared': 'First title' })) + await f.vm.navigateToSlug('first') + f.fail() + await f.vm.navigateToSlug('second') + assert.equal(f.vm.selectedPage.slug, 'first') + assert.equal(f.vm.slugDisplayName('concept/shared'), 'First title') + assert.equal(f.errors.length, 1) + } finally { f.close() } +}) diff --git a/frontend/src/views/knowledge/wiki/wikiBacklinkTitles.test.ts b/frontend/src/views/knowledge/wiki/wikiBacklinkTitles.test.ts new file mode 100644 index 00000000..9e723061 --- /dev/null +++ b/frontend/src/views/knowledge/wiki/wikiBacklinkTitles.test.ts @@ -0,0 +1,45 @@ +import assert from 'node:assert/strict' +import test from 'node:test' + +import { resolveWikiBacklinkTitle } from './wikiBacklinkTitles.ts' + +test('uses the response title for an unloaded backlink', () => { + assert.equal( + resolveWikiBacklinkTitle( + 'concept/gong-si-zi-ben-zhi-du', + { 'concept/gong-si-zi-ben-zhi-du': '公司资本制度' }, + [], + ), + '公司资本制度', + ) +}) + +test('only uses own string titles and preserves fallback for prototype property names', () => { + for (const slug of ['constructor', 'toString', '__proto__', 'hasOwnProperty']) { + assert.equal(resolveWikiBacklinkTitle(slug, {}, []), slug) + assert.equal(resolveWikiBacklinkTitle(slug, {}, [{ slug, title: 'Loaded title' }]), 'Loaded title') + const titles = JSON.parse(JSON.stringify({ [slug]: ' 中文标题 ' })) + assert.equal(resolveWikiBacklinkTitle(slug, titles, []), '中文标题') + } + const inherited = Object.create({ 'concept/page': 'Inherited title' }) + assert.equal(resolveWikiBacklinkTitle('concept/page', inherited, []), 'page') + for (const value of [undefined, null, 42, true, {}, [], () => 'title', '', ' ']) { + const titles = { 'concept/page': value } as unknown as Record + assert.equal(resolveWikiBacklinkTitle('concept/page', titles, []), 'page') + assert.equal(resolveWikiBacklinkTitle('concept/page', titles, [{ slug: 'concept/page', title: 'Loaded' }]), 'Loaded') + } +}) + +test('prefers the response title and retains hierarchical slug fallback', () => { + assert.equal(resolveWikiBacklinkTitle('concept/a', { 'concept/a': ' Current ' }, [{ slug: 'concept/a', title: 'Old' }]), 'Current') + assert.equal(resolveWikiBacklinkTitle('concept/a/b', {}, []), 'a/b') + assert.equal(resolveWikiBacklinkTitle('', {}, []), '') +}) + +test('keeps loaded page titles and slug fallback behavior', () => { + assert.equal( + resolveWikiBacklinkTitle('entity/acme', {}, [{ slug: 'entity/acme', title: 'Acme' }]), + 'Acme', + ) + assert.equal(resolveWikiBacklinkTitle('concept/unknown-page', {}, []), 'unknown-page') +}) diff --git a/frontend/src/views/knowledge/wiki/wikiBacklinkTitles.ts b/frontend/src/views/knowledge/wiki/wikiBacklinkTitles.ts new file mode 100644 index 00000000..3db0d094 --- /dev/null +++ b/frontend/src/views/knowledge/wiki/wikiBacklinkTitles.ts @@ -0,0 +1,23 @@ +export interface WikiBacklinkPage { + slug: string + title: string +} + +// Resolve a backlink using the page detail's title map first, then pages +// already loaded in the sidebar, and finally the historical slug fallback. +export function resolveWikiBacklinkTitle( + slug: string, + titles: Record, + pages: WikiBacklinkPage[], +): string { + if (Object.prototype.hasOwnProperty.call(titles, slug)) { + const value = titles[slug] + if (typeof value === 'string' && value.trim()) return value.trim() + } + + const loadedPage = pages.find(page => page.slug === slug) + if (loadedPage?.title) return loadedPage.title + + const parts = slug.split('/') + return parts.length > 1 ? parts.slice(1).join('/') : slug +} diff --git a/internal/handler/wiki_page.go b/internal/handler/wiki_page.go index fb8e0700..602d6050 100644 --- a/internal/handler/wiki_page.go +++ b/internal/handler/wiki_page.go @@ -405,12 +405,12 @@ func (h *WikiPageHandler) recordManualWikiActivity( // GetPage godoc // @Summary Get a wiki page by slug -// @Description Retrieve a wiki page by its slug +// @Description Retrieve a wiki page by its slug, including titles of existing backlinks // @Tags Wiki // @Produce json // @Param kb_id path string true "Knowledge base ID" // @Param slug path string true "Page slug" -// @Success 200 {object} types.WikiPage +// @Success 200 {object} types.WikiPageDetail // @Failure 404 {object} errors.AppError // @Security Bearer // @Router /knowledgebase/{kb_id}/wiki/pages/{slug} [get] @@ -437,7 +437,24 @@ func (h *WikiPageHandler) GetPage(c *gin.Context) { return } - c.JSON(http.StatusOK, page) + titles := make(map[string]string, len(page.InLinks)) + // Bound SQL parameters while resolving every backlink, including pages + // outside the sidebar's paginated window. + const batchSize = 1000 + for start := 0; start < len(page.InLinks); start += batchSize { + end := min(start+batchSize, len(page.InLinks)) + pages, err := h.wikiService.ListBySlugs(c.Request.Context(), kbID, page.InLinks[start:end]) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + for slug, backlink := range pages { + if backlink != nil { + titles[slug] = backlink.Title + } + } + } + c.JSON(http.StatusOK, types.WikiPageDetail{WikiPage: page, InLinkTitles: titles}) } // UpdatePage godoc diff --git a/internal/handler/wiki_page_titles_test.go b/internal/handler/wiki_page_titles_test.go new file mode 100644 index 00000000..18b3cd2c --- /dev/null +++ b/internal/handler/wiki_page_titles_test.go @@ -0,0 +1,270 @@ +package handler + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Tencent/WeKnora/internal/application/repository" + "github.com/Tencent/WeKnora/internal/application/service" + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gorm.io/driver/sqlite" + "gorm.io/gorm" +) + +type fakeWikiPageTitlesService struct { + interfaces.WikiPageService + page *types.WikiPage + pages map[string]*types.WikiPageLite + got []string + getErr error + lookupErr error + failAfter int + lookupKBs []string + getKB string + getSlug string +} + +func (f *fakeWikiPageTitlesService) GetPageBySlug(_ context.Context, kbID, slug string) (*types.WikiPage, error) { + f.getKB, f.getSlug = kbID, slug + return f.page, f.getErr +} + +func (f *fakeWikiPageTitlesService) ListBySlugs( + _ context.Context, kbID string, slugs []string, +) (map[string]*types.WikiPageLite, error) { + f.lookupKBs = append(f.lookupKBs, kbID) + if f.lookupErr != nil && len(f.got) >= f.failAfter { + return nil, f.lookupErr + } + f.got = append(f.got, slugs...) + out := make(map[string]*types.WikiPageLite) + for _, slug := range slugs { + if page, ok := f.pages[slug]; ok { + out[slug] = page + } + } + return out, nil +} + +type fakeWikiPageTitlesKBService struct { + interfaces.KnowledgeBaseService + err error + disabled bool +} + +func (f fakeWikiPageTitlesKBService) GetKnowledgeBaseByID( + context.Context, string, +) (*types.KnowledgeBase, error) { + if f.err != nil { + return nil, f.err + } + if f.disabled { + return &types.KnowledgeBase{}, nil + } + return &types.KnowledgeBase{ + Type: types.KnowledgeBaseTypeWiki, + IndexingStrategy: types.IndexingStrategy{WikiEnabled: true}, + }, nil +} + +func wikiPageTitlesEngine(h *WikiPageHandler) *gin.Engine { + gin.SetMode(gin.TestMode) + r := gin.New() + r.GET("/knowledgebase/:kb_id/wiki/pages/*slug", h.GetPage) + return r +} + +func TestGetPageResolvesBacklinkTitles(t *testing.T) { + fake := &fakeWikiPageTitlesService{ + page: &types.WikiPage{ + ID: "page-id", KnowledgeBaseID: "kb-1", Slug: "concept/current", + Title: "当前页面", Content: "正文", Version: 7, + InLinks: types.StringArray{ + "concept/a", "concept/a", "entity/b", "missing", "nil-page", "constructor", "__proto__", + }, + }, + pages: map[string]*types.WikiPageLite{ + "concept/a": {Slug: "concept/a", Title: "概念 A"}, + "entity/b": {Slug: "entity/b", Title: "实体 B"}, + "nil-page": nil, + "constructor": {Slug: "constructor", Title: "构造函数"}, + "__proto__": {Slug: "__proto__", Title: "原型"}, + }, + } + rec := requestWikiPageTitles(fake, fakeWikiPageTitlesKBService{}, "concept/current") + require.Equal(t, http.StatusOK, rec.Code) + assert.Equal(t, "kb-1", fake.getKB) + assert.Equal(t, "concept/current", fake.getSlug) + for _, kbID := range fake.lookupKBs { + assert.Equal(t, "kb-1", kbID) + } + var body types.WikiPageDetail + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body)) + expectedPage, err := json.Marshal(fake.page) + require.NoError(t, err) + actualPage, err := json.Marshal(body.WikiPage) + require.NoError(t, err) + assert.JSONEq(t, string(expectedPage), string(actualPage)) + assert.Equal(t, map[string]string{ + "concept/a": "概念 A", + "entity/b": "实体 B", + "constructor": "构造函数", + "__proto__": "原型", + }, body.InLinkTitles) +} + +func requestWikiPageTitles( + fake *fakeWikiPageTitlesService, kb fakeWikiPageTitlesKBService, slug string, +) *httptest.ResponseRecorder { + h := &WikiPageHandler{wikiService: fake, kbService: kb} + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/knowledgebase/kb-1/wiki/pages/"+slug, nil) + wikiPageTitlesEngine(h).ServeHTTP(rec, req) + return rec +} + +func TestGetPageResolvesAllLargeAndLongBacklinkSets(t *testing.T) { + // Cross several lookup boundaries so earlier results cannot be silently lost. + for _, count := range []int{999, 1000, 1001, 2507} { + t.Run(fmt.Sprint(count), func(t *testing.T) { + fake := &fakeWikiPageTitlesService{ + page: &types.WikiPage{Slug: "current"}, pages: map[string]*types.WikiPageLite{}, + } + for i := 0; i < count; i++ { + slug := fmt.Sprintf("concept/%d-%s", i, strings.Repeat("a", 200)) + fake.page.InLinks = append(fake.page.InLinks, slug) + fake.pages[slug] = &types.WikiPageLite{Slug: slug, Title: fmt.Sprintf("标题 %d", i)} + } + rec := requestWikiPageTitles(fake, fakeWikiPageTitlesKBService{}, "current") + require.Equal(t, http.StatusOK, rec.Code) + var body types.WikiPageDetail + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body)) + require.Len(t, body.InLinkTitles, count) + assert.ElementsMatch(t, []string(fake.page.InLinks), fake.got) + for slug, page := range fake.pages { + assert.Equal(t, page.Title, body.InLinkTitles[slug]) + } + }) + } +} + +func TestGetPageReturnsEmptyTitleObject(t *testing.T) { + for _, links := range []types.StringArray{nil, {}, {"missing"}} { + fake := &fakeWikiPageTitlesService{page: &types.WikiPage{Slug: "current", InLinks: links}} + rec := requestWikiPageTitles(fake, fakeWikiPageTitlesKBService{}, "current") + require.Equal(t, http.StatusOK, rec.Code) + var body map[string]json.RawMessage + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body)) + assert.JSONEq(t, `{}`, string(body["in_link_titles"])) + if len(links) == 0 { + assert.Empty(t, fake.lookupKBs) + } + } +} + +func TestGetPageTitleLookupFailureDoesNotReturnPartialSuccess(t *testing.T) { + for _, failAfter := range []int{0, 1000} { + t.Run(fmt.Sprint(failAfter), func(t *testing.T) { + fake := &fakeWikiPageTitlesService{ + page: &types.WikiPage{Slug: "current"}, pages: map[string]*types.WikiPageLite{}, + lookupErr: errors.New("title query failed"), failAfter: failAfter, + } + for i := 0; i < 2001; i++ { + slug := fmt.Sprintf("concept/%d", i) + fake.page.InLinks = append(fake.page.InLinks, slug) + fake.pages[slug] = &types.WikiPageLite{Slug: slug, Title: "Title"} + } + rec := requestWikiPageTitles(fake, fakeWikiPageTitlesKBService{}, "current") + assert.Equal(t, http.StatusInternalServerError, rec.Code) + assert.JSONEq(t, `{"error":"title query failed"}`, rec.Body.String()) + }) + } +} + +func TestGetPageValidatesBeforeTitleLookup(t *testing.T) { + for _, tc := range []struct { + name string + slug string + kb fakeWikiPageTitlesKBService + getErr error + status int + }{ + {"missing slug", "", fakeWikiPageTitlesKBService{}, nil, http.StatusBadRequest}, + { + "inaccessible KB", "current", + fakeWikiPageTitlesKBService{err: errors.New("denied")}, + nil, http.StatusBadRequest, + }, + {"wiki disabled", "current", fakeWikiPageTitlesKBService{disabled: true}, nil, http.StatusBadRequest}, + {"missing page", "current", fakeWikiPageTitlesKBService{}, repository.ErrWikiPageNotFound, http.StatusNotFound}, + { + "page query failure", "current", + fakeWikiPageTitlesKBService{}, + errors.New("page query failed"), http.StatusInternalServerError, + }, + } { + t.Run(tc.name, func(t *testing.T) { + fake := &fakeWikiPageTitlesService{getErr: tc.getErr} + rec := requestWikiPageTitles(fake, tc.kb, tc.slug) + assert.Equal(t, tc.status, rec.Code) + assert.Empty(t, fake.lookupKBs) + }) + } +} + +func TestGetPageBacklinkTitlesThroughRepository(t *testing.T) { + db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) + require.NoError(t, err) + sqlDB, err := db.DB() + require.NoError(t, err) + sqlDB.SetMaxOpenConns(1) + t.Cleanup(func() { require.NoError(t, sqlDB.Close()) }) + require.NoError(t, db.AutoMigrate(&types.WikiPage{})) + current := &types.WikiPage{ID: "current", KnowledgeBaseID: "kb-1", Slug: "current", Title: "Current"} + pages := make([]types.WikiPage, 0, 2507) + for i := 0; i < 2507; i++ { + slug := fmt.Sprintf("concept/%d-%s", i, strings.Repeat("a", 200)) + current.InLinks = append(current.InLinks, slug) + pages = append(pages, types.WikiPage{ + ID: fmt.Sprint(i), KnowledgeBaseID: "kb-1", Slug: slug, Title: fmt.Sprintf("标题 %d", i), + }) + } + current.InLinks = append(current.InLinks, "other-kb-only", "deleted", "missing") + require.NoError(t, db.CreateInBatches(pages, 100).Error) + require.NoError(t, db.Create(current).Error) + require.NoError(t, db.Create(&types.WikiPage{ + ID: "other", KnowledgeBaseID: "kb-2", Slug: "other-kb-only", Title: "Private", + }).Error) + // Seed a target that was soft-deleted before the request. + require.NoError(t, db.Exec(`INSERT INTO wiki_pages (id, knowledge_base_id, slug, title, deleted_at) + VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)`, + "deleted", "kb-1", "deleted", "Deleted title").Error) + repo := repository.NewWikiPageRepository(db) + h := &WikiPageHandler{ + wikiService: service.NewWikiPageService(repo, nil, nil, nil, nil, nil), + kbService: fakeWikiPageTitlesKBService{}, + } + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/knowledgebase/kb-1/wiki/pages/current", nil) + wikiPageTitlesEngine(h).ServeHTTP(rec, req) + require.Equal(t, http.StatusOK, rec.Code) + var body types.WikiPageDetail + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body)) + require.Len(t, body.InLinkTitles, len(pages)) + for _, page := range pages { + assert.Equal(t, page.Title, body.InLinkTitles[page.Slug]) + } + assert.NotContains(t, body.InLinkTitles, "other-kb-only") + assert.NotContains(t, body.InLinkTitles, "deleted") + assert.NotContains(t, body.InLinkTitles, "missing") +} diff --git a/internal/types/wiki_page.go b/internal/types/wiki_page.go index 8d17d0ac..b40d18f1 100644 --- a/internal/types/wiki_page.go +++ b/internal/types/wiki_page.go @@ -273,6 +273,13 @@ type WikiPage struct { DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"` } +// WikiPageDetail adds display titles to the page detail response without +// persisting them or loading backlink content. +type WikiPageDetail struct { + *WikiPage + InLinkTitles map[string]string `json:"in_link_titles"` +} + // TableName specifies the database table name func (WikiPage) TableName() string { return "wiki_pages" diff --git a/website-docs/04-api/02-api-faq-wiki.md b/website-docs/04-api/02-api-faq-wiki.md index f959ed4d..40536b69 100644 --- a/website-docs/04-api/02-api-faq-wiki.md +++ b/website-docs/04-api/02-api-faq-wiki.md @@ -241,7 +241,7 @@ curl -X PUT $BASE/api/v1/knowledgebase/kb-1/wiki/move-page -H "Authorization: Be 用途:获取页面(`*slug` 为通配路径)。 -响应:200 `WikiPage` +响应:200 `WikiPageDetail`。保留 `WikiPage` 的所有字段,并增加 `in_link_titles`,将 `in_links` 中存在的页面 slug 映射为展示标题,例如 `{"concept/example":"示例标题"}`。没有可解析的反向链接时返回空对象;不存在的目标不出现在映射中。标题查询失败时返回 500,避免返回不完整的成功响应。 ```bash curl $BASE/api/v1/knowledgebase/kb-1/wiki/pages/overview -H "Authorization: Bearer $TOKEN"