Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 63e9fc5920 | |||
| c64a48647c | |||
| 84f65a809f | |||
| 5d0326f987 | |||
| d283fabc99 | |||
| 50eb48c344 | |||
| 075b16d6ca | |||
| 43839f7830 | |||
| e0b6a71503 | |||
| 014cf4e545 |
+5
-2
@@ -685,10 +685,13 @@ LANGFUSE_HOST=http://langfuse-web:3000
|
||||
#
|
||||
# ===== 向量库地址的 SSRF 校验 =====
|
||||
# 通过 API 创建/测试向量库连接时,地址会经过 SSRF 校验。docker-compose 内置服务
|
||||
# (qdrant, milvus, weaviate, doris-fe, searxng)已通过 SSRF_WHITELIST_EXTRA 默认放行。
|
||||
# (qdrant, milvus, weaviate, doris-fe, doris-be, searxng)已通过 SSRF_WHITELIST_EXTRA 默认放行。
|
||||
# 如使用外部私网地址或被拦截端口(5432, 9200 等),请将主机加入 SSRF_WHITELIST_EXTRA
|
||||
# (注意:自定义该变量会覆盖 compose 默认值,需重新包含内置服务名),例如:
|
||||
# SSRF_WHITELIST_EXTRA=searxng,qdrant,milvus,weaviate,doris-fe,my-opensearch.internal
|
||||
# SSRF_WHITELIST_EXTRA=searxng,qdrant,milvus,weaviate,doris-fe,doris-be,my-opensearch.internal
|
||||
#
|
||||
# Doris Stream Load:FE 会将请求 307 重定向到 BE;docker compose 默认放行
|
||||
# doris-fe 与 doris-be(见 SSRF_WHITELIST_EXTRA)。
|
||||
#
|
||||
# 本地开发(go run + docker-compose.dev.yml --profile opensearch):后端跑在宿主机,
|
||||
# OpenSearch 经 published 端口 http://localhost:9200 访问;通过 API 创建该向量库前,
|
||||
|
||||
@@ -5,3 +5,5 @@
|
||||
# acceptance/contract envelope tests.
|
||||
*.go text eol=lf
|
||||
cli/acceptance/testdata/**/*.json text eol=lf
|
||||
mcp-server/Dockerfile text eol=lf
|
||||
mcp-server/requirements.txt text eol=lf
|
||||
|
||||
@@ -2,6 +2,52 @@
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
## [0.7.1] - 2026-07-24
|
||||
|
||||
### New Features
|
||||
|
||||
- **NEW**: **Yunzhijia (云之家) IM Integration** — a new instant-messaging platform integration for Yunzhijia, including WebSocket message handling, request signing, image-message ingestion with SSRF-checked downloads, and markdown-formatted replies by default. Add the channel under **Settings → IM Integration** and fill in the credentials.
|
||||
- **NEW**: **Volcengine Rerank Provider** — Volcengine is now a first-class rerank provider, with request batching that transparently splits payloads exceeding the API's per-request document limit. vLLM rerankers no longer send `truncate_prompt_tokens` by default for broader compatibility.
|
||||
- **NEW**: **Zhipu AI Web Search Provider** — Zhipu AI added as a configurable web search provider alongside the existing options.
|
||||
- **NEW**: **Platform-Scoped API Keys** — control-plane automation now has dedicated platform API keys with capability-based access to tenant management, system settings, runtime queues, and audit logs, plus an admin UI for key lifecycle and system-wide audit-log viewing (migration `000071_platform_api_keys`).
|
||||
- **NEW**: **Knowledge Base Activity Audit Trail** — a scoped, per-KB activity audit trail records knowledge operations (including FAQ imports) with a dedicated activity settings view and localized audit-log detail drawer (migration `000073_kb_activity_scope`).
|
||||
- **NEW**: **FAQ Management Enhancements** — richer FAQ workflows: entry filtering and tagging, export support, and import result tracking with clearer UI feedback and activity logging.
|
||||
- **NEW**: **Langfuse OTLP/OTel Tracing** — Langfuse tracing migrated from the legacy ingestion batch API to the OpenTelemetry Go SDK emitting OTLP/HTTP (`/api/public/otel/v1/traces`), the Langfuse v3+ standard. Adds W3C `traceparent` cross-service propagation so upstream trace IDs are inherited, and merges finish metadata with auto-exported root spans.
|
||||
- **NEW**: **Chat Header Actions & Markdown Export** — a new chat header with docked state and references-panel support, session header actions, and one-click Markdown export of a conversation. Wiki tool results now surface in the references drawer, and model reasoning renders inline in the agent timeline.
|
||||
- **NEW**: **Prompt-Cache Observability** — prompt-cache hit/usage observability with cache-friendly wiki prompts to improve LLM cost and latency.
|
||||
- **NEW**: **Session Channel Governance** — IM / embed / API-key channel sessions are gated behind admin scope, with a dedicated admin API session bucket, strict owner scoping for API-key sessions, and a stabilized sidebar source filter. Archived queue tasks can now be bulk-purged.
|
||||
|
||||
### Improvements
|
||||
|
||||
- **IMPROVED**: **Removed Neo4j conversation memory** — the Neo4j-based episodic memory pipeline, its API fields, settings UI, and embed toggles were dropped, so chat no longer depends on Neo4j graph storage. This simplifies deployment and reduces the required infrastructure footprint.
|
||||
- **IMPROVED**: **Shared SSRF-safe HTTP transport** — model clients, embedders, the Doris Stream Load client, and datasource connectors now reuse a single SSRF-safe HTTP transport, consolidating outbound-request protection.
|
||||
- **IMPROVED**: **Resilient Feishu large-wiki sync** — Feishu wiki synchronization now retries, resumes streaming, and surfaces failure reasons for large spaces.
|
||||
- **IMPROVED**: **Organization & shared-space UI** — polished organization space UI, share-to-space panels, shared-space settings, and join-preview UI, with disambiguated shared-space terminology and tightened invite search.
|
||||
- **IMPROVED**: **Compose & config alignment** — docker-compose env vars aligned with code defaults (including a Helm GraphRAG fix, #2164), PDF render parallelism follows the CPU-aware code default, and BSD `netcat` compatibility in the dev script (#2205).
|
||||
- **IMPROVED**: **Chat layout** — conversation content area widened from 800px to 960px.
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- **FIXED**: Wiki summary slugs are preserved during citation compaction, and slug integrity is hardened across ingest and agent write paths (with sqlite alias support).
|
||||
- **FIXED**: IM Q&A could not read its session (#session lookup); DingTalk/IM session reads now resolve correctly.
|
||||
- **FIXED**: API keys can no longer be assigned the owner role; scoped keys can access file-serve and ingest-batch routes as intended.
|
||||
- **FIXED**: MCP OAuth token refresh and authorization polling are now coordinated to avoid races (migration `000074_mcp_oauth_refresh_lease`).
|
||||
- **FIXED**: API-key expiry timestamps normalized to UTC (#2137, migration `000072_auth_timestamp_tz`).
|
||||
- **FIXED**: Async knowledge deletion no longer leaves visible/zombie rows (#2192); KB deletion queue cleanup is detached from the request context and dequeues work for deleted knowledge bases.
|
||||
- **FIXED**: Source file download restricted to Editor role and above; shared knowledge base document preview path corrected.
|
||||
- **FIXED**: Hybrid search query text is validated; top-k retrieval ordering stabilized.
|
||||
- **FIXED**: Embedded chunk images copied into the exports namespace; parent/clone chunk image URLs rewritten via a global pass.
|
||||
- **FIXED**: Optimistic organization state corrected after review and detail loads; state synchronized after writes and pending join-request counts refreshed after review.
|
||||
- **FIXED**: Suggested-questions limit parameter honored; model debug upload limit aligned with the global `MAX_FILE_SIZE`.
|
||||
- **FIXED**: Frontend robustness — custom theme tokens kept in production builds, complete TDesign styles loaded, TDesign textarea autosize crash prevented in the org settings popup, and `crypto.randomUUID` fallback for older browsers / HTTP mode.
|
||||
- **FIXED**: nginx base image pinned by digest for old-host compatibility; graph and multimodal processing traces corrected; task-inspector lazy-queue "not found" errors handled.
|
||||
|
||||
### Infrastructure & Build
|
||||
|
||||
- **BUILD**: Migrations `000071_platform_api_keys`, `000072_auth_timestamp_tz`, `000073_kb_activity_scope`, `000074_mcp_oauth_refresh_lease`.
|
||||
- **BUILD**: `tenant_api_keys` table structure updated and legacy migration files removed; Langfuse tracing client replaced by an OTel exporter.
|
||||
- **BUILD**: Swagger / API docs regenerated for platform API keys, activity audit trail, web-search providers, and the removed memory feature.
|
||||
|
||||
## [0.7.0] - 2026-07-17
|
||||
|
||||
### New Features
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
<img src="https://img.shields.io/badge/License-MIT-ffffff?labelColor=d4eaf7&color=2e6cc4" alt="License">
|
||||
</a>
|
||||
<a href="./CHANGELOG.md">
|
||||
<img alt="Version" src="https://img.shields.io/badge/version-0.7.0-2e6cc4?labelColor=d4eaf7">
|
||||
<img alt="Version" src="https://img.shields.io/badge/version-0.7.1-2e6cc4?labelColor=d4eaf7">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
@@ -57,6 +57,7 @@ The framework supports auto-syncing knowledge from Feishu, Notion, and Yuque (mo
|
||||
|
||||
## ✨ Latest Updates
|
||||
|
||||
- **v0.7.1** — New **Yunzhijia (云之家) IM integration** (WebSocket + image messages + markdown replies); **Volcengine rerank** provider (with request batching) and **Zhipu AI web search** provider; **platform-scoped API keys** for control-plane automation (tenant management, system settings, runtime queues, audit logs); **per-KB activity audit trail**; FAQ management enhancements (filtering, tagging, export, import tracking); **Langfuse OTLP/OTel tracing** migration with W3C traceparent propagation; chat header actions with one-click **Markdown export** and wiki tool results in the references drawer; prompt-cache observability; session channel governance (admin-scoped IM/embed/API sessions); resilient Feishu large-wiki sync; and removal of the legacy Neo4j conversation-memory dependency. Plus broad slug-integrity, SSRF-transport, and state-sync hardening. See [`CHANGELOG.md`](./CHANGELOG.md).
|
||||
- **v0.7.0** — Fine-grained **scoped API keys & principal model** (capability-level grants + per-KB restriction + API integration playground); **runtime task-queue observability dashboard & worker-pool governance** (per-stage pools + per-model concurrency governors + failed-task inspection/retry); **multi-instance storage backends** (multiple storage instances per workspace, per-KB binding, default instance); **session-scoped temporary attachments** (async image/doc parsing + combined limits); question & follow-up suggestions; stable resource registry with LLM-context alias compaction; `@Skill / @MCP` mentions with scoped agent runtime; mid-conversation MCP OAuth; QQBot & Lark (Feishu International) IM integration; Redis TLS; Requesty model provider + Keenable web search; tenantless provisioning & gated self-service workspaces; admin password reset; knowledge base duplicate flow; `weknora` CLI v0.10. Plus broad security hardening (SSRF, secret redaction, SQL validation, IDOR). See [`CHANGELOG.md`](./CHANGELOG.md).
|
||||
- **v0.6.3** — Website embed widget & Integrations Center (secure-mode token exchange + rate limits); chat experience overhaul (citation popovers, RAG pipeline progress, streaming markdown); document multi-tag & batch reparse; Wiki folders & hierarchy navigation; RSS data source; MCP OAuth2; EPUB / MHTML parsing; agent model-readiness checks; model test debugger; session source filter; workspace deletion UI. See [`CHANGELOG.md`](./CHANGELOG.md).
|
||||
- **v0.6.2** — Per-upload process configuration with upload-confirm dialog; document reparse with `process_config`; `weknora` CLI v0.9 (bundled Agent Skills, `session stop`, auth/profile harmonization); KB marquee multi-select; HNSW index for 1024-dim pgvector embeddings; chat resources store refactor; Langfuse-only tracing (Jaeger removed). See [`CHANGELOG.md`](./CHANGELOG.md).
|
||||
@@ -137,7 +138,7 @@ Fully modular pipeline from document parsing, vectorization, and retrieval to LL
|
||||
| Embeddings | Ollama / BGE / GTE / Zhipu / OpenAI-compatible APIs |
|
||||
| Vector DBs | PostgreSQL (pgvector) / Elasticsearch / OpenSearch / Milvus / Weaviate / Qdrant / Apache Doris / Tencent VectorDB |
|
||||
| Object Storage | Local / MinIO / AWS S3 / Volcengine TOS / Alibaba Cloud OSS / Kingsoft Cloud KS3 / Huawei Cloud OBS; **multiple storage instances per workspace** with per-KB binding and a default instance |
|
||||
| IM Channels | WeCom / Feishu / Lark (Feishu International) / QQBot / Slack / Telegram / DingTalk / Mattermost / WeChat |
|
||||
| IM Channels | WeCom / Feishu / Lark (Feishu International) / QQBot / Slack / Telegram / DingTalk / Mattermost / WeChat / Yunzhijia |
|
||||
| Website Embed | Publish agents via embed widget with domain allowlists, rate limits, and secure-mode token exchange |
|
||||
| Web Search | DuckDuckGo / Bing / Google / Tavily / Baidu / Ollama / SearXNG / Keenable / Zhipu AI |
|
||||
| API Integration | Scoped API keys (capability-level grants + per-KB restriction + throttled last-used tracking) with an API integration playground; MCP OAuth and embed sessions isolated per principal |
|
||||
|
||||
+3
-2
@@ -28,7 +28,7 @@
|
||||
<img src="https://img.shields.io/badge/License-MIT-ffffff?labelColor=d4eaf7&color=2e6cc4" alt="License">
|
||||
</a>
|
||||
<a href="./CHANGELOG.md">
|
||||
<img alt="版本" src="https://img.shields.io/badge/version-0.7.0-2e6cc4?labelColor=d4eaf7">
|
||||
<img alt="版本" src="https://img.shields.io/badge/version-0.7.1-2e6cc4?labelColor=d4eaf7">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
@@ -56,6 +56,7 @@
|
||||
|
||||
## ✨ 最新更新
|
||||
|
||||
- **v0.7.1** —— 新增**云之家 IM 集成**(WebSocket + 图片消息 + Markdown 回复);**火山引擎 Rerank** 供应商(自动分批请求)与**智谱 AI 网络搜索**供应商;**平台级 API Key**,用于控制面自动化(租户管理、系统设置、运行时队列、审计日志);**按知识库的活动审计追踪**;FAQ 管理增强(筛选、打标签、导出、导入结果追踪);**Langfuse OTLP/OTel 追踪**迁移,支持 W3C traceparent 跨服务传播;对话头部操作栏,支持一键 **Markdown 导出**,并在引用抽屉中展示 Wiki 工具结果;Prompt 缓存可观测性;会话渠道治理(IM/嵌入/API 会话按管理员范围隔离);飞书大型 Wiki 同步韧性增强;移除旧版 Neo4j 会话记忆依赖。另有大范围的 slug 完整性、SSRF 传输与状态同步加固。详见 [`CHANGELOG.md`](./CHANGELOG.md)。
|
||||
- **v0.7.0** —— 细粒度**权限范围 API Key 与 Principal 模型**(能力级授权 + 按 KB 限制 + API 集成调试台);**运行时任务队列可观测面板与 Worker 池治理**(分阶段独立池 + 按模型并发治理 + 失败任务排查/重试);**多实例存储后端**(每空间多存储实例、按 KB 绑定、默认实例);**会话级临时附件**(图片/文档异步解析 + 合并限额);推荐问题与追问;稳定资源注册表与 LLM 上下文别名压缩;`@Skill / @MCP` 提及范围化 Agent 运行时;会话内 MCP OAuth 授权;QQBot 与 Lark(飞书国际版)IM 集成;Redis TLS;Requesty 模型厂商 + Keenable 网络搜索;无租户预置与受控自助创建工作区;管理员密码重置;知识库复制流程;`weknora` CLI v0.10。同时完成大范围安全加固(SSRF、密钥脱敏、SQL 校验、越权)。详见 [`CHANGELOG.md`](./CHANGELOG.md)。
|
||||
- **v0.6.3** —— 网站嵌入 Widget 与发布集成中心(安全模式 Token 交换 + 限流);对话体验全面革新(引用浮层、RAG 流水线进度、流式 Markdown);文档多标签与批量重新解析;Wiki 文件夹与层级导航;RSS 数据源;MCP OAuth2;EPUB / MHTML 解析;Agent 模型就绪校验;模型调试器;会话来源筛选;工作区删除 UI。详见 [`CHANGELOG.md`](./CHANGELOG.md)。
|
||||
- **v0.6.2** —— 按批次解析配置(`process_config`)+ 上传确认对话框;文档重新解析(reparse)支持覆盖配置;`weknora` CLI v0.9(内置 Agent Skills、`session stop`、auth/profile 统一);知识库框选多选;pgvector 1024 维 HNSW 索引;对话资源 Store 重构;仅保留 Langfuse 追踪(移除 Jaeger)。详见 [`CHANGELOG.md`](./CHANGELOG.md)。
|
||||
@@ -136,7 +137,7 @@
|
||||
| 向量数据库 | PostgreSQL (pgvector) / Elasticsearch / OpenSearch / Milvus / Weaviate / Qdrant / Apache Doris / 腾讯云 VectorDB |
|
||||
| Embedding | Ollama / BGE / GTE / 智谱 / OpenAI 兼容接口 |
|
||||
| 对象存储 | 本地 / 腾讯云COS / 火山引擎 TOS / MinIO / AWS S3 / 阿里云 OSS / 金山云 KS3 / 华为云 OBS;支持**每空间多实例存储后端**,不同知识库可绑定不同实例并设置默认实例 |
|
||||
| IM 集成 | 企业微信 / 飞书 / Lark(飞书国际版)/ QQBot / Slack / Telegram / 钉钉 / Mattermost / 微信 |
|
||||
| IM 集成 | 企业微信 / 飞书 / Lark(飞书国际版)/ QQBot / Slack / Telegram / 钉钉 / Mattermost / 微信 / 云之家 |
|
||||
| 网站嵌入 | 通过嵌入 Widget 发布智能体,支持域名白名单、限流与安全模式 Token 交换 |
|
||||
| 网络搜索 | DuckDuckGo / Bing / Google / Tavily / Baidu / Ollama / SearXNG / Keenable / 智谱 AI |
|
||||
| API 集成 | 权限范围 API Key(能力级授权 + 按 KB 限制 + 节流的 last_used 追踪)与 API 集成调试台;MCP OAuth 与嵌入会话按 Principal 隔离 |
|
||||
|
||||
+3
-2
@@ -28,7 +28,7 @@
|
||||
<img src="https://img.shields.io/badge/License-MIT-ffffff?labelColor=d4eaf7&color=2e6cc4" alt="License">
|
||||
</a>
|
||||
<a href="./CHANGELOG.md">
|
||||
<img alt="バージョン" src="https://img.shields.io/badge/version-0.7.0-2e6cc4?labelColor=d4eaf7">
|
||||
<img alt="バージョン" src="https://img.shields.io/badge/version-0.7.1-2e6cc4?labelColor=d4eaf7">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
@@ -56,6 +56,7 @@ Feishu、Notion、Yuqueなどの外部プラットフォームからのナレッ
|
||||
|
||||
## ✨ 最新アップデート
|
||||
|
||||
- **v0.7.1** — 新しい**Yunzhijia(云之家)IM 連携**(WebSocket + 画像メッセージ + Markdown 返信);**Volcengine Rerank** プロバイダー(リクエストの自動分割)と **Zhipu AI Web 検索**プロバイダー;コントロールプレーン自動化向けの**プラットフォームスコープ API キー**(テナント管理、システム設定、ランタイムキュー、監査ログ);**KB 単位のアクティビティ監査証跡**;FAQ 管理の強化(フィルタリング、タグ付け、エクスポート、インポート結果追跡);**Langfuse OTLP/OTel トレーシング**への移行と W3C traceparent 伝播;チャットヘッダーアクションによるワンクリック **Markdown エクスポート**、参照ドロワーへの Wiki ツール結果表示;プロンプトキャッシュ可観測性;セッションチャネルガバナンス(IM/埋め込み/API セッションを管理者スコープで分離);Feishu 大規模 Wiki 同期の堅牢化;レガシー Neo4j 会話メモリ依存の削除。加えて広範な slug 整合性・SSRF トランスポート・状態同期の強化。詳細は [`CHANGELOG.md`](./CHANGELOG.md)。
|
||||
- **v0.7.0** — きめ細かい**スコープ付き API キーと Principal モデル**(能力単位の付与 + KB 単位の制限 + API 連携プレイグラウンド);**ランタイムタスクキュー可観測ダッシュボードと Worker プール統治**(ステージ別プール + モデル別並行度ガバナー + 失敗タスクの調査/再試行);**マルチインスタンスストレージバックエンド**(ワークスペースごとに複数のストレージインスタンス、KB 単位のバインド、デフォルトインスタンス);**セッションスコープの一時添付**(画像/ドキュメントの非同期解析 + 合算上限);推奨質問とフォローアップ;安定リソースレジストリと LLM コンテキストのエイリアス圧縮;`@Skill / @MCP` メンションによるスコープ化 Agent ランタイム;会話中の MCP OAuth;QQBot と Lark(Feishu 国際版)IM 連携;Redis TLS;Requesty モデルプロバイダー + Keenable Web 検索;テナントレスプロビジョニングと制御されたセルフサービスワークスペース;管理者パスワードリセット;ナレッジベース複製フロー;`weknora` CLI v0.10。加えて大規模なセキュリティ強化(SSRF、シークレットのマスキング、SQL 検証、IDOR)。詳細は [`CHANGELOG.md`](./CHANGELOG.md)。
|
||||
- **v0.6.3** — ウェブサイト埋め込み Widget と統合センター(セキュアモード Token 交換 + レート制限);チャット体験の全面刷新(引用ポップオーバー、RAG パイプライン進捗、ストリーミング Markdown);ドキュメント複数タグと一括 reparse;Wiki フォルダーと階層ナビゲーション;RSS データソース;MCP OAuth2;EPUB / MHTML 解析;Agent モデル準備状態チェック;モデルデバッガー;セッションソースフィルター;ワークスペース削除 UI。詳細は [`CHANGELOG.md`](./CHANGELOG.md)。
|
||||
- **v0.6.2** — アップロード単位の解析設定(`process_config`)+ アップロード確認ダイアログ;reparse 時の設定上書き;`weknora` CLI v0.9(同梱 Agent Skills、`session stop`、auth/profile 統合);KB マーキー複数選択;pgvector 1024 次元 HNSW インデックス;チャットリソース Store 刷新;Langfuse のみのトレーシング(Jaeger 削除)。詳細は [`CHANGELOG.md`](./CHANGELOG.md)。
|
||||
@@ -137,7 +138,7 @@ Feishu、Notion、Yuqueなどの外部プラットフォームからのナレッ
|
||||
| Embedding | Ollama / BGE / GTE / OpenAI 互換 API |
|
||||
| ベクトル DB | PostgreSQL (pgvector) / Elasticsearch / OpenSearch / Milvus / Weaviate / Qdrant / Apache Doris / Tencent VectorDB |
|
||||
| オブジェクトストレージ | ローカル / MinIO / AWS S3 / 火山引擎 TOS / Alibaba Cloud OSS / 金山雲 KS3 / 華為雲 OBS;**ワークスペースごとに複数のストレージインスタンス**、KB 単位のバインドとデフォルトインスタンス |
|
||||
| IM 統合 | WeChat Work / Feishu / Lark(Feishu 国際版)/ QQBot / Slack / Telegram / DingTalk / Mattermost / WeChat |
|
||||
| IM 統合 | WeChat Work / Feishu / Lark(Feishu 国際版)/ QQBot / Slack / Telegram / DingTalk / Mattermost / WeChat / Yunzhijia |
|
||||
| ウェブ埋め込み | 埋め込み Widget でエージェントを公開、ドメイン許可リスト・レート制限・セキュアモード Token 交換 |
|
||||
| Web 検索 | DuckDuckGo / Bing / Google / Tavily / Baidu / Ollama / SearXNG / Keenable / Zhipu AI |
|
||||
| API 連携 | スコープ付き API キー(能力単位の付与 + KB 単位の制限 + 節流付き last_used 追跡)と API 連携プレイグラウンド;MCP OAuth と埋め込みセッションを Principal 単位で分離 |
|
||||
|
||||
+3
-2
@@ -28,7 +28,7 @@
|
||||
<img src="https://img.shields.io/badge/License-MIT-ffffff?labelColor=d4eaf7&color=2e6cc4" alt="License">
|
||||
</a>
|
||||
<a href="./CHANGELOG.md">
|
||||
<img alt="버전" src="https://img.shields.io/badge/version-0.7.0-2e6cc4?labelColor=d4eaf7">
|
||||
<img alt="버전" src="https://img.shields.io/badge/version-0.7.1-2e6cc4?labelColor=d4eaf7">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
@@ -56,6 +56,7 @@ Feishu, Notion, Yuque 등 외부 플랫폼에서 지식 자동 동기화를 지
|
||||
|
||||
## ✨ 최신 업데이트
|
||||
|
||||
- **v0.7.1** — 새로운 **Yunzhijia(云之家) IM 통합**(WebSocket + 이미지 메시지 + Markdown 응답); **Volcengine Rerank** 제공자(요청 자동 분할)와 **Zhipu AI 웹 검색** 제공자; 컨트롤 플레인 자동화를 위한 **플랫폼 범위 API 키**(테넌트 관리, 시스템 설정, 런타임 큐, 감사 로그); **KB 단위 활동 감사 추적**; FAQ 관리 강화(필터링, 태깅, 내보내기, 가져오기 결과 추적); **Langfuse OTLP/OTel 트레이싱** 마이그레이션 및 W3C traceparent 전파; 채팅 헤더 액션을 통한 원클릭 **Markdown 내보내기** 및 참조 드로어의 Wiki 도구 결과 표시; 프롬프트 캐시 가시성; 세션 채널 거버넌스(IM/임베드/API 세션을 관리자 범위로 분리); Feishu 대규모 Wiki 동기화 견고화; 레거시 Neo4j 대화 메모리 의존성 제거. 또한 광범위한 slug 무결성, SSRF 전송, 상태 동기화 강화. 자세한 내용은 [`CHANGELOG.md`](./CHANGELOG.md).
|
||||
- **v0.7.0** — 세분화된 **범위 지정 API 키 및 Principal 모델**(능력 단위 권한 + KB 단위 제한 + API 통합 플레이그라운드); **런타임 작업 큐 가시성 대시보드 및 Worker 풀 거버넌스**(단계별 풀 + 모델별 동시성 거버너 + 실패 작업 조사/재시도); **다중 인스턴스 스토리지 백엔드**(워크스페이스당 여러 스토리지 인스턴스, KB 단위 바인딩, 기본 인스턴스); **세션 범위 임시 첨부**(이미지/문서 비동기 파싱 + 통합 한도); 추천 질문 및 후속 질문; 안정적인 리소스 레지스트리 및 LLM 컨텍스트 별칭 압축; `@Skill / @MCP` 멘션 기반 범위 지정 Agent 런타임; 대화 중 MCP OAuth; QQBot 및 Lark(Feishu 국제판) IM 통합; Redis TLS; Requesty 모델 제공자 + Keenable 웹 검색; 테넌트리스 프로비저닝 및 제어된 셀프서비스 워크스페이스; 관리자 비밀번호 재설정; 지식 베이스 복제 플로우; `weknora` CLI v0.10. 또한 대규모 보안 강화(SSRF, 비밀 마스킹, SQL 검증, IDOR). 자세한 내용은 [`CHANGELOG.md`](./CHANGELOG.md).
|
||||
- **v0.6.3** — 웹사이트 임베드 Widget 및 통합 센터(보안 모드 Token 교환 + 속도 제한); 채팅 경험 전면 개편(인용 팝오버, RAG 파이프라인 진행, 스트리밍 Markdown); 문서 다중 태그 및 일괄 reparse; Wiki 폴더 및 계층 탐색; RSS 데이터 소스; MCP OAuth2; EPUB / MHTML 파싱; Agent 모델 준비 상태 검사; 모델 디버거; 세션 소스 필터; 워크스페이스 삭제 UI. 자세한 내용은 [`CHANGELOG.md`](./CHANGELOG.md).
|
||||
- **v0.6.2** — 업로드 단위 파싱 설정(`process_config`) + 업로드 확인 대화상자; reparse 시 설정 덮어쓰기; `weknora` CLI v0.9(번들 Agent Skills, `session stop`, auth/profile 통합); KB 마키 선택 다중 선택; pgvector 1024차원 HNSW 인덱스; 채팅 리소스 Store 리팩터; Langfuse 단일 추적(Jaeger 제거). 자세한 내용은 [`CHANGELOG.md`](./CHANGELOG.md).
|
||||
@@ -146,7 +147,7 @@ Feishu, Notion, Yuque 등 외부 플랫폼에서 지식 자동 동기화를 지
|
||||
| Embedding | Ollama / BGE / GTE / OpenAI 호환 API |
|
||||
| 벡터 DB | PostgreSQL (pgvector) / Elasticsearch / OpenSearch / Milvus / Weaviate / Qdrant / Apache Doris / Tencent VectorDB |
|
||||
| 오브젝트 스토리지 | 로컬 / MinIO / AWS S3 / Volcengine TOS / Alibaba Cloud OSS / Kingsoft Cloud KS3 / Huawei Cloud OBS; **워크스페이스당 여러 스토리지 인스턴스**, KB 단위 바인딩 및 기본 인스턴스 |
|
||||
| IM 통합 | WeChat Work / Feishu / Lark(Feishu 국제판) / QQBot / Slack / Telegram / DingTalk / Mattermost / WeChat |
|
||||
| IM 통합 | WeChat Work / Feishu / Lark(Feishu 국제판) / QQBot / Slack / Telegram / DingTalk / Mattermost / WeChat / Yunzhijia |
|
||||
| 웹사이트 임베드 | 임베드 Widget으로 에이전트 게시, 도메인 허용 목록·속도 제한·보안 모드 Token 교환 |
|
||||
| 웹 검색 | DuckDuckGo / Bing / Google / Tavily / Baidu / Ollama / SearXNG / Keenable / Zhipu AI |
|
||||
| API 통합 | 범위 지정 API 키(능력 단위 권한 + KB 단위 제한 + 스로틀링된 last_used 추적)와 API 통합 플레이그라운드; MCP OAuth 및 임베드 세션을 Principal 단위로 격리 |
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
# Copy to .env and replace every REQUIRED value before deployment.
|
||||
COMPOSE_PROJECT_NAME=weknora-v071
|
||||
APP_BIND_IP=127.0.0.1
|
||||
APP_PORT=8080
|
||||
FRONTEND_BIND_IP=127.0.0.1
|
||||
FRONTEND_PORT=8088
|
||||
MCP_BIND_IP=127.0.0.1
|
||||
MCP_PORT=18082
|
||||
|
||||
# RDS PostgreSQL 17 (private VPC)
|
||||
DB_HOST=REQUIRED_RDS_PRIVATE_HOST
|
||||
DB_PORT=5432
|
||||
DB_USER=REQUIRED_DB_USER
|
||||
DB_PASSWORD=REQUIRED_DB_PASSWORD
|
||||
DB_NAME=REQUIRED_DB_NAME
|
||||
|
||||
# Self-managed or Alibaba Cloud Elasticsearch 8.x
|
||||
ELASTICSEARCH_ADDR=REQUIRED_ELASTICSEARCH_URL
|
||||
ELASTICSEARCH_USERNAME=
|
||||
ELASTICSEARCH_PASSWORD=
|
||||
ELASTICSEARCH_INDEX=weknora_chunks
|
||||
|
||||
# Self-managed Redis/Tair
|
||||
REDIS_ADDR=REQUIRED_REDIS_HOST_PORT
|
||||
REDIS_USERNAME=
|
||||
REDIS_PASSWORD=REQUIRED_REDIS_PASSWORD
|
||||
REDIS_DB=0
|
||||
REDIS_PREFIX=weknora
|
||||
WEKNORA_REDIS_NAMESPACE=REQUIRED_ENV_NAMESPACE
|
||||
REDIS_USE_TLS=false
|
||||
REDIS_TLS_SERVER_NAME=
|
||||
REDIS_TLS_INSECURE_SKIP_VERIFY=false
|
||||
|
||||
# Private Alibaba Cloud OSS
|
||||
OSS_ENDPOINT=REQUIRED_OSS_ENDPOINT
|
||||
OSS_REGION=REQUIRED_OSS_REGION
|
||||
OSS_ACCESS_KEY=REQUIRED_OSS_ACCESS_KEY
|
||||
OSS_SECRET_KEY=REQUIRED_OSS_SECRET_KEY
|
||||
OSS_BUCKET_NAME=REQUIRED_PRIVATE_BUCKET
|
||||
OSS_PATH_PREFIX=weknora/
|
||||
OSS_TEMP_BUCKET_NAME=
|
||||
OSS_TEMP_REGION=
|
||||
|
||||
# These values must be generated and stored only on the server.
|
||||
SYSTEM_AES_KEY=REQUIRED_EXACTLY_32_BYTES
|
||||
JWT_SECRET=REQUIRED_RANDOM_SECRET
|
||||
WEKNORA_API_KEY=REQUIRED_AFTER_BOOTSTRAP
|
||||
MCP_SERVER_AUTH_TOKEN=REQUIRED_RANDOM_SECRET
|
||||
|
||||
# Optional integrations
|
||||
NEO4J_ENABLE=false
|
||||
NEO4J_URI=
|
||||
NEO4J_USERNAME=
|
||||
NEO4J_PASSWORD=
|
||||
OLLAMA_BASE_URL=http://host.docker.internal:11434
|
||||
LANGFUSE_ENABLED=false
|
||||
LANGFUSE_HOST=
|
||||
LANGFUSE_PUBLIC_KEY=
|
||||
LANGFUSE_SECRET_KEY=
|
||||
|
||||
# Exact trusted hostnames only; never whitelist a whole private/Fake-IP CIDR.
|
||||
SSRF_WHITELIST_EXTRA=host.docker.internal
|
||||
|
||||
# Runtime tuning matching the current low-concurrency baseline.
|
||||
MAX_FILE_SIZE_MB=100
|
||||
WEKNORA_ASYNQ_CORE_CONCURRENCY=4
|
||||
WEKNORA_ASYNQ_POSTPROCESS_CONCURRENCY=1
|
||||
WEKNORA_ASYNQ_ENRICHMENT_CONCURRENCY=4
|
||||
WEKNORA_WIKI_ASYNQ_CONCURRENCY=2
|
||||
CONCURRENCY_POOL_SIZE=4
|
||||
@@ -0,0 +1,18 @@
|
||||
# Runtime secrets and generated state
|
||||
.env
|
||||
*.env
|
||||
!.env.example
|
||||
secrets/
|
||||
credentials/
|
||||
|
||||
# Persistent data and backups
|
||||
data/
|
||||
backups/
|
||||
volumes/
|
||||
exports/
|
||||
|
||||
# Logs, caches, and generated evidence
|
||||
logs/
|
||||
*.log
|
||||
__pycache__/
|
||||
*.pyc
|
||||
@@ -0,0 +1,63 @@
|
||||
# 当前服务器 WeKnora v0.7.1 发布包
|
||||
|
||||
本目录固化 2026-08-26 正在运行的 WeKnora 核心版本,并提供迁移到新服务器时使用的无密钥部署模板。
|
||||
|
||||
## 版本身份
|
||||
|
||||
- WeKnora 源码:`c64a48647cd6f7eb8b0fb020b2e8fec74ee375fb`
|
||||
- 上游标签:`v0.7.1`
|
||||
- App 镜像:`wechatopenai/weknora-app:v0.7.1@sha256:d88bef9912f6abb8bc7c22144ee7f314016055b8075bda4ea8fbb28af41c3bcf`
|
||||
- UI 镜像:`wechatopenai/weknora-ui:v0.7.1@sha256:169678d4ba4c1f127b36c5f58a6ad567bd745d48488d693e4d3eb4117689c730`
|
||||
- DocReader 镜像:`wechatopenai/weknora-docreader:v0.7.1@sha256:262bab1a4b12f24dd99958e32868ffc2d2cb09270465a88820420ac378c0e149`
|
||||
- 当前 App 二进制 SHA-256:`aa6c6223f9980ef08120e65cdc091996b1eadbc828c69540e7e6b9cdc24bbca3`
|
||||
|
||||
`runtime-manifest.json` 保存运行容器、镜像内容 ID 和源码修订的脱敏取证结果。当前 App 容器的 OCI revision 与源码 Commit 一致。
|
||||
|
||||
## 与上游 v0.7.1 的唯一代码差异
|
||||
|
||||
当前 MCP 镜像需要 MCP Python SDK 1.x,因此本分支保留两处运行修复:
|
||||
|
||||
1. `mcp-server/requirements.txt` 将依赖固定为 `mcp>=1.0.0,<2.0.0`;
|
||||
2. `mcp-server/Dockerfile` 在构建期验证 `Server.list_tools()` 契约。
|
||||
|
||||
WeKnora App、UI、DocReader本身使用上述官方不可变镜像,没有把钉钉专用分支混入当前运行版本。
|
||||
|
||||
## 文件用途
|
||||
|
||||
- `compose.managed-data-plane.yaml`:新阿里云服务器部署核心服务的模板;RDS PostgreSQL、Elasticsearch、Redis和私有OSS从环境变量接入。
|
||||
- `.env.example`:只包含变量名和非敏感默认值;复制为`.env`后填写真实值。
|
||||
- `runtime-manifest.json`:当前服务器运行版本取证,不用于保存运行数据。
|
||||
|
||||
静态检查:
|
||||
|
||||
```bash
|
||||
cp deploy/server-running-v0.7.1/.env.example deploy/server-running-v0.7.1/.env
|
||||
# 填写所有 REQUIRED 值后:
|
||||
docker compose \
|
||||
--env-file deploy/server-running-v0.7.1/.env \
|
||||
-f deploy/server-running-v0.7.1/compose.managed-data-plane.yaml \
|
||||
config --quiet
|
||||
```
|
||||
|
||||
`.env`受Git忽略。生产密钥必须由服务器上的`0600`文件或云Secret管理注入。
|
||||
|
||||
## 不进入 Gitea 的内容
|
||||
|
||||
- 当前服务器`.env`和所有API Key、Token、密码、`SYSTEM_AES_KEY`;
|
||||
- PostgreSQL、Redis、Elasticsearch、Neo4j、ClickHouse数据卷;
|
||||
- OSS对象、上传文档、`/data/files`、日志、缓存和验收中的业务数据;
|
||||
- 已构建的DobotAI二进制;
|
||||
- 旧的本地API Adapter目录。Adapter和DobotAI必须使用各自独立仓库及固定Commit部署。
|
||||
|
||||
## 新服务器迁移边界
|
||||
|
||||
此分支固化了“代码和部署契约”,不等于已经迁移数据。迁移时还必须单独完成:
|
||||
|
||||
1. PostgreSQL原生逻辑备份和隔离恢复验证;
|
||||
2. OSS对象清单、大小和SHA-256核对;
|
||||
3. Elasticsearch索引重建或受控迁移;
|
||||
4. 保管并恢复原`SYSTEM_AES_KEY`,否则数据库内模型凭据无法解密;
|
||||
5. 健康、文档解析、混合检索、引用、图片、Agent和Adapter端到端验收;
|
||||
6. 回滚副本验证。
|
||||
|
||||
v0.7.1 PostgreSQL连接当前使用`sslmode=disable`。接入阿里云RDS时必须走私有VPC;若目标强制TLS,需要先改造并验证连接配置,不能直接上线。
|
||||
@@ -0,0 +1,148 @@
|
||||
name: ${COMPOSE_PROJECT_NAME:-weknora-v071}
|
||||
|
||||
services:
|
||||
docreader:
|
||||
image: wechatopenai/weknora-docreader:v0.7.1@sha256:262bab1a4b12f24dd99958e32868ffc2d2cb09270465a88820420ac378c0e149
|
||||
environment:
|
||||
TZ: Asia/Shanghai
|
||||
LOG_LEVEL: INFO
|
||||
DOCREADER_IMAGE_OUTPUT_DIR: /tmp/docreader
|
||||
DOCREADER_GRPC_PORT: 50051
|
||||
DOCREADER_GRPC_MAX_WORKERS: 2
|
||||
DOCREADER_MARKITDOWN_MAX_WORKERS: 1
|
||||
DOCREADER_PDF_RENDER_MAX_WORKERS: 1
|
||||
volumes:
|
||||
- docreader_tmp:/tmp/docreader
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import socket;s=socket.create_connection(('127.0.0.1',50051),5);s.close()"]
|
||||
interval: 10s
|
||||
timeout: 10s
|
||||
retries: 20
|
||||
start_period: 30s
|
||||
restart: unless-stopped
|
||||
networks: [weknora]
|
||||
|
||||
app:
|
||||
image: wechatopenai/weknora-app:v0.7.1@sha256:d88bef9912f6abb8bc7c22144ee7f314016055b8075bda4ea8fbb28af41c3bcf
|
||||
depends_on:
|
||||
docreader:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
GIN_MODE: release
|
||||
TZ: Asia/Shanghai
|
||||
AUTO_MIGRATE: "true"
|
||||
AUTO_RECOVER_DIRTY: "true"
|
||||
DISABLE_REGISTRATION: "true"
|
||||
DB_DRIVER: postgres
|
||||
DB_HOST: ${DB_HOST:?DB_HOST is required}
|
||||
DB_PORT: ${DB_PORT:-5432}
|
||||
DB_USER: ${DB_USER:?DB_USER is required}
|
||||
DB_PASSWORD: ${DB_PASSWORD:?DB_PASSWORD is required}
|
||||
DB_NAME: ${DB_NAME:?DB_NAME is required}
|
||||
RETRIEVE_DRIVER: elasticsearch_v8
|
||||
ELASTICSEARCH_ADDR: ${ELASTICSEARCH_ADDR:?ELASTICSEARCH_ADDR is required}
|
||||
ELASTICSEARCH_USERNAME: ${ELASTICSEARCH_USERNAME:-}
|
||||
ELASTICSEARCH_PASSWORD: ${ELASTICSEARCH_PASSWORD:-}
|
||||
ELASTICSEARCH_INDEX: ${ELASTICSEARCH_INDEX:-weknora_chunks}
|
||||
STREAM_MANAGER_TYPE: redis
|
||||
REDIS_ADDR: ${REDIS_ADDR:?REDIS_ADDR is required}
|
||||
REDIS_USERNAME: ${REDIS_USERNAME:-}
|
||||
REDIS_PASSWORD: ${REDIS_PASSWORD:?REDIS_PASSWORD is required}
|
||||
REDIS_DB: ${REDIS_DB:-0}
|
||||
REDIS_PREFIX: ${REDIS_PREFIX:-weknora}
|
||||
WEKNORA_REDIS_NAMESPACE: ${WEKNORA_REDIS_NAMESPACE:?WEKNORA_REDIS_NAMESPACE is required}
|
||||
REDIS_USE_TLS: ${REDIS_USE_TLS:-false}
|
||||
REDIS_TLS_SERVER_NAME: ${REDIS_TLS_SERVER_NAME:-}
|
||||
REDIS_TLS_INSECURE_SKIP_VERIFY: ${REDIS_TLS_INSECURE_SKIP_VERIFY:-false}
|
||||
STORAGE_TYPE: oss
|
||||
OSS_ENDPOINT: ${OSS_ENDPOINT:?OSS_ENDPOINT is required}
|
||||
OSS_REGION: ${OSS_REGION:?OSS_REGION is required}
|
||||
OSS_ACCESS_KEY: ${OSS_ACCESS_KEY:?OSS_ACCESS_KEY is required}
|
||||
OSS_SECRET_KEY: ${OSS_SECRET_KEY:?OSS_SECRET_KEY is required}
|
||||
OSS_BUCKET_NAME: ${OSS_BUCKET_NAME:?OSS_BUCKET_NAME is required}
|
||||
OSS_PATH_PREFIX: ${OSS_PATH_PREFIX:-weknora/}
|
||||
OSS_TEMP_BUCKET_NAME: ${OSS_TEMP_BUCKET_NAME:-}
|
||||
OSS_TEMP_REGION: ${OSS_TEMP_REGION:-}
|
||||
DOCREADER_ADDR: docreader:50051
|
||||
DOCREADER_TRANSPORT: grpc
|
||||
NEO4J_ENABLE: ${NEO4J_ENABLE:-false}
|
||||
NEO4J_URI: ${NEO4J_URI:-}
|
||||
NEO4J_USERNAME: ${NEO4J_USERNAME:-}
|
||||
NEO4J_PASSWORD: ${NEO4J_PASSWORD:-}
|
||||
SYSTEM_AES_KEY: ${SYSTEM_AES_KEY:?SYSTEM_AES_KEY is required}
|
||||
JWT_SECRET: ${JWT_SECRET:?JWT_SECRET is required}
|
||||
OLLAMA_BASE_URL: ${OLLAMA_BASE_URL:-http://host.docker.internal:11434}
|
||||
OLLAMA_OPTIONAL: "true"
|
||||
LANGFUSE_ENABLED: ${LANGFUSE_ENABLED:-false}
|
||||
LANGFUSE_HOST: ${LANGFUSE_HOST:-}
|
||||
LANGFUSE_PUBLIC_KEY: ${LANGFUSE_PUBLIC_KEY:-}
|
||||
LANGFUSE_SECRET_KEY: ${LANGFUSE_SECRET_KEY:-}
|
||||
SSRF_WHITELIST_EXTRA: ${SSRF_WHITELIST_EXTRA:-host.docker.internal}
|
||||
WEKNORA_TENANT_AUTO_CREATE_API_KEY: "false"
|
||||
WEKNORA_SANDBOX_MODE: disabled
|
||||
WEKNORA_ASYNQ_CORE_CONCURRENCY: ${WEKNORA_ASYNQ_CORE_CONCURRENCY:-4}
|
||||
WEKNORA_ASYNQ_POSTPROCESS_CONCURRENCY: ${WEKNORA_ASYNQ_POSTPROCESS_CONCURRENCY:-1}
|
||||
WEKNORA_ASYNQ_ENRICHMENT_CONCURRENCY: ${WEKNORA_ASYNQ_ENRICHMENT_CONCURRENCY:-4}
|
||||
WEKNORA_WIKI_ASYNQ_CONCURRENCY: ${WEKNORA_WIKI_ASYNQ_CONCURRENCY:-2}
|
||||
CONCURRENCY_POOL_SIZE: ${CONCURRENCY_POOL_SIZE:-4}
|
||||
MAX_FILE_SIZE_MB: ${MAX_FILE_SIZE_MB:-100}
|
||||
ports:
|
||||
- "${APP_BIND_IP:-127.0.0.1}:${APP_PORT:-8080}:8080"
|
||||
volumes:
|
||||
- app_files:/data/files
|
||||
- docreader_tmp:/tmp/docreader:ro
|
||||
- ../../config/config.yaml:/app/config/config.yaml:ro
|
||||
- ../../skills/preloaded:/app/skills/preloaded
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
|
||||
interval: 10s
|
||||
timeout: 10s
|
||||
retries: 30
|
||||
start_period: 60s
|
||||
extra_hosts:
|
||||
- host.docker.internal:host-gateway
|
||||
restart: unless-stopped
|
||||
networks: [weknora]
|
||||
|
||||
frontend:
|
||||
image: wechatopenai/weknora-ui:v0.7.1@sha256:169678d4ba4c1f127b36c5f58a6ad567bd745d48488d693e4d3eb4117689c730
|
||||
depends_on:
|
||||
app:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
APP_HOST: app
|
||||
APP_PORT: 8080
|
||||
APP_SCHEME: http
|
||||
MAX_FILE_SIZE_MB: ${MAX_FILE_SIZE_MB:-100}
|
||||
ports:
|
||||
- "${FRONTEND_BIND_IP:-127.0.0.1}:${FRONTEND_PORT:-8088}:80"
|
||||
restart: unless-stopped
|
||||
networks: [weknora]
|
||||
|
||||
mcp:
|
||||
profiles: ["mcp"]
|
||||
build:
|
||||
context: ../../mcp-server
|
||||
image: weknora-mcp:v0.7.1-server-running
|
||||
depends_on:
|
||||
app:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
WEKNORA_BASE_URL: http://app:8080/api/v1
|
||||
WEKNORA_API_KEY: ${WEKNORA_API_KEY:?WEKNORA_API_KEY is required for MCP profile}
|
||||
MCP_SERVER_AUTH_TOKEN: ${MCP_SERVER_AUTH_TOKEN:?MCP_SERVER_AUTH_TOKEN is required for MCP profile}
|
||||
WEKNORA_CHAT_TIMEOUT: 300
|
||||
WEKNORA_VERIFY_SSL: "true"
|
||||
MCP_ALLOWED_UPLOAD_DIRS: ""
|
||||
ports:
|
||||
- "${MCP_BIND_IP:-127.0.0.1}:${MCP_PORT:-18082}:8000"
|
||||
restart: unless-stopped
|
||||
networks: [weknora]
|
||||
|
||||
networks:
|
||||
weknora:
|
||||
name: ${COMPOSE_PROJECT_NAME:-weknora-v071}-network
|
||||
|
||||
volumes:
|
||||
app_files:
|
||||
docreader_tmp:
|
||||
@@ -0,0 +1,102 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"captured_at": "2026-08-26T18:35:58+08:00",
|
||||
"capture_scope": "current server, read-only, secrets excluded",
|
||||
"compose": {
|
||||
"project": "weknora071full",
|
||||
"config_file": "/home/zheromiku/weknora-local-full/compose.yaml",
|
||||
"api_health": "http://127.0.0.1:8080/health returned HTTP 200",
|
||||
"frontend_health": "http://127.0.0.1:8088 returned HTTP 200"
|
||||
},
|
||||
"source": {
|
||||
"repository": "https://gitea.zheromiku.top/Weknora/Enterprise-Knowledge-Base.git",
|
||||
"upstream_tag": "v0.7.1",
|
||||
"commit": "c64a48647cd6f7eb8b0fb020b2e8fec74ee375fb",
|
||||
"packaging_branch": "release/server-running-v0.7.1",
|
||||
"app_binary_sha256": "aa6c6223f9980ef08120e65cdc091996b1eadbc828c69540e7e6b9cdc24bbca3"
|
||||
},
|
||||
"core_images": [
|
||||
{
|
||||
"service": "app",
|
||||
"container_id": "08ffd65c295efbf732b52ca3b3728fe9b423d18bc7fefcb047d0a939be2c6a73",
|
||||
"image": "wechatopenai/weknora-app:v0.7.1@sha256:d88bef9912f6abb8bc7c22144ee7f314016055b8075bda4ea8fbb28af41c3bcf",
|
||||
"image_content_id": "sha256:5036f926f9888aec13b2713d90efc0d7e96320141493bdddded5f25788f1e73b",
|
||||
"oci_revision": "c64a48647cd6f7eb8b0fb020b2e8fec74ee375fb",
|
||||
"running_at_capture": true
|
||||
},
|
||||
{
|
||||
"service": "frontend",
|
||||
"container_id": "a62eb44dcd5e9f0dba666b991c69fff9bbd58592d73afa8f2d4e9e70f74fe64c",
|
||||
"image": "wechatopenai/weknora-ui:v0.7.1@sha256:169678d4ba4c1f127b36c5f58a6ad567bd745d48488d693e4d3eb4117689c730",
|
||||
"image_content_id": "sha256:5973deb6f996ee6a6a21a4f32f7a7e47cc5cfa4f50c0dfceee48c9335a691110",
|
||||
"oci_revision": "c64a48647cd6f7eb8b0fb020b2e8fec74ee375fb",
|
||||
"running_at_capture": true
|
||||
},
|
||||
{
|
||||
"service": "docreader",
|
||||
"container_id": "038a52048ae15daf2940d440ed8964cabf258b03bb5afcf9f9865baa72da3b11",
|
||||
"image": "wechatopenai/weknora-docreader:v0.7.1@sha256:262bab1a4b12f24dd99958e32868ffc2d2cb09270465a88820420ac378c0e149",
|
||||
"image_content_id": "sha256:154dc42ff610bd9d06e54f9c7e827df85b63987aeda484c7e6d412d97f08e45f",
|
||||
"oci_revision": "c64a48647cd6f7eb8b0fb020b2e8fec74ee375fb",
|
||||
"running_at_capture": true
|
||||
},
|
||||
{
|
||||
"service": "mcp",
|
||||
"container_id": "80bc682a0589e9efcdf8169101e507bd0fb64f49b4315f1ec181defe6cb92f41",
|
||||
"image": "weknora-mcp:local",
|
||||
"image_content_id": "sha256:3cd8bdf8a6db1c443a33cbd95db744ad28a4a8a8e55615cda1cd9703f6516a74",
|
||||
"source": "v0.7.1 plus the two MCP SDK compatibility changes committed on the packaging branch",
|
||||
"running_at_capture": true
|
||||
}
|
||||
],
|
||||
"data_plane_observed": [
|
||||
{
|
||||
"service": "postgres",
|
||||
"image": "postgres:17-alpine",
|
||||
"image_content_id": "sha256:93aa428db0aeeb71d24dcad1491bef6e1396a4255697e4bfc4c725bfeb981b74"
|
||||
},
|
||||
{
|
||||
"service": "redis",
|
||||
"image": "redis:7.0-alpine",
|
||||
"image_content_id": "sha256:426f6fb54a1b82a2254bce70e5f4a72d15c14ecd3cc70d799465b956e7a32548"
|
||||
},
|
||||
{
|
||||
"service": "elasticsearch",
|
||||
"image": "docker.elastic.co/elasticsearch/elasticsearch:8.17.10",
|
||||
"image_content_id": "sha256:89e31594e1405bc7f2aa8aca12b02a6da165540c37cadfe7394a62baef6924e3"
|
||||
},
|
||||
{
|
||||
"service": "neo4j",
|
||||
"image": "neo4j:2025.10.1",
|
||||
"image_content_id": "sha256:5ff6e5ba92302482483cb07e6278ed76511ca6692acb93a4df3df07d1fea88ad"
|
||||
}
|
||||
],
|
||||
"effective_non_secret_configuration": {
|
||||
"DB_DRIVER": "postgres",
|
||||
"RETRIEVE_DRIVER": "elasticsearch_v8",
|
||||
"STORAGE_TYPE": "oss",
|
||||
"OSS_REGION": "cn-shenzhen",
|
||||
"NEO4J_ENABLE": true,
|
||||
"APP_PORT": 8080,
|
||||
"FRONTEND_PORT": 8088
|
||||
},
|
||||
"excluded_from_git": [
|
||||
".env and all credentials",
|
||||
"SYSTEM_AES_KEY and JWT/API tokens",
|
||||
"database, cache, search, graph and observability data",
|
||||
"OSS objects and uploaded/generated files",
|
||||
"logs, caches, runtime reports containing business identifiers",
|
||||
"host-built DobotAI binary",
|
||||
"unversioned legacy API Adapter source"
|
||||
],
|
||||
"separately_versioned_integrations": {
|
||||
"dobotai": {
|
||||
"repository": "https://gitea.zheromiku.top/Weknora/dobotai-platform.git",
|
||||
"current_worktree_commit_at_capture": "aa0513eb59dc3189ad59bd28b4990f998d19e2bd",
|
||||
"note": "The host-mounted runtime binary is not copied into this repository."
|
||||
},
|
||||
"knowledge_adapter": {
|
||||
"note": "The currently running legacy adapter image came from an unversioned local directory and is intentionally excluded. The replacement adapter must be published from its own repository before cloud deployment."
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -291,7 +291,9 @@ services:
|
||||
# overrides don't clobber it. (postgres is intentionally NOT listed: it
|
||||
# is not a user-registerable vector store, and whitelisting the app's own
|
||||
# DB host would skip the 5432 port block.)
|
||||
- SSRF_WHITELIST_EXTRA=${SSRF_WHITELIST_EXTRA:-searxng,qdrant,milvus,weaviate,doris-fe}
|
||||
# doris-be: Stream Load follows FE→BE redirects that must receive Basic
|
||||
# credentials on whitelisted BE hosts.
|
||||
- SSRF_WHITELIST_EXTRA=${SSRF_WHITELIST_EXTRA:-searxng,qdrant,milvus,weaviate,doris-fe,doris-be}
|
||||
- CONCURRENCY_POOL_SIZE=${CONCURRENCY_POOL_SIZE:-5}
|
||||
- JWT_SECRET=${JWT_SECRET:-}
|
||||
# File size limit (in MB)
|
||||
|
||||
+15
@@ -362,5 +362,20 @@ SystemAdmin 可在 **系统管理 → 平台 API Key** 创建 `scope_type=platfo
|
||||
|
||||
0.7.0 随附 **CLI v0.10**(Agent 优先,破坏性变更):新增 `model` / `message` / `config` / `skills` 命令组,`doc reparse` / `doc update`,`kb config` / `kb config set`;`session continue` 更名为 `session resume`,新增 `session tool-approval`;提供 agent-first 的 chat 与 `session ask` 输出模式,并强化了 SSE 可靠性与类型化错误。详见 [`cli/CHANGELOG.md`](../cli/CHANGELOG.md)。
|
||||
|
||||
## 35. 如何接入云之家(Yunzhijia)?
|
||||
|
||||
0.7.1 新增 **云之家 IM 集成**。在 **设置 → IM 集成** 添加云之家渠道并填写应用凭据即可;集成基于 WebSocket 长连接接收消息,支持图片消息入库(带 SSRF 安全下载),默认以 **Markdown** 格式回复。若图片无法下载,请检查出站网络与凭据是否具备下载权限。
|
||||
|
||||
## 36. 如何使用火山引擎 Rerank / 智谱 AI 网络搜索?
|
||||
|
||||
0.7.1 新增两个供应商:
|
||||
|
||||
- **火山引擎 Rerank**:在 **设置 → 模型** 中添加 Rerank 模型并选择火山引擎。当单次请求文档数超过 API 上限时,客户端会自动分批发送并合并结果。vLLM Rerank 现默认不再发送 `truncate_prompt_tokens` 以提升兼容性。
|
||||
- **智谱 AI 网络搜索**:在 **设置 → 网络搜索** 中选择智谱 AI 作为搜索供应商并填写凭据即可,用于 Agent 联网检索。
|
||||
|
||||
## 37. 升级到 0.7.1 后对话记忆(Memory)设置消失了?还需要 Neo4j 吗?
|
||||
|
||||
0.7.1 **移除了基于 Neo4j 的会话记忆(episodic memory)** 功能,相关 API 字段、设置项与嵌入开关一并下线,对话不再依赖 Neo4j 做记忆召回。**注意:知识图谱(GraphRAG / 图检索)仍然使用 Neo4j**,因此若你启用了图谱检索,Neo4j 依旧是必需组件,无需移除部署。若你此前仅为记忆功能部署 Neo4j 且未使用图谱,可按需精简。
|
||||
|
||||
## P.S.
|
||||
如果以上方式未解决问题,请在issue中描述您的问题,并提供必要的日志信息辅助我们进行问题排查
|
||||
|
||||
+3
-3
@@ -655,7 +655,7 @@ const docTemplate = `{
|
||||
},
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "返回数量上限(默认6)",
|
||||
"description": "返回数量上限(未传时使用智能体配置的开场问题数量,最大30)",
|
||||
"name": "limit",
|
||||
"in": "query"
|
||||
}
|
||||
@@ -9987,7 +9987,7 @@ const docTemplate = `{
|
||||
"Bearer": []
|
||||
}
|
||||
],
|
||||
"description": "搜索空间(排除已加入的空间)用于邀请加入组织;按空间去重,附带代表用户",
|
||||
"description": "按空间名搜索可邀请的空间(排除已加入的空间)用于邀请加入组织;按空间去重",
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -10005,7 +10005,7 @@ const docTemplate = `{
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "搜索关键词(空间名、用户名或邮箱)",
|
||||
"description": "搜索关键词(空间名)",
|
||||
"name": "q",
|
||||
"in": "query",
|
||||
"required": true
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 1.3 MiB After Width: | Height: | Size: 1.3 MiB |
+3
-3
@@ -648,7 +648,7 @@
|
||||
},
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "返回数量上限(默认6)",
|
||||
"description": "返回数量上限(未传时使用智能体配置的开场问题数量,最大30)",
|
||||
"name": "limit",
|
||||
"in": "query"
|
||||
}
|
||||
@@ -9980,7 +9980,7 @@
|
||||
"Bearer": []
|
||||
}
|
||||
],
|
||||
"description": "搜索空间(排除已加入的空间)用于邀请加入组织;按空间去重,附带代表用户",
|
||||
"description": "按空间名搜索可邀请的空间(排除已加入的空间)用于邀请加入组织;按空间去重",
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -9998,7 +9998,7 @@
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "搜索关键词(空间名、用户名或邮箱)",
|
||||
"description": "搜索关键词(空间名)",
|
||||
"name": "q",
|
||||
"in": "query",
|
||||
"required": true
|
||||
|
||||
+3
-3
@@ -6098,7 +6098,7 @@ paths:
|
||||
in: query
|
||||
name: tag_scopes
|
||||
type: string
|
||||
- description: 返回数量上限(默认6)
|
||||
- description: 返回数量上限(未传时使用智能体配置的开场问题数量,最大30)
|
||||
in: query
|
||||
name: limit
|
||||
type: integer
|
||||
@@ -11950,14 +11950,14 @@ paths:
|
||||
- 组织管理
|
||||
/organizations/{id}/search-tenants:
|
||||
get:
|
||||
description: 搜索空间(排除已加入的空间)用于邀请加入组织;按空间去重,附带代表用户
|
||||
description: 按空间名搜索可邀请的空间(排除已加入的空间)用于邀请加入组织;按空间去重
|
||||
parameters:
|
||||
- description: 组织ID
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
type: string
|
||||
- description: 搜索关键词(空间名、用户名或邮箱)
|
||||
- description: 搜索关键词(空间名)
|
||||
in: query
|
||||
name: q
|
||||
required: true
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "knowledage-base",
|
||||
"version": "0.7.0",
|
||||
"version": "0.7.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "knowledage-base",
|
||||
"version": "0.7.0",
|
||||
"version": "0.7.1",
|
||||
"dependencies": {
|
||||
"@microsoft/fetch-event-source": "^2.0.1",
|
||||
"@types/dompurify": "^3.2.0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "knowledage-base",
|
||||
"version": "0.7.0",
|
||||
"version": "0.7.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -225,9 +225,11 @@ export async function getEmbedChunkById(channelId: string, token: string, chunkI
|
||||
)
|
||||
}
|
||||
|
||||
export async function getEmbedSuggestedQuestions(channelId: string, token: string, limit = 6) {
|
||||
export async function getEmbedSuggestedQuestions(channelId: string, token: string, limit?: number) {
|
||||
// Omit limit to let the channel agent's configured starter count apply.
|
||||
const qs = typeof limit === 'number' && limit > 0 ? `?limit=${limit}` : ''
|
||||
return get<{ success: boolean; data: { questions: SuggestedQuestion[] } }>(
|
||||
`/api/v1/embed/${channelId}/suggested-questions?limit=${limit}`,
|
||||
`/api/v1/embed/${channelId}/suggested-questions${qs}`,
|
||||
{ headers: { Authorization: `Embed ${token}` } },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -122,7 +122,7 @@ import { ref, computed, watch, onMounted } from 'vue'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useOrganizationStore } from '@/stores/organization'
|
||||
import { shareAgent, listAgentShares, removeAgentShare } from '@/api/organization'
|
||||
import { listAgentShares } from '@/api/organization'
|
||||
import type { AgentShareResponse } from '@/api/organization'
|
||||
import type { CustomAgent } from '@/api/agent'
|
||||
import SpaceAvatar from '@/components/SpaceAvatar.vue'
|
||||
@@ -224,7 +224,7 @@ async function handleShare() {
|
||||
if (!selectedOrgId.value) return
|
||||
submitting.value = true
|
||||
try {
|
||||
const result = await shareAgent(props.agentId, {
|
||||
const result = await orgStore.shareAgent(props.agentId, {
|
||||
organization_id: selectedOrgId.value,
|
||||
permission: 'viewer'
|
||||
})
|
||||
@@ -246,7 +246,11 @@ async function handleShare() {
|
||||
|
||||
async function handleUnshare(share: AgentShareResponse) {
|
||||
try {
|
||||
const result = await removeAgentShare(props.agentId, share.id)
|
||||
const result = await orgStore.unshareAgent(
|
||||
props.agentId,
|
||||
share.id,
|
||||
share.organization_id
|
||||
)
|
||||
if (result.success) {
|
||||
MessagePlugin.success(t('organization.share.unshareSuccess'))
|
||||
await loadShares()
|
||||
|
||||
+102
-102
@@ -5069,18 +5069,18 @@ export default {
|
||||
organization: {
|
||||
title: 'Shared Spaces',
|
||||
subtitle: 'Create or join shared spaces so multiple workspaces can collaborate and share knowledge bases and agents',
|
||||
createOrg: 'Create Space',
|
||||
createOrg: 'Create Shared Space',
|
||||
createOrgShort: 'New',
|
||||
joinOrg: 'Join Space',
|
||||
joinOrg: 'Join Shared Space',
|
||||
joinOrgShort: 'Join',
|
||||
name: 'Space Name',
|
||||
namePlaceholder: 'Enter space name',
|
||||
nameRequired: 'Please enter space name',
|
||||
avatar: 'Space Avatar',
|
||||
name: 'Shared Space Name',
|
||||
namePlaceholder: 'Enter shared space name',
|
||||
nameRequired: 'Please enter shared space name',
|
||||
avatar: 'Shared Space Avatar',
|
||||
avatarClear: 'Clear',
|
||||
avatarPickerHint: 'Choose an emoji as space avatar',
|
||||
description: 'Description',
|
||||
descriptionPlaceholder: 'Enter space description (optional)',
|
||||
avatarPickerHint: 'Choose an emoji as shared space avatar',
|
||||
description: 'Shared Space Description',
|
||||
descriptionPlaceholder: 'Enter shared space description (optional)',
|
||||
noDescription: 'No description',
|
||||
members: 'members',
|
||||
memberCount: 'Member count',
|
||||
@@ -5088,7 +5088,7 @@ export default {
|
||||
inviteCode: 'Invite Code',
|
||||
inviteCodePlaceholder: 'Enter invite code',
|
||||
inviteCodeRequired: 'Please enter invite code',
|
||||
inviteCodeTip: 'Share this invite code with others to let them join your space',
|
||||
inviteCodeTip: 'Share this invite code with others to let them join the shared space',
|
||||
refreshInviteCode: 'Refresh Invite Code',
|
||||
inviteCodeRefreshed: 'Invite code refreshed',
|
||||
inviteCodeRefreshFailed: 'Failed to refresh invite code',
|
||||
@@ -5100,36 +5100,36 @@ export default {
|
||||
cannotManage: 'Your workspace role is insufficient to manage this shared space',
|
||||
},
|
||||
join: {
|
||||
title: 'Join Space',
|
||||
joining: 'Joining space...',
|
||||
success: 'Successfully joined space!',
|
||||
failed: 'Failed to join space',
|
||||
title: 'Join Shared Space',
|
||||
joining: 'Joining shared space...',
|
||||
success: 'Successfully joined shared space!',
|
||||
failed: 'Failed to join shared space',
|
||||
noCode: 'Invite code not found',
|
||||
goToOrganizations: 'Go to Spaces',
|
||||
confirmTitle: 'Confirm Join Space',
|
||||
goToOrganizations: 'Go to Shared Spaces',
|
||||
confirmTitle: 'Confirm Join Shared Space',
|
||||
confirm: 'Confirm Join',
|
||||
preview: 'Preview & Join',
|
||||
memberCount: '{count} members',
|
||||
shareCount: '{count} shared knowledge bases',
|
||||
agentShareCount: '{count} agents',
|
||||
alreadyMember: 'You are already a member of this space',
|
||||
alreadyMember: 'You are already a member of this shared space',
|
||||
invalidCode: 'Invalid invite code',
|
||||
byInviteCode: 'Enter invite code',
|
||||
searchSpaces: 'Search spaces',
|
||||
searchSpacesDesc: 'Browse or search spaces that are open for discovery; join without an invite code',
|
||||
searchSpacesPlaceholder: 'Search by space name, description or space ID',
|
||||
spaceId: 'Space ID',
|
||||
noSearchResult: 'No matching spaces',
|
||||
noSearchableSpaces: 'No discoverable spaces yet, or try a search',
|
||||
searchSpaces: 'Search shared spaces',
|
||||
searchSpacesDesc: 'Browse or search shared spaces that are open for discovery; join without an invite code',
|
||||
searchSpacesPlaceholder: 'Search by shared space name, description or ID',
|
||||
spaceId: 'Shared Space ID',
|
||||
noSearchResult: 'No matching shared spaces',
|
||||
noSearchableSpaces: 'No discoverable shared spaces yet, or try a search',
|
||||
membersWithLimit: '{current}/{limit} members',
|
||||
memberLimitReached: 'Full',
|
||||
backToSearch: 'Back to search',
|
||||
},
|
||||
invite: {
|
||||
loading: 'Loading...',
|
||||
previewTitle: 'Join Space',
|
||||
previewInfo: 'Space Overview',
|
||||
inputDesc: 'Enter the invite code (or paste from an invite link) to view the space and join',
|
||||
previewTitle: 'Join Shared Space',
|
||||
previewInfo: 'Shared Space Overview',
|
||||
inputDesc: 'Enter the invite code (or paste from an invite link) to view the shared space and join',
|
||||
previewAction: 'View',
|
||||
primaryJoin: 'Join',
|
||||
invalidTitle: 'Invalid Invitation',
|
||||
@@ -5138,10 +5138,10 @@ export default {
|
||||
members: 'Members',
|
||||
knowledgeBases: 'Knowledge Bases',
|
||||
agents: 'Agents',
|
||||
alreadyMember: 'You are already a member of this space',
|
||||
alreadyMember: 'You are already a member of this shared space',
|
||||
confirmJoin: 'Confirm Join',
|
||||
submitRequest: 'Request to Join',
|
||||
requireApprovalTip: 'This space requires admin approval to join',
|
||||
requireApprovalTip: 'This shared space requires admin approval to join',
|
||||
approvalLabel: 'Join method',
|
||||
needApproval: 'Requires approval',
|
||||
noApproval: 'No approval required',
|
||||
@@ -5150,31 +5150,31 @@ export default {
|
||||
selectRole: 'Select role',
|
||||
messagePlaceholder: 'Optional: message (e.g. intro or reason to join)',
|
||||
applicationNote: 'Application note (optional)',
|
||||
joinSuccess: 'Successfully joined space!',
|
||||
joinSuccess: 'Successfully joined shared space!',
|
||||
joinFailed: 'Failed to join, please try again',
|
||||
requestSubmitted: 'Request submitted, please wait for admin approval',
|
||||
requestFailed: 'Failed to submit request, please try again',
|
||||
viewOrganization: 'View Space',
|
||||
viewOrganization: 'View Shared Space',
|
||||
},
|
||||
leave: 'Leave Space',
|
||||
leaveConfirm: 'Are you sure you want to leave this space?',
|
||||
leaveConfirmTitle: 'Leave Space',
|
||||
leaveConfirmMessage: 'Are you sure you want to leave "{name}"? You will lose access to shared knowledge bases.',
|
||||
leaveSuccess: 'Left space successfully',
|
||||
leaveFailed: 'Failed to leave space',
|
||||
deleteConfirm: 'Are you sure you want to delete this space? This action cannot be undone.',
|
||||
deleteConfirmTitle: 'Delete Space',
|
||||
deleteConfirmMessage: 'Are you sure you want to delete "{name}"? All members will be removed. This action cannot be undone.',
|
||||
deleteSuccess: 'Space deleted',
|
||||
deleteFailed: 'Failed to delete space',
|
||||
createSuccess: 'Space created successfully',
|
||||
createFailed: 'Failed to create space',
|
||||
joinSuccess: 'Joined space successfully',
|
||||
joinFailed: 'Failed to join space',
|
||||
leave: 'Leave Shared Space',
|
||||
leaveConfirm: 'Are you sure you want to leave this shared space?',
|
||||
leaveConfirmTitle: 'Leave Shared Space',
|
||||
leaveConfirmMessage: 'Are you sure you want to leave shared space "{name}"? You will no longer have access to knowledge bases shared in this shared space.',
|
||||
leaveSuccess: 'Left shared space successfully',
|
||||
leaveFailed: 'Failed to leave shared space',
|
||||
deleteConfirm: 'Are you sure you want to delete this shared space? This action cannot be undone.',
|
||||
deleteConfirmTitle: 'Delete Shared Space',
|
||||
deleteConfirmMessage: 'Are you sure you want to delete shared space "{name}"? All members will be removed. This action cannot be undone.',
|
||||
deleteSuccess: 'Shared space deleted',
|
||||
deleteFailed: 'Failed to delete shared space',
|
||||
createSuccess: 'Shared space created successfully',
|
||||
createFailed: 'Failed to create shared space',
|
||||
joinSuccess: 'Joined shared space successfully',
|
||||
joinFailed: 'Failed to join shared space',
|
||||
manageMembers: 'Manage Members',
|
||||
noMembers: 'No members',
|
||||
members: {
|
||||
listTitle: 'Space members',
|
||||
listTitle: 'Shared space members',
|
||||
searchPlaceholder: 'Search members…',
|
||||
loading: 'Loading members…',
|
||||
emptySearch: 'No members matching "{q}"',
|
||||
@@ -5219,17 +5219,17 @@ export default {
|
||||
memberRemoved: 'Member removed',
|
||||
memberRemoveFailed: 'Failed to remove member',
|
||||
empty: 'You have not joined any shared space yet',
|
||||
emptyDesc: 'Create a space or join an existing one with an invite code',
|
||||
emptyDesc: 'Create a shared space or join an existing one with an invite code',
|
||||
all: 'All',
|
||||
createdByMe: 'Created by me',
|
||||
joinedByMe: 'Joined',
|
||||
createdTag: 'Created',
|
||||
joinedTag: 'Joined',
|
||||
joinedLabel: 'Joined',
|
||||
emptyCreated: 'You have not created any space yet',
|
||||
emptyCreatedDesc: 'Click "Create Space" to create one',
|
||||
emptyJoined: 'You have not joined any space yet',
|
||||
emptyJoinedDesc: 'Join an existing space with an invite code',
|
||||
emptyCreated: 'You have not created any shared space yet',
|
||||
emptyCreatedDesc: 'Click "Create Shared Space" to create a new one',
|
||||
emptyJoined: 'You have not joined any shared space yet',
|
||||
emptyJoinedDesc: 'Join an existing shared space with an invite code',
|
||||
role: {
|
||||
admin: 'Admin',
|
||||
editor: 'Editor',
|
||||
@@ -5240,29 +5240,29 @@ export default {
|
||||
removeMemberTitle: 'Remove Member',
|
||||
removeMemberConfirm: 'Are you sure you want to remove "{name}"?',
|
||||
removeMember: 'Remove Member',
|
||||
shareKBTip: 'Go to knowledge base list, select a knowledge base and click share to share it to this space',
|
||||
shareKBTip: 'Go to knowledge base list, select a knowledge base and click share to share it to this shared space',
|
||||
},
|
||||
settings: {
|
||||
editTitle: 'Space Settings',
|
||||
detailTitle: 'Space Details',
|
||||
myRoleDesc: 'Your role in this space determines your permissions',
|
||||
membersDesc: 'View and manage space members and their roles. Each member represents a workspace — all users in the same workspace share access to this space.',
|
||||
editTitle: 'Shared Space Settings',
|
||||
detailTitle: 'Shared Space Details',
|
||||
myRoleDesc: 'Your role in this shared space determines your permissions',
|
||||
membersDesc: 'View and manage shared space members and their roles. Each member represents a workspace — all users in the same workspace share access to this shared space.',
|
||||
permissionsIconHint: 'View role permissions',
|
||||
sharedDesc: 'View all knowledge bases shared to this space',
|
||||
sharedDesc: 'View all knowledge bases shared to this shared space',
|
||||
noSharedKB: 'No shared knowledge bases yet',
|
||||
noSharedKBTip: 'Knowledge base owners can share their knowledge bases to this space in KB settings',
|
||||
noSharedKBTip: 'Knowledge base owners can share their knowledge bases to this shared space in KB settings',
|
||||
sharedAgents: 'Shared Agents',
|
||||
noSharedAgents: 'No shared agents yet',
|
||||
sharedAgentsDesc: 'Agents shared to this space; members can use them in chat',
|
||||
sharedAgentsKbHint: 'Knowledge bases linked to an agent are only available (read-only) when members use that agent in a conversation (via {\'@\'}). They do not appear in the Knowledge Base list. To let members see or edit a knowledge base in the list, share that knowledge base to this space separately.',
|
||||
sharedAgentsDesc: 'Agents shared to this shared space; members can use them in chat',
|
||||
sharedAgentsKbHint: 'Knowledge bases linked to an agent are only available (read-only) when members use that agent in a conversation (via {\'@\'}). They do not appear in the Knowledge Base list. To let members see or edit a knowledge base in the list, share that knowledge base to this shared space separately.',
|
||||
sharedAgentsKbHintShort: 'Agent-linked knowledge is read-only in chat; share the KB to this space if members should see or edit it in the list.',
|
||||
noSharedAgentsTip: 'Admins can share agents to this space from agent settings',
|
||||
sharePermissionLabel: 'Space permission',
|
||||
noSharedAgentsTip: 'Admins can share agents to this shared space from agent settings',
|
||||
sharePermissionLabel: 'Shared space permission',
|
||||
myPermissionLabel: 'Effective',
|
||||
permissionCalcFormula: 'Space permission is set when sharing; effective permission is the lower of that and your space role',
|
||||
permissionCalcTip: 'Effective permission is the lower of space permission and your role here; viewers get at most read-only on this KB.',
|
||||
permissionCalcFormula: 'Shared space permission is set when sharing; effective permission is the lower of that and your shared space role',
|
||||
permissionCalcTip: 'Effective permission is the lower of shared space permission and your role here; viewers get at most read-only on this KB.',
|
||||
inviteMembers: 'Invite Members',
|
||||
inviteMembersDesc: 'Invite others to join the space via code or link',
|
||||
inviteMembersDesc: 'Invite others to join the shared space via code or link',
|
||||
inviteLink: 'Invite Link',
|
||||
inviteLinkValidity: 'Invite link validity',
|
||||
inviteLinkValidityDesc: 'Validity period for newly generated invite links',
|
||||
@@ -5273,21 +5273,21 @@ export default {
|
||||
remainingValidity: 'Expires in {n} days',
|
||||
remainingValidityNever: 'Never expire',
|
||||
remainingValidityExpired: 'Expired',
|
||||
removeShareFromOrg: 'Remove from space',
|
||||
removeShareConfirm: 'Remove "{name}" from this space? Members will no longer have access to this knowledge base.',
|
||||
removeAgentShareConfirm: 'Remove "{name}" from this space? Members will no longer have access to this agent.',
|
||||
removeShareSuccess: 'Removed from space',
|
||||
removeShareFromOrg: 'Remove from shared space',
|
||||
removeShareConfirm: 'Remove "{name}" from this shared space? Members will no longer have access to this knowledge base.',
|
||||
removeAgentShareConfirm: 'Remove "{name}" from this shared space? Members will no longer have access to this agent.',
|
||||
removeShareSuccess: 'Removed from shared space',
|
||||
removeShareFailed: 'Failed to remove, please try again',
|
||||
requireApproval: 'Require Approval',
|
||||
requireApprovalDesc: 'When enabled, new members need admin approval to join',
|
||||
searchable: 'Open for search',
|
||||
searchableDesc: 'When enabled, this space appears in the "Join Space" search list; others can search and request to join without an invite code',
|
||||
searchableDesc: 'When enabled, this shared space appears in the "Join Shared Space" search list; others can search and request to join without an invite code',
|
||||
memberLimit: 'Member limit',
|
||||
memberLimitDesc: 'No new members can be added when the limit is reached; 0 means unlimited',
|
||||
memberLimitPlaceholder: '0 = unlimited',
|
||||
memberLimitHint: 'Current members: {count}',
|
||||
joinRequests: 'Join Requests',
|
||||
joinRequestsDesc: 'Review pending requests to join the space',
|
||||
joinRequestsDesc: 'Review pending requests to join the shared space',
|
||||
noPendingRequests: 'No pending requests',
|
||||
pendingJoinRequestsBadge: 'Pending join requests to review',
|
||||
pendingReview: 'Pending',
|
||||
@@ -5306,37 +5306,37 @@ export default {
|
||||
editor: {
|
||||
navBasic: 'Basic Info',
|
||||
navPermissions: 'Permissions',
|
||||
navJoin: 'Join Space',
|
||||
navJoin: 'Join Shared Space',
|
||||
basicTitle: 'Basic Information',
|
||||
basicDesc: 'Set the space name and description for easy identification',
|
||||
basicDesc: 'Set the shared space name and description for easy identification',
|
||||
nameTip: 'Use your team or project name for easy identification',
|
||||
descriptionTip: 'Describe the purpose and goals of the space',
|
||||
descriptionTip: 'Describe the purpose and goals of the shared space to help members understand it',
|
||||
permissionsTitle: 'Member Permissions',
|
||||
permissionsDesc: 'Understand the permission scope of different roles for knowledge bases and agents in the space',
|
||||
permissionsDesc: 'Understand the permission scope of different roles for knowledge bases and agents in the shared space',
|
||||
permissionFeature: 'Permission Feature',
|
||||
fullAccess: 'Full Access',
|
||||
editAccess: 'Edit Access',
|
||||
viewAccess: 'View Only',
|
||||
adminPerm1: 'Manage space settings, members, and knowledge base & agent sharing',
|
||||
adminPerm1: 'Manage shared space settings, members, and knowledge base & agent sharing',
|
||||
adminPerm2: 'Share and manage knowledge bases and agents',
|
||||
adminPerm3: 'Edit shared knowledge base content',
|
||||
adminPerm4: 'View and search knowledge bases',
|
||||
useSharedAgentsPerm: 'Use shared agents',
|
||||
shareKBPerm: 'Share knowledge bases to space',
|
||||
shareKBPerm: 'Share knowledge bases to shared space',
|
||||
editorPerm1: 'Edit shared knowledge base content',
|
||||
editorPerm2: 'View and search knowledge bases',
|
||||
editorPerm3: 'Manage space settings and members',
|
||||
editorPerm3: 'Manage shared space settings and members',
|
||||
viewerPerm1: 'View and search knowledge bases',
|
||||
viewerPerm2: 'Edit knowledge base content',
|
||||
viewerPerm3: 'Manage space settings',
|
||||
ownerNote: 'As the space creator, you will automatically become an admin with full permissions.',
|
||||
joinTitle: 'Join Space',
|
||||
joinDesc: 'Join an existing space with an invite code to access shared knowledge bases and agents',
|
||||
joinIllustration: 'Enter the invite code provided by the space admin to join',
|
||||
inviteCodeTip: 'The invite code is generated by space admins, please ask them for it',
|
||||
viewerPerm3: 'Manage shared space settings',
|
||||
ownerNote: 'As the shared space creator, you will automatically become an admin with full permissions.',
|
||||
joinTitle: 'Join Shared Space',
|
||||
joinDesc: 'Join an existing shared space with an invite code to access shared knowledge bases and agents',
|
||||
joinIllustration: 'Enter the invite code provided by the shared space admin to join',
|
||||
inviteCodeTip: 'The invite code is generated by shared space admins, please ask them for it',
|
||||
howToGetCode: 'How to get an invite code?',
|
||||
step1: 'Contact the admin of the space you want to join',
|
||||
step2: 'Ask them to share the space invite code',
|
||||
step1: 'Contact the admin of the shared space you want to join',
|
||||
step2: 'Ask them to share the shared space invite code',
|
||||
step3: 'Paste the invite code in the input field above',
|
||||
},
|
||||
upgrade: {
|
||||
@@ -5356,12 +5356,12 @@ export default {
|
||||
addMember: {
|
||||
button: 'Add Member',
|
||||
dialogTitle: 'Add Member',
|
||||
tip: 'Added users will immediately become space members and can access shared knowledge bases.',
|
||||
tip: 'Added users will immediately become shared space members and can access knowledge bases shared in this shared space.',
|
||||
tipTenant: 'Membership is at the workspace level: once a workspace joins, all of its users share access to this space. Results below are deduplicated by workspace.',
|
||||
searchUser: 'Select User',
|
||||
searchTenant: 'Select Workspace',
|
||||
searchPlaceholder: 'Search by username or email...',
|
||||
searchTenantPlaceholder: 'Search by workspace name, username or email...',
|
||||
searchTenantPlaceholder: 'Search by workspace name...',
|
||||
searchHint: 'Type at least 2 characters to search',
|
||||
searchTenantHint: 'Type at least 2 characters; results are deduplicated by workspace and exclude workspaces already in this space',
|
||||
selectRole: 'Assign Role',
|
||||
@@ -5375,9 +5375,9 @@ export default {
|
||||
},
|
||||
},
|
||||
share: {
|
||||
title: 'Share Knowledge Base',
|
||||
selectOrg: 'Select Space',
|
||||
selectOrgPlaceholder: 'Select a space to share with',
|
||||
title: 'Share to Shared Space',
|
||||
selectOrg: 'Select Shared Space',
|
||||
selectOrgPlaceholder: 'Select a shared space to share with',
|
||||
permission: 'Permission',
|
||||
permissionTip: 'Editable permission allows members to modify knowledge base content, Read-only permission only allows search and Q&A',
|
||||
shareSuccess: 'Knowledge base shared',
|
||||
@@ -5385,25 +5385,25 @@ export default {
|
||||
unshareSuccess: 'Share cancelled',
|
||||
unshareFailed: 'Failed to cancel share',
|
||||
sharedTo: 'Shared to',
|
||||
noShares: 'Not shared to any space yet',
|
||||
searchPlaceholder: 'Search spaces…',
|
||||
noShares: 'Not shared to any shared space yet',
|
||||
searchPlaceholder: 'Search shared spaces…',
|
||||
loading: 'Loading…',
|
||||
emptySearch: 'No spaces matching "{q}"',
|
||||
addShareDialogTitle: 'Share to space',
|
||||
emptySearch: 'No shared spaces matching "{q}"',
|
||||
addShareDialogTitle: 'Share to shared space',
|
||||
unshareAction: 'Remove share',
|
||||
columns: {
|
||||
space: 'Space',
|
||||
space: 'Shared Space',
|
||||
permission: 'Permission',
|
||||
sharedAt: 'Shared',
|
||||
operations: 'Actions',
|
||||
},
|
||||
sharedKnowledgeBase: 'Shared Knowledge Base',
|
||||
shareToSpace: 'Share to space',
|
||||
shareModelToSpace: 'Share "{name}" to space',
|
||||
shareAgentToSpace: 'Share "{name}" to space',
|
||||
modelShareDesc: 'Share this model to a space so members can use it',
|
||||
agentShareDesc: 'Share this agent to a space so members can use it',
|
||||
spaceAgentShareCountTip: 'Number of agents shared to this space',
|
||||
shareToSpace: 'Share to shared space',
|
||||
shareModelToSpace: 'Share "{name}" to shared space',
|
||||
shareAgentToSpace: 'Share "{name}" to shared space',
|
||||
modelShareDesc: 'Share this model to a shared space so members can use it',
|
||||
agentShareDesc: 'Share this agent to a shared space so members can use it',
|
||||
spaceAgentShareCountTip: 'Number of agents shared to this shared space',
|
||||
sharedFrom: 'From',
|
||||
sharedBadge: 'Shared',
|
||||
permissionReadonly: 'Read-only',
|
||||
|
||||
+112
-112
@@ -3,7 +3,7 @@ export default {
|
||||
knowledgeBase: "지식베이스",
|
||||
agents: "에이전트",
|
||||
integrations: "게시 및 통합",
|
||||
organizations: "공유 스페이스",
|
||||
organizations: "공유 공간",
|
||||
chat: "대화",
|
||||
newChat: "새 대화",
|
||||
createChat: "대화 생성",
|
||||
@@ -352,10 +352,10 @@ export default {
|
||||
tenantTooltip: "워크스페이스의 다른 멤버가 생성",
|
||||
tenantTooltipWithCreator: "{creator}님이 생성",
|
||||
space: "스페이스",
|
||||
spaceTooltip: "공유 스페이스 「{space}」에서 가져옴",
|
||||
spaceTooltipWithTenant: "공유 스페이스 「{space}」 · 출처 {tenant}",
|
||||
spaceTooltip: "공유 공간 「{space}」에서 가져옴",
|
||||
spaceTooltipWithTenant: "공유 공간 「{space}」 · 출처 {tenant}",
|
||||
shared: "외부 공유",
|
||||
sharedTooltip: "공유 스페이스를 통해 외부 워크스페이스에서 접근",
|
||||
sharedTooltip: "공유 공간를 통해 외부 워크스페이스에서 접근",
|
||||
},
|
||||
knowledgeBase: {
|
||||
title: "지식베이스",
|
||||
@@ -369,7 +369,7 @@ export default {
|
||||
permissionAdmin: "공유 설정 편집 및 관리",
|
||||
permissionEditor: "편집 가능한 문서 및 태그",
|
||||
permissionViewer: "보기 및 검색만 가능",
|
||||
fromOrg: "공유 스페이스에서",
|
||||
fromOrg: "공유 공간에서",
|
||||
sharedAt: "공유일시",
|
||||
lastUpdated: "마지막 업데이트",
|
||||
},
|
||||
@@ -2103,7 +2103,7 @@ export default {
|
||||
},
|
||||
shareScope: {
|
||||
title: "공유 범위 설명",
|
||||
desc: "스페이스 구성원은 읽기 전용 모드로 에이전트를 사용하며 현재 구성된 기능과 리소스를 따릅니다. 에이전트에 대한 수정 사항은 공유 스페이스에 동기화됩니다. 스페이스 구성원이 지식베이스 콘텐츠를 편집할 수 있도록 허용하려면 지식베이스를 스페이스에 공유하세요.",
|
||||
desc: "스페이스 구성원은 읽기 전용 모드로 에이전트를 사용하며 현재 구성된 기능과 리소스를 따릅니다. 에이전트에 대한 수정 사항은 공유 공간에 동기화됩니다. 스페이스 구성원이 지식베이스 콘텐츠를 편집할 수 있도록 허용하려면 지식베이스를 스페이스에 공유하세요.",
|
||||
knowledgeBase: "지식베이스",
|
||||
chatModel: "대화 모델",
|
||||
rerankModel: "모델을 재배열하다",
|
||||
@@ -3600,14 +3600,14 @@ export default {
|
||||
uninitializedBanner:
|
||||
"일부 지식베이스가 아직 초기화되지 않았습니다. 지식 문서를 추가하려면 먼저 설정에서 모델 정보를 구성해야 합니다",
|
||||
emptyShared:
|
||||
"현재 공동 작업 지식베이스가 없습니다. 공유 스페이스에 참여하여 다른 사람들이 공유하는 지식베이스를 얻을 수 있습니다.",
|
||||
"현재 공동 작업 지식베이스가 없습니다. 공유 공간에 참여하여 다른 사람들이 공유하는 지식베이스를 얻을 수 있습니다.",
|
||||
empty: {
|
||||
title: "지식베이스 없음",
|
||||
description:
|
||||
'왼쪽 빠른 작업에서 "지식베이스 생성" 버튼을 클릭하여 첫 번째 지식베이스를 생성하세요',
|
||||
sharedTitle: "아직 공유 지식베이스가 없습니다.",
|
||||
sharedDescription:
|
||||
"공유 스페이스에 참여하거나 다른 사람에게 지식베이스를 공유해 달라고 요청할 수 있습니다.",
|
||||
"공유 공간에 참여하거나 다른 사람에게 지식베이스를 공유해 달라고 요청할 수 있습니다.",
|
||||
favoritesTitle: "즐겨찾기 없음",
|
||||
favoritesDescription: "카드의 별표 아이콘을 눌러 즐겨찾기에 추가하세요",
|
||||
recentsTitle: "최근 항목 없음",
|
||||
@@ -5069,21 +5069,21 @@ export default {
|
||||
withWebSearch: "웹 검색",
|
||||
},
|
||||
organization: {
|
||||
title: "공유 스페이스",
|
||||
title: "공유 공간",
|
||||
subtitle:
|
||||
"공유 스페이스를 만들거나 참여하여 여러 스페이스가 함께 협업하고 지식베이스와 에이전트를 공유하세요.",
|
||||
createOrg: "스페이스 생성",
|
||||
"공유 공간를 만들거나 참여하여 여러 스페이스가 함께 협업하고 지식베이스와 에이전트를 공유하세요.",
|
||||
createOrg: "공유 공간 생성",
|
||||
createOrgShort: "새로 만들기",
|
||||
joinOrg: "스페이스에 참여하기",
|
||||
joinOrg: "공유 공간에 참여하기",
|
||||
joinOrgShort: "참여",
|
||||
name: "스페이스 이름",
|
||||
namePlaceholder: "스페이스 이름을 입력해주세요",
|
||||
nameRequired: "스페이스 이름을 입력해주세요",
|
||||
avatar: "스페이스 아바타",
|
||||
name: "공유 공간 이름",
|
||||
namePlaceholder: "공유 공간 이름을 입력해주세요",
|
||||
nameRequired: "공유 공간 이름을 입력해주세요",
|
||||
avatar: "공유 공간 아바타",
|
||||
avatarClear: "지우기",
|
||||
avatarPickerHint: "스페이스 아바타로 이모티콘을 선택하세요",
|
||||
description: "스페이스 설명",
|
||||
descriptionPlaceholder: "스페이스 설명을 입력하세요(선택사항).",
|
||||
avatarPickerHint: "공유 공간 아바타로 이모티콘을 선택하세요",
|
||||
description: "공유 공간 설명",
|
||||
descriptionPlaceholder: "공유 공간 설명을 입력하세요(선택사항).",
|
||||
noDescription: "아직 설명이 없습니다",
|
||||
members: "회원",
|
||||
memberCount: "회원 수",
|
||||
@@ -5092,7 +5092,7 @@ export default {
|
||||
inviteCodePlaceholder: "초대코드를 입력해주세요",
|
||||
inviteCodeRequired: "초대코드를 입력해주세요",
|
||||
inviteCodeTip:
|
||||
"이 초대 코드를 다른 사람들과 공유하면 초대 코드를 통해 스페이스에 참여할 수 있습니다.",
|
||||
"이 초대 코드를 다른 사람들과 공유하면 초대 코드를 통해 공유 공간에 참여할 수 있습니다.",
|
||||
refreshInviteCode: "초대 코드 새로 고침",
|
||||
inviteCodeRefreshed: "초대 코드가 새로 고쳐졌습니다.",
|
||||
inviteCodeRefreshFailed: "초대 코드를 새로 고치지 못했습니다.",
|
||||
@@ -5104,39 +5104,39 @@ export default {
|
||||
cannotManage: "현재 워크스페이스 역할이 부족하여 공유 공간을 관리할 수 없습니다",
|
||||
},
|
||||
join: {
|
||||
title: "스페이스에 참여하기",
|
||||
joining: "스페이스에 참여하는 중..",
|
||||
success: "성공적으로 스페이스에 합류했습니다!",
|
||||
failed: "스페이스에 참여하지 못했습니다.",
|
||||
title: "공유 공간에 참여하기",
|
||||
joining: "공유 공간에 참여하는 중..",
|
||||
success: "성공적으로 공유 공간에 합류했습니다!",
|
||||
failed: "공유 공간에 참여하지 못했습니다.",
|
||||
noCode: "초대 코드를 찾을 수 없습니다",
|
||||
goToOrganizations: "스페이스 목록으로 이동",
|
||||
confirmTitle: "스페이스에 참여하려면 확인하세요.",
|
||||
goToOrganizations: "공유 공간 목록으로 이동",
|
||||
confirmTitle: "공유 공간에 참여하려면 확인하세요.",
|
||||
confirm: "가입 확인",
|
||||
preview: "미리보기 및 참여",
|
||||
memberCount: "{count} 회원",
|
||||
shareCount: "{count} 공유 지식베이스",
|
||||
agentShareCount: "{count} 에이전트",
|
||||
alreadyMember: "귀하는 이미 이 스페이스의 회원입니다.",
|
||||
alreadyMember: "귀하는 이미 이 공유 공간의 회원입니다.",
|
||||
invalidCode: "잘못된 초대 코드",
|
||||
byInviteCode: "초대코드를 입력하세요",
|
||||
searchSpaces: "검색 스페이스",
|
||||
searchSpaces: "공유 공간 검색",
|
||||
searchSpacesDesc:
|
||||
"검색이 가능한 스페이스를 찾아보거나 검색해 보세요. 초대코드 없이도 참여할 수 있습니다.",
|
||||
searchSpacesPlaceholder: "스페이스 이름, 설명 또는 스페이스 ID로 검색",
|
||||
spaceId: "스페이스ID",
|
||||
noSearchResult: "일치하는 스페이스를 찾을 수 없습니다.",
|
||||
"검색이 가능한 공유 공간을 찾아보거나 검색해 보세요. 초대코드 없이도 참여할 수 있습니다.",
|
||||
searchSpacesPlaceholder: "공유 공간 이름, 설명 또는 ID로 검색",
|
||||
spaceId: "공유 공간 ID",
|
||||
noSearchResult: "일치하는 공유 공간을 찾을 수 없습니다.",
|
||||
noSearchableSpaces:
|
||||
"현재 검색 가능한 공개 스페이스가 없거나, 키워드를 입력하여 검색하실 수 있습니다.",
|
||||
"현재 검색 가능한 공개 공유 공간이 없거나, 키워드를 입력하여 검색하실 수 있습니다.",
|
||||
membersWithLimit: "{current}/{limit} 회원",
|
||||
memberLimitReached: "회원이 꽉 찼습니다.",
|
||||
backToSearch: "검색으로 돌아가기",
|
||||
},
|
||||
invite: {
|
||||
loading: "로드 중..",
|
||||
previewTitle: "스페이스에 참여하기",
|
||||
previewInfo: "스페이스개요",
|
||||
previewTitle: "공유 공간에 참여하기",
|
||||
previewInfo: "공유 공간 개요",
|
||||
inputDesc:
|
||||
"초대코드를 입력하거나 초대링크에 초대코드를 붙여넣고 스페이스정보를 확인 후 참여하세요",
|
||||
"초대코드를 입력하거나 초대링크에 초대코드를 붙여넣고 공유 공간 정보를 확인 후 참여하세요",
|
||||
previewAction: "확인하다",
|
||||
primaryJoin: "참여",
|
||||
invalidTitle: "잘못된 초대",
|
||||
@@ -5145,10 +5145,10 @@ export default {
|
||||
members: "회원",
|
||||
knowledgeBases: "지식베이스",
|
||||
agents: "에이전트",
|
||||
alreadyMember: "귀하는 이미 이 스페이스의 회원입니다.",
|
||||
alreadyMember: "귀하는 이미 이 공유 공간의 회원입니다.",
|
||||
confirmJoin: "가입 확인",
|
||||
submitRequest: "가입 신청",
|
||||
requireApprovalTip: "이 스페이스에 참여하려면 관리자의 검토가 필요합니다.",
|
||||
requireApprovalTip: "이 공유 공간에 참여하려면 관리자의 검토가 필요합니다.",
|
||||
approvalLabel: "가입방법",
|
||||
needApproval: "검토 필요",
|
||||
noApproval: "검토가 필요하지 않습니다.",
|
||||
@@ -5157,33 +5157,33 @@ export default {
|
||||
selectRole: "역할 선택",
|
||||
messagePlaceholder: "선택사항 : 지원서 설명(자기소개, 입사이유 등)",
|
||||
applicationNote: "신청방법(선택)",
|
||||
joinSuccess: "성공적으로 스페이스에 합류했습니다!",
|
||||
joinSuccess: "성공적으로 공유 공간에 합류했습니다!",
|
||||
joinFailed: "참여하지 못했습니다. 나중에 다시 시도해 주세요.",
|
||||
requestSubmitted: "신청서가 제출되었습니다. 관리자의 검토를 기다려주세요.",
|
||||
requestFailed: "신청서 제출에 실패했습니다. 나중에 다시 시도해 주세요.",
|
||||
viewOrganization: "스페이스 보기",
|
||||
viewOrganization: "공유 공간 보기",
|
||||
},
|
||||
leave: "스페이스 나가기",
|
||||
leaveConfirm: "정말로 이 스페이스를 나가시겠습니까?",
|
||||
leaveConfirmTitle: "스페이스 나가기",
|
||||
leave: "공유 공간 나가기",
|
||||
leaveConfirm: "정말로 이 공유 공간을 나가시겠습니까?",
|
||||
leaveConfirmTitle: "공유 공간 나가기",
|
||||
leaveConfirmMessage:
|
||||
'정말로 "{name}" 스페이스에서 나가시겠습니까? 로그아웃한 후에는 이 스페이스에서 공유하는 지식베이스에 액세스할 수 없습니다.',
|
||||
leaveSuccess: "스페이스를 나갔습니다.",
|
||||
leaveFailed: "스페이스를 종료하지 못했습니다.",
|
||||
deleteConfirm: "정말로 이 스페이스를 삭제하시겠습니까? 이 작업은 취소할 수 없습니다.",
|
||||
deleteConfirmTitle: "스페이스 삭제",
|
||||
'정말로 "{name}" 공유 공간에서 나가시겠습니까? 나간 후에는 이 공유 공간에서 공유하는 지식베이스에 액세스할 수 없습니다.',
|
||||
leaveSuccess: "공유 공간을 나갔습니다.",
|
||||
leaveFailed: "공유 공간을 나가지 못했습니다.",
|
||||
deleteConfirm: "정말로 이 공유 공간을 삭제하시겠습니까? 이 작업은 취소할 수 없습니다.",
|
||||
deleteConfirmTitle: "공유 공간 삭제",
|
||||
deleteConfirmMessage:
|
||||
'"{name}" 스페이스를 삭제하시겠습니까? 삭제 후에는 모든 구성원이 제거되며 이 작업은 되돌릴 수 없습니다.',
|
||||
deleteSuccess: "스페이스가 삭제되었습니다.",
|
||||
deleteFailed: "스페이스를 삭제하지 못했습니다.",
|
||||
createSuccess: "스페이스가 생성되었습니다.",
|
||||
createFailed: "스페이스를 만들지 못했습니다.",
|
||||
joinSuccess: "스페이스에 성공적으로 참여했습니다.",
|
||||
joinFailed: "스페이스에 참여하지 못했습니다.",
|
||||
'"{name}" 공유 공간을 삭제하시겠습니까? 삭제 후에는 모든 구성원이 제거되며 이 작업은 되돌릴 수 없습니다.',
|
||||
deleteSuccess: "공유 공간이 삭제되었습니다.",
|
||||
deleteFailed: "공유 공간을 삭제하지 못했습니다.",
|
||||
createSuccess: "공유 공간이 생성되었습니다.",
|
||||
createFailed: "공유 공간을 만들지 못했습니다.",
|
||||
joinSuccess: "공유 공간에 성공적으로 참여했습니다.",
|
||||
joinFailed: "공유 공간에 참여하지 못했습니다.",
|
||||
manageMembers: "회원관리",
|
||||
noMembers: "아직 회원이 없습니다.",
|
||||
members: {
|
||||
listTitle: "스페이스 구성원",
|
||||
listTitle: "공유 공간 구성원",
|
||||
searchPlaceholder: "구성원 검색…",
|
||||
loading: "구성원 로딩 중…",
|
||||
emptySearch: "「{q}」와(과) 일치하는 구성원이 없습니다",
|
||||
@@ -5227,18 +5227,18 @@ export default {
|
||||
roleUpdateFailed: "역할을 업데이트하지 못했습니다.",
|
||||
memberRemoved: "회원이 삭제되었습니다.",
|
||||
memberRemoveFailed: "구성원을 제거하지 못했습니다.",
|
||||
empty: "아직 공유 스페이스에 참여하지 않았습니다.",
|
||||
emptyDesc: "초대 코드를 사용하여 스페이스를 만들거나 기존 스페이스에 참여하세요.",
|
||||
empty: "아직 공유 공간에 참여하지 않았습니다.",
|
||||
emptyDesc: "초대 코드를 사용하여 공유 공간을 만들거나 기존 공유 공간에 참여하세요.",
|
||||
all: "모두",
|
||||
createdByMe: "내가 생성한",
|
||||
joinedByMe: "내가 참여한",
|
||||
createdTag: "생성",
|
||||
joinedTag: "참여",
|
||||
joinedLabel: "이미 가입했습니다",
|
||||
emptyCreated: "아직 공유 스페이스를 만들지 않았습니다.",
|
||||
emptyCreatedDesc: '새 스페이스를 만들려면 "스페이스 만들기"를 클릭하세요.',
|
||||
emptyJoined: "아직 공유 스페이스에 참여하지 않았습니다.",
|
||||
emptyJoinedDesc: "초대 코드를 통해 기존 스페이스에 참여하기",
|
||||
emptyCreated: "아직 공유 공간를 만들지 않았습니다.",
|
||||
emptyCreatedDesc: '새 공유 공간을 만들려면 "공유 공간 만들기"를 클릭하세요.',
|
||||
emptyJoined: "아직 공유 공간에 참여하지 않았습니다.",
|
||||
emptyJoinedDesc: "초대 코드를 통해 기존 공유 공간에 참여하기",
|
||||
role: {
|
||||
admin: "관리자",
|
||||
editor: "편집자",
|
||||
@@ -5250,34 +5250,34 @@ export default {
|
||||
removeMemberConfirm: '"{name}" 구성원을 삭제하시겠습니까?',
|
||||
removeMember: "회원 삭제",
|
||||
shareKBTip:
|
||||
"지식베이스 목록에서 지식베이스를 선택하고 공유 버튼을 클릭하여 이 스페이스에 공유하세요.",
|
||||
"지식베이스 목록에서 지식베이스를 선택하고 공유 버튼을 클릭하여 이 공유 공간에 공유하세요.",
|
||||
},
|
||||
settings: {
|
||||
editTitle: "스페이스 설정",
|
||||
detailTitle: "스페이스 세부정보",
|
||||
myRoleDesc: "이 스페이스에서의 귀하의 역할은 귀하의 권한 범위를 결정합니다.",
|
||||
editTitle: "공유 공간 설정",
|
||||
detailTitle: "공유 공간 세부정보",
|
||||
myRoleDesc: "이 공유 공간에서의 귀하의 역할은 귀하의 권한 범위를 결정합니다.",
|
||||
membersDesc: "스페이스 구성원과 역할을 조회·관리합니다. 각 구성원은 하나의 워크스페이스를 의미하며, 같은 워크스페이스의 모든 사용자가 이 스페이스 접근 권한을 공유합니다.",
|
||||
permissionsIconHint: "역할별 권한 보기",
|
||||
sharedDesc: "이 스페이스에 공유된 모든 지식베이스 보기",
|
||||
sharedDesc: "이 공유 공간에 공유된 모든 지식베이스 보기",
|
||||
noSharedKB: "아직 공유 지식베이스가 없습니다.",
|
||||
noSharedKBTip:
|
||||
"지식베이스 소유자는 지식베이스 설정에서 이 스페이스에 지식베이스를 공유할 수 있습니다.",
|
||||
"지식베이스 소유자는 지식베이스 설정에서 이 공유 공간에 지식베이스를 공유할 수 있습니다.",
|
||||
sharedAgents: "공유 에이전트",
|
||||
noSharedAgents: "아직 공유 에이전트가 없습니다.",
|
||||
sharedAgentsDesc: "이 스페이스에 공유되었으며 대화에서 구성원이 사용할 수 있는 에이전트",
|
||||
sharedAgentsDesc: "이 공유 공간에 공유되었으며 대화에서 구성원이 사용할 수 있는 에이전트",
|
||||
sharedAgentsKbHint:
|
||||
"에이전트에 바인딩된 지식베이스는 구성원이 에이전트를 사용하여 대화하는 경우(읽기 전용) {'@'}에만 사용할 수 있으며 \"지식베이스 목록\"에는 표시되지 않습니다. 회원들이 목록에 있는 지식베이스를 보거나 편집할 수 있도록 하려면 이 스페이스에 별도로 지식베이스를 공유해 주세요.",
|
||||
"에이전트에 바인딩된 지식베이스는 구성원이 에이전트를 사용하여 대화하는 경우(읽기 전용) {'@'}에만 사용할 수 있으며 \"지식베이스 목록\"에는 표시되지 않습니다. 회원들이 목록에 있는 지식베이스를 보거나 편집할 수 있도록 하려면 이 공유 공간에 별도로 지식베이스를 공유해 주세요.",
|
||||
sharedAgentsKbHintShort:
|
||||
"에이전트 바인딩 지식은 대화 내에서만 읽을 수 있습니다. 목록에서 보거나 수정하고 싶으시면 지식베이스를 별도로 공유해주세요.",
|
||||
noSharedAgentsTip: "관리자는 에이전트 설정에서 이 스페이스에 에이전트를 공유할 수 있습니다.",
|
||||
sharePermissionLabel: "스페이스 허가",
|
||||
noSharedAgentsTip: "관리자는 에이전트 설정에서 이 공유 공간에 에이전트를 공유할 수 있습니다.",
|
||||
sharePermissionLabel: "공유 공간 권한",
|
||||
myPermissionLabel: "적용 권한",
|
||||
permissionCalcFormula:
|
||||
"스페이스 권한은 공유 시 설정되며, 적용 권한은 스페이스 권한과 내 역할 중 낮은 값입니다",
|
||||
"공유 공간 권한은 공유 시 설정되며, 적용 권한은 공유 공간 권한과 내 공유 공간 역할 중 낮은 값입니다",
|
||||
permissionCalcTip:
|
||||
"적용 권한은 스페이스 권한과 내 역할 중 낮은 값이며, 읽기 전용 구성원은 이 지식베이스에 읽기만 가능합니다.",
|
||||
"적용 권한은 공유 공간 권한과 내 공유 공간 역할 중 낮은 값이며, 읽기 전용 구성원은 이 지식베이스에 읽기만 가능합니다.",
|
||||
inviteMembers: "회원 초대",
|
||||
inviteMembersDesc: "초대 코드 또는 링크를 통해 다른 사람을 스페이스에 초대하세요.",
|
||||
inviteMembersDesc: "초대 코드 또는 링크를 통해 다른 사람을 공유 공간에 초대하세요.",
|
||||
inviteLink: "초대링크",
|
||||
inviteLinkValidity: "초대링크 유효기간",
|
||||
inviteLinkValidityDesc:
|
||||
@@ -5289,24 +5289,24 @@ export default {
|
||||
remainingValidity: "{n}일 남음",
|
||||
remainingValidityNever: "만료되지 않음",
|
||||
remainingValidityExpired: "만료됨",
|
||||
removeShareFromOrg: "스페이스에서 제거",
|
||||
removeShareFromOrg: "공유 공간에서 제거",
|
||||
removeShareConfirm:
|
||||
'이 스페이스에서 "{name}"을(를) 제거하시겠습니까? 제거 후에는 스페이스 구성원이 더 이상 지식베이스에 액세스할 수 없습니다.',
|
||||
'이 공유 공간에서 "{name}"을(를) 제거하시겠습니까? 제거 후에는 공유 공간 구성원이 더 이상 지식베이스에 액세스할 수 없습니다.',
|
||||
removeAgentShareConfirm:
|
||||
'이 스페이스에서 "{name}"을(를) 제거하시겠습니까? 제거 후에는 스페이스 구성원이 더 이상 에이전트에 액세스할 수 없습니다.',
|
||||
removeShareSuccess: "우주에서 제거됨",
|
||||
'이 공유 공간에서 "{name}"을(를) 제거하시겠습니까? 제거 후에는 공유 공간 구성원이 더 이상 에이전트에 액세스할 수 없습니다.',
|
||||
removeShareSuccess: "공유 공간에서 제거됨",
|
||||
removeShareFailed: "제거하지 못했습니다. 다시 시도해 주세요.",
|
||||
requireApproval: "검토 필요",
|
||||
requireApprovalDesc: "활성화되면 새 회원은 관리자의 검토를 받아야 합니다.",
|
||||
searchable: "공개 및 검색 가능",
|
||||
searchableDesc:
|
||||
'오픈 후, "Join Space" 검색 목록에 해당 스페이스가 나타납니다. 다른 사람도 초대코드 없이 검색하여 가입신청을 할 수 있습니다.',
|
||||
'오픈 후, "공유 공간 참여" 검색 목록에 해당 공유 공간이 나타납니다. 다른 사람도 초대코드 없이 검색하여 가입신청을 할 수 있습니다.',
|
||||
memberLimit: "최대 회원 수",
|
||||
memberLimitDesc: "한도를 초과한 후에는 새 회원을 추가할 수 없습니다. 제한 없이 0으로 설정",
|
||||
memberLimitPlaceholder: "0은 제한이 없음을 의미합니다.",
|
||||
memberLimitHint: "현재 회원 수: {count}",
|
||||
joinRequests: "가입 신청",
|
||||
joinRequestsDesc: "스페이스에 참여하려면 신청서를 검토하세요.",
|
||||
joinRequestsDesc: "공유 공간 참여 신청을 검토하세요.",
|
||||
noPendingRequests: "검토 대기중인 신청서가 없습니다.",
|
||||
pendingJoinRequestsBadge: "가입 신청 대기 중",
|
||||
pendingReview: "승인 대기 중",
|
||||
@@ -5325,39 +5325,39 @@ export default {
|
||||
editor: {
|
||||
navBasic: "기본정보",
|
||||
navPermissions: "권한 설명",
|
||||
navJoin: "스페이스에 참여하기",
|
||||
navJoin: "공유 공간에 참여하기",
|
||||
basicTitle: "기본정보",
|
||||
basicDesc: "회원 식별이 용이하도록 스페이스의 이름과 설명을 설정합니다.",
|
||||
basicDesc: "회원 식별이 용이하도록 공유 공간의 이름과 설명을 설정합니다.",
|
||||
nameTip: "구성원 식별이 용이하도록 팀 또는 프로젝트 이름 사용을 권장합니다.",
|
||||
descriptionTip: "회원들이 스페이스를 이해할 수 있도록 스페이스의 목적과 목표를 설명합니다.",
|
||||
descriptionTip: "회원들이 공유 공간을 이해할 수 있도록 공유 공간의 목적과 목표를 설명합니다.",
|
||||
permissionsTitle: "회원 권한",
|
||||
permissionsDesc:
|
||||
"지식베이스와 에이전트를 통해 스페이스 내 다양한 역할의 권한 범위를 이해합니다.",
|
||||
"지식베이스와 에이전트를 통해 공유 공간 내 다양한 역할의 권한 범위를 이해합니다.",
|
||||
permissionFeature: "권한 기능",
|
||||
fullAccess: "전체 권한",
|
||||
editAccess: "편집 권한",
|
||||
viewAccess: "읽기 전용 권한",
|
||||
adminPerm1: "스페이스 설정, 구성원, 에이전트과의 지식베이스 공유를 관리하세요.",
|
||||
adminPerm1: "공유 공간 설정, 구성원, 에이전트과의 지식베이스 공유를 관리하세요.",
|
||||
adminPerm2: "지식베이스와 에이전트 공유 및 관리",
|
||||
adminPerm3: "공유 지식베이스 콘텐츠 편집",
|
||||
adminPerm4: "지식베이스 보기 및 검색",
|
||||
useSharedAgentsPerm: "공유 에이전트 사용",
|
||||
shareKBPerm: "지식베이스를 스페이스에 공유",
|
||||
shareKBPerm: "지식베이스를 공유 공간에 공유",
|
||||
editorPerm1: "공유 지식베이스 콘텐츠 편집",
|
||||
editorPerm2: "지식베이스 보기 및 검색",
|
||||
editorPerm3: "스페이스 설정 및 구성원 관리",
|
||||
editorPerm3: "공유 공간 설정 및 구성원 관리",
|
||||
viewerPerm1: "지식베이스 보기 및 검색",
|
||||
viewerPerm2: "지식베이스 콘텐츠 편집",
|
||||
viewerPerm3: "스페이스 설정 관리",
|
||||
viewerPerm3: "공유 공간 설정 관리",
|
||||
ownerNote:
|
||||
"스페이스 작성자로서 귀하는 자동으로 스페이스의 관리자가 되며 모든 권한을 갖게 됩니다.",
|
||||
joinTitle: "스페이스에 참여하기",
|
||||
joinDesc: "초대 코드를 통해 기존 스페이스에 참여하고 지식베이스 및 에이전트에 액세스하세요.",
|
||||
joinIllustration: "스페이스 관리자가 제공한 초대 코드를 입력하여 참여하세요.",
|
||||
inviteCodeTip: "초대코드는 스페이스 관리자가 생성한 것이므로 관리자에게 문의하세요.",
|
||||
"공유 공간 작성자로서 귀하는 자동으로 공유 공간의 관리자가 되며 모든 권한을 갖게 됩니다.",
|
||||
joinTitle: "공유 공간에 참여하기",
|
||||
joinDesc: "초대 코드를 통해 기존 공유 공간에 참여하고 지식베이스 및 에이전트에 액세스하세요.",
|
||||
joinIllustration: "공유 공간 관리자가 제공한 초대 코드를 입력하여 참여하세요.",
|
||||
inviteCodeTip: "초대코드는 공유 공간 관리자가 생성한 것이므로 관리자에게 문의하세요.",
|
||||
howToGetCode: "초대코드는 어떻게 받나요?",
|
||||
step1: "참여하려는 스페이스의 관리자에게 문의하세요.",
|
||||
step2: "스페이스 초대 코드를 공유하도록 요청하세요.",
|
||||
step1: "참여하려는 공유 공간의 관리자에게 문의하세요.",
|
||||
step2: "공유 공간 초대 코드를 공유하도록 요청하세요.",
|
||||
step3: "위의 입력창에 초대코드를 붙여넣으세요",
|
||||
},
|
||||
upgrade: {
|
||||
@@ -5377,12 +5377,12 @@ export default {
|
||||
addMember: {
|
||||
button: "회원 추가",
|
||||
dialogTitle: "회원 추가",
|
||||
tip: "추가된 사용자는 즉시 스페이스 구성원이 되며, 스페이스에 공유된 지식베이스에 접근할 수 있습니다.",
|
||||
tip: "추가된 사용자는 즉시 공유 공간 구성원이 되며, 공유 공간에 공유된 지식베이스에 접근할 수 있습니다.",
|
||||
tipTenant: "구성원의 최소 단위는 워크스페이스입니다: 한 워크스페이스가 가입하면 해당 워크스페이스의 모든 사용자가 이 스페이스 접근 권한을 공유합니다. 아래 결과는 워크스페이스 기준으로 중복 제거됩니다.",
|
||||
searchUser: "사용자 선택",
|
||||
searchTenant: "워크스페이스 선택",
|
||||
searchPlaceholder: "검색하려면 사용자 이름이나 이메일을 입력하세요..",
|
||||
searchTenantPlaceholder: "워크스페이스 이름, 사용자 이름 또는 이메일로 검색...",
|
||||
searchTenantPlaceholder: "워크스페이스 이름으로 검색...",
|
||||
searchHint: "검색을 시작하려면 2자 이상 입력하세요.",
|
||||
searchTenantHint: "2자 이상 입력하세요. 결과는 워크스페이스 기준으로 중복 제거되며 이미 가입한 워크스페이스는 제외됩니다.",
|
||||
selectRole: "역할 할당",
|
||||
@@ -5396,16 +5396,16 @@ export default {
|
||||
},
|
||||
},
|
||||
share: {
|
||||
title: "스페이스에 공유",
|
||||
shareToSpace: "스페이스에 공유",
|
||||
shareModelToSpace: '"{name}"을 스페이스에 공유',
|
||||
shareAgentToSpace: '"{name}"을 스페이스에 공유',
|
||||
modelShareDesc: "스페이스 구성원이 모델을 사용할 수 있도록 모델을 스페이스에 공유합니다.",
|
||||
title: "공유 공간에 공유",
|
||||
shareToSpace: "공유 공간에 공유",
|
||||
shareModelToSpace: '"{name}"을 공유 공간에 공유',
|
||||
shareAgentToSpace: '"{name}"을 공유 공간에 공유',
|
||||
modelShareDesc: "공유 공간 구성원이 모델을 사용할 수 있도록 모델을 공유 공간에 공유합니다.",
|
||||
agentShareDesc:
|
||||
"스페이스 구성원이 에이전트를 사용할 수 있도록 에이전트를 스페이스에 공유합니다.",
|
||||
spaceAgentShareCountTip: "스페이스에 있는 공유 에이전트 수",
|
||||
selectOrg: "스페이스 선택",
|
||||
selectOrgPlaceholder: "공유할 스페이스를 선택해주세요",
|
||||
"공유 공간 구성원이 에이전트를 사용할 수 있도록 에이전트를 공유 공간에 공유합니다.",
|
||||
spaceAgentShareCountTip: "공유 공간에 있는 공유 에이전트 수",
|
||||
selectOrg: "공유 공간 선택",
|
||||
selectOrgPlaceholder: "공유할 공유 공간을 선택해주세요",
|
||||
permission: "권한",
|
||||
permissionTip:
|
||||
"편집 가능한 권한을 통해 구성원은 지식베이스 콘텐츠를 수정할 수 있으며, 읽기 전용 권한은 검색 및 Q&A만 허용합니다.",
|
||||
@@ -5414,14 +5414,14 @@ export default {
|
||||
unshareSuccess: "공유되지 않음",
|
||||
unshareFailed: "공유를 취소하지 못했습니다.",
|
||||
sharedTo: "공유된 스페이스",
|
||||
noShares: "아직 어떤 스페이스에도 공유되지 않았습니다.",
|
||||
searchPlaceholder: "스페이스 검색…",
|
||||
noShares: "아직 어떤 공유 공간에도 공유되지 않았습니다.",
|
||||
searchPlaceholder: "공유 공간 검색…",
|
||||
loading: "로딩 중…",
|
||||
emptySearch: "「{q}」와(과) 일치하는 스페이스가 없습니다",
|
||||
addShareDialogTitle: "스페이스에 공유",
|
||||
emptySearch: "「{q}」와(과) 일치하는 공유 공간이 없습니다",
|
||||
addShareDialogTitle: "공유 공간에 공유",
|
||||
unshareAction: "공유 해제",
|
||||
columns: {
|
||||
space: "스페이스",
|
||||
space: "공유 공간",
|
||||
permission: "권한",
|
||||
sharedAt: "공유 시간",
|
||||
operations: "작업",
|
||||
|
||||
+102
-102
@@ -5712,18 +5712,18 @@ export default {
|
||||
organization: {
|
||||
title: 'Shared Spaces',
|
||||
subtitle: 'Create or join shared spaces so multiple workspaces can collaborate and share knowledge bases and agents',
|
||||
createOrg: 'Create Space',
|
||||
createOrg: 'Создать общее пространство',
|
||||
createOrgShort: 'New',
|
||||
joinOrg: 'Join Space',
|
||||
joinOrg: 'Присоединиться к общему пространству',
|
||||
joinOrgShort: 'Join',
|
||||
name: 'Space Name',
|
||||
namePlaceholder: 'Enter space name',
|
||||
nameRequired: 'Please enter space name',
|
||||
avatar: 'Space Avatar',
|
||||
name: 'Название общего пространства',
|
||||
namePlaceholder: 'Введите название общего пространства',
|
||||
nameRequired: 'Введите название общего пространства',
|
||||
avatar: 'Аватар общего пространства',
|
||||
avatarClear: 'Clear',
|
||||
avatarPickerHint: 'Choose an emoji as space avatar',
|
||||
description: 'Description',
|
||||
descriptionPlaceholder: 'Enter space description (optional)',
|
||||
avatarPickerHint: 'Выберите эмодзи в качестве аватара общего пространства',
|
||||
description: 'Описание общего пространства',
|
||||
descriptionPlaceholder: 'Введите описание общего пространства (необязательно)',
|
||||
noDescription: 'No description',
|
||||
members: 'members',
|
||||
memberCount: 'Member count',
|
||||
@@ -5731,7 +5731,7 @@ export default {
|
||||
inviteCode: 'Invite Code',
|
||||
inviteCodePlaceholder: 'Enter invite code',
|
||||
inviteCodeRequired: 'Please enter invite code',
|
||||
inviteCodeTip: 'Share this invite code with others to let them join your space',
|
||||
inviteCodeTip: 'Поделитесь этим кодом приглашения с другими, чтобы они могли присоединиться к общему пространству',
|
||||
refreshInviteCode: 'Refresh Invite Code',
|
||||
inviteCodeRefreshed: 'Invite code refreshed',
|
||||
inviteCodeRefreshFailed: 'Failed to refresh invite code',
|
||||
@@ -5743,36 +5743,36 @@ export default {
|
||||
cannotManage: 'Недостаточно прав в текущем пространстве для управления общим пространством',
|
||||
},
|
||||
join: {
|
||||
title: 'Join Space',
|
||||
joining: 'Joining space...',
|
||||
success: 'Successfully joined space!',
|
||||
failed: 'Failed to join space',
|
||||
title: 'Присоединиться к общему пространству',
|
||||
joining: 'Присоединение к общему пространству...',
|
||||
success: 'Вы успешно присоединились к общему пространству!',
|
||||
failed: 'Не удалось присоединиться к общему пространству',
|
||||
noCode: 'Invite code not found',
|
||||
goToOrganizations: 'Go to Spaces',
|
||||
confirmTitle: 'Confirm Join Space',
|
||||
goToOrganizations: 'Перейти к списку общих пространств',
|
||||
confirmTitle: 'Подтвердите присоединение к общему пространству',
|
||||
confirm: 'Confirm Join',
|
||||
preview: 'Preview & Join',
|
||||
memberCount: '{count} members',
|
||||
shareCount: '{count} shared knowledge bases',
|
||||
agentShareCount: '{count} agents',
|
||||
alreadyMember: 'You are already a member of this space',
|
||||
alreadyMember: 'Вы уже являетесь участником этого общего пространства',
|
||||
invalidCode: 'Invalid invite code',
|
||||
byInviteCode: 'Enter invite code',
|
||||
searchSpaces: 'Search spaces',
|
||||
searchSpacesDesc: 'Browse or search spaces that are open for discovery; join without an invite code',
|
||||
searchSpacesPlaceholder: 'Search by space name, description or space ID',
|
||||
spaceId: 'Space ID',
|
||||
noSearchResult: 'No matching spaces',
|
||||
noSearchableSpaces: 'No discoverable spaces yet, or try a search',
|
||||
searchSpaces: 'Поиск общих пространств',
|
||||
searchSpacesDesc: 'Просматривайте или ищите открытые для поиска общие пространства и присоединяйтесь к ним без кода приглашения',
|
||||
searchSpacesPlaceholder: 'Поиск по названию, описанию или ID общего пространства',
|
||||
spaceId: 'ID общего пространства',
|
||||
noSearchResult: 'Подходящие общие пространства не найдены',
|
||||
noSearchableSpaces: 'Пока нет открытых для поиска общих пространств, или введите ключевые слова для поиска',
|
||||
membersWithLimit: '{current}/{limit} members',
|
||||
memberLimitReached: 'Full',
|
||||
backToSearch: 'Back to search'
|
||||
},
|
||||
invite: {
|
||||
loading: 'Loading...',
|
||||
previewTitle: 'Join Space',
|
||||
previewInfo: 'Space Overview',
|
||||
inputDesc: 'Enter the invite code (or paste from an invite link) to view the space and join',
|
||||
previewTitle: 'Присоединиться к общему пространству',
|
||||
previewInfo: 'Обзор общего пространства',
|
||||
inputDesc: 'Введите код приглашения (или вставьте его из ссылки-приглашения), чтобы просмотреть информацию об общем пространстве и присоединиться',
|
||||
previewAction: 'View',
|
||||
primaryJoin: 'Join',
|
||||
invalidTitle: 'Invalid Invitation',
|
||||
@@ -5781,10 +5781,10 @@ export default {
|
||||
members: 'Members',
|
||||
knowledgeBases: 'Knowledge Bases',
|
||||
agents: 'Agents',
|
||||
alreadyMember: 'You are already a member of this space',
|
||||
alreadyMember: 'Вы уже являетесь участником этого общего пространства',
|
||||
confirmJoin: 'Confirm Join',
|
||||
submitRequest: 'Request to Join',
|
||||
requireApprovalTip: 'This space requires admin approval to join',
|
||||
requireApprovalTip: 'Для присоединения к этому общему пространству требуется одобрение администратора',
|
||||
approvalLabel: 'Join method',
|
||||
needApproval: 'Requires approval',
|
||||
noApproval: 'No approval required',
|
||||
@@ -5793,31 +5793,31 @@ export default {
|
||||
selectRole: 'Select role',
|
||||
messagePlaceholder: 'Optional: message (e.g. intro or reason to join)',
|
||||
applicationNote: 'Application note (optional)',
|
||||
joinSuccess: 'Successfully joined space!',
|
||||
joinSuccess: 'Вы успешно присоединились к общему пространству!',
|
||||
joinFailed: 'Failed to join, please try again',
|
||||
requestSubmitted: 'Request submitted, please wait for admin approval',
|
||||
requestFailed: 'Failed to submit request, please try again',
|
||||
viewOrganization: 'View Space'
|
||||
viewOrganization: 'Просмотреть общее пространство'
|
||||
},
|
||||
leave: 'Leave Space',
|
||||
leaveConfirm: 'Are you sure you want to leave this space?',
|
||||
leaveConfirmTitle: 'Leave Space',
|
||||
leaveConfirmMessage: 'Are you sure you want to leave "{name}"? You will lose access to shared knowledge bases.',
|
||||
leaveSuccess: 'Left space successfully',
|
||||
leaveFailed: 'Failed to leave space',
|
||||
deleteConfirm: 'Are you sure you want to delete this space? This action cannot be undone.',
|
||||
deleteConfirmTitle: 'Delete Space',
|
||||
deleteConfirmMessage: 'Are you sure you want to delete "{name}"? All members will be removed. This action cannot be undone.',
|
||||
deleteSuccess: 'Space deleted',
|
||||
deleteFailed: 'Failed to delete space',
|
||||
createSuccess: 'Space created successfully',
|
||||
createFailed: 'Failed to create space',
|
||||
joinSuccess: 'Joined space successfully',
|
||||
joinFailed: 'Failed to join space',
|
||||
leave: 'Покинуть общее пространство',
|
||||
leaveConfirm: 'Вы уверены, что хотите покинуть это общее пространство?',
|
||||
leaveConfirmTitle: 'Покинуть общее пространство',
|
||||
leaveConfirmMessage: 'Вы уверены, что хотите покинуть общее пространство «{name}»? После выхода вы потеряете доступ к базам знаний, которыми поделились в этом общем пространстве.',
|
||||
leaveSuccess: 'Вы покинули общее пространство',
|
||||
leaveFailed: 'Не удалось покинуть общее пространство',
|
||||
deleteConfirm: 'Вы уверены, что хотите удалить это общее пространство? Это действие необратимо.',
|
||||
deleteConfirmTitle: 'Удалить общее пространство',
|
||||
deleteConfirmMessage: 'Вы уверены, что хотите удалить общее пространство «{name}»? Все участники будут удалены. Это действие необратимо.',
|
||||
deleteSuccess: 'Общее пространство удалено',
|
||||
deleteFailed: 'Не удалось удалить общее пространство',
|
||||
createSuccess: 'Общее пространство успешно создано',
|
||||
createFailed: 'Не удалось создать общее пространство',
|
||||
joinSuccess: 'Вы успешно присоединились к общему пространству',
|
||||
joinFailed: 'Не удалось присоединиться к общему пространству',
|
||||
manageMembers: 'Manage Members',
|
||||
noMembers: 'No members',
|
||||
members: {
|
||||
listTitle: 'Space members',
|
||||
listTitle: 'Участники общего пространства',
|
||||
searchPlaceholder: 'Search members…',
|
||||
loading: 'Loading members…',
|
||||
emptySearch: 'No members matching "{q}"',
|
||||
@@ -5861,18 +5861,18 @@ export default {
|
||||
roleUpdateFailed: 'Failed to update role',
|
||||
memberRemoved: 'Member removed',
|
||||
memberRemoveFailed: 'Failed to remove member',
|
||||
empty: 'You have not joined any shared space yet',
|
||||
emptyDesc: 'Create a space or join an existing one with an invite code',
|
||||
empty: 'Вы ещё не присоединились ни к одному общему пространству',
|
||||
emptyDesc: 'Создайте общее пространство или присоединитесь к существующему по коду приглашения',
|
||||
all: 'All',
|
||||
createdByMe: 'Created by me',
|
||||
joinedByMe: 'Joined',
|
||||
createdTag: 'Created',
|
||||
joinedTag: 'Joined',
|
||||
joinedLabel: 'Joined',
|
||||
emptyCreated: 'You have not created any space yet',
|
||||
emptyCreatedDesc: 'Click "Create Space" to create one',
|
||||
emptyJoined: 'You have not joined any space yet',
|
||||
emptyJoinedDesc: 'Join an existing space with an invite code',
|
||||
emptyCreated: 'Вы ещё не создали ни одного общего пространства',
|
||||
emptyCreatedDesc: 'Нажмите «Создать общее пространство», чтобы создать новое',
|
||||
emptyJoined: 'Вы ещё не присоединились ни к одному общему пространству',
|
||||
emptyJoinedDesc: 'Присоединитесь к существующему общему пространству по коду приглашения',
|
||||
role: {
|
||||
admin: 'Admin',
|
||||
editor: 'Editor',
|
||||
@@ -5883,29 +5883,29 @@ export default {
|
||||
removeMemberTitle: 'Remove Member',
|
||||
removeMemberConfirm: 'Are you sure you want to remove "{name}"?',
|
||||
removeMember: 'Remove Member',
|
||||
shareKBTip: 'Go to knowledge base list, select a knowledge base and click share to share it to this space'
|
||||
shareKBTip: 'В списке баз знаний выберите базу знаний и нажмите кнопку «Поделиться», чтобы поделиться ею в этом общем пространстве'
|
||||
},
|
||||
settings: {
|
||||
editTitle: 'Space Settings',
|
||||
detailTitle: 'Space Details',
|
||||
myRoleDesc: 'Your role in this space determines your permissions',
|
||||
editTitle: 'Настройки общего пространства',
|
||||
detailTitle: 'Сведения об общем пространстве',
|
||||
myRoleDesc: 'Ваша роль в этом общем пространстве определяет объём ваших прав',
|
||||
membersDesc: 'Просмотр и управление участниками пространства и их ролями. Каждый участник представляет одно рабочее пространство: все его пользователи получают одинаковый доступ к общему пространству.',
|
||||
permissionsIconHint: 'Просмотр прав по ролям',
|
||||
sharedDesc: 'View all knowledge bases shared to this space',
|
||||
sharedDesc: 'Просмотр всех баз знаний, которыми поделились в этом общем пространстве',
|
||||
noSharedKB: 'No shared knowledge bases yet',
|
||||
noSharedKBTip: 'Knowledge base owners can share their knowledge bases to this space in KB settings',
|
||||
noSharedKBTip: 'Владельцы баз знаний могут поделиться ими в этом общем пространстве в настройках базы знаний',
|
||||
sharedAgents: 'Shared Agents',
|
||||
noSharedAgents: 'No shared agents yet',
|
||||
sharedAgentsDesc: 'Agents shared to this space; members can use them in chat',
|
||||
sharedAgentsKbHint: "Knowledge bases linked to an agent are only available (read-only) when members use that agent in a conversation (via {'@'}). They do not appear in the Knowledge Base list. To let members see or edit a knowledge base in the list, share that knowledge base to this space separately.",
|
||||
sharedAgentsDesc: 'Агенты, которыми поделились в этом общем пространстве; участники могут использовать их в чате',
|
||||
sharedAgentsKbHint: "Базы знаний, привязанные к агенту, доступны (только для чтения) лишь когда участники используют этого агента в разговоре (через {'@'}). Они не отображаются в «Списке баз знаний». Чтобы участники могли видеть или редактировать базу знаний в списке, поделитесь этой базой знаний в этом общем пространстве отдельно.",
|
||||
sharedAgentsKbHintShort: 'Agent-linked knowledge is read-only in chat; share the KB to this space if members should see or edit it in the list.',
|
||||
noSharedAgentsTip: 'Admins can share agents to this space from agent settings',
|
||||
sharePermissionLabel: 'Space permission',
|
||||
noSharedAgentsTip: 'Администраторы могут поделиться агентами в этом общем пространстве из настроек агента',
|
||||
sharePermissionLabel: 'Права в общем пространстве',
|
||||
myPermissionLabel: 'Effective',
|
||||
permissionCalcFormula: 'Space permission is set when sharing; effective permission is the lower of that and your space role',
|
||||
permissionCalcTip: 'Effective permission is the lower of space permission and your role here; viewers get at most read-only on this KB.',
|
||||
permissionCalcFormula: 'Права в общем пространстве задаются при предоставлении доступа; действующие права — это меньшее из прав в общем пространстве и вашей роли в общем пространстве',
|
||||
permissionCalcTip: 'Действующие права — это меньшее из прав в общем пространстве и вашей роли в нём; участники с ролью «только чтение» получают не более чем доступ на чтение к этой базе знаний.',
|
||||
inviteMembers: 'Invite Members',
|
||||
inviteMembersDesc: 'Invite others to join the space via code or link',
|
||||
inviteMembersDesc: 'Приглашайте других присоединиться к общему пространству по коду или ссылке',
|
||||
inviteLink: 'Invite Link',
|
||||
inviteLinkValidity: 'Invite link validity',
|
||||
inviteLinkValidityDesc: 'Validity period for newly generated invite links',
|
||||
@@ -5916,21 +5916,21 @@ export default {
|
||||
remainingValidity: 'Expires in {n} days',
|
||||
remainingValidityNever: 'Never expire',
|
||||
remainingValidityExpired: 'Expired',
|
||||
removeShareFromOrg: 'Remove from space',
|
||||
removeShareConfirm: 'Remove "{name}" from this space? Members will no longer have access to this knowledge base.',
|
||||
removeAgentShareConfirm: 'Remove "{name}" from this space? Members will no longer have access to this agent.',
|
||||
removeShareSuccess: 'Removed from space',
|
||||
removeShareFromOrg: 'Удалить из общего пространства',
|
||||
removeShareConfirm: 'Удалить «{name}» из этого общего пространства? После удаления участники общего пространства потеряют доступ к этой базе знаний.',
|
||||
removeAgentShareConfirm: 'Удалить «{name}» из этого общего пространства? После удаления участники общего пространства потеряют доступ к этому агенту.',
|
||||
removeShareSuccess: 'Удалено из общего пространства',
|
||||
removeShareFailed: 'Failed to remove, please try again',
|
||||
requireApproval: 'Require Approval',
|
||||
requireApprovalDesc: 'When enabled, new members need admin approval to join',
|
||||
searchable: 'Open for search',
|
||||
searchableDesc: 'When enabled, this space appears in the "Join Space" search list; others can search and request to join without an invite code',
|
||||
searchableDesc: 'Когда включено, общее пространство появляется в списке поиска «Присоединиться к общему пространству»; другие могут находить его и подавать заявку на вступление без кода приглашения',
|
||||
memberLimit: 'Member limit',
|
||||
memberLimitDesc: 'No new members can be added when the limit is reached; 0 means unlimited',
|
||||
memberLimitPlaceholder: '0 = unlimited',
|
||||
memberLimitHint: 'Current members: {count}',
|
||||
joinRequests: 'Join Requests',
|
||||
joinRequestsDesc: 'Review pending requests to join the space',
|
||||
joinRequestsDesc: 'Рассмотрение заявок на вступление в общее пространство',
|
||||
noPendingRequests: 'No pending requests',
|
||||
pendingJoinRequestsBadge: 'Pending join requests to review',
|
||||
pendingReview: 'Pending',
|
||||
@@ -5949,37 +5949,37 @@ export default {
|
||||
editor: {
|
||||
navBasic: 'Basic Info',
|
||||
navPermissions: 'Permissions',
|
||||
navJoin: 'Join Space',
|
||||
navJoin: 'Присоединиться к общему пространству',
|
||||
basicTitle: 'Basic Information',
|
||||
basicDesc: 'Set the space name and description for easy identification',
|
||||
basicDesc: 'Задайте название и описание общего пространства, чтобы участникам было легче его узнавать',
|
||||
nameTip: 'Use your team or project name for easy identification',
|
||||
descriptionTip: 'Describe the purpose and goals of the space',
|
||||
descriptionTip: 'Опишите назначение и цели общего пространства, чтобы участники лучше его понимали',
|
||||
permissionsTitle: 'Member Permissions',
|
||||
permissionsDesc: 'Understand the permission scope of different roles for knowledge bases and agents in the space',
|
||||
permissionsDesc: 'Узнайте объём прав разных ролей на базы знаний и агентов в общем пространстве',
|
||||
permissionFeature: 'Permission Feature',
|
||||
fullAccess: 'Full Access',
|
||||
editAccess: 'Edit Access',
|
||||
viewAccess: 'View Only',
|
||||
adminPerm1: 'Manage space settings, members, and knowledge base & agent sharing',
|
||||
adminPerm1: 'Управление настройками общего пространства, участниками и общим доступом к базам знаний и агентам',
|
||||
adminPerm2: 'Share and manage knowledge bases and agents',
|
||||
adminPerm3: 'Edit shared knowledge base content',
|
||||
adminPerm4: 'View and search knowledge bases',
|
||||
useSharedAgentsPerm: 'Use shared agents',
|
||||
shareKBPerm: 'Share knowledge bases to space',
|
||||
shareKBPerm: 'Предоставлять доступ к базам знаний в общем пространстве',
|
||||
editorPerm1: 'Edit shared knowledge base content',
|
||||
editorPerm2: 'View and search knowledge bases',
|
||||
editorPerm3: 'Manage space settings and members',
|
||||
editorPerm3: 'Управление настройками и участниками общего пространства',
|
||||
viewerPerm1: 'View and search knowledge bases',
|
||||
viewerPerm2: 'Edit knowledge base content',
|
||||
viewerPerm3: 'Manage space settings',
|
||||
ownerNote: 'As the space creator, you will automatically become an admin with full permissions.',
|
||||
joinTitle: 'Join Space',
|
||||
joinDesc: 'Join an existing space with an invite code to access shared knowledge bases and agents',
|
||||
joinIllustration: 'Enter the invite code provided by the space admin to join',
|
||||
inviteCodeTip: 'The invite code is generated by space admins, please ask them for it',
|
||||
viewerPerm3: 'Управление настройками общего пространства',
|
||||
ownerNote: 'Как создатель общего пространства, вы автоматически становитесь администратором с полными правами.',
|
||||
joinTitle: 'Присоединиться к общему пространству',
|
||||
joinDesc: 'Присоединитесь к существующему общему пространству по коду приглашения, чтобы получить доступ к базам знаний и агентам',
|
||||
joinIllustration: 'Введите код приглашения, предоставленный администратором общего пространства, чтобы присоединиться',
|
||||
inviteCodeTip: 'Код приглашения создаётся администраторами общего пространства, запросите его у них',
|
||||
howToGetCode: 'How to get an invite code?',
|
||||
step1: 'Contact the admin of the space you want to join',
|
||||
step2: 'Ask them to share the space invite code',
|
||||
step1: 'Свяжитесь с администратором общего пространства, к которому хотите присоединиться',
|
||||
step2: 'Попросите их поделиться кодом приглашения общего пространства',
|
||||
step3: 'Paste the invite code in the input field above'
|
||||
},
|
||||
upgrade: {
|
||||
@@ -5999,12 +5999,12 @@ export default {
|
||||
addMember: {
|
||||
button: 'Add Member',
|
||||
dialogTitle: 'Add Member',
|
||||
tip: 'Added users will immediately become space members and can access shared knowledge bases.',
|
||||
tip: 'Добавленные пользователи сразу станут участниками общего пространства и получат доступ к базам знаний, которыми поделились в общем пространстве.',
|
||||
tipTenant: 'Членство задаётся на уровне пространства: после присоединения пространства все его пользователи получают доступ к этому пространству. Результаты ниже сгруппированы по пространству.',
|
||||
searchUser: 'Select User',
|
||||
searchTenant: 'Выбрать пространство',
|
||||
searchPlaceholder: 'Search by username or email...',
|
||||
searchTenantPlaceholder: 'Поиск по имени пространства, пользователя или email...',
|
||||
searchTenantPlaceholder: 'Поиск по имени пространства...',
|
||||
searchHint: 'Type at least 2 characters to search',
|
||||
searchTenantHint: 'Введите не менее 2 символов; результаты сгруппированы по пространству и не включают уже добавленных.',
|
||||
selectRole: 'Assign Role',
|
||||
@@ -6018,15 +6018,15 @@ export default {
|
||||
}
|
||||
},
|
||||
share: {
|
||||
title: 'Share Knowledge Base',
|
||||
shareToSpace: 'Share to space',
|
||||
shareModelToSpace: 'Share "{name}" to space',
|
||||
shareAgentToSpace: 'Share "{name}" to space',
|
||||
modelShareDesc: 'Share this model to a space so members can use it',
|
||||
agentShareDesc: 'Share this agent to a space so members can use it',
|
||||
spaceAgentShareCountTip: 'Number of agents shared to this space',
|
||||
selectOrg: 'Select Space',
|
||||
selectOrgPlaceholder: 'Select a space to share with',
|
||||
title: 'Поделиться в общем пространстве',
|
||||
shareToSpace: 'Поделиться в общем пространстве',
|
||||
shareModelToSpace: 'Поделиться «{name}» в общем пространстве',
|
||||
shareAgentToSpace: 'Поделиться «{name}» в общем пространстве',
|
||||
modelShareDesc: 'Поделитесь моделью в общем пространстве, чтобы участники общего пространства могли её использовать',
|
||||
agentShareDesc: 'Поделитесь агентом в общем пространстве, чтобы участники общего пространства могли его использовать',
|
||||
spaceAgentShareCountTip: 'Количество агентов, которыми поделились в этом общем пространстве',
|
||||
selectOrg: 'Выберите общее пространство',
|
||||
selectOrgPlaceholder: 'Выберите общее пространство для предоставления доступа',
|
||||
permission: 'Permission',
|
||||
permissionTip: 'Editable permission allows members to modify knowledge base content, Read-only permission only allows search and Q&A',
|
||||
shareSuccess: 'Knowledge base shared',
|
||||
@@ -6034,14 +6034,14 @@ export default {
|
||||
unshareSuccess: 'Share cancelled',
|
||||
unshareFailed: 'Failed to cancel share',
|
||||
sharedTo: 'Shared to',
|
||||
noShares: 'Not shared to any space yet',
|
||||
searchPlaceholder: 'Search spaces…',
|
||||
noShares: 'Пока не предоставлен доступ ни в одном общем пространстве',
|
||||
searchPlaceholder: 'Поиск общих пространств…',
|
||||
loading: 'Loading…',
|
||||
emptySearch: 'No spaces matching "{q}"',
|
||||
addShareDialogTitle: 'Share to space',
|
||||
emptySearch: 'Не найдено общих пространств по запросу «{q}»',
|
||||
addShareDialogTitle: 'Поделиться в общем пространстве',
|
||||
unshareAction: 'Remove share',
|
||||
columns: {
|
||||
space: 'Space',
|
||||
space: 'Общее пространство',
|
||||
permission: 'Permission',
|
||||
sharedAt: 'Shared',
|
||||
operations: 'Actions',
|
||||
|
||||
@@ -5123,26 +5123,25 @@ export default {
|
||||
organization: {
|
||||
title: "共享空间",
|
||||
subtitle: "创建或加入共享空间,让多个空间互相协作,共享知识库与智能体",
|
||||
createOrg: "创建空间",
|
||||
createOrg: "创建共享空间",
|
||||
createOrgShort: "新建",
|
||||
joinOrg: "加入空间",
|
||||
joinOrg: "加入共享空间",
|
||||
joinOrgShort: "加入",
|
||||
name: "空间名称",
|
||||
namePlaceholder: "请输入空间名称",
|
||||
nameRequired: "请输入空间名称",
|
||||
avatar: "空间头像",
|
||||
name: "共享空间名称",
|
||||
namePlaceholder: "请输入共享空间名称",
|
||||
nameRequired: "请输入共享空间名称",
|
||||
avatar: "共享空间头像",
|
||||
avatarClear: "清除",
|
||||
avatarPickerHint: "选择 Emoji 作为空间头像",
|
||||
description: "空间描述",
|
||||
descriptionPlaceholder: "请输入空间描述(选填)",
|
||||
avatarPickerHint: "选择 Emoji 作为共享空间头像",
|
||||
description: "共享空间描述",
|
||||
descriptionPlaceholder: "请输入共享空间描述(选填)",
|
||||
noDescription: "暂无描述",
|
||||
members: "成员",
|
||||
memberCount: "成员数量",
|
||||
owner: "创建者",
|
||||
inviteCode: "邀请码",
|
||||
inviteCodePlaceholder: "请输入邀请码",
|
||||
inviteCodeRequired: "请输入邀请码",
|
||||
inviteCodeTip: "分享此邀请码给他人,他们可以通过邀请码加入空间",
|
||||
inviteCodeTip: "分享此邀请码给他人,他们可以通过邀请码加入共享空间",
|
||||
refreshInviteCode: "刷新邀请码",
|
||||
inviteCodeRefreshed: "邀请码已刷新",
|
||||
inviteCodeRefreshFailed: "刷新邀请码失败",
|
||||
@@ -5154,36 +5153,36 @@ export default {
|
||||
cannotManage: "当前空间角色不足,无法管理共享空间",
|
||||
},
|
||||
join: {
|
||||
title: "加入空间",
|
||||
joining: "正在加入空间...",
|
||||
success: "成功加入空间!",
|
||||
failed: "加入空间失败",
|
||||
title: "加入共享空间",
|
||||
joining: "正在加入共享空间...",
|
||||
success: "成功加入共享空间!",
|
||||
failed: "加入共享空间失败",
|
||||
noCode: "未找到邀请码",
|
||||
goToOrganizations: "前往空间列表",
|
||||
confirmTitle: "确认加入空间",
|
||||
goToOrganizations: "前往共享空间列表",
|
||||
confirmTitle: "确认加入共享空间",
|
||||
confirm: "确认加入",
|
||||
preview: "预览并加入",
|
||||
memberCount: "{count} 个成员",
|
||||
shareCount: "{count} 个共享知识库",
|
||||
agentShareCount: "{count} 个智能体",
|
||||
alreadyMember: "您已经是该空间的成员",
|
||||
alreadyMember: "您已经是该共享空间的成员",
|
||||
invalidCode: "无效的邀请码",
|
||||
byInviteCode: "输入邀请码",
|
||||
searchSpaces: "搜索空间",
|
||||
searchSpacesDesc: "浏览或搜索已开放可被搜索的空间,无需邀请码即可加入",
|
||||
searchSpacesPlaceholder: "按空间名称、描述或空间ID搜索",
|
||||
spaceId: "空间ID",
|
||||
noSearchResult: "未找到匹配的空间",
|
||||
noSearchableSpaces: "暂无开放可被搜索的空间,或输入关键词搜索",
|
||||
searchSpaces: "搜索共享空间",
|
||||
searchSpacesDesc: "浏览或搜索已开放可被搜索的共享空间,无需邀请码即可加入",
|
||||
searchSpacesPlaceholder: "按共享空间名称、描述或 ID 搜索",
|
||||
spaceId: "共享空间ID",
|
||||
noSearchResult: "未找到匹配的共享空间",
|
||||
noSearchableSpaces: "暂无开放可被搜索的共享空间,或输入关键词搜索",
|
||||
membersWithLimit: "{current}/{limit} 成员",
|
||||
memberLimitReached: "成员已满",
|
||||
backToSearch: "返回搜索",
|
||||
},
|
||||
invite: {
|
||||
loading: "加载中...",
|
||||
previewTitle: "加入空间",
|
||||
previewInfo: "空间概览",
|
||||
inputDesc: "输入邀请码或粘贴邀请链接中的邀请码,查看空间信息后加入",
|
||||
previewTitle: "加入共享空间",
|
||||
previewInfo: "共享空间概览",
|
||||
inputDesc: "输入邀请码或粘贴邀请链接中的邀请码,查看共享空间信息后加入",
|
||||
previewAction: "查看",
|
||||
primaryJoin: "加入",
|
||||
invalidTitle: "无效邀请",
|
||||
@@ -5192,10 +5191,10 @@ export default {
|
||||
members: "成员",
|
||||
knowledgeBases: "知识库",
|
||||
agents: "智能体",
|
||||
alreadyMember: "您已经是该空间的成员",
|
||||
alreadyMember: "您已经是该共享空间的成员",
|
||||
confirmJoin: "确认加入",
|
||||
submitRequest: "申请加入",
|
||||
requireApprovalTip: "该空间需要管理员审核后才能加入",
|
||||
requireApprovalTip: "该共享空间需要管理员审核后才能加入",
|
||||
approvalLabel: "加入方式",
|
||||
needApproval: "需要审核",
|
||||
noApproval: "无需审核",
|
||||
@@ -5204,31 +5203,31 @@ export default {
|
||||
selectRole: "选择角色",
|
||||
messagePlaceholder: "选填:申请说明(如自我介绍或加入原因)",
|
||||
applicationNote: "申请说明(选填)",
|
||||
joinSuccess: "成功加入空间!",
|
||||
joinSuccess: "成功加入共享空间!",
|
||||
joinFailed: "加入失败,请稍后重试",
|
||||
requestSubmitted: "申请已提交,请等待管理员审核",
|
||||
requestFailed: "申请提交失败,请稍后重试",
|
||||
viewOrganization: "查看空间",
|
||||
viewOrganization: "查看共享空间",
|
||||
},
|
||||
leave: "退出空间",
|
||||
leaveConfirm: "确定要退出该空间吗?",
|
||||
leaveConfirmTitle: "退出空间",
|
||||
leaveConfirmMessage: "确定要退出空间「{name}」吗?退出后将无法访问该空间共享的知识库。",
|
||||
leaveSuccess: "已退出空间",
|
||||
leaveFailed: "退出空间失败",
|
||||
deleteConfirm: "确定要删除该空间吗?此操作不可撤销。",
|
||||
deleteConfirmTitle: "删除空间",
|
||||
deleteConfirmMessage: "确定要删除空间「{name}」吗?删除后所有成员将被移除,此操作不可撤销。",
|
||||
deleteSuccess: "空间已删除",
|
||||
deleteFailed: "删除空间失败",
|
||||
createSuccess: "空间创建成功",
|
||||
createFailed: "创建空间失败",
|
||||
joinSuccess: "成功加入空间",
|
||||
joinFailed: "加入空间失败",
|
||||
leave: "退出共享空间",
|
||||
leaveConfirm: "确定要退出该共享空间吗?",
|
||||
leaveConfirmTitle: "退出共享空间",
|
||||
leaveConfirmMessage: "确定要退出共享空间「{name}」吗?退出后将无法访问该共享空间共享的知识库。",
|
||||
leaveSuccess: "已退出共享空间",
|
||||
leaveFailed: "退出共享空间失败",
|
||||
deleteConfirm: "确定要删除该共享空间吗?此操作不可撤销。",
|
||||
deleteConfirmTitle: "删除共享空间",
|
||||
deleteConfirmMessage: "确定要删除共享空间「{name}」吗?删除后所有成员将被移除,此操作不可撤销。",
|
||||
deleteSuccess: "共享空间已删除",
|
||||
deleteFailed: "删除共享空间失败",
|
||||
createSuccess: "共享空间创建成功",
|
||||
createFailed: "创建共享空间失败",
|
||||
joinSuccess: "成功加入共享空间",
|
||||
joinFailed: "加入共享空间失败",
|
||||
manageMembers: "成员管理",
|
||||
noMembers: "暂无成员",
|
||||
members: {
|
||||
listTitle: "空间成员",
|
||||
listTitle: "共享空间成员",
|
||||
searchPlaceholder: "搜索成员…",
|
||||
loading: "加载成员中…",
|
||||
emptySearch: "未找到匹配「{q}」的成员",
|
||||
@@ -5273,7 +5272,7 @@ export default {
|
||||
memberRemoved: "成员已移除",
|
||||
memberRemoveFailed: "移除成员失败",
|
||||
empty: "您还没有加入任何共享空间",
|
||||
emptyDesc: "创建一个空间或通过邀请码加入现有空间",
|
||||
emptyDesc: "创建一个共享空间或通过邀请码加入现有共享空间",
|
||||
all: "全部",
|
||||
createdByMe: "我创建的",
|
||||
joinedByMe: "我加入的",
|
||||
@@ -5281,9 +5280,9 @@ export default {
|
||||
joinedTag: "加入",
|
||||
joinedLabel: "已加入",
|
||||
emptyCreated: "您还没有创建任何共享空间",
|
||||
emptyCreatedDesc: "点击「创建空间」创建一个新空间",
|
||||
emptyCreatedDesc: "点击「创建共享空间」创建一个新的共享空间",
|
||||
emptyJoined: "您还没有加入任何共享空间",
|
||||
emptyJoinedDesc: "通过邀请码加入现有空间",
|
||||
emptyJoinedDesc: "通过邀请码加入现有共享空间",
|
||||
role: {
|
||||
admin: "管理员",
|
||||
editor: "编辑",
|
||||
@@ -5294,29 +5293,29 @@ export default {
|
||||
removeMemberTitle: "移除成员",
|
||||
removeMemberConfirm: "确定要移除成员「{name}」吗?",
|
||||
removeMember: "移除成员",
|
||||
shareKBTip: "在知识库列表中选择知识库,点击共享按钮将其共享到此空间",
|
||||
shareKBTip: "在知识库列表中选择知识库,点击共享按钮将其共享到此共享空间",
|
||||
},
|
||||
settings: {
|
||||
editTitle: "空间设置",
|
||||
detailTitle: "空间详情",
|
||||
myRoleDesc: "您在此空间中的角色决定了您的权限范围",
|
||||
editTitle: "共享空间设置",
|
||||
detailTitle: "共享空间详情",
|
||||
myRoleDesc: "您在此共享空间中的角色决定了您的权限范围",
|
||||
membersDesc: "查看和管理共享空间成员、调整成员角色。成员的最小单位是空间——加入后该空间下的所有用户都将获得访问权限。",
|
||||
permissionsIconHint: "查看各角色权限说明",
|
||||
sharedDesc: "查看共享到此空间的所有知识库",
|
||||
sharedDesc: "查看共享到此共享空间的所有知识库",
|
||||
noSharedKB: "暂无共享的知识库",
|
||||
noSharedKBTip: "知识库拥有者可以在知识库设置中将其共享到此空间",
|
||||
noSharedKBTip: "知识库拥有者可以在知识库设置中将其共享到此共享空间",
|
||||
sharedAgents: "共享智能体",
|
||||
noSharedAgents: "暂无共享的智能体",
|
||||
sharedAgentsDesc: "已共享到本空间的智能体,成员可在对话中使用",
|
||||
sharedAgentsKbHint: "智能体绑定的知识库仅在成员使用该智能体对话时可 {'@'} 使用(只读),不会出现在「知识库列表」中。若需成员在列表中看到或编辑知识库,请单独将知识库共享到本空间。",
|
||||
sharedAgentsDesc: "已共享到本共享空间的智能体,成员可在对话中使用",
|
||||
sharedAgentsKbHint: "智能体绑定的知识库仅在成员使用该智能体对话时可 {'@'} 使用(只读),不会出现在「知识库列表」中。若需成员在列表中看到或编辑知识库,请单独将知识库共享到本共享空间。",
|
||||
sharedAgentsKbHintShort: "智能体绑定知识仅对话内只读;需在列表看到或编辑请单独共享知识库",
|
||||
noSharedAgentsTip: "管理员可将智能体从智能体设置中共享到本空间",
|
||||
sharePermissionLabel: "空间权限",
|
||||
noSharedAgentsTip: "管理员可将智能体从智能体设置中共享到本共享空间",
|
||||
sharePermissionLabel: "共享空间权限",
|
||||
myPermissionLabel: "生效权限",
|
||||
permissionCalcFormula: "空间权限为共享时设定;生效权限取空间权限与你的空间角色中较低值",
|
||||
permissionCalcTip: "生效权限取空间权限与你的空间角色中较低值;只读成员对此库最多只读。",
|
||||
permissionCalcFormula: "共享空间权限为共享时设定;生效权限取共享空间权限与你的共享空间角色中较低值",
|
||||
permissionCalcTip: "生效权限取共享空间权限与你的共享空间角色中较低值;只读成员对此库最多只读。",
|
||||
inviteMembers: "邀请成员",
|
||||
inviteMembersDesc: "通过邀请码或链接邀请他人加入空间",
|
||||
inviteMembersDesc: "通过邀请码或链接邀请他人加入共享空间",
|
||||
inviteLink: "邀请链接",
|
||||
inviteLinkValidity: "邀请链接有效期",
|
||||
inviteLinkValidityDesc: "新生成的邀请链接的有效期,仅影响之后刷新生成的链接",
|
||||
@@ -5327,21 +5326,21 @@ export default {
|
||||
remainingValidity: "剩余 {n} 天",
|
||||
remainingValidityNever: "永不过期",
|
||||
remainingValidityExpired: "已过期",
|
||||
removeShareFromOrg: "从空间中移除",
|
||||
removeShareConfirm: "确定将「{name}」从本空间中移除?移除后空间成员将无法再访问该知识库。",
|
||||
removeAgentShareConfirm: "确定将「{name}」从本空间中移除?移除后空间成员将无法再访问该智能体。",
|
||||
removeShareSuccess: "已从空间中移除",
|
||||
removeShareFromOrg: "从共享空间中移除",
|
||||
removeShareConfirm: "确定将「{name}」从本共享空间中移除?移除后共享空间成员将无法再访问该知识库。",
|
||||
removeAgentShareConfirm: "确定将「{name}」从本共享空间中移除?移除后共享空间成员将无法再访问该智能体。",
|
||||
removeShareSuccess: "已从共享空间中移除",
|
||||
removeShareFailed: "移除失败,请重试",
|
||||
requireApproval: "需要审核",
|
||||
requireApprovalDesc: "开启后,新成员加入需要管理员审核",
|
||||
searchable: "开放可被搜索",
|
||||
searchableDesc: "开启后,空间将出现在「加入空间」的搜索列表中,他人可搜索并申请加入,无需邀请码",
|
||||
searchableDesc: "开启后,共享空间将出现在「加入共享空间」的搜索列表中,他人可搜索并申请加入,无需邀请码",
|
||||
memberLimit: "成员数量上限",
|
||||
memberLimitDesc: "超过上限后无法再添加新成员;设为 0 表示不限制",
|
||||
memberLimitPlaceholder: "0 表示不限制",
|
||||
memberLimitHint: "当前成员数:{count}",
|
||||
joinRequests: "加入申请",
|
||||
joinRequestsDesc: "审核待加入空间的申请",
|
||||
joinRequestsDesc: "审核待加入共享空间的申请",
|
||||
noPendingRequests: "暂无待审核的申请",
|
||||
pendingJoinRequestsBadge: "有待审批的加入申请",
|
||||
pendingReview: "待审批",
|
||||
@@ -5360,37 +5359,37 @@ export default {
|
||||
editor: {
|
||||
navBasic: "基本信息",
|
||||
navPermissions: "权限说明",
|
||||
navJoin: "加入空间",
|
||||
navJoin: "加入共享空间",
|
||||
basicTitle: "基本信息",
|
||||
basicDesc: "设置空间的名称和描述,便于成员识别",
|
||||
basicDesc: "设置共享空间的名称和描述,便于成员识别",
|
||||
nameTip: "建议使用团队或项目名称,便于成员识别",
|
||||
descriptionTip: "描述空间的用途和目标,帮助成员了解空间",
|
||||
descriptionTip: "描述共享空间的用途和目标,帮助成员了解共享空间",
|
||||
permissionsTitle: "成员权限",
|
||||
permissionsDesc: "了解空间中不同角色对知识库与智能体的权限范围",
|
||||
permissionsDesc: "了解共享空间中不同角色对知识库与智能体的权限范围",
|
||||
permissionFeature: "权限功能",
|
||||
fullAccess: "完整权限",
|
||||
editAccess: "编辑权限",
|
||||
viewAccess: "只读权限",
|
||||
adminPerm1: "管理空间设置、成员及知识库与智能体共享",
|
||||
adminPerm1: "管理共享空间设置、成员及知识库与智能体共享",
|
||||
adminPerm2: "共享和管理知识库与智能体",
|
||||
adminPerm3: "编辑共享知识库内容",
|
||||
adminPerm4: "查看和检索知识库",
|
||||
useSharedAgentsPerm: "使用共享智能体",
|
||||
shareKBPerm: "共享知识库到空间",
|
||||
shareKBPerm: "共享知识库到共享空间",
|
||||
editorPerm1: "编辑共享知识库内容",
|
||||
editorPerm2: "查看和检索知识库",
|
||||
editorPerm3: "管理空间设置和成员",
|
||||
editorPerm3: "管理共享空间设置和成员",
|
||||
viewerPerm1: "查看和检索知识库",
|
||||
viewerPerm2: "编辑知识库内容",
|
||||
viewerPerm3: "管理空间设置",
|
||||
ownerNote: "作为空间创建者,您将自动成为空间的管理员,拥有完整权限。",
|
||||
joinTitle: "加入空间",
|
||||
joinDesc: "通过邀请码加入现有空间,获得知识库与智能体访问权限",
|
||||
joinIllustration: "输入空间管理员提供的邀请码即可加入",
|
||||
inviteCodeTip: "邀请码由空间管理员生成,请向他们索取",
|
||||
viewerPerm3: "管理共享空间设置",
|
||||
ownerNote: "作为共享空间创建者,您将自动成为共享空间的管理员,拥有完整权限。",
|
||||
joinTitle: "加入共享空间",
|
||||
joinDesc: "通过邀请码加入现有共享空间,获得知识库与智能体访问权限",
|
||||
joinIllustration: "输入共享空间管理员提供的邀请码即可加入",
|
||||
inviteCodeTip: "邀请码由共享空间管理员生成,请向他们索取",
|
||||
howToGetCode: "如何获取邀请码?",
|
||||
step1: "联系您要加入的空间管理员",
|
||||
step2: "请求他们分享空间邀请码",
|
||||
step1: "联系您要加入的共享空间管理员",
|
||||
step2: "请求他们分享共享空间邀请码",
|
||||
step3: "将邀请码粘贴到上方输入框",
|
||||
},
|
||||
upgrade: {
|
||||
@@ -5410,12 +5409,12 @@ export default {
|
||||
addMember: {
|
||||
button: "添加成员",
|
||||
dialogTitle: "添加成员",
|
||||
tip: "添加的用户将立即成为空间成员,可以访问空间内共享的知识库。",
|
||||
tip: "添加的用户将立即成为共享空间成员,可以访问共享空间内共享的知识库。",
|
||||
tipTenant: "共享空间的成员单位是空间:选定一个空间后,其下全部用户都将获得访问权限。下方搜索结果按空间去重。",
|
||||
searchUser: "选择用户",
|
||||
searchTenant: "选择空间",
|
||||
searchPlaceholder: "输入用户名或邮箱搜索...",
|
||||
searchTenantPlaceholder: "输入空间名、用户名或邮箱搜索...",
|
||||
searchTenantPlaceholder: "输入空间名搜索...",
|
||||
searchHint: "输入至少 2 个字符开始搜索",
|
||||
searchTenantHint: "输入至少 2 个字符开始搜索,按空间去重并自动过滤已加入的空间",
|
||||
selectRole: "分配角色",
|
||||
@@ -5429,15 +5428,15 @@ export default {
|
||||
},
|
||||
},
|
||||
share: {
|
||||
title: "共享到空间",
|
||||
shareToSpace: "共享到空间",
|
||||
shareModelToSpace: "共享「{name}」到空间",
|
||||
shareAgentToSpace: "共享「{name}」到空间",
|
||||
modelShareDesc: "将模型共享到空间,空间成员可使用该模型",
|
||||
agentShareDesc: "将智能体共享到空间,空间成员可使用该智能体",
|
||||
spaceAgentShareCountTip: "该空间的共享智能体数量",
|
||||
selectOrg: "选择空间",
|
||||
selectOrgPlaceholder: "请选择要共享的空间",
|
||||
title: "共享到共享空间",
|
||||
shareToSpace: "共享到共享空间",
|
||||
shareModelToSpace: "共享「{name}」到共享空间",
|
||||
shareAgentToSpace: "共享「{name}」到共享空间",
|
||||
modelShareDesc: "将模型共享到共享空间,共享空间成员可使用该模型",
|
||||
agentShareDesc: "将智能体共享到共享空间,共享空间成员可使用该智能体",
|
||||
spaceAgentShareCountTip: "该共享空间的共享智能体数量",
|
||||
selectOrg: "选择共享空间",
|
||||
selectOrgPlaceholder: "请选择要共享的共享空间",
|
||||
permission: "权限",
|
||||
permissionTip: "可编辑权限允许成员修改知识库内容,只读权限仅允许检索和问答",
|
||||
shareSuccess: "已共享",
|
||||
@@ -5445,14 +5444,14 @@ export default {
|
||||
unshareSuccess: "已取消共享",
|
||||
unshareFailed: "取消共享失败",
|
||||
sharedTo: "已共享到",
|
||||
noShares: "尚未共享到任何空间",
|
||||
searchPlaceholder: "搜索空间…",
|
||||
noShares: "尚未共享到任何共享空间",
|
||||
searchPlaceholder: "搜索共享空间…",
|
||||
loading: "加载中…",
|
||||
emptySearch: "未找到匹配「{q}」的空间",
|
||||
addShareDialogTitle: "共享到空间",
|
||||
emptySearch: "未找到匹配「{q}」的共享空间",
|
||||
addShareDialogTitle: "共享到共享空间",
|
||||
unshareAction: "取消共享",
|
||||
columns: {
|
||||
space: "空间",
|
||||
space: "共享空间",
|
||||
permission: "权限",
|
||||
sharedAt: "共享时间",
|
||||
operations: "操作",
|
||||
|
||||
@@ -6,14 +6,25 @@ import type {
|
||||
SharedKnowledgeBase,
|
||||
SharedAgentInfo,
|
||||
OrganizationPreview,
|
||||
ResourceCountsByOrg
|
||||
ResourceCountsByOrg,
|
||||
SearchableOrganizationItem,
|
||||
UpdateOrganizationRequest,
|
||||
ShareKnowledgeBaseRequest,
|
||||
UpdateSharePermissionRequest,
|
||||
InviteMemberRequest,
|
||||
ReviewJoinRequestRequest,
|
||||
RequestRoleUpgradeRequest,
|
||||
ApiResponse,
|
||||
KnowledgeBaseShare,
|
||||
AgentShareResponse
|
||||
} from '@/api/organization'
|
||||
import {
|
||||
listMyOrganizations,
|
||||
createOrganization,
|
||||
updateOrganization,
|
||||
updateOrganization as updateOrganizationApi,
|
||||
deleteOrganization,
|
||||
joinOrganization,
|
||||
joinOrganization as joinOrganizationApi,
|
||||
joinOrganizationById as joinOrganizationByIdApi,
|
||||
previewOrganization,
|
||||
leaveOrganization,
|
||||
generateInviteCode,
|
||||
@@ -21,8 +32,24 @@ import {
|
||||
updateMemberRole,
|
||||
removeMember,
|
||||
listSharedKnowledgeBases,
|
||||
listSharedAgents
|
||||
listSharedAgents,
|
||||
searchSearchableOrganizations,
|
||||
shareKnowledgeBase as shareKnowledgeBaseApi,
|
||||
removeShare as removeShareApi,
|
||||
updateSharePermission as updateSharePermissionApi,
|
||||
shareAgent as shareAgentApi,
|
||||
removeAgentShare as removeAgentShareApi,
|
||||
inviteMember as inviteMemberApi,
|
||||
reviewJoinRequest as reviewJoinRequestApi,
|
||||
requestRoleUpgrade as requestRoleUpgradeApi
|
||||
} from '@/api/organization'
|
||||
import { createVersionedRequestCoordinator } from './versionedRequest'
|
||||
import {
|
||||
applyOrganizationResourceDelta,
|
||||
upsertById,
|
||||
mergeById,
|
||||
reviewMemberCountDelta
|
||||
} from './organizationState'
|
||||
|
||||
export const useOrganizationStore = defineStore('organization', () => {
|
||||
// State
|
||||
@@ -31,20 +58,24 @@ export const useOrganizationStore = defineStore('organization', () => {
|
||||
const currentMembers = ref<OrganizationMember[]>([])
|
||||
const sharedKnowledgeBases = ref<SharedKnowledgeBase[]>([])
|
||||
const sharedAgents = ref<SharedAgentInfo[]>([])
|
||||
const searchableOrganizations = ref<SearchableOrganizationItem[]>([])
|
||||
const previewData = ref<OrganizationPreview | null>(null)
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
/** 各空间内知识库/智能体数量(由 GET /organizations 的 resource_counts 填充,供列表侧栏使用) */
|
||||
const resourceCounts = ref<ResourceCountsByOrg | null>(null)
|
||||
/** 用于去重:同一时刻只允许一次 GET /organizations 请求 */
|
||||
let fetchOrganizationsPromise: Promise<void> | null = null
|
||||
let organizationsLoadedAt = 0
|
||||
/** 共享资源缓存 TTL,与 chatResources 对齐 */
|
||||
const SHARED_RESOURCE_TTL_MS = 60_000
|
||||
const SEARCHABLE_ORGANIZATION_TTL_MS = 5 * 60_000
|
||||
let sharedKbLoadedAt = 0
|
||||
let sharedAgentsLoadedAt = 0
|
||||
let fetchSharedKbPromise: Promise<SharedKnowledgeBase[]> | null = null
|
||||
let fetchSharedAgentsPromise: Promise<SharedAgentInfo[]> | null = null
|
||||
let searchableOrganizationsQuery = ''
|
||||
const searchableOrganizationCache = new Map<
|
||||
string,
|
||||
{ data: SearchableOrganizationItem[]; loadedAt: number }
|
||||
>()
|
||||
|
||||
// Computed
|
||||
const myOrganizations = computed(() => organizations.value)
|
||||
@@ -68,6 +99,28 @@ export const useOrganizationStore = defineStore('organization', () => {
|
||||
* Fetch all organizations the user belongs to.
|
||||
* 去重 + 短期缓存,列表页与侧栏等多处共用。
|
||||
*/
|
||||
const organizationsRequest = createVersionedRequestCoordinator(
|
||||
async () => {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
return await listMyOrganizations()
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
},
|
||||
(response) => {
|
||||
if (response.success && response.data) {
|
||||
organizations.value = response.data.organizations
|
||||
resourceCounts.value = response.data.resource_counts ?? null
|
||||
organizationsLoadedAt = Date.now()
|
||||
} else {
|
||||
resourceCounts.value = null
|
||||
error.value = response.message || 'Failed to fetch organizations'
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
async function fetchOrganizations(options?: { force?: boolean }) {
|
||||
const force = options?.force ?? false
|
||||
if (
|
||||
@@ -77,29 +130,62 @@ export const useOrganizationStore = defineStore('organization', () => {
|
||||
) {
|
||||
return
|
||||
}
|
||||
if (fetchOrganizationsPromise) return fetchOrganizationsPromise
|
||||
loading.value = true
|
||||
error.value = null
|
||||
fetchOrganizationsPromise = (async () => {
|
||||
try {
|
||||
const response = await listMyOrganizations()
|
||||
if (response.success && response.data) {
|
||||
organizations.value = response.data.organizations
|
||||
resourceCounts.value = response.data.resource_counts ?? null
|
||||
organizationsLoadedAt = Date.now()
|
||||
} else {
|
||||
resourceCounts.value = null
|
||||
error.value = response.message || 'Failed to fetch organizations'
|
||||
}
|
||||
} catch (e: any) {
|
||||
error.value = e.message || 'Failed to fetch organizations'
|
||||
resourceCounts.value = null
|
||||
} finally {
|
||||
loading.value = false
|
||||
fetchOrganizationsPromise = null
|
||||
}
|
||||
})()
|
||||
return fetchOrganizationsPromise
|
||||
return organizationsRequest.fetch(force)
|
||||
}
|
||||
|
||||
function patchOrganization(id: string, patch: Partial<Organization>) {
|
||||
organizationsRequest.invalidate()
|
||||
organizationsLoadedAt = 0
|
||||
organizations.value = organizations.value.map(org =>
|
||||
org.id === id ? { ...org, ...patch } : org
|
||||
)
|
||||
if (currentOrganization.value?.id === id) {
|
||||
currentOrganization.value = { ...currentOrganization.value, ...patch }
|
||||
}
|
||||
}
|
||||
|
||||
function upsertOrganization(organization: Organization) {
|
||||
organizationsRequest.invalidate()
|
||||
organizationsLoadedAt = 0
|
||||
organizations.value = upsertById(organizations.value, organization)
|
||||
if (currentOrganization.value?.id === organization.id) {
|
||||
currentOrganization.value = organization
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge a detail payload (which may omit list-only aggregate fields) onto the
|
||||
* existing card instead of replacing it, so badges like share_count survive.
|
||||
*/
|
||||
function mergeOrganizationDetail(organization: Organization) {
|
||||
organizationsRequest.invalidate()
|
||||
organizationsLoadedAt = 0
|
||||
const next = mergeById(organizations.value, organization)
|
||||
organizations.value = next
|
||||
currentOrganization.value =
|
||||
next.find(org => org.id === organization.id) ?? organization
|
||||
}
|
||||
|
||||
function adjustOrganizationResourceCount(
|
||||
organizationId: string,
|
||||
resource: 'knowledge_bases' | 'agents',
|
||||
delta: number
|
||||
) {
|
||||
organizationsRequest.invalidate()
|
||||
organizationsLoadedAt = 0
|
||||
const result = applyOrganizationResourceDelta(
|
||||
organizations.value,
|
||||
resourceCounts.value,
|
||||
organizationId,
|
||||
resource,
|
||||
delta
|
||||
)
|
||||
organizations.value = result.organizations
|
||||
resourceCounts.value = result.resourceCounts
|
||||
if (currentOrganization.value?.id === organizationId) {
|
||||
currentOrganization.value =
|
||||
result.organizations.find(org => org.id === organizationId) ?? currentOrganization.value
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -111,10 +197,11 @@ export const useOrganizationStore = defineStore('organization', () => {
|
||||
try {
|
||||
const response = await createOrganization({ name, description })
|
||||
if (response.success && response.data) {
|
||||
organizations.value.unshift(response.data)
|
||||
upsertOrganization(response.data)
|
||||
// 创建成功后重置缓存时间戳,确保后续 fetchOrganizations() 不会被 TTL 缓存跳过,
|
||||
// 从而刷新 resource_counts 等创建接口不返回的聚合字段。
|
||||
organizationsLoadedAt = 0
|
||||
void fetchOrganizations({ force: true })
|
||||
return response.data
|
||||
} else {
|
||||
error.value = response.message || 'Failed to create organization'
|
||||
@@ -131,19 +218,14 @@ export const useOrganizationStore = defineStore('organization', () => {
|
||||
/**
|
||||
* Update an organization
|
||||
*/
|
||||
async function update(id: string, name?: string, description?: string) {
|
||||
async function updateOrganization(id: string, updates: UpdateOrganizationRequest) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await updateOrganization(id, { name, description })
|
||||
const response = await updateOrganizationApi(id, updates)
|
||||
if (response.success && response.data) {
|
||||
const index = organizations.value.findIndex(o => o.id === id)
|
||||
if (index !== -1) {
|
||||
organizations.value[index] = response.data
|
||||
}
|
||||
if (currentOrganization.value?.id === id) {
|
||||
currentOrganization.value = response.data
|
||||
}
|
||||
upsertOrganization(response.data)
|
||||
void fetchOrganizations({ force: true })
|
||||
return response.data
|
||||
} else {
|
||||
error.value = response.message || 'Failed to update organization'
|
||||
@@ -157,6 +239,10 @@ export const useOrganizationStore = defineStore('organization', () => {
|
||||
}
|
||||
}
|
||||
|
||||
async function update(id: string, name?: string, description?: string) {
|
||||
return updateOrganization(id, { name, description })
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete an organization
|
||||
*/
|
||||
@@ -166,6 +252,8 @@ export const useOrganizationStore = defineStore('organization', () => {
|
||||
try {
|
||||
const response = await deleteOrganization(id)
|
||||
if (response.success) {
|
||||
organizationsRequest.invalidate()
|
||||
organizationsLoadedAt = 0
|
||||
organizations.value = organizations.value.filter(o => o.id !== id)
|
||||
if (currentOrganization.value?.id === id) {
|
||||
currentOrganization.value = null
|
||||
@@ -214,13 +302,11 @@ export const useOrganizationStore = defineStore('organization', () => {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await joinOrganization({ invite_code: inviteCode })
|
||||
const response = await joinOrganizationApi({ invite_code: inviteCode })
|
||||
if (response.success && response.data) {
|
||||
// Check if already in list
|
||||
const exists = organizations.value.some(o => o.id === response.data!.id)
|
||||
if (!exists) {
|
||||
organizations.value.unshift(response.data)
|
||||
}
|
||||
upsertOrganization(response.data)
|
||||
invalidateSearchableOrganizations(response.data.id)
|
||||
void fetchOrganizations({ force: true })
|
||||
return response.data
|
||||
} else {
|
||||
error.value = response.message || 'Failed to join organization'
|
||||
@@ -243,6 +329,8 @@ export const useOrganizationStore = defineStore('organization', () => {
|
||||
try {
|
||||
const response = await leaveOrganization(id)
|
||||
if (response.success) {
|
||||
organizationsRequest.invalidate()
|
||||
organizationsLoadedAt = 0
|
||||
organizations.value = organizations.value.filter(o => o.id !== id)
|
||||
if (currentOrganization.value?.id === id) {
|
||||
currentOrganization.value = null
|
||||
@@ -269,13 +357,8 @@ export const useOrganizationStore = defineStore('organization', () => {
|
||||
try {
|
||||
const response = await generateInviteCode(id)
|
||||
if (response.success && response.data) {
|
||||
const org = organizations.value.find(o => o.id === id)
|
||||
if (org) {
|
||||
org.invite_code = response.data.invite_code
|
||||
}
|
||||
if (currentOrganization.value?.id === id) {
|
||||
currentOrganization.value.invite_code = response.data.invite_code
|
||||
}
|
||||
patchOrganization(id, { invite_code: response.data.invite_code })
|
||||
void fetchOrganizations({ force: true })
|
||||
return response.data.invite_code
|
||||
} else {
|
||||
error.value = response.message || 'Failed to generate invite code'
|
||||
@@ -348,6 +431,11 @@ export const useOrganizationStore = defineStore('organization', () => {
|
||||
const response = await removeMember(orgId, tenantId)
|
||||
if (response.success) {
|
||||
currentMembers.value = currentMembers.value.filter(m => m.tenant_id !== tenantId)
|
||||
const organization = organizations.value.find(org => org.id === orgId)
|
||||
patchOrganization(orgId, {
|
||||
member_count: Math.max(0, (organization?.member_count ?? 0) - 1)
|
||||
})
|
||||
void fetchOrganizations({ force: true })
|
||||
return true
|
||||
} else {
|
||||
error.value = response.message || 'Failed to remove member'
|
||||
@@ -365,6 +453,26 @@ export const useOrganizationStore = defineStore('organization', () => {
|
||||
* Fetch shared knowledge bases.
|
||||
* 去重 + 短期缓存,避免对话页等多处并发重复请求。
|
||||
*/
|
||||
const sharedKnowledgeBasesRequest = createVersionedRequestCoordinator(
|
||||
async () => {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
return await listSharedKnowledgeBases()
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
},
|
||||
(response) => {
|
||||
if (response.success && response.data) {
|
||||
sharedKnowledgeBases.value = response.data.filter(s => s.knowledge_base != null)
|
||||
sharedKbLoadedAt = Date.now()
|
||||
} else {
|
||||
error.value = response.message || 'Failed to fetch shared knowledge bases'
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
async function fetchSharedKnowledgeBases(options?: { force?: boolean }) {
|
||||
const force = options?.force ?? false
|
||||
if (
|
||||
@@ -374,35 +482,24 @@ export const useOrganizationStore = defineStore('organization', () => {
|
||||
) {
|
||||
return sharedKnowledgeBases.value
|
||||
}
|
||||
if (fetchSharedKbPromise) return fetchSharedKbPromise
|
||||
|
||||
loading.value = true
|
||||
error.value = null
|
||||
fetchSharedKbPromise = (async () => {
|
||||
try {
|
||||
const response = await listSharedKnowledgeBases()
|
||||
if (response.success && response.data) {
|
||||
sharedKnowledgeBases.value = response.data.filter(s => s.knowledge_base != null)
|
||||
sharedKbLoadedAt = Date.now()
|
||||
return sharedKnowledgeBases.value
|
||||
}
|
||||
error.value = response.message || 'Failed to fetch shared knowledge bases'
|
||||
return []
|
||||
} catch (e: any) {
|
||||
error.value = e.message || 'Failed to fetch shared knowledge bases'
|
||||
return []
|
||||
} finally {
|
||||
loading.value = false
|
||||
fetchSharedKbPromise = null
|
||||
}
|
||||
})()
|
||||
return fetchSharedKbPromise
|
||||
await sharedKnowledgeBasesRequest.fetch(force)
|
||||
return sharedKnowledgeBases.value
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch shared agents (shared to me through organizations).
|
||||
* 去重 + 短期缓存。
|
||||
*/
|
||||
const sharedAgentsRequest = createVersionedRequestCoordinator(
|
||||
listSharedAgents,
|
||||
(response) => {
|
||||
if (response.success && response.data) {
|
||||
sharedAgents.value = response.data.filter(s => s.agent != null)
|
||||
sharedAgentsLoadedAt = Date.now()
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
async function fetchSharedAgents(options?: { force?: boolean }) {
|
||||
const force = options?.force ?? false
|
||||
if (
|
||||
@@ -412,31 +509,247 @@ export const useOrganizationStore = defineStore('organization', () => {
|
||||
) {
|
||||
return sharedAgents.value
|
||||
}
|
||||
if (fetchSharedAgentsPromise) return fetchSharedAgentsPromise
|
||||
await sharedAgentsRequest.fetch(force)
|
||||
return sharedAgents.value
|
||||
}
|
||||
|
||||
fetchSharedAgentsPromise = (async () => {
|
||||
try {
|
||||
const response = await listSharedAgents()
|
||||
if (response.success && response.data) {
|
||||
sharedAgents.value = response.data.filter(s => s.agent != null)
|
||||
sharedAgentsLoadedAt = Date.now()
|
||||
return sharedAgents.value
|
||||
}
|
||||
return []
|
||||
} catch {
|
||||
return []
|
||||
} finally {
|
||||
fetchSharedAgentsPromise = null
|
||||
interface InvalidateOrganizationDataOptions {
|
||||
organizations?: boolean
|
||||
sharedKnowledgeBases?: boolean
|
||||
sharedAgents?: boolean
|
||||
searchableOrganizations?: boolean
|
||||
excludeSearchableOrganizationId?: string
|
||||
}
|
||||
|
||||
function invalidateSearchableOrganizations(organizationId?: string) {
|
||||
searchableOrganizationCache.clear()
|
||||
if (organizationId) {
|
||||
searchableOrganizations.value = searchableOrganizations.value.filter(
|
||||
organization => organization.id !== organizationId
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function invalidateOrganizationData(options: InvalidateOrganizationDataOptions) {
|
||||
if (options.organizations) {
|
||||
organizationsRequest.invalidate()
|
||||
organizationsLoadedAt = 0
|
||||
}
|
||||
if (options.sharedKnowledgeBases) {
|
||||
sharedKnowledgeBasesRequest.invalidate()
|
||||
sharedKbLoadedAt = 0
|
||||
}
|
||||
if (options.sharedAgents) {
|
||||
sharedAgentsRequest.invalidate()
|
||||
sharedAgentsLoadedAt = 0
|
||||
}
|
||||
if (options.searchableOrganizations) {
|
||||
invalidateSearchableOrganizations(options.excludeSearchableOrganizationId)
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchSearchableOrganizations(
|
||||
query: string,
|
||||
options?: { force?: boolean; limit?: number }
|
||||
) {
|
||||
const normalizedQuery = query.trim()
|
||||
searchableOrganizationsQuery = normalizedQuery
|
||||
const cached = searchableOrganizationCache.get(normalizedQuery)
|
||||
if (
|
||||
!options?.force &&
|
||||
cached &&
|
||||
Date.now() - cached.loadedAt < SEARCHABLE_ORGANIZATION_TTL_MS
|
||||
) {
|
||||
searchableOrganizations.value = cached.data
|
||||
return cached.data
|
||||
}
|
||||
|
||||
const response = await searchSearchableOrganizations(normalizedQuery, options?.limit ?? 20)
|
||||
if (response.success && response.data) {
|
||||
const data = response.data.data.filter(organization => !organization.is_already_member)
|
||||
searchableOrganizationCache.set(normalizedQuery, { data, loadedAt: Date.now() })
|
||||
if (searchableOrganizationsQuery === normalizedQuery) {
|
||||
searchableOrganizations.value = data
|
||||
}
|
||||
})()
|
||||
return fetchSharedAgentsPromise
|
||||
return data
|
||||
}
|
||||
if (searchableOrganizationsQuery === normalizedQuery) {
|
||||
searchableOrganizations.value = []
|
||||
}
|
||||
return []
|
||||
}
|
||||
|
||||
function clearSearchableOrganizations() {
|
||||
searchableOrganizationsQuery = ''
|
||||
searchableOrganizations.value = []
|
||||
}
|
||||
|
||||
async function joinById(
|
||||
organizationId: string,
|
||||
message?: string,
|
||||
role?: 'admin' | 'editor' | 'viewer',
|
||||
options?: { requiresApproval?: boolean }
|
||||
) {
|
||||
const response = await joinOrganizationByIdApi(organizationId, message, role)
|
||||
if (response.success) {
|
||||
invalidateOrganizationData({
|
||||
searchableOrganizations: true,
|
||||
excludeSearchableOrganizationId: organizationId
|
||||
})
|
||||
if (!options?.requiresApproval && response.data) {
|
||||
upsertOrganization(response.data)
|
||||
void fetchOrganizations({ force: true })
|
||||
}
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
async function shareKnowledgeBase(
|
||||
knowledgeBaseId: string,
|
||||
request: ShareKnowledgeBaseRequest
|
||||
): Promise<ApiResponse<KnowledgeBaseShare>> {
|
||||
const response = await shareKnowledgeBaseApi(knowledgeBaseId, request)
|
||||
if (response.success) {
|
||||
adjustOrganizationResourceCount(request.organization_id, 'knowledge_bases', 1)
|
||||
invalidateOrganizationData({ sharedKnowledgeBases: true })
|
||||
void Promise.all([
|
||||
fetchOrganizations({ force: true }),
|
||||
fetchSharedKnowledgeBases({ force: true })
|
||||
])
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
async function unshareKnowledgeBase(
|
||||
knowledgeBaseId: string,
|
||||
shareId: string,
|
||||
organizationId: string
|
||||
): Promise<ApiResponse<void>> {
|
||||
const response = await removeShareApi(knowledgeBaseId, shareId)
|
||||
if (response.success) {
|
||||
adjustOrganizationResourceCount(organizationId, 'knowledge_bases', -1)
|
||||
invalidateOrganizationData({ sharedKnowledgeBases: true })
|
||||
void Promise.all([
|
||||
fetchOrganizations({ force: true }),
|
||||
fetchSharedKnowledgeBases({ force: true })
|
||||
])
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
async function changeKnowledgeBaseSharePermission(
|
||||
knowledgeBaseId: string,
|
||||
shareId: string,
|
||||
request: UpdateSharePermissionRequest
|
||||
): Promise<ApiResponse<void>> {
|
||||
const response = await updateSharePermissionApi(knowledgeBaseId, shareId, request)
|
||||
if (response.success) {
|
||||
invalidateOrganizationData({ sharedKnowledgeBases: true })
|
||||
void fetchSharedKnowledgeBases({ force: true })
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
async function shareAgent(
|
||||
agentId: string,
|
||||
request: ShareKnowledgeBaseRequest
|
||||
): Promise<ApiResponse<AgentShareResponse>> {
|
||||
const response = await shareAgentApi(agentId, request)
|
||||
if (response.success) {
|
||||
adjustOrganizationResourceCount(request.organization_id, 'agents', 1)
|
||||
invalidateOrganizationData({ sharedAgents: true, sharedKnowledgeBases: true })
|
||||
void Promise.all([
|
||||
fetchOrganizations({ force: true }),
|
||||
fetchSharedAgents({ force: true }),
|
||||
fetchSharedKnowledgeBases({ force: true })
|
||||
])
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
async function unshareAgent(
|
||||
agentId: string,
|
||||
shareId: string,
|
||||
organizationId: string
|
||||
): Promise<ApiResponse<void>> {
|
||||
const response = await removeAgentShareApi(agentId, shareId)
|
||||
if (response.success) {
|
||||
adjustOrganizationResourceCount(organizationId, 'agents', -1)
|
||||
invalidateOrganizationData({ sharedAgents: true, sharedKnowledgeBases: true })
|
||||
void Promise.all([
|
||||
fetchOrganizations({ force: true }),
|
||||
fetchSharedAgents({ force: true }),
|
||||
fetchSharedKnowledgeBases({ force: true })
|
||||
])
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
async function inviteOrganizationMember(
|
||||
organizationId: string,
|
||||
request: InviteMemberRequest
|
||||
): Promise<ApiResponse<void>> {
|
||||
const response = await inviteMemberApi(organizationId, request)
|
||||
if (response.success) {
|
||||
const organization = organizations.value.find(org => org.id === organizationId)
|
||||
patchOrganization(organizationId, {
|
||||
member_count: (organization?.member_count ?? 0) + 1
|
||||
})
|
||||
void fetchOrganizations({ force: true })
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
async function reviewOrganizationJoinRequest(
|
||||
organizationId: string,
|
||||
requestId: string,
|
||||
request: ReviewJoinRequestRequest,
|
||||
options?: { requestType?: 'join' | 'upgrade' }
|
||||
): Promise<ApiResponse<void>> {
|
||||
const response = await reviewJoinRequestApi(organizationId, requestId, request)
|
||||
if (response.success) {
|
||||
const organization = organizations.value.find(org => org.id === organizationId)
|
||||
patchOrganization(organizationId, {
|
||||
member_count:
|
||||
(organization?.member_count ?? 0) +
|
||||
reviewMemberCountDelta(request.approved, options?.requestType),
|
||||
pending_join_request_count: Math.max(
|
||||
0,
|
||||
(organization?.pending_join_request_count ?? 0) - 1
|
||||
)
|
||||
})
|
||||
void fetchOrganizations({ force: true })
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
async function requestOrganizationRoleUpgrade(
|
||||
organizationId: string,
|
||||
request: RequestRoleUpgradeRequest
|
||||
) {
|
||||
const response = await requestRoleUpgradeApi(organizationId, request)
|
||||
if (response.success) {
|
||||
patchOrganization(organizationId, { has_pending_upgrade: true })
|
||||
void fetchOrganizations({ force: true })
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
/**
|
||||
* Set current organization for detail view
|
||||
*/
|
||||
function setCurrentOrganization(org: Organization | null) {
|
||||
currentOrganization.value = org
|
||||
if (org) {
|
||||
mergeOrganizationDetail(org)
|
||||
void fetchOrganizations({ force: true })
|
||||
} else {
|
||||
currentOrganization.value = null
|
||||
}
|
||||
}
|
||||
|
||||
function clearCurrentOrganizationContext() {
|
||||
currentOrganization.value = null
|
||||
currentMembers.value = []
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -477,15 +790,18 @@ export const useOrganizationStore = defineStore('organization', () => {
|
||||
currentMembers.value = []
|
||||
sharedKnowledgeBases.value = []
|
||||
sharedAgents.value = []
|
||||
searchableOrganizations.value = []
|
||||
resourceCounts.value = null
|
||||
previewData.value = null
|
||||
error.value = null
|
||||
sharedKbLoadedAt = 0
|
||||
sharedAgentsLoadedAt = 0
|
||||
fetchSharedKbPromise = null
|
||||
fetchSharedAgentsPromise = null
|
||||
organizationsLoadedAt = 0
|
||||
fetchOrganizationsPromise = null
|
||||
searchableOrganizationsQuery = ''
|
||||
searchableOrganizationCache.clear()
|
||||
organizationsRequest.invalidate()
|
||||
sharedKnowledgeBasesRequest.invalidate()
|
||||
sharedAgentsRequest.invalidate()
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -495,6 +811,7 @@ export const useOrganizationStore = defineStore('organization', () => {
|
||||
currentMembers,
|
||||
sharedKnowledgeBases,
|
||||
sharedAgents,
|
||||
searchableOrganizations,
|
||||
resourceCounts,
|
||||
previewData,
|
||||
loading,
|
||||
@@ -509,6 +826,7 @@ export const useOrganizationStore = defineStore('organization', () => {
|
||||
// Actions
|
||||
fetchOrganizations,
|
||||
create,
|
||||
updateOrganization,
|
||||
update,
|
||||
remove,
|
||||
preview,
|
||||
@@ -520,7 +838,20 @@ export const useOrganizationStore = defineStore('organization', () => {
|
||||
kickMember,
|
||||
fetchSharedKnowledgeBases,
|
||||
fetchSharedAgents,
|
||||
fetchSearchableOrganizations,
|
||||
clearSearchableOrganizations,
|
||||
invalidateOrganizationData,
|
||||
joinById,
|
||||
shareKnowledgeBase,
|
||||
unshareKnowledgeBase,
|
||||
changeKnowledgeBaseSharePermission,
|
||||
shareAgent,
|
||||
unshareAgent,
|
||||
inviteOrganizationMember,
|
||||
reviewOrganizationJoinRequest,
|
||||
requestOrganizationRoleUpgrade,
|
||||
setCurrentOrganization,
|
||||
clearCurrentOrganizationContext,
|
||||
getKBPermission,
|
||||
canEditKB,
|
||||
canManageKB,
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import {
|
||||
applyOrganizationResourceDelta,
|
||||
upsertById,
|
||||
mergeById,
|
||||
reviewMemberCountDelta
|
||||
} from './organizationState.ts'
|
||||
|
||||
test('upsert adds a newly joined organization to the front', () => {
|
||||
const result = upsertById(
|
||||
[{ id: 'existing', name: 'Existing' }],
|
||||
{ id: 'joined', name: 'Joined' }
|
||||
)
|
||||
|
||||
assert.deepEqual(result.map(organization => organization.id), ['joined', 'existing'])
|
||||
})
|
||||
|
||||
test('upsert replaces edited organization data without duplicating the card', () => {
|
||||
const result = upsertById(
|
||||
[{ id: 'space-1', name: 'Old name' }],
|
||||
{ id: 'space-1', name: 'New name' }
|
||||
)
|
||||
|
||||
assert.deepEqual(result, [{ id: 'space-1', name: 'New name' }])
|
||||
})
|
||||
|
||||
test('knowledge base sharing updates card and resource counts immediately', () => {
|
||||
const result = applyOrganizationResourceDelta(
|
||||
[{ id: 'space-1', share_count: 2 }],
|
||||
{
|
||||
knowledge_bases: { by_organization: { 'space-1': 2 } },
|
||||
agents: { by_organization: { 'space-1': 1 } }
|
||||
},
|
||||
'space-1',
|
||||
'knowledge_bases',
|
||||
1
|
||||
)
|
||||
|
||||
assert.equal(result.organizations[0].share_count, 3)
|
||||
assert.equal(result.resourceCounts?.knowledge_bases.by_organization['space-1'], 3)
|
||||
})
|
||||
|
||||
test('resource counts never become negative when a share is removed', () => {
|
||||
const result = applyOrganizationResourceDelta(
|
||||
[{ id: 'space-1', agent_share_count: 0 }],
|
||||
{
|
||||
knowledge_bases: { by_organization: {} },
|
||||
agents: { by_organization: { 'space-1': 0 } }
|
||||
},
|
||||
'space-1',
|
||||
'agents',
|
||||
-1
|
||||
)
|
||||
|
||||
assert.equal(result.organizations[0].agent_share_count, 0)
|
||||
assert.equal(result.resourceCounts?.agents.by_organization['space-1'], 0)
|
||||
})
|
||||
|
||||
test('merge keeps list-only aggregate fields when a detail payload omits them', () => {
|
||||
const result = mergeById(
|
||||
[{ id: 'space-1', name: 'Old name', share_count: 5, agent_share_count: 2 }],
|
||||
{ id: 'space-1', name: 'New name' }
|
||||
)
|
||||
|
||||
assert.deepEqual(result, [
|
||||
{ id: 'space-1', name: 'New name', share_count: 5, agent_share_count: 2 }
|
||||
])
|
||||
})
|
||||
|
||||
test('merge inserts a brand-new organization at the front', () => {
|
||||
const result = mergeById(
|
||||
[{ id: 'existing', name: 'Existing' }],
|
||||
{ id: 'new', name: 'New' }
|
||||
)
|
||||
|
||||
assert.deepEqual(result.map(organization => organization.id), ['new', 'existing'])
|
||||
})
|
||||
|
||||
test('approving a new join request adds one member', () => {
|
||||
assert.equal(reviewMemberCountDelta(true, 'join'), 1)
|
||||
})
|
||||
|
||||
test('approving a role upgrade does not change member_count', () => {
|
||||
assert.equal(reviewMemberCountDelta(true, 'upgrade'), 0)
|
||||
})
|
||||
|
||||
test('rejecting any request does not change member_count', () => {
|
||||
assert.equal(reviewMemberCountDelta(false, 'join'), 0)
|
||||
assert.equal(reviewMemberCountDelta(false, 'upgrade'), 0)
|
||||
})
|
||||
@@ -0,0 +1,79 @@
|
||||
export function upsertById<T extends { id: string }>(items: T[], item: T): T[] {
|
||||
const exists = items.some(existing => existing.id === item.id)
|
||||
return exists
|
||||
? items.map(existing => existing.id === item.id ? item : existing)
|
||||
: [item, ...items]
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge a (possibly partial) organization payload onto the existing card.
|
||||
*
|
||||
* Detail endpoints (e.g. GET /organizations/:id) may omit list-only aggregate
|
||||
* fields such as share_count / agent_share_count / pending_join_request_count.
|
||||
* A plain replace would blank those badges until the background refresh lands,
|
||||
* so when a card already exists we shallow-merge instead of overwriting it.
|
||||
*/
|
||||
export function mergeById<T extends { id: string }>(items: T[], item: T): T[] {
|
||||
const existing = items.find(entry => entry.id === item.id)
|
||||
const merged = existing ? { ...existing, ...item } : item
|
||||
return upsertById(items, merged)
|
||||
}
|
||||
|
||||
/**
|
||||
* How much a join-request review changes the organization's member_count.
|
||||
*
|
||||
* Only brand-new "join" approvals add a member. Approving an "upgrade" request
|
||||
* (an existing member asking for a higher role) must not change member_count.
|
||||
*/
|
||||
export function reviewMemberCountDelta(
|
||||
approved: boolean,
|
||||
requestType: 'join' | 'upgrade' | undefined
|
||||
): number {
|
||||
return approved && requestType !== 'upgrade' ? 1 : 0
|
||||
}
|
||||
|
||||
interface OrganizationResourceCounts {
|
||||
knowledge_bases: { by_organization: Record<string, number> }
|
||||
agents: { by_organization: Record<string, number> }
|
||||
}
|
||||
|
||||
interface CountedOrganization {
|
||||
id: string
|
||||
share_count?: number
|
||||
agent_share_count?: number
|
||||
}
|
||||
|
||||
export function applyOrganizationResourceDelta<T extends CountedOrganization>(
|
||||
organizations: T[],
|
||||
resourceCounts: OrganizationResourceCounts | null,
|
||||
organizationId: string,
|
||||
resource: 'knowledge_bases' | 'agents',
|
||||
delta: number
|
||||
): { organizations: T[]; resourceCounts: OrganizationResourceCounts | null } {
|
||||
const field = resource === 'knowledge_bases' ? 'share_count' : 'agent_share_count'
|
||||
const organizationsAfterUpdate = organizations.map(organization => {
|
||||
if (organization.id !== organizationId) return organization
|
||||
return {
|
||||
...organization,
|
||||
[field]: Math.max(0, (organization[field] ?? 0) + delta)
|
||||
}
|
||||
})
|
||||
|
||||
if (!resourceCounts) {
|
||||
return { organizations: organizationsAfterUpdate, resourceCounts }
|
||||
}
|
||||
|
||||
const counts = resourceCounts[resource].by_organization
|
||||
return {
|
||||
organizations: organizationsAfterUpdate,
|
||||
resourceCounts: {
|
||||
...resourceCounts,
|
||||
[resource]: {
|
||||
by_organization: {
|
||||
...counts,
|
||||
[organizationId]: Math.max(0, (counts[organizationId] ?? 0) + delta)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -418,8 +418,12 @@ export const useSettingsStore = defineStore("settings", {
|
||||
return this.settings.selectedFiles || [];
|
||||
},
|
||||
|
||||
/** Scope for suggested-questions API (KB / file / tag @mentions). */
|
||||
getSuggestedQuestionsParams(limit = 6) {
|
||||
/**
|
||||
* Scope for suggested-questions API (KB / file / tag @mentions).
|
||||
* Leave `limit` undefined to let the backend apply the agent's configured
|
||||
* starter count; pass a number only to request a specific count.
|
||||
*/
|
||||
getSuggestedQuestionsParams(limit?: number) {
|
||||
const selectedKBs = this.getSelectedKnowledgeBases();
|
||||
const selectedFiles = this.getSelectedFiles();
|
||||
const tags = this.settings.selectedTags || [];
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { createVersionedRequestCoordinator } from './versionedRequest.ts'
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void
|
||||
const promise = new Promise<T>((done) => {
|
||||
resolve = done
|
||||
})
|
||||
return { promise, resolve }
|
||||
}
|
||||
|
||||
test('force queues a fresh request behind an existing request', async () => {
|
||||
const first = deferred<string>()
|
||||
const second = deferred<string>()
|
||||
const requests = [first, second]
|
||||
const applied: string[] = []
|
||||
let calls = 0
|
||||
const coordinator = createVersionedRequestCoordinator(
|
||||
() => requests[calls++].promise,
|
||||
value => applied.push(value)
|
||||
)
|
||||
|
||||
const initial = coordinator.fetch()
|
||||
const forced = coordinator.fetch(true)
|
||||
assert.equal(calls, 1)
|
||||
|
||||
first.resolve('old')
|
||||
await initial
|
||||
await new Promise<void>(resolve => queueMicrotask(resolve))
|
||||
assert.equal(calls, 2)
|
||||
|
||||
second.resolve('fresh')
|
||||
await forced
|
||||
assert.deepEqual(applied, ['old', 'fresh'])
|
||||
})
|
||||
|
||||
test('an invalidated older response cannot overwrite newer state', async () => {
|
||||
const first = deferred<string>()
|
||||
const second = deferred<string>()
|
||||
const requests = [first, second]
|
||||
const applied: string[] = []
|
||||
let calls = 0
|
||||
const coordinator = createVersionedRequestCoordinator(
|
||||
() => requests[calls++].promise,
|
||||
value => applied.push(value)
|
||||
)
|
||||
|
||||
const initial = coordinator.fetch()
|
||||
coordinator.invalidate()
|
||||
const forced = coordinator.fetch(true)
|
||||
|
||||
first.resolve('stale')
|
||||
await initial
|
||||
await new Promise<void>(resolve => queueMicrotask(resolve))
|
||||
second.resolve('fresh')
|
||||
await forced
|
||||
|
||||
assert.deepEqual(applied, ['fresh'])
|
||||
})
|
||||
|
||||
test('a newer force request extends an active force queue after invalidation', async () => {
|
||||
const first = deferred<string>()
|
||||
const second = deferred<string>()
|
||||
const third = deferred<string>()
|
||||
const requests = [first, second, third]
|
||||
const applied: string[] = []
|
||||
let calls = 0
|
||||
const coordinator = createVersionedRequestCoordinator(
|
||||
() => requests[calls++].promise,
|
||||
value => applied.push(value)
|
||||
)
|
||||
|
||||
void coordinator.fetch()
|
||||
const firstForce = coordinator.fetch(true)
|
||||
first.resolve('first')
|
||||
await new Promise<void>(resolve => queueMicrotask(resolve))
|
||||
|
||||
coordinator.invalidate()
|
||||
const secondForce = coordinator.fetch(true)
|
||||
second.resolve('stale-second')
|
||||
await new Promise<void>(resolve => queueMicrotask(resolve))
|
||||
assert.equal(calls, 3)
|
||||
|
||||
third.resolve('fresh-third')
|
||||
await Promise.all([firstForce, secondForce])
|
||||
assert.deepEqual(applied, ['first', 'fresh-third'])
|
||||
})
|
||||
@@ -0,0 +1,90 @@
|
||||
export interface VersionedRequestCoordinator<T> {
|
||||
fetch: (force?: boolean) => Promise<void>
|
||||
invalidate: () => void
|
||||
hasInFlightRequest: () => boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Coordinates cached reads that also need a reliable "force refresh" mode.
|
||||
*
|
||||
* A forced read requested while another read is running is queued after the
|
||||
* current request. Invalidating the coordinator also prevents an older
|
||||
* response from overwriting state changed by a newer write.
|
||||
*/
|
||||
export function createVersionedRequestCoordinator<T>(
|
||||
request: () => Promise<T>,
|
||||
apply: (value: T) => void
|
||||
): VersionedRequestCoordinator<T> {
|
||||
let revision = 0
|
||||
let startedSequence = 0
|
||||
let completedSequence = 0
|
||||
let forceTargetSequence = 0
|
||||
let inFlight: Promise<void> | null = null
|
||||
let forceQueue: Promise<void> | null = null
|
||||
|
||||
const start = (): Promise<void> => {
|
||||
const requestRevision = revision
|
||||
const sequence = ++startedSequence
|
||||
const current = (async () => {
|
||||
const value = await request()
|
||||
if (requestRevision === revision) {
|
||||
apply(value)
|
||||
}
|
||||
})()
|
||||
|
||||
inFlight = current
|
||||
void current.then(
|
||||
() => {
|
||||
completedSequence = Math.max(completedSequence, sequence)
|
||||
if (inFlight === current) inFlight = null
|
||||
},
|
||||
() => {
|
||||
completedSequence = Math.max(completedSequence, sequence)
|
||||
if (inFlight === current) inFlight = null
|
||||
}
|
||||
)
|
||||
return current
|
||||
}
|
||||
|
||||
const fetch = (force = false): Promise<void> => {
|
||||
if (!inFlight) return start()
|
||||
if (!force) return inFlight
|
||||
|
||||
// A force call always requires at least one request newer than the one
|
||||
// that was in flight when force was requested.
|
||||
forceTargetSequence = Math.max(forceTargetSequence, startedSequence + 1)
|
||||
if (!forceQueue) {
|
||||
const queued = (async () => {
|
||||
while (completedSequence < forceTargetSequence) {
|
||||
if (inFlight) {
|
||||
try {
|
||||
await inFlight
|
||||
} catch {
|
||||
// The queued forced request must still run after a failed read.
|
||||
}
|
||||
} else {
|
||||
await start()
|
||||
}
|
||||
}
|
||||
})()
|
||||
forceQueue = queued
|
||||
void queued.then(
|
||||
() => {
|
||||
if (forceQueue === queued) forceQueue = null
|
||||
},
|
||||
() => {
|
||||
if (forceQueue === queued) forceQueue = null
|
||||
}
|
||||
)
|
||||
}
|
||||
return forceQueue
|
||||
}
|
||||
|
||||
return {
|
||||
fetch,
|
||||
invalidate: () => {
|
||||
revision += 1
|
||||
},
|
||||
hasInFlightRequest: () => inFlight !== null
|
||||
}
|
||||
}
|
||||
@@ -314,7 +314,7 @@ const fetchSuggestedQuestions = async () => {
|
||||
try {
|
||||
const agentId = useSettingsStoreInstance.selectedAgentId;
|
||||
if (!agentId) return;
|
||||
const res = await getSuggestedQuestions(agentId, useSettingsStoreInstance.getSuggestedQuestionsParams(6));
|
||||
const res = await getSuggestedQuestions(agentId, useSettingsStoreInstance.getSuggestedQuestionsParams());
|
||||
if (fetchId === suggestedQuestionsFetchId) {
|
||||
suggestedQuestions.value = res?.data?.questions || [];
|
||||
}
|
||||
|
||||
@@ -139,7 +139,7 @@ const fetchSuggestedQuestions = async () => {
|
||||
try {
|
||||
const agentId = settingsStore.selectedAgentId;
|
||||
if (!agentId) return;
|
||||
const res = await getSuggestedQuestions(agentId, settingsStore.getSuggestedQuestionsParams(6));
|
||||
const res = await getSuggestedQuestions(agentId, settingsStore.getSuggestedQuestionsParams());
|
||||
if (fetchId === suggestedQuestionsFetchId) {
|
||||
sqCardsRevealed.value = false;
|
||||
sqRenderKey.value++;
|
||||
|
||||
@@ -315,7 +315,7 @@ const fetchSuggestedQuestions = async () => {
|
||||
}
|
||||
suggestedLoading.value = true
|
||||
try {
|
||||
const res = await getEmbedSuggestedQuestions(props.channelId, props.token, 6)
|
||||
const res = await getEmbedSuggestedQuestions(props.channelId, props.token)
|
||||
suggestedQuestions.value = res?.data?.questions || []
|
||||
} catch {
|
||||
suggestedQuestions.value = []
|
||||
|
||||
@@ -140,7 +140,7 @@ import { ref, computed, watch } from 'vue'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useOrganizationStore } from '@/stores/organization'
|
||||
import { shareKnowledgeBase, listKBShares, removeShare, updateSharePermission } from '@/api/organization'
|
||||
import { listKBShares } from '@/api/organization'
|
||||
import type { KnowledgeBaseShare } from '@/api/organization'
|
||||
import SpaceAvatar from '@/components/SpaceAvatar.vue'
|
||||
import ShareToSpaceOrgSelect from '@/components/ShareToSpaceOrgSelect.vue'
|
||||
@@ -261,7 +261,7 @@ async function handleShare() {
|
||||
|
||||
submitting.value = true
|
||||
try {
|
||||
const result = await shareKnowledgeBase(props.kbId, {
|
||||
const result = await orgStore.shareKnowledgeBase(props.kbId, {
|
||||
organization_id: selectedOrgId.value,
|
||||
permission: selectedPermission.value
|
||||
})
|
||||
@@ -286,7 +286,7 @@ async function handleUpdatePermission(share: KnowledgeBaseShare, newPermission:
|
||||
if (share.permission === newPermission) return
|
||||
|
||||
try {
|
||||
const result = await updateSharePermission(props.kbId, share.id, {
|
||||
const result = await orgStore.changeKnowledgeBaseSharePermission(props.kbId, share.id, {
|
||||
permission: newPermission as 'viewer' | 'editor'
|
||||
})
|
||||
if (result.success) {
|
||||
@@ -303,7 +303,11 @@ async function handleUpdatePermission(share: KnowledgeBaseShare, newPermission:
|
||||
|
||||
async function handleUnshare(share: KnowledgeBaseShare) {
|
||||
try {
|
||||
const result = await removeShare(props.kbId, share.id)
|
||||
const result = await orgStore.unshareKnowledgeBase(
|
||||
props.kbId,
|
||||
share.id,
|
||||
share.organization_id
|
||||
)
|
||||
if (result.success) {
|
||||
MessagePlugin.success(t('organization.share.unshareSuccess'))
|
||||
await loadShares()
|
||||
|
||||
@@ -99,10 +99,10 @@
|
||||
<span class="card-title" :title="org.name">{{ org.name }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<t-popup v-model="org.showMore" overlayClassName="card-more-popup"
|
||||
<t-popup v-model="organizationMenuVisibility[org.id]" overlayClassName="card-more-popup"
|
||||
:on-visible-change="(visible: boolean) => onVisibleChange(visible, org)" trigger="click"
|
||||
destroy-on-close placement="bottom-right">
|
||||
<div class="more-wrap" @click.stop :class="{ 'active-more': org.showMore }">
|
||||
<div class="more-wrap" @click.stop :class="{ 'active-more': organizationMenuVisibility[org.id] }">
|
||||
<img class="more-icon" src="@/assets/img/more.png" alt="" />
|
||||
</div>
|
||||
<template #content>
|
||||
@@ -201,7 +201,7 @@
|
||||
|
||||
<!-- Organization Settings Modal (用于创建和编辑组织) -->
|
||||
<OrganizationSettingsModal :visible="showSettingsModal" :org-id="settingsOrgId" :mode="settingsMode"
|
||||
@update:visible="showSettingsModal = $event" @saved="handleSettingsSaved" />
|
||||
@update:visible="showSettingsModal = $event" />
|
||||
|
||||
<!-- Delete Confirm Dialog -->
|
||||
<t-dialog v-model:visible="deleteVisible" dialogClassName="del-org-dialog" :closeBtn="false" :cancelBtn="null"
|
||||
@@ -474,22 +474,20 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, onUnmounted, computed, watch, nextTick } from 'vue'
|
||||
import { ref, reactive, onMounted, onUnmounted, computed, watch, nextTick } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import { useOrganizationStore } from '@/stores/organization'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import type { Organization, OrganizationPreview, SearchableOrganizationItem } from '@/api/organization'
|
||||
import { previewOrganization, joinOrganization, submitJoinRequest, searchSearchableOrganizations, joinOrganizationById } from '@/api/organization'
|
||||
import { previewOrganization, submitJoinRequest } from '@/api/organization'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import OrganizationSettingsModal from './OrganizationSettingsModal.vue'
|
||||
import SpaceAvatar from '@/components/SpaceAvatar.vue'
|
||||
import ListSpaceSidebar from '@/components/ListSpaceSidebar.vue'
|
||||
import { shouldShowOrgRelationTag } from '@/utils/card-list-badge'
|
||||
|
||||
interface OrgWithUI extends Organization {
|
||||
showMore?: boolean
|
||||
}
|
||||
type OrgWithUI = Organization
|
||||
|
||||
const { t } = useI18n()
|
||||
const route = useRoute()
|
||||
@@ -534,12 +532,11 @@ const invitePreviewError = ref('')
|
||||
// 加入方式:邀请码 / 搜索空间
|
||||
const joinStep = ref<'invite' | 'search'>('invite')
|
||||
const searchQuery = ref('')
|
||||
const searchableList = ref<SearchableOrganizationItem[]>([])
|
||||
const searchableList = computed(() => orgStore.searchableOrganizations)
|
||||
const searchLoading = ref(false)
|
||||
let searchDebounceTimer: ReturnType<typeof setTimeout> | null = null
|
||||
// 搜索结果缓存:避免重复点击时重复请求导致高度跳动
|
||||
const searchCache = ref<{ query: string; data: SearchableOrganizationItem[]; timestamp: number } | null>(null)
|
||||
const CACHE_DURATION = 5 * 60 * 1000 // 缓存5分钟
|
||||
const organizationMenuVisibility = reactive<Record<string, boolean>>({})
|
||||
|
||||
// Tab 内容容器 ref,用于高度过渡
|
||||
const tabContentWrapperRef = ref<HTMLElement | null>(null)
|
||||
@@ -693,7 +690,7 @@ const handleOrganizationDialogEvent = ((event: CustomEvent<{ type: 'create' | 'j
|
||||
invitePreviewLoading.value = false
|
||||
joinStep.value = 'invite'
|
||||
searchQuery.value = ''
|
||||
searchableList.value = []
|
||||
orgStore.clearSearchableOrganizations()
|
||||
// 注意:不清空缓存,保留搜索结果以便下次快速显示
|
||||
showInvitePreview.value = true
|
||||
}
|
||||
@@ -704,7 +701,7 @@ const spaceSelection = ref<'all' | 'created' | 'joined'>('all')
|
||||
|
||||
// Computed
|
||||
const loading = computed(() => orgStore.loading)
|
||||
const organizations = ref<OrgWithUI[]>([])
|
||||
const organizations = computed<OrgWithUI[]>(() => orgStore.organizations)
|
||||
|
||||
const createdCount = computed(() => organizations.value.filter(o => o.is_owner).length)
|
||||
const joinedCount = computed(() => organizations.value.filter(o => !o.is_owner).length)
|
||||
@@ -758,15 +755,6 @@ const emptyStateDesc = computed(() => {
|
||||
return t('organization.emptyDesc')
|
||||
})
|
||||
|
||||
// Watch store changes and update local organizations
|
||||
watch(
|
||||
() => orgStore.organizations,
|
||||
(newOrgs) => {
|
||||
organizations.value = newOrgs.map(org => ({ ...org, showMore: false }))
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
// Methods
|
||||
function getRoleTheme(role: string) {
|
||||
switch (role) {
|
||||
@@ -778,7 +766,7 @@ function getRoleTheme(role: string) {
|
||||
|
||||
const onVisibleChange = (visible: boolean, org: OrgWithUI) => {
|
||||
if (!visible) {
|
||||
org.showMore = false
|
||||
organizationMenuVisibility[org.id] = false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -806,13 +794,13 @@ function handleJoinOrganization() {
|
||||
invitePreviewLoading.value = false
|
||||
joinStep.value = 'invite'
|
||||
searchQuery.value = ''
|
||||
searchableList.value = []
|
||||
orgStore.clearSearchableOrganizations()
|
||||
showInvitePreview.value = true
|
||||
}
|
||||
|
||||
function handleCardClick(org: OrgWithUI) {
|
||||
// 如果弹窗正在显示,不触发设置
|
||||
if (org.showMore) {
|
||||
if (organizationMenuVisibility[org.id]) {
|
||||
return
|
||||
}
|
||||
settingsOrgId.value = org.id
|
||||
@@ -820,20 +808,15 @@ function handleCardClick(org: OrgWithUI) {
|
||||
showSettingsModal.value = true
|
||||
}
|
||||
|
||||
function handleSettingsSaved() {
|
||||
orgStore.fetchOrganizations()
|
||||
}
|
||||
|
||||
|
||||
function handleSettings(org: OrgWithUI) {
|
||||
org.showMore = false
|
||||
organizationMenuVisibility[org.id] = false
|
||||
settingsOrgId.value = org.id
|
||||
settingsMode.value = 'edit'
|
||||
showSettingsModal.value = true
|
||||
}
|
||||
|
||||
function handleLeave(org: OrgWithUI) {
|
||||
org.showMore = false
|
||||
organizationMenuVisibility[org.id] = false
|
||||
leavingOrg.value = org
|
||||
leaveVisible.value = true
|
||||
}
|
||||
@@ -851,7 +834,7 @@ async function confirmLeave() {
|
||||
}
|
||||
|
||||
function handleDelete(org: OrgWithUI) {
|
||||
org.showMore = false
|
||||
organizationMenuVisibility[org.id] = false
|
||||
deletingOrg.value = org
|
||||
deleteVisible.value = true
|
||||
}
|
||||
@@ -936,18 +919,16 @@ async function confirmJoinOrganization() {
|
||||
}
|
||||
} else {
|
||||
// 直接加入
|
||||
const result = await joinOrganization({ invite_code: inviteCode.value })
|
||||
if (result.success) {
|
||||
const result = await orgStore.join(inviteCode.value)
|
||||
if (result) {
|
||||
MessagePlugin.success(t('organization.invite.joinSuccess'))
|
||||
showInvitePreview.value = false
|
||||
inviteCode.value = ''
|
||||
invitePreviewData.value = null
|
||||
// 清除 URL 中的 invite_code 参数
|
||||
router.replace({ path: route.path, query: {} })
|
||||
// 刷新组织列表
|
||||
orgStore.fetchOrganizations()
|
||||
} else {
|
||||
MessagePlugin.error(result.message || t('organization.invite.joinFailed'))
|
||||
MessagePlugin.error(orgStore.error || t('organization.invite.joinFailed'))
|
||||
}
|
||||
}
|
||||
} catch (e: any) {
|
||||
@@ -977,7 +958,7 @@ function closeInvitePreview() {
|
||||
invitePreviewError.value = ''
|
||||
joinStep.value = 'invite'
|
||||
searchQuery.value = ''
|
||||
searchableList.value = []
|
||||
orgStore.clearSearchableOrganizations()
|
||||
inviteRequestRole.value = 'viewer'
|
||||
inviteRequestMessage.value = ''
|
||||
router.replace({ path: route.path, query: {} })
|
||||
@@ -994,60 +975,21 @@ function backFromPreview() {
|
||||
}
|
||||
}
|
||||
|
||||
// 处理搜索标签点击:如果有缓存,先显示缓存,避免高度跳动
|
||||
// 搜索缓存由 Store 统一管理,切换标签时直接读取缓存或请求最新结果
|
||||
function handleSearchTabClick() {
|
||||
joinStep.value = 'search'
|
||||
|
||||
// 检查是否有有效的缓存
|
||||
const currentQuery = searchQuery.value.trim()
|
||||
if (searchCache.value &&
|
||||
searchCache.value.query === currentQuery &&
|
||||
Date.now() - searchCache.value.timestamp < CACHE_DURATION) {
|
||||
// 先显示缓存结果(已过滤已加入空间),避免高度跳动
|
||||
searchableList.value = searchCache.value.data
|
||||
// 然后在后台刷新(可选,如果需要最新数据)
|
||||
// doSearchSearchable()
|
||||
} else {
|
||||
// 没有缓存或缓存过期,执行搜索
|
||||
doSearchSearchable()
|
||||
}
|
||||
void doSearchSearchable()
|
||||
}
|
||||
|
||||
// 搜索可加入空间
|
||||
async function doSearchSearchable() {
|
||||
const currentQuery = searchQuery.value.trim()
|
||||
|
||||
// 检查缓存
|
||||
if (searchCache.value &&
|
||||
searchCache.value.query === currentQuery &&
|
||||
Date.now() - searchCache.value.timestamp < CACHE_DURATION) {
|
||||
// 使用缓存(已是过滤后的列表),不重新请求
|
||||
searchableList.value = searchCache.value.data
|
||||
return
|
||||
}
|
||||
|
||||
searchLoading.value = true
|
||||
try {
|
||||
const res = await searchSearchableOrganizations(currentQuery, 20)
|
||||
if (res.success && res.data) {
|
||||
const raw = res.data.data || []
|
||||
// 不展示已加入的空间
|
||||
const data = raw.filter((org: SearchableOrganizationItem) => !org.is_already_member)
|
||||
searchableList.value = data
|
||||
// 更新缓存(存过滤后的列表)
|
||||
searchCache.value = {
|
||||
query: currentQuery,
|
||||
data: data,
|
||||
timestamp: Date.now()
|
||||
}
|
||||
} else {
|
||||
searchableList.value = []
|
||||
// 清空缓存
|
||||
searchCache.value = null
|
||||
}
|
||||
await orgStore.fetchSearchableOrganizations(currentQuery, { limit: 20 })
|
||||
} catch (e) {
|
||||
searchableList.value = []
|
||||
searchCache.value = null
|
||||
orgStore.clearSearchableOrganizations()
|
||||
} finally {
|
||||
searchLoading.value = false
|
||||
}
|
||||
@@ -1142,17 +1084,21 @@ async function joinBySearchOrg() {
|
||||
// 如果需要审核,传递角色和消息;否则直接加入
|
||||
const message = invitePreviewData.value.require_approval ? inviteRequestMessage.value?.trim() || undefined : undefined
|
||||
const role = invitePreviewData.value.require_approval ? inviteRequestRole.value : undefined
|
||||
const result = await joinOrganizationById(invitePreviewData.value.id, message, role)
|
||||
const result = await orgStore.joinById(
|
||||
invitePreviewData.value.id,
|
||||
message,
|
||||
role,
|
||||
{ requiresApproval: invitePreviewData.value.require_approval }
|
||||
)
|
||||
if (result.success) {
|
||||
if (invitePreviewData.value.require_approval) {
|
||||
MessagePlugin.success(t('organization.invite.requestSubmitted'))
|
||||
} else {
|
||||
MessagePlugin.success(t('organization.invite.joinSuccess'))
|
||||
orgStore.fetchOrganizations()
|
||||
}
|
||||
showInvitePreview.value = false
|
||||
invitePreviewData.value = null
|
||||
searchableList.value = []
|
||||
orgStore.clearSearchableOrganizations()
|
||||
searchQuery.value = ''
|
||||
joinStep.value = 'invite'
|
||||
inviteRequestRole.value = 'viewer'
|
||||
@@ -1169,7 +1115,7 @@ async function joinBySearchOrg() {
|
||||
|
||||
// Lifecycle
|
||||
onMounted(async () => {
|
||||
orgStore.fetchOrganizations()
|
||||
void orgStore.fetchOrganizations()
|
||||
window.addEventListener('openOrganizationDialog', handleOrganizationDialogEvent)
|
||||
|
||||
// 检查 URL 中是否有邀请码
|
||||
|
||||
@@ -4,12 +4,13 @@ import test from 'node:test'
|
||||
|
||||
const source = readFileSync(new URL('./OrganizationSettingsModal.vue', import.meta.url), 'utf8')
|
||||
|
||||
test('reviewing join requests refreshes local and cached global organization data', () => {
|
||||
test('reviewing join requests goes through the store and refreshes modal data', () => {
|
||||
assert.match(
|
||||
source,
|
||||
/const refreshOrganizationAfterReview = async \(\) => \{\s*await Promise\.all\(\[\s*fetchOrgDetail\(\),\s*orgStore\.fetchOrganizations\(\{ force: true \}\)\s*\]\)\s*\}/
|
||||
/const refreshOrganizationAfterReview = async \(\) => \{\s*await Promise\.all\(\[\s*fetchOrgDetail\(\),\s*fetchMembers\(\)\s*\]\)\s*\}/
|
||||
)
|
||||
|
||||
assert.match(source, /orgStore\.reviewOrganizationJoinRequest\(/)
|
||||
const refreshCalls = source.match(/await refreshOrganizationAfterReview\(\)/g) ?? []
|
||||
assert.equal(refreshCalls.length, 2)
|
||||
})
|
||||
|
||||
@@ -573,7 +573,7 @@
|
||||
<div class="join-request-actions">
|
||||
<t-popup :visible="approvePopupRequestId === row.id"
|
||||
placement="left-start" destroy-on-close overlay-class-name="org-approve-request-popup-overlay"
|
||||
@visible-change="(visible) => handleApprovePopupVisibleChange(visible, row)">
|
||||
@visible-change="(visible: boolean) => handleApprovePopupVisibleChange(visible, row)">
|
||||
<t-tooltip :content="$t('organization.settings.approve')" placement="top">
|
||||
<t-button theme="primary" variant="text" shape="square" size="small"
|
||||
:loading="reviewingRequestId === row.id" @click.stop="openApprovePopup(row)">
|
||||
@@ -824,21 +824,10 @@ import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import {
|
||||
getOrganization,
|
||||
listMembers,
|
||||
updateOrganization,
|
||||
updateMemberRole,
|
||||
removeMember,
|
||||
generateInviteCode,
|
||||
listOrgShares,
|
||||
listOrgAgentShares,
|
||||
listJoinRequests,
|
||||
reviewJoinRequest,
|
||||
removeShare,
|
||||
removeAgentShare,
|
||||
requestRoleUpgrade,
|
||||
searchTenantsForInvite,
|
||||
inviteMember,
|
||||
type Organization,
|
||||
type OrganizationMember,
|
||||
type KnowledgeBaseShare,
|
||||
type AgentShareResponse,
|
||||
@@ -874,8 +863,8 @@ const emit = defineEmits<{
|
||||
|
||||
// State
|
||||
const currentSection = ref('basic')
|
||||
const orgInfo = ref<Organization | null>(null)
|
||||
const members = ref<OrganizationMember[]>([])
|
||||
const orgInfo = computed(() => orgStore.currentOrganization)
|
||||
const members = computed(() => orgStore.currentMembers)
|
||||
const sharedKnowledgeBases = ref<KnowledgeBaseShare[]>([])
|
||||
const sharedAgents = ref<AgentShareResponse[]>([])
|
||||
const joinRequests = ref<JoinRequestResponse[]>([])
|
||||
@@ -985,19 +974,13 @@ const addMemberRoleOptions = computed(() => [
|
||||
{ label: t('organization.role.admin'), value: 'admin' },
|
||||
])
|
||||
|
||||
// 空间搜索结果选项。主标签展示空间名,括号里附带代表用户名(不再展示
|
||||
// 邮箱、不带"代表:"前缀,避免冗长和译文别扭);空间名缺失时回退到
|
||||
// 代表用户名 / 空间 ID。
|
||||
// 空间搜索结果选项。成员单位是空间,只按空间名搜索,因此直接展示空间名;
|
||||
// 空间名缺失时回退到空间 ID。
|
||||
const tenantSearchOptions = computed(() =>
|
||||
tenantSearchResults.value.map((c) => {
|
||||
const tenantLabel = c.tenant_name || c.representative_username || `tenant#${c.tenant_id}`
|
||||
const showsTenantName = !!c.tenant_name
|
||||
const label =
|
||||
showsTenantName && c.representative_username
|
||||
? `${tenantLabel}(${c.representative_username})`
|
||||
: tenantLabel
|
||||
return { label, value: c.tenant_id }
|
||||
})
|
||||
tenantSearchResults.value.map((c) => ({
|
||||
label: c.tenant_name || `tenant#${c.tenant_id}`,
|
||||
value: c.tenant_id,
|
||||
}))
|
||||
)
|
||||
|
||||
const modalTitle = computed(() => {
|
||||
@@ -1310,6 +1293,10 @@ const remainingValidityText = computed(() => {
|
||||
|
||||
// Methods
|
||||
const handleClose = () => {
|
||||
// Blur before unmount so TDesign textarea autosize won't run on a detached node.
|
||||
if (document.activeElement instanceof HTMLElement) {
|
||||
document.activeElement.blur()
|
||||
}
|
||||
emit('update:visible', false)
|
||||
}
|
||||
|
||||
@@ -1317,8 +1304,9 @@ const fetchOrgDetail = async () => {
|
||||
if (!props.orgId) return
|
||||
try {
|
||||
const res = await getOrganization(props.orgId)
|
||||
if (!props.visible) return
|
||||
if (res.success && res.data) {
|
||||
orgInfo.value = res.data
|
||||
orgStore.setCurrentOrganization(res.data)
|
||||
const validity = res.data.invite_code_validity_days
|
||||
const memberLimit = res.data.member_limit
|
||||
formData.value = {
|
||||
@@ -1344,10 +1332,7 @@ const fetchMembers = async () => {
|
||||
if (!props.orgId) return
|
||||
membersLoading.value = true
|
||||
try {
|
||||
const res = await listMembers(props.orgId)
|
||||
if (res.success && res.data) {
|
||||
members.value = res.data.members || []
|
||||
}
|
||||
await orgStore.fetchMembers(props.orgId)
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch members:', error)
|
||||
} finally {
|
||||
@@ -1445,7 +1430,7 @@ const fetchJoinRequests = async () => {
|
||||
const refreshOrganizationAfterReview = async () => {
|
||||
await Promise.all([
|
||||
fetchOrgDetail(),
|
||||
orgStore.fetchOrganizations({ force: true })
|
||||
fetchMembers()
|
||||
])
|
||||
}
|
||||
|
||||
@@ -1458,7 +1443,12 @@ const handleApproveRequest = async (req: JoinRequestResponse, assignRole: 'viewe
|
||||
if (!props.orgId) return false
|
||||
reviewingRequestId.value = req.id
|
||||
try {
|
||||
const res = await reviewJoinRequest(props.orgId, req.id, { approved: true, role: assignRole })
|
||||
const res = await orgStore.reviewOrganizationJoinRequest(
|
||||
props.orgId,
|
||||
req.id,
|
||||
{ approved: true, role: assignRole },
|
||||
{ requestType: req.request_type }
|
||||
)
|
||||
if (res.success) {
|
||||
MessagePlugin.success(t('organization.settings.approveSuccess'))
|
||||
joinRequests.value = joinRequests.value.filter(r => r.id !== req.id)
|
||||
@@ -1479,7 +1469,12 @@ const handleRejectRequest = async (req: JoinRequestResponse) => {
|
||||
if (!props.orgId) return
|
||||
reviewingRequestId.value = req.id
|
||||
try {
|
||||
const res = await reviewJoinRequest(props.orgId, req.id, { approved: false })
|
||||
const res = await orgStore.reviewOrganizationJoinRequest(
|
||||
props.orgId,
|
||||
req.id,
|
||||
{ approved: false },
|
||||
{ requestType: req.request_type }
|
||||
)
|
||||
if (res.success) {
|
||||
MessagePlugin.success(t('organization.settings.rejectSuccess'))
|
||||
joinRequests.value = joinRequests.value.filter(r => r.id !== req.id)
|
||||
@@ -1519,7 +1514,7 @@ const handleSave = async () => {
|
||||
} else {
|
||||
// 编辑模式
|
||||
if (!props.orgId) return
|
||||
const res = await updateOrganization(props.orgId, {
|
||||
const result = await orgStore.updateOrganization(props.orgId, {
|
||||
name: formData.value.name.trim(),
|
||||
description: formData.value.description.trim(),
|
||||
avatar: formData.value.avatar || undefined,
|
||||
@@ -1528,12 +1523,12 @@ const handleSave = async () => {
|
||||
invite_code_validity_days: formData.value.invite_code_validity_days,
|
||||
member_limit: formData.value.member_limit
|
||||
})
|
||||
if (res.success) {
|
||||
if (result) {
|
||||
MessagePlugin.success(t('common.saveSuccess'))
|
||||
emit('saved')
|
||||
handleClose()
|
||||
} else {
|
||||
MessagePlugin.error(res.message || t('common.saveFailed'))
|
||||
MessagePlugin.error(orgStore.error || t('common.saveFailed'))
|
||||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
@@ -1546,13 +1541,15 @@ const handleSave = async () => {
|
||||
const handleRoleChange = async (member: OrganizationMember, newRole: string) => {
|
||||
if (!props.orgId) return
|
||||
try {
|
||||
const res = await updateMemberRole(props.orgId, member.tenant_id, {
|
||||
role: newRole as 'admin' | 'editor' | 'viewer'
|
||||
})
|
||||
if (res.success) {
|
||||
const success = await orgStore.changeMemberRole(
|
||||
props.orgId,
|
||||
member.tenant_id,
|
||||
newRole as 'admin' | 'editor' | 'viewer'
|
||||
)
|
||||
if (success) {
|
||||
MessagePlugin.success(t('organization.roleUpdated'))
|
||||
} else {
|
||||
MessagePlugin.error(res.message || t('organization.roleUpdateFailed'))
|
||||
MessagePlugin.error(orgStore.error || t('organization.roleUpdateFailed'))
|
||||
fetchMembers()
|
||||
}
|
||||
} catch (error: any) {
|
||||
@@ -1565,12 +1562,11 @@ const confirmRemoveMember = async (member: OrganizationMember) => {
|
||||
if (!props.orgId) return
|
||||
|
||||
try {
|
||||
const res = await removeMember(props.orgId, member.tenant_id)
|
||||
if (res.success) {
|
||||
const success = await orgStore.kickMember(props.orgId, member.tenant_id)
|
||||
if (success) {
|
||||
MessagePlugin.success(t('organization.memberRemoved'))
|
||||
fetchMembers()
|
||||
} else {
|
||||
MessagePlugin.error(res.message || t('organization.memberRemoveFailed'))
|
||||
MessagePlugin.error(orgStore.error || t('organization.memberRemoveFailed'))
|
||||
}
|
||||
} catch (error: any) {
|
||||
MessagePlugin.error(error?.message || t('organization.memberRemoveFailed'))
|
||||
@@ -1578,10 +1574,10 @@ const confirmRemoveMember = async (member: OrganizationMember) => {
|
||||
}
|
||||
|
||||
watch(upgradePopupVisible, (visible) => {
|
||||
if (visible && upgradeRoleOptions.value.length > 0) {
|
||||
upgradeForm.value.requested_role = upgradeRoleOptions.value[0].value as 'editor' | 'admin'
|
||||
} else if (!visible && !upgradeSubmitting.value) {
|
||||
upgradeForm.value = { requested_role: 'editor', message: '' }
|
||||
if (!visible) return
|
||||
upgradeForm.value = {
|
||||
requested_role: (upgradeRoleOptions.value[0]?.value as 'editor' | 'admin') || 'editor',
|
||||
message: '',
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1590,16 +1586,14 @@ const handleSubmitUpgrade = async () => {
|
||||
|
||||
upgradeSubmitting.value = true
|
||||
try {
|
||||
const res = await requestRoleUpgrade(props.orgId, {
|
||||
const res = await orgStore.requestOrganizationRoleUpgrade(props.orgId, {
|
||||
requested_role: upgradeForm.value.requested_role,
|
||||
message: upgradeForm.value.message
|
||||
})
|
||||
if (res.success) {
|
||||
MessagePlugin.success(t('organization.upgrade.submitSuccess'))
|
||||
upgradePopupVisible.value = false
|
||||
hasPendingUpgrade.value = true
|
||||
// Reset form
|
||||
upgradeForm.value = { requested_role: 'editor', message: '' }
|
||||
upgradePopupVisible.value = false
|
||||
} else {
|
||||
MessagePlugin.error(res.message || t('organization.upgrade.submitFailed'))
|
||||
}
|
||||
@@ -1610,7 +1604,7 @@ const handleSubmitUpgrade = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
// 添加成员:搜索空间(按空间名 / 用户名 / 邮箱模糊匹配,按 tenant_id 去重)
|
||||
// 添加成员:搜索空间(仅按空间名模糊匹配,按 tenant_id 去重)
|
||||
let tenantSearchTimer: ReturnType<typeof setTimeout> | null = null
|
||||
const handleTenantSearch = (query: string) => {
|
||||
if (tenantSearchTimer) {
|
||||
@@ -1647,7 +1641,7 @@ const handleAddMember = async () => {
|
||||
|
||||
addMemberSubmitting.value = true
|
||||
try {
|
||||
const res = await inviteMember(props.orgId, {
|
||||
const res = await orgStore.inviteOrganizationMember(props.orgId, {
|
||||
tenant_id: selectedTenantId.value,
|
||||
representative_user_id: candidate?.representative_user_id,
|
||||
role: addMemberRole.value,
|
||||
@@ -1721,13 +1715,13 @@ const refreshInviteCode = async () => {
|
||||
if (!props.orgId) return
|
||||
refreshingCode.value = true
|
||||
try {
|
||||
const res = await generateInviteCode(props.orgId) as any
|
||||
if (res.success) {
|
||||
inviteCode.value = res.invite_code || (res as any).data?.invite_code
|
||||
const code = await orgStore.refreshInviteCode(props.orgId)
|
||||
if (code) {
|
||||
inviteCode.value = code
|
||||
MessagePlugin.success(t('organization.inviteCodeRefreshed'))
|
||||
await fetchOrgDetail()
|
||||
} else {
|
||||
MessagePlugin.error(res.message || t('organization.inviteCodeRefreshFailed'))
|
||||
MessagePlugin.error(orgStore.error || t('organization.inviteCodeRefreshFailed'))
|
||||
}
|
||||
} catch (error: any) {
|
||||
MessagePlugin.error(error?.message || t('organization.inviteCodeRefreshFailed'))
|
||||
@@ -1739,12 +1733,14 @@ const refreshInviteCode = async () => {
|
||||
const handleValidityChange = async (value: number) => {
|
||||
if (!props.orgId) return
|
||||
try {
|
||||
const res = await updateOrganization(props.orgId, { invite_code_validity_days: value })
|
||||
if (res.success) {
|
||||
const result = await orgStore.updateOrganization(props.orgId, {
|
||||
invite_code_validity_days: value
|
||||
})
|
||||
if (result) {
|
||||
MessagePlugin.success(t('common.saveSuccess'))
|
||||
} else {
|
||||
formData.value.invite_code_validity_days = orgInfo.value?.invite_code_validity_days ?? 7
|
||||
MessagePlugin.error(res.message || t('common.saveFailed'))
|
||||
MessagePlugin.error(orgStore.error || t('common.saveFailed'))
|
||||
}
|
||||
} catch (error: any) {
|
||||
formData.value.invite_code_validity_days = orgInfo.value?.invite_code_validity_days ?? 7
|
||||
@@ -1756,15 +1752,15 @@ const handleValidityChange = async (value: number) => {
|
||||
const handleApprovalToggle = async (value: boolean) => {
|
||||
if (!props.orgId) return
|
||||
try {
|
||||
const res = await updateOrganization(props.orgId, {
|
||||
const result = await orgStore.updateOrganization(props.orgId, {
|
||||
require_approval: value
|
||||
})
|
||||
if (res.success) {
|
||||
if (result) {
|
||||
MessagePlugin.success(t('common.saveSuccess'))
|
||||
} else {
|
||||
// 回滚
|
||||
formData.value.require_approval = !value
|
||||
MessagePlugin.error(res.message || t('common.saveFailed'))
|
||||
MessagePlugin.error(orgStore.error || t('common.saveFailed'))
|
||||
}
|
||||
} catch (error: any) {
|
||||
// 回滚
|
||||
@@ -1777,14 +1773,14 @@ const handleApprovalToggle = async (value: boolean) => {
|
||||
const handleSearchableToggle = async (value: boolean) => {
|
||||
if (!props.orgId) return
|
||||
try {
|
||||
const res = await updateOrganization(props.orgId, {
|
||||
const result = await orgStore.updateOrganization(props.orgId, {
|
||||
searchable: value
|
||||
})
|
||||
if (res.success) {
|
||||
if (result) {
|
||||
MessagePlugin.success(t('common.saveSuccess'))
|
||||
} else {
|
||||
formData.value.searchable = !value
|
||||
MessagePlugin.error(res.message || t('common.saveFailed'))
|
||||
MessagePlugin.error(orgStore.error || t('common.saveFailed'))
|
||||
}
|
||||
} catch (error: any) {
|
||||
formData.value.searchable = !value
|
||||
@@ -1800,7 +1796,11 @@ const handleShareClick = (share: KnowledgeBaseShare) => {
|
||||
const handleRemoveShare = async (share: KnowledgeBaseShare) => {
|
||||
if (!props.orgId) return
|
||||
try {
|
||||
const res = await removeShare(share.knowledge_base_id, share.id)
|
||||
const res = await orgStore.unshareKnowledgeBase(
|
||||
share.knowledge_base_id,
|
||||
share.id,
|
||||
props.orgId
|
||||
)
|
||||
if (res.success) {
|
||||
MessagePlugin.success(t('organization.settings.removeShareSuccess'))
|
||||
sharedKnowledgeBases.value = sharedKnowledgeBases.value.filter(s => s.id !== share.id)
|
||||
@@ -1815,7 +1815,7 @@ const handleRemoveShare = async (share: KnowledgeBaseShare) => {
|
||||
const handleRemoveAgentShare = async (share: AgentShareResponse) => {
|
||||
if (!props.orgId) return
|
||||
try {
|
||||
const res = await removeAgentShare(share.agent_id, share.id)
|
||||
const res = await orgStore.unshareAgent(share.agent_id, share.id, props.orgId)
|
||||
if (res.success) {
|
||||
MessagePlugin.success(t('organization.settings.removeShareSuccess'))
|
||||
sharedAgents.value = sharedAgents.value.filter(s => s.id !== share.id)
|
||||
@@ -1865,12 +1865,16 @@ watch(() => props.visible, (newVal) => {
|
||||
if (props.mode === 'create') {
|
||||
// 创建模式:重置表单
|
||||
formData.value = { name: '', description: '', avatar: '', require_approval: false, searchable: false, invite_code_validity_days: 7, member_limit: 50 }
|
||||
orgInfo.value = null
|
||||
members.value = []
|
||||
orgStore.clearCurrentOrganizationContext()
|
||||
sharedKnowledgeBases.value = []
|
||||
inviteCode.value = ''
|
||||
inviteCodeExpiresAt.value = null
|
||||
} else if (props.orgId) {
|
||||
// 清空上一个组织的详情上下文,避免在 fetchOrgDetail 返回前短暂显示旧组织信息
|
||||
if (orgStore.currentOrganization?.id !== props.orgId) {
|
||||
orgStore.clearCurrentOrganizationContext()
|
||||
sharedKnowledgeBases.value = []
|
||||
}
|
||||
fetchOrgDetail()
|
||||
fetchMembers()
|
||||
fetchSharedKBs()
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
|
||||
const listSource = readFileSync(new URL('./OrganizationList.vue', import.meta.url), 'utf8')
|
||||
const settingsSource = readFileSync(new URL('./OrganizationSettingsModal.vue', import.meta.url), 'utf8')
|
||||
const kbShareSource = readFileSync(
|
||||
new URL('../knowledge/settings/KBShareSettings.vue', import.meta.url),
|
||||
'utf8'
|
||||
)
|
||||
const agentShareSource = readFileSync(
|
||||
new URL('../../components/AgentShareSettings.vue', import.meta.url),
|
||||
'utf8'
|
||||
)
|
||||
const storeSource = readFileSync(
|
||||
new URL('../../stores/organization.ts', import.meta.url),
|
||||
'utf8'
|
||||
)
|
||||
|
||||
test('organization list directly derives cards from the store', () => {
|
||||
assert.match(
|
||||
listSource,
|
||||
/const organizations = computed<OrgWithUI\[\]>\(\(\) => orgStore\.organizations\)/
|
||||
)
|
||||
assert.doesNotMatch(listSource, /organizations\.value = newOrgs\.map/)
|
||||
})
|
||||
|
||||
test('join flows and searchable cache are coordinated by the store', () => {
|
||||
assert.match(listSource, /orgStore\.join\(inviteCode\.value\)/)
|
||||
assert.match(listSource, /orgStore\.joinById\(/)
|
||||
assert.match(listSource, /orgStore\.fetchSearchableOrganizations\(/)
|
||||
assert.doesNotMatch(listSource, /const searchCache = ref/)
|
||||
})
|
||||
|
||||
test('organization settings writes use store actions', () => {
|
||||
for (const action of [
|
||||
'updateOrganization',
|
||||
'reviewOrganizationJoinRequest',
|
||||
'inviteOrganizationMember',
|
||||
'requestOrganizationRoleUpgrade',
|
||||
'unshareKnowledgeBase',
|
||||
'unshareAgent'
|
||||
]) {
|
||||
assert.match(settingsSource, new RegExp(`orgStore\\.${action}\\(`))
|
||||
}
|
||||
})
|
||||
|
||||
test('knowledge base and agent share editors use store actions', () => {
|
||||
assert.match(kbShareSource, /orgStore\.shareKnowledgeBase\(/)
|
||||
assert.match(kbShareSource, /orgStore\.unshareKnowledgeBase\(/)
|
||||
assert.match(kbShareSource, /orgStore\.changeKnowledgeBaseSharePermission\(/)
|
||||
assert.match(agentShareSource, /orgStore\.shareAgent\(/)
|
||||
assert.match(agentShareSource, /orgStore\.unshareAgent\(/)
|
||||
})
|
||||
|
||||
test('store invalidates all affected organization caches after sharing', () => {
|
||||
assert.match(
|
||||
storeSource,
|
||||
/invalidateOrganizationData\(\{ sharedKnowledgeBases: true \}\)/
|
||||
)
|
||||
assert.match(
|
||||
storeSource,
|
||||
/invalidateOrganizationData\(\{ sharedAgents: true, sharedKnowledgeBases: true \}\)/
|
||||
)
|
||||
assert.match(storeSource, /adjustOrganizationResourceCount\(/)
|
||||
})
|
||||
+1
-1
@@ -5,7 +5,7 @@ description: |
|
||||
with document parsing, vector search, and LLM integration.
|
||||
type: application
|
||||
version: 0.1.0
|
||||
appVersion: "v0.7.0"
|
||||
appVersion: "v0.7.1"
|
||||
kubeVersion: ">=1.25.0-0"
|
||||
home: https://github.com/Tencent/WeKnora
|
||||
icon: https://raw.githubusercontent.com/Tencent/WeKnora/main/docs/images/logo.png
|
||||
|
||||
@@ -70,6 +70,61 @@ func TestStreamLLMResourceAliasesRoundTrip(t *testing.T) {
|
||||
require.Equal(t, "source=res://0001", model.calls[0][0].Content)
|
||||
}
|
||||
|
||||
// TestStreamLLMSummarySlugSurvivesDocumentCompaction is the regression guard for
|
||||
// the mangled `summary/<uuid>` → `summary/d1` bug. A wiki summary-page slug
|
||||
// embeds a document's UUID, and sourceRefs.EncodeMessages compacts that same
|
||||
// UUID into a citation alias (d1) via a blind substring replace. resourceRefs
|
||||
// must alias the slug to a res:// token BEFORE citation compaction runs;
|
||||
// otherwise the model is shown a mangled slug it then copies into a wiki tool
|
||||
// call that 404s. See the EncodeMessages ordering in streamLLMToEventBus.
|
||||
func TestStreamLLMSummarySlugSurvivesDocumentCompaction(t *testing.T) {
|
||||
const knowledgeID = "07a20bb1-a662-47cf-9929-06fb5d5b5b5e"
|
||||
const summarySlug = "summary/" + knowledgeID
|
||||
|
||||
// The model copies the protected token it saw back into a wiki_read call.
|
||||
model := &mockChat{responses: []mockResponse{{chunks: []types.StreamResponse{
|
||||
{
|
||||
ResponseType: types.ResponseTypeAnswer,
|
||||
Content: "reading the summary",
|
||||
ToolCalls: []types.LLMToolCall{{
|
||||
Type: "function",
|
||||
Function: types.FunctionCall{
|
||||
Name: "wiki_read_page",
|
||||
Arguments: `{"slugs":["res://0001"]}`,
|
||||
},
|
||||
}},
|
||||
Done: true,
|
||||
FinishReason: "tool_calls",
|
||||
},
|
||||
}}}}
|
||||
|
||||
engine := newTestEngine(t, model)
|
||||
// The document UUID is registered as citation alias d1, exactly as the RAG
|
||||
// context (<document id="d1">…) would have registered it upstream.
|
||||
require.Equal(t, "d1", engine.sourceRefs.RegisterDocument(knowledgeID))
|
||||
|
||||
toolMsg := chat.Message{
|
||||
Role: "tool",
|
||||
Content: `<link>[[` + summarySlug + `|Weknora 试错记录.md - Summary]]</link>`,
|
||||
}
|
||||
result, err := engine.streamLLMToEventBus(context.Background(),
|
||||
[]chat.Message{toolMsg}, nil, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
// What the model actually saw must NOT contain the mangled slug; the UUID
|
||||
// must have been aliased to a res:// token before citation compaction ran.
|
||||
require.Len(t, model.calls, 1)
|
||||
sent := model.calls[0][0].Content
|
||||
require.NotContains(t, sent, "summary/d1",
|
||||
"summary slug was clobbered by document-id compaction (encode ordering regressed)")
|
||||
require.Contains(t, sent, "res://", "summary slug must be protected as a res:// token")
|
||||
|
||||
// The model's tool call echoing the token must decode back to the real slug.
|
||||
require.Len(t, result.ToolCalls, 1)
|
||||
require.Contains(t, result.ToolCalls[0].Function.Arguments, summarySlug)
|
||||
require.NotContains(t, result.ToolCalls[0].Function.Arguments, "res://")
|
||||
}
|
||||
|
||||
func TestStreamLLMChunkReferenceExpandsBeforeEmission(t *testing.T) {
|
||||
model := &mockChat{responses: []mockResponse{{chunks: []types.StreamResponse{
|
||||
{ResponseType: types.ResponseTypeAnswer, Content: `answer <ref id="`},
|
||||
|
||||
@@ -453,21 +453,23 @@ const WikiLogEntryTemplate = `## [{{.Date}}] {{.Operation}} | {{.Title}}
|
||||
|
||||
// WikiDeduplicationPrompt asks the LLM to identify duplicate entities/concepts
|
||||
// between newly extracted items and existing wiki pages.
|
||||
const WikiDeduplicationPrompt = `You are a strict deduplication system. Given a list of newly extracted items and a list of existing wiki pages, determine which new items refer to the **exact same** real-world entity or concept as an existing page.
|
||||
const WikiDeduplicationPrompt = `You are a strict deduplication system. You are given a list of newly extracted items. Each item carries its OWN short list of existing wiki pages that are surface-similar to it (its <candidates>). For each item, decide whether it refers to the **exact same** real-world entity or concept as ONE of its own candidates.
|
||||
|
||||
<new_items>
|
||||
{{.NewItems}}
|
||||
</new_items>
|
||||
|
||||
<existing_pages>
|
||||
{{.ExistingPages}}
|
||||
</existing_pages>
|
||||
<items>
|
||||
{{.Candidates}}
|
||||
</items>
|
||||
|
||||
<instructions>
|
||||
### How to read the input
|
||||
Each <item> is a newly extracted entity/concept. The <candidates> nested inside it are the ONLY existing pages you may merge that item into — they were pre-selected as similar to that specific item. A page listed under one item tells you NOTHING about any other item.
|
||||
|
||||
### Hard constraints — a merge is only valid when ALL hold:
|
||||
- The target slug is one of the candidate <page> slugs listed **inside that same item**. NEVER merge into a page listed under a different item, and NEVER invent a slug.
|
||||
- The types are compatible: entities merge with entities, concepts merge with concepts. **Never merge an entity into a concept or vice versa.**
|
||||
|
||||
### Merge criteria — ALL must be true:
|
||||
1. The new item and the existing page refer to the **same real-world thing** (same person, same organization, same specific concept).
|
||||
1. The new item and the candidate page refer to the **same real-world thing** (same person, same organization, same specific concept).
|
||||
2. The match is a **name variation**: abbreviation ↔ full name, translation, or minor spelling difference.
|
||||
3. The types are compatible: entities merge with entities, concepts merge with concepts. **Never merge an entity into a concept or vice versa.**
|
||||
|
||||
### Examples of CORRECT merges:
|
||||
- "Acme Corp" → "Acme Corporation" (same company, abbreviation)
|
||||
|
||||
+10
-1
@@ -39,8 +39,17 @@ func (e *AgentEngine) streamLLMToEventBus(
|
||||
llmCtx, llmCancel := context.WithTimeout(ctx, e.getLLMCallTimeout())
|
||||
defer llmCancel()
|
||||
|
||||
messages = e.sourceRefs.EncodeMessages(messages)
|
||||
// Order matters. resourceRefs must alias durable resource handles FIRST,
|
||||
// because wiki summary-page slugs (summary/<knowledgeID>) embed a document's
|
||||
// UUID and sourceRefs.EncodeMessages compacts that same UUID into a document
|
||||
// citation alias (d1, d2, …) via a blind substring replace. Running
|
||||
// sourceRefs first mangled `[[summary/<uuid>|Title]]` into `[[summary/d1]]`
|
||||
// — an unrecoverable dead link the model then copied into wiki tool calls.
|
||||
// Encoding resourceRefs first turns the slug into a res:// token so the UUID
|
||||
// is gone before citation compaction runs; the two alias spaces (res://NNNN
|
||||
// vs d/c/b/w-N) are disjoint, so decode order is unaffected.
|
||||
messages = e.resourceRefs.EncodeMessages(messages)
|
||||
messages = e.sourceRefs.EncodeMessages(messages)
|
||||
prefixFingerprint := chat.PromptPrefixFingerprint(messages, opts)
|
||||
llmCtx = types.WithLLMCallMetadata(llmCtx, "agent_round", prefixFingerprint)
|
||||
stream, err := e.chatModel.ChatStream(llmCtx, messages, opts)
|
||||
|
||||
@@ -92,12 +92,45 @@ func (t *wikiWritePageTool) Execute(ctx context.Context, args json.RawMessage) (
|
||||
return &types.ToolResult{Success: false, Error: "title, summary, content, and page_type are required for write action"}, nil
|
||||
}
|
||||
|
||||
// Validate + normalize the slug up front. The model routinely emits
|
||||
// malformed slugs (stray characters, mangled UUIDs); persisting them
|
||||
// verbatim creates unreachable pages and dead cross-links.
|
||||
normalizedSlug, slugErr := normalizeAndValidateWikiSlug(params.Slug)
|
||||
if slugErr != nil {
|
||||
return &types.ToolResult{Success: false, Error: slugErr.Error()}, nil
|
||||
}
|
||||
params.Slug = normalizedSlug
|
||||
|
||||
// Try to get the existing page
|
||||
existingPage, err := t.wikiPageService.GetPageBySlug(ctx, kbID, params.Slug)
|
||||
if err != nil && !errors.Is(err, repository.ErrWikiPageNotFound) {
|
||||
return &types.ToolResult{Success: false, Error: "Failed to check existing page: " + err.Error()}, nil
|
||||
}
|
||||
|
||||
// Summary pages are system-owned: they are generated deterministically
|
||||
// from a source document and keyed by its knowledge ID
|
||||
// (summary/<knowledgeID>). Letting the agent CREATE one with an
|
||||
// arbitrary/hand-typed slug is precisely how mangled-UUID ghost summary
|
||||
// pages (e.g. summary/…b171c…) get into the KB. Allow updating an
|
||||
// existing summary page, but never fabricating a new one.
|
||||
if existingPage == nil &&
|
||||
(isSummaryNamespace(params.Slug) || strings.EqualFold(params.PageType, types.WikiPageTypeSummary)) {
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
Error: "summary pages are generated automatically from source documents and cannot be created manually. " +
|
||||
"Use page_type 'synthesis'/'comparison'/'entity'/'concept' for authored pages, " +
|
||||
"or target an existing summary page to update it.",
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Auto-repair dead [[slug]] references in the body before persisting.
|
||||
// This rewrites LLM-mangled links (most importantly UUID-based summary
|
||||
// slugs) back to their real target when a confident match exists, and
|
||||
// leaves everything else untouched. Best-effort — never block the write.
|
||||
if repaired, changed, rerr := t.wikiPageService.RepairContentLinks(ctx, kbID, params.Slug, params.Content); rerr == nil && changed {
|
||||
params.Content = repaired
|
||||
}
|
||||
|
||||
resolvedRefs := resolveSourceRefs(ctx, t.knowledgeService, params.SourceRefs)
|
||||
|
||||
var action string
|
||||
@@ -164,3 +197,37 @@ func (t *wikiWritePageTool) Execute(ctx context.Context, args json.RawMessage) (
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// normalizeAndValidateWikiSlug lowercases + trims a model-supplied slug and
|
||||
// rejects malformed ones. A valid slug contains only lowercase ASCII letters,
|
||||
// digits, '-', '/', or CJK characters, has no leading/trailing/duplicate '/',
|
||||
// and is non-empty. Keeping this strict stops the agent from persisting
|
||||
// unreachable pages built from stray characters or garbled identifiers.
|
||||
func normalizeAndValidateWikiSlug(raw string) (string, error) {
|
||||
s := strings.ToLower(strings.TrimSpace(raw))
|
||||
s = strings.ReplaceAll(s, " ", "-")
|
||||
if s == "" {
|
||||
return "", errors.New("slug is required and must be non-empty")
|
||||
}
|
||||
if strings.Contains(s, "//") || strings.HasPrefix(s, "/") || strings.HasSuffix(s, "/") {
|
||||
return "", fmt.Errorf("invalid slug %q: '/' separators are malformed", raw)
|
||||
}
|
||||
for _, r := range s {
|
||||
switch {
|
||||
case r >= 'a' && r <= 'z', r >= '0' && r <= '9', r == '-', r == '/':
|
||||
case r >= 0x4E00 && r <= 0x9FFF: // keep CJK characters
|
||||
default:
|
||||
return "", fmt.Errorf(
|
||||
"invalid slug %q: character %q is not allowed (use lowercase letters, digits, '-', '/', or CJK)",
|
||||
raw, string(r),
|
||||
)
|
||||
}
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// isSummaryNamespace reports whether a slug lives in the system-owned summary
|
||||
// namespace (summary/…).
|
||||
func isSummaryNamespace(slug string) bool {
|
||||
return strings.HasPrefix(slug, types.WikiPageTypeSummary+"/")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package tools
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestNormalizeAndValidateWikiSlug(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
in string
|
||||
want string
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "already valid", in: "entity/acme-corp", want: "entity/acme-corp"},
|
||||
{name: "lowercased and spaces", in: "Entity/Acme Corp", want: "entity/acme-corp"},
|
||||
{name: "trimmed", in: " concept/rag ", want: "concept/rag"},
|
||||
{name: "cjk kept", in: "entity/上海中心大厦", want: "entity/上海中心大厦"},
|
||||
{name: "uuid summary", in: "summary/07a20bb1-a662-47cf-9929-06fb5d5b5b5e", want: "summary/07a20bb1-a662-47cf-9929-06fb5d5b5b5e"},
|
||||
{name: "empty", in: " ", wantErr: true},
|
||||
{name: "leading slash", in: "/entity/x", wantErr: true},
|
||||
{name: "trailing slash", in: "entity/x/", wantErr: true},
|
||||
{name: "double slash", in: "entity//x", wantErr: true},
|
||||
{name: "invalid char", in: "entity/x!y", wantErr: true},
|
||||
{name: "invalid space-only becomes empty", in: " ", wantErr: true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := normalizeAndValidateWikiSlug(tt.in)
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Fatalf("expected error for %q, got slug %q", tt.in, got)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error for %q: %v", tt.in, err)
|
||||
}
|
||||
if got != tt.want {
|
||||
t.Fatalf("normalizeAndValidateWikiSlug(%q) = %q, want %q", tt.in, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsSummaryNamespace(t *testing.T) {
|
||||
if !isSummaryNamespace("summary/abc") {
|
||||
t.Fatal("summary/abc must be in the summary namespace")
|
||||
}
|
||||
if isSummaryNamespace("summary") {
|
||||
t.Fatal("bare 'summary' (no slash) must not count as the summary namespace")
|
||||
}
|
||||
if isSummaryNamespace("entity/summary-of-x") {
|
||||
t.Fatal("entity/summary-of-x must not count as the summary namespace")
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
@@ -42,15 +41,15 @@ func NewDorisRetrieveEngineRepository(
|
||||
}
|
||||
|
||||
repo := &dorisRepository{
|
||||
db: db,
|
||||
httpClient: &http.Client{},
|
||||
feHTTPBase: strings.TrimRight(feHTTPBase, "/"),
|
||||
username: username,
|
||||
password: password,
|
||||
database: database,
|
||||
tableBaseName: tableBaseName,
|
||||
bucketsNum: indexCfg.GetBucketsNum(0),
|
||||
replicationNum: indexCfg.GetReplicationNum(0),
|
||||
db: db,
|
||||
httpClient: newDorisStreamLoadHTTPClient(),
|
||||
feHTTPBase: strings.TrimRight(feHTTPBase, "/"),
|
||||
username: username,
|
||||
password: password,
|
||||
database: database,
|
||||
tableBaseName: tableBaseName,
|
||||
bucketsNum: indexCfg.GetBucketsNum(0),
|
||||
replicationNum: indexCfg.GetReplicationNum(0),
|
||||
compatModeRequested: compatMode,
|
||||
}
|
||||
log.Infof("[Doris] Repository initialized: db=%s, base=%s, fe_http=%s, compat_mode=%s",
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
secutils "github.com/Tencent/WeKnora/internal/utils"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
@@ -25,6 +26,12 @@ import (
|
||||
// 返回的 cleanup 用 defer 调用即可。
|
||||
func newTestRepo(t *testing.T) (*dorisRepository, sqlmock.Sqlmock, *httptest.Server, func()) {
|
||||
t.Helper()
|
||||
// httptest binds to loopback, which production SSRF policy correctly blocks.
|
||||
// Make that one test host explicit and restore the process-global policy when
|
||||
// the test completes.
|
||||
secutils.SetSSRFWhitelistFromRaw("127.0.0.1")
|
||||
t.Cleanup(secutils.ResetSSRFWhitelistForTest)
|
||||
|
||||
db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherRegexp))
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -231,6 +238,63 @@ func TestPartialUpdateRows_FailureSurfaced(t *testing.T) {
|
||||
assert.Contains(t, err.Error(), "stream load failed")
|
||||
}
|
||||
|
||||
func TestStreamLoadOnce_BlocksUnsafeTarget(t *testing.T) {
|
||||
repo, _, _, cleanup := newTestRepo(t)
|
||||
defer cleanup()
|
||||
|
||||
// Override the helper's loopback allowance: link-local metadata endpoints
|
||||
// must be rejected before the HTTP client is called.
|
||||
secutils.SetSSRFWhitelistFromRaw("")
|
||||
repo.feHTTPBase = "http://169.254.169.254"
|
||||
|
||||
err := repo.streamLoadOnce(context.Background(), "t", []string{"id"},
|
||||
[]map[string]any{{"id": "x"}})
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "blocked by SSRF validation")
|
||||
}
|
||||
|
||||
func TestDorisStreamLoadHTTPClient_BlocksUnsafeRedirect(t *testing.T) {
|
||||
secutils.SetSSRFWhitelistFromRaw("127.0.0.1")
|
||||
t.Cleanup(secutils.ResetSSRFWhitelistForTest)
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, "http://169.254.169.254/latest/meta-data", http.StatusTemporaryRedirect)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
req, err := http.NewRequest(http.MethodPut, server.URL, strings.NewReader("[]"))
|
||||
require.NoError(t, err)
|
||||
_, err = newDorisStreamLoadHTTPClient().Do(req)
|
||||
require.Error(t, err)
|
||||
assert.ErrorIs(t, err, secutils.ErrSSRFRedirectBlocked)
|
||||
}
|
||||
|
||||
func TestDorisStreamLoadHTTPClient_ForwardsAuthorizationToTrustedRedirect(t *testing.T) {
|
||||
secutils.SetSSRFWhitelistFromRaw("127.0.0.1")
|
||||
t.Cleanup(secutils.ResetSSRFWhitelistForTest)
|
||||
|
||||
var gotAuthorization string
|
||||
be := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotAuthorization = r.Header.Get(headerAuthorization)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer be.Close()
|
||||
|
||||
fe := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, be.URL, http.StatusTemporaryRedirect)
|
||||
}))
|
||||
defer fe.Close()
|
||||
|
||||
req, err := http.NewRequest(http.MethodPut, fe.URL, strings.NewReader("[]"))
|
||||
require.NoError(t, err)
|
||||
req.Header.Set(headerAuthorization, "Basic trusted-doris-credential")
|
||||
|
||||
resp, err := newDorisStreamLoadHTTPClient().Do(req)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
assert.Equal(t, "Basic trusted-doris-credential", gotAuthorization)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// repository.go:SQL 形态
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -8,9 +8,11 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
secutils "github.com/Tencent/WeKnora/internal/utils"
|
||||
)
|
||||
|
||||
// Stream Load 相关常量。
|
||||
@@ -52,7 +54,47 @@ type streamLoadResponse struct {
|
||||
// streamLoadURL 拼装某张表的 Stream Load HTTP 端点。
|
||||
func (r *dorisRepository) streamLoadURL(table string) string {
|
||||
return fmt.Sprintf("%s/api/%s/%s/_stream_load",
|
||||
r.feHTTPBase, r.database, table)
|
||||
r.feHTTPBase, url.PathEscape(r.database), url.PathEscape(table))
|
||||
}
|
||||
|
||||
// newDorisStreamLoadHTTPClient protects both the initial FE request and every
|
||||
// FE -> BE redirect at connection time. Doris requires Basic auth to survive
|
||||
// the 307 redirect, so redirect targets on another host must be explicitly
|
||||
// trusted through the SSRF whitelist before credentials are forwarded.
|
||||
func newDorisStreamLoadHTTPClient() *http.Client {
|
||||
cfg := secutils.DefaultSSRFSafeHTTPClientConfig()
|
||||
// Stream Load calls carry their own context deadline. Preserve the previous
|
||||
// client behaviour instead of imposing the generic 30-second HTTP timeout.
|
||||
cfg.Timeout = 0
|
||||
|
||||
client := secutils.NewSSRFSafeHTTPClient(cfg)
|
||||
ssrfCheckRedirect := client.CheckRedirect
|
||||
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
|
||||
// Keep the shared client's redirect limit, scheme/target validation and
|
||||
// sensitive-header stripping as the authoritative SSRF behaviour.
|
||||
if err := ssrfCheckRedirect(req, via); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(via) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
sourceHost := via[len(via)-1].URL.Hostname()
|
||||
targetHost := req.URL.Hostname()
|
||||
if !strings.EqualFold(sourceHost, targetHost) && !secutils.IsSSRFWhitelisted(targetHost) {
|
||||
return fmt.Errorf(
|
||||
"stream load redirect blocked: target host %q is not trusted to receive credentials",
|
||||
targetHost,
|
||||
)
|
||||
}
|
||||
|
||||
// The shared client deliberately strips Authorization on cross-host
|
||||
// redirects. Doris is the exceptional case where an explicitly trusted
|
||||
// BE needs the same Basic credentials after the FE's 307 response.
|
||||
req.Header.Set(headerAuthorization, via[0].Header.Get(headerAuthorization))
|
||||
return nil
|
||||
}
|
||||
return client
|
||||
}
|
||||
|
||||
// partialUpdateRows 把若干行通过 Stream Load 的 partial update 模式写回目标表。
|
||||
@@ -96,6 +138,12 @@ func (r *dorisRepository) streamLoadOnce(ctx context.Context,
|
||||
}
|
||||
|
||||
url := r.streamLoadURL(table)
|
||||
// Validate at the final outbound boundary as well as when user-supplied
|
||||
// vector-store configuration is created. This covers stored/env configs and
|
||||
// keeps the tainted value from reaching http.Client.Do unchecked.
|
||||
if err := secutils.ValidateURLForSSRF(url); err != nil {
|
||||
return fmt.Errorf("stream load URL blocked by SSRF validation: %w", err)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPut, url, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return fmt.Errorf("build stream load request: %w", err)
|
||||
|
||||
@@ -23,6 +23,16 @@ var (
|
||||
ErrAgentNameRequired = errors.New("agent name is required")
|
||||
)
|
||||
|
||||
const (
|
||||
// suggestionDefaultLimit is the fallback count when neither the caller nor
|
||||
// the agent configuration specifies how many suggestions to return.
|
||||
suggestionDefaultLimit = 6
|
||||
// suggestionMaxLimit caps how many suggestions a single request may ask for.
|
||||
// It bounds the downstream candidate pool (limit*5) so an oversized limit
|
||||
// cannot turn into an unbounded chunk query.
|
||||
suggestionMaxLimit = 30
|
||||
)
|
||||
|
||||
// customAgentService implements the CustomAgentService interface
|
||||
type customAgentService struct {
|
||||
repo interfaces.CustomAgentRepository
|
||||
@@ -497,8 +507,15 @@ func (s *customAgentService) getSuggestedQuestions(
|
||||
limit int,
|
||||
includeCurated bool,
|
||||
) ([]types.SuggestedQuestion, error) {
|
||||
if limit <= 0 {
|
||||
limit = 6
|
||||
// A non-positive limit means "unspecified": fall back to the agent's
|
||||
// configured Starters.Count (below) or the default. An explicit limit is
|
||||
// authoritative and only bounded by the safety cap.
|
||||
limitProvided := limit > 0
|
||||
if !limitProvided {
|
||||
limit = suggestionDefaultLimit
|
||||
}
|
||||
if limit > suggestionMaxLimit {
|
||||
limit = suggestionMaxLimit
|
||||
}
|
||||
|
||||
if err := types.AuthorizeTenantAPIKeyKnowledgeTargets(ctx, kbIDs, knowledgeIDs); err != nil {
|
||||
@@ -529,7 +546,10 @@ func (s *customAgentService) getSuggestedQuestions(
|
||||
if suggestionConfig == nil || !suggestionConfig.Starters.Enabled {
|
||||
return []types.SuggestedQuestion{}, nil
|
||||
}
|
||||
if limit > suggestionConfig.Starters.Count {
|
||||
// Starters.Count is the agent-author default, applied only when the
|
||||
// caller did not request a specific limit. An explicit limit stays
|
||||
// authoritative so ?limit=N actually changes how many are returned.
|
||||
if !limitProvided && suggestionConfig.Starters.Count > 0 {
|
||||
limit = suggestionConfig.Starters.Count
|
||||
}
|
||||
starterMode = suggestionConfig.Starters.Mode
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// suggestionLimitAgentRepo returns a single curated-starter agent so the
|
||||
// suggestion path resolves without touching chunk/KB repositories.
|
||||
type suggestionLimitAgentRepo struct {
|
||||
interfaces.CustomAgentRepository
|
||||
agent *types.CustomAgent
|
||||
}
|
||||
|
||||
func (r *suggestionLimitAgentRepo) GetAgentByID(
|
||||
_ context.Context, _ string, _ uint64,
|
||||
) (*types.CustomAgent, error) {
|
||||
return r.agent, nil
|
||||
}
|
||||
|
||||
func newCuratedStarterAgent(count int, items []string) *types.CustomAgent {
|
||||
return &types.CustomAgent{
|
||||
ID: "agent-1",
|
||||
TenantID: 1,
|
||||
Config: types.CustomAgentConfig{
|
||||
QuestionSuggestions: &types.QuestionSuggestionConfig{
|
||||
Starters: types.StarterSuggestionConfig{
|
||||
Enabled: true,
|
||||
Mode: types.SuggestionModeCurated,
|
||||
Count: count,
|
||||
Items: items,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetSuggestedQuestions_ExplicitLimitOverridesStarterCount is the
|
||||
// regression test for issue #2238: an explicit limit must be honored instead
|
||||
// of being clamped down to the agent's configured Starters.Count.
|
||||
func TestGetSuggestedQuestions_ExplicitLimitOverridesStarterCount(t *testing.T) {
|
||||
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1))
|
||||
items := []string{"q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10"}
|
||||
svc := &customAgentService{
|
||||
repo: &suggestionLimitAgentRepo{agent: newCuratedStarterAgent(6, items)},
|
||||
}
|
||||
|
||||
got, err := svc.GetSuggestedQuestions(ctx, "agent-1", nil, nil, nil, 10)
|
||||
require.NoError(t, err)
|
||||
// Before the fix limit was clamped to Starters.Count (6); now the explicit
|
||||
// request of 10 is honored.
|
||||
assert.Len(t, got, 10)
|
||||
}
|
||||
|
||||
// TestGetSuggestedQuestions_SmallerLimitStillHonored guards the other
|
||||
// direction: a limit below Starters.Count must also take effect.
|
||||
func TestGetSuggestedQuestions_SmallerLimitStillHonored(t *testing.T) {
|
||||
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1))
|
||||
items := []string{"q1", "q2", "q3", "q4", "q5", "q6"}
|
||||
svc := &customAgentService{
|
||||
repo: &suggestionLimitAgentRepo{agent: newCuratedStarterAgent(6, items)},
|
||||
}
|
||||
|
||||
got, err := svc.GetSuggestedQuestions(ctx, "agent-1", nil, nil, nil, 2)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, got, 2)
|
||||
}
|
||||
|
||||
// TestGetSuggestedQuestions_UnspecifiedLimitFallsBackToStarterCount confirms
|
||||
// that omitting the limit (<= 0) still uses the agent's configured count.
|
||||
func TestGetSuggestedQuestions_UnspecifiedLimitFallsBackToStarterCount(t *testing.T) {
|
||||
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1))
|
||||
items := []string{"q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8"}
|
||||
svc := &customAgentService{
|
||||
repo: &suggestionLimitAgentRepo{agent: newCuratedStarterAgent(4, items)},
|
||||
}
|
||||
|
||||
got, err := svc.GetSuggestedQuestions(ctx, "agent-1", nil, nil, nil, 0)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, got, 4)
|
||||
}
|
||||
|
||||
// TestGetSuggestedQuestions_LimitBoundedByMax ensures an oversized limit is
|
||||
// capped so it cannot inflate the downstream candidate pool without bound.
|
||||
func TestGetSuggestedQuestions_LimitBoundedByMax(t *testing.T) {
|
||||
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1))
|
||||
items := make([]string, 0, 100)
|
||||
for i := 0; i < 100; i++ {
|
||||
items = append(items, "q"+string(rune('A'+i%26))+string(rune('0'+i/26)))
|
||||
}
|
||||
svc := &customAgentService{
|
||||
repo: &suggestionLimitAgentRepo{agent: newCuratedStarterAgent(6, items)},
|
||||
}
|
||||
|
||||
got, err := svc.GetSuggestedQuestions(ctx, "agent-1", nil, nil, nil, 999)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, got, suggestionMaxLimit)
|
||||
}
|
||||
@@ -322,9 +322,8 @@ func (s *embedChannelService) SuggestedQuestions(
|
||||
if ch == nil || !ch.ShowSuggestedQuestions {
|
||||
return nil, nil
|
||||
}
|
||||
if limit <= 0 {
|
||||
limit = 6
|
||||
}
|
||||
// A non-positive limit is forwarded as "unspecified" so GetSuggestedQuestions
|
||||
// falls back to the agent's configured starter count rather than a fixed 6.
|
||||
kbIDs := s.resolveKnowledgeBaseIDs(ctx, ch)
|
||||
return s.agentService.GetSuggestedQuestions(ctx, ch.AgentID, kbIDs, nil, nil, limit)
|
||||
}
|
||||
|
||||
@@ -2170,19 +2170,39 @@ func (s *wikiIngestService) publishDraftPages(ctx context.Context, kbID string,
|
||||
}
|
||||
}
|
||||
|
||||
// writeDedupItemXML renders a single entity/concept entry as a structured XML
|
||||
// block for the deduplication prompt. Structured form (versus a single
|
||||
// pipe-separated line) helps the LLM reliably tell name / aliases / type apart
|
||||
// and reduces nonsensical merges like "居民身份证" → "工作居住证".
|
||||
func writeDedupItemXML(buf *strings.Builder, slug, name, itemType string, aliases []string) {
|
||||
fmt.Fprintf(buf, " <item slug=%q type=%q>\n", slug, itemType)
|
||||
fmt.Fprintf(buf, " <name>%s</name>\n", xmlEscape(name))
|
||||
for _, alias := range aliases {
|
||||
// writeDedupCandidateGroup renders one new item together with its own
|
||||
// similarity-candidate existing pages, nested under a <candidates> element.
|
||||
// This per-item grouping is what constrains the dedup model to local
|
||||
// decisions (see the grouping rationale in deduplicateExtractedBatch). The
|
||||
// candidate pages keep their aliases so the model still has the acronym /
|
||||
// translation signal it needs to accept a legitimate merge.
|
||||
func writeDedupCandidateGroup(
|
||||
buf *strings.Builder, item extractedItem, itemType string, candidates []*types.WikiPageLite,
|
||||
) {
|
||||
fmt.Fprintf(buf, " <item slug=%q type=%q>\n", item.Slug, itemType)
|
||||
fmt.Fprintf(buf, " <name>%s</name>\n", xmlEscape(item.Name))
|
||||
for _, alias := range item.Aliases {
|
||||
if alias == "" {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(buf, " <alias>%s</alias>\n", xmlEscape(alias))
|
||||
}
|
||||
buf.WriteString(" <candidates>\n")
|
||||
for _, p := range candidates {
|
||||
if p == nil {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(buf, " <page slug=%q type=%q>\n", p.Slug, p.PageType)
|
||||
fmt.Fprintf(buf, " <name>%s</name>\n", xmlEscape(p.Title))
|
||||
for _, alias := range []string(p.Aliases) {
|
||||
if alias == "" {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(buf, " <alias>%s</alias>\n", xmlEscape(alias))
|
||||
}
|
||||
buf.WriteString(" </page>\n")
|
||||
}
|
||||
buf.WriteString(" </candidates>\n")
|
||||
buf.WriteString(" </item>\n")
|
||||
}
|
||||
|
||||
@@ -2226,7 +2246,16 @@ func (s *wikiIngestService) deduplicateExtractedBatch(
|
||||
// Build the candidate set: for each new item, ask the repo for
|
||||
// the top-K trigram-similar pages and union the results. Dedup by
|
||||
// slug as we go so the prompt only carries each candidate once.
|
||||
//
|
||||
// itemCandidates additionally records, per new item, the slugs that
|
||||
// surfaced for THAT item specifically. The prompt only ever sees the
|
||||
// flattened union, so validMerge below uses this per-item scoping to
|
||||
// reject a merge whose target was pulled in for a *different* item —
|
||||
// the class of hallucination the union otherwise enables (e.g. weak
|
||||
// models emitting entity/tencent-open → entity/hiring-agent, which
|
||||
// share no trigram signal and were never candidates for each other).
|
||||
candidatePages := make(map[string]*types.WikiPageLite)
|
||||
itemCandidates := make(map[string]map[string]bool)
|
||||
probe := func(item extractedItem) {
|
||||
queries := make([]string, 0, 1+len(item.Aliases))
|
||||
if item.Name != "" {
|
||||
@@ -2237,6 +2266,11 @@ func (s *wikiIngestService) deduplicateExtractedBatch(
|
||||
queries = append(queries, alias)
|
||||
}
|
||||
}
|
||||
own := itemCandidates[item.Slug]
|
||||
if own == nil {
|
||||
own = make(map[string]bool)
|
||||
itemCandidates[item.Slug] = own
|
||||
}
|
||||
for _, q := range queries {
|
||||
pages, err := s.wikiService.FindSimilarPages(ctx, kbID, q,
|
||||
[]string{types.WikiPageTypeEntity, types.WikiPageTypeConcept},
|
||||
@@ -2252,6 +2286,7 @@ func (s *wikiIngestService) deduplicateExtractedBatch(
|
||||
if _, ok := candidatePages[p.Slug]; !ok {
|
||||
candidatePages[p.Slug] = p
|
||||
}
|
||||
own[p.Slug] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2270,25 +2305,59 @@ func (s *wikiIngestService) deduplicateExtractedBatch(
|
||||
logger.Infof(ctx, "wiki ingest: %d similar existing pages selected for %d new items",
|
||||
len(candidatePages), len(entities)+len(concepts))
|
||||
|
||||
var existingBuf strings.Builder
|
||||
for _, p := range candidatePages {
|
||||
writeDedupItemXML(&existingBuf, p.Slug, p.Title, p.PageType, []string(p.Aliases))
|
||||
// Group each new item with ONLY the existing pages that surfaced for
|
||||
// its own similarity probe. Presenting the model two flat lists (all
|
||||
// new items × all candidates) invites cross-item mispairings — it has
|
||||
// no way to tell which candidate is relevant to which item, so a weak
|
||||
// model pairs unrelated slugs that merely coexist in the prompt. A
|
||||
// per-item shortlist turns dedup into a local yes/no decision against
|
||||
// a handful of genuinely-similar pages and makes cross-item pairings
|
||||
// structurally unnatural to express. Items with no candidate are
|
||||
// omitted entirely (they cannot merge and only add hallucination
|
||||
// surface + tokens).
|
||||
var candBuf strings.Builder
|
||||
groups := 0
|
||||
renderGroup := func(item extractedItem, itemType string) {
|
||||
cset := itemCandidates[item.Slug]
|
||||
if len(cset) == 0 {
|
||||
return
|
||||
}
|
||||
slugs := make([]string, 0, len(cset))
|
||||
for slug := range cset {
|
||||
// Skip the item's own slug: an identically-slugged existing
|
||||
// page is a re-ingest/update, not a merge target.
|
||||
if slug == item.Slug {
|
||||
continue
|
||||
}
|
||||
if _, ok := candidatePages[slug]; ok {
|
||||
slugs = append(slugs, slug)
|
||||
}
|
||||
}
|
||||
if len(slugs) == 0 {
|
||||
return
|
||||
}
|
||||
sort.Strings(slugs)
|
||||
pages := make([]*types.WikiPageLite, 0, len(slugs))
|
||||
for _, slug := range slugs {
|
||||
pages = append(pages, candidatePages[slug])
|
||||
}
|
||||
writeDedupCandidateGroup(&candBuf, item, itemType, pages)
|
||||
groups++
|
||||
}
|
||||
if existingBuf.Len() == 0 {
|
||||
for _, item := range entities {
|
||||
renderGroup(item, "entity")
|
||||
}
|
||||
for _, item := range concepts {
|
||||
renderGroup(item, "concept")
|
||||
}
|
||||
if groups == 0 {
|
||||
// Every new item's candidate list is empty after scoping —
|
||||
// nothing the model could safely merge.
|
||||
return entities, concepts
|
||||
}
|
||||
|
||||
var newBuf strings.Builder
|
||||
for _, item := range entities {
|
||||
writeDedupItemXML(&newBuf, item.Slug, item.Name, "entity", item.Aliases)
|
||||
}
|
||||
for _, item := range concepts {
|
||||
writeDedupItemXML(&newBuf, item.Slug, item.Name, "concept", item.Aliases)
|
||||
}
|
||||
|
||||
dedupeJSON, err := s.generateWithTemplate(ctx, chatModel, agent.WikiDeduplicationPrompt, map[string]string{
|
||||
"NewItems": newBuf.String(),
|
||||
"ExistingPages": existingBuf.String(),
|
||||
"Candidates": candBuf.String(),
|
||||
})
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "wiki ingest: deduplication LLM call failed: %v", err)
|
||||
@@ -2309,36 +2378,9 @@ func (s *wikiIngestService) deduplicateExtractedBatch(
|
||||
return entities, concepts
|
||||
}
|
||||
|
||||
// Build the existing-slug set from the candidate map: anything not
|
||||
// in candidates is rejected as an LLM hallucination, since by
|
||||
// construction the model only ever saw those slugs as merge
|
||||
// targets. Compare with the legacy "look up against allPages"
|
||||
// path which had a wider acceptance window.
|
||||
existingSlugs := make(map[string]bool, len(candidatePages))
|
||||
for slug := range candidatePages {
|
||||
existingSlugs[slug] = true
|
||||
}
|
||||
|
||||
validMerge := func(srcSlug, dstSlug string) bool {
|
||||
if !existingSlugs[dstSlug] {
|
||||
logger.Warnf(ctx, "wiki ingest: dedup rejected %s → %s (target slug does not exist in candidate set)", srcSlug, dstSlug)
|
||||
return false
|
||||
}
|
||||
srcSlash := strings.Index(srcSlug, "/")
|
||||
dstSlash := strings.Index(dstSlug, "/")
|
||||
if srcSlash <= 0 || dstSlash <= 0 {
|
||||
// A type-prefixed slug must look like "entity/foo" or
|
||||
// "concept/bar". An LLM that emits an un-prefixed slug
|
||||
// here is hallucinating; reject rather than fall through
|
||||
// the prefix-equality check (which would treat both empty
|
||||
// prefixes as a match).
|
||||
logger.Warnf(ctx, "wiki ingest: dedup rejected %s → %s (missing type prefix)", srcSlug, dstSlug)
|
||||
return false
|
||||
}
|
||||
srcPrefix := srcSlug[:srcSlash+1]
|
||||
dstPrefix := dstSlug[:dstSlash+1]
|
||||
if srcPrefix != dstPrefix {
|
||||
logger.Warnf(ctx, "wiki ingest: dedup rejected %s → %s (type mismatch: %s vs %s)", srcSlug, dstSlug, srcPrefix, dstPrefix)
|
||||
if reason := dedupMergeRejectReason(srcSlug, dstSlug, itemCandidates[srcSlug]); reason != "" {
|
||||
logger.Warnf(ctx, "wiki ingest: dedup rejected %s → %s (%s)", srcSlug, dstSlug, reason)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
|
||||
@@ -2003,9 +2003,27 @@ func (s *wikiIngestService) reduceSlugUpdates(
|
||||
|
||||
if len(additions) > 0 || len(retracts) > 0 {
|
||||
titles := batchCtx.SlugTitleMany(ctx, []string(page.OutLinks))
|
||||
|
||||
// aliaser escapes high-entropy slugs behind short reference tokens
|
||||
// (ref-1, ref-2, …) for the editor LLM, then translates them back to
|
||||
// real slugs after generation (see dealiasContent below).
|
||||
aliaser := newSlugAliaser()
|
||||
|
||||
// Escape every out-link slug behind a reference token so the editor
|
||||
// never has to retype a real slug — this is where UUID-based summary
|
||||
// slugs (summary/<uuid>) got mangled into 404-ing links. Both the
|
||||
// <valid_wiki_links> listing AND the [[...]] refs already present in
|
||||
// <existing_page_content> are aliased with the SAME token map, so the
|
||||
// model sees one consistent, copy-safe identifier space; we translate
|
||||
// the tokens back to real slugs after generation.
|
||||
known := make(map[string]struct{}, len(page.OutLinks))
|
||||
for _, outSlug := range page.OutLinks {
|
||||
known[outSlug] = struct{}{}
|
||||
aliaser.token(outSlug) // pre-assign for stable ordering
|
||||
}
|
||||
for _, outSlug := range page.OutLinks {
|
||||
if title := titles[outSlug]; title != "" {
|
||||
fmt.Fprintf(&relatedSlugs, "- %s (%s)\n", outSlug, title)
|
||||
fmt.Fprintf(&relatedSlugs, "- %s (%s)\n", aliaser.token(outSlug), title)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2013,6 +2031,7 @@ func (s *wikiIngestService) reduceSlugUpdates(
|
||||
// [c003]. They are internal ingest metadata; keep the editor context
|
||||
// clean so a subsequent update cannot copy them into rewritten prose.
|
||||
existingContent := stripWikiInlineChunkCitations(page.Content)
|
||||
existingContent = aliaser.aliasContent(existingContent, known)
|
||||
if !exists || existingContent == "" {
|
||||
existingContent = "(New page)"
|
||||
}
|
||||
@@ -2060,6 +2079,10 @@ func (s *wikiIngestService) reduceSlugUpdates(
|
||||
})
|
||||
|
||||
if err == nil && updatedContent != "" {
|
||||
// Translate reference tokens (ref-N) the model copied from the
|
||||
// aliased context back to their real slugs BEFORE the content is
|
||||
// parsed/stored, so out_links reflect real pages again.
|
||||
updatedContent = aliaser.dealiasContent(updatedContent)
|
||||
updatedSummary, updatedBody := splitSummaryLine(updatedContent)
|
||||
if updatedBody != "" {
|
||||
page.Content = updatedBody
|
||||
|
||||
@@ -23,11 +23,15 @@ import (
|
||||
// external calls, and it only ever *removes* candidates from the prompt —
|
||||
// the downstream validMerge check still guards the final write.
|
||||
const (
|
||||
// dedupCandidateTopK is how many existing pages we keep per new item
|
||||
// even if none pass the score floor. Guarantees the LLM sees a small
|
||||
// ordered shortlist rather than an empty list when nothing matches
|
||||
// strongly.
|
||||
dedupCandidateTopK = 20
|
||||
// dedupCandidateTopK bounds how many trigram-similar existing pages
|
||||
// each new item's similarity probe returns (the LIMIT passed to
|
||||
// FindSimilarPages, applied per query term = name + each alias). Kept
|
||||
// deliberately small: the DB already orders by similarity desc behind a
|
||||
// pg_trgm threshold, so a genuine same-entity target is essentially
|
||||
// always the top hit. A tight K keeps each item's <candidates> list in
|
||||
// the dedup prompt short, which improves the model's precision and cuts
|
||||
// tokens, at negligible recall cost.
|
||||
dedupCandidateTopK = 5
|
||||
|
||||
// dedupCandidateScoreFloor is the Jaccard floor. Pairs at or above
|
||||
// this similarity are always included regardless of the top-K cap.
|
||||
@@ -170,6 +174,44 @@ func selectDedupCandidatePages(
|
||||
return out
|
||||
}
|
||||
|
||||
// dedupMergeRejectReason validates a single LLM-proposed merge (srcSlug →
|
||||
// dstSlug) against deterministic, model-independent rules. It returns an
|
||||
// empty string when the merge is allowed, or a short human-readable reason
|
||||
// when it must be rejected. srcCandidates is the set of existing-page slugs
|
||||
// that surfaced for srcSlug's OWN similarity probe (see itemCandidates in
|
||||
// deduplicateExtractedBatch).
|
||||
//
|
||||
// The per-item scoping check is the key guard: the dedup prompt shows the
|
||||
// model a flattened union of candidates across every new item, so nothing
|
||||
// stops a weak model from pairing an item with a page that was only similar
|
||||
// to a *different* item (observed: entity/tencent-open → entity/hiring-agent,
|
||||
// which share no trigram signal). Requiring dstSlug to be one of srcSlug's
|
||||
// own candidates rejects that entire class without depending on the model
|
||||
// getting the semantic judgment right.
|
||||
func dedupMergeRejectReason(srcSlug, dstSlug string, srcCandidates map[string]bool) string {
|
||||
if !srcCandidates[dstSlug] {
|
||||
// Covers both an outright hallucinated target (in no candidate
|
||||
// set at all) and a real page that was only similar to another
|
||||
// item. Either way the pair lacks a similarity signal for THIS
|
||||
// item, so it is not a safe merge.
|
||||
return "target is not a similarity candidate for this item"
|
||||
}
|
||||
srcSlash := strings.Index(srcSlug, "/")
|
||||
dstSlash := strings.Index(dstSlug, "/")
|
||||
if srcSlash <= 0 || dstSlash <= 0 {
|
||||
// A type-prefixed slug must look like "entity/foo" or
|
||||
// "concept/bar". An LLM that emits an un-prefixed slug here is
|
||||
// hallucinating; reject rather than fall through the prefix-
|
||||
// equality check (which would treat both empty prefixes as a
|
||||
// match).
|
||||
return "missing type prefix"
|
||||
}
|
||||
if srcSlug[:srcSlash+1] != dstSlug[:dstSlash+1] {
|
||||
return "type mismatch: " + srcSlug[:srcSlash+1] + " vs " + dstSlug[:dstSlash+1]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// dedupPairScore is the max similarity between any surface form of a and
|
||||
// b (plus the slug-token similarity). Slug and name signals live in
|
||||
// different symbol spaces (ASCII pinyin vs raw surface form) so we take
|
||||
|
||||
@@ -7,6 +7,61 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
func TestDedupMergeRejectReason(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
src, dst string
|
||||
candidates map[string]bool
|
||||
wantAllowed bool
|
||||
}{
|
||||
{
|
||||
name: "allowed: dst is a candidate for this item, same type prefix",
|
||||
src: "entity/acme-corp",
|
||||
dst: "entity/acme-corporation",
|
||||
candidates: map[string]bool{"entity/acme-corporation": true},
|
||||
wantAllowed: true,
|
||||
},
|
||||
{
|
||||
name: "rejected: dst similar to a DIFFERENT item (union hallucination)",
|
||||
src: "entity/tencent-open",
|
||||
dst: "entity/hiring-agent",
|
||||
candidates: map[string]bool{"entity/tencent-ur": true}, // hiring-agent not here
|
||||
wantAllowed: false,
|
||||
},
|
||||
{
|
||||
name: "rejected: dst is not a candidate at all (pure hallucination)",
|
||||
src: "entity/hy3-preview",
|
||||
dst: "entity/llm-cli-tool",
|
||||
candidates: nil,
|
||||
wantAllowed: false,
|
||||
},
|
||||
{
|
||||
name: "rejected: type mismatch even when dst is a candidate",
|
||||
src: "entity/foo",
|
||||
dst: "concept/foo",
|
||||
candidates: map[string]bool{"concept/foo": true},
|
||||
wantAllowed: false,
|
||||
},
|
||||
{
|
||||
name: "rejected: missing type prefix",
|
||||
src: "foo",
|
||||
dst: "entity/foo",
|
||||
candidates: map[string]bool{"entity/foo": true},
|
||||
wantAllowed: false,
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
reason := dedupMergeRejectReason(tc.src, tc.dst, tc.candidates)
|
||||
gotAllowed := reason == ""
|
||||
if gotAllowed != tc.wantAllowed {
|
||||
t.Fatalf("dedupMergeRejectReason(%q, %q) allowed=%v (reason=%q), want allowed=%v",
|
||||
tc.src, tc.dst, gotAllowed, reason, tc.wantAllowed)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// helper: build a minimal entity/concept WikiPage.
|
||||
func makePage(slug, title, typ string, aliases ...string) *types.WikiPage {
|
||||
return &types.WikiPage{
|
||||
|
||||
@@ -918,6 +918,151 @@ func normalizeSlug(slug string) string {
|
||||
return slug
|
||||
}
|
||||
|
||||
// slugNamespace returns the prefix of a slug up to (but excluding) the first
|
||||
// '/', e.g. "summary/abc" -> "summary". Slugs without a '/' map to "".
|
||||
func slugNamespace(slug string) string {
|
||||
if i := strings.IndexByte(slug, '/'); i >= 0 {
|
||||
return slug[:i]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// rewriteDeadWikiLinks walks every [[slug]] / [[slug|display]] occurrence in
|
||||
// content and lets `resolve` decide, per link, whether to rewrite the slug.
|
||||
// `resolve` receives the normalized slug and its display text and returns the
|
||||
// replacement slug plus true to rewrite, or ("", false) to leave the link
|
||||
// untouched. Display text is preserved verbatim. This is a pure helper — the
|
||||
// resolution policy lives entirely in the callback.
|
||||
func rewriteDeadWikiLinks(content string, resolve func(normSlug, display string) (string, bool)) (string, bool) {
|
||||
changed := false
|
||||
out := wikiLinkRegex.ReplaceAllStringFunc(content, func(match string) string {
|
||||
inner := match[2 : len(match)-2]
|
||||
rawSlug := inner
|
||||
display := ""
|
||||
if parts := strings.SplitN(inner, "|", 2); len(parts) == 2 {
|
||||
rawSlug = parts[0]
|
||||
display = strings.TrimSpace(parts[1])
|
||||
}
|
||||
norm := normalizeSlug(rawSlug)
|
||||
if norm == "" {
|
||||
return match
|
||||
}
|
||||
newSlug, ok := resolve(norm, display)
|
||||
if !ok || newSlug == "" || newSlug == norm {
|
||||
return match
|
||||
}
|
||||
changed = true
|
||||
if display != "" {
|
||||
return "[[" + newSlug + "|" + display + "]]"
|
||||
}
|
||||
return "[[" + newSlug + "]]"
|
||||
})
|
||||
return out, changed
|
||||
}
|
||||
|
||||
// RepairContentLinks rewrites [[slug]] / [[slug|display]] references in
|
||||
// `content` whose target does not exist in the KB but is almost certainly a
|
||||
// mangled form of a real page. The canonical case: an LLM re-typed a summary
|
||||
// page's UUID-based slug and inserted/dropped a hex digit
|
||||
// (summary/…06fb5d5b5b5e → summary/…06fb14d5b14b14e), producing a link that
|
||||
// 404s and can never be recovered by exact lookup.
|
||||
//
|
||||
// Unlike stripDeadWikiLinks (the ingest cleanup pass), this method is
|
||||
// REWRITE-ONLY: a dead link is corrected only when a confident live candidate
|
||||
// exists; otherwise it is left completely untouched. It NEVER strips a link to
|
||||
// plain text, so it is safe on any write path — including writes whose targets
|
||||
// legitimately do not exist yet (those simply stay as-is until they do).
|
||||
//
|
||||
// The candidate pool for each dead link is scoped to live slugs that share the
|
||||
// same namespace prefix (a dead `summary/<uuid>` only resolves against live
|
||||
// `summary/*` slugs). Scoping keeps the bigram-similarity lever safe: distinct
|
||||
// high-entropy UUIDs in one namespace don't collide, while a one-character
|
||||
// mangle stays comfortably above threshold against its true source.
|
||||
//
|
||||
// Returns the possibly-updated content and whether any rewrite happened.
|
||||
// Errors are only returned for hard repo failures; callers may treat repair as
|
||||
// best-effort and ignore them.
|
||||
func (s *wikiPageService) RepairContentLinks(
|
||||
ctx context.Context, kbID, selfSlug, content string,
|
||||
) (string, bool, error) {
|
||||
if strings.TrimSpace(content) == "" {
|
||||
return content, false, nil
|
||||
}
|
||||
outLinks := s.parseOutLinks(content)
|
||||
if len(outLinks) == 0 {
|
||||
return content, false, nil
|
||||
}
|
||||
|
||||
existMap, err := s.repo.ExistsSlugs(ctx, kbID, outLinks)
|
||||
if err != nil {
|
||||
return content, false, err
|
||||
}
|
||||
deadPrefixes := make(map[string]struct{})
|
||||
for _, l := range outLinks {
|
||||
if l == selfSlug || existMap[l] {
|
||||
continue
|
||||
}
|
||||
deadPrefixes[slugNamespace(l)] = struct{}{}
|
||||
}
|
||||
if len(deadPrefixes) == 0 {
|
||||
return content, false, nil
|
||||
}
|
||||
|
||||
allSlugs, err := s.repo.ListAllSlugs(ctx, kbID)
|
||||
if err != nil {
|
||||
return content, false, err
|
||||
}
|
||||
liveByPrefix := make(map[string]map[string]struct{})
|
||||
var candidateSlugs []string
|
||||
for _, sl := range allSlugs {
|
||||
ns := slugNamespace(sl)
|
||||
if _, want := deadPrefixes[ns]; !want {
|
||||
continue
|
||||
}
|
||||
set, ok := liveByPrefix[ns]
|
||||
if !ok {
|
||||
set = make(map[string]struct{})
|
||||
liveByPrefix[ns] = set
|
||||
}
|
||||
set[sl] = struct{}{}
|
||||
candidateSlugs = append(candidateSlugs, sl)
|
||||
}
|
||||
if len(candidateSlugs) == 0 {
|
||||
return content, false, nil
|
||||
}
|
||||
|
||||
// Build a title -> slug reverse lookup for candidate pages so the
|
||||
// display-text lever (the safest, most precise one) can fire. Bounded to
|
||||
// the relevant namespaces so this stays cheap even on large KBs.
|
||||
titleToSlug := make(map[string]string)
|
||||
if lites, lerr := s.repo.ListBySlugs(ctx, kbID, candidateSlugs); lerr == nil {
|
||||
for _, lp := range lites {
|
||||
if lp != nil && lp.Title != "" {
|
||||
titleToSlug[lp.Title] = lp.Slug
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
resolveCache := make(map[string]string)
|
||||
newContent, changed := rewriteDeadWikiLinks(content, func(norm, display string) (string, bool) {
|
||||
if norm == selfSlug || existMap[norm] {
|
||||
return "", false
|
||||
}
|
||||
key := norm + "\x00" + display
|
||||
if cached, ok := resolveCache[key]; ok {
|
||||
return cached, cached != ""
|
||||
}
|
||||
resolved, ok := resolveDeadSlug(norm, display, liveByPrefix[slugNamespace(norm)], titleToSlug)
|
||||
if !ok || resolved == norm {
|
||||
resolveCache[key] = ""
|
||||
return "", false
|
||||
}
|
||||
resolveCache[key] = resolved
|
||||
return resolved, true
|
||||
})
|
||||
return newContent, changed, nil
|
||||
}
|
||||
|
||||
// updateInLinks adds the source slug to the in_links of target pages
|
||||
func (s *wikiPageService) updateInLinks(ctx context.Context, kbID string, sourceSlug string, targets types.StringArray) {
|
||||
for _, targetSlug := range targets {
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/repository"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
@@ -140,6 +141,60 @@ func TestParseOutLinks(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRepairContentLinks(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open(fmt.Sprintf("file:%s?mode=memory&cache=shared", t.Name())), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.AutoMigrate(&types.WikiFolder{}, &types.WikiPage{}))
|
||||
|
||||
ctx := context.Background()
|
||||
repo := repository.NewWikiPageRepository(db)
|
||||
svc := NewWikiPageService(repo, nil, nil, nil, nil)
|
||||
const kbID = "kb-repair"
|
||||
now := time.Now()
|
||||
|
||||
seed := func(slug, title, pageType string) {
|
||||
require.NoError(t, repo.Create(ctx, &types.WikiPage{
|
||||
ID: uuid.New().String(), TenantID: 1, KnowledgeBaseID: kbID,
|
||||
Slug: slug, Title: title, PageType: pageType,
|
||||
Status: types.WikiPageStatusPublished, Version: 1,
|
||||
CreatedAt: now, UpdatedAt: now,
|
||||
}))
|
||||
}
|
||||
|
||||
// Real summary page (clean UUID slug) + a distractor summary + an entity.
|
||||
realSummary := "summary/07a20bb1-a662-47cf-9929-06fb5d5b5b5e"
|
||||
seed(realSummary, "Weknora 试错记录.md - Summary", types.WikiPageTypeSummary)
|
||||
seed("summary/fcadcaab-e094-4037-b71c-9edfdcdba058", "Another Doc - Summary", types.WikiPageTypeSummary)
|
||||
seed("entity/mongodb", "MongoDB", types.WikiPageTypeEntity)
|
||||
|
||||
t.Run("mangled uuid summary link repaired via bigram", func(t *testing.T) {
|
||||
// One hex digit inserted into the last group — 404s on exact lookup.
|
||||
content := "See [[summary/07a20bb1-a662-47cf-9929-06fb14d5b14b14e|Weknora 试错记录.md - Summary]] for context."
|
||||
got, changed, err := svc.RepairContentLinks(ctx, kbID, "synthesis/notes", content)
|
||||
require.NoError(t, err)
|
||||
require.True(t, changed, "expected the mangled summary link to be rewritten")
|
||||
require.Contains(t, got, "[["+realSummary+"|Weknora 试错记录.md - Summary]]")
|
||||
require.NotContains(t, got, "06fb14d5b14b14e")
|
||||
})
|
||||
|
||||
t.Run("live links untouched", func(t *testing.T) {
|
||||
content := "Fine: [[entity/mongodb]] and [[" + realSummary + "]]."
|
||||
got, changed, err := svc.RepairContentLinks(ctx, kbID, "synthesis/notes", content)
|
||||
require.NoError(t, err)
|
||||
require.False(t, changed)
|
||||
require.Equal(t, content, got)
|
||||
})
|
||||
|
||||
t.Run("unresolvable dead link left as-is, never stripped", func(t *testing.T) {
|
||||
// A future entity page that doesn't exist and isn't similar to anything.
|
||||
content := "Pending: [[entity/some-brand-new-topic|New Topic]]."
|
||||
got, changed, err := svc.RepairContentLinks(ctx, kbID, "synthesis/notes", content)
|
||||
require.NoError(t, err)
|
||||
require.False(t, changed)
|
||||
require.Equal(t, content, got, "unresolvable links must be preserved verbatim, not stripped")
|
||||
})
|
||||
}
|
||||
|
||||
func TestNormalizeSlug(t *testing.T) {
|
||||
tests := []struct {
|
||||
input string
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// slugAliaser maps real wiki slugs to short, low-entropy reference tokens
|
||||
// (ref-1, ref-2, …) so the ingest editor LLM never has to reproduce a
|
||||
// high-entropy slug verbatim — most importantly the UUID-based summary slugs
|
||||
// (summary/<knowledgeID>) that models routinely mangle by inserting or
|
||||
// dropping hex digits. The model copies the tiny token; we translate tokens
|
||||
// back to real slugs on output.
|
||||
//
|
||||
// This is the generation-stage counterpart to wiki_write_page's slug
|
||||
// validation: rather than repairing a mangled slug after the fact, it removes
|
||||
// the opportunity to mangle at the source. It mirrors the chunk-alias
|
||||
// (c000/c001) indirection already used by the chunk-citation pass in
|
||||
// wiki_ingest_cite.go.
|
||||
//
|
||||
// A slugAliaser is single-use and NOT safe for concurrent use; construct one
|
||||
// per LLM call.
|
||||
type slugAliaser struct {
|
||||
toToken map[string]string // real slug -> token
|
||||
toSlug map[string]string // token -> real slug
|
||||
}
|
||||
|
||||
func newSlugAliaser() *slugAliaser {
|
||||
return &slugAliaser{
|
||||
toToken: make(map[string]string),
|
||||
toSlug: make(map[string]string),
|
||||
}
|
||||
}
|
||||
|
||||
// token returns the stable token for a real slug, assigning a fresh one on
|
||||
// first use. An empty slug returns "". Tokens have no '/' so they can never
|
||||
// collide with a namespaced real slug (entity/…, summary/…).
|
||||
func (a *slugAliaser) token(realSlug string) string {
|
||||
realSlug = strings.TrimSpace(realSlug)
|
||||
if realSlug == "" {
|
||||
return ""
|
||||
}
|
||||
if t, ok := a.toToken[realSlug]; ok {
|
||||
return t
|
||||
}
|
||||
t := fmt.Sprintf("ref-%d", len(a.toToken)+1)
|
||||
a.toToken[realSlug] = t
|
||||
a.toSlug[t] = realSlug
|
||||
return t
|
||||
}
|
||||
|
||||
// empty reports whether no tokens have been assigned yet (nothing to alias).
|
||||
func (a *slugAliaser) empty() bool { return len(a.toToken) == 0 }
|
||||
|
||||
// aliasContent rewrites [[realSlug|disp]] / [[realSlug]] occurrences to their
|
||||
// token form, but only for slugs present in `known`. Unknown links are left
|
||||
// untouched. Assigns tokens on demand so a slug that appears only in the body
|
||||
// (not in the listing) still gets a consistent token.
|
||||
func (a *slugAliaser) aliasContent(content string, known map[string]struct{}) string {
|
||||
if content == "" || len(known) == 0 {
|
||||
return content
|
||||
}
|
||||
out, _ := rewriteDeadWikiLinks(content, func(norm, _ string) (string, bool) {
|
||||
if _, ok := known[norm]; !ok {
|
||||
return "", false
|
||||
}
|
||||
return a.token(norm), true
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
// dealiasContent rewrites [[token|disp]] / [[token]] occurrences back to their
|
||||
// real slug. Tokens with no mapping are left untouched — they fall through to
|
||||
// the ordinary parse/dead-link-cleanup path, which is the correct behavior for
|
||||
// anything the model invented that isn't a known reference.
|
||||
func (a *slugAliaser) dealiasContent(content string) string {
|
||||
if content == "" || a.empty() {
|
||||
return content
|
||||
}
|
||||
out, _ := rewriteDeadWikiLinks(content, func(norm, _ string) (string, bool) {
|
||||
real, ok := a.toSlug[norm]
|
||||
if !ok {
|
||||
return "", false
|
||||
}
|
||||
return real, true
|
||||
})
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSlugAliaser_RoundTripEscapesUUIDSlugs(t *testing.T) {
|
||||
summarySlug := "summary/07a20bb1-a662-47cf-9929-06fb5d5b5b5e"
|
||||
entitySlug := "entity/mongodb"
|
||||
known := map[string]struct{}{summarySlug: {}, entitySlug: {}}
|
||||
|
||||
a := newSlugAliaser()
|
||||
// Pre-assign tokens the way the ingest listing loop does.
|
||||
tSummary := a.token(summarySlug)
|
||||
tEntity := a.token(entitySlug)
|
||||
if tSummary == summarySlug || tEntity == entitySlug {
|
||||
t.Fatalf("tokens must differ from real slugs: %q %q", tSummary, tEntity)
|
||||
}
|
||||
if strings.Contains(tSummary, "/") {
|
||||
t.Fatalf("token %q must not contain '/'", tSummary)
|
||||
}
|
||||
|
||||
body := "See [[" + summarySlug + "|Weknora 试错记录.md - Summary]] and [[" + entitySlug + "]]."
|
||||
aliased := a.aliasContent(body, known)
|
||||
|
||||
// The high-entropy UUID must no longer be present in what the model sees.
|
||||
if strings.Contains(aliased, "06fb5d5b5b5e") {
|
||||
t.Fatalf("aliased content still exposes the UUID: %q", aliased)
|
||||
}
|
||||
if !strings.Contains(aliased, "[["+tSummary+"|Weknora 试错记录.md - Summary]]") {
|
||||
t.Fatalf("summary link not aliased: %q", aliased)
|
||||
}
|
||||
if !strings.Contains(aliased, "[["+tEntity+"]]") {
|
||||
t.Fatalf("entity link not aliased: %q", aliased)
|
||||
}
|
||||
|
||||
// Round-trip must restore the original body exactly.
|
||||
if got := a.dealiasContent(aliased); got != body {
|
||||
t.Fatalf("dealias round-trip mismatch:\n got %q\n want %q", got, body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlugAliaser_UnknownTokensAndSlugsUntouched(t *testing.T) {
|
||||
a := newSlugAliaser()
|
||||
a.token("summary/real-uuid")
|
||||
|
||||
// A slug not in `known` must not be aliased.
|
||||
known := map[string]struct{}{"summary/real-uuid": {}}
|
||||
body := "keep [[entity/invented-by-model]] as-is"
|
||||
if got := a.aliasContent(body, known); got != body {
|
||||
t.Fatalf("unknown slug should be left untouched, got %q", got)
|
||||
}
|
||||
|
||||
// An unmapped token in output must be left untouched (falls through to the
|
||||
// normal dead-link cleanup path).
|
||||
out := "stray [[ref-999|X]] token"
|
||||
if got := a.dealiasContent(out); got != out {
|
||||
t.Fatalf("unmapped token should be left untouched, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlugAliaser_EmptyIsNoop(t *testing.T) {
|
||||
a := newSlugAliaser()
|
||||
if !a.empty() {
|
||||
t.Fatal("fresh aliaser must be empty")
|
||||
}
|
||||
body := "[[summary/x]] unchanged"
|
||||
if got := a.dealiasContent(body); got != body {
|
||||
t.Fatalf("empty aliaser dealias must be a no-op, got %q", got)
|
||||
}
|
||||
}
|
||||
@@ -563,7 +563,7 @@ func (h *CustomAgentHandler) GetAgentTypePresets(c *gin.Context) {
|
||||
// @Param knowledge_base_ids query string false "知识库ID列表(逗号分隔),覆盖智能体默认配置"
|
||||
// @Param knowledge_ids query string false "知识ID列表(逗号分隔),限定到具体文档"
|
||||
// @Param tag_scopes query string false "带知识库归属的标签范围(JSON)"
|
||||
// @Param limit query int false "返回数量上限(默认6)"
|
||||
// @Param limit query int false "返回数量上限(未传时使用智能体配置的开场问题数量,最大30)"
|
||||
// @Success 200 {object} map[string]interface{} "推荐问题列表"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Failure 404 {object} errors.AppError "智能体不存在"
|
||||
@@ -608,7 +608,10 @@ func (h *CustomAgentHandler) GetSuggestedQuestions(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
limit := 6
|
||||
// limit == 0 signals "unspecified" so the service falls back to the agent's
|
||||
// configured starter count. A provided value is passed through unchanged and
|
||||
// bounded by the service's safety cap.
|
||||
limit := 0
|
||||
if limitStr := c.Query("limit"); limitStr != "" {
|
||||
if parsed, err := strconv.Atoi(limitStr); err == nil && parsed > 0 {
|
||||
limit = parsed
|
||||
|
||||
@@ -382,13 +382,15 @@ func (h *EmbedChannelHandler) GetEmbedSuggestedQuestions(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"questions": []types.SuggestedQuestion{}}})
|
||||
return
|
||||
}
|
||||
limit := 6
|
||||
// limit == 0 signals "unspecified" so the channel agent's starter count
|
||||
// applies. A provided value is honored up to the embed cap.
|
||||
limit := 0
|
||||
if raw := c.Query("limit"); raw != "" {
|
||||
if n, err := strconv.Atoi(raw); err == nil && n > 0 {
|
||||
limit = n
|
||||
}
|
||||
if limit > 12 {
|
||||
limit = 12
|
||||
if limit > 12 {
|
||||
limit = 12
|
||||
}
|
||||
}
|
||||
}
|
||||
questions, err := h.embedSvc.SuggestedQuestions(c.Request.Context(), ch, limit)
|
||||
|
||||
@@ -540,9 +540,14 @@ func (h *OrganizationHandler) GenerateInviteCode(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// Wrap in `data` to match the ApiResponse<{invite_code}> contract both the
|
||||
// web frontend and the Go SDK expect; a flat top-level field is silently
|
||||
// dropped by those clients (they read data.invite_code).
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"invite_code": code,
|
||||
"success": true,
|
||||
"data": gin.H{
|
||||
"invite_code": code,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1827,18 +1832,18 @@ func (h *OrganizationHandler) toOrgResponse(ctx context.Context, org *types.Orga
|
||||
|
||||
// SearchTenantsForInvite searches candidate tenants for inviting to organization.
|
||||
//
|
||||
// Plan 3 (#1303) makes the tenant the unit of membership. This endpoint replaces
|
||||
// the older per-user search: it accepts a free-text query, looks up matching users
|
||||
// (by username/email), groups them by their TenantID, resolves the tenant's
|
||||
// canonical name, filters out tenants already in the org, and returns one row
|
||||
// per candidate tenant with one representative user attached for display.
|
||||
// Plan 3 (#1303) makes the tenant the unit of membership. Because a single user
|
||||
// may belong to multiple workspaces, matching by username/email is ambiguous
|
||||
// (which workspace did the admin mean?), so this endpoint matches strictly by
|
||||
// tenant (workspace) name: it resolves matching tenants, filters out tenants
|
||||
// already in the org, and returns one row per candidate tenant.
|
||||
//
|
||||
// @Summary 搜索可邀请的空间
|
||||
// @Description 搜索空间(排除已加入的空间)用于邀请加入组织;按空间去重,附带代表用户
|
||||
// @Description 按空间名搜索可邀请的空间(排除已加入的空间)用于邀请加入组织;按空间去重
|
||||
// @Tags 组织管理
|
||||
// @Produce json
|
||||
// @Param id path string true "组织ID"
|
||||
// @Param q query string true "搜索关键词(空间名、用户名或邮箱)"
|
||||
// @Param q query string true "搜索关键词(空间名)"
|
||||
// @Param limit query int false "返回数量限制" default(10)
|
||||
// @Success 200 {object} map[string]interface{}
|
||||
// @Failure 403 {object} apperrors.AppError
|
||||
@@ -1880,50 +1885,24 @@ func (h *OrganizationHandler) SearchTenantsForInvite(c *gin.Context) {
|
||||
existingTenantIDs[m.TenantID] = true
|
||||
}
|
||||
|
||||
// 1) Match users by query and group by TenantID. We over-fetch so the
|
||||
// de-duplication after filtering "already a member" tenants still
|
||||
// leaves us with enough candidates to fill `limit`.
|
||||
// User PII (email/username) is intentionally omitted from results:
|
||||
// org admins only need tenant identity to send an invite.
|
||||
users, err := h.userService.SearchUsers(ctx, query, limit*3+20)
|
||||
// Match tenants by name only. A single user may belong to multiple
|
||||
// workspaces, so resolving a query to "the user's tenant" is ambiguous;
|
||||
// the membership unit is the tenant, so we invite by workspace name.
|
||||
// SearchTenants uses page/pageSize; pageSize=limit*2 is a safe ceiling
|
||||
// given the soft cap of 50 above.
|
||||
tenantsByName, _, err := h.tenantService.SearchTenants(ctx, query, 0, 1, limit*2)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to search users: %v", err)
|
||||
logger.Errorf(ctx, "Failed to search tenants: %v", err)
|
||||
c.Error(apperrors.NewInternalServerError("Failed to search candidates"))
|
||||
return
|
||||
}
|
||||
|
||||
// 2) Direct tenant-name match (admins may want to invite by tenant name).
|
||||
// SearchTenants uses page/pageSize; pageSize=limit*2 is a safe ceiling
|
||||
// given the soft cap of 50 above.
|
||||
tenantsByName, _, _ := h.tenantService.SearchTenants(ctx, query, 0, 1, limit*2)
|
||||
|
||||
// Insertion-ordered map: first match wins, so the first user that
|
||||
// brought a tenant in becomes the representative.
|
||||
// Insertion-ordered map: first match wins, preserving search ordering.
|
||||
type entry struct {
|
||||
idx int // preserve search ordering
|
||||
candidate types.TenantInviteCandidate
|
||||
}
|
||||
seen := make(map[uint64]*entry)
|
||||
addUser := func(u *types.User) {
|
||||
if u == nil || u.TenantID == 0 {
|
||||
return
|
||||
}
|
||||
if existingTenantIDs[u.TenantID] {
|
||||
return
|
||||
}
|
||||
if _, ok := seen[u.TenantID]; ok {
|
||||
return
|
||||
}
|
||||
seen[u.TenantID] = &entry{
|
||||
idx: len(seen),
|
||||
candidate: types.TenantInviteCandidate{
|
||||
TenantID: u.TenantID,
|
||||
},
|
||||
}
|
||||
}
|
||||
for _, u := range users {
|
||||
addUser(u)
|
||||
}
|
||||
addTenantByID := func(tid uint64) {
|
||||
if tid == 0 || existingTenantIDs[tid] {
|
||||
return
|
||||
|
||||
@@ -536,12 +536,47 @@ func (r *Registry) CompactKnownText(text string) string {
|
||||
sort.SliceStable(pairs, func(i, j int) bool { return len(pairs[i].real) > len(pairs[j].real) })
|
||||
for _, item := range pairs {
|
||||
if item.real != "" {
|
||||
text = strings.ReplaceAll(text, item.real, item.alias)
|
||||
text = replaceIDExceptWikiSummarySlug(text, item.real, item.alias)
|
||||
}
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
// wikiSummarySlugPrefix guards wiki summary-page slugs (summary/<knowledgeID>)
|
||||
// from citation compaction. A summary slug embeds a document's knowledge ID
|
||||
// verbatim, so a blind ReplaceAll of that ID into its citation alias (d1) would
|
||||
// mangle the slug into summary/d1 — an unrecoverable dead link the model then
|
||||
// copies into wiki tool calls. Only the slug-embedded occurrence is preserved;
|
||||
// the same document ID elsewhere in the text still compacts normally.
|
||||
const wikiSummarySlugPrefix = "summary/"
|
||||
|
||||
// replaceIDExceptWikiSummarySlug replaces every occurrence of real with alias,
|
||||
// except one that is immediately preceded by "summary/" (i.e. it is the
|
||||
// identifier segment of a wiki summary-page slug). Go's regexp package has no
|
||||
// lookbehind, so the scan is done manually.
|
||||
func replaceIDExceptWikiSummarySlug(text, real, alias string) string {
|
||||
if real == "" || !strings.Contains(text, real) {
|
||||
return text
|
||||
}
|
||||
var b strings.Builder
|
||||
b.Grow(len(text))
|
||||
for {
|
||||
i := strings.Index(text, real)
|
||||
if i < 0 {
|
||||
b.WriteString(text)
|
||||
break
|
||||
}
|
||||
b.WriteString(text[:i])
|
||||
if strings.HasSuffix(text[:i], wikiSummarySlugPrefix) {
|
||||
b.WriteString(real) // part of a summary slug — keep intact
|
||||
} else {
|
||||
b.WriteString(alias)
|
||||
}
|
||||
text = text[i+len(real):]
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
var (
|
||||
refTagRE = regexp.MustCompile(`(?i)<ref\s+id\s*=\s*"([^"]+)"\s*/?>`)
|
||||
refCandidateRE = regexp.MustCompile(`(?is)<ref(?:\s|$)[^>]*(?:>|$)`)
|
||||
|
||||
@@ -32,6 +32,30 @@ func TestRegistryChunkAliasIsStableAndExpandsCanonicalCitation(t *testing.T) {
|
||||
)
|
||||
}
|
||||
|
||||
func TestCompactKnownTextPreservesWikiSummarySlug(t *testing.T) {
|
||||
const knowledgeID = "07a20bb1-a662-47cf-9929-06fb5d5b5b5e"
|
||||
const kbID = "250368ff-f5a2-4e9e-868a-07bc9b857c44"
|
||||
|
||||
registry := NewRegistry()
|
||||
require.Equal(t, "d1", registry.RegisterDocument(knowledgeID))
|
||||
require.Equal(t, "b1", registry.RegisterKnowledgeBase(kbID))
|
||||
|
||||
// A wiki_search result: the summary slug embeds the document UUID, and the
|
||||
// same UUID also appears as a standalone <knowledge_id> label.
|
||||
in := "<knowledge_base_id>" + kbID + "</knowledge_base_id>\n" +
|
||||
"<link>[[summary/" + knowledgeID + "|Doc - Summary]]</link>\n" +
|
||||
"<knowledge_id>" + knowledgeID + "</knowledge_id>"
|
||||
|
||||
got := registry.CompactKnownText(in)
|
||||
|
||||
// The slug-embedded UUID must survive verbatim — no summary/d1 mangling.
|
||||
require.Contains(t, got, "[[summary/"+knowledgeID+"|Doc - Summary]]")
|
||||
require.NotContains(t, got, "summary/d1")
|
||||
// The standalone label and the KB id still compact normally.
|
||||
require.Contains(t, got, "<knowledge_id>d1</knowledge_id>")
|
||||
require.Contains(t, got, "<knowledge_base_id>b1</knowledge_base_id>")
|
||||
}
|
||||
|
||||
func TestRegistrySuppressesSourceCitationsWhenDisabled(t *testing.T) {
|
||||
registry := NewRegistry(false)
|
||||
registry.RegisterChunk(ChunkReference{ChunkID: "chunk-1", DocumentTitle: "Doc"})
|
||||
|
||||
@@ -17,10 +17,22 @@ import (
|
||||
// resource:// handles, but old chunks and message history can still contain a
|
||||
// provider URL. Giving both forms the same request-local alias makes rollout
|
||||
// safe without a blocking full-table content rewrite.
|
||||
//
|
||||
// The final alternative aliases wiki summary-page slugs (summary/<uuid>). They
|
||||
// are not storage handles, but they share the exact failure mode this registry
|
||||
// exists to prevent: a high-entropy identifier the model must reproduce
|
||||
// verbatim (inside [[slug|display]] links and as wiki-tool slug arguments).
|
||||
// Models routinely mangle the UUID by inserting or dropping hex digits, which
|
||||
// yields dead cross-links. Aliasing the slug to a low-entropy res:// token
|
||||
// removes the opportunity to mangle at the source; the token round-trips back
|
||||
// to the real slug on stream output and in decoded tool-call arguments before
|
||||
// anything is persisted. Entity slugs (entity/<readable-title>) are low-entropy
|
||||
// and semantically meaningful, so they are deliberately left untouched.
|
||||
var storedRefRE = regexp.MustCompile(
|
||||
`resource://[0-9A-Za-z_-]{22}|` +
|
||||
`(?:storage://[0-9A-Za-z_-]+/)?` +
|
||||
`(?:local|minio|cos|tos|s3|oss|ks3|obs)://[^\s)\]>"']+`,
|
||||
`(?:local|minio|cos|tos|s3|oss|ks3|obs)://[^\s)\]>"']+|` +
|
||||
`summary/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}`,
|
||||
)
|
||||
|
||||
// aliasShapeRE matches the alias syntax produced by EncodeText. It is used only
|
||||
|
||||
@@ -23,6 +23,25 @@ func TestRegistryAliasesLegacyPhysicalReferencesDuringRollout(t *testing.T) {
|
||||
require.Equal(t, "", r.DecodeText(encoded))
|
||||
}
|
||||
|
||||
func TestRegistryAliasesWikiSummarySlug(t *testing.T) {
|
||||
r := NewRegistry()
|
||||
slug := "summary/07a20bb1-a662-47cf-9929-06fb5d5b5b5e"
|
||||
// Inside a [[slug|display]] link the model must copy verbatim.
|
||||
encoded := r.EncodeText("see [[" + slug + "|Foo.md - Summary]]")
|
||||
require.Equal(t, "see [[res://0001|Foo.md - Summary]]", encoded)
|
||||
require.Equal(t, "see [["+slug+"|Foo.md - Summary]]", r.DecodeText(encoded))
|
||||
|
||||
// The same slug as a tool-call argument value resolves to one alias.
|
||||
require.Equal(t, "res://0001", r.EncodeText(slug))
|
||||
}
|
||||
|
||||
func TestRegistryLeavesEntitySlugUntouched(t *testing.T) {
|
||||
r := NewRegistry()
|
||||
// Entity slugs are low-entropy and semantically meaningful; not aliased.
|
||||
entity := "[[entity/weknora-error-log|WeKnora 试错记录]]"
|
||||
require.Equal(t, entity, r.EncodeText(entity))
|
||||
}
|
||||
|
||||
func TestRegistryEncodesMessageCopies(t *testing.T) {
|
||||
r := NewRegistry()
|
||||
ref := "resource://AbCdEfGhIjKlMnOpQrStUv"
|
||||
|
||||
@@ -39,6 +39,13 @@ type WikiPageService interface {
|
||||
// GetPageBySlug retrieves a wiki page by its slug within a knowledge base.
|
||||
GetPageBySlug(ctx context.Context, kbID string, slug string) (*types.WikiPage, error)
|
||||
|
||||
// RepairContentLinks rewrites dead [[slug]] references in content to their
|
||||
// most likely live target (rewrite-only — never strips). Used by the agent
|
||||
// write path to auto-correct LLM-mangled slugs (especially UUID-based
|
||||
// summary slugs) before persistence. Returns the possibly-updated content
|
||||
// and whether any rewrite happened. Best-effort: callers may ignore errors.
|
||||
RepairContentLinks(ctx context.Context, kbID, selfSlug, content string) (string, bool, error)
|
||||
|
||||
// GetPageByID retrieves a wiki page by its unique ID.
|
||||
GetPageByID(ctx context.Context, id string) (*types.WikiPage, error)
|
||||
|
||||
|
||||
+18
-17
@@ -1,17 +1,18 @@
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY . .
|
||||
RUN pip install --no-cache-dir -e .
|
||||
|
||||
ENV MCP_HOST=0.0.0.0
|
||||
ENV MCP_PORT=8000
|
||||
ENV WEKNORA_BASE_URL=http://app:8080/api/v1
|
||||
# Set MCP_SERVER_AUTH_TOKEN at runtime; HTTP transport refuses to start without it.
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
CMD ["weknora-mcp-server", "--transport", "http", "--host", "0.0.0.0", "--port", "8000"]
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
RUN python -c "from mcp.server import Server; assert hasattr(Server('contract-check'), 'list_tools'), 'incompatible mcp SDK'"
|
||||
|
||||
COPY . .
|
||||
RUN pip install --no-cache-dir -e .
|
||||
|
||||
ENV MCP_HOST=0.0.0.0
|
||||
ENV MCP_PORT=8000
|
||||
ENV WEKNORA_BASE_URL=http://app:8080/api/v1
|
||||
# Set MCP_SERVER_AUTH_TOKEN at runtime; HTTP transport refuses to start without it.
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
CMD ["weknora-mcp-server", "--transport", "http", "--host", "0.0.0.0", "--port", "8000"]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
mcp>=1.0.0
|
||||
requests>=2.31.0
|
||||
starlette>=0.27.0
|
||||
mcp>=1.0.0,<2.0.0
|
||||
requests>=2.31.0
|
||||
starlette>=0.27.0
|
||||
uvicorn>=0.24.0
|
||||
+15
-11
@@ -86,28 +86,32 @@ show_help() {
|
||||
}
|
||||
|
||||
# 加载 .env 与可选的 .env.local(后者覆盖前者)
|
||||
# 读取 .env 时去掉行尾的 \r,兼容 Windows 风格(CRLF)换行符,
|
||||
# 读取时去掉行尾 \r,兼容 Windows 风格(CRLF)换行符,
|
||||
# 否则 bash source 会把残留的 \r 当成命令导致 "...: $'\r': command not found"。
|
||||
_clean_env_file() {
|
||||
sed -e 's/\r$//' "$1"
|
||||
# 注意:不能用 source <(sed ...)——macOS 自带 Bash 3.2 对 process substitution
|
||||
# 的 source 不会把变量导入当前 shell;必须落到可 seek 的临时文件再 source。
|
||||
_source_env_file() {
|
||||
local src="$1"
|
||||
local tmp
|
||||
tmp="$(mktemp)" || return 1
|
||||
sed -e 's/\r$//' "$src" > "$tmp"
|
||||
set -a
|
||||
# shellcheck source=/dev/null
|
||||
source "$tmp"
|
||||
set +a
|
||||
rm -f "$tmp"
|
||||
}
|
||||
|
||||
load_env_files() {
|
||||
if [ -f ".env" ]; then
|
||||
set -a
|
||||
# shellcheck source=/dev/null
|
||||
source <(_clean_env_file .env)
|
||||
set +a
|
||||
_source_env_file .env || return 1
|
||||
else
|
||||
return 1
|
||||
fi
|
||||
|
||||
if [ -f ".env.local" ]; then
|
||||
log_info "加载 .env.local 覆盖配置..."
|
||||
set -a
|
||||
# shellcheck source=/dev/null
|
||||
source <(_clean_env_file .env.local)
|
||||
set +a
|
||||
_source_env_file .env.local || return 1
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user