This commit is contained in:
新新 committed 2026-04-27 17:03:56 +08:00
commit fe636432d0
154 files changed
+30381

No files matched your search

@@ -0,0 +1,61 @@
# Dify Diff And Group UX Plan
> **For agent:** Execute directly against the existing implementation. Keep the current server deployment and avoid rebuilding core business logic.
**Goal:** Make the group area operationally clean, add a concrete Dify-vs-local diff surface for selected groups, prevent accidental duplicate pushes, and resolve the current stuck sync pair on the server.
**Architecture:** Keep the current FastAPI + worker + Vue SPA + Docker Compose structure. Add a lightweight comparison endpoint and a focused workspace UI refinement without introducing new dependencies.
## Current Findings
- The current sync failure is not caused by missing embedding or rerank model settings.
- The latest failed job timed out while waiting for Dify indexing, and the remote document remained stuck in `indexing`.
- Group cards still expose oversized management controls and the workspace does not yet provide a direct “show me local vs Dify differences” view.
- Current wording around Dify actions still risks reading like bidirectional sync when the implemented behavior is local push plus remote mapping.
## Execution Tracks
### Track 1: Group UX refinement
**Files:**
- Modify: `frontend/src/views/WorkspaceView.vue`
- Modify: `frontend/src/style.css`
- Modify: `frontend/src/lib/i18n.ts`
**Steps:**
1. Replace large group edit/delete buttons with compact icon actions on the group card.
2. Keep inline create only for the empty-state path.
3. Move group management to card-level actions only and keep the selected-group summary informational.
4. Tighten copy so Dify actions read as push/status, not realtime bidirectional sync.
### Track 2: Dify diff surface
**Files:**
- Modify: `backend/app/services/dify_service.py`
- Modify: `backend/app/api/groups.py`
- Modify: `frontend/src/views/WorkspaceView.vue`
- Modify: `frontend/src/lib/i18n.ts`
- Modify tests under `backend/tests/`
**Steps:**
1. List remote Dify documents for the selected dataset.
2. Compare local documents and remote documents by normalized document name within the selected group.
3. Return summary buckets and row-level status so the UI can show matched, local-only, Dify-only, and attention items.
4. Add a modal viewer in the workspace with search by file name inside the selected group.
### Track 3: Duplicate push guard and dirty data cleanup
**Files:**
- Modify: `backend/app/api/files.py`
- Apply one-off server cleanup for the current stuck local/remote record pair
**Steps:**
1. Reject single-document pushes when the current version is already marked `synced`.
2. Skip already-synced rows during batch push.
3. Delete the currently stuck remote Dify document and clear the corresponding local failed sync state so the next push starts from a clean baseline.
4. Rebuild only affected services and run a real server verification pass.
## Verification
1. Run targeted backend tests for diff and push guard behavior.
2. Run frontend `npm run build`.
3. Deploy updated backend and frontend services to `192.168.100.230`.
4. Verify group actions are compact and usable in the browser.
5. Verify the Dify diff modal reflects matched, local-only, Dify-only, and attention states.
6. Re-run a real Dify push after cleanup and confirm it reaches a completed indexing state.
@@ -0,0 +1,82 @@
# Local And Server Integration Plan
> **For agent:** REQUIRED SUB-SKILL: Use Section 4 or Section 5 to implement this plan.
**Goal:** Prepare `D:\Document Cleaning` for local and server integration, then execute real smoke tests for upload, conversion, download, deletion, and Dify sync where credentials allow.
**Architecture:** Keep the existing Docker deployment path for server use, but add a direct local execution path that does not depend on Docker, Redis, or PostgreSQL being installed on the developer workstation. Real conversion should run through the existing `edkb_system` and LibreOffice chain. Dify sync should use the existing production service when a real API key is present.
**Tech Stack:** FastAPI, SQLAlchemy, Alembic, RQ, Redis, PostgreSQL, SQLite, Vue/Vite, LibreOffice
## Current Environment Findings
- `docker` and `docker compose` are not installed or not on PATH in the current Windows environment.
- LibreOffice is installed locally at `C:\Program Files\LibreOffice\program\soffice.exe`.
- Python and Node are installed locally.
- Root `.env` is missing.
- `DIFY_API_KEY` is currently empty in `.env.example`, `backend.env.example`, and the current process/user/machine environment.
## Execution Strategy
### Track 1: Server Path
**Files:**
- Modify as needed: `docker-compose.yml`
- Modify as needed: `.env.example`
- Modify as needed: `backend/backend.env.example`
**Steps:**
1. Normalize environment variable handling so `PUBLIC_BASE_URL` and the Dify settings are driven by `.env`.
2. Create a real root `.env` file for the current machine.
3. Verify the compose configuration is ready for the target server once Docker is available.
### Track 2: Local Path
**Files:**
- Modify as needed: `backend/app/config.py`
- Modify as needed: `backend/app/services/queue_service.py`
- Modify as needed: `backend/worker.py`
- Modify as needed: `.env.example`
- Modify as needed: `backend/backend.env.example`
**Steps:**
1. Add a local task execution mode that can run queue tasks inline without Redis.
2. Keep the existing RQ mode unchanged for server deployment.
3. Configure the current workstation to use SQLite plus inline execution for local smoke tests.
### Task 1: Prepare integration configuration
**Files:**
- Modify: `docker-compose.yml`
- Modify: `.env.example`
- Modify: `backend/backend.env.example`
- Create: `.env`
**Step 1:** Add all required variables for local and server paths, including `PUBLIC_BASE_URL` and a task execution mode switch.
**Step 2:** Keep production defaults intact where possible.
**Step 3:** Verify the resulting configuration files are internally consistent.
### Task 2: Add local inline task execution mode
**Files:**
- Modify: `backend/app/config.py`
- Modify: `backend/app/services/queue_service.py`
- Modify as needed: `backend/tests/*`
**Step 1:** Add a configuration switch that chooses between `rq` and `sync`.
**Step 2:** In `sync` mode, execute `app.tasks.run_convert_job` and `app.tasks.run_sync_job` inline while preserving persisted job state.
**Step 3:** Verify the existing backend tests still pass after the change.
### Task 3: Start the local integration stack
**Files:**
- Read: `frontend/vite.config.ts`
- Read: `backend/alembic.ini`
- Read: `backend/migrations/env.py`
**Step 1:** Run Alembic against the local database.
**Step 2:** Start the backend locally.
**Step 3:** Start the frontend locally if needed for manual browser access.
**Step 4:** Confirm health and login endpoints respond over HTTP.
### Task 4: Run real smoke tests
**Files:**
- Read: `backend/data/original/**/*`
- Use runtime data under `backend/data/`
**Step 1:** Create a real group and upload a real document through the running API.
**Step 2:** Verify conversion completes using the existing document cleaning pipeline and LibreOffice path.
**Step 3:** Verify original download, markdown download, and local delete.
**Step 4:** Attempt real Dify sync if a valid key is available; otherwise capture the exact blocker and the furthest successful precondition.
### Task 5: Report integration status
**Files:**
- Read: generated runtime output and logs
**Step 1:** Record what was prepared for server deployment.
**Step 2:** Record what was proven locally with real runtime execution.
**Step 3:** Record any remaining blockers, especially around Docker and Dify credentials.
@@ -0,0 +1,69 @@
# Product UI And Deploy Hygiene Plan
> **For agent:** Execute directly against the existing implementation. Do not rebuild the stack from scratch.
**Goal:** Lift the current document cleaning system from an internal-tool baseline to a more professional product interface, tighten the local-to-server deployment workflow, and make Dify dataset model selection automatic instead of relying on manual console completion.
**Architecture:** Keep the current FastAPI + worker + Vue SPA + Docker Compose structure. Improve only the frontend experience, Dify integration defaults, and deployment packaging boundaries.
## Current Findings
- The core business flow is already usable end to end on the server.
- The frontend still reads as an engineering utility rather than a finished product surface.
- Server deployments were previously syncing non-runtime content such as `project-governance` and test artifacts.
- Dify dataset creation succeeded, but embedding and rerank model assignment was not being written by the API layer.
## Execution Tracks
### Track 1: Productize the frontend
**Files:**
- Modify: `frontend/src/style.css`
- Modify: `frontend/src/App.vue`
- Modify: `frontend/src/views/LoginView.vue`
- Modify: `frontend/src/views/WorkspaceView.vue`
- Modify: `frontend/src/views/AdminView.vue`
- Modify as needed: `frontend/src/components/*`
- Modify as needed: `frontend/src/lib/i18n.ts`
**Steps:**
1. Introduce a clearer visual direction with stronger surfaces, hierarchy, spacing, and global polish.
2. Keep the existing route structure and API contract intact.
3. Add bilingual UI support and a global language switch without introducing new dependencies.
4. Improve the admin configuration experience so Dify defaults feel like product settings, not raw system fields.
### Track 2: Automate Dify model selection
**Files:**
- Modify: `backend/app/services/dify_service.py`
- Modify: `backend/app/tasks.py`
- Modify: `backend/app/models.py`
- Modify: `backend/app/schemas.py`
- Modify: `backend/app/serializers.py`
- Modify: `backend/app/api/admin.py`
- Modify: `backend/app/services/bootstrap_service.py`
- Modify: `backend/app/config.py`
- Create: `backend/migrations/versions/20260328_0002_dify_model_defaults.py`
- Modify tests under `backend/tests/`
**Steps:**
1. Query the live Dify model catalog for embedding and rerank providers/models.
2. Apply a deterministic automatic choice when admin settings leave model fields empty.
3. Expose available models and automatic defaults in the admin API.
4. Allow explicit override from the admin UI while keeping automatic selection as the default path.
### Track 3: Tighten deployment boundaries
**Files:**
- Modify as needed: deployment packaging commands/scripts
- Keep on server only runtime files and secrets
**Steps:**
1. Exclude governance docs, tests, caches, local databases, and built artifacts from server syncs.
2. Remove already-synced non-runtime directories from the server deployment tree.
3. Rebuild only affected services after frontend/backend changes.
## Verification
1. Run targeted backend tests for admin settings and Dify task flows.
2. Run full backend `pytest` once the backend changes settle.
3. Run frontend `npm run build`.
4. Rebuild the changed Docker services on the server.
5. Execute a real server smoke test for login, upload, conversion, markdown download, Dify sync, and delete with `delete_dify=true`.
6. Confirm through the Dify API that new datasets carry embedding/rerank model settings and that remote documents return `404` after delete.
@@ -0,0 +1,91 @@
# Stability Hardening Implementation Plan
> **For agent:** REQUIRED SUB-SKILL: Use Section 4 or Section 5 to implement this plan.
**Goal:** Strengthen the existing document cleaning system without redesign by expanding backend coverage for critical workflows and removing known deprecations.
**Architecture:** Keep the current FastAPI + SQLAlchemy + RQ structure intact. Add focused backend tests around task execution and admin APIs, then make the smallest production changes needed to satisfy those tests and remove framework/runtime deprecation warnings.
**Tech Stack:** FastAPI, SQLAlchemy, pytest, Vue/Vite build verification, SQLite test database
## Constraints
- Continue from the current implementation. Do not rebuild flows or replace the current architecture.
- Save governance artifacts under `project-governance/`.
- Run targeted verification after each completed block, then run the full backend suite and frontend build at the end.
- Frontend code is out of scope unless backend changes force a UI adjustment.
### Task 1: Establish plan and baseline
**Files:**
- Create: `project-governance/plans/2026-03-28-stability-hardening-plan.md`
- Read: `backend/tests/conftest.py`
- Read: `backend/app/tasks.py`
- Read: `backend/app/main.py`
- Read: `backend/app/models.py`
**Step 1:** Record the implementation plan in this file.
**Step 2:** Confirm the current backend and frontend verification commands still pass:
- `cd backend && python -m pytest tests -q`
- `cd frontend && npm run build`
**Step 3:** Use the baseline output as the comparison point for later changes.
### Task 2: Add conversion and Dify task coverage
**Files:**
- Modify: `backend/tests/conftest.py`
- Create or modify: `backend/tests/test_tasks.py`
- Modify as needed: `backend/app/tasks.py`
**Step 1:** Write failing tests covering:
- conversion task success path
- conversion task failure path
- Dify sync success path
- Dify sync failure path
**Step 2:** Run only the new task-focused tests and confirm they fail for the expected reasons.
**Step 3:** Implement the smallest production changes needed to make those tests pass.
**Step 4:** Re-run the task-focused tests and confirm they pass cleanly.
### Task 3: Add delete flow coverage
**Files:**
- Modify: `backend/tests/test_uploads.py` or create `backend/tests/test_files_api.py`
- Modify as needed: `backend/app/api/files.py`
**Step 1:** Write failing tests for:
- delete local document only
- delete local document and remote Dify document
**Step 2:** Run the delete-focused tests and confirm they fail for the expected reasons.
**Step 3:** Apply the minimum production changes required.
**Step 4:** Re-run the delete-focused tests and confirm they pass.
### Task 4: Add admin API coverage
**Files:**
- Create: `backend/tests/test_admin_api.py`
- Modify as needed: `backend/app/api/admin.py`
- Modify as needed: `backend/app/api/jobs.py`
- Modify as needed: `backend/app/api/auth.py`
**Step 1:** Write failing tests for the core management endpoints:
- create user
- update user
- fetch settings
- update settings
- list jobs
- enforce admin protection on admin endpoints
**Step 2:** Run the admin-focused tests and confirm they fail for the expected reasons.
**Step 3:** Make the smallest production changes required.
**Step 4:** Re-run the admin-focused tests and confirm they pass.
### Task 5: Remove known deprecations
**Files:**
- Modify: `backend/app/main.py`
- Modify: `backend/app/models.py`
- Modify: `backend/app/tasks.py`
- Modify as needed: `backend/tests/conftest.py`
**Step 1:** Replace FastAPI startup `on_event` usage with a `lifespan` handler.
**Step 2:** Replace `datetime.utcnow()` defaults and timestamps with timezone-aware UTC helpers.
**Step 3:** Run the backend suite and check that the previously observed deprecation warnings are removed.
**Step 4:** If warnings remain, trace the exact source and make the smallest additional fix.
### Task 6: Final verification
**Files:**
- Read: `backend/tests/*.py`
- Read: `frontend/package.json`
**Step 1:** Run the full backend suite:
- `cd backend && python -m pytest tests -q`
**Step 2:** Run the frontend build:
- `cd frontend && npm run build`
**Step 3:** Summarize:
- changed behavior
- test evidence
- remaining risks or uncovered areas
@@ -0,0 +1,19 @@
# Workspace Productization Round 2 Plan
> **For agent:** REQUIRED SUB-SKILL: Use Section 4 or Section 5 to implement this plan.
**Goal:** Tighten the knowledge-base workspace into a compact product-grade operations UI without changing the backend data model.
**Architecture:** Keep the current Vue SPA and FastAPI APIs, but restructure the workspace around three layers: knowledge-base navigation, global system overview, and current knowledge-base actions. Support features such as global Dify diff, modal uploads, and online preview through existing APIs, adding only lightweight summary/diff endpoints where needed.
**Tech Stack:** Vue 3, TypeScript, Tailwind CSS, Uppy, FastAPI, SQLAlchemy, Dify API
## Scope
- Replace the sidebar “detail cards” with compact knowledge-base navigation items.
- Add global summary metrics and a global Dify diff entry point.
- Move batch upload into a modal and separate file vs folder selection.
- Simplify filters and document actions.
- Add online preview for source/Markdown where browser support allows.
- Keep all user-facing terminology as “知识库 / Knowledge Base”.
## Verification
- `cd backend && python -m pytest tests/test_uploads.py tests/test_files_api.py -q`
- `cd frontend && npm run build`
- Deploy updated `backend` and `frontend` to `192.168.100.230`
- Verify homepage, login, knowledge-base list, global diff, upload modal, preview actions, and delete flows on server
@@ -0,0 +1,39 @@
# Access Control And Admin UI Implementation Plan
> **For agent:** REQUIRED SUB-SKILL: Use Section 4 or Section 5 to implement this plan.
**Goal:** Add three-tier roles plus knowledge-base access control, and simplify workspace/admin UI around Dify settings and diff management.
**Architecture:** Backend introduces a user-to-knowledge-base access table and expands role handling from two levels to three. Frontend aligns workspace and admin around a shared account/settings pattern, removes noisy admin panels, and tightens diff/search/delete flows.
**Tech Stack:** FastAPI, SQLAlchemy, Alembic, Vue 3, TypeScript, Tailwind CSS
## Tasks
### Task 1: Role and access schema
- Add `super_admin` role handling.
- Add `user_group_access` table and ORM relationships.
- Update bootstrap defaults so the seeded admin becomes `super_admin`.
- Add Alembic migration.
### Task 2: API authorization
- Restrict knowledge-base and file access by role + assigned knowledge bases.
- Keep `super_admin` global.
- Allow `admin` to access operational admin pages, but require `super_admin` for user management.
- Support storing `accessible_group_ids` on user create/update.
### Task 3: Workspace header and settings
- Move Dify settings into the account menu.
- Reuse the same account-menu pattern in workspace and admin.
- Keep admin console entry only for admin tiers.
### Task 4: Diff and delete dialogs
- Global diff search uses explicit search type (`knowledge_base` / `file_name`) with matching placeholder.
- Diff table uses fixed-width layout and stable footer.
- Knowledge-base delete dialog uses top-right `X` and simplified body.
### Task 5: Admin page simplification
- Remove knowledge-base management and recent jobs panels.
- Keep Dify health and user management.
- Add per-user knowledge-base access controls and three role options.
### Task 6: Verification and deployment
- Run backend pytest coverage for admin/files/groups access behavior.
- Run frontend build.
- Apply migration on server and rebuild `api`/`frontend`.
@@ -0,0 +1,51 @@
# Department Permission And Admin Refactor Plan
> For this round, continue based on the existing implementation and do not rebuild from scratch.
## Goal
Refactor the admin and permission model so that:
- the `admin` account is the only `super_admin`
- permissions are centered on departments instead of direct user-to-knowledge-base bindings
- knowledge bases belong to departments
- workspace visibility is filtered by department
- the admin page becomes a focused permission management console
- Dify health moves into a user-menu dialog
## Scope
### Backend
- Add `Department` and `UserDepartmentAccess` models
- Add `primary_department_id` to `users`
- Add `department_id` to `groups`
- Backfill existing users and knowledge bases into a default department
- Enforce `admin` as the only `super_admin`
- Replace group visibility calculation from `UserGroupAccess` to department-based access
- Add department CRUD and user permission management endpoints
### Frontend
- Replace admin page with permission management
- Move Dify health to a modal entry under the user menu
- Rename user menu setting entry to `Dify设置`
- Change inline user editing to dialog-driven create/edit flows
- Add department selector to workspace sidebar and group creation flow
- Keep UI feedback lightweight with toast-style transient notices
### Validation
- Update backend tests for new department-based access model
- Run full backend pytest
- Run frontend build
- Deploy `api + worker + frontend`
- Verify role enforcement, department visibility, and Dify dialogs on server
## Implementation Order
1. Introduce department data model and migration with safe backfill.
2. Update permission helpers, group/file APIs, and admin APIs to use departments.
3. Rebuild the admin page into permission management and move Dify health into a dialog.
4. Update workspace department filter and knowledge-base ownership UX.
5. Run full validation and deploy.
@@ -0,0 +1,24 @@
# Dify Self-Healing Implementation Plan
> **For agent:** REQUIRED SUB-SKILL: Use Section 4 or Section 5 to implement this plan.
**Goal:** Add automatic Dify sync self-healing so stuck syncs recover cleanly, admins can see Dify health, and the server can restart Dify worker when queue execution stalls.
**Architecture:** The backend gains a watchdog service layer for stale-sync recovery and health snapshot reading, plus admin APIs for inspection and manual recovery. A host-level watchdog script on the deployment server inspects Dify queues/tasks via Docker, persists a JSON health snapshot into the app data volume, and restarts `dify-worker` when stuck-task thresholds are exceeded.
**Tech Stack:** FastAPI, SQLAlchemy, Vue 3, Docker Compose, Redis, PostgreSQL, host-side Python watchdog script.
## Scope
- Backend stale sync recovery logic
- Admin health/status APIs
- Host watchdog script and server cron installation
- Admin console Dify health panel
- Real server verification
## Non-Goals
- Replacing Dify’s own queue implementation
- Automatic blind resync loops for failed documents
- Adding Docker socket access into the app containers
## Task Outline
1. Add watchdog-oriented backend services for stale-sync recovery and persisted health snapshot access.
2. Add admin API endpoints for Dify health visibility and manual stale-sync cleanup.
3. Add host watchdog script and deployment wiring on `192.168.100.230`.
4. Extend admin UI with a compact Dify health panel.
5. Verify locally, deploy to server, run real Dify health and sync smoke checks.
@@ -0,0 +1,55 @@
# Permission Console And Department Workflow Plan
> Continue from the existing implementation. Do not rebuild the system from scratch.
## Goal
Make the admin experience coherent around department-based permissions, keep `admin` as the only super admin, and move Dify operational controls into the user menu while keeping workspace behavior department-aware.
## Outcomes
- `admin` remains the only `super_admin`
- users are managed through modal create/edit flows
- departments become the primary access boundary for knowledge bases
- workspace exposes a department selector on the left and respects that scope
- Dify settings and Dify health move under the username menu
- stale-sync recovery uses toast feedback only
## Backend
1. Re-verify the unique-super-admin policy around `admin`
2. Keep department-based visibility and department ownership on knowledge bases
3. Ensure user payloads expose:
- `primary_department_id`
- `primary_department_name`
- `accessible_department_ids`
- `extra_department_ids`
4. Keep Dify health and stale recovery endpoints, but align wording with “stuck sync” semantics
## Frontend
1. Workspace
- show department switcher in the left sidebar
- keep knowledge-base create/edit department ownership in dialogs
- expose `Dify设置` and `Dify健康状态` from the username menu
2. Admin
- use the page as `权限管理`
- left side: department management
- right side: users and department access
- create/edit users via modal only
- remove obsolete knowledge-base-management and recent-jobs sections
3. Dify Health
- render as dialog from the username menu
- replace banner-style feedback with 3-second toast feedback
- explain each health metric in plain language
## Validation
- run backend pytest
- run frontend build
- deploy `api + worker + frontend`
- smoke-check:
- `admin` is the only super admin
- department list and user list load
- workspace department switch filters knowledge bases
- Dify health opens from username menu and stale recovery shows toast
@@ -0,0 +1,24 @@
# Convert Watchdog And Integration API Plan
> **For agent:** REQUIRED SUB-SKILL: Use Section 4 or Section 5 to implement this plan.
**Goal:** Add self-healing for stuck local conversion jobs, expose a read-only integration API for other internal sites, and finish the server path migration to `/home/inspur/tools/document-cleaning` without leaving old deployment paths behind.
**Architecture:** Extend the existing watchdog service into a shared health/recovery layer for both sync and convert jobs, then wire the host watchdog script to observe the local RQ queue and restart the local worker when it stalls. Add a separate token-protected integration router that exposes knowledge-base, file, version, and download relationships without direct database access.
**Tech Stack:** FastAPI, SQLAlchemy, Redis/RQ, Vue (existing UI untouched for this task), Docker Compose, host-side watchdog Python script.
## Scope
- Local convert stale detection and recovery
- Host watchdog extension for local RQ queue / worker recovery
- Token-protected external read-only API
- Server cron/path updates from old project root to `/home/inspur/tools/document-cleaning`
- Verification on both local tests and deployed server
## Non-Goals
- PostgreSQL storage relocation
- New UI surfaces for convert watchdog
- Multi-tenant API key management
## Task Outline
1. Add convert health summary and stale-recovery services plus tests.
2. Extend watchdog CLI and host watchdog script to monitor the local convert queue and restart the app worker when it stalls.
3. Add integration API settings, auth dependency, endpoints, and tests.
4. Sync the latest code to `/home/inspur/tools/document-cleaning`, update cron/default paths, and remove old deployment paths.
5. Run local tests, rebuild the server, and verify the new endpoints and watchdog behavior.