diff --git a/docs/refactor/frontend_architecture_refactor.md b/docs/refactor/frontend_architecture_refactor.md
index fa43c5c3..0ffa783b 100644
--- a/docs/refactor/frontend_architecture_refactor.md
+++ b/docs/refactor/frontend_architecture_refactor.md
@@ -129,7 +129,7 @@ frontend/src/
│ │ │ ├── announcements/
│ │ │ ├── questions/
│ │ │ ├── wecom/
-│ │ │ ├── schedules/
+│ │ │ ├── schedules/ # types/utils + context + panel/overlays(见 §10.5)
│ │ │ └── knowledge-base/
│ │ └── components/
│ │ └── AdminNav.vue
@@ -144,7 +144,8 @@ frontend/src/
│ │ ├── useKbWorkspace.ts # 编排入口
│ │ └── kb-workspace/ # state / computed / data / pathUpload / documents / modals
│ ├── views/
-│ │ └── KbWorkspaceView.vue # 作业面壳(模板 + 弹窗)
+│ │ ├── KbWorkspaceView.vue # 作业面主内容壳
+│ │ └── components/KbWorkspaceOverlays.vue # 弹窗层
│ └── components/ # 治理面:KbAdminPanel、Dify*Dialog
│
├── locales/ # i18n 按语言 + 业务域拆分
@@ -330,7 +331,7 @@ flowchart TB
| 项 | 说明 |
|----|------|
-| API | `features/kb/api/kb.api.ts`(`src/api/kb.ts` deprecated 转发) |
+| API | `features/kb/api/kb.api.ts`(`src/api/kb.ts` 已删除) |
| 作业面编排 | `useKbWorkspace` + `kb-workspace/*` 子 composable |
| 权限 | `hasKnowledgeBaseAccess` / 作业面批量操作:`role === 'admin'` |
| i18n | `locales/{en,zh-CN,zh-TW,th}/kb.json` |
@@ -509,6 +510,8 @@ features/admin/modules/
└── composables/use*Admin.ts + components/
```
+**schedules/**(2026-06 瘦身,详见 §10.5):`SchedulesPage.vue` 薄壳 + `useSchedulesAdmin` + `schedule-admin/*` + `schedules.context` + 6 个子组件(Header / Overview / Workbench / Overlays / TestRun / CreateEdit)。
+
### 9.3 构建验证
`npm run build` 通过;`AdminView.vue` 已删除。
@@ -565,9 +568,27 @@ Phase 2 Chat 目标:将原 `views/ChatView.vue`(~5500 行)拆为 feature
- ~~KB 域收口~~ → 见 §16
- ~~`locales/` 按域拆分~~ → 见 §15.2
+### 10.5 Admin Schedules 模块瘦身(2026-06,已实现)
+
+参照 KB 作业面模式,将原 `SchedulesPage.vue`(~1200 行)与 `useSchedulesAdmin.ts`(~1100 行)拆为薄壳 + provide/inject 子组件。
+
+| 项 | 路径 / 约行数 |
+|----|---------------|
+| 页面壳层 | `SchedulesPage.vue`(~26 行:`reactive(useSchedulesAdmin())` + `provide` + 4 子组件) |
+| 编排入口 | `composables/useSchedulesAdmin.ts`(~28 行,组合子模块) |
+| 子 composable | `composables/schedule-admin/`:`state`(~145)、`useScheduleAdminLookups`(~40)、`useScheduleAdminList`(~124)、`useScheduleAdminRuns`(~196)、`useScheduleAdminForm`(~329)、`useScheduleAdminTestRun`(~95) |
+| provide/inject | `composables/schedules.context.ts`(~26 行) |
+| 类型与默认工厂 | `types/schedule-admin.types.ts`(~127 行) |
+| 纯函数 | `utils/schedule-cron.utils.ts`、`utils/schedule-format.utils.ts`、`utils/schedule-form-payload.utils.ts` |
+| 子组件 | `SchedulePageHeader`(~44)、`ScheduleOverviewPanel`(~146)、`ScheduleWorkbenchPanel`(~329)、`SchedulesPageOverlays`(~24)、`ScheduleTestRunDialog`(~175)、`ScheduleCreateEditModal`(~525) |
+
+子 panel / overlays 通过 `useSchedulesAdminContext()` inject,无 props 透传。`npm run build` 通过。
+
+**i18n(2026-06)**:`ScheduleCreateEditModal`、`ScheduleTestRunDialog`、`ScheduleWorkbenchPanel`(Dify 快照区)硬编码中文已外置至 `locales/*/admin.json`(`schedule.form.*`、`schedule.difySnapshot.*`、`schedule.testRun.*`);合并脚本 `frontend/scripts/merge-schedule-form-i18n.mjs`。顺带修复创建按钮误用 `admin.schedule.form.admin.createSchedule` 键。
+
---
-## 11. Phase 3 Workspace 模块(部分实现)
+## 11. Phase 3 Workspace 模块(已实现)
Phase 3 目标:将原 `WorkspaceView.vue` 拆为独立 feature,路由 `/workspace/*`。
@@ -587,7 +608,7 @@ Phase 3 目标:将原 `WorkspaceView.vue` 拆为独立 feature,路由 `/work
| 页面 | 现状 |
|------|------|
| `KnowledgeBasePage.vue` | ✅ 嵌入 `features/kb/views/KbWorkspaceView.vue`(`embedded`) |
-| `ShippingNoticePage.vue` | 嵌入 `src/views/ShippingNoticeView.vue`(待迁入 workspace) |
+| `ShippingNoticePage.vue` | ✅ 嵌入 `features/workspace/views/ShippingNoticeView.vue`(`embedded`) |
### 11.3 路由
@@ -595,7 +616,7 @@ Phase 3 目标:将原 `WorkspaceView.vue` 拆为独立 feature,路由 `/work
/workspace/applications → HomePage
/workspace/profile → ProfilePage
/workspace/schedule-runs → ScheduleRunsPage
-/workspace/shipping-notice → ShippingNoticePage(legacy 嵌入)
+/workspace/shipping-notice → ShippingNoticePage(嵌入 ShippingNoticeView)
/workspace/knowledge-base → KnowledgeBasePage(legacy 嵌入)
/workspace/history → chat/history/HistoryPage
```
@@ -619,7 +640,9 @@ 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` | `features/kb/api/kb.api.ts` | ✅ deprecated 转发保留 |
+| `src/api/toolRunProgress.ts` | `features/chat/api/toolRunProgress.api.ts` | ✅ |
+| 工具进度类型 | `features/chat/types/tool-run-progress.types.ts` | ✅ |
+| `src/api/kb.ts` | `features/kb/api/kb.api.ts` | ✅(deprecated 转发已删除) |
### 12.2 新代码 import 规范
@@ -647,9 +670,8 @@ import { getWorkspaceShippingTask } from '@/features/chat';
### 12.3 兼容策略
-- ~~`src/api/{client,admin,schedule,shippingNotice,chat,user}.ts` deprecated 转发~~ → **已删除**(2026-06-11)
-- **新代码必须使用 feature / shared 路径**
-- `src/api/kb.ts` 保留 deprecated 转发,新代码使用 `@/features/kb/api/kb.api`
+- ~~`src/api/{client,admin,schedule,shippingNotice,chat,user,toolRunProgress,kb}.ts` deprecated 转发~~ → **已全部删除**(2026-06-11)
+- **`src/api/` 目录已清空**;新代码必须使用 `@/features/*/api/*` 或 `@/shared/api/client`
### 12.4 构建验证
@@ -658,7 +680,7 @@ import { getWorkspaceShippingTask } from '@/features/chat';
### 12.5 下一步
- ~~KB API 迁入 `features/kb/api/kb.api.ts`~~ → 已完成(见 §16)
-- ~~清理 deprecated `src/api/*` 转发~~ → 已完成(仅保留 `kb.ts`)
+- ~~清理 deprecated `src/api/*` 转发~~ → 已完成(`src/api/` 已清空)
- `locales/` 按域拆分 → 见 §15
---
@@ -736,26 +758,25 @@ import { useTheme, requestJson } from '@/shared';
| 删除 `src/composables/` | 7 个 deprecated 转发已移除 |
| 删除 `src/utils/` | 6 个 deprecated 转发已移除 |
| 删除 `src/styles/` | 3 个 CSS 转发已移除 |
-| 删除 `src/api/*`(除 kb) | client/admin/chat/user/schedule/shippingNotice 转发已移除 |
-| 删除 `src/router/index.ts` | 全仓已改用 `@/app/router` |
-| 修复 `api/kb.ts` | 改为引用 `@/shared/api/client` |
+| 删除 `src/api/*` | 全部转发已移除,`src/api/` 目录已清空 |
| 移除 `axios` 依赖 | 代码未使用,已从 `package.json` 删除 |
| `main.ts` / `App.vue` | 保留在 `src/` 根(见 §7.2 约定) |
### 15.2 i18n 按域拆分(已完成)
-**现状**:`src/i18n.ts` 仅保留 `createI18n` 注册与 locale 默认值;各业务域 messages 均已外置 JSON。
+**现状**:`src/i18n.ts` 仅保留 `createI18n` 注册与空 locale 骨架;**全部** messages 均已外置 JSON。
**已完成 ✅**
| 域 | 路径 |
|----|------|
| `errors` | `locales/{en,zh-CN,zh-TW,th}/errors.json` |
-| `auth` | `locales/{en,zh-CN,zh-TW,th}/auth.json` |
+| `auth` | `locales/{en,zh-CN,zh-TW,th}/auth.json`(展平合并:`login.*` 等) |
| `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` |
+| `kb` | `locales/{en,zh-CN,zh-TW,th}/kb.json`(展平合并:`kbDifySettings.*` 等) |
+| `common` / `scheduleRuns` / `filePreview` / `profile` / `feedback` / `theme` | 同上四语言 JSON |
| 合并入口 | `locales/index.ts` → `mergeExternalLocales()` |
`i18n.ts` 在 `createI18n` 前调用 `mergeExternalLocales(messages)`,四语言外置域与拆分前行为一致。
@@ -771,7 +792,13 @@ src/locales/
│ ├── workspace.json
│ ├── chat.json
│ ├── admin.json
-│ └── kb.json
+│ ├── kb.json
+│ ├── common.json
+│ ├── scheduleRuns.json
+│ ├── filePreview.json
+│ ├── profile.json
+│ ├── feedback.json
+│ └── theme.json
```
**迁移步骤**(均已完成):
@@ -782,41 +809,55 @@ src/locales/
4. ~~拆 `chat.*` → `chat.json`~~ ✅
5. ~~拆 `admin.*` → `admin.json`~~ ✅
6. ~~拆 `kb.*` → `kb.json`(四语言)~~ ✅
-7. 每步 `npm run build` + 四语言 spot check
-8. `i18n.ts` 仅保留 `createI18n` 注册与 locale 默认值
+7. ~~拆共享域 `common` / `scheduleRuns` / `filePreview` / `profile` / `feedback` / `theme`~~ ✅
+8. 每步 `npm run build` + 四语言 spot check
+9. `i18n.ts` 仅保留 `createI18n` 注册与 locale 骨架
**注意**:AGENTS.md 要求四语言同步;拆分时用脚本或 CI 校验 key 对齐。
-### 15.3 待办:清理 `src/views/`(优先级:低)
+### 15.3 清理 `src/views/`(已完成 ✅)
-| 文件 | 引用方 | 处理方式 |
-|------|--------|----------|
-| ~~`KbWorkspaceView.vue`~~ | — | ✅ 已迁入 `features/kb/views/`(见 §16) |
-| `ShippingNoticeView.vue` (~250 行) | `workspace/shipping-notice` | 迁入 `features/workspace/pages/` 或独立 feature |
+| 文件 | 状态 |
+|------|------|
+| ~~`KbWorkspaceView.vue`~~ | ✅ 已迁入 `features/kb/views/`(见 §16) |
+| ~~`ShippingNoticeView.vue`~~ | ✅ 已迁入 `features/workspace/views/` |
-### 15.4 KB 域收口(已实现,见 §16)
+`src/views/`、`src/api/` 空目录已删除。
+
+### 15.4 deprecated 遗留清理(已完成 ✅)
+
+| 项 | 状态 |
+|----|------|
+| `shared/components/kb/*` | 已删除(canonical:`features/kb/components/*`) |
+| `shared/composables/useChat.ts` | 已删除(canonical:`features/chat/composables/useChat`) |
+| `features/workspace/pages/HistoryPage.vue` | 已删除(canonical:`chat/history/HistoryPage`) |
+| `features/workspace/composables/useWorkspaceHistory.ts` | 已删除 |
+| `src/api/toolRunProgress.ts` | 已迁入 `features/chat/api/toolRunProgress.api.ts` |
+| `src/api/kb.ts` | 已删除 |
+
+### 15.5 KB 域收口(已实现,见 §16)
- ~~`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 可选优化(非必须)
+### 15.6 可选优化(非必须)
| 项 | 说明 |
|----|------|
-| `index.html` `lang="zh-CN"` | 主语言为中文,利于 SEO/无障碍 |
-| `App.vue` 文件头注释 | 与项目注释规范一致 |
+| ~~`index.html` `lang="zh-CN"`~~ | ✅ |
+| ~~`App.vue` 文件头注释~~ | ✅ |
| `frontend/.env.development` | 若需纯前端多环境 API 地址,再用 `VITE_*` |
| Vite 8 beta → stable | 关注正式版发布后升级 |
-### 15.6 推荐执行顺序
+### 15.7 推荐执行顺序
```text
✅ Phase A:删 deprecated 转发 + 去 axios
✅ Phase B:i18n 拆 locales/(errors → auth → workspace → chat → admin → kb)
-→ Phase C:ShippingNoticeView 迁入 workspace
-✅ Phase D:KB 域收口(治理/作业面拆分 + composable 拆分)→ 见 §16
+✅ Phase C:ShippingNoticeView 迁入 workspace
+✅ Phase E:API 遗留清理 + deprecated 文件删除 + i18n 共享域外置
```
---
@@ -857,7 +898,8 @@ features/kb/
│ ├── useKbWorkspacePathUpload.ts
│ ├── useKbWorkspaceDocuments.ts
│ └── useKbWorkspaceModals.ts
-├── views/KbWorkspaceView.vue # 模板壳(~1160 行,逻辑在 composable)
+├── views/KbWorkspaceView.vue # 主内容壳(~550 行)
+├── components/KbWorkspaceOverlays.vue # 弹窗层(~635 行)
└── components/
├── KbAdminPanel.vue
├── DifySettingsDialog.vue
@@ -868,7 +910,7 @@ features/kb/
| 项 | 说明 |
|----|------|
-| API 迁入 | `features/kb/api/kb.api.ts`;`src/api/kb.ts` deprecated 转发 |
+| API 迁入 | `features/kb/api/kb.api.ts`(`src/api/kb.ts` 已删除) |
| 组件迁入 | `KbAdminPanel`、`DifySettingsDialog`、`DifyHealthDialog` |
| 作业面拆分 | 类型/纯函数 utils + `useKbWorkspace` 子 composable |
| 视图薄壳 | `KbWorkspaceView.vue` script 仅 `useKbWorkspace({ embedded })` |
@@ -884,13 +926,13 @@ features/kb/
| 项 | 说明 |
|----|------|
-| 作业面 View 继续瘦身 | 弹窗块可抽为 `features/kb/components/*Modal.vue`,目标 View < 300 行 |
-| 作业面 i18n 全覆盖 | 模板内仍有部分硬编码中文(批量操作按钮等),需迁入 `kb.json` |
-| 删除 `src/api/kb.ts` | 确认全仓无 `@/api/kb` import 后移除 deprecated 转发 |
+| 作业面 View 继续瘦身 | ✅ 弹窗已抽至 `KbWorkspaceOverlays.vue`(View ~550 行 → 主内容壳;Overlays ~620 行);文档列表区可继续拆 panel |
+| 作业面 i18n 全覆盖 | ✅ 模板 + utils/composable 运行时文案已迁入 `kb.json`(`kbWorkspace.*` 四语言);`kb.api.ts` 错误 fallback 仍为中文(低优先级) |
+| 删除 `src/api/kb.ts` | ✅ 全仓已无 `@/api/kb` import,deprecated 转发已移除 |
### 16.6 下一步(全项目)
-- `ShippingNoticeView` 迁入 workspace → §15.3 Phase C
+- ~~`ShippingNoticeView` 迁入 workspace~~ → §15.3 ✅
- Chat / admin 域内低优先级待办 → §10.3
---
diff --git a/frontend/index.html b/frontend/index.html
index 7bc203dd..14c766e8 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -1,5 +1,5 @@
-
+
diff --git a/frontend/scripts/merge-kb-runtime-i18n.mjs b/frontend/scripts/merge-kb-runtime-i18n.mjs
new file mode 100644
index 00000000..c52d9f65
--- /dev/null
+++ b/frontend/scripts/merge-kb-runtime-i18n.mjs
@@ -0,0 +1,406 @@
+/**
+ * scripts/merge-kb-runtime-i18n.mjs
+ * 合并 kbWorkspace 运行时文案(status / workflow / errors / msg)至各语言 kb.json
+ */
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const localesRoot = path.resolve(__dirname, '../src/locales');
+
+const patches = {
+ en: {
+ status: {
+ draft: 'Pending upload',
+ uploaded: 'Uploaded',
+ processing: 'Cleaning',
+ cleaned: 'Cleaned',
+ ready: 'Ready',
+ synced: 'Synced',
+ syncing: 'Syncing',
+ failed: 'Failed',
+ queued: 'Queued',
+ running: 'Running',
+ success: 'Success',
+ cancelled: 'Cancelled',
+ idle: 'Not started',
+ done: 'Completed',
+ pendingClean: 'Pending clean',
+ pendingSync: 'Pending sync',
+ cleaning: 'Cleaning',
+ uploading: 'Uploading',
+ unknown: 'Unknown status',
+ unnamedDocument: 'Untitled document',
+ },
+ workflow: { upload: 'Upload', clean: 'Clean', sync: 'Sync' },
+ failureModal: {
+ uploadData: 'Upload failures',
+ cleanData: 'Clean failures',
+ syncData: 'Sync failures',
+ generic: 'Failure data',
+ stageUploadFailed: 'Upload failed',
+ stageCleanFailed: 'Clean failed',
+ stageSyncFailed: 'Sync failed',
+ },
+ errors: {
+ unreadableClean: 'Historical failure reason is unreadable. Click "Clean data" to retry.',
+ unreadableSync: 'Historical sync failure is unreadable. Please retry sync.',
+ unreadableUpload: 'Historical upload failure is unreadable. Please re-upload.',
+ legacyCleanRecovered: 'Legacy clean task was recovered manually. Click "Clean data" to retry.',
+ sourceFileNotFound: 'Source file not found. Re-upload before cleaning.',
+ cleanTimeout: 'Clean timed out. Retry later or check if the source file is corrupted.',
+ duplicateFile: 'Upload failed: file already exists.',
+ apiRequestFailed: 'Knowledge base API request failed.',
+ localFolder: 'Local folder',
+ fileFallback: 'File {index}',
+ uploadFailed: 'Upload failed',
+ },
+ msg: {
+ operationFailed: 'Operation failed',
+ loadGroupsFailed: 'Failed to load groups',
+ loadDocumentsFailed: 'Failed to load documents',
+ loadJobsFailed: 'Failed to load jobs',
+ readSourceFailed: 'Failed to read source file',
+ noVersion: 'No version',
+ readMarkdownFailed: 'Failed to read cleaned Markdown',
+ saveMarkdownFailed: 'Failed to save Markdown',
+ markdownSaved: 'Cleaned Markdown saved',
+ deleteDocumentFailed: 'Failed to delete document',
+ documentDeleted: 'Document deleted',
+ selectDocumentsToSync: 'Please select documents to sync',
+ batchSyncResult: 'Batch sync submitted: {success} succeeded, {fail} failed. {detail}',
+ batchSyncSuccess: 'Batch sync submitted: {success} succeeded',
+ selectDocumentsToClean: 'Please select documents to clean',
+ noDocumentsToClean: 'No selected documents can be cleaned',
+ batchCleanResult: 'Batch clean submitted: {success} succeeded, {fail} failed. {detail}',
+ batchCleanSuccess: 'Batch clean submitted: {success} succeeded',
+ selectDocumentsToDelete: 'Please select documents to delete',
+ batchDeleteResult: 'Batch delete completed: {success} succeeded, {fail} failed. {detail}',
+ batchDeleteSuccess: 'Batch delete completed: {success} succeeded',
+ reselectFile: 'Please re-select a file for "{name}"',
+ recleanFailed: 'Re-clean failed',
+ recleanSubmitted: 'Re-clean submitted: {name}',
+ resyncFailed: 'Re-sync failed: {detail}',
+ resyncSubmitted: 'Re-sync submitted: {name}',
+ processingFile: 'Processing file...',
+ uploadFailed: 'File upload failed',
+ versionUploaded: 'Version "{file}" uploaded, clean queued',
+ uploadingProgress: 'Uploading {current}/{total}: {file}',
+ createDocumentFailed: 'Failed to create document',
+ uploadVersionFailed: 'Failed to upload version',
+ uploadCleanupFailed: 'Upload failed and empty document could not be removed ({detail})',
+ uploadSummary: 'Upload done: {success} succeeded, {fail} failed. {detail}',
+ uploadAllSuccess: 'Uploaded {count} file(s), clean tasks queued',
+ syncDifyFailed: 'Sync to Dify failed: {detail}',
+ syncDifyFailedGeneric: 'Sync to Dify failed',
+ syncSubmitted: 'Sync task submitted',
+ pathUploadBusy: 'Upload in progress, please wait',
+ selectGroupFirst: 'Please select a group first',
+ selectPathFiles: 'Please select at least one local folder or file',
+ createPathJobFailed: 'Failed to create path upload job',
+ pathStageFailed: 'Path file staging failed',
+ pathUploadDone: 'Path files uploaded and clean submitted',
+ deletePathFileConfirm: 'Delete path file "{path}"?',
+ deletePathFileFailed: 'Failed to delete path file',
+ pathRecordDeletedWithDoc: 'Path record deleted with document',
+ pathRecordDeleted: 'Path record deleted',
+ selectPathFilesToDelete: 'Please select files to delete',
+ batchDeletePathConfirm: 'Delete {count} selected path file(s)?',
+ batchDeletePathResult: 'Batch delete: {success} succeeded, {fail} failed. {detail}',
+ batchDeletePathSuccess: 'Batch delete: {success} succeeded',
+ retryPathFailed: 'Failed to retry files',
+ retryPathOne: 'Failed file resubmitted',
+ retryPathAll: 'Failed files resubmitted',
+ pathUploadProgress: 'Path upload: total {total}, pending {pending}, uploaded {uploaded}, failed {failed}',
+ deleteDocumentConfirm: 'Delete document "{name}"?',
+ batchDeleteDocumentsConfirm: 'Delete {count} selected document(s)? Dify documents will also be removed.',
+ markdownFailedWithReason: 'Clean failed, no Markdown yet. Reason: {reason}',
+ markdownFailedRetry: 'Clean failed, no Markdown yet. Please re-clean.',
+ markdownProcessing: 'Document is being cleaned, no Markdown yet.',
+ markdownPendingClean: 'Document pending clean, no Markdown yet.',
+ markdownNotGenerated: 'No Markdown generated for this document yet.',
+ },
+ },
+ 'zh-CN': {
+ status: {
+ draft: '待上传', uploaded: '已上传', processing: '清洗中', cleaned: '已清洗', ready: '已就绪',
+ synced: '已同步', syncing: '同步中', failed: '失败', queued: '排队中', running: '进行中',
+ success: '成功', cancelled: '已取消', idle: '未开始', done: '已完成', pendingClean: '待清洗',
+ pendingSync: '待同步', cleaning: '清洗中', uploading: '上传中', unknown: '未知状态', unnamedDocument: '未命名文档',
+ },
+ workflow: { upload: '上传', clean: '清洗', sync: '同步' },
+ failureModal: {
+ uploadData: '上传失败数据', cleanData: '清洗失败数据', syncData: '同步失败数据', generic: '失败数据',
+ stageUploadFailed: '上传失败', stageCleanFailed: '清洗失败', stageSyncFailed: '同步失败',
+ },
+ errors: {
+ unreadableClean: '历史失败任务原因不可读,请重新点击“清洗数据”发起清洗',
+ unreadableSync: '历史同步失败原因不可读,请重新发起同步',
+ unreadableUpload: '历史上传失败原因不可读,请重新上传文件',
+ legacyCleanRecovered: '历史遗留清洗任务已人工回收,请重新点击“清洗数据”发起清洗',
+ sourceFileNotFound: '原始文件不存在,请重新上传后再清洗',
+ cleanTimeout: '文件清洗超时,请稍后重试;若多次失败,请检查源文件是否损坏',
+ duplicateFile: '上传失败,文件已存在',
+ apiRequestFailed: '知识库接口请求失败',
+ localFolder: '本地目录',
+ fileFallback: '文件{index}',
+ uploadFailed: '上传失败',
+ },
+ msg: {
+ operationFailed: '操作失败',
+ loadGroupsFailed: '加载知识库分组失败',
+ loadDocumentsFailed: '加载文档列表失败',
+ loadJobsFailed: '加载任务列表失败',
+ readSourceFailed: '读取原始文件失败',
+ noVersion: '暂无版本',
+ readMarkdownFailed: '读取清洗后的 Markdown 失败',
+ saveMarkdownFailed: '保存 Markdown 失败',
+ markdownSaved: '清洗后的 Markdown 已保存',
+ deleteDocumentFailed: '删除文档失败',
+ documentDeleted: '文档已删除',
+ selectDocumentsToSync: '请先选择要批量同步的文档',
+ batchSyncResult: '批量同步任务已提交:成功 {success} 条,失败 {fail} 条。{detail}',
+ batchSyncSuccess: '批量同步任务已提交:共成功 {success} 条',
+ selectDocumentsToClean: '请先选择要清洗的文档',
+ noDocumentsToClean: '当前所选文档没有可重新清洗的项',
+ batchCleanResult: '批量清洗任务已提交:成功 {success} 条,失败 {fail} 条。{detail}',
+ batchCleanSuccess: '批量清洗任务已提交:共成功 {success} 条',
+ selectDocumentsToDelete: '请先选择要批量删除的文档',
+ batchDeleteResult: '批量删除完成:成功 {success} 条,失败 {fail} 条。{detail}',
+ batchDeleteSuccess: '批量删除完成:共成功 {success} 条',
+ reselectFile: '请重新为「{name}」选择文件后提交',
+ recleanFailed: '重新清洗失败',
+ recleanSubmitted: '已重新提交清洗:{name}',
+ resyncFailed: '重新同步失败:{detail}',
+ resyncSubmitted: '已重新提交同步:{name}',
+ processingFile: '开始处理文件...',
+ uploadFailed: '文件上传失败',
+ versionUploaded: '版本文件「{file}」上传成功,清洗已排队',
+ uploadingProgress: '正在上传 {current}/{total}: {file}',
+ createDocumentFailed: '创建文档失败',
+ uploadVersionFailed: '上传文档版本失败',
+ uploadCleanupFailed: '上传失败后未能自动清理空文档({detail})',
+ uploadSummary: '上传完成:成功 {success} 个,失败 {fail} 个。{detail}',
+ uploadAllSuccess: '成功上传 {count} 个文件,清洗任务已排队',
+ syncDifyFailed: '同步到 Dify 失败:{detail}',
+ syncDifyFailedGeneric: '同步到 Dify 失败',
+ syncSubmitted: '同步任务已提交,等待后台处理',
+ pathUploadBusy: '有文件正在上传请稍等再试~',
+ selectGroupFirst: '请先选择知识库分组',
+ selectPathFiles: '请先选择至少一个本地目录或文件',
+ createPathJobFailed: '创建上传路径任务失败',
+ pathStageFailed: '路径文件暂存失败',
+ pathUploadDone: '路径文件已逐个上传并提交清洗',
+ deletePathFileConfirm: '确认删除路径文件「{path}」吗?',
+ deletePathFileFailed: '删除路径上传文件失败',
+ pathRecordDeletedWithDoc: '已删除路径记录,并同步删除对应文档',
+ pathRecordDeleted: '已删除路径记录',
+ selectPathFilesToDelete: '请先选择要删除的文件',
+ batchDeletePathConfirm: '确认批量删除已选中的 {count} 条路径文件吗?',
+ batchDeletePathResult: '批量删除完成:成功 {success} 条,失败 {fail} 条。{detail}',
+ batchDeletePathSuccess: '批量删除完成:共成功 {success} 条',
+ retryPathFailed: '重试失败文件失败',
+ retryPathOne: '已重新提交该失败文件',
+ retryPathAll: '已重新提交失败文件',
+ pathUploadProgress: '路径上传进度:总计 {total} 条,待上传 {pending} 条,已上传 {uploaded} 条,失败 {failed} 条',
+ deleteDocumentConfirm: '确认删除文档「{name}」吗?',
+ batchDeleteDocumentsConfirm: '确认批量删除已选中的 {count} 条文档吗?会同步删除 Dify 对应文档。',
+ markdownFailedWithReason: '当前文档清洗失败,尚未生成 Markdown。失败原因:{reason}',
+ markdownFailedRetry: '当前文档清洗失败,尚未生成 Markdown,请重新清洗后重试',
+ markdownProcessing: '当前文档正在清洗中,暂未生成 Markdown,请稍后再试',
+ markdownPendingClean: '当前文档待清洗,暂未生成 Markdown,请先发起清洗',
+ markdownNotGenerated: '当前文档尚未生成 Markdown',
+ },
+ },
+ 'zh-TW': {
+ status: {
+ draft: '待上傳', uploaded: '已上傳', processing: '清洗中', cleaned: '已清洗', ready: '已就緒',
+ synced: '已同步', syncing: '同步中', failed: '失敗', queued: '排隊中', running: '進行中',
+ success: '成功', cancelled: '已取消', idle: '未開始', done: '已完成', pendingClean: '待清洗',
+ pendingSync: '待同步', cleaning: '清洗中', uploading: '上傳中', unknown: '未知狀態', unnamedDocument: '未命名文檔',
+ },
+ workflow: { upload: '上傳', clean: '清洗', sync: '同步' },
+ failureModal: {
+ uploadData: '上傳失敗數據', cleanData: '清洗失敗數據', syncData: '同步失敗數據', generic: '失敗數據',
+ stageUploadFailed: '上傳失敗', stageCleanFailed: '清洗失敗', stageSyncFailed: '同步失敗',
+ },
+ errors: {
+ unreadableClean: '歷史失敗任務原因不可讀,請重新點擊「清洗數據」發起清洗',
+ unreadableSync: '歷史同步失敗原因不可讀,請重新發起同步',
+ unreadableUpload: '歷史上傳失敗原因不可讀,請重新上傳文件',
+ legacyCleanRecovered: '歷史遺留清洗任務已人工回收,請重新點擊「清洗數據」發起清洗',
+ sourceFileNotFound: '原始文件不存在,請重新上傳後再清洗',
+ cleanTimeout: '文件清洗超時,請稍後重試;若多次失敗,請檢查源文件是否損壞',
+ duplicateFile: '上傳失敗,文件已存在',
+ apiRequestFailed: '知識庫接口請求失敗',
+ localFolder: '本地目錄',
+ fileFallback: '文件{index}',
+ uploadFailed: '上傳失敗',
+ },
+ msg: {
+ operationFailed: '操作失敗',
+ loadGroupsFailed: '載入知識庫分組失敗',
+ loadDocumentsFailed: '載入文檔列表失敗',
+ loadJobsFailed: '載入任務列表失敗',
+ readSourceFailed: '讀取原始文件失敗',
+ noVersion: '暫無版本',
+ readMarkdownFailed: '讀取清洗後的 Markdown 失敗',
+ saveMarkdownFailed: '保存 Markdown 失敗',
+ markdownSaved: '清洗後的 Markdown 已保存',
+ deleteDocumentFailed: '刪除文檔失敗',
+ documentDeleted: '文檔已刪除',
+ selectDocumentsToSync: '請先選擇要批量同步的文檔',
+ batchSyncResult: '批量同步任務已提交:成功 {success} 條,失敗 {fail} 條。{detail}',
+ batchSyncSuccess: '批量同步任務已提交:共成功 {success} 條',
+ selectDocumentsToClean: '請先選擇要清洗的文檔',
+ noDocumentsToClean: '當前所選文檔沒有可重新清洗的項',
+ batchCleanResult: '批量清洗任務已提交:成功 {success} 條,失敗 {fail} 條。{detail}',
+ batchCleanSuccess: '批量清洗任務已提交:共成功 {success} 條',
+ selectDocumentsToDelete: '請先選擇要批量刪除的文檔',
+ batchDeleteResult: '批量刪除完成:成功 {success} 條,失敗 {fail} 條。{detail}',
+ batchDeleteSuccess: '批量刪除完成:共成功 {success} 條',
+ reselectFile: '請重新為「{name}」選擇文件後提交',
+ recleanFailed: '重新清洗失敗',
+ recleanSubmitted: '已重新提交清洗:{name}',
+ resyncFailed: '重新同步失敗:{detail}',
+ resyncSubmitted: '已重新提交同步:{name}',
+ processingFile: '開始處理文件...',
+ uploadFailed: '文件上傳失敗',
+ versionUploaded: '版本文件「{file}」上傳成功,清洗已排隊',
+ uploadingProgress: '正在上傳 {current}/{total}: {file}',
+ createDocumentFailed: '創建文檔失敗',
+ uploadVersionFailed: '上傳文檔版本失敗',
+ uploadCleanupFailed: '上傳失敗後未能自動清理空文檔({detail})',
+ uploadSummary: '上傳完成:成功 {success} 個,失敗 {fail} 個。{detail}',
+ uploadAllSuccess: '成功上傳 {count} 個文件,清洗任務已排隊',
+ syncDifyFailed: '同步到 Dify 失敗:{detail}',
+ syncDifyFailedGeneric: '同步到 Dify 失敗',
+ syncSubmitted: '同步任務已提交,等待後台處理',
+ pathUploadBusy: '有文件正在上傳請稍等再試~',
+ selectGroupFirst: '請先選擇知識庫分組',
+ selectPathFiles: '請先選擇至少一個本地目錄或文件',
+ createPathJobFailed: '創建上傳路徑任務失敗',
+ pathStageFailed: '路徑文件暫存失敗',
+ pathUploadDone: '路徑文件已逐個上傳並提交清洗',
+ deletePathFileConfirm: '確認刪除路徑文件「{path}」嗎?',
+ deletePathFileFailed: '刪除路徑上傳文件失敗',
+ pathRecordDeletedWithDoc: '已刪除路徑記錄,並同步刪除對應文檔',
+ pathRecordDeleted: '已刪除路徑記錄',
+ selectPathFilesToDelete: '請先選擇要刪除的文件',
+ batchDeletePathConfirm: '確認批量刪除已選中的 {count} 條路徑文件嗎?',
+ batchDeletePathResult: '批量刪除完成:成功 {success} 條,失敗 {fail} 條。{detail}',
+ batchDeletePathSuccess: '批量刪除完成:共成功 {success} 條',
+ retryPathFailed: '重試失敗文件失敗',
+ retryPathOne: '已重新提交該失敗文件',
+ retryPathAll: '已重新提交失敗文件',
+ pathUploadProgress: '路徑上傳進度:總計 {total} 條,待上傳 {pending} 條,已上傳 {uploaded} 條,失敗 {failed} 條',
+ deleteDocumentConfirm: '確認刪除文檔「{name}」嗎?',
+ batchDeleteDocumentsConfirm: '確認批量刪除已選中的 {count} 條文檔嗎?會同步刪除 Dify 對應文檔。',
+ markdownFailedWithReason: '當前文檔清洗失敗,尚未生成 Markdown。失敗原因:{reason}',
+ markdownFailedRetry: '當前文檔清洗失敗,尚未生成 Markdown,請重新清洗後重試',
+ markdownProcessing: '當前文檔正在清洗中,暫未生成 Markdown,請稍後再試',
+ markdownPendingClean: '當前文檔待清洗,暫未生成 Markdown,請先發起清洗',
+ markdownNotGenerated: '當前文檔尚未生成 Markdown',
+ },
+ },
+ th: {
+ status: {
+ draft: 'รออัปโหลด', uploaded: 'อัปโหลดแล้ว', processing: 'กำลังทำความสะอาด', cleaned: 'ทำความสะอาดแล้ว', ready: 'พร้อม',
+ synced: 'ซิงค์แล้ว', syncing: 'กำลังซิงค์', failed: 'ล้มเหลว', queued: 'อยู่ในคิว', running: 'กำลังดำเนินการ',
+ success: 'สำเร็จ', cancelled: 'ยกเลิกแล้ว', idle: 'ยังไม่เริ่ม', done: 'เสร็จสิ้น', pendingClean: 'รอทำความสะอาด',
+ pendingSync: 'รอซิงค์', cleaning: 'กำลังทำความสะอาด', uploading: 'กำลังอัปโหลด', unknown: 'สถานะไม่ทราบ', unnamedDocument: 'เอกสารไม่มีชื่อ',
+ },
+ workflow: { upload: 'อัปโหลด', clean: 'ทำความสะอาด', sync: 'ซิงค์' },
+ failureModal: {
+ uploadData: 'ข้อมูลอัปโหลดล้มเหลว', cleanData: 'ข้อมูลทำความสะอาดล้มเหลว', syncData: 'ข้อมูลซิงค์ล้มเหลว', generic: 'ข้อมูลล้มเหลว',
+ stageUploadFailed: 'อัปโหลดล้มเหลว', stageCleanFailed: 'ทำความสะอาดล้มเหลว', stageSyncFailed: 'ซิงค์ล้มเหลว',
+ },
+ errors: {
+ unreadableClean: 'ไม่สามารถอ่านสาเหตุความล้มเหลวในอดีตได้ กด "ทำความสะอาดข้อมูล" เพื่อลองใหม่',
+ unreadableSync: 'ไม่สามารถอ่านสาเหตุซิงค์ล้มเหลวในอดีตได้ โปรดซิงค์ใหม่',
+ unreadableUpload: 'ไม่สามารถอ่านสาเหตุอัปโหลดล้มเหลวในอดีตได้ โปรดอัปโหลดใหม่',
+ legacyCleanRecovered: 'งานทำความสะอาดเก่าถูกกู้คืนด้วยตนเอง กด "ทำความสะอาดข้อมูล" เพื่อลองใหม่',
+ sourceFileNotFound: 'ไม่พบไฟล์ต้นฉบับ โปรดอัปโหลดใหม่ก่อนทำความสะอาด',
+ cleanTimeout: 'ทำความสะอาดหมดเวลา ลองใหม่ภายหลังหรือตรวจสอบไฟล์ต้นฉบับ',
+ duplicateFile: 'อัปโหลดล้มเหลว: มีไฟล์นี้อยู่แล้ว',
+ apiRequestFailed: 'คำขอ API คลังความรู้ล้มเหลว',
+ localFolder: 'โฟลเดอร์ในเครื่อง',
+ fileFallback: 'ไฟล์ {index}',
+ uploadFailed: 'อัปโหลดล้มเหลว',
+ },
+ msg: {
+ operationFailed: 'ดำเนินการล้มเหลว',
+ loadGroupsFailed: 'โหลดกลุ่มล้มเหลว',
+ loadDocumentsFailed: 'โหลดเอกสารล้มเหลว',
+ loadJobsFailed: 'โหลดงานล้มเหลว',
+ readSourceFailed: 'อ่านไฟล์ต้นฉบับล้มเหลว',
+ noVersion: 'ไม่มีเวอร์ชัน',
+ readMarkdownFailed: 'อ่าน Markdown ที่ทำความสะอาดแล้วล้มเหลว',
+ saveMarkdownFailed: 'บันทึก Markdown ล้มเหลว',
+ markdownSaved: 'บันทึก Markdown ที่ทำความสะอาดแล้ว',
+ deleteDocumentFailed: 'ลบเอกสารล้มเหลว',
+ documentDeleted: 'ลบเอกสารแล้ว',
+ selectDocumentsToSync: 'โปรดเลือกเอกสารที่จะซิงค์เป็นชุด',
+ batchSyncResult: 'ส่งซิงค์เป็นชุด: สำเร็จ {success}, ล้มเหลว {fail}. {detail}',
+ batchSyncSuccess: 'ส่งซิงค์เป็นชุด: สำเร็จ {success}',
+ selectDocumentsToClean: 'โปรดเลือกเอกสารที่จะทำความสะอาด',
+ noDocumentsToClean: 'เอกสารที่เลือกไม่มีรายการที่ทำความสะอาดได้',
+ batchCleanResult: 'ส่งทำความสะอาดเป็นชุด: สำเร็จ {success}, ล้มเหลว {fail}. {detail}',
+ batchCleanSuccess: 'ส่งทำความสะอาดเป็นชุด: สำเร็จ {success}',
+ selectDocumentsToDelete: 'โปรดเลือกเอกสารที่จะลบเป็นชุด',
+ batchDeleteResult: 'ลบเป็นชุดเสร็จ: สำเร็จ {success}, ล้มเหลว {fail}. {detail}',
+ batchDeleteSuccess: 'ลบเป็นชุดเสร็จ: สำเร็จ {success}',
+ reselectFile: 'โปรดเลือกไฟล์ใหม่สำหรับ "{name}"',
+ recleanFailed: 'ทำความสะอาดใหม่ล้มเหลว',
+ recleanSubmitted: 'ส่งทำความสะอาดใหม่: {name}',
+ resyncFailed: 'ซิงค์ใหม่ล้มเหลว: {detail}',
+ resyncSubmitted: 'ส่งซิงค์ใหม่: {name}',
+ processingFile: 'เริ่มประมวลผลไฟล์...',
+ uploadFailed: 'อัปโหลดไฟล์ล้มเหลว',
+ versionUploaded: 'อัปโหลดเวอร์ชัน "{file}" แล้ว งานทำความสะอาดอยู่ในคิว',
+ uploadingProgress: 'กำลังอัปโหลด {current}/{total}: {file}',
+ createDocumentFailed: 'สร้างเอกสารล้มเหลว',
+ uploadVersionFailed: 'อัปโหลดเวอร์ชันเอกสารล้มเหลว',
+ uploadCleanupFailed: 'อัปโหลดล้มเหลวและลบเอกสารว่างไม่ได้ ({detail})',
+ uploadSummary: 'อัปโหลดเสร็จ: สำเร็จ {success}, ล้มเหลว {fail}. {detail}',
+ uploadAllSuccess: 'อัปโหลด {count} ไฟล์สำเร็จ งานทำความสะอาดอยู่ในคิว',
+ syncDifyFailed: 'ซิงค์ไป Dify ล้มเหลว: {detail}',
+ syncDifyFailedGeneric: 'ซิงค์ไป Dify ล้มเหลว',
+ syncSubmitted: 'ส่งงานซิงค์แล้ว',
+ pathUploadBusy: 'กำลังอัปโหลด โปรดรอสักครู่',
+ selectGroupFirst: 'โปรดเลือกกลุ่มก่อน',
+ selectPathFiles: 'โปรดเลือกโฟลเดอร์หรือไฟล์ในเครื่องอย่างน้อยหนึ่งรายการ',
+ createPathJobFailed: 'สร้างงานอัปโหลด path ล้มเหลว',
+ pathStageFailed: 'จัดเก็บไฟล์ path ชั่วคราวล้มเหลว',
+ pathUploadDone: 'อัปโหลดไฟล์ path และส่งทำความสะอาดแล้ว',
+ deletePathFileConfirm: 'ลบไฟล์ path "{path}"?',
+ deletePathFileFailed: 'ลบไฟล์ path ล้มเหลว',
+ pathRecordDeletedWithDoc: 'ลบบันทึก path และเอกสารที่เกี่ยวข้องแล้ว',
+ pathRecordDeleted: 'ลบบันทึก path แล้ว',
+ selectPathFilesToDelete: 'โปรดเลือกไฟล์ที่จะลบ',
+ batchDeletePathConfirm: 'ลบไฟล์ path ที่เลือก {count} รายการ?',
+ batchDeletePathResult: 'ลบเป็นชุด: สำเร็จ {success}, ล้มเหลว {fail}. {detail}',
+ batchDeletePathSuccess: 'ลบเป็นชุด: สำเร็จ {success}',
+ retryPathFailed: 'ลองใหม่ไฟล์ล้มเหลวไม่สำเร็จ',
+ retryPathOne: 'ส่งไฟล์ที่ล้มเหลวใหม่แล้ว',
+ retryPathAll: 'ส่งไฟล์ล้มเหลวทั้งหมดใหม่แล้ว',
+ pathUploadProgress: 'อัปโหลด path: ทั้งหมด {total}, รอ {pending}, อัปโหลด {uploaded}, ล้มเหลว {failed}',
+ deleteDocumentConfirm: 'ลบเอกสาร "{name}"?',
+ batchDeleteDocumentsConfirm: 'ลบเอกสารที่เลือก {count} รายการ? จะลบใน Dify ด้วย',
+ markdownFailedWithReason: 'ทำความสะอาดล้มเหลว ยังไม่มี Markdown. สาเหตุ: {reason}',
+ markdownFailedRetry: 'ทำความสะอาดล้มเหลว ยังไม่มี Markdown โปรดทำความสะอาดใหม่',
+ markdownProcessing: 'กำลังทำความสะอาด ยังไม่มี Markdown',
+ markdownPendingClean: 'รอทำความสะอาด ยังไม่มี Markdown',
+ markdownNotGenerated: 'ยังไม่มี Markdown สำหรับเอกสารนี้',
+ },
+ },
+};
+
+for (const [locale, patch] of Object.entries(patches)) {
+ const filePath = path.join(localesRoot, locale, 'kb.json');
+ const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
+ data.kbWorkspace = { ...data.kbWorkspace, ...patch };
+ fs.writeFileSync(filePath, `${JSON.stringify(data, null, 2)}\n`, 'utf8');
+ console.log(`Merged runtime i18n into ${locale}/kb.json`);
+}
diff --git a/frontend/scripts/merge-kb-workspace-i18n.mjs b/frontend/scripts/merge-kb-workspace-i18n.mjs
new file mode 100644
index 00000000..0e9feefa
--- /dev/null
+++ b/frontend/scripts/merge-kb-workspace-i18n.mjs
@@ -0,0 +1,629 @@
+/**
+ * scripts/merge-kb-workspace-i18n.mjs
+ * 合并 kbWorkspace 作业面 i18n 键至各语言 locales 下 kb.json
+ */
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const localesRoot = path.resolve(__dirname, '../src/locales');
+
+const patches = {
+ en: {
+ sidebar: {
+ groupsTitle: 'Groups',
+ loadingGroups: 'Loading groups...',
+ emptyGroups: 'No knowledge base groups yet.',
+ noDescription: 'No description',
+ },
+ summary: {
+ currentGroup: 'Current group',
+ documentCount: 'Documents',
+ pendingSync: 'Pending sync',
+ uploadFailed: 'Upload failures',
+ cleanFailed: 'Clean failures',
+ syncFailed: 'Sync failures',
+ },
+ filters: { all: 'All', upload: 'Upload', clean: 'Clean', sync: 'Sync' },
+ common: {
+ processing: 'Processing...',
+ delete: 'Delete',
+ close: 'Close',
+ cancel: 'Cancel',
+ retry: 'Retry',
+ remove: 'Remove',
+ none: 'None',
+ countUnit: 'items',
+ failureReason: 'Reason: {reason}',
+ perPage: 'Per page',
+ prevPage: 'Previous',
+ nextPage: 'Next',
+ },
+ documents: {
+ title: 'Documents',
+ infoTip: 'Basic document entries in this group. Uploading files creates documents and starts cleaning automatically.',
+ uploadPath: 'Upload path',
+ uploadFile: 'Upload file',
+ batchClean: 'Clean data',
+ batchCleanCount: 'Clean data ({count})',
+ batchSync: 'Batch sync',
+ batchSyncCount: 'Batch sync ({count})',
+ batchDelete: 'Batch delete',
+ batchDeleteCount: 'Batch delete ({count})',
+ historyBatches: 'History batches',
+ searchPlaceholder: 'Search by file name',
+ clearSearch: 'Clear search',
+ selectGroup: 'Please select a knowledge base group.',
+ loadingDocuments: 'Loading documents...',
+ emptyNoDocs: 'No documents in this group. Upload a file above to create the first record.',
+ emptyNoSearchMatch: 'No documents match the current search and filters.',
+ emptyNoFilterMatch: 'No documents match the current filters.',
+ versionCount: 'Versions: {count}',
+ currentVersion: 'Current: v{version}',
+ viewRecord: 'View history',
+ uploadVersion: 'Upload version',
+ syncDify: 'Sync to Dify',
+ syncingDify: 'Syncing...',
+ updatedAt: 'Updated: {time}',
+ selectedCount: 'Selected {selected} · Total {total}',
+ showingRange: 'Showing {start}-{end}',
+ pageInfo: 'Page {page} / {totalPages} · {total} items',
+ documentFallback: 'Document #{id}',
+ },
+ pathUpload: {
+ progressTitle: 'Path upload progress',
+ uploading: 'Uploading',
+ completed: 'Completed',
+ batchHint: 'Recommended {batchSize} files per batch, auto-continue every {seconds}s.',
+ total: 'Total {count}',
+ pending: 'Pending {count}',
+ uploaded: 'Uploaded {count}',
+ failed: 'Failed {count}',
+ success: 'Success {count}',
+ pendingProcess: 'Pending {count}',
+ currentFile: 'Current file: {name}',
+ details: 'Upload details',
+ viewHistory: 'View history',
+ retryFailedFiles: 'Retry failed files',
+ retryAllFailed: 'Retry all failed files',
+ selectAllFiltered: 'Select all filtered',
+ deselectAllFiltered: 'Deselect all',
+ selectAll: 'Select all',
+ deselectAll: 'Deselect all',
+ batchLabel: 'Batch #{id}',
+ createdAt: 'Created: {time}',
+ finishedAt: ' · Finished: {time}',
+ noBatchMessage: 'No batch description',
+ batchDelete: 'Batch delete',
+ batchDeleteCount: 'Batch delete ({count})',
+ deleting: 'Deleting...',
+ emptyHistory: 'No path upload history yet.',
+ },
+ recordModal: {
+ title: 'Document history',
+ viewing: 'Viewing: {name}',
+ loading: 'Loading document history...',
+ versionsTitle: 'Versions',
+ versionsCount: '{count} items',
+ versionsEmpty: 'No versions yet. Upload a version to see it here.',
+ syncTitle: 'Dify sync records',
+ syncEmpty: 'No Dify sync records. Click "Sync to Dify" to create one.',
+ versionLabel: 'Version: {id}',
+ sizeBytes: 'Size: {size} bytes',
+ },
+ markdownModal: {
+ readingVersion: 'Loading current version...',
+ previewText: 'Preview text',
+ cleanMarkdown: 'Cleaned Markdown',
+ loading: 'Loading cleaned Markdown...',
+ placeholder: 'No Markdown yet. Paste or edit content here.',
+ saving: 'Saving...',
+ save: 'Save Markdown',
+ editorTitle: 'Markdown editor',
+ },
+ sourceInfoModal: {
+ title: 'Source file info',
+ viewing: 'Viewing: {name}',
+ loading: 'Loading source file info...',
+ empty: 'No source file info. Upload a version to see it here.',
+ currentVersion: 'Current version',
+ opening: 'Opening...',
+ fileName: 'File: {name}',
+ fileSize: 'Size: {size}',
+ fileType: 'Type: {ext}',
+ },
+ failureModal: {
+ summary: '{count} failure records in this group, {pageSize} per page.',
+ empty: 'No failure data.',
+ currentVersion: 'Current version:',
+ noVersion: 'No version',
+ resubmit: 'Resubmit',
+ reclean: 'Re-clean',
+ resync: 'Re-sync',
+ pageInfo: 'Page {page} / {totalPages}',
+ },
+ pathUploadModal: {
+ title: 'Upload path',
+ subtitle: 'Select a local folder. Files are imported in batches and enter the cleaning workflow automatically.',
+ localPickerTitle: 'Local folder picker',
+ localPickerHint: 'You can add folders multiple times. Browsers cannot read arbitrary pasted paths.',
+ pickFolder: 'Select local folder',
+ pathListLabel: 'Path list',
+ pathListPlaceholder: 'Paths fill in after folder selection; paste notes for multiple paths if needed.',
+ pendingFiles: 'Pending files',
+ selectedRoots: 'Selected roots: {paths}',
+ noRoots: 'None',
+ pickFolderFirst: 'Select a local folder before confirming upload.',
+ confirmUpload: 'Confirm upload',
+ },
+ pathUploadHistoryModal: {
+ title: 'Path upload history',
+ subtitle: 'View batch results, failed files, and retry options.',
+ },
+ },
+ 'zh-CN': {
+ sidebar: {
+ groupsTitle: '分组列表',
+ loadingGroups: '正在加载分组...',
+ emptyGroups: '暂无知识库分组。',
+ noDescription: '暂无描述',
+ },
+ summary: {
+ currentGroup: '当前知识库分组',
+ documentCount: '文档数量',
+ pendingSync: '待同步数量',
+ uploadFailed: '上传失败数量',
+ cleanFailed: '清洗失败数量',
+ syncFailed: '同步失败数量',
+ },
+ filters: { all: '全部', upload: '上传', clean: '清洗', sync: '同步' },
+ common: {
+ processing: '处理中...',
+ delete: '删除',
+ close: '关闭',
+ cancel: '取消',
+ retry: '重试',
+ remove: '移除',
+ none: '暂无',
+ countUnit: '条',
+ failureReason: '失败原因:{reason}',
+ perPage: '每页',
+ prevPage: '上一页',
+ nextPage: '下一页',
+ },
+ documents: {
+ title: '文档列表',
+ infoTip: '当前分组下的基础文档条目,上传文件后将自动创建文档并开始清洗流程。',
+ uploadPath: '上传路径',
+ uploadFile: '上传文件',
+ batchClean: '清洗数据',
+ batchCleanCount: '清洗数据({count})',
+ batchSync: '批量同步',
+ batchSyncCount: '批量同步({count})',
+ batchDelete: '批量删除',
+ batchDeleteCount: '批量删除({count})',
+ historyBatches: '历史批次',
+ searchPlaceholder: '按文件名称模糊搜索',
+ clearSearch: '清空搜索',
+ selectGroup: '请选择一个知识库分组。',
+ loadingDocuments: '正在加载文档...',
+ emptyNoDocs: '当前分组暂无文档,可直接在上方创建第一条文档记录。',
+ emptyNoSearchMatch: '当前搜索和筛选条件下暂无匹配文档。',
+ emptyNoFilterMatch: '当前筛选条件下暂无匹配文档。',
+ versionCount: '版本数:{count}',
+ currentVersion: ' · 当前版本:v{version} · ',
+ viewRecord: '查看记录',
+ uploadVersion: '上传版本',
+ syncDify: '同步 Dify',
+ syncingDify: '同步中...',
+ updatedAt: '更新时间:{time}',
+ selectedCount: '已选 {selected} 条 · 共 {total} 条',
+ showingRange: '当前显示 {start}-{end} 条',
+ pageInfo: '第 {page} / {totalPages} 页 · 共 {total} 条',
+ documentFallback: '文档 #{id}',
+ },
+ pathUpload: {
+ progressTitle: '路径上传进度',
+ uploading: '上传中',
+ completed: '已完成',
+ batchHint: '建议每批 {batchSize} 条,间隔 {seconds} 秒自动继续。',
+ total: '总计 {count}',
+ pending: '待上传 {count}',
+ uploaded: '已上传 {count}',
+ failed: '失败 {count}',
+ success: '成功 {count}',
+ pendingProcess: '待处理 {count}',
+ currentFile: '当前文件:{name}',
+ details: '上传详情',
+ viewHistory: '查看历史',
+ retryFailedFiles: '重试失败文件',
+ retryAllFailed: '重试全部失败文件',
+ selectAllFiltered: '全选当前筛选',
+ deselectAllFiltered: '取消全选',
+ selectAll: '全选',
+ deselectAll: '取消全选',
+ batchLabel: '批次 #{id}',
+ createdAt: '创建时间:{time}',
+ finishedAt: ' · 完成时间:{time}',
+ noBatchMessage: '暂无批次说明',
+ batchDelete: '批量删除',
+ batchDeleteCount: '批量删除 ({count})',
+ deleting: '删除中...',
+ emptyHistory: '当前暂无上传路径历史批次。',
+ },
+ recordModal: {
+ title: '文档记录',
+ viewing: '当前查看:{name}',
+ loading: '正在加载文档记录...',
+ versionsTitle: '版本记录',
+ versionsCount: '{count} 条',
+ versionsEmpty: '暂无版本记录,上传版本后会显示在这里。',
+ syncTitle: 'Dify 同步记录',
+ syncEmpty: '暂无 Dify 同步记录,手动点击“同步 Dify”后会显示在这里。',
+ versionLabel: '版本:{id}',
+ sizeBytes: '大小:{size} bytes',
+ },
+ markdownModal: {
+ readingVersion: '正在读取当前版本...',
+ previewText: '预览文本',
+ cleanMarkdown: '清洗 Markdown',
+ loading: '正在加载清洗后的 Markdown...',
+ placeholder: '当前文档尚未生成 Markdown,可在此粘贴或编辑内容。',
+ saving: '保存中...',
+ save: '保存 Markdown',
+ editorTitle: 'Markdown 编辑器',
+ },
+ sourceInfoModal: {
+ title: '源文件信息',
+ viewing: '当前查看:{name}',
+ loading: '正在加载源文件信息...',
+ empty: '暂无源文件信息,上传版本后会显示在这里。',
+ currentVersion: '当前版本',
+ opening: '正在打开...',
+ fileName: '文件名:{name}',
+ fileSize: '大小:{size}',
+ fileType: '类型:{ext}',
+ },
+ failureModal: {
+ summary: '当前分组共 {count} 条失败记录,每页 {pageSize} 条。',
+ empty: '当前没有失败数据。',
+ currentVersion: '当前版本:',
+ noVersion: '暂无版本',
+ resubmit: '重新提交',
+ reclean: '重新清洗',
+ resync: '重新同步',
+ pageInfo: '第 {page} / {totalPages} 页',
+ },
+ pathUploadModal: {
+ title: '上传路径',
+ subtitle: '选择本地目录后,系统会按批次将该路径下文件导入当前分组并自动进入清洗流程。',
+ localPickerTitle: '本地路径选择',
+ localPickerHint: '支持多次选择目录追加文件;当前浏览器安全限制下,手动粘贴任意本机路径不能直接读取文件内容。',
+ pickFolder: '选择本地目录',
+ pathListLabel: '路径清单',
+ pathListPlaceholder: '目录选择后会自动填充路径清单;如需记录多路径,可在此粘贴备注。',
+ pendingFiles: '待上传文件',
+ selectedRoots: '已选根路径:{paths}',
+ noRoots: '暂无',
+ pickFolderFirst: '请选择本地目录后再确认上传。',
+ confirmUpload: '确认上传',
+ },
+ pathUploadHistoryModal: {
+ title: '上传路径历史批次',
+ subtitle: '查看每次路径上传的批次结果、失败文件与重试入口。',
+ },
+ },
+ 'zh-TW': {
+ sidebar: {
+ groupsTitle: '分組列表',
+ loadingGroups: '正在載入分組...',
+ emptyGroups: '暫無知識庫分組。',
+ noDescription: '暫無描述',
+ },
+ summary: {
+ currentGroup: '當前知識庫分組',
+ documentCount: '文檔數量',
+ pendingSync: '待同步數量',
+ uploadFailed: '上傳失敗數量',
+ cleanFailed: '清洗失敗數量',
+ syncFailed: '同步失敗數量',
+ },
+ filters: { all: '全部', upload: '上傳', clean: '清洗', sync: '同步' },
+ common: {
+ processing: '處理中...',
+ delete: '刪除',
+ close: '關閉',
+ cancel: '取消',
+ retry: '重試',
+ remove: '移除',
+ none: '暫無',
+ countUnit: '條',
+ failureReason: '失敗原因:{reason}',
+ perPage: '每頁',
+ prevPage: '上一頁',
+ nextPage: '下一頁',
+ },
+ documents: {
+ title: '文檔列表',
+ infoTip: '當前分組下的基礎文檔條目,上傳文件後將自動創建文檔並開始清洗流程。',
+ uploadPath: '上傳路徑',
+ uploadFile: '上傳文件',
+ batchClean: '清洗數據',
+ batchCleanCount: '清洗數據({count})',
+ batchSync: '批量同步',
+ batchSyncCount: '批量同步({count})',
+ batchDelete: '批量刪除',
+ batchDeleteCount: '批量刪除({count})',
+ historyBatches: '歷史批次',
+ searchPlaceholder: '按文件名稱模糊搜索',
+ clearSearch: '清空搜索',
+ selectGroup: '請選擇一個知識庫分組。',
+ loadingDocuments: '正在載入文檔...',
+ emptyNoDocs: '當前分組暫無文檔,可直接在上方創建第一條文檔記錄。',
+ emptyNoSearchMatch: '當前搜索和篩選條件下暫無匹配文檔。',
+ emptyNoFilterMatch: '當前篩選條件下暫無匹配文檔。',
+ versionCount: '版本數:{count}',
+ currentVersion: ' · 當前版本:v{version} · ',
+ viewRecord: '查看記錄',
+ uploadVersion: '上傳版本',
+ syncDify: '同步 Dify',
+ syncingDify: '同步中...',
+ updatedAt: '更新時間:{time}',
+ selectedCount: '已選 {selected} 條 · 共 {total} 條',
+ showingRange: '當前顯示 {start}-{end} 條',
+ pageInfo: '第 {page} / {totalPages} 頁 · 共 {total} 條',
+ documentFallback: '文檔 #{id}',
+ },
+ pathUpload: {
+ progressTitle: '路徑上傳進度',
+ uploading: '上傳中',
+ completed: '已完成',
+ batchHint: '建議每批 {batchSize} 條,間隔 {seconds} 秒自動繼續。',
+ total: '總計 {count}',
+ pending: '待上傳 {count}',
+ uploaded: '已上傳 {count}',
+ failed: '失敗 {count}',
+ success: '成功 {count}',
+ pendingProcess: '待處理 {count}',
+ currentFile: '當前文件:{name}',
+ details: '上傳詳情',
+ viewHistory: '查看歷史',
+ retryFailedFiles: '重試失敗文件',
+ retryAllFailed: '重試全部失敗文件',
+ selectAllFiltered: '全選當前篩選',
+ deselectAllFiltered: '取消全選',
+ selectAll: '全選',
+ deselectAll: '取消全選',
+ batchLabel: '批次 #{id}',
+ createdAt: '創建時間:{time}',
+ finishedAt: ' · 完成時間:{time}',
+ noBatchMessage: '暫無批次說明',
+ batchDelete: '批量刪除',
+ batchDeleteCount: '批量刪除 ({count})',
+ deleting: '刪除中...',
+ emptyHistory: '當前暫無上傳路徑歷史批次。',
+ },
+ recordModal: {
+ title: '文檔記錄',
+ viewing: '當前查看:{name}',
+ loading: '正在載入文檔記錄...',
+ versionsTitle: '版本記錄',
+ versionsCount: '{count} 條',
+ versionsEmpty: '暫無版本記錄,上傳版本後會顯示在這裡。',
+ syncTitle: 'Dify 同步記錄',
+ syncEmpty: '暫無 Dify 同步記錄,手動點擊「同步 Dify」後會顯示在這裡。',
+ versionLabel: '版本:{id}',
+ sizeBytes: '大小:{size} bytes',
+ },
+ markdownModal: {
+ readingVersion: '正在讀取當前版本...',
+ previewText: '預覽文本',
+ cleanMarkdown: '清洗 Markdown',
+ loading: '正在載入清洗後的 Markdown...',
+ placeholder: '當前文檔尚未生成 Markdown,可在此粘貼或編輯內容。',
+ saving: '保存中...',
+ save: '保存 Markdown',
+ editorTitle: 'Markdown 編輯器',
+ },
+ sourceInfoModal: {
+ title: '源文件信息',
+ viewing: '當前查看:{name}',
+ loading: '正在載入源文件信息...',
+ empty: '暫無源文件信息,上傳版本後會顯示在這裡。',
+ currentVersion: '當前版本',
+ opening: '正在打開...',
+ fileName: '文件名:{name}',
+ fileSize: '大小:{size}',
+ fileType: '類型:{ext}',
+ },
+ failureModal: {
+ summary: '當前分組共 {count} 條失敗記錄,每頁 {pageSize} 條。',
+ empty: '當前沒有失敗數據。',
+ currentVersion: '當前版本:',
+ noVersion: '暫無版本',
+ resubmit: '重新提交',
+ reclean: '重新清洗',
+ resync: '重新同步',
+ pageInfo: '第 {page} / {totalPages} 頁',
+ },
+ pathUploadModal: {
+ title: '上傳路徑',
+ subtitle: '選擇本地目錄後,系統會按批次將該路徑下文件導入當前分組並自動進入清洗流程。',
+ localPickerTitle: '本地路徑選擇',
+ localPickerHint: '支持多次選擇目錄追加文件;當前瀏覽器安全限制下,手動粘貼任意本機路徑不能直接讀取文件內容。',
+ pickFolder: '選擇本地目錄',
+ pathListLabel: '路徑清單',
+ pathListPlaceholder: '目錄選擇後會自動填充路徑清單;如需記錄多路徑,可在此粘貼備註。',
+ pendingFiles: '待上傳文件',
+ selectedRoots: '已選根路徑:{paths}',
+ noRoots: '暫無',
+ pickFolderFirst: '請選擇本地目錄後再確認上傳。',
+ confirmUpload: '確認上傳',
+ },
+ pathUploadHistoryModal: {
+ title: '上傳路徑歷史批次',
+ subtitle: '查看每次路徑上傳的批次結果、失敗文件與重試入口。',
+ },
+ },
+ th: {
+ sidebar: {
+ groupsTitle: 'รายการกลุ่ม',
+ loadingGroups: 'กำลังโหลดกลุ่ม...',
+ emptyGroups: 'ยังไม่มีกลุ่มคลังความรู้',
+ noDescription: 'ไม่มีคำอธิบาย',
+ },
+ summary: {
+ currentGroup: 'กลุ่มปัจจุบัน',
+ documentCount: 'จำนวนเอกสาร',
+ pendingSync: 'รอซิงค์',
+ uploadFailed: 'อัปโหลดล้มเหลว',
+ cleanFailed: 'ทำความสะอาดล้มเหลว',
+ syncFailed: 'ซิงค์ล้มเหลว',
+ },
+ filters: { all: 'ทั้งหมด', upload: 'อัปโหลด', clean: 'ทำความสะอาด', sync: 'ซิงค์' },
+ common: {
+ processing: 'กำลังดำเนินการ...',
+ delete: 'ลบ',
+ close: 'ปิด',
+ cancel: 'ยกเลิก',
+ retry: 'ลองใหม่',
+ remove: 'นำออก',
+ none: 'ไม่มี',
+ countUnit: 'รายการ',
+ failureReason: 'สาเหตุ: {reason}',
+ perPage: 'ต่อหน้า',
+ prevPage: 'ก่อนหน้า',
+ nextPage: 'ถัดไป',
+ },
+ documents: {
+ title: 'รายการเอกสาร',
+ infoTip: 'รายการเอกสารพื้นฐานในกลุ่มนี้ การอัปโหลดไฟล์จะสร้างเอกสารและเริ่มทำความสะอาดอัตโนมัติ',
+ uploadPath: 'อัปโหลดจาก path',
+ uploadFile: 'อัปโหลดไฟล์',
+ batchClean: 'ทำความสะอาดข้อมูล',
+ batchCleanCount: 'ทำความสะอาดข้อมูล ({count})',
+ batchSync: 'ซิงค์เป็นชุด',
+ batchSyncCount: 'ซิงค์เป็นชุด ({count})',
+ batchDelete: 'ลบเป็นชุด',
+ batchDeleteCount: 'ลบเป็นชุด ({count})',
+ historyBatches: 'ประวัติ batch',
+ searchPlaceholder: 'ค้นหาตามชื่อไฟล์',
+ clearSearch: 'ล้างการค้นหา',
+ selectGroup: 'โปรดเลือกกลุ่มคลังความรู้',
+ loadingDocuments: 'กำลังโหลดเอกสาร...',
+ emptyNoDocs: 'ยังไม่มีเอกสารในกลุ่มนี้ อัปโหลดไฟล์ด้านบนเพื่อสร้างรายการแรก',
+ emptyNoSearchMatch: 'ไม่พบเอกสารที่ตรงกับการค้นหาและตัวกรอง',
+ emptyNoFilterMatch: 'ไม่พบเอกสารที่ตรงกับตัวกรอง',
+ versionCount: 'เวอร์ชัน: {count}',
+ currentVersion: ' · เวอร์ชันปัจจุบัน: v{version} · ',
+ viewRecord: 'ดูประวัติ',
+ uploadVersion: 'อัปโหลดเวอร์ชัน',
+ syncDify: 'ซิงค์ไป Dify',
+ syncingDify: 'กำลังซิงค์...',
+ updatedAt: 'อัปเดต: {time}',
+ selectedCount: 'เลือก {selected} · ทั้งหมด {total}',
+ showingRange: 'แสดง {start}-{end}',
+ pageInfo: 'หน้า {page} / {totalPages} · {total} รายการ',
+ documentFallback: 'เอกสาร #{id}',
+ },
+ pathUpload: {
+ progressTitle: 'ความคืบหน้าการอัปโหลด path',
+ uploading: 'กำลังอัปโหลด',
+ completed: 'เสร็จสิ้น',
+ batchHint: 'แนะนำ {batchSize} ไฟล์ต่อ batch ทำต่ออัตโนมัติทุก {seconds} วินาที',
+ total: 'ทั้งหมด {count}',
+ pending: 'รออัปโหลด {count}',
+ uploaded: 'อัปโหลดแล้ว {count}',
+ failed: 'ล้มเหลว {count}',
+ success: 'สำเร็จ {count}',
+ pendingProcess: 'รอดำเนินการ {count}',
+ currentFile: 'ไฟล์ปัจจุบัน: {name}',
+ details: 'รายละเอียดการอัปโหลด',
+ viewHistory: 'ดูประวัติ',
+ retryFailedFiles: 'ลองใหม่ไฟล์ที่ล้มเหลว',
+ retryAllFailed: 'ลองใหม่ไฟล์ล้มเหลวทั้งหมด',
+ selectAllFiltered: 'เลือกทั้งหมดที่กรอง',
+ deselectAllFiltered: 'ยกเลิกการเลือก',
+ selectAll: 'เลือกทั้งหมด',
+ deselectAll: 'ยกเลิกการเลือก',
+ batchLabel: 'Batch #{id}',
+ createdAt: 'สร้างเมื่อ: {time}',
+ finishedAt: ' · เสร็จเมื่อ: {time}',
+ noBatchMessage: 'ไม่มีคำอธิบาย batch',
+ batchDelete: 'ลบเป็นชุด',
+ batchDeleteCount: 'ลบเป็นชุด ({count})',
+ deleting: 'กำลังลบ...',
+ emptyHistory: 'ยังไม่มีประวัติการอัปโหลด path',
+ },
+ recordModal: {
+ title: 'ประวัติเอกสาร',
+ viewing: 'กำลังดู: {name}',
+ loading: 'กำลังโหลดประวัติเอกสาร...',
+ versionsTitle: 'เวอร์ชัน',
+ versionsCount: '{count} รายการ',
+ versionsEmpty: 'ยังไม่มีเวอร์ชัน อัปโหลดเวอร์ชันเพื่อดูที่นี่',
+ syncTitle: 'บันทึกซิงค์ Dify',
+ syncEmpty: 'ยังไม่มีบันทึกซิงค์ Dify คลิก "ซิงค์ไป Dify" เพื่อสร้าง',
+ versionLabel: 'เวอร์ชัน: {id}',
+ sizeBytes: 'ขนาด: {size} bytes',
+ },
+ markdownModal: {
+ readingVersion: 'กำลังโหลดเวอร์ชันปัจจุบัน...',
+ previewText: 'ข้อความตัวอย่าง',
+ cleanMarkdown: 'Markdown ที่ทำความสะอาดแล้ว',
+ loading: 'กำลังโหลด Markdown...',
+ placeholder: 'ยังไม่มี Markdown วางหรือแก้ไขเนื้อหาได้ที่นี่',
+ saving: 'กำลังบันทึก...',
+ save: 'บันทึก Markdown',
+ editorTitle: 'ตัวแก้ไข Markdown',
+ },
+ sourceInfoModal: {
+ title: 'ข้อมูลไฟล์ต้นฉบับ',
+ viewing: 'กำลังดู: {name}',
+ loading: 'กำลังโหลดข้อมูลไฟล์ต้นฉบับ...',
+ empty: 'ยังไม่มีข้อมูลไฟล์ต้นฉบับ อัปโหลดเวอร์ชันเพื่อดูที่นี่',
+ currentVersion: 'เวอร์ชันปัจจุบัน',
+ opening: 'กำลังเปิด...',
+ fileName: 'ไฟล์: {name}',
+ fileSize: 'ขนาด: {size}',
+ fileType: 'ประเภท: {ext}',
+ },
+ failureModal: {
+ summary: 'กลุ่มนี้มี {count} รายการล้มเหลว {pageSize} รายการต่อหน้า',
+ empty: 'ไม่มีข้อมูลล้มเหลว',
+ currentVersion: 'เวอร์ชันปัจจุบัน:',
+ noVersion: 'ไม่มีเวอร์ชัน',
+ resubmit: 'ส่งใหม่',
+ reclean: 'ทำความสะอาดใหม่',
+ resync: 'ซิงค์ใหม่',
+ pageInfo: 'หน้า {page} / {totalPages}',
+ },
+ pathUploadModal: {
+ title: 'อัปโหลด path',
+ subtitle: 'เลือกโฟลเดอร์ในเครื่อง ระบบจะนำเข้าไฟล์เป็น batch และเข้าสู่ workflow ทำความสะอาดอัตโนมัติ',
+ localPickerTitle: 'เลือกโฟลเดอร์ในเครื่อง',
+ localPickerHint: 'เลือกโฟลเดอร์ได้หลายครั้ง เบราว์เซอร์ไม่สามารถอ่าน path ที่วางเองได้',
+ pickFolder: 'เลือกโฟลเดอร์ในเครื่อง',
+ pathListLabel: 'รายการ path',
+ pathListPlaceholder: 'path จะเติมหลังเลือกโฟลเดอร์ วางหมายเหตุหลาย path ได้ที่นี่',
+ pendingFiles: 'ไฟล์รออัปโหลด',
+ selectedRoots: 'root ที่เลือก: {paths}',
+ noRoots: 'ไม่มี',
+ pickFolderFirst: 'โปรดเลือกโฟลเดอร์ในเครื่องก่อนยืนยันอัปโหลด',
+ confirmUpload: 'ยืนยันอัปโหลด',
+ },
+ pathUploadHistoryModal: {
+ title: 'ประวัติ batch อัปโหลด path',
+ subtitle: 'ดูผลลัพธ์ batch ไฟล์ล้มเหลว และตัวเลือกลองใหม่',
+ },
+ },
+};
+
+for (const [locale, patch] of Object.entries(patches)) {
+ const filePath = path.join(localesRoot, locale, 'kb.json');
+ const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
+ data.kbWorkspace = { ...data.kbWorkspace, ...patch };
+ fs.writeFileSync(filePath, `${JSON.stringify(data, null, 2)}\n`, 'utf8');
+ console.log(`Merged kbWorkspace i18n into ${locale}/kb.json`);
+}
diff --git a/frontend/scripts/merge-schedule-form-i18n.mjs b/frontend/scripts/merge-schedule-form-i18n.mjs
new file mode 100644
index 00000000..7f187dde
--- /dev/null
+++ b/frontend/scripts/merge-schedule-form-i18n.mjs
@@ -0,0 +1,259 @@
+/**
+ * scripts/merge-schedule-form-i18n.mjs
+ * 合并排程创建/编辑弹窗与 Dify 快照相关文案至各语言 admin.json
+ */
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const localesRoot = path.resolve(__dirname, '../src/locales');
+
+const patches = {
+ en: {
+ form: {
+ dsDbType: 'Database type',
+ dsHost: 'Host',
+ dsHostPlaceholder: 'e.g. 192.168.1.100 or ${SRM_SQLSERVER_HOST}',
+ dsPort: 'Port',
+ dsDatabase: 'Database',
+ dsDatabasePlaceholder: 'Database name',
+ dsUsername: 'Username',
+ dsPassword: 'Password',
+ dsPasswordPlaceholder: 'or ${ENV_VAR}',
+ dsDriver: 'ODBC driver',
+ dsEncrypt: 'Encrypt',
+ dsTrustCert: 'TrustServerCertificate',
+ defaultNo: 'Default (no)',
+ defaultYes: 'Default (yes)',
+ envVarHint: 'Values support {token} format and are resolved from environment variables at runtime (recommended for passwords).',
+ envVarToken: '${ENV_VAR_NAME}',
+ baseFetchSql: 'Base fetch SQL (base_fetch_sql) — SELECT + FROM + JOIN only, no WHERE',
+ fetchWhereConditions: 'WHERE clause (fetch_where_conditions) — edit to test different filters',
+ fetchOrderBy: 'Order by (fetch_order_by)',
+ detailSql: 'Detail SQL (detail_sql)',
+ writebackSql: 'Writeback SQL (writeback_sql)',
+ rowIdKey: 'Row ID key (row_id_key)',
+ logPrefix: 'Log prefix (log_prefix)',
+ aliasOrder: 'Field order (alias_order) — comma-separated',
+ detailAliasOrder: 'Detail field order (detail_alias_order) — comma-separated',
+ headerLabels: 'Header labels (header_labels) — JSON',
+ apiUrl: 'API URL',
+ apiMethod: 'HTTP method',
+ apiTimeoutSeconds: 'Timeout (seconds)',
+ apiHeaders: 'Request headers (Headers) — JSON',
+ apiBodyTemplate: 'Request body template (Body)',
+ agentLabel: 'Agent',
+ agentOptionId: ' (ID: {id})',
+ difySystemPrompt: 'Dify System Prompt',
+ difySystemPromptHint: 'Available when a Dify Agent is enabled. Saved as system_prompt in the Workflow; LLM nodes must reference this variable.',
+ difySystemPromptPlaceholder:
+ 'e.g. You are a material compliance assistant. Based on record test data, return JSON with dify_result (pass/fail/manual review) and dify_message.',
+ },
+ difySnapshot: {
+ title: 'Dify execution snapshot (audit)',
+ agent: 'Agent',
+ agentId: ' (ID: {id})',
+ difyAppId: 'Dify App ID',
+ systemPrompt: 'System Prompt',
+ notConfigured: '(Not configured)',
+ notConfiguredUseDefault: '(Not configured; using Dify workflow default prompt)',
+ notEnabledTest: 'Dify was not enabled for this test',
+ notEnabledRun: 'Dify Agent was not enabled for this run',
+ },
+ testRun: {
+ baseFetchSqlReadonly: 'Base fetch SQL (base_fetch_sql) — read-only',
+ limitRows: 'Row limit (limit)',
+ },
+ },
+ 'zh-CN': {
+ form: {
+ dsDbType: '数据库类型',
+ dsHost: '主机地址',
+ dsHostPlaceholder: '如 192.168.1.100 或 ${SRM_SQLSERVER_HOST}',
+ dsPort: '端口',
+ dsDatabase: '数据库',
+ dsDatabasePlaceholder: '数据库名',
+ dsUsername: '用户名',
+ dsPassword: '密码',
+ dsPasswordPlaceholder: '或 ${ENV_VAR}',
+ dsDriver: 'ODBC 驱动',
+ dsEncrypt: 'Encrypt',
+ dsTrustCert: 'TrustServerCertificate',
+ defaultNo: '默认 (no)',
+ defaultYes: '默认 (yes)',
+ envVarHint: '值支持 {token} 格式,运行时自动从环境变量解析(推荐密码使用此方式)',
+ envVarToken: '${环境变量名}',
+ baseFetchSql: '基础查询 SQL (base_fetch_sql) — SELECT + FROM + JOIN 部分,不含 WHERE',
+ fetchWhereConditions: 'WHERE 条件 (fetch_where_conditions) — 可修改以测试不同筛选条件',
+ fetchOrderBy: '排序 (fetch_order_by)',
+ detailSql: '明细 SQL (detail_sql)',
+ writebackSql: '回写 SQL (writeback_sql)',
+ rowIdKey: '主键字段 (row_id_key)',
+ logPrefix: '日志前缀 (log_prefix)',
+ aliasOrder: '字段顺序 (alias_order) — 逗号分隔',
+ detailAliasOrder: '明细字段顺序 (detail_alias_order) — 逗号分隔',
+ headerLabels: '表头标签 (header_labels) — JSON 格式',
+ apiUrl: 'API 地址',
+ apiMethod: '请求方法',
+ apiTimeoutSeconds: '超时(秒)',
+ apiHeaders: '请求头 (Headers) — JSON 格式',
+ apiBodyTemplate: '请求体模板 (Body)',
+ agentLabel: 'Agent',
+ agentOptionId: '(ID: {id})',
+ difySystemPrompt: 'Dify System Prompt',
+ difySystemPromptHint:
+ '仅在启用 Dify Agent 时可配置。保存后将作为 system_prompt 传入 Workflow;编排中 LLM 节点需引用该变量。',
+ difySystemPromptPlaceholder:
+ '例如:你是物料合规判定助手。根据 record 中的检测数据判定是否合格,仅返回 JSON:dify_result(合格/不合格/人工判定)与 dify_message。',
+ },
+ difySnapshot: {
+ title: 'Dify 执行快照(审计)',
+ agent: 'Agent',
+ agentId: '(ID: {id})',
+ difyAppId: 'Dify App ID',
+ systemPrompt: 'System Prompt',
+ notConfigured: '(未配置)',
+ notConfiguredUseDefault: '(未配置,使用 Dify 编排内默认提示词)',
+ notEnabledTest: '本次测试未启用 Dify',
+ notEnabledRun: '本次执行未启用 Dify Agent',
+ },
+ testRun: {
+ baseFetchSqlReadonly: '基础查询 SQL (base_fetch_sql) — 只读',
+ limitRows: '限制行数 (limit)',
+ },
+ },
+ 'zh-TW': {
+ form: {
+ dsDbType: '資料庫類型',
+ dsHost: '主機位址',
+ dsHostPlaceholder: '如 192.168.1.100 或 ${SRM_SQLSERVER_HOST}',
+ dsPort: '連接埠',
+ dsDatabase: '資料庫',
+ dsDatabasePlaceholder: '資料庫名稱',
+ dsUsername: '使用者名稱',
+ dsPassword: '密碼',
+ dsPasswordPlaceholder: '或 ${ENV_VAR}',
+ dsDriver: 'ODBC 驅動',
+ dsEncrypt: 'Encrypt',
+ dsTrustCert: 'TrustServerCertificate',
+ defaultNo: '預設 (no)',
+ defaultYes: '預設 (yes)',
+ envVarHint: '值支援 {token} 格式,執行時自動從環境變數解析(建議密碼使用此方式)',
+ envVarToken: '${環境變數名}',
+ baseFetchSql: '基礎查詢 SQL (base_fetch_sql) — SELECT + FROM + JOIN 部分,不含 WHERE',
+ fetchWhereConditions: 'WHERE 條件 (fetch_where_conditions) — 可修改以測試不同篩選條件',
+ fetchOrderBy: '排序 (fetch_order_by)',
+ detailSql: '明細 SQL (detail_sql)',
+ writebackSql: '回寫 SQL (writeback_sql)',
+ rowIdKey: '主鍵欄位 (row_id_key)',
+ logPrefix: '日誌前綴 (log_prefix)',
+ aliasOrder: '欄位順序 (alias_order) — 逗號分隔',
+ detailAliasOrder: '明細欄位順序 (detail_alias_order) — 逗號分隔',
+ headerLabels: '表頭標籤 (header_labels) — JSON 格式',
+ apiUrl: 'API 位址',
+ apiMethod: '請求方法',
+ apiTimeoutSeconds: '逾時(秒)',
+ apiHeaders: '請求標頭 (Headers) — JSON 格式',
+ apiBodyTemplate: '請求體模板 (Body)',
+ agentLabel: 'Agent',
+ agentOptionId: '(ID: {id})',
+ difySystemPrompt: 'Dify System Prompt',
+ difySystemPromptHint:
+ '僅在啟用 Dify Agent 時可配置。保存後將作為 system_prompt 傳入 Workflow;編排中 LLM 節點需引用該變數。',
+ difySystemPromptPlaceholder:
+ '例如:你是物料合規判定助手。根據 record 中的檢測資料判定是否合格,僅返回 JSON:dify_result(合格/不合格/人工判定)與 dify_message。',
+ },
+ difySnapshot: {
+ title: 'Dify 執行快照(審計)',
+ agent: 'Agent',
+ agentId: '(ID: {id})',
+ difyAppId: 'Dify App ID',
+ systemPrompt: 'System Prompt',
+ notConfigured: '(未配置)',
+ notConfiguredUseDefault: '(未配置,使用 Dify 編排內預設提示詞)',
+ notEnabledTest: '本次測試未啟用 Dify',
+ notEnabledRun: '本次執行未啟用 Dify Agent',
+ },
+ testRun: {
+ baseFetchSqlReadonly: '基礎查詢 SQL (base_fetch_sql) — 唯讀',
+ limitRows: '限制行數 (limit)',
+ },
+ },
+ th: {
+ form: {
+ dsDbType: 'ประเภทฐานข้อมูล',
+ dsHost: 'โฮสต์',
+ dsHostPlaceholder: 'เช่น 192.168.1.100 หรือ ${SRM_SQLSERVER_HOST}',
+ dsPort: 'พอร์ต',
+ dsDatabase: 'ฐานข้อมูล',
+ dsDatabasePlaceholder: 'ชื่อฐานข้อมูล',
+ dsUsername: 'ชื่อผู้ใช้',
+ dsPassword: 'รหัสผ่าน',
+ dsPasswordPlaceholder: 'หรือ ${ENV_VAR}',
+ dsDriver: 'ไดรเวอร์ ODBC',
+ dsEncrypt: 'Encrypt',
+ dsTrustCert: 'TrustServerCertificate',
+ defaultNo: 'ค่าเริ่มต้น (no)',
+ defaultYes: 'ค่าเริ่มต้น (yes)',
+ envVarHint: 'รองรับรูปแบบ {token} และจะถูกแก้จากตัวแปรสภาพแวดล้อมขณะรัน (แนะนำสำหรับรหัสผ่าน)',
+ envVarToken: '${ชื่อตัวแปรสภาพแวดล้อม}',
+ baseFetchSql: 'SQL ดึงข้อมูลพื้นฐาน (base_fetch_sql) — เฉพาะ SELECT + FROM + JOIN ไม่รวม WHERE',
+ fetchWhereConditions: 'เงื่อนไข WHERE (fetch_where_conditions) — แก้ไขเพื่อทดสอบตัวกรอง',
+ fetchOrderBy: 'เรียงลำดับ (fetch_order_by)',
+ detailSql: 'SQL รายละเอียด (detail_sql)',
+ writebackSql: 'SQL เขียนกลับ (writeback_sql)',
+ rowIdKey: 'คีย์แถว (row_id_key)',
+ logPrefix: 'คำนำหน้าบันทึก (log_prefix)',
+ aliasOrder: 'ลำดับฟิลด์ (alias_order) — คั่นด้วยจุลภาค',
+ detailAliasOrder: 'ลำดับฟิลด์รายละเอียด (detail_alias_order) — คั่นด้วยจุลภาค',
+ headerLabels: 'ป้ายหัวตาราง (header_labels) — JSON',
+ apiUrl: 'URL ของ API',
+ apiMethod: 'วิธี HTTP',
+ apiTimeoutSeconds: 'หมดเวลา (วินาที)',
+ apiHeaders: 'ส่วนหัวคำขอ (Headers) — JSON',
+ apiBodyTemplate: 'เทมเพลต body คำขอ (Body)',
+ agentLabel: 'Agent',
+ agentOptionId: ' (ID: {id})',
+ difySystemPrompt: 'Dify System Prompt',
+ difySystemPromptHint:
+ 'ใช้ได้เมื่อเปิดใช้ Dify Agent จะบันทึกเป็น system_prompt ใน Workflow; โหนด LLM ต้องอ้างอิงตัวแปรนี้',
+ difySystemPromptPlaceholder:
+ 'เช่น คุณเป็นผู้ช่วยตรวจสอบความสอดคล้องของวัสดุ จากข้อมูล record ให้คืน JSON: dify_result (ผ่าน/ไม่ผ่าน/ตรวจด้วยมือ) และ dify_message',
+ },
+ difySnapshot: {
+ title: 'สแนปช็อตการทำงาน Dify (ตรวจสอบ)',
+ agent: 'Agent',
+ agentId: ' (ID: {id})',
+ difyAppId: 'Dify App ID',
+ systemPrompt: 'System Prompt',
+ notConfigured: '(ยังไม่ได้ตั้งค่า)',
+ notConfiguredUseDefault: '(ยังไม่ได้ตั้งค่า ใช้ prompt เริ่มต้นใน Dify workflow)',
+ notEnabledTest: 'การทดสอบนี้ไม่ได้เปิดใช้ Dify',
+ notEnabledRun: 'การรันนี้ไม่ได้เปิดใช้ Dify Agent',
+ },
+ testRun: {
+ baseFetchSqlReadonly: 'SQL ดึงข้อมูลพื้นฐาน (base_fetch_sql) — อ่านอย่างเดียว',
+ limitRows: 'จำกัดจำนวนแถว (limit)',
+ },
+ },
+};
+
+function deepMerge(target, source) {
+ for (const [key, value] of Object.entries(source)) {
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
+ target[key] = deepMerge(target[key] ?? {}, value);
+ } else {
+ target[key] = value;
+ }
+ }
+ return target;
+}
+
+for (const [locale, patch] of Object.entries(patches)) {
+ const filePath = path.join(localesRoot, locale, 'admin.json');
+ const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
+ data.schedule = deepMerge(data.schedule ?? {}, patch);
+ fs.writeFileSync(filePath, `${JSON.stringify(data, null, 2)}\n`, 'utf8');
+ console.log(`Updated ${filePath}`);
+}
diff --git a/frontend/src/App.vue b/frontend/src/App.vue
index 31cd9c13..79ec771a 100644
--- a/frontend/src/App.vue
+++ b/frontend/src/App.vue
@@ -1,5 +1,8 @@
-
-
-
-
-
-
-
-
-
-
-
- {{ scheduleViewMode === 'overview' ? $t('admin.schedule.overviewTitle') : $t('admin.schedule.workbenchTitle') }}
-
-
- {{ scheduleViewMode === 'overview' ? $t('admin.schedule.overviewSubtitle') : $t('admin.schedule.workbenchSubtitle') }}
-
-
-
-
-
-
-
-
-
-
-
-
{{ schedules.length }}
-
{{ $t('admin.schedule.stats.total') }}
-
-
-
{{ scheduleEnabledCount }}
-
{{ $t('admin.schedule.stats.enabled') }}
-
-
-
{{ scheduleDisabledCount }}
-
{{ $t('admin.schedule.stats.disabled') }}
-
-
-
{{ scheduleRunningCount }}
-
{{ $t('admin.schedule.stats.running') }}
-
-
-
-
-
{{ $t('admin.schedule.sectionOverview') }}
- {{ $t('admin.schedule.switchByCard') }}
-
-
{{ $t('admin.schedule.loading') }}
-
-
-
-
-
-
-
{{ $t('admin.schedule.addTitle') }}
-
-
- {{ $t('admin.schedule.addHint') }}
-
-
-
-
-
-
-
-
-
-
- {{ $t('admin.schedule.lastRun') }}:{{ formatDateTime(s.last_run_at) }}
-
-
- {{ $t('admin.schedule.nextRun') }}:{{ formatDateTime(s.next_run_at) }}
-
-
-
-
-
-
-
-
-
-
-
-
- {{ $t('admin.schedule.emptyList') }}
-
-
-
-
-
-
-
-
-
-
-
{{ selectedSchedule?.name || $t('admin.schedule.noSelection') }}
-
{{ $t('admin.schedule.selectedHint', { time: selectedScheduleLatestRunAt }) }}
-
-
-
{{ selectedScheduleRuns.length }}
-
{{ $t('admin.schedule.runBatches') }}
-
-
-
{{ selectedScheduleRunMetrics.total }}
-
{{ $t('admin.schedule.totalProcessed') }}
-
-
-
{{ selectedScheduleRunMetrics.success }}
-
{{ $t('admin.schedule.totalSuccess') }}
-
-
-
{{ selectedScheduleRunMetrics.failed }}
-
{{ $t('admin.schedule.totalFailed') }}
-
-
-
-
-
-
-
-
{{ $t('admin.schedule.listTitle') }}
- {{ $t('admin.schedule.switchByCard') }}
-
-
-
-
-
-
-
-
-
-
-
{{ $t('admin.schedule.recordsTitle', { name: selectedSchedule.name }) }}
-
{{ $t('admin.schedule.recordsSubtitle') }}
-
-
-
-
-
-
- {{ $t('admin.schedule.noSelectionHint') }}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {{ testRunKbSyncAvailable ? $t('admin.schedule.testRun.writeToKbHint') : $t('admin.schedule.testRun.noKbGroupHint') }}
-
-
-
-
- {{ testRunLoading ? $t('admin.schedule.testRun.running') : $t('admin.schedule.testRun.start') }}
-
- {{ $t('admin.schedule.testRun.waitingHint') }}
-
-
-
-
-
-
{{ testRunResult.total_count }}
-
{{ $t('admin.schedule.testRun.total') }}
-
-
-
{{ testRunResult.success_count }}
-
{{ $t('admin.schedule.testRun.success') }}
-
-
-
{{ testRunResult.failed_count }}
-
{{ $t('admin.schedule.testRun.failed') }}
-
-
-
{{ testRunResult.skipped_count }}
-
{{ $t('admin.schedule.testRun.skipped') }}
-
-
- {{ $t('admin.schedule.testRun.limitSummary', { limit: testRunResult.limit, agentId: testRunResult.dify_agent_id || $t('admin.schedule.testRun.noAgent') }) }}
-
-
-
-
-
Dify 执行快照(审计)
-
-
- Agent:
- {{ testRunResult.dify_execution_snapshot.dify_agent_name || '-' }}
- (ID: {{ testRunResult.dify_execution_snapshot.dify_agent_id ?? '-' }})
-
-
-
System Prompt:
-
{{ testRunResult.dify_execution_snapshot.dify_system_prompt }}
-
(未配置)
-
-
-
本次测试未启用 Dify
-
-
-
-
{{ $t('admin.schedule.testRun.stepLogs') }}
-
-
-
-
- {{ (stepStatusMap[log.status] || { label: log.status }).label }}
-
- {{ stepLabelMap[log.step] || log.step }}
- row_id={{ log.row_id }}
- {{ log.duration_ms }}ms
-
-
- {{ $t('admin.schedule.viewDetail') }}
- {{ JSON.stringify(log.detail, null, 2) }}
-
-
-
-
-
-
- {{ $t('admin.schedule.testRun.viewSql') }}
- {{ testRunResult.sql }}
-
-
-
- {{ $t('admin.schedule.testRun.errors', { count: testRunResult.errors.length }) }}
- {{ testRunResult.errors.join('\n') }}
-
-
-
-
- {{ $t('admin.schedule.kbSync.title') }}
-
-
- {{ $t('admin.schedule.kbSync.status') }}:
- {{ testRunResult.kb_sync_status }}
-
-
- {{ $t('admin.schedule.testRun.kbSyncNoStatus') }}
-
-
- {{ $t('admin.schedule.kbSync.document') }}:
- {{ testRunResult.kb_document_id }}
-
-
- {{ testRunResult.kb_sync_error }}
-
-
-
-
-
-
-
-
-
-
-
{{ scheduleEditingId ? $t('admin.schedule.form.editTitle') : $t('admin.schedule.form.createTitle') }}
-
- ✕
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {{ u.real_name || u.username }}{{ u.employee_id ? '(' + u.employee_id + ')' : '' }}
-
-
- {{ $t('admin.wecom.noData') }}
-
-
-
-
-
-
-
-
-
{{ $t('admin.schedule.form.dataSourceConfig') }}
-
-
- {{ $t('admin.schedule.form.databaseDirect') }}
- {{ $t('admin.schedule.form.externalApi') }}
-
-
- {{ scheduleTestLoading ? $t('admin.schedule.form.querying') : $t('admin.schedule.form.testQuery') }}
-
-
-
-
- {{ scheduleConfigCollapsed ? $t('admin.schedule.form.expandConfig') : $t('admin.schedule.form.collapseConfig') }}
-
-
-
-
-
-
-
-
- {{ $t('admin.schedule.form.dataSourceSection') }}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
值支持 ${环境变量名} 格式,运行时自动从环境变量解析(推荐密码使用此方式)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
{{ $t('admin.schedule.testRun.queryResult') }}
-
- {{ $t('admin.schedule.testRun.resultSummary', { total: scheduleTestResult.total, showing: scheduleTestResult.showing }) }}
- ✕
-
-
-
-
-
-
- | {{ col }} |
-
-
-
-
- | {{ row[col] }} |
-
-
-
-
-
- {{ $t('admin.schedule.testRun.viewGeneratedSql') }}
- {{ scheduleTestResult.sql }}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
{{ $t('admin.schedule.form.kbSyncHint') }}
-
-
-
-
-
-
-
-
-
-
仅在启用 Dify Agent 时可配置。保存后将作为 system_prompt 传入 Workflow;编排中 LLM 节点需引用该变量。
-
-
-
-
-
-
-
{{ $t('admin.schedule.form.cronTitle') }}
-
{{ $t('admin.schedule.form.cronHint') }}
-
-
-
- {{ $t('admin.schedule.form.everyMinutes') }}
-
-
- {{ $t('admin.schedule.form.hourly') }}
-
-
- {{ $t('admin.schedule.form.daily') }}
-
-
- {{ $t('admin.schedule.form.weekly') }}
-
-
-
-
-
- {{ $t('admin.schedule.form.cronPreview') }}:{{ scheduleCronPreview }}
- {{ $t('admin.schedule.form.nextRun') }}:{{ formatDateTime(scheduleNextRunPreview.toISOString()) }}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
diff --git a/frontend/src/features/admin/modules/schedules/components/ScheduleCreateEditModal.vue b/frontend/src/features/admin/modules/schedules/components/ScheduleCreateEditModal.vue
new file mode 100644
index 00000000..377c6254
--- /dev/null
+++ b/frontend/src/features/admin/modules/schedules/components/ScheduleCreateEditModal.vue
@@ -0,0 +1,534 @@
+
+
+
+
+
+
+
{{ admin.scheduleEditingId ? $t('admin.schedule.form.editTitle') : $t('admin.schedule.form.createTitle') }}
+
+ ✕
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {{ u.real_name || u.username }}{{ u.employee_id ? '(' + u.employee_id + ')' : '' }}
+
+
+ {{ $t('admin.wecom.noData') }}
+
+
+
+
+
+
+
+
+
{{ $t('admin.schedule.form.dataSourceConfig') }}
+
+
+ {{ $t('admin.schedule.form.databaseDirect') }}
+ {{ $t('admin.schedule.form.externalApi') }}
+
+
+ {{ admin.scheduleTestLoading ? $t('admin.schedule.form.querying') : $t('admin.schedule.form.testQuery') }}
+
+
+
+
+ {{ admin.scheduleConfigCollapsed ? $t('admin.schedule.form.expandConfig') : $t('admin.schedule.form.collapseConfig') }}
+
+
+
+
+
+
+
+
+ {{ $t('admin.schedule.form.dataSourceSection') }}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
{{ $t('admin.schedule.form.envVarHint', { token: $t('admin.schedule.form.envVarToken') }) }}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
{{ $t('admin.schedule.testRun.queryResult') }}
+
+ {{ $t('admin.schedule.testRun.resultSummary', { total: admin.scheduleTestResult.total, showing: admin.scheduleTestResult.showing }) }}
+ ✕
+
+
+
+
+
+
+ | {{ col }} |
+
+
+
+
+ | {{ row[col] }} |
+
+
+
+
+
+ {{ $t('admin.schedule.testRun.viewGeneratedSql') }}
+ {{ admin.scheduleTestResult.sql }}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
{{ $t('admin.schedule.form.kbSyncHint') }}
+
+
+
+
+
+
+
+
+
+
{{ $t('admin.schedule.form.difySystemPromptHint') }}
+
+
+
+
+
+
+
{{ $t('admin.schedule.form.cronTitle') }}
+
{{ $t('admin.schedule.form.cronHint') }}
+
+
+
+ {{ $t('admin.schedule.form.everyMinutes') }}
+
+
+ {{ $t('admin.schedule.form.hourly') }}
+
+
+ {{ $t('admin.schedule.form.daily') }}
+
+
+ {{ $t('admin.schedule.form.weekly') }}
+
+
+
+
+
+ {{ $t('admin.schedule.form.cronPreview') }}:{{ admin.scheduleCronPreview }}
+ {{ $t('admin.schedule.form.nextRun') }}:{{ admin.formatDateTime(admin.scheduleNextRunPreview.toISOString()) }}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/frontend/src/features/admin/modules/schedules/components/ScheduleOverviewPanel.vue b/frontend/src/features/admin/modules/schedules/components/ScheduleOverviewPanel.vue
new file mode 100644
index 00000000..f9273c50
--- /dev/null
+++ b/frontend/src/features/admin/modules/schedules/components/ScheduleOverviewPanel.vue
@@ -0,0 +1,149 @@
+/**
+ * features/admin/modules/schedules/components/ScheduleOverviewPanel.vue
+ * 定时任务概览模式:统计卡片与任务卡片网格。
+ * 依赖:schedules.context、lucide-vue-next。
+ * 逻辑:inject admin;展示 schedules 列表与快捷操作。
+ */
+
+
+
+
+
+
+
{{ admin.schedules.length }}
+
{{ $t('admin.schedule.stats.total') }}
+
+
+
{{ admin.scheduleEnabledCount }}
+
{{ $t('admin.schedule.stats.enabled') }}
+
+
+
{{ admin.scheduleDisabledCount }}
+
{{ $t('admin.schedule.stats.disabled') }}
+
+
+
{{ admin.scheduleRunningCount }}
+
{{ $t('admin.schedule.stats.running') }}
+
+
+
+
+
{{ $t('admin.schedule.sectionOverview') }}
+ {{ $t('admin.schedule.switchByCard') }}
+
+
{{ $t('admin.schedule.loading') }}
+
+
+
+
+
+
+
{{ $t('admin.schedule.addTitle') }}
+
+
+ {{ $t('admin.schedule.addHint') }}
+
+
+
+
+ {{ $t('admin.schedule.addButton') }}
+
+
+
+
+
+
+
+
+
{{ s.name }}
+
+ {{ s.enabled ? $t('admin.schedule.enabled') : $t('admin.schedule.disabled') }}
+
+
+
{{ $t('admin.schedule.scheduleNo') }}:{{ s.schedule_no }}
+
Cron:{{ s.cron_expr }}
+
+ {{ $t('admin.schedule.config') }}:{{ s.platform_api_path }}
+
+
{{ $t('admin.schedule.owner') }}:{{ s.owner_username || s.owner_user_id }}
+
+
+
+
+ {{ $t('admin.schedule.lastRun') }}:{{ admin.formatDateTime(s.last_run_at) }}
+
+
+ {{ $t('admin.schedule.nextRun') }}:{{ admin.formatDateTime(s.next_run_at) }}
+
+
+
+
+ {{ $t('admin.schedule.actions.edit') }}
+
+
+
+ {{ $t('admin.schedule.actions.start') }}
+
+
+
+ {{ $t('admin.schedule.actions.pause') }}
+
+
+
+ {{ $t('admin.schedule.actions.run') }}
+
+
+
+ {{ $t('admin.schedule.actions.test') }}
+
+
+
+ {{ $t('admin.schedule.actions.delete') }}
+
+
+
+
+
+ {{ $t('admin.schedule.emptyList') }}
+
+
+
+
+
diff --git a/frontend/src/features/admin/modules/schedules/components/SchedulePageHeader.vue b/frontend/src/features/admin/modules/schedules/components/SchedulePageHeader.vue
new file mode 100644
index 00000000..3ea3da8b
--- /dev/null
+++ b/frontend/src/features/admin/modules/schedules/components/SchedulePageHeader.vue
@@ -0,0 +1,46 @@
+/**
+ * features/admin/modules/schedules/components/SchedulePageHeader.vue
+ * 定时任务页顶栏:返回、标题、刷新。
+ * 依赖:schedules.context、lucide-vue-next。
+ * 逻辑:inject admin 上下文;概览/工作台模式切换标题与返回按钮。
+ */
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {{ admin.scheduleViewMode === 'overview' ? $t('admin.schedule.overviewTitle') : $t('admin.schedule.workbenchTitle') }}
+
+
+ {{ admin.scheduleViewMode === 'overview' ? $t('admin.schedule.overviewSubtitle') : $t('admin.schedule.workbenchSubtitle') }}
+
+
+
+
+
+ {{ $t('admin.schedule.refresh') }}
+
+
+
+
diff --git a/frontend/src/features/admin/modules/schedules/components/ScheduleTestRunDialog.vue b/frontend/src/features/admin/modules/schedules/components/ScheduleTestRunDialog.vue
new file mode 100644
index 00000000..a46c09c3
--- /dev/null
+++ b/frontend/src/features/admin/modules/schedules/components/ScheduleTestRunDialog.vue
@@ -0,0 +1,183 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {{ admin.testRunKbSyncAvailable ? $t('admin.schedule.testRun.writeToKbHint') : $t('admin.schedule.testRun.noKbGroupHint') }}
+
+
+
+
+ {{ admin.testRunLoading ? $t('admin.schedule.testRun.running') : $t('admin.schedule.testRun.start') }}
+
+ {{ $t('admin.schedule.testRun.waitingHint') }}
+
+
+
+
+
+
{{ admin.testRunResult.total_count }}
+
{{ $t('admin.schedule.testRun.total') }}
+
+
+
{{ admin.testRunResult.success_count }}
+
{{ $t('admin.schedule.testRun.success') }}
+
+
+
{{ admin.testRunResult.failed_count }}
+
{{ $t('admin.schedule.testRun.failed') }}
+
+
+
{{ admin.testRunResult.skipped_count }}
+
{{ $t('admin.schedule.testRun.skipped') }}
+
+
+ {{ $t('admin.schedule.testRun.limitSummary', { limit: admin.testRunResult.limit, agentId: admin.testRunResult.dify_agent_id || $t('admin.schedule.testRun.noAgent') }) }}
+
+
+
+
+
{{ $t('admin.schedule.difySnapshot.title') }}
+
+
+ {{ $t('admin.schedule.difySnapshot.agent') }}:
+ {{ admin.testRunResult.dify_execution_snapshot.dify_agent_name || '-' }}
+ {{ $t('admin.schedule.difySnapshot.agentId', { id: admin.testRunResult.dify_execution_snapshot.dify_agent_id ?? '-' }) }}
+
+
+
{{ $t('admin.schedule.difySnapshot.systemPrompt') }}:
+
{{ admin.testRunResult.dify_execution_snapshot.dify_system_prompt }}
+
{{ $t('admin.schedule.difySnapshot.notConfigured') }}
+
+
+
{{ $t('admin.schedule.difySnapshot.notEnabledTest') }}
+
+
+
+
{{ $t('admin.schedule.testRun.stepLogs') }}
+
+
+
+
+ {{ (admin.stepStatusMap[log.status] || { label: log.status }).label }}
+
+ {{ admin.stepLabelMap[log.step] || log.step }}
+ row_id={{ log.row_id }}
+ {{ log.duration_ms }}ms
+
+
+ {{ $t('admin.schedule.viewDetail') }}
+ {{ JSON.stringify(log.detail, null, 2) }}
+
+
+
+
+
+
+ {{ $t('admin.schedule.testRun.viewSql') }}
+ {{ admin.testRunResult.sql }}
+
+
+
+ {{ $t('admin.schedule.testRun.errors', { count: admin.testRunResult.errors.length }) }}
+ {{ admin.testRunResult.errors.join('\n') }}
+
+
+
+
+ {{ $t('admin.schedule.kbSync.title') }}
+
+
+ {{ $t('admin.schedule.kbSync.status') }}:
+ {{ admin.testRunResult.kb_sync_status }}
+
+
+ {{ $t('admin.schedule.testRun.kbSyncNoStatus') }}
+
+
+ {{ $t('admin.schedule.kbSync.document') }}:
+ {{ admin.testRunResult.kb_document_id }}
+
+
+ {{ admin.testRunResult.kb_sync_error }}
+
+
+
+
+
+
+
diff --git a/frontend/src/features/admin/modules/schedules/components/ScheduleWorkbenchPanel.vue b/frontend/src/features/admin/modules/schedules/components/ScheduleWorkbenchPanel.vue
new file mode 100644
index 00000000..504bf378
--- /dev/null
+++ b/frontend/src/features/admin/modules/schedules/components/ScheduleWorkbenchPanel.vue
@@ -0,0 +1,334 @@
+/**
+ * features/admin/modules/schedules/components/ScheduleWorkbenchPanel.vue
+ * 定时任务工作台模式:侧边任务列表与运行记录表格。
+ * 依赖:schedules.context、lucide-vue-next。
+ * 逻辑:inject admin;筛选/查询运行记录、展开日志详情。
+ */
+
+
+
+
+
+
+
{{ admin.selectedSchedule?.name || $t('admin.schedule.noSelection') }}
+
{{ $t('admin.schedule.selectedHint', { time: admin.selectedScheduleLatestRunAt }) }}
+
+
+
{{ admin.selectedScheduleRuns.length }}
+
{{ $t('admin.schedule.runBatches') }}
+
+
+
{{ admin.selectedScheduleRunMetrics.total }}
+
{{ $t('admin.schedule.totalProcessed') }}
+
+
+
{{ admin.selectedScheduleRunMetrics.success }}
+
{{ $t('admin.schedule.totalSuccess') }}
+
+
+
{{ admin.selectedScheduleRunMetrics.failed }}
+
{{ $t('admin.schedule.totalFailed') }}
+
+
+
+
+
+
+
+
{{ $t('admin.schedule.listTitle') }}
+ {{ $t('admin.schedule.switchByCard') }}
+
+
+
+
+
+
{{ s.name }}
+
{{ s.schedule_no }}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {{ s.enabled ? $t('admin.schedule.enabled') : $t('admin.schedule.disabled') }}
+
+
+
+
+
+
+
+
+
+
+
{{ $t('admin.schedule.recordsTitle', { name: admin.selectedSchedule.name }) }}
+
{{ $t('admin.schedule.recordsSubtitle') }}
+
+
+
+
+
+
+ {{ $t('admin.schedule.noSelectionHint') }}
+
+
+
+
+
+
diff --git a/frontend/src/features/admin/modules/schedules/components/SchedulesPageOverlays.vue b/frontend/src/features/admin/modules/schedules/components/SchedulesPageOverlays.vue
new file mode 100644
index 00000000..dbae864f
--- /dev/null
+++ b/frontend/src/features/admin/modules/schedules/components/SchedulesPageOverlays.vue
@@ -0,0 +1,24 @@
+
+
+
+
+
+
+
diff --git a/frontend/src/features/admin/modules/schedules/composables/schedule-admin/schedule-admin.state.ts b/frontend/src/features/admin/modules/schedules/composables/schedule-admin/schedule-admin.state.ts
new file mode 100644
index 00000000..9dc8381c
--- /dev/null
+++ b/frontend/src/features/admin/modules/schedules/composables/schedule-admin/schedule-admin.state.ts
@@ -0,0 +1,158 @@
+/**
+ * features/admin/modules/schedules/composables/schedule-admin/schedule-admin.state.ts
+ * 定时任务管理页共享 ref 与删除确认弹窗状态。
+ */
+import { ref } from 'vue';
+import type { ScheduleRun, ScheduleTask, TestScheduleRunResult } from '@/features/admin/api/schedule.api';
+import type { AdminAgentOption, AdminUserRow } from '@/features/admin/types/admin.types';
+import type { KbGroup } from '@/features/kb/api/kb.api';
+import {
+ createDefaultCronDesigner,
+ createDefaultScheduleCreateForm,
+ createDefaultScheduleSqlEditForm,
+} from '../../types/schedule-admin.types';
+
+export function createScheduleAdminState() {
+ const agents = ref([]);
+ const users = ref([]);
+ const kbGroups = ref([]);
+
+ const showDeleteConfirmDialog = ref(false);
+ const deleteConfirmTitle = ref('');
+ const deleteConfirmMessage = ref('');
+ let deleteConfirmAction: (() => Promise | void) | null = null;
+
+ const openDeleteConfirm = (
+ message: string,
+ onConfirm: () => Promise | void,
+ title = '',
+ ): void => {
+ deleteConfirmTitle.value = title;
+ deleteConfirmMessage.value = message;
+ deleteConfirmAction = onConfirm;
+ showDeleteConfirmDialog.value = true;
+ };
+
+ const closeDeleteConfirm = (): void => {
+ showDeleteConfirmDialog.value = false;
+ deleteConfirmTitle.value = '';
+ deleteConfirmMessage.value = '';
+ deleteConfirmAction = null;
+ };
+
+ const confirmDelete = async (): Promise => {
+ if (!deleteConfirmAction) return;
+ try {
+ await deleteConfirmAction();
+ } finally {
+ closeDeleteConfirm();
+ }
+ };
+
+ const schedules = ref([]);
+ const schedulesLoaded = ref(false);
+ void schedulesLoaded;
+ const selectedScheduleRuns = ref([]);
+ const scheduleLoading = ref(false);
+ const scheduleRunsLoading = ref(false);
+ const selectedScheduleId = ref(null);
+ const scheduleRunStatusFilter = ref<'all' | string>('all');
+ const scheduleRunStartedAfter = ref('');
+ const scheduleRunStartedBefore = ref('');
+ const scheduleRunColumnDefs = ref([
+ { key: 'run_no', label: '', width: 280, min: 60 },
+ { key: 'started_at', label: '', width: 190, min: 60 },
+ { key: 'finished_at', label: '', width: 190, min: 60 },
+ { key: 'status', label: '', width: 130, min: 50 },
+ { key: 'total_count', label: '', width: 70, min: 40 },
+ { key: 'success_count', label: '', width: 70, min: 40 },
+ { key: 'failed_count', label: '', width: 70, min: 40 },
+ { key: 'wecom_notified', label: '', width: 100, min: 80 },
+ { key: 'detail', label: '', width: 100, min: 80 },
+ { key: 'log', label: '', width: 100, min: 80 },
+ ]);
+ const resizingScheduleCol = ref<{ index: number; startX: number; startWidth: number } | null>(null);
+
+ const scheduleViewMode = ref<'overview' | 'workbench'>('overview');
+ const showScheduleCreateModal = ref(false);
+ const scheduleCreateSaving = ref(false);
+ const scheduleEditingId = ref(null);
+ const scheduleCreateForm = ref(createDefaultScheduleCreateForm());
+ const scheduleConfigCollapsed = ref(true);
+ const scheduleCronDesigner = ref(createDefaultCronDesigner());
+
+ const expandedScheduleRunId = ref(null);
+
+ const showTestRunDialog = ref(false);
+ const testRunSchedule = ref(null);
+ const testRunWhere = ref('');
+ const testRunOrderBy = ref('');
+ const testRunBaseFetchSql = ref('');
+ const testRunLimit = ref(3);
+ const testRunKbSync = ref(false);
+ const testRunKbSyncAttempted = ref(false);
+ const testRunLoading = ref(false);
+ const testRunResult = ref(null);
+
+ const scheduleSqlEditForm = ref(createDefaultScheduleSqlEditForm());
+ const scheduleSqlSaving = ref(false);
+ void scheduleSqlSaving;
+ const scheduleTestLoading = ref(false);
+ const scheduleTestResult = ref<{ total: number; showing: number; columns: string[]; rows: any[]; sql: string } | null>(null);
+
+ const scheduleNotifyDropdownOpen = ref(false);
+ const scheduleNotifyUserQuery = ref('');
+ const scheduleOwnerDropdownOpen = ref(false);
+ const scheduleOwnerQuery = ref('');
+
+ return {
+ agents,
+ users,
+ kbGroups,
+ showDeleteConfirmDialog,
+ deleteConfirmTitle,
+ deleteConfirmMessage,
+ openDeleteConfirm,
+ closeDeleteConfirm,
+ confirmDelete,
+ schedules,
+ schedulesLoaded,
+ selectedScheduleRuns,
+ scheduleLoading,
+ scheduleRunsLoading,
+ selectedScheduleId,
+ scheduleRunStatusFilter,
+ scheduleRunStartedAfter,
+ scheduleRunStartedBefore,
+ scheduleRunColumnDefs,
+ resizingScheduleCol,
+ scheduleViewMode,
+ showScheduleCreateModal,
+ scheduleCreateSaving,
+ scheduleEditingId,
+ scheduleCreateForm,
+ scheduleConfigCollapsed,
+ scheduleCronDesigner,
+ expandedScheduleRunId,
+ showTestRunDialog,
+ testRunSchedule,
+ testRunWhere,
+ testRunOrderBy,
+ testRunBaseFetchSql,
+ testRunLimit,
+ testRunKbSync,
+ testRunKbSyncAttempted,
+ testRunLoading,
+ testRunResult,
+ scheduleSqlEditForm,
+ scheduleSqlSaving,
+ scheduleTestLoading,
+ scheduleTestResult,
+ scheduleNotifyDropdownOpen,
+ scheduleNotifyUserQuery,
+ scheduleOwnerDropdownOpen,
+ scheduleOwnerQuery,
+ };
+}
+
+export type ScheduleAdminState = ReturnType;
diff --git a/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminForm.ts b/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminForm.ts
new file mode 100644
index 00000000..b5de5cbc
--- /dev/null
+++ b/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminForm.ts
@@ -0,0 +1,359 @@
+/**
+ * features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminForm.ts
+ * 创建/编辑弹窗:Cron 设计器、负责人/通知人、SQL 配置与提交。
+ */
+import { computed, watch } from 'vue';
+import type { ComposerTranslation } from 'vue-i18n';
+import {
+ createAdminSchedule,
+ getAdminScheduleTaskConfig,
+ testAdminScheduleSql,
+ updateAdminSchedule,
+ type ScheduleTask,
+} from '@/features/admin/api/schedule.api';
+import type { AdminUserRow } from '@/features/admin/types/admin.types';
+import { useMessage } from '@/shared/composables/useMessage';
+import {
+ createDefaultCronDesigner,
+ createDefaultScheduleCreateForm,
+ createDefaultScheduleSqlEditForm,
+} from '../../types/schedule-admin.types';
+import { buildScheduleConfigPayload } from '../../utils/schedule-form-payload.utils';
+import {
+ buildCronExprFromDesigner,
+ computeNextRunPreview,
+ parseCronExprToDesigner,
+} from '../../utils/schedule-cron.utils';
+import type { ScheduleAdminState } from './schedule-admin.state';
+import type { ScheduleAdminLookups } from './useScheduleAdminLookups';
+import type { ScheduleAdminList } from './useScheduleAdminList';
+import type { ScheduleAdminRuns } from './useScheduleAdminRuns';
+
+export function useScheduleAdminForm(
+ state: ScheduleAdminState,
+ lookups: Pick,
+ list: Pick,
+ runs: Pick,
+ t: ComposerTranslation,
+) {
+ const msg = useMessage();
+ const {
+ users,
+ showScheduleCreateModal,
+ scheduleCreateSaving,
+ scheduleEditingId,
+ scheduleCreateForm,
+ scheduleConfigCollapsed,
+ scheduleCronDesigner,
+ scheduleSqlEditForm,
+ scheduleTestLoading,
+ scheduleTestResult,
+ scheduleNotifyDropdownOpen,
+ scheduleNotifyUserQuery,
+ scheduleOwnerDropdownOpen,
+ scheduleOwnerQuery,
+ } = state;
+
+ let scheduleNotifyCloseTimer: ReturnType | null = null;
+ let scheduleOwnerCloseTimer: ReturnType | null = null;
+
+ const weeklyDayOptions = computed(() => [
+ { value: 1, label: t('admin.schedule.weekday.mon') },
+ { value: 2, label: t('admin.schedule.weekday.tue') },
+ { value: 3, label: t('admin.schedule.weekday.wed') },
+ { value: 4, label: t('admin.schedule.weekday.thu') },
+ { value: 5, label: t('admin.schedule.weekday.fri') },
+ { value: 6, label: t('admin.schedule.weekday.sat') },
+ { value: 0, label: t('admin.schedule.weekday.sun') },
+ ]);
+
+ const scheduleCronPreview = computed(() => buildCronExprFromDesigner(scheduleCronDesigner.value));
+ const scheduleNextRunPreview = computed(() => computeNextRunPreview(scheduleCronPreview.value));
+
+ const formatUserOptionLabel = (u: AdminUserRow) =>
+ `${u.real_name || u.username}${u.employee_id ? `(${u.employee_id})` : ''}`;
+
+ const filteredNotifyUsers = computed(() => {
+ const keyword = scheduleNotifyUserQuery.value.trim().toLowerCase();
+ return users.value.filter((u) => {
+ if (!keyword) return true;
+ return [u.real_name, u.username, u.employee_id, String(u.id)]
+ .filter(Boolean)
+ .some((val) => String(val).toLowerCase().includes(keyword));
+ });
+ });
+
+ const filteredOwnerUsers = computed(() => {
+ const keyword = scheduleOwnerQuery.value.trim().toLowerCase();
+ return users.value.filter((u) => {
+ if (!keyword) return true;
+ return [u.real_name, u.username, u.employee_id, String(u.id)]
+ .filter(Boolean)
+ .some((val) => String(val).toLowerCase().includes(keyword));
+ });
+ });
+
+ const syncScheduleOwnerQuery = (): void => {
+ const ownerId = scheduleCreateForm.value.owner_user_id;
+ if (!ownerId) {
+ scheduleOwnerQuery.value = '';
+ return;
+ }
+ const u = users.value.find((x) => x.id === ownerId);
+ scheduleOwnerQuery.value = u ? formatUserOptionLabel(u) : String(ownerId);
+ };
+
+ const resetScheduleCreateForm = () => {
+ scheduleEditingId.value = null;
+ scheduleCreateForm.value = createDefaultScheduleCreateForm();
+ scheduleSqlEditForm.value = createDefaultScheduleSqlEditForm();
+ scheduleTestResult.value = null;
+ scheduleNotifyUserQuery.value = '';
+ scheduleNotifyDropdownOpen.value = false;
+ scheduleOwnerQuery.value = '';
+ scheduleOwnerDropdownOpen.value = false;
+ scheduleCronDesigner.value = createDefaultCronDesigner();
+ };
+
+ const openScheduleCreateModal = async () => {
+ resetScheduleCreateForm();
+ scheduleConfigCollapsed.value = true;
+ await Promise.all([lookups.loadAgents(), lookups.loadUsers(), lookups.loadKbGroups()]);
+ showScheduleCreateModal.value = true;
+ };
+
+ const openScheduleEditModal = async (task: ScheduleTask) => {
+ await Promise.all([lookups.loadAgents(), lookups.loadUsers(), lookups.loadKbGroups()]);
+ scheduleConfigCollapsed.value = true;
+ scheduleNotifyUserQuery.value = '';
+ scheduleNotifyDropdownOpen.value = false;
+ scheduleOwnerDropdownOpen.value = false;
+ scheduleEditingId.value = task.id;
+ scheduleCreateForm.value = {
+ name: task.name || '',
+ platform_api_path: task.platform_api_path || '',
+ dify_agent_id: task.dify_agent_id || null,
+ owner_user_id: task.owner_user_id || null,
+ wait_seconds: task.wait_seconds || 0,
+ notify_enabled: !!task.notify_enabled,
+ notify_user_ids_json: task.notify_user_ids_json || [],
+ kb_sync_enabled: !!task.kb_sync_enabled,
+ kb_group_id: task.kb_group_id || null,
+ enabled: !!task.enabled,
+ data_source_type: (task.data_source_type || 'database') as 'database' | 'external_api',
+ };
+
+ try {
+ const result = await getAdminScheduleTaskConfig(task.id);
+ const cfg = result.config;
+ scheduleCreateForm.value.data_source_type = (result.data_source_type || 'database') as 'database' | 'external_api';
+ if (cfg) {
+ scheduleSqlEditForm.value = {
+ base_fetch_sql: cfg.base_fetch_sql || '',
+ fetch_where_conditions: cfg.fetch_where_conditions || '',
+ fetch_order_by: cfg.fetch_order_by || '',
+ detail_sql: cfg.detail_sql || '',
+ writeback_sql: cfg.writeback_sql || '',
+ row_id_key: cfg.row_id_key || 'id',
+ log_prefix: cfg.log_prefix || '',
+ alias_order_str: (cfg.alias_order || []).join(','),
+ detail_alias_order_str: (cfg.detail_alias_order || []).join(','),
+ header_labels_str: cfg.header_labels ? JSON.stringify(cfg.header_labels, null, 2) : '{}',
+ ds_db_type: cfg.data_source?.db_type || 'sqlserver',
+ ds_host: cfg.data_source?.host || '',
+ ds_port: cfg.data_source?.port || '',
+ ds_database: cfg.data_source?.database || '',
+ ds_username: cfg.data_source?.username || '',
+ ds_password: cfg.data_source?.password || '',
+ ds_driver: cfg.data_source?.driver || '',
+ ds_encrypt: cfg.data_source?.encrypt || '',
+ ds_trust_cert: cfg.data_source?.trust_cert || '',
+ api_url: cfg.external_api?.url || '',
+ api_method: cfg.external_api?.method || 'POST',
+ api_headers_str: cfg.external_api?.headers ? JSON.stringify(cfg.external_api.headers, null, 2) : '{}',
+ api_body_template: cfg.external_api?.body_template || '',
+ dify_system_prompt: cfg.dify_system_prompt || '',
+ };
+ }
+ } catch {
+ scheduleSqlEditForm.value = createDefaultScheduleSqlEditForm();
+ }
+
+ scheduleTestResult.value = null;
+ scheduleCronDesigner.value = parseCronExprToDesigner(task.cron_expr);
+ syncScheduleOwnerQuery();
+ showScheduleCreateModal.value = true;
+ };
+
+ const scheduleCloseNotifyDropdown = (): void => {
+ if (scheduleNotifyCloseTimer) clearTimeout(scheduleNotifyCloseTimer);
+ scheduleNotifyCloseTimer = setTimeout(() => {
+ scheduleNotifyDropdownOpen.value = false;
+ }, 150);
+ };
+
+ const selectScheduleOwner = (id: number): void => {
+ const u = users.value.find((x) => x.id === id);
+ if (!u) return;
+ scheduleCreateForm.value.owner_user_id = id;
+ scheduleOwnerQuery.value = formatUserOptionLabel(u);
+ scheduleOwnerDropdownOpen.value = false;
+ };
+
+ const handleScheduleOwnerInput = (): void => {
+ scheduleOwnerDropdownOpen.value = true;
+ const ownerId = scheduleCreateForm.value.owner_user_id;
+ if (!ownerId) return;
+ const u = users.value.find((x) => x.id === ownerId);
+ const currentLabel = u ? formatUserOptionLabel(u) : '';
+ if (scheduleOwnerQuery.value.trim() !== currentLabel) {
+ scheduleCreateForm.value.owner_user_id = null;
+ }
+ };
+
+ const scheduleCloseOwnerDropdown = (): void => {
+ if (scheduleOwnerCloseTimer) clearTimeout(scheduleOwnerCloseTimer);
+ scheduleOwnerCloseTimer = setTimeout(() => {
+ scheduleOwnerDropdownOpen.value = false;
+ }, 150);
+ };
+
+ watch(() => scheduleCreateForm.value.dify_agent_id, (agentId) => {
+ if (!agentId) {
+ scheduleSqlEditForm.value.dify_system_prompt = '';
+ }
+ });
+
+ const getUserName = (uid: number) => {
+ const u = users.value.find((x) => x.id === uid);
+ return u ? (u.real_name || u.username) : String(uid);
+ };
+
+ const toggleNotifyUser = (uid: number) => {
+ const notifyList = scheduleCreateForm.value.notify_user_ids_json;
+ if (notifyList.includes(uid)) {
+ scheduleCreateForm.value.notify_user_ids_json = notifyList.filter((id: number) => id !== uid);
+ } else {
+ scheduleCreateForm.value.notify_user_ids_json = [...notifyList, uid];
+ }
+ };
+
+ const removeNotifyUser = (uid: number) => {
+ scheduleCreateForm.value.notify_user_ids_json = scheduleCreateForm.value.notify_user_ids_json.filter((id: number) => id !== uid);
+ };
+
+ const handleTestScheduleSql = async () => {
+ const taskId = scheduleEditingId.value;
+ if (!taskId) return;
+
+ scheduleTestLoading.value = true;
+ scheduleTestResult.value = null;
+ try {
+ const result = await testAdminScheduleSql(taskId, {
+ fetch_where_conditions: scheduleSqlEditForm.value.fetch_where_conditions,
+ fetch_order_by: scheduleSqlEditForm.value.fetch_order_by,
+ limit: 10,
+ });
+ scheduleTestResult.value = result;
+ } catch (e: any) {
+ msg.error(`${t('admin.schedule.msg.testQueryFailed')}: ${e?.message || e}`);
+ } finally {
+ scheduleTestLoading.value = false;
+ }
+ };
+
+ const createSchedule = async () => {
+ if (!scheduleCreateForm.value.name || !scheduleCreateForm.value.owner_user_id) return;
+
+ const dst = scheduleCreateForm.value.data_source_type;
+ const hasAgent = !!scheduleCreateForm.value.dify_agent_id;
+ const hasSql = dst === 'database' && !!scheduleSqlEditForm.value.base_fetch_sql.trim();
+ const hasApi = dst === 'external_api' && !!scheduleSqlEditForm.value.api_url.trim();
+ if (!hasAgent && !hasSql && !hasApi) {
+ msg.error(t('admin.schedule.msg.configRequired'));
+ return;
+ }
+
+ let headerLabels: Record = {};
+ try {
+ headerLabels = JSON.parse(scheduleSqlEditForm.value.header_labels_str || '{}');
+ } catch {
+ msg.error(t('admin.schedule.msg.headerLabelsJsonInvalid'));
+ return;
+ }
+ let apiHeaders: Record = {};
+ if (dst === 'external_api') {
+ try {
+ apiHeaders = JSON.parse(scheduleSqlEditForm.value.api_headers_str || '{}');
+ } catch {
+ msg.error(t('admin.schedule.msg.apiHeadersJsonInvalid'));
+ return;
+ }
+ }
+
+ let configPayload: Record;
+ configPayload = buildScheduleConfigPayload(
+ scheduleSqlEditForm.value,
+ hasAgent,
+ headerLabels,
+ apiHeaders,
+ );
+
+ scheduleCreateSaving.value = true;
+ try {
+ const payload: Record = {
+ name: scheduleCreateForm.value.name,
+ schedule_type: 'platform_app',
+ owner_user_id: scheduleCreateForm.value.owner_user_id,
+ cron_expr: scheduleCronPreview.value,
+ wait_seconds: Math.max(0, Number(scheduleCreateForm.value.wait_seconds || 0)),
+ dify_agent_id: scheduleCreateForm.value.dify_agent_id || undefined,
+ notify_user_ids_json: scheduleCreateForm.value.notify_enabled ? scheduleCreateForm.value.notify_user_ids_json : [],
+ notify_enabled: scheduleCreateForm.value.notify_enabled,
+ kb_sync_enabled: scheduleCreateForm.value.kb_sync_enabled,
+ kb_group_id: scheduleCreateForm.value.kb_sync_enabled ? scheduleCreateForm.value.kb_group_id : null,
+ enabled: scheduleCreateForm.value.enabled,
+ data_source_type: dst,
+ config: configPayload,
+ };
+ let resultData: { id?: number; schedule?: { id?: number } } | null = null;
+ if (scheduleEditingId.value) {
+ resultData = await updateAdminSchedule(scheduleEditingId.value, payload) as { id?: number; schedule?: { id?: number } };
+ } else {
+ resultData = await createAdminSchedule(payload) as { id?: number; schedule?: { id?: number } };
+ }
+ const createdId = resultData?.id ?? resultData?.schedule?.id ?? null;
+ const targetId = scheduleEditingId.value || createdId;
+ showScheduleCreateModal.value = false;
+ await list.loadSchedules();
+ if (targetId) {
+ await runs.viewScheduleRuns(targetId);
+ }
+ } catch (err: any) {
+ msg.error(err?.message || t('common.errorOccurred'));
+ } finally {
+ scheduleCreateSaving.value = false;
+ }
+ };
+
+ return {
+ weeklyDayOptions,
+ scheduleCronPreview,
+ scheduleNextRunPreview,
+ filteredNotifyUsers,
+ filteredOwnerUsers,
+ openScheduleCreateModal,
+ openScheduleEditModal,
+ scheduleCloseNotifyDropdown,
+ selectScheduleOwner,
+ handleScheduleOwnerInput,
+ scheduleCloseOwnerDropdown,
+ getUserName,
+ toggleNotifyUser,
+ removeNotifyUser,
+ handleTestScheduleSql,
+ createSchedule,
+ };
+}
+
+export type ScheduleAdminForm = ReturnType;
diff --git a/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminList.ts b/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminList.ts
new file mode 100644
index 00000000..fa103443
--- /dev/null
+++ b/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminList.ts
@@ -0,0 +1,136 @@
+/**
+ * features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminList.ts
+ * 任务列表加载、概览统计、启停/立即执行/删除与视图切换。
+ */
+import { computed } from 'vue';
+import type { ComposerTranslation } from 'vue-i18n';
+import {
+ deleteAdminSchedule,
+ listAdminSchedules,
+ runAdminSchedule,
+ toggleAdminSchedule,
+ type ScheduleTask,
+} from '@/features/admin/api/schedule.api';
+import { useMessage } from '@/shared/composables/useMessage';
+import type { ScheduleAdminState } from './schedule-admin.state';
+import type { ScheduleAdminRuns } from './useScheduleAdminRuns';
+
+export function useScheduleAdminList(
+ state: ScheduleAdminState,
+ runs: Pick,
+ t: ComposerTranslation,
+) {
+ const msg = useMessage();
+ const {
+ schedules,
+ scheduleLoading,
+ selectedScheduleId,
+ selectedScheduleRuns,
+ scheduleViewMode,
+ openDeleteConfirm,
+ } = state;
+
+ const scheduleEnabledCount = computed(() => schedules.value.filter((item) => item.enabled).length);
+ const scheduleDisabledCount = computed(() => schedules.value.filter((item) => !item.enabled).length);
+ const scheduleRunningCount = computed(() => schedules.value.filter((item) => item.last_status === 'running').length);
+
+ const loadSchedules = async () => {
+ scheduleLoading.value = true;
+ try {
+ schedules.value = await listAdminSchedules();
+ if (schedules.value.length === 0) {
+ selectedScheduleId.value = null;
+ selectedScheduleRuns.value = [];
+ scheduleViewMode.value = 'overview';
+ return;
+ }
+ const exists = selectedScheduleId.value && schedules.value.some((item) => item.id === selectedScheduleId.value);
+ const nextScheduleId = exists && selectedScheduleId.value ? selectedScheduleId.value : schedules.value[0]?.id ?? null;
+ if (!exists && nextScheduleId) {
+ selectedScheduleId.value = nextScheduleId;
+ }
+ if (scheduleViewMode.value === 'workbench' && nextScheduleId) {
+ await runs.viewScheduleRuns(nextScheduleId);
+ }
+ } finally {
+ scheduleLoading.value = false;
+ }
+ };
+
+ const loadAll = async (): Promise => {
+ await loadSchedules();
+ };
+
+ const openScheduleRunSubmenu = async (taskId: number) => {
+ scheduleViewMode.value = 'workbench';
+ await runs.viewScheduleRuns(taskId);
+ };
+
+ const backToScheduleOverview = () => {
+ scheduleViewMode.value = 'overview';
+ };
+
+ const runScheduleNow = async (taskId: number) => {
+ try {
+ await runAdminSchedule(taskId);
+ } catch (err: any) {
+ msg.error(err?.message || t('admin.schedule.msg.runNowFailed'));
+ return;
+ }
+ await runs.viewScheduleRuns(taskId);
+ await loadSchedules();
+
+ const pollInterval = setInterval(async () => {
+ await runs.viewScheduleRuns(taskId);
+ await loadSchedules();
+ const target = schedules.value.find((s: ScheduleTask) => s.id === taskId);
+ if (target && target.last_status && target.last_status !== 'running') {
+ clearInterval(pollInterval);
+ }
+ }, 5000);
+ };
+
+ const setScheduleEnabled = async (taskId: number, enabled: boolean) => {
+ try {
+ await toggleAdminSchedule(taskId, enabled);
+ await loadSchedules();
+ } catch (err: any) {
+ msg.error(err?.message || t('common.errorOccurred'));
+ }
+ };
+
+ const deleteSchedule = (task: ScheduleTask) => {
+ openDeleteConfirm(
+ t('admin.schedule.deleteConfirmMessage', { name: task.name }),
+ async () => {
+ try {
+ await deleteAdminSchedule(task.id);
+ } catch (err: any) {
+ msg.error(err?.message || t('admin.schedule.msg.deleteFailed'));
+ return;
+ }
+ if (selectedScheduleId.value === task.id) {
+ selectedScheduleId.value = null;
+ selectedScheduleRuns.value = [];
+ }
+ await loadSchedules();
+ },
+ t('admin.schedule.deleteDialogTitle'),
+ );
+ };
+
+ return {
+ scheduleEnabledCount,
+ scheduleDisabledCount,
+ scheduleRunningCount,
+ loadSchedules,
+ loadAll,
+ openScheduleRunSubmenu,
+ backToScheduleOverview,
+ runScheduleNow,
+ setScheduleEnabled,
+ deleteSchedule,
+ };
+}
+
+export type ScheduleAdminList = ReturnType;
diff --git a/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminLookups.ts b/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminLookups.ts
new file mode 100644
index 00000000..1dc70e76
--- /dev/null
+++ b/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminLookups.ts
@@ -0,0 +1,46 @@
+/**
+ * features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminLookups.ts
+ * 定时任务表单依赖的下拉数据:Agent、用户、知识库分组。
+ */
+import { listAdminAgents, listAdminUsers } from '@/features/admin/api/admin.api';
+import { getKbGroups } from '@/features/kb/api/kb.api';
+import type { ScheduleAdminState } from './schedule-admin.state';
+
+export function useScheduleAdminLookups(state: ScheduleAdminState) {
+ const { agents, users, kbGroups } = state;
+
+ const loadAgents = async (): Promise => {
+ try {
+ agents.value = await listAdminAgents();
+ } catch (e) {
+ console.error('Failed to load agents', e);
+ agents.value = [];
+ }
+ };
+
+ const loadUsers = async (): Promise => {
+ try {
+ users.value = await listAdminUsers();
+ } catch (e) {
+ console.error('Error loading users:', e);
+ users.value = [];
+ }
+ };
+
+ const loadKbGroups = async (): Promise => {
+ try {
+ kbGroups.value = await getKbGroups();
+ } catch (e) {
+ console.error('Failed to load kb groups', e);
+ kbGroups.value = [];
+ }
+ };
+
+ return {
+ loadAgents,
+ loadUsers,
+ loadKbGroups,
+ };
+}
+
+export type ScheduleAdminLookups = ReturnType;
diff --git a/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminRuns.ts b/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminRuns.ts
new file mode 100644
index 00000000..fcccfc1a
--- /dev/null
+++ b/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminRuns.ts
@@ -0,0 +1,215 @@
+/**
+ * features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminRuns.ts
+ * 执行批次列表:筛选、列宽、展开详情、Excel 下载与指标派生。
+ */
+import { computed, watch, type Ref } from 'vue';
+import type { ComposerTranslation } from 'vue-i18n';
+import { listAdminScheduleRuns } from '@/features/admin/api/schedule.api';
+import { useMessage } from '@/shared/composables/useMessage';
+import { getAuthHeaders } from '@/shared/utils/auth';
+import { formatDateTime } from '../../utils/schedule-format.utils';
+import type { ScheduleAdminState } from './schedule-admin.state';
+
+export function useScheduleAdminRuns(
+ state: ScheduleAdminState,
+ t: ComposerTranslation,
+ locale: Ref,
+) {
+ const msg = useMessage();
+ const {
+ schedules,
+ selectedScheduleRuns,
+ scheduleRunsLoading,
+ selectedScheduleId,
+ scheduleRunStatusFilter,
+ scheduleRunStartedAfter,
+ scheduleRunStartedBefore,
+ scheduleRunColumnDefs,
+ resizingScheduleCol,
+ expandedScheduleRunId,
+ } = state;
+
+ const syncScheduleRunColumnLabels = () => {
+ const keyToI18n: Record = {
+ run_no: 'runNo',
+ started_at: 'startedAt',
+ finished_at: 'finishedAt',
+ status: 'status',
+ total_count: 'totalCount',
+ success_count: 'successCount',
+ failed_count: 'failedCount',
+ wecom_notified: 'wecomNotified',
+ detail: 'detail',
+ log: 'log',
+ };
+ scheduleRunColumnDefs.value.forEach((col) => {
+ const i18nKey = keyToI18n[col.key];
+ if (i18nKey) col.label = t(`admin.schedule.columns.${i18nKey}`);
+ });
+ };
+ watch(locale, syncScheduleRunColumnLabels, { immediate: true });
+
+ const onScheduleColResizeMove = (event: MouseEvent) => {
+ const resizeState = resizingScheduleCol.value;
+ if (!resizeState) return;
+ const def = scheduleRunColumnDefs.value[resizeState.index];
+ if (!def) return;
+ const delta = event.clientX - resizeState.startX;
+ def.width = Math.max(def.min, resizeState.startWidth + delta);
+ };
+
+ const stopScheduleColResize = () => {
+ if (!resizingScheduleCol.value) return;
+ resizingScheduleCol.value = null;
+ window.removeEventListener('mousemove', onScheduleColResizeMove);
+ window.removeEventListener('mouseup', stopScheduleColResize);
+ };
+
+ const startScheduleColResize = (index: number, event: MouseEvent) => {
+ const def = scheduleRunColumnDefs.value[index];
+ if (!def) return;
+ resizingScheduleCol.value = {
+ index,
+ startX: event.clientX,
+ startWidth: def.width,
+ };
+ window.addEventListener('mousemove', onScheduleColResizeMove);
+ window.addEventListener('mouseup', stopScheduleColResize);
+ };
+
+ const selectedSchedule = computed(() =>
+ schedules.value.find((item) => item.id === selectedScheduleId.value) || null,
+ );
+
+ const scheduleRunStatusOptions = computed(() => [
+ { value: 'all', label: t('admin.schedule.status.all') },
+ { value: 'success', label: t('admin.schedule.status.success') },
+ { value: 'partial_failed', label: t('admin.schedule.status.partialFailed') },
+ { value: 'failed', label: t('admin.schedule.status.failed') },
+ { value: 'running', label: t('admin.schedule.status.running') },
+ ]);
+
+ const getScheduleRunStatusBadge = (status: string) => {
+ const map: Record = {
+ success: { cls: 'bg-emerald-100 text-emerald-700', label: t('admin.schedule.status.success') },
+ partial_failed: { cls: 'bg-blue-100 text-blue-700', label: t('admin.schedule.status.partialFailed') },
+ failed: { cls: 'bg-rose-100 text-rose-700', label: t('admin.schedule.status.failed') },
+ running: { cls: 'bg-amber-100 text-amber-700', label: t('admin.schedule.status.running') },
+ queued: { cls: 'bg-surface-soft text-secondary', label: t('admin.schedule.status.queued') },
+ };
+ return map[status] || { cls: 'bg-surface-soft text-secondary', label: status };
+ };
+
+ const filteredScheduleRuns = computed(() => {
+ if (scheduleRunStatusFilter.value === 'all') return selectedScheduleRuns.value;
+ return selectedScheduleRuns.value.filter((item) => item.status === scheduleRunStatusFilter.value);
+ });
+
+ const expandedScheduleRun = computed(() => {
+ if (!expandedScheduleRunId.value) return null;
+ return filteredScheduleRuns.value.find((x) => x.id === expandedScheduleRunId.value) || null;
+ });
+
+ const stepLabelMap: Record = {
+ fetch_srm: t('admin.schedule.step.fetchSrm'),
+ call_dify: t('admin.schedule.step.callDify'),
+ writeback_srm: t('admin.schedule.step.writebackSrm'),
+ call_internal_api: t('admin.schedule.step.callInternalApi'),
+ pre_dify: t('admin.schedule.step.preDify'),
+ };
+ const stepStatusMap: Record = {
+ success: { cls: 'bg-emerald-100 text-emerald-700', label: t('admin.schedule.status.success') },
+ failed: { cls: 'bg-rose-100 text-rose-700', label: t('admin.schedule.status.failed') },
+ };
+
+ const selectedScheduleRunMetrics = computed(() => {
+ const runs = selectedScheduleRuns.value;
+ return runs.reduce(
+ (acc, item) => {
+ acc.total += item.total_count || 0;
+ acc.success += item.success_count || 0;
+ acc.failed += item.failed_count || 0;
+ return acc;
+ },
+ { total: 0, success: 0, failed: 0 },
+ );
+ });
+
+ const selectedScheduleLatestRunAt = computed(() => {
+ const raw = selectedScheduleRuns.value[0]?.started_at || selectedSchedule.value?.last_run_at;
+ return raw ? formatDateTime(raw) : '-';
+ });
+
+ const todayStart = () => {
+ const d = new Date();
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}T00:00:00`;
+ };
+ const todayEnd = () => {
+ const d = new Date();
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}T23:59:59`;
+ };
+
+ const resetScheduleRunFilters = () => {
+ scheduleRunStatusFilter.value = 'all';
+ scheduleRunStartedAfter.value = todayStart();
+ scheduleRunStartedBefore.value = todayEnd();
+ };
+
+ const viewScheduleRuns = async (taskId: number) => {
+ selectedScheduleId.value = taskId;
+ scheduleRunsLoading.value = true;
+ if (!scheduleRunStartedAfter.value && !scheduleRunStartedBefore.value) {
+ resetScheduleRunFilters();
+ }
+ try {
+ const params: { status?: string; started_after?: string; started_before?: string } = {};
+ if (scheduleRunStatusFilter.value !== 'all') params.status = scheduleRunStatusFilter.value;
+ if (scheduleRunStartedAfter.value) {
+ params.started_after = new Date(scheduleRunStartedAfter.value).toISOString();
+ }
+ if (scheduleRunStartedBefore.value) {
+ params.started_before = new Date(scheduleRunStartedBefore.value).toISOString();
+ }
+ selectedScheduleRuns.value = await listAdminScheduleRuns(taskId, params);
+ } finally {
+ scheduleRunsLoading.value = false;
+ }
+ };
+
+ const downloadScheduleExcel = async (runId: number) => {
+ const res = await fetch(`/api/admin/schedule-runs/${runId}/excel`, { headers: getAuthHeaders() });
+ if (!res.ok) {
+ msg.error(t('admin.schedule.msg.downloadExcelFailed'));
+ return;
+ }
+ const blob = await res.blob();
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ const disposition = res.headers.get('content-disposition');
+ a.download = disposition?.match(/filename\*?=(?:UTF-8'')?["']?([^;"'\n]+)/)?.[1] || 'result.xlsx';
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ URL.revokeObjectURL(url);
+ };
+
+ return {
+ selectedSchedule,
+ scheduleRunStatusOptions,
+ getScheduleRunStatusBadge,
+ filteredScheduleRuns,
+ expandedScheduleRun,
+ stepLabelMap,
+ stepStatusMap,
+ selectedScheduleRunMetrics,
+ selectedScheduleLatestRunAt,
+ resetScheduleRunFilters,
+ viewScheduleRuns,
+ downloadScheduleExcel,
+ startScheduleColResize,
+ formatDateTime,
+ };
+}
+
+export type ScheduleAdminRuns = ReturnType;
diff --git a/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminTestRun.ts b/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminTestRun.ts
new file mode 100644
index 00000000..c93ca853
--- /dev/null
+++ b/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminTestRun.ts
@@ -0,0 +1,101 @@
+/**
+ * features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminTestRun.ts
+ * 定时任务试运行弹窗:加载配置、提交试跑、刷新列表。
+ */
+import { computed } from 'vue';
+import type { ComposerTranslation } from 'vue-i18n';
+import {
+ getAdminSchedule,
+ getAdminScheduleTaskConfig,
+ testAdminScheduleRun,
+ type ScheduleTask,
+} from '@/features/admin/api/schedule.api';
+import { useMessage } from '@/shared/composables/useMessage';
+import type { ScheduleAdminState } from './schedule-admin.state';
+import type { ScheduleAdminList } from './useScheduleAdminList';
+import type { ScheduleAdminRuns } from './useScheduleAdminRuns';
+
+export function useScheduleAdminTestRun(
+ state: ScheduleAdminState,
+ list: Pick,
+ runs: Pick,
+ t: ComposerTranslation,
+) {
+ const msg = useMessage();
+ const {
+ showTestRunDialog,
+ testRunSchedule,
+ testRunWhere,
+ testRunOrderBy,
+ testRunBaseFetchSql,
+ testRunLimit,
+ testRunKbSync,
+ testRunKbSyncAttempted,
+ testRunLoading,
+ testRunResult,
+ } = state;
+
+ const testRunKbSyncAvailable = computed(
+ () => !!(testRunSchedule.value?.kb_group_id),
+ );
+
+ const openTestRunDialog = async (s: ScheduleTask) => {
+ let freshTask = s;
+ try {
+ freshTask = await getAdminSchedule(s.id);
+ } catch {
+ // 列表数据兜底
+ }
+ testRunSchedule.value = freshTask;
+ try {
+ const result = await getAdminScheduleTaskConfig(s.id);
+ const cfg = result.config;
+ testRunWhere.value = cfg?.fetch_where_conditions || '';
+ testRunOrderBy.value = cfg?.fetch_order_by || '';
+ testRunBaseFetchSql.value = cfg?.base_fetch_sql || '';
+ } catch {
+ testRunWhere.value = '';
+ testRunOrderBy.value = '';
+ testRunBaseFetchSql.value = '';
+ }
+ testRunLimit.value = 3;
+ testRunKbSync.value = !!(freshTask.kb_group_id && freshTask.kb_sync_enabled);
+ testRunKbSyncAttempted.value = false;
+ testRunResult.value = null;
+ testRunLoading.value = false;
+ showTestRunDialog.value = true;
+ };
+
+ const handleTestRun = async () => {
+ const s = testRunSchedule.value;
+ if (!s?.id) return;
+ testRunLoading.value = true;
+ testRunResult.value = null;
+ testRunKbSyncAttempted.value = testRunKbSync.value;
+ try {
+ const result = await testAdminScheduleRun(s.id, {
+ fetch_where_conditions: testRunWhere.value,
+ fetch_order_by: testRunOrderBy.value,
+ limit: testRunLimit.value,
+ kb_sync_enabled: testRunKbSync.value,
+ });
+ testRunResult.value = result;
+ await list.loadSchedules();
+ if (s.id) {
+ await runs.viewScheduleRuns(s.id);
+ }
+ } catch (e: any) {
+ msg.error(`${t('admin.schedule.msg.testRunFailed')}: ${e?.message || e}`);
+ } finally {
+ testRunLoading.value = false;
+ }
+ };
+
+ return {
+ testRunKbSyncAvailable,
+ openTestRunDialog,
+ handleTestRun,
+ };
+}
+
+export type ScheduleAdminTestRun = ReturnType;
diff --git a/frontend/src/features/admin/modules/schedules/composables/schedules.context.ts b/frontend/src/features/admin/modules/schedules/composables/schedules.context.ts
new file mode 100644
index 00000000..e8cf7077
--- /dev/null
+++ b/frontend/src/features/admin/modules/schedules/composables/schedules.context.ts
@@ -0,0 +1,30 @@
+/**
+ * features/admin/modules/schedules/composables/schedules.context.ts
+ * 定时任务管理页 provide/inject 上下文类型与注入 key。
+ * 依赖:useSchedulesAdmin。
+ * 逻辑:SchedulesPage provide;子 panel / overlays inject 消费 admin 状态。
+ */
+import { inject, type InjectionKey, type Reactive, type UnwrapNestedRefs } from 'vue';
+import type { useSchedulesAdmin } from './useSchedulesAdmin';
+
+/** useSchedulesAdmin() 原始返回(含 Ref/ComputedRef) */
+export type SchedulesAdminContext = ReturnType;
+
+/** SchedulesPage provide 后经 reactive() 包装、供子组件 inject 的类型 */
+export type SchedulesAdminContextProvided = Reactive>;
+
+export const SCHEDULES_ADMIN_KEY: InjectionKey = Symbol('schedulesAdmin');
+
+/**
+ * 在 SchedulesPage 子树中获取定时任务管理上下文。
+ * 必须在已 provide(SCHEDULES_ADMIN_KEY) 的组件树内调用。
+ * @returns reactive 包装后的 admin 上下文
+ * @throws 未 provide 时抛出 Error
+ */
+export function useSchedulesAdminContext(): SchedulesAdminContextProvided {
+ const ctx = inject(SCHEDULES_ADMIN_KEY);
+ if (!ctx) {
+ throw new Error('[schedules] useSchedulesAdminContext() must be used inside SchedulesPage (provide SCHEDULES_ADMIN_KEY)');
+ }
+ return ctx;
+}
diff --git a/frontend/src/features/admin/modules/schedules/composables/useSchedulesAdmin.ts b/frontend/src/features/admin/modules/schedules/composables/useSchedulesAdmin.ts
index 58a0035b..73d5c6cc 100644
--- a/frontend/src/features/admin/modules/schedules/composables/useSchedulesAdmin.ts
+++ b/frontend/src/features/admin/modules/schedules/composables/useSchedulesAdmin.ts
@@ -1,1111 +1,30 @@
/**
* features/admin/modules/schedules/composables/useSchedulesAdmin.ts
- * 定时任务管理:概览、工作台、创建/编辑、试运行。
+ * 定时任务管理编排入口:组合 state / lookups / list / runs / form / testRun。
*/
-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 '@/features/kb/api/kb.api';
-import {
- createAdminSchedule,
- deleteAdminSchedule,
- getAdminSchedule,
- getAdminScheduleTaskConfig,
- listAdminScheduleRuns,
- listAdminSchedules,
- runAdminSchedule,
- testAdminScheduleRun,
- testAdminScheduleSql,
- toggleAdminSchedule,
- updateAdminSchedule,
- type ScheduleRun,
- type ScheduleTask,
- type TestScheduleRunResult,
-} from '@/features/admin/api/schedule.api';
-import { useMessage } from '@/shared/composables/useMessage';
-import { getAuthHeaders } from '@/shared/utils/auth';
-import type { AdminAgentOption, AdminUserRow } from '@/features/admin/types/admin.types';
+import { createScheduleAdminState } from './schedule-admin/schedule-admin.state';
+import { useScheduleAdminForm } from './schedule-admin/useScheduleAdminForm';
+import { useScheduleAdminList } from './schedule-admin/useScheduleAdminList';
+import { useScheduleAdminLookups } from './schedule-admin/useScheduleAdminLookups';
+import { useScheduleAdminRuns } from './schedule-admin/useScheduleAdminRuns';
+import { useScheduleAdminTestRun } from './schedule-admin/useScheduleAdminTestRun';
export function useSchedulesAdmin() {
const { t, locale } = useI18n();
- const msg = useMessage();
-
- const agents = ref([]);
- const users = ref([]);
- const kbGroups = ref([]);
-
- const showDeleteConfirmDialog = ref(false);
- const deleteConfirmTitle = ref('');
- const deleteConfirmMessage = ref('');
- let deleteConfirmAction: (() => Promise | void) | null = null;
-
- const openDeleteConfirm = (
- message: string,
- onConfirm: () => Promise | void,
- title = '',
- ): void => {
- deleteConfirmTitle.value = title;
- deleteConfirmMessage.value = message;
- deleteConfirmAction = onConfirm;
- showDeleteConfirmDialog.value = true;
- };
-
- const closeDeleteConfirm = (): void => {
- showDeleteConfirmDialog.value = false;
- deleteConfirmTitle.value = '';
- deleteConfirmMessage.value = '';
- deleteConfirmAction = null;
- };
-
- const confirmDelete = async (): Promise => {
- if (!deleteConfirmAction) return;
- try {
- await deleteConfirmAction();
- } finally {
- closeDeleteConfirm();
- }
- };
-
- const loadAgents = async (): Promise => {
- try {
- agents.value = await listAdminAgents();
- } catch (e) {
- console.error('Failed to load agents', e);
- agents.value = [];
- }
- };
-
- const loadUsers = async (): Promise => {
- try {
- users.value = await listAdminUsers();
- } catch (e) {
- console.error('Error loading users:', e);
- users.value = [];
- }
- };
-
- const loadKbGroups = async (): Promise => {
- try {
- kbGroups.value = await getKbGroups();
- } catch (e) {
- console.error('Failed to load kb groups', e);
- kbGroups.value = [];
- }
- };
-
-const schedules = ref([]);
-const schedulesLoaded = ref(false); void schedulesLoaded;
-const selectedScheduleRuns = ref([]);
-const scheduleLoading = ref(false);
-const scheduleRunsLoading = ref(false);
-const selectedScheduleId = ref(null);
-const scheduleRunStatusFilter = ref<'all' | string>('all');
-const scheduleRunStartedAfter = ref('');
-const scheduleRunStartedBefore = ref('');
-const scheduleRunColumnDefs = ref([
- { key: 'run_no', label: '', width: 280, min: 60 },
- { key: 'started_at', label: '', width: 190, min: 60 },
- { key: 'finished_at', label: '', width: 190, min: 60 },
- { key: 'status', label: '', width: 130, min: 50 },
- { key: 'total_count', label: '', width: 70, min: 40 },
- { key: 'success_count', label: '', width: 70, min: 40 },
- { key: 'failed_count', label: '', width: 70, min: 40 },
- { key: 'wecom_notified', label: '', width: 100, min: 80 },
- { key: 'detail', label: '', width: 100, min: 80 },
- { key: 'log', label: '', width: 100, min: 80 },
-]);
-
-const syncScheduleRunColumnLabels = () => {
- const keyToI18n: Record = {
- run_no: 'runNo',
- started_at: 'startedAt',
- finished_at: 'finishedAt',
- status: 'status',
- total_count: 'totalCount',
- success_count: 'successCount',
- failed_count: 'failedCount',
- wecom_notified: 'wecomNotified',
- detail: 'detail',
- log: 'log',
- };
- scheduleRunColumnDefs.value.forEach((col) => {
- const i18nKey = keyToI18n[col.key];
- if (i18nKey) col.label = t(`admin.schedule.columns.${i18nKey}`);
- });
-};
-watch(locale, syncScheduleRunColumnLabels, { immediate: true });
-const resizingScheduleCol = ref<{ index: number; startX: number; startWidth: number } | null>(null);
-
-const onScheduleColResizeMove = (event: MouseEvent) => {
- const state = resizingScheduleCol.value;
- if (!state) return;
- const def = scheduleRunColumnDefs.value[state.index];
- if (!def) return;
- const delta = event.clientX - state.startX;
- def.width = Math.max(def.min, state.startWidth + delta);
-};
-
-const stopScheduleColResize = () => {
- if (!resizingScheduleCol.value) return;
- resizingScheduleCol.value = null;
- window.removeEventListener('mousemove', onScheduleColResizeMove);
- window.removeEventListener('mouseup', stopScheduleColResize);
-};
-
-const startScheduleColResize = (index: number, event: MouseEvent) => {
- const def = scheduleRunColumnDefs.value[index];
- if (!def) return;
- resizingScheduleCol.value = {
- index,
- startX: event.clientX,
- startWidth: def.width,
- };
- window.addEventListener('mousemove', onScheduleColResizeMove);
- window.addEventListener('mouseup', stopScheduleColResize);
-};
-const scheduleViewMode = ref<'overview' | 'workbench'>('overview');
-const showScheduleCreateModal = ref(false);
-const scheduleCreateSaving = ref(false);
-const scheduleEditingId = ref(null);
-const scheduleCreateForm = ref({
- name: '',
- platform_api_path: '',
- data_source_type: 'database' as 'database' | 'external_api',
- dify_agent_id: null as number | null,
- owner_user_id: null as number | null,
- wait_seconds: 300,
- notify_enabled: true,
- notify_user_ids_json: [] as number[],
- kb_sync_enabled: false,
- kb_group_id: null as number | null,
- enabled: true,
-});
-const scheduleConfigCollapsed = ref(true);
-const scheduleCronDesigner = ref({
- mode: 'every_minutes' as 'every_minutes' | 'hourly' | 'daily' | 'weekly',
- every_minutes: 30,
- hourly_minute: 0,
- daily_hour: 9,
- daily_minute: 0,
- weekly_day: 1,
- weekly_hour: 9,
- weekly_minute: 0,
-});
-const weeklyDayOptions = computed(() => [
- { value: 1, label: t('admin.schedule.weekday.mon') },
- { value: 2, label: t('admin.schedule.weekday.tue') },
- { value: 3, label: t('admin.schedule.weekday.wed') },
- { value: 4, label: t('admin.schedule.weekday.thu') },
- { value: 5, label: t('admin.schedule.weekday.fri') },
- { value: 6, label: t('admin.schedule.weekday.sat') },
- { value: 0, label: t('admin.schedule.weekday.sun') },
-]);
-
-const buildCronExprFromDesigner = () => {
- const cfg = scheduleCronDesigner.value;
- if (cfg.mode === 'every_minutes') {
- const every = Math.max(1, Math.min(59, Number(cfg.every_minutes || 30)));
- return `*/${every} * * * *`;
- }
- if (cfg.mode === 'hourly') {
- const minute = Math.max(0, Math.min(59, Number(cfg.hourly_minute || 0)));
- return `${minute} * * * *`;
- }
- if (cfg.mode === 'daily') {
- const minute = Math.max(0, Math.min(59, Number(cfg.daily_minute || 0)));
- const hour = Math.max(0, Math.min(23, Number(cfg.daily_hour || 0)));
- return `${minute} ${hour} * * *`;
- }
- const minute = Math.max(0, Math.min(59, Number(cfg.weekly_minute || 0)));
- const hour = Math.max(0, Math.min(23, Number(cfg.weekly_hour || 0)));
- const day = Number(cfg.weekly_day);
- return `${minute} ${hour} * * ${Number.isNaN(day) ? 1 : day}`;
-};
-
-const scheduleCronPreview = computed(() => buildCronExprFromDesigner());
-
-const scheduleNextRunPreview = computed(() => {
- const expr = scheduleCronPreview.value;
- if (!expr) return null;
- try {
- const parts = expr.trim().split(/\s+/);
- if (parts.length !== 5) return null;
- const now = new Date();
- const minuteRaw = parts[0]!;
- const hourRaw = parts[1]!;
- const dayOfMonth = parts[2]!;
- const month = parts[3]!;
- const dayOfWeek = parts[4]!;
- if (month !== '*') return null;
- if (dayOfMonth !== '*' && dayOfWeek !== '*') return null;
- const minute = minuteRaw.startsWith('*/') ? undefined : parseInt(minuteRaw, 10);
- const hour = hourRaw === '*' ? undefined : parseInt(hourRaw, 10);
- if (minuteRaw.startsWith('*/')) {
- const every = parseInt(minuteRaw.replace('*/', ''), 10);
- const next = new Date(now);
- next.setSeconds(0, 0);
- const mod = next.getMinutes() % every;
- next.setMinutes(next.getMinutes() + (every - mod));
- if (next <= now) next.setMinutes(next.getMinutes() + every);
- return next;
- }
- if (minute !== undefined && hour === undefined) {
- const next = new Date(now);
- next.setMinutes(minute, 0, 0);
- if (next <= now) next.setHours(next.getHours() + 1);
- return next;
- }
- if (minute !== undefined && hour !== undefined) {
- const next = new Date(now);
- next.setHours(hour, minute, 0, 0);
- if (next <= now) {
- if (dayOfWeek !== '*') {
- const dow = parseInt(dayOfWeek, 10);
- const currentDow = next.getDay();
- let diff = dow - currentDow;
- if (diff <= 0) diff += 7;
- next.setDate(next.getDate() + diff);
- } else {
- next.setDate(next.getDate() + 1);
- }
- } else if (dayOfWeek !== '*') {
- const dow = parseInt(dayOfWeek, 10);
- const target = new Date(next);
- const currentDow = target.getDay();
- let diff = dow - currentDow;
- if (diff < 0) diff += 7;
- if (diff > 0) target.setDate(target.getDate() + diff);
- if (target <= now) {
- target.setDate(target.getDate() + 7);
- }
- return target;
- }
- return next;
- }
- return null;
- } catch {
- return null;
- }
-});
-
-const parseCronExprToDesigner = (expr: string | null | undefined) => {
- const text = String(expr || '').trim();
- const parts = text.split(/\s+/);
- if (parts.length !== 5) {
- scheduleCronDesigner.value = {
- mode: 'every_minutes',
- every_minutes: 30,
- hourly_minute: 0,
- daily_hour: 9,
- daily_minute: 0,
- weekly_day: 1,
- weekly_hour: 9,
- weekly_minute: 0,
- };
- return;
- }
- const m = parts[0] ?? '';
- const h = parts[1] ?? '';
- const dow = parts[4] ?? '';
- if (/^\*\/\d+$/.test(m) && h === '*' && dow === '*') {
- scheduleCronDesigner.value.mode = 'every_minutes';
- scheduleCronDesigner.value.every_minutes = Number(m.replace('*/', '')) || 30;
- return;
- }
- if (/^\d+$/.test(m) && h === '*' && dow === '*') {
- scheduleCronDesigner.value.mode = 'hourly';
- scheduleCronDesigner.value.hourly_minute = Number(m) || 0;
- return;
- }
- if (/^\d+$/.test(m) && /^\d+$/.test(h) && dow === '*') {
- scheduleCronDesigner.value.mode = 'daily';
- scheduleCronDesigner.value.daily_hour = Number(h) || 0;
- scheduleCronDesigner.value.daily_minute = Number(m) || 0;
- return;
- }
- if (/^\d+$/.test(m) && /^\d+$/.test(h) && /^\d+$/.test(dow)) {
- scheduleCronDesigner.value.mode = 'weekly';
- scheduleCronDesigner.value.weekly_hour = Number(h) || 0;
- scheduleCronDesigner.value.weekly_minute = Number(m) || 0;
- scheduleCronDesigner.value.weekly_day = Number(dow);
- return;
- }
- scheduleCronDesigner.value.mode = 'every_minutes';
- scheduleCronDesigner.value.every_minutes = 30;
-};
-
-const resetScheduleCreateForm = () => {
- scheduleEditingId.value = null;
- scheduleCreateForm.value = {
- name: '',
- platform_api_path: '',
- data_source_type: 'database',
- dify_agent_id: null,
- owner_user_id: null,
- wait_seconds: 300,
- notify_enabled: true,
- notify_user_ids_json: [],
- kb_sync_enabled: false,
- kb_group_id: null,
- enabled: true,
- };
- scheduleSqlEditForm.value = {
- base_fetch_sql: '',
- fetch_where_conditions: '',
- fetch_order_by: '',
- detail_sql: '',
- writeback_sql: '',
- row_id_key: 'id',
- log_prefix: '',
- alias_order_str: '',
- detail_alias_order_str: '',
- header_labels_str: '{}',
- ds_db_type: 'sqlserver',
- ds_host: '',
- ds_port: '',
- ds_database: '',
- ds_username: '',
- ds_password: '',
- ds_driver: '',
- ds_encrypt: '',
- ds_trust_cert: '',
- api_url: '',
- api_method: 'POST',
- api_headers_str: '{}',
- api_body_template: '',
- dify_system_prompt: '',
- };
- scheduleTestResult.value = null;
- scheduleNotifyUserQuery.value = '';
- scheduleNotifyDropdownOpen.value = false;
- scheduleOwnerQuery.value = '';
- scheduleOwnerDropdownOpen.value = false;
- scheduleCronDesigner.value = {
- mode: 'every_minutes',
- every_minutes: 30,
- hourly_minute: 0,
- daily_hour: 9,
- daily_minute: 0,
- weekly_day: 1,
- weekly_hour: 9,
- weekly_minute: 0,
- };
-};
-
-const openScheduleCreateModal = async () => {
- resetScheduleCreateForm();
- scheduleConfigCollapsed.value = true;
- await Promise.all([loadAgents(), loadUsers(), loadKbGroups()]);
- showScheduleCreateModal.value = true;
-};
-
-const openScheduleEditModal = async (task: ScheduleTask) => {
- await Promise.all([loadAgents(), loadUsers(), loadKbGroups()]);
- scheduleConfigCollapsed.value = true;
- scheduleNotifyUserQuery.value = '';
- scheduleNotifyDropdownOpen.value = false;
- scheduleOwnerDropdownOpen.value = false;
- scheduleEditingId.value = task.id;
- scheduleCreateForm.value = {
- name: task.name || '',
- platform_api_path: task.platform_api_path || '',
- dify_agent_id: task.dify_agent_id || null,
- owner_user_id: task.owner_user_id || null,
- wait_seconds: task.wait_seconds || 0,
- notify_enabled: !!task.notify_enabled,
- notify_user_ids_json: task.notify_user_ids_json || [],
- kb_sync_enabled: !!task.kb_sync_enabled,
- kb_group_id: task.kb_group_id || null,
- enabled: !!task.enabled,
- data_source_type: (task.data_source_type || 'database') as 'database' | 'external_api',
- };
-
- try {
- const result = await getAdminScheduleTaskConfig(task.id);
- const cfg = result.config;
- scheduleCreateForm.value.data_source_type = (result.data_source_type || 'database') as 'database' | 'external_api';
- if (cfg) {
- scheduleSqlEditForm.value = {
- base_fetch_sql: cfg.base_fetch_sql || '',
- fetch_where_conditions: cfg.fetch_where_conditions || '',
- fetch_order_by: cfg.fetch_order_by || '',
- detail_sql: cfg.detail_sql || '',
- writeback_sql: cfg.writeback_sql || '',
- row_id_key: cfg.row_id_key || 'id',
- log_prefix: cfg.log_prefix || '',
- alias_order_str: (cfg.alias_order || []).join(','),
- detail_alias_order_str: (cfg.detail_alias_order || []).join(','),
- header_labels_str: cfg.header_labels ? JSON.stringify(cfg.header_labels, null, 2) : '{}',
- ds_db_type: cfg.data_source?.db_type || 'sqlserver',
- ds_host: cfg.data_source?.host || '',
- ds_port: cfg.data_source?.port || '',
- ds_database: cfg.data_source?.database || '',
- ds_username: cfg.data_source?.username || '',
- ds_password: cfg.data_source?.password || '',
- ds_driver: cfg.data_source?.driver || '',
- ds_encrypt: cfg.data_source?.encrypt || '',
- ds_trust_cert: cfg.data_source?.trust_cert || '',
- api_url: cfg.external_api?.url || '',
- api_method: cfg.external_api?.method || 'POST',
- api_headers_str: cfg.external_api?.headers ? JSON.stringify(cfg.external_api.headers, null, 2) : '{}',
- api_body_template: cfg.external_api?.body_template || '',
- dify_system_prompt: cfg.dify_system_prompt || '',
- };
- }
- } catch {
- scheduleSqlEditForm.value = {
- base_fetch_sql: '',
- fetch_where_conditions: '',
- fetch_order_by: '',
- detail_sql: '',
- writeback_sql: '',
- row_id_key: 'id',
- log_prefix: '',
- alias_order_str: '',
- detail_alias_order_str: '',
- header_labels_str: '{}',
- ds_db_type: 'sqlserver',
- ds_host: '',
- ds_port: '',
- ds_database: '',
- ds_username: '',
- ds_password: '',
- ds_driver: '',
- ds_encrypt: '',
- ds_trust_cert: '',
- api_url: '',
- api_method: 'POST',
- api_headers_str: '{}',
- api_body_template: '',
- dify_system_prompt: '',
- };
- }
-
- scheduleTestResult.value = null;
- parseCronExprToDesigner(task.cron_expr);
- syncScheduleOwnerQuery();
- showScheduleCreateModal.value = true;
-};
-
-const selectedSchedule = computed(() =>
- schedules.value.find((item) => item.id === selectedScheduleId.value) || null
-);
-
-const scheduleRunStatusOptions = computed(() => [
- { value: 'all', label: t('admin.schedule.status.all') },
- { value: 'success', label: t('admin.schedule.status.success') },
- { value: 'partial_failed', label: t('admin.schedule.status.partialFailed') },
- { value: 'failed', label: t('admin.schedule.status.failed') },
- { value: 'running', label: t('admin.schedule.status.running') },
-]);
-
-const getScheduleRunStatusBadge = (status: string) => {
- const map: Record = {
- success: { cls: 'bg-emerald-100 text-emerald-700', label: t('admin.schedule.status.success') },
- partial_failed: { cls: 'bg-blue-100 text-blue-700', label: t('admin.schedule.status.partialFailed') },
- failed: { cls: 'bg-rose-100 text-rose-700', label: t('admin.schedule.status.failed') },
- running: { cls: 'bg-amber-100 text-amber-700', label: t('admin.schedule.status.running') },
- queued: { cls: 'bg-surface-soft text-secondary', label: t('admin.schedule.status.queued') },
- };
- return map[status] || { cls: 'bg-surface-soft text-secondary', label: status };
-};
-
-const parseApiUtcDate = (iso: string) => {
- const normalized = /(?:Z|[+-]\d{2}:\d{2})$/i.test(iso) ? iso : `${iso}Z`;
- return new Date(normalized);
-};
-
-const formatDateTime = (iso?: string | null) => {
- if (!iso) return '-';
- const d = parseApiUtcDate(iso);
- if (isNaN(d.getTime())) return iso;
- const pad = (n: number) => String(n).padStart(2, '0');
- return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
-};
-
-const expandedScheduleRunId = ref(null);
-
-const expandedScheduleRun = computed(() => {
- if (!expandedScheduleRunId.value) return null;
- return filteredScheduleRuns.value.find((x) => x.id === expandedScheduleRunId.value) || null;
-});
-
-const stepLabelMap: Record = {
- fetch_srm: t('admin.schedule.step.fetchSrm'),
- call_dify: t('admin.schedule.step.callDify'),
- writeback_srm: t('admin.schedule.step.writebackSrm'),
- call_internal_api: t('admin.schedule.step.callInternalApi'),
- pre_dify: t('admin.schedule.step.preDify'),
-};
-const stepStatusMap: Record = {
- success: { cls: 'bg-emerald-100 text-emerald-700', label: t('admin.schedule.status.success') },
- failed: { cls: 'bg-rose-100 text-rose-700', label: t('admin.schedule.status.failed') },
-};
-
-const showTestRunDialog = ref(false);
-const testRunSchedule = ref(null);
-const testRunWhere = ref('');
-const testRunOrderBy = ref('');
-const testRunBaseFetchSql = ref('');
-const testRunLimit = ref(3);
-const testRunKbSync = ref(false);
-const testRunKbSyncAttempted = ref(false);
-const testRunLoading = ref(false);
-const testRunResult = ref(null);
-
-const testRunKbSyncAvailable = computed(
- () => !!(testRunSchedule.value?.kb_group_id),
-);
-
-const openTestRunDialog = async (s: ScheduleTask) => {
- let freshTask = s;
- try {
- freshTask = await getAdminSchedule(s.id);
- } catch {
- // 列表数据兜底
- }
- testRunSchedule.value = freshTask;
- try {
- const result = await getAdminScheduleTaskConfig(s.id);
- const cfg = result.config;
- testRunWhere.value = cfg?.fetch_where_conditions || '';
- testRunOrderBy.value = cfg?.fetch_order_by || '';
- testRunBaseFetchSql.value = cfg?.base_fetch_sql || '';
- } catch {
- testRunWhere.value = '';
- testRunOrderBy.value = '';
- testRunBaseFetchSql.value = '';
- }
- testRunLimit.value = 3;
- testRunKbSync.value = !!(freshTask.kb_group_id && freshTask.kb_sync_enabled);
- testRunKbSyncAttempted.value = false;
- testRunResult.value = null;
- testRunLoading.value = false;
- showTestRunDialog.value = true;
-};
-
-const handleTestRun = async () => {
- const s = testRunSchedule.value;
- if (!s?.id) return;
- testRunLoading.value = true;
- testRunResult.value = null;
- testRunKbSyncAttempted.value = testRunKbSync.value;
- try {
- const result = await testAdminScheduleRun(s.id, {
- fetch_where_conditions: testRunWhere.value,
- fetch_order_by: testRunOrderBy.value,
- limit: testRunLimit.value,
- kb_sync_enabled: testRunKbSync.value,
- });
- testRunResult.value = result;
- await loadSchedules();
- if (s.id) {
- await viewScheduleRuns(s.id);
- }
- } catch (e: any) {
- msg.error(`${t('admin.schedule.msg.testRunFailed')}: ${e?.message || e}`);
- } finally {
- testRunLoading.value = false;
- }
-};
-
-const filteredScheduleRuns = computed(() => {
- if (scheduleRunStatusFilter.value === 'all') return selectedScheduleRuns.value;
- return selectedScheduleRuns.value.filter((item) => item.status === scheduleRunStatusFilter.value);
-});
-
-const selectedScheduleRunMetrics = computed(() => {
- const runs = selectedScheduleRuns.value;
- return runs.reduce(
- (acc, item) => {
- acc.total += item.total_count || 0;
- acc.success += item.success_count || 0;
- acc.failed += item.failed_count || 0;
- return acc;
- },
- { total: 0, success: 0, failed: 0 }
- );
-});
-
-const selectedScheduleLatestRunAt = computed(() => {
- const raw = selectedScheduleRuns.value[0]?.started_at || selectedSchedule.value?.last_run_at;
- return raw ? formatDateTime(raw) : '-';
-});
-
-const scheduleEnabledCount = computed(() => schedules.value.filter((item) => item.enabled).length);
-const scheduleDisabledCount = computed(() => schedules.value.filter((item) => !item.enabled).length);
-const scheduleRunningCount = computed(() => schedules.value.filter((item) => item.last_status === 'running').length);
-
-const loadSchedules = async () => {
- scheduleLoading.value = true;
- try {
- schedules.value = await listAdminSchedules();
- if (schedules.value.length === 0) {
- selectedScheduleId.value = null;
- selectedScheduleRuns.value = [];
- scheduleViewMode.value = 'overview';
- return;
- }
- const exists = selectedScheduleId.value && schedules.value.some((item) => item.id === selectedScheduleId.value);
- const nextScheduleId = exists && selectedScheduleId.value ? selectedScheduleId.value : schedules.value[0]?.id ?? null;
- if (!exists && nextScheduleId) {
- selectedScheduleId.value = nextScheduleId;
- }
- if (scheduleViewMode.value === 'workbench' && nextScheduleId) {
- await viewScheduleRuns(nextScheduleId);
- }
- } finally {
- scheduleLoading.value = false;
- }
-};
-
-const scheduleSqlEditForm = ref({
- base_fetch_sql: '',
- fetch_where_conditions: '',
- fetch_order_by: '',
- detail_sql: '',
- writeback_sql: '',
- row_id_key: 'id',
- log_prefix: '',
- alias_order_str: '',
- detail_alias_order_str: '',
- header_labels_str: '{}',
- ds_db_type: 'sqlserver',
- ds_host: '',
- ds_port: '',
- ds_database: '',
- ds_username: '',
- ds_password: '',
- ds_driver: '',
- ds_encrypt: '',
- ds_trust_cert: '',
- api_url: '',
- api_method: 'POST',
- api_headers_str: '{}',
- api_body_template: '',
- dify_system_prompt: '',
-});
-const scheduleSqlSaving = ref(false); void scheduleSqlSaving;
-const scheduleTestLoading = ref(false);
-const scheduleTestResult = ref<{ total: number; showing: number; columns: string[]; rows: any[]; sql: string } | null>(null);
-
-const handleTestScheduleSql = async () => {
- const taskId = scheduleEditingId.value;
- if (!taskId) return;
-
- scheduleTestLoading.value = true;
- scheduleTestResult.value = null;
- try {
- const result = await testAdminScheduleSql(taskId, {
- fetch_where_conditions: scheduleSqlEditForm.value.fetch_where_conditions,
- fetch_order_by: scheduleSqlEditForm.value.fetch_order_by,
- limit: 10,
- });
- scheduleTestResult.value = result;
- } catch (e: any) {
- msg.error(`${t('admin.schedule.msg.testQueryFailed')}: ${e?.message || e}`);
- } finally {
- scheduleTestLoading.value = false;
- }
-};
-
-const scheduleNotifyDropdownOpen = ref(false);
-const scheduleNotifyUserQuery = ref('');
-let scheduleNotifyCloseTimer: ReturnType | null = null;
-
-const filteredNotifyUsers = computed(() => {
- const keyword = scheduleNotifyUserQuery.value.trim().toLowerCase();
- return users.value.filter((u) => {
- if (!keyword) return true;
- return [u.real_name, u.username, u.employee_id, String(u.id)]
- .filter(Boolean)
- .some((val) => String(val).toLowerCase().includes(keyword));
- });
-});
-
-const scheduleCloseNotifyDropdown = (): void => {
- if (scheduleNotifyCloseTimer) clearTimeout(scheduleNotifyCloseTimer);
- scheduleNotifyCloseTimer = setTimeout(() => {
- scheduleNotifyDropdownOpen.value = false;
- }, 150);
-};
-
-const scheduleOwnerDropdownOpen = ref(false);
-const scheduleOwnerQuery = ref('');
-let scheduleOwnerCloseTimer: ReturnType | null = null;
-
-const formatUserOptionLabel = (u: AdminUserRow) =>
- `${u.real_name || u.username}${u.employee_id ? `(${u.employee_id})` : ''}`;
-
-const filteredOwnerUsers = computed(() => {
- const keyword = scheduleOwnerQuery.value.trim().toLowerCase();
- return users.value.filter((u) => {
- if (!keyword) return true;
- return [u.real_name, u.username, u.employee_id, String(u.id)]
- .filter(Boolean)
- .some((val) => String(val).toLowerCase().includes(keyword));
- });
-});
-
-const syncScheduleOwnerQuery = (): void => {
- const ownerId = scheduleCreateForm.value.owner_user_id;
- if (!ownerId) {
- scheduleOwnerQuery.value = '';
- return;
- }
- const u = users.value.find((x) => x.id === ownerId);
- scheduleOwnerQuery.value = u ? formatUserOptionLabel(u) : String(ownerId);
-};
-
-const selectScheduleOwner = (id: number): void => {
- const u = users.value.find((x) => x.id === id);
- if (!u) return;
- scheduleCreateForm.value.owner_user_id = id;
- scheduleOwnerQuery.value = formatUserOptionLabel(u);
- scheduleOwnerDropdownOpen.value = false;
-};
-
-const handleScheduleOwnerInput = (): void => {
- scheduleOwnerDropdownOpen.value = true;
- const ownerId = scheduleCreateForm.value.owner_user_id;
- if (!ownerId) return;
- const u = users.value.find((x) => x.id === ownerId);
- const currentLabel = u ? formatUserOptionLabel(u) : '';
- if (scheduleOwnerQuery.value.trim() !== currentLabel) {
- scheduleCreateForm.value.owner_user_id = null;
- }
-};
-
-const scheduleCloseOwnerDropdown = (): void => {
- if (scheduleOwnerCloseTimer) clearTimeout(scheduleOwnerCloseTimer);
- scheduleOwnerCloseTimer = setTimeout(() => {
- scheduleOwnerDropdownOpen.value = false;
- }, 150);
-};
-
-watch(() => scheduleCreateForm.value.dify_agent_id, (agentId) => {
- if (!agentId) {
- scheduleSqlEditForm.value.dify_system_prompt = '';
- }
-});
-
-const getUserName = (uid: number) => {
- const u = users.value.find(x => x.id === uid);
- return u ? (u.real_name || u.username) : String(uid);
-};
-
-const toggleNotifyUser = (uid: number) => {
- const list = scheduleCreateForm.value.notify_user_ids_json;
- if (list.includes(uid)) {
- scheduleCreateForm.value.notify_user_ids_json = list.filter((id: number) => id !== uid);
- } else {
- scheduleCreateForm.value.notify_user_ids_json = [...list, uid];
- }
-};
-
-const removeNotifyUser = (uid: number) => {
- scheduleCreateForm.value.notify_user_ids_json = scheduleCreateForm.value.notify_user_ids_json.filter((id: number) => id !== uid);
-};
-
-const createSchedule = async () => {
- if (!scheduleCreateForm.value.name || !scheduleCreateForm.value.owner_user_id) return;
-
- const dst = scheduleCreateForm.value.data_source_type;
- const hasAgent = !!scheduleCreateForm.value.dify_agent_id;
- const hasSql = dst === 'database' && !!scheduleSqlEditForm.value.base_fetch_sql.trim();
- const hasApi = dst === 'external_api' && !!scheduleSqlEditForm.value.api_url.trim();
- if (!hasAgent && !hasSql && !hasApi) {
- msg.error(t('admin.schedule.msg.configRequired'));
- return;
- }
-
- let headerLabels: Record = {};
- try {
- headerLabels = JSON.parse(scheduleSqlEditForm.value.header_labels_str || '{}');
- } catch {
- msg.error(t('admin.schedule.msg.headerLabelsJsonInvalid'));
- return;
- }
- let apiHeaders: Record = {};
- if (dst === 'external_api') {
- try {
- apiHeaders = JSON.parse(scheduleSqlEditForm.value.api_headers_str || '{}');
- } catch {
- msg.error(t('admin.schedule.msg.apiHeadersJsonInvalid'));
- return;
- }
- }
- const aliasOrder = scheduleSqlEditForm.value.alias_order_str.split(',').map(s => s.trim()).filter(Boolean);
- const detailAliasOrder = scheduleSqlEditForm.value.detail_alias_order_str.split(',').map(s => s.trim()).filter(Boolean);
-
- const configPayload: Record = {
- base_fetch_sql: scheduleSqlEditForm.value.base_fetch_sql,
- fetch_where_conditions: scheduleSqlEditForm.value.fetch_where_conditions,
- fetch_order_by: scheduleSqlEditForm.value.fetch_order_by,
- detail_sql: scheduleSqlEditForm.value.detail_sql,
- writeback_sql: scheduleSqlEditForm.value.writeback_sql,
- row_id_key: scheduleSqlEditForm.value.row_id_key || 'id',
- log_prefix: scheduleSqlEditForm.value.log_prefix,
- alias_order: aliasOrder,
- detail_alias_order: detailAliasOrder,
- header_labels: headerLabels,
- data_source: scheduleSqlEditForm.value.ds_host.trim() ? {
- db_type: scheduleSqlEditForm.value.ds_db_type,
- host: scheduleSqlEditForm.value.ds_host,
- port: scheduleSqlEditForm.value.ds_port,
- database: scheduleSqlEditForm.value.ds_database,
- username: scheduleSqlEditForm.value.ds_username,
- password: scheduleSqlEditForm.value.ds_password,
- driver: scheduleSqlEditForm.value.ds_driver,
- encrypt: scheduleSqlEditForm.value.ds_encrypt,
- trust_cert: scheduleSqlEditForm.value.ds_trust_cert,
- } : undefined,
- external_api: scheduleSqlEditForm.value.api_url.trim() ? {
- url: scheduleSqlEditForm.value.api_url,
- method: scheduleSqlEditForm.value.api_method,
- headers: apiHeaders,
- body_template: scheduleSqlEditForm.value.api_body_template,
- } : undefined,
- dify_system_prompt: hasAgent ? scheduleSqlEditForm.value.dify_system_prompt : '',
- };
-
- scheduleCreateSaving.value = true;
- try {
- const payload: any = {
- name: scheduleCreateForm.value.name,
- schedule_type: 'platform_app',
- owner_user_id: scheduleCreateForm.value.owner_user_id,
- cron_expr: scheduleCronPreview.value,
- wait_seconds: Math.max(0, Number(scheduleCreateForm.value.wait_seconds || 0)),
- dify_agent_id: scheduleCreateForm.value.dify_agent_id || undefined,
- notify_user_ids_json: scheduleCreateForm.value.notify_enabled ? scheduleCreateForm.value.notify_user_ids_json : [],
- notify_enabled: scheduleCreateForm.value.notify_enabled,
- kb_sync_enabled: scheduleCreateForm.value.kb_sync_enabled,
- kb_group_id: scheduleCreateForm.value.kb_sync_enabled ? scheduleCreateForm.value.kb_group_id : null,
- enabled: scheduleCreateForm.value.enabled,
- data_source_type: dst,
- config: configPayload,
- };
- let resultData: any = null;
- if (scheduleEditingId.value) {
- resultData = await updateAdminSchedule(scheduleEditingId.value, payload);
- } else {
- resultData = await createAdminSchedule(payload);
- }
- const createdId = resultData?.id ?? resultData?.schedule?.id ?? null;
- const targetId = scheduleEditingId.value || createdId;
- showScheduleCreateModal.value = false;
- await loadSchedules();
- if (targetId) {
- await viewScheduleRuns(targetId);
- }
- } catch (err: any) {
- msg.error(err?.message || t('common.errorOccurred'));
- } finally {
- scheduleCreateSaving.value = false;
- }
-};
-
-const todayStart = () => {
- const d = new Date();
- return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}T00:00:00`;
-};
-const todayEnd = () => {
- const d = new Date();
- return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}T23:59:59`;
-};
-
-const resetScheduleRunFilters = () => {
- scheduleRunStatusFilter.value = 'all';
- scheduleRunStartedAfter.value = todayStart();
- scheduleRunStartedBefore.value = todayEnd();
-};
-
-const viewScheduleRuns = async (taskId: number) => {
- selectedScheduleId.value = taskId;
- scheduleRunsLoading.value = true;
- if (!scheduleRunStartedAfter.value && !scheduleRunStartedBefore.value) {
- resetScheduleRunFilters();
- }
- try {
- const params: { status?: string; started_after?: string; started_before?: string } = {};
- if (scheduleRunStatusFilter.value !== 'all') params.status = scheduleRunStatusFilter.value;
- if (scheduleRunStartedAfter.value) {
- params.started_after = new Date(scheduleRunStartedAfter.value).toISOString();
- }
- if (scheduleRunStartedBefore.value) {
- params.started_before = new Date(scheduleRunStartedBefore.value).toISOString();
- }
- selectedScheduleRuns.value = await listAdminScheduleRuns(taskId, params);
- } finally {
- scheduleRunsLoading.value = false;
- }
-};
-
-const openScheduleRunSubmenu = async (taskId: number) => {
- scheduleViewMode.value = 'workbench';
- await viewScheduleRuns(taskId);
-};
-
-const backToScheduleOverview = () => {
- scheduleViewMode.value = 'overview';
-};
-
-const runScheduleNow = async (taskId: number) => {
- try {
- await runAdminSchedule(taskId);
- } catch (err: any) {
- msg.error(err?.message || t('admin.schedule.msg.runNowFailed'));
- return;
- }
- await viewScheduleRuns(taskId);
- await loadSchedules();
-
- const pollInterval = setInterval(async () => {
- await viewScheduleRuns(taskId);
- await loadSchedules();
- const target = schedules.value.find((s: ScheduleTask) => s.id === taskId);
- if (target && target.last_status && target.last_status !== 'running') {
- clearInterval(pollInterval);
- }
- }, 5000);
-};
-
-const setScheduleEnabled = async (taskId: number, enabled: boolean) => {
- try {
- await toggleAdminSchedule(taskId, enabled);
- await loadSchedules();
- } catch (err: any) {
- msg.error(err?.message || t('common.errorOccurred'));
- }
-};
-
-const downloadScheduleExcel = async (runId: number) => {
- const res = await fetch(`/api/admin/schedule-runs/${runId}/excel`, { headers: getAuthHeaders() });
- if (!res.ok) {
- msg.error(t('admin.schedule.msg.downloadExcelFailed'));
- return;
- }
- const blob = await res.blob();
- const url = URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = url;
- const disposition = res.headers.get('content-disposition');
- a.download = disposition?.match(/filename\*?=(?:UTF-8'')?["']?([^;"'\n]+)/)?.[1] || 'result.xlsx';
- document.body.appendChild(a);
- a.click();
- document.body.removeChild(a);
- URL.revokeObjectURL(url);
-};
-
-const deleteSchedule = (task: ScheduleTask) => {
- openDeleteConfirm(
- t('admin.schedule.deleteConfirmMessage', { name: task.name }),
- async () => {
- try {
- await deleteAdminSchedule(task.id);
- } catch (err: any) {
- msg.error(err?.message || t('admin.schedule.msg.deleteFailed'));
- return;
- }
- if (selectedScheduleId.value === task.id) {
- selectedScheduleId.value = null;
- selectedScheduleRuns.value = [];
- }
- await loadSchedules();
- },
- t('admin.schedule.deleteDialogTitle')
- );
-};
- const loadAll = async (): Promise => {
- await loadSchedules();
- };
+ const state = createScheduleAdminState();
+ const lookups = useScheduleAdminLookups(state);
+ const runs = useScheduleAdminRuns(state, t, locale);
+ const list = useScheduleAdminList(state, runs, t);
+ const form = useScheduleAdminForm(state, lookups, list, runs, t);
+ const testRun = useScheduleAdminTestRun(state, list, runs, t);
return {
- agents,
- users,
- kbGroups,
- schedules,
- selectedScheduleRuns,
- scheduleLoading,
- scheduleRunsLoading,
- selectedScheduleId,
- scheduleRunStatusFilter,
- scheduleRunStartedAfter,
- scheduleRunStartedBefore,
- scheduleRunColumnDefs,
- scheduleViewMode,
- showScheduleCreateModal,
- scheduleCreateSaving,
- scheduleEditingId,
- scheduleCreateForm,
- scheduleConfigCollapsed,
- scheduleCronDesigner,
- weeklyDayOptions,
- scheduleCronPreview,
- scheduleNextRunPreview,
- selectedSchedule,
- scheduleRunStatusOptions,
- getScheduleRunStatusBadge,
- formatDateTime,
- expandedScheduleRunId,
- expandedScheduleRun,
- stepLabelMap,
- stepStatusMap,
- showTestRunDialog,
- testRunSchedule,
- testRunWhere,
- testRunOrderBy,
- testRunBaseFetchSql,
- testRunLimit,
- testRunKbSync,
- testRunKbSyncAvailable,
- testRunKbSyncAttempted,
- testRunLoading,
- testRunResult,
- filteredScheduleRuns,
- selectedScheduleRunMetrics,
- selectedScheduleLatestRunAt,
- scheduleEnabledCount,
- scheduleDisabledCount,
- scheduleRunningCount,
- scheduleSqlEditForm,
- scheduleTestLoading,
- scheduleTestResult,
- scheduleNotifyDropdownOpen,
- scheduleNotifyUserQuery,
- filteredNotifyUsers,
- scheduleCloseNotifyDropdown,
- scheduleOwnerDropdownOpen,
- scheduleOwnerQuery,
- filteredOwnerUsers,
- selectScheduleOwner,
- handleScheduleOwnerInput,
- scheduleCloseOwnerDropdown,
- showDeleteConfirmDialog,
- deleteConfirmTitle,
- deleteConfirmMessage,
- loadAll,
- loadSchedules,
- startScheduleColResize,
- openScheduleCreateModal,
- openScheduleEditModal,
- openScheduleRunSubmenu,
- backToScheduleOverview,
- viewScheduleRuns,
- resetScheduleRunFilters,
- runScheduleNow,
- setScheduleEnabled,
- deleteSchedule,
- downloadScheduleExcel,
- openTestRunDialog,
- handleTestRun,
- handleTestScheduleSql,
- getUserName,
- toggleNotifyUser,
- removeNotifyUser,
- createSchedule,
- closeDeleteConfirm,
- confirmDelete,
+ ...state,
+ ...lookups,
+ ...runs,
+ ...list,
+ ...form,
+ ...testRun,
};
}
diff --git a/frontend/src/features/admin/modules/schedules/types/schedule-admin.types.ts b/frontend/src/features/admin/modules/schedules/types/schedule-admin.types.ts
new file mode 100644
index 00000000..cae60c78
--- /dev/null
+++ b/frontend/src/features/admin/modules/schedules/types/schedule-admin.types.ts
@@ -0,0 +1,134 @@
+/**
+ * features/admin/modules/schedules/types/schedule-admin.types.ts
+ * 定时任务管理页表单与 Cron 设计器类型及默认工厂。
+ * 依赖:无运行时依赖。
+ * 逻辑:由 useSchedulesAdmin 与 schedule-cron.utils 引用。
+ */
+
+/** Cron 设计器模式 */
+export type ScheduleCronDesignerMode = 'every_minutes' | 'hourly' | 'daily' | 'weekly';
+
+/** Cron 可视化设计器状态 */
+export interface ScheduleCronDesigner {
+ mode: ScheduleCronDesignerMode;
+ every_minutes: number;
+ hourly_minute: number;
+ daily_hour: number;
+ daily_minute: number;
+ weekly_day: number;
+ weekly_hour: number;
+ weekly_minute: number;
+}
+
+/** 创建/编辑定时任务主表单 */
+export interface ScheduleCreateForm {
+ name: string;
+ platform_api_path: string;
+ data_source_type: 'database' | 'external_api';
+ dify_agent_id: number | null;
+ owner_user_id: number | null;
+ wait_seconds: number;
+ notify_enabled: boolean;
+ notify_user_ids_json: number[];
+ kb_sync_enabled: boolean;
+ kb_group_id: number | null;
+ enabled: boolean;
+}
+
+/** SQL / 外部 API 配置编辑表单 */
+export interface ScheduleSqlEditForm {
+ base_fetch_sql: string;
+ fetch_where_conditions: string;
+ fetch_order_by: string;
+ detail_sql: string;
+ writeback_sql: string;
+ row_id_key: string;
+ log_prefix: string;
+ alias_order_str: string;
+ detail_alias_order_str: string;
+ header_labels_str: string;
+ ds_db_type: string;
+ ds_host: string;
+ ds_port: string;
+ ds_database: string;
+ ds_username: string;
+ ds_password: string;
+ ds_driver: string;
+ ds_encrypt: string;
+ ds_trust_cert: string;
+ api_url: string;
+ api_method: string;
+ api_headers_str: string;
+ api_body_template: string;
+ dify_system_prompt: string;
+}
+
+/**
+ * 返回 Cron 设计器默认值(每 30 分钟)。
+ * @returns 新的 ScheduleCronDesigner 副本
+ */
+export function createDefaultCronDesigner(): ScheduleCronDesigner {
+ return {
+ mode: 'every_minutes',
+ every_minutes: 30,
+ hourly_minute: 0,
+ daily_hour: 9,
+ daily_minute: 0,
+ weekly_day: 1,
+ weekly_hour: 9,
+ weekly_minute: 0,
+ };
+}
+
+/**
+ * 返回创建任务主表单默认值。
+ * @returns 新的 ScheduleCreateForm 副本
+ */
+export function createDefaultScheduleCreateForm(): ScheduleCreateForm {
+ return {
+ name: '',
+ platform_api_path: '',
+ data_source_type: 'database',
+ dify_agent_id: null,
+ owner_user_id: null,
+ wait_seconds: 300,
+ notify_enabled: true,
+ notify_user_ids_json: [],
+ kb_sync_enabled: false,
+ kb_group_id: null,
+ enabled: true,
+ };
+}
+
+/**
+ * 返回 SQL/API 配置表单默认值。
+ * @returns 新的 ScheduleSqlEditForm 副本
+ */
+export function createDefaultScheduleSqlEditForm(): ScheduleSqlEditForm {
+ return {
+ base_fetch_sql: '',
+ fetch_where_conditions: '',
+ fetch_order_by: '',
+ detail_sql: '',
+ writeback_sql: '',
+ row_id_key: 'id',
+ log_prefix: '',
+ alias_order_str: '',
+ detail_alias_order_str: '',
+ header_labels_str: '{}',
+ ds_db_type: 'sqlserver',
+ ds_host: '',
+ ds_port: '',
+ ds_database: '',
+ ds_username: '',
+ ds_password: '',
+ ds_driver: '',
+ ds_encrypt: '',
+ ds_trust_cert: '',
+ api_url: '',
+ api_method: 'POST',
+ api_headers_str: '{}',
+ api_body_template: '',
+ dify_system_prompt: '',
+ };
+}
diff --git a/frontend/src/features/admin/modules/schedules/utils/schedule-cron.utils.ts b/frontend/src/features/admin/modules/schedules/utils/schedule-cron.utils.ts
new file mode 100644
index 00000000..5059e648
--- /dev/null
+++ b/frontend/src/features/admin/modules/schedules/utils/schedule-cron.utils.ts
@@ -0,0 +1,154 @@
+/**
+ * features/admin/modules/schedules/utils/schedule-cron.utils.ts
+ * Cron 表达式与设计器互转及下次执行时间预览纯函数。
+ * 依赖:schedule-admin.types。
+ * 逻辑:由 useSchedulesAdmin 的 computed 与编辑流程调用。
+ */
+import type { ScheduleCronDesigner } from '../types/schedule-admin.types';
+import { createDefaultCronDesigner } from '../types/schedule-admin.types';
+
+export { createDefaultCronDesigner } from '../types/schedule-admin.types';
+
+/**
+ * 根据 Cron 设计器状态生成五段 cron 表达式。
+ * 核心逻辑:按 mode clamp 数值后拼接 `分 时 日 月 周`。
+ * @param cfg - 设计器当前配置
+ * @returns cron 表达式字符串
+ */
+export function buildCronExprFromDesigner(cfg: ScheduleCronDesigner): string {
+ if (cfg.mode === 'every_minutes') {
+ const every = Math.max(1, Math.min(59, Number(cfg.every_minutes || 30)));
+ return `*/${every} * * * *`;
+ }
+ if (cfg.mode === 'hourly') {
+ const minute = Math.max(0, Math.min(59, Number(cfg.hourly_minute || 0)));
+ return `${minute} * * * *`;
+ }
+ if (cfg.mode === 'daily') {
+ const minute = Math.max(0, Math.min(59, Number(cfg.daily_minute || 0)));
+ const hour = Math.max(0, Math.min(23, Number(cfg.daily_hour || 0)));
+ return `${minute} ${hour} * * *`;
+ }
+ const minute = Math.max(0, Math.min(59, Number(cfg.weekly_minute || 0)));
+ const hour = Math.max(0, Math.min(23, Number(cfg.weekly_hour || 0)));
+ const day = Number(cfg.weekly_day);
+ return `${minute} ${hour} * * ${Number.isNaN(day) ? 1 : day}`;
+}
+
+/**
+ * 解析 cron 表达式为设计器状态(不修改入参,返回新对象)。
+ * 核心逻辑:匹配 every_minutes(星斜杠 N)、hourly、daily、weekly 四种已知模式,否则回退默认。
+ * @param expr - 后端存储的 cron 表达式
+ * @returns 新的 ScheduleCronDesigner
+ */
+export function parseCronExprToDesigner(expr: string | null | undefined): ScheduleCronDesigner {
+ const text = String(expr || '').trim();
+ const parts = text.split(/\s+/);
+ if (parts.length !== 5) {
+ return createDefaultCronDesigner();
+ }
+ const m = parts[0] ?? '';
+ const h = parts[1] ?? '';
+ const dow = parts[4] ?? '';
+ if (/^\*\/\d+$/.test(m) && h === '*' && dow === '*') {
+ return {
+ ...createDefaultCronDesigner(),
+ mode: 'every_minutes',
+ every_minutes: Number(m.replace('*/', '')) || 30,
+ };
+ }
+ if (/^\d+$/.test(m) && h === '*' && dow === '*') {
+ return {
+ ...createDefaultCronDesigner(),
+ mode: 'hourly',
+ hourly_minute: Number(m) || 0,
+ };
+ }
+ if (/^\d+$/.test(m) && /^\d+$/.test(h) && dow === '*') {
+ return {
+ ...createDefaultCronDesigner(),
+ mode: 'daily',
+ daily_hour: Number(h) || 0,
+ daily_minute: Number(m) || 0,
+ };
+ }
+ if (/^\d+$/.test(m) && /^\d+$/.test(h) && /^\d+$/.test(dow)) {
+ return {
+ ...createDefaultCronDesigner(),
+ mode: 'weekly',
+ weekly_hour: Number(h) || 0,
+ weekly_minute: Number(m) || 0,
+ weekly_day: Number(dow),
+ };
+ }
+ return createDefaultCronDesigner();
+}
+
+/**
+ * 根据 cron 表达式估算下一次本地执行时间(仅支持设计器可表达的模式)。
+ * 核心逻辑:解析五段式 cron,按 every_minutes / hourly / daily / weekly 分支推算 Date。
+ * @param expr - cron 表达式
+ * @returns 下次执行时间,无法解析时 null
+ */
+export function computeNextRunPreview(expr: string): Date | null {
+ if (!expr) return null;
+ try {
+ const parts = expr.trim().split(/\s+/);
+ if (parts.length !== 5) return null;
+ const now = new Date();
+ const minuteRaw = parts[0]!;
+ const hourRaw = parts[1]!;
+ const dayOfMonth = parts[2]!;
+ const month = parts[3]!;
+ const dayOfWeek = parts[4]!;
+ if (month !== '*') return null;
+ if (dayOfMonth !== '*' && dayOfWeek !== '*') return null;
+ const minute = minuteRaw.startsWith('*/') ? undefined : parseInt(minuteRaw, 10);
+ const hour = hourRaw === '*' ? undefined : parseInt(hourRaw, 10);
+ if (minuteRaw.startsWith('*/')) {
+ const every = parseInt(minuteRaw.replace('*/', ''), 10);
+ const next = new Date(now);
+ next.setSeconds(0, 0);
+ const mod = next.getMinutes() % every;
+ next.setMinutes(next.getMinutes() + (every - mod));
+ if (next <= now) next.setMinutes(next.getMinutes() + every);
+ return next;
+ }
+ if (minute !== undefined && hour === undefined) {
+ const next = new Date(now);
+ next.setMinutes(minute, 0, 0);
+ if (next <= now) next.setHours(next.getHours() + 1);
+ return next;
+ }
+ if (minute !== undefined && hour !== undefined) {
+ const next = new Date(now);
+ next.setHours(hour, minute, 0, 0);
+ if (next <= now) {
+ if (dayOfWeek !== '*') {
+ const dow = parseInt(dayOfWeek, 10);
+ const currentDow = next.getDay();
+ let diff = dow - currentDow;
+ if (diff <= 0) diff += 7;
+ next.setDate(next.getDate() + diff);
+ } else {
+ next.setDate(next.getDate() + 1);
+ }
+ } else if (dayOfWeek !== '*') {
+ const dow = parseInt(dayOfWeek, 10);
+ const target = new Date(next);
+ const currentDow = target.getDay();
+ let diff = dow - currentDow;
+ if (diff < 0) diff += 7;
+ if (diff > 0) target.setDate(target.getDate() + diff);
+ if (target <= now) {
+ target.setDate(target.getDate() + 7);
+ }
+ return target;
+ }
+ return next;
+ }
+ return null;
+ } catch {
+ return null;
+ }
+}
diff --git a/frontend/src/features/admin/modules/schedules/utils/schedule-form-payload.utils.ts b/frontend/src/features/admin/modules/schedules/utils/schedule-form-payload.utils.ts
new file mode 100644
index 00000000..b6eddb18
--- /dev/null
+++ b/frontend/src/features/admin/modules/schedules/utils/schedule-form-payload.utils.ts
@@ -0,0 +1,46 @@
+/**
+ * features/admin/modules/schedules/utils/schedule-form-payload.utils.ts
+ * 创建/编辑定时任务时 config 与请求 payload 组装。
+ */
+import type { ScheduleSqlEditForm } from '../types/schedule-admin.types';
+
+export function buildScheduleConfigPayload(
+ scheduleSqlEditForm: ScheduleSqlEditForm,
+ hasAgent: boolean,
+ headerLabels: Record,
+ apiHeaders: Record,
+) {
+ const aliasOrder = scheduleSqlEditForm.alias_order_str.split(',').map((s) => s.trim()).filter(Boolean);
+ const detailAliasOrder = scheduleSqlEditForm.detail_alias_order_str.split(',').map((s) => s.trim()).filter(Boolean);
+
+ return {
+ base_fetch_sql: scheduleSqlEditForm.base_fetch_sql,
+ fetch_where_conditions: scheduleSqlEditForm.fetch_where_conditions,
+ fetch_order_by: scheduleSqlEditForm.fetch_order_by,
+ detail_sql: scheduleSqlEditForm.detail_sql,
+ writeback_sql: scheduleSqlEditForm.writeback_sql,
+ row_id_key: scheduleSqlEditForm.row_id_key || 'id',
+ log_prefix: scheduleSqlEditForm.log_prefix,
+ alias_order: aliasOrder,
+ detail_alias_order: detailAliasOrder,
+ header_labels: headerLabels,
+ data_source: scheduleSqlEditForm.ds_host.trim() ? {
+ db_type: scheduleSqlEditForm.ds_db_type,
+ host: scheduleSqlEditForm.ds_host,
+ port: scheduleSqlEditForm.ds_port,
+ database: scheduleSqlEditForm.ds_database,
+ username: scheduleSqlEditForm.ds_username,
+ password: scheduleSqlEditForm.ds_password,
+ driver: scheduleSqlEditForm.ds_driver,
+ encrypt: scheduleSqlEditForm.ds_encrypt,
+ trust_cert: scheduleSqlEditForm.ds_trust_cert,
+ } : undefined,
+ external_api: scheduleSqlEditForm.api_url.trim() ? {
+ url: scheduleSqlEditForm.api_url,
+ method: scheduleSqlEditForm.api_method,
+ headers: apiHeaders,
+ body_template: scheduleSqlEditForm.api_body_template,
+ } : undefined,
+ dify_system_prompt: hasAgent ? scheduleSqlEditForm.dify_system_prompt : '',
+ };
+}
diff --git a/frontend/src/features/admin/modules/schedules/utils/schedule-format.utils.ts b/frontend/src/features/admin/modules/schedules/utils/schedule-format.utils.ts
new file mode 100644
index 00000000..555f0c7d
--- /dev/null
+++ b/frontend/src/features/admin/modules/schedules/utils/schedule-format.utils.ts
@@ -0,0 +1,29 @@
+/**
+ * features/admin/modules/schedules/utils/schedule-format.utils.ts
+ * 定时任务 API 日期解析与展示格式化纯函数。
+ * 依赖:无。
+ * 逻辑:由 useSchedulesAdmin 及视图组件通过 admin.formatDateTime 间接使用。
+ */
+
+/**
+ * 将 API 返回的 ISO 字符串解析为 Date(无时区后缀则按 UTC 处理)。
+ * @param iso - ISO 8601 或无时区后缀的时间字符串
+ * @returns Date 实例
+ */
+export function parseApiUtcDate(iso: string): Date {
+ const normalized = /(?:Z|[+-]\d{2}:\d{2})$/i.test(iso) ? iso : `${iso}Z`;
+ return new Date(normalized);
+}
+
+/**
+ * 格式化为本地 `YYYY-MM-DD HH:mm:ss`;空值或非法日期返回 `-` 或原字符串。
+ * @param iso - 可选 ISO 时间字符串
+ * @returns 展示用日期时间文本
+ */
+export function formatDateTime(iso?: string | null): string {
+ if (!iso) return '-';
+ const d = parseApiUtcDate(iso);
+ if (isNaN(d.getTime())) return iso;
+ const pad = (n: number) => String(n).padStart(2, '0');
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
+}
diff --git a/frontend/src/features/chat/api/toolRunProgress.api.ts b/frontend/src/features/chat/api/toolRunProgress.api.ts
new file mode 100644
index 00000000..beae2882
--- /dev/null
+++ b/frontend/src/features/chat/api/toolRunProgress.api.ts
@@ -0,0 +1,12 @@
+/**
+ * features/chat/api/toolRunProgress.api.ts
+ * 工具运行进度查询 API(Chat 输入栏进度卡片轮询)。
+ */
+import { requestJson } from '@/shared/api/client';
+import { getAuthHeaders } from '@/shared/utils/auth';
+import type { ToolRunProgressResponse } from '../types/tool-run-progress.types';
+
+export type { ToolRunProgress, ToolRunProgressResponse } from '../types/tool-run-progress.types';
+
+export const getToolRunProgress = (url: string) =>
+ requestJson(url, { headers: getAuthHeaders() });
diff --git a/frontend/src/features/chat/components/ChatInputBar.vue b/frontend/src/features/chat/components/ChatInputBar.vue
index fbafda12..825581e0 100644
--- a/frontend/src/features/chat/components/ChatInputBar.vue
+++ b/frontend/src/features/chat/components/ChatInputBar.vue
@@ -18,7 +18,7 @@ import {
X,
} from 'lucide-vue-next';
import ToolRunProgressCard from './ToolRunProgressCard.vue';
-import type { ToolRunProgress } from '@/api/toolRunProgress';
+import type { ToolRunProgress } from '../api/toolRunProgress.api';
import type { PendingAttachment } from '../types/shipping.types';
export interface ChatInputAttachmentPolicy {
diff --git a/frontend/src/features/chat/components/ToolRunProgressCard.vue b/frontend/src/features/chat/components/ToolRunProgressCard.vue
index 446f5542..5b19c827 100644
--- a/frontend/src/features/chat/components/ToolRunProgressCard.vue
+++ b/frontend/src/features/chat/components/ToolRunProgressCard.vue
@@ -1,6 +1,6 @@
+
+
+
+
+
+
+
{{ kb.t('kbWorkspace.recordModal.title') }}
+
+ {{ kb.t('kbWorkspace.recordModal.viewing', { name: kb.documentDisplayName(kb.selectedDocument, kb.selectedDocumentId) }) }}
+
+
+
+
+
+
+
+
+ {{ kb.t('kbWorkspace.recordModal.loading') }}
+
+
+
+
+
{{ kb.t('kbWorkspace.recordModal.versionsTitle') }}
+ {{ kb.t('kbWorkspace.recordModal.versionsCount', { count: kb.selectedDocumentVersions.length }) }}
+
+
+ {{ kb.t('kbWorkspace.recordModal.versionsEmpty') }}
+
+
+
+
+
+
+ v{{ version.version_no }} · {{ version.source_file_name }}
+
+
+
+ {{ kb.getStatusLabel(version.status) }}
+
+ {{ kb.t('kbWorkspace.recordModal.sizeBytes', { size: version.source_file_size ?? 0 }) }}
+
+
+
+ {{ kb.formatDateTime(version.created_at) }}
+
+
+
+
+
+
+
+
+
{{ kb.t('kbWorkspace.recordModal.syncTitle') }}
+ {{ kb.t('kbWorkspace.recordModal.versionsCount', { count: kb.selectedDocumentSyncRecords.length }) }}
+
+
+ {{ kb.t('kbWorkspace.recordModal.syncEmpty') }}
+
+
+
+
+
+
+ {{ record.dataset_name || record.dataset_id }} · {{ record.remote_document_name || record.remote_document_id }}
+
+
+
+ {{ kb.getStatusLabel(record.status) }}
+
+ {{ kb.t('kbWorkspace.recordModal.versionLabel', { id: record.document_version_id }) }}
+
+
+
+ {{ kb.formatDateTime(record.updated_at) }}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
{{ kb.markdownModalTitle }}
+
+ {{ kb.markdownVersionLabel || kb.t('kbWorkspace.markdownModal.readingVersion') }}
+
+ {{ kb.markdownKind === 'preview' ? kb.t('kbWorkspace.markdownModal.previewText') : kb.t('kbWorkspace.markdownModal.cleanMarkdown') }}
+
+
+
+
+
+
+
+
+
+ {{ kb.markdownError }}
+
+
+
+ {{ kb.t('kbWorkspace.markdownModal.loading') }}
+
+
+
+
+
+ {{ kb.t('kbWorkspace.common.close') }}
+
+
+ {{ kb.isMarkdownSaving ? kb.t('kbWorkspace.markdownModal.saving') : kb.t('kbWorkspace.markdownModal.save') }}
+
+
+
+
+
+
+
+
+
+
{{ kb.t('kbWorkspace.sourceInfoModal.title') }}
+
+ {{ kb.t('kbWorkspace.sourceInfoModal.viewing', { name: kb.documentDisplayName(kb.sourceInfoDocument, kb.sourceInfoDocumentId) }) }}
+
+
+
+
+
+
+
+
+ {{ kb.t('kbWorkspace.sourceInfoModal.loading') }}
+
+
+ {{ kb.t('kbWorkspace.sourceInfoModal.empty') }}
+
+
+
+
+
+
+
+ v{{ version.version_no }} · {{ version.source_file_name }}
+
+
+ {{ kb.t('kbWorkspace.sourceInfoModal.currentVersion') }}
+
+
+ {{ kb.t('kbWorkspace.sourceInfoModal.opening') }}
+
+
+
+
+ {{ kb.getStatusLabel(version.status) }}
+
+ {{ kb.t('kbWorkspace.sourceInfoModal.fileName', { name: version.source_file_name }) }}
+ {{ kb.t('kbWorkspace.sourceInfoModal.fileSize', { size: kb.formatFileSize(version.source_file_size) }) }}
+ {{ kb.t('kbWorkspace.sourceInfoModal.fileType', { ext: version.source_file_ext }) }}
+
+
+ {{ kb.t('kbWorkspace.common.failureReason', { reason: version.error_message }) }}
+
+
+
+ {{ kb.formatDateTime(version.created_at) }}
+
+
+
+
+
+
+
+ {{ kb.t('kbWorkspace.common.close') }}
+
+
+
+
+
+
+
+
+
+
{{ kb.failureModalTitle }}
+
+ {{ kb.t('kbWorkspace.failureModal.summary', { count: kb.failureModalItems.length, pageSize: kb.FAILURE_PAGE_SIZE }) }}
+
+
+
+
+
+
+
+
+ {{ kb.t('kbWorkspace.failureModal.empty') }}
+
+
+
+
+
+
+
+ {{ kb.getDocumentDisplayTitle(item.document) }}
+
+
+ {{ item.stageLabel }}
+
+
+
+ {{ kb.t('kbWorkspace.failureModal.currentVersion') }}
+
+ v{{ item.document.latest_version.version_no }} · {{ item.document.latest_version.source_file_name }}
+
+ {{ kb.t('kbWorkspace.failureModal.noVersion') }}
+
+
+ {{ kb.t('kbWorkspace.common.failureReason', { reason: item.errorMessage }) }}
+
+
+
+ {{ kb.formatDateTime(item.updatedAt) }}
+
+
+
+
+ {{ kb.retryingFailureKey === `${item.key}-submit` ? kb.t('kbWorkspace.common.processing') : kb.t('kbWorkspace.failureModal.resubmit') }}
+
+
+ {{ kb.retryingFailureKey === `${item.key}-clean` ? kb.t('kbWorkspace.common.processing') : kb.t('kbWorkspace.failureModal.reclean') }}
+
+
+ {{ kb.retryingFailureKey === `${item.key}-sync` ? kb.t('kbWorkspace.common.processing') : kb.t('kbWorkspace.failureModal.resync') }}
+
+
+
+
+
+
+
+ {{ kb.t('kbWorkspace.failureModal.pageInfo', { page: kb.failureModalPage, totalPages: kb.failureModalTotalPages }) }}
+
+
+
+ {{ kb.t('kbWorkspace.common.prevPage') }}
+
+
+ {{ kb.t('kbWorkspace.common.nextPage') }}
+
+
+
+
+
+
+
+
+
+
+
{{ kb.t('kbWorkspace.pathUploadModal.title') }}
+
+ {{ kb.t('kbWorkspace.pathUploadModal.subtitle') }}
+
+
+
+
+
+
+
+
+
+
+
+
{{ kb.t('kbWorkspace.pathUploadModal.localPickerTitle') }}
+
+ {{ kb.t('kbWorkspace.pathUploadModal.localPickerHint') }}
+
+
+
+
+ {{ kb.t('kbWorkspace.pathUploadModal.pickFolder') }}
+
+
+
+
+
+
+
+
+
+
+
+
+ {{ kb.t('kbWorkspace.pathUploadModal.pendingFiles') }}
+ {{ kb.t('kbWorkspace.recordModal.versionsCount', { count: kb.pathUploadSelectedFiles.length }) }}
+
+
+ {{ kb.t('kbWorkspace.pathUploadModal.selectedRoots', { paths: kb.selectedPathRoots.length ? kb.selectedPathRoots.join('、') : kb.t('kbWorkspace.pathUploadModal.noRoots') }) }}
+
+
+
+ {{ kb.t('kbWorkspace.pathUploadModal.pickFolderFirst') }}
+
+
+
+
+
{{ item.file.name }}
+
{{ item.displayPath }}
+
+
+ {{ kb.t('kbWorkspace.common.remove') }}
+
+
+
+
+
+
+
+
+ {{ kb.t('kbWorkspace.common.cancel') }}
+
+
+
+ {{ kb.t('kbWorkspace.pathUploadModal.confirmUpload') }}
+
+
+
+
+
+
+
+
+
+
{{ kb.t('kbWorkspace.pathUploadHistoryModal.title') }}
+
{{ kb.t('kbWorkspace.pathUploadHistoryModal.subtitle') }}
+
+
+
+
+
+
+
+ {{ kb.t('kbWorkspace.pathUpload.emptyHistory') }}
+
+
+
+
+
+
+
{{ kb.t('kbWorkspace.pathUpload.batchLabel', { id: job.id }) }}
+
{{ kb.formatDateTime(job.created_at) }}
+
+
+ {{ kb.getStatusLabel(job.status) }}
+
+
+
+
{{ kb.t('kbWorkspace.pathUpload.total', { count: kb.getPathUploadJobSummary(job).total }) }}
+
{{ kb.t('kbWorkspace.pathUpload.success', { count: kb.getPathUploadJobSummary(job).success }) }}
+
{{ kb.t('kbWorkspace.pathUpload.failed', { count: kb.getPathUploadJobSummary(job).failed }) }}
+
{{ kb.t('kbWorkspace.pathUpload.pendingProcess', { count: kb.getPathUploadJobSummary(job).pending }) }}
+
+
+
+
+
+
+
+
{{ kb.t('kbWorkspace.pathUpload.batchLabel', { id: kb.selectedPathUploadHistoryJob.id }) }}
+
+ {{ kb.t('kbWorkspace.pathUpload.createdAt', { time: kb.formatDateTime(kb.selectedPathUploadHistoryJob.created_at) }) }}
+ {{ kb.t('kbWorkspace.pathUpload.finishedAt', { time: kb.formatDateTime(kb.selectedPathUploadHistoryJob.finished_at) }) }}
+
+
{{ kb.selectedPathUploadHistoryJob.message || kb.t('kbWorkspace.pathUpload.noBatchMessage') }}
+
+
+
+ {{ kb.getStatusLabel(kb.selectedPathUploadHistoryJob.status) }}
+
+
+ {{ kb.isAllPathUploadHistoryItemsSelected ? kb.t('kbWorkspace.pathUpload.deselectAll') : kb.t('kbWorkspace.pathUpload.selectAll') }}
+
+
+ {{ kb.pathUploadBatchDeleteLabel(kb.deletingPathUploadBatch, kb.selectedPathUploadHistorySelectedItems.length) }}
+
+
+ {{ kb.retryingPathUploadKey === `${kb.selectedPathUploadHistoryJob.id}:all` ? kb.t('kbWorkspace.common.processing') : kb.t('kbWorkspace.pathUpload.retryAllFailed') }}
+
+
+
+
+
+
{{ kb.t('kbWorkspace.pathUpload.total', { count: kb.getPathUploadJobSummary(kb.selectedPathUploadHistoryJob).total }) }}
+
{{ kb.t('kbWorkspace.pathUpload.success', { count: kb.getPathUploadJobSummary(kb.selectedPathUploadHistoryJob).success }) }}
+
{{ kb.t('kbWorkspace.pathUpload.failed', { count: kb.getPathUploadJobSummary(kb.selectedPathUploadHistoryJob).failed }) }}
+
{{ kb.t('kbWorkspace.pathUpload.pendingProcess', { count: kb.getPathUploadJobSummary(kb.selectedPathUploadHistoryJob).pending }) }}
+
+
+
+
+
+
+
{{ item.title }}
+
{{ item.displayPath }}
+
{{ kb.t('kbWorkspace.common.failureReason', { reason: item.error }) }}
+
+
+
+ {{ kb.getPathUploadItemDisplayState(item).label }}
+
+
+ {{ kb.retryingPathUploadKey === `${kb.selectedPathUploadHistoryJob.id}:${item.displayPath}` ? kb.t('kbWorkspace.common.processing') : kb.t('kbWorkspace.common.retry') }}
+
+
+ {{ kb.t('kbWorkspace.common.delete') }}
+
+
+
+
+
+
+
+
+
+
+
diff --git a/frontend/src/features/kb/composables/kb-workspace/kb-workspace.state.ts b/frontend/src/features/kb/composables/kb-workspace/kb-workspace.state.ts
index 4aecc299..9150004b 100644
--- a/frontend/src/features/kb/composables/kb-workspace/kb-workspace.state.ts
+++ b/frontend/src/features/kb/composables/kb-workspace/kb-workspace.state.ts
@@ -135,7 +135,7 @@ export function createKbWorkspaceState(options: CreateKbWorkspaceStateOptions =
await pendingDeleteAction();
} catch (err) {
console.error('[deleteConfirm]', err);
- feedback.value = String(err) || '操作失败';
+ feedback.value = String(err) || t('kbWorkspace.msg.operationFailed');
feedbackType.value = 'error';
}
closeDeleteConfirmDialog();
diff --git a/frontend/src/features/kb/composables/kb-workspace/useKbWorkspaceComputed.ts b/frontend/src/features/kb/composables/kb-workspace/useKbWorkspaceComputed.ts
index def0bd4f..a7a4f772 100644
--- a/frontend/src/features/kb/composables/kb-workspace/useKbWorkspaceComputed.ts
+++ b/frontend/src/features/kb/composables/kb-workspace/useKbWorkspaceComputed.ts
@@ -47,6 +47,7 @@ export function useKbWorkspaceComputed(state: KbWorkspaceState) {
selectedPathUploadHistoryJobId,
selectedPathUploadHistoryItemKeys,
groups,
+ t,
} = state;
const selectedDocument = computed(() =>
@@ -60,7 +61,7 @@ export function useKbWorkspaceComputed(state: KbWorkspaceState) {
);
const markdownModalTitle = computed(() => {
const current = documents.value.find((item) => item.id === markdownDocumentId.value);
- return current ? getDocumentDisplayTitle(current) : 'Markdown 编辑器';
+ return current ? getDocumentDisplayTitle(current, t) : t('kbWorkspace.markdownModal.editorTitle');
});
const activeGroupJobs = computed(() =>
jobs.value.filter((item) => item.group_id === selectedGroupId.value),
@@ -68,13 +69,13 @@ export function useKbWorkspaceComputed(state: KbWorkspaceState) {
const getLatestJobForDocument = buildGetLatestJobForDocument(() => activeGroupJobs.value);
const resolveWorkflowState = (doc: KbDocumentItem) =>
- getDocumentWorkflowState(doc, getLatestJobForDocument);
+ getDocumentWorkflowState(doc, getLatestJobForDocument, t);
const getWorkflowBadgesForDoc = (doc: KbDocumentItem) =>
- getWorkflowBadges(doc, getLatestJobForDocument);
+ getWorkflowBadges(doc, getLatestJobForDocument, t);
const getMarkdownUnavailableMessageForDoc = (
doc: KbDocumentItem,
fallback?: string | null,
- ) => getMarkdownUnavailableMessage(doc, getLatestJobForDocument, fallback);
+ ) => getMarkdownUnavailableMessage(doc, getLatestJobForDocument, t, fallback);
const groupSummaryItems = computed(() => {
const docItems = documents.value;
@@ -86,12 +87,12 @@ export function useKbWorkspaceComputed(state: KbWorkspaceState) {
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 },
+ { label: t('kbWorkspace.summary.currentGroup'), value: groupName, wide: true, clickable: false },
+ { label: t('kbWorkspace.summary.documentCount'), value: String(docItems.length), wide: false, clickable: false },
+ { label: t('kbWorkspace.summary.pendingSync'), value: String(pendingSyncCount), wide: false, clickable: false },
+ { label: t('kbWorkspace.summary.uploadFailed'), value: String(uploadFailedCount), wide: false, clickable: uploadFailedCount > 0, failureType: 'upload' as const },
+ { label: t('kbWorkspace.summary.cleanFailed'), value: String(cleanFailedCount), wide: false, clickable: cleanFailedCount > 0, failureType: 'clean' as const },
+ { label: t('kbWorkspace.summary.syncFailed'), value: String(syncFailedCount), wide: false, clickable: syncFailedCount > 0, failureType: 'sync' as const },
];
});
@@ -114,8 +115,8 @@ export function useKbWorkspaceComputed(state: KbWorkspaceState) {
const normalizedKeyword = keyword.trim().toLowerCase();
if (!normalizedKeyword) return true;
const candidates = [
- getDocumentDisplayTitle(doc),
- getDocumentDisplayDescription(doc),
+ getDocumentDisplayTitle(doc, t),
+ getDocumentDisplayDescription(doc, t),
doc.title,
doc.description,
doc.latest_version?.source_file_name,
@@ -125,10 +126,10 @@ export function useKbWorkspaceComputed(state: KbWorkspaceState) {
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: '同步' },
+ { key: 'all', label: t('kbWorkspace.filters.all') },
+ { key: 'upload', label: t('kbWorkspace.filters.upload') },
+ { key: 'clean', label: t('kbWorkspace.filters.clean') },
+ { key: 'sync', label: t('kbWorkspace.filters.sync') },
];
return filters.map((item) => ({
...item,
@@ -189,8 +190,8 @@ export function useKbWorkspaceComputed(state: KbWorkspaceState) {
key: `${doc.id}-clean`,
document: doc,
stage: 'clean',
- stageLabel: '清洗失败',
- errorMessage: workflow.clean.errorMessage || workflow.primaryError || '清洗失败',
+ stageLabel: t('kbWorkspace.failureModal.stageCleanFailed'),
+ errorMessage: workflow.clean.errorMessage || workflow.primaryError || t('kbWorkspace.failureModal.stageCleanFailed'),
latestJob: getLatestJobForDocument(doc, 'clean'),
updatedAt: doc.updated_at || doc.latest_version?.created_at || null,
}];
@@ -200,8 +201,8 @@ export function useKbWorkspaceComputed(state: KbWorkspaceState) {
key: `${doc.id}-sync`,
document: doc,
stage: 'sync',
- stageLabel: '同步失败',
- errorMessage: workflow.sync.errorMessage || workflow.primaryError || '同步失败',
+ stageLabel: t('kbWorkspace.failureModal.stageSyncFailed'),
+ errorMessage: workflow.sync.errorMessage || workflow.primaryError || t('kbWorkspace.failureModal.stageSyncFailed'),
latestJob: getLatestJobForDocument(doc, 'sync_dify'),
updatedAt: doc.updated_at || doc.latest_version?.created_at || null,
}];
@@ -211,8 +212,8 @@ export function useKbWorkspaceComputed(state: KbWorkspaceState) {
key: `${doc.id}-upload`,
document: doc,
stage: 'upload',
- stageLabel: '上传失败',
- errorMessage: workflow.upload.errorMessage || workflow.primaryError || '上传失败',
+ stageLabel: t('kbWorkspace.failureModal.stageUploadFailed'),
+ errorMessage: workflow.upload.errorMessage || workflow.primaryError || t('kbWorkspace.failureModal.stageUploadFailed'),
latestJob: getLatestJobForDocument(doc, 'upload'),
updatedAt: doc.updated_at || doc.latest_version?.created_at || null,
}];
@@ -232,11 +233,11 @@ export function useKbWorkspaceComputed(state: KbWorkspaceState) {
const failureModalTitle = computed(() => {
const map = {
- upload: '上传失败数据',
- clean: '清洗失败数据',
- sync: '同步失败数据',
+ upload: t('kbWorkspace.failureModal.uploadData'),
+ clean: t('kbWorkspace.failureModal.cleanData'),
+ sync: t('kbWorkspace.failureModal.syncData'),
};
- return failureModalType.value ? map[failureModalType.value] : '失败数据';
+ return failureModalType.value ? map[failureModalType.value] : t('kbWorkspace.failureModal.generic');
});
const documentById = computed(() =>
@@ -273,7 +274,7 @@ export function useKbWorkspaceComputed(state: KbWorkspaceState) {
);
const selectedPathUploadHistoryItems = computed(() =>
- getPathUploadJobItems(selectedPathUploadHistoryJob.value),
+ getPathUploadJobItems(selectedPathUploadHistoryJob.value, t),
);
const selectedPathUploadHistorySelectedItems = computed(() => {
@@ -290,7 +291,7 @@ export function useKbWorkspaceComputed(state: KbWorkspaceState) {
if (item.status === 'failed') {
return {
normalized: 'failed',
- label: '失败',
+ label: t('kbWorkspace.status.failed'),
className: getStatusBadgeClass('failed'),
};
}
@@ -299,27 +300,27 @@ export function useKbWorkspaceComputed(state: KbWorkspaceState) {
const latestStatus = String(doc?.latest_version?.status || doc?.status || '').toLowerCase();
if (latestStatus === 'processing') {
- return { normalized: 'processing', label: '清洗中', className: getStatusBadgeClass('processing') };
+ return { normalized: 'processing', label: t('kbWorkspace.status.cleaning'), className: getStatusBadgeClass('processing') };
}
if (['cleaned', 'ready'].includes(latestStatus)) {
- return { normalized: latestStatus, label: '已清洗', className: getStatusBadgeClass(latestStatus) };
+ return { normalized: latestStatus, label: t('kbWorkspace.status.cleaned'), className: getStatusBadgeClass(latestStatus) };
}
if (latestStatus === 'syncing') {
- return { normalized: 'syncing', label: '同步中', className: getStatusBadgeClass('processing') };
+ return { normalized: 'syncing', label: t('kbWorkspace.status.syncing'), className: getStatusBadgeClass('processing') };
}
if (latestStatus === 'synced') {
- return { normalized: 'synced', label: '已同步', className: getStatusBadgeClass('synced') };
+ return { normalized: 'synced', label: t('kbWorkspace.status.synced'), className: getStatusBadgeClass('synced') };
}
if (latestStatus === 'uploaded') {
- return { normalized: 'uploaded', label: '待清洗', className: getStatusBadgeClass('uploaded') };
+ return { normalized: 'uploaded', label: t('kbWorkspace.status.pendingClean'), className: getStatusBadgeClass('uploaded') };
}
if (item.status === 'success' || item.documentId) {
- return { normalized: 'success', label: '已上传', className: getStatusBadgeClass('success') };
+ return { normalized: 'success', label: t('kbWorkspace.status.uploaded'), className: getStatusBadgeClass('success') };
}
if (item.status === 'uploading') {
- return { normalized: 'uploading', label: '上传中', className: getStatusBadgeClass('processing') };
+ return { normalized: 'uploading', label: t('kbWorkspace.status.uploading'), className: getStatusBadgeClass('processing') };
}
- return { normalized: 'queued', label: '待上传', className: getStatusBadgeClass('queued') };
+ return { normalized: 'queued', label: t('kbWorkspace.status.draft'), className: getStatusBadgeClass('queued') };
};
const pathUploadSummary = computed(() => {
diff --git a/frontend/src/features/kb/composables/kb-workspace/useKbWorkspaceData.ts b/frontend/src/features/kb/composables/kb-workspace/useKbWorkspaceData.ts
index 45eef740..6b0e20c9 100644
--- a/frontend/src/features/kb/composables/kb-workspace/useKbWorkspaceData.ts
+++ b/frontend/src/features/kb/composables/kb-workspace/useKbWorkspaceData.ts
@@ -48,6 +48,8 @@ export function useKbWorkspaceData(
selectedPathUploadHistoryJobId,
} = state;
+ const { t } = state;
+
const {
kbJobPollingActive,
latestPathUploadJob,
@@ -63,7 +65,7 @@ export function useKbWorkspaceData(
try {
const result = await getKbGroupsSafe();
if (!result.ok) {
- feedback.value = result.error || '加载知识库分组失败';
+ feedback.value = result.error || t('kbWorkspace.msg.loadGroupsFailed');
feedbackType.value = 'error';
return;
}
@@ -93,7 +95,7 @@ export function useKbWorkspaceData(
}
const result = await getKbGroupFilesSafe(groupId);
if (!result.ok) {
- feedback.value = result.error || '加载文档列表失败';
+ feedback.value = result.error || t('kbWorkspace.msg.loadDocumentsFailed');
feedbackType.value = 'error';
return;
}
@@ -126,13 +128,13 @@ export function useKbWorkspaceData(
const hadActiveKbJobs = kbJobPollingActive.value;
const result = await getKbJobsSafe();
if (!result.ok) {
- feedback.value = result.error || '加载任务列表失败';
+ feedback.value = result.error || t('kbWorkspace.msg.loadJobsFailed');
feedbackType.value = 'error';
return;
}
jobs.value = result.data;
applyPathUploadJob(latestPathUploadJob.value);
- if (latestPathUploadJob.value && getPathUploadJobSummary(latestPathUploadJob.value).failed > 0) {
+ if (latestPathUploadJob.value && getPathUploadJobSummary(latestPathUploadJob.value, t).failed > 0) {
showPathUploadDetails.value = true;
}
if (
diff --git a/frontend/src/features/kb/composables/kb-workspace/useKbWorkspaceDocuments.ts b/frontend/src/features/kb/composables/kb-workspace/useKbWorkspaceDocuments.ts
index 5c35e3d7..d48f69b5 100644
--- a/frontend/src/features/kb/composables/kb-workspace/useKbWorkspaceDocuments.ts
+++ b/frontend/src/features/kb/composables/kb-workspace/useKbWorkspaceDocuments.ts
@@ -48,6 +48,8 @@ export function useKbWorkspaceDocuments(
openDeleteConfirmDialog,
} = state;
+ const { t } = state;
+
const {
filteredDocuments,
selectedDocuments,
@@ -86,10 +88,10 @@ export function useKbWorkspaceDocuments(
};
const handleDeleteDocument = async (doc: KbDocumentItem) => {
- openDeleteConfirmDialog(`确认删除文档「${getDocumentDisplayTitle(doc)}」吗?`, async () => {
+ openDeleteConfirmDialog(t('kbWorkspace.msg.deleteDocumentConfirm', { name: getDocumentDisplayTitle(doc, t) }), async () => {
const result = await deleteKbDocument(doc.id);
if (!result.ok) {
- feedback.value = result.error || '删除文档失败';
+ feedback.value = result.error || t('kbWorkspace.msg.deleteDocumentFailed');
feedbackType.value = 'error';
return;
}
@@ -98,7 +100,7 @@ export function useKbWorkspaceDocuments(
selectedDocumentId.value = null;
showRecordModal.value = false;
}
- feedback.value = '文档已删除';
+ feedback.value = t('kbWorkspace.msg.documentDeleted');
feedbackType.value = 'success';
await Promise.all([loadGroups(), loadDocuments(selectedGroupId.value), loadJobs()]);
selectedDocumentVersions.value = [];
@@ -108,7 +110,7 @@ export function useKbWorkspaceDocuments(
const handleBatchSync = async () => {
if (!selectedDocuments.value.length) {
- feedback.value = '请先选择要批量同步的文档';
+ feedback.value = t('kbWorkspace.msg.selectDocumentsToSync');
feedbackType.value = 'error';
return;
}
@@ -123,10 +125,12 @@ export function useKbWorkspaceDocuments(
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 || '同步失败'}`);
+ const errors = failResults.map(({ doc, result }) =>
+ `${getDocumentDisplayTitle(doc, t)}: ${result.error || t('kbWorkspace.failureModal.stageSyncFailed')}`,
+ );
feedback.value = failCount
- ? `批量同步任务已提交:成功 ${successCount} 条,失败 ${failCount} 条。${errors[0] || ''}`
- : `批量同步任务已提交:共成功 ${successCount} 条`;
+ ? t('kbWorkspace.msg.batchSyncResult', { success: successCount, fail: failCount, detail: errors[0] || '' })
+ : t('kbWorkspace.msg.batchSyncSuccess', { success: successCount });
feedbackType.value = failCount ? 'error' : 'success';
if (successCount > 0) {
startPathUploadPolling();
@@ -139,12 +143,12 @@ export function useKbWorkspaceDocuments(
const handleBatchClean = async () => {
if (!selectedDocuments.value.length) {
- feedback.value = '请先选择要清洗的文档';
+ feedback.value = t('kbWorkspace.msg.selectDocumentsToClean');
feedbackType.value = 'error';
return;
}
if (!selectedCleanableDocuments.value.length) {
- feedback.value = '当前所选文档没有可重新清洗的项';
+ feedback.value = t('kbWorkspace.msg.noDocumentsToClean');
feedbackType.value = 'error';
return;
}
@@ -159,10 +163,12 @@ export function useKbWorkspaceDocuments(
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 || '提交清洗失败'}`);
+ const errors = failResults.map(({ doc, result }) =>
+ `${getDocumentDisplayTitle(doc, t)}: ${result.error || t('kbWorkspace.failureModal.stageCleanFailed')}`,
+ );
feedback.value = failCount
- ? `批量清洗任务已提交:成功 ${successCount} 条,失败 ${failCount} 条。${errors[0] || ''}`
- : `批量清洗任务已提交:共成功 ${successCount} 条`;
+ ? t('kbWorkspace.msg.batchCleanResult', { success: successCount, fail: failCount, detail: errors[0] || '' })
+ : t('kbWorkspace.msg.batchCleanSuccess', { success: successCount });
feedbackType.value = failCount ? 'error' : 'success';
if (successCount > 0) {
startPathUploadPolling();
@@ -175,12 +181,12 @@ export function useKbWorkspaceDocuments(
const handleBatchDelete = async () => {
if (!selectedDocuments.value.length) {
- feedback.value = '请先选择要批量删除的文档';
+ feedback.value = t('kbWorkspace.msg.selectDocumentsToDelete');
feedbackType.value = 'error';
return;
}
openDeleteConfirmDialog(
- `确认批量删除已选中的 ${selectedDocuments.value.length} 条文档吗?会同步删除 Dify 对应文档。`,
+ t('kbWorkspace.msg.batchDeleteDocumentsConfirm', { count: selectedDocuments.value.length }),
async () => {
batchSubmitting.value = true;
let successCount = 0;
@@ -193,12 +199,12 @@ export function useKbWorkspaceDocuments(
successCount += 1;
} else {
failCount += 1;
- errors.push(`${getDocumentDisplayTitle(doc)}: ${result.error || '删除失败'}`);
+ errors.push(`${getDocumentDisplayTitle(doc, t)}: ${result.error || t('kbWorkspace.msg.deleteDocumentFailed')}`);
}
}
feedback.value = failCount
- ? `批量删除完成:成功 ${successCount} 条,失败 ${failCount} 条。${errors[0] || ''}`
- : `批量删除完成:共成功 ${successCount} 条`;
+ ? t('kbWorkspace.msg.batchDeleteResult', { success: successCount, fail: failCount, detail: errors[0] || '' })
+ : t('kbWorkspace.msg.batchDeleteSuccess', { success: successCount });
feedbackType.value = failCount ? 'error' : 'success';
selectedDocumentIds.value = [];
await Promise.all([loadGroups(), loadDocuments(selectedGroupId.value), loadJobs()]);
@@ -223,28 +229,30 @@ export function useKbWorkspaceDocuments(
try {
if (action === 'submit') {
triggerUploadForDocument(item.document.id);
- feedback.value = `请重新为「${getDocumentDisplayTitle(item.document)}」选择文件后提交`;
+ feedback.value = t('kbWorkspace.msg.reselectFile', { name: getDocumentDisplayTitle(item.document, t) });
feedbackType.value = 'success';
return;
}
if (action === 'clean') {
const result = await submitKbDocumentClean(item.document.id);
if (!result.ok) {
- feedback.value = result.error || '重新清洗失败';
+ feedback.value = result.error || t('kbWorkspace.msg.recleanFailed');
feedbackType.value = 'error';
return;
}
- feedback.value = result.message || `已重新提交清洗:${getDocumentDisplayTitle(item.document)}`;
+ feedback.value = result.message || t('kbWorkspace.msg.recleanSubmitted', { name: getDocumentDisplayTitle(item.document, t) });
feedbackType.value = 'success';
startPathUploadPolling();
} else {
const result = await syncKbDocumentToDify(item.document.id);
if (!result.ok) {
- feedback.value = result.error ? `重新同步失败:${result.error}` : '重新同步失败';
+ feedback.value = result.error
+ ? t('kbWorkspace.msg.resyncFailed', { detail: result.error })
+ : t('kbWorkspace.failureModal.stageSyncFailed');
feedbackType.value = 'error';
return;
}
- feedback.value = result.job?.message || `已重新提交同步:${getDocumentDisplayTitle(item.document)}`;
+ feedback.value = result.job?.message || t('kbWorkspace.msg.resyncSubmitted', { name: getDocumentDisplayTitle(item.document, t) });
feedbackType.value = 'success';
startPathUploadPolling();
}
@@ -270,7 +278,7 @@ export function useKbWorkspaceDocuments(
}
isSubmitting.value = true;
- feedback.value = '开始处理文件...';
+ feedback.value = t('kbWorkspace.msg.processingFile');
feedbackType.value = 'success';
if (activeUploadDocumentId.value) {
@@ -278,10 +286,10 @@ export function useKbWorkspaceDocuments(
if (!file) return;
const result = await uploadKbDocumentVersion(activeUploadDocumentId.value, file);
if (!result.ok) {
- feedback.value = result.error || '文件上传失败';
+ feedback.value = result.error || t('kbWorkspace.msg.uploadFailed');
feedbackType.value = 'error';
} else {
- feedback.value = result.message || `版本文件「${file.name}」上传成功,清洗已排队`;
+ feedback.value = result.message || t('kbWorkspace.msg.versionUploaded', { file: file.name });
feedbackType.value = 'success';
startPathUploadPolling();
}
@@ -296,7 +304,11 @@ export function useKbWorkspaceDocuments(
for (let i = 0; i < fileArray.length; i++) {
const file = fileArray[i];
if (!file) continue;
- feedback.value = `正在上传 ${i + 1}/${fileArray.length}: ${file.name}`;
+ feedback.value = t('kbWorkspace.msg.uploadingProgress', {
+ current: i + 1,
+ total: fileArray.length,
+ file: file.name,
+ });
const createResult = await createKbDocument(selectedGroupId.value, {
title: file.name,
@@ -305,18 +317,21 @@ export function useKbWorkspaceDocuments(
if (!createResult.ok || !createResult.document) {
failCount++;
- errors.push(`${file.name}: ${normalizeDuplicateDocumentError(createResult.error || '创建文档失败')}`);
+ const createError = createResult.error
+ ? normalizeDuplicateDocumentError(createResult.error, t)
+ : t('kbWorkspace.msg.createDocumentFailed');
+ errors.push(`${file.name}: ${createError}`);
continue;
}
const uploadResult = await uploadKbDocumentVersion(createResult.document.id, file);
if (!uploadResult.ok) {
failCount++;
- const uploadError = uploadResult.error || '上传文档版本失败';
+ const uploadError = uploadResult.error || t('kbWorkspace.msg.uploadVersionFailed');
errors.push(`${file.name}: ${uploadError}`);
const cleanupResult = await deleteKbDocument(createResult.document.id);
if (!cleanupResult.ok) {
- errors.push(`${file.name}: 上传失败后未能自动清理空文档(${cleanupResult.error || '删除失败'})`);
+ errors.push(`${file.name}: ${t('kbWorkspace.msg.uploadCleanupFailed', { detail: cleanupResult.error || t('kbWorkspace.msg.deleteDocumentFailed') })}`);
}
} else {
successCount++;
@@ -324,10 +339,14 @@ export function useKbWorkspaceDocuments(
}
if (failCount > 0) {
- feedback.value = `上传完成:成功 ${successCount} 个,失败 ${failCount} 个。${errors[0] || ''}`;
+ feedback.value = t('kbWorkspace.msg.uploadSummary', {
+ success: successCount,
+ fail: failCount,
+ detail: errors[0] || '',
+ });
feedbackType.value = successCount > 0 ? 'success' : 'error';
} else {
- feedback.value = `成功上传 ${successCount} 个文件,清洗任务已排队`;
+ feedback.value = t('kbWorkspace.msg.uploadAllSuccess', { count: successCount });
feedbackType.value = 'success';
}
if (successCount > 0) {
@@ -355,14 +374,16 @@ export function useKbWorkspaceDocuments(
syncingDocumentId.value = null;
if (!result.ok) {
- feedback.value = result.error ? `同步到 Dify 失败:${result.error}` : '同步到 Dify 失败';
+ feedback.value = result.error
+ ? t('kbWorkspace.msg.syncDifyFailed', { detail: result.error })
+ : t('kbWorkspace.msg.syncDifyFailedGeneric');
feedbackType.value = 'error';
await loadDocuments(selectedGroupId.value, { silent: true });
await loadJobs();
return;
}
- feedback.value = result.job?.message || '同步任务已提交,等待后台处理';
+ feedback.value = result.job?.message || t('kbWorkspace.msg.syncSubmitted');
feedbackType.value = 'success';
startPathUploadPolling();
await loadDocuments(selectedGroupId.value, { silent: true });
diff --git a/frontend/src/features/kb/composables/kb-workspace/useKbWorkspaceModals.ts b/frontend/src/features/kb/composables/kb-workspace/useKbWorkspaceModals.ts
index 17ecab66..3db76eeb 100644
--- a/frontend/src/features/kb/composables/kb-workspace/useKbWorkspaceModals.ts
+++ b/frontend/src/features/kb/composables/kb-workspace/useKbWorkspaceModals.ts
@@ -46,6 +46,7 @@ export function useKbWorkspaceModals(
selectedGroupId,
} = state;
+ const { t } = state;
const { getMarkdownUnavailableMessageForDoc } = computed;
const { loadDocumentVersions, loadSourceInfoVersions, loadDocuments, loadJobs } = data;
@@ -78,7 +79,7 @@ export function useKbWorkspaceModals(
const result = await getKbDocumentVersionSourceFile(version.id);
openingSourceVersionId.value = null;
if (!result.ok || !result.blob) {
- feedback.value = result.error || '读取原始文件失败';
+ feedback.value = result.error || t('kbWorkspace.msg.readSourceFailed');
feedbackType.value = 'error';
return;
}
@@ -112,7 +113,7 @@ export function useKbWorkspaceModals(
markdownKind.value = payload.kind;
markdownVersionLabel.value = payload.version
? `v${payload.version.version_no} · ${payload.version.source_file_name}`
- : '暂无版本';
+ : t('kbWorkspace.msg.noVersion');
};
const openMarkdownEditor = async (doc: KbDocumentItem) => {
@@ -127,7 +128,10 @@ export function useKbWorkspaceModals(
const result = await getKbDocumentMarkdown(doc.id);
isMarkdownLoading.value = false;
if (!result.ok || !result.data) {
- markdownError.value = getMarkdownUnavailableMessageForDoc(doc, result.error || '读取清洗后的 Markdown 失败');
+ markdownError.value = getMarkdownUnavailableMessageForDoc(
+ doc,
+ result.error || t('kbWorkspace.msg.readMarkdownFailed'),
+ );
return;
}
applyMarkdownPayload(result.data);
@@ -156,13 +160,13 @@ export function useKbWorkspaceModals(
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 失败');
+ ? getMarkdownUnavailableMessageForDoc(currentDoc, result.error || t('kbWorkspace.msg.saveMarkdownFailed'))
+ : (result.error || t('kbWorkspace.msg.saveMarkdownFailed'));
return;
}
applyMarkdownPayload(result.data);
- feedback.value = '清洗后的 Markdown 已保存';
+ feedback.value = t('kbWorkspace.msg.markdownSaved');
feedbackType.value = 'success';
await loadDocuments(selectedGroupId.value);
await loadJobs();
diff --git a/frontend/src/features/kb/composables/kb-workspace/useKbWorkspacePathUpload.ts b/frontend/src/features/kb/composables/kb-workspace/useKbWorkspacePathUpload.ts
index e4ef35b8..421474ae 100644
--- a/frontend/src/features/kb/composables/kb-workspace/useKbWorkspacePathUpload.ts
+++ b/frontend/src/features/kb/composables/kb-workspace/useKbWorkspacePathUpload.ts
@@ -50,6 +50,8 @@ export function useKbWorkspacePathUpload(
openDeleteConfirmDialog,
} = state;
+ const { t } = state;
+
const {
pathUploadRunning,
kbJobPollingActive,
@@ -77,7 +79,12 @@ export function useKbWorkspacePathUpload(
const updatePathUploadFeedback = () => {
const summary = pathUploadSummary.value;
if (!pathUploadTask.value.total) return;
- feedback.value = `路径上传进度:总计 ${summary.total} 条,待上传 ${summary.pending} 条,已上传 ${summary.uploaded} 条,失败 ${summary.failed} 条`;
+ feedback.value = t('kbWorkspace.msg.pathUploadProgress', {
+ total: summary.total,
+ pending: summary.pending,
+ uploaded: summary.uploaded,
+ failed: summary.failed,
+ });
feedbackType.value = summary.failed > 0 ? 'error' : 'success';
};
@@ -102,9 +109,9 @@ export function useKbWorkspacePathUpload(
const items = Array.isArray(payload.files)
? payload.files.map((item: Record, index: number) => ({
key: String(item.relative_path || item.original_name || index),
- title: String(item.original_name || item.relative_path || `文件${index + 1}`),
+ title: String(item.original_name || item.relative_path || t('kbWorkspace.errors.fileFallback', { index: index + 1 })),
displayPath: String(item.relative_path || item.original_name || ''),
- rootLabel: String(item.relative_path || item.original_name || '').split('/')[0] || '本地目录',
+ rootLabel: String(item.relative_path || item.original_name || '').split('/')[0] || t('kbWorkspace.errors.localFolder'),
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,
@@ -148,7 +155,7 @@ export function useKbWorkspacePathUpload(
const openPathUploadModal = () => {
if (pathUploadRunning.value) {
- feedback.value = '有文件正在上传请稍等再试~';
+ feedback.value = t('kbWorkspace.msg.pathUploadBusy');
feedbackType.value = 'error';
return;
}
@@ -224,17 +231,17 @@ export function useKbWorkspacePathUpload(
const handleConfirmPathUpload = async () => {
if (pathUploadRunning.value) {
- feedback.value = '有文件正在上传请稍等再试~';
+ feedback.value = t('kbWorkspace.msg.pathUploadBusy');
feedbackType.value = 'error';
return;
}
if (!selectedGroupId.value) {
- feedback.value = '请先选择知识库分组';
+ feedback.value = t('kbWorkspace.msg.selectGroupFirst');
feedbackType.value = 'error';
return;
}
if (!pathUploadSelectedFiles.value.length) {
- feedback.value = '请先选择至少一个本地目录或文件';
+ feedback.value = t('kbWorkspace.msg.selectPathFiles');
feedbackType.value = 'error';
return;
}
@@ -249,13 +256,13 @@ export function useKbWorkspacePathUpload(
})),
});
if (!createResult.ok || !createResult.job) {
- feedback.value = createResult.error || '创建上传路径任务失败';
+ feedback.value = createResult.error || t('kbWorkspace.msg.createPathJobFailed');
feedbackType.value = 'error';
isPathUploadStaging.value = false;
return;
}
const createdJob = createResult.job;
- const existingJobItems = getPathUploadJobItems(createdJob);
+ const existingJobItems = getPathUploadJobItems(createdJob, t);
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) => {
@@ -302,7 +309,9 @@ export function useKbWorkspacePathUpload(
const stageResult = await uploadKbPathJobFile(createdJob.id, item.file, item.displayPath);
if (!stageResult.ok) {
- const errorMessage = normalizeDuplicateDocumentError(stageResult.error || '路径文件暂存失败');
+ const errorMessage = stageResult.error
+ ? normalizeDuplicateDocumentError(stageResult.error, t)
+ : t('kbWorkspace.msg.pathStageFailed');
const failedResult = await markKbPathJobFileFailed(createdJob.id, {
relative_path: item.displayPath,
original_name: item.file.name,
@@ -345,7 +354,7 @@ export function useKbWorkspacePathUpload(
isPathUploadStaging.value = false;
pathUploadTask.value.currentFile = '';
- feedback.value = '路径文件已逐个上传并提交清洗';
+ feedback.value = t('kbWorkspace.msg.pathUploadDone');
feedbackType.value = 'success';
startPathUploadPolling();
resetPathUploadDraft();
@@ -354,14 +363,16 @@ export function useKbWorkspacePathUpload(
const handleDeletePathUploadItem = async (job: KbJob | null, item: PathUploadTaskItem) => {
if (!job) return;
- openDeleteConfirmDialog(`确认删除路径文件「${item.displayPath || item.title}」吗?`, async () => {
+ openDeleteConfirmDialog(t('kbWorkspace.msg.deletePathFileConfirm', { path: item.displayPath || item.title }), async () => {
const result = await deleteKbPathJobFile(job.id, item.displayPath);
if (!result.ok) {
- feedback.value = result.error || '删除路径上传文件失败';
+ feedback.value = result.error || t('kbWorkspace.msg.deletePathFileFailed');
feedbackType.value = 'error';
return;
}
- feedback.value = result.document_deleted ? '已删除路径记录,并同步删除对应文档' : '已删除路径记录';
+ feedback.value = result.document_deleted
+ ? t('kbWorkspace.msg.pathRecordDeletedWithDoc')
+ : t('kbWorkspace.msg.pathRecordDeleted');
feedbackType.value = 'success';
if (pathUploadTask.value.items.length <= 1) {
showPathUploadDetails.value = false;
@@ -374,11 +385,11 @@ export function useKbWorkspacePathUpload(
const job = selectedPathUploadHistoryJob.value;
const items = selectedPathUploadHistorySelectedItems.value;
if (!job || !items.length) {
- feedback.value = '请先选择要删除的文件';
+ feedback.value = t('kbWorkspace.msg.selectPathFilesToDelete');
feedbackType.value = 'error';
return;
}
- openDeleteConfirmDialog(`确认批量删除已选中的 ${items.length} 条路径文件吗?`, async () => {
+ openDeleteConfirmDialog(t('kbWorkspace.msg.batchDeletePathConfirm', { count: items.length }), async () => {
deletingPathUploadBatch.value = true;
let successCount = 0;
let failCount = 0;
@@ -391,11 +402,11 @@ export function useKbWorkspacePathUpload(
continue;
}
failCount += 1;
- errors.push(`${item.displayPath}: ${result.error || '删除失败'}`);
+ errors.push(`${item.displayPath}: ${result.error || t('kbWorkspace.msg.deleteDocumentFailed')}`);
}
feedback.value = failCount
- ? `批量删除完成:成功 ${successCount} 条,失败 ${failCount} 条。${errors[0] || ''}`
- : `批量删除完成:共成功 ${successCount} 条`;
+ ? t('kbWorkspace.msg.batchDeletePathResult', { success: successCount, fail: failCount, detail: errors[0] || '' })
+ : t('kbWorkspace.msg.batchDeletePathSuccess', { success: successCount });
feedbackType.value = failCount ? 'error' : 'success';
selectedPathUploadHistoryItemKeys.value = [];
await Promise.all([
@@ -419,13 +430,15 @@ export function useKbWorkspacePathUpload(
const result = await retryFailedKbPathUploadJob(job.id, relativePaths?.length ? { relative_paths: relativePaths } : {});
retryingPathUploadKey.value = '';
if (!result.ok || !result.job) {
- feedback.value = result.error || '重试失败文件失败';
+ feedback.value = result.error || t('kbWorkspace.msg.retryPathFailed');
feedbackType.value = 'error';
return;
}
applyPathUploadJob(result.job);
startPathUploadPolling();
- feedback.value = relativePaths?.length === 1 ? '已重新提交该失败文件' : '已重新提交失败文件';
+ feedback.value = relativePaths?.length === 1
+ ? t('kbWorkspace.msg.retryPathOne')
+ : t('kbWorkspace.msg.retryPathAll');
feedbackType.value = 'success';
await bridge.refreshWorkflowStatusOnly();
};
diff --git a/frontend/src/features/kb/composables/useKbWorkspace.ts b/frontend/src/features/kb/composables/useKbWorkspace.ts
index 80d1e223..68f33aee 100644
--- a/frontend/src/features/kb/composables/useKbWorkspace.ts
+++ b/frontend/src/features/kb/composables/useKbWorkspace.ts
@@ -30,6 +30,7 @@ import { useKbWorkspaceData } from './kb-workspace/useKbWorkspaceData';
import { useKbWorkspaceDocuments } from './kb-workspace/useKbWorkspaceDocuments';
import { useKbWorkspaceModals } from './kb-workspace/useKbWorkspaceModals';
import { useKbWorkspacePathUpload } from './kb-workspace/useKbWorkspacePathUpload';
+import type { KbDocumentItem } from '../api/kb.api';
export interface UseKbWorkspaceOptions {
embedded?: boolean;
@@ -108,7 +109,7 @@ export function useKbWorkspace(options: UseKbWorkspaceOptions = {}) {
});
watch(selectedPathUploadHistoryJob, (job) => {
- const validKeys = new Set(getPathUploadJobItems(job).map((item) => item.key));
+ const validKeys = new Set(getPathUploadJobItems(job, t).map((item) => item.key));
selectedPathUploadHistoryItemKeys.value = selectedPathUploadHistoryItemKeys.value.filter((key) => validKeys.has(key));
if (!job) {
selectedPathUploadHistoryItemKeys.value = [];
@@ -128,6 +129,37 @@ export function useKbWorkspace(options: UseKbWorkspaceOptions = {}) {
pathUpload.stopPathUploadPollTimer();
});
+ const { t } = state;
+
+ const batchActionLabel = (action: 'clean' | 'sync' | 'delete', submitting: boolean, count: number) => {
+ if (submitting) return t('kbWorkspace.common.processing');
+ const keys = {
+ clean: ['batchClean', 'batchCleanCount'],
+ sync: ['batchSync', 'batchSyncCount'],
+ delete: ['batchDelete', 'batchDeleteCount'],
+ } as const;
+ const [base, withCount] = keys[action];
+ return count > 0
+ ? t(`kbWorkspace.documents.${withCount}`, { count })
+ : t(`kbWorkspace.documents.${base}`);
+ };
+
+ const pathUploadBatchDeleteLabel = (submitting: boolean, count: number) => {
+ if (submitting) return t('kbWorkspace.pathUpload.deleting');
+ return count > 0
+ ? t('kbWorkspace.pathUpload.batchDeleteCount', { count })
+ : t('kbWorkspace.pathUpload.batchDelete');
+ };
+
+ const documentEmptyMessage = (documentsLength: number, hasKeyword: boolean) => {
+ if (documentsLength === 0) return t('kbWorkspace.documents.emptyNoDocs');
+ if (hasKeyword) return t('kbWorkspace.documents.emptyNoSearchMatch');
+ return t('kbWorkspace.documents.emptyNoFilterMatch');
+ };
+
+ const documentDisplayName = (doc: KbDocumentItem | null | undefined, id: number | null) =>
+ doc ? getDocumentDisplayTitle(doc, t) : t('kbWorkspace.documents.documentFallback', { id });
+
// reactive 便于模板以 kb.xxx 统一访问,ref/computed 在属性读取时自动解包
return reactive({
...state,
@@ -140,17 +172,22 @@ export function useKbWorkspace(options: UseKbWorkspaceOptions = {}) {
getDocumentWorkflowState: computed.resolveWorkflowState,
formatDateTime,
formatFileSize,
- getDocumentDisplayTitle,
- getDocumentDisplayDescription,
- getStatusLabel,
+ getDocumentDisplayTitle: (doc: KbDocumentItem) => getDocumentDisplayTitle(doc, t),
+ getDocumentDisplayDescription: (doc: KbDocumentItem) => getDocumentDisplayDescription(doc, t),
+ getStatusLabel: (status: string | null | undefined) => getStatusLabel(status, t),
getStatusBadgeClass,
- getPathUploadJobItems,
- hasRetryablePathUploadFailure,
- getPathUploadJobSummary,
+ getPathUploadJobItems: (job: Parameters[0]) => getPathUploadJobItems(job, t),
+ hasRetryablePathUploadFailure: (job: Parameters[0]) =>
+ hasRetryablePathUploadFailure(job, t),
+ getPathUploadJobSummary: (job: Parameters[0]) => getPathUploadJobSummary(job, t),
DOCUMENT_PAGE_SIZE_OPTIONS,
FAILURE_PAGE_SIZE,
PATH_UPLOAD_BATCH_SIZE,
PATH_UPLOAD_BATCH_INTERVAL_MS,
PATH_UPLOAD_CONCURRENCY,
+ batchActionLabel,
+ pathUploadBatchDeleteLabel,
+ documentEmptyMessage,
+ documentDisplayName,
});
}
diff --git a/frontend/src/features/kb/utils/kb-display.utils.ts b/frontend/src/features/kb/utils/kb-display.utils.ts
index d4685b01..a7f7b319 100644
--- a/frontend/src/features/kb/utils/kb-display.utils.ts
+++ b/frontend/src/features/kb/utils/kb-display.utils.ts
@@ -3,6 +3,7 @@
* 文档标题、时间、文件大小与状态徽标等纯展示工具。
*/
import type { KbDocumentItem } from '../api/kb.api';
+import type { KbTranslateFn } from './kb-i18n.types';
export const formatDateTime = (value?: string | null) => {
if (!value) return '--';
@@ -27,40 +28,43 @@ const trimPathText = (value?: string | null) => {
return text.split(/[\\/]/).filter(Boolean).pop() || text;
};
-export const getDocumentDisplayTitle = (doc: KbDocumentItem) => trimPathText(doc.title) || '未命名文档';
+const STATUS_I18N_KEYS: Record = {
+ draft: 'kbWorkspace.status.draft',
+ uploaded: 'kbWorkspace.status.uploaded',
+ processing: 'kbWorkspace.status.processing',
+ cleaned: 'kbWorkspace.status.cleaned',
+ ready: 'kbWorkspace.status.ready',
+ synced: 'kbWorkspace.status.synced',
+ syncing: 'kbWorkspace.status.syncing',
+ failed: 'kbWorkspace.status.failed',
+ queued: 'kbWorkspace.status.queued',
+ running: 'kbWorkspace.status.running',
+ success: 'kbWorkspace.status.success',
+ cancelled: 'kbWorkspace.status.cancelled',
+};
-export const getDocumentDisplayDescription = (doc: KbDocumentItem) => {
+export const getDocumentDisplayTitle = (doc: KbDocumentItem, t: KbTranslateFn) =>
+ trimPathText(doc.title) || t('kbWorkspace.status.unnamedDocument');
+
+export const getDocumentDisplayDescription = (doc: KbDocumentItem, t: KbTranslateFn) => {
const text = trimPathText(doc.description);
- return text || getDocumentDisplayTitle(doc);
+ return text || getDocumentDisplayTitle(doc, t);
};
/** 将后端重复文档错误归一为前端可展示的简短文案 */
-export const normalizeDuplicateDocumentError = (message?: string | null) => {
+export const normalizeDuplicateDocumentError = (message: string | null | undefined, t: KbTranslateFn) => {
const text = String(message || '').trim();
- if (!text) return '知识库接口请求失败';
+ if (!text) return t('kbWorkspace.errors.apiRequestFailed');
if (text.includes('当前分组下已存在同名文档') || text.includes('上传失败,文件已存在')) {
- return '上传失败,文件已存在';
+ return t('kbWorkspace.errors.duplicateFile');
}
return text;
};
-export const getStatusLabel = (status?: string | null) => {
+export const getStatusLabel = (status: string | null | undefined, t: KbTranslateFn) => {
const normalized = String(status || '').toLowerCase();
- const map: Record = {
- draft: '待上传',
- uploaded: '已上传',
- processing: '清洗中',
- cleaned: '已清洗',
- ready: '已就绪',
- synced: '已同步',
- syncing: '同步中',
- failed: '失败',
- queued: '排队中',
- running: '进行中',
- success: '成功',
- cancelled: '已取消',
- };
- return map[normalized] || status || '未知状态';
+ const key = STATUS_I18N_KEYS[normalized];
+ return key ? t(key) : (status || t('kbWorkspace.status.unknown'));
};
export const getStatusBadgeClass = (status?: string | null) => {
diff --git a/frontend/src/features/kb/utils/kb-i18n.types.ts b/frontend/src/features/kb/utils/kb-i18n.types.ts
new file mode 100644
index 00000000..57e36895
--- /dev/null
+++ b/frontend/src/features/kb/utils/kb-i18n.types.ts
@@ -0,0 +1,2 @@
+/** 知识库作业面 i18n 翻译函数(vue-i18n `t` 的简化类型) */
+export type KbTranslateFn = (key: string, params?: Record) => string;
diff --git a/frontend/src/features/kb/utils/kb-path-upload.utils.ts b/frontend/src/features/kb/utils/kb-path-upload.utils.ts
index ce7ff14e..bd2dd34b 100644
--- a/frontend/src/features/kb/utils/kb-path-upload.utils.ts
+++ b/frontend/src/features/kb/utils/kb-path-upload.utils.ts
@@ -4,6 +4,7 @@
*/
import type { KbJob } from '../api/kb.api';
import type { PathUploadStatus, PathUploadTaskItem } from '../types/kb-workspace.types';
+import type { KbTranslateFn } from './kb-i18n.types';
export const getPathUploadJobProgress = (job: KbJob | null) => {
const payload = job?.payload_json || {};
@@ -32,22 +33,22 @@ export const getPathUploadJobPriority = (job: KbJob) => {
return (hasProgress ? 1000 : 0) + statusScore;
};
-export const getPathUploadJobItems = (job: KbJob | null): PathUploadTaskItem[] => {
+export const getPathUploadJobItems = (job: KbJob | null, t: KbTranslateFn): 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, index: number) => ({
key: `${job.id}-${item.relative_path || item.original_name || index}`,
- title: String(item.original_name || item.relative_path || `文件${index + 1}`),
+ title: String(item.original_name || item.relative_path || t('kbWorkspace.errors.fileFallback', { index: index + 1 })),
displayPath: String(item.relative_path || item.original_name || ''),
- rootLabel: String(item.relative_path || item.original_name || '').split('/')[0] || '本地目录',
+ rootLabel: String(item.relative_path || item.original_name || '').split('/')[0] || t('kbWorkspace.errors.localFolder'),
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 || '上传失败')
+ ? (job.error_message || job.message || t('kbWorkspace.errors.uploadFailed'))
: undefined),
documentId: (item.document_id as number | undefined) || undefined,
retryable: Boolean(String(item.staged_path || '').trim()) && String(item.status || '').toLowerCase() === 'failed',
@@ -56,11 +57,11 @@ export const getPathUploadJobItems = (job: KbJob | null): PathUploadTaskItem[] =
}));
};
-export const hasRetryablePathUploadFailure = (job: KbJob | null) =>
- getPathUploadJobItems(job).some((item) => item.retryable);
+export const hasRetryablePathUploadFailure = (job: KbJob | null, t: KbTranslateFn) =>
+ getPathUploadJobItems(job, t).some((item) => item.retryable);
-export const getPathUploadJobSummary = (job: KbJob | null) => {
- const items = getPathUploadJobItems(job);
+export const getPathUploadJobSummary = (job: KbJob | null, t: KbTranslateFn) => {
+ const items = getPathUploadJobItems(job, t);
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);
diff --git a/frontend/src/features/kb/utils/kb-workflow.utils.ts b/frontend/src/features/kb/utils/kb-workflow.utils.ts
index f590a928..c364afb3 100644
--- a/frontend/src/features/kb/utils/kb-workflow.utils.ts
+++ b/frontend/src/features/kb/utils/kb-workflow.utils.ts
@@ -5,6 +5,7 @@
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';
+import type { KbTranslateFn } from './kb-i18n.types';
export const isUnreadableErrorMessage = (value: string | null | undefined) => {
const text = String(value || '').trim();
@@ -17,27 +18,24 @@ export const isUnreadableErrorMessage = (value: string | null | undefined) => {
export const normalizeWorkflowErrorMessage = (
value: string | null | undefined,
stage: 'upload' | 'clean' | 'sync',
+ t: KbTranslateFn,
) => {
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 (stage === 'clean') return t('kbWorkspace.errors.unreadableClean');
+ if (stage === 'sync') return t('kbWorkspace.errors.unreadableSync');
+ return t('kbWorkspace.errors.unreadableUpload');
}
if (upper.includes('LEGACY_CLEAN_TASK_RECOVERED_MANUALLY')) {
- return '历史遗留清洗任务已人工回收,请重新点击“清洗数据”发起清洗';
+ return t('kbWorkspace.errors.legacyCleanRecovered');
}
if (upper.includes('SOURCE_FILE_NOT_FOUND') || text.includes('源文件不存在')) {
- return '原始文件不存在,请重新上传后再清洗';
+ return t('kbWorkspace.errors.sourceFileNotFound');
}
if (upper.includes('CLEAN_TIMEOUT') || text.includes('清洗超时')) {
- return '文件清洗超时,请稍后重试;若多次失败,请检查源文件是否损坏';
+ return t('kbWorkspace.errors.cleanTimeout');
}
return text;
};
@@ -69,6 +67,7 @@ export type GetLatestJobForDocument = ReturnType {
const latestStatus = String(doc.latest_version?.status || '').toLowerCase();
const uploadJob = getLatestJobForDocument(doc, 'upload');
@@ -76,72 +75,73 @@ export const getDocumentWorkflowState = (
const syncJob = getLatestJobForDocument(doc, 'sync_dify');
const uploadStage: WorkflowStageState = !doc.latest_version
- ? { code: 'pending', label: '待上传', className: getStatusBadgeClass('draft') }
+ ? { code: 'pending', label: t('kbWorkspace.status.draft'), className: getStatusBadgeClass('draft') }
: uploadJob?.status === 'failed'
? {
code: 'failed',
- label: '失败',
+ label: t('kbWorkspace.status.failed'),
className: getStatusBadgeClass('failed'),
- errorMessage: normalizeWorkflowErrorMessage(uploadJob.error_message || uploadJob.message, 'upload'),
+ errorMessage: normalizeWorkflowErrorMessage(uploadJob.error_message || uploadJob.message, 'upload', t),
}
- : { code: 'success', label: '已完成', className: getStatusBadgeClass('success') };
+ : { code: 'success', label: t('kbWorkspace.status.done'), className: getStatusBadgeClass('success') };
let cleanStage: WorkflowStageState;
if (!doc.latest_version) {
- cleanStage = { code: 'idle', label: '未开始', className: IDLE_BADGE_CLASS };
+ cleanStage = { code: 'idle', label: t('kbWorkspace.status.idle'), className: IDLE_BADGE_CLASS };
} else if (cleanJob?.status === 'failed' || latestStatus === 'failed') {
cleanStage = {
code: 'failed',
- label: '失败',
+ label: t('kbWorkspace.status.failed'),
className: getStatusBadgeClass('failed'),
errorMessage: normalizeWorkflowErrorMessage(
cleanJob?.error_message || doc.latest_version?.error_message || cleanJob?.message || null,
'clean',
+ t,
),
};
} else if (['cleaned', 'ready', 'syncing', 'synced'].includes(latestStatus)) {
- cleanStage = { code: 'success', label: '已完成', className: getStatusBadgeClass('success') };
+ cleanStage = { code: 'success', label: t('kbWorkspace.status.done'), className: getStatusBadgeClass('success') };
} else if (['running', 'queued'].includes(String(cleanJob?.status || '').toLowerCase()) || latestStatus === 'processing') {
cleanStage = {
code: 'running',
- label: latestStatus === 'processing' ? '清洗中' : '待清洗',
+ label: latestStatus === 'processing' ? t('kbWorkspace.status.cleaning') : t('kbWorkspace.status.pendingClean'),
className: getStatusBadgeClass(latestStatus === 'processing' ? 'processing' : 'uploaded'),
};
} else if (latestStatus === 'uploaded') {
- cleanStage = { code: 'pending', label: '待清洗', className: getStatusBadgeClass('uploaded') };
+ cleanStage = { code: 'pending', label: t('kbWorkspace.status.pendingClean'), className: getStatusBadgeClass('uploaded') };
} else {
- cleanStage = { code: 'idle', label: '未开始', className: IDLE_BADGE_CLASS };
+ cleanStage = { code: 'idle', label: t('kbWorkspace.status.idle'), className: IDLE_BADGE_CLASS };
}
let syncStage: WorkflowStageState;
if (!doc.latest_version || cleanStage.code === 'failed') {
- syncStage = { code: 'idle', label: '未开始', className: IDLE_BADGE_CLASS };
+ syncStage = { code: 'idle', label: t('kbWorkspace.status.idle'), className: IDLE_BADGE_CLASS };
} else if (syncJob?.status === 'failed') {
syncStage = {
code: 'failed',
- label: '失败',
+ label: t('kbWorkspace.status.failed'),
className: getStatusBadgeClass('failed'),
- errorMessage: normalizeWorkflowErrorMessage(syncJob.error_message || syncJob.message, 'sync'),
+ errorMessage: normalizeWorkflowErrorMessage(syncJob.error_message || syncJob.message, 'sync', t),
};
} else if (latestStatus === 'synced' || syncJob?.status === 'success') {
- syncStage = { code: 'success', label: '已完成', className: getStatusBadgeClass('success') };
+ syncStage = { code: 'success', label: t('kbWorkspace.status.done'), className: getStatusBadgeClass('success') };
} else if (['running', 'queued'].includes(String(syncJob?.status || '').toLowerCase()) || latestStatus === 'syncing') {
syncStage = {
code: 'running',
- label: latestStatus === 'syncing' ? '同步中' : '待同步',
+ label: latestStatus === 'syncing' ? t('kbWorkspace.status.syncing') : t('kbWorkspace.status.pendingSync'),
className: getStatusBadgeClass(latestStatus === 'syncing' ? 'processing' : 'uploaded'),
};
} else if (['cleaned', 'ready'].includes(latestStatus)) {
- syncStage = { code: 'pending', label: '待同步', className: getStatusBadgeClass('uploaded') };
+ syncStage = { code: 'pending', label: t('kbWorkspace.status.pendingSync'), className: getStatusBadgeClass('uploaded') };
} else {
- syncStage = { code: 'idle', label: '未开始', className: IDLE_BADGE_CLASS };
+ syncStage = { code: 'idle', label: t('kbWorkspace.status.idle'), className: IDLE_BADGE_CLASS };
}
const primaryError =
syncStage.errorMessage ||
cleanStage.errorMessage ||
uploadStage.errorMessage ||
- normalizeWorkflowErrorMessage(doc.latest_version?.error_message, 'clean') ||
+ normalizeWorkflowErrorMessage(doc.latest_version?.error_message, 'clean', t) ||
null;
return {
@@ -155,39 +155,42 @@ export const getDocumentWorkflowState = (
export const getWorkflowBadges = (
doc: KbDocumentItem,
getLatestJobForDocument: GetLatestJobForDocument,
+ t: KbTranslateFn,
) => {
- const workflow = getDocumentWorkflowState(doc, getLatestJobForDocument);
+ const workflow = getDocumentWorkflowState(doc, getLatestJobForDocument, t);
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 },
+ { label: t('kbWorkspace.workflow.upload'), value: workflow.upload.label, className: workflow.upload.className },
+ { label: t('kbWorkspace.workflow.clean'), value: workflow.clean.label, className: workflow.clean.className },
+ { label: t('kbWorkspace.workflow.sync'), value: workflow.sync.label, className: workflow.sync.className },
];
};
export const getMarkdownUnavailableMessage = (
doc: KbDocumentItem,
_getLatestJobForDocument: GetLatestJobForDocument,
+ t: KbTranslateFn,
fallback?: string | null,
) => {
const latestStatus = String(doc.latest_version?.status || '').toLowerCase();
const normalizedReason = normalizeWorkflowErrorMessage(
doc.latest_version?.error_message,
'clean',
+ t,
);
if (latestStatus === 'failed') {
return normalizedReason
- ? `当前文档清洗失败,尚未生成 Markdown。失败原因:${normalizedReason}`
- : '当前文档清洗失败,尚未生成 Markdown,请重新清洗后重试';
+ ? t('kbWorkspace.msg.markdownFailedWithReason', { reason: normalizedReason })
+ : t('kbWorkspace.msg.markdownFailedRetry');
}
if (latestStatus === 'processing') {
- return '当前文档正在清洗中,暂未生成 Markdown,请稍后再试';
+ return t('kbWorkspace.msg.markdownProcessing');
}
if (latestStatus === 'uploaded') {
- return '当前文档待清洗,暂未生成 Markdown,请先发起清洗';
+ return t('kbWorkspace.msg.markdownPendingClean');
}
- return fallback || '当前文档尚未生成 Markdown';
+ return fallback || t('kbWorkspace.msg.markdownNotGenerated');
};
diff --git a/frontend/src/features/kb/views/KbWorkspaceView.vue b/frontend/src/features/kb/views/KbWorkspaceView.vue
index e081a0f6..4217bc6c 100644
--- a/frontend/src/features/kb/views/KbWorkspaceView.vue
+++ b/frontend/src/features/kb/views/KbWorkspaceView.vue
@@ -3,8 +3,8 @@
* 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 { ArrowLeft, BookOpen, ChevronDown, ChevronUp, FileText, Info, RefreshCw, Search, Trash2, Upload } from 'lucide-vue-next';
+import KbWorkspaceOverlays from '../components/KbWorkspaceOverlays.vue';
import { useKbWorkspace } from '../composables/useKbWorkspace';
const props = defineProps<{
@@ -131,13 +131,12 @@ const kb = useKbWorkspace({ embedded: props.embedded });
/>
-
分组列表
- 接口壳已接入
+ {{ kb.t('kbWorkspace.sidebar.groupsTitle') }}
- 正在加载分组...
+ {{ kb.t('kbWorkspace.sidebar.loadingGroups') }}
- 暂无知识库分组。后续接通 `/api/kb/groups` 后将在这里显示真实数据。
+ {{ kb.t('kbWorkspace.sidebar.emptyGroups') }}
{{ group.name }}
-
{{ group.description || '暂无描述' }}
+
{{ group.description || kb.t('kbWorkspace.sidebar.noDescription') }}
{{ group.document_count ?? 0 }}
@@ -165,7 +164,7 @@ const kb = useKbWorkspace({ embedded: props.embedded });
-
文档列表
+
{{ kb.t('kbWorkspace.documents.title') }}
- 当前分组下的基础文档条目,上传文件后将自动创建文档并开始清洗流程。
+ {{ kb.t('kbWorkspace.documents.infoTip') }}
@@ -186,7 +185,7 @@ const kb = useKbWorkspace({ embedded: props.embedded });
class="inline-flex items-center gap-2 rounded-2xl border border-brand-200 px-4 py-2.5 text-sm font-medium text-brand-700 transition-colors hover:bg-brand-50 disabled:cursor-not-allowed disabled:opacity-60 border-brand-200 hover:bg-brand-50"
>
- 上传路径
+ {{ kb.t('kbWorkspace.documents.uploadPath') }}
- 上传文件
+ {{ kb.t('kbWorkspace.documents.uploadFile') }}
@@ -207,7 +206,7 @@ const kb = useKbWorkspace({ embedded: props.embedded });
class="inline-flex items-center gap-2 rounded-2xl border border-amber-200 px-4 py-2.5 text-sm font-medium text-amber-700 transition-colors hover:bg-amber-50 disabled:cursor-not-allowed disabled:opacity-60"
>
- {{ kb.batchSubmitting ? '处理中...' : `清洗数据${kb.selectedDocuments.length ? `(${kb.selectedDocuments.length})` : ''}` }}
+ {{ kb.batchActionLabel('clean', kb.batchSubmitting, kb.selectedDocuments.length) }}
- {{ kb.batchSubmitting ? '处理中...' : `批量同步${kb.selectedDocuments.length ? `(${kb.selectedDocuments.length})` : ''}` }}
+ {{ kb.batchActionLabel('sync', kb.batchSubmitting, kb.selectedDocuments.length) }}
- {{ kb.batchSubmitting ? '处理中...' : `批量删除${kb.selectedDocuments.length ? `(${kb.selectedDocuments.length})` : ''}` }}
+ {{ kb.batchActionLabel('delete', kb.batchSubmitting, kb.selectedDocuments.length) }}
- 历史批次
+ {{ kb.t('kbWorkspace.documents.historyBatches') }}
@@ -243,7 +242,7 @@ const kb = useKbWorkspace({ embedded: props.embedded });
v-model.trim="kb.documentKeyword"
type="text"
class="w-full rounded-2xl border border-default bg-surface py-2.5 pl-10 pr-4 text-sm text-primary outline-none transition-colors focus:border-brand-300"
- placeholder="按文件名称模糊搜索"
+ :placeholder="kb.t('kbWorkspace.documents.searchPlaceholder')"
/>
- 清空搜索
+ {{ kb.t('kbWorkspace.documents.clearSearch') }}
@@ -271,29 +270,29 @@ const kb = useKbWorkspace({ embedded: props.embedded });
- 路径上传进度
+ {{ kb.t('kbWorkspace.pathUpload.progressTitle') }}
- {{ kb.pathUploadRunning ? '上传中' : '已完成' }}
+ {{ kb.pathUploadRunning ? kb.t('kbWorkspace.pathUpload.uploading') : kb.t('kbWorkspace.pathUpload.completed') }}
- 建议每批 {{ kb.pathUploadTask.batchSize }} 条,间隔 {{ kb.PATH_UPLOAD_BATCH_INTERVAL_MS / 1000 }} 秒自动继续。
+ {{ kb.t('kbWorkspace.pathUpload.batchHint', { batchSize: kb.pathUploadTask.batchSize, seconds: kb.PATH_UPLOAD_BATCH_INTERVAL_MS / 1000 }) }}
-
总计 {{ kb.pathUploadSummary.total }}
-
待上传 {{ kb.pathUploadSummary.pending }}
-
已上传 {{ kb.pathUploadSummary.uploaded }}
-
失败 {{ kb.pathUploadSummary.failed }}
+
{{ kb.t('kbWorkspace.pathUpload.total', { count: kb.pathUploadSummary.total }) }}
+
{{ kb.t('kbWorkspace.pathUpload.pending', { count: kb.pathUploadSummary.pending }) }}
+
{{ kb.t('kbWorkspace.pathUpload.uploaded', { count: kb.pathUploadSummary.uploaded }) }}
+
{{ kb.t('kbWorkspace.pathUpload.failed', { count: kb.pathUploadSummary.failed }) }}
- 当前文件:{{ kb.pathUploadTask.currentFile }}
+ {{ kb.t('kbWorkspace.pathUpload.currentFile', { name: kb.pathUploadTask.currentFile }) }}
@@ -302,7 +301,7 @@ const kb = useKbWorkspace({ embedded: props.embedded });
@click="kb.showPathUploadDetails = !kb.showPathUploadDetails"
class="inline-flex items-center gap-2 text-sm font-medium text-secondary transition-colors hover:text-brand-600 hover:text-brand-600"
>
- 上传详情
+ {{ kb.t('kbWorkspace.pathUpload.details') }}
@@ -311,7 +310,7 @@ const kb = useKbWorkspace({ embedded: props.embedded });
@click="kb.openPathUploadHistoryModal(kb.latestPathUploadJob?.id || null)"
class="inline-flex items-center rounded-xl border border-default px-3 py-1.5 text-xs font-medium text-secondary transition-colors hover:bg-surface-soft hover-surface-soft"
>
- 查看历史
+ {{ kb.t('kbWorkspace.pathUpload.viewHistory') }}
- {{ kb.retryingPathUploadKey === `${kb.latestPathUploadJob.id}:all` ? '处理中...' : '重试失败文件' }}
+ {{ kb.retryingPathUploadKey === `${kb.latestPathUploadJob.id}:all` ? kb.t('kbWorkspace.common.processing') : kb.t('kbWorkspace.pathUpload.retryFailedFiles') }}
@@ -332,7 +331,7 @@ const kb = useKbWorkspace({ embedded: props.embedded });
{{ item.title }}
{{ item.displayPath }}
-
失败原因:{{ item.error }}
+
{{ kb.t('kbWorkspace.common.failureReason', { reason: item.error }) }}
- {{ kb.retryingPathUploadKey === `${kb.latestPathUploadJob.id}:${item.displayPath}` ? '处理中...' : '重试' }}
+ {{ kb.retryingPathUploadKey === `${kb.latestPathUploadJob.id}:${item.displayPath}` ? kb.t('kbWorkspace.common.processing') : kb.t('kbWorkspace.common.retry') }}
- 删除
+ {{ kb.t('kbWorkspace.common.delete') }}
@@ -370,7 +369,7 @@ const kb = useKbWorkspace({ embedded: props.embedded });
@click="kb.toggleSelectAllFiltered"
class="inline-flex items-center gap-2 rounded-full border border-default bg-surface px-4 py-2 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft hover-surface-soft"
>
- {{ kb.isAllFilteredSelected ? '取消全选' : '全选当前筛选' }}
+ {{ kb.isAllFilteredSelected ? kb.t('kbWorkspace.pathUpload.deselectAllFiltered') : kb.t('kbWorkspace.pathUpload.selectAllFiltered') }}
- 已选 {{ kb.selectedDocuments.length }} 条 · 共 {{ kb.filteredDocuments.length }} 条
- 当前显示 {{ kb.pagedDocumentRange.start }}-{{ kb.pagedDocumentRange.end }} 条
+ {{ kb.t('kbWorkspace.documents.selectedCount', { selected: kb.selectedDocuments.length, total: kb.filteredDocuments.length }) }}
+ {{ kb.t('kbWorkspace.documents.showingRange', { start: kb.pagedDocumentRange.start, end: kb.pagedDocumentRange.end }) }}
- 请选择一个知识库分组。
+ {{ kb.t('kbWorkspace.documents.selectGroup') }}
- 正在加载文档...
+ {{ kb.t('kbWorkspace.documents.loadingDocuments') }}
- {{ kb.documents.length === 0 ? '当前分组暂无文档,可直接在上方创建第一条文档记录。' : (kb.documentKeyword ? '当前搜索和筛选条件下暂无匹配文档。' : '当前筛选条件下暂无匹配文档。') }}
+ {{ kb.documentEmptyMessage(kb.documents.length, !!kb.documentKeyword) }}
- 版本数:{{ doc.version_count ?? 0 }}
+ {{ kb.t('kbWorkspace.documents.versionCount', { count: doc.version_count ?? 0 }) }}
- · 当前版本:v{{ doc.latest_version.version_no }} ·
+ {{ kb.t('kbWorkspace.documents.currentVersion', { version: doc.latest_version.version_no }) }}
- 查看记录
+ {{ kb.t('kbWorkspace.documents.viewRecord') }}
- 上传版本
+ {{ kb.t('kbWorkspace.documents.uploadVersion') }}
- {{ kb.syncingDocumentId === doc.id ? '同步中...' : '同步 Dify' }}
+ {{ kb.syncingDocumentId === doc.id ? kb.t('kbWorkspace.documents.syncingDify') : kb.t('kbWorkspace.documents.syncDify') }}
- 删除
+ {{ kb.t('kbWorkspace.common.delete') }}
-
+
- 更新时间:{{ kb.formatDateTime(doc.updated_at) }}
+ {{ kb.t('kbWorkspace.documents.updatedAt', { time: kb.formatDateTime(doc.updated_at) }) }}
- 失败原因:{{ kb.getDocumentWorkflowState(doc).primaryError }}
+ {{ kb.t('kbWorkspace.common.failureReason', { reason: kb.getDocumentWorkflowState(doc).primaryError }) }}
@@ -520,7 +519,7 @@ const kb = useKbWorkspace({ embedded: props.embedded });
class="flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-default px-4 py-3 "
>
- 第 {{ kb.documentListPage }} / {{ kb.filteredDocumentTotalPages }} 页 · 共 {{ kb.filteredDocuments.length }} 条
+ {{ kb.t('kbWorkspace.documents.pageInfo', { page: kb.documentListPage, totalPages: kb.filteredDocumentTotalPages, total: kb.filteredDocuments.length }) }}
- 上一页
+ {{ kb.t('kbWorkspace.common.prevPage') }}
- 下一页
+ {{ kb.t('kbWorkspace.common.nextPage') }}
@@ -546,621 +545,8 @@ const kb = useKbWorkspace({ embedded: props.embedded });
-
-
-
-
-
文档记录
-
- 当前查看:{{ kb.selectedDocument ? kb.getDocumentDisplayTitle(kb.selectedDocument) : `文档 #${kb.selectedDocumentId}` }}
-
-
-
-
-
-
-
- 正在加载文档记录...
-
-
-
-
-
版本记录
- {{ kb.selectedDocumentVersions.length }} 条
-
-
- 暂无版本记录,上传版本后会显示在这里。
-
-
-
-
-
-
- v{{ version.version_no }} · {{ version.source_file_name }}
-
-
-
- {{ kb.getStatusLabel(version.status) }}
-
- 大小:{{ version.source_file_size ?? 0 }} bytes
-
-
-
- {{ kb.formatDateTime(version.created_at) }}
-
-
-
-
-
-
-
-
-
Dify 同步记录
- {{ kb.selectedDocumentSyncRecords.length }} 条
-
-
- 暂无 Dify 同步记录,手动点击“同步 Dify”后会显示在这里。
-
-
-
-
-
-
- {{ record.dataset_name || record.dataset_id }} · {{ record.remote_document_name || record.remote_document_id }}
-
-
-
- {{ kb.getStatusLabel(record.status) }}
-
- 版本:{{ record.document_version_id }}
-
-
-
- {{ kb.formatDateTime(record.updated_at) }}
-
-
-
-
-
-
-
-
-
-
-
-
-
{{ kb.markdownModalTitle }}
-
- {{ kb.markdownVersionLabel || '正在读取当前版本...' }}
-
- {{ kb.markdownKind === 'preview' ? '预览文本' : '清洗 Markdown' }}
-
-
-
-
-
-
-
-
-
- {{ kb.markdownError }}
-
-
-
- 正在加载清洗后的 Markdown...
-
-
-
-
-
- 关闭
-
-
- {{ kb.isMarkdownSaving ? '保存中...' : '保存 Markdown' }}
-
-
-
-
-
-
-
-
-
源文件信息
-
- 当前查看:{{ kb.sourceInfoDocument ? kb.getDocumentDisplayTitle(kb.sourceInfoDocument) : `文档 #${kb.sourceInfoDocumentId}` }}
-
-
-
-
-
-
-
-
- 正在加载源文件信息...
-
-
- 暂无源文件信息,上传版本后会显示在这里。
-
-
-
-
-
-
-
- v{{ version.version_no }} · {{ version.source_file_name }}
-
-
- 当前版本
-
-
- 正在打开...
-
-
-
-
- {{ kb.getStatusLabel(version.status) }}
-
- 文件名:{{ version.source_file_name }}
- 大小:{{ kb.formatFileSize(version.source_file_size) }}
- 类型:{{ version.source_file_ext }}
-
-
- 失败原因:{{ version.error_message }}
-
-
-
- {{ kb.formatDateTime(version.created_at) }}
-
-
-
-
-
-
-
- 关闭
-
-
-
-
-
-
-
-
-
{{ kb.failureModalTitle }}
-
- 当前分组共 {{ kb.failureModalItems.length }} 条失败记录,每页 {{ kb.FAILURE_PAGE_SIZE }} 条。
-
-
-
-
-
-
-
-
- 当前没有失败数据。
-
-
-
-
-
-
-
- {{ kb.getDocumentDisplayTitle(item.document) }}
-
-
- {{ item.stageLabel }}
-
-
-
- 当前版本:
-
- v{{ item.document.latest_version.version_no }} · {{ item.document.latest_version.source_file_name }}
-
- 暂无版本
-
-
- 失败原因:{{ item.errorMessage }}
-
-
-
- {{ kb.formatDateTime(item.updatedAt) }}
-
-
-
-
- {{ kb.retryingFailureKey === `${item.key}-submit` ? '处理中...' : '重新提交' }}
-
-
- {{ kb.retryingFailureKey === `${item.key}-clean` ? '处理中...' : '重新清洗' }}
-
-
- {{ kb.retryingFailureKey === `${item.key}-sync` ? '处理中...' : '重新同步' }}
-
-
-
-
-
-
-
- 第 {{ kb.failureModalPage }} / {{ kb.failureModalTotalPages }} 页
-
-
-
- 上一页
-
-
- 下一页
-
-
-
-
-
-
-
-
-
-
上传路径
-
- 选择本地目录后,系统会按批次将该路径下文件导入当前分组并自动进入清洗流程。
-
-
-
-
-
-
-
-
-
-
-
-
本地路径选择
-
- 支持多次选择目录追加文件;当前浏览器安全限制下,手动粘贴任意本机路径不能直接读取文件内容。
-
-
-
-
- 选择本地目录
-
-
-
-
-
-
-
-
-
-
-
-
- 待上传文件
- {{ kb.pathUploadSelectedFiles.length }} 条
-
-
- 已选根路径:{{ kb.selectedPathRoots.length ? kb.selectedPathRoots.join('、') : '暂无' }}
-
-
-
- 请选择本地目录后再确认上传。
-
-
-
-
-
{{ item.file.name }}
-
{{ item.displayPath }}
-
-
- 移除
-
-
-
-
-
-
-
-
- 取消
-
-
-
- 确认上传
-
-
-
-
-
-
-
-
-
上传路径历史批次
-
查看每次路径上传的批次结果、失败文件与重试入口。
-
-
-
-
-
-
-
- 当前暂无上传路径历史批次。
-
-
-
-
-
-
-
批次 #{{ job.id }}
-
{{ kb.formatDateTime(job.created_at) }}
-
-
- {{ kb.getStatusLabel(job.status) }}
-
-
-
-
总计 {{ kb.getPathUploadJobSummary(job).total }}
-
成功 {{ kb.getPathUploadJobSummary(job).success }}
-
失败 {{ kb.getPathUploadJobSummary(job).failed }}
-
待处理 {{ kb.getPathUploadJobSummary(job).pending }}
-
-
-
-
-
-
-
-
批次 #{{ kb.selectedPathUploadHistoryJob.id }}
-
- 创建时间:{{ kb.formatDateTime(kb.selectedPathUploadHistoryJob.created_at) }}
- · 完成时间:{{ kb.formatDateTime(kb.selectedPathUploadHistoryJob.finished_at) }}
-
-
{{ kb.selectedPathUploadHistoryJob.message || '暂无批次说明' }}
-
-
-
- {{ kb.getStatusLabel(kb.selectedPathUploadHistoryJob.status) }}
-
-
- {{ kb.isAllPathUploadHistoryItemsSelected ? '取消全选' : '全选' }}
-
-
- {{ kb.deletingPathUploadBatch ? '删除中...' : `批量删除${kb.selectedPathUploadHistorySelectedItems.length ? ` (${kb.selectedPathUploadHistorySelectedItems.length})` : ''}` }}
-
-
- {{ kb.retryingPathUploadKey === `${kb.selectedPathUploadHistoryJob.id}:all` ? '处理中...' : '重试全部失败文件' }}
-
-
-
-
-
-
总计 {{ kb.getPathUploadJobSummary(kb.selectedPathUploadHistoryJob).total }}
-
成功 {{ kb.getPathUploadJobSummary(kb.selectedPathUploadHistoryJob).success }}
-
失败 {{ kb.getPathUploadJobSummary(kb.selectedPathUploadHistoryJob).failed }}
-
待处理 {{ kb.getPathUploadJobSummary(kb.selectedPathUploadHistoryJob).pending }}
-
-
-
-
-
-
-
{{ item.title }}
-
{{ item.displayPath }}
-
失败原因:{{ item.error }}
-
-
-
- {{ kb.getPathUploadItemDisplayState(item).label }}
-
-
- {{ kb.retryingPathUploadKey === `${kb.selectedPathUploadHistoryJob.id}:${item.displayPath}` ? '处理中...' : '重试' }}
-
-
- 删除
-
-
-
-
-
-
-
-
-
-
-
+
diff --git a/frontend/src/features/workspace/pages/ShippingNoticePage.vue b/frontend/src/features/workspace/pages/ShippingNoticePage.vue
index 186a4e3f..650a5246 100644
--- a/frontend/src/features/workspace/pages/ShippingNoticePage.vue
+++ b/frontend/src/features/workspace/pages/ShippingNoticePage.vue
@@ -3,7 +3,7 @@
* features/workspace/pages/ShippingNoticePage.vue
* 货代发货通知嵌入页,复用 ShippingNoticeView 的 embedded 模式。
*/
-import ShippingNoticeView from '@/views/ShippingNoticeView.vue';
+import ShippingNoticeView from '../views/ShippingNoticeView.vue';
diff --git a/frontend/src/views/ShippingNoticeView.vue b/frontend/src/features/workspace/views/ShippingNoticeView.vue
similarity index 98%
rename from frontend/src/views/ShippingNoticeView.vue
rename to frontend/src/features/workspace/views/ShippingNoticeView.vue
index 25dcbb1d..63977084 100644
--- a/frontend/src/views/ShippingNoticeView.vue
+++ b/frontend/src/features/workspace/views/ShippingNoticeView.vue
@@ -1,4 +1,8 @@
-