merge conflict
This commit is contained in:
commit
03570dbf5a
25 files changed
+405
-25
No files matched your search
@@ -34,5 +34,13 @@ CASDOOR_SCOPE=openid profile email
|
|||||||
# Casdoor Providers → wecom(Name=wecom,与 prod 共用同一 Provider 即可)
|
# Casdoor Providers → wecom(Name=wecom,与 prod 共用同一 Provider 即可)
|
||||||
CASDOOR_WECOM_PROVIDER_HINT=wecom
|
CASDOOR_WECOM_PROVIDER_HINT=wecom
|
||||||
|
|
||||||
|
# 知识库 Dify 对接
|
||||||
|
PUBLIC_BASE_URL=http://192.168.100.192:8891
|
||||||
|
DIFY_API_BASE=http://192.168.100.192:8882/v1
|
||||||
|
DIFY_API_KEY=dataset-7xxs1P1QnqBmkEAjGhXLjmwF
|
||||||
|
DEFAULT_ADMIN_USERNAME=admin
|
||||||
|
DEFAULT_ADMIN_PASSWORD=admin123456
|
||||||
|
TASK_EXECUTION_MODE=sync
|
||||||
|
|
||||||
# Gunicorn配置
|
# Gunicorn配置
|
||||||
GUNICORN_WORKERS=10
|
GUNICORN_WORKERS=10
|
||||||
@@ -34,5 +34,13 @@ CASDOOR_SCOPE=openid profile email
|
|||||||
# Casdoor Providers → wecom:Name 字段(截图即为 wecom);Organization=organization_HX,Sub type=Internal,Scope=snsapi_userinfo
|
# Casdoor Providers → wecom:Name 字段(截图即为 wecom);Organization=organization_HX,Sub type=Internal,Scope=snsapi_userinfo
|
||||||
CASDOOR_WECOM_PROVIDER_HINT=wecom
|
CASDOOR_WECOM_PROVIDER_HINT=wecom
|
||||||
|
|
||||||
|
# 知识库 Dify 对接
|
||||||
|
PUBLIC_BASE_URL=http://192.168.100.230:8891
|
||||||
|
DIFY_API_BASE=http://192.168.100.230:8882/v1
|
||||||
|
DIFY_API_KEY=dataset-7xxs1P1QnqBmkEAjGhXLjmwF
|
||||||
|
DEFAULT_ADMIN_USERNAME=admin
|
||||||
|
DEFAULT_ADMIN_PASSWORD=admin123456
|
||||||
|
TASK_EXECUTION_MODE=rq
|
||||||
|
|
||||||
# Gunicorn配置
|
# Gunicorn配置
|
||||||
GUNICORN_WORKERS=20
|
GUNICORN_WORKERS=20
|
||||||
@@ -33,6 +33,14 @@ CASDOOR_SCOPE=openid profile email
|
|||||||
# Casdoor Providers → wecom:Name 字段(截图即为 wecom);Organization=organization_HX,Sub type=Internal,Scope=snsapi_userinfo
|
# Casdoor Providers → wecom:Name 字段(截图即为 wecom);Organization=organization_HX,Sub type=Internal,Scope=snsapi_userinfo
|
||||||
CASDOOR_WECOM_PROVIDER_HINT=wecom
|
CASDOOR_WECOM_PROVIDER_HINT=wecom
|
||||||
|
|
||||||
|
# 知识库 Dify 对接
|
||||||
|
PUBLIC_BASE_URL=http://192.168.100.192:8891
|
||||||
|
DIFY_API_BASE=http://192.168.100.192:8882/v1
|
||||||
|
DIFY_API_KEY=dataset-7xxs1P1QnqBmkEAjGhXLjmwF
|
||||||
|
DEFAULT_ADMIN_USERNAME=admin
|
||||||
|
DEFAULT_ADMIN_PASSWORD=admin123456
|
||||||
|
TASK_EXECUTION_MODE=rq
|
||||||
|
|
||||||
# Gunicorn配置
|
# Gunicorn配置
|
||||||
GUNICORN_WORKERS=6
|
GUNICORN_WORKERS=6
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ from flask import Blueprint, jsonify, request
|
|||||||
from app import db
|
from app import db
|
||||||
from app.models import ScheduleRun, ScheduleTask
|
from app.models import ScheduleRun, ScheduleTask
|
||||||
from app.services.schedule import _run_generic_check_job
|
from app.services.schedule import _run_generic_check_job
|
||||||
|
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
||||||
|
|
||||||
internal_jobs_bp = Blueprint('internal_jobs', __name__)
|
internal_jobs_bp = Blueprint('internal_jobs', __name__)
|
||||||
|
|
||||||
@@ -47,6 +48,10 @@ def run_internal_job(name: str):
|
|||||||
db.session.add(run)
|
db.session.add(run)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
|
if not run.dify_execution_snapshot:
|
||||||
|
capture_dify_execution_snapshot(run, task)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = _run_generic_check_job(task, run)
|
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = _run_generic_check_job(task, run)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
@@ -68,6 +73,7 @@ def run_internal_job(name: str):
|
|||||||
run.finished_at = datetime.utcnow()
|
run.finished_at = datetime.utcnow()
|
||||||
if run.started_at and run.finished_at:
|
if run.started_at and run.finished_at:
|
||||||
run.duration_ms = int((run.finished_at - run.started_at).total_seconds() * 1000)
|
run.duration_ms = int((run.finished_at - run.started_at).total_seconds() * 1000)
|
||||||
|
run.step_logs = step_logs if step_logs else None
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
return jsonify({
|
return jsonify({
|
||||||
|
|||||||
@@ -1036,10 +1036,11 @@ def delete_document(document_id: int):
|
|||||||
if not document or document.is_deleted:
|
if not document or document.is_deleted:
|
||||||
return jsonify({'error': 'Knowledge base document not found'}), 404
|
return jsonify({'error': 'Knowledge base document not found'}), 404
|
||||||
|
|
||||||
|
delete_result = None
|
||||||
try:
|
try:
|
||||||
delete_result = delete_document_from_dify(document.id)
|
delete_result = delete_document_from_dify(document.id)
|
||||||
except Exception as exc:
|
except Exception:
|
||||||
return jsonify({'error': f'删除 Dify 远端文档失败:{exc}'}), 400
|
pass
|
||||||
|
|
||||||
document.is_deleted = True
|
document.is_deleted = True
|
||||||
document.updated_by_id = getattr(current_user, 'id', None)
|
document.updated_by_id = getattr(current_user, 'id', None)
|
||||||
|
|||||||
@@ -62,6 +62,7 @@ def _serialize_task_config(cfg_model: ScheduleTaskConfig) -> dict:
|
|||||||
"headers": cfg_model.api_headers or {},
|
"headers": cfg_model.api_headers or {},
|
||||||
"body_template": cfg_model.api_body_template or "",
|
"body_template": cfg_model.api_body_template or "",
|
||||||
},
|
},
|
||||||
|
"dify_system_prompt": cfg_model.dify_system_prompt or "",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -206,6 +207,10 @@ def test_schedule_run(task_id: int):
|
|||||||
db.session.add(run)
|
db.session.add(run)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
|
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
||||||
|
capture_dify_execution_snapshot(run, task)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
if not cfg.fetch_sql:
|
if not cfg.fetch_sql:
|
||||||
run.status = 'success'
|
run.status = 'success'
|
||||||
run.finished_at = datetime.utcnow()
|
run.finished_at = datetime.utcnow()
|
||||||
@@ -289,6 +294,7 @@ def test_schedule_run(task_id: int):
|
|||||||
fetch_sql=test_sql,
|
fetch_sql=test_sql,
|
||||||
max_rows=limit,
|
max_rows=limit,
|
||||||
pre_dify_fn=test_pre_dify,
|
pre_dify_fn=test_pre_dify,
|
||||||
|
dify_system_prompt=cfg.dify_system_prompt,
|
||||||
)
|
)
|
||||||
|
|
||||||
duration_ms = int((_time.time() - start_ts) * 1000)
|
duration_ms = int((_time.time() - start_ts) * 1000)
|
||||||
@@ -363,6 +369,7 @@ def test_schedule_run(task_id: int):
|
|||||||
"errors": errors,
|
"errors": errors,
|
||||||
"step_logs": step_logs,
|
"step_logs": step_logs,
|
||||||
"dify_agent_id": dify_agent_id,
|
"dify_agent_id": dify_agent_id,
|
||||||
|
"dify_execution_snapshot": run.dify_execution_snapshot,
|
||||||
})
|
})
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
duration_ms = int((_time.time() - start_ts) * 1000)
|
duration_ms = int((_time.time() - start_ts) * 1000)
|
||||||
@@ -510,6 +517,11 @@ def post_schedule():
|
|||||||
config_data = data.get('config')
|
config_data = data.get('config')
|
||||||
if config_data:
|
if config_data:
|
||||||
upsert_schedule_task_config(task.id, config_data)
|
upsert_schedule_task_config(task.id, config_data)
|
||||||
|
if not task.dify_agent_id:
|
||||||
|
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task.id).first()
|
||||||
|
if cfg_model and cfg_model.dify_system_prompt:
|
||||||
|
cfg_model.dify_system_prompt = None
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
return jsonify(serialize_task(task)), 201
|
return jsonify(serialize_task(task)), 201
|
||||||
|
|
||||||
@@ -541,6 +553,13 @@ def patch_schedule(task_id: int):
|
|||||||
upsert_schedule_task_config(task_id, config_data)
|
upsert_schedule_task_config(task_id, config_data)
|
||||||
|
|
||||||
task = update_task(task, payload=data, actor_id=getattr(user, 'id', None))
|
task = update_task(task, payload=data, actor_id=getattr(user, 'id', None))
|
||||||
|
|
||||||
|
if not task.dify_agent_id:
|
||||||
|
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||||
|
if cfg_model and cfg_model.dify_system_prompt:
|
||||||
|
cfg_model.dify_system_prompt = None
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
return jsonify(serialize_task(task))
|
return jsonify(serialize_task(task))
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ def _load_environment_files() -> str:
|
|||||||
|
|
||||||
env_file = _ROOT_DIR / f'.env.{env_name}'
|
env_file = _ROOT_DIR / f'.env.{env_name}'
|
||||||
if env_file.exists():
|
if env_file.exists():
|
||||||
load_dotenv(env_file, override=False)
|
load_dotenv(env_file, override=True)
|
||||||
|
|
||||||
if env_name == 'dev':
|
if env_name == 'dev':
|
||||||
local_file = _ROOT_DIR / '.env.local'
|
local_file = _ROOT_DIR / '.env.local'
|
||||||
@@ -64,6 +64,10 @@ class Config:
|
|||||||
'pool_recycle': 3600,
|
'pool_recycle': 3600,
|
||||||
'pool_pre_ping': True,
|
'pool_pre_ping': True,
|
||||||
}
|
}
|
||||||
|
PUBLIC_BASE_URL = os.getenv('PUBLIC_BASE_URL')
|
||||||
|
DEFAULT_ADMIN_USERNAME = os.getenv('DEFAULT_ADMIN_USERNAME')
|
||||||
|
DEFAULT_ADMIN_PASSWORD = os.getenv('DEFAULT_ADMIN_PASSWORD')
|
||||||
|
TASK_EXECUTION_MODE = os.getenv('TASK_EXECUTION_MODE', 'sync').strip().lower()
|
||||||
# Dify 网关配置
|
# Dify 网关配置
|
||||||
DIFY_API_BASE = os.getenv('DIFY_API_BASE')
|
DIFY_API_BASE = os.getenv('DIFY_API_BASE')
|
||||||
DIFY_API_KEY = os.getenv('DIFY_API_KEY')
|
DIFY_API_KEY = os.getenv('DIFY_API_KEY')
|
||||||
|
|||||||
@@ -613,6 +613,7 @@ class ScheduleTaskConfig(Base):
|
|||||||
api_method: Mapped[str] = mapped_column(String(16), default='POST')
|
api_method: Mapped[str] = mapped_column(String(16), default='POST')
|
||||||
api_headers: Mapped[Optional[dict]] = mapped_column(JSON, default={})
|
api_headers: Mapped[Optional[dict]] = mapped_column(JSON, default={})
|
||||||
api_body_template: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
api_body_template: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||||
|
dify_system_prompt: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||||
|
|
||||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||||
@@ -644,6 +645,7 @@ class ScheduleRun(Base):
|
|||||||
api_response_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
api_response_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||||
response_summary_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
response_summary_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||||
step_logs: Mapped[Optional[list]] = mapped_column(JSON)
|
step_logs: Mapped[Optional[list]] = mapped_column(JSON)
|
||||||
|
dify_execution_snapshot: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||||
error_message: Mapped[Optional[str]] = mapped_column(Text)
|
error_message: Mapped[Optional[str]] = mapped_column(Text)
|
||||||
excel_file_data: Mapped[Optional[bytes]] = mapped_column(LargeBinary)
|
excel_file_data: Mapped[Optional[bytes]] = mapped_column(LargeBinary)
|
||||||
excel_file_name: Mapped[Optional[str]] = mapped_column(String(255))
|
excel_file_name: Mapped[Optional[str]] = mapped_column(String(255))
|
||||||
|
|||||||
@@ -17,7 +17,10 @@ def enqueue_kb_job(job_id: int) -> tuple[bool, str]:
|
|||||||
- worker: 仅保留 queued,等待独立 worker 轮询;
|
- worker: 仅保留 queued,等待独立 worker 轮询;
|
||||||
- manual: 保留 queued,等待管理台手动执行。
|
- manual: 保留 queued,等待管理台手动执行。
|
||||||
"""
|
"""
|
||||||
mode = str(current_app.config.get('KB_TASK_EXECUTION_MODE', 'sync')).strip().lower()
|
mode = str(
|
||||||
|
current_app.config.get('TASK_EXECUTION_MODE')
|
||||||
|
or current_app.config.get('KB_TASK_EXECUTION_MODE', 'sync')
|
||||||
|
).strip().lower()
|
||||||
|
|
||||||
job = db.session.get(KbJob, job_id)
|
job = db.session.get(KbJob, job_id)
|
||||||
if not job:
|
if not job:
|
||||||
@@ -32,7 +35,7 @@ def enqueue_kb_job(job_id: int) -> tuple[bool, str]:
|
|||||||
return run_path_upload_job(job_id)
|
return run_path_upload_job(job_id)
|
||||||
return False, f'unsupported_sync_job:{job.job_type}'
|
return False, f'unsupported_sync_job:{job.job_type}'
|
||||||
|
|
||||||
if mode == 'worker':
|
if mode in ('worker', 'rq'):
|
||||||
return True, 'queued_for_worker'
|
return True, 'queued_for_worker'
|
||||||
|
|
||||||
return True, 'queued_manual'
|
return True, 'queued_manual'
|
||||||
|
|||||||
@@ -258,6 +258,7 @@ def _run_generic_check_job(task: ScheduleTask, run: ScheduleRun) -> ScheduleExec
|
|||||||
log_prefix=cfg.log_prefix,
|
log_prefix=cfg.log_prefix,
|
||||||
fetch_sql=cfg.fetch_sql,
|
fetch_sql=cfg.fetch_sql,
|
||||||
pre_dify_fn=pre_dify_fn,
|
pre_dify_fn=pre_dify_fn,
|
||||||
|
dify_system_prompt=cfg.dify_system_prompt,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app import db
|
||||||
|
from app.models import Agent, ScheduleRun, ScheduleTask
|
||||||
|
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
|
||||||
|
|
||||||
|
|
||||||
|
def build_dify_execution_snapshot(task: ScheduleTask) -> dict[str, Any]:
|
||||||
|
"""Capture Dify agent + system prompt used at execution time for audit."""
|
||||||
|
captured_at = datetime.utcnow().isoformat() + "Z"
|
||||||
|
if not task.dify_agent_id:
|
||||||
|
return {
|
||||||
|
"dify_enabled": False,
|
||||||
|
"dify_agent_id": None,
|
||||||
|
"dify_agent_name": None,
|
||||||
|
"dify_app_id": None,
|
||||||
|
"dify_system_prompt": "",
|
||||||
|
"captured_at": captured_at,
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg = get_schedule_sql_config_by_task_id(task.id)
|
||||||
|
prompt = str(cfg.dify_system_prompt if cfg else "").strip()
|
||||||
|
agent = db.session.get(Agent, task.dify_agent_id)
|
||||||
|
return {
|
||||||
|
"dify_enabled": True,
|
||||||
|
"dify_agent_id": task.dify_agent_id,
|
||||||
|
"dify_agent_name": getattr(agent, "name", None) if agent else None,
|
||||||
|
"dify_app_id": getattr(agent, "dify_app_id", None) if agent else None,
|
||||||
|
"dify_system_prompt": prompt,
|
||||||
|
"captured_at": captured_at,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def capture_dify_execution_snapshot(run: ScheduleRun, task: ScheduleTask) -> dict[str, Any]:
|
||||||
|
snapshot = build_dify_execution_snapshot(task)
|
||||||
|
run.dify_execution_snapshot = snapshot
|
||||||
|
return snapshot
|
||||||
@@ -54,6 +54,7 @@ def serialize_run(run: ScheduleRun) -> dict:
|
|||||||
'api_response_json': run.api_response_json,
|
'api_response_json': run.api_response_json,
|
||||||
'response_summary_json': run.response_summary_json,
|
'response_summary_json': run.response_summary_json,
|
||||||
'step_logs': run.step_logs,
|
'step_logs': run.step_logs,
|
||||||
|
'dify_execution_snapshot': run.dify_execution_snapshot,
|
||||||
'error_message': run.error_message,
|
'error_message': run.error_message,
|
||||||
'excel_file_name': run.excel_file_name,
|
'excel_file_name': run.excel_file_name,
|
||||||
'excel_file_size': run.excel_file_size,
|
'excel_file_size': run.excel_file_size,
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ from app.models import ScheduleRun, ScheduleTask, User
|
|||||||
from app.services.schedule import normalize_platform_api_path, resolve_schedule_executor, resolve_schedule_header
|
from app.services.schedule import normalize_platform_api_path, resolve_schedule_executor, resolve_schedule_header
|
||||||
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
|
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
|
||||||
from app.services.schedule.excel_service import export_schedule_result_excel
|
from app.services.schedule.excel_service import export_schedule_result_excel
|
||||||
|
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
||||||
|
|
||||||
_worker_started = False
|
_worker_started = False
|
||||||
_worker_lock = threading.Lock()
|
_worker_lock = threading.Lock()
|
||||||
@@ -248,6 +249,9 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
|
|||||||
db.session.add(run)
|
db.session.add(run)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
|
capture_dify_execution_snapshot(run, task)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
if task.cron_expr and trigger_type == "cron":
|
if task.cron_expr and trigger_type == "cron":
|
||||||
try:
|
try:
|
||||||
iter = croniter(task.cron_expr, datetime.utcnow())
|
iter = croniter(task.cron_expr, datetime.utcnow())
|
||||||
|
|||||||
@@ -94,6 +94,7 @@ class ScheduleSqlConfig:
|
|||||||
data_source: DataSourceConfig = field(default_factory=DataSourceConfig)
|
data_source: DataSourceConfig = field(default_factory=DataSourceConfig)
|
||||||
external_api: ExternalApiConfig = field(default_factory=ExternalApiConfig)
|
external_api: ExternalApiConfig = field(default_factory=ExternalApiConfig)
|
||||||
data_source_type: str = "database"
|
data_source_type: str = "database"
|
||||||
|
dify_system_prompt: str = ""
|
||||||
|
|
||||||
|
|
||||||
def _build_fetch_sql(base: str, where_conds: str, order_by: str) -> str:
|
def _build_fetch_sql(base: str, where_conds: str, order_by: str) -> str:
|
||||||
@@ -153,6 +154,7 @@ def _config_from_model(cfg_model: Any) -> ScheduleSqlConfig:
|
|||||||
data_source=ds,
|
data_source=ds,
|
||||||
external_api=ext,
|
external_api=ext,
|
||||||
data_source_type=str(task.data_source_type if task else "database"),
|
data_source_type=str(task.data_source_type if task else "database"),
|
||||||
|
dify_system_prompt=str(cfg_model.dify_system_prompt or ""),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -233,6 +235,8 @@ def upsert_schedule_task_config(task_id: int, data: dict[str, Any]) -> ScheduleS
|
|||||||
setattr(cfg_model, k, list(v) if isinstance(v, (list, tuple)) else [])
|
setattr(cfg_model, k, list(v) if isinstance(v, (list, tuple)) else [])
|
||||||
elif k == "header_labels":
|
elif k == "header_labels":
|
||||||
setattr(cfg_model, k, dict(v) if isinstance(v, dict) else {})
|
setattr(cfg_model, k, dict(v) if isinstance(v, dict) else {})
|
||||||
|
elif k == "dify_system_prompt":
|
||||||
|
setattr(cfg_model, k, str(v) if v is not None else None)
|
||||||
|
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
db.session.refresh(cfg_model)
|
db.session.refresh(cfg_model)
|
||||||
|
|||||||
@@ -117,6 +117,17 @@ def _truncate_str(s: str, max_len: int = _MAX_DIFY_RESPONSE_LEN) -> str:
|
|||||||
return s[:max_len] + f"...[truncated, total {len(s)} chars]"
|
return s[:max_len] + f"...[truncated, total {len(s)} chars]"
|
||||||
|
|
||||||
|
|
||||||
|
def _serialize_dify_inputs_for_log(inputs: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
"""Log Dify request inputs; keep system_prompt intact for audit."""
|
||||||
|
out: dict[str, Any] = {}
|
||||||
|
for k, v in inputs.items():
|
||||||
|
if k == "system_prompt":
|
||||||
|
out[k] = str(v)
|
||||||
|
else:
|
||||||
|
out[k] = _truncate_str(str(v), 500)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
def _run_check_job_loop(
|
def _run_check_job_loop(
|
||||||
*,
|
*,
|
||||||
conn_str: str,
|
conn_str: str,
|
||||||
@@ -134,6 +145,7 @@ def _run_check_job_loop(
|
|||||||
fetch_sql: str = "",
|
fetch_sql: str = "",
|
||||||
max_rows: int = 0,
|
max_rows: int = 0,
|
||||||
pre_dify_fn: PreDifyFunc | None = None,
|
pre_dify_fn: PreDifyFunc | None = None,
|
||||||
|
dify_system_prompt: str = "",
|
||||||
) -> tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]:
|
) -> tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]:
|
||||||
from app.services.schedule.scheduler_service import is_run_cancelled
|
from app.services.schedule.scheduler_service import is_run_cancelled
|
||||||
|
|
||||||
@@ -218,6 +230,9 @@ def _run_check_job_loop(
|
|||||||
"record": record_text,
|
"record": record_text,
|
||||||
"attachment_url": attachment_url,
|
"attachment_url": attachment_url,
|
||||||
}
|
}
|
||||||
|
prompt = str(dify_system_prompt or "").strip()
|
||||||
|
if prompt:
|
||||||
|
dify_inputs["system_prompt"] = prompt
|
||||||
t_dify = _ts()
|
t_dify = _ts()
|
||||||
try:
|
try:
|
||||||
dify_res = DifyService.run_workflow_streaming(
|
dify_res = DifyService.run_workflow_streaming(
|
||||||
@@ -228,7 +243,10 @@ def _run_check_job_loop(
|
|||||||
)
|
)
|
||||||
except Exception as dify_exc:
|
except Exception as dify_exc:
|
||||||
step_logs.append(_make_step("call_dify", "failed", t_dify, _ts(), row_id=row_id_value, detail={
|
step_logs.append(_make_step("call_dify", "failed", t_dify, _ts(), row_id=row_id_value, detail={
|
||||||
"request": {"inputs": {k: _truncate_str(str(v), 500) for k, v in dify_inputs.items()}, "agent_id": getattr(agent, "id", None)},
|
"request": {
|
||||||
|
"inputs": _serialize_dify_inputs_for_log(dify_inputs),
|
||||||
|
"agent_id": getattr(agent, "id", None),
|
||||||
|
},
|
||||||
"error": str(dify_exc),
|
"error": str(dify_exc),
|
||||||
}))
|
}))
|
||||||
raise
|
raise
|
||||||
@@ -243,7 +261,10 @@ def _run_check_job_loop(
|
|||||||
dify_message = f"Dify执行失败:{err_detail}"
|
dify_message = f"Dify执行失败:{err_detail}"
|
||||||
|
|
||||||
step_logs.append(_make_step("call_dify", "failed", t_dify, _ts(), row_id=row_id_value, detail={
|
step_logs.append(_make_step("call_dify", "failed", t_dify, _ts(), row_id=row_id_value, detail={
|
||||||
"request": {"inputs": {k: _truncate_str(str(v), 500) for k, v in dify_inputs.items()}, "agent_id": getattr(agent, "id", None)},
|
"request": {
|
||||||
|
"inputs": _serialize_dify_inputs_for_log(dify_inputs),
|
||||||
|
"agent_id": getattr(agent, "id", None),
|
||||||
|
},
|
||||||
"response": _truncate_str(str(dify_res)),
|
"response": _truncate_str(str(dify_res)),
|
||||||
"workflow_run_id": workflow_run_id,
|
"workflow_run_id": workflow_run_id,
|
||||||
}))
|
}))
|
||||||
@@ -271,7 +292,10 @@ def _run_check_job_loop(
|
|||||||
dify_ok = True
|
dify_ok = True
|
||||||
|
|
||||||
step_logs.append(_make_step("call_dify", "success", t_dify, _ts(), row_id=row_id_value, detail={
|
step_logs.append(_make_step("call_dify", "success", t_dify, _ts(), row_id=row_id_value, detail={
|
||||||
"request": {"inputs": {k: _truncate_str(str(v), 500) for k, v in dify_inputs.items()}, "agent_id": getattr(agent, "id", None)},
|
"request": {
|
||||||
|
"inputs": _serialize_dify_inputs_for_log(dify_inputs),
|
||||||
|
"agent_id": getattr(agent, "id", None),
|
||||||
|
},
|
||||||
"response": {
|
"response": {
|
||||||
"status": dify_status,
|
"status": dify_status,
|
||||||
"dify_result": dify_result,
|
"dify_result": dify_result,
|
||||||
|
|||||||
Binary file not shown.
+25
@@ -0,0 +1,25 @@
|
|||||||
|
"""add_dify_system_prompt_to_schedule_configs
|
||||||
|
|
||||||
|
Revision ID: d2e3f4a5b6c7
|
||||||
|
Revises: c1d2e3f4a5b6
|
||||||
|
Create Date: 2026-05-25
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
revision = 'd2e3f4a5b6c7'
|
||||||
|
down_revision = 'c1d2e3f4a5b6'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
with op.batch_alter_table('schedule_task_configs', schema=None) as batch_op:
|
||||||
|
batch_op.add_column(sa.Column('dify_system_prompt', sa.Text(), nullable=True))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
with op.batch_alter_table('schedule_task_configs', schema=None) as batch_op:
|
||||||
|
batch_op.drop_column('dify_system_prompt')
|
||||||
+25
@@ -0,0 +1,25 @@
|
|||||||
|
"""add_dify_execution_snapshot_to_schedule_runs
|
||||||
|
|
||||||
|
Revision ID: e3f4a5b6c7d8
|
||||||
|
Revises: d2e3f4a5b6c7
|
||||||
|
Create Date: 2026-05-25
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
revision = 'e3f4a5b6c7d8'
|
||||||
|
down_revision = 'd2e3f4a5b6c7'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
with op.batch_alter_table('schedule_runs', schema=None) as batch_op:
|
||||||
|
batch_op.add_column(sa.Column('dify_execution_snapshot', sa.JSON(), nullable=True))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
with op.batch_alter_table('schedule_runs', schema=None) as batch_op:
|
||||||
|
batch_op.drop_column('dify_execution_snapshot')
|
||||||
@@ -40,6 +40,7 @@ export interface ScheduleRun {
|
|||||||
api_response_json?: Record<string, any> | null;
|
api_response_json?: Record<string, any> | null;
|
||||||
response_summary_json?: Record<string, any> | null;
|
response_summary_json?: Record<string, any> | null;
|
||||||
step_logs?: StepLog[] | null;
|
step_logs?: StepLog[] | null;
|
||||||
|
dify_execution_snapshot?: DifyExecutionSnapshot | null;
|
||||||
error_message?: string | null;
|
error_message?: string | null;
|
||||||
excel_file_name?: string | null;
|
excel_file_name?: string | null;
|
||||||
excel_file_size?: number | null;
|
excel_file_size?: number | null;
|
||||||
@@ -59,6 +60,15 @@ export interface StepLog {
|
|||||||
detail?: Record<string, any>;
|
detail?: Record<string, any>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface DifyExecutionSnapshot {
|
||||||
|
dify_enabled?: boolean;
|
||||||
|
dify_agent_id?: number | null;
|
||||||
|
dify_agent_name?: string | null;
|
||||||
|
dify_app_id?: string | null;
|
||||||
|
dify_system_prompt?: string;
|
||||||
|
captured_at?: string;
|
||||||
|
}
|
||||||
|
|
||||||
async function getJson<T>(url: string): Promise<T> {
|
async function getJson<T>(url: string): Promise<T> {
|
||||||
const res = await fetch(url, { headers: getAuthHeaders() });
|
const res = await fetch(url, { headers: getAuthHeaders() });
|
||||||
if (!res.ok) throw new Error((await res.json().catch(() => ({})))?.error || 'Request failed');
|
if (!res.ok) throw new Error((await res.json().catch(() => ({})))?.error || 'Request failed');
|
||||||
@@ -119,6 +129,7 @@ export interface TestScheduleRunResult {
|
|||||||
errors: string[];
|
errors: string[];
|
||||||
step_logs: StepLog[];
|
step_logs: StepLog[];
|
||||||
dify_agent_id: number | null;
|
dify_agent_id: number | null;
|
||||||
|
dify_execution_snapshot?: DifyExecutionSnapshot | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const testAdminScheduleRun = (taskId: number, payload: { fetch_where_conditions?: string; fetch_order_by?: string; limit?: number }) =>
|
export const testAdminScheduleRun = (taskId: number, payload: { fetch_where_conditions?: string; fetch_order_by?: string; limit?: number }) =>
|
||||||
|
|||||||
@@ -73,6 +73,7 @@ onBeforeUnmount(() => {
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
|
<Teleport to="body">
|
||||||
<Transition name="delete-dialog-fade">
|
<Transition name="delete-dialog-fade">
|
||||||
<div
|
<div
|
||||||
v-if="modelValue"
|
v-if="modelValue"
|
||||||
@@ -108,6 +109,7 @@ onBeforeUnmount(() => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</Transition>
|
</Transition>
|
||||||
|
</Teleport>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
|
|||||||
+40
-4
@@ -1356,7 +1356,16 @@ const messages = {
|
|||||||
oaDataConnected: 'Connected to OA database view query.',
|
oaDataConnected: 'Connected to OA database view query.',
|
||||||
searchByNameOrEmployeeId: 'Search by name or employee ID, press Enter',
|
searchByNameOrEmployeeId: 'Search by name or employee ID, press Enter',
|
||||||
name: 'Name',
|
name: 'Name',
|
||||||
employeeIdRequired: 'Employee ID is required.'
|
employeeIdRequired: 'Employee ID is required.',
|
||||||
|
actions: {
|
||||||
|
copy: 'Copy',
|
||||||
|
edit: 'Edit',
|
||||||
|
resend: 'Resend',
|
||||||
|
regenerate: 'Regenerate',
|
||||||
|
copySuccess: 'Copied',
|
||||||
|
copyFailed: 'Copy failed. Please allow clipboard access or try again.',
|
||||||
|
copyEmpty: 'Nothing to copy'
|
||||||
|
}
|
||||||
},
|
},
|
||||||
profile: {
|
profile: {
|
||||||
title: 'Profile',
|
title: 'Profile',
|
||||||
@@ -2780,7 +2789,16 @@ const messages = {
|
|||||||
oaDataConnected: '已接入 OA 数据库视图查询。',
|
oaDataConnected: '已接入 OA 数据库视图查询。',
|
||||||
searchByNameOrEmployeeId: '输入姓名或工号搜索,按回车键查询',
|
searchByNameOrEmployeeId: '输入姓名或工号搜索,按回车键查询',
|
||||||
name: '姓名',
|
name: '姓名',
|
||||||
employeeIdRequired: '工号不能为空。'
|
employeeIdRequired: '工号不能为空。',
|
||||||
|
actions: {
|
||||||
|
copy: '复制',
|
||||||
|
edit: '编辑',
|
||||||
|
resend: '重新发送',
|
||||||
|
regenerate: '重新生成',
|
||||||
|
copySuccess: '已复制',
|
||||||
|
copyFailed: '复制失败,请允许剪贴板权限后重试',
|
||||||
|
copyEmpty: '没有可复制的内容'
|
||||||
|
}
|
||||||
},
|
},
|
||||||
profile: {
|
profile: {
|
||||||
title: '个人资料',
|
title: '个人资料',
|
||||||
@@ -4063,7 +4081,16 @@ const messages = {
|
|||||||
oaDataConnected: '已接入 OA 資料庫視圖查詢。',
|
oaDataConnected: '已接入 OA 資料庫視圖查詢。',
|
||||||
searchByNameOrEmployeeId: '輸入姓名或工號搜尋,按 Enter 查詢',
|
searchByNameOrEmployeeId: '輸入姓名或工號搜尋,按 Enter 查詢',
|
||||||
name: '姓名',
|
name: '姓名',
|
||||||
employeeIdRequired: '工號不能為空。'
|
employeeIdRequired: '工號不能為空。',
|
||||||
|
actions: {
|
||||||
|
copy: '複製',
|
||||||
|
edit: '編輯',
|
||||||
|
resend: '重新發送',
|
||||||
|
regenerate: '重新生成',
|
||||||
|
copySuccess: '已複製',
|
||||||
|
copyFailed: '複製失敗,請允許剪貼簿權限後重試',
|
||||||
|
copyEmpty: '沒有可複製的內容'
|
||||||
|
}
|
||||||
},
|
},
|
||||||
profile: {
|
profile: {
|
||||||
title: '個人資料',
|
title: '個人資料',
|
||||||
@@ -5263,7 +5290,16 @@ const messages = {
|
|||||||
oaDataConnected: 'เชื่อมต่อการค้นหามุมมองฐานข้อมูล OA แล้ว',
|
oaDataConnected: 'เชื่อมต่อการค้นหามุมมองฐานข้อมูล OA แล้ว',
|
||||||
searchByNameOrEmployeeId: 'ค้นหาด้วยชื่อหรือรหัสพนักงาน แล้วกด Enter',
|
searchByNameOrEmployeeId: 'ค้นหาด้วยชื่อหรือรหัสพนักงาน แล้วกด Enter',
|
||||||
name: 'ชื่อ',
|
name: 'ชื่อ',
|
||||||
employeeIdRequired: 'รหัสพนักงานห้ามว่าง'
|
employeeIdRequired: 'รหัสพนักงานห้ามว่าง',
|
||||||
|
actions: {
|
||||||
|
copy: 'คัดลอก',
|
||||||
|
edit: 'แก้ไข',
|
||||||
|
resend: 'ส่งอีกครั้ง',
|
||||||
|
regenerate: 'สร้างใหม่',
|
||||||
|
copySuccess: 'คัดลอกแล้ว',
|
||||||
|
copyFailed: 'คัดลอกไม่สำเร็จ โปรดอนุญาตการเข้าถึงคลิปบอร์ดแล้วลองอีกครั้ง',
|
||||||
|
copyEmpty: 'ไม่มีเนื้อหาให้คัดลอก'
|
||||||
|
}
|
||||||
},
|
},
|
||||||
profile: {
|
profile: {
|
||||||
title: 'โปรไฟล์',
|
title: 'โปรไฟล์',
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
/**
|
||||||
|
* Copy plain text to the clipboard with fallbacks for restricted browsers
|
||||||
|
* (e.g. WeCom embedded WebView, HTTP deployments).
|
||||||
|
*/
|
||||||
|
export async function copyTextToClipboard(text: string): Promise<boolean> {
|
||||||
|
const value = String(text ?? '');
|
||||||
|
if (!value.trim()) return false;
|
||||||
|
|
||||||
|
if (navigator.clipboard?.writeText) {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(value);
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
// Fall through to legacy copy.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const textarea = document.createElement('textarea');
|
||||||
|
textarea.value = value;
|
||||||
|
textarea.setAttribute('readonly', 'true');
|
||||||
|
textarea.style.position = 'fixed';
|
||||||
|
textarea.style.left = '-9999px';
|
||||||
|
textarea.style.top = '0';
|
||||||
|
textarea.style.opacity = '0';
|
||||||
|
document.body.appendChild(textarea);
|
||||||
|
textarea.focus();
|
||||||
|
textarea.select();
|
||||||
|
textarea.setSelectionRange(0, value.length);
|
||||||
|
const ok = document.execCommand('copy');
|
||||||
|
document.body.removeChild(textarea);
|
||||||
|
return ok;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -722,6 +722,7 @@ const resetScheduleCreateForm = () => {
|
|||||||
api_method: 'POST',
|
api_method: 'POST',
|
||||||
api_headers_str: '{}',
|
api_headers_str: '{}',
|
||||||
api_body_template: '',
|
api_body_template: '',
|
||||||
|
dify_system_prompt: '',
|
||||||
};
|
};
|
||||||
scheduleTestResult.value = null;
|
scheduleTestResult.value = null;
|
||||||
scheduleCronDesigner.value = {
|
scheduleCronDesigner.value = {
|
||||||
@@ -788,6 +789,7 @@ const openScheduleEditModal = async (task: ScheduleTask) => {
|
|||||||
api_method: cfg.external_api?.method || 'POST',
|
api_method: cfg.external_api?.method || 'POST',
|
||||||
api_headers_str: cfg.external_api?.headers ? JSON.stringify(cfg.external_api.headers, null, 2) : '{}',
|
api_headers_str: cfg.external_api?.headers ? JSON.stringify(cfg.external_api.headers, null, 2) : '{}',
|
||||||
api_body_template: cfg.external_api?.body_template || '',
|
api_body_template: cfg.external_api?.body_template || '',
|
||||||
|
dify_system_prompt: cfg.dify_system_prompt || '',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
@@ -815,6 +817,7 @@ const openScheduleEditModal = async (task: ScheduleTask) => {
|
|||||||
api_method: 'POST',
|
api_method: 'POST',
|
||||||
api_headers_str: '{}',
|
api_headers_str: '{}',
|
||||||
api_body_template: '',
|
api_body_template: '',
|
||||||
|
dify_system_prompt: '',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -856,6 +859,11 @@ const formatDateTime = (iso?: string | null) => {
|
|||||||
|
|
||||||
const expandedScheduleRunId = ref<number | null>(null);
|
const expandedScheduleRunId = ref<number | null>(null);
|
||||||
|
|
||||||
|
const expandedScheduleRun = computed(() => {
|
||||||
|
if (!expandedScheduleRunId.value) return null;
|
||||||
|
return filteredScheduleRuns.value.find((x) => x.id === expandedScheduleRunId.value) || null;
|
||||||
|
});
|
||||||
|
|
||||||
const stepLabelMap: Record<string, string> = {
|
const stepLabelMap: Record<string, string> = {
|
||||||
fetch_srm: t('admin.schedule.step.fetchSrm'),
|
fetch_srm: t('admin.schedule.step.fetchSrm'),
|
||||||
call_dify: t('admin.schedule.step.callDify'),
|
call_dify: t('admin.schedule.step.callDify'),
|
||||||
@@ -992,6 +1000,7 @@ const scheduleSqlEditForm = ref({
|
|||||||
api_method: 'POST',
|
api_method: 'POST',
|
||||||
api_headers_str: '{}',
|
api_headers_str: '{}',
|
||||||
api_body_template: '',
|
api_body_template: '',
|
||||||
|
dify_system_prompt: '',
|
||||||
});
|
});
|
||||||
const scheduleSqlSaving = ref(false); void scheduleSqlSaving;
|
const scheduleSqlSaving = ref(false); void scheduleSqlSaving;
|
||||||
const scheduleTestLoading = ref(false);
|
const scheduleTestLoading = ref(false);
|
||||||
@@ -1019,6 +1028,12 @@ const handleTestScheduleSql = async () => {
|
|||||||
|
|
||||||
const scheduleNotifyDropdownOpen = ref(false);
|
const scheduleNotifyDropdownOpen = ref(false);
|
||||||
|
|
||||||
|
watch(() => scheduleCreateForm.value.dify_agent_id, (agentId) => {
|
||||||
|
if (!agentId) {
|
||||||
|
scheduleSqlEditForm.value.dify_system_prompt = '';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
const getUserName = (uid: number) => {
|
const getUserName = (uid: number) => {
|
||||||
const u = users.value.find(x => x.id === uid);
|
const u = users.value.find(x => x.id === uid);
|
||||||
return u ? (u.real_name || u.username) : String(uid);
|
return u ? (u.real_name || u.username) : String(uid);
|
||||||
@@ -1096,6 +1111,7 @@ const createSchedule = async () => {
|
|||||||
headers: apiHeaders,
|
headers: apiHeaders,
|
||||||
body_template: scheduleSqlEditForm.value.api_body_template,
|
body_template: scheduleSqlEditForm.value.api_body_template,
|
||||||
} : undefined,
|
} : undefined,
|
||||||
|
dify_system_prompt: hasAgent ? scheduleSqlEditForm.value.dify_system_prompt : '',
|
||||||
};
|
};
|
||||||
|
|
||||||
scheduleCreateSaving.value = true;
|
scheduleCreateSaving.value = true;
|
||||||
@@ -4644,7 +4660,7 @@ const handlePermissionImport = async (event: Event) => {
|
|||||||
<td class="px-4 py-2.5">
|
<td class="px-4 py-2.5">
|
||||||
<div class="flex items-center">
|
<div class="flex items-center">
|
||||||
<button
|
<button
|
||||||
v-if="r.step_logs && r.step_logs.length > 0"
|
v-if="(r.step_logs && r.step_logs.length > 0) || r.dify_execution_snapshot"
|
||||||
@click="expandedScheduleRunId = expandedScheduleRunId === r.id ? null : r.id"
|
@click="expandedScheduleRunId = expandedScheduleRunId === r.id ? null : r.id"
|
||||||
class="inline-flex items-center gap-1 rounded-lg border border-blue-200 px-2 py-1 text-xs font-medium text-blue-600 transition-colors hover:bg-blue-50"
|
class="inline-flex items-center gap-1 rounded-lg border border-blue-200 px-2 py-1 text-xs font-medium text-blue-600 transition-colors hover:bg-blue-50"
|
||||||
>
|
>
|
||||||
@@ -4658,17 +4674,49 @@ const handlePermissionImport = async (event: Event) => {
|
|||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
<tr
|
<tr
|
||||||
v-if="expandedScheduleRunId && filteredScheduleRuns.find(x => x.id === expandedScheduleRunId)"
|
v-if="expandedScheduleRun"
|
||||||
:key="'expanded-' + expandedScheduleRunId"
|
:key="'expanded-' + expandedScheduleRunId"
|
||||||
>
|
>
|
||||||
<td colspan="10" class="px-4 py-3 bg-slate-50/60">
|
<td colspan="10" class="px-4 py-3 bg-slate-50/60">
|
||||||
|
<div class="space-y-3">
|
||||||
|
<div
|
||||||
|
v-if="expandedScheduleRun.dify_execution_snapshot"
|
||||||
|
class="rounded-xl border border-indigo-200 bg-indigo-50/50 p-3"
|
||||||
|
>
|
||||||
|
<div class="mb-2 flex items-center justify-between">
|
||||||
|
<h5 class="text-xs font-bold uppercase text-indigo-800">Dify 执行快照(审计)</h5>
|
||||||
|
<span class="text-[10px] text-indigo-600/80">
|
||||||
|
{{ expandedScheduleRun.dify_execution_snapshot.captured_at || '-' }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div v-if="expandedScheduleRun.dify_execution_snapshot.dify_enabled" class="space-y-2 text-xs text-slate-700">
|
||||||
|
<div>
|
||||||
|
<span class="font-semibold text-slate-500">Agent:</span>
|
||||||
|
{{ expandedScheduleRun.dify_execution_snapshot.dify_agent_name || '-' }}
|
||||||
|
<span class="text-slate-400">(ID: {{ expandedScheduleRun.dify_execution_snapshot.dify_agent_id ?? '-' }})</span>
|
||||||
|
</div>
|
||||||
|
<div v-if="expandedScheduleRun.dify_execution_snapshot.dify_app_id">
|
||||||
|
<span class="font-semibold text-slate-500">Dify App ID:</span>
|
||||||
|
{{ expandedScheduleRun.dify_execution_snapshot.dify_app_id }}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span class="mb-1 block font-semibold text-slate-500">System Prompt:</span>
|
||||||
|
<pre
|
||||||
|
v-if="expandedScheduleRun.dify_execution_snapshot.dify_system_prompt"
|
||||||
|
class="max-h-[240px] overflow-auto whitespace-pre-wrap rounded-lg border border-indigo-100 bg-white p-3 font-mono text-[11px] leading-relaxed text-slate-800"
|
||||||
|
>{{ expandedScheduleRun.dify_execution_snapshot.dify_system_prompt }}</pre>
|
||||||
|
<span v-else class="text-slate-400">(未配置,使用 Dify 编排内默认提示词)</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div v-else class="text-xs text-slate-500">本次执行未启用 Dify Agent</div>
|
||||||
|
</div>
|
||||||
<div class="space-y-2">
|
<div class="space-y-2">
|
||||||
<div class="flex items-center justify-between mb-2">
|
<div class="flex items-center justify-between mb-2">
|
||||||
<h5 class="text-xs font-bold text-slate-600 uppercase">{{ $t('admin.schedule.runLogs') }}</h5>
|
<h5 class="text-xs font-bold text-slate-600 uppercase">{{ $t('admin.schedule.runLogs') }}</h5>
|
||||||
<span class="text-xs text-slate-400">{{ $t('admin.schedule.stepsCount', { count: filteredScheduleRuns.find(x => x.id === expandedScheduleRunId)?.step_logs?.length || 0 }) }}</span>
|
<span class="text-xs text-slate-400">{{ $t('admin.schedule.stepsCount', { count: expandedScheduleRun.step_logs?.length || 0 }) }}</span>
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
v-for="(log, li) in filteredScheduleRuns.find(x => x.id === expandedScheduleRunId)?.step_logs || []"
|
v-for="(log, li) in expandedScheduleRun.step_logs || []"
|
||||||
:key="li"
|
:key="li"
|
||||||
class="rounded-xl border p-3"
|
class="rounded-xl border p-3"
|
||||||
:class="log.status === 'failed' ? 'border-rose-200 bg-rose-50/40' : 'border-slate-200 bg-white'"
|
:class="log.status === 'failed' ? 'border-rose-200 bg-rose-50/40' : 'border-slate-200 bg-white'"
|
||||||
@@ -4688,6 +4736,7 @@ const handlePermissionImport = async (event: Event) => {
|
|||||||
</details>
|
</details>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
</tbody>
|
</tbody>
|
||||||
@@ -5703,6 +5752,29 @@ const handlePermissionImport = async (event: Event) => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div
|
||||||
|
v-if="testRunResult.dify_execution_snapshot"
|
||||||
|
class="rounded-xl border border-indigo-200 bg-indigo-50/50 p-3"
|
||||||
|
>
|
||||||
|
<h4 class="mb-2 text-sm font-bold text-indigo-900">Dify 执行快照(审计)</h4>
|
||||||
|
<div v-if="testRunResult.dify_execution_snapshot.dify_enabled" class="space-y-2 text-xs text-slate-700">
|
||||||
|
<div>
|
||||||
|
<span class="font-semibold text-slate-500">Agent:</span>
|
||||||
|
{{ testRunResult.dify_execution_snapshot.dify_agent_name || '-' }}
|
||||||
|
(ID: {{ testRunResult.dify_execution_snapshot.dify_agent_id ?? '-' }})
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span class="mb-1 block font-semibold text-slate-500">System Prompt:</span>
|
||||||
|
<pre
|
||||||
|
v-if="testRunResult.dify_execution_snapshot.dify_system_prompt"
|
||||||
|
class="max-h-[200px] overflow-auto whitespace-pre-wrap rounded-lg border border-indigo-100 bg-white p-3 font-mono text-[11px] text-slate-800"
|
||||||
|
>{{ testRunResult.dify_execution_snapshot.dify_system_prompt }}</pre>
|
||||||
|
<span v-else class="text-slate-400">(未配置)</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div v-else class="text-xs text-slate-500">本次测试未启用 Dify</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<h4 class="text-sm font-bold text-slate-700 mb-2">{{ $t('admin.schedule.testRun.stepLogs') }}</h4>
|
<h4 class="text-sm font-bold text-slate-700 mb-2">{{ $t('admin.schedule.testRun.stepLogs') }}</h4>
|
||||||
<div class="space-y-2">
|
<div class="space-y-2">
|
||||||
@@ -6018,6 +6090,18 @@ const handlePermissionImport = async (event: Event) => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div v-if="scheduleCreateForm.dify_agent_id" class="rounded-2xl border border-indigo-200 bg-indigo-50/40 p-4">
|
||||||
|
<div class="mb-2">
|
||||||
|
<label class="block text-sm font-medium text-slate-700">Dify System Prompt</label>
|
||||||
|
<p class="mt-1 text-xs text-slate-500">仅在启用 Dify Agent 时可配置。保存后将作为 <code class="rounded bg-white px-1 py-0.5 text-indigo-700">system_prompt</code> 传入 Workflow;编排中 LLM 节点需引用该变量。</p>
|
||||||
|
</div>
|
||||||
|
<textarea
|
||||||
|
v-model="scheduleSqlEditForm.dify_system_prompt"
|
||||||
|
class="w-full min-h-[140px] rounded-xl border border-indigo-200 bg-white p-3 text-sm leading-relaxed text-slate-700 font-mono focus:border-indigo-300 focus:outline-none focus:ring-1 focus:ring-indigo-200 resize-y"
|
||||||
|
placeholder="例如:你是物料合规判定助手。根据 record 中的检测数据判定是否合格,仅返回 JSON:dify_result(合格/不合格/人工判定)与 dify_message。"
|
||||||
|
></textarea>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="rounded-2xl border border-slate-200 bg-slate-50/40 p-4">
|
<div class="rounded-2xl border border-slate-200 bg-slate-50/40 p-4">
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<h4 class="text-base font-bold text-slate-900">{{ $t('admin.schedule.form.cronTitle') }}</h4>
|
<h4 class="text-base font-bold text-slate-900">{{ $t('admin.schedule.form.cronTitle') }}</h4>
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ import { useMessage } from '../composables/useMessage';
|
|||||||
import { useIsMobile } from '../composables/useIsMobile';
|
import { useIsMobile } from '../composables/useIsMobile';
|
||||||
import { useTheme } from '../composables/useTheme';
|
import { useTheme } from '../composables/useTheme';
|
||||||
import { getAuthHeaders, getStoredAuthUser, clearAuthUser } from '../utils/auth';
|
import { getAuthHeaders, getStoredAuthUser, clearAuthUser } from '../utils/auth';
|
||||||
|
import { copyTextToClipboard } from '../utils/clipboard';
|
||||||
|
|
||||||
const { t, locale } = useI18n();
|
const { t, locale } = useI18n();
|
||||||
const { appliedTheme, toggleLightDark } = useTheme();
|
const { appliedTheme, toggleLightDark } = useTheme();
|
||||||
@@ -1613,16 +1614,29 @@ const confirmLeaveSubmission = async (msg: any) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const copyToClipboard = async (text: string, index: number) => {
|
const getMessageCopyText = (msg: { role?: string; content?: string; type?: string }) => {
|
||||||
try {
|
const content = String(msg?.content ?? '').trim();
|
||||||
await navigator.clipboard.writeText(text);
|
if (content) return content;
|
||||||
|
return '';
|
||||||
|
};
|
||||||
|
|
||||||
|
const copyToClipboard = async (msg: { role?: string; content?: string; type?: string }, index: number) => {
|
||||||
|
const text = getMessageCopyText(msg);
|
||||||
|
if (!text) {
|
||||||
|
showMessageDialog('warning', t('chat.actions.copyEmpty'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ok = await copyTextToClipboard(text);
|
||||||
|
if (ok) {
|
||||||
copiedIndex.value = index;
|
copiedIndex.value = index;
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
copiedIndex.value = null;
|
copiedIndex.value = null;
|
||||||
}, 2000);
|
}, 2000);
|
||||||
} catch (err) {
|
return;
|
||||||
console.error('Failed to copy:', err);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
showMessageDialog('error', t('chat.actions.copyFailed'));
|
||||||
};
|
};
|
||||||
|
|
||||||
const regenerate = () => {
|
const regenerate = () => {
|
||||||
@@ -2364,7 +2378,8 @@ const showChatRating = ref(false);
|
|||||||
:class="msg.role === 'user' ? 'justify-end text-slate-500' : 'justify-start text-slate-500'"
|
:class="msg.role === 'user' ? 'justify-end text-slate-500' : 'justify-start text-slate-500'"
|
||||||
>
|
>
|
||||||
<button
|
<button
|
||||||
@click="copyToClipboard(msg.content, index)"
|
type="button"
|
||||||
|
@click.stop="copyToClipboard(msg, index)"
|
||||||
class="rounded-md p-1.5 text-xs transition-colors hover:bg-slate-100 dark:hover:bg-slate-800"
|
class="rounded-md p-1.5 text-xs transition-colors hover:bg-slate-100 dark:hover:bg-slate-800"
|
||||||
:title="$t('chat.actions.copy')"
|
:title="$t('chat.actions.copy')"
|
||||||
>
|
>
|
||||||
@@ -2374,14 +2389,16 @@ const showChatRating = ref(false);
|
|||||||
|
|
||||||
<template v-if="msg.role === 'user'">
|
<template v-if="msg.role === 'user'">
|
||||||
<button
|
<button
|
||||||
@click="input = msg.content"
|
type="button"
|
||||||
|
@click.stop="input = msg.content"
|
||||||
class="rounded-md p-1.5 text-xs transition-colors hover:bg-slate-100 dark:hover:bg-slate-800"
|
class="rounded-md p-1.5 text-xs transition-colors hover:bg-slate-100 dark:hover:bg-slate-800"
|
||||||
:title="$t('chat.actions.edit')"
|
:title="$t('chat.actions.edit')"
|
||||||
>
|
>
|
||||||
<Edit2 class="h-3.5 w-3.5" />
|
<Edit2 class="h-3.5 w-3.5" />
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
@click="handleSend(msg.content)"
|
type="button"
|
||||||
|
@click.stop="handleSend(msg.content)"
|
||||||
class="rounded-md p-1.5 text-xs transition-colors hover:bg-slate-100 dark:hover:bg-slate-800"
|
class="rounded-md p-1.5 text-xs transition-colors hover:bg-slate-100 dark:hover:bg-slate-800"
|
||||||
:title="$t('chat.actions.resend')"
|
:title="$t('chat.actions.resend')"
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -102,9 +102,11 @@ const openDeleteConfirmDialog = (
|
|||||||
message: string,
|
message: string,
|
||||||
onConfirm: () => Promise<void> | void
|
onConfirm: () => Promise<void> | void
|
||||||
) => {
|
) => {
|
||||||
|
console.log('[KB] openDeleteConfirmDialog', message);
|
||||||
deleteConfirmMessage.value = message;
|
deleteConfirmMessage.value = message;
|
||||||
pendingDeleteAction = onConfirm;
|
pendingDeleteAction = onConfirm;
|
||||||
showDeleteConfirmDialog.value = true;
|
showDeleteConfirmDialog.value = true;
|
||||||
|
console.log('[KB] showDeleteConfirmDialog set to', showDeleteConfirmDialog.value);
|
||||||
};
|
};
|
||||||
|
|
||||||
const closeDeleteConfirmDialog = () => {
|
const closeDeleteConfirmDialog = () => {
|
||||||
@@ -115,7 +117,13 @@ const closeDeleteConfirmDialog = () => {
|
|||||||
|
|
||||||
const handleDeleteConfirm = async () => {
|
const handleDeleteConfirm = async () => {
|
||||||
if (!pendingDeleteAction) return;
|
if (!pendingDeleteAction) return;
|
||||||
|
try {
|
||||||
await pendingDeleteAction();
|
await pendingDeleteAction();
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[deleteConfirm]', err);
|
||||||
|
feedback.value = String(err) || '操作失败';
|
||||||
|
feedbackType.value = 'error';
|
||||||
|
}
|
||||||
closeDeleteConfirmDialog();
|
closeDeleteConfirmDialog();
|
||||||
};
|
};
|
||||||
const selectedDocument = computed(() => documents.value.find((item) => item.id === selectedDocumentId.value) || null);
|
const selectedDocument = computed(() => documents.value.find((item) => item.id === selectedDocumentId.value) || null);
|
||||||
@@ -1110,6 +1118,7 @@ const toggleSelectAllFiltered = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleDeleteDocument = async (doc: KbDocumentItem) => {
|
const handleDeleteDocument = async (doc: KbDocumentItem) => {
|
||||||
|
console.log('[KB] handleDeleteDocument called', doc.id, doc.title);
|
||||||
openDeleteConfirmDialog(`确认删除文档「${getDocumentDisplayTitle(doc)}」吗?`, async () => {
|
openDeleteConfirmDialog(`确认删除文档「${getDocumentDisplayTitle(doc)}」吗?`, async () => {
|
||||||
const result = await deleteKbDocument(doc.id);
|
const result = await deleteKbDocument(doc.id);
|
||||||
if (!result.ok) {
|
if (!result.ok) {
|
||||||
@@ -1161,6 +1170,7 @@ const handleBatchSync = async () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleBatchDelete = async () => {
|
const handleBatchDelete = async () => {
|
||||||
|
console.log('[KB] handleBatchDelete called, selected:', selectedDocuments.value.length);
|
||||||
if (!selectedDocuments.value.length) {
|
if (!selectedDocuments.value.length) {
|
||||||
feedback.value = '请先选择要批量删除的文档';
|
feedback.value = '请先选择要批量删除的文档';
|
||||||
feedbackType.value = 'error';
|
feedbackType.value = 'error';
|
||||||
@@ -2581,11 +2591,12 @@ onUnmounted(() => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
<DeleteConfirmDialog
|
<DeleteConfirmDialog
|
||||||
v-model="showDeleteConfirmDialog"
|
v-model="showDeleteConfirmDialog"
|
||||||
:message="deleteConfirmMessage"
|
:message="deleteConfirmMessage"
|
||||||
@confirm="handleDeleteConfirm"
|
@confirm="handleDeleteConfirm"
|
||||||
@cancel="closeDeleteConfirmDialog"
|
@cancel="closeDeleteConfirmDialog"
|
||||||
/>
|
/>
|
||||||
</div>
|
|
||||||
</template>
|
</template>
|
||||||
Reference in new issue
Block a user