fix: repo sync error
This commit is contained in:
@@ -13,6 +13,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/engigu/baihu-panel/internal/services/tasks"
|
||||
"github.com/engigu/baihu-panel/internal/utils"
|
||||
)
|
||||
|
||||
@@ -31,6 +32,9 @@ type Config struct {
|
||||
Blacklist string // Script filter blacklist keywords, vertical line separated
|
||||
Dependence string // Script dependence file keywords, vertical line separated
|
||||
Extensions string // Script file extensions, vertical line separated
|
||||
TaskID string
|
||||
TaskLanguages string
|
||||
TaskTimeout int
|
||||
}
|
||||
|
||||
func Run(args []string) {
|
||||
@@ -50,26 +54,38 @@ func Run(args []string) {
|
||||
fs.StringVar(&cfg.Blacklist, "blacklist", "", "Script filter blacklist keywords (| separated)")
|
||||
fs.StringVar(&cfg.Dependence, "dependence", "", "Script dependence keywords (| separated)")
|
||||
fs.StringVar(&cfg.Extensions, "extensions", "", "Script extensions (| separated)")
|
||||
fs.StringVar(&cfg.TaskID, "task-id", "", "Task ID for metadata")
|
||||
fs.StringVar(&cfg.TaskLanguages, "task-langs", "", "Configured languages (JSON)")
|
||||
fs.StringVar(&cfg.TaskID, "repo-task-id", "", "Original Task ID")
|
||||
fs.IntVar(&cfg.TaskTimeout, "task-timeout", 30, "Task timeout (minutes)")
|
||||
|
||||
fs.Parse(args)
|
||||
|
||||
if cfg.SourceURL == "" || cfg.TargetPath == "" {
|
||||
fmt.Println("错误: 缺少 --source-url 或 --target-path 参数")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
fmt.Printf("参数: %s\n", strings.Join(args, " "))
|
||||
fmt.Println("========================================")
|
||||
fmt.Println(" 仓库同步任务开始 ")
|
||||
fmt.Println("========================================")
|
||||
fmt.Printf("[1/3] 解析同步参数: %s\n", strings.Join(args, " "))
|
||||
|
||||
if cfg.SourceType == "git" {
|
||||
fmt.Printf("[2/3] 正在通过 Git 同步内容...\n")
|
||||
syncGit(cfg)
|
||||
} else {
|
||||
fmt.Printf("[2/3] 正在通过 URL 下载内容...\n")
|
||||
syncURL(cfg)
|
||||
}
|
||||
|
||||
// 执行脚本过滤(仅限 git 模式,url 加载通常为单文件,暂不处理过滤)
|
||||
if cfg.SourceType == "git" {
|
||||
fmt.Printf("[3/3] 正在执行脚本过滤与文件清理...\n")
|
||||
filterFiles(cfg)
|
||||
|
||||
if cfg.TaskID != "" {
|
||||
tasks.ParseRepoScriptsAndAddCron(nil, cfg.TaskID, os.Stdout)
|
||||
}
|
||||
}
|
||||
fmt.Println("\n========================================")
|
||||
fmt.Println(" 仓库同步任务完成 ")
|
||||
fmt.Println("========================================")
|
||||
}
|
||||
|
||||
func syncGit(cfg Config) {
|
||||
@@ -692,5 +708,6 @@ func cleanEmptyDirs(root string) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -29,17 +29,22 @@ func New() *App {
|
||||
return app
|
||||
}
|
||||
|
||||
// InitBasic 初始化基础环境(配置和数据库),不启动后台服务和路由
|
||||
func InitBasic() *App {
|
||||
app := &App{}
|
||||
utils.InitRuntime()
|
||||
app.initConfig()
|
||||
|
||||
// 自动加载配置 (内部会自动处理 BH_CONFIG_PATH 环境变量与默认路径的优先级)
|
||||
app.initConfigWithPath("")
|
||||
app.initDatabase()
|
||||
return app
|
||||
}
|
||||
|
||||
func (a *App) initConfig() {
|
||||
cfg, err := services.LoadConfig(constant.ConfigPath)
|
||||
a.initConfigWithPath(constant.ConfigPath)
|
||||
}
|
||||
|
||||
func (a *App) initConfigWithPath(path string) {
|
||||
cfg, err := services.LoadConfig(path)
|
||||
if err != nil {
|
||||
logger.Fatalf("Failed to load config: %v", err)
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package controllers
|
||||
import (
|
||||
"encoding/json"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/engigu/baihu-panel/internal/constant"
|
||||
"github.com/engigu/baihu-panel/internal/models"
|
||||
@@ -39,6 +40,9 @@ func resolveWorkDir(workDir string) string {
|
||||
return absPath
|
||||
}
|
||||
// 如果已经是绝对路径,直接返回
|
||||
if strings.HasPrefix(workDir, "$SCRIPTS_DIR$") {
|
||||
return workDir
|
||||
}
|
||||
if filepath.IsAbs(workDir) {
|
||||
return workDir
|
||||
}
|
||||
|
||||
@@ -67,6 +67,15 @@ func getEnvInt(key string, target *int) {
|
||||
}
|
||||
|
||||
func LoadConfig(path string) (*AppConfig, error) {
|
||||
// 路径发现逻辑:参数优先 -> 环境变量优先 -> 默认常量
|
||||
if path == "" {
|
||||
if envPath := os.Getenv("BH_CONFIG_PATH"); envPath != "" {
|
||||
path = envPath
|
||||
} else {
|
||||
path = constant.ConfigPath
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化默认配置
|
||||
Config = &AppConfig{
|
||||
Server: ServerConfig{
|
||||
|
||||
@@ -241,9 +241,7 @@ func (h *ServerSchedulerHandler) OnTaskCompleted(req *executor.ExecutionRequest,
|
||||
// 处理任务完成(更新统计、清理旧日志等)
|
||||
h.es.taskLogService.ProcessTaskCompletion(taskLog)
|
||||
|
||||
if task.Type == constant.TaskTypeRepo && result.Status == constant.TaskStatusSuccess {
|
||||
go ParseRepoScriptsAndAddCron(h.es, task)
|
||||
}
|
||||
|
||||
|
||||
// 更新内存缓冲
|
||||
h.es.UpdateResult(*result)
|
||||
@@ -966,6 +964,13 @@ func (es *ExecutorService) BuildRepoCommand(task *models.Task) (string, string)
|
||||
if config.Extensions != "" {
|
||||
args = append(args, "--extensions", config.Extensions)
|
||||
}
|
||||
|
||||
// 传递任务 ID,以便 reposync 内部直接处理脚本注册并输出日志
|
||||
args = append(args, "--task-id", task.ID)
|
||||
args = append(args, "--task-timeout", fmt.Sprintf("%d", task.Timeout))
|
||||
if langData, err := json.Marshal(task.Languages); err == nil {
|
||||
args = append(args, "--task-langs", string(langData))
|
||||
}
|
||||
|
||||
// 为了防止 shell 解释特殊字符(如 |),对每个参数进行转义/加引号
|
||||
quotedArgs := make([]string, len(args))
|
||||
@@ -974,7 +979,8 @@ func (es *ExecutorService) BuildRepoCommand(task *models.Task) (string, string)
|
||||
quotedArgs[i] = "'" + strings.ReplaceAll(arg, "'", "'\\''") + "'"
|
||||
}
|
||||
|
||||
return "'" + strings.ReplaceAll(exePath, "'", "'\\''") + "' " + strings.Join(quotedArgs, " "), filepath.Dir(exePath)
|
||||
cmdStr := "'" + strings.ReplaceAll(exePath, "'", "'\\''") + "' " + strings.Join(quotedArgs, " ")
|
||||
return buildRepoCommandEnvPrefix()+cmdStr, filepath.Dir(exePath)
|
||||
}
|
||||
|
||||
// loadEnvVars 加载环境变量,支持全局注入及重名合并
|
||||
@@ -1007,6 +1013,45 @@ func (es *ExecutorService) loadEnvVars(taskID string, envIDs string) []string {
|
||||
}
|
||||
|
||||
func (es *ExecutorService) ResolvePath(path string) string {
|
||||
absScriptsDir, _ := filepath.Abs(constant.ScriptsWorkDir)
|
||||
absScriptsDir := resolveAbsScriptsDir()
|
||||
return strings.ReplaceAll(path, "$SCRIPTS_DIR$", absScriptsDir)
|
||||
}
|
||||
|
||||
func buildRepoCommandEnvPrefix() string {
|
||||
absConfig, err := filepath.Abs(constant.ConfigPath)
|
||||
if err != nil {
|
||||
absConfig = constant.ConfigPath
|
||||
}
|
||||
|
||||
absScriptsDir := resolveAbsScriptsDir()
|
||||
return "BH_CONFIG_PATH='" + strings.ReplaceAll(absConfig, "'", "'\\''") + "' BH_SCRIPTS_DIR='" + strings.ReplaceAll(absScriptsDir, "'", "'\\''") + "' "
|
||||
}
|
||||
|
||||
func resolveAbsScriptsDir() string {
|
||||
if scriptsDir := os.Getenv("BH_SCRIPTS_DIR"); scriptsDir != "" {
|
||||
if filepath.IsAbs(scriptsDir) {
|
||||
return filepath.Clean(scriptsDir)
|
||||
}
|
||||
if absScriptsDir, err := filepath.Abs(scriptsDir); err == nil {
|
||||
return absScriptsDir
|
||||
}
|
||||
return filepath.Clean(scriptsDir)
|
||||
}
|
||||
|
||||
if configPath := os.Getenv("BH_CONFIG_PATH"); configPath != "" {
|
||||
if !filepath.IsAbs(configPath) {
|
||||
if absConfigPath, err := filepath.Abs(configPath); err == nil {
|
||||
configPath = absConfigPath
|
||||
}
|
||||
}
|
||||
|
||||
projectRoot := filepath.Dir(filepath.Dir(configPath))
|
||||
return filepath.Clean(filepath.Join(projectRoot, constant.ScriptsWorkDir))
|
||||
}
|
||||
|
||||
if absScriptsDir, err := filepath.Abs(constant.ScriptsWorkDir); err == nil {
|
||||
return absScriptsDir
|
||||
}
|
||||
|
||||
return filepath.Clean(constant.ScriptsWorkDir)
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -23,8 +24,25 @@ var (
|
||||
)
|
||||
|
||||
// ParseRepoScriptsAndAddCron scans the repo dir for scripts, parses cron and env comments, and registers tasks
|
||||
func ParseRepoScriptsAndAddCron(es *ExecutorService, repoTask *models.Task) {
|
||||
if repoTask == nil || repoTask.Type != constant.TaskTypeRepo {
|
||||
func ParseRepoScriptsAndAddCron(es *ExecutorService, taskID string, logWriter io.Writer) {
|
||||
// help print logs to writer if provided
|
||||
log := func(format string, a ...interface{}) {
|
||||
msg := fmt.Sprintf(format, a...)
|
||||
if !strings.HasSuffix(msg, "\n") {
|
||||
msg += "\n"
|
||||
}
|
||||
if logWriter != nil {
|
||||
logWriter.Write([]byte(msg))
|
||||
}
|
||||
// logger.Info(msg)
|
||||
}
|
||||
|
||||
var repoTask models.Task
|
||||
if err := database.DB.Where("id = ?", taskID).First(&repoTask).Error; err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if repoTask.Type != constant.TaskTypeRepo {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -41,10 +59,13 @@ func ParseRepoScriptsAndAddCron(es *ExecutorService, repoTask *models.Task) {
|
||||
targetPath := repoCfg.TargetPath
|
||||
if targetPath == "" {
|
||||
targetPath = repoTask.WorkDir
|
||||
} else if !filepath.IsAbs(targetPath) {
|
||||
targetPath = filepath.Join(resolveAbsScriptsDir(), targetPath)
|
||||
}
|
||||
if targetPath == "" {
|
||||
return
|
||||
}
|
||||
targetPath = filepath.Clean(targetPath)
|
||||
|
||||
// We might have appended a repo id to targetPath
|
||||
repoId := utils.GetRepoIdentifier(repoCfg.SourceURL, repoCfg.Branch)
|
||||
@@ -81,7 +102,13 @@ func ParseRepoScriptsAndAddCron(es *ExecutorService, repoTask *models.Task) {
|
||||
}
|
||||
}
|
||||
|
||||
log("\n----------------------------------------")
|
||||
log(" 开始扫描脚本并自动注册定时任务 ")
|
||||
log("----------------------------------------")
|
||||
|
||||
foundSourceIDs := make(map[string]bool)
|
||||
newTaskCount := 0
|
||||
updateTaskCount := 0
|
||||
|
||||
filepath.WalkDir(targetPath, func(path string, d fs.DirEntry, err error) error {
|
||||
if err != nil || d.IsDir() {
|
||||
@@ -234,7 +261,8 @@ func ParseRepoScriptsAndAddCron(es *ExecutorService, repoTask *models.Task) {
|
||||
|
||||
if taskName != "" && taskCron != "" {
|
||||
// 获取脚本相对于数据目录的路径
|
||||
absScriptsDir, _ := filepath.Abs(constant.ScriptsWorkDir)
|
||||
absScriptsDir := resolveAbsScriptsDir()
|
||||
absTargetPath, _ := filepath.Abs(targetPath)
|
||||
absPath, _ := filepath.Abs(path)
|
||||
|
||||
// 计算 SourceID: 相对于脚本目录的完整路径,并清洗特殊符号
|
||||
@@ -245,9 +273,11 @@ func ParseRepoScriptsAndAddCron(es *ExecutorService, repoTask *models.Task) {
|
||||
displayPath := path
|
||||
displayWorkDir := targetPath
|
||||
if strings.HasPrefix(absPath, absScriptsDir) {
|
||||
displayPath = filepath.Join("$SCRIPTS_DIR$", relPath)
|
||||
if relCommandPath, err := filepath.Rel(absTargetPath, absPath); err == nil && relCommandPath != "" {
|
||||
displayPath = filepath.Clean(relCommandPath)
|
||||
}
|
||||
// 获取目录路径
|
||||
relDir, _ := filepath.Rel(absScriptsDir, targetPath)
|
||||
relDir, _ := filepath.Rel(absScriptsDir, absTargetPath)
|
||||
displayWorkDir = filepath.Join("$SCRIPTS_DIR$", relDir)
|
||||
}
|
||||
|
||||
@@ -259,15 +289,12 @@ func ParseRepoScriptsAndAddCron(es *ExecutorService, repoTask *models.Task) {
|
||||
|
||||
// See if task exists (优先通过 SourceID 匹配)
|
||||
var existing models.Task
|
||||
err := database.DB.Where("source_id = ?", sourceID).First(&existing).Error
|
||||
if err != nil {
|
||||
// 降级使用 command + tag 匹配 (兼容旧数据)
|
||||
err = database.DB.Where("command = ? AND tags LIKE ?", command, "%"+tag+"%").First(&existing).Error
|
||||
}
|
||||
tx := database.DB.Where("source_id = ? AND repo_task_id = ?", sourceID, repoTask.ID).Limit(1).Find(&existing)
|
||||
|
||||
if err == nil {
|
||||
if tx.RowsAffected > 0 {
|
||||
// update
|
||||
existing.Name = taskName
|
||||
existing.Command = models.BigText(command)
|
||||
existing.Schedule = normalizeCron(taskCron)
|
||||
existing.Languages = repoTask.Languages
|
||||
existing.SourceID = sourceID
|
||||
@@ -286,6 +313,8 @@ func ParseRepoScriptsAndAddCron(es *ExecutorService, repoTask *models.Task) {
|
||||
if existing.Enabled && es != nil {
|
||||
es.AddCronTask(&existing)
|
||||
}
|
||||
log("[更新] 任务: %s (%s)", taskName, filename)
|
||||
updateTaskCount++
|
||||
foundSourceIDs[sourceID] = true
|
||||
} else {
|
||||
// create new
|
||||
@@ -310,6 +339,8 @@ func ParseRepoScriptsAndAddCron(es *ExecutorService, repoTask *models.Task) {
|
||||
if es != nil {
|
||||
es.AddCronTask(newTask)
|
||||
}
|
||||
log("[新增] 任务: %s (%s)", taskName, filename)
|
||||
newTaskCount++
|
||||
foundSourceIDs[sourceID] = true
|
||||
}
|
||||
}
|
||||
@@ -318,10 +349,13 @@ func ParseRepoScriptsAndAddCron(es *ExecutorService, repoTask *models.Task) {
|
||||
})
|
||||
|
||||
// 清理该仓库任务下不再存在的旧脚本任务
|
||||
deletedTaskCount := 0
|
||||
var oldTasks []models.Task
|
||||
if err := database.DB.Where("repo_task_id = ?", repoTask.ID).Find(&oldTasks).Error; err == nil {
|
||||
for _, ot := range oldTasks {
|
||||
if !foundSourceIDs[ot.SourceID] {
|
||||
log("[移除] 脚本已不存在,删除对应任务: %s", ot.Name)
|
||||
deletedTaskCount++
|
||||
if es != nil {
|
||||
if es.taskService != nil {
|
||||
es.taskService.DeleteTask(ot.ID)
|
||||
@@ -334,6 +368,9 @@ func ParseRepoScriptsAndAddCron(es *ExecutorService, repoTask *models.Task) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log("\n扫描完成: [新增 %d] [更新 %d] [移除 %d]", newTaskCount, updateTaskCount, deletedTaskCount)
|
||||
log("----------------------------------------")
|
||||
}
|
||||
|
||||
func sanitizeIdentifier(s string) string {
|
||||
|
||||
@@ -139,6 +139,11 @@ func (l *TinyLog) Write(p []byte) (n int, err error) {
|
||||
return originalInputLen, nil
|
||||
}
|
||||
|
||||
// WriteString 方便地写入字符串
|
||||
func (l *TinyLog) WriteString(s string) (n int, err error) {
|
||||
return l.Write([]byte(s))
|
||||
}
|
||||
|
||||
// Subscribe 返回一个实时接收日志块的通道
|
||||
func (l *TinyLog) Subscribe() chan []byte {
|
||||
l.mu.Lock()
|
||||
|
||||
@@ -52,6 +52,7 @@ func main() {
|
||||
}
|
||||
|
||||
if handler, ok := cmd.Handlers[commandName]; ok {
|
||||
bootstrap.InitBasic() // 启动基础环境(配置和数据库)
|
||||
handler(os.Args[2:])
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { ref, onMounted, computed, watch, nextTick } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { TASK_STATUS } from '@/constants'
|
||||
import { TASK_STATUS, TASK_TYPE } from '@/constants'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import Pagination from '@/components/Pagination.vue'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import {
|
||||
RefreshCw, X, Search, Trash2, Maximize2
|
||||
} from 'lucide-vue-next'
|
||||
import LogViewer from './LogViewer.vue'
|
||||
import Ansi from 'ansi-to-vue3'
|
||||
import {
|
||||
RefreshCw, X, Search, Maximize2, GitBranch, Terminal,
|
||||
CheckCircle2, XCircle, AlertCircle, Ban, Clock, Zap as ZapIcon, Check, Trash2
|
||||
} from 'lucide-vue-next'
|
||||
import { api, type TaskLog } from '@/api'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import {
|
||||
@@ -24,6 +26,7 @@ import {
|
||||
} from '@/components/ui/alert-dialog'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { useSiteSettings } from '@/composables/useSiteSettings'
|
||||
import TextOverflow from '@/components/TextOverflow.vue'
|
||||
|
||||
const route = useRoute()
|
||||
const { pageSize } = useSiteSettings()
|
||||
@@ -36,12 +39,27 @@ const filterStatus = ref<string | undefined>(undefined)
|
||||
const currentPage = ref(1)
|
||||
const total = ref(0)
|
||||
|
||||
const showDeleteDialog = ref(false)
|
||||
const deleteLogId = ref<string | null>(null)
|
||||
let searchTimer: ReturnType<typeof setTimeout> | null = null
|
||||
let durationTimer: ReturnType<typeof setInterval> | null = null
|
||||
|
||||
// 全屏查看
|
||||
const showFullscreen = ref(false)
|
||||
|
||||
// 清除所有日志弹窗
|
||||
const showClearDialog = ref(false)
|
||||
|
||||
let searchTimer: ReturnType<typeof setTimeout> | null = null
|
||||
// 删除单条日志弹窗
|
||||
const showDeleteDialog = ref(false)
|
||||
const deleteLogId = ref<string | null>(null)
|
||||
|
||||
const wsContent = ref('')
|
||||
const isWsLoading = ref(false)
|
||||
let logSocket: WebSocket | null = null
|
||||
|
||||
|
||||
const decompressedOutput = computed(() => {
|
||||
return wsContent.value || '无输出'
|
||||
})
|
||||
|
||||
async function loadLogs() {
|
||||
try {
|
||||
@@ -85,11 +103,126 @@ function handlePageChange(page: number) {
|
||||
}
|
||||
|
||||
async function selectLog(log: TaskLog) {
|
||||
if (logSocket) {
|
||||
logSocket.onopen = null
|
||||
logSocket.onmessage = null
|
||||
logSocket.onerror = null
|
||||
logSocket.onclose = null
|
||||
logSocket.close()
|
||||
}
|
||||
|
||||
// 清理旧定时器
|
||||
if (durationTimer) {
|
||||
clearInterval(durationTimer)
|
||||
durationTimer = null
|
||||
}
|
||||
|
||||
selectedLog.value = log
|
||||
|
||||
// 如果是运行中状态,启动定时器轮询最新日志信息(主要是更新耗时)
|
||||
if (log.status === TASK_STATUS.RUNNING) {
|
||||
const updateLog = async () => {
|
||||
try {
|
||||
const res = await api.logs.get(log.id)
|
||||
if (res && selectedLog.value && selectedLog.value.id === log.id) {
|
||||
// 只更新需要变动的字段
|
||||
selectedLog.value.duration = res.duration
|
||||
// 同步更新列表中的数据
|
||||
const listItem = logs.value.find(l => l.id === log.id)
|
||||
if (listItem) {
|
||||
listItem.duration = res.duration
|
||||
}
|
||||
// 如果状态变了,更新状态并停止轮询
|
||||
if (res.status !== TASK_STATUS.RUNNING) {
|
||||
selectedLog.value.status = res.status
|
||||
selectedLog.value.end_time = res.end_time
|
||||
if (listItem) {
|
||||
listItem.status = res.status
|
||||
listItem.end_time = res.end_time
|
||||
}
|
||||
if (durationTimer) {
|
||||
clearInterval(durationTimer)
|
||||
durationTimer = null
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
durationTimer = setInterval(updateLog, 3000)
|
||||
}
|
||||
|
||||
wsContent.value = ''
|
||||
isWsLoading.value = true
|
||||
|
||||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
|
||||
const host = window.location.host
|
||||
const baseUrl = (window as any).__BASE_URL__ || ''
|
||||
const apiVersion = (window as any).__API_VERSION__ || '/api/v1'
|
||||
const wsUrl = `${protocol}//${host}${baseUrl}${apiVersion}/logs/ws?log_id=${log.id}`
|
||||
|
||||
logSocket = new WebSocket(wsUrl)
|
||||
|
||||
logSocket.onopen = () => {
|
||||
isWsLoading.value = false
|
||||
console.log('[LogWS] Connection opened')
|
||||
}
|
||||
|
||||
logSocket.onmessage = (event) => {
|
||||
isWsLoading.value = false
|
||||
if (log.status !== TASK_STATUS.RUNNING) {
|
||||
wsContent.value = event.data
|
||||
} else {
|
||||
wsContent.value += event.data
|
||||
// 自动滚动到底部
|
||||
nextTick(() => {
|
||||
const pre = document.querySelector('.log-pre')
|
||||
if (pre) pre.scrollTop = pre.scrollHeight
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
logSocket.onerror = (e) => {
|
||||
isWsLoading.value = false
|
||||
console.error('[LogWS] Connection error', e)
|
||||
toast.error('日志连接异常')
|
||||
}
|
||||
|
||||
logSocket.onclose = (e) => {
|
||||
isWsLoading.value = false
|
||||
console.log('[LogWS] Connection closed', e.code, e.reason)
|
||||
}
|
||||
}
|
||||
|
||||
function closeDetail() {
|
||||
if (durationTimer) {
|
||||
clearInterval(durationTimer)
|
||||
durationTimer = null
|
||||
}
|
||||
if (logSocket) {
|
||||
logSocket.onopen = null
|
||||
logSocket.onmessage = null
|
||||
logSocket.onerror = null
|
||||
logSocket.onclose = null
|
||||
logSocket.close()
|
||||
logSocket = null
|
||||
}
|
||||
selectedLog.value = null
|
||||
wsContent.value = ''
|
||||
}
|
||||
|
||||
const isStopping = ref(false)
|
||||
async function stopTask() {
|
||||
if (!selectedLog.value || isStopping.value) return
|
||||
|
||||
try {
|
||||
isStopping.value = true
|
||||
await api.tasks.stop(selectedLog.value.id)
|
||||
toast.success('停止请求已发送')
|
||||
} catch (err: any) {
|
||||
toast.error(err.message || '停止失败')
|
||||
} finally {
|
||||
isStopping.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function formatDuration(ms: number): string {
|
||||
@@ -120,6 +253,7 @@ async function handleDeleteLog() {
|
||||
await api.logs.delete(deleteLogId.value)
|
||||
toast.success('该日志已删除')
|
||||
|
||||
// 如果当前选中的是这条日志,关闭详情页
|
||||
if (selectedLog.value?.id === deleteLogId.value) {
|
||||
closeDetail()
|
||||
}
|
||||
@@ -150,7 +284,12 @@ function getStatusBadgeClass(status: string) {
|
||||
}
|
||||
}
|
||||
|
||||
function getTaskTypeTitle(type: string) {
|
||||
return type === TASK_TYPE.REPO ? '仓库同步' : '普通任务'
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
// 从 URL 读取参数
|
||||
const taskIdParam = route.query.task_id
|
||||
if (taskIdParam) {
|
||||
filterTaskId.value = String(taskIdParam)
|
||||
@@ -161,56 +300,82 @@ onMounted(() => {
|
||||
}
|
||||
loadLogs()
|
||||
})
|
||||
|
||||
// 监听路由变化
|
||||
watch(() => route.query, (newQuery) => {
|
||||
filterTaskId.value = newQuery.task_id ? String(newQuery.task_id) : undefined
|
||||
filterStatus.value = newQuery.status ? String(newQuery.status) : undefined
|
||||
currentPage.value = 1
|
||||
loadLogs()
|
||||
}, { deep: true })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-4 h-full">
|
||||
<!-- 头部工具栏 -->
|
||||
<div class="flex flex-col md:flex-row md:items-center justify-between gap-4 shrink-0 px-1">
|
||||
<div class="flex items-center gap-3">
|
||||
<div class="space-y-6">
|
||||
<div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
|
||||
<div>
|
||||
<h2 class="text-xl sm:text-2xl font-bold tracking-tight">执行历史</h2>
|
||||
<p class="text-muted-foreground text-sm">查看任务执行记录和日志</p>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col sm:flex-row gap-2.5 w-full md:w-auto">
|
||||
<div class="flex items-center gap-2 w-full sm:w-auto">
|
||||
<div class="relative flex-1 sm:flex-none">
|
||||
<Search class="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input v-model="filterKeyword" placeholder="搜索任务名称..." class="h-9 pl-9 w-full sm:w-48 text-sm"
|
||||
@input="handleSearch" />
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="relative flex-1 sm:flex-none">
|
||||
<Search class="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input v-model="filterKeyword" placeholder="搜索任务..." class="h-9 pl-9 w-full sm:w-40 md:w-56 text-sm"
|
||||
@input="handleSearch" />
|
||||
</div>
|
||||
<div class="relative flex-1 sm:flex-none">
|
||||
<Select v-model="filterStatus" @update:model-value="handleStatusChange">
|
||||
<SelectTrigger class="h-9 w-[110px] text-sm shrink-0">
|
||||
<SelectValue placeholder="所有状态" />
|
||||
<SelectTrigger class="h-9 w-full sm:w-28 text-sm">
|
||||
<SelectValue placeholder="状态" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">所有状态</SelectItem>
|
||||
<SelectItem :value="TASK_STATUS.SUCCESS">成功</SelectItem>
|
||||
<SelectItem :value="TASK_STATUS.FAILED">失败</SelectItem>
|
||||
<SelectItem :value="TASK_STATUS.RUNNING">运行中</SelectItem>
|
||||
<SelectItem :value="TASK_STATUS.PENDING">排队中</SelectItem>
|
||||
<SelectItem :value="TASK_STATUS.TIMEOUT">超时</SelectItem>
|
||||
<SelectItem :value="TASK_STATUS.CANCELLED">已取消</SelectItem>
|
||||
<SelectItem value="running">正在运行</SelectItem>
|
||||
<SelectItem value="success">成功</SelectItem>
|
||||
<SelectItem value="failed">失败</SelectItem>
|
||||
<SelectItem value="timeout">超时</SelectItem>
|
||||
<SelectItem value="cancelled">取消</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-2 shrink-0">
|
||||
<Button variant="outline" size="sm" class="h-9 gap-2 shadow-sm text-destructive border-destructive/20 hover:bg-destructive/10" @click="showClearDialog = true">
|
||||
<Trash2 class="h-4 w-4" />
|
||||
<span>清空日志</span>
|
||||
</Button>
|
||||
<Button variant="outline" size="icon" class="h-9 w-9 shadow-sm" @click="loadLogs" title="刷新">
|
||||
<RefreshCw class="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<Button variant="outline" size="icon" class="h-9 w-9 shrink-0" @click="loadLogs" title="刷新">
|
||||
<RefreshCw class="h-4 w-4" />
|
||||
</Button>
|
||||
<Button variant="outline"
|
||||
class="h-9 px-4 shrink-0 text-sm text-destructive hover:bg-destructive/10 hover:text-destructive border-destructive/20"
|
||||
@click="showClearDialog = true">
|
||||
<Trash2 class="h-4 w-4 sm:mr-2" /> <span class="hidden sm:inline" style="padding-left: 2px;">清空日志</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 主体区域 -->
|
||||
<div class="flex-1 flex flex-col lg:flex-row gap-4 min-h-0">
|
||||
<div class="flex flex-col lg:flex-row gap-4" style="height: 520px;">
|
||||
<!-- 日志列表 -->
|
||||
<div class="flex-1 min-w-0 rounded-lg border bg-card overflow-hidden flex flex-col">
|
||||
<div class="divide-y flex-1 overflow-y-auto">
|
||||
<!-- 小屏表头 -->
|
||||
<div
|
||||
class="flex sm:hidden items-center gap-2 px-3 py-2 border-b bg-muted/20 text-xs text-muted-foreground font-medium">
|
||||
<span class="w-14 shrink-0">序号</span>
|
||||
<span class="w-10 shrink-0 text-center">类型</span>
|
||||
<span class="flex-1 min-w-0">任务名称</span>
|
||||
<span class="w-8 shrink-0 text-center">状态</span>
|
||||
<span class="w-12 text-right shrink-0">耗时</span>
|
||||
<span class="w-8 text-center shrink-0"></span>
|
||||
</div>
|
||||
<!-- 大屏表头 -->
|
||||
<div
|
||||
class="hidden sm:flex items-center gap-4 px-4 h-11 border-b bg-muted/20 text-sm text-muted-foreground font-medium">
|
||||
<span class="w-16 shrink-0">序号</span>
|
||||
<span class="w-12 shrink-0 text-center">类型</span>
|
||||
<span class="w-36 shrink-0">任务名称</span>
|
||||
<span class="flex-1 min-w-0">命令</span>
|
||||
<span class="w-12 shrink-0 text-center">状态</span>
|
||||
<span class="w-16 text-right shrink-0">耗时</span>
|
||||
<span v-if="!selectedLog" class="w-40 text-right shrink-0 hidden md:block">执行时间</span>
|
||||
<span class="w-10 shrink-0 text-center"></span>
|
||||
</div>
|
||||
<!-- 列表 -->
|
||||
<div class="divide-y flex-1">
|
||||
<div v-if="logs.length === 0" class="text-sm text-muted-foreground text-center py-8">
|
||||
暂无日志
|
||||
</div>
|
||||
@@ -218,87 +383,234 @@ onMounted(() => {
|
||||
'cursor-pointer hover:bg-muted/30 transition-colors group',
|
||||
selectedLog?.id === log.id && 'bg-accent/50'
|
||||
]" @click="selectLog(log)">
|
||||
<div class="flex items-center gap-4 px-4 py-3">
|
||||
<span class="w-16 shrink-0 text-muted-foreground text-sm">#{{ total - (currentPage - 1) * pageSize - index }}</span>
|
||||
<!-- 小屏行 -->
|
||||
<div class="flex sm:hidden items-center gap-2 px-3 py-2">
|
||||
<span class="w-14 shrink-0 text-muted-foreground text-xs">#{{ total - (currentPage - 1) * pageSize - index
|
||||
}}</span>
|
||||
<span class="w-6 shrink-0 flex justify-center" :title="getTaskTypeTitle(log.task_type || 'task')">
|
||||
<GitBranch v-if="log.task_type === TASK_TYPE.REPO" class="h-3.5 w-3.5 text-primary" />
|
||||
<Terminal v-else class="h-3.5 w-3.5 text-primary" />
|
||||
</span>
|
||||
<span class="flex-1 min-w-0 font-medium truncate text-xs">{{ log.task_name }}</span>
|
||||
<span class="w-8 flex justify-center shrink-0">
|
||||
<div v-if="log.status === TASK_STATUS.SUCCESS"
|
||||
class="h-5 w-5 rounded-full bg-green-500/10 flex items-center justify-center">
|
||||
<Check class="h-3 w-3 text-green-500 stroke-[3]" />
|
||||
</div>
|
||||
<div v-else-if="log.status === TASK_STATUS.FAILED"
|
||||
class="h-5 w-5 rounded-full bg-red-500/10 flex items-center justify-center">
|
||||
<X class="h-3 w-3 text-red-500 stroke-[3]" />
|
||||
</div>
|
||||
<div v-else-if="log.status === TASK_STATUS.RUNNING"
|
||||
class="h-5 w-5 rounded-full bg-yellow-500/10 flex items-center justify-center">
|
||||
<ZapIcon class="h-3 w-3 text-yellow-500 fill-yellow-500 animate-pulse" />
|
||||
</div>
|
||||
<div v-else-if="log.status === TASK_STATUS.PENDING"
|
||||
class="h-5 w-5 rounded-full bg-yellow-500/10 flex items-center justify-center">
|
||||
<Clock class="h-3 w-3 text-yellow-500" />
|
||||
</div>
|
||||
<div v-else-if="log.status === TASK_STATUS.TIMEOUT"
|
||||
class="h-5 w-5 rounded-full bg-orange-500/10 flex items-center justify-center">
|
||||
<AlertCircle class="h-3 w-3 text-orange-500" />
|
||||
</div>
|
||||
<div v-else-if="log.status === TASK_STATUS.CANCELLED"
|
||||
class="h-5 w-5 rounded-full bg-muted flex items-center justify-center">
|
||||
<Ban class="h-3 w-3 text-muted-foreground" />
|
||||
</div>
|
||||
</span>
|
||||
<span class="w-12 text-right shrink-0 text-muted-foreground text-xs">{{ formatDuration(log.duration)
|
||||
}}</span>
|
||||
<span class="w-8 shrink-0 flex justify-center opacity-100">
|
||||
<Button variant="ghost" size="icon"
|
||||
class="h-6 w-6 text-muted-foreground hover:text-destructive shrink-0"
|
||||
@click.stop="confirmDeleteLog(log.id)" title="删除该日志">
|
||||
<Trash2 class="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</span>
|
||||
</div>
|
||||
<!-- 大屏行 -->
|
||||
<div class="hidden sm:flex items-center gap-4 px-4 py-2">
|
||||
<span class="w-16 shrink-0 text-muted-foreground text-sm">#{{ total - (currentPage - 1) * pageSize - index
|
||||
}}</span>
|
||||
<span class="w-10 shrink-0 flex justify-center" :title="getTaskTypeTitle(log.task_type || 'task')">
|
||||
<GitBranch v-if="log.task_type === TASK_TYPE.REPO" class="h-4 w-4 text-primary" />
|
||||
<Terminal v-else class="h-4 w-4 text-primary" />
|
||||
</span>
|
||||
<span class="w-36 shrink-0 font-medium truncate text-sm">{{ log.task_name }}</span>
|
||||
<code class="flex-1 min-w-0 text-muted-foreground truncate text-xs bg-muted/40 px-2 py-1 rounded">
|
||||
{{ log.command }}
|
||||
<TextOverflow :text="log.command" title="执行命令" />
|
||||
</code>
|
||||
<Badge variant="outline" :class="getStatusBadgeClass(log.status)" class="shrink-0">
|
||||
{{ log.status }}
|
||||
</Badge>
|
||||
<span class="w-16 text-right shrink-0 text-muted-foreground text-xs">{{ formatDuration(log.duration) }}</span>
|
||||
<Button variant="ghost" size="icon" class="h-8 w-8 text-muted-foreground hover:text-destructive" @click.stop="confirmDeleteLog(log.id)">
|
||||
<Trash2 class="h-4 w-4" />
|
||||
</Button>
|
||||
<span class="w-12 flex justify-center shrink-0">
|
||||
<div v-if="log.status === TASK_STATUS.SUCCESS"
|
||||
class="h-6 w-6 rounded-full bg-green-500/10 flex items-center justify-center">
|
||||
<Check class="h-3.5 w-3.5 text-green-500 stroke-[3]" />
|
||||
</div>
|
||||
<div v-else-if="log.status === TASK_STATUS.FAILED"
|
||||
class="h-6 w-6 rounded-full bg-red-500/10 flex items-center justify-center">
|
||||
<X class="h-3.5 w-3.5 text-red-500 stroke-[3]" />
|
||||
</div>
|
||||
<div v-else-if="log.status === TASK_STATUS.RUNNING"
|
||||
class="h-6 w-6 rounded-full bg-yellow-500/10 flex items-center justify-center">
|
||||
<ZapIcon class="h-3.5 w-3.5 text-yellow-500 fill-yellow-500 animate-pulse" />
|
||||
</div>
|
||||
<div v-else-if="log.status === TASK_STATUS.PENDING"
|
||||
class="h-6 w-6 rounded-full bg-yellow-500/10 flex items-center justify-center">
|
||||
<Clock class="h-3.5 w-3.5 text-yellow-500" />
|
||||
</div>
|
||||
<div v-else-if="log.status === TASK_STATUS.TIMEOUT"
|
||||
class="h-6 w-6 rounded-full bg-orange-500/10 flex items-center justify-center">
|
||||
<AlertCircle class="h-3.5 w-3.5 text-orange-500" />
|
||||
</div>
|
||||
<div v-else-if="log.status === TASK_STATUS.CANCELLED"
|
||||
class="h-6 w-6 rounded-full bg-muted flex items-center justify-center">
|
||||
<Ban class="h-3.5 w-3.5 text-muted-foreground" />
|
||||
</div>
|
||||
</span>
|
||||
<span class="w-16 text-right shrink-0 text-muted-foreground text-xs">{{ formatDuration(log.duration)
|
||||
}}</span>
|
||||
<span v-if="!selectedLog"
|
||||
class="w-40 text-right shrink-0 text-muted-foreground text-xs hidden md:block">{{ log.start_time ||
|
||||
log.created_at }}</span>
|
||||
<span class="w-10 shrink-0 flex justify-center opacity-100">
|
||||
<Button variant="ghost" size="icon"
|
||||
class="h-6 w-6 text-muted-foreground hover:text-destructive shrink-0"
|
||||
@click.stop="confirmDeleteLog(log.id)" title="删除该日志">
|
||||
<Trash2 class="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Pagination :total="total" :page="currentPage" @update:page="handlePageChange" class="p-4 border-t" />
|
||||
<!-- 分页 -->
|
||||
<Pagination :total="total" :page="currentPage" @update:page="handlePageChange" />
|
||||
</div>
|
||||
|
||||
<!-- 日志详情侧边栏 -->
|
||||
<div v-if="selectedLog"
|
||||
class="w-full lg:w-[480px] rounded-lg border bg-card flex flex-col overflow-hidden shrink-0 max-h-[80vh] lg:max-h-none">
|
||||
class="w-full lg:w-[480px] rounded-lg border bg-card flex flex-col overflow-hidden shrink-0">
|
||||
<div class="flex items-center justify-between px-4 h-11 border-b bg-muted/20">
|
||||
<span class="text-sm font-medium">日志详情</span>
|
||||
<div class="flex items-center gap-1">
|
||||
<Button variant="ghost" size="icon" @click="showFullscreen = true" title="全屏查看">
|
||||
<Maximize2 class="h-4 w-4" />
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="text-sm font-medium text-muted-foreground">日志详情</span>
|
||||
<Button v-if="selectedLog.status === TASK_STATUS.RUNNING" variant="destructive" size="sm"
|
||||
class="h-6 px-2 text-[10px]" :disabled="isStopping" @click="stopTask">
|
||||
{{ isStopping ? '停止中...' : '停止任务' }}
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon" @click="closeDetail">
|
||||
<X class="h-4 w-4" />
|
||||
</div>
|
||||
<div class="flex items-center gap-1">
|
||||
<Button variant="ghost" size="icon" class="h-7 w-7 text-muted-foreground hover:text-destructive"
|
||||
title="删除该日志" @click="confirmDeleteLog(selectedLog.id)">
|
||||
<Trash2 class="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon" class="h-7 w-7" @click="closeDetail" title="关闭">
|
||||
<X class="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex-1 overflow-y-auto p-4 space-y-4">
|
||||
<div class="grid grid-cols-2 gap-y-3 text-sm">
|
||||
<span class="text-muted-foreground">任务名称</span>
|
||||
<span class="text-right font-medium">{{ selectedLog.task_name }}</span>
|
||||
<span class="text-muted-foreground">执行状态</span>
|
||||
<Badge :class="getStatusBadgeClass(selectedLog.status)" class="ml-auto">{{ selectedLog.status }}</Badge>
|
||||
<span class="text-muted-foreground">执行耗时</span>
|
||||
<span class="text-right">{{ formatDuration(selectedLog.duration) }}</span>
|
||||
</div>
|
||||
<div class="border-t pt-4">
|
||||
<span class="text-xs font-semibold uppercase text-muted-foreground block mb-2">执行命令</span>
|
||||
<code class="block p-2 bg-muted rounded text-xs break-all font-mono">{{ selectedLog.command }}</code>
|
||||
</div>
|
||||
<div class="border-t pt-4 flex flex-col items-center justify-center py-12 text-muted-foreground text-xs bg-muted/10 rounded">
|
||||
<p>侧边栏仅展示详情</p>
|
||||
<p class="mt-1 opacity-70">查看完整日志请点击右上角全屏按钮</p>
|
||||
</div>
|
||||
<div class="px-4 py-3 border-b space-y-2 text-sm">
|
||||
<div class="flex justify-between items-center h-6">
|
||||
<span class="text-muted-foreground">任务名称</span>
|
||||
<span class="font-medium">{{ selectedLog.task_name }}</span>
|
||||
</div>
|
||||
<div class="flex justify-between items-center h-8">
|
||||
<span class="text-muted-foreground">状态</span>
|
||||
<Badge variant="outline" :class="[
|
||||
'capitalize px-3 py-1 font-semibold rounded-full border shadow-sm transition-all duration-300',
|
||||
getStatusBadgeClass(selectedLog.status)
|
||||
]">
|
||||
<div class="flex items-center gap-1.5">
|
||||
<CheckCircle2 v-if="selectedLog.status === TASK_STATUS.SUCCESS" class="h-3.5 w-3.5" />
|
||||
<XCircle v-else-if="selectedLog.status === TASK_STATUS.FAILED" class="h-3.5 w-3.5" />
|
||||
<ZapIcon v-else-if="selectedLog.status === TASK_STATUS.RUNNING"
|
||||
class="h-3.5 w-3.5 fill-current animate-pulse text-blue-500" />
|
||||
<Clock v-else-if="selectedLog.status === TASK_STATUS.PENDING" class="h-3.5 w-3.5" />
|
||||
<AlertCircle v-else-if="selectedLog.status === TASK_STATUS.TIMEOUT" class="h-3.5 w-3.5" />
|
||||
<Ban v-else-if="selectedLog.status === TASK_STATUS.CANCELLED" class="h-3.5 w-3.5" />
|
||||
<span class="text-xs tracking-wide uppercase">{{ selectedLog.status }}</span>
|
||||
</div>
|
||||
</Badge>
|
||||
</div>
|
||||
<div class="flex justify-between items-center h-6">
|
||||
<span class="text-muted-foreground">耗时</span>
|
||||
<span class="font-medium">{{ formatDuration(selectedLog.duration) }}</span>
|
||||
</div>
|
||||
<div class="flex justify-between items-center h-6">
|
||||
<span class="text-muted-foreground">开始时间</span>
|
||||
<span class="font-mono text-xs">{{ selectedLog.start_time || '-' }}</span>
|
||||
</div>
|
||||
<div class="flex justify-between items-center h-6">
|
||||
<span class="text-muted-foreground">结束时间</span>
|
||||
<span class="font-mono text-xs">{{ selectedLog.end_time || '-' }}</span>
|
||||
</div>
|
||||
<div class="pt-1.5">
|
||||
<span class="text-muted-foreground block mb-1">执行命令</span>
|
||||
<code
|
||||
class="block font-mono bg-muted/40 px-3 py-2 rounded text-xs break-all border border-muted-foreground/10">
|
||||
{{ selectedLog.command }}
|
||||
</code>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex-1 flex flex-col overflow-hidden">
|
||||
<div v-if="selectedLog.error" class="px-4 py-3 border-b bg-red-500/5 space-y-2 text-sm">
|
||||
<div class="flex items-center gap-2 text-red-500 font-medium">
|
||||
<X class="h-4 w-4" />
|
||||
<span>系统错误</span>
|
||||
</div>
|
||||
<code class="block font-mono bg-red-500/10 text-red-600 px-2 py-1 rounded text-xs break-all">
|
||||
{{ selectedLog.error }}
|
||||
</code>
|
||||
</div>
|
||||
<div class="px-4 py-2.5 text-sm text-muted-foreground border-b bg-muted/20 flex items-center justify-between">
|
||||
<span class="font-medium">日志输出</span>
|
||||
<Button variant="ghost" size="icon" class="h-6 w-6" @click="showFullscreen = true" title="全屏查看">
|
||||
<Maximize2 class="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
<div class="flex-1 overflow-auto bg-black/5 dark:bg-white/5 min-h-[160px]">
|
||||
<div class="p-4 text-xs font-mono whitespace-pre-wrap break-all log-pre leading-relaxed"><Ansi>{{ decompressedOutput }}</Ansi></div>
|
||||
<div v-if="isWsLoading" class="p-4 text-sm text-muted-foreground italic">连接中...</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 全屏查看日志 -->
|
||||
<LogViewer v-model:open="showFullscreen" :task-name="selectedLog?.task_name"
|
||||
:log-id="selectedLog?.id" :initial-status="selectedLog?.status" />
|
||||
<LogViewer v-model:open="showFullscreen" :title="`日志输出 - ${selectedLog?.task_name || ''}`"
|
||||
:content="decompressedOutput" :status="selectedLog?.status" />
|
||||
|
||||
<!-- 弹窗 (清空/删除) -->
|
||||
<!-- 清空日志确认弹窗 -->
|
||||
<AlertDialog :open="showClearDialog" @update:open="showClearDialog = $event">
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>确认清空日志?</AlertDialogTitle>
|
||||
<AlertDialogDescription>此操作不可撤销。</AlertDialogDescription>
|
||||
<AlertDialogDescription>
|
||||
此操作将永久删除{{ filterTaskId ? '当前任务的' : '所有' }}任务历史记录,包括控制台输出,并且无法撤销。
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>取消</AlertDialogCancel>
|
||||
<AlertDialogAction @click="handleClearLogs" variant="destructive">清空</AlertDialogAction>
|
||||
<AlertDialogAction @click="handleClearLogs"
|
||||
class="bg-red-500 text-white hover:bg-red-600 dark:bg-red-600 dark:text-white dark:hover:bg-red-700">
|
||||
清空
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
<!-- 单条删除确认弹窗 -->
|
||||
<AlertDialog :open="showDeleteDialog" @update:open="showDeleteDialog = $event">
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>确认删除日志?</AlertDialogTitle>
|
||||
<AlertDialogDescription>数据将永久删除。</AlertDialogDescription>
|
||||
<AlertDialogTitle>确认删除这条日志?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
此操作将永久删除该次运行记录和日志文件,且不可恢复。
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>取消</AlertDialogCancel>
|
||||
<AlertDialogAction @click="handleDeleteLog" variant="destructive">删除</AlertDialogAction>
|
||||
<AlertDialogAction @click="handleDeleteLog"
|
||||
class="bg-red-500 text-white hover:bg-red-600 dark:bg-red-600 dark:text-white dark:hover:bg-red-700">
|
||||
删除
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
@@ -1,119 +1,49 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, watch, onUnmounted } from 'vue'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { X, Loader2 } from 'lucide-vue-next'
|
||||
import LogTerminal from '@/components/LogTerminal.vue'
|
||||
import { useTheme } from '@/composables/useTheme'
|
||||
import { api } from '@/api'
|
||||
// import { toast } from 'vue-sonner' // redundant here
|
||||
import { TASK_STATUS } from '@/constants'
|
||||
|
||||
const { resolvedTheme } = useTheme()
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { X, Search } from 'lucide-vue-next'
|
||||
import Ansi from 'ansi-to-vue3'
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean
|
||||
logId?: string
|
||||
taskName?: string
|
||||
initialStatus?: string
|
||||
title: string
|
||||
content: string
|
||||
status?: string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:open': [value: boolean]
|
||||
}>()
|
||||
|
||||
const logContent = ref('')
|
||||
const logStatus = ref(props.initialStatus || '')
|
||||
const isWsLoading = ref(false)
|
||||
let logSocket: WebSocket | null = null
|
||||
let durationTimer: ReturnType<typeof setInterval> | null = null
|
||||
|
||||
const lightLogBackgroundClass = 'bg-zinc-100'
|
||||
const darkLogBackgroundClass = 'bg-zinc-950'
|
||||
const searchKeyword = ref('')
|
||||
|
||||
function close() {
|
||||
emit('update:open', false)
|
||||
}
|
||||
|
||||
function connectLogSocket(id: string) {
|
||||
if (logSocket) {
|
||||
logSocket.close()
|
||||
}
|
||||
isWsLoading.value = true
|
||||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
|
||||
const host = window.location.host
|
||||
const baseUrl = (window as any).__BASE_URL__ || ''
|
||||
const apiVersion = (window as any).__API_VERSION__ || '/api/v1'
|
||||
const wsUrl = `${protocol}//${host}${baseUrl}${apiVersion}/logs/ws?log_id=${id}`
|
||||
|
||||
logSocket = new WebSocket(wsUrl)
|
||||
|
||||
logSocket.onopen = () => {
|
||||
isWsLoading.value = false
|
||||
logContent.value = ''
|
||||
}
|
||||
|
||||
logSocket.onmessage = (event) => {
|
||||
if (logStatus.value !== TASK_STATUS.RUNNING) {
|
||||
logContent.value = event.data
|
||||
} else {
|
||||
logContent.value += event.data
|
||||
}
|
||||
}
|
||||
|
||||
logSocket.onerror = () => {
|
||||
isWsLoading.value = false
|
||||
logContent.value = '日志连接异常'
|
||||
}
|
||||
|
||||
logSocket.onclose = () => {
|
||||
isWsLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function startPolling(id: string) {
|
||||
if (durationTimer) clearInterval(durationTimer)
|
||||
durationTimer = setInterval(async () => {
|
||||
try {
|
||||
if (!props.open) {
|
||||
if (durationTimer) clearInterval(durationTimer)
|
||||
return
|
||||
}
|
||||
const logRes = await api.logs.get(id)
|
||||
if (logRes) {
|
||||
logStatus.value = logRes.status
|
||||
if (logRes.status !== TASK_STATUS.RUNNING) {
|
||||
if (durationTimer) clearInterval(durationTimer)
|
||||
}
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
}, 3000)
|
||||
}
|
||||
|
||||
watch(() => props.open, (val) => {
|
||||
if (val && props.logId) {
|
||||
logStatus.value = props.initialStatus || ''
|
||||
connectLogSocket(props.logId)
|
||||
if (logStatus.value === TASK_STATUS.RUNNING) {
|
||||
startPolling(props.logId)
|
||||
}
|
||||
// 统一控制 Body 滚动
|
||||
function toggleBodyScroll(lock: boolean) {
|
||||
if (lock) {
|
||||
document.body.style.overflow = 'hidden'
|
||||
} else {
|
||||
if (logSocket) {
|
||||
logSocket.close()
|
||||
logSocket = null
|
||||
}
|
||||
if (durationTimer) {
|
||||
clearInterval(durationTimer)
|
||||
durationTimer = null
|
||||
}
|
||||
document.body.style.overflow = ''
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// 监听打开状态
|
||||
watch(() => props.open, (val) => {
|
||||
if (val) {
|
||||
searchKeyword.value = ''
|
||||
toggleBodyScroll(true)
|
||||
} else {
|
||||
toggleBodyScroll(false)
|
||||
}
|
||||
}, { immediate: true })
|
||||
|
||||
// 确保组件卸载时恢复滚动
|
||||
onUnmounted(() => {
|
||||
if (logSocket) logSocket.close()
|
||||
if (durationTimer) clearInterval(durationTimer)
|
||||
document.body.style.overflow = ''
|
||||
toggleBodyScroll(false)
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -123,36 +53,36 @@ onUnmounted(() => {
|
||||
@click.self="close">
|
||||
<div
|
||||
class="bg-background rounded-lg shadow-lg flex flex-col w-full sm:w-[90vw] md:w-[80vw] max-w-5xl h-[90vh] sm:h-[85vh]">
|
||||
<div class="flex items-center justify-between px-3 sm:px-4 py-2 sm:py-3 border-b shrink-0 gap-3">
|
||||
<div class="flex items-center gap-3 min-w-0 flex-1">
|
||||
<span class="text-sm font-medium truncate">最新日志 - {{ taskName }}</span>
|
||||
<div v-if="logStatus"
|
||||
<div
|
||||
class="flex flex-col sm:flex-row sm:items-center justify-between px-3 sm:px-4 py-2 sm:py-3 border-b shrink-0 gap-2">
|
||||
<div class="flex items-center gap-3 min-w-0">
|
||||
<span class="text-sm font-medium truncate">{{ title }}</span>
|
||||
<div v-if="status"
|
||||
class="flex items-center gap-1.5 px-2 py-0.5 rounded text-[10px] font-bold uppercase transition-colors shrink-0"
|
||||
:class="logStatus === TASK_STATUS.SUCCESS ? 'bg-green-500/10 text-green-500 border border-green-500/20' :
|
||||
logStatus === TASK_STATUS.FAILED ? 'bg-red-500/10 text-red-500 border border-red-500/20' :
|
||||
:class="status === 'success' ? 'bg-green-500/10 text-green-500 border border-green-500/20' :
|
||||
status === 'failed' ? 'bg-red-500/10 text-red-500 border border-red-500/20' :
|
||||
'bg-yellow-500/10 text-yellow-500 border border-yellow-500/20'">
|
||||
<span v-if="logStatus === TASK_STATUS.RUNNING" class="relative flex h-1.5 w-1.5 mr-0.5">
|
||||
<span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-yellow-400 opacity-75"></span>
|
||||
<span v-if="status === 'running'" class="relative flex h-1.5 w-1.5 mr-0.5">
|
||||
<span
|
||||
class="animate-ping absolute inline-flex h-full w-full rounded-full bg-yellow-400 opacity-75"></span>
|
||||
<span class="relative inline-flex rounded-full h-1.5 w-1.5 bg-yellow-500"></span>
|
||||
</span>
|
||||
{{ logStatus === TASK_STATUS.SUCCESS ? '成功' : logStatus === TASK_STATUS.FAILED ? '失败' : '执行中' }}
|
||||
{{ status === 'success' ? '成功' : status === 'failed' ? '失败' : '执行中' }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center gap-2 shrink-0">
|
||||
<Button variant="ghost" size="icon" class="h-8 w-8 sm:h-7 sm:w-7" @click="close">
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="relative flex-1 sm:flex-none">
|
||||
<Search class="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input v-model="searchKeyword" placeholder="搜索内容..." class="h-8 pl-9 w-full sm:w-56 text-sm" />
|
||||
</div>
|
||||
<Button variant="ghost" size="icon" class="h-7 w-7 shrink-0" @click="close">
|
||||
<X class="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex-1 overflow-hidden relative"
|
||||
:class="resolvedTheme === 'dark' ? darkLogBackgroundClass : lightLogBackgroundClass">
|
||||
<LogTerminal v-if="logContent" :content="logContent" :theme="resolvedTheme" />
|
||||
<div v-else-if="isWsLoading" class="absolute inset-0 flex items-center justify-center gap-2 text-zinc-500 font-mono text-sm">
|
||||
<Loader2 class="h-4 w-4 animate-spin" />
|
||||
连接中...
|
||||
</div>
|
||||
<div v-else class="absolute inset-0 flex items-center justify-center text-zinc-500 font-mono text-sm italic">
|
||||
无日志输出
|
||||
<div class="flex-1 overflow-auto bg-black/5 dark:bg-white/5">
|
||||
<div class="p-3 sm:p-4 text-xs font-mono whitespace-pre-wrap break-all leading-relaxed">
|
||||
<Ansi>{{ content }}</Ansi>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -12,7 +12,7 @@ import DirTreeSelect from '@/components/DirTreeSelect.vue'
|
||||
import { Plus, ChevronDown, X, Search, Check, ChevronsUpDown, Loader2, AlertCircle, Terminal, Clock, Zap } from 'lucide-vue-next'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { api, type Task, type EnvVar, type Agent, type MiseLanguage } from '@/api'
|
||||
import { TRIGGER_TYPE } from '@/constants'
|
||||
import { PATHS, TRIGGER_TYPE } from '@/constants'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { getCronDescription } from '@/utils/cron'
|
||||
|
||||
@@ -54,6 +54,8 @@ const workDirCache = ref<Record<string, string>>({})
|
||||
const concurrency = ref(0)
|
||||
const concurrencyEnabled = ref(false)
|
||||
const allEnvsEnabled = ref(false)
|
||||
const SCRIPTS_DIR_PLACEHOLDER = '$SCRIPTS_DIR$'
|
||||
const scriptsDir = ref(PATHS.SCRIPTS_DIR)
|
||||
|
||||
const cronDescription = computed(() => {
|
||||
if (!form.value.schedule) return ''
|
||||
@@ -307,6 +309,11 @@ watch(() => props.open, async (val) => {
|
||||
envSearchQuery.value = ''
|
||||
// 加载数据
|
||||
await loadData()
|
||||
workDirCache.value = {
|
||||
[agentId]: agentId === 'local'
|
||||
? normalizeLocalWorkDirForDisplay(props.task?.work_dir)
|
||||
: (props.task?.work_dir || '')
|
||||
}
|
||||
if (selectedAgentId.value === 'local') {
|
||||
await fetchInstalledLangs()
|
||||
// 更新所有语言的可用版本
|
||||
@@ -319,12 +326,14 @@ watch(() => props.open, async (val) => {
|
||||
|
||||
async function loadData() {
|
||||
try {
|
||||
const [envs, agents] = await Promise.all([
|
||||
const [envs, agents, paths] = await Promise.all([
|
||||
api.env.all(),
|
||||
api.agents.list()
|
||||
api.agents.list(),
|
||||
api.settings.getPaths().catch(() => ({ scripts_dir: PATHS.SCRIPTS_DIR }))
|
||||
])
|
||||
allEnvVars.value = envs
|
||||
allAgents.value = agents
|
||||
scriptsDir.value = paths?.scripts_dir || PATHS.SCRIPTS_DIR
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
|
||||
@@ -338,6 +347,34 @@ function removeEnv(id: string) {
|
||||
selectedEnvIds.value = selectedEnvIds.value.filter(envId => envId !== id)
|
||||
}
|
||||
|
||||
function normalizeLocalWorkDirForDisplay(workDir?: string | null): string {
|
||||
if (!workDir) return ''
|
||||
if (workDir === SCRIPTS_DIR_PLACEHOLDER) return ''
|
||||
if (workDir.startsWith(`${SCRIPTS_DIR_PLACEHOLDER}/`)) {
|
||||
return workDir.slice(SCRIPTS_DIR_PLACEHOLDER.length + 1)
|
||||
}
|
||||
const base = scriptsDir.value || PATHS.SCRIPTS_DIR
|
||||
if (workDir === base) return ''
|
||||
if (workDir.startsWith(`${base}/`)) {
|
||||
return workDir.slice(base.length + 1)
|
||||
}
|
||||
return workDir
|
||||
}
|
||||
|
||||
function encodeLocalWorkDir(workDir?: string | null): string {
|
||||
const value = workDir?.trim() || ''
|
||||
if (!value) return SCRIPTS_DIR_PLACEHOLDER
|
||||
if (value === SCRIPTS_DIR_PLACEHOLDER || value.startsWith(`${SCRIPTS_DIR_PLACEHOLDER}/`)) {
|
||||
return value
|
||||
}
|
||||
const base = scriptsDir.value || PATHS.SCRIPTS_DIR
|
||||
if (value === base) return SCRIPTS_DIR_PLACEHOLDER
|
||||
if (value.startsWith(`${base}/`)) {
|
||||
return `${SCRIPTS_DIR_PLACEHOLDER}/${value.slice(base.length + 1)}`
|
||||
}
|
||||
return `${SCRIPTS_DIR_PLACEHOLDER}/${value.replace(/^\/+/, '')}`
|
||||
}
|
||||
|
||||
async function save() {
|
||||
try {
|
||||
form.value.clean_config = cleanConfig.value
|
||||
@@ -376,7 +413,9 @@ async function save() {
|
||||
form.value.config = JSON.stringify(config)
|
||||
|
||||
// 保存当前选择的执行位置对应的工作目录
|
||||
form.value.work_dir = currentWorkDir.value
|
||||
form.value.work_dir = selectedAgentId.value === 'local'
|
||||
? encodeLocalWorkDir(currentWorkDir.value)
|
||||
: currentWorkDir.value
|
||||
|
||||
if (props.isEdit && form.value.id) {
|
||||
await api.tasks.update(form.value.id, form.value)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, computed, watch } from 'vue'
|
||||
import { ref, onMounted, computed, watch, onUnmounted } from 'vue'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog'
|
||||
import { Input } from '@/components/ui/input'
|
||||
@@ -218,6 +218,30 @@ const showLogViewer = ref(false)
|
||||
const selectedLogId = ref<string | undefined>()
|
||||
const latestLogStatus = ref('')
|
||||
const latestLogTitle = ref('')
|
||||
const logContent = ref('')
|
||||
let logSocket: WebSocket | null = null
|
||||
|
||||
function cleanupLogSocket() {
|
||||
if (logSocket) {
|
||||
logSocket.onopen = null
|
||||
logSocket.onmessage = null
|
||||
logSocket.onerror = null
|
||||
logSocket.onclose = null
|
||||
logSocket.close()
|
||||
logSocket = null
|
||||
}
|
||||
}
|
||||
|
||||
watch(showLogViewer, (val) => {
|
||||
if (!val) {
|
||||
cleanupLogSocket()
|
||||
logContent.value = ''
|
||||
}
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
cleanupLogSocket()
|
||||
})
|
||||
|
||||
async function viewLogs(taskId: string) {
|
||||
try {
|
||||
@@ -228,7 +252,25 @@ async function viewLogs(taskId: string) {
|
||||
latestLogTitle.value = latestLog.task_name || ''
|
||||
latestLogStatus.value = latestLog.status || ''
|
||||
selectedLogId.value = latestLog.id
|
||||
logContent.value = ''
|
||||
showLogViewer.value = true
|
||||
|
||||
// Connect WebSocket to load log content
|
||||
cleanupLogSocket()
|
||||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
|
||||
const host = window.location.host
|
||||
const baseUrl = (window as any).__BASE_URL__ || ''
|
||||
const apiVersion = (window as any).__API_VERSION__ || '/api/v1'
|
||||
const wsUrl = `${protocol}//${host}${baseUrl}${apiVersion}/logs/ws?log_id=${latestLog.id}`
|
||||
|
||||
logSocket = new WebSocket(wsUrl)
|
||||
logSocket.onmessage = (event) => {
|
||||
if (latestLog.status !== 'running') {
|
||||
logContent.value = event.data
|
||||
} else {
|
||||
logContent.value += event.data
|
||||
}
|
||||
}
|
||||
} else {
|
||||
toast.info('该任务暂无执行日志')
|
||||
}
|
||||
@@ -460,8 +502,8 @@ watch(() => route.query.agent_id, (newVal) => {
|
||||
<RepoDialog v-model:open="showRepoDialog" :task="editingTask" :is-edit="isEdit" @saved="loadTasks" />
|
||||
|
||||
<!-- 最新日志全屏查看 -->
|
||||
<LogViewer v-model:open="showLogViewer" :task-name="latestLogTitle"
|
||||
:log-id="selectedLogId" :initial-status="latestLogStatus" />
|
||||
<LogViewer v-model:open="showLogViewer" :title="`最新日志 - ${latestLogTitle}`"
|
||||
:content="logContent || '无输出'" :status="latestLogStatus" />
|
||||
|
||||
<!-- 删除确认 (批量) -->
|
||||
<AlertDialog v-model:open="showBatchDeleteDialog">
|
||||
|
||||
Reference in New Issue
Block a user