Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat(integrations): add CLI setup page (#3081)
lyingbug5be8d13fc625
diff --git a/frontend/src/config/integrations.ts b/frontend/src/config/integrations.tsindex 8dc2b3418..bed068b6c 100644--- a/frontend/src/config/integrations.ts+++ b/frontend/src/config/integrations.ts@@ -5,9 +5,9 @@ export const CHROME_EXTENSION_URL =export const CLAWHUB_SKILL_URL = 'https://clawhub.ai/lyingbug/weknora'-export type IntegrationTab = 'im' | 'embed' | 'api' | 'chrome' | 'claw'+export type IntegrationTab = 'im' | 'embed' | 'api' | 'cli' | 'chrome' | 'claw'-export const INTEGRATION_TABS: IntegrationTab[] = ['im', 'embed', 'api', 'chrome', 'claw']+export const INTEGRATION_TABS: IntegrationTab[] = ['im', 'embed', 'api', 'cli', 'chrome', 'claw']/** Aligns with Settings.vue SECTION_MIN_ROLE.api and router.go g.Owner() on /api-principal-config. */export type IntegrationTabRole = 'viewer' | 'contributor' | 'admin' | 'owner'@@ -34,6 +34,7 @@ export const INTEGRATION_PREVIEW_ITEMS: Array<{{ key: 'im', icon: { type: 'icon', name: 'chat-message' } },{ key: 'embed', icon: { type: 'icon', name: 'code' } },{ key: 'api', icon: { type: 'icon', name: 'secured' } },+ { key: 'cli', icon: { type: 'icon', name: 'code' } },{ key: 'chrome', icon: { type: 'icon', name: 'extension' } },{ key: 'claw', icon: { type: 'emoji', value: '🦞' } },]diff --git a/frontend/src/config/settingsRoute.test.ts b/frontend/src/config/settingsRoute.test.tsindex 078d40e1c..5439cf1f1 100644--- a/frontend/src/config/settingsRoute.test.ts+++ b/frontend/src/config/settingsRoute.test.ts@@ -46,11 +46,14 @@ test('every settings nav item writes only section', () => {test('legacy api / integrations / bare-tab query strings normalize to nav keys', () => {assert.equal(normalizeSettingsSection('api'), 'integration-api')assert.equal(normalizeSettingsSection('claw'), 'integration-claw')+ assert.equal(normalizeSettingsSection('cli'), 'integration-cli')+ assert.equal(normalizeSettingsSection('integrations', 'cli'), 'integration-cli')assert.equal(normalizeSettingsSection('integrations', 'embed'), 'integration-embed')assert.equal(normalizeSettingsSection('integrations'), 'integration-im')assert.equal(normalizeSettingsSection('integration-chrome'), 'integration-chrome')assert.equal(normalizeSettingsSection('system-global'), 'system-global')assert.equal(isIntegrationSection('integration-chrome'), true)+ assert.equal(isIntegrationSection('integration-cli'), true)assert.equal(isIntegrationSection('models'), false)assert.equal(isIntegrationSection('integration-unknown'), false)})diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex 6aea42d6b..b80c222fb 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -6269,12 +6269,32 @@ export default {}},integrations: {+ cli: {+ title: 'WeKnora CLI',+ subtitle: 'Manage knowledge bases and documents, search content, and ask questions from your terminal. Connect scripts and AI tools through the CLI or MCP.',+ docs: 'CLI documentation',+ docsHint: 'Installation and complete command reference',+ quickstart: 'Quick start',+ installTitle: 'Install the CLI',+ installDesc: 'Build from source with Git and Go 1.26+. This macOS / Linux example updates PATH for the current terminal only. For regular use, place the binary in a directory on PATH.',+ connectTitle: 'Connect to this server',+ connectDesc: 'Create and activate a profile named weknora, then sign in with your email and password. If that profile already exists, choose another name and update the MCP example to match.',+ verifyTitle: 'Verify the connection',+ verifyDesc: 'Check server and authentication status, then list the knowledge bases your account can access.',+ commandsTitle: 'Common commands',+ commandsDesc: 'Replace KB_ID with a knowledge base ID and adapt the file path, query, and question. Uploaded documents must finish processing before they can be searched.',+ mcpTitle: 'Connect an MCP client',+ mcpDesc: 'After signing in, add this configuration to an MCP client that supports stdio. If the client cannot find weknora, set command to the absolute path of the binary.',+ copy: 'Copy',+ copied: 'Copied',+ },title: 'Publish & Integrations',tabs: {im: 'IM Integration',embed: 'Web Embed',api: 'API Integration',chrome: 'Chrome Extension',+ cli: 'CLI',claw: 'Claw Skill'},api: {diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex 892888e5c..4031d3cc5 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -261,6 +261,25 @@ export default {confirmRemove: '제거 확인'},integrations: {+ cli: {+ title: 'WeKnora CLI',+ subtitle: '터미널에서 지식 베이스와 문서를 관리하고, 콘텐츠를 검색하고, 질문하세요. CLI 또는 MCP로 스크립트와 AI 도구를 연결할 수 있습니다.',+ docs: 'CLI 문서 보기',+ docsHint: '설치 안내 및 전체 명령어 참조',+ quickstart: '빠른 시작',+ installTitle: 'CLI 설치',+ installDesc: 'Git과 Go 1.26+로 소스에서 빌드합니다. 아래 macOS / Linux 예제의 PATH 설정은 현재 터미널에만 적용됩니다. 계속 사용하려면 바이너리를 PATH에 포함된 디렉터리에 배치하세요.',+ connectTitle: '현재 서버에 연결',+ connectDesc: 'weknora 프로필을 생성하고 활성화한 후 이메일과 비밀번호로 로그인하세요. 같은 이름의 프로필이 있다면 다른 이름을 사용하고 MCP 예제의 프로필 이름도 변경하세요.',+ verifyTitle: '연결 확인',+ verifyDesc: '서버 및 인증 상태를 확인하고 현재 계정으로 접근할 수 있는 지식 베이스를 조회합니다.',+ commandsTitle: '주요 명령어',+ commandsDesc: 'KB_ID를 지식 베이스 ID로 바꾸고 파일 경로, 검색어, 질문을 수정하세요. 업로드한 문서는 처리가 완료되어야 검색할 수 있습니다.',+ mcpTitle: 'MCP 클라이언트 연결',+ mcpDesc: '로그인 후 stdio를 지원하는 MCP 클라이언트에 아래 설정을 추가하세요. 클라이언트가 weknora를 찾지 못하면 command를 바이너리의 절대 경로로 변경하세요.',+ copy: '복사',+ copied: '복사됨',+ },title: '게시 및 통합',selectAgentPlaceholder: '에이전트를 선택하세요',selectAgentHint: '먼저 에이전트를 선택하세요',@@ -548,6 +567,7 @@ export default {embed: '웹 임베드',api: 'API 연동',chrome: 'Chrome 확장',+ cli: 'CLI',claw: 'Claw Skill'}},diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex 286ccb521..6481c52be 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -261,6 +261,25 @@ export default {confirmRemove: 'Подтвердить удаление'},integrations: {+ cli: {+ title: 'WeKnora CLI',+ subtitle: 'Управляйте базами знаний и документами, ищите информацию и задавайте вопросы из терминала. Подключайте скрипты и инструменты ИИ через CLI или MCP.',+ docs: 'Документация CLI',+ docsHint: 'Установка и полный справочник команд',+ quickstart: 'Быстрый старт',+ installTitle: 'Установка CLI',+ installDesc: 'Соберите из исходного кода с помощью Git и Go 1.26+. В этом примере для macOS / Linux PATH меняется только для текущего терминала. Для постоянного использования поместите бинарный файл в каталог из PATH.',+ connectTitle: 'Подключение к этому серверу',+ connectDesc: 'Создайте и активируйте профиль weknora, затем войдите с электронной почтой и паролем. Если такой профиль уже существует, выберите другое имя и измените имя профиля в примере MCP.',+ verifyTitle: 'Проверка подключения',+ verifyDesc: 'Проверьте состояние сервера и авторизации, затем выведите базы знаний, доступные вашей учётной записи.',+ commandsTitle: 'Основные команды',+ commandsDesc: 'Замените KB_ID на ID базы знаний и измените путь к файлу, поисковый запрос и вопрос. Загруженные документы доступны для поиска после завершения обработки.',+ mcpTitle: 'Подключение клиента MCP',+ mcpDesc: 'После входа добавьте эту конфигурацию в клиент MCP с поддержкой stdio. Если клиент не находит weknora, укажите в command абсолютный путь к бинарному файлу.',+ copy: 'Копировать',+ copied: 'Скопировано',+ },title: 'Публикация и интеграция',selectAgentPlaceholder: 'Выберите агента',selectAgentHint: 'Сначала выберите агента',@@ -548,6 +567,7 @@ export default {embed: 'Веб-встраивание',api: 'API-интеграция',chrome: 'Расширение Chrome',+ cli: 'CLI',claw: 'Claw Skill'}},diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex 5e10e795f..7242de675 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -261,6 +261,25 @@ export default {confirmRemove: '确认移除'},integrations: {+ cli: {+ title: 'WeKnora CLI',+ subtitle: '在终端中管理知识库和文档、检索内容并发起问答,也可通过脚本或 MCP 接入 AI 工具。',+ docs: '查看 CLI 文档',+ docsHint: '安装说明与完整命令参考',+ quickstart: '快速开始',+ installTitle: '安装 CLI',+ installDesc: '目前支持源码构建,需要 Git 和 Go 1.26+。以下示例适用于 macOS / Linux,PATH 设置仅在当前终端生效;长期使用请将二进制放入 PATH 目录。',+ connectTitle: '连接当前服务',+ connectDesc: '创建并启用名为 weknora 的连接配置,然后使用邮箱和密码登录。如果已有同名配置,请更换名称,并同步修改 MCP 示例中的配置名。',+ verifyTitle: '验证连接',+ verifyDesc: '检查服务与认证状态,并列出当前账号可访问的知识库。',+ commandsTitle: '常用命令',+ commandsDesc: '将 KB_ID 替换为知识库 ID,按需替换文件路径、检索词和问题。上传后的文档需解析完成才能检索。',+ mcpTitle: '接入 MCP 客户端',+ mcpDesc: '完成登录后,将以下配置添加到支持 stdio 的 MCP 客户端。若客户端无法找到 weknora,请将 command 改为二进制的绝对路径。',+ copy: '复制',+ copied: '已复制',+ },title: '发布集成',selectAgentPlaceholder: '请选择智能体',selectAgentHint: '请先选择一个智能体',@@ -548,6 +567,7 @@ export default {embed: '网页嵌入',api: 'API 集成',chrome: 'Chrome 插件',+ cli: 'CLI',claw: 'Claw Skill'}},diff --git a/frontend/src/views/integrations/CliIntegrationLanding.vue b/frontend/src/views/integrations/CliIntegrationLanding.vuenew file mode 100644index 000000000..c94a9a44e--- /dev/null+++ b/frontend/src/views/integrations/CliIntegrationLanding.vue@@ -0,0 +1,108 @@+<template>+ <IntegrationLandingLayout+ :title="$t('integrations.cli.title')"+ :subtitle="$t('integrations.cli.subtitle')"+ >+ <template #actions>+ <IntegrationExternalCta+ :label="$t('integrations.cli.docs')"+ :hint="$t('integrations.cli.docsHint')"+ @click="openDocs"+ >+ <template #icon><t-icon name="code" /></template>+ </IntegrationExternalCta>+ </template>++ <template #main>+ <div class="landing-group">+ <section class="setting-drawer__section">+ <h4 class="setting-drawer__section-title">{{ $t('integrations.cli.quickstart') }}</h4>+ <ol class="landing-steps">+ <li v-for="(step, index) in steps" :key="step.key" class="landing-step">+ <span class="landing-step-num">{{ index + 1 }}</span>+ <div class="landing-step-body">+ <div class="landing-step-title">{{ $t(`integrations.cli.${step.key}Title`) }}</div>+ <p class="landing-step-desc">{{ $t(`integrations.cli.${step.key}Desc`) }}</p>+ <div class="landing-step-embed code-toolbar">+ <pre class="code-toolbar__code">{{ step.command }}</pre>+ <t-button+ class="code-toolbar__copy"+ size="small"+ variant="text"+ shape="square"+ :title="$t('integrations.cli.copy')"+ :aria-label="$t('integrations.cli.copy')"+ @click="copy(step.command)"+ >+ <t-icon name="file-copy" size="16px" />+ </t-button>+ </div>+ </div>+ </li>+ </ol>+ </section>+ </div>+ </template>++ <template #aside>+ <div class="landing-group">+ <section v-for="example in examples" :key="example.key" class="setting-drawer__section">+ <h4 class="setting-drawer__section-title">{{ $t(`integrations.cli.${example.key}Title`) }}</h4>+ <p class="field-desc">{{ $t(`integrations.cli.${example.key}Desc`) }}</p>+ <div class="code-toolbar">+ <pre class="code-toolbar__code">{{ example.command }}</pre>+ <t-button+ class="code-toolbar__copy"+ size="small"+ variant="text"+ shape="square"+ :title="$t('integrations.cli.copy')"+ :aria-label="$t('integrations.cli.copy')"+ @click="copy(example.command)"+ >+ <t-icon name="file-copy" size="16px" />+ </t-button>+ </div>+ </section>+ </div>+ </template>+ </IntegrationLandingLayout>+</template>++<script setup lang="ts">+import { computed } from 'vue'+import { useApiBaseUrlDisplay } from '@/composables/useApiBaseUrlDisplay'+import { copyWithToast } from '@/utils/clipboard'+import IntegrationLandingLayout from './IntegrationLandingLayout.vue'+import IntegrationExternalCta from './IntegrationExternalCta.vue'+import { buildCLIConnectCommand } from './cliIntegration'++const { apiBaseUrlDisplay } = useApiBaseUrlDisplay()+const steps = computed(() => [+ {+ key: 'install',+ command: 'git clone https://github.com/Tencent/WeKnora.git\ncd WeKnora/cli\ngo build -o weknora .\nexport PATH="$PWD:$PATH"',+ },+ { key: 'connect', command: buildCLIConnectCommand(apiBaseUrlDisplay.value, window.location.origin) },+ { key: 'verify', command: 'weknora doctor\nweknora kb list' },+])+const examples = [+ {+ key: 'commands',+ command: 'weknora doc upload ./document.pdf --kb "KB_ID"\nweknora search chunks "query" --kb "KB_ID"\nweknora chat "question" --kb "KB_ID" --format text\nweknora agent list',+ },+ {+ key: 'mcp',+ command: JSON.stringify({+ mcpServers: {+ weknora: { command: 'weknora', args: ['--profile', 'weknora', 'mcp', 'serve'] },+ },+ }, null, 2),+ },+]++const copy = (command: string) => copyWithToast(command, 'integrations.cli.copied')+const openDocs = () => {+ window.open('https://github.com/Tencent/WeKnora/blob/main/cli/README.md', '_blank', 'noopener,noreferrer')+}+</script>diff --git a/frontend/src/views/integrations/IntegrationSettingsSection.vue b/frontend/src/views/integrations/IntegrationSettingsSection.vueindex 017235ae3..629a604e5 100644--- a/frontend/src/views/integrations/IntegrationSettingsSection.vue+++ b/frontend/src/views/integrations/IntegrationSettingsSection.vue@@ -38,6 +38,7 @@<ChromeExtensionLanding v-if="tab === 'chrome'" /><ClawSkillLanding v-if="tab === 'claw'" />+ <CliIntegrationLanding v-if="tab === 'cli'" /></div></div></template>@@ -50,6 +51,7 @@ import AgentEmbedChannelPanel from '@/components/AgentEmbedChannelPanel.vue'import ApiIntegrationSettings from '@/views/integrations/ApiIntegrationSettings.vue'import ChromeExtensionLanding from '@/views/integrations/ChromeExtensionLanding.vue'import ClawSkillLanding from '@/views/integrations/ClawSkillLanding.vue'+import CliIntegrationLanding from '@/views/integrations/CliIntegrationLanding.vue'import type { IntegrationTab } from '@/config/integrations'const filterAgentId = ref('')@@ -61,7 +63,7 @@ const props = defineProps<{const route = useRoute()const isLandingSection = computed(- () => props.tab === 'chrome' || props.tab === 'claw',+ () => props.tab === 'chrome' || props.tab === 'claw' || props.tab === 'cli',)function applyAgentFilterFromRoute() {diff --git a/frontend/src/views/integrations/cliIntegration.test.ts b/frontend/src/views/integrations/cliIntegration.test.tsnew file mode 100644index 000000000..c5f58204c--- /dev/null+++ b/frontend/src/views/integrations/cliIntegration.test.ts@@ -0,0 +1,31 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import { spawnSync } from 'node:child_process'+import { buildCLIConnectCommand } from './cliIntegration'++test('CLI hosts preserve proxy prefixes and omit the SDK API suffix', () => {+ for (const [base, origin, host] of [+ ['https://kb.example.com/api/v1', 'https://ui.example.com', 'https://kb.example.com'],+ ['/app/weknora/api/v1', 'https://kb.example.com', 'https://kb.example.com/app/weknora'],+ ['http://127.0.0.1:19321/api/v1/', 'wails://wails.localhost', 'http://127.0.0.1:19321'],+ ['http://127.0.0.1:19321/api/v1', 'null', 'http://127.0.0.1:19321'],+ ]) {+ const command = buildCLIConnectCommand(base!, origin!)+ assert.ok(command.includes(`--host '${host}' --use &&\nweknora auth login`))+ }+})++test('unresolved desktop URLs use an explicit server placeholder', () => {+ assert.ok(buildCLIConnectCommand('/api/v1', 'null').includes("--host 'https://your-server.com'"))+ assert.ok(buildCLIConnectCommand('/api/v1', 'wails://wails.localhost').includes("--host 'https://your-server.com'"))+})++test('copyable host arguments remain literal in a POSIX shell', () => {+ const host = "https://kb.example.com/team'/$HOME/`printf-injected`/$(printf-injected)"+ const command = buildCLIConnectCommand(`${host}/api/v1`, 'https://kb.example.com')+ const argument = command.split(' --host ')[1]!.split(' --use')[0]!+ const result = spawnSync('/bin/sh', ['-c', `printf '%s' ${argument}`], { encoding: 'utf8' })+ assert.equal(result.status, 0)+ assert.equal(result.stderr, '')+ assert.equal(result.stdout, "https://kb.example.com/team'/$HOME/%60printf-injected%60/$(printf-injected)")+})diff --git a/frontend/src/views/integrations/cliIntegration.ts b/frontend/src/views/integrations/cliIntegration.tsnew file mode 100644index 000000000..2b1aef4e9--- /dev/null+++ b/frontend/src/views/integrations/cliIntegration.ts@@ -0,0 +1,16 @@+/** The CLI appends /api/v1 itself; retain any reverse-proxy path prefix. */+export function buildCLIConnectCommand(apiBaseUrl: string, origin: string): string {+ let host = 'https://your-server.com'+ try {+ const url = new URL(apiBaseUrl, origin && origin !== 'null' ? origin : undefined)+ if (url.protocol === 'https:' || url.protocol === 'http:') {+ const path = url.pathname.replace(/\/+$/, '').replace(/\/api\/v1$/, '')+ host = `${url.origin}${path}`+ }+ } catch {+ // Desktop bindings can still be loading when the page first renders.+ }+ // POSIX shell quoting prevents URL characters from becoming shell syntax.+ const quotedHost = `'${host.replace(/'/g, `'"'"'`)}'`+ return `weknora profile add weknora --host ${quotedHost} --use &&\nweknora auth login`+}diff --git a/frontend/src/views/settings/Settings.vue b/frontend/src/views/settings/Settings.vueindex fabb91f61..e1a86bd01 100644--- a/frontend/src/views/settings/Settings.vue+++ b/frontend/src/views/settings/Settings.vue@@ -427,13 +427,7 @@ const navGroups = computed<NavGroup[]>(() => {{key: 'integrations',label: t('integrations.title'),- items: pickItems([- integrationSectionKey('im'),- integrationSectionKey('embed'),- integrationSectionKey('api'),- integrationSectionKey('chrome'),- integrationSectionKey('claw'),- ]),+ items: pickItems(INTEGRATION_PREVIEW_ITEMS.map((item) => integrationSectionKey(item.key))),},{key: 'data_extensions',diff --git a/frontend/src/views/settings/settingsNavigation.test.ts b/frontend/src/views/settings/settingsNavigation.test.tsnew file mode 100644index 000000000..2e9c04a7e--- /dev/null+++ b/frontend/src/views/settings/settingsNavigation.test.ts@@ -0,0 +1,46 @@+import assert from 'node:assert/strict'+import { readFileSync } from 'node:fs'+import test from 'node:test'+import { runInNewContext } from 'node:vm'+import ts from 'typescript'+import { computed } from 'vue'+import { INTEGRATION_PREVIEW_ITEMS } from '../../config/integrations'+import { integrationSectionKey } from '../../config/settingsRoute'++// Exercise the actual sidebar grouping without mounting the settings panels.+const source = readFileSync(new URL('./Settings.vue', import.meta.url), 'utf8')+const script = source.match(/<script setup lang="ts">([\s\S]*?)<\/script>/)![1]!+const ast = ts.createSourceFile('Settings.ts', script, ts.ScriptTarget.Latest, true)+const grouping = ast.statements.find((statement) =>+ ts.isVariableStatement(statement) && statement.declarationList.declarations.some(+ (declaration) => ts.isIdentifier(declaration.name) && declaration.name.text === 'navGroups',+ ),+)+assert.ok(grouping, 'Settings must define sidebar groups')+const compiled = ts.transpileModule(grouping.getText(ast), {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+}).outputText++function integrationMenu(visibleKeys: string[]): string[] {+ const groups = runInNewContext(`${compiled}\nnavGroups.value`, {+ computed,+ navItems: { value: visibleKeys.map((key) => ({ key })) },+ t: (key: string) => key,+ integrationSectionKey,+ INTEGRATION_PREVIEW_ITEMS,+ }) as Array<{ key: string; items: Array<{ key: string }> }>+ const integrationGroup = groups.find((group) => group.key === 'integrations')+ return Array.from(integrationGroup?.items ?? [], (item) => item.key)+}++const integrationKeys = INTEGRATION_PREVIEW_ITEMS.map((item) => integrationSectionKey(item.key))++test('settings sidebar includes every registered integration, including CLI, in navigation order', () => {+ assert.deepEqual(integrationMenu(['general', ...integrationKeys]), integrationKeys)+})++test('settings sidebar preserves visibility filtering without hiding CLI', () => {+ const visible = integrationKeys.filter((key) => key !== 'integration-api' && key !== 'integration-im')+ assert.deepEqual(integrationMenu(visible), visible)+ assert.deepEqual(integrationMenu(['general']), [])+})