diff --git a/.github/workflows/plugin-sdk.yml b/.github/workflows/plugin-sdk.yml
index 6c06455f..fd863d09 100644
--- a/.github/workflows/plugin-sdk.yml
+++ b/.github/workflows/plugin-sdk.yml
@@ -11,11 +11,13 @@ on:
paths:
- 'pluginsdk/**'
- 'examples/plugins/notebooks/**'
+ - 'examples/plugins/links/**'
- '.github/workflows/plugin-sdk.yml'
pull_request:
paths:
- 'pluginsdk/**'
- 'examples/plugins/notebooks/**'
+ - 'examples/plugins/links/**'
- '.github/workflows/plugin-sdk.yml'
defaults:
@@ -63,6 +65,8 @@ jobs:
defaults:
run:
working-directory: pluginsdk/python
+ # A job's run defaults replace the workflow's, shell included.
+ shell: bash
steps:
- uses: actions/checkout@v6
- uses: actions/setup-python@v6
@@ -70,8 +74,9 @@ jobs:
python-version: ${{ matrix.python }}
- name: unittest
run: python -W error::ResourceWarning -m unittest discover -s tests -v
- - name: example plugin
- working-directory: examples/plugins/notebooks
- run: python -m unittest -v test_main
+ - name: example plugins
+ run: |
+ (cd ../../examples/plugins/notebooks && python -m unittest -v test_main)
+ (cd ../../examples/plugins/links && python -m unittest -v test_main)
- name: build the package
run: python -m pip install build && python -m build
diff --git a/examples/plugins/links/main.py b/examples/plugins/links/main.py
new file mode 100644
index 00000000..184a1c1d
--- /dev/null
+++ b/examples/plugins/links/main.py
@@ -0,0 +1,78 @@
+"""A WeKnora plugin with pages, written with the Python SDK: a toolbox page
+listing the workspace's links, a settings section where admins edit them,
+and a tab on each knowledge base with links about it. The pages run
+sandboxed in the browser and reach this code only through the bridge
+(wk.get / wk.put), which WeKnora relays as UI requests."""
+
+from __future__ import annotations
+
+import re
+from urllib.parse import urlparse
+
+from weknora_plugin import ErrorCode, Plugin, PluginError, UIResponse
+
+plugin = Plugin("weknora-examples.links", "1.0.0")
+
+MAX_LINKS = 200
+EDITORS = {"contributor", "admin", "owner"}
+KB_PATH = re.compile(r"^/kb/([A-Za-z0-9_-]{1,64})/links$")
+
+
+def clean_links(value) -> list:
+ """Validates links from a page: [{title, url}], http(s) only."""
+ if not isinstance(value, list) or len(value) > MAX_LINKS:
+ raise ValueError(f"send a list of at most {MAX_LINKS} links")
+ out = []
+ for item in value:
+ if not isinstance(item, dict):
+ raise ValueError("each link is an object with a title and a url")
+ title = str(item.get("title") or "").strip()[:120]
+ url = str(item.get("url") or "").strip()
+ parsed = urlparse(url)
+ if parsed.scheme not in ("http", "https") or not parsed.netloc:
+ raise ValueError(f"{url or 'an empty url'} is not an http(s) link")
+ out.append({"title": title or parsed.netloc, "url": url[:2000]})
+ return out
+
+
+def store(call):
+ host = call.host()
+ if host is None:
+ raise PluginError(ErrorCode.UNAVAILABLE, "the Host API is not available to this plugin")
+ return host
+
+
+def handle(call, req) -> UIResponse:
+ host = store(call)
+ if req.path == "/links":
+ if req.method == "GET":
+ return UIResponse(body=host.kv_get("links", []))
+ # Only the settings section edits the workspace's links; WeKnora
+ # lets admins alone open it.
+ if req.method == "PUT" and req.mount == "settingsSections/manage":
+ return save(host, "links", req.body)
+ m = KB_PATH.match(req.path)
+ if m and req.mount == "kbTabs/links":
+ key = f"kb:{m.group(1)}"
+ if req.method == "GET":
+ return UIResponse(body=host.kv_get(key, []))
+ if req.method == "PUT":
+ if req.role not in EDITORS:
+ return UIResponse(status=403, body={"error": "only editors of the workspace can change links"})
+ return save(host, key, req.body)
+ return UIResponse(status=404, body={"error": f"no {req.method} {req.path} here"})
+
+
+def save(host, key, body) -> UIResponse:
+ try:
+ links = clean_links(body)
+ except ValueError as e:
+ return UIResponse(status=400, body={"error": str(e)})
+ host.kv_put(key, links)
+ return UIResponse(body=links)
+
+
+plugin.ui(handle)
+
+if __name__ == "__main__":
+ plugin.serve()
diff --git a/examples/plugins/links/package.sh b/examples/plugins/links/package.sh
new file mode 100755
index 00000000..18d1b053
--- /dev/null
+++ b/examples/plugins/links/package.sh
@@ -0,0 +1,18 @@
+#!/usr/bin/env bash
+# Packages the links example plugin as a .wkp: plugin.yaml, main.py, the
+# pages under ui/ with the bridge library, and the Python SDK under vendor/.
+set -euo pipefail
+cd "$(dirname "$0")"
+version=$(sed -n 's/^version: //p' plugin.yaml)
+out=${1:-"weknora-examples-links-${version}.wkp"}
+stage=$(mktemp -d)
+trap 'rm -rf "$stage"' EXIT
+cp plugin.yaml main.py "$stage"/
+cp -r ui "$stage"/
+cp ../../../packages/plugin-ui/index.js "$stage/ui/weknora-plugin-ui.js"
+mkdir -p "$stage/vendor"
+cp -r ../../../pluginsdk/python/src/weknora_plugin "$stage/vendor/"
+find "$stage" -name __pycache__ -prune -exec rm -rf {} +
+rm -f "$out"
+(cd "$stage" && zip -qr - .) > "$out"
+echo "wrote $out"
diff --git a/examples/plugins/links/plugin.yaml b/examples/plugins/links/plugin.yaml
new file mode 100644
index 00000000..007a1a6e
--- /dev/null
+++ b/examples/plugins/links/plugin.yaml
@@ -0,0 +1,31 @@
+schemaVersion: 1
+id: weknora-examples.links
+version: 1.0.0
+apiVersion: weknora.plugin/v1
+name: { en-US: Team links, zh-CN: 团队链接 }
+description:
+ en-US: A page of links for the workspace and a tab of links on each knowledge base. Shows plugin pages, written in Python.
+ zh-CN: 空间的常用链接页,以及每个知识库上的链接页签。演示插件页面,用 Python 编写。
+publisher: { id: weknora-examples, name: WeKnora examples }
+homepage: https://github.com/Tencent/WeKnora/tree/main/examples/plugins/links
+license: MIT
+runtime: { type: host, kind: python, entry: main.py }
+permissions:
+ # Links live in the plugin's key-value store, per workspace.
+ hostApi: [kv]
+contributes:
+ pages:
+ - id: links
+ name: { en-US: Team links, zh-CN: 团队链接 }
+ description: { en-US: Links the workspace shares, zh-CN: 空间共享的常用链接 }
+ entry: ui/index.html
+ settingsSections:
+ - id: manage
+ name: { en-US: Team links, zh-CN: 团队链接 }
+ entry: ui/manage.html
+ # minRole defaults to admin for settings sections
+ kbTabs:
+ - id: links
+ name: { en-US: Links, zh-CN: 链接 }
+ description: { en-US: Links about this knowledge base, zh-CN: 与本知识库相关的链接 }
+ entry: ui/kb.html
diff --git a/examples/plugins/links/test_main.py b/examples/plugins/links/test_main.py
new file mode 100644
index 00000000..0726c619
--- /dev/null
+++ b/examples/plugins/links/test_main.py
@@ -0,0 +1,56 @@
+import os
+import sys
+import unittest
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, os.path.join(HERE, "..", "..", "..", "pluginsdk", "python", "src"))
+sys.path.insert(0, HERE)
+
+import main # noqa: E402
+from weknora_plugin import UIRequest # noqa: E402
+
+
+class FakeHost:
+ def __init__(self):
+ self.data = {}
+
+ def kv_get(self, key, default=None):
+ return self.data.get(key, default)
+
+ def kv_put(self, key, value, ttl=0):
+ self.data[key] = value
+
+
+class LinksTest(unittest.TestCase):
+ def setUp(self):
+ self.host = FakeHost()
+ main.store = lambda call: self.host
+
+ def req(self, mount, method, path, body=None, role="viewer"):
+ return main.handle(None, UIRequest(mount=mount, method=method, path=path, body=body, role=role))
+
+ def test_workspace_links(self):
+ self.assertEqual(self.req("pages/links", "GET", "/links").body, [])
+ links = [{"title": "", "url": "https://github.com/Tencent/WeKnora"}]
+ # Only the settings section (admins) writes the workspace's links.
+ self.assertEqual(self.req("pages/links", "PUT", "/links", links, role="owner").status, 404)
+ saved = self.req("settingsSections/manage", "PUT", "/links", links, role="admin")
+ self.assertEqual(saved.body, [{"title": "github.com", "url": "https://github.com/Tencent/WeKnora"}])
+ self.assertEqual(self.req("pages/links", "GET", "/links").body, saved.body)
+
+ def test_kb_links(self):
+ path = "/kb/kb-1/links"
+ self.assertEqual(self.req("kbTabs/links", "PUT", path, [], role="viewer").status, 403)
+ self.assertEqual(self.req("kbTabs/links", "PUT", path, [{"title": "Spec", "url": "http://x.example"}], role="contributor").status, 200)
+ self.assertEqual(self.req("kbTabs/links", "GET", path).body[0]["title"], "Spec")
+ self.assertEqual(self.req("kbTabs/links", "GET", "/kb/kb-2/links").body, [])
+ self.assertEqual(self.req("pages/links", "GET", path).status, 404)
+
+ def test_bad_links(self):
+ for body in ({"url": "x"}, [{"url": "javascript:alert(1)"}], [{"url": "ftp://x"}], [{}] * 201):
+ resp = self.req("settingsSections/manage", "PUT", "/links", body, role="admin")
+ self.assertEqual(resp.status, 400, body)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/examples/plugins/links/ui/app.css b/examples/plugins/links/ui/app.css
new file mode 100644
index 00000000..d875d490
--- /dev/null
+++ b/examples/plugins/links/ui/app.css
@@ -0,0 +1,41 @@
+/* Colours and fonts come from the app theme (--wk-* variables, set by the
+ bridge), with fallbacks for opening the page on its own. */
+:root {
+ color-scheme: light;
+ --fg: var(--wk-text-color-primary, #1f2329);
+ --muted: var(--wk-text-color-secondary, #646a73);
+ --line: var(--wk-component-border, #dee0e3);
+ --card: var(--wk-bg-color-container, #fff);
+ --brand: var(--wk-brand-color, #0052d9);
+ --danger: var(--wk-error-color, #d54941);
+ --radius: var(--wk-radius-default, 6px);
+}
+:root[data-theme='dark'] { color-scheme: dark; }
+* { box-sizing: border-box; }
+body {
+ margin: 0;
+ font: 14px/1.5 var(--wk-font-family, system-ui, sans-serif);
+ color: var(--fg);
+ background: transparent;
+}
+main { padding: 4px 2px 12px; }
+.empty { color: var(--muted); padding: 24px 0; text-align: center; }
+ul.links { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; }
+.links li {
+ display: flex; align-items: center; gap: 10px;
+ padding: 10px 12px; border: 1px solid var(--line); border-radius: var(--radius); background: var(--card);
+}
+.links a { color: var(--brand); text-decoration: none; font-weight: 500; }
+.links a:hover { text-decoration: underline; }
+.links .url { color: var(--muted); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; }
+form { display: flex; gap: 8px; margin-top: 12px; flex-wrap: wrap; }
+input {
+ flex: 1; min-width: 140px; padding: 6px 10px; font: inherit; color: var(--fg);
+ background: var(--card); border: 1px solid var(--line); border-radius: var(--radius);
+}
+button {
+ padding: 6px 14px; font: inherit; border-radius: var(--radius); cursor: pointer;
+ border: 1px solid var(--brand); background: var(--brand); color: #fff;
+}
+button.remove { border-color: transparent; background: transparent; color: var(--danger); padding: 4px 8px; }
+button:disabled { opacity: 0.6; cursor: default; }
diff --git a/examples/plugins/links/ui/index.html b/examples/plugins/links/ui/index.html
new file mode 100644
index 00000000..d71690eb
--- /dev/null
+++ b/examples/plugins/links/ui/index.html
@@ -0,0 +1,13 @@
+
+
+
+
+
+ Team links
+
+
+
+
+
+
+
diff --git a/examples/plugins/links/ui/kb.html b/examples/plugins/links/ui/kb.html
new file mode 100644
index 00000000..f1214a57
--- /dev/null
+++ b/examples/plugins/links/ui/kb.html
@@ -0,0 +1,13 @@
+
+
+
+
+
+ Team links
+
+
+
+
+
+
+
diff --git a/examples/plugins/links/ui/links.js b/examples/plugins/links/ui/links.js
new file mode 100644
index 00000000..f2bdbb40
--- /dev/null
+++ b/examples/plugins/links/ui/links.js
@@ -0,0 +1,95 @@
+// The three pages of the plugin. They run in a sandboxed iframe: no network,
+// no storage of the app. Everything goes through the bridge (wk.*), which
+// the app relays to main.py.
+import { connect } from './weknora-plugin-ui.js'
+
+const TEXT = {
+ en: {
+ empty: 'No links yet.', emptyManage: 'No links yet. Add the first one below.',
+ title: 'Title', url: 'https://…', add: 'Add', remove: 'Remove', saved: 'Links saved',
+ confirm: 'Remove this link?', readOnly: 'Only editors of the workspace can change these links.',
+ },
+ zh: {
+ empty: '还没有链接。', emptyManage: '还没有链接,在下方添加第一个。',
+ title: '标题', url: 'https://…', add: '添加', remove: '删除', saved: '链接已保存',
+ confirm: '删除这个链接?', readOnly: '只有空间的编辑者可以修改这些链接。',
+ },
+}
+
+const wk = await connect()
+const app = document.getElementById('app')
+const mode = document.body.dataset.mode
+let text = pick(wk.context.locale)
+wk.on('locale', (locale) => {
+ text = pick(locale)
+ void load()
+})
+// A knowledge base tab follows the app to another knowledge base.
+wk.on('init', () => void load())
+
+function pick(locale) {
+ return String(locale || '').startsWith('zh') ? TEXT.zh : TEXT.en
+}
+
+function path() {
+ return mode === 'kb' ? `/kb/${wk.context.context.knowledgeBaseId}/links` : '/links'
+}
+
+function el(tag, props = {}, ...children) {
+ const node = Object.assign(document.createElement(tag), props)
+ node.append(...children)
+ return node
+}
+
+async function load() {
+ app.setAttribute('aria-busy', 'true')
+ try {
+ const { body } = await wk.get(path())
+ render(Array.isArray(body) ? body : [])
+ } catch (e) {
+ app.replaceChildren(el('p', { className: 'empty', textContent: e.message }))
+ } finally {
+ app.removeAttribute('aria-busy')
+ }
+}
+
+async function save(links) {
+ try {
+ const { body } = await wk.put(path(), links)
+ await wk.toast(text.saved, 'success')
+ render(body)
+ } catch (e) {
+ await wk.toast(e.message, 'error')
+ }
+}
+
+function render(links) {
+ const editable = mode === 'manage' || (mode === 'kb' && wk.context.role !== 'viewer')
+ const list = el('ul', { className: 'links' })
+ links.forEach((link, i) => {
+ const a = el('a', { href: link.url, target: '_blank', rel: 'noopener noreferrer', textContent: link.title })
+ const item = el('li', {}, a, el('span', { className: 'url', textContent: link.url }))
+ if (editable) {
+ const remove = el('button', { className: 'remove', type: 'button', textContent: text.remove })
+ remove.addEventListener('click', async () => {
+ if (await wk.confirm(text.confirm)) await save(links.filter((_, j) => j !== i))
+ })
+ item.append(remove)
+ }
+ list.append(item)
+ })
+ const nodes = links.length ? [list] : [el('p', { className: 'empty', textContent: mode === 'manage' ? text.emptyManage : text.empty })]
+ if (editable) {
+ const title = el('input', { placeholder: text.title, maxLength: 120 })
+ const url = el('input', { placeholder: text.url, type: 'url', required: true })
+ const form = el('form', {}, title, url, el('button', { type: 'submit', textContent: text.add }))
+ form.addEventListener('submit', async (event) => {
+ event.preventDefault()
+ await save([...links, { title: title.value, url: url.value }])
+ })
+ nodes.push(form)
+ }
+ app.replaceChildren(...nodes)
+}
+
+await load()
diff --git a/examples/plugins/links/ui/manage.html b/examples/plugins/links/ui/manage.html
new file mode 100644
index 00000000..9a63b9d8
--- /dev/null
+++ b/examples/plugins/links/ui/manage.html
@@ -0,0 +1,13 @@
+
+
+
+
+
+ Team links
+
+
+
+
+
+
+
diff --git a/frontend/src/api/plugin.ts b/frontend/src/api/plugin.ts
index d866a04b..9310bfb2 100644
--- a/frontend/src/api/plugin.ts
+++ b/frontend/src/api/plugin.ts
@@ -1,4 +1,4 @@
-import { get, put } from '@/utils/request'
+import { get, post, put } from '@/utils/request'
import type { ConfigSchema, ConfigValue } from '@/components/schema-form/schema'
import type { LocalizedText } from '@/utils/localizedText'
@@ -14,6 +14,9 @@ export type ExtensionPoint =
| 'parsers'
| 'skills'
| 'mcpServers'
+ | 'pages'
+ | 'settingsSections'
+ | 'kbTabs'
export interface PluginContribution {
id: string
@@ -27,6 +30,23 @@ export interface PluginContribution {
path?: string
/** Remote MCP server an installed plugin contributes. */
mcp?: { url: string; transport?: string; headers?: Record }
+ /** The HTML page of a UI contribution (pages, settingsSections, kbTabs), under ui/. */
+ entry?: string
+ /** Workspace role a UI contribution needs. */
+ minRole?: 'viewer' | 'contributor' | 'admin' | 'owner'
+}
+
+/** A contribution as GET /plugins/contributions lists it. */
+export interface ListedContribution extends PluginContribution {
+ pluginId: string
+ qualifiedId: string
+ version?: string
+ enabled: boolean
+}
+
+export interface ContributionListing {
+ points: Array<{ point: ExtensionPoint; thirdParty: boolean; declarative: boolean }>
+ contributions: Partial>
}
export interface PluginPermissions {
@@ -98,6 +118,25 @@ export function setPluginEnabled(id: string, enabled: boolean) {
return put<{ data: TenantPlugin }>(`/api/v1/plugins/${encodeURIComponent(id)}/enabled`, { enabled })
}
+/** Every contribution the deployment has, with the workspace's switches. */
+export function listContributions(point?: ExtensionPoint) {
+ return get<{ data: ContributionListing }>('/api/v1/plugins/contributions', point ? { params: { point } } : undefined)
+}
+
+/** What a plugin page's request returned. */
+export interface PluginPageResponse {
+ status: number
+ body?: unknown
+}
+
+/** Relays a request from a plugin page to the plugin's backend. */
+export function pluginPageRequest(
+ pluginId: string,
+ req: { mount: string; method: string; path: string; body?: unknown },
+) {
+ return post<{ data: PluginPageResponse }>(`/api/v1/plugins/${encodeURIComponent(pluginId)}/ui-request`, req)
+}
+
/** The workspace's configuration of a plugin (Admin+). */
export function getPluginConfig(id: string) {
return get<{ data: PluginConfig }>(`/api/v1/plugins/${encodeURIComponent(id)}/config`)
diff --git a/frontend/src/config/toolbox.test.ts b/frontend/src/config/toolbox.test.ts
index 3059169f..7539cf93 100644
--- a/frontend/src/config/toolbox.test.ts
+++ b/frontend/src/config/toolbox.test.ts
@@ -95,6 +95,7 @@ test('settings no longer render moved panels, and old bookmarks reach toolbox',
assert.match(router, /to\.path === '\/platform\/settings' && isToolboxSection\(to\.query\.section\)/)
assert.match(router, /toolboxLocation\(to\.query\.section/)
const page = readFileSync(new URL('../views/toolbox/Toolbox.vue', import.meta.url), 'utf8')
- assert.match(page, /if \(!selectedItem\.value && fallback\) void router\.replace\(toolboxLocation\(fallback\.key\)\)/)
+ // Unknown sections (and plugin pages that are gone) fall back to the first tool.
+ assert.match(page, /if \(!selectedItem\.value && !selectedPage\.value && !pendingPage && fallback\) \{\s*void router\.replace\(toolboxLocation\(fallback\.key\)\)/)
assert.match(page, /:key="sandboxId"\s+:initial-sandbox-id="sandboxId"/)
})
diff --git a/frontend/src/extensions/pluginFrame/PluginFrame.vue b/frontend/src/extensions/pluginFrame/PluginFrame.vue
new file mode 100644
index 00000000..f9edba07
--- /dev/null
+++ b/frontend/src/extensions/pluginFrame/PluginFrame.vue
@@ -0,0 +1,192 @@
+
+
+
+
+
+ {{ t('pluginPages.notResponding') }}
+
+
+
+
+
+
+
diff --git a/frontend/src/extensions/pluginFrame/bridgeHost.test.ts b/frontend/src/extensions/pluginFrame/bridgeHost.test.ts
new file mode 100644
index 00000000..933eddfa
--- /dev/null
+++ b/frontend/src/extensions/pluginFrame/bridgeHost.test.ts
@@ -0,0 +1,113 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+
+// The page's side of the bridge, as plugins ship it.
+import { BridgeError, connect } from '../../../../packages/plugin-ui/index.js'
+import { createBridgeHost, createRateLimiter, isAppPath, type BridgeHandlers } from './bridgeHost'
+
+type Listener = (event: { data: unknown; source: unknown }) => void
+
+/** A window that other windows post to; `source` is set by the pairing. */
+class FakeWindow {
+ listeners: Listener[] = []
+ parent: FakeWindow = this
+ from: FakeWindow | null = null
+ document = undefined
+ addEventListener(_type: string, fn: Listener) {
+ this.listeners.push(fn)
+ }
+ postMessage(data: unknown) {
+ const source = this.from
+ const copy = structuredClone(data)
+ setTimeout(() => this.listeners.forEach((fn) => fn({ data: copy, source })), 0)
+ }
+}
+
+function setup(overrides: Partial = {}, burst = 30) {
+ const app = new FakeWindow()
+ const frame = new FakeWindow()
+ frame.parent = app
+ app.from = frame // what reaches the app comes from the frame
+ frame.from = app
+ const calls: string[] = []
+ const handlers: BridgeHandlers = {
+ apiRequest: async (p) => {
+ calls.push(`api ${p.method} ${p.path} ${JSON.stringify(p.body ?? null)}`)
+ return p.path === '/missing' ? { status: 404, body: { error: 'no such link' } } : { status: 200, body: { ok: true } }
+ },
+ toast: (m, t) => calls.push(`toast ${t} ${m}`),
+ confirm: async (m) => m === 'yes?',
+ navigate: (p) => calls.push(`navigate ${p}`),
+ resize: (h) => calls.push(`resize ${h}`),
+ close: () => calls.push('close'),
+ ...overrides,
+ }
+ const host = createBridgeHost({
+ frame: () => frame as unknown as Window,
+ init: () => ({
+ pluginId: 'acme.links', version: '1.0.0', mount: 'pages/links', locale: 'zh-CN', role: 'viewer',
+ theme: { mode: 'dark', tokens: { 'brand-color': '#0052d9' } }, context: { knowledgeBaseId: 'kb1' },
+ }),
+ handlers,
+ burst,
+ perSecond: 0.001,
+ })
+ app.addEventListener('message', (e) => host.handle(e as unknown as MessageEvent))
+ return { app, frame, host, calls }
+}
+
+test('a page connects, calls its backend and the app', async () => {
+ const { frame, calls } = setup()
+ const wk = await connect({ window: frame as unknown as Window, autoResize: false, applyTheme: false })
+ assert.equal(wk.context.mount, 'pages/links')
+ assert.deepEqual(wk.context.context, { knowledgeBaseId: 'kb1' })
+
+ assert.deepEqual(await wk.put('/links', { a: 1 }), { status: 200, body: { ok: true } })
+ await assert.rejects(wk.get('/missing'), (e: unknown) => e instanceof BridgeError && e.status === 404 && e.message === 'no such link')
+ assert.equal((await wk.get('/missing', { throwOnError: false })).status, 404)
+
+ await wk.toast('saved', 'success')
+ assert.equal(await wk.confirm('yes?'), true)
+ assert.equal(await wk.confirm('no?'), false)
+ await wk.navigate('/platform/knowledge-bases')
+ await assert.rejects(wk.navigate('//evil.example'), /path of the app/)
+ await wk.resize(321.4)
+ await wk.close()
+ assert.deepEqual(calls, [
+ 'api PUT /links {"a":1}',
+ 'api GET /missing null',
+ 'api GET /missing null',
+ 'toast success saved',
+ 'navigate /platform/knowledge-bases',
+ 'resize 322',
+ 'close',
+ ])
+})
+
+test('the app ignores other windows and rate-limits a page', async () => {
+ const { app, frame, calls } = setup({}, 2)
+ const wk = await connect({ window: frame as unknown as Window, autoResize: false, applyTheme: false })
+
+ // A message that does not come from the plugin's frame is dropped.
+ const stranger = new FakeWindow()
+ app.listeners.forEach((fn) =>
+ fn({ data: { weknora: 1, kind: 'request', id: 99, method: 'ui.close', params: {} }, source: stranger }),
+ )
+ assert.equal(calls.length, 0)
+
+ await wk.toast('one')
+ await wk.toast('two')
+ await assert.rejects(wk.toast('three'), /too many requests/)
+})
+
+test('helpers', () => {
+ assert.equal(isAppPath('/platform/x'), true)
+ assert.equal(isAppPath('//x.com'), false)
+ assert.equal(isAppPath('https://x.com'), false)
+ let t = 0
+ const allow = createRateLimiter(1, 1, () => t)
+ assert.equal(allow(), true)
+ assert.equal(allow(), false)
+ t = 1000
+ assert.equal(allow(), true)
+})
diff --git a/frontend/src/extensions/pluginFrame/bridgeHost.ts b/frontend/src/extensions/pluginFrame/bridgeHost.ts
new file mode 100644
index 00000000..14c661c1
--- /dev/null
+++ b/frontend/src/extensions/pluginFrame/bridgeHost.ts
@@ -0,0 +1,214 @@
+// The app's side of the plugin page bridge (packages/plugin-ui is the
+// page's side). A plugin page runs in a sandboxed iframe with an opaque
+// origin; it can only post messages to the app, and the app answers only
+// messages that come from that iframe, at a bounded rate.
+
+/** Protocol version; also marks bridge messages. */
+export const BRIDGE_PROTOCOL = 1
+
+export interface BridgeTheme {
+ mode: 'light' | 'dark'
+ tokens: Record
+}
+
+/** What the page receives in `init`. */
+export interface BridgeInit {
+ pluginId: string
+ version: string
+ mount: string
+ locale: string
+ /** The user's workspace role, for what the page offers; the server decides. */
+ role: string
+ theme: BridgeTheme
+ context: Record
+}
+
+export interface ApiResult {
+ status: number
+ body: unknown
+}
+
+/** What the app does for each call a page makes. */
+export interface BridgeHandlers {
+ apiRequest(params: { method: string; path: string; body?: unknown }): Promise
+ toast(message: string, theme: ToastTheme): void
+ confirm(message: string, title?: string): Promise
+ navigate(path: string): void
+ resize(height: number): void
+ close(): void
+}
+
+export type ToastTheme = 'info' | 'success' | 'warning' | 'error'
+
+export interface BridgeHostOptions {
+ /** The iframe's window; messages from any other source are ignored. */
+ frame: () => Window | null | undefined
+ init: () => BridgeInit
+ handlers: BridgeHandlers
+ /** Calls allowed in a burst and per second after it. */
+ burst?: number
+ perSecond?: number
+ now?: () => number
+}
+
+interface RequestMessage {
+ weknora: number
+ kind: 'request'
+ id: number
+ method: string
+ params?: unknown
+}
+
+export class BridgeCallError extends Error {
+ constructor(
+ message: string,
+ readonly status?: number,
+ ) {
+ super(message)
+ }
+}
+
+const MAX_TOAST = 300
+const MAX_HEIGHT = 20_000
+const TOAST_THEMES = new Set(['info', 'success', 'warning', 'error'])
+
+function isObject(v: unknown): v is Record {
+ return v !== null && typeof v === 'object' && !Array.isArray(v)
+}
+
+/** A path inside the app: "/platform/...", never another origin. */
+export function isAppPath(path: unknown): path is string {
+ return typeof path === 'string' && path.startsWith('/') && !path.startsWith('//') && !path.includes('\\')
+}
+
+/** A token bucket: `burst` calls at once, refilled at `perSecond`. */
+export function createRateLimiter(burst: number, perSecond: number, now: () => number = Date.now) {
+ let tokens = burst
+ let last = now()
+ return () => {
+ const t = now()
+ tokens = Math.min(burst, tokens + ((t - last) / 1000) * perSecond)
+ last = t
+ if (tokens < 1) return false
+ tokens -= 1
+ return true
+ }
+}
+
+export interface BridgeHost {
+ /** Feed every window `message` event here. */
+ handle(event: MessageEvent): void
+ /** Sends an event to the page (init, theme, locale). */
+ send(name: string, data: unknown): void
+}
+
+export function createBridgeHost(opts: BridgeHostOptions): BridgeHost {
+ const allow = createRateLimiter(opts.burst ?? 30, opts.perSecond ?? 10, opts.now)
+ const post = (msg: Record) => {
+ // The page's origin is opaque ("null"), so it cannot be named as the
+ // target; only that window receives the message.
+ opts.frame()?.postMessage({ weknora: BRIDGE_PROTOCOL, ...msg }, '*')
+ }
+ const send = (name: string, data: unknown) => post({ kind: 'event', name, data })
+ const reply = (id: number, result: unknown) => post({ kind: 'response', id, ok: true, result })
+ const fail = (id: number, err: unknown) => {
+ const message = err instanceof Error ? err.message : String(err)
+ const status = err instanceof BridgeCallError ? err.status : undefined
+ post({ kind: 'response', id, ok: false, error: { message, status } })
+ }
+
+ const dispatch = async (method: string, params: Record): Promise => {
+ const h = opts.handlers
+ switch (method) {
+ case 'api.request': {
+ const verb = typeof params.method === 'string' ? params.method.toUpperCase() : 'GET'
+ if (!/^[A-Z]{3,7}$/.test(verb)) throw new BridgeCallError('bad method', 400)
+ if (typeof params.path !== 'string' || !params.path.startsWith('/')) {
+ throw new BridgeCallError('path must start with /', 400)
+ }
+ return h.apiRequest({ method: verb, path: params.path, body: params.body })
+ }
+ case 'ui.toast': {
+ if (typeof params.message !== 'string' || !params.message) throw new BridgeCallError('message is required', 400)
+ const theme = TOAST_THEMES.has(params.theme as ToastTheme) ? (params.theme as ToastTheme) : 'info'
+ h.toast(params.message.slice(0, MAX_TOAST), theme)
+ return null
+ }
+ case 'ui.confirm': {
+ if (typeof params.message !== 'string' || !params.message) throw new BridgeCallError('message is required', 400)
+ const title = typeof params.title === 'string' ? params.title.slice(0, 100) : undefined
+ return h.confirm(params.message.slice(0, MAX_TOAST), title)
+ }
+ case 'ui.navigate':
+ if (!isAppPath(params.path)) throw new BridgeCallError('path must be a path of the app', 400)
+ h.navigate(params.path)
+ return null
+ case 'ui.resize': {
+ const height = Number(params.height)
+ if (!Number.isFinite(height) || height < 0) throw new BridgeCallError('height must be a number', 400)
+ h.resize(Math.min(Math.ceil(height), MAX_HEIGHT))
+ return null
+ }
+ case 'ui.close':
+ h.close()
+ return null
+ default:
+ throw new BridgeCallError(`unknown method ${method}`, 404)
+ }
+ }
+
+ return {
+ send,
+ handle(event: MessageEvent) {
+ const frame = opts.frame()
+ if (!frame || event.source !== frame) return
+ const data = event.data as unknown
+ if (!isObject(data) || data.weknora !== BRIDGE_PROTOCOL) return
+ if (data.kind === 'hello') {
+ send('init', opts.init())
+ return
+ }
+ if (data.kind !== 'request') return
+ const msg = data as unknown as RequestMessage
+ if (typeof msg.id !== 'number' || typeof msg.method !== 'string') return
+ if (!allow()) {
+ fail(msg.id, new BridgeCallError('too many requests', 429))
+ return
+ }
+ dispatch(msg.method, isObject(msg.params) ? msg.params : {}).then(
+ (result) => reply(msg.id, result ?? null),
+ (err) => fail(msg.id, err),
+ )
+ },
+ }
+}
+
+/** The app's design tokens a page may use, read from the root element. */
+export const THEME_TOKENS = [
+ 'brand-color',
+ 'brand-color-light',
+ 'text-color-primary',
+ 'text-color-secondary',
+ 'text-color-placeholder',
+ 'bg-color-page',
+ 'bg-color-container',
+ 'bg-color-secondarycontainer',
+ 'component-border',
+ 'border-level-1-color',
+ 'error-color',
+ 'warning-color',
+ 'success-color',
+ 'radius-default',
+ 'font-family',
+] as const
+
+export function readTheme(doc: Document = document): BridgeTheme {
+ const root = doc.documentElement
+ const style = getComputedStyle(root)
+ const tokens: Record = {}
+ for (const name of THEME_TOKENS) {
+ const value = style.getPropertyValue(`--td-${name}`).trim()
+ if (value) tokens[name] = value
+ }
+ return { mode: root.getAttribute('theme-mode') === 'dark' ? 'dark' : 'light', tokens }
+}
diff --git a/frontend/src/extensions/pluginFrame/pluginPages.test.ts b/frontend/src/extensions/pluginFrame/pluginPages.test.ts
new file mode 100644
index 00000000..29be5145
--- /dev/null
+++ b/frontend/src/extensions/pluginFrame/pluginPages.test.ts
@@ -0,0 +1,44 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+
+import type { ContributionListing, ListedContribution } from '../../api/plugin'
+import { findPage, pageFileUrl, pagesOf } from './pluginPages'
+
+const c = (over: Partial): ListedContribution => ({
+ id: 'links', name: { default: 'Links' }, pluginId: 'acme.links', qualifiedId: 'acme.links/links',
+ version: '1.0.0', enabled: true, entry: 'ui/index.html', ...over,
+})
+
+const listing: ContributionListing = {
+ points: [],
+ contributions: {
+ pages: [
+ c({ id: 'b', qualifiedId: 'acme.links/b', order: 2 }),
+ c({ id: 'a', qualifiedId: 'acme.links/a', order: 1, icon: 'ui/icon.svg' }),
+ c({ id: 'off', qualifiedId: 'acme.links/off', enabled: false }),
+ c({ id: 'noentry', qualifiedId: 'acme.links/noentry', entry: undefined }),
+ ],
+ settingsSections: [c({ id: 'admin', qualifiedId: 'acme.links/admin', icon: 'icon.svg' })],
+ },
+}
+
+test('pagesOf keeps enabled pages in order, with role defaults', () => {
+ const pages = pagesOf(listing, 'pages')
+ assert.deepEqual(pages.map((p) => p.key), ['plugin:acme.links/a', 'plugin:acme.links/b'])
+ assert.equal(pages[0].mount, 'pages/a')
+ assert.equal(pages[0].minRole, 'viewer')
+ assert.equal(pages[0].icon, 'ui/icon.svg')
+
+ const [section] = pagesOf(listing, 'settingsSections')
+ assert.equal(section.minRole, 'admin')
+ // Only files under ui/ are served, so other icons are dropped.
+ assert.equal(section.icon, undefined)
+ assert.deepEqual(pagesOf(null, 'kbTabs'), [])
+ assert.equal(findPage(pages, 'plugin:acme.links/b')?.id, 'b')
+})
+
+test('pageFileUrl escapes each segment', () => {
+ const page = pagesOf(listing, 'pages')[0]
+ assert.equal(pageFileUrl('/app', page), '/app/api/v1/plugin-ui/assets/acme.links/1.0.0/ui/index.html')
+ assert.equal(pageFileUrl('', page, 'ui/a b.js'), '/api/v1/plugin-ui/assets/acme.links/1.0.0/ui/a%20b.js')
+})
diff --git a/frontend/src/extensions/pluginFrame/pluginPages.ts b/frontend/src/extensions/pluginFrame/pluginPages.ts
new file mode 100644
index 00000000..67aacbe9
--- /dev/null
+++ b/frontend/src/extensions/pluginFrame/pluginPages.ts
@@ -0,0 +1,74 @@
+import type { ContributionListing, ListedContribution, PluginContribution } from '@/api/plugin'
+import type { LocalizedText } from '@/utils/localizedText'
+
+/** The points whose contributions are sandboxed plugin pages. */
+export const PAGE_POINTS = ['pages', 'settingsSections', 'kbTabs'] as const
+export type PagePoint = (typeof PAGE_POINTS)[number]
+
+export type PageRole = NonNullable
+
+/** One plugin page the workspace can show. */
+export interface PluginPage {
+ /** Unique across mounts: "plugin:/". */
+ key: string
+ pluginId: string
+ version: string
+ id: string
+ qualifiedId: string
+ point: PagePoint
+ /** What the page's requests name: "/". */
+ mount: string
+ name: LocalizedText
+ description?: LocalizedText
+ /** Icon file under ui/, if the plugin ships one. */
+ icon?: string
+ entry: string
+ minRole: PageRole
+ order: number
+}
+
+/** The role a page needs when the plugin names none. */
+export function defaultMinRole(point: PagePoint): PageRole {
+ return point === 'settingsSections' ? 'admin' : 'viewer'
+}
+
+function toPage(point: PagePoint, c: ListedContribution): PluginPage | null {
+ if (!c.enabled || !c.entry || !c.version) return null
+ return {
+ key: `plugin:${c.qualifiedId}`,
+ pluginId: c.pluginId,
+ version: c.version,
+ id: c.id,
+ qualifiedId: c.qualifiedId,
+ point,
+ mount: `${point}/${c.id}`,
+ name: c.name,
+ description: c.description,
+ icon: c.icon?.startsWith('ui/') ? c.icon : undefined,
+ entry: c.entry,
+ minRole: c.minRole ?? defaultMinRole(point),
+ order: c.order ?? 0,
+ }
+}
+
+/** The enabled pages of one point, in display order. */
+export function pagesOf(listing: ContributionListing | null | undefined, point: PagePoint): PluginPage[] {
+ const out: PluginPage[] = []
+ for (const c of listing?.contributions?.[point] ?? []) {
+ const page = toPage(point, c)
+ if (page) out.push(page)
+ }
+ return out.sort((a, b) => a.order - b.order || a.qualifiedId.localeCompare(b.qualifiedId))
+}
+
+/** The URL of a file of a plugin's pages (the entry by default). */
+export function pageFileUrl(apiBase: string, page: Pick, file = page.entry) {
+ const seg = (s: string) => encodeURIComponent(s)
+ const path = file.split('/').map(seg).join('/')
+ return `${apiBase}/api/v1/plugin-ui/assets/${seg(page.pluginId)}/${seg(page.version)}/${path}`
+}
+
+/** The page a key names, among pages. */
+export function findPage(pages: readonly PluginPage[], key: string): PluginPage | undefined {
+ return pages.find((p) => p.key === key)
+}
diff --git a/frontend/src/extensions/pluginFrame/settingsSync.ts b/frontend/src/extensions/pluginFrame/settingsSync.ts
new file mode 100644
index 00000000..fb00d93f
--- /dev/null
+++ b/frontend/src/extensions/pluginFrame/settingsSync.ts
@@ -0,0 +1,41 @@
+import { markRaw } from 'vue'
+
+import i18n from '@/i18n'
+import { localizedText } from '@/utils/localizedText'
+
+import { settingsSections } from '../settingsSections'
+import PluginFrame from './PluginFrame.vue'
+import type { PluginPage } from './pluginPages'
+
+const registered = new Map void>()
+
+/**
+ * Makes the settings registry hold exactly these plugin sections: new ones
+ * are registered under the plugins group, ones no longer enabled removed.
+ */
+export function syncPluginSettingsSections(pages: readonly PluginPage[]) {
+ const wanted = new Map(pages.map((p) => [p.key, p]))
+ for (const [key, unregister] of registered) {
+ if (!wanted.has(key)) {
+ unregister()
+ registered.delete(key)
+ }
+ }
+ for (const page of pages) {
+ if (registered.has(page.key)) continue
+ registered.set(
+ page.key,
+ settingsSections.register({
+ key: page.key,
+ group: 'plugins',
+ order: 100 + page.order,
+ label: () => localizedText(page.name, i18n.global.locale.value),
+ icon: { kind: 'tdesign', name: 'app' },
+ component: markRaw(PluginFrame),
+ props: () => ({ page }),
+ pluginId: page.pluginId,
+ access: { minRole: page.minRole },
+ }),
+ )
+ }
+}
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index 56668c1e..10fb12f6 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -2859,6 +2859,11 @@ export default {
rotateFailed: 'Failed to rotate the secret'
}
},
+ pluginPages: {
+ notResponding: 'The plugin page is not responding; it may have failed to load.',
+ requestFailed: 'The plugin request failed',
+ fromPlugin: 'Provided by the plugin {id}'
+ },
pluginCenter: {
installed: 'Installed',
configure: 'Configure',
@@ -2889,7 +2894,10 @@ export default {
tools: 'Agent tools',
parsers: 'Document parsing',
skills: 'Skills',
- mcpServers: 'MCP servers'
+ mcpServers: 'MCP servers',
+ pages: 'Pages',
+ settingsSections: 'Settings sections',
+ kbTabs: 'Knowledge base tabs'
}
},
schemaForm: {
diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts
index eae98ba8..9496f547 100644
--- a/frontend/src/i18n/locales/ja-JP.ts
+++ b/frontend/src/i18n/locales/ja-JP.ts
@@ -2859,6 +2859,11 @@ export default {
rotateFailed: 'シークレットのローテーションに失敗しました'
}
},
+ pluginPages: {
+ notResponding: 'プラグインページが応答しません。読み込みに失敗した可能性があります。',
+ requestFailed: 'プラグインへのリクエストに失敗しました',
+ fromPlugin: 'プラグイン {id} が提供'
+ },
pluginCenter: {
installed: 'インストール済み',
configure: '設定',
@@ -2889,7 +2894,10 @@ export default {
tools: 'エージェントツール',
parsers: 'ドキュメント解析',
skills: 'スキル',
- mcpServers: 'MCP サーバー'
+ mcpServers: 'MCP サーバー',
+ pages: 'ページ',
+ settingsSections: '設定セクション',
+ kbTabs: 'ナレッジベースのタブ'
}
},
schemaForm: {
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index 739b4fa6..5a860d9a 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -5377,6 +5377,11 @@ export default {
rotateFailed: '비밀 키를 교체하지 못했습니다'
}
},
+ pluginPages: {
+ notResponding: '플러그인 페이지가 응답하지 않습니다. 로드에 실패했을 수 있습니다.',
+ requestFailed: '플러그인 요청에 실패했습니다',
+ fromPlugin: '플러그인 {id} 제공'
+ },
pluginCenter: {
installed: '설치됨',
configure: '설정',
@@ -5407,7 +5412,10 @@ export default {
tools: '에이전트 도구',
parsers: '문서 파싱',
skills: '스킬',
- mcpServers: 'MCP 서버'
+ mcpServers: 'MCP 서버',
+ pages: '페이지',
+ settingsSections: '설정 섹션',
+ kbTabs: '지식 베이스 탭'
}
},
schemaForm: {
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index 72956254..1378a979 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -5377,6 +5377,11 @@ export default {
rotateFailed: 'Не удалось сменить секрет'
}
},
+ pluginPages: {
+ notResponding: 'Страница плагина не отвечает; возможно, она не загрузилась.',
+ requestFailed: 'Запрос к плагину не выполнен',
+ fromPlugin: 'Предоставлено плагином {id}'
+ },
pluginCenter: {
installed: 'Установлен',
configure: 'Настроить',
@@ -5407,7 +5412,10 @@ export default {
tools: 'Инструменты агента',
parsers: 'Разбор документов',
skills: 'Навыки',
- mcpServers: 'MCP-серверы'
+ mcpServers: 'MCP-серверы',
+ pages: 'Страницы',
+ settingsSections: 'Разделы настроек',
+ kbTabs: 'Вкладки базы знаний'
}
},
schemaForm: {
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index f8cc9337..c68f18a2 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -5379,6 +5379,11 @@ export default {
rotateFailed: '轮换密钥失败'
}
},
+ pluginPages: {
+ notResponding: '插件页面没有响应,可能加载失败。',
+ requestFailed: '插件请求失败',
+ fromPlugin: '由插件 {id} 提供'
+ },
pluginCenter: {
installed: '已安装',
configure: '配置',
@@ -5409,7 +5414,10 @@ export default {
tools: 'Agent 工具',
parsers: '文档解析',
skills: '技能',
- mcpServers: 'MCP 服务'
+ mcpServers: 'MCP 服务',
+ pages: '页面',
+ settingsSections: '设置页',
+ kbTabs: '知识库页签'
}
},
schemaForm: {
diff --git a/frontend/src/stores/auth.ts b/frontend/src/stores/auth.ts
index 488bd45d..fbb4d396 100644
--- a/frontend/src/stores/auth.ts
+++ b/frontend/src/stores/auth.ts
@@ -11,12 +11,14 @@ import { BUILTIN_QUICK_ANSWER_ID } from '@/api/agent'
import { useChatResourcesStore } from '@/stores/chatResources'
import { useEditorResourcesStore } from '@/stores/editorResources'
import { useOrganizationStore } from '@/stores/organization'
+import { usePluginPagesStore } from '@/stores/pluginPages'
import { createSequencedRefresh } from '@/stores/sequencedRefresh'
/** 登出时丢弃 Pinia 内的空间级资源缓存,避免 SPA 重登复用上一账号数据。 */
function clearSessionResourceCaches() {
useChatResourcesStore().invalidate()
useEditorResourcesStore().invalidate()
+ usePluginPagesStore().invalidate()
useOrganizationStore().clearState()
}
diff --git a/frontend/src/stores/pluginPages.ts b/frontend/src/stores/pluginPages.ts
new file mode 100644
index 00000000..f943b895
--- /dev/null
+++ b/frontend/src/stores/pluginPages.ts
@@ -0,0 +1,55 @@
+import { computed, ref } from 'vue'
+import { defineStore } from 'pinia'
+
+import { listContributions, type ContributionListing } from '@/api/plugin'
+import { useAuthStore } from '@/stores/auth'
+import { pagesOf, type PagePoint, type PluginPage } from '@/extensions/pluginFrame/pluginPages'
+
+import { createCachedResource } from './resourceCache'
+
+/**
+ * The plugin pages of the current workspace (toolbox pages, settings
+ * sections, knowledge base tabs). No TTL: reloaded when the workspace
+ * changes, and invalidated when a plugin is switched on or off.
+ */
+export const usePluginPagesStore = defineStore('pluginPages', () => {
+ const listing = ref(null)
+ const loadedFor = ref(null)
+ const auth = useAuthStore()
+
+ const resource = createCachedResource(
+ async () => (await listContributions()).data,
+ (value) => {
+ listing.value = value
+ },
+ )
+
+ /** Loads the pages for the current workspace, if not loaded yet. */
+ async function ensure(force = false) {
+ const tenant = auth.currentTenantId ?? null
+ if (tenant !== loadedFor.value) {
+ resource.invalidate()
+ listing.value = null
+ loadedFor.value = tenant
+ }
+ if (force || !resource.isLoaded()) await resource.ensure(force)
+ }
+
+ function invalidate() {
+ resource.invalidate()
+ loadedFor.value = null
+ }
+
+ const visible = (point: PagePoint) =>
+ computed(() =>
+ pagesOf(listing.value, point).filter((p) => auth.canAccessAllTenants || auth.hasRole(p.minRole)),
+ )
+
+ return {
+ ensure,
+ invalidate,
+ pages: visible('pages'),
+ settingsSections: visible('settingsSections'),
+ kbTabs: visible('kbTabs'),
+ }
+})
diff --git a/frontend/src/views/knowledge/KnowledgeBase.vue b/frontend/src/views/knowledge/KnowledgeBase.vue
index 15b931f8..15c5d802 100644
--- a/frontend/src/views/knowledge/KnowledgeBase.vue
+++ b/frontend/src/views/knowledge/KnowledgeBase.vue
@@ -81,10 +81,14 @@ import {
type DocumentSortValue,
} from './documentSorting';
import { useI18n } from 'vue-i18n';
+import PluginFrame from '@/extensions/pluginFrame/PluginFrame.vue';
+import { findPage } from '@/extensions/pluginFrame/pluginPages';
+import { usePluginPagesStore } from '@/stores/pluginPages';
+import { localizedText } from '@/utils/localizedText';
import { useMarqueeSelect } from '@/hooks/useMarqueeSelect';
import type { ParserEngineInfo } from '@/api/system';
const route = useRoute();
-const { t } = useI18n();
+const { t, locale } = useI18n();
const kbId = computed(() => (route.params as any).kbId as string || '');
const kbInfo = ref(null);
const uploadSourceRef = ref | null>(null);
@@ -93,9 +97,19 @@ const docListLoading = ref(true);
const isFAQ = computed(() => (kbInfo.value?.type || '') === 'faq');
const isWiki = computed(() => !!kbInfo.value?.indexing_strategy?.wiki_enabled);
const validTabs = ['documents', 'wiki', 'graph', 'gallery'] as const
-type KbTab = typeof validTabs[number]
-const initTab = validTabs.includes(route.query.tab as any) ? (route.query.tab as KbTab) : 'documents'
+// Plugin tabs are keyed "plugin:/".
+type KbTab = typeof validTabs[number] | `plugin:${string}`
+const isPluginTab = (tab: unknown): tab is `plugin:${string}` => typeof tab === 'string' && tab.startsWith('plugin:')
+const initTab: KbTab = validTabs.includes(route.query.tab as any) || isPluginTab(route.query.tab)
+ ? (route.query.tab as KbTab)
+ : 'documents'
const activeKbTab = ref(initTab);
+const pluginPages = usePluginPagesStore()
+const pluginPagesLoaded = ref(false)
+void pluginPages.ensure().catch(() => {}).finally(() => {
+ pluginPagesLoaded.value = true
+})
+const activePluginTab = computed(() => (isPluginTab(activeKbTab.value) ? findPage(pluginPages.kbTabs, activeKbTab.value) : undefined))
// Wiki 状态用于面包屑上的索引中指示。父组件自行拉取,避免依赖 WikiBrowser 挂载状态
// (用户切到"文档" tab 时 WikiBrowser 会卸载,这里仍需持续反映后台索引进度)。
@@ -125,11 +139,19 @@ const kbViewTabs = computed(() => {
)
}
tabs.push({ key: 'gallery', icon: 'image', label: t(`${w}.tabGallery`), tip: t(`${w}.tabGalleryTip`) })
+ for (const page of pluginPages.kbTabs) {
+ const label = localizedText(page.name, locale.value)
+ const tip = page.description ? localizedText(page.description, locale.value) : label
+ tabs.push({ key: page.key as KbTab, icon: 'app', label, tip })
+ }
return tabs
})
-const shownKbTab = computed(() =>
- kbViewTabs.value.some((tab) => tab.key === activeKbTab.value) ? activeKbTab.value : 'documents',
-)
+const shownKbTab = computed(() => {
+ if (kbViewTabs.value.some((tab) => tab.key === activeKbTab.value)) return activeKbTab.value
+ // A plugin tab named in the URL waits for the plugin tabs to load.
+ if (isPluginTab(activeKbTab.value) && !pluginPagesLoaded.value) return activeKbTab.value
+ return 'documents'
+})
const onWikiStatusChange = (payload: { pendingTasks: number; isActive: boolean; pendingIssues: number }) => {
wikiStatus.value = payload
}
@@ -2341,7 +2363,13 @@ const handleKBEditorSuccess = (kbIdValue: string) => {
-
+
+
+
+
{
overflow: hidden;
}
+.plugin-tab-area {
+ flex: 1;
+ min-height: 0;
+ display: flex;
+ padding-top: 12px;
+}
+
// Directory navigation and the document content share the available width.
.knowledge-main {
display: flex;
diff --git a/frontend/src/views/settings/PluginCenter.vue b/frontend/src/views/settings/PluginCenter.vue
index 40685ea7..fd83c0d9 100644
--- a/frontend/src/views/settings/PluginCenter.vue
+++ b/frontend/src/views/settings/PluginCenter.vue
@@ -90,6 +90,7 @@