refactor(frontend): 重构前端第三版
This commit is contained in:
1 parent
bf32f8b954
commit
dc141d19a2
49 files changed
+5333
-4234
No files matched your search
@@ -0,0 +1,70 @@
|
||||
---
|
||||
description: 文件层与函数层注释强制规范(撰写与调整代码时均适用)
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# 代码注释(强制)
|
||||
|
||||
撰写或**修改**代码时,必须补齐或更新两层注释。完整说明见 `AGENTS.md` §5。
|
||||
|
||||
## 文件层(文件顶部)
|
||||
|
||||
块注释须包含:**用途**、**主要 import/依赖**、**与上下游文件的逻辑关系**。
|
||||
|
||||
```typescript
|
||||
/**
|
||||
* features/kb/composables/useKbWorkspace.ts
|
||||
* 用途:知识库作业面编排入口,组合 state / computed / data 等子模块。
|
||||
* 依赖:kb-workspace/* composables、kb.api、kb-display.utils。
|
||||
* 逻辑:KbWorkspaceView 调用本 composable;本文件再分发至 useKbWorkspaceData 等子模块。
|
||||
*/
|
||||
```
|
||||
|
||||
```python
|
||||
"""
|
||||
services/kb_sync.py
|
||||
|
||||
用途:知识库文档与 Dify 之间的同步编排。
|
||||
依赖:dify_service、models.KbDocument、minio_service。
|
||||
逻辑:由 api/knowledge_base 路由调用;内部委托 chunking 与 job 状态机。
|
||||
"""
|
||||
```
|
||||
|
||||
## 函数层(每个函数定义上方)
|
||||
|
||||
须说明:**用途**、**核心逻辑与实现方式**、**参数**与**返回值**(及异常)。
|
||||
|
||||
```typescript
|
||||
/**
|
||||
* 加载当前分组下的文档列表,并在静默刷新时合并 stable 项避免闪烁。
|
||||
* 核心逻辑:调用 getKbGroupFilesSafe,按 mergeStableItems 策略合并新旧列表。
|
||||
* @param options.silent - 为 true 时不切换 loading,用于轮询刷新
|
||||
* @returns 是否成功拉取到数据
|
||||
*/
|
||||
async function loadDocuments(options?: LoadListOptions): Promise<boolean> { ... }
|
||||
```
|
||||
|
||||
```python
|
||||
def sync_document_to_dify(document_id: int, *, force: bool = False) -> SyncResult:
|
||||
"""
|
||||
将指定文档切片同步至 Dify 知识库。
|
||||
|
||||
核心逻辑:读 MinIO 原文 → 切块 → 调 Dify API upsert;失败写入 KbJob 供重试。
|
||||
|
||||
Args:
|
||||
document_id: 本地 KbDocument 主键。
|
||||
force: 为 True 时忽略已完成状态强制重同步。
|
||||
|
||||
Returns:
|
||||
SyncResult: 含 dify_document_id 与分段数。
|
||||
|
||||
Raises:
|
||||
KbNotFoundError: 文档不存在或无权限。
|
||||
"""
|
||||
```
|
||||
|
||||
## 修改既有文件时
|
||||
|
||||
- 改函数逻辑/签名 → 同步改该函数注释。
|
||||
- 改 import 或模块协作关系 → 同步改文件头注释。
|
||||
- Vue SFC:`<script setup>` 内每个函数同样要求函数层注释。
|
||||
@@ -75,14 +75,48 @@ docker compose logs -f hxops-backend
|
||||
|
||||
## 5. 代码规范与注释
|
||||
|
||||
- **注释写「为什么」,不写「是什么」**:避免逐行复述代码(如 `// 自增 i`、`# 调用接口`);只对非显而易见的意图、权衡、约束、坑点、外部协议/边界条件加注释。
|
||||
- **公共接口必须有文档注释**:
|
||||
- 后端:对外的函数/类/接口使用 docstring,说明用途、参数、返回、可能抛出的异常;FastAPI 路由用类型注解 + Pydantic 模型,复杂逻辑补 docstring。
|
||||
- 前端:导出的 composable / 工具函数 / 复杂组件 props 用 JSDoc/TSDoc 说明。
|
||||
- **复杂或临时方案要留痕**:含业务规则、算法、兼容性处理的代码段加简要说明;临时方案用 `TODO:` / `FIXME:` 标注并附原因或关联任务号。
|
||||
- **注释与代码同步更新**:改逻辑必须同步改注释,禁止留下与实现不符的过期注释。
|
||||
- **统一语言**:注释可用中文,但术语/标识符保持与代码一致,避免中英混排导致歧义。
|
||||
- 不要用注释提交被注释掉的废弃代码(交给 Git 历史管理)。
|
||||
> **适用范围**:**新建或调整**业务代码(人工与 AI Agent 均适用)。Agent 持久规则见 **[`.cursor/rules/code-comments.mdc`](.cursor/rules/code-comments.mdc)**。
|
||||
|
||||
### 5.1 文件层注释(必须)
|
||||
|
||||
每个源文件顶部须有块注释,说明:
|
||||
|
||||
1. **用途**:本文件在模块/业务流程中的职责。
|
||||
2. **引用关系**:主要 `import` / 依赖的上游模块或文件(不必列全量 import,列关键依赖即可)。
|
||||
3. **逻辑关系**:与同级或上下游文件如何协作(谁调用谁、数据/状态如何流转)。
|
||||
|
||||
| 语言/形态 | 写法 |
|
||||
| --- | --- |
|
||||
| 前端 TS/JS | 文件首行 `/** ... */`(JSDoc 块注释) |
|
||||
| Vue SFC | 写在 `<script>` / `<script setup>` 块内首行 |
|
||||
| 后端 Python | 模块级 docstring(文件首行三引号字符串) |
|
||||
|
||||
### 5.2 函数层注释(必须)
|
||||
|
||||
**每个函数**(含方法、composable、路由 handler、类方法;导出的工具函数、组件内 `<script setup>` 函数均包含在内)在定义**上方**须有注释,说明:
|
||||
|
||||
1. **用途**:该函数解决什么问题、在调用链中的位置。
|
||||
2. **核心逻辑与实现方式**:关键步骤、算法/策略、外部服务或副作用。
|
||||
3. **参数与输出**:每个入参含义、返回值含义;可能抛出的异常或错误码(如有)。
|
||||
|
||||
| 语言 | 写法 |
|
||||
| --- | --- |
|
||||
| 前端 | JSDoc:`@param` / `@returns` / `@throws`(TypeScript 类型无法表达的业务约束写在描述里) |
|
||||
| 后端 | docstring(Google 或 NumPy 风格均可,须含 Args/Returns/Raises 或等价段落) |
|
||||
|
||||
**调整既有代码时**:修改函数签名、逻辑或副作用,必须**同步更新**对应函数注释;协作关系变化时同步更新文件层注释。
|
||||
|
||||
### 5.3 其它约定
|
||||
|
||||
- **函数内**:不必逐行复述「是什么」;对非显而易见的分支、业务规则、兼容处理、外部协议/边界条件可补 brief 行内注释。
|
||||
- **复杂或临时方案**:临时方案用 `TODO:` / `FIXME:` 标注并附原因或关联任务号。
|
||||
- **注释与代码同步**:禁止留下与实现不符的过期注释。
|
||||
- **统一语言**:注释可用中文,术语/标识符保持与代码一致。
|
||||
- **禁止**用注释提交被注释掉的废弃代码(交给 Git 历史管理)。
|
||||
|
||||
### 5.4 测试代码
|
||||
|
||||
测试代码在 §5.1–§5.2 基础上,另须 **代码层注释**(函数内关键断言与分支意图),见 **[docs/test_plan_matrix.md](docs/test_plan_matrix.md) §1**。
|
||||
|
||||
---
|
||||
|
||||
@@ -93,7 +127,7 @@ docker compose logs -f hxops-backend
|
||||
- 格式:`<type>(<scope>): <subject>`;`type`/`scope` 英文(scope 为 kebab-case 模块名),`subject` 中文,祈使语气、不以句号结尾、≤100 字符。
|
||||
- 允许的 `type`:`feat` `fix` `docs` `style` `refactor` `perf` `test` `build` `ci` `chore` `revert`。
|
||||
- 禁止无语义提交(`update`、`fix bug`、`111`);一个提交只做一件事。
|
||||
- **Cursor IDE**:源代码管理 ✨「Generate commit message」仅读取根目录 **`.cursorrules`**(不读 `.cursor/rules/`、`AGENTS.md`);Agent 代提交读 `.cursor/rules/`。
|
||||
- **Cursor IDE**:源代码管理 ✨「Generate commit message」仅读取根目录 **`.cursorrules`**(不读 `.cursor/rules/`、`AGENTS.md`);**Agent 写/改代码**读 `AGENTS.md` §5 与 **`.cursor/rules/`**(如 `code-comments.mdc`);Agent 代提交读 `.cursor/rules/`。
|
||||
|
||||
详见 **[docs/convention/COMMIT_CONVENTION.md](docs/convention/COMMIT_CONVENTION.md)** 与 **[docs/GIT_HOOKS.md](docs/GIT_HOOKS.md)**。
|
||||
|
||||
@@ -120,6 +154,7 @@ docker compose logs -f hxops-backend
|
||||
- 📡 **SSE 流式约束**:对话链路依赖 Gevent 异步 worker + Nginx `proxy_buffering off`;对话接口(`chat.py`)使用原生 Fetch/SSE 而非 Axios,改动需保持流式不被破坏。
|
||||
- 🔌 **外部集成依赖**:Oracle Instant Client 19.30 / `pyodbc` / `zeep`(OA、PLM、HR)等本地未必可运行,涉及这些 service 时谨慎并说明。
|
||||
- ➕ **新增依赖需克制**:不擅自引入未经评审的第三方依赖;如需新增,在提交说明中给出理由。
|
||||
- 📝 **注释两层标准(强制)**:新建或调整代码须满足 §5 文件层 + 函数层注释;AI 生成/重构代码同样适用,不得省略。
|
||||
- ⚠️ 改动**数据库结构、部署脚本(`scripts/`、`Jenkinsfile`、`docker-compose.yml`)或敏感配置**前,先说明影响面再动手。
|
||||
|
||||
合并前最低自检(详见 [新人文档 §3.3](docs/新人环境搭建与配置文档.md)):前后端可启动、`frontend/` 改动后 `npm run build` 通过、关键页面与登录可用。
|
||||
|
||||
@@ -97,6 +97,8 @@ frontend/src/
|
||||
│ │ │ ├── useChat.ts # SSE 流式对话(保留并增强)
|
||||
│ │ │ ├── useChatSessions.ts
|
||||
│ │ │ └── useSourceFiles.ts # 源文件 / 检索来源逻辑
|
||||
│ │ ├── page/ # useChatPage 编排子模块(composable,非路由页)
|
||||
│ │ ├── history/ # 跨 Agent 历史(HistoryPage.vue)
|
||||
│ │ ├── views/
|
||||
│ │ │ └── ChatView.vue # 页面编排,目标 < 300 行
|
||||
│ │ └── components/
|
||||
@@ -135,9 +137,15 @@ frontend/src/
|
||||
│ └── kb/
|
||||
│ ├── api/
|
||||
│ │ └── kb.api.ts
|
||||
│ ├── types/
|
||||
│ │ └── kb-workspace.types.ts
|
||||
│ ├── utils/ # 列表/展示/工作流/路径上传纯函数
|
||||
│ ├── composables/
|
||||
│ │ ├── useKbWorkspace.ts # 编排入口
|
||||
│ │ └── kb-workspace/ # state / computed / data / pathUpload / documents / modals
|
||||
│ ├── views/
|
||||
│ │ └── KbWorkspaceView.vue
|
||||
│ └── components/ # 迁移现有 components/kb/*
|
||||
│ │ └── KbWorkspaceView.vue # 作业面壳(模板 + 弹窗)
|
||||
│ └── components/ # 治理面:KbAdminPanel、Dify*Dialog
|
||||
│
|
||||
├── locales/ # i18n 按语言 + 业务域拆分
|
||||
│ ├── zh-CN/
|
||||
@@ -162,11 +170,11 @@ frontend/src/
|
||||
| `src/main.ts`、`src/App.vue` | **保留 `src/` 根目录** | Vite 入口约定;不迁入 `app/` |
|
||||
| `src/router/index.ts` | `app/router/` | 路由表与守卫拆分 |
|
||||
| `src/api/client.ts` | `shared/api/client.ts` | 权威实现;`src/api/client.ts` deprecated 转发 |
|
||||
| `src/api/*.ts` | `features/*/api/` | 按业务域归属(KB 暂缓,见 §12) |
|
||||
| `src/api/*.ts` | `features/*/api/` | 按业务域归属(KB 已迁入,见 §16) |
|
||||
| `src/composables/`(通用) | `shared/composables/` | useTheme、useMessage 等 |
|
||||
| `src/composables/useChat.ts` | `features/chat/composables/` | 聊天域专属 |
|
||||
| `src/components/`(通用 Dialog 等) | `shared/components/` | 跨域复用 UI |
|
||||
| `src/components/kb/` | `shared/components/kb/` | 暂留 shared,KB redesign 后迁 `features/kb/` |
|
||||
| `src/components/kb/` | `features/kb/components/` | ✅ 已迁入(2026-06-11) |
|
||||
| `src/layouts/` | `shared/layouts/` | 页面壳层 |
|
||||
| `src/utils/` | `shared/utils/` | 纯工具函数 |
|
||||
| `src/styles/` | `shared/styles/` | 设计 token 与全局样式 |
|
||||
@@ -311,11 +319,24 @@ flowchart TB
|
||||
|
||||
### 4.4 kb(知识库)
|
||||
|
||||
**职责拆分(治理面 vs 作业面):**
|
||||
|
||||
| 入口 | 路由 | 组件 | 职责 |
|
||||
|------|------|------|------|
|
||||
| 管理控制台 | `/admin/knowledge-base` | `KbAdminPanel` | 分组 CRUD、Dify 配置、健康检查、任务队列 |
|
||||
| 工作台 | `/workspace/knowledge-base` | `KbWorkspaceView`(`embedded`) | 只读选分组 → 文档上传/清洗/同步 |
|
||||
| 兼容 | `/kb/workspace` → `/workspace/knowledge-base` | redirect | 旧书签 |
|
||||
| 兼容 | `/kb/admin` → `/admin/knowledge-base` | redirect | 旧书签 |
|
||||
|
||||
| 项 | 说明 |
|
||||
|----|------|
|
||||
| 路由 | `/kb/workspace`;`/kb/admin` redirect 至 `/admin/knowledge-base` |
|
||||
| 组件 | 迁移 `components/kb/KbAdminPanel.vue`、`DifyHealthDialog.vue` 等 |
|
||||
| 迁移来源 | `views/KbWorkspaceView.vue`(~2400 行)、`api/kb.ts` |
|
||||
| API | `features/kb/api/kb.api.ts`(`src/api/kb.ts` deprecated 转发) |
|
||||
| 作业面编排 | `useKbWorkspace` + `kb-workspace/*` 子 composable |
|
||||
| 权限 | `hasKnowledgeBaseAccess` / 作业面批量操作:`role === 'admin'` |
|
||||
| i18n | `locales/{en,zh-CN,zh-TW,th}/kb.json` |
|
||||
| 迁移来源 | 原 `views/KbWorkspaceView.vue`(~3000 行 monolith) |
|
||||
|
||||
详见 §16。
|
||||
|
||||
---
|
||||
|
||||
@@ -512,7 +533,7 @@ Phase 2 Chat 目标:将原 `views/ChatView.vue`(~5500 行)拆为 feature
|
||||
| 路由 lazy | `app/router/routes/chat.routes.ts` → `features/chat/views/ChatView.vue` |
|
||||
| API | `features/chat/api/chat.api.ts`(`src/api/chat.ts` deprecated 转发) |
|
||||
| 货代 API | `features/chat/api/shipping.api.ts`(`src/api/shippingNotice.ts` deprecated 转发) |
|
||||
| 跨 Agent 历史 | `features/chat/pages/HistoryPage.vue` + `useChatHistory` |
|
||||
| 跨 Agent 历史 | `features/chat/history/HistoryPage.vue` + `useChatHistory` |
|
||||
| Pinia 接入 | `chat.store`:`currentAgentId`(路由同步)、`sidebarCollapsed`、`sessionHistoryByAgent` 缓存 |
|
||||
| 内置浏览器 | 输入栏「打开/收起浏览器」按钮已恢复,逻辑在 `useChatBrowserPanel` |
|
||||
| provide/inject | `chat.context.ts`:`CHAT_PAGE_KEY` + `useChatPageContext()`;`reactive(useChatPage())` 解包嵌套 Ref;`markRaw` 保留 template ref holder |
|
||||
@@ -541,8 +562,8 @@ Phase 2 Chat 目标:将原 `views/ChatView.vue`(~5500 行)拆为 feature
|
||||
- Workspace 壳层 → 见 §11
|
||||
- ~~API 按 feature 归属~~ → 见 §12
|
||||
- ~~`shared/` composables/components/layouts/utils/styles 迁移~~ → 见 §14
|
||||
- KB 域重新设计(暂缓)
|
||||
- `locales/` 按域拆分
|
||||
- ~~KB 域收口~~ → 见 §16
|
||||
- ~~`locales/` 按域拆分~~ → 见 §15.2
|
||||
|
||||
---
|
||||
|
||||
@@ -559,14 +580,14 @@ Phase 3 目标:将原 `WorkspaceView.vue` 拆为独立 feature,路由 `/work
|
||||
| 路由 | `app/router/routes/workspace.routes.ts` |
|
||||
| Composable | `useWorkspace`、`useWorkspaceHome`、`useWorkspaceNavigation` 等 |
|
||||
| 排程 API | `features/workspace/api/schedule.api.ts` |
|
||||
| 历史页 | 复用 `features/chat/pages/HistoryPage.vue` |
|
||||
| 历史页 | 复用 `features/chat/history/HistoryPage.vue` |
|
||||
|
||||
### 11.2 薄包装页(待真正迁入 feature)
|
||||
### 11.2 薄包装页
|
||||
|
||||
| 页面 | 现状 |
|
||||
|------|------|
|
||||
| `KnowledgeBasePage.vue` | 嵌入 `src/views/KbWorkspaceView.vue`(KB 域暂缓 redesign) |
|
||||
| `ShippingNoticePage.vue` | 嵌入 `src/views/ShippingNoticeView.vue` |
|
||||
| `KnowledgeBasePage.vue` | ✅ 嵌入 `features/kb/views/KbWorkspaceView.vue`(`embedded`) |
|
||||
| `ShippingNoticePage.vue` | 嵌入 `src/views/ShippingNoticeView.vue`(待迁入 workspace) |
|
||||
|
||||
### 11.3 路由
|
||||
|
||||
@@ -576,12 +597,12 @@ Phase 3 目标:将原 `WorkspaceView.vue` 拆为独立 feature,路由 `/work
|
||||
/workspace/schedule-runs → ScheduleRunsPage
|
||||
/workspace/shipping-notice → ShippingNoticePage(legacy 嵌入)
|
||||
/workspace/knowledge-base → KnowledgeBasePage(legacy 嵌入)
|
||||
/workspace/history → chat/pages/HistoryPage
|
||||
/workspace/history → chat/history/HistoryPage
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 12. Phase 4 API 按 Feature 归属(已实现,KB 除外)
|
||||
## 12. Phase 4 API 按 Feature 归属(已实现)
|
||||
|
||||
Phase 4 目标:领域 HTTP 请求迁入对应 `features/*/api/`,`shared/api/client.ts` 作为唯一 JSON 客户端。
|
||||
|
||||
@@ -598,7 +619,7 @@ Phase 4 目标:领域 HTTP 请求迁入对应 `features/*/api/`,`shared/api/
|
||||
| 排程共用类型 | `shared/types/schedule.types.ts` | ✅ |
|
||||
| `src/api/shippingNotice.ts` | `features/chat/api/shipping.api.ts` | ✅ |
|
||||
| 货代类型 | `features/chat/types/shipping.api.types.ts` | ✅ |
|
||||
| `src/api/kb.ts` | — | ⏸ 暂缓(KB 域 redesign 后迁移) |
|
||||
| `src/api/kb.ts` | `features/kb/api/kb.api.ts` | ✅ deprecated 转发保留 |
|
||||
|
||||
### 12.2 新代码 import 规范
|
||||
|
||||
@@ -613,6 +634,7 @@ import { listWorkspaceScheduleRuns } from '@/features/workspace/api/schedule.api
|
||||
import { listChatSessions } from '@/features/chat/api/chat.api';
|
||||
import { getWorkspaceShippingTask } from '@/features/chat/api/shipping.api';
|
||||
import { getUserProfile } from '@/features/auth/api/user.api';
|
||||
import { getKbGroupsSafe } from '@/features/kb/api/kb.api';
|
||||
```
|
||||
|
||||
或通过 feature 入口 re-export:
|
||||
@@ -627,7 +649,7 @@ import { getWorkspaceShippingTask } from '@/features/chat';
|
||||
|
||||
- ~~`src/api/{client,admin,schedule,shippingNotice,chat,user}.ts` deprecated 转发~~ → **已删除**(2026-06-11)
|
||||
- **新代码必须使用 feature / shared 路径**
|
||||
- `src/api/kb.ts` 暂保留原位(KB redesign 后迁入 `features/kb/api/`)
|
||||
- `src/api/kb.ts` 保留 deprecated 转发,新代码使用 `@/features/kb/api/kb.api`
|
||||
|
||||
### 12.4 构建验证
|
||||
|
||||
@@ -635,7 +657,7 @@ import { getWorkspaceShippingTask } from '@/features/chat';
|
||||
|
||||
### 12.5 下一步
|
||||
|
||||
- KB API 待 redesign 后迁入 `features/kb/api/kb.api.ts`
|
||||
- ~~KB API 迁入 `features/kb/api/kb.api.ts`~~ → 已完成(见 §16)
|
||||
- ~~清理 deprecated `src/api/*` 转发~~ → 已完成(仅保留 `kb.ts`)
|
||||
- `locales/` 按域拆分 → 见 §15
|
||||
|
||||
@@ -650,7 +672,7 @@ Phase 5 目标:将原 `src/` 根目录下的跨域代码迁入 `src/shared/`
|
||||
| 原路径 | 新路径 | 状态 |
|
||||
|--------|--------|------|
|
||||
| `src/composables/*` | `shared/composables/*` | ✅ |
|
||||
| `src/components/*` | `shared/components/*` | ✅(含 `kb/` 子目录,待 KB redesign) |
|
||||
| `src/components/*` | `shared/components/*` | ✅(`kb/` 已迁 `features/kb/components/`) |
|
||||
| `src/layouts/*` | `shared/layouts/*` | ✅ |
|
||||
| `src/utils/*` | `shared/utils/*` | ✅ |
|
||||
| `src/styles/*` | `shared/styles/*` | ✅ |
|
||||
@@ -663,7 +685,7 @@ shared/
|
||||
├── index.ts # 统一导出入口
|
||||
├── api/client.ts
|
||||
├── composables/ # useTheme、useMessage、useIsMobile 等
|
||||
├── components/ # Dialog、LocaleToggle、kb/* 等
|
||||
├── components/ # Dialog、LocaleToggle 等(无 kb 子目录)
|
||||
├── layouts/ # AppShell、ChatShell、MarketingShell 等
|
||||
├── utils/ # auth、clipboard、wecom 等
|
||||
├── styles/ # tokens.css、components-ds.css、utilities.css
|
||||
@@ -688,7 +710,7 @@ import { useTheme, requestJson } from '@/shared';
|
||||
- ~~`src/composables/`、`src/utils/`、`src/styles/` deprecated 转发~~ → **已删除**(2026-06-11)
|
||||
- `src/components/`、`src/layouts/` **已删除**(全仓 import 已切换)
|
||||
- **新代码必须使用 `@/shared/*` 路径**
|
||||
- `shared/components/kb/*` 仍依赖 `@/api/kb`(KB redesign 后整体迁出)
|
||||
- ~~`shared/components/kb/*`~~ → 已迁入 `features/kb/components/`
|
||||
|
||||
### 14.5 构建验证
|
||||
|
||||
@@ -696,7 +718,7 @@ import { useTheme, requestJson } from '@/shared';
|
||||
|
||||
### 14.6 下一步
|
||||
|
||||
- KB 组件/API 待 redesign 后迁入 `features/kb/`
|
||||
- ~~KB 组件/API 迁入 `features/kb/`~~ → 已完成(见 §16)
|
||||
- ~~清理 deprecated 转发~~ → 已完成
|
||||
- `locales/` 按域拆分 → 见 §15
|
||||
|
||||
@@ -720,9 +742,9 @@ import { useTheme, requestJson } from '@/shared';
|
||||
| 移除 `axios` 依赖 | 代码未使用,已从 `package.json` 删除 |
|
||||
| `main.ts` / `App.vue` | 保留在 `src/` 根(见 §7.2 约定) |
|
||||
|
||||
### 15.2 i18n 按域拆分(进行中)
|
||||
### 15.2 i18n 按域拆分(已完成)
|
||||
|
||||
**现状**:`src/i18n.ts` 仍承载剩余内联 messages;`errors`、`auth`、`workspace`、`chat`、`admin` 域已外置。
|
||||
**现状**:`src/i18n.ts` 仅保留 `createI18n` 注册与 locale 默认值;各业务域 messages 均已外置 JSON。
|
||||
|
||||
**已完成 ✅**
|
||||
|
||||
@@ -733,53 +755,51 @@ import { useTheme, requestJson } from '@/shared';
|
||||
| `workspace` | `locales/{en,zh-CN,zh-TW,th}/workspace.json` |
|
||||
| `chat` | `locales/{en,zh-CN,zh-TW,th}/chat.json` |
|
||||
| `admin` | `locales/{en,zh-CN,zh-TW,th}/admin.json` |
|
||||
| `kb` | `locales/{en,zh-CN,zh-TW,th}/kb.json` |
|
||||
| 合并入口 | `locales/index.ts` → `mergeExternalLocales()` |
|
||||
|
||||
`i18n.ts` 在 `createI18n` 前调用 `mergeExternalLocales(messages)`,四语言外置域与拆分前行为一致。
|
||||
|
||||
**目标结构**(剩余域):
|
||||
**目标结构**(已达成):
|
||||
|
||||
```text
|
||||
src/locales/
|
||||
├── index.ts # createI18n + 合并 messages
|
||||
├── zh-CN/
|
||||
│ ├── common.json
|
||||
├── index.ts # mergeExternalLocales + 导出
|
||||
├── zh-CN/ zh-TW/ en/ th/
|
||||
│ ├── errors.json
|
||||
│ ├── auth.json
|
||||
│ ├── workspace.json
|
||||
│ ├── chat.json
|
||||
│ ├── admin.json
|
||||
│ ├── workspace.json
|
||||
│ ├── kb.json
|
||||
│ └── errors.json
|
||||
├── zh-TW/ en/ th/ # 同上
|
||||
│ └── kb.json
|
||||
```
|
||||
|
||||
**建议步骤**(可分 PR 执行):
|
||||
**迁移步骤**(均已完成):
|
||||
|
||||
1. ~~拆 `errors.*` → `errors.json`~~ ✅
|
||||
2. ~~拆 `auth.*` → `auth.json`~~ ✅
|
||||
3. ~~拆 `workspace.*` → `workspace.json`~~ ✅
|
||||
4. ~~拆 `chat.*` → `chat.json`~~ ✅
|
||||
5. ~~拆 `admin.*` → `admin.json`~~ ✅
|
||||
6. 拆 `kb`(每域四语言 JSON;KB redesign 后可一并收口)
|
||||
6. ~~拆 `kb.*` → `kb.json`(四语言)~~ ✅
|
||||
7. 每步 `npm run build` + 四语言 spot check
|
||||
8. 全部外置后,`i18n.ts` 仅保留 `createI18n` 注册与 locale 默认值
|
||||
8. `i18n.ts` 仅保留 `createI18n` 注册与 locale 默认值
|
||||
|
||||
**注意**:AGENTS.md 要求四语言同步;拆分时用脚本或 CI 校验 key 对齐。
|
||||
|
||||
### 15.3 待办:清理 `src/views/`(优先级:低,依赖 KB redesign)
|
||||
### 15.3 待办:清理 `src/views/`(优先级:低)
|
||||
|
||||
| 文件 | 引用方 | 处理方式 |
|
||||
|------|--------|----------|
|
||||
| `KbWorkspaceView.vue` (~3000 行) | `/kb/workspace`、`workspace/knowledge-base` | KB redesign 后迁入 `features/kb/` |
|
||||
| ~~`KbWorkspaceView.vue`~~ | — | ✅ 已迁入 `features/kb/views/`(见 §16) |
|
||||
| `ShippingNoticeView.vue` (~250 行) | `workspace/shipping-notice` | 迁入 `features/workspace/pages/` 或独立 feature |
|
||||
|
||||
**当前可做**:统一 import 为 `@/api/kb`、`@/shared/*`(已部分完成)。
|
||||
### 15.4 KB 域收口(已实现,见 §16)
|
||||
|
||||
### 15.4 待办:KB 域一次性收口(优先级:低,blocked on redesign)
|
||||
|
||||
- `src/api/kb.ts` → `features/kb/api/kb.api.ts`
|
||||
- `shared/components/kb/*` → `features/kb/components/*`
|
||||
- 路由 `/kb/workspace` 与 `/workspace/knowledge-base` 合并
|
||||
- ~~`src/api/kb.ts` → `features/kb/api/kb.api.ts`~~ ✅
|
||||
- ~~`shared/components/kb/*` → `features/kb/components/*`~~ ✅
|
||||
- ~~路由收敛:`/kb/workspace` redirect → `/workspace/knowledge-base`~~ ✅
|
||||
- ~~作业面 monolith 拆分:`useKbWorkspace` + `kb-workspace/*`~~ ✅
|
||||
|
||||
### 15.5 可选优化(非必须)
|
||||
|
||||
@@ -794,13 +814,87 @@ src/locales/
|
||||
|
||||
```text
|
||||
✅ Phase A:删 deprecated 转发 + 去 axios
|
||||
→ Phase B:i18n 拆 locales/(errors ✅ → auth ✅ → workspace ✅ → chat ✅ → admin ✅ → kb)
|
||||
✅ Phase B:i18n 拆 locales/(errors → auth → workspace → chat → admin → kb)
|
||||
→ Phase C:ShippingNoticeView 迁入 workspace
|
||||
→ Phase D:KB redesign + views/api/components 收口
|
||||
✅ Phase D:KB 域收口(治理/作业面拆分 + composable 拆分)→ 见 §16
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 16. Phase 6 KB 域落地说明(已实现)
|
||||
|
||||
Phase 6 目标:知识库从 monolith 迁入 `features/kb/`,治理面与作业面职责分离,作业面逻辑 composable 化。
|
||||
|
||||
### 16.1 职责与路由
|
||||
|
||||
| 面 | Canonical 路由 | 组件 | 说明 |
|
||||
|----|----------------|------|------|
|
||||
| 治理面 | `/admin/knowledge-base` | `KbAdminPanel` | 分组 CRUD、Dify 设置、健康检查、任务队列 |
|
||||
| 作业面 | `/workspace/knowledge-base` | `KbWorkspaceView`(`embedded`) | 选分组 → 文档上传/清洗/同步(无分组 CRUD) |
|
||||
| 兼容 | `/kb/workspace` | redirect | → `/workspace/knowledge-base` |
|
||||
| 兼容 | `/kb/admin` | redirect | → `/admin/knowledge-base` |
|
||||
|
||||
权限:`hasKnowledgeBaseAccess`(工作台入口)与作业面批量操作均收敛为 `role === 'admin'`。
|
||||
|
||||
### 16.2 目录结构
|
||||
|
||||
```text
|
||||
features/kb/
|
||||
├── api/kb.api.ts
|
||||
├── types/kb-workspace.types.ts
|
||||
├── utils/
|
||||
│ ├── kb-list.utils.ts
|
||||
│ ├── kb-display.utils.ts
|
||||
│ ├── kb-workflow.utils.ts
|
||||
│ └── kb-path-upload.utils.ts
|
||||
├── composables/
|
||||
│ ├── useKbWorkspace.ts # 编排入口(~160 行)
|
||||
│ └── kb-workspace/
|
||||
│ ├── kb-workspace.state.ts # 共享 ref + 删除确认
|
||||
│ ├── kb-workspace.bridge.ts # pathUpload ↔ data 延迟绑定
|
||||
│ ├── useKbWorkspaceComputed.ts
|
||||
│ ├── useKbWorkspaceData.ts
|
||||
│ ├── useKbWorkspacePathUpload.ts
|
||||
│ ├── useKbWorkspaceDocuments.ts
|
||||
│ └── useKbWorkspaceModals.ts
|
||||
├── views/KbWorkspaceView.vue # 模板壳(~1160 行,逻辑在 composable)
|
||||
└── components/
|
||||
├── KbAdminPanel.vue
|
||||
├── DifySettingsDialog.vue
|
||||
└── DifyHealthDialog.vue
|
||||
```
|
||||
|
||||
### 16.3 已完成项
|
||||
|
||||
| 项 | 说明 |
|
||||
|----|------|
|
||||
| API 迁入 | `features/kb/api/kb.api.ts`;`src/api/kb.ts` deprecated 转发 |
|
||||
| 组件迁入 | `KbAdminPanel`、`DifySettingsDialog`、`DifyHealthDialog` |
|
||||
| 作业面拆分 | 类型/纯函数 utils + `useKbWorkspace` 子 composable |
|
||||
| 视图薄壳 | `KbWorkspaceView.vue` script 仅 `useKbWorkspace({ embedded })` |
|
||||
| 工作台嵌入 | `workspace/pages/KnowledgeBasePage.vue` → `KbWorkspaceView` |
|
||||
| i18n | `locales/*/kb.json` 四语言外置 |
|
||||
| 路由收敛 | `app/router/routes/kb.routes.ts` 仅保留 redirect |
|
||||
|
||||
### 16.4 构建验证
|
||||
|
||||
拆分后 `npm run build` 通过。
|
||||
|
||||
### 16.5 待办(KB 域内,优先级低)
|
||||
|
||||
| 项 | 说明 |
|
||||
|----|------|
|
||||
| 作业面 View 继续瘦身 | 弹窗块可抽为 `features/kb/components/*Modal.vue`,目标 View < 300 行 |
|
||||
| 作业面 i18n 全覆盖 | 模板内仍有部分硬编码中文(批量操作按钮等),需迁入 `kb.json` |
|
||||
| 删除 `src/api/kb.ts` | 确认全仓无 `@/api/kb` import 后移除 deprecated 转发 |
|
||||
|
||||
### 16.6 下一步(全项目)
|
||||
|
||||
- `ShippingNoticeView` 迁入 workspace → §15.3 Phase C
|
||||
- Chat / admin 域内低优先级待办 → §10.3
|
||||
|
||||
---
|
||||
|
||||
- [项目上下文与技术栈](./project_context.md)
|
||||
- [UI 设计系统](./ui/DESIGN_SYSTEM.md)
|
||||
- [UI 编码规范](./ui/UI_CODING_GUIDELINES.md)
|
||||
@@ -3,10 +3,12 @@
|
||||
本文档旨在对系统的所有功能进行提炼,并规范化测试代码的撰写要求。
|
||||
|
||||
## 1. 测试代码撰写通用要求
|
||||
所有测试代码必须遵循以下三层注释标准:
|
||||
1. **文件层注释**:注明文件用途、引用的模块、逻辑关系。
|
||||
2. **函数层注释**:在函数名上方说明其用途、核心逻辑与实现方式,对传参与输出进行说明。
|
||||
3. **代码层注释**:在函数内部,对关键代码行进行注释,解释逻辑意图。
|
||||
|
||||
业务代码的文件层 + 函数层标准见 **[AGENTS.md §5](../AGENTS.md)**。测试代码在此基础上增加第三层:
|
||||
|
||||
1. **文件层注释**:注明文件用途、引用的模块、逻辑关系(同 AGENTS.md §5.1)。
|
||||
2. **函数层注释**:在函数名上方说明其用途、核心逻辑与实现方式,对传参与输出进行说明(同 AGENTS.md §5.2)。
|
||||
3. **代码层注释**(测试专有):在函数内部,对关键代码行进行注释,解释逻辑意图。
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* scripts/extract-i18n-kb.mjs
|
||||
* 将 i18n.ts 内联的 kb 相关文案外置至 locales 下 kb.json,并从 i18n.ts 移除。
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const i18nPath = path.resolve(__dirname, '../src/i18n.ts');
|
||||
const localesDir = path.resolve(__dirname, '../src/locales');
|
||||
const KB_KEYS = ['kbDifySettings', 'kbDifyHealth', 'kbAdmin', 'kbWorkspace'];
|
||||
const LOCALE_DIRS = { en: 'en', 'zh-CN': 'zh-CN', 'zh-TW': 'zh-TW', th: 'th' };
|
||||
|
||||
const content = fs.readFileSync(i18nPath, 'utf8');
|
||||
const start = content.indexOf('const messages = {') + 'const messages = '.length;
|
||||
const end = content.indexOf('const i18n = createI18n');
|
||||
const messagesStr = content.slice(start, end).trim().replace(/,\s*$/, '');
|
||||
const messages = new Function(`return ${messagesStr}`)();
|
||||
|
||||
for (const [loc, dir] of Object.entries(LOCALE_DIRS)) {
|
||||
const kbPayload = {};
|
||||
for (const key of KB_KEYS) {
|
||||
if (messages[loc]?.[key]) kbPayload[key] = messages[loc][key];
|
||||
delete messages[loc][key];
|
||||
}
|
||||
const outPath = path.join(localesDir, dir, 'kb.json');
|
||||
fs.writeFileSync(outPath, `${JSON.stringify(kbPayload, null, 2)}\n`, 'utf8');
|
||||
console.log('Wrote', outPath);
|
||||
}
|
||||
|
||||
const header = content.slice(0, content.indexOf('const messages = {'));
|
||||
const footer = content.slice(end);
|
||||
const serialized = JSON.stringify(messages, null, 2);
|
||||
const newContent = `${header}const messages = ${serialized};\n\n${footer}`;
|
||||
fs.writeFileSync(i18nPath, newContent, 'utf8');
|
||||
console.log('Stripped kb keys from i18n.ts');
|
||||
@@ -0,0 +1,300 @@
|
||||
/**
|
||||
* scripts/extract-kb-workspace-composable.mjs
|
||||
* 将 KbWorkspaceView.vue 的 script 提取为 useKbWorkspace.ts 骨架。
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const vuePath = path.resolve(__dirname, '../src/features/kb/views/KbWorkspaceView.vue');
|
||||
const outPath = path.resolve(__dirname, '../src/features/kb/composables/useKbWorkspace.ts');
|
||||
|
||||
const vue = fs.readFileSync(vuePath, 'utf8');
|
||||
const scriptMatch = vue.match(/<script setup lang="ts">([\s\S]*?)<\/script>/);
|
||||
if (!scriptMatch) throw new Error('script block not found');
|
||||
|
||||
let body = scriptMatch[1]
|
||||
.replace(/^\s*\/\*\*[\s\S]*?\*\/\s*/m, '')
|
||||
.replace(/const props = defineProps<\{[\s\S]*?\}\>\(\);/, 'const embedded = options.embedded ?? false;')
|
||||
.replace(/props\.embedded/g, 'embedded');
|
||||
|
||||
const header = `/**
|
||||
* features/kb/composables/useKbWorkspace.ts
|
||||
* 知识库作业面编排:分组导航、文档列表、路径上传、清洗同步与弹窗状态。
|
||||
*/
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { getStoredAuthUser } from '@/shared/utils/auth';
|
||||
import {
|
||||
createKbDocument,
|
||||
createKbPathUploadJob,
|
||||
deleteKbPathJobFile,
|
||||
deleteKbDocument,
|
||||
getKbDocumentMarkdown,
|
||||
getKbDocumentSyncRecords,
|
||||
getKbDocumentVersionSourceFile,
|
||||
getKbDocumentVersions,
|
||||
getKbGroupFilesSafe,
|
||||
getKbGroupsSafe,
|
||||
getKbJobsSafe,
|
||||
markKbPathJobFileFailed,
|
||||
retryFailedKbPathUploadJob,
|
||||
submitKbDocumentClean,
|
||||
syncKbDocumentToDify,
|
||||
uploadKbPathJobFile,
|
||||
uploadKbDocumentVersion,
|
||||
updateKbDocumentMarkdown,
|
||||
type KbDocumentItem,
|
||||
type KbJob,
|
||||
type KbDocumentMarkdown,
|
||||
type KbSyncRecordItem,
|
||||
type KbDocumentVersionItem,
|
||||
type KbGroup,
|
||||
} from '../api/kb.api';
|
||||
import {
|
||||
DOCUMENT_PAGE_SIZE_OPTIONS,
|
||||
FAILURE_PAGE_SIZE,
|
||||
IDLE_BADGE_CLASS,
|
||||
PATH_UPLOAD_BATCH_INTERVAL_MS,
|
||||
PATH_UPLOAD_BATCH_SIZE,
|
||||
PATH_UPLOAD_CONCURRENCY,
|
||||
type FailureModalItem,
|
||||
type KbWorkspaceViewMode,
|
||||
type LoadListOptions,
|
||||
type PathUploadTaskItem,
|
||||
type WorkflowStageState,
|
||||
} from '../types/kb-workspace.types';
|
||||
import { mergeStableItems } from '../utils/kb-list.utils';
|
||||
import {
|
||||
formatDateTime,
|
||||
formatFileSize,
|
||||
getDocumentDisplayDescription,
|
||||
getDocumentDisplayTitle,
|
||||
getStatusBadgeClass,
|
||||
getStatusLabel,
|
||||
normalizeDuplicateDocumentError,
|
||||
} from '../utils/kb-display.utils';
|
||||
import {
|
||||
getPathUploadJobItems,
|
||||
getPathUploadJobPriority,
|
||||
getPathUploadJobProgress,
|
||||
getPathUploadJobSummary,
|
||||
hasRetryablePathUploadFailure,
|
||||
} from '../utils/kb-path-upload.utils';
|
||||
import {
|
||||
buildGetLatestJobForDocument,
|
||||
getDocumentWorkflowState,
|
||||
getMarkdownUnavailableMessage,
|
||||
getWorkflowBadges,
|
||||
normalizeWorkflowErrorMessage,
|
||||
} from '../utils/kb-workflow.utils';
|
||||
|
||||
export interface UseKbWorkspaceOptions {
|
||||
embedded?: boolean;
|
||||
}
|
||||
|
||||
export function useKbWorkspace(options: UseKbWorkspaceOptions = {}) {
|
||||
`;
|
||||
|
||||
const footer = `
|
||||
return {
|
||||
embedded,
|
||||
router,
|
||||
t,
|
||||
isKbAdmin,
|
||||
isLoading,
|
||||
isDocumentsLoading,
|
||||
isSubmitting,
|
||||
isRecordLoading,
|
||||
groups,
|
||||
documents,
|
||||
jobs,
|
||||
selectedGroupId,
|
||||
selectedDocumentId,
|
||||
activeUploadDocumentId,
|
||||
syncingDocumentId,
|
||||
selectedDocumentVersions,
|
||||
selectedDocumentSyncRecords,
|
||||
feedback,
|
||||
feedbackType,
|
||||
viewMode,
|
||||
showMarkdownModal,
|
||||
showRecordModal,
|
||||
showSourceInfoModal,
|
||||
showFailureModal,
|
||||
showPathUploadModal,
|
||||
showPathUploadHistoryModal,
|
||||
showDeleteConfirmDialog,
|
||||
deleteConfirmMessage,
|
||||
showPathUploadDetails,
|
||||
fileInputRef,
|
||||
pathUploadInputRef,
|
||||
markdownDocumentId,
|
||||
sourceInfoDocumentId,
|
||||
markdownContent,
|
||||
markdownKind,
|
||||
markdownVersionLabel,
|
||||
markdownError,
|
||||
isMarkdownLoading,
|
||||
isMarkdownSaving,
|
||||
isSourceInfoLoading,
|
||||
openingSourceVersionId,
|
||||
failureModalType,
|
||||
failureModalPage,
|
||||
retryingFailureKey,
|
||||
documentStageFilter,
|
||||
documentListPage,
|
||||
documentListPageSize,
|
||||
documentKeyword,
|
||||
batchSubmitting,
|
||||
selectedDocumentIds,
|
||||
pathUploadDraftText,
|
||||
pathUploadSelectedFiles,
|
||||
isPathUploadStaging,
|
||||
pathUploadJobId,
|
||||
selectedPathUploadHistoryJobId,
|
||||
selectedPathUploadHistoryItemKeys,
|
||||
retryingPathUploadKey,
|
||||
deletingPathUploadBatch,
|
||||
openDeleteConfirmDialog,
|
||||
closeDeleteConfirmDialog,
|
||||
handleDeleteConfirm,
|
||||
selectedDocument,
|
||||
sourceInfoDocument,
|
||||
selectedGroup,
|
||||
markdownModalTitle,
|
||||
sourceInfoVersions,
|
||||
activeGroupJobs,
|
||||
pathUploadTask,
|
||||
groupSummaryItems,
|
||||
stageFilterTabs,
|
||||
filteredDocuments,
|
||||
filteredDocumentTotalPages,
|
||||
pagedFilteredDocuments,
|
||||
pagedDocumentRange,
|
||||
selectedDocuments,
|
||||
selectedCleanableDocuments,
|
||||
isAllFilteredSelected,
|
||||
failureModalItems,
|
||||
failureModalTotalPages,
|
||||
pagedFailureModalItems,
|
||||
failureModalTitle,
|
||||
documentById,
|
||||
latestPathUploadJob,
|
||||
pathUploadHistoryJobs,
|
||||
selectedPathUploadHistoryJob,
|
||||
selectedPathUploadHistoryItems,
|
||||
selectedPathUploadHistorySelectedItems,
|
||||
isAllPathUploadHistoryItemsSelected,
|
||||
pathUploadSummary,
|
||||
recentPathUploadItems,
|
||||
pathUploadRunning,
|
||||
kbJobPollingActive,
|
||||
selectedPathRoots,
|
||||
loadGroups,
|
||||
loadJobs,
|
||||
refreshWorkflowStatusOnly,
|
||||
refreshCurrentView,
|
||||
formatDateTime,
|
||||
formatFileSize,
|
||||
getDocumentDisplayTitle,
|
||||
getDocumentDisplayDescription,
|
||||
getStatusLabel,
|
||||
getStatusBadgeClass,
|
||||
getWorkflowBadges,
|
||||
getDocumentWorkflowState,
|
||||
openGroupDetail,
|
||||
backToGroupOverview,
|
||||
loadDocuments,
|
||||
loadDocumentVersions,
|
||||
openDocumentDetail,
|
||||
closeDocumentDetail,
|
||||
openSourceInfo,
|
||||
closeSourceInfoModal,
|
||||
openOriginalSourceFile,
|
||||
openFailureModal,
|
||||
closeFailureModal,
|
||||
resetPathUploadDraft,
|
||||
openPathUploadModal,
|
||||
closePathUploadModal,
|
||||
triggerPathUploadSelection,
|
||||
handlePathFilesSelected,
|
||||
removeSelectedPathFile,
|
||||
openPathUploadHistoryModal,
|
||||
closePathUploadHistoryModal,
|
||||
togglePathUploadHistoryItemSelection,
|
||||
toggleSelectAllPathUploadHistoryItems,
|
||||
handleConfirmPathUpload,
|
||||
handleDeletePathUploadItem,
|
||||
handleBatchDeletePathUploadItems,
|
||||
handleRetryFailedPathUpload,
|
||||
toggleDocumentSelection,
|
||||
toggleSelectAllFiltered,
|
||||
handleDeleteDocument,
|
||||
handleBatchSync,
|
||||
handleBatchClean,
|
||||
handleBatchDelete,
|
||||
handleRetryFailedItem,
|
||||
triggerUploadForDocument,
|
||||
handleFileSelected,
|
||||
triggerMultiUpload,
|
||||
handleSyncDocument,
|
||||
openMarkdownEditor,
|
||||
closeMarkdownModal,
|
||||
handleSaveMarkdown,
|
||||
getPathUploadItemDisplayState,
|
||||
getPathUploadJobItems,
|
||||
hasRetryablePathUploadFailure,
|
||||
getPathUploadJobSummary,
|
||||
DOCUMENT_PAGE_SIZE_OPTIONS,
|
||||
FAILURE_PAGE_SIZE,
|
||||
};
|
||||
}
|
||||
`;
|
||||
|
||||
// Remove duplicate imports from body
|
||||
body = body.replace(/^import[\s\S]*?from ['"][^'"]+['"];?\s*/gm, '');
|
||||
body = body.replace(/type WorkflowStageState[\s\S]*?type LoadListOptions[\s\S]*?};\s*/m, '');
|
||||
body = body.replace(/const FAILURE_PAGE_SIZE[\s\S]*?const DOCUMENT_PAGE_SIZE_OPTIONS[\s\S]*?as const;\s*/m, '');
|
||||
body = body.replace(/const idleBadgeClass[\s\S]*?;/m, 'const idleBadgeClass = IDLE_BADGE_CLASS;');
|
||||
body = body.replace(/const mergeStableItems[\s\S]*?};\s*/m, '');
|
||||
body = body.replace(/const getLatestJobForDocument[\s\S]*?};\s*/m, '');
|
||||
body = body.replace(/const isUnreadableErrorMessage[\s\S]*?};\s*/m, '');
|
||||
body = body.replace(/const normalizeWorkflowErrorMessage[\s\S]*?};\s*/m, '');
|
||||
body = body.replace(/const getDocumentWorkflowState[\s\S]*?};\s*/m, '');
|
||||
body = body.replace(/const formatDateTime[\s\S]*?};\s*/m, '');
|
||||
body = body.replace(/const formatFileSize[\s\S]*?};\s*/m, '');
|
||||
body = body.replace(/const trimPathText[\s\S]*?};\s*/m, '');
|
||||
body = body.replace(/const getDocumentDisplayTitle[\s\S]*?};\s*/m, '');
|
||||
body = body.replace(/const getDocumentDisplayDescription[\s\S]*?};\s*/m, '');
|
||||
body = body.replace(/const normalizeDuplicateDocumentError[\s\S]*?};\s*/m, '');
|
||||
body = body.replace(/const getStatusLabel[\s\S]*?};\s*/m, '');
|
||||
body = body.replace(/const getStatusBadgeClass[\s\S]*?};\s*/m, '');
|
||||
body = body.replace(/const getWorkflowBadges[\s\S]*?};\s*/m, '');
|
||||
body = body.replace(/const getMarkdownUnavailableMessage[\s\S]*?};\s*/m, '');
|
||||
body = body.replace(/const getPathUploadJobProgress[\s\S]*?};\s*/m, '');
|
||||
body = body.replace(/const getPathUploadJobPriority[\s\S]*?};\s*/m, '');
|
||||
body = body.replace(/const getPathUploadJobItems[\s\S]*?};\s*/m, '');
|
||||
body = body.replace(/const hasRetryablePathUploadFailure[\s\S]*?;/m, '');
|
||||
body = body.replace(/const getPathUploadJobSummary[\s\S]*?};\s*/m, '');
|
||||
|
||||
const getLatestJobBlock = `
|
||||
const getLatestJobForDocument = buildGetLatestJobForDocument(() => activeGroupJobs.value);
|
||||
const resolveWorkflowState = (doc: KbDocumentItem) =>
|
||||
getDocumentWorkflowState(doc, getLatestJobForDocument);
|
||||
`;
|
||||
|
||||
body = body.replace(
|
||||
/const groupSummaryItems = computed/,
|
||||
`${getLatestJobBlock}\nconst groupSummaryItems = computed`,
|
||||
);
|
||||
body = body.replace(/getDocumentWorkflowState\(/g, 'resolveWorkflowState(');
|
||||
body = body.replace(/getWorkflowBadges = \(doc: KbDocumentItem\) => \{[\s\S]*?\};/m,
|
||||
'const getWorkflowBadgesForDoc = (doc: KbDocumentItem) => getWorkflowBadges(doc, getLatestJobForDocument);');
|
||||
body = body.replace(/getWorkflowBadges\(/g, 'getWorkflowBadgesForDoc(');
|
||||
|
||||
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
||||
fs.writeFileSync(outPath, `${header}${body}${footer}`, 'utf8');
|
||||
console.log('Wrote', outPath);
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* scripts/slim-kb-workspace-view.mjs
|
||||
* 将 KbWorkspaceView.vue 的 script 替换为 useKbWorkspace 薄壳(kb 单对象绑定)。
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const composablePath = path.resolve(__dirname, '../src/features/kb/composables/useKbWorkspace.ts');
|
||||
const vuePath = path.resolve(__dirname, '../src/features/kb/views/KbWorkspaceView.vue');
|
||||
|
||||
const composable = fs.readFileSync(composablePath, 'utf8');
|
||||
const returnStart = composable.lastIndexOf('\n return {');
|
||||
const returnBody = composable.slice(returnStart + '\n return {'.length, composable.lastIndexOf('\n };'));
|
||||
const keys = returnBody
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter(Boolean)
|
||||
.map((line) => {
|
||||
const alias = line.match(/^(\w+):\s*(\w+),?$/);
|
||||
if (alias) return alias[1];
|
||||
return line.replace(/,$/, '');
|
||||
});
|
||||
|
||||
const script = `<script setup lang="ts">
|
||||
/**
|
||||
* features/kb/views/KbWorkspaceView.vue
|
||||
* 知识库作业面视图壳:模板与弹窗布局,业务逻辑见 useKbWorkspace。
|
||||
*/
|
||||
import { ArrowLeft, BookOpen, ChevronDown, ChevronUp, FileText, Info, RefreshCw, Search, Trash2, Upload, X } from 'lucide-vue-next';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
import { useKbWorkspace } from '../composables/useKbWorkspace';
|
||||
|
||||
const props = defineProps<{
|
||||
embedded?: boolean;
|
||||
}>();
|
||||
|
||||
const kb = useKbWorkspace({ embedded: props.embedded });
|
||||
</script>`;
|
||||
|
||||
let vue = fs.readFileSync(vuePath, 'utf8');
|
||||
let template = vue.match(/<template>[\s\S]*/)?.[0];
|
||||
if (!template) throw new Error('template not found');
|
||||
|
||||
// 按 key 长度降序,避免短名误替换长名前缀
|
||||
const sortedKeys = [...keys].sort((a, b) => b.length - a.length);
|
||||
for (const key of sortedKeys) {
|
||||
const re = new RegExp(`(?<![.\\w])${key}(?![.\\w])`, 'g');
|
||||
template = template.replace(re, `kb.${key}`);
|
||||
}
|
||||
template = template.replace(/kb\.kb\./g, 'kb.');
|
||||
|
||||
fs.writeFileSync(vuePath, `${script}\n\n${template}\n`, 'utf8');
|
||||
console.log(`Slimmed KbWorkspaceView.vue with kb.* bindings (${keys.length} keys)`);
|
||||
+2
-546
@@ -1,548 +1,4 @@
|
||||
/**
|
||||
* src/api/kb.ts
|
||||
* 知识库 HTTP API(暂缓迁入 features/kb,KB redesign 后迁移)。
|
||||
* @deprecated 请使用 `@/features/kb/api/kb.api`。本文件仅为兼容旧 import 保留转发。
|
||||
*/
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { BusinessError, requestJson } from '@/shared/api/client';
|
||||
|
||||
export interface KbGroup {
|
||||
id: number;
|
||||
name: string;
|
||||
description?: string | null;
|
||||
department_id?: number | null;
|
||||
document_count?: number;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
}
|
||||
|
||||
export interface KbDocumentItem {
|
||||
id: number;
|
||||
group_id?: number;
|
||||
title: string;
|
||||
description?: string | null;
|
||||
status?: string;
|
||||
source_type?: string | null;
|
||||
created_at?: string | null;
|
||||
updated_at?: string;
|
||||
version_count?: number;
|
||||
latest_version?: KbDocumentVersionItem | null;
|
||||
}
|
||||
|
||||
export interface KbDocumentVersionItem {
|
||||
id: number;
|
||||
document_id: number;
|
||||
version_no: number;
|
||||
status: string;
|
||||
is_current: boolean;
|
||||
source_file_name: string;
|
||||
source_file_ext?: string | null;
|
||||
source_file_size?: number | null;
|
||||
sha256?: string | null;
|
||||
cleaned_file_path?: string | null;
|
||||
cleaned_preview_path?: string | null;
|
||||
error_message?: string | null;
|
||||
created_at?: string | null;
|
||||
}
|
||||
|
||||
export interface KbSyncRecordItem {
|
||||
id: number;
|
||||
group_id?: number | null;
|
||||
document_id?: number | null;
|
||||
document_version_id: number;
|
||||
dataset_id: string;
|
||||
dataset_name?: string | null;
|
||||
remote_document_id: string;
|
||||
remote_document_name?: string | null;
|
||||
status: string;
|
||||
sync_hash?: string | null;
|
||||
error_message?: string | null;
|
||||
synced_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
}
|
||||
|
||||
export interface KbDocumentMarkdown {
|
||||
document_id: number;
|
||||
title: string;
|
||||
version: KbDocumentVersionItem | null;
|
||||
content: string;
|
||||
kind: 'markdown' | 'preview';
|
||||
}
|
||||
|
||||
export interface KbJob {
|
||||
id: number | string;
|
||||
job_type: string;
|
||||
status: string;
|
||||
group_id?: number | null;
|
||||
document_id?: number | null;
|
||||
document_version_id?: number | null;
|
||||
progress?: number;
|
||||
message?: string | null;
|
||||
error_message?: string | null;
|
||||
payload_json?: Record<string, any> | null;
|
||||
result_json?: Record<string, any> | null;
|
||||
created_at?: string;
|
||||
started_at?: string | null;
|
||||
finished_at?: string | null;
|
||||
}
|
||||
|
||||
export interface KbQueuedJobResponse extends KbJob {
|
||||
accepted?: boolean;
|
||||
queue_result?: string;
|
||||
}
|
||||
|
||||
export interface KbUploadVersionResponse {
|
||||
accepted?: boolean;
|
||||
message?: string;
|
||||
queue_result?: string;
|
||||
version: KbDocumentVersionItem;
|
||||
clean_job?: KbJob | null;
|
||||
}
|
||||
|
||||
export interface KbDifySettings {
|
||||
DIFY_API_BASE: string;
|
||||
DIFY_API_KEY: string;
|
||||
KB_DIFY_PERMISSION: string;
|
||||
KB_DIFY_INDEXING_TECHNIQUE: string;
|
||||
KB_DIFY_SEARCH_METHOD: string;
|
||||
KB_DIFY_DOC_FORM: string;
|
||||
dify_api_configured?: boolean;
|
||||
}
|
||||
|
||||
export interface KbDifyHealth {
|
||||
dify_base_url: string;
|
||||
dify_api_configured: boolean;
|
||||
api: {
|
||||
configured: boolean;
|
||||
reachable: boolean;
|
||||
dataset_count?: number | null;
|
||||
error?: string | null;
|
||||
};
|
||||
local_sync_health: {
|
||||
dataset_bound_groups: number;
|
||||
sync_records: number;
|
||||
syncing_versions: number;
|
||||
synced_versions: number;
|
||||
failed_sync_records: number;
|
||||
pending_sync_jobs: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface KbListResponse<T> {
|
||||
ok: boolean;
|
||||
data: T;
|
||||
error?: string;
|
||||
status?: number;
|
||||
}
|
||||
|
||||
const auth = () => ({ headers: getAuthHeaders() });
|
||||
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
|
||||
|
||||
const kbErrorMessage = (e: unknown, fallback: string) => (e as Error).message || fallback;
|
||||
|
||||
const getJson = async <T>(path: string, fallback: T): Promise<T> => {
|
||||
try {
|
||||
return await requestJson<T>(path, auth());
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
};
|
||||
|
||||
const getJsonWithStatus = async <T>(path: string, fallback: T): Promise<KbListResponse<T>> => {
|
||||
try {
|
||||
const data = await requestJson<T>(path, auth());
|
||||
return { ok: true, data };
|
||||
} catch (e) {
|
||||
const err = e as BusinessError;
|
||||
return {
|
||||
ok: false,
|
||||
data: fallback,
|
||||
error: kbErrorMessage(e, '知识库接口请求失败'),
|
||||
status: err.status,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
export const getKbGroups = async (): Promise<KbGroup[]> => {
|
||||
return getJson<KbGroup[]>('/api/kb/groups', []);
|
||||
};
|
||||
|
||||
export const getKbGroupFiles = async (groupId: number): Promise<KbDocumentItem[]> => {
|
||||
return getJson<KbDocumentItem[]>(`/api/kb/groups/${groupId}/files`, []);
|
||||
};
|
||||
|
||||
export const getKbGroupsSafe = async (): Promise<KbListResponse<KbGroup[]>> => {
|
||||
return getJsonWithStatus<KbGroup[]>('/api/kb/groups', []);
|
||||
};
|
||||
|
||||
export const getKbGroupFilesSafe = async (groupId: number): Promise<KbListResponse<KbDocumentItem[]>> => {
|
||||
return getJsonWithStatus<KbDocumentItem[]>(`/api/kb/groups/${groupId}/files`, []);
|
||||
};
|
||||
|
||||
export const createKbGroup = async (payload: {
|
||||
name: string;
|
||||
description?: string;
|
||||
}): Promise<{ ok: boolean; error?: string; group?: KbGroup }> => {
|
||||
try {
|
||||
const group = await requestJson<KbGroup>('/api/kb/groups', {
|
||||
method: 'POST',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
return { ok: true, group };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '创建知识库分组失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const getKbJobs = async (): Promise<KbJob[]> => {
|
||||
return getJson<KbJob[]>('/api/kb/jobs', []);
|
||||
};
|
||||
|
||||
export const getKbJobsSafe = async (): Promise<KbListResponse<KbJob[]>> => {
|
||||
return getJsonWithStatus<KbJob[]>('/api/kb/jobs', []);
|
||||
};
|
||||
|
||||
export const getKbDifySettings = async (): Promise<KbDifySettings | null> => {
|
||||
return getJson<KbDifySettings | null>('/api/kb/dify/settings', null);
|
||||
};
|
||||
|
||||
export const updateKbDifySettings = async (
|
||||
payload: Partial<KbDifySettings>
|
||||
): Promise<{ ok: boolean; error?: string; settings?: KbDifySettings }> => {
|
||||
try {
|
||||
const settings = await requestJson<KbDifySettings>('/api/kb/dify/settings', {
|
||||
method: 'PATCH',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
return { ok: true, settings };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '保存 Dify 设置失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const getKbDifyHealth = async (): Promise<KbDifyHealth | null> => {
|
||||
return getJson<KbDifyHealth | null>('/api/kb/dify/health', null);
|
||||
};
|
||||
|
||||
export const runKbJob = async (
|
||||
jobId: number | string
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob; run_result?: string }> => {
|
||||
try {
|
||||
const job = await requestJson<KbJob & { run_result?: string }>(`/api/kb/jobs/${jobId}/run`, {
|
||||
method: 'POST',
|
||||
...auth(),
|
||||
});
|
||||
return { ok: true, job, run_result: job.run_result };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '执行任务失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const createKbDocument = async (
|
||||
groupId: number,
|
||||
payload: { title: string; description?: string }
|
||||
): Promise<{ ok: boolean; error?: string; document?: KbDocumentItem }> => {
|
||||
try {
|
||||
const document = await requestJson<KbDocumentItem>(`/api/kb/groups/${groupId}/files`, {
|
||||
method: 'POST',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
return { ok: true, document };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '创建文档失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const updateKbDocument = async (
|
||||
documentId: number,
|
||||
payload: { title: string; description?: string; status?: string }
|
||||
): Promise<{ ok: boolean; error?: string; document?: KbDocumentItem }> => {
|
||||
try {
|
||||
const document = await requestJson<KbDocumentItem>(`/api/kb/documents/${documentId}`, {
|
||||
method: 'PATCH',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
return { ok: true, document };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '更新文档失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const deleteKbDocument = async (
|
||||
documentId: number
|
||||
): Promise<{ ok: boolean; error?: string }> => {
|
||||
try {
|
||||
await requestJson(`/api/kb/documents/${documentId}`, { method: 'DELETE', ...auth() });
|
||||
return { ok: true };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '删除文档失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const getKbDocumentVersions = async (
|
||||
documentId: number
|
||||
): Promise<KbDocumentVersionItem[]> => {
|
||||
return getJson<KbDocumentVersionItem[]>(`/api/kb/documents/${documentId}/versions`, []);
|
||||
};
|
||||
|
||||
export const getKbDocumentVersionSourceFile = async (
|
||||
versionId: number
|
||||
): Promise<{ ok: boolean; error?: string; blob?: Blob; filename?: string; contentType?: string }> => {
|
||||
try {
|
||||
const res = await fetch(`/api/kb/document-versions/${versionId}/source-file`, {
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
if (!res.ok) {
|
||||
let message = '读取原始文件失败';
|
||||
try {
|
||||
const data = await res.json();
|
||||
if (typeof data?.error === 'string' && data.error.trim()) message = data.error;
|
||||
else if (typeof data?.message === 'string' && data.message.trim()) message = data.message;
|
||||
} catch {
|
||||
// ignore non-json error body
|
||||
}
|
||||
return { ok: false, error: message };
|
||||
}
|
||||
const disposition = res.headers.get('content-disposition') || '';
|
||||
const filenameMatch = disposition.match(/filename\*=UTF-8''([^;]+)|filename="?([^"]+)"?/i);
|
||||
const filename = decodeURIComponent(filenameMatch?.[1] || filenameMatch?.[2] || '');
|
||||
return {
|
||||
ok: true,
|
||||
blob: await res.blob(),
|
||||
filename: filename || undefined,
|
||||
contentType: res.headers.get('content-type') || undefined,
|
||||
};
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
}
|
||||
};
|
||||
|
||||
export const getKbDocumentSyncRecords = async (
|
||||
documentId: number
|
||||
): Promise<KbSyncRecordItem[]> => {
|
||||
return getJson<KbSyncRecordItem[]>(`/api/kb/documents/${documentId}/sync-records`, []);
|
||||
};
|
||||
|
||||
export const getKbDocumentMarkdown = async (
|
||||
documentId: number
|
||||
): Promise<{ ok: boolean; error?: string; data?: KbDocumentMarkdown }> => {
|
||||
try {
|
||||
const data = await requestJson<KbDocumentMarkdown>(`/api/kb/documents/${documentId}/markdown`, auth());
|
||||
return { ok: true, data };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '读取清洗后的 Markdown 失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const updateKbDocumentMarkdown = async (
|
||||
documentId: number,
|
||||
payload: { content: string }
|
||||
): Promise<{ ok: boolean; error?: string; data?: KbDocumentMarkdown }> => {
|
||||
try {
|
||||
const data = await requestJson<KbDocumentMarkdown>(`/api/kb/documents/${documentId}/markdown`, {
|
||||
method: 'PATCH',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
return { ok: true, data };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '保存 Markdown 失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const uploadKbDocumentVersion = async (
|
||||
documentId: number,
|
||||
file: File
|
||||
): Promise<{ ok: boolean; error?: string; version?: KbDocumentVersionItem; clean_job?: KbJob | null; message?: string; status?: number }> => {
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
const payload = await requestJson<KbUploadVersionResponse>(`/api/kb/documents/${documentId}/upload`, {
|
||||
method: 'POST',
|
||||
...auth(),
|
||||
body: formData,
|
||||
});
|
||||
return { ok: true, version: payload.version, clean_job: payload.clean_job, message: payload.message };
|
||||
} catch (e) {
|
||||
const err = e as BusinessError;
|
||||
if (err.status === 413) {
|
||||
return {
|
||||
ok: false,
|
||||
error: '文件过大,超过当前上传限制,请联系管理员放宽限制后重试',
|
||||
status: 413,
|
||||
};
|
||||
}
|
||||
return { ok: false, error: kbErrorMessage(e, '上传文档版本失败'), status: err.status };
|
||||
}
|
||||
};
|
||||
|
||||
export const submitKbDocumentClean = async (
|
||||
documentId: number
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob | null; message?: string; status?: number }> => {
|
||||
try {
|
||||
const job = await requestJson<KbQueuedJobResponse>(`/api/kb/documents/${documentId}/clean`, {
|
||||
method: 'POST',
|
||||
...auth(),
|
||||
});
|
||||
return { ok: true, job, message: job.message || undefined };
|
||||
} catch (e) {
|
||||
const err = e as BusinessError;
|
||||
return { ok: false, error: kbErrorMessage(e, '提交清洗任务失败'), status: err.status };
|
||||
}
|
||||
};
|
||||
|
||||
export const createKbPathUploadJob = async (
|
||||
groupId: number,
|
||||
payload: {
|
||||
total_files: number;
|
||||
selected_paths: string[];
|
||||
files?: Array<{ relative_path: string; original_name: string }>;
|
||||
}
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob; status?: number }> => {
|
||||
try {
|
||||
const job = await requestJson<KbJob>(`/api/kb/groups/${groupId}/path-upload-jobs`, {
|
||||
method: 'POST',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
return { ok: true, job };
|
||||
} catch (e) {
|
||||
const err = e as BusinessError;
|
||||
return { ok: false, error: kbErrorMessage(e, '创建路径上传任务失败'), status: err.status };
|
||||
}
|
||||
};
|
||||
|
||||
export const uploadKbPathJobFile = async (
|
||||
jobId: number | string,
|
||||
file: File,
|
||||
relativePath: string,
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob; status?: number }> => {
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
formData.append('relative_path', relativePath);
|
||||
const job = await requestJson<KbJob>(`/api/kb/path-upload-jobs/${jobId}/files`, {
|
||||
method: 'POST',
|
||||
...auth(),
|
||||
body: formData,
|
||||
});
|
||||
return { ok: true, job };
|
||||
} catch (e) {
|
||||
const err = e as BusinessError;
|
||||
if (err.status === 413) {
|
||||
return {
|
||||
ok: false,
|
||||
error: '文件过大,超过当前上传限制,请联系管理员放宽限制后重试',
|
||||
status: 413,
|
||||
};
|
||||
}
|
||||
return { ok: false, error: kbErrorMessage(e, '上传路径文件失败'), status: err.status };
|
||||
}
|
||||
};
|
||||
|
||||
export const markKbPathJobFileFailed = async (
|
||||
jobId: number | string,
|
||||
payload: { relative_path: string; original_name?: string; error: string }
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob }> => {
|
||||
try {
|
||||
const job = await requestJson<KbJob>(`/api/kb/path-upload-jobs/${jobId}/files/fail`, {
|
||||
method: 'POST',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
return { ok: true, job };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '记录路径文件失败状态失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const finalizeKbPathUploadJob = async (
|
||||
jobId: number | string,
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob }> => {
|
||||
try {
|
||||
const job = await requestJson<KbQueuedJobResponse>(`/api/kb/path-upload-jobs/${jobId}/finalize`, {
|
||||
method: 'POST',
|
||||
...auth(),
|
||||
});
|
||||
return { ok: true, job };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '提交路径上传任务失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const retryFailedKbPathUploadJob = async (
|
||||
jobId: number | string,
|
||||
payload?: { relative_paths?: string[] },
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob; status?: number }> => {
|
||||
try {
|
||||
const job = await requestJson<KbJob>(`/api/kb/path-upload-jobs/${jobId}/retry-failed`, {
|
||||
method: 'POST',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload || {}),
|
||||
});
|
||||
return { ok: true, job };
|
||||
} catch (e) {
|
||||
const err = e as BusinessError;
|
||||
return { ok: false, error: kbErrorMessage(e, '重试失败文件失败'), status: err.status };
|
||||
}
|
||||
};
|
||||
|
||||
export const deleteKbPathJobFile = async (
|
||||
jobId: number | string,
|
||||
relativePath: string,
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob; document_deleted?: boolean }> => {
|
||||
try {
|
||||
const query = new URLSearchParams({ relative_path: relativePath });
|
||||
const result = await requestJson<{ ok: boolean; job: KbJob; document_deleted?: boolean }>(
|
||||
`/api/kb/path-upload-jobs/${jobId}/files?${query.toString()}`,
|
||||
{ method: 'DELETE', ...auth() }
|
||||
);
|
||||
return { ok: true, job: result.job, document_deleted: result.document_deleted };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '删除路径上传文件失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const syncKbDocumentToDify = async (
|
||||
documentId: number
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbQueuedJobResponse }> => {
|
||||
try {
|
||||
const job = await requestJson<KbQueuedJobResponse>(`/api/kb/documents/${documentId}/sync`, {
|
||||
method: 'POST',
|
||||
...auth(),
|
||||
});
|
||||
return { ok: true, job };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '同步到 Dify 失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const updateKbGroup = async (
|
||||
groupId: number,
|
||||
payload: { name: string; description?: string }
|
||||
): Promise<{ ok: boolean; error?: string; group?: KbGroup }> => {
|
||||
try {
|
||||
const group = await requestJson<KbGroup>(`/api/kb/groups/${groupId}`, {
|
||||
method: 'PATCH',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
return { ok: true, group };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '更新知识库分组失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const deleteKbGroup = async (
|
||||
groupId: number
|
||||
): Promise<{ ok: boolean; error?: string }> => {
|
||||
try {
|
||||
await requestJson(`/api/kb/groups/${groupId}`, { method: 'DELETE', ...auth() });
|
||||
return { ok: true };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '删除知识库分组失败') };
|
||||
}
|
||||
};
|
||||
export * from '@/features/kb/api/kb.api';
|
||||
@@ -77,7 +77,7 @@ export const adminRoutes: RouteRecordRaw[] = [
|
||||
meta: {
|
||||
requiresAdmin: true,
|
||||
adminModule: "knowledge_base",
|
||||
title: "知识库",
|
||||
title: "知识库配置",
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
/**
|
||||
* app/router/routes/kb.routes.ts
|
||||
* 知识库相关路由。
|
||||
* 知识库兼容路由:旧 URL 重定向至 canonical 路径。
|
||||
*/
|
||||
import type { RouteRecordRaw } from 'vue-router';
|
||||
import KbWorkspaceView from '@/views/KbWorkspaceView.vue';
|
||||
|
||||
export const kbRoutes: RouteRecordRaw[] = [
|
||||
{ path: '/kb/workspace', name: 'KbWorkspace', component: KbWorkspaceView, meta: { title: '知识库工作台' } },
|
||||
{ path: '/kb/workspace', redirect: { path: '/workspace/knowledge-base' } },
|
||||
{ path: '/kb/admin', redirect: { path: '/admin/knowledge-base' } },
|
||||
];
|
||||
@@ -33,7 +33,7 @@ export const workspaceRoutes: RouteRecordRaw[] = [
|
||||
path: 'knowledge-base',
|
||||
name: 'workspace-knowledge-base',
|
||||
component: () => import('@/features/workspace/pages/KnowledgeBasePage.vue'),
|
||||
meta: { title: '知识库管理' },
|
||||
meta: { title: '知识库' },
|
||||
},
|
||||
{
|
||||
path: 'schedule-runs',
|
||||
@@ -56,7 +56,7 @@ export const workspaceRoutes: RouteRecordRaw[] = [
|
||||
{
|
||||
path: 'history',
|
||||
name: 'workspace-history',
|
||||
component: () => import('@/features/chat/pages/HistoryPage.vue'),
|
||||
component: () => import('@/features/chat/history/HistoryPage.vue'),
|
||||
meta: { title: '聊天历史' },
|
||||
},
|
||||
],
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
/**
|
||||
* features/admin/modules/knowledge-base/KnowledgeBasePage.vue
|
||||
* 知识库管理独立页面。路由:/admin/knowledge-base
|
||||
* 知识库配置页(治理面)。路由:/admin/knowledge-base
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import KbAdminPanel from '@/shared/components/kb/KbAdminPanel.vue';
|
||||
import KbAdminPanel from '@/features/kb/components/KbAdminPanel.vue';
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { listAdminAgents, listAdminUsers } from '@/features/admin/api/admin.api';
|
||||
import { getKbGroups, type KbGroup } from '@/api/kb';
|
||||
import { getKbGroups, type KbGroup } from '@/features/kb/api/kb.api';
|
||||
import {
|
||||
createAdminSchedule,
|
||||
deleteAdminSchedule,
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/chat/pages/HistoryPage.vue
|
||||
* features/chat/history/HistoryPage.vue
|
||||
* 跨 Agent 聊天历史列表,点击跳转对应会话(工作台 / 移动端 Tab 入口)。
|
||||
*/
|
||||
import { inject } from 'vue';
|
||||
@@ -0,0 +1,548 @@
|
||||
/**
|
||||
* features/kb/api/kb.api.ts
|
||||
* 知识库 HTTP API。
|
||||
*/
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { BusinessError, requestJson } from '@/shared/api/client';
|
||||
|
||||
export interface KbGroup {
|
||||
id: number;
|
||||
name: string;
|
||||
description?: string | null;
|
||||
department_id?: number | null;
|
||||
document_count?: number;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
}
|
||||
|
||||
export interface KbDocumentItem {
|
||||
id: number;
|
||||
group_id?: number;
|
||||
title: string;
|
||||
description?: string | null;
|
||||
status?: string;
|
||||
source_type?: string | null;
|
||||
created_at?: string | null;
|
||||
updated_at?: string;
|
||||
version_count?: number;
|
||||
latest_version?: KbDocumentVersionItem | null;
|
||||
}
|
||||
|
||||
export interface KbDocumentVersionItem {
|
||||
id: number;
|
||||
document_id: number;
|
||||
version_no: number;
|
||||
status: string;
|
||||
is_current: boolean;
|
||||
source_file_name: string;
|
||||
source_file_ext?: string | null;
|
||||
source_file_size?: number | null;
|
||||
sha256?: string | null;
|
||||
cleaned_file_path?: string | null;
|
||||
cleaned_preview_path?: string | null;
|
||||
error_message?: string | null;
|
||||
created_at?: string | null;
|
||||
}
|
||||
|
||||
export interface KbSyncRecordItem {
|
||||
id: number;
|
||||
group_id?: number | null;
|
||||
document_id?: number | null;
|
||||
document_version_id: number;
|
||||
dataset_id: string;
|
||||
dataset_name?: string | null;
|
||||
remote_document_id: string;
|
||||
remote_document_name?: string | null;
|
||||
status: string;
|
||||
sync_hash?: string | null;
|
||||
error_message?: string | null;
|
||||
synced_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
}
|
||||
|
||||
export interface KbDocumentMarkdown {
|
||||
document_id: number;
|
||||
title: string;
|
||||
version: KbDocumentVersionItem | null;
|
||||
content: string;
|
||||
kind: 'markdown' | 'preview';
|
||||
}
|
||||
|
||||
export interface KbJob {
|
||||
id: number | string;
|
||||
job_type: string;
|
||||
status: string;
|
||||
group_id?: number | null;
|
||||
document_id?: number | null;
|
||||
document_version_id?: number | null;
|
||||
progress?: number;
|
||||
message?: string | null;
|
||||
error_message?: string | null;
|
||||
payload_json?: Record<string, any> | null;
|
||||
result_json?: Record<string, any> | null;
|
||||
created_at?: string;
|
||||
started_at?: string | null;
|
||||
finished_at?: string | null;
|
||||
}
|
||||
|
||||
export interface KbQueuedJobResponse extends KbJob {
|
||||
accepted?: boolean;
|
||||
queue_result?: string;
|
||||
}
|
||||
|
||||
export interface KbUploadVersionResponse {
|
||||
accepted?: boolean;
|
||||
message?: string;
|
||||
queue_result?: string;
|
||||
version: KbDocumentVersionItem;
|
||||
clean_job?: KbJob | null;
|
||||
}
|
||||
|
||||
export interface KbDifySettings {
|
||||
DIFY_API_BASE: string;
|
||||
DIFY_API_KEY: string;
|
||||
KB_DIFY_PERMISSION: string;
|
||||
KB_DIFY_INDEXING_TECHNIQUE: string;
|
||||
KB_DIFY_SEARCH_METHOD: string;
|
||||
KB_DIFY_DOC_FORM: string;
|
||||
dify_api_configured?: boolean;
|
||||
}
|
||||
|
||||
export interface KbDifyHealth {
|
||||
dify_base_url: string;
|
||||
dify_api_configured: boolean;
|
||||
api: {
|
||||
configured: boolean;
|
||||
reachable: boolean;
|
||||
dataset_count?: number | null;
|
||||
error?: string | null;
|
||||
};
|
||||
local_sync_health: {
|
||||
dataset_bound_groups: number;
|
||||
sync_records: number;
|
||||
syncing_versions: number;
|
||||
synced_versions: number;
|
||||
failed_sync_records: number;
|
||||
pending_sync_jobs: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface KbListResponse<T> {
|
||||
ok: boolean;
|
||||
data: T;
|
||||
error?: string;
|
||||
status?: number;
|
||||
}
|
||||
|
||||
const auth = () => ({ headers: getAuthHeaders() });
|
||||
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
|
||||
|
||||
const kbErrorMessage = (e: unknown, fallback: string) => (e as Error).message || fallback;
|
||||
|
||||
const getJson = async <T>(path: string, fallback: T): Promise<T> => {
|
||||
try {
|
||||
return await requestJson<T>(path, auth());
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
};
|
||||
|
||||
const getJsonWithStatus = async <T>(path: string, fallback: T): Promise<KbListResponse<T>> => {
|
||||
try {
|
||||
const data = await requestJson<T>(path, auth());
|
||||
return { ok: true, data };
|
||||
} catch (e) {
|
||||
const err = e as BusinessError;
|
||||
return {
|
||||
ok: false,
|
||||
data: fallback,
|
||||
error: kbErrorMessage(e, '知识库接口请求失败'),
|
||||
status: err.status,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
export const getKbGroups = async (): Promise<KbGroup[]> => {
|
||||
return getJson<KbGroup[]>('/api/kb/groups', []);
|
||||
};
|
||||
|
||||
export const getKbGroupFiles = async (groupId: number): Promise<KbDocumentItem[]> => {
|
||||
return getJson<KbDocumentItem[]>(`/api/kb/groups/${groupId}/files`, []);
|
||||
};
|
||||
|
||||
export const getKbGroupsSafe = async (): Promise<KbListResponse<KbGroup[]>> => {
|
||||
return getJsonWithStatus<KbGroup[]>('/api/kb/groups', []);
|
||||
};
|
||||
|
||||
export const getKbGroupFilesSafe = async (groupId: number): Promise<KbListResponse<KbDocumentItem[]>> => {
|
||||
return getJsonWithStatus<KbDocumentItem[]>(`/api/kb/groups/${groupId}/files`, []);
|
||||
};
|
||||
|
||||
export const createKbGroup = async (payload: {
|
||||
name: string;
|
||||
description?: string;
|
||||
}): Promise<{ ok: boolean; error?: string; group?: KbGroup }> => {
|
||||
try {
|
||||
const group = await requestJson<KbGroup>('/api/kb/groups', {
|
||||
method: 'POST',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
return { ok: true, group };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '创建知识库分组失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const getKbJobs = async (): Promise<KbJob[]> => {
|
||||
return getJson<KbJob[]>('/api/kb/jobs', []);
|
||||
};
|
||||
|
||||
export const getKbJobsSafe = async (): Promise<KbListResponse<KbJob[]>> => {
|
||||
return getJsonWithStatus<KbJob[]>('/api/kb/jobs', []);
|
||||
};
|
||||
|
||||
export const getKbDifySettings = async (): Promise<KbDifySettings | null> => {
|
||||
return getJson<KbDifySettings | null>('/api/kb/dify/settings', null);
|
||||
};
|
||||
|
||||
export const updateKbDifySettings = async (
|
||||
payload: Partial<KbDifySettings>
|
||||
): Promise<{ ok: boolean; error?: string; settings?: KbDifySettings }> => {
|
||||
try {
|
||||
const settings = await requestJson<KbDifySettings>('/api/kb/dify/settings', {
|
||||
method: 'PATCH',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
return { ok: true, settings };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '保存 Dify 设置失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const getKbDifyHealth = async (): Promise<KbDifyHealth | null> => {
|
||||
return getJson<KbDifyHealth | null>('/api/kb/dify/health', null);
|
||||
};
|
||||
|
||||
export const runKbJob = async (
|
||||
jobId: number | string
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob; run_result?: string }> => {
|
||||
try {
|
||||
const job = await requestJson<KbJob & { run_result?: string }>(`/api/kb/jobs/${jobId}/run`, {
|
||||
method: 'POST',
|
||||
...auth(),
|
||||
});
|
||||
return { ok: true, job, run_result: job.run_result };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '执行任务失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const createKbDocument = async (
|
||||
groupId: number,
|
||||
payload: { title: string; description?: string }
|
||||
): Promise<{ ok: boolean; error?: string; document?: KbDocumentItem }> => {
|
||||
try {
|
||||
const document = await requestJson<KbDocumentItem>(`/api/kb/groups/${groupId}/files`, {
|
||||
method: 'POST',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
return { ok: true, document };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '创建文档失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const updateKbDocument = async (
|
||||
documentId: number,
|
||||
payload: { title: string; description?: string; status?: string }
|
||||
): Promise<{ ok: boolean; error?: string; document?: KbDocumentItem }> => {
|
||||
try {
|
||||
const document = await requestJson<KbDocumentItem>(`/api/kb/documents/${documentId}`, {
|
||||
method: 'PATCH',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
return { ok: true, document };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '更新文档失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const deleteKbDocument = async (
|
||||
documentId: number
|
||||
): Promise<{ ok: boolean; error?: string }> => {
|
||||
try {
|
||||
await requestJson(`/api/kb/documents/${documentId}`, { method: 'DELETE', ...auth() });
|
||||
return { ok: true };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '删除文档失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const getKbDocumentVersions = async (
|
||||
documentId: number
|
||||
): Promise<KbDocumentVersionItem[]> => {
|
||||
return getJson<KbDocumentVersionItem[]>(`/api/kb/documents/${documentId}/versions`, []);
|
||||
};
|
||||
|
||||
export const getKbDocumentVersionSourceFile = async (
|
||||
versionId: number
|
||||
): Promise<{ ok: boolean; error?: string; blob?: Blob; filename?: string; contentType?: string }> => {
|
||||
try {
|
||||
const res = await fetch(`/api/kb/document-versions/${versionId}/source-file`, {
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
if (!res.ok) {
|
||||
let message = '读取原始文件失败';
|
||||
try {
|
||||
const data = await res.json();
|
||||
if (typeof data?.error === 'string' && data.error.trim()) message = data.error;
|
||||
else if (typeof data?.message === 'string' && data.message.trim()) message = data.message;
|
||||
} catch {
|
||||
// ignore non-json error body
|
||||
}
|
||||
return { ok: false, error: message };
|
||||
}
|
||||
const disposition = res.headers.get('content-disposition') || '';
|
||||
const filenameMatch = disposition.match(/filename\*=UTF-8''([^;]+)|filename="?([^"]+)"?/i);
|
||||
const filename = decodeURIComponent(filenameMatch?.[1] || filenameMatch?.[2] || '');
|
||||
return {
|
||||
ok: true,
|
||||
blob: await res.blob(),
|
||||
filename: filename || undefined,
|
||||
contentType: res.headers.get('content-type') || undefined,
|
||||
};
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
}
|
||||
};
|
||||
|
||||
export const getKbDocumentSyncRecords = async (
|
||||
documentId: number
|
||||
): Promise<KbSyncRecordItem[]> => {
|
||||
return getJson<KbSyncRecordItem[]>(`/api/kb/documents/${documentId}/sync-records`, []);
|
||||
};
|
||||
|
||||
export const getKbDocumentMarkdown = async (
|
||||
documentId: number
|
||||
): Promise<{ ok: boolean; error?: string; data?: KbDocumentMarkdown }> => {
|
||||
try {
|
||||
const data = await requestJson<KbDocumentMarkdown>(`/api/kb/documents/${documentId}/markdown`, auth());
|
||||
return { ok: true, data };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '读取清洗后的 Markdown 失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const updateKbDocumentMarkdown = async (
|
||||
documentId: number,
|
||||
payload: { content: string }
|
||||
): Promise<{ ok: boolean; error?: string; data?: KbDocumentMarkdown }> => {
|
||||
try {
|
||||
const data = await requestJson<KbDocumentMarkdown>(`/api/kb/documents/${documentId}/markdown`, {
|
||||
method: 'PATCH',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
return { ok: true, data };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '保存 Markdown 失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const uploadKbDocumentVersion = async (
|
||||
documentId: number,
|
||||
file: File
|
||||
): Promise<{ ok: boolean; error?: string; version?: KbDocumentVersionItem; clean_job?: KbJob | null; message?: string; status?: number }> => {
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
const payload = await requestJson<KbUploadVersionResponse>(`/api/kb/documents/${documentId}/upload`, {
|
||||
method: 'POST',
|
||||
...auth(),
|
||||
body: formData,
|
||||
});
|
||||
return { ok: true, version: payload.version, clean_job: payload.clean_job, message: payload.message };
|
||||
} catch (e) {
|
||||
const err = e as BusinessError;
|
||||
if (err.status === 413) {
|
||||
return {
|
||||
ok: false,
|
||||
error: '文件过大,超过当前上传限制,请联系管理员放宽限制后重试',
|
||||
status: 413,
|
||||
};
|
||||
}
|
||||
return { ok: false, error: kbErrorMessage(e, '上传文档版本失败'), status: err.status };
|
||||
}
|
||||
};
|
||||
|
||||
export const submitKbDocumentClean = async (
|
||||
documentId: number
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob | null; message?: string; status?: number }> => {
|
||||
try {
|
||||
const job = await requestJson<KbQueuedJobResponse>(`/api/kb/documents/${documentId}/clean`, {
|
||||
method: 'POST',
|
||||
...auth(),
|
||||
});
|
||||
return { ok: true, job, message: job.message || undefined };
|
||||
} catch (e) {
|
||||
const err = e as BusinessError;
|
||||
return { ok: false, error: kbErrorMessage(e, '提交清洗任务失败'), status: err.status };
|
||||
}
|
||||
};
|
||||
|
||||
export const createKbPathUploadJob = async (
|
||||
groupId: number,
|
||||
payload: {
|
||||
total_files: number;
|
||||
selected_paths: string[];
|
||||
files?: Array<{ relative_path: string; original_name: string }>;
|
||||
}
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob; status?: number }> => {
|
||||
try {
|
||||
const job = await requestJson<KbJob>(`/api/kb/groups/${groupId}/path-upload-jobs`, {
|
||||
method: 'POST',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
return { ok: true, job };
|
||||
} catch (e) {
|
||||
const err = e as BusinessError;
|
||||
return { ok: false, error: kbErrorMessage(e, '创建路径上传任务失败'), status: err.status };
|
||||
}
|
||||
};
|
||||
|
||||
export const uploadKbPathJobFile = async (
|
||||
jobId: number | string,
|
||||
file: File,
|
||||
relativePath: string,
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob; status?: number }> => {
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
formData.append('relative_path', relativePath);
|
||||
const job = await requestJson<KbJob>(`/api/kb/path-upload-jobs/${jobId}/files`, {
|
||||
method: 'POST',
|
||||
...auth(),
|
||||
body: formData,
|
||||
});
|
||||
return { ok: true, job };
|
||||
} catch (e) {
|
||||
const err = e as BusinessError;
|
||||
if (err.status === 413) {
|
||||
return {
|
||||
ok: false,
|
||||
error: '文件过大,超过当前上传限制,请联系管理员放宽限制后重试',
|
||||
status: 413,
|
||||
};
|
||||
}
|
||||
return { ok: false, error: kbErrorMessage(e, '上传路径文件失败'), status: err.status };
|
||||
}
|
||||
};
|
||||
|
||||
export const markKbPathJobFileFailed = async (
|
||||
jobId: number | string,
|
||||
payload: { relative_path: string; original_name?: string; error: string }
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob }> => {
|
||||
try {
|
||||
const job = await requestJson<KbJob>(`/api/kb/path-upload-jobs/${jobId}/files/fail`, {
|
||||
method: 'POST',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
return { ok: true, job };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '记录路径文件失败状态失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const finalizeKbPathUploadJob = async (
|
||||
jobId: number | string,
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob }> => {
|
||||
try {
|
||||
const job = await requestJson<KbQueuedJobResponse>(`/api/kb/path-upload-jobs/${jobId}/finalize`, {
|
||||
method: 'POST',
|
||||
...auth(),
|
||||
});
|
||||
return { ok: true, job };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '提交路径上传任务失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const retryFailedKbPathUploadJob = async (
|
||||
jobId: number | string,
|
||||
payload?: { relative_paths?: string[] },
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob; status?: number }> => {
|
||||
try {
|
||||
const job = await requestJson<KbJob>(`/api/kb/path-upload-jobs/${jobId}/retry-failed`, {
|
||||
method: 'POST',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload || {}),
|
||||
});
|
||||
return { ok: true, job };
|
||||
} catch (e) {
|
||||
const err = e as BusinessError;
|
||||
return { ok: false, error: kbErrorMessage(e, '重试失败文件失败'), status: err.status };
|
||||
}
|
||||
};
|
||||
|
||||
export const deleteKbPathJobFile = async (
|
||||
jobId: number | string,
|
||||
relativePath: string,
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob; document_deleted?: boolean }> => {
|
||||
try {
|
||||
const query = new URLSearchParams({ relative_path: relativePath });
|
||||
const result = await requestJson<{ ok: boolean; job: KbJob; document_deleted?: boolean }>(
|
||||
`/api/kb/path-upload-jobs/${jobId}/files?${query.toString()}`,
|
||||
{ method: 'DELETE', ...auth() }
|
||||
);
|
||||
return { ok: true, job: result.job, document_deleted: result.document_deleted };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '删除路径上传文件失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const syncKbDocumentToDify = async (
|
||||
documentId: number
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbQueuedJobResponse }> => {
|
||||
try {
|
||||
const job = await requestJson<KbQueuedJobResponse>(`/api/kb/documents/${documentId}/sync`, {
|
||||
method: 'POST',
|
||||
...auth(),
|
||||
});
|
||||
return { ok: true, job };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '同步到 Dify 失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const updateKbGroup = async (
|
||||
groupId: number,
|
||||
payload: { name: string; description?: string }
|
||||
): Promise<{ ok: boolean; error?: string; group?: KbGroup }> => {
|
||||
try {
|
||||
const group = await requestJson<KbGroup>(`/api/kb/groups/${groupId}`, {
|
||||
method: 'PATCH',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
return { ok: true, group };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '更新知识库分组失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const deleteKbGroup = async (
|
||||
groupId: number
|
||||
): Promise<{ ok: boolean; error?: string }> => {
|
||||
try {
|
||||
await requestJson(`/api/kb/groups/${groupId}`, { method: 'DELETE', ...auth() });
|
||||
return { ok: true };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '删除知识库分组失败') };
|
||||
}
|
||||
};
|
||||
+3
-3
@@ -1,12 +1,12 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* shared/components/kb/DifyHealthDialog.vue
|
||||
* 知识库 Dify 健康检查弹窗(KB 暂缓 redesign)。
|
||||
* features/kb/components/DifyHealthDialog.vue
|
||||
* 知识库 Dify 健康检查弹窗。
|
||||
*/
|
||||
|
||||
import { ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { getKbDifyHealth, type KbDifyHealth } from '@/api/kb';
|
||||
import { getKbDifyHealth, type KbDifyHealth } from '../api/kb.api';
|
||||
|
||||
const props = defineProps<{ open: boolean }>();
|
||||
const emit = defineEmits<{ close: []; error: [message: string] }>();
|
||||
+3
-3
@@ -1,12 +1,12 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* shared/components/kb/DifySettingsDialog.vue
|
||||
* 知识库 Dify 配置弹窗(KB 暂缓 redesign)。
|
||||
* features/kb/components/DifySettingsDialog.vue
|
||||
* 知识库 Dify 配置弹窗。
|
||||
*/
|
||||
|
||||
import { reactive, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { getKbDifySettings, updateKbDifySettings } from '@/api/kb';
|
||||
import { getKbDifySettings, updateKbDifySettings } from '../api/kb.api';
|
||||
|
||||
const props = defineProps<{ open: boolean }>();
|
||||
const emit = defineEmits<{ close: []; saved: [message: string]; error: [message: string] }>();
|
||||
+5
-4
@@ -1,7 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* shared/components/kb/KbAdminPanel.vue
|
||||
* 知识库管理面板(KB 暂缓 redesign)。
|
||||
* features/kb/components/KbAdminPanel.vue
|
||||
* 知识库配置面板(治理面:分组、Dify、任务队列)。
|
||||
*/
|
||||
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
@@ -11,6 +11,7 @@ import { Activity, FolderPlus, Pencil, Play, Settings, Trash2, Wrench, X } from
|
||||
import DifyHealthDialog from './DifyHealthDialog.vue';
|
||||
import DifySettingsDialog from './DifySettingsDialog.vue';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
import { WORKSPACE_PATHS } from '@/features/workspace/constants/routes';
|
||||
import {
|
||||
createKbGroup,
|
||||
deleteKbGroup,
|
||||
@@ -20,7 +21,7 @@ import {
|
||||
updateKbGroup,
|
||||
type KbGroup,
|
||||
type KbJob,
|
||||
} from '@/api/kb';
|
||||
} from '../api/kb.api';
|
||||
|
||||
const router = useRouter();
|
||||
const { t } = useI18n();
|
||||
@@ -196,7 +197,7 @@ defineExpose({ loadData });
|
||||
<button
|
||||
type="button"
|
||||
class="btn-primary inline-flex w-full items-center justify-center gap-2 px-5 py-2.5 text-sm sm:w-auto"
|
||||
@click="router.push('/kb/workspace')"
|
||||
@click="router.push(WORKSPACE_PATHS.knowledgeBase)"
|
||||
>
|
||||
<Wrench class="h-4 w-4 shrink-0" />
|
||||
<span class="whitespace-nowrap">{{ t('kbAdmin.goWorkspace') }}</span>
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* features/kb/composables/kb-workspace/kb-workspace.bridge.ts
|
||||
* 子 composable 间的延迟绑定:先建 pathUpload,再注入 data 加载函数,打破循环依赖。
|
||||
*/
|
||||
import type { LoadListOptions } from '../../types/kb-workspace.types';
|
||||
|
||||
export interface KbWorkspaceDataBridge {
|
||||
loadGroups: (options?: LoadListOptions) => Promise<void>;
|
||||
loadJobs: () => Promise<void>;
|
||||
loadDocuments: (groupId: number | null, options?: LoadListOptions) => Promise<void>;
|
||||
refreshWorkflowStatusOnly: () => Promise<void>;
|
||||
}
|
||||
|
||||
/** 创建可后续 Object.assign 填充的桥接对象 */
|
||||
export function createKbWorkspaceDataBridge(): KbWorkspaceDataBridge {
|
||||
const noop = async () => {};
|
||||
return {
|
||||
loadGroups: noop,
|
||||
loadJobs: noop,
|
||||
loadDocuments: noop,
|
||||
refreshWorkflowStatusOnly: noop,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
/**
|
||||
* features/kb/composables/kb-workspace/kb-workspace.state.ts
|
||||
* 作业面共享响应式状态:各子 composable 通过同一 state 读写,避免重复 ref。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { getStoredAuthUser } from '@/shared/utils/auth';
|
||||
import type {
|
||||
KbDocumentItem,
|
||||
KbJob,
|
||||
KbDocumentVersionItem,
|
||||
KbSyncRecordItem,
|
||||
KbGroup,
|
||||
} from '../../api/kb.api';
|
||||
import {
|
||||
PATH_UPLOAD_BATCH_SIZE,
|
||||
type PathUploadTaskItem,
|
||||
} from '../../types/kb-workspace.types';
|
||||
|
||||
export interface CreateKbWorkspaceStateOptions {
|
||||
embedded?: boolean;
|
||||
}
|
||||
|
||||
/** 作业面全部 ref 与删除确认辅助逻辑 */
|
||||
export function createKbWorkspaceState(options: CreateKbWorkspaceStateOptions = {}) {
|
||||
const embedded = options.embedded ?? false;
|
||||
const router = useRouter();
|
||||
const { t } = useI18n({ useScope: 'global' });
|
||||
|
||||
const isKbAdmin = computed(
|
||||
() => String(getStoredAuthUser()?.role || '').trim().toLowerCase() === 'admin',
|
||||
);
|
||||
|
||||
const isLoading = ref(true);
|
||||
const isDocumentsLoading = ref(false);
|
||||
const isSubmitting = ref(false);
|
||||
const isRecordLoading = ref(false);
|
||||
const groups = ref<KbGroup[]>([]);
|
||||
const documents = ref<KbDocumentItem[]>([]);
|
||||
const jobs = ref<KbJob[]>([]);
|
||||
const selectedGroupId = ref<number | null>(null);
|
||||
const selectedDocumentId = ref<number | null>(null);
|
||||
const activeUploadDocumentId = ref<number | null>(null);
|
||||
const syncingDocumentId = ref<number | null>(null);
|
||||
const selectedDocumentVersions = ref<KbDocumentVersionItem[]>([]);
|
||||
const selectedDocumentSyncRecords = ref<KbSyncRecordItem[]>([]);
|
||||
const feedback = ref('');
|
||||
const feedbackType = ref<'success' | 'error' | ''>('');
|
||||
const viewMode = ref<'group_overview' | 'group_detail'>(embedded ? 'group_overview' : 'group_detail');
|
||||
|
||||
const showMarkdownModal = ref(false);
|
||||
const showRecordModal = ref(false);
|
||||
const showSourceInfoModal = ref(false);
|
||||
const showFailureModal = ref(false);
|
||||
const showPathUploadModal = ref(false);
|
||||
const showPathUploadHistoryModal = ref(false);
|
||||
const showDeleteConfirmDialog = ref(false);
|
||||
const deleteConfirmMessage = ref('');
|
||||
let pendingDeleteAction: (() => Promise<void> | void) | null = null;
|
||||
const showPathUploadDetails = ref(false);
|
||||
const fileInputRef = ref<HTMLInputElement | null>(null);
|
||||
const pathUploadInputRef = ref<HTMLInputElement | null>(null);
|
||||
|
||||
const markdownDocumentId = ref<number | null>(null);
|
||||
const sourceInfoDocumentId = ref<number | null>(null);
|
||||
const markdownContent = ref('');
|
||||
const markdownKind = ref<'markdown' | 'preview'>('markdown');
|
||||
const markdownVersionLabel = ref('');
|
||||
const markdownError = ref('');
|
||||
const isMarkdownLoading = ref(false);
|
||||
const isMarkdownSaving = ref(false);
|
||||
const isSourceInfoLoading = ref(false);
|
||||
const openingSourceVersionId = ref<number | null>(null);
|
||||
|
||||
const failureModalType = ref<'upload' | 'clean' | 'sync' | null>(null);
|
||||
const failureModalPage = ref(1);
|
||||
const retryingFailureKey = ref('');
|
||||
|
||||
const documentStageFilter = ref<'all' | 'upload' | 'clean' | 'sync'>('all');
|
||||
const documentListPage = ref(1);
|
||||
const documentListPageSize = ref(20);
|
||||
const documentKeyword = ref('');
|
||||
const batchSubmitting = ref(false);
|
||||
const selectedDocumentIds = ref<number[]>([]);
|
||||
|
||||
const pathUploadDraftText = ref('');
|
||||
const pathUploadSelectedFiles = ref<Array<{ key: string; file: File; displayPath: string; rootLabel: string }>>([]);
|
||||
const isPathUploadStaging = ref(false);
|
||||
const pathUploadJobId = ref<number | string | null>(null);
|
||||
const selectedPathUploadHistoryJobId = ref<number | string | null>(null);
|
||||
const selectedPathUploadHistoryItemKeys = ref<string[]>([]);
|
||||
const retryingPathUploadKey = ref('');
|
||||
const deletingPathUploadBatch = ref(false);
|
||||
|
||||
const sourceInfoVersions = ref<KbDocumentVersionItem[]>([]);
|
||||
const pathUploadTask = ref<{
|
||||
running: boolean;
|
||||
groupId: number | null;
|
||||
total: number;
|
||||
success: number;
|
||||
failed: number;
|
||||
currentFile: string;
|
||||
batchSize: number;
|
||||
items: PathUploadTaskItem[];
|
||||
}>({
|
||||
running: false,
|
||||
groupId: null,
|
||||
total: 0,
|
||||
success: 0,
|
||||
failed: 0,
|
||||
currentFile: '',
|
||||
batchSize: PATH_UPLOAD_BATCH_SIZE,
|
||||
items: [],
|
||||
});
|
||||
|
||||
const openDeleteConfirmDialog = (
|
||||
message: string,
|
||||
onConfirm: () => Promise<void> | void,
|
||||
) => {
|
||||
deleteConfirmMessage.value = message;
|
||||
pendingDeleteAction = onConfirm;
|
||||
showDeleteConfirmDialog.value = true;
|
||||
};
|
||||
|
||||
const closeDeleteConfirmDialog = () => {
|
||||
showDeleteConfirmDialog.value = false;
|
||||
deleteConfirmMessage.value = '';
|
||||
pendingDeleteAction = null;
|
||||
};
|
||||
|
||||
const handleDeleteConfirm = async () => {
|
||||
if (!pendingDeleteAction) return;
|
||||
try {
|
||||
await pendingDeleteAction();
|
||||
} catch (err) {
|
||||
console.error('[deleteConfirm]', err);
|
||||
feedback.value = String(err) || '操作失败';
|
||||
feedbackType.value = 'error';
|
||||
}
|
||||
closeDeleteConfirmDialog();
|
||||
};
|
||||
|
||||
return {
|
||||
embedded,
|
||||
router,
|
||||
t,
|
||||
isKbAdmin,
|
||||
isLoading,
|
||||
isDocumentsLoading,
|
||||
isSubmitting,
|
||||
isRecordLoading,
|
||||
groups,
|
||||
documents,
|
||||
jobs,
|
||||
selectedGroupId,
|
||||
selectedDocumentId,
|
||||
activeUploadDocumentId,
|
||||
syncingDocumentId,
|
||||
selectedDocumentVersions,
|
||||
selectedDocumentSyncRecords,
|
||||
feedback,
|
||||
feedbackType,
|
||||
viewMode,
|
||||
showMarkdownModal,
|
||||
showRecordModal,
|
||||
showSourceInfoModal,
|
||||
showFailureModal,
|
||||
showPathUploadModal,
|
||||
showPathUploadHistoryModal,
|
||||
showDeleteConfirmDialog,
|
||||
deleteConfirmMessage,
|
||||
showPathUploadDetails,
|
||||
fileInputRef,
|
||||
pathUploadInputRef,
|
||||
markdownDocumentId,
|
||||
sourceInfoDocumentId,
|
||||
markdownContent,
|
||||
markdownKind,
|
||||
markdownVersionLabel,
|
||||
markdownError,
|
||||
isMarkdownLoading,
|
||||
isMarkdownSaving,
|
||||
isSourceInfoLoading,
|
||||
openingSourceVersionId,
|
||||
failureModalType,
|
||||
failureModalPage,
|
||||
retryingFailureKey,
|
||||
documentStageFilter,
|
||||
documentListPage,
|
||||
documentListPageSize,
|
||||
documentKeyword,
|
||||
batchSubmitting,
|
||||
selectedDocumentIds,
|
||||
pathUploadDraftText,
|
||||
pathUploadSelectedFiles,
|
||||
isPathUploadStaging,
|
||||
pathUploadJobId,
|
||||
selectedPathUploadHistoryJobId,
|
||||
selectedPathUploadHistoryItemKeys,
|
||||
retryingPathUploadKey,
|
||||
deletingPathUploadBatch,
|
||||
sourceInfoVersions,
|
||||
pathUploadTask,
|
||||
openDeleteConfirmDialog,
|
||||
closeDeleteConfirmDialog,
|
||||
handleDeleteConfirm,
|
||||
};
|
||||
}
|
||||
|
||||
export type KbWorkspaceState = ReturnType<typeof createKbWorkspaceState>;
|
||||
@@ -0,0 +1,408 @@
|
||||
/**
|
||||
* features/kb/composables/kb-workspace/useKbWorkspaceComputed.ts
|
||||
* 作业面派生状态:筛选分页、工作流徽标、失败列表、路径上传批次视图。
|
||||
*/
|
||||
import { computed } from 'vue';
|
||||
import type { KbDocumentItem } from '../../api/kb.api';
|
||||
import {
|
||||
FAILURE_PAGE_SIZE,
|
||||
type FailureModalItem,
|
||||
type PathUploadTaskItem,
|
||||
} from '../../types/kb-workspace.types';
|
||||
import {
|
||||
getDocumentDisplayDescription,
|
||||
getDocumentDisplayTitle,
|
||||
getStatusBadgeClass,
|
||||
} from '../../utils/kb-display.utils';
|
||||
import {
|
||||
getPathUploadJobItems,
|
||||
getPathUploadJobPriority,
|
||||
} from '../../utils/kb-path-upload.utils';
|
||||
import {
|
||||
buildGetLatestJobForDocument,
|
||||
getDocumentWorkflowState,
|
||||
getMarkdownUnavailableMessage,
|
||||
getWorkflowBadges,
|
||||
} from '../../utils/kb-workflow.utils';
|
||||
import type { KbWorkspaceState } from './kb-workspace.state';
|
||||
|
||||
export function useKbWorkspaceComputed(state: KbWorkspaceState) {
|
||||
const {
|
||||
documents,
|
||||
jobs,
|
||||
selectedGroupId,
|
||||
selectedDocumentId,
|
||||
sourceInfoDocumentId,
|
||||
markdownDocumentId,
|
||||
failureModalType,
|
||||
failureModalPage,
|
||||
documentStageFilter,
|
||||
documentListPage,
|
||||
documentListPageSize,
|
||||
documentKeyword,
|
||||
selectedDocumentIds,
|
||||
pathUploadTask,
|
||||
pathUploadSelectedFiles,
|
||||
isPathUploadStaging,
|
||||
selectedPathUploadHistoryJobId,
|
||||
selectedPathUploadHistoryItemKeys,
|
||||
groups,
|
||||
} = state;
|
||||
|
||||
const selectedDocument = computed(() =>
|
||||
documents.value.find((item) => item.id === selectedDocumentId.value) || null,
|
||||
);
|
||||
const sourceInfoDocument = computed(() =>
|
||||
documents.value.find((item) => item.id === sourceInfoDocumentId.value) || null,
|
||||
);
|
||||
const selectedGroup = computed(() =>
|
||||
groups.value.find((item) => item.id === selectedGroupId.value) || null,
|
||||
);
|
||||
const markdownModalTitle = computed(() => {
|
||||
const current = documents.value.find((item) => item.id === markdownDocumentId.value);
|
||||
return current ? getDocumentDisplayTitle(current) : 'Markdown 编辑器';
|
||||
});
|
||||
const activeGroupJobs = computed(() =>
|
||||
jobs.value.filter((item) => item.group_id === selectedGroupId.value),
|
||||
);
|
||||
|
||||
const getLatestJobForDocument = buildGetLatestJobForDocument(() => activeGroupJobs.value);
|
||||
const resolveWorkflowState = (doc: KbDocumentItem) =>
|
||||
getDocumentWorkflowState(doc, getLatestJobForDocument);
|
||||
const getWorkflowBadgesForDoc = (doc: KbDocumentItem) =>
|
||||
getWorkflowBadges(doc, getLatestJobForDocument);
|
||||
const getMarkdownUnavailableMessageForDoc = (
|
||||
doc: KbDocumentItem,
|
||||
fallback?: string | null,
|
||||
) => getMarkdownUnavailableMessage(doc, getLatestJobForDocument, fallback);
|
||||
|
||||
const groupSummaryItems = computed(() => {
|
||||
const docItems = documents.value;
|
||||
const groupName = selectedGroup.value?.name || '--';
|
||||
const workflowStates = docItems.map((item) => resolveWorkflowState(item));
|
||||
const pendingSyncCount = workflowStates.filter((item) => item.sync.code === 'pending').length;
|
||||
const uploadFailedCount = workflowStates.filter((item) => item.upload.code === 'failed').length;
|
||||
const cleanFailedCount = workflowStates.filter((item) => item.clean.code === 'failed').length;
|
||||
const syncFailedCount = workflowStates.filter((item) => item.sync.code === 'failed').length;
|
||||
|
||||
return [
|
||||
{ label: '当前知识库分组', value: groupName, wide: true, clickable: false },
|
||||
{ label: '文档数量', value: String(docItems.length), wide: false, clickable: false },
|
||||
{ label: '待同步数量', value: String(pendingSyncCount), wide: false, clickable: false },
|
||||
{ label: '上传失败数量', value: String(uploadFailedCount), wide: false, clickable: uploadFailedCount > 0, failureType: 'upload' as const },
|
||||
{ label: '清洗失败数量', value: String(cleanFailedCount), wide: false, clickable: cleanFailedCount > 0, failureType: 'clean' as const },
|
||||
{ label: '同步失败数量', value: String(syncFailedCount), wide: false, clickable: syncFailedCount > 0, failureType: 'sync' as const },
|
||||
];
|
||||
});
|
||||
|
||||
const matchesDocumentStageFilter = (
|
||||
doc: KbDocumentItem,
|
||||
filter: 'all' | 'upload' | 'clean' | 'sync',
|
||||
) => {
|
||||
const workflow = resolveWorkflowState(doc);
|
||||
if (filter === 'all') return true;
|
||||
if (filter === 'upload') {
|
||||
return workflow.upload.code !== 'success';
|
||||
}
|
||||
if (filter === 'clean') {
|
||||
return ['pending', 'running', 'failed'].includes(workflow.clean.code);
|
||||
}
|
||||
return ['pending', 'running', 'failed'].includes(workflow.sync.code);
|
||||
};
|
||||
|
||||
const matchesDocumentKeyword = (doc: KbDocumentItem, keyword: string) => {
|
||||
const normalizedKeyword = keyword.trim().toLowerCase();
|
||||
if (!normalizedKeyword) return true;
|
||||
const candidates = [
|
||||
getDocumentDisplayTitle(doc),
|
||||
getDocumentDisplayDescription(doc),
|
||||
doc.title,
|
||||
doc.description,
|
||||
doc.latest_version?.source_file_name,
|
||||
];
|
||||
return candidates.some((item) => String(item || '').toLowerCase().includes(normalizedKeyword));
|
||||
};
|
||||
|
||||
const stageFilterTabs = computed(() => {
|
||||
const filters: Array<{ key: 'all' | 'upload' | 'clean' | 'sync'; label: string }> = [
|
||||
{ key: 'all', label: '全部' },
|
||||
{ key: 'upload', label: '上传' },
|
||||
{ key: 'clean', label: '清洗' },
|
||||
{ key: 'sync', label: '同步' },
|
||||
];
|
||||
return filters.map((item) => ({
|
||||
...item,
|
||||
count: documents.value.filter((doc) =>
|
||||
matchesDocumentStageFilter(doc, item.key) && matchesDocumentKeyword(doc, documentKeyword.value),
|
||||
).length,
|
||||
}));
|
||||
});
|
||||
|
||||
const filteredDocuments = computed(() =>
|
||||
documents.value.filter((doc) =>
|
||||
matchesDocumentStageFilter(doc, documentStageFilter.value)
|
||||
&& matchesDocumentKeyword(doc, documentKeyword.value),
|
||||
),
|
||||
);
|
||||
|
||||
const filteredDocumentTotalPages = computed(() =>
|
||||
Math.max(1, Math.ceil(filteredDocuments.value.length / documentListPageSize.value)),
|
||||
);
|
||||
|
||||
const pagedFilteredDocuments = computed(() => {
|
||||
const start = (documentListPage.value - 1) * documentListPageSize.value;
|
||||
return filteredDocuments.value.slice(start, start + documentListPageSize.value);
|
||||
});
|
||||
|
||||
const pagedDocumentRange = computed(() => {
|
||||
if (filteredDocuments.value.length === 0) {
|
||||
return { start: 0, end: 0 };
|
||||
}
|
||||
const start = (documentListPage.value - 1) * documentListPageSize.value + 1;
|
||||
const end = Math.min(filteredDocuments.value.length, documentListPage.value * documentListPageSize.value);
|
||||
return { start, end };
|
||||
});
|
||||
|
||||
const selectedDocuments = computed(() =>
|
||||
documents.value.filter((doc) => selectedDocumentIds.value.includes(doc.id)),
|
||||
);
|
||||
|
||||
const selectedCleanableDocuments = computed(() =>
|
||||
selectedDocuments.value.filter((doc) => {
|
||||
if (!doc.latest_version) return false;
|
||||
const workflow = resolveWorkflowState(doc);
|
||||
return ['failed', 'pending', 'idle'].includes(workflow.clean.code);
|
||||
}),
|
||||
);
|
||||
|
||||
const isAllFilteredSelected = computed(() =>
|
||||
filteredDocuments.value.length > 0
|
||||
&& filteredDocuments.value.every((doc) => selectedDocumentIds.value.includes(doc.id)),
|
||||
);
|
||||
|
||||
const failureModalItems = computed<FailureModalItem[]>(() => {
|
||||
if (!failureModalType.value) return [];
|
||||
return documents.value.flatMap<FailureModalItem>((doc) => {
|
||||
const workflow = resolveWorkflowState(doc);
|
||||
if (failureModalType.value === 'clean' && workflow.clean.code === 'failed') {
|
||||
return [{
|
||||
key: `${doc.id}-clean`,
|
||||
document: doc,
|
||||
stage: 'clean',
|
||||
stageLabel: '清洗失败',
|
||||
errorMessage: workflow.clean.errorMessage || workflow.primaryError || '清洗失败',
|
||||
latestJob: getLatestJobForDocument(doc, 'clean'),
|
||||
updatedAt: doc.updated_at || doc.latest_version?.created_at || null,
|
||||
}];
|
||||
}
|
||||
if (failureModalType.value === 'sync' && workflow.sync.code === 'failed') {
|
||||
return [{
|
||||
key: `${doc.id}-sync`,
|
||||
document: doc,
|
||||
stage: 'sync',
|
||||
stageLabel: '同步失败',
|
||||
errorMessage: workflow.sync.errorMessage || workflow.primaryError || '同步失败',
|
||||
latestJob: getLatestJobForDocument(doc, 'sync_dify'),
|
||||
updatedAt: doc.updated_at || doc.latest_version?.created_at || null,
|
||||
}];
|
||||
}
|
||||
if (failureModalType.value === 'upload' && workflow.upload.code === 'failed') {
|
||||
return [{
|
||||
key: `${doc.id}-upload`,
|
||||
document: doc,
|
||||
stage: 'upload',
|
||||
stageLabel: '上传失败',
|
||||
errorMessage: workflow.upload.errorMessage || workflow.primaryError || '上传失败',
|
||||
latestJob: getLatestJobForDocument(doc, 'upload'),
|
||||
updatedAt: doc.updated_at || doc.latest_version?.created_at || null,
|
||||
}];
|
||||
}
|
||||
return [];
|
||||
});
|
||||
});
|
||||
|
||||
const failureModalTotalPages = computed(() =>
|
||||
Math.max(1, Math.ceil(failureModalItems.value.length / FAILURE_PAGE_SIZE)),
|
||||
);
|
||||
|
||||
const pagedFailureModalItems = computed(() => {
|
||||
const start = (failureModalPage.value - 1) * FAILURE_PAGE_SIZE;
|
||||
return failureModalItems.value.slice(start, start + FAILURE_PAGE_SIZE);
|
||||
});
|
||||
|
||||
const failureModalTitle = computed(() => {
|
||||
const map = {
|
||||
upload: '上传失败数据',
|
||||
clean: '清洗失败数据',
|
||||
sync: '同步失败数据',
|
||||
};
|
||||
return failureModalType.value ? map[failureModalType.value] : '失败数据';
|
||||
});
|
||||
|
||||
const documentById = computed(() =>
|
||||
new Map(documents.value.map((doc) => [doc.id, doc])),
|
||||
);
|
||||
|
||||
const latestPathUploadJob = computed(() => {
|
||||
const pathJobs = activeGroupJobs.value.filter((job) => job.job_type === 'path_upload');
|
||||
if (!pathJobs.length) return null;
|
||||
return [...pathJobs].sort((a, b) => {
|
||||
const priorityDiff = getPathUploadJobPriority(b) - getPathUploadJobPriority(a);
|
||||
if (priorityDiff !== 0) return priorityDiff;
|
||||
const aTime = new Date(a.created_at || a.finished_at || a.started_at || 0).getTime();
|
||||
const bTime = new Date(b.created_at || b.finished_at || b.started_at || 0).getTime();
|
||||
if (aTime !== bTime) return bTime - aTime;
|
||||
return Number(b.id) - Number(a.id);
|
||||
})[0] ?? null;
|
||||
});
|
||||
|
||||
const pathUploadHistoryJobs = computed(() =>
|
||||
[...activeGroupJobs.value]
|
||||
.filter((job) => job.job_type === 'path_upload')
|
||||
.sort((a, b) => {
|
||||
const aTime = new Date(a.created_at || a.finished_at || a.started_at || 0).getTime();
|
||||
const bTime = new Date(b.created_at || b.finished_at || b.started_at || 0).getTime();
|
||||
return bTime - aTime;
|
||||
}),
|
||||
);
|
||||
|
||||
const selectedPathUploadHistoryJob = computed(() =>
|
||||
pathUploadHistoryJobs.value.find((job) => String(job.id) === String(selectedPathUploadHistoryJobId.value))
|
||||
|| latestPathUploadJob.value
|
||||
|| null,
|
||||
);
|
||||
|
||||
const selectedPathUploadHistoryItems = computed(() =>
|
||||
getPathUploadJobItems(selectedPathUploadHistoryJob.value),
|
||||
);
|
||||
|
||||
const selectedPathUploadHistorySelectedItems = computed(() => {
|
||||
const selectedKeySet = new Set(selectedPathUploadHistoryItemKeys.value);
|
||||
return selectedPathUploadHistoryItems.value.filter((item) => selectedKeySet.has(item.key));
|
||||
});
|
||||
|
||||
const isAllPathUploadHistoryItemsSelected = computed(() =>
|
||||
selectedPathUploadHistoryItems.value.length > 0
|
||||
&& selectedPathUploadHistoryItems.value.every((item) => selectedPathUploadHistoryItemKeys.value.includes(item.key)),
|
||||
);
|
||||
|
||||
const getPathUploadItemDisplayState = (item: PathUploadTaskItem) => {
|
||||
if (item.status === 'failed') {
|
||||
return {
|
||||
normalized: 'failed',
|
||||
label: '失败',
|
||||
className: getStatusBadgeClass('failed'),
|
||||
};
|
||||
}
|
||||
|
||||
const doc = item.documentId ? documentById.value.get(item.documentId) || null : null;
|
||||
const latestStatus = String(doc?.latest_version?.status || doc?.status || '').toLowerCase();
|
||||
|
||||
if (latestStatus === 'processing') {
|
||||
return { normalized: 'processing', label: '清洗中', className: getStatusBadgeClass('processing') };
|
||||
}
|
||||
if (['cleaned', 'ready'].includes(latestStatus)) {
|
||||
return { normalized: latestStatus, label: '已清洗', className: getStatusBadgeClass(latestStatus) };
|
||||
}
|
||||
if (latestStatus === 'syncing') {
|
||||
return { normalized: 'syncing', label: '同步中', className: getStatusBadgeClass('processing') };
|
||||
}
|
||||
if (latestStatus === 'synced') {
|
||||
return { normalized: 'synced', label: '已同步', className: getStatusBadgeClass('synced') };
|
||||
}
|
||||
if (latestStatus === 'uploaded') {
|
||||
return { normalized: 'uploaded', label: '待清洗', className: getStatusBadgeClass('uploaded') };
|
||||
}
|
||||
if (item.status === 'success' || item.documentId) {
|
||||
return { normalized: 'success', label: '已上传', className: getStatusBadgeClass('success') };
|
||||
}
|
||||
if (item.status === 'uploading') {
|
||||
return { normalized: 'uploading', label: '上传中', className: getStatusBadgeClass('processing') };
|
||||
}
|
||||
return { normalized: 'queued', label: '待上传', className: getStatusBadgeClass('queued') };
|
||||
};
|
||||
|
||||
const pathUploadSummary = computed(() => {
|
||||
const task = pathUploadTask.value;
|
||||
const displayedStates = task.items.map((item) => getPathUploadItemDisplayState(item).normalized);
|
||||
const queued = displayedStates.filter((status) => status === 'queued').length;
|
||||
const uploading = displayedStates.filter((status) => status === 'uploading').length;
|
||||
const failed = displayedStates.filter((status) => status === 'failed').length;
|
||||
const uploaded = Math.max(task.total - queued - uploading - failed, 0);
|
||||
return {
|
||||
total: task.total,
|
||||
pending: queued + uploading,
|
||||
uploaded,
|
||||
failed,
|
||||
queued,
|
||||
uploading,
|
||||
};
|
||||
});
|
||||
|
||||
const recentPathUploadItems = computed(() =>
|
||||
[...pathUploadTask.value.items]
|
||||
.sort((a, b) => {
|
||||
const aTime = new Date(a.finishedAt || a.startedAt || 0).getTime();
|
||||
const bTime = new Date(b.finishedAt || b.startedAt || 0).getTime();
|
||||
return bTime - aTime;
|
||||
})
|
||||
.slice(0, 30),
|
||||
);
|
||||
|
||||
const pathUploadRunning = computed(() =>
|
||||
isPathUploadStaging.value
|
||||
|| ['draft', 'staging', 'queued', 'running'].includes(String(latestPathUploadJob.value?.status || '').toLowerCase()),
|
||||
);
|
||||
|
||||
const kbJobPollingActive = computed(() =>
|
||||
pathUploadRunning.value
|
||||
|| activeGroupJobs.value.some((job) =>
|
||||
['clean', 'sync_dify'].includes(String(job.job_type || '').toLowerCase())
|
||||
&& ['queued', 'running'].includes(String(job.status || '').toLowerCase()),
|
||||
),
|
||||
);
|
||||
|
||||
const selectedPathRoots = computed(() => {
|
||||
const roots = new Set(pathUploadSelectedFiles.value.map((item) => item.rootLabel));
|
||||
return Array.from(roots);
|
||||
});
|
||||
|
||||
return {
|
||||
selectedDocument,
|
||||
sourceInfoDocument,
|
||||
selectedGroup,
|
||||
markdownModalTitle,
|
||||
activeGroupJobs,
|
||||
resolveWorkflowState,
|
||||
getWorkflowBadgesForDoc,
|
||||
getMarkdownUnavailableMessageForDoc,
|
||||
groupSummaryItems,
|
||||
stageFilterTabs,
|
||||
filteredDocuments,
|
||||
filteredDocumentTotalPages,
|
||||
pagedFilteredDocuments,
|
||||
pagedDocumentRange,
|
||||
selectedDocuments,
|
||||
selectedCleanableDocuments,
|
||||
isAllFilteredSelected,
|
||||
failureModalItems,
|
||||
failureModalTotalPages,
|
||||
pagedFailureModalItems,
|
||||
failureModalTitle,
|
||||
documentById,
|
||||
latestPathUploadJob,
|
||||
pathUploadHistoryJobs,
|
||||
selectedPathUploadHistoryJob,
|
||||
selectedPathUploadHistoryItems,
|
||||
selectedPathUploadHistorySelectedItems,
|
||||
isAllPathUploadHistoryItemsSelected,
|
||||
getPathUploadItemDisplayState,
|
||||
pathUploadSummary,
|
||||
recentPathUploadItems,
|
||||
pathUploadRunning,
|
||||
kbJobPollingActive,
|
||||
selectedPathRoots,
|
||||
};
|
||||
}
|
||||
|
||||
export type KbWorkspaceComputed = ReturnType<typeof useKbWorkspaceComputed>;
|
||||
@@ -0,0 +1,239 @@
|
||||
/**
|
||||
* features/kb/composables/kb-workspace/useKbWorkspaceData.ts
|
||||
* 分组/文档/任务加载、静默轮询刷新与视图导航。
|
||||
*/
|
||||
import {
|
||||
getKbDocumentSyncRecords,
|
||||
getKbDocumentVersions,
|
||||
getKbGroupFilesSafe,
|
||||
getKbGroupsSafe,
|
||||
getKbJobsSafe,
|
||||
} from '../../api/kb.api';
|
||||
import type { LoadListOptions } from '../../types/kb-workspace.types';
|
||||
import { mergeStableItems } from '../../utils/kb-list.utils';
|
||||
import { getPathUploadJobSummary } from '../../utils/kb-path-upload.utils';
|
||||
import type { KbWorkspaceState } from './kb-workspace.state';
|
||||
import type { KbWorkspaceComputed } from './useKbWorkspaceComputed';
|
||||
import type { KbWorkspacePathUpload } from './useKbWorkspacePathUpload';
|
||||
|
||||
let autoRefreshTimer: number | null = null;
|
||||
|
||||
export function useKbWorkspaceData(
|
||||
state: KbWorkspaceState,
|
||||
computed: KbWorkspaceComputed,
|
||||
pathUpload: Pick<
|
||||
KbWorkspacePathUpload,
|
||||
'applyPathUploadJob' | 'startPathUploadPolling' | 'stopPathUploadPollTimer'
|
||||
>,
|
||||
) {
|
||||
const {
|
||||
isLoading,
|
||||
isDocumentsLoading,
|
||||
groups,
|
||||
documents,
|
||||
jobs,
|
||||
selectedGroupId,
|
||||
selectedDocumentId,
|
||||
selectedDocumentVersions,
|
||||
selectedDocumentSyncRecords,
|
||||
feedback,
|
||||
feedbackType,
|
||||
viewMode,
|
||||
showRecordModal,
|
||||
showSourceInfoModal,
|
||||
sourceInfoDocumentId,
|
||||
sourceInfoVersions,
|
||||
selectedDocumentIds,
|
||||
showPathUploadDetails,
|
||||
selectedPathUploadHistoryJobId,
|
||||
} = state;
|
||||
|
||||
const {
|
||||
kbJobPollingActive,
|
||||
latestPathUploadJob,
|
||||
pathUploadHistoryJobs,
|
||||
} = computed;
|
||||
|
||||
const { applyPathUploadJob, startPathUploadPolling, stopPathUploadPollTimer } = pathUpload;
|
||||
|
||||
const loadGroups = async (options: LoadListOptions = {}) => {
|
||||
if (!options.silent) {
|
||||
isLoading.value = true;
|
||||
}
|
||||
try {
|
||||
const result = await getKbGroupsSafe();
|
||||
if (!result.ok) {
|
||||
feedback.value = result.error || '加载知识库分组失败';
|
||||
feedbackType.value = 'error';
|
||||
return;
|
||||
}
|
||||
groups.value = options.silent ? mergeStableItems(groups.value, result.data) : result.data;
|
||||
const firstGroup = groups.value[0];
|
||||
if (!selectedGroupId.value && firstGroup && viewMode.value === 'group_detail') {
|
||||
selectedGroupId.value = firstGroup.id;
|
||||
}
|
||||
} finally {
|
||||
if (!options.silent) {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const loadDocuments = async (groupId: number | null, options: LoadListOptions = {}) => {
|
||||
if (!options.silent) {
|
||||
isDocumentsLoading.value = true;
|
||||
}
|
||||
try {
|
||||
if (!groupId) {
|
||||
documents.value = [];
|
||||
selectedDocumentId.value = null;
|
||||
selectedDocumentVersions.value = [];
|
||||
selectedDocumentSyncRecords.value = [];
|
||||
return;
|
||||
}
|
||||
const result = await getKbGroupFilesSafe(groupId);
|
||||
if (!result.ok) {
|
||||
feedback.value = result.error || '加载文档列表失败';
|
||||
feedbackType.value = 'error';
|
||||
return;
|
||||
}
|
||||
const nextDocuments = options.silent
|
||||
? mergeStableItems(documents.value, result.data)
|
||||
: result.data;
|
||||
documents.value = nextDocuments;
|
||||
if (selectedDocumentId.value && !documents.value.some((item) => item.id === selectedDocumentId.value)) {
|
||||
selectedDocumentId.value = null;
|
||||
selectedDocumentVersions.value = [];
|
||||
selectedDocumentSyncRecords.value = [];
|
||||
showRecordModal.value = false;
|
||||
}
|
||||
if (sourceInfoDocumentId.value && !documents.value.some((item) => item.id === sourceInfoDocumentId.value)) {
|
||||
sourceInfoDocumentId.value = null;
|
||||
sourceInfoVersions.value = [];
|
||||
showSourceInfoModal.value = false;
|
||||
}
|
||||
selectedDocumentIds.value = selectedDocumentIds.value.filter((id) =>
|
||||
documents.value.some((item) => item.id === id),
|
||||
);
|
||||
} finally {
|
||||
if (!options.silent) {
|
||||
isDocumentsLoading.value = false;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const loadJobs = async () => {
|
||||
const hadActiveKbJobs = kbJobPollingActive.value;
|
||||
const result = await getKbJobsSafe();
|
||||
if (!result.ok) {
|
||||
feedback.value = result.error || '加载任务列表失败';
|
||||
feedbackType.value = 'error';
|
||||
return;
|
||||
}
|
||||
jobs.value = result.data;
|
||||
applyPathUploadJob(latestPathUploadJob.value);
|
||||
if (latestPathUploadJob.value && getPathUploadJobSummary(latestPathUploadJob.value).failed > 0) {
|
||||
showPathUploadDetails.value = true;
|
||||
}
|
||||
if (
|
||||
selectedPathUploadHistoryJobId.value
|
||||
&& !pathUploadHistoryJobs.value.some((job) => String(job.id) === String(selectedPathUploadHistoryJobId.value))
|
||||
) {
|
||||
selectedPathUploadHistoryJobId.value = latestPathUploadJob.value?.id || null;
|
||||
}
|
||||
if (kbJobPollingActive.value) {
|
||||
startPathUploadPolling();
|
||||
} else {
|
||||
stopPathUploadPollTimer();
|
||||
if (hadActiveKbJobs && viewMode.value === 'group_detail') {
|
||||
await Promise.all([
|
||||
loadDocuments(selectedGroupId.value, { silent: true }),
|
||||
loadGroups({ silent: true }),
|
||||
]);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const refreshWorkflowStatusOnly = async () => {
|
||||
await Promise.all([
|
||||
loadJobs(),
|
||||
loadGroups({ silent: true }),
|
||||
loadDocuments(selectedGroupId.value, { silent: true }),
|
||||
]);
|
||||
};
|
||||
|
||||
const refreshCurrentView = async () => {
|
||||
if (viewMode.value === 'group_overview') {
|
||||
await Promise.all([loadGroups(), loadJobs()]);
|
||||
return;
|
||||
}
|
||||
await Promise.all([loadDocuments(selectedGroupId.value), loadJobs()]);
|
||||
};
|
||||
|
||||
const startAutoRefresh = () => {
|
||||
if (autoRefreshTimer !== null) {
|
||||
window.clearInterval(autoRefreshTimer);
|
||||
}
|
||||
autoRefreshTimer = window.setInterval(() => {
|
||||
void refreshCurrentView();
|
||||
}, 120000);
|
||||
};
|
||||
|
||||
const stopAutoRefresh = () => {
|
||||
if (autoRefreshTimer !== null) {
|
||||
window.clearInterval(autoRefreshTimer);
|
||||
autoRefreshTimer = null;
|
||||
}
|
||||
};
|
||||
|
||||
const openGroupDetail = async (groupId: number) => {
|
||||
selectedGroupId.value = groupId;
|
||||
viewMode.value = 'group_detail';
|
||||
feedback.value = '';
|
||||
feedbackType.value = '';
|
||||
await loadDocuments(groupId);
|
||||
};
|
||||
|
||||
const backToGroupOverview = () => {
|
||||
viewMode.value = 'group_overview';
|
||||
selectedGroupId.value = null;
|
||||
documents.value = [];
|
||||
selectedDocumentId.value = null;
|
||||
selectedDocumentVersions.value = [];
|
||||
selectedDocumentSyncRecords.value = [];
|
||||
};
|
||||
|
||||
const loadDocumentVersions = async (documentId: number | null) => {
|
||||
if (!documentId) {
|
||||
selectedDocumentVersions.value = [];
|
||||
selectedDocumentSyncRecords.value = [];
|
||||
return;
|
||||
}
|
||||
selectedDocumentVersions.value = await getKbDocumentVersions(documentId);
|
||||
selectedDocumentSyncRecords.value = await getKbDocumentSyncRecords(documentId);
|
||||
};
|
||||
|
||||
const loadSourceInfoVersions = async (documentId: number | null) => {
|
||||
if (!documentId) {
|
||||
sourceInfoVersions.value = [];
|
||||
return;
|
||||
}
|
||||
sourceInfoVersions.value = await getKbDocumentVersions(documentId);
|
||||
};
|
||||
|
||||
return {
|
||||
loadGroups,
|
||||
loadJobs,
|
||||
loadDocuments,
|
||||
refreshWorkflowStatusOnly,
|
||||
refreshCurrentView,
|
||||
startAutoRefresh,
|
||||
stopAutoRefresh,
|
||||
openGroupDetail,
|
||||
backToGroupOverview,
|
||||
loadDocumentVersions,
|
||||
loadSourceInfoVersions,
|
||||
};
|
||||
}
|
||||
|
||||
export type KbWorkspaceData = ReturnType<typeof useKbWorkspaceData>;
|
||||
@@ -0,0 +1,389 @@
|
||||
/**
|
||||
* features/kb/composables/kb-workspace/useKbWorkspaceDocuments.ts
|
||||
* 文档列表选择、上传、清洗、同步、删除与失败重试。
|
||||
*/
|
||||
import type { KbDocumentItem } from '../../api/kb.api';
|
||||
import {
|
||||
createKbDocument,
|
||||
deleteKbDocument,
|
||||
submitKbDocumentClean,
|
||||
syncKbDocumentToDify,
|
||||
uploadKbDocumentVersion,
|
||||
} from '../../api/kb.api';
|
||||
import type { FailureModalItem } from '../../types/kb-workspace.types';
|
||||
import {
|
||||
getDocumentDisplayTitle,
|
||||
normalizeDuplicateDocumentError,
|
||||
} from '../../utils/kb-display.utils';
|
||||
import type { KbWorkspaceState } from './kb-workspace.state';
|
||||
import type { KbWorkspaceComputed } from './useKbWorkspaceComputed';
|
||||
import type { KbWorkspaceData } from './useKbWorkspaceData';
|
||||
import type { KbWorkspacePathUpload } from './useKbWorkspacePathUpload';
|
||||
|
||||
export function useKbWorkspaceDocuments(
|
||||
state: KbWorkspaceState,
|
||||
computed: KbWorkspaceComputed,
|
||||
data: Pick<
|
||||
KbWorkspaceData,
|
||||
'loadGroups' | 'loadJobs' | 'loadDocuments' | 'refreshWorkflowStatusOnly' | 'loadDocumentVersions'
|
||||
>,
|
||||
pathUpload: Pick<KbWorkspacePathUpload, 'startPathUploadPolling'>,
|
||||
) {
|
||||
const {
|
||||
feedback,
|
||||
feedbackType,
|
||||
selectedGroupId,
|
||||
selectedDocumentId,
|
||||
selectedDocumentIds,
|
||||
selectedDocumentVersions,
|
||||
selectedDocumentSyncRecords,
|
||||
batchSubmitting,
|
||||
isSubmitting,
|
||||
activeUploadDocumentId,
|
||||
syncingDocumentId,
|
||||
fileInputRef,
|
||||
showRecordModal,
|
||||
failureModalPage,
|
||||
retryingFailureKey,
|
||||
openDeleteConfirmDialog,
|
||||
} = state;
|
||||
|
||||
const {
|
||||
filteredDocuments,
|
||||
selectedDocuments,
|
||||
selectedCleanableDocuments,
|
||||
isAllFilteredSelected,
|
||||
failureModalTotalPages,
|
||||
} = computed;
|
||||
|
||||
const {
|
||||
loadGroups,
|
||||
loadJobs,
|
||||
loadDocuments,
|
||||
refreshWorkflowStatusOnly,
|
||||
loadDocumentVersions,
|
||||
} = data;
|
||||
|
||||
const { startPathUploadPolling } = pathUpload;
|
||||
|
||||
const toggleDocumentSelection = (documentId: number) => {
|
||||
if (selectedDocumentIds.value.includes(documentId)) {
|
||||
selectedDocumentIds.value = selectedDocumentIds.value.filter((id) => id !== documentId);
|
||||
return;
|
||||
}
|
||||
selectedDocumentIds.value = [...selectedDocumentIds.value, documentId];
|
||||
};
|
||||
|
||||
const toggleSelectAllFiltered = () => {
|
||||
if (isAllFilteredSelected.value) {
|
||||
const filteredIds = new Set(filteredDocuments.value.map((doc) => doc.id));
|
||||
selectedDocumentIds.value = selectedDocumentIds.value.filter((id) => !filteredIds.has(id));
|
||||
return;
|
||||
}
|
||||
const merged = new Set(selectedDocumentIds.value);
|
||||
filteredDocuments.value.forEach((doc) => merged.add(doc.id));
|
||||
selectedDocumentIds.value = Array.from(merged);
|
||||
};
|
||||
|
||||
const handleDeleteDocument = async (doc: KbDocumentItem) => {
|
||||
openDeleteConfirmDialog(`确认删除文档「${getDocumentDisplayTitle(doc)}」吗?`, async () => {
|
||||
const result = await deleteKbDocument(doc.id);
|
||||
if (!result.ok) {
|
||||
feedback.value = result.error || '删除文档失败';
|
||||
feedbackType.value = 'error';
|
||||
return;
|
||||
}
|
||||
|
||||
if (selectedDocumentId.value === doc.id) {
|
||||
selectedDocumentId.value = null;
|
||||
showRecordModal.value = false;
|
||||
}
|
||||
feedback.value = '文档已删除';
|
||||
feedbackType.value = 'success';
|
||||
await Promise.all([loadGroups(), loadDocuments(selectedGroupId.value), loadJobs()]);
|
||||
selectedDocumentVersions.value = [];
|
||||
selectedDocumentSyncRecords.value = [];
|
||||
});
|
||||
};
|
||||
|
||||
const handleBatchSync = async () => {
|
||||
if (!selectedDocuments.value.length) {
|
||||
feedback.value = '请先选择要批量同步的文档';
|
||||
feedbackType.value = 'error';
|
||||
return;
|
||||
}
|
||||
batchSubmitting.value = true;
|
||||
try {
|
||||
const results = await Promise.all(
|
||||
selectedDocuments.value.map(async (doc) => ({
|
||||
doc,
|
||||
result: await syncKbDocumentToDify(doc.id),
|
||||
})),
|
||||
);
|
||||
const successCount = results.filter(({ result }) => result.ok).length;
|
||||
const failResults = results.filter(({ result }) => !result.ok);
|
||||
const failCount = failResults.length;
|
||||
const errors = failResults.map(({ doc, result }) => `${getDocumentDisplayTitle(doc)}: ${result.error || '同步失败'}`);
|
||||
feedback.value = failCount
|
||||
? `批量同步任务已提交:成功 ${successCount} 条,失败 ${failCount} 条。${errors[0] || ''}`
|
||||
: `批量同步任务已提交:共成功 ${successCount} 条`;
|
||||
feedbackType.value = failCount ? 'error' : 'success';
|
||||
if (successCount > 0) {
|
||||
startPathUploadPolling();
|
||||
}
|
||||
await refreshWorkflowStatusOnly();
|
||||
} finally {
|
||||
batchSubmitting.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const handleBatchClean = async () => {
|
||||
if (!selectedDocuments.value.length) {
|
||||
feedback.value = '请先选择要清洗的文档';
|
||||
feedbackType.value = 'error';
|
||||
return;
|
||||
}
|
||||
if (!selectedCleanableDocuments.value.length) {
|
||||
feedback.value = '当前所选文档没有可重新清洗的项';
|
||||
feedbackType.value = 'error';
|
||||
return;
|
||||
}
|
||||
batchSubmitting.value = true;
|
||||
try {
|
||||
const results = await Promise.all(
|
||||
selectedCleanableDocuments.value.map(async (doc) => ({
|
||||
doc,
|
||||
result: await submitKbDocumentClean(doc.id),
|
||||
})),
|
||||
);
|
||||
const successCount = results.filter(({ result }) => result.ok).length;
|
||||
const failResults = results.filter(({ result }) => !result.ok);
|
||||
const failCount = failResults.length;
|
||||
const errors = failResults.map(({ doc, result }) => `${getDocumentDisplayTitle(doc)}: ${result.error || '提交清洗失败'}`);
|
||||
feedback.value = failCount
|
||||
? `批量清洗任务已提交:成功 ${successCount} 条,失败 ${failCount} 条。${errors[0] || ''}`
|
||||
: `批量清洗任务已提交:共成功 ${successCount} 条`;
|
||||
feedbackType.value = failCount ? 'error' : 'success';
|
||||
if (successCount > 0) {
|
||||
startPathUploadPolling();
|
||||
}
|
||||
await refreshWorkflowStatusOnly();
|
||||
} finally {
|
||||
batchSubmitting.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const handleBatchDelete = async () => {
|
||||
if (!selectedDocuments.value.length) {
|
||||
feedback.value = '请先选择要批量删除的文档';
|
||||
feedbackType.value = 'error';
|
||||
return;
|
||||
}
|
||||
openDeleteConfirmDialog(
|
||||
`确认批量删除已选中的 ${selectedDocuments.value.length} 条文档吗?会同步删除 Dify 对应文档。`,
|
||||
async () => {
|
||||
batchSubmitting.value = true;
|
||||
let successCount = 0;
|
||||
let failCount = 0;
|
||||
const errors: string[] = [];
|
||||
try {
|
||||
for (const doc of selectedDocuments.value) {
|
||||
const result = await deleteKbDocument(doc.id);
|
||||
if (result.ok) {
|
||||
successCount += 1;
|
||||
} else {
|
||||
failCount += 1;
|
||||
errors.push(`${getDocumentDisplayTitle(doc)}: ${result.error || '删除失败'}`);
|
||||
}
|
||||
}
|
||||
feedback.value = failCount
|
||||
? `批量删除完成:成功 ${successCount} 条,失败 ${failCount} 条。${errors[0] || ''}`
|
||||
: `批量删除完成:共成功 ${successCount} 条`;
|
||||
feedbackType.value = failCount ? 'error' : 'success';
|
||||
selectedDocumentIds.value = [];
|
||||
await Promise.all([loadGroups(), loadDocuments(selectedGroupId.value), loadJobs()]);
|
||||
} finally {
|
||||
batchSubmitting.value = false;
|
||||
}
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const triggerUploadForDocument = (documentId: number) => {
|
||||
activeUploadDocumentId.value = documentId;
|
||||
fileInputRef.value?.click();
|
||||
};
|
||||
|
||||
const handleRetryFailedItem = async (
|
||||
item: FailureModalItem,
|
||||
action: 'submit' | 'clean' | 'sync',
|
||||
) => {
|
||||
const actionKey = `${item.key}-${action}`;
|
||||
retryingFailureKey.value = actionKey;
|
||||
try {
|
||||
if (action === 'submit') {
|
||||
triggerUploadForDocument(item.document.id);
|
||||
feedback.value = `请重新为「${getDocumentDisplayTitle(item.document)}」选择文件后提交`;
|
||||
feedbackType.value = 'success';
|
||||
return;
|
||||
}
|
||||
if (action === 'clean') {
|
||||
const result = await submitKbDocumentClean(item.document.id);
|
||||
if (!result.ok) {
|
||||
feedback.value = result.error || '重新清洗失败';
|
||||
feedbackType.value = 'error';
|
||||
return;
|
||||
}
|
||||
feedback.value = result.message || `已重新提交清洗:${getDocumentDisplayTitle(item.document)}`;
|
||||
feedbackType.value = 'success';
|
||||
startPathUploadPolling();
|
||||
} else {
|
||||
const result = await syncKbDocumentToDify(item.document.id);
|
||||
if (!result.ok) {
|
||||
feedback.value = result.error ? `重新同步失败:${result.error}` : '重新同步失败';
|
||||
feedbackType.value = 'error';
|
||||
return;
|
||||
}
|
||||
feedback.value = result.job?.message || `已重新提交同步:${getDocumentDisplayTitle(item.document)}`;
|
||||
feedbackType.value = 'success';
|
||||
startPathUploadPolling();
|
||||
}
|
||||
await refreshWorkflowStatusOnly();
|
||||
if (selectedDocumentId.value) {
|
||||
await loadDocumentVersions(selectedDocumentId.value);
|
||||
}
|
||||
if (failureModalPage.value > failureModalTotalPages.value) {
|
||||
failureModalPage.value = failureModalTotalPages.value;
|
||||
}
|
||||
} finally {
|
||||
retryingFailureKey.value = '';
|
||||
}
|
||||
};
|
||||
|
||||
const handleFileSelected = async (event: Event) => {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const files = input.files;
|
||||
if (!files || files.length === 0 || !selectedGroupId.value) {
|
||||
input.value = '';
|
||||
activeUploadDocumentId.value = null;
|
||||
return;
|
||||
}
|
||||
|
||||
isSubmitting.value = true;
|
||||
feedback.value = '开始处理文件...';
|
||||
feedbackType.value = 'success';
|
||||
|
||||
if (activeUploadDocumentId.value) {
|
||||
const file = files[0];
|
||||
if (!file) return;
|
||||
const result = await uploadKbDocumentVersion(activeUploadDocumentId.value, file);
|
||||
if (!result.ok) {
|
||||
feedback.value = result.error || '文件上传失败';
|
||||
feedbackType.value = 'error';
|
||||
} else {
|
||||
feedback.value = result.message || `版本文件「${file.name}」上传成功,清洗已排队`;
|
||||
feedbackType.value = 'success';
|
||||
startPathUploadPolling();
|
||||
}
|
||||
selectedDocumentId.value = activeUploadDocumentId.value;
|
||||
activeUploadDocumentId.value = null;
|
||||
} else {
|
||||
let successCount = 0;
|
||||
let failCount = 0;
|
||||
const errors: string[] = [];
|
||||
const fileArray = Array.from(files);
|
||||
|
||||
for (let i = 0; i < fileArray.length; i++) {
|
||||
const file = fileArray[i];
|
||||
if (!file) continue;
|
||||
feedback.value = `正在上传 ${i + 1}/${fileArray.length}: ${file.name}`;
|
||||
|
||||
const createResult = await createKbDocument(selectedGroupId.value, {
|
||||
title: file.name,
|
||||
description: file.name,
|
||||
});
|
||||
|
||||
if (!createResult.ok || !createResult.document) {
|
||||
failCount++;
|
||||
errors.push(`${file.name}: ${normalizeDuplicateDocumentError(createResult.error || '创建文档失败')}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const uploadResult = await uploadKbDocumentVersion(createResult.document.id, file);
|
||||
if (!uploadResult.ok) {
|
||||
failCount++;
|
||||
const uploadError = uploadResult.error || '上传文档版本失败';
|
||||
errors.push(`${file.name}: ${uploadError}`);
|
||||
const cleanupResult = await deleteKbDocument(createResult.document.id);
|
||||
if (!cleanupResult.ok) {
|
||||
errors.push(`${file.name}: 上传失败后未能自动清理空文档(${cleanupResult.error || '删除失败'})`);
|
||||
}
|
||||
} else {
|
||||
successCount++;
|
||||
}
|
||||
}
|
||||
|
||||
if (failCount > 0) {
|
||||
feedback.value = `上传完成:成功 ${successCount} 个,失败 ${failCount} 个。${errors[0] || ''}`;
|
||||
feedbackType.value = successCount > 0 ? 'success' : 'error';
|
||||
} else {
|
||||
feedback.value = `成功上传 ${successCount} 个文件,清洗任务已排队`;
|
||||
feedbackType.value = 'success';
|
||||
}
|
||||
if (successCount > 0) {
|
||||
startPathUploadPolling();
|
||||
}
|
||||
}
|
||||
|
||||
input.value = '';
|
||||
isSubmitting.value = false;
|
||||
|
||||
await refreshWorkflowStatusOnly();
|
||||
if (selectedDocumentId.value) {
|
||||
await loadDocumentVersions(selectedDocumentId.value);
|
||||
}
|
||||
};
|
||||
|
||||
const triggerMultiUpload = () => {
|
||||
activeUploadDocumentId.value = null;
|
||||
fileInputRef.value?.click();
|
||||
};
|
||||
|
||||
const handleSyncDocument = async (documentId: number) => {
|
||||
syncingDocumentId.value = documentId;
|
||||
const result = await syncKbDocumentToDify(documentId);
|
||||
syncingDocumentId.value = null;
|
||||
|
||||
if (!result.ok) {
|
||||
feedback.value = result.error ? `同步到 Dify 失败:${result.error}` : '同步到 Dify 失败';
|
||||
feedbackType.value = 'error';
|
||||
await loadDocuments(selectedGroupId.value, { silent: true });
|
||||
await loadJobs();
|
||||
return;
|
||||
}
|
||||
|
||||
feedback.value = result.job?.message || '同步任务已提交,等待后台处理';
|
||||
feedbackType.value = 'success';
|
||||
startPathUploadPolling();
|
||||
await loadDocuments(selectedGroupId.value, { silent: true });
|
||||
await loadJobs();
|
||||
selectedDocumentId.value = documentId;
|
||||
await loadDocumentVersions(documentId);
|
||||
};
|
||||
|
||||
return {
|
||||
toggleDocumentSelection,
|
||||
toggleSelectAllFiltered,
|
||||
handleDeleteDocument,
|
||||
handleBatchSync,
|
||||
handleBatchClean,
|
||||
handleBatchDelete,
|
||||
handleRetryFailedItem,
|
||||
triggerUploadForDocument,
|
||||
handleFileSelected,
|
||||
triggerMultiUpload,
|
||||
handleSyncDocument,
|
||||
};
|
||||
}
|
||||
|
||||
export type KbWorkspaceDocuments = ReturnType<typeof useKbWorkspaceDocuments>;
|
||||
@@ -0,0 +1,188 @@
|
||||
/**
|
||||
* features/kb/composables/kb-workspace/useKbWorkspaceModals.ts
|
||||
* 记录/来源/Markdown/失败弹窗与原始文件预览。
|
||||
*/
|
||||
import type { KbDocumentItem, KbDocumentMarkdown, KbDocumentVersionItem } from '../../api/kb.api';
|
||||
import {
|
||||
getKbDocumentMarkdown,
|
||||
getKbDocumentVersionSourceFile,
|
||||
updateKbDocumentMarkdown,
|
||||
} from '../../api/kb.api';
|
||||
import type { KbWorkspaceState } from './kb-workspace.state';
|
||||
import type { KbWorkspaceComputed } from './useKbWorkspaceComputed';
|
||||
import type { KbWorkspaceData } from './useKbWorkspaceData';
|
||||
|
||||
export function useKbWorkspaceModals(
|
||||
state: KbWorkspaceState,
|
||||
computed: KbWorkspaceComputed,
|
||||
data: Pick<
|
||||
KbWorkspaceData,
|
||||
'loadDocumentVersions' | 'loadSourceInfoVersions' | 'loadDocuments' | 'loadJobs'
|
||||
>,
|
||||
) {
|
||||
const {
|
||||
selectedDocumentId,
|
||||
isRecordLoading,
|
||||
showRecordModal,
|
||||
showSourceInfoModal,
|
||||
showFailureModal,
|
||||
sourceInfoDocumentId,
|
||||
isSourceInfoLoading,
|
||||
openingSourceVersionId,
|
||||
failureModalType,
|
||||
failureModalPage,
|
||||
retryingFailureKey,
|
||||
feedback,
|
||||
feedbackType,
|
||||
showMarkdownModal,
|
||||
markdownDocumentId,
|
||||
markdownContent,
|
||||
markdownKind,
|
||||
markdownVersionLabel,
|
||||
markdownError,
|
||||
isMarkdownLoading,
|
||||
isMarkdownSaving,
|
||||
documents,
|
||||
selectedGroupId,
|
||||
} = state;
|
||||
|
||||
const { getMarkdownUnavailableMessageForDoc } = computed;
|
||||
const { loadDocumentVersions, loadSourceInfoVersions, loadDocuments, loadJobs } = data;
|
||||
|
||||
const openDocumentDetail = async (documentId: number) => {
|
||||
selectedDocumentId.value = documentId;
|
||||
isRecordLoading.value = true;
|
||||
showRecordModal.value = true;
|
||||
await loadDocumentVersions(documentId);
|
||||
isRecordLoading.value = false;
|
||||
};
|
||||
|
||||
const closeDocumentDetail = () => {
|
||||
showRecordModal.value = false;
|
||||
};
|
||||
|
||||
const openSourceInfo = async (doc: KbDocumentItem) => {
|
||||
sourceInfoDocumentId.value = doc.id;
|
||||
isSourceInfoLoading.value = true;
|
||||
showSourceInfoModal.value = true;
|
||||
await loadSourceInfoVersions(doc.id);
|
||||
isSourceInfoLoading.value = false;
|
||||
};
|
||||
|
||||
const closeSourceInfoModal = () => {
|
||||
showSourceInfoModal.value = false;
|
||||
};
|
||||
|
||||
const openOriginalSourceFile = async (version: KbDocumentVersionItem) => {
|
||||
openingSourceVersionId.value = version.id;
|
||||
const result = await getKbDocumentVersionSourceFile(version.id);
|
||||
openingSourceVersionId.value = null;
|
||||
if (!result.ok || !result.blob) {
|
||||
feedback.value = result.error || '读取原始文件失败';
|
||||
feedbackType.value = 'error';
|
||||
return;
|
||||
}
|
||||
|
||||
const objectUrl = window.URL.createObjectURL(result.blob);
|
||||
const opened = window.open(objectUrl, '_blank', 'noopener,noreferrer');
|
||||
if (!opened) {
|
||||
const link = window.document.createElement('a');
|
||||
link.href = objectUrl;
|
||||
link.download = result.filename || version.source_file_name || `source-${version.id}`;
|
||||
link.click();
|
||||
}
|
||||
window.setTimeout(() => window.URL.revokeObjectURL(objectUrl), 60_000);
|
||||
};
|
||||
|
||||
const openFailureModal = (type: 'upload' | 'clean' | 'sync') => {
|
||||
failureModalType.value = type;
|
||||
failureModalPage.value = 1;
|
||||
showFailureModal.value = true;
|
||||
};
|
||||
|
||||
const closeFailureModal = () => {
|
||||
showFailureModal.value = false;
|
||||
failureModalType.value = null;
|
||||
failureModalPage.value = 1;
|
||||
retryingFailureKey.value = '';
|
||||
};
|
||||
|
||||
const applyMarkdownPayload = (payload: KbDocumentMarkdown) => {
|
||||
markdownContent.value = payload.content || '';
|
||||
markdownKind.value = payload.kind;
|
||||
markdownVersionLabel.value = payload.version
|
||||
? `v${payload.version.version_no} · ${payload.version.source_file_name}`
|
||||
: '暂无版本';
|
||||
};
|
||||
|
||||
const openMarkdownEditor = async (doc: KbDocumentItem) => {
|
||||
showMarkdownModal.value = true;
|
||||
markdownDocumentId.value = doc.id;
|
||||
markdownContent.value = '';
|
||||
markdownKind.value = 'markdown';
|
||||
markdownVersionLabel.value = '';
|
||||
markdownError.value = '';
|
||||
isMarkdownLoading.value = true;
|
||||
|
||||
const result = await getKbDocumentMarkdown(doc.id);
|
||||
isMarkdownLoading.value = false;
|
||||
if (!result.ok || !result.data) {
|
||||
markdownError.value = getMarkdownUnavailableMessageForDoc(doc, result.error || '读取清洗后的 Markdown 失败');
|
||||
return;
|
||||
}
|
||||
applyMarkdownPayload(result.data);
|
||||
};
|
||||
|
||||
const closeMarkdownModal = () => {
|
||||
if (isMarkdownSaving.value) return;
|
||||
showMarkdownModal.value = false;
|
||||
markdownDocumentId.value = null;
|
||||
markdownContent.value = '';
|
||||
markdownVersionLabel.value = '';
|
||||
markdownError.value = '';
|
||||
isMarkdownLoading.value = false;
|
||||
};
|
||||
|
||||
const handleSaveMarkdown = async () => {
|
||||
if (!markdownDocumentId.value) return;
|
||||
|
||||
isMarkdownSaving.value = true;
|
||||
markdownError.value = '';
|
||||
const result = await updateKbDocumentMarkdown(markdownDocumentId.value, {
|
||||
content: markdownContent.value,
|
||||
});
|
||||
isMarkdownSaving.value = false;
|
||||
|
||||
if (!result.ok || !result.data) {
|
||||
const currentDoc = documents.value.find((item) => item.id === markdownDocumentId.value) || null;
|
||||
markdownError.value = currentDoc
|
||||
? getMarkdownUnavailableMessageForDoc(currentDoc, result.error || '保存 Markdown 失败')
|
||||
: (result.error || '保存 Markdown 失败');
|
||||
return;
|
||||
}
|
||||
|
||||
applyMarkdownPayload(result.data);
|
||||
feedback.value = '清洗后的 Markdown 已保存';
|
||||
feedbackType.value = 'success';
|
||||
await loadDocuments(selectedGroupId.value);
|
||||
await loadJobs();
|
||||
selectedDocumentId.value = markdownDocumentId.value;
|
||||
await loadDocumentVersions(markdownDocumentId.value);
|
||||
closeMarkdownModal();
|
||||
};
|
||||
|
||||
return {
|
||||
openDocumentDetail,
|
||||
closeDocumentDetail,
|
||||
openSourceInfo,
|
||||
closeSourceInfoModal,
|
||||
openOriginalSourceFile,
|
||||
openFailureModal,
|
||||
closeFailureModal,
|
||||
openMarkdownEditor,
|
||||
closeMarkdownModal,
|
||||
handleSaveMarkdown,
|
||||
};
|
||||
}
|
||||
|
||||
export type KbWorkspaceModals = ReturnType<typeof useKbWorkspaceModals>;
|
||||
@@ -0,0 +1,454 @@
|
||||
/**
|
||||
* features/kb/composables/kb-workspace/useKbWorkspacePathUpload.ts
|
||||
* 路径上传:选文件、分批 job、轮询进度与历史批次操作。
|
||||
*/
|
||||
import type { KbJob } from '../../api/kb.api';
|
||||
import {
|
||||
createKbPathUploadJob,
|
||||
deleteKbPathJobFile,
|
||||
markKbPathJobFileFailed,
|
||||
retryFailedKbPathUploadJob,
|
||||
uploadKbPathJobFile,
|
||||
} from '../../api/kb.api';
|
||||
import {
|
||||
PATH_UPLOAD_BATCH_INTERVAL_MS,
|
||||
PATH_UPLOAD_BATCH_SIZE,
|
||||
PATH_UPLOAD_CONCURRENCY,
|
||||
type PathUploadStatus,
|
||||
type PathUploadTaskItem,
|
||||
} from '../../types/kb-workspace.types';
|
||||
import { normalizeDuplicateDocumentError } from '../../utils/kb-display.utils';
|
||||
import { getPathUploadJobItems } from '../../utils/kb-path-upload.utils';
|
||||
import type { KbWorkspaceDataBridge } from './kb-workspace.bridge';
|
||||
import type { KbWorkspaceState } from './kb-workspace.state';
|
||||
import type { KbWorkspaceComputed } from './useKbWorkspaceComputed';
|
||||
|
||||
let pathUploadPollTimer: number | null = null;
|
||||
|
||||
export function useKbWorkspacePathUpload(
|
||||
state: KbWorkspaceState,
|
||||
computed: KbWorkspaceComputed,
|
||||
bridge: KbWorkspaceDataBridge,
|
||||
) {
|
||||
const {
|
||||
feedback,
|
||||
feedbackType,
|
||||
selectedGroupId,
|
||||
pathUploadInputRef,
|
||||
pathUploadDraftText,
|
||||
pathUploadSelectedFiles,
|
||||
isPathUploadStaging,
|
||||
pathUploadJobId,
|
||||
pathUploadTask,
|
||||
showPathUploadModal,
|
||||
showPathUploadHistoryModal,
|
||||
showPathUploadDetails,
|
||||
selectedPathUploadHistoryJobId,
|
||||
selectedPathUploadHistoryItemKeys,
|
||||
retryingPathUploadKey,
|
||||
deletingPathUploadBatch,
|
||||
openDeleteConfirmDialog,
|
||||
} = state;
|
||||
|
||||
const {
|
||||
pathUploadRunning,
|
||||
kbJobPollingActive,
|
||||
pathUploadSummary,
|
||||
latestPathUploadJob,
|
||||
pathUploadHistoryJobs,
|
||||
selectedPathUploadHistoryJob,
|
||||
selectedPathUploadHistoryItems,
|
||||
selectedPathUploadHistorySelectedItems,
|
||||
isAllPathUploadHistoryItemsSelected,
|
||||
selectedPathRoots,
|
||||
} = computed;
|
||||
|
||||
const stopPathUploadPollTimer = () => {
|
||||
if (pathUploadPollTimer !== null) {
|
||||
window.clearInterval(pathUploadPollTimer);
|
||||
pathUploadPollTimer = null;
|
||||
}
|
||||
};
|
||||
|
||||
const wait = (ms: number) => new Promise((resolve) => {
|
||||
window.setTimeout(resolve, ms);
|
||||
});
|
||||
|
||||
const updatePathUploadFeedback = () => {
|
||||
const summary = pathUploadSummary.value;
|
||||
if (!pathUploadTask.value.total) return;
|
||||
feedback.value = `路径上传进度:总计 ${summary.total} 条,待上传 ${summary.pending} 条,已上传 ${summary.uploaded} 条,失败 ${summary.failed} 条`;
|
||||
feedbackType.value = summary.failed > 0 ? 'error' : 'success';
|
||||
};
|
||||
|
||||
const applyPathUploadJob = (job: KbJob | null) => {
|
||||
if (!job || job.job_type !== 'path_upload') {
|
||||
if (!isPathUploadStaging.value) {
|
||||
pathUploadTask.value = {
|
||||
running: false,
|
||||
groupId: selectedGroupId.value,
|
||||
total: 0,
|
||||
success: 0,
|
||||
failed: 0,
|
||||
currentFile: '',
|
||||
batchSize: PATH_UPLOAD_BATCH_SIZE,
|
||||
items: [],
|
||||
};
|
||||
}
|
||||
return;
|
||||
}
|
||||
const payload = job.payload_json || {};
|
||||
const result = job.result_json || {};
|
||||
const items = Array.isArray(payload.files)
|
||||
? payload.files.map((item: Record<string, unknown>, index: number) => ({
|
||||
key: String(item.relative_path || item.original_name || index),
|
||||
title: String(item.original_name || item.relative_path || `文件${index + 1}`),
|
||||
displayPath: String(item.relative_path || item.original_name || ''),
|
||||
rootLabel: String(item.relative_path || item.original_name || '').split('/')[0] || '本地目录',
|
||||
status: (['queued', 'uploading', 'success', 'failed'].includes(String(item.status)) ? item.status : 'queued') as PathUploadStatus,
|
||||
error: item.error as string | undefined,
|
||||
documentId: item.document_id as number | undefined,
|
||||
retryable: Boolean(String(item.staged_path || '').trim()) && String(item.status || '').toLowerCase() === 'failed',
|
||||
}))
|
||||
: [];
|
||||
|
||||
pathUploadJobId.value = job.id;
|
||||
pathUploadTask.value = {
|
||||
running: ['draft', 'staging', 'queued', 'running'].includes(String(job.status || '').toLowerCase()) || isPathUploadStaging.value,
|
||||
groupId: job.group_id ? Number(job.group_id) : selectedGroupId.value,
|
||||
total: Number(payload.total_files || result.total || items.length || 0),
|
||||
success: Number(result.success || items.filter((item) => item.status === 'success').length || 0),
|
||||
failed: Number(result.failed || items.filter((item) => item.status === 'failed').length || 0),
|
||||
currentFile: String(payload.current_file || ''),
|
||||
batchSize: PATH_UPLOAD_BATCH_SIZE,
|
||||
items,
|
||||
};
|
||||
updatePathUploadFeedback();
|
||||
};
|
||||
|
||||
const startPathUploadPolling = () => {
|
||||
stopPathUploadPollTimer();
|
||||
pathUploadPollTimer = window.setInterval(() => {
|
||||
if (!kbJobPollingActive.value) {
|
||||
stopPathUploadPollTimer();
|
||||
return;
|
||||
}
|
||||
void Promise.all([
|
||||
bridge.loadJobs(),
|
||||
bridge.loadDocuments(selectedGroupId.value, { silent: true }),
|
||||
bridge.loadGroups({ silent: true }),
|
||||
]);
|
||||
}, 3000);
|
||||
};
|
||||
|
||||
const resetPathUploadDraft = () => {
|
||||
pathUploadDraftText.value = '';
|
||||
pathUploadSelectedFiles.value = [];
|
||||
};
|
||||
|
||||
const openPathUploadModal = () => {
|
||||
if (pathUploadRunning.value) {
|
||||
feedback.value = '有文件正在上传请稍等再试~';
|
||||
feedbackType.value = 'error';
|
||||
return;
|
||||
}
|
||||
resetPathUploadDraft();
|
||||
showPathUploadModal.value = true;
|
||||
};
|
||||
|
||||
const closePathUploadModal = () => {
|
||||
if (pathUploadRunning.value) return;
|
||||
showPathUploadModal.value = false;
|
||||
resetPathUploadDraft();
|
||||
};
|
||||
|
||||
const triggerPathUploadSelection = () => {
|
||||
pathUploadInputRef.value?.click();
|
||||
};
|
||||
|
||||
const handlePathFilesSelected = (event: Event) => {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const files = Array.from(input.files || []);
|
||||
if (!files.length) {
|
||||
input.value = '';
|
||||
return;
|
||||
}
|
||||
const existing = new Set(pathUploadSelectedFiles.value.map((item) => item.displayPath));
|
||||
const nextItems = files.flatMap((file, index) => {
|
||||
const relativePath = (file as File & { webkitRelativePath?: string }).webkitRelativePath || file.name;
|
||||
if (existing.has(relativePath)) return [];
|
||||
const rootLabel = relativePath.includes('/') ? relativePath.split('/')[0] || file.name : file.name;
|
||||
return [{
|
||||
key: `${Date.now()}-${index}-${relativePath}`,
|
||||
file,
|
||||
displayPath: relativePath,
|
||||
rootLabel,
|
||||
}];
|
||||
});
|
||||
pathUploadSelectedFiles.value = [...pathUploadSelectedFiles.value, ...nextItems];
|
||||
pathUploadDraftText.value = pathUploadSelectedFiles.value.map((item) => item.displayPath).join('\n');
|
||||
input.value = '';
|
||||
};
|
||||
|
||||
const removeSelectedPathFile = (key: string) => {
|
||||
pathUploadSelectedFiles.value = pathUploadSelectedFiles.value.filter((item) => item.key !== key);
|
||||
pathUploadDraftText.value = pathUploadSelectedFiles.value.map((item) => item.displayPath).join('\n');
|
||||
};
|
||||
|
||||
const openPathUploadHistoryModal = (jobId?: number | string | null) => {
|
||||
selectedPathUploadHistoryJobId.value = jobId || latestPathUploadJob.value?.id || pathUploadHistoryJobs.value[0]?.id || null;
|
||||
showPathUploadHistoryModal.value = true;
|
||||
};
|
||||
|
||||
const closePathUploadHistoryModal = () => {
|
||||
showPathUploadHistoryModal.value = false;
|
||||
selectedPathUploadHistoryJobId.value = null;
|
||||
selectedPathUploadHistoryItemKeys.value = [];
|
||||
};
|
||||
|
||||
const togglePathUploadHistoryItemSelection = (itemKey: string) => {
|
||||
if (selectedPathUploadHistoryItemKeys.value.includes(itemKey)) {
|
||||
selectedPathUploadHistoryItemKeys.value = selectedPathUploadHistoryItemKeys.value.filter((key) => key !== itemKey);
|
||||
return;
|
||||
}
|
||||
selectedPathUploadHistoryItemKeys.value = [...selectedPathUploadHistoryItemKeys.value, itemKey];
|
||||
};
|
||||
|
||||
const toggleSelectAllPathUploadHistoryItems = () => {
|
||||
if (isAllPathUploadHistoryItemsSelected.value) {
|
||||
selectedPathUploadHistoryItemKeys.value = [];
|
||||
return;
|
||||
}
|
||||
selectedPathUploadHistoryItemKeys.value = selectedPathUploadHistoryItems.value.map((item) => item.key);
|
||||
};
|
||||
|
||||
const handleConfirmPathUpload = async () => {
|
||||
if (pathUploadRunning.value) {
|
||||
feedback.value = '有文件正在上传请稍等再试~';
|
||||
feedbackType.value = 'error';
|
||||
return;
|
||||
}
|
||||
if (!selectedGroupId.value) {
|
||||
feedback.value = '请先选择知识库分组';
|
||||
feedbackType.value = 'error';
|
||||
return;
|
||||
}
|
||||
if (!pathUploadSelectedFiles.value.length) {
|
||||
feedback.value = '请先选择至少一个本地目录或文件';
|
||||
feedbackType.value = 'error';
|
||||
return;
|
||||
}
|
||||
|
||||
isPathUploadStaging.value = true;
|
||||
const createResult = await createKbPathUploadJob(selectedGroupId.value, {
|
||||
total_files: pathUploadSelectedFiles.value.length,
|
||||
selected_paths: selectedPathRoots.value,
|
||||
files: pathUploadSelectedFiles.value.map((item) => ({
|
||||
relative_path: item.displayPath,
|
||||
original_name: item.file.name,
|
||||
})),
|
||||
});
|
||||
if (!createResult.ok || !createResult.job) {
|
||||
feedback.value = createResult.error || '创建上传路径任务失败';
|
||||
feedbackType.value = 'error';
|
||||
isPathUploadStaging.value = false;
|
||||
return;
|
||||
}
|
||||
const createdJob = createResult.job;
|
||||
const existingJobItems = getPathUploadJobItems(createdJob);
|
||||
const existingItemMap = new Map(existingJobItems.map((item) => [item.displayPath, item]));
|
||||
const selectedPathSet = new Set(pathUploadSelectedFiles.value.map((item) => item.displayPath));
|
||||
const pendingFiles = pathUploadSelectedFiles.value.filter((item) => {
|
||||
const existingItem = existingItemMap.get(item.displayPath);
|
||||
return !existingItem || existingItem.status !== 'success';
|
||||
});
|
||||
|
||||
pathUploadJobId.value = createdJob.id;
|
||||
showPathUploadDetails.value = false;
|
||||
pathUploadTask.value = {
|
||||
running: true,
|
||||
groupId: selectedGroupId.value,
|
||||
total: Number(createdJob.payload_json?.total_files || existingJobItems.length || pathUploadSelectedFiles.value.length),
|
||||
success: Number(createdJob.result_json?.success || existingJobItems.filter((item) => item.status === 'success').length || 0),
|
||||
failed: Number(createdJob.result_json?.failed || existingJobItems.filter((item) => item.status === 'failed').length || 0),
|
||||
currentFile: String(createdJob.payload_json?.current_file || ''),
|
||||
batchSize: PATH_UPLOAD_BATCH_SIZE,
|
||||
items: [
|
||||
...pathUploadSelectedFiles.value.map((item) => {
|
||||
const existingItem = existingItemMap.get(item.displayPath);
|
||||
return {
|
||||
key: item.key,
|
||||
title: item.file.name,
|
||||
displayPath: item.displayPath,
|
||||
rootLabel: item.rootLabel,
|
||||
status: existingItem?.status || 'queued',
|
||||
error: existingItem?.error,
|
||||
documentId: existingItem?.documentId,
|
||||
retryable: existingItem?.retryable,
|
||||
} satisfies PathUploadTaskItem;
|
||||
}),
|
||||
...existingJobItems.filter((item) => !selectedPathSet.has(item.displayPath)),
|
||||
],
|
||||
};
|
||||
updatePathUploadFeedback();
|
||||
showPathUploadModal.value = false;
|
||||
|
||||
const stageSinglePathUploadFile = async (item: { key: string; file: File; displayPath: string; rootLabel: string }) => {
|
||||
pathUploadTask.value.currentFile = item.displayPath;
|
||||
const localItem = pathUploadTask.value.items.find((candidate) => candidate.key === item.key);
|
||||
if (localItem) {
|
||||
localItem.status = 'uploading';
|
||||
}
|
||||
|
||||
const stageResult = await uploadKbPathJobFile(createdJob.id, item.file, item.displayPath);
|
||||
if (!stageResult.ok) {
|
||||
const errorMessage = normalizeDuplicateDocumentError(stageResult.error || '路径文件暂存失败');
|
||||
const failedResult = await markKbPathJobFileFailed(createdJob.id, {
|
||||
relative_path: item.displayPath,
|
||||
original_name: item.file.name,
|
||||
error: errorMessage,
|
||||
});
|
||||
if (failedResult.ok && failedResult.job) {
|
||||
applyPathUploadJob(failedResult.job);
|
||||
} else if (localItem) {
|
||||
localItem.status = 'failed';
|
||||
localItem.error = errorMessage;
|
||||
updatePathUploadFeedback();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (stageResult.job) {
|
||||
applyPathUploadJob(stageResult.job);
|
||||
} else if (localItem) {
|
||||
localItem.status = 'success';
|
||||
localItem.error = undefined;
|
||||
updatePathUploadFeedback();
|
||||
}
|
||||
await Promise.all([
|
||||
bridge.loadDocuments(selectedGroupId.value, { silent: true }),
|
||||
bridge.loadJobs(),
|
||||
]);
|
||||
};
|
||||
|
||||
const files = [...pendingFiles];
|
||||
for (let batchStart = 0; batchStart < files.length; batchStart += PATH_UPLOAD_BATCH_SIZE) {
|
||||
const batch = files.slice(batchStart, batchStart + PATH_UPLOAD_BATCH_SIZE);
|
||||
for (let i = 0; i < batch.length; i += PATH_UPLOAD_CONCURRENCY) {
|
||||
const chunk = batch.slice(i, i + PATH_UPLOAD_CONCURRENCY);
|
||||
await Promise.all(chunk.map((item) => stageSinglePathUploadFile(item)));
|
||||
}
|
||||
if (batchStart + PATH_UPLOAD_BATCH_SIZE < files.length) {
|
||||
await wait(PATH_UPLOAD_BATCH_INTERVAL_MS);
|
||||
}
|
||||
}
|
||||
|
||||
isPathUploadStaging.value = false;
|
||||
pathUploadTask.value.currentFile = '';
|
||||
feedback.value = '路径文件已逐个上传并提交清洗';
|
||||
feedbackType.value = 'success';
|
||||
startPathUploadPolling();
|
||||
resetPathUploadDraft();
|
||||
await bridge.refreshWorkflowStatusOnly();
|
||||
};
|
||||
|
||||
const handleDeletePathUploadItem = async (job: KbJob | null, item: PathUploadTaskItem) => {
|
||||
if (!job) return;
|
||||
openDeleteConfirmDialog(`确认删除路径文件「${item.displayPath || item.title}」吗?`, async () => {
|
||||
const result = await deleteKbPathJobFile(job.id, item.displayPath);
|
||||
if (!result.ok) {
|
||||
feedback.value = result.error || '删除路径上传文件失败';
|
||||
feedbackType.value = 'error';
|
||||
return;
|
||||
}
|
||||
feedback.value = result.document_deleted ? '已删除路径记录,并同步删除对应文档' : '已删除路径记录';
|
||||
feedbackType.value = 'success';
|
||||
if (pathUploadTask.value.items.length <= 1) {
|
||||
showPathUploadDetails.value = false;
|
||||
}
|
||||
await bridge.refreshWorkflowStatusOnly();
|
||||
});
|
||||
};
|
||||
|
||||
const handleBatchDeletePathUploadItems = async () => {
|
||||
const job = selectedPathUploadHistoryJob.value;
|
||||
const items = selectedPathUploadHistorySelectedItems.value;
|
||||
if (!job || !items.length) {
|
||||
feedback.value = '请先选择要删除的文件';
|
||||
feedbackType.value = 'error';
|
||||
return;
|
||||
}
|
||||
openDeleteConfirmDialog(`确认批量删除已选中的 ${items.length} 条路径文件吗?`, async () => {
|
||||
deletingPathUploadBatch.value = true;
|
||||
let successCount = 0;
|
||||
let failCount = 0;
|
||||
const errors: string[] = [];
|
||||
try {
|
||||
for (const item of items) {
|
||||
const result = await deleteKbPathJobFile(job.id, item.displayPath);
|
||||
if (result.ok) {
|
||||
successCount += 1;
|
||||
continue;
|
||||
}
|
||||
failCount += 1;
|
||||
errors.push(`${item.displayPath}: ${result.error || '删除失败'}`);
|
||||
}
|
||||
feedback.value = failCount
|
||||
? `批量删除完成:成功 ${successCount} 条,失败 ${failCount} 条。${errors[0] || ''}`
|
||||
: `批量删除完成:共成功 ${successCount} 条`;
|
||||
feedbackType.value = failCount ? 'error' : 'success';
|
||||
selectedPathUploadHistoryItemKeys.value = [];
|
||||
await Promise.all([
|
||||
bridge.loadJobs(),
|
||||
bridge.loadDocuments(selectedGroupId.value),
|
||||
bridge.loadGroups(),
|
||||
]);
|
||||
} finally {
|
||||
deletingPathUploadBatch.value = false;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const handleRetryFailedPathUpload = async (
|
||||
job: KbJob | null,
|
||||
relativePaths?: string[],
|
||||
) => {
|
||||
if (!job) return;
|
||||
const key = `${job.id}:${(relativePaths || []).join('|') || 'all'}`;
|
||||
retryingPathUploadKey.value = key;
|
||||
const result = await retryFailedKbPathUploadJob(job.id, relativePaths?.length ? { relative_paths: relativePaths } : {});
|
||||
retryingPathUploadKey.value = '';
|
||||
if (!result.ok || !result.job) {
|
||||
feedback.value = result.error || '重试失败文件失败';
|
||||
feedbackType.value = 'error';
|
||||
return;
|
||||
}
|
||||
applyPathUploadJob(result.job);
|
||||
startPathUploadPolling();
|
||||
feedback.value = relativePaths?.length === 1 ? '已重新提交该失败文件' : '已重新提交失败文件';
|
||||
feedbackType.value = 'success';
|
||||
await bridge.refreshWorkflowStatusOnly();
|
||||
};
|
||||
|
||||
return {
|
||||
stopPathUploadPollTimer,
|
||||
startPathUploadPolling,
|
||||
applyPathUploadJob,
|
||||
resetPathUploadDraft,
|
||||
openPathUploadModal,
|
||||
closePathUploadModal,
|
||||
triggerPathUploadSelection,
|
||||
handlePathFilesSelected,
|
||||
removeSelectedPathFile,
|
||||
openPathUploadHistoryModal,
|
||||
closePathUploadHistoryModal,
|
||||
togglePathUploadHistoryItemSelection,
|
||||
toggleSelectAllPathUploadHistoryItems,
|
||||
handleConfirmPathUpload,
|
||||
handleDeletePathUploadItem,
|
||||
handleBatchDeletePathUploadItems,
|
||||
handleRetryFailedPathUpload,
|
||||
};
|
||||
}
|
||||
|
||||
export type KbWorkspacePathUpload = ReturnType<typeof useKbWorkspacePathUpload>;
|
||||
@@ -0,0 +1,156 @@
|
||||
/**
|
||||
* features/kb/composables/useKbWorkspace.ts
|
||||
* 知识库作业面编排入口:组合 state / computed / data / pathUpload / documents / modals。
|
||||
*/
|
||||
import { onMounted, onUnmounted, reactive, watch } from 'vue';
|
||||
import {
|
||||
DOCUMENT_PAGE_SIZE_OPTIONS,
|
||||
FAILURE_PAGE_SIZE,
|
||||
PATH_UPLOAD_BATCH_INTERVAL_MS,
|
||||
PATH_UPLOAD_BATCH_SIZE,
|
||||
PATH_UPLOAD_CONCURRENCY,
|
||||
} from '../types/kb-workspace.types';
|
||||
import {
|
||||
formatDateTime,
|
||||
formatFileSize,
|
||||
getDocumentDisplayDescription,
|
||||
getDocumentDisplayTitle,
|
||||
getStatusBadgeClass,
|
||||
getStatusLabel,
|
||||
} from '../utils/kb-display.utils';
|
||||
import {
|
||||
getPathUploadJobItems,
|
||||
getPathUploadJobSummary,
|
||||
hasRetryablePathUploadFailure,
|
||||
} from '../utils/kb-path-upload.utils';
|
||||
import { createKbWorkspaceDataBridge } from './kb-workspace/kb-workspace.bridge';
|
||||
import { createKbWorkspaceState } from './kb-workspace/kb-workspace.state';
|
||||
import { useKbWorkspaceComputed } from './kb-workspace/useKbWorkspaceComputed';
|
||||
import { useKbWorkspaceData } from './kb-workspace/useKbWorkspaceData';
|
||||
import { useKbWorkspaceDocuments } from './kb-workspace/useKbWorkspaceDocuments';
|
||||
import { useKbWorkspaceModals } from './kb-workspace/useKbWorkspaceModals';
|
||||
import { useKbWorkspacePathUpload } from './kb-workspace/useKbWorkspacePathUpload';
|
||||
|
||||
export interface UseKbWorkspaceOptions {
|
||||
embedded?: boolean;
|
||||
}
|
||||
|
||||
export function useKbWorkspace(options: UseKbWorkspaceOptions = {}) {
|
||||
const state = createKbWorkspaceState(options);
|
||||
const computed = useKbWorkspaceComputed(state);
|
||||
|
||||
// pathUpload 先于 data 创建;data 加载函数通过 bridge 延迟注入,打破循环依赖
|
||||
const bridge = createKbWorkspaceDataBridge();
|
||||
const pathUpload = useKbWorkspacePathUpload(state, computed, bridge);
|
||||
const data = useKbWorkspaceData(state, computed, pathUpload);
|
||||
Object.assign(bridge, {
|
||||
loadGroups: data.loadGroups,
|
||||
loadJobs: data.loadJobs,
|
||||
loadDocuments: data.loadDocuments,
|
||||
refreshWorkflowStatusOnly: data.refreshWorkflowStatusOnly,
|
||||
});
|
||||
|
||||
const modals = useKbWorkspaceModals(state, computed, data);
|
||||
const documents = useKbWorkspaceDocuments(state, computed, data, pathUpload);
|
||||
|
||||
const {
|
||||
selectedGroupId,
|
||||
feedback,
|
||||
feedbackType,
|
||||
documentListPage,
|
||||
selectedDocumentId,
|
||||
selectedDocumentIds,
|
||||
selectedDocumentVersions,
|
||||
selectedDocumentSyncRecords,
|
||||
documentStageFilter,
|
||||
documentKeyword,
|
||||
documentListPageSize,
|
||||
selectedPathUploadHistoryItemKeys,
|
||||
} = state;
|
||||
|
||||
const {
|
||||
filteredDocumentTotalPages,
|
||||
latestPathUploadJob,
|
||||
selectedPathUploadHistoryJob,
|
||||
} = computed;
|
||||
|
||||
const { applyPathUploadJob } = pathUpload;
|
||||
|
||||
// --- 筛选/分页/路径上传历史联动 ---
|
||||
watch(selectedGroupId, (groupId) => {
|
||||
feedback.value = '';
|
||||
feedbackType.value = '';
|
||||
documentListPage.value = 1;
|
||||
selectedDocumentId.value = null;
|
||||
selectedDocumentIds.value = [];
|
||||
selectedDocumentVersions.value = [];
|
||||
selectedDocumentSyncRecords.value = [];
|
||||
void data.loadDocuments(groupId);
|
||||
applyPathUploadJob(latestPathUploadJob.value);
|
||||
});
|
||||
|
||||
watch(documentStageFilter, () => {
|
||||
documentListPage.value = 1;
|
||||
});
|
||||
|
||||
watch(documentKeyword, () => {
|
||||
documentListPage.value = 1;
|
||||
});
|
||||
|
||||
watch(documentListPageSize, () => {
|
||||
documentListPage.value = 1;
|
||||
});
|
||||
|
||||
watch(filteredDocumentTotalPages, (totalPages) => {
|
||||
if (documentListPage.value > totalPages) {
|
||||
documentListPage.value = totalPages;
|
||||
}
|
||||
});
|
||||
|
||||
watch(selectedPathUploadHistoryJob, (job) => {
|
||||
const validKeys = new Set(getPathUploadJobItems(job).map((item) => item.key));
|
||||
selectedPathUploadHistoryItemKeys.value = selectedPathUploadHistoryItemKeys.value.filter((key) => validKeys.has(key));
|
||||
if (!job) {
|
||||
selectedPathUploadHistoryItemKeys.value = [];
|
||||
}
|
||||
});
|
||||
|
||||
onMounted(async () => {
|
||||
await Promise.all([data.loadGroups(), data.loadJobs()]);
|
||||
if (state.viewMode.value === 'group_detail') {
|
||||
await data.loadDocuments(selectedGroupId.value);
|
||||
}
|
||||
data.startAutoRefresh();
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
data.stopAutoRefresh();
|
||||
pathUpload.stopPathUploadPollTimer();
|
||||
});
|
||||
|
||||
// reactive 便于模板以 kb.xxx 统一访问,ref/computed 在属性读取时自动解包
|
||||
return reactive({
|
||||
...state,
|
||||
...computed,
|
||||
...data,
|
||||
...pathUpload,
|
||||
...modals,
|
||||
...documents,
|
||||
getWorkflowBadges: computed.getWorkflowBadgesForDoc,
|
||||
getDocumentWorkflowState: computed.resolveWorkflowState,
|
||||
formatDateTime,
|
||||
formatFileSize,
|
||||
getDocumentDisplayTitle,
|
||||
getDocumentDisplayDescription,
|
||||
getStatusLabel,
|
||||
getStatusBadgeClass,
|
||||
getPathUploadJobItems,
|
||||
hasRetryablePathUploadFailure,
|
||||
getPathUploadJobSummary,
|
||||
DOCUMENT_PAGE_SIZE_OPTIONS,
|
||||
FAILURE_PAGE_SIZE,
|
||||
PATH_UPLOAD_BATCH_SIZE,
|
||||
PATH_UPLOAD_BATCH_INTERVAL_MS,
|
||||
PATH_UPLOAD_CONCURRENCY,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* features/kb/types/kb-workspace.types.ts
|
||||
* 知识库作业面类型与分页/批处理常量。
|
||||
*/
|
||||
import type { KbDocumentItem, KbJob } from '../api/kb.api';
|
||||
|
||||
/** 作业面视图:分组概览(只读选择)或分组内文档维护 */
|
||||
export type KbWorkspaceViewMode = 'group_overview' | 'group_detail';
|
||||
|
||||
export type KbFeedbackType = 'success' | 'error' | '';
|
||||
|
||||
/** 上传 → 清洗 → 同步 各阶段展示状态 */
|
||||
export type WorkflowStageState = {
|
||||
code: 'pending' | 'running' | 'success' | 'failed' | 'idle';
|
||||
label: string;
|
||||
className: string;
|
||||
errorMessage?: string | null;
|
||||
};
|
||||
|
||||
/** 失败弹窗列表项 */
|
||||
export type FailureModalItem = {
|
||||
key: string;
|
||||
document: KbDocumentItem;
|
||||
stage: 'upload' | 'clean' | 'sync';
|
||||
stageLabel: string;
|
||||
errorMessage: string;
|
||||
latestJob: KbJob | null;
|
||||
updatedAt?: string | null;
|
||||
};
|
||||
|
||||
export type PathUploadStatus = 'queued' | 'uploading' | 'success' | 'failed';
|
||||
|
||||
export type PathUploadTaskItem = {
|
||||
key: string;
|
||||
title: string;
|
||||
displayPath: string;
|
||||
rootLabel: string;
|
||||
status: PathUploadStatus;
|
||||
error?: string;
|
||||
documentId?: number;
|
||||
retryable?: boolean;
|
||||
startedAt?: string;
|
||||
finishedAt?: string;
|
||||
};
|
||||
|
||||
/** 静默刷新时不切换 loading 态,避免列表闪烁 */
|
||||
export type LoadListOptions = {
|
||||
silent?: boolean;
|
||||
};
|
||||
|
||||
export const FAILURE_PAGE_SIZE = 15;
|
||||
export const PATH_UPLOAD_BATCH_SIZE = 30;
|
||||
export const PATH_UPLOAD_BATCH_INTERVAL_MS = 500;
|
||||
export const PATH_UPLOAD_CONCURRENCY = 3;
|
||||
export const DOCUMENT_PAGE_SIZE_OPTIONS = [20, 50, 100, 200] as const;
|
||||
|
||||
/** 未开始阶段的徽标样式,与 getStatusBadgeClass 默认一致 */
|
||||
export const IDLE_BADGE_CLASS = 'border-default bg-surface-soft text-muted';
|
||||
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* features/kb/utils/kb-display.utils.ts
|
||||
* 文档标题、时间、文件大小与状态徽标等纯展示工具。
|
||||
*/
|
||||
import type { KbDocumentItem } from '../api/kb.api';
|
||||
|
||||
export const formatDateTime = (value?: string | null) => {
|
||||
if (!value) return '--';
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return value;
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
||||
};
|
||||
|
||||
export const formatFileSize = (value?: number | null) => {
|
||||
const size = Number(value || 0);
|
||||
if (!Number.isFinite(size) || size <= 0) return '0 B';
|
||||
if (size < 1024) return `${size} B`;
|
||||
if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`;
|
||||
if (size < 1024 * 1024 * 1024) return `${(size / (1024 * 1024)).toFixed(1)} MB`;
|
||||
return `${(size / (1024 * 1024 * 1024)).toFixed(1)} GB`;
|
||||
};
|
||||
|
||||
const trimPathText = (value?: string | null) => {
|
||||
const text = String(value || '').trim();
|
||||
if (!text) return '';
|
||||
return text.split(/[\\/]/).filter(Boolean).pop() || text;
|
||||
};
|
||||
|
||||
export const getDocumentDisplayTitle = (doc: KbDocumentItem) => trimPathText(doc.title) || '未命名文档';
|
||||
|
||||
export const getDocumentDisplayDescription = (doc: KbDocumentItem) => {
|
||||
const text = trimPathText(doc.description);
|
||||
return text || getDocumentDisplayTitle(doc);
|
||||
};
|
||||
|
||||
/** 将后端重复文档错误归一为前端可展示的简短文案 */
|
||||
export const normalizeDuplicateDocumentError = (message?: string | null) => {
|
||||
const text = String(message || '').trim();
|
||||
if (!text) return '知识库接口请求失败';
|
||||
if (text.includes('当前分组下已存在同名文档') || text.includes('上传失败,文件已存在')) {
|
||||
return '上传失败,文件已存在';
|
||||
}
|
||||
return text;
|
||||
};
|
||||
|
||||
export const getStatusLabel = (status?: string | null) => {
|
||||
const normalized = String(status || '').toLowerCase();
|
||||
const map: Record<string, string> = {
|
||||
draft: '待上传',
|
||||
uploaded: '已上传',
|
||||
processing: '清洗中',
|
||||
cleaned: '已清洗',
|
||||
ready: '已就绪',
|
||||
synced: '已同步',
|
||||
syncing: '同步中',
|
||||
failed: '失败',
|
||||
queued: '排队中',
|
||||
running: '进行中',
|
||||
success: '成功',
|
||||
cancelled: '已取消',
|
||||
};
|
||||
return map[normalized] || status || '未知状态';
|
||||
};
|
||||
|
||||
export const getStatusBadgeClass = (status?: string | null) => {
|
||||
const normalized = String(status || '').toLowerCase();
|
||||
if (['cleaned', 'ready', 'synced', 'success'].includes(normalized)) {
|
||||
return 'border-emerald-200 bg-emerald-50 text-emerald-700';
|
||||
}
|
||||
if (['processing', 'running'].includes(normalized)) {
|
||||
return 'border-amber-200 bg-amber-50 text-amber-700';
|
||||
}
|
||||
if (['uploaded', 'queued', 'draft'].includes(normalized)) {
|
||||
return 'border-sky-200 bg-sky-50 text-sky-700';
|
||||
}
|
||||
if (normalized === 'failed') {
|
||||
return 'border-rose-200 bg-rose-50 text-rose-700';
|
||||
}
|
||||
if (normalized === 'cancelled') {
|
||||
return 'border-default bg-surface-soft text-secondary';
|
||||
}
|
||||
return 'border-default bg-surface-soft text-secondary';
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* features/kb/utils/kb-list.utils.ts
|
||||
* 列表合并工具:轮询刷新时保持已有项顺序,减少 UI 跳动。
|
||||
*/
|
||||
|
||||
/** 按当前列表顺序合并服务端数据,新增项追加在末尾 */
|
||||
export function mergeStableItems<T extends { id: number | string }>(current: T[], incoming: T[]): T[] {
|
||||
const incomingMap = new Map(incoming.map((item) => [String(item.id), item] as const));
|
||||
const next: T[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
current.forEach((item) => {
|
||||
const key = String(item.id);
|
||||
const incomingItem = incomingMap.get(key);
|
||||
if (!incomingItem) return;
|
||||
next.push(incomingItem);
|
||||
seen.add(key);
|
||||
});
|
||||
|
||||
incoming.forEach((item) => {
|
||||
const key = String(item.id);
|
||||
if (seen.has(key)) return;
|
||||
next.push(item);
|
||||
});
|
||||
|
||||
return next;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* features/kb/utils/kb-path-upload.utils.ts
|
||||
* 路径上传任务(path_upload job)解析与排序权重。
|
||||
*/
|
||||
import type { KbJob } from '../api/kb.api';
|
||||
import type { PathUploadStatus, PathUploadTaskItem } from '../types/kb-workspace.types';
|
||||
|
||||
export const getPathUploadJobProgress = (job: KbJob | null) => {
|
||||
const payload = job?.payload_json || {};
|
||||
const result = job?.result_json || {};
|
||||
const success = Number(result.success || 0);
|
||||
const failed = Number(result.failed || 0);
|
||||
const processed = Number(result.processed || success + failed || 0);
|
||||
const total = Number(result.total || payload.total_files || 0);
|
||||
return { total, success, failed, processed };
|
||||
};
|
||||
|
||||
/** 用于在历史批次列表中优先展示有进度或进行中的任务 */
|
||||
export const getPathUploadJobPriority = (job: KbJob) => {
|
||||
const normalizedStatus = String(job.status || '').toLowerCase();
|
||||
const { processed, success, failed } = getPathUploadJobProgress(job);
|
||||
const hasProgress = processed > 0 || success > 0 || failed > 0 || Boolean(job.started_at) || Boolean(job.finished_at);
|
||||
const statusScore = normalizedStatus === 'running'
|
||||
? 50
|
||||
: normalizedStatus === 'success'
|
||||
? 40
|
||||
: normalizedStatus === 'failed'
|
||||
? 35
|
||||
: ['queued', 'staging', 'draft'].includes(normalizedStatus)
|
||||
? 20
|
||||
: 0;
|
||||
return (hasProgress ? 1000 : 0) + statusScore;
|
||||
};
|
||||
|
||||
export const getPathUploadJobItems = (job: KbJob | null): PathUploadTaskItem[] => {
|
||||
if (!job || job.job_type !== 'path_upload') return [];
|
||||
const payload = job.payload_json || {};
|
||||
const files = Array.isArray(payload.files) ? payload.files : [];
|
||||
const failedCount = files.filter((item: { status?: string }) => String(item?.status || '').toLowerCase() === 'failed').length;
|
||||
return files.map((item: Record<string, unknown>, index: number) => ({
|
||||
key: `${job.id}-${item.relative_path || item.original_name || index}`,
|
||||
title: String(item.original_name || item.relative_path || `文件${index + 1}`),
|
||||
displayPath: String(item.relative_path || item.original_name || ''),
|
||||
rootLabel: String(item.relative_path || item.original_name || '').split('/')[0] || '本地目录',
|
||||
status: (['queued', 'uploading', 'success', 'failed'].includes(String(item.status))
|
||||
? item.status
|
||||
: 'queued') as PathUploadStatus,
|
||||
error: (item.error as string | undefined)
|
||||
|| (String(item.status || '').toLowerCase() === 'failed' && failedCount === 1
|
||||
? (job.error_message || job.message || '上传失败')
|
||||
: undefined),
|
||||
documentId: (item.document_id as number | undefined) || undefined,
|
||||
retryable: Boolean(String(item.staged_path || '').trim()) && String(item.status || '').toLowerCase() === 'failed',
|
||||
startedAt: undefined,
|
||||
finishedAt: undefined,
|
||||
}));
|
||||
};
|
||||
|
||||
export const hasRetryablePathUploadFailure = (job: KbJob | null) =>
|
||||
getPathUploadJobItems(job).some((item) => item.retryable);
|
||||
|
||||
export const getPathUploadJobSummary = (job: KbJob | null) => {
|
||||
const items = getPathUploadJobItems(job);
|
||||
const total = Number(job?.payload_json?.total_files || job?.result_json?.total || items.length || 0);
|
||||
const success = Number(job?.result_json?.success || items.filter((item) => item.status === 'success').length || 0);
|
||||
const failed = Number(job?.result_json?.failed || items.filter((item) => item.status === 'failed').length || 0);
|
||||
const pending = Math.max(total - success - failed, 0);
|
||||
return { total, success, failed, pending };
|
||||
};
|
||||
@@ -0,0 +1,193 @@
|
||||
/**
|
||||
* features/kb/utils/kb-workflow.utils.ts
|
||||
* 文档工作流(上传/清洗/同步)状态推导与错误文案归一。
|
||||
*/
|
||||
import type { KbDocumentItem, KbJob } from '../api/kb.api';
|
||||
import { IDLE_BADGE_CLASS, type WorkflowStageState } from '../types/kb-workspace.types';
|
||||
import { getStatusBadgeClass } from './kb-display.utils';
|
||||
|
||||
export const isUnreadableErrorMessage = (value: string | null | undefined) => {
|
||||
const text = String(value || '').trim();
|
||||
if (!text) return true;
|
||||
const compact = text.replace(/[\s::,,。.!!;;\-_/\\()[\]【】]/g, '');
|
||||
if (!compact) return true;
|
||||
return /^[??]+$/.test(compact);
|
||||
};
|
||||
|
||||
export const normalizeWorkflowErrorMessage = (
|
||||
value: string | null | undefined,
|
||||
stage: 'upload' | 'clean' | 'sync',
|
||||
) => {
|
||||
const text = String(value || '').trim();
|
||||
if (!text) return null;
|
||||
const upper = text.toUpperCase();
|
||||
if (isUnreadableErrorMessage(text)) {
|
||||
if (stage === 'clean') {
|
||||
return '历史失败任务原因不可读,请重新点击“清洗数据”发起清洗';
|
||||
}
|
||||
if (stage === 'sync') {
|
||||
return '历史同步失败原因不可读,请重新发起同步';
|
||||
}
|
||||
return '历史上传失败原因不可读,请重新上传文件';
|
||||
}
|
||||
if (upper.includes('LEGACY_CLEAN_TASK_RECOVERED_MANUALLY')) {
|
||||
return '历史遗留清洗任务已人工回收,请重新点击“清洗数据”发起清洗';
|
||||
}
|
||||
if (upper.includes('SOURCE_FILE_NOT_FOUND') || text.includes('源文件不存在')) {
|
||||
return '原始文件不存在,请重新上传后再清洗';
|
||||
}
|
||||
if (upper.includes('CLEAN_TIMEOUT') || text.includes('清洗超时')) {
|
||||
return '文件清洗超时,请稍后重试;若多次失败,请检查源文件是否损坏';
|
||||
}
|
||||
return text;
|
||||
};
|
||||
|
||||
/** 按文档与任务类型取当前分组下最新一条关联任务 */
|
||||
export function buildGetLatestJobForDocument(getActiveGroupJobs: () => KbJob[]) {
|
||||
return (doc: KbDocumentItem, jobType: string): KbJob | null => {
|
||||
const activeGroupJobs = getActiveGroupJobs();
|
||||
const currentVersionId = doc.latest_version?.id;
|
||||
const candidates = activeGroupJobs.filter((job) => {
|
||||
if (job.job_type !== jobType || job.document_id !== doc.id) return false;
|
||||
if (currentVersionId) {
|
||||
return job.document_version_id === currentVersionId;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
if (!candidates.length) return null;
|
||||
return [...candidates].sort((a, b) => {
|
||||
const aTime = new Date(a.created_at || a.finished_at || a.started_at || 0).getTime();
|
||||
const bTime = new Date(b.created_at || b.finished_at || b.started_at || 0).getTime();
|
||||
if (aTime !== bTime) return bTime - aTime;
|
||||
return Number(b.id) - Number(a.id);
|
||||
})[0] ?? null;
|
||||
};
|
||||
}
|
||||
|
||||
export type GetLatestJobForDocument = ReturnType<typeof buildGetLatestJobForDocument>;
|
||||
|
||||
export const getDocumentWorkflowState = (
|
||||
doc: KbDocumentItem,
|
||||
getLatestJobForDocument: GetLatestJobForDocument,
|
||||
) => {
|
||||
const latestStatus = String(doc.latest_version?.status || '').toLowerCase();
|
||||
const uploadJob = getLatestJobForDocument(doc, 'upload');
|
||||
const cleanJob = getLatestJobForDocument(doc, 'clean');
|
||||
const syncJob = getLatestJobForDocument(doc, 'sync_dify');
|
||||
|
||||
const uploadStage: WorkflowStageState = !doc.latest_version
|
||||
? { code: 'pending', label: '待上传', className: getStatusBadgeClass('draft') }
|
||||
: uploadJob?.status === 'failed'
|
||||
? {
|
||||
code: 'failed',
|
||||
label: '失败',
|
||||
className: getStatusBadgeClass('failed'),
|
||||
errorMessage: normalizeWorkflowErrorMessage(uploadJob.error_message || uploadJob.message, 'upload'),
|
||||
}
|
||||
: { code: 'success', label: '已完成', className: getStatusBadgeClass('success') };
|
||||
|
||||
let cleanStage: WorkflowStageState;
|
||||
if (!doc.latest_version) {
|
||||
cleanStage = { code: 'idle', label: '未开始', className: IDLE_BADGE_CLASS };
|
||||
} else if (cleanJob?.status === 'failed' || latestStatus === 'failed') {
|
||||
cleanStage = {
|
||||
code: 'failed',
|
||||
label: '失败',
|
||||
className: getStatusBadgeClass('failed'),
|
||||
errorMessage: normalizeWorkflowErrorMessage(
|
||||
cleanJob?.error_message || doc.latest_version?.error_message || cleanJob?.message || null,
|
||||
'clean',
|
||||
),
|
||||
};
|
||||
} else if (['cleaned', 'ready', 'syncing', 'synced'].includes(latestStatus)) {
|
||||
cleanStage = { code: 'success', label: '已完成', className: getStatusBadgeClass('success') };
|
||||
} else if (['running', 'queued'].includes(String(cleanJob?.status || '').toLowerCase()) || latestStatus === 'processing') {
|
||||
cleanStage = {
|
||||
code: 'running',
|
||||
label: latestStatus === 'processing' ? '清洗中' : '待清洗',
|
||||
className: getStatusBadgeClass(latestStatus === 'processing' ? 'processing' : 'uploaded'),
|
||||
};
|
||||
} else if (latestStatus === 'uploaded') {
|
||||
cleanStage = { code: 'pending', label: '待清洗', className: getStatusBadgeClass('uploaded') };
|
||||
} else {
|
||||
cleanStage = { code: 'idle', label: '未开始', className: IDLE_BADGE_CLASS };
|
||||
}
|
||||
|
||||
let syncStage: WorkflowStageState;
|
||||
if (!doc.latest_version || cleanStage.code === 'failed') {
|
||||
syncStage = { code: 'idle', label: '未开始', className: IDLE_BADGE_CLASS };
|
||||
} else if (syncJob?.status === 'failed') {
|
||||
syncStage = {
|
||||
code: 'failed',
|
||||
label: '失败',
|
||||
className: getStatusBadgeClass('failed'),
|
||||
errorMessage: normalizeWorkflowErrorMessage(syncJob.error_message || syncJob.message, 'sync'),
|
||||
};
|
||||
} else if (latestStatus === 'synced' || syncJob?.status === 'success') {
|
||||
syncStage = { code: 'success', label: '已完成', className: getStatusBadgeClass('success') };
|
||||
} else if (['running', 'queued'].includes(String(syncJob?.status || '').toLowerCase()) || latestStatus === 'syncing') {
|
||||
syncStage = {
|
||||
code: 'running',
|
||||
label: latestStatus === 'syncing' ? '同步中' : '待同步',
|
||||
className: getStatusBadgeClass(latestStatus === 'syncing' ? 'processing' : 'uploaded'),
|
||||
};
|
||||
} else if (['cleaned', 'ready'].includes(latestStatus)) {
|
||||
syncStage = { code: 'pending', label: '待同步', className: getStatusBadgeClass('uploaded') };
|
||||
} else {
|
||||
syncStage = { code: 'idle', label: '未开始', className: IDLE_BADGE_CLASS };
|
||||
}
|
||||
|
||||
const primaryError =
|
||||
syncStage.errorMessage ||
|
||||
cleanStage.errorMessage ||
|
||||
uploadStage.errorMessage ||
|
||||
normalizeWorkflowErrorMessage(doc.latest_version?.error_message, 'clean') ||
|
||||
null;
|
||||
|
||||
return {
|
||||
upload: uploadStage,
|
||||
clean: cleanStage,
|
||||
sync: syncStage,
|
||||
primaryError,
|
||||
};
|
||||
};
|
||||
|
||||
export const getWorkflowBadges = (
|
||||
doc: KbDocumentItem,
|
||||
getLatestJobForDocument: GetLatestJobForDocument,
|
||||
) => {
|
||||
const workflow = getDocumentWorkflowState(doc, getLatestJobForDocument);
|
||||
return [
|
||||
{ label: '上传', value: workflow.upload.label, className: workflow.upload.className },
|
||||
{ label: '清洗', value: workflow.clean.label, className: workflow.clean.className },
|
||||
{ label: '同步', value: workflow.sync.label, className: workflow.sync.className },
|
||||
];
|
||||
};
|
||||
|
||||
export const getMarkdownUnavailableMessage = (
|
||||
doc: KbDocumentItem,
|
||||
_getLatestJobForDocument: GetLatestJobForDocument,
|
||||
fallback?: string | null,
|
||||
) => {
|
||||
const latestStatus = String(doc.latest_version?.status || '').toLowerCase();
|
||||
const normalizedReason = normalizeWorkflowErrorMessage(
|
||||
doc.latest_version?.error_message,
|
||||
'clean',
|
||||
);
|
||||
|
||||
if (latestStatus === 'failed') {
|
||||
return normalizedReason
|
||||
? `当前文档清洗失败,尚未生成 Markdown。失败原因:${normalizedReason}`
|
||||
: '当前文档清洗失败,尚未生成 Markdown,请重新清洗后重试';
|
||||
}
|
||||
|
||||
if (latestStatus === 'processing') {
|
||||
return '当前文档正在清洗中,暂未生成 Markdown,请稍后再试';
|
||||
}
|
||||
|
||||
if (latestStatus === 'uploaded') {
|
||||
return '当前文档待清洗,暂未生成 Markdown,请先发起清洗';
|
||||
}
|
||||
|
||||
return fallback || '当前文档尚未生成 Markdown';
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
@@ -19,7 +19,7 @@ export function useWorkspaceSession(deps: WorkspaceDeps, options: SessionOptions
|
||||
|
||||
const isLoggedIn = computed(() => !!currentUser.value && currentUser.value.role !== 'guest');
|
||||
const hasKnowledgeBaseAccess = computed(
|
||||
() => String(currentUser.value?.username || '').trim().toLowerCase() === 'admin',
|
||||
() => String(currentUser.value?.role || '').trim().toLowerCase() === 'admin',
|
||||
);
|
||||
|
||||
const loadAuthUser = () => {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* @deprecated 请使用 @/features/chat/pages/HistoryPage.vue
|
||||
* @deprecated 请使用 @/features/chat/history/HistoryPage.vue
|
||||
*/
|
||||
import HistoryPage from '@/features/chat/pages/HistoryPage.vue';
|
||||
import HistoryPage from '@/features/chat/history/HistoryPage.vue';
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/workspace/pages/KnowledgeBasePage.vue
|
||||
* 知识库管理嵌入页,复用 KbWorkspaceView 的 embedded 模式。
|
||||
* 知识库作业面嵌入页,复用 KbWorkspaceView 的 embedded 模式。
|
||||
*/
|
||||
import KbWorkspaceView from '@/views/KbWorkspaceView.vue';
|
||||
import KbWorkspaceView from '@/features/kb/views/KbWorkspaceView.vue';
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -94,6 +94,6 @@ export const SECTION_TITLE_KEY_MAP: Record<string, string> = {
|
||||
};
|
||||
|
||||
export const DEFAULT_POST_LOGIN_AGENT_ID = 16;
|
||||
export const KB_ACCESS_DENIED_MESSAGE = '暂无权限,请登录admin账号操作知识库!';
|
||||
export const KB_ACCESS_DENIED_MESSAGE = '需要管理员权限才能访问知识库。';
|
||||
export const WS_SCHEDULE_FILTER_INPUT_CLASS = 'admin-table-filter-input text-xs py-1.5 px-2';
|
||||
export const CHANGE_PASSWORD_ENABLED = true;
|
||||
+1
-405
@@ -1,7 +1,7 @@
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import { mergeExternalLocales } from './locales';
|
||||
|
||||
/** 内联 messages;errors、auth、workspace、chat、admin 等域已外置至 locales/,由 mergeExternalLocales 合并。 */
|
||||
/** 内联 messages;errors、auth、workspace、chat、admin、kb 等域已外置至 locales/,由 mergeExternalLocales 合并。 */
|
||||
const messages = {
|
||||
"en": {
|
||||
"common": {
|
||||
@@ -51,86 +51,6 @@ const messages = {
|
||||
"unknownError": "Unknown error"
|
||||
}
|
||||
},
|
||||
"kbDifySettings": {
|
||||
"title": "Dify Settings",
|
||||
"subtitle": "Manage Dify connection and default sync parameters for the knowledge base module.",
|
||||
"loading": "Loading settings...",
|
||||
"save": "Save Settings",
|
||||
"saving": "Saving...",
|
||||
"msg": {
|
||||
"loadFailed": "Failed to load Dify settings",
|
||||
"saveFailed": "Failed to save Dify settings",
|
||||
"saved": "Dify settings saved"
|
||||
}
|
||||
},
|
||||
"kbDifyHealth": {
|
||||
"title": "Dify Health Check",
|
||||
"subtitle": "View Dify connectivity and local sync overview for knowledge base module.",
|
||||
"loading": "Checking...",
|
||||
"reachable": "Reachable",
|
||||
"unreachable": "Unreachable",
|
||||
"notConfigured": "Not configured",
|
||||
"datasetCount": "Dataset Count",
|
||||
"configured": "Configured: ",
|
||||
"boundGroups": "Bound Groups",
|
||||
"localSyncRecords": "Local Sync Records: ",
|
||||
"syncingVersions": "Syncing Versions",
|
||||
"syncedVersions": "Synced Versions",
|
||||
"pendingSyncJobs": "Pending Sync Jobs",
|
||||
"msg": {
|
||||
"loadFailed": "Failed to load Dify health status"
|
||||
}
|
||||
},
|
||||
"kbAdmin": {
|
||||
"title": "Knowledge Base Management",
|
||||
"subtitle": "Phase 1 includes group, job and Dify entry management. Cleaning pipeline will be added later.",
|
||||
"toolbar": "Knowledge base tools",
|
||||
"difySettings": "Dify Settings",
|
||||
"healthCheck": "Health Check",
|
||||
"goWorkspace": "Go to Workspace",
|
||||
"groupsTitle": "Group Overview",
|
||||
"groupsEmpty": "No group yet, or knowledge base APIs are not ready.",
|
||||
"noDescription": "No description",
|
||||
"documentCount": "{count} docs",
|
||||
"updatedAt": "Updated at: ",
|
||||
"jobsTitle": "Job Queue Placeholder",
|
||||
"jobsEmpty": "No jobs. Cleaning, syncing and retry jobs will be integrated in phase 2.",
|
||||
"noJobMessage": "No job message",
|
||||
"jobMeta": "Doc: {docId} · Version: {versionId} · Progress: {progress}%",
|
||||
"running": "Running...",
|
||||
"runJob": "Run Job",
|
||||
"form": {
|
||||
"editTitle": "Edit Knowledge Base Group",
|
||||
"createTitle": "Create Knowledge Base Group",
|
||||
"editDesc": "Edit name and description of the group. List refreshes after save.",
|
||||
"createDesc": "Used to validate the knowledge base management entry and API shell in main platform.",
|
||||
"saving": "Saving...",
|
||||
"submitting": "Submitting...",
|
||||
"saveChanges": "Save Changes",
|
||||
"create": "Create Group",
|
||||
"groupName": "Group Name",
|
||||
"groupNamePlaceholder": "e.g. Finance Policy Library",
|
||||
"groupDesc": "Group Description",
|
||||
"groupDescPlaceholder": "Describe business scope or cleaning goals of this group",
|
||||
"cancelEdit": "Cancel Edit"
|
||||
},
|
||||
"deleteDialog": {
|
||||
"title": "Are you sure you want to delete?",
|
||||
"message": "This will delete knowledge base group \"{name}\". This action cannot be undone."
|
||||
},
|
||||
"msg": {
|
||||
"loadGroupsFailed": "Failed to load knowledge base groups",
|
||||
"loadJobsFailed": "Failed to load jobs",
|
||||
"nameRequired": "Please enter group name",
|
||||
"createFailed": "Creation failed",
|
||||
"created": "Group created",
|
||||
"updated": "Group updated",
|
||||
"deleteFailed": "Delete failed",
|
||||
"deleted": "Group deleted",
|
||||
"runFailed": "Job run failed",
|
||||
"runDone": "Job executed"
|
||||
}
|
||||
},
|
||||
"profile": {
|
||||
"title": "Profile",
|
||||
"personalInfo": "Personal Information",
|
||||
@@ -192,27 +112,6 @@ const messages = {
|
||||
"submitting": "Submitting...",
|
||||
"submit": "Submit"
|
||||
},
|
||||
"kbWorkspace": {
|
||||
"header": {
|
||||
"groupOverviewTitle": "Knowledge Base Group Overview",
|
||||
"workspaceTitle": "Knowledge Base Workspace",
|
||||
"groupOverviewSubtitle": "Click a group card to enter that group workspace.",
|
||||
"workspaceSubtitle": "The data cleaning and knowledge base management module has been integrated into the platform. This is the phase-1 shell page."
|
||||
},
|
||||
"actions": {
|
||||
"backToOverview": "Back to Group Overview",
|
||||
"backToWorkspace": "Back to Workspace",
|
||||
"refreshGroups": "Refresh Groups",
|
||||
"refreshDocuments": "Refresh Documents"
|
||||
},
|
||||
"overview": {
|
||||
"title": "Knowledge Base Group Overview",
|
||||
"loadingGroups": "Loading groups...",
|
||||
"createGroupTitle": "Create Knowledge Base Group",
|
||||
"createGroupDesc": "Use the knowledge base entry pattern. Click the button, fill the popup form, then create a new group.",
|
||||
"createGroupButton": "Create Knowledge Base"
|
||||
}
|
||||
},
|
||||
"theme": {
|
||||
"label": "Theme",
|
||||
"light": "Light",
|
||||
@@ -270,86 +169,6 @@ const messages = {
|
||||
"unknownError": "未知错误"
|
||||
}
|
||||
},
|
||||
"kbDifySettings": {
|
||||
"title": "Dify 设置",
|
||||
"subtitle": "管理知识库模块使用的 Dify 连接和默认同步参数。",
|
||||
"loading": "正在加载设置...",
|
||||
"save": "保存设置",
|
||||
"saving": "保存中...",
|
||||
"msg": {
|
||||
"loadFailed": "加载 Dify 设置失败",
|
||||
"saveFailed": "保存 Dify 设置失败",
|
||||
"saved": "Dify 设置已保存"
|
||||
}
|
||||
},
|
||||
"kbDifyHealth": {
|
||||
"title": "Dify 健康检查",
|
||||
"subtitle": "查看知识库模块当前的 Dify 连接情况和本地同步概况。",
|
||||
"loading": "正在检测...",
|
||||
"reachable": "可访问",
|
||||
"unreachable": "不可访问",
|
||||
"notConfigured": "未配置",
|
||||
"datasetCount": "Dataset 数量",
|
||||
"configured": "配置完成:",
|
||||
"boundGroups": "已绑定分组",
|
||||
"localSyncRecords": "本地同步记录:",
|
||||
"syncingVersions": "同步中版本",
|
||||
"syncedVersions": "已同步版本",
|
||||
"pendingSyncJobs": "待同步任务",
|
||||
"msg": {
|
||||
"loadFailed": "加载 Dify 健康状态失败"
|
||||
}
|
||||
},
|
||||
"kbAdmin": {
|
||||
"title": "知识库管理",
|
||||
"subtitle": "第一阶段先承接分组、任务和 Dify 管理入口,后续再接入清洗链路。",
|
||||
"toolbar": "知识库工具操作",
|
||||
"difySettings": "Dify 设置",
|
||||
"healthCheck": "健康检查",
|
||||
"goWorkspace": "前往工作台",
|
||||
"groupsTitle": "知识库分组概览",
|
||||
"groupsEmpty": "当前暂无分组,或知识库接口尚未联调完成。",
|
||||
"noDescription": "暂无描述",
|
||||
"documentCount": "{count} 文档",
|
||||
"updatedAt": "更新时间:",
|
||||
"jobsTitle": "任务队列占位",
|
||||
"jobsEmpty": "暂无任务。第二阶段会在这里接入清洗、同步和重试任务。",
|
||||
"noJobMessage": "暂无任务说明",
|
||||
"jobMeta": "文档:{docId} · 版本:{versionId} · 进度:{progress}%",
|
||||
"running": "执行中...",
|
||||
"runJob": "执行任务",
|
||||
"form": {
|
||||
"editTitle": "编辑知识库分组",
|
||||
"createTitle": "新建知识库分组",
|
||||
"editDesc": "修改知识库分组名称和描述,保存后会立即刷新列表。",
|
||||
"createDesc": "用于验证主平台里的知识库管理入口和基础接口壳。",
|
||||
"saving": "保存中...",
|
||||
"submitting": "提交中...",
|
||||
"saveChanges": "保存修改",
|
||||
"create": "创建分组",
|
||||
"groupName": "分组名称",
|
||||
"groupNamePlaceholder": "例如:财务制度库",
|
||||
"groupDesc": "分组描述",
|
||||
"groupDescPlaceholder": "描述该知识库分组的业务范围或清洗目标",
|
||||
"cancelEdit": "取消编辑"
|
||||
},
|
||||
"deleteDialog": {
|
||||
"title": "您确定要删除吗?",
|
||||
"message": "确认删除知识库分组“{name}”吗?"
|
||||
},
|
||||
"msg": {
|
||||
"loadGroupsFailed": "加载知识库分组失败",
|
||||
"loadJobsFailed": "加载任务列表失败",
|
||||
"nameRequired": "请输入知识库分组名称",
|
||||
"createFailed": "创建失败",
|
||||
"created": "知识库分组创建成功",
|
||||
"updated": "知识库分组已更新",
|
||||
"deleteFailed": "删除失败",
|
||||
"deleted": "知识库分组已删除",
|
||||
"runFailed": "任务执行失败",
|
||||
"runDone": "任务已执行"
|
||||
}
|
||||
},
|
||||
"profile": {
|
||||
"title": "个人资料",
|
||||
"personalInfo": "基本信息",
|
||||
@@ -411,27 +230,6 @@ const messages = {
|
||||
"submitting": "提交中...",
|
||||
"submit": "提交"
|
||||
},
|
||||
"kbWorkspace": {
|
||||
"header": {
|
||||
"groupOverviewTitle": "知识库分组概览",
|
||||
"workspaceTitle": "知识库工作台",
|
||||
"groupOverviewSubtitle": "点击分组卡片进入该分组工作台。",
|
||||
"workspaceSubtitle": "数据清洗与知识库管理模块已接入主平台,当前为第一阶段页面壳。"
|
||||
},
|
||||
"actions": {
|
||||
"backToOverview": "返回分组概览",
|
||||
"backToWorkspace": "返回工作台",
|
||||
"refreshGroups": "刷新分组",
|
||||
"refreshDocuments": "刷新文档"
|
||||
},
|
||||
"overview": {
|
||||
"title": "知识库分组概览",
|
||||
"loadingGroups": "正在加载分组...",
|
||||
"createGroupTitle": "新增知识库分组",
|
||||
"createGroupDesc": "参考知识库入口,点击按钮弹窗输入后创建新分组。",
|
||||
"createGroupButton": "新增知识库"
|
||||
}
|
||||
},
|
||||
"theme": {
|
||||
"label": "主题",
|
||||
"light": "明亮",
|
||||
@@ -489,86 +287,6 @@ const messages = {
|
||||
"unknownError": "未知錯誤"
|
||||
}
|
||||
},
|
||||
"kbDifySettings": {
|
||||
"title": "Dify 設定",
|
||||
"subtitle": "管理知識庫模組使用的 Dify 連線和預設同步參數。",
|
||||
"loading": "正在載入設定...",
|
||||
"save": "儲存設定",
|
||||
"saving": "儲存中...",
|
||||
"msg": {
|
||||
"loadFailed": "載入 Dify 設定失敗",
|
||||
"saveFailed": "儲存 Dify 設定失敗",
|
||||
"saved": "Dify 設定已儲存"
|
||||
}
|
||||
},
|
||||
"kbDifyHealth": {
|
||||
"title": "Dify 健康檢查",
|
||||
"subtitle": "查看知識庫模組目前的 Dify 連線情況和本地同步概況。",
|
||||
"loading": "正在檢測...",
|
||||
"reachable": "可訪問",
|
||||
"unreachable": "不可訪問",
|
||||
"notConfigured": "未配置",
|
||||
"datasetCount": "Dataset 數量",
|
||||
"configured": "配置完成:",
|
||||
"boundGroups": "已綁定分組",
|
||||
"localSyncRecords": "本地同步記錄:",
|
||||
"syncingVersions": "同步中版本",
|
||||
"syncedVersions": "已同步版本",
|
||||
"pendingSyncJobs": "待同步任務",
|
||||
"msg": {
|
||||
"loadFailed": "載入 Dify 健康狀態失敗"
|
||||
}
|
||||
},
|
||||
"kbAdmin": {
|
||||
"title": "知識庫管理",
|
||||
"subtitle": "第一階段先承接分組、任務和 Dify 管理入口,後續再接入清洗鏈路。",
|
||||
"toolbar": "知識庫工具操作",
|
||||
"difySettings": "Dify 設定",
|
||||
"healthCheck": "健康檢查",
|
||||
"goWorkspace": "前往工作台",
|
||||
"groupsTitle": "知識庫分組概覽",
|
||||
"groupsEmpty": "當前暫無分組,或知識庫介面尚未聯調完成。",
|
||||
"noDescription": "暫無描述",
|
||||
"documentCount": "{count} 文件",
|
||||
"updatedAt": "更新時間:",
|
||||
"jobsTitle": "任務隊列占位",
|
||||
"jobsEmpty": "暫無任務。第二階段會在這裡接入清洗、同步和重試任務。",
|
||||
"noJobMessage": "暫無任務說明",
|
||||
"jobMeta": "文檔:{docId} · 版本:{versionId} · 進度:{progress}%",
|
||||
"running": "執行中...",
|
||||
"runJob": "執行任務",
|
||||
"form": {
|
||||
"editTitle": "編輯知識庫分組",
|
||||
"createTitle": "新建知識庫分組",
|
||||
"editDesc": "修改知識庫分組名稱和描述,儲存後會立即刷新列表。",
|
||||
"createDesc": "用於驗證主平台裡的知識庫管理入口和基礎介面殼。",
|
||||
"saving": "儲存中...",
|
||||
"submitting": "提交中...",
|
||||
"saveChanges": "儲存修改",
|
||||
"create": "建立分組",
|
||||
"groupName": "分組名稱",
|
||||
"groupNamePlaceholder": "例如:財務制度庫",
|
||||
"groupDesc": "分組描述",
|
||||
"groupDescPlaceholder": "描述該知識庫分組的業務範圍或清洗目標",
|
||||
"cancelEdit": "取消編輯"
|
||||
},
|
||||
"deleteDialog": {
|
||||
"title": "您確定要刪除嗎?",
|
||||
"message": "確認刪除知識庫分組「{name}」嗎?"
|
||||
},
|
||||
"msg": {
|
||||
"loadGroupsFailed": "載入知識庫分組失敗",
|
||||
"loadJobsFailed": "載入任務列表失敗",
|
||||
"nameRequired": "請輸入知識庫分組名稱",
|
||||
"createFailed": "建立失敗",
|
||||
"created": "知識庫分組建立成功",
|
||||
"updated": "知識庫分組已更新",
|
||||
"deleteFailed": "刪除失敗",
|
||||
"deleted": "知識庫分組已刪除",
|
||||
"runFailed": "任務執行失敗",
|
||||
"runDone": "任務已執行"
|
||||
}
|
||||
},
|
||||
"profile": {
|
||||
"title": "個人資料",
|
||||
"personalInfo": "基本信息",
|
||||
@@ -630,27 +348,6 @@ const messages = {
|
||||
"submitting": "提交中...",
|
||||
"submit": "提交"
|
||||
},
|
||||
"kbWorkspace": {
|
||||
"header": {
|
||||
"groupOverviewTitle": "知識庫分組概覽",
|
||||
"workspaceTitle": "知識庫工作台",
|
||||
"groupOverviewSubtitle": "點擊分組卡片進入該分組工作台。",
|
||||
"workspaceSubtitle": "資料清洗與知識庫管理模塊已接入主平台,當前為第一階段頁面殼。"
|
||||
},
|
||||
"actions": {
|
||||
"backToOverview": "返回分組概覽",
|
||||
"backToWorkspace": "返回工作台",
|
||||
"refreshGroups": "刷新分組",
|
||||
"refreshDocuments": "刷新文檔"
|
||||
},
|
||||
"overview": {
|
||||
"title": "知識庫分組概覽",
|
||||
"loadingGroups": "正在加載分組...",
|
||||
"createGroupTitle": "新增知識庫分組",
|
||||
"createGroupDesc": "參考知識庫入口,點擊按鈕彈窗輸入後創建新分組。",
|
||||
"createGroupButton": "新增知識庫"
|
||||
}
|
||||
},
|
||||
"theme": {
|
||||
"label": "主題",
|
||||
"light": "明亮",
|
||||
@@ -708,86 +405,6 @@ const messages = {
|
||||
"unknownError": "ข้อผิดพลาดที่ไม่ทราบสาเหตุ"
|
||||
}
|
||||
},
|
||||
"kbDifySettings": {
|
||||
"title": "ตั้งค่า Dify",
|
||||
"subtitle": "จัดการการเชื่อมต่อ Dify และค่าซิงค์เริ่มต้นของโมดูลคลังความรู้",
|
||||
"loading": "กำลังโหลดการตั้งค่า...",
|
||||
"save": "บันทึกการตั้งค่า",
|
||||
"saving": "กำลังบันทึก...",
|
||||
"msg": {
|
||||
"loadFailed": "โหลดการตั้งค่า Dify ล้มเหลว",
|
||||
"saveFailed": "บันทึกการตั้งค่า Dify ล้มเหลว",
|
||||
"saved": "บันทึกการตั้งค่า Dify แล้ว"
|
||||
}
|
||||
},
|
||||
"kbDifyHealth": {
|
||||
"title": "ตรวจสุขภาพ Dify",
|
||||
"subtitle": "ดูสถานะการเชื่อมต่อ Dify และภาพรวมการซิงค์ภายในของโมดูลคลังความรู้",
|
||||
"loading": "กำลังตรวจสอบ...",
|
||||
"reachable": "เข้าถึงได้",
|
||||
"unreachable": "เข้าถึงไม่ได้",
|
||||
"notConfigured": "ยังไม่ตั้งค่า",
|
||||
"datasetCount": "จำนวน Dataset",
|
||||
"configured": "ตั้งค่าแล้ว: ",
|
||||
"boundGroups": "กลุ่มที่ผูกแล้ว",
|
||||
"localSyncRecords": "บันทึกซิงค์ภายใน: ",
|
||||
"syncingVersions": "เวอร์ชันที่กำลังซิงค์",
|
||||
"syncedVersions": "เวอร์ชันที่ซิงค์แล้ว",
|
||||
"pendingSyncJobs": "งานซิงค์ที่รออยู่",
|
||||
"msg": {
|
||||
"loadFailed": "โหลดสถานะสุขภาพ Dify ล้มเหลว"
|
||||
}
|
||||
},
|
||||
"kbAdmin": {
|
||||
"title": "จัดการคลังความรู้",
|
||||
"subtitle": "ระยะแรกครอบคลุมการจัดการกลุ่ม งาน และทางเข้า Dify ก่อน จากนั้นค่อยต่อสายงานทำความสะอาด",
|
||||
"toolbar": "เครื่องมือคลังความรู้",
|
||||
"difySettings": "ตั้งค่า Dify",
|
||||
"healthCheck": "ตรวจสุขภาพ",
|
||||
"goWorkspace": "ไปยังเวิร์กสเปซ",
|
||||
"groupsTitle": "ภาพรวมกลุ่มคลังความรู้",
|
||||
"groupsEmpty": "ยังไม่มีกลุ่ม หรือ API คลังความรู้ยังไม่พร้อม",
|
||||
"noDescription": "ไม่มีคำอธิบาย",
|
||||
"documentCount": "{count} เอกสาร",
|
||||
"updatedAt": "อัปเดตเมื่อ: ",
|
||||
"jobsTitle": "พื้นที่งานคิว",
|
||||
"jobsEmpty": "ยังไม่มีงาน ระยะถัดไปจะเชื่อมงานทำความสะอาด ซิงค์ และลองใหม่",
|
||||
"noJobMessage": "ไม่มีคำอธิบายงาน",
|
||||
"jobMeta": "เอกสาร: {docId} · เวอร์ชัน: {versionId} · ความคืบหน้า: {progress}%",
|
||||
"running": "กำลังรัน...",
|
||||
"runJob": "รันงาน",
|
||||
"form": {
|
||||
"editTitle": "แก้ไขกลุ่มคลังความรู้",
|
||||
"createTitle": "สร้างกลุ่มคลังความรู้",
|
||||
"editDesc": "แก้ไขชื่อและคำอธิบายกลุ่ม รายการจะรีเฟรชทันทีหลังบันทึก",
|
||||
"createDesc": "ใช้ตรวจสอบทางเข้าจัดการคลังความรู้และโครง API พื้นฐานในแพลตฟอร์มหลัก",
|
||||
"saving": "กำลังบันทึก...",
|
||||
"submitting": "กำลังส่ง...",
|
||||
"saveChanges": "บันทึกการแก้ไข",
|
||||
"create": "สร้างกลุ่ม",
|
||||
"groupName": "ชื่อกลุ่ม",
|
||||
"groupNamePlaceholder": "เช่น: คลังนโยบายการเงิน",
|
||||
"groupDesc": "คำอธิบายกลุ่ม",
|
||||
"groupDescPlaceholder": "อธิบายขอบเขตงานหรือเป้าหมายการทำความสะอาดของกลุ่มนี้",
|
||||
"cancelEdit": "ยกเลิกการแก้ไข"
|
||||
},
|
||||
"deleteDialog": {
|
||||
"title": "คุณแน่ใจหรือไม่ว่าต้องการลบ?",
|
||||
"message": "ยืนยันลบกลุ่มคลังความรู้ \"{name}\" หรือไม่?"
|
||||
},
|
||||
"msg": {
|
||||
"loadGroupsFailed": "โหลดกลุ่มคลังความรู้ล้มเหลว",
|
||||
"loadJobsFailed": "โหลดรายการงานล้มเหลว",
|
||||
"nameRequired": "กรุณากรอกชื่อกลุ่มคลังความรู้",
|
||||
"createFailed": "สร้างไม่สำเร็จ",
|
||||
"created": "สร้างกลุ่มคลังความรู้สำเร็จ",
|
||||
"updated": "อัปเดตกลุ่มคลังความรู้แล้ว",
|
||||
"deleteFailed": "ลบไม่สำเร็จ",
|
||||
"deleted": "ลบกลุ่มคลังความรู้แล้ว",
|
||||
"runFailed": "รันงานล้มเหลว",
|
||||
"runDone": "รันงานแล้ว"
|
||||
}
|
||||
},
|
||||
"profile": {
|
||||
"title": "โปรไฟล์",
|
||||
"personalInfo": "ข้อมูลส่วนตัว",
|
||||
@@ -849,27 +466,6 @@ const messages = {
|
||||
"submitting": "กำลังส่ง...",
|
||||
"submit": "ส่ง"
|
||||
},
|
||||
"kbWorkspace": {
|
||||
"header": {
|
||||
"groupOverviewTitle": "ภาพรวมกลุ่มคลังความรู้",
|
||||
"workspaceTitle": "เวิร์กสเปซคลังความรู้",
|
||||
"groupOverviewSubtitle": "คลิกการ์ดกลุ่มเพื่อเข้าสู่เวิร์กสเปซของกลุ่มนั้น",
|
||||
"workspaceSubtitle": "โมดูลจัดการคลังความรู้และทำความสะอาดข้อมูลได้เชื่อมเข้ากับแพลตฟอร์มแล้ว หน้านี้เป็นโครงหน้าเฟสแรก"
|
||||
},
|
||||
"actions": {
|
||||
"backToOverview": "กลับไปภาพรวมกลุ่ม",
|
||||
"backToWorkspace": "กลับไปเวิร์กสเปซ",
|
||||
"refreshGroups": "รีเฟรชกลุ่ม",
|
||||
"refreshDocuments": "รีเฟรชเอกสาร"
|
||||
},
|
||||
"overview": {
|
||||
"title": "ภาพรวมกลุ่มคลังความรู้",
|
||||
"loadingGroups": "กำลังโหลดกลุ่ม...",
|
||||
"createGroupTitle": "สร้างกลุ่มคลังความรู้",
|
||||
"createGroupDesc": "อ้างอิงรูปแบบทางเข้าคลังความรู้ คลิกปุ่ม กรอกในป๊อปอัป แล้วสร้างกลุ่มใหม่",
|
||||
"createGroupButton": "สร้างคลังความรู้"
|
||||
}
|
||||
},
|
||||
"theme": {
|
||||
"label": "ธีม",
|
||||
"light": "สว่าง",
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
"users": "User Maintenance",
|
||||
"departments": "Departments",
|
||||
"agents": "Agent Management",
|
||||
"knowledgeBase": "Knowledge Base",
|
||||
"knowledgeBase": "KB Settings",
|
||||
"announcements": "Announcements",
|
||||
"questions": "Common Questions",
|
||||
"wecom": "WeCom",
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
{
|
||||
"kbDifySettings": {
|
||||
"title": "Dify Settings",
|
||||
"subtitle": "Manage Dify connection and default sync parameters for the knowledge base module.",
|
||||
"loading": "Loading settings...",
|
||||
"save": "Save Settings",
|
||||
"saving": "Saving...",
|
||||
"msg": {
|
||||
"loadFailed": "Failed to load Dify settings",
|
||||
"saveFailed": "Failed to save Dify settings",
|
||||
"saved": "Dify settings saved"
|
||||
}
|
||||
},
|
||||
"kbDifyHealth": {
|
||||
"title": "Dify Health Check",
|
||||
"subtitle": "View Dify connectivity and local sync overview for knowledge base module.",
|
||||
"loading": "Checking...",
|
||||
"reachable": "Reachable",
|
||||
"unreachable": "Unreachable",
|
||||
"notConfigured": "Not configured",
|
||||
"datasetCount": "Dataset Count",
|
||||
"configured": "Configured: ",
|
||||
"boundGroups": "Bound Groups",
|
||||
"localSyncRecords": "Local Sync Records: ",
|
||||
"syncingVersions": "Syncing Versions",
|
||||
"syncedVersions": "Synced Versions",
|
||||
"pendingSyncJobs": "Pending Sync Jobs",
|
||||
"msg": {
|
||||
"loadFailed": "Failed to load Dify health status"
|
||||
}
|
||||
},
|
||||
"kbAdmin": {
|
||||
"title": "Knowledge Base Settings",
|
||||
"subtitle": "Configure Dify integration, manage group structure and monitor jobs. Daily content work is in Workspace → Knowledge Base.",
|
||||
"toolbar": "Knowledge base tools",
|
||||
"difySettings": "Dify Settings",
|
||||
"healthCheck": "Health Check",
|
||||
"goWorkspace": "Go to Knowledge Base",
|
||||
"groupsTitle": "Group Overview",
|
||||
"groupsEmpty": "No group yet, or knowledge base APIs are not ready.",
|
||||
"noDescription": "No description",
|
||||
"documentCount": "{count} docs",
|
||||
"updatedAt": "Updated at: ",
|
||||
"jobsTitle": "Job Queue Placeholder",
|
||||
"jobsEmpty": "No jobs. Cleaning, syncing and retry jobs will be integrated in phase 2.",
|
||||
"noJobMessage": "No job message",
|
||||
"jobMeta": "Doc: {docId} · Version: {versionId} · Progress: {progress}%",
|
||||
"running": "Running...",
|
||||
"runJob": "Run Job",
|
||||
"form": {
|
||||
"editTitle": "Edit Knowledge Base Group",
|
||||
"createTitle": "Create Knowledge Base Group",
|
||||
"editDesc": "Edit name and description of the group. List refreshes after save.",
|
||||
"createDesc": "Used to validate the knowledge base management entry and API shell in main platform.",
|
||||
"saving": "Saving...",
|
||||
"submitting": "Submitting...",
|
||||
"saveChanges": "Save Changes",
|
||||
"create": "Create Group",
|
||||
"groupName": "Group Name",
|
||||
"groupNamePlaceholder": "e.g. Finance Policy Library",
|
||||
"groupDesc": "Group Description",
|
||||
"groupDescPlaceholder": "Describe business scope or cleaning goals of this group",
|
||||
"cancelEdit": "Cancel Edit"
|
||||
},
|
||||
"deleteDialog": {
|
||||
"title": "Are you sure you want to delete?",
|
||||
"message": "This will delete knowledge base group \"{name}\". This action cannot be undone."
|
||||
},
|
||||
"msg": {
|
||||
"loadGroupsFailed": "Failed to load knowledge base groups",
|
||||
"loadJobsFailed": "Failed to load jobs",
|
||||
"nameRequired": "Please enter group name",
|
||||
"createFailed": "Creation failed",
|
||||
"created": "Group created",
|
||||
"updated": "Group updated",
|
||||
"deleteFailed": "Delete failed",
|
||||
"deleted": "Group deleted",
|
||||
"runFailed": "Job run failed",
|
||||
"runDone": "Job executed"
|
||||
}
|
||||
},
|
||||
"kbWorkspace": {
|
||||
"header": {
|
||||
"groupOverviewTitle": "Knowledge Base",
|
||||
"workspaceTitle": "Knowledge Base",
|
||||
"groupOverviewSubtitle": "Select a group to manage documents. Group structure is configured in Admin → KB Settings.",
|
||||
"workspaceSubtitle": "Upload, clean and sync documents within the selected group."
|
||||
},
|
||||
"actions": {
|
||||
"backToOverview": "Back to Group Overview",
|
||||
"backToWorkspace": "Back to Workspace",
|
||||
"refreshGroups": "Refresh Groups",
|
||||
"refreshDocuments": "Refresh Documents"
|
||||
},
|
||||
"overview": {
|
||||
"title": "Select a Group",
|
||||
"loadingGroups": "Loading groups...",
|
||||
"emptyGroups": "No groups yet. Create groups in Admin → KB Settings first.",
|
||||
"noDescription": "No description",
|
||||
"documentCount": "{count} docs",
|
||||
"updatedAt": "Updated at: "
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,13 +22,17 @@ import enAdmin from './en/admin.json';
|
||||
import zhCNAdmin from './zh-CN/admin.json';
|
||||
import zhTWAdmin from './zh-TW/admin.json';
|
||||
import thAdmin from './th/admin.json';
|
||||
import enKb from './en/kb.json';
|
||||
import zhCNKb from './zh-CN/kb.json';
|
||||
import zhTWKb from './zh-TW/kb.json';
|
||||
import thKb from './th/kb.json';
|
||||
|
||||
/** 已外置的 locale 域模块(locale → 域名 → 内容) */
|
||||
/** 已外置的 locale 域模块(locale → 域名 → 内容);auth 展平至顶层以匹配 login.* / landing.* / register.* 键路径 */
|
||||
const externalModules: Record<string, Record<string, unknown>> = {
|
||||
en: { errors: enErrors, auth: enAuth, workspace: enWorkspace, chat: enChat, admin: enAdmin },
|
||||
'zh-CN': { errors: zhCNErrors, auth: zhCNAuth, workspace: zhCNWorkspace, chat: zhCNChat, admin: zhCNAdmin },
|
||||
'zh-TW': { errors: zhTWErrors, auth: zhTWAuth, workspace: zhTWWorkspace, chat: zhTWChat, admin: zhTWAdmin },
|
||||
th: { errors: thErrors, auth: thAuth, workspace: thWorkspace, chat: thChat, admin: thAdmin },
|
||||
en: { errors: enErrors, ...enAuth, workspace: enWorkspace, chat: enChat, admin: enAdmin, ...enKb },
|
||||
'zh-CN': { errors: zhCNErrors, ...zhCNAuth, workspace: zhCNWorkspace, chat: zhCNChat, admin: zhCNAdmin, ...zhCNKb },
|
||||
'zh-TW': { errors: zhTWErrors, ...zhTWAuth, workspace: zhTWWorkspace, chat: zhTWChat, admin: zhTWAdmin, ...zhTWKb },
|
||||
th: { errors: thErrors, ...thAuth, workspace: thWorkspace, chat: thChat, admin: thAdmin, ...thKb },
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -44,4 +48,11 @@ export function mergeExternalLocales(messages: Record<string, Record<string, unk
|
||||
return merged;
|
||||
}
|
||||
|
||||
export { enErrors, zhCNErrors, zhTWErrors, thErrors, enAuth, zhCNAuth, zhTWAuth, thAuth, enWorkspace, zhCNWorkspace, zhTWWorkspace, thWorkspace, enChat, zhCNChat, zhTWChat, thChat, enAdmin, zhCNAdmin, zhTWAdmin, thAdmin };
|
||||
export {
|
||||
enErrors, zhCNErrors, zhTWErrors, thErrors,
|
||||
enAuth, zhCNAuth, zhTWAuth, thAuth,
|
||||
enWorkspace, zhCNWorkspace, zhTWWorkspace, thWorkspace,
|
||||
enChat, zhCNChat, zhTWChat, thChat,
|
||||
enAdmin, zhCNAdmin, zhTWAdmin, thAdmin,
|
||||
enKb, zhCNKb, zhTWKb, thKb,
|
||||
};
|
||||
@@ -19,7 +19,7 @@
|
||||
"users": "การจัดการผู้ใช้",
|
||||
"departments": "การจัดการแผนก",
|
||||
"agents": "การจัดการตัวแทน",
|
||||
"knowledgeBase": "การจัดการคลังความรู้",
|
||||
"knowledgeBase": "การตั้งค่าคลังความรู้",
|
||||
"announcements": "การจัดการประกาศ",
|
||||
"questions": "คำถามทั่วไป",
|
||||
"wecom": "WeCom",
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
{
|
||||
"kbDifySettings": {
|
||||
"title": "ตั้งค่า Dify",
|
||||
"subtitle": "จัดการการเชื่อมต่อ Dify และค่าซิงค์เริ่มต้นของโมดูลคลังความรู้",
|
||||
"loading": "กำลังโหลดการตั้งค่า...",
|
||||
"save": "บันทึกการตั้งค่า",
|
||||
"saving": "กำลังบันทึก...",
|
||||
"msg": {
|
||||
"loadFailed": "โหลดการตั้งค่า Dify ล้มเหลว",
|
||||
"saveFailed": "บันทึกการตั้งค่า Dify ล้มเหลว",
|
||||
"saved": "บันทึกการตั้งค่า Dify แล้ว"
|
||||
}
|
||||
},
|
||||
"kbDifyHealth": {
|
||||
"title": "ตรวจสุขภาพ Dify",
|
||||
"subtitle": "ดูสถานะการเชื่อมต่อ Dify และภาพรวมการซิงค์ภายในของโมดูลคลังความรู้",
|
||||
"loading": "กำลังตรวจสอบ...",
|
||||
"reachable": "เข้าถึงได้",
|
||||
"unreachable": "เข้าถึงไม่ได้",
|
||||
"notConfigured": "ยังไม่ตั้งค่า",
|
||||
"datasetCount": "จำนวน Dataset",
|
||||
"configured": "ตั้งค่าแล้ว: ",
|
||||
"boundGroups": "กลุ่มที่ผูกแล้ว",
|
||||
"localSyncRecords": "บันทึกซิงค์ภายใน: ",
|
||||
"syncingVersions": "เวอร์ชันที่กำลังซิงค์",
|
||||
"syncedVersions": "เวอร์ชันที่ซิงค์แล้ว",
|
||||
"pendingSyncJobs": "งานซิงค์ที่รออยู่",
|
||||
"msg": {
|
||||
"loadFailed": "โหลดสถานะสุขภาพ Dify ล้มเหลว"
|
||||
}
|
||||
},
|
||||
"kbAdmin": {
|
||||
"title": "การตั้งค่าคลังความรู้",
|
||||
"subtitle": "กำหนดค่า Dify จัดการโครงสร้างกลุ่ม และติดตามงาน งานเนื้อหาประจำวันอยู่ที่เวิร์กสเปซ → คลังความรู้",
|
||||
"toolbar": "เครื่องมือคลังความรู้",
|
||||
"difySettings": "ตั้งค่า Dify",
|
||||
"healthCheck": "ตรวจสุขภาพ",
|
||||
"goWorkspace": "ไปยังคลังความรู้",
|
||||
"groupsTitle": "ภาพรวมกลุ่มคลังความรู้",
|
||||
"groupsEmpty": "ยังไม่มีกลุ่ม หรือ API คลังความรู้ยังไม่พร้อม",
|
||||
"noDescription": "ไม่มีคำอธิบาย",
|
||||
"documentCount": "{count} เอกสาร",
|
||||
"updatedAt": "อัปเดตเมื่อ: ",
|
||||
"jobsTitle": "พื้นที่งานคิว",
|
||||
"jobsEmpty": "ยังไม่มีงาน ระยะถัดไปจะเชื่อมงานทำความสะอาด ซิงค์ และลองใหม่",
|
||||
"noJobMessage": "ไม่มีคำอธิบายงาน",
|
||||
"jobMeta": "เอกสาร: {docId} · เวอร์ชัน: {versionId} · ความคืบหน้า: {progress}%",
|
||||
"running": "กำลังรัน...",
|
||||
"runJob": "รันงาน",
|
||||
"form": {
|
||||
"editTitle": "แก้ไขกลุ่มคลังความรู้",
|
||||
"createTitle": "สร้างกลุ่มคลังความรู้",
|
||||
"editDesc": "แก้ไขชื่อและคำอธิบายกลุ่ม รายการจะรีเฟรชทันทีหลังบันทึก",
|
||||
"createDesc": "ใช้ตรวจสอบทางเข้าจัดการคลังความรู้และโครง API พื้นฐานในแพลตฟอร์มหลัก",
|
||||
"saving": "กำลังบันทึก...",
|
||||
"submitting": "กำลังส่ง...",
|
||||
"saveChanges": "บันทึกการแก้ไข",
|
||||
"create": "สร้างกลุ่ม",
|
||||
"groupName": "ชื่อกลุ่ม",
|
||||
"groupNamePlaceholder": "เช่น: คลังนโยบายการเงิน",
|
||||
"groupDesc": "คำอธิบายกลุ่ม",
|
||||
"groupDescPlaceholder": "อธิบายขอบเขตงานหรือเป้าหมายการทำความสะอาดของกลุ่มนี้",
|
||||
"cancelEdit": "ยกเลิกการแก้ไข"
|
||||
},
|
||||
"deleteDialog": {
|
||||
"title": "คุณแน่ใจหรือไม่ว่าต้องการลบ?",
|
||||
"message": "ยืนยันลบกลุ่มคลังความรู้ \"{name}\" หรือไม่?"
|
||||
},
|
||||
"msg": {
|
||||
"loadGroupsFailed": "โหลดกลุ่มคลังความรู้ล้มเหลว",
|
||||
"loadJobsFailed": "โหลดรายการงานล้มเหลว",
|
||||
"nameRequired": "กรุณากรอกชื่อกลุ่มคลังความรู้",
|
||||
"createFailed": "สร้างไม่สำเร็จ",
|
||||
"created": "สร้างกลุ่มคลังความรู้สำเร็จ",
|
||||
"updated": "อัปเดตกลุ่มคลังความรู้แล้ว",
|
||||
"deleteFailed": "ลบไม่สำเร็จ",
|
||||
"deleted": "ลบกลุ่มคลังความรู้แล้ว",
|
||||
"runFailed": "รันงานล้มเหลว",
|
||||
"runDone": "รันงานแล้ว"
|
||||
}
|
||||
},
|
||||
"kbWorkspace": {
|
||||
"header": {
|
||||
"groupOverviewTitle": "คลังความรู้",
|
||||
"workspaceTitle": "คลังความรู้",
|
||||
"groupOverviewSubtitle": "เลือกกลุ่มเพื่อจัดการเอกสาร โครงสร้างกลุ่มตั้งค่าได้ที่คอนโซลผู้ดูแล → การตั้งค่าคลังความรู้",
|
||||
"workspaceSubtitle": "อัปโหลด ทำความสะอาด และซิงค์เอกสารภายในกลุ่มที่เลือก"
|
||||
},
|
||||
"actions": {
|
||||
"backToOverview": "กลับไปรายการกลุ่ม",
|
||||
"backToWorkspace": "กลับไปเวิร์กสเปซ",
|
||||
"refreshGroups": "รีเฟรชกลุ่ม",
|
||||
"refreshDocuments": "รีเฟรชเอกสาร"
|
||||
},
|
||||
"overview": {
|
||||
"title": "เลือกกลุ่ม",
|
||||
"loadingGroups": "กำลังโหลดกลุ่ม...",
|
||||
"emptyGroups": "ยังไม่มีกลุ่ม โปรดสร้างกลุ่มที่คอนโซลผู้ดูแล → การตั้งค่าคลังความรู้ก่อน",
|
||||
"noDescription": "ไม่มีคำอธิบาย",
|
||||
"documentCount": "{count} เอกสาร",
|
||||
"updatedAt": "อัปเดตเมื่อ: "
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,7 @@
|
||||
"users": "用户管理",
|
||||
"departments": "部门管理",
|
||||
"agents": "应用管理",
|
||||
"knowledgeBase": "知识库管理",
|
||||
"knowledgeBase": "知识库配置",
|
||||
"announcements": "公告管理",
|
||||
"questions": "常用问题",
|
||||
"wecom": "企业微信",
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
{
|
||||
"kbDifySettings": {
|
||||
"title": "Dify 设置",
|
||||
"subtitle": "管理知识库模块使用的 Dify 连接和默认同步参数。",
|
||||
"loading": "正在加载设置...",
|
||||
"save": "保存设置",
|
||||
"saving": "保存中...",
|
||||
"msg": {
|
||||
"loadFailed": "加载 Dify 设置失败",
|
||||
"saveFailed": "保存 Dify 设置失败",
|
||||
"saved": "Dify 设置已保存"
|
||||
}
|
||||
},
|
||||
"kbDifyHealth": {
|
||||
"title": "Dify 健康检查",
|
||||
"subtitle": "查看知识库模块当前的 Dify 连接情况和本地同步概况。",
|
||||
"loading": "正在检测...",
|
||||
"reachable": "可访问",
|
||||
"unreachable": "不可访问",
|
||||
"notConfigured": "未配置",
|
||||
"datasetCount": "Dataset 数量",
|
||||
"configured": "配置完成:",
|
||||
"boundGroups": "已绑定分组",
|
||||
"localSyncRecords": "本地同步记录:",
|
||||
"syncingVersions": "同步中版本",
|
||||
"syncedVersions": "已同步版本",
|
||||
"pendingSyncJobs": "待同步任务",
|
||||
"msg": {
|
||||
"loadFailed": "加载 Dify 健康状态失败"
|
||||
}
|
||||
},
|
||||
"kbAdmin": {
|
||||
"title": "知识库配置",
|
||||
"subtitle": "配置 Dify 集成、管理分组结构与任务队列。日常文档维护请在工作台「知识库」操作。",
|
||||
"toolbar": "知识库工具操作",
|
||||
"difySettings": "Dify 设置",
|
||||
"healthCheck": "健康检查",
|
||||
"goWorkspace": "前往知识库",
|
||||
"groupsTitle": "知识库分组概览",
|
||||
"groupsEmpty": "当前暂无分组,或知识库接口尚未联调完成。",
|
||||
"noDescription": "暂无描述",
|
||||
"documentCount": "{count} 文档",
|
||||
"updatedAt": "更新时间:",
|
||||
"jobsTitle": "任务队列占位",
|
||||
"jobsEmpty": "暂无任务。第二阶段会在这里接入清洗、同步和重试任务。",
|
||||
"noJobMessage": "暂无任务说明",
|
||||
"jobMeta": "文档:{docId} · 版本:{versionId} · 进度:{progress}%",
|
||||
"running": "执行中...",
|
||||
"runJob": "执行任务",
|
||||
"form": {
|
||||
"editTitle": "编辑知识库分组",
|
||||
"createTitle": "新建知识库分组",
|
||||
"editDesc": "修改知识库分组名称和描述,保存后会立即刷新列表。",
|
||||
"createDesc": "用于验证主平台里的知识库管理入口和基础接口壳。",
|
||||
"saving": "保存中...",
|
||||
"submitting": "提交中...",
|
||||
"saveChanges": "保存修改",
|
||||
"create": "创建分组",
|
||||
"groupName": "分组名称",
|
||||
"groupNamePlaceholder": "例如:财务制度库",
|
||||
"groupDesc": "分组描述",
|
||||
"groupDescPlaceholder": "描述该知识库分组的业务范围或清洗目标",
|
||||
"cancelEdit": "取消编辑"
|
||||
},
|
||||
"deleteDialog": {
|
||||
"title": "您确定要删除吗?",
|
||||
"message": "确认删除知识库分组“{name}”吗?"
|
||||
},
|
||||
"msg": {
|
||||
"loadGroupsFailed": "加载知识库分组失败",
|
||||
"loadJobsFailed": "加载任务列表失败",
|
||||
"nameRequired": "请输入知识库分组名称",
|
||||
"createFailed": "创建失败",
|
||||
"created": "知识库分组创建成功",
|
||||
"updated": "知识库分组已更新",
|
||||
"deleteFailed": "删除失败",
|
||||
"deleted": "知识库分组已删除",
|
||||
"runFailed": "任务执行失败",
|
||||
"runDone": "任务已执行"
|
||||
}
|
||||
},
|
||||
"kbWorkspace": {
|
||||
"header": {
|
||||
"groupOverviewTitle": "知识库",
|
||||
"workspaceTitle": "知识库",
|
||||
"groupOverviewSubtitle": "选择分组进入文档维护。分组结构请在管理控制台「知识库配置」中管理。",
|
||||
"workspaceSubtitle": "在所选分组内上传、清洗与同步文档。"
|
||||
},
|
||||
"actions": {
|
||||
"backToOverview": "返回分组列表",
|
||||
"backToWorkspace": "返回工作台",
|
||||
"refreshGroups": "刷新分组",
|
||||
"refreshDocuments": "刷新文档"
|
||||
},
|
||||
"overview": {
|
||||
"title": "选择分组",
|
||||
"loadingGroups": "正在加载分组...",
|
||||
"emptyGroups": "暂无分组,请先在管理控制台「知识库配置」中创建分组。",
|
||||
"noDescription": "暂无描述",
|
||||
"documentCount": "{count} 文档",
|
||||
"updatedAt": "更新时间:"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -86,7 +86,7 @@
|
||||
"profile": "个人中心",
|
||||
"admin": "管理后台",
|
||||
"applications": "应用管理",
|
||||
"knowledgeBase": "知识库管理",
|
||||
"knowledgeBase": "知识库",
|
||||
"scheduleRuns": "排程记录",
|
||||
"shippingNotice": "货代发货",
|
||||
"feedback": "意见反馈",
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
"users": "用戶管理",
|
||||
"departments": "部門管理",
|
||||
"agents": "應用管理",
|
||||
"knowledgeBase": "知識庫管理",
|
||||
"knowledgeBase": "知識庫配置",
|
||||
"announcements": "公告管理",
|
||||
"questions": "常用問題",
|
||||
"wecom": "企業微信",
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
{
|
||||
"kbDifySettings": {
|
||||
"title": "Dify 設定",
|
||||
"subtitle": "管理知識庫模組使用的 Dify 連線和預設同步參數。",
|
||||
"loading": "正在載入設定...",
|
||||
"save": "儲存設定",
|
||||
"saving": "儲存中...",
|
||||
"msg": {
|
||||
"loadFailed": "載入 Dify 設定失敗",
|
||||
"saveFailed": "儲存 Dify 設定失敗",
|
||||
"saved": "Dify 設定已儲存"
|
||||
}
|
||||
},
|
||||
"kbDifyHealth": {
|
||||
"title": "Dify 健康檢查",
|
||||
"subtitle": "查看知識庫模組目前的 Dify 連線情況和本地同步概況。",
|
||||
"loading": "正在檢測...",
|
||||
"reachable": "可訪問",
|
||||
"unreachable": "不可訪問",
|
||||
"notConfigured": "未配置",
|
||||
"datasetCount": "Dataset 數量",
|
||||
"configured": "配置完成:",
|
||||
"boundGroups": "已綁定分組",
|
||||
"localSyncRecords": "本地同步記錄:",
|
||||
"syncingVersions": "同步中版本",
|
||||
"syncedVersions": "已同步版本",
|
||||
"pendingSyncJobs": "待同步任務",
|
||||
"msg": {
|
||||
"loadFailed": "載入 Dify 健康狀態失敗"
|
||||
}
|
||||
},
|
||||
"kbAdmin": {
|
||||
"title": "知識庫配置",
|
||||
"subtitle": "配置 Dify 整合、管理分組結構與任務隊列。日常文檔維護請在工作台「知識庫」操作。",
|
||||
"toolbar": "知識庫工具操作",
|
||||
"difySettings": "Dify 設定",
|
||||
"healthCheck": "健康檢查",
|
||||
"goWorkspace": "前往知識庫",
|
||||
"groupsTitle": "知識庫分組概覽",
|
||||
"groupsEmpty": "當前暫無分組,或知識庫介面尚未聯調完成。",
|
||||
"noDescription": "暫無描述",
|
||||
"documentCount": "{count} 文件",
|
||||
"updatedAt": "更新時間:",
|
||||
"jobsTitle": "任務隊列占位",
|
||||
"jobsEmpty": "暫無任務。第二階段會在這裡接入清洗、同步和重試任務。",
|
||||
"noJobMessage": "暫無任務說明",
|
||||
"jobMeta": "文檔:{docId} · 版本:{versionId} · 進度:{progress}%",
|
||||
"running": "執行中...",
|
||||
"runJob": "執行任務",
|
||||
"form": {
|
||||
"editTitle": "編輯知識庫分組",
|
||||
"createTitle": "新建知識庫分組",
|
||||
"editDesc": "修改知識庫分組名稱和描述,儲存後會立即刷新列表。",
|
||||
"createDesc": "用於驗證主平台裡的知識庫管理入口和基礎介面殼。",
|
||||
"saving": "儲存中...",
|
||||
"submitting": "提交中...",
|
||||
"saveChanges": "儲存修改",
|
||||
"create": "建立分組",
|
||||
"groupName": "分組名稱",
|
||||
"groupNamePlaceholder": "例如:財務制度庫",
|
||||
"groupDesc": "分組描述",
|
||||
"groupDescPlaceholder": "描述該知識庫分組的業務範圍或清洗目標",
|
||||
"cancelEdit": "取消編輯"
|
||||
},
|
||||
"deleteDialog": {
|
||||
"title": "您確定要刪除嗎?",
|
||||
"message": "確認刪除知識庫分組「{name}」嗎?"
|
||||
},
|
||||
"msg": {
|
||||
"loadGroupsFailed": "載入知識庫分組失敗",
|
||||
"loadJobsFailed": "載入任務列表失敗",
|
||||
"nameRequired": "請輸入知識庫分組名稱",
|
||||
"createFailed": "建立失敗",
|
||||
"created": "知識庫分組建立成功",
|
||||
"updated": "知識庫分組已更新",
|
||||
"deleteFailed": "刪除失敗",
|
||||
"deleted": "知識庫分組已刪除",
|
||||
"runFailed": "任務執行失敗",
|
||||
"runDone": "任務已執行"
|
||||
}
|
||||
},
|
||||
"kbWorkspace": {
|
||||
"header": {
|
||||
"groupOverviewTitle": "知識庫",
|
||||
"workspaceTitle": "知識庫",
|
||||
"groupOverviewSubtitle": "選擇分組進入文檔維護。分組結構請在管理控制台「知識庫配置」中管理。",
|
||||
"workspaceSubtitle": "在所選分組內上傳、清洗與同步文檔。"
|
||||
},
|
||||
"actions": {
|
||||
"backToOverview": "返回分組列表",
|
||||
"backToWorkspace": "返回工作台",
|
||||
"refreshGroups": "刷新分組",
|
||||
"refreshDocuments": "刷新文檔"
|
||||
},
|
||||
"overview": {
|
||||
"title": "選擇分組",
|
||||
"loadingGroups": "正在加載分組...",
|
||||
"emptyGroups": "暫無分組,請先在管理控制台「知識庫配置」中建立分組。",
|
||||
"noDescription": "暫無描述",
|
||||
"documentCount": "{count} 文檔",
|
||||
"updatedAt": "更新時間:"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -86,7 +86,7 @@
|
||||
"profile": "個人中心",
|
||||
"admin": "管理後台",
|
||||
"applications": "應用管理",
|
||||
"knowledgeBase": "知識庫管理",
|
||||
"knowledgeBase": "知識庫",
|
||||
"scheduleRuns": "排程記錄",
|
||||
"feedback": "意見反饋",
|
||||
"updates": "最近更新",
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user