fix(knowledge-base): 优化知识库页面,重构后端job队列

This commit is contained in:
sophie committed 2026-06-29 18:56:56 +08:00
1 parent 7e4a2037d8
commit b476b58a91
38 files changed
+992 -428

No files matched your search

+75 -1
View File
@@ -382,6 +382,77 @@ def _remove_path_upload_staged_file(staged_path: str | None):
break
parent = parent.parent
def _cancel_active_kb_jobs_for_documents(document_ids: list[int], message: str) -> int:
"""
取消已删除文档关联的后台任务。
Args:
document_ids: 被软删的知识库文档 id 列表。
message: 写入任务状态的取消原因。
Returns:
被标记为 cancelled 的任务数量。
"""
ids = [int(item) for item in document_ids if item]
if not ids:
return 0
version_ids = [
row[0]
for row in db.session.query(KbDocumentVersion.id)
.filter(KbDocumentVersion.document_id.in_(ids))
.all()
]
query = db.session.query(KbJob).filter(
KbJob.status.in_(('queued', 'running')),
KbJob.job_type.in_(('clean', 'sync_dify')),
)
if version_ids:
query = query.filter(
(KbJob.document_id.in_(ids)) | (KbJob.document_version_id.in_(version_ids))
)
else:
query = query.filter(KbJob.document_id.in_(ids))
now = datetime.utcnow()
cancelled = 0
for job in query.all():
job.status = 'cancelled'
job.progress = 100
job.message = message
job.error_message = None
job.finished_at = job.finished_at or now
cancelled += 1
return cancelled
def _cancel_active_kb_jobs_for_group(group_id: int, message: str) -> int:
"""
取消已停用知识库分组下仍未完成的后台任务。
Args:
group_id: 知识库分组 id。
message: 写入任务状态的取消原因。
Returns:
被标记为 cancelled 的任务数量。
"""
now = datetime.utcnow()
jobs = (
db.session.query(KbJob)
.filter(
KbJob.group_id == group_id,
KbJob.status.in_(('draft', 'staging', 'queued', 'running')),
KbJob.job_type.in_(('path_upload', 'clean', 'sync_dify')),
)
.all()
)
for job in jobs:
job.status = 'cancelled'
job.progress = 100
job.message = message
job.error_message = None
job.finished_at = job.finished_at or now
return len(jobs)
def _soft_delete_document(document_id: int | None, user_id: int | None):
if not document_id:
return False
@@ -394,6 +465,7 @@ def _soft_delete_document(document_id: int | None, user_id: int | None):
pass
document.is_deleted = True
document.updated_by_id = user_id
_cancel_active_kb_jobs_for_documents([document.id], '文档已删除,后台任务已取消')
return True
@knowledge_base_bp.route('/groups', methods=['GET'])
@@ -463,6 +535,7 @@ def delete_group(group_id: int):
current_user = get_current_user()
group.is_active = False
group.updated_by_id = getattr(current_user, 'id', None)
_cancel_active_kb_jobs_for_group(group.id, '知识库分组已删除,后台任务已取消')
db.session.commit()
return jsonify({'ok': True, 'id': group_id})
@@ -1009,8 +1082,9 @@ def delete_document(document_id: int):
pass
document.is_deleted = True
document.updated_by_id = getattr(current_user, 'id', None)
cancelled_jobs = _cancel_active_kb_jobs_for_documents([document.id], '文档已删除,后台任务已取消')
db.session.commit()
return jsonify({'ok': True, 'id': document_id, 'delete_dify': delete_result})
return jsonify({'ok': True, 'id': document_id, 'delete_dify': delete_result, 'cancelled_jobs': cancelled_jobs})
@knowledge_base_bp.route('/jobs', methods=['GET'])
def list_jobs():
+1 -1
View File
@@ -71,7 +71,7 @@ def _backend_path(env_key: str, *parts: str) -> str:
class Config:
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = os.getenv('SECRET_KEY')
KB_STORAGE_ROOT = os.getenv('KB_STORAGE_ROOT', str(_BACKEND_DIR / 'data' / 'kb'))
KB_STORAGE_ROOT = _data_path('KB_STORAGE_ROOT', 'kb')
KB_TASK_EXECUTION_MODE = os.getenv('KB_TASK_EXECUTION_MODE', 'worker').strip().lower()
KB_WORKER_POLL_SECONDS = float(os.getenv('KB_WORKER_POLL_SECONDS', '2'))
KB_WORKER_CONCURRENCY = int(os.getenv('KB_WORKER_CONCURRENCY', '3') or '3')
+18 -7
View File
@@ -1,8 +1,8 @@
"""
backend/app/jobs/handlers/kb_clean.py
用途:KB 文档清洗任务 handler。
逻辑:Wave 2 包装 knowledge_cleaning.queue_service.process_next_clean_job。
用途:KB 文档清洗 / 路径上传任务 handler。
逻辑:包装 knowledge_cleaning.tasks.run_clean_job / run_path_upload_job。
"""
from __future__ import annotations
@@ -14,11 +14,22 @@ from app.jobs.types import JobType
@register_handler(JobType.KB_CLEAN)
def run_kb_clean(ctx: JobContext, payload: dict) -> None:
"""
执行单条 KB 清洗任务。
执行单条 KB 清洗或路径上传任务。
Args:
ctx: Worker 上下文。
payload: 含 document_id 等字段。
payload: 须含 job_id;raw_job_type 为 path_upload 时走路径上传分支。
"""
ctx.logger.info('kb_clean handler skeleton invoked payload=%s', payload)
# Wave 2: from app.services.knowledge_cleaning.queue_service import process_job
raise NotImplementedError('kb_clean handler pending Wave 2')
job_id = int(payload['job_id'])
raw_type = str(payload.get('raw_job_type') or 'clean').strip()
from app.services.knowledge_cleaning.tasks import run_clean_job, run_path_upload_job
if raw_type == 'path_upload':
ok, message = run_path_upload_job(job_id)
else:
ok, message = run_clean_job(job_id)
level = ctx.logger.info if ok else ctx.logger.warning
level('kb_clean job_id=%s raw_type=%s ok=%s message=%s', job_id, raw_type, ok, message)
if not ok:
raise RuntimeError(message)
+15 -4
View File
@@ -2,7 +2,7 @@
backend/app/jobs/handlers/kb_dify_sync.py
用途:KB 文档同步至 Dify 任务 handler。
逻辑:Wave 2 包装 knowledge_cleaning.dify_sync_service。
逻辑:包装 knowledge_cleaning.tasks.run_sync_job。
"""
from __future__ import annotations
@@ -13,6 +13,17 @@ from app.jobs.types import JobType
@register_handler(JobType.KB_DIFY_SYNC)
def run_kb_dify_sync(ctx: JobContext, payload: dict) -> None:
"""同步已清洗文档到 Dify。"""
ctx.logger.info('kb_dify_sync handler skeleton invoked payload=%s', payload)
raise NotImplementedError('kb_dify_sync handler pending Wave 2')
"""
同步已清洗文档到 Dify。
Args:
ctx: Worker 上下文。
payload: 须含 job_id(KbJob 主键)。
"""
job_id = int(payload['job_id'])
from app.services.knowledge_cleaning.tasks import run_sync_job
ok, message = run_sync_job(job_id)
level = ctx.logger.info if ok else ctx.logger.warning
level('kb_dify_sync job_id=%s ok=%s message=%s', job_id, ok, message)
if not ok:
raise RuntimeError(message)
@@ -15,5 +15,12 @@ from app.services.shipping_notice.queue_service import run_shipping_notice_job
@register_handler(JobType.SHIPPING_NOTICE_RUN)
def run_shipping_notice(ctx: JobContext, payload: dict) -> None:
"""消费单票发货后台任务。"""
run_shipping_notice_job(payload, logger=ctx.logger)
"""
消费单票发货后台任务。
Args:
ctx: Worker 上下文。
payload: 须含 job_id 或 task_no。
"""
ok, message = run_shipping_notice_job(payload, logger=ctx.logger)
if not ok:
raise RuntimeError(message)
+74 -10
View File
@@ -1,16 +1,46 @@
"""
backend/app/jobs/queue.py
用途:任务入队 API。
逻辑:API / services 调用 enqueue;Wave 2 写入 Job 表并 adapter KbJob。
用途:任务入队 API(Wave 2:adapter 至 KbJob + 域内 enqueue 函数)。
逻辑:API / services 在创建 KbJob 后调用 enqueue;sync 模式仍由域内函数同步执行。
"""
from __future__ import annotations
from typing import Any
from app.core.errors import ValidationError
from app.jobs.types import JobType
def _find_shipping_notice_job_id(task_no: str) -> int | None:
"""
按 task_no 查找发货任务对应的 KbJob。
Args:
task_no: 发货任务号;由 AI 或业务代码传入时可大小写混用。
Returns:
匹配到的最新 KbJob 主键;未找到返回 None。
"""
from app import db
from app.models import KbJob
normalized_task_no = str(task_no or '').strip().upper()
candidates = (
db.session.query(KbJob)
.filter(
KbJob.job_type == JobType.SHIPPING_NOTICE_RUN.value,
KbJob.status.in_(('queued', 'running', 'success', 'failed')),
)
.order_by(KbJob.id.desc())
.limit(50)
.all()
)
for job in candidates:
payload_json = job.payload_json or {}
if str(payload_json.get('task_no') or '').strip().upper() == normalized_task_no:
return job.id
return None
def enqueue(
job_type: JobType,
payload: dict[str, Any],
@@ -19,16 +49,50 @@ def enqueue(
scheduled_at: Any = None,
) -> int:
"""
将任务写入队列并返回 job id。
核心逻辑:Wave 2 实现 store.create + KbJob adapter。
将任务提交执行并返回 job id(Wave 2 要求 payload 含已持久化的 KbJob id 或发货参数)。
核心逻辑:KB/发货任务委托既有 queue_service;未创建 KbJob 的调用方须先写库再 enqueue。
Args:
job_type: 任务类型。
payload: 任务参数 JSON。
correlation_id: 关联业务 id(如 kb_document_id)。
scheduled_at: 延迟执行时间(可选)。
payload: 任务参数;KB 类须含 job_id,发货类须含 task_no。
correlation_id: 关联业务 id(预留,当前未写入 KbJob)。
scheduled_at: 延迟执行时间(预留)。
Returns:
Job 主键。
KbJob 主键。
Raises:
NotImplementedError: Wave 0 占位。
ValidationError: 参数缺失或域 enqueue 失败。
"""
raise NotImplementedError('jobs.enqueue is not wired until Wave 2')
_ = correlation_id, scheduled_at # Wave 4 通用 Job 表再使用
if job_type in (JobType.KB_CLEAN, JobType.KB_DIFY_SYNC):
job_id = payload.get('job_id')
if not job_id:
raise ValidationError('enqueue KB job 须在 payload 中提供 job_id(先创建 KbJob)')
from app.services.knowledge_cleaning.queue_service import enqueue_kb_job
ok, msg = enqueue_kb_job(int(job_id))
if not ok:
raise ValidationError(f'KB job enqueue failed: {msg}')
return int(job_id)
if job_type == JobType.SHIPPING_NOTICE_RUN:
task_no = str(payload.get('task_no') or '').strip()
if not task_no:
raise ValidationError('enqueue shipping job 须在 payload 中提供 task_no')
from app.services.shipping_notice.queue_service import enqueue_shipping_notice_job
ok, msg = enqueue_shipping_notice_job(
task_no=task_no,
created_by_id=payload.get('created_by_id'),
batch_no=payload.get('batch_no'),
)
if not ok:
raise ValidationError(f'shipping job enqueue failed: {msg}')
# sync/worker/already_queued 均需按 task_no 精确回查,避免返回其他发货任务的 id。
if payload.get('job_id'):
return int(payload['job_id'])
job_id = _find_shipping_notice_job_id(task_no)
if job_id:
return job_id
raise ValidationError(f'shipping job enqueue ambiguous: {msg}')
raise ValidationError(f'JobType {job_type} enqueue not implemented in Wave 2')
+33 -16
View File
@@ -2,37 +2,54 @@
backend/app/jobs/runner.py
用途:Worker 主循环 poll → dispatch → ack/fail。
逻辑:worker.py 调用 run_forever(ctx);Wave 2 接入 store 与 registry。
逻辑:worker.py 调用 run_forever(ctx);claim 走 store,执行走 registry handler。
"""
from __future__ import annotations
import time
from typing import TYPE_CHECKING
from app.jobs.context import JobContext
from app.jobs.registry import get_handler
from app.jobs import store
from app.jobs.registry import get_handler
if TYPE_CHECKING:
from app.jobs.context import JobContext
def run_forever(ctx: JobContext, *, poll_interval_seconds: float = 2.0) -> None:
def _resolve_poll_seconds(ctx: JobContext) -> float:
"""按队列配置读取轮询间隔。"""
queues = ctx.extras.get('queues') or ['kb']
if 'shipping' in queues and 'kb' not in queues:
return float(ctx.config.get('SHIPPING_NOTICE_WORKER_POLL_SECONDS', 2))
return float(ctx.config.get('KB_WORKER_POLL_SECONDS', 2))
def run_forever(ctx: JobContext, *, poll_interval_seconds: float | None = None) -> None:
"""
持续轮询并执行任务。
核心逻辑:claim_next → get_handler → handler(ctx, payload) → 更新状态。
核心逻辑:claim_next → get_handler → handler(ctx, payload);异常时 mark_failed。
Args:
ctx: Worker 上下文。
poll_interval_seconds: 无任务时的休眠秒数。
ctx: Worker 上下文(extras.queues 指定消费队列)。
poll_interval_seconds: 无任务时的休眠秒数;默认按队列读 config。
"""
ctx.logger.info('Job runner started (skeleton mode — Wave 2 will enable claim loop)')
queues = ctx.extras.get('queues') or ['kb']
poll = poll_interval_seconds if poll_interval_seconds is not None else _resolve_poll_seconds(ctx)
ctx.logger.info('Job runner started queues=%s poll_seconds=%s', queues, poll)
while True:
try:
job = store.claim_next()
except NotImplementedError:
time.sleep(poll_interval_seconds)
continue
job = store.claim_next(queues=queues)
if not job:
time.sleep(poll_interval_seconds)
time.sleep(poll)
continue
handler = get_handler(job['job_type'])
if not handler:
ctx.logger.error('No handler for job_type=%s', job.get('job_type'))
ctx.logger.error('No handler for job_type=%s job_id=%s', job.get('job_type'), job.get('id'))
store.mark_failed(job['id'], message=f'no handler for {job.get("job_type")}')
continue
handler(ctx, job.get('payload') or {})
try:
handler(ctx, job.get('payload') or {})
except Exception as exc:
ctx.logger.exception('Handler failed job_id=%s', job.get('id'))
store.mark_failed(job['id'], message=str(exc))
+94 -8
View File
@@ -1,20 +1,106 @@
"""
backend/app/jobs/store.py
用途:Job 表 CRUD(claim、update status)。
逻辑:runner 通过 claim_next 获取待执行任务;Wave 2 落地 SQLAlchemy 模型。
用途:Job 认领与状态读写(Wave 2:KbJob 双轨 adapter,无新表)。
依赖:KbJob、各域 queue_service 的 claim/recover 逻辑。
逻辑:runner 通过 claim_next 获取待执行任务;返回归一化 dict 供 handler 分发。
"""
from __future__ import annotations
from typing import Any
from app.jobs.types import QUEUE_KB_JOB_TYPES, JobType, handler_type_for_kb_job
from app.models import KbJob
def claim_next() -> dict[str, Any] | None:
def _normalize_kb_job(job: KbJob) -> dict[str, Any]:
"""
认领下一条待执行 Job(SELECT FOR UPDATE SKIP LOCKED)。
将 KbJob ORM 实例转为 runner/handler 使用的归一化任务 dict。
Args:
job: 已 claim 的 KbJob。
Returns:
job 字典或 None。
Raises:
NotImplementedError: Wave 0 占位。
含 id、job_type(handler 键)、payload、raw_job_type 的字典。
"""
raise NotImplementedError('jobs.store.claim_next is not wired until Wave 2')
handler_type = handler_type_for_kb_job(job.job_type)
if handler_type is None:
raise ValueError(f'unsupported kb job_type={job.job_type!r}')
return {
'id': job.id,
'job_type': handler_type,
'raw_job_type': job.job_type,
'payload': {
'job_id': job.id,
'raw_job_type': job.job_type,
**(job.payload_json or {}),
},
}
def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
"""
认领下一条待执行 Job(SELECT FOR UPDATE SKIP LOCKED,委托各域 queue_service)。
核心逻辑:按 queues 顺序依次尝试 kb / shipping 队列;先 recover 卡死 running 任务。
Args:
queues: worker 消费的队列名,如 ['kb'] 或 ['kb', 'shipping']。
Returns:
归一化 job dict 或 None(无任务)。
"""
queue_names = [q.strip() for q in (queues or ['kb']) if q and q.strip()]
if not queue_names:
queue_names = ['kb']
# [STEP 1] 超时回收(按队列涉及的类型)
allowed_types: set[str] = set()
for name in queue_names:
allowed_types.update(QUEUE_KB_JOB_TYPES.get(name, frozenset()))
if allowed_types & QUEUE_KB_JOB_TYPES['kb']:
from app.services.knowledge_cleaning.queue_service import recover_stale_running_jobs
recover_stale_running_jobs()
if 'shipping_notice_run' in allowed_types:
from app.services.shipping_notice.queue_service import recover_stale_shipping_notice_jobs
recover_stale_shipping_notice_jobs()
# [STEP 2] 按队列优先级 claim
for name in queue_names:
if name == 'kb':
from app.services.knowledge_cleaning.queue_service import claim_next_kb_job
job = claim_next_kb_job()
if job:
return _normalize_kb_job(job)
elif name == 'shipping':
from app.services.shipping_notice.queue_service import claim_next_shipping_notice_job
job = claim_next_shipping_notice_job()
if job:
return _normalize_kb_job(job)
return None
def mark_failed(job_id: int, *, message: str) -> None:
"""
handler 未捕获异常时,将 KbJob 标记为 failed。
Args:
job_id: KbJob 主键。
message: 失败原因(截断至 1000 字符)。
"""
from datetime import datetime
from app import db
job = db.session.get(KbJob, job_id)
if not job or job.status != 'running':
return
now = datetime.utcnow()
job.status = 'failed'
job.error_message = message[:1000]
job.message = message[:500]
job.finished_at = now
job.progress = 100
db.session.commit()
+48 -4
View File
@@ -1,8 +1,8 @@
"""
backend/app/jobs/types.py
用途:Job 类型与状态枚举。
逻辑:handlers 与 queue 通过 JobType 注册;store 持久化 status 字符串。
用途:Job 类型与状态枚举;KbJob.job_type 与 handler JobType 的双向映射。
逻辑:handlers 与 queue 通过 JobType 注册;store 持久化仍走 KbJob 表(Wave 2 双轨)。
"""
from __future__ import annotations
@@ -10,7 +10,7 @@ from enum import StrEnum
class JobType(StrEnum):
"""后台任务类型。"""
"""后台任务类型(handler 注册键)。"""
KB_CLEAN = 'kb_clean'
KB_DIFY_SYNC = 'kb_dify_sync'
@@ -21,10 +21,54 @@ class JobType(StrEnum):
class JobStatus(StrEnum):
"""Job 生命周期状态。"""
"""通用 Job 生命周期状态(Wave 4 通用 Job 表预留;当前 KbJob 仍用 queued/running/success/failed)。"""
PENDING = 'pending'
RUNNING = 'running'
SUCCEEDED = 'succeeded'
FAILED = 'failed'
DEAD = 'dead'
# KbJob.job_type 字符串 → handler JobType
_KB_JOB_TYPE_TO_HANDLER: dict[str, JobType] = {
'clean': JobType.KB_CLEAN,
'path_upload': JobType.KB_CLEAN,
'sync_dify': JobType.KB_DIFY_SYNC,
'shipping_notice_run': JobType.SHIPPING_NOTICE_RUN,
}
# handler JobType → 写入 KbJob 时使用的 job_type
_HANDLER_TO_KB_JOB_TYPE: dict[JobType, str] = {
JobType.KB_CLEAN: 'clean',
JobType.KB_DIFY_SYNC: 'sync_dify',
JobType.SHIPPING_NOTICE_RUN: 'shipping_notice_run',
}
# worker --queues 参数 → 可消费的 KbJob.job_type 集合
QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
'kb': frozenset({'clean', 'path_upload', 'sync_dify'}),
'shipping': frozenset({'shipping_notice_run'}),
}
def handler_type_for_kb_job(kb_job_type: str) -> JobType | None:
"""
将 KbJob.job_type 映射为 handler 注册用的 JobType。
Args:
kb_job_type: KbJob 表 job_type 列值。
Returns:
对应 JobType;未知类型返回 None。
"""
return _KB_JOB_TYPE_TO_HANDLER.get(str(kb_job_type or '').strip())
def kb_job_type_for_handler(job_type: JobType) -> str | None:
"""
将 handler JobType 映射为写入 KbJob 的 job_type 字符串。
Args:
job_type: handler 注册键。
Returns:
KbJob.job_type 值;path_upload 等需调用方显式指定时不经此函数。
"""
return _HANDLER_TO_KB_JOB_TYPE.get(job_type)
@@ -12,10 +12,11 @@ import logging
from datetime import datetime, timedelta
from flask import current_app
from sqlalchemy import exists
from sqlalchemy.exc import OperationalError
from app import db
from app.models import KbDocumentVersion, KbJob
from app.models import KbDocument, KbDocumentVersion, KbJob
logger = logging.getLogger('kb-worker')
_WORD_EXTENSIONS = {'doc', 'docx'}
@@ -144,9 +145,22 @@ def claim_next_kb_job() -> KbJob | None:
now = datetime.utcnow()
try:
has_running_word_job = _has_running_word_clean_job()
missing_version = exists().where(
KbDocumentVersion.id == KbJob.document_version_id,
)
deleted_document = exists().where(
KbDocumentVersion.id == KbJob.document_version_id,
KbDocument.id == KbDocumentVersion.document_id,
KbDocument.is_deleted.is_(True),
)
candidates = (
db.session.query(KbJob)
.filter(KbJob.job_type.in_(('path_upload', 'clean', 'sync_dify')), KbJob.status == 'queued')
.filter(
KbJob.job_type.in_(('path_upload', 'clean', 'sync_dify')),
KbJob.status == 'queued',
(KbJob.document_version_id.is_(None)) | missing_version,
(KbJob.document_version_id.is_(None)) | (~deleted_document),
)
.order_by(KbJob.created_at.asc(), KbJob.id.asc())
.with_for_update(skip_locked=True)
.limit(20)
+61
View File
@@ -0,0 +1,61 @@
"""
tests/jobs/test_store.py
用途:验证 store.claim_next 归一化与空队列行为。
"""
from app.jobs.store import _normalize_kb_job
from app.jobs.types import JobType
from app.models import KbJob
def test_normalize_kb_job_clean(app):
with app.app_context():
job = KbJob(
job_type='clean',
status='running',
progress=1,
payload_json={'document_version_id': 42},
)
normalized = _normalize_kb_job(job)
assert normalized['id'] == job.id
assert normalized['job_type'] == JobType.KB_CLEAN
assert normalized['raw_job_type'] == 'clean'
assert normalized['payload']['job_id'] == job.id
assert normalized['payload']['document_version_id'] == 42
def test_normalize_kb_job_sync_dify(app):
with app.app_context():
job = KbJob(job_type='sync_dify', status='running', progress=1)
normalized = _normalize_kb_job(job)
assert normalized['job_type'] == JobType.KB_DIFY_SYNC
def test_claim_next_returns_none_when_empty(app):
from app.jobs import store
with app.app_context():
assert store.claim_next(queues=['kb']) is None
def test_find_shipping_notice_job_id_matches_task_no(app):
from app import db
from app.jobs.queue import _find_shipping_notice_job_id
with app.app_context():
target = KbJob(
job_type=JobType.SHIPPING_NOTICE_RUN.value,
status='queued',
progress=0,
payload_json={'task_no': 'SHIP-A'},
)
newer_other = KbJob(
job_type=JobType.SHIPPING_NOTICE_RUN.value,
status='queued',
progress=0,
payload_json={'task_no': 'SHIP-B'},
)
db.session.add_all([target, newer_other])
db.session.commit()
assert _find_shipping_notice_job_id('ship-a') == target.id
+20
View File
@@ -0,0 +1,20 @@
"""
tests/jobs/test_types.py
用途:验证 JobType 与 KbJob.job_type 映射。
"""
from app.jobs.types import JobType, handler_type_for_kb_job, kb_job_type_for_handler
def test_handler_type_for_kb_job_mapping():
assert handler_type_for_kb_job('clean') == JobType.KB_CLEAN
assert handler_type_for_kb_job('path_upload') == JobType.KB_CLEAN
assert handler_type_for_kb_job('sync_dify') == JobType.KB_DIFY_SYNC
assert handler_type_for_kb_job('shipping_notice_run') == JobType.SHIPPING_NOTICE_RUN
assert handler_type_for_kb_job('unknown') is None
def test_kb_job_type_for_handler_mapping():
assert kb_job_type_for_handler(JobType.KB_CLEAN) == 'clean'
assert kb_job_type_for_handler(JobType.KB_DIFY_SYNC) == 'sync_dify'
assert kb_job_type_for_handler(JobType.SHIPPING_NOTICE_RUN) == 'shipping_notice_run'
+35
View File
@@ -0,0 +1,35 @@
"""
tests/jobs/test_worker_kb.py
用途:验证 KB worker 兼容入口读取 Flask config 中的并发配置。
"""
def test_main_kb_uses_app_config_concurrency(monkeypatch):
import worker_kb
started: list[str] = []
class FakeApp:
config = {'KB_WORKER_CONCURRENCY': 3}
class FakeProcess:
def __init__(self, *, target, args, name):
self.name = name
self.target = target
self.args = args
def start(self):
started.append(self.name)
def join(self, timeout=None):
return None
monkeypatch.setattr(worker_kb, 'create_app', lambda _config_name: FakeApp())
monkeypatch.setattr(worker_kb, '_resolve_config_name', lambda: 'production')
monkeypatch.setattr(worker_kb.mp, 'Process', FakeProcess)
worker_kb.main_kb()
# 断言多进程数量来自 app.config,而非直接读取环境变量默认值。
assert started == ['kb-worker-1', 'kb-worker-2', 'kb-worker-3']
@@ -0,0 +1,59 @@
"""
tests/test_kb_delete_cancels_jobs.py
用途:验证知识库文档软删时会取消未完成的后台任务。
"""
from app import db
from app.api.knowledge_base import _cancel_active_kb_jobs_for_documents
from app.models import KbDocument, KbDocumentVersion, KbGroup, KbJob
def test_cancel_active_kb_jobs_for_deleted_document(app):
with app.app_context():
group = KbGroup(name='kb-delete-cancel')
document = KbDocument(group=group, title='doc.pdf', status='uploaded')
version = KbDocumentVersion(
document=document,
version_no=1,
status='uploaded',
is_current=True,
source_file_name='doc.pdf',
source_file_path='data/kb/doc.pdf',
)
db.session.add_all([group, document, version])
db.session.flush()
queued = KbJob(
job_type='clean',
status='queued',
group_id=group.id,
document_id=document.id,
document_version_id=version.id,
progress=0,
)
running = KbJob(
job_type='sync_dify',
status='running',
group_id=group.id,
document_id=document.id,
document_version_id=version.id,
progress=20,
)
done = KbJob(
job_type='upload',
status='success',
group_id=group.id,
document_id=document.id,
document_version_id=version.id,
progress=100,
)
db.session.add_all([queued, running, done])
db.session.commit()
cancelled = _cancel_active_kb_jobs_for_documents([document.id], '文档已删除,后台任务已取消')
db.session.commit()
assert cancelled == 2
assert db.session.get(KbJob, queued.id).status == 'cancelled'
assert db.session.get(KbJob, running.id).status == 'cancelled'
assert db.session.get(KbJob, done.id).status == 'success'
+6
View File
@@ -15,6 +15,12 @@ def test_resolve_backend_relative_path_data_prefix():
assert resolved == (root / "data" / "shipping_notice").resolve()
def test_resolve_backend_relative_path_kb_storage_legacy_prefix():
root = backend_dir()
resolved = Path(resolve_backend_relative_path("backend/data/kb"))
assert resolved == (root / "data" / "kb").resolve()
def test_resolve_backend_relative_path_default():
root = backend_dir()
default = root / "data" / "freight_rpa" / "inventory_drop"
+41 -42
View File
@@ -3,86 +3,85 @@ backend/worker.py
用途:统一后台 worker 入口(方案 D)。
依赖:app.create_app、app.jobs.runner、app.jobs.handlers。
逻辑:Wave 2 替代 worker_kb.py 主循环;Compose/Supervisor 可配置 --queues。
逻辑:--queues kb,shipping;Wave 2 经 jobs.runner 统一 poll → dispatch。
"""
from __future__ import annotations
import argparse
import logging
import os
import sys
from app import create_app
from app.jobs.context import JobContext
from app.jobs.runner import run_forever
_LOG_FORMAT = '%(asctime)s %(levelname)s [worker] %(message)s'
def _configure_logging() -> logging.Logger:
logger = logging.getLogger('hxops.worker')
def _configure_logging(label: str = 'main') -> logging.Logger:
logger = logging.getLogger(f'hxops.worker.{label}')
if not logger.handlers:
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter(_LOG_FORMAT))
handler.setFormatter(logging.Formatter(f'{_LOG_FORMAT} [worker={label}]'))
logger.addHandler(handler)
logger.setLevel(logging.INFO)
logger.propagate = False
return logger
def _resolve_processor(queue_name: str):
if queue_name == 'kb':
from app.services.knowledge_cleaning.queue_service import process_next_kb_job
def _resolve_config_name() -> str:
"""
与 worker_kb 对齐的环境配置解析。
FLASK_ENV=test 表示测试部署主机(.env.test),非 pytest;testing 仅 APP_CONFIG 显式指定时使用。
"""
explicit = (os.getenv('APP_CONFIG') or '').strip().lower()
if explicit:
if explicit in ('testing', 'test'):
return 'test'
return explicit
return process_next_kb_job
if queue_name == 'shipping':
from app.services.shipping_notice.queue_service import process_next_shipping_notice_job
return process_next_shipping_notice_job
raise ValueError(f'Unsupported queue: {queue_name}')
env_name = (os.getenv('ENV_NAME') or os.getenv('FLASK_ENV') or 'production').strip().lower()
mapping = {
'dev': 'development',
'development': 'development',
'test': 'production',
'env': 'production',
'prod': 'production',
'production': 'production',
'testing': 'test',
}
return mapping.get(env_name, 'production')
def main(*, queues: list[str] | None = None, config_name: str = 'default') -> None:
def main(*, queues: list[str] | None = None, config_name: str | None = None) -> None:
"""
启动 worker 主循环。
Args:
queues: 消费的队列名列表(Wave 2 按 JobType 过滤)。
config_name: Flask 配置名。
queues: 消费的队列名列表,如 ['kb'] 或 ['kb', 'shipping']。
config_name: Flask 配置名;默认 _resolve_config_name()。
"""
resolved_config = config_name or _resolve_config_name()
logger = _configure_logging()
app = create_app(config_name)
app = create_app(resolved_config)
queue_names = queues or ['kb']
with app.app_context():
import app.jobs.handlers # noqa: F401
import app.jobs.handlers # noqa: F401 — 触发 @register_handler
ctx = JobContext(
config=dict(app.config),
logger=logger,
extras={'queues': queues or ['kb']},
extras={'queues': queue_names},
)
queue_names = ctx.extras['queues']
poll_seconds = 2.0
if 'shipping' in queue_names:
poll_seconds = float(app.config.get('SHIPPING_NOTICE_WORKER_POLL_SECONDS', poll_seconds))
elif 'kb' in queue_names:
poll_seconds = float(app.config.get('KB_WORKER_POLL_SECONDS', poll_seconds))
logger.info('Worker starting queues=%s poll_seconds=%s', queue_names, poll_seconds)
processors = [_resolve_processor(name) for name in queue_names]
import time
while True:
handled = False
for processor in processors:
processed, message = processor()
if processed:
handled = True
logger.info('processed job: %s', message)
if not handled:
time.sleep(poll_seconds)
logger.info('Worker starting config=%s queues=%s', resolved_config, queue_names)
run_forever(ctx)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='HXOPS unified background worker')
parser.add_argument('--queues', default='kb', help='Comma-separated queue names')
parser.add_argument('--config', default='default', dest='config_name')
parser.add_argument('--queues', default='kb', help='Comma-separated queue names (kb, shipping)')
parser.add_argument('--config', default=None, dest='config_name', help='Flask config name (optional)')
args = parser.parse_args()
queue_list = [q.strip() for q in args.queues.split(',') if q.strip()]
main(queues=queue_list, config_name=args.config_name)
+14 -69
View File
@@ -1,90 +1,35 @@
"""
backend/worker_kb.py
文件用途:知识库最小 worker 入口
用途:知识库 worker 部署兼容入口(Compose / Supervisor 沿用此路径)。
逻辑:Wave 2 转调 worker.py,默认 --queues kb;保留多进程并发配置。
"""
from __future__ import annotations
import logging
import multiprocessing as mp
import os
import sys
import time
from app import create_app
from app.services.knowledge_cleaning.queue_service import process_next_clean_job
_LOG_FORMAT = '%(asctime)s %(levelname)s [kb-worker] %(message)s'
_LOG_DATEFMT = '%Y-%m-%d %H:%M:%S'
from worker import _configure_logging, _resolve_config_name, main
def _configure_logging(worker_label: str = 'main') -> logging.Logger:
logger = logging.getLogger(f'kb-worker.{worker_label}')
if logger.handlers:
return logger
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter(f'{_LOG_FORMAT} [worker={worker_label}]', datefmt=_LOG_DATEFMT))
logger.addHandler(handler)
logger.setLevel(logging.INFO)
logger.propagate = False
return logger
def _worker_loop(worker_index: int) -> None:
log = _configure_logging(str(worker_index))
log.info('kb-worker process started index=%s', worker_index)
main(queues=['kb'], config_name=_resolve_config_name())
def _resolve_config_name() -> str:
"""Keep the worker aligned with container/runtime environment selection.
Note: ``FLASK_ENV=test`` / ``ENV_NAME=test`` mean the *test deployment* host
(``.env.test``), not pytest. Use ``production`` so DATABASE_URL from env_file
is honored. ``testing`` is only for in-memory unit tests (``TestingConfig``).
"""
explicit = (os.getenv('APP_CONFIG') or '').strip().lower()
if explicit:
if explicit in ('testing', 'test'):
# Allow explicit pytest-style config only when APP_CONFIG is set;
# never infer this from FLASK_ENV=test on deploy hosts.
return 'test'
return explicit
env_name = (os.getenv('ENV_NAME') or os.getenv('FLASK_ENV') or 'production').strip().lower()
mapping = {
'dev': 'development',
'development': 'development',
# Deploy env files: test/prod hosts use real DB via ProductionConfig
'test': 'production',
'env': 'production',
'prod': 'production',
'production': 'production',
# Pytest-only aliases (not used on deploy unless APP_CONFIG forces it)
'testing': 'test',
}
return mapping.get(env_name, 'production')
def _worker_loop(worker_index: int):
worker_label = str(worker_index)
log = _configure_logging(worker_label)
app = create_app(_resolve_config_name())
poll_seconds = float(app.config.get('KB_WORKER_POLL_SECONDS', 2))
with app.app_context():
log.info('started, poll_seconds=%s', poll_seconds)
while True:
processed, message = process_next_clean_job()
if not processed:
time.sleep(poll_seconds)
continue
log.info('processed job: %s', message)
def main():
def main_kb() -> None:
"""启动 KB worker;KB_WORKER_CONCURRENCY>1 时 fork 多进程。"""
bootstrap_app = create_app(_resolve_config_name())
concurrency = max(int(bootstrap_app.config.get('KB_WORKER_CONCURRENCY', 1) or 1), 1)
if concurrency == 1:
_worker_loop(1)
main(queues=['kb'], config_name=_resolve_config_name())
return
log = _configure_logging('master')
log.info('starting %s worker processes', concurrency)
log.info('starting %s kb worker processes', concurrency)
workers: list[mp.Process] = []
for index in range(concurrency):
proc = mp.Process(target=_worker_loop, args=(index + 1,), name=f'kb-worker-{index + 1}')
@@ -95,7 +40,7 @@ def main():
for proc in workers:
proc.join()
except KeyboardInterrupt:
log.info('stopping worker pool')
log.info('stopping kb worker pool')
for proc in workers:
if proc.is_alive():
proc.terminate()
@@ -105,4 +50,4 @@ def main():
if __name__ == '__main__':
mp.freeze_support()
main()
main_kb()
@@ -35,6 +35,12 @@ export const workspaceRoutes: RouteRecordRaw[] = [
component: () => import('@/features/workspace/pages/KnowledgeBasePage.vue'),
meta: { title: '知识库' },
},
{
path: 'knowledge-base/groups/:groupId',
name: 'workspace-knowledge-base-group',
component: () => import('@/features/workspace/pages/KnowledgeBasePage.vue'),
meta: { title: '知识库' },
},
{
path: 'schedule-runs',
name: 'workspace-schedule-runs',
@@ -77,9 +77,9 @@ export function createKbWorkspaceState(options: CreateKbWorkspaceStateOptions =
const failureModalPage = ref(1);
const retryingFailureKey = ref('');
const documentStageFilter = ref<'all' | 'upload' | 'clean' | 'sync'>('all');
const documentStageFilter = ref<'all' | 'pending_clean' | 'cleaning' | 'pending_sync' | 'failed'>('all');
const documentListPage = ref(1);
const documentListPageSize = ref(20);
const documentListPageSize = ref(10);
const documentKeyword = ref('');
const batchSubmitting = ref(false);
const selectedDocumentIds = ref<number[]>([]);
@@ -98,17 +98,20 @@ export function useKbWorkspaceComputed(state: KbWorkspaceState) {
const matchesDocumentStageFilter = (
doc: KbDocumentItem,
filter: 'all' | 'upload' | 'clean' | 'sync',
filter: 'all' | 'pending_clean' | 'cleaning' | 'pending_sync' | 'failed',
) => {
const workflow = resolveWorkflowState(doc);
if (filter === 'all') return true;
if (filter === 'upload') {
return workflow.upload.code !== 'success';
if (filter === 'pending_clean') {
return workflow.clean.code === 'pending';
}
if (filter === 'clean') {
return ['pending', 'queued', 'running', 'failed'].includes(workflow.clean.code);
if (filter === 'cleaning') {
return ['queued', 'running'].includes(workflow.clean.code);
}
return ['pending', 'running', 'failed'].includes(workflow.sync.code);
if (filter === 'pending_sync') {
return workflow.sync.code === 'pending';
}
return [workflow.upload.code, workflow.clean.code, workflow.sync.code].includes('failed');
};
const matchesDocumentKeyword = (doc: KbDocumentItem, keyword: string) => {
@@ -125,11 +128,12 @@ export function useKbWorkspaceComputed(state: KbWorkspaceState) {
};
const stageFilterTabs = computed(() => {
const filters: Array<{ key: 'all' | 'upload' | 'clean' | 'sync'; label: string }> = [
const filters: Array<{ key: 'all' | 'pending_clean' | 'cleaning' | 'pending_sync' | 'failed'; label: string }> = [
{ 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') },
{ key: 'pending_clean', label: t('kbWorkspace.filters.pendingClean') },
{ key: 'cleaning', label: t('kbWorkspace.filters.cleaning') },
{ key: 'pending_sync', label: t('kbWorkspace.filters.pendingSync') },
{ key: 'failed', label: t('kbWorkspace.filters.failed') },
];
return filters.map((item) => ({
...item,
@@ -46,6 +46,7 @@ export function useKbWorkspaceData(
selectedDocumentIds,
showPathUploadDetails,
selectedPathUploadHistoryJobId,
router,
} = state;
const { t } = state;
@@ -189,6 +190,9 @@ export function useKbWorkspaceData(
};
const openGroupDetail = async (groupId: number) => {
if (viewMode.value === 'group_overview') {
await router.push({ name: 'workspace-knowledge-base-group', params: { groupId } });
}
selectedGroupId.value = groupId;
viewMode.value = 'group_detail';
feedback.value = '';
@@ -197,6 +201,9 @@ export function useKbWorkspaceData(
};
const backToGroupOverview = () => {
if (viewMode.value === 'group_detail') {
void router.push({ name: 'workspace-knowledge-base' });
}
viewMode.value = 'group_overview';
selectedGroupId.value = null;
documents.value = [];
@@ -2,7 +2,7 @@
* features/kb/composables/useKbWorkspace.ts
* 知识库作业面编排入口:组合 state / computed / data / pathUpload / documents / modals。
*/
import { onMounted, onUnmounted, reactive, watch } from 'vue';
import { computed as vueComputed, onMounted, onUnmounted, reactive, watch } from 'vue';
import {
DOCUMENT_PAGE_SIZE_OPTIONS,
FAILURE_PAGE_SIZE,
@@ -76,6 +76,29 @@ export function useKbWorkspace(options: UseKbWorkspaceOptions = {}) {
} = computed;
const { applyPathUploadJob } = pathUpload;
const routeGroupId = vueComputed(() => {
const raw = state.router.currentRoute.value.params.groupId;
const value = Array.isArray(raw) ? raw[0] : raw;
const parsed = Number(value);
return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
});
const syncViewModeFromRoute = () => {
const groupId = routeGroupId.value;
if (groupId) {
state.viewMode.value = 'group_detail';
if (selectedGroupId.value !== groupId) {
selectedGroupId.value = groupId;
}
return;
}
if (state.embedded) {
state.viewMode.value = 'group_overview';
if (selectedGroupId.value !== null) {
selectedGroupId.value = null;
}
}
};
// --- 筛选/分页/路径上传历史联动 ---
watch(selectedGroupId, (groupId) => {
@@ -90,6 +113,10 @@ export function useKbWorkspace(options: UseKbWorkspaceOptions = {}) {
applyPathUploadJob(latestPathUploadJob.value);
});
watch(routeGroupId, () => {
syncViewModeFromRoute();
});
watch(documentStageFilter, () => {
documentListPage.value = 1;
});
@@ -117,6 +144,7 @@ export function useKbWorkspace(options: UseKbWorkspaceOptions = {}) {
});
onMounted(async () => {
syncViewModeFromRoute();
await Promise.all([data.loadGroups(), data.loadJobs()]);
if (state.viewMode.value === 'group_detail') {
await data.loadDocuments(selectedGroupId.value);
@@ -52,7 +52,7 @@ export const FAILURE_PAGE_SIZE = 15;
export const PATH_UPLOAD_BATCH_SIZE = 30;
export const PATH_UPLOAD_BATCH_INTERVAL_MS = 500;
export const PATH_UPLOAD_CONCURRENCY = 3;
export const DOCUMENT_PAGE_SIZE_OPTIONS = [20, 50, 100, 200] as const;
export const DOCUMENT_PAGE_SIZE_OPTIONS = [10, 20, 50, 100] as const;
/** 未开始阶段的徽标样式,与 getStatusBadgeClass 默认一致 */
export const IDLE_BADGE_CLASS = 'border-default bg-surface-soft text-muted';
+175 -207
View File
@@ -46,11 +46,12 @@ const kb = useKbWorkspace({ embedded: props.embedded });
</div>
<div class="flex flex-wrap items-center gap-3">
<button
v-if="kb.viewMode !== 'group_overview'"
@click="kb.refreshCurrentView"
class="btn-secondary"
>
<RefreshCw class="h-4 w-4" />
{{ kb.viewMode === 'group_overview' ? kb.t('kbWorkspace.actions.refreshGroups') : kb.t('kbWorkspace.actions.refreshDocuments') }}
{{ kb.t('kbWorkspace.actions.refreshDocuments') }}
</button>
<button
v-if="kb.viewMode === 'group_overview'"
@@ -66,9 +67,8 @@ const kb = useKbWorkspace({ embedded: props.embedded });
<template v-if="kb.viewMode === 'group_overview'">
<section class="kb-ws-section">
<div class="mb-4 flex items-center justify-between">
<div class="mb-4 flex items-center">
<h2 class="text-lg font-semibold text-primary">{{ kb.t('kbWorkspace.overview.title') }}</h2>
<span class="text-xs text-muted">`/api/kb/groups`</span>
</div>
<div v-if="kb.isLoading" class="py-10 text-center text-sm text-muted">{{ kb.t('kbWorkspace.overview.loadingGroups') }}</div>
<div v-else-if="kb.groups.length === 0" class="kb-ws-empty py-10 text-center text-sm text-muted">
@@ -101,29 +101,6 @@ const kb = useKbWorkspace({ embedded: props.embedded });
</template>
<template v-else>
<div class="kb-ws-stat-grid">
<div
v-for="item in kb.groupSummaryItems"
:key="item.label"
class="kb-ws-stat-tile "
:class="[
item.wide ? 'col-span-2 xl:col-span-2' : '',
item.clickable
? 'cursor-pointer hover:bg-rose-50 hover:bg-rose-50'
: '',
]"
@click="item.clickable && item.failureType ? kb.openFailureModal(item.failureType) : undefined"
>
<div
class="text-base font-semibold text-primary break-words"
:style="item.wide ? '-webkit-line-clamp: 2; -webkit-box-orient: vertical; display: -webkit-box; overflow: hidden;' : undefined"
>
{{ item.value }}
</div>
<div class="mt-1 text-xs text-muted">{{ item.label }}</div>
</div>
</div>
<div class="grid grid-cols-1 gap-6 lg:grid-cols-[320px_minmax(0,1fr)]">
<input
:ref="(el) => { kb.fileInputRef = el as HTMLInputElement | null }"
type="file"
@@ -140,54 +117,49 @@ const kb = useKbWorkspace({ embedded: props.embedded });
class="hidden"
@change="kb.handlePathFilesSelected"
/>
<section class="kb-ws-section">
<div class="mb-4 flex items-center justify-between">
<h2 class="text-lg font-semibold text-primary">{{ kb.t('kbWorkspace.sidebar.groupsTitle') }}</h2>
</div>
<div v-if="kb.isLoading" class="py-10 text-center text-sm text-muted">{{ kb.t('kbWorkspace.sidebar.loadingGroups') }}</div>
<div v-else-if="kb.groups.length === 0" class="rounded-2xl border border-dashed border-default px-4 py-8 text-center text-sm text-muted ">
{{ kb.t('kbWorkspace.sidebar.emptyGroups') }}
</div>
<div v-else class="space-y-3">
<button
v-for="group in kb.groups"
:key="group.id"
@click="kb.selectedGroupId = group.id"
class="kb-ws-group-list-btn"
:class="{ 'kb-ws-group-list-btn--active': kb.selectedGroupId === group.id }"
>
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
<div class="truncate font-semibold">{{ group.name }}</div>
<div class="mt-1 text-sm opacity-80">{{ group.description || kb.t('kbWorkspace.sidebar.noDescription') }}</div>
</div>
<span class="rounded-full bg-surface/70 px-2 py-1 text-xs ">
{{ group.document_count ?? 0 }}
</span>
</div>
</button>
</div>
</section>
<section class="space-y-6">
<div class="kb-ws-section">
<div class="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
<div class="min-w-0">
<div class="text-xs font-medium text-muted">{{ kb.t('kbWorkspace.summary.currentGroup') }}</div>
<h2 class="mt-1 text-2xl font-bold text-primary break-words">{{ kb.selectedGroup?.name || '--' }}</h2>
<p class="mt-2 max-w-3xl text-sm text-muted">
{{ kb.selectedGroup?.description || kb.t('kbWorkspace.overview.noDescription') }}
</p>
</div>
<div class="grid min-w-full grid-cols-2 gap-2 sm:grid-cols-5 lg:min-w-[520px]">
<button
v-for="item in kb.groupSummaryItems.filter((summary) => !summary.wide)"
:key="item.label"
type="button"
class="rounded-2xl border border-default bg-surface-soft px-3 py-3 text-left transition-colors"
:class="item.clickable ? 'hover:border-rose-200 hover:bg-rose-50' : ''"
@click="item.clickable && item.failureType ? kb.openFailureModal(item.failureType) : undefined"
>
<div class="text-lg font-semibold text-primary">{{ item.value }}</div>
<div class="mt-1 text-xs text-muted">{{ item.label }}</div>
</button>
</div>
</div>
</div>
<div class="kb-ws-section">
<div class="mb-4 space-y-3">
<div class="flex flex-wrap items-center justify-between gap-3">
<div class="flex items-center gap-2">
<h2 class="text-lg font-semibold text-primary">{{ kb.t('kbWorkspace.documents.title') }}</h2>
<div class="group relative">
<button
type="button"
class="inline-flex h-6 w-6 items-center justify-center rounded-full border border-default text-muted transition-colors hover:border-brand-300 hover:text-brand-500 hover:border-brand-300 hover:text-brand-600"
>
<Info class="h-3.5 w-3.5" />
</button>
<div class="pointer-events-none absolute left-0 top-8 z-10 hidden w-80 rounded-2xl border border-default bg-surface px-4 py-3 text-sm text-muted shadow-xl group-hover:block">
{{ kb.t('kbWorkspace.documents.infoTip') }}
<h2 class="text-lg font-semibold text-primary">{{ kb.t('kbWorkspace.documents.title') }}</h2>
<div class="group relative">
<button
type="button"
class="inline-flex h-6 w-6 items-center justify-center rounded-full border border-default text-muted transition-colors hover:border-brand-300 hover:text-brand-600"
>
<Info class="h-3.5 w-3.5" />
</button>
<div class="pointer-events-none absolute left-0 top-8 z-10 hidden w-80 rounded-2xl border border-default bg-surface px-4 py-3 text-sm text-muted shadow-xl group-hover:block">
{{ kb.t('kbWorkspace.documents.infoTip') }}
</div>
</div>
</div>
</div>
<div class="flex flex-wrap items-center gap-3">
<button
v-if="kb.selectedGroupId"
@@ -209,62 +181,6 @@ const kb = useKbWorkspace({ embedded: props.embedded });
</button>
</div>
</div>
<div class="flex flex-wrap items-center gap-3">
<button
v-if="kb.isKbAdmin && kb.selectedGroupId"
@click="kb.handleBatchClean"
:disabled="kb.batchSubmitting || kb.selectedDocuments.length === 0"
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"
>
<RefreshCw class="h-4 w-4" />
{{ kb.batchActionLabel('clean', kb.batchSubmitting, kb.selectedDocuments.length) }}
</button>
<button
v-if="kb.isKbAdmin && kb.selectedGroupId"
@click="kb.handleBatchSync"
:disabled="kb.batchSubmitting || kb.selectedDocuments.length === 0"
class="inline-flex items-center gap-2 rounded-2xl border border-emerald-200 px-4 py-2.5 text-sm font-medium text-emerald-700 transition-colors hover:bg-emerald-50 disabled:cursor-not-allowed disabled:opacity-60 border-emerald-200"
>
<RefreshCw class="h-4 w-4" />
{{ kb.batchActionLabel('sync', kb.batchSubmitting, kb.selectedDocuments.length) }}
</button>
<button
v-if="kb.selectedGroupId"
@click="kb.handleBatchDelete"
:disabled="kb.batchSubmitting || kb.selectedDocuments.length === 0"
class="inline-flex items-center gap-2 rounded-2xl border border-rose-200 px-4 py-2.5 text-sm font-medium text-rose-600 transition-colors hover:bg-rose-50 disabled:cursor-not-allowed disabled:opacity-60 border-rose-200 hover:bg-rose-50"
>
<Trash2 class="h-4 w-4" />
{{ kb.batchActionLabel('delete', kb.batchSubmitting, kb.selectedDocuments.length) }}
</button>
<button
v-if="kb.selectedGroupId"
@click="kb.openPathUploadHistoryModal()"
class="btn-secondary"
>
<FileText class="h-4 w-4" />
{{ kb.t('kbWorkspace.documents.historyBatches') }}
</button>
</div>
<div v-if="kb.selectedGroupId" class="flex flex-wrap items-center gap-3">
<label class="relative w-full max-w-md">
<Search class="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted" />
<input
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="kb.t('kbWorkspace.documents.searchPlaceholder')"
/>
</label>
<button
v-if="kb.documentKeyword"
type="button"
@click="kb.documentKeyword = ''"
class="inline-flex items-center rounded-xl border border-default px-3 py-2 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft"
>
{{ kb.t('kbWorkspace.documents.clearSearch') }}
</button>
</div>
</div>
<p
@@ -373,41 +289,99 @@ const kb = useKbWorkspace({ embedded: props.embedded });
</div>
<div
v-if="kb.selectedGroupId"
class="mb-4 flex flex-wrap items-center justify-between gap-3 rounded-2xl bg-surface-soft px-4 py-3 "
>
<div class="flex flex-wrap items-center gap-2">
<button
@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.t('kbWorkspace.pathUpload.deselectAllFiltered') : kb.t('kbWorkspace.pathUpload.selectAllFiltered') }}
</button>
<button
v-for="tab in kb.stageFilterTabs"
:key="tab.key"
@click="kb.documentStageFilter = tab.key"
class="inline-flex items-center gap-2 rounded-full border px-4 py-2 text-sm font-medium transition-colors"
:class="kb.documentStageFilter === tab.key
? 'border-brand-200 bg-brand-50 text-brand-700 border-brand-200 '
: 'border-default bg-surface text-secondary hover:bg-surface-soft hover-surface-soft'"
>
<span>{{ tab.label }}</span>
<span class="rounded-full bg-surface-soft px-2 py-0.5 text-xs ">{{ tab.count }}</span>
</button>
</div>
<div class="flex flex-wrap items-center gap-3 text-sm text-muted">
<label class="inline-flex items-center gap-2">
<span>{{ kb.t('kbWorkspace.common.perPage') }}</span>
<select
v-model.number="kb.documentListPageSize"
class="rounded-xl border border-default bg-surface px-3 py-1.5 text-sm text-secondary outline-none transition-colors focus:border-brand-300"
class="mb-4 space-y-3 rounded-2xl bg-surface-soft px-4 py-3"
>
<div class="flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between">
<div class="flex flex-wrap items-center gap-2">
<button
v-for="tab in kb.stageFilterTabs"
:key="tab.key"
@click="kb.documentStageFilter = tab.key"
class="inline-flex items-center gap-2 rounded-full border px-4 py-2 text-sm font-medium transition-colors"
:class="kb.documentStageFilter === tab.key
? 'border-brand-200 bg-brand-50 text-brand-700'
: 'border-default bg-surface text-secondary hover:bg-surface-soft'"
>
<option v-for="size in kb.DOCUMENT_PAGE_SIZE_OPTIONS" :key="size" :value="size">{{ size }}</option>
</select>
<span>{{ kb.t('kbWorkspace.common.countUnit') }}</span>
</label>
<span>{{ kb.t('kbWorkspace.documents.selectedCount', { selected: kb.selectedDocuments.length, total: kb.filteredDocuments.length }) }}</span>
<span v-if="kb.filteredDocuments.length > 0">{{ kb.t('kbWorkspace.documents.showingRange', { start: kb.pagedDocumentRange.start, end: kb.pagedDocumentRange.end }) }}</span>
<span>{{ tab.label }}</span>
<span class="rounded-full bg-surface-soft px-2 py-0.5 text-xs">{{ tab.count }}</span>
</button>
</div>
<div class="flex flex-wrap items-center gap-3 text-sm text-muted">
<label class="relative min-w-[260px] flex-1 xl:w-80 xl:flex-none">
<Search class="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted" />
<input
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="kb.t('kbWorkspace.documents.searchPlaceholder')"
/>
</label>
<button
v-if="kb.documentKeyword"
type="button"
@click="kb.documentKeyword = ''"
class="inline-flex items-center rounded-xl border border-default bg-surface px-3 py-2 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft"
>
{{ kb.t('kbWorkspace.documents.clearSearch') }}
</button>
<label class="inline-flex items-center gap-2">
<span>{{ kb.t('kbWorkspace.common.perPage') }}</span>
<select
v-model.number="kb.documentListPageSize"
class="rounded-xl border border-default bg-surface px-3 py-1.5 text-sm text-secondary outline-none transition-colors focus:border-brand-300"
>
<option v-for="size in kb.DOCUMENT_PAGE_SIZE_OPTIONS" :key="size" :value="size">{{ size }}</option>
</select>
<span>{{ kb.t('kbWorkspace.common.countUnit') }}</span>
</label>
</div>
</div>
<div class="flex flex-col gap-3 border-t border-default pt-3 lg:flex-row lg:items-center lg:justify-between">
<div class="flex flex-wrap items-center gap-2">
<button
@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"
>
{{ kb.isAllFilteredSelected ? kb.t('kbWorkspace.pathUpload.deselectAllFiltered') : kb.t('kbWorkspace.pathUpload.selectAllFiltered') }}
</button>
<button
v-if="kb.isKbAdmin"
@click="kb.handleBatchClean"
:disabled="kb.batchSubmitting || kb.selectedDocuments.length === 0"
class="inline-flex items-center gap-2 rounded-full border border-amber-200 bg-surface px-4 py-2 text-sm font-medium text-amber-700 transition-colors hover:bg-amber-50 disabled:cursor-not-allowed disabled:opacity-60"
>
<RefreshCw class="h-4 w-4" />
{{ kb.batchActionLabel('clean', kb.batchSubmitting, kb.selectedDocuments.length) }}
</button>
<button
v-if="kb.isKbAdmin"
@click="kb.handleBatchSync"
:disabled="kb.batchSubmitting || kb.selectedDocuments.length === 0"
class="inline-flex items-center gap-2 rounded-full border border-emerald-200 bg-surface px-4 py-2 text-sm font-medium text-emerald-700 transition-colors hover:bg-emerald-50 disabled:cursor-not-allowed disabled:opacity-60"
>
<RefreshCw class="h-4 w-4" />
{{ kb.batchActionLabel('sync', kb.batchSubmitting, kb.selectedDocuments.length) }}
</button>
<button
@click="kb.handleBatchDelete"
:disabled="kb.batchSubmitting || kb.selectedDocuments.length === 0"
class="inline-flex items-center gap-2 rounded-full border border-rose-200 bg-surface px-4 py-2 text-sm font-medium text-rose-600 transition-colors hover:bg-rose-50 disabled:cursor-not-allowed disabled:opacity-60"
>
<Trash2 class="h-4 w-4" />
{{ kb.batchActionLabel('delete', kb.batchSubmitting, kb.selectedDocuments.length) }}
</button>
<button
@click="kb.openPathUploadHistoryModal()"
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"
>
<FileText class="h-4 w-4" />
{{ kb.t('kbWorkspace.documents.historyBatches') }}
</button>
</div>
<div class="flex flex-wrap items-center gap-3 text-sm text-muted">
<span>{{ kb.t('kbWorkspace.documents.selectedCount', { selected: kb.selectedDocuments.length, total: kb.filteredDocuments.length }) }}</span>
<span v-if="kb.filteredDocuments.length > 0">{{ kb.t('kbWorkspace.documents.showingRange', { start: kb.pagedDocumentRange.start, end: kb.pagedDocumentRange.end }) }}</span>
</div>
</div>
</div>
@@ -424,13 +398,13 @@ const kb = useKbWorkspace({ embedded: props.embedded });
<div
v-for="doc in kb.pagedFilteredDocuments"
:key="doc.id"
class="rounded-2xl border px-4 py-4 transition-colors"
class="rounded-2xl border px-4 py-3 transition-colors"
:class="kb.selectedDocumentId === doc.id
? 'border-brand-200 bg-brand-50/50 border-brand-200'
: 'border-default'"
>
<div class="flex items-start justify-between gap-3">
<div class="flex min-w-0 flex-1 gap-3">
<div class="grid gap-3 xl:grid-cols-[minmax(0,1.3fr)_minmax(360px,0.9fr)_auto] xl:items-center">
<div class="flex min-w-0 gap-3">
<label class="mt-1 inline-flex shrink-0 cursor-pointer items-center">
<input
type="checkbox"
@@ -440,35 +414,53 @@ const kb = useKbWorkspace({ embedded: props.embedded });
/>
</label>
<div class="min-w-0 flex-1">
<button
@click="kb.openMarkdownEditor(doc)"
class="block max-w-full truncate text-left font-semibold text-primary transition-colors hover:text-brand-600 hover:text-brand-600"
>
{{ kb.getDocumentDisplayTitle(doc) }}
</button>
<button
type="button"
@click="kb.openSourceInfo(doc)"
class="mt-1 block max-w-full text-left text-sm text-muted transition-colors hover:text-brand-600 hover:text-brand-600"
>
{{ kb.getDocumentDisplayDescription(doc) }}
</button>
<div class="mt-2 text-xs text-muted">
<span>{{ kb.t('kbWorkspace.documents.versionCount', { count: doc.version_count ?? 0 }) }}</span>
<span v-if="doc.latest_version">
<span>{{ kb.t('kbWorkspace.documents.currentVersion', { version: doc.latest_version.version_no }) }}</span>
<button
@click="kb.openMarkdownEditor(doc)"
class="block max-w-full truncate text-left font-semibold text-primary transition-colors hover:text-brand-600 hover:text-brand-600"
>
{{ kb.getDocumentDisplayTitle(doc) }}
</button>
<button
type="button"
@click="kb.openSourceInfo(doc)"
class="mt-1 block max-w-full truncate text-left text-sm text-muted transition-colors hover:text-brand-600 hover:text-brand-600"
>
{{ kb.getDocumentDisplayDescription(doc) }}
</button>
<div class="mt-2 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted">
<span>{{ kb.t('kbWorkspace.documents.versionCount', { count: doc.version_count ?? 0 }) }}</span>
<span v-if="doc.latest_version">{{ kb.t('kbWorkspace.documents.currentVersion', { version: doc.latest_version.version_no }) }}</span>
<button
v-if="doc.latest_version"
type="button"
@click="kb.openSourceInfo(doc)"
class="inline text-xs text-muted underline-offset-2 transition-colors hover:text-brand-600 hover:underline hover:text-brand-600"
>
class="max-w-full truncate text-xs text-muted underline-offset-2 transition-colors hover:text-brand-600 hover:underline hover:text-brand-600"
>
{{ doc.latest_version.source_file_name }}
</button>
</span>
</div>
<span>{{ kb.t('kbWorkspace.documents.updatedAt', { time: kb.formatDateTime(doc.updated_at) }) }}</span>
</div>
<div
v-if="kb.getDocumentWorkflowState(doc).primaryError"
class="mt-1 max-w-xl text-xs text-rose-500"
>
{{ kb.t('kbWorkspace.common.failureReason', { reason: kb.getDocumentWorkflowState(doc).primaryError }) }}
</div>
</div>
</div>
<div class="flex items-center gap-2">
<div class="flex flex-wrap items-center gap-2 xl:justify-end">
<div
v-for="badge in kb.getWorkflowBadges(doc)"
:key="`${doc.id}-${badge.label}`"
class="inline-flex items-center rounded-full border px-3 py-1 text-xs font-semibold"
:class="badge.className"
>
{{ badge.label }}:{{ badge.value }}
</div>
</div>
<div class="flex flex-wrap items-center gap-2 xl:justify-end">
<button
@click="kb.openDocumentDetail(doc.id)"
class="inline-flex items-center gap-1 rounded-xl border border-violet-200 px-3 py-2 text-xs font-medium text-violet-700 transition-colors hover:bg-violet-50"
@@ -501,32 +493,9 @@ const kb = useKbWorkspace({ embedded: props.embedded });
</button>
</div>
</div>
<div class="mt-4 flex items-end justify-between gap-3 border-t border-default pt-3 ">
<div class="space-y-1">
<div class="text-xs text-muted">
{{ kb.t('kbWorkspace.documents.updatedAt', { time: kb.formatDateTime(doc.updated_at) }) }}
</div>
<div
v-if="kb.getDocumentWorkflowState(doc).primaryError"
class="max-w-xl text-xs text-rose-500"
>
{{ kb.t('kbWorkspace.common.failureReason', { reason: kb.getDocumentWorkflowState(doc).primaryError }) }}
</div>
</div>
<div class="flex flex-wrap items-center justify-end gap-2">
<div
v-for="badge in kb.getWorkflowBadges(doc)"
:key="`${doc.id}-${badge.label}`"
class="inline-flex items-center rounded-full border px-3 py-1 text-sm font-semibold"
:class="badge.className"
>
{{ badge.label }}:{{ badge.value }}
</div>
</div>
</div>
</div>
<div
v-if="kb.filteredDocuments.length > kb.documentListPageSize"
v-if="kb.filteredDocuments.length > 0"
class="flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-default px-4 py-3 "
>
<div class="text-sm text-muted">
@@ -552,7 +521,6 @@ const kb = useKbWorkspace({ embedded: props.embedded });
</div>
</div>
</section>
</div>
</template>
</div>
</div>
@@ -6,11 +6,15 @@
import { inject } from 'vue';
import { useRoute } from 'vue-router';
import {
LayoutGrid, Bot, FileText, User, LogOut, Edit, Megaphone, Clock, Package,
LayoutGrid, Bot, FileText, User, LogOut, Edit, Megaphone, Clock, Package, PanelLeftClose, PanelLeftOpen,
} from 'lucide-vue-next';
import { WORKSPACE_PATHS } from '../constants/routes';
import { WORKSPACE_KEY } from '../composables/workspace.context';
defineProps<{
collapsed?: boolean;
}>();
const ws = inject(WORKSPACE_KEY)! as any;
const route = useRoute();
@@ -30,54 +34,97 @@ function isActive(match: readonly string[]) {
<template>
<aside class="lg:sticky lg:top-0 lg:h-screen">
<div class="flex h-full flex-col border-r border-default bg-surface px-5 py-6 shadow-sm">
<div class="border-b border-subtle pb-6">
<div class="flex items-center gap-3">
<div class="flex h-12 w-12 items-center justify-center rounded-2xl bg-gradient-to-br from-brand-500 via-brand-600 to-purple-600 text-white shadow-lg shadow-brand-500/25">
<Bot class="h-6 w-6" />
<div
class="flex h-full flex-col border-r border-default bg-surface shadow-sm transition-all duration-200"
:class="collapsed ? 'px-3 py-4' : 'px-4 py-4'"
>
<template v-if="collapsed">
<button
type="button"
class="mb-6 inline-flex h-10 w-full items-center justify-center rounded-xl text-muted transition-colors hover:bg-surface-soft hover:text-secondary"
:title="$t('workspace.expandSidebar')"
@click="ws.toggleSidebarCollapsed"
>
<PanelLeftOpen class="h-5 w-5" />
</button>
</template>
<div class="border-b border-subtle pb-4">
<div class="flex items-center gap-3" :class="collapsed ? 'justify-center' : ''">
<div class="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-sm font-bold text-white shadow-sm shadow-brand-500/25">
AI
</div>
<div class="min-w-0">
<div class="text-2xl font-extrabold tracking-tight text-primary">{{ $t('workspace.brandTitle') }}</div>
<div class="truncate text-xs font-medium text-muted">
<div v-if="!collapsed" class="min-w-0 flex-1">
<div class="truncate text-lg font-bold text-primary">{{ $t('workspace.brandTitle') }}</div>
<div class="mt-1 truncate text-[11px] text-muted">
{{ ws.currentUser?.username }} / {{ ws.currentUser?.role }}
</div>
</div>
<button
v-if="!collapsed"
type="button"
class="ml-2 inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-xl text-muted transition-colors hover:bg-surface-soft hover:text-secondary"
:title="$t('workspace.collapseSidebar')"
@click="ws.toggleSidebarCollapsed"
>
<PanelLeftClose class="h-5 w-5" />
</button>
</div>
</div>
<div class="flex-1 py-6">
<div class="flex-1 py-4">
<nav class="space-y-2">
<RouterLink
v-for="item in linkItems"
:key="item.path"
:to="item.path"
class="ws-nav-btn"
:class="{ 'ws-nav-btn--active': isActive(item.match) }"
:class="[
{ 'ws-nav-btn--active': isActive(item.match) },
collapsed ? 'justify-center px-0' : '',
]"
:title="$t(item.labelKey)"
>
<component :is="item.icon" class="h-4 w-4" />
<span>{{ $t(item.labelKey) }}</span>
<component :is="item.icon" class="h-[18px] w-[18px]" />
<span v-if="!collapsed">{{ $t(item.labelKey) }}</span>
</RouterLink>
<button
type="button"
class="ws-nav-btn w-full"
:class="{ 'ws-nav-btn--active': isActive(['workspace-knowledge-base']) }"
:class="[
{ 'ws-nav-btn--active': isActive(['workspace-knowledge-base', 'workspace-knowledge-base-group']) },
collapsed ? 'justify-center px-0' : '',
]"
:title="$t('workspace.nav.knowledgeBase')"
@click="ws.navigateToKnowledgeBase"
>
<FileText class="h-4 w-4" />
<span>{{ $t('workspace.nav.knowledgeBase') }}</span>
<FileText class="h-[18px] w-[18px]" />
<span v-if="!collapsed">{{ $t('workspace.nav.knowledgeBase') }}</span>
</button>
</nav>
</div>
<div class="border-t border-subtle pt-6">
<div class="border-t border-subtle pt-4">
<div class="space-y-2">
<button type="button" @click="ws.navigateToGeneralChat" class="ws-nav-btn">
<Bot class="h-4 w-4" />
<span>{{ $t('workspace.nav.backToChat') }}</span>
<button
type="button"
@click="ws.navigateToGeneralChat"
class="ws-nav-btn"
:class="collapsed ? 'justify-center px-0' : ''"
:title="$t('workspace.nav.backToChat')"
>
<Bot class="h-[18px] w-[18px]" />
<span v-if="!collapsed">{{ $t('workspace.nav.backToChat') }}</span>
</button>
<button type="button" @click="ws.handleLogout" class="ws-nav-btn ws-nav-btn--danger">
<LogOut class="h-4 w-4" />
<span>{{ $t('workspace.nav.logout') }}</span>
<button
type="button"
@click="ws.handleLogout"
class="ws-nav-btn ws-nav-btn--danger"
:class="collapsed ? 'justify-center px-0' : ''"
:title="$t('workspace.nav.logout')"
>
<LogOut class="h-[18px] w-[18px]" />
<span v-if="!collapsed">{{ $t('workspace.nav.logout') }}</span>
</button>
</div>
</div>
@@ -30,6 +30,7 @@ export function useWorkspace() {
const deps = { t, locale, msg, router, route, setThemePreference, appliedTheme };
const isLoading = ref(true);
const currentUser = ref<WorkspaceUser | null>(null);
const isSidebarCollapsed = ref(false);
const sessionRef: { handleLogout?: () => void } = {};
const home = useWorkspaceHome(deps, {
@@ -65,6 +66,7 @@ export function useWorkspace() {
onMounted(async () => {
window.addEventListener('hxops:logout', session.onAuthLogout);
localeApi.loadLanguagePreference();
isSidebarCollapsed.value = localStorage.getItem('hxops.workspace.sidebarCollapsed') === 'true';
session.loadAuthUser();
if (!session.isLoggedIn.value) {
@@ -88,6 +90,11 @@ export function useWorkspace() {
window.removeEventListener('hxops:logout', session.onAuthLogout);
});
const toggleSidebarCollapsed = () => {
isSidebarCollapsed.value = !isSidebarCollapsed.value;
localStorage.setItem('hxops.workspace.sidebarCollapsed', String(isSidebarCollapsed.value));
};
return reactive({
config,
msg,
@@ -95,6 +102,8 @@ export function useWorkspace() {
route,
isMobile,
isLoading,
isSidebarCollapsed,
toggleSidebarCollapsed,
...localeApi,
...session,
...home,
@@ -17,6 +17,7 @@ const ROUTE_NAME_TO_SIDEBAR: Record<string, WorkspaceSidebarItem> = {
'workspace-applications': 'applications',
'workspace-updates': 'updates',
'workspace-knowledge-base': 'knowledge_base',
'workspace-knowledge-base-group': 'knowledge_base',
'workspace-schedule-runs': 'schedule_runs',
'workspace-shipping-notice': 'shipping_notice',
'workspace-feedback': 'feedback',
@@ -173,7 +174,7 @@ export function useWorkspaceNavigation(deps: WorkspaceDeps, options: NavigationO
if (name === 'workspace-schedule-runs') {
await loadWorkspaceScheduleRuns();
}
if (name === 'workspace-knowledge-base' && !hasKnowledgeBaseAccess.value) {
if (['workspace-knowledge-base', 'workspace-knowledge-base-group'].includes(name) && !hasKnowledgeBaseAccess.value) {
showKnowledgeBaseAccessDenied();
await router.replace(WORKSPACE_PATHS.applications);
}
@@ -42,8 +42,11 @@ const mobileTabs = [
</div>
</header>
<div class="grid min-h-screen gap-0 lg:grid-cols-[232px_minmax(0,1fr)]">
<WorkspaceSidebar v-if="!ws.isMobile" />
<div
class="grid min-h-screen gap-0 transition-[grid-template-columns] duration-200"
:class="ws.isMobile ? '' : (ws.isSidebarCollapsed ? 'lg:grid-cols-[72px_minmax(0,1fr)]' : 'lg:grid-cols-[320px_minmax(0,1fr)]')"
>
<WorkspaceSidebar v-if="!ws.isMobile" :collapsed="ws.isSidebarCollapsed" />
<section class="ws-main" :class="ws.isMobile ? 'pb-20' : ''">
<RouterView />
+4 -3
View File
@@ -144,9 +144,10 @@
},
"filters": {
"all": "All",
"upload": "Upload",
"clean": "Clean",
"sync": "Sync"
"pendingClean": "Pending clean",
"cleaning": "Cleaning",
"pendingSync": "Pending sync",
"failed": "Failed"
},
"common": {
"processing": "Processing...",
+2
View File
@@ -1,6 +1,8 @@
{
"title": "AI Workspace",
"brandTitle": "Hexin AI Workspace",
"collapseSidebar": "Collapse sidebar",
"expandSidebar": "Expand sidebar",
"languageLabel": "Language",
"userTitle": "{username}'s AI Workspace",
"subtitle": "Choose an agent or click a quick question to start",
+4 -3
View File
@@ -144,9 +144,10 @@
},
"filters": {
"all": "ทั้งหมด",
"upload": "อัปโหลด",
"clean": "ทำความสะอาด",
"sync": "ซิงค์"
"pendingClean": "รอทำความสะอาด",
"cleaning": "กำลังทำความสะอาด",
"pendingSync": "รอซิงค์",
"failed": "ผิดปกติ"
},
"common": {
"processing": "กำลังดำเนินการ...",
+2
View File
@@ -1,6 +1,8 @@
{
"title": "พื้นที่ทำงาน AI",
"brandTitle": "Hexin AI Workspace",
"collapseSidebar": "ยุบแถบนำทาง",
"expandSidebar": "ขยายแถบนำทาง",
"languageLabel": "ภาษา",
"userTitle": "พื้นที่ทำงาน AI ของ {username}",
"subtitle": "เลือกผู้ช่วยหรือคลิกคำถามด่วนเพื่อเริ่ม",
+4 -3
View File
@@ -144,9 +144,10 @@
},
"filters": {
"all": "全部",
"upload": "上传",
"clean": "清洗",
"sync": "同步"
"pendingClean": "待清洗",
"cleaning": "清洗中",
"pendingSync": "待同步",
"failed": "异常"
},
"common": {
"processing": "处理中...",
@@ -1,6 +1,8 @@
{
"title": "AI 工作台",
"brandTitle": "AI工作台",
"collapseSidebar": "折叠导航栏",
"expandSidebar": "展开导航栏",
"languageLabel": "语言",
"userTitle": "{username} 的 AI 工作台",
"subtitle": "选择一个助手,或点击常用问题快速开始",
+4 -3
View File
@@ -144,9 +144,10 @@
},
"filters": {
"all": "全部",
"upload": "上傳",
"clean": "清洗",
"sync": "同步"
"pendingClean": "待清洗",
"cleaning": "清洗中",
"pendingSync": "待同步",
"failed": "異常"
},
"common": {
"processing": "處理中...",
@@ -1,6 +1,8 @@
{
"title": "AI 工作台",
"brandTitle": "AI工作台",
"collapseSidebar": "折疊導航欄",
"expandSidebar": "展開導航欄",
"languageLabel": "語言",
"userTitle": "{username} 的 AI 工作台",
"subtitle": "選擇一個助手,或點擊常用問題快速開始",
+1 -1
View File
@@ -765,7 +765,7 @@
}
.ws-nav-btn {
@apply flex w-full items-center gap-3 rounded-2xl px-4 py-3 text-left text-[15px] font-medium transition-all;
@apply flex w-full items-center gap-3 rounded-xl px-4 py-3 text-left text-sm font-medium transition-all;
color: var(--text-secondary);
}
+28 -2
View File
@@ -2,7 +2,8 @@ param(
[ValidateSet("sqlite", "postgres")]
[string]$DbMode = "sqlite",
[string]$DatabaseUrl = "",
[switch]$SkipInstall
[switch]$SkipInstall,
[switch]$SkipWorker
)
$ErrorActionPreference = "Stop"
@@ -132,6 +133,23 @@ function Start-BackendWindow {
Start-Process powershell -ArgumentList @("-NoExit", "-ExecutionPolicy", "Bypass", "-Command", $cmd) | Out-Null
}
function Start-KbWorkerWindow {
param(
[string]$BackendPath,
[string]$Mode,
[string]$DbUrl
)
$dbExport = ""
if ($Mode -eq "postgres" -and -not [string]::IsNullOrWhiteSpace($DbUrl)) {
$escaped = $DbUrl.Replace("'", "''")
$dbExport = "`$env:DATABASE_URL='$escaped'; "
}
$cmd = "$dbExport Set-Location '$BackendPath'; .\venv\Scripts\python.exe .\worker_kb.py"
Start-Process powershell -ArgumentList @("-NoExit", "-ExecutionPolicy", "Bypass", "-Command", $cmd) | Out-Null
}
function Start-FrontendWindow {
param([string]$FrontendPath)
$cmd = "Set-Location '$FrontendPath'; npm run dev"
@@ -155,9 +173,17 @@ Ensure-Backend -BackendPath $backendDir -PyCmd $pythonCmd -Mode $DbMode -DbUrl $
Ensure-Frontend -FrontendPath $frontendDir -DoInstall $doInstall
Start-BackendWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $DatabaseUrl
if (-not $SkipWorker.IsPresent) {
Start-KbWorkerWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $DatabaseUrl
}
Start-FrontendWindow -FrontendPath $frontendDir
Write-Host ""
Write-Host "Started in two new PowerShell windows." -ForegroundColor Green
if ($SkipWorker.IsPresent) {
Write-Host "Started in two new PowerShell windows." -ForegroundColor Green
}
else {
Write-Host "Started in three new PowerShell windows." -ForegroundColor Green
}
Write-Host "Frontend URL: http://127.0.0.1:8881" -ForegroundColor Green
Write-Host "Default local admin (sqlite/init scripts): admin / Hxit@54321" -ForegroundColor Green