feat: status constant define

This commit is contained in:
engigu
2026-02-10 17:07:11 +08:00
parent 04de467a67
commit cca069dd98
16 changed files with 152 additions and 109 deletions
+16 -15
View File
@@ -13,6 +13,7 @@ import (
"sync"
"time"
"github.com/engigu/baihu-panel/internal/constant"
"github.com/engigu/baihu-panel/internal/executor"
"github.com/engigu/baihu-panel/internal/logger"
"github.com/engigu/baihu-panel/internal/utils"
@@ -21,19 +22,19 @@ import (
// WebSocket 消息类型
const (
WSTypeHeartbeat = "heartbeat"
WSTypeHeartbeatAck = "heartbeat_ack"
WSTypeTasks = "tasks"
WSTypeTaskResult = "task_result"
WSTypeUpdate = "update"
WSTypeConnected = "connected"
WSTypeDisabled = "disabled"
WSTypeEnabled = "enabled"
WSTypeFetchTasks = "fetch_tasks"
WSTypeTaskLog = "task_log"
WSTypeExecute = "execute"
WSTypeTaskHeartbeat = "task_heartbeat"
WSTypeStop = "stop"
WSTypeHeartbeat = constant.WSTypeHeartbeat
WSTypeHeartbeatAck = constant.WSTypeHeartbeatAck
WSTypeTasks = constant.WSTypeTasks
WSTypeTaskResult = constant.WSTypeTaskResult
WSTypeUpdate = constant.WSTypeUpdate
WSTypeConnected = constant.WSTypeConnected
WSTypeDisabled = constant.WSTypeDisabled
WSTypeEnabled = constant.WSTypeEnabled
WSTypeFetchTasks = constant.WSTypeFetchTasks
WSTypeTaskLog = constant.WSTypeTaskLog
WSTypeExecute = constant.WSTypeExecute
WSTypeTaskHeartbeat = constant.WSTypeTaskHeartbeat
WSTypeStop = constant.WSTypeStop
)
type WSMessage struct {
@@ -193,7 +194,7 @@ func (h *AgentHandler) OnTaskCompleted(req *executor.ExecutionRequest, result *e
EndTime: result.EndTime.Unix(),
})
if result.Status == "failed" {
if result.Status == constant.TaskStatusFailed {
h.agent.printLastLogs(result.LogID)
}
h.agent.clearTaskLog(result.LogID)
@@ -216,7 +217,7 @@ func (h *AgentHandler) OnTaskFailed(req *executor.ExecutionRequest, err error) {
Command: req.Command,
Output: "",
Error: err.Error(),
Status: "failed",
Status: constant.TaskStatusFailed,
Duration: 0,
ExitCode: 1,
StartTime: time.Now().Unix(),
+17
View File
@@ -64,6 +64,23 @@ const (
WSTypeFetchTasks = "fetch_tasks"
WSTypeTaskHeartbeat = "task_heartbeat"
WSTypeStop = "stop"
// 任务状态
TaskStatusSuccess = "success"
TaskStatusFailed = "failed"
TaskStatusRunning = "running"
TaskStatusPending = "pending"
TaskStatusTimeout = "timeout"
TaskStatusCancelled = "cancelled"
TaskStatusQueued = "queued"
// 任务类型
TaskTypeNormal = "task"
TaskTypeRepo = "repo"
// Agent 状态
AgentStatusOnline = "online"
AgentStatusOffline = "offline"
)
// TablePrefix 表前缀,从配置文件读取
+1 -1
View File
@@ -111,7 +111,7 @@ func (dc *DashboardController) GetSendStats(c *gin.Context) {
}
ds := dayMap[s.Day]
ds.Total += s.Num
if s.Status == "success" {
if s.Status == constant.TaskStatusSuccess {
ds.Success += s.Num
} else {
ds.Failed += s.Num
+1 -1
View File
@@ -69,7 +69,7 @@ func (tc *TaskController) CreateTask(c *gin.Context) {
}
// 普通任务需要命令
if req.Type != "repo" && req.Command == "" {
if req.Type != constant.TaskTypeRepo && req.Command == "" {
utils.BadRequest(c, "命令不能为空")
return
}
+5 -4
View File
@@ -10,6 +10,7 @@ import (
"time"
"github.com/creack/pty"
"github.com/engigu/baihu-panel/internal/constant"
"github.com/engigu/baihu-panel/internal/logger"
"github.com/engigu/baihu-panel/internal/utils"
)
@@ -76,7 +77,7 @@ func ExecuteWithHooks(ctx context.Context, req Request, stdout, stderr io.Writer
id, err := hooks.PreExecute(ctx, req)
if err != nil {
return &Result{
Status: "failed",
Status: constant.TaskStatusFailed,
Duration: 0,
ExitCode: 1,
StartTime: start,
@@ -185,7 +186,7 @@ func ExecuteWithHooks(ctx context.Context, req Request, stdout, stderr io.Writer
// Start 失败的处理
end := time.Now()
result := &Result{
Status: "failed",
Status: constant.TaskStatusFailed,
Duration: end.Sub(start).Milliseconds(),
ExitCode: 1,
StartTime: start, // 修正为 start
@@ -248,7 +249,7 @@ func ExecuteWithHooks(ctx context.Context, req Request, stdout, stderr io.Writer
}
if err != nil {
result.Status = "failed"
result.Status = constant.TaskStatusFailed
result.Error = err.Error()
if exitErr, ok := err.(*exec.ExitError); ok {
result.ExitCode = exitErr.ExitCode()
@@ -256,7 +257,7 @@ func ExecuteWithHooks(ctx context.Context, req Request, stdout, stderr io.Writer
result.ExitCode = 1
}
} else {
result.Status = "success"
result.Status = constant.TaskStatusSuccess
result.ExitCode = 0
}
+13 -11
View File
@@ -8,6 +8,8 @@ import (
"os"
"sync"
"time"
"github.com/engigu/baihu-panel/internal/constant"
)
// safeBuffer 一个线程安全的字节缓冲区,用于合并 stdout 和 stderr
@@ -49,12 +51,12 @@ const (
type TaskStatus string
const (
TaskStatusPending TaskStatus = "pending" // 等待中
TaskStatusRunning TaskStatus = "running" // 运行中
TaskStatusSuccess TaskStatus = "success" // 成功
TaskStatusFailed TaskStatus = "failed" // 失败
TaskStatusTimeout TaskStatus = "timeout" // 超时
TaskStatusCancelled TaskStatus = "cancelled" // 已取消
TaskStatusPending TaskStatus = TaskStatus(constant.TaskStatusPending) // 等待中
TaskStatusRunning TaskStatus = TaskStatus(constant.TaskStatusRunning) // 运行中
TaskStatusSuccess TaskStatus = TaskStatus(constant.TaskStatusSuccess) // 成功
TaskStatusFailed TaskStatus = TaskStatus(constant.TaskStatusFailed) // 失败
TaskStatusTimeout TaskStatus = TaskStatus(constant.TaskStatusTimeout) // 超时
TaskStatusCancelled TaskStatus = TaskStatus(constant.TaskStatusCancelled) // 已取消
)
// ExecutionRequest 执行请求(标准接口)
@@ -329,7 +331,7 @@ func (s *Scheduler) executeTask(req *ExecutionRequest) (*ExecutionResult, error)
return &ExecutionResult{
TaskID: req.TaskID,
Success: false,
Status: "failed",
Status: constant.TaskStatusFailed,
Error: err.Error(),
Duration: 0,
ExitCode: 1,
@@ -402,7 +404,7 @@ func (s *Scheduler) executeTask(req *ExecutionRequest) (*ExecutionResult, error)
}
if execResult != nil {
result.Success = execResult.Status == "success"
result.Success = execResult.Status == constant.TaskStatusSuccess
result.Output = combinedBuf.String()
result.Status = execResult.Status
result.Duration = execResult.Duration
@@ -411,7 +413,7 @@ func (s *Scheduler) executeTask(req *ExecutionRequest) (*ExecutionResult, error)
result.EndTime = execResult.EndTime
} else {
result.Success = false
result.Status = "failed"
result.Status = constant.TaskStatusFailed
result.StartTime = start
result.EndTime = time.Now()
result.Duration = result.EndTime.Sub(result.StartTime).Milliseconds()
@@ -421,9 +423,9 @@ func (s *Scheduler) executeTask(req *ExecutionRequest) (*ExecutionResult, error)
if execErr != nil {
result.Error = execErr.Error()
if ctx.Err() == context.Canceled {
result.Status = "cancelled"
result.Status = constant.TaskStatusCancelled
} else if ctx.Err() == context.DeadlineExceeded {
result.Status = "timeout"
result.Status = constant.TaskStatusTimeout
}
}
+14 -14
View File
@@ -9,20 +9,20 @@ import (
// Agent 远程执行代理
type Agent struct {
ID uint `json:"id" gorm:"primaryKey"`
Name string `json:"name" gorm:"size:100;not null"` // Agent 名称
Token string `json:"token" gorm:"size:64;index"` // 认证 Token(可重复使用)
MachineID string `json:"machine_id" gorm:"size:64;uniqueIndex"` // 机器识别码(唯一)
Description string `json:"description" gorm:"size:255"` // 描述
Status string `json:"status" gorm:"size:20;default:'pending'"` // 状态: pending(待审核), online, offline, blocked(拉黑)
LastSeen *LocalTime `json:"last_seen"` // 最后心跳时间
IP string `json:"ip" gorm:"size:45"` // Agent IP 地址
Version string `json:"version" gorm:"size:50"` // Agent 版本
BuildTime string `json:"build_time" gorm:"size:30"` // Agent 构建时间
Hostname string `json:"hostname" gorm:"size:100"` // Agent 主机名
OS string `json:"os" gorm:"size:20"` // 操作系统
Arch string `json:"arch" gorm:"size:20"` // 架构
ForceUpdate bool `json:"force_update" gorm:"default:false"` // 强制更新标志
Enabled bool `json:"enabled" gorm:"default:true"` // 是否启用
Name string `json:"name" gorm:"size:100;not null"` // Agent 名称
Token string `json:"token" gorm:"size:64;index"` // 认证 Token(可重复使用)
MachineID string `json:"machine_id" gorm:"size:64;uniqueIndex"` // 机器识别码(唯一)
Description string `json:"description" gorm:"size:255"` // 描述
Status string `json:"status" gorm:"size:20;default:'pending';index"` // 状态: constant.AgentStatusOnline, constant.AgentStatusOffline
LastSeen *LocalTime `json:"last_seen"` // 最后心跳时间
IP string `json:"ip" gorm:"size:45"` // Agent IP 地址
Version string `json:"version" gorm:"size:50"` // Agent 版本
BuildTime string `json:"build_time" gorm:"size:30"` // Agent 构建时间
Hostname string `json:"hostname" gorm:"size:100"` // Agent 主机名
OS string `json:"os" gorm:"size:20"` // 操作系统
Arch string `json:"arch" gorm:"size:20"` // 架构
ForceUpdate bool `json:"force_update" gorm:"default:false"` // 强制更新标志
Enabled bool `json:"enabled" gorm:"default:true"` // 是否启用
CreatedAt LocalTime `json:"created_at"`
UpdatedAt LocalTime `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
+1 -1
View File
@@ -10,7 +10,7 @@ type LoginLog struct {
Username string `json:"username" gorm:"size:100;index;not null"`
IP string `json:"ip" gorm:"size:50"`
UserAgent string `json:"user_agent" gorm:"size:500"`
Status string `json:"status" gorm:"size:20"` // success, failed
Status string `json:"status" gorm:"size:20;index"` // success, failed
Message string `json:"message" gorm:"size:255"`
CreatedAt LocalTime `json:"created_at" gorm:"index"`
}
+5 -5
View File
@@ -37,7 +37,7 @@ type Task struct {
ID uint `json:"id" gorm:"primaryKey"`
Name string `json:"name" gorm:"size:255;not null"`
Command string `json:"command" gorm:"type:text"` // 普通任务的命令
Type string `json:"type" gorm:"size:20;default:'task'"` // 任务类型: task(普通任务), repo(仓库同步)
Type string `json:"type" gorm:"size:20;default:'task'"` // 任务类型: constant.TaskTypeNormal, constant.TaskTypeRepo
Config string `json:"config" gorm:"type:text"` // 配置 JSON(仓库同步配置等)
Schedule string `json:"schedule" gorm:"size:100"` // cron expression
Timeout int `json:"timeout" gorm:"default:30"` // 超时时间(分钟),默认30分钟
@@ -92,10 +92,10 @@ type TaskLog struct {
TaskID uint `json:"task_id" gorm:"index"`
AgentID *uint `json:"agent_id" gorm:"index"` // Agent ID,为空表示本地执行
Command string `json:"command" gorm:"type:text"`
Output string `json:"-" gorm:"type:longtext"` // gzip+base64 compressed
Error string `json:"error" gorm:"type:text"` // 额外的系统错误信息
Status string `json:"status" gorm:"size:20"` // success, failed
Duration int64 `json:"duration"` // milliseconds
Output string `json:"-" gorm:"type:longtext"` // gzip+base64 compressed
Error string `json:"error" gorm:"type:text"` // 额外的系统错误信息
Status string `json:"status" gorm:"size:20;index"` // success, failed
Duration int64 `json:"duration"` // milliseconds
ExitCode int `json:"exit_code"`
StartTime *LocalTime `json:"start_time"`
EndTime *LocalTime `json:"end_time"`
+8 -8
View File
@@ -122,7 +122,7 @@ func (s *AgentService) RegisterByToken(token string, machineID string, ip string
database.DB.Model(&existing).Updates(map[string]interface{}{
"token": token,
"ip": ip,
"status": "online",
"status": constant.AgentStatusOnline,
"last_seen": now,
})
s.UseToken(agentToken.ID)
@@ -138,7 +138,7 @@ func (s *AgentService) RegisterByToken(token string, machineID string, ip string
Token: token,
MachineID: machineID,
IP: ip,
Status: "online",
Status: constant.AgentStatusOnline,
LastSeen: &now,
Enabled: true,
}
@@ -179,7 +179,7 @@ func (s *AgentService) Register(req *models.AgentRegisterRequest, ip string) (*m
Version: req.Version,
BuildTime: req.BuildTime,
IP: ip,
Status: "online",
Status: constant.AgentStatusOnline,
LastSeen: &now,
Enabled: true,
}
@@ -288,7 +288,7 @@ func (s *AgentService) Heartbeat(token, ip, version, buildTime, hostname, osType
database.DB.Model(&models.Agent{}).Where("id = ?", agent.ID).Updates(updates)
agent.Status = "online"
agent.Status = constant.AgentStatusOnline
agent.LastSeen = &now
agent.IP = ip
agent.Version = version
@@ -386,15 +386,15 @@ func (s *AgentService) UpdateTaskDuration(logID uint, duration int64) error {
func (s *AgentService) UpdateOfflineAgents() {
cutoff := time.Now().Add(-2 * time.Minute)
database.DB.Model(&models.Agent{}).
Where("status = ? AND last_seen < ?", "online", cutoff).
Update("status", "offline")
Where("status = ? AND last_seen < ?", constant.AgentStatusOnline, cutoff).
Update("status", constant.AgentStatusOffline)
}
// ResetAllAgentsToOffline 将所有 Agents 状态重置为离线(用于服务启动时)
func (s *AgentService) ResetAllAgentsToOffline() {
database.DB.Model(&models.Agent{}).
Where("status = ?", "online").
Update("status", "offline")
Where("status = ?", constant.AgentStatusOnline).
Update("status", constant.AgentStatusOffline)
}
// GetLatestVersion 获取最新 Agent 版本
+3 -3
View File
@@ -292,7 +292,7 @@ func (m *AgentWSManager) cleanupLoop() {
conn.Close()
delete(m.connections, agentID)
// 更新数据库状态
database.DB.Model(&models.Agent{}).Where("id = ?", agentID).Update("status", "offline")
database.DB.Model(&models.Agent{}).Where("id = ?", agentID).Update("status", constant.AgentStatusOffline)
logger.Infof("[AgentWS] Agent #%d 心跳超时,已断开", agentID)
}
}
@@ -301,8 +301,8 @@ func (m *AgentWSManager) cleanupLoop() {
// 有些 Agent 虽然没有连接,但数据库状态可能是 "online"
cutoff := now.Add(-2 * time.Minute)
database.DB.Model(&models.Agent{}).
Where("status = ? AND last_seen < ?", "online", cutoff).
Update("status", "offline")
Where("status = ? AND last_seen < ?", constant.AgentStatusOnline, cutoff).
Update("status", constant.AgentStatusOffline)
// 清理过期的限流记录(超过 10 分钟未活动)
+6 -6
View File
@@ -134,7 +134,7 @@ func (h *ServerSchedulerHandler) OnTaskExecuting(req *executor.ExecutionRequest)
goid, err := h.es.AddRunningGo(task.ID)
if err != nil {
// 并发限制,更新日志状态为失败
taskLog.Status = "failed"
taskLog.Status = constant.TaskStatusFailed
taskLog.Output, _ = utils.CompressToBase64("任务并发数限制,拒绝执行")
h.es.taskLogService.SaveTaskLog(taskLog)
return nil, nil, fmt.Errorf("任务并发限制: %v", err)
@@ -268,7 +268,7 @@ func (h *ServerSchedulerHandler) OnTaskFailed(req *executor.ExecutionRequest, er
Command: req.Command,
Output: output,
Error: err.Error(),
Status: "failed",
Status: constant.TaskStatusFailed,
Duration: 0,
ExitCode: 1,
StartTime: &now,
@@ -330,7 +330,7 @@ func (es *ExecutorService) ExecuteDispatcher(ctx context.Context, req *executor.
}
// 特殊处理仓库同步任务
if task.Type == "repo" {
if task.Type == constant.TaskTypeRepo {
cmd, workDir := es.BuildRepoCommand(task)
if cmd != "" {
req.Command = cmd
@@ -475,7 +475,7 @@ func (es *ExecutorService) ExecuteTask(taskID int) *executor.ExecutionResult {
return &executor.ExecutionResult{
TaskID: fmt.Sprintf("%d", task.ID),
Success: true,
Status: "queued",
Status: constant.TaskStatusQueued,
StartTime: time.Now(),
}
}
@@ -487,7 +487,7 @@ func (es *ExecutorService) StopTaskExecution(logID uint) error {
return fmt.Errorf("日志不存在")
}
if taskLog.Status != "running" {
if taskLog.Status != constant.TaskStatusRunning {
return fmt.Errorf("任务已结束")
}
@@ -692,7 +692,7 @@ func (es *ExecutorService) ExecuteRemoteForScheduler(task *models.Task, logID ui
case <-time.After(time.Duration(timeout) * time.Minute):
end := time.Now()
return &executor.Result{
Status: "failed",
Status: constant.TaskStatusFailed,
Error: "等待 Agent 结果超时",
Duration: end.Sub(start).Milliseconds(),
ExitCode: -1,
+22
View File
@@ -17,3 +17,25 @@ export const FILE_RUNNERS: Record<string, string> = {
sh: 'bash',
bash: 'bash',
} as const
// 任务状态
export const TASK_STATUS = {
SUCCESS: 'success',
FAILED: 'failed',
RUNNING: 'running',
PENDING: 'pending',
TIMEOUT: 'timeout',
CANCELLED: 'cancelled',
} as const
// 任务类型
export const TASK_TYPE = {
NORMAL: 'task',
REPO: 'repo',
} as const
// Agent 状态
export const AGENT_STATUS = {
ONLINE: 'online',
OFFLINE: 'offline',
} as const
+3 -6
View File
@@ -10,6 +10,7 @@ import { RefreshCw, Trash2, Edit, Copy, Server, Search, Download, RotateCw, Plus
import { api, type Agent, type AgentToken } from '@/api'
import { toast } from 'vue-sonner'
import { useRouter } from 'vue-router'
import { AGENT_STATUS } from '@/constants'
const router = useRouter()
@@ -43,11 +44,7 @@ const filteredAgents = computed(() => {
})
function isOnline(agent: Agent): boolean {
if (!agent.last_seen) return false
const lastSeen = new Date(agent.last_seen)
const now = new Date()
const diffMs = now.getTime() - lastSeen.getTime()
return diffMs < 2 * 60 * 1000
return agent.status === AGENT_STATUS.ONLINE
}
async function loadAgents() {
@@ -326,7 +323,7 @@ onUnmounted(() => {
class="w-24 sm:w-32 shrink-0 font-medium text-xs sm:text-sm truncate cursor-pointer hover:text-primary"
@click="viewDetail(agent)" :title="agent.name">{{ agent.name }}</span>
<span class="w-24 sm:w-28 shrink-0 text-xs sm:text-sm text-muted-foreground truncate">{{ agent.ip || '-'
}}</span>
}}</span>
<span class="w-20 sm:w-32 shrink-0 text-xs sm:text-sm text-muted-foreground truncate hidden md:block">{{
agent.hostname || '-' }}</span>
<span class="w-20 sm:w-36 shrink-0 text-xs sm:text-sm text-muted-foreground truncate hidden lg:block">{{
+29 -27
View File
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { ref, onMounted, computed, watch, nextTick } from 'vue'
import { useRoute } from 'vue-router'
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'
@@ -84,7 +85,7 @@ async function selectLog(log: TaskLog) {
selectedLog.value = log
// 如果是运行中状态,启动定时器轮询最新日志信息(主要是更新耗时)
if (log.status === 'running') {
if (log.status === TASK_STATUS.RUNNING) {
const updateLog = async () => {
try {
const res = await api.logs.get(log.id)
@@ -97,7 +98,7 @@ async function selectLog(log: TaskLog) {
listItem.duration = res.duration
}
// 如果状态变了,更新状态并停止轮询
if (res.status !== 'running') {
if (res.status !== TASK_STATUS.RUNNING) {
selectedLog.value.status = res.status
selectedLog.value.end_time = res.end_time
if (listItem) {
@@ -133,7 +134,7 @@ async function selectLog(log: TaskLog) {
logSocket.onmessage = (event) => {
isWsLoading.value = false
if (log.status !== 'running') {
if (log.status !== TASK_STATUS.RUNNING) {
wsContent.value = event.data
} else {
wsContent.value += event.data
@@ -192,7 +193,7 @@ function formatDuration(ms: number): string {
}
function getTaskTypeTitle(type: string) {
return type === 'repo' ? '仓库同步' : '普通任务'
return type === TASK_TYPE.REPO ? '仓库同步' : '普通任务'
}
onMounted(() => {
@@ -267,32 +268,32 @@ watch(() => route.query.task_id, (newTaskId) => {
<div class="flex sm:hidden items-center gap-2 px-3 py-2">
<span class="w-14 shrink-0 text-muted-foreground text-xs">#{{ log.id }}</span>
<span class="w-6 shrink-0 flex justify-center" :title="getTaskTypeTitle(log.task_type || 'task')">
<GitBranch v-if="log.task_type === 'repo'" class="h-3.5 w-3.5 text-primary" />
<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 === 'success'"
<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 === 'failed'"
<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 === 'running'"
<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">
<Zap class="h-3 w-3 text-yellow-500 fill-yellow-500 animate-pulse" />
</div>
<div v-else-if="log.status === 'pending'"
<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 === 'timeout'"
<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 === 'cancelled'"
<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>
@@ -304,7 +305,7 @@ watch(() => route.query.task_id, (newTaskId) => {
<div class="hidden sm:flex items-center gap-4 px-4 py-2">
<span class="w-16 shrink-0 text-muted-foreground text-sm">#{{ log.id }}</span>
<span class="w-10 shrink-0 flex justify-center" :title="getTaskTypeTitle(log.task_type || 'task')">
<GitBranch v-if="log.task_type === 'repo'" class="h-4 w-4 text-primary" />
<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>
@@ -312,27 +313,27 @@ watch(() => route.query.task_id, (newTaskId) => {
<TextOverflow :text="log.command" title="执行命令" />
</code>
<span class="w-12 flex justify-center shrink-0">
<div v-if="log.status === 'success'"
<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 === 'failed'"
<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 === 'running'"
<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">
<Zap class="h-3.5 w-3.5 text-yellow-500 fill-yellow-500 animate-pulse" />
</div>
<div v-else-if="log.status === 'pending'"
<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 === 'timeout'"
<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 === 'cancelled'"
<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>
@@ -355,8 +356,8 @@ watch(() => route.query.task_id, (newTaskId) => {
<div class="flex items-center justify-between px-4 py-3 border-b">
<div class="flex items-center gap-2">
<span class="text-sm font-medium">日志详情</span>
<Button v-if="selectedLog.status === 'running'" variant="destructive" size="sm" class="h-6 px-2 text-[10px]"
:disabled="isStopping" @click="stopTask">
<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>
</div>
@@ -372,15 +373,16 @@ watch(() => route.query.task_id, (newTaskId) => {
<div class="flex justify-between items-center">
<span class="text-muted-foreground">状态</span>
<Badge
:variant="selectedLog.status === 'success' ? 'default' : selectedLog.status === 'failed' ? 'destructive' : 'secondary'"
:variant="selectedLog.status === TASK_STATUS.SUCCESS ? 'default' : selectedLog.status === TASK_STATUS.FAILED ? 'destructive' : 'secondary'"
class="capitalize px-4 py-0.5">
<div class="flex items-center gap-1.5">
<CheckCircle2 v-if="selectedLog.status === 'success'" class="h-3 w-3" />
<XCircle v-else-if="selectedLog.status === 'failed'" class="h-3 w-3" />
<Zap v-else-if="selectedLog.status === 'running'" class="h-3 w-3 fill-current animate-pulse" />
<Clock v-else-if="selectedLog.status === 'pending'" class="h-3 w-3" />
<AlertCircle v-else-if="selectedLog.status === 'timeout'" class="h-3 w-3" />
<Ban v-else-if="selectedLog.status === 'cancelled'" class="h-3 w-3" />
<CheckCircle2 v-if="selectedLog.status === TASK_STATUS.SUCCESS" class="h-3 w-3" />
<XCircle v-else-if="selectedLog.status === TASK_STATUS.FAILED" class="h-3 w-3" />
<Zap v-else-if="selectedLog.status === TASK_STATUS.RUNNING"
class="h-3 w-3 fill-current animate-pulse" />
<Clock v-else-if="selectedLog.status === TASK_STATUS.PENDING" class="h-3 w-3" />
<AlertCircle v-else-if="selectedLog.status === TASK_STATUS.TIMEOUT" class="h-3 w-3" />
<Ban v-else-if="selectedLog.status === TASK_STATUS.CANCELLED" class="h-3 w-3" />
{{ selectedLog.status }}
</div>
</Badge>
+8 -7
View File
@@ -11,6 +11,7 @@ import { api, type Task, type Agent } from '@/api'
import { toast } from 'vue-sonner'
import { useSiteSettings } from '@/composables/useSiteSettings'
import { useRouter, useRoute } from 'vue-router'
import { TASK_TYPE, AGENT_STATUS } from '@/constants'
import TextOverflow from '@/components/TextOverflow.vue'
const router = useRouter()
@@ -57,7 +58,7 @@ function getExecutorName(task: Task): string {
function getExecutorStatus(task: Task): 'local' | 'online' | 'offline' {
if (!task.agent_id) return 'local'
const agent = agentMap.value[task.agent_id]
return agent?.status === 'online' ? 'online' : 'offline'
return agent?.status === AGENT_STATUS.ONLINE ? 'online' : 'offline'
}
async function loadTasks() {
@@ -100,13 +101,13 @@ function clearAgentFilter() {
}
function openCreate() {
editingTask.value = { name: '', command: '', type: 'task', schedule: '0 * * * * *', timeout: 30, work_dir: '', enabled: true, clean_config: '', envs: '' }
editingTask.value = { name: '', command: '', type: TASK_TYPE.NORMAL, schedule: '0 * * * * *', timeout: 30, work_dir: '', enabled: true, clean_config: '', envs: '' }
isEdit.value = false
showTaskDialog.value = true
}
function openCreateRepo() {
editingTask.value = { name: '', type: 'repo', schedule: '0 0 0 * * *', timeout: 30, enabled: true, clean_config: '', envs: '' }
editingTask.value = { name: '', type: TASK_TYPE.REPO, schedule: '0 0 0 * * *', timeout: 30, enabled: true, clean_config: '', envs: '' }
isEdit.value = false
showRepoDialog.value = true
}
@@ -114,7 +115,7 @@ function openCreateRepo() {
function openEdit(task: Task) {
editingTask.value = { ...task }
isEdit.value = true
if (task.type === 'repo') {
if (task.type === TASK_TYPE.REPO) {
showRepoDialog.value = true
} else {
showTaskDialog.value = true
@@ -168,7 +169,7 @@ function viewLogs(taskId: number) {
}
function getTaskTypeTitle(type: string) {
return type === 'repo' ? '仓库同步' : '普通任务'
return type === TASK_TYPE.REPO ? '仓库同步' : '普通任务'
}
onMounted(async () => {
@@ -244,7 +245,7 @@ watch(() => route.query.agent_id, (newVal) => {
class="flex items-center gap-2 sm:gap-4 px-3 sm:px-4 py-2 hover:bg-muted/50 transition-colors">
<span class="w-12 sm:w-14 shrink-0 text-muted-foreground text-xs sm:text-sm">#{{ task.id }}</span>
<span class="w-6 sm:w-8 shrink-0 flex justify-center" :title="getTaskTypeTitle(task.type || 'task')">
<GitBranch v-if="task.type === 'repo'" class="h-3.5 w-3.5 sm:h-4 sm:w-4 text-primary" />
<GitBranch v-if="task.type === TASK_TYPE.REPO" class="h-3.5 w-3.5 sm:h-4 sm:w-4 text-primary" />
<Terminal v-else class="h-3.5 w-3.5 sm:h-4 sm:w-4 text-primary" />
</span>
<span class="flex-1 min-w-0 font-medium truncate text-xs sm:text-sm">{{ task.name }}</span>
@@ -258,7 +259,7 @@ watch(() => route.query.agent_id, (newVal) => {
</span>
<code
class="w-32 sm:flex-1 shrink-0 sm:shrink text-muted-foreground truncate text-xs bg-muted px-2 py-1 rounded hidden sm:block">
<TextOverflow :text="task.command" :title="task.type === 'repo' ? '同步地址' : '执行命令'" />
<TextOverflow :text="task.command" :title="task.type === TASK_TYPE.REPO ? '同步地址' : '执行命令'" />
</code>
<code class="w-36 shrink-0 text-muted-foreground text-xs bg-muted px-2 py-1 rounded hidden md:block">{{ task.schedule
}}</code>