gui 客户端
This commit is contained in:
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -29,6 +30,14 @@ type ShortClient struct {
|
||||
Status string `json:"status"` // 连接状态: "stopped", "connecting", "connected"
|
||||
}
|
||||
|
||||
// ConnectionLog 连接日志项
|
||||
type ConnectionLog struct {
|
||||
Timestamp string `json:"timestamp"`
|
||||
Message string `json:"message"`
|
||||
Type string `json:"type"` // "info", "error", "warning", "success"
|
||||
ClientId string `json:"clientId"`
|
||||
}
|
||||
|
||||
var (
|
||||
shortcuts []ShortClient
|
||||
shortcutsMu sync.Mutex
|
||||
@@ -36,18 +45,118 @@ var (
|
||||
// 改为用 context 管理内置客户端,而不是外部进程
|
||||
running = make(map[string]context.CancelFunc)
|
||||
clients = make(map[string]*client.TRPClient)
|
||||
clientErrors = make(map[string]string) // 存储客户端连接错误信息
|
||||
clientConnected = make(map[string]bool) // 存储客户端连接状态 (true=connected)
|
||||
clientAttempted = make(map[string]bool) // 存储客户端是否尝试过连接
|
||||
statusMu sync.Mutex // 状态锁
|
||||
clientErrors = make(map[string]string) // 存储客户端连接错误信息
|
||||
clientConnected = make(map[string]bool) // 存储客户端连接状态 (true=connected)
|
||||
clientAttempted = make(map[string]bool) // 存储客户端是否尝试过连接
|
||||
clientLoggers = make(map[string]*logs.BeeLogger) // 为每个客户端单独管理 logger
|
||||
statusMu sync.Mutex // 状态锁
|
||||
runningMu sync.Mutex
|
||||
loggerMu sync.Mutex // 保护 clientLoggers 的并发访问
|
||||
disconnectTimeout = 60
|
||||
connType = "tcp"
|
||||
|
||||
// 日志缓存机制,避免频繁读取文件
|
||||
logsCacheMu sync.RWMutex
|
||||
logsCache = make(map[string][]ConnectionLog) // 缓存:clientId -> logs
|
||||
logsCacheTime = make(map[string]time.Time) // 缓存时间:clientId -> time
|
||||
logsCacheTTL = 2 * time.Second // 缓存有效期 2 秒
|
||||
)
|
||||
|
||||
// extractClientIdFromLog 从日志行中提取客户端 ID (IP:PORT|KEY 格式)
|
||||
func extractClientIdFromLog(line string) string {
|
||||
// 查找 IP:PORT|KEY 模式
|
||||
parts := strings.Fields(line)
|
||||
for _, part := range parts {
|
||||
if strings.Contains(part, ":") && strings.Contains(part, "|") {
|
||||
if isValidClientId(part) {
|
||||
return part
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// isValidClientId 检查是否是有效的客户端 ID (IP:PORT|KEY)
|
||||
func isValidClientId(s string) bool {
|
||||
parts := strings.Split(s, "|")
|
||||
if len(parts) != 2 {
|
||||
return false
|
||||
}
|
||||
addrParts := strings.Split(parts[0], ":")
|
||||
return len(addrParts) == 2 && len(parts[1]) > 0
|
||||
}
|
||||
|
||||
func NewApp() *App { return &App{} }
|
||||
|
||||
func (a *App) startup(ctx context.Context) {}
|
||||
func (a *App) startup(ctx context.Context) {
|
||||
// 初始化日志系统,同时使用 store logger 和文件 logger
|
||||
// store logger 用于内存缓存,文件 logger 用于持久化
|
||||
logs.SetLogger("store")
|
||||
|
||||
// 可选:同时输出到文件
|
||||
logsPath := getLogsPath()
|
||||
// Windows 路径中的反斜杠需要转义
|
||||
logFilePath := strings.ReplaceAll(filepath.Join(logsPath, "npc.log"), "\\", "\\\\")
|
||||
logs.SetLogger(logs.AdapterFile, `{"filename":"`+logFilePath+`","daily":true,"maxdays":7}`)
|
||||
|
||||
logs.SetLevel(logs.LevelDebug)
|
||||
}
|
||||
|
||||
func getLogsPath() string {
|
||||
dir, err := os.UserConfigDir()
|
||||
if err != nil {
|
||||
dir = "."
|
||||
}
|
||||
cfgDir := filepath.Join(dir, "nps")
|
||||
_ = os.MkdirAll(cfgDir, 0o755)
|
||||
logsDir := filepath.Join(cfgDir, "logs")
|
||||
_ = os.MkdirAll(logsDir, 0o755)
|
||||
return logsDir
|
||||
}
|
||||
|
||||
// getClientLogFilePath 获取客户端的独立日志文件路径
|
||||
func getClientLogFilePath(id string) string {
|
||||
logsDir := getLogsPath()
|
||||
// 将 addr|key 格式转换为 clientId-{hash}.log
|
||||
// 为了避免文件名中出现冒号等特殊字符,使用简单的转换
|
||||
sanitizedId := strings.NewReplacer(
|
||||
"|", "-",
|
||||
":", "-",
|
||||
"/", "-",
|
||||
).Replace(id)
|
||||
return filepath.Join(logsDir, fmt.Sprintf("npc-client-%s.log", sanitizedId))
|
||||
}
|
||||
|
||||
// initClientLogger 为客户端初始化独立的 logger
|
||||
func initClientLogger(id string) {
|
||||
// 不需要单独初始化,使用全局日志 logger
|
||||
// 但我们需要记录该 logger 已被初始化(用于日志查询时的过滤)
|
||||
loggerMu.Lock()
|
||||
defer loggerMu.Unlock()
|
||||
|
||||
if _, exists := clientLoggers[id]; !exists {
|
||||
// 标记该客户端的日志已初始化
|
||||
clientLoggers[id] = nil // 使用 nil 来表示已初始化但使用全局 logger
|
||||
}
|
||||
}
|
||||
|
||||
// getClientLogger 获取客户端的 logger
|
||||
func getClientLogger(id string) *logs.BeeLogger {
|
||||
// 返回全局 beego logger,因为所有客户端共用一个全局日志系统
|
||||
// 日志中会包含客户端 ID 信息用于后续过滤
|
||||
return nil // 使用全局 logs 系统
|
||||
}
|
||||
|
||||
// closeClientLogger 关闭客户端的 logger
|
||||
func closeClientLogger(id string) {
|
||||
loggerMu.Lock()
|
||||
defer loggerMu.Unlock()
|
||||
|
||||
if _, exists := clientLoggers[id]; exists {
|
||||
delete(clientLoggers, id)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) shutdown(ctx context.Context) {}
|
||||
|
||||
func getStoragePath() string {
|
||||
@@ -322,12 +431,22 @@ func startNpcClient(id, server, vkey string, tlsEnable bool) {
|
||||
|
||||
// startNpcClientWithContext 在给定的 context 中运行 npc 客户端
|
||||
func startNpcClientWithContext(ctx context.Context, id, server, vkey string, tlsEnable bool) {
|
||||
// 为该客户端初始化独立的日志文件
|
||||
initClientLogger(id)
|
||||
clientLogger := getClientLogger(id)
|
||||
|
||||
client.SetTlsEnable(tlsEnable)
|
||||
if clientLogger != nil {
|
||||
clientLogger.Info("启动 NPC 客户端: server=%s, vkey=%s, tls=%v", server, vkey, tlsEnable)
|
||||
}
|
||||
logs.Info("启动 NPC 客户端: server=%s, vkey=%s, tls=%v", server, vkey, tlsEnable)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
if clientLogger != nil {
|
||||
clientLogger.Info("停止 NPC 客户端: %s", id)
|
||||
}
|
||||
logs.Info("停止 NPC 客户端: %s", id)
|
||||
statusMu.Lock()
|
||||
delete(clientConnected, id)
|
||||
@@ -340,10 +459,15 @@ func startNpcClientWithContext(ctx context.Context, id, server, vkey string, tls
|
||||
delete(clients, id)
|
||||
}
|
||||
runningMu.Unlock()
|
||||
// 关闭客户端日志
|
||||
closeClientLogger(id)
|
||||
return
|
||||
default:
|
||||
}
|
||||
|
||||
if clientLogger != nil {
|
||||
clientLogger.Info("连接服务器: %s", id)
|
||||
}
|
||||
logs.Info("连接服务器: %s", id)
|
||||
|
||||
// 重置连接状态,准备新的连接尝试
|
||||
@@ -365,6 +489,9 @@ func startNpcClientWithContext(ctx context.Context, id, server, vkey string, tls
|
||||
go func() {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
if clientLogger != nil {
|
||||
clientLogger.Info("Context 已取消,关闭客户端: %s", id)
|
||||
}
|
||||
logs.Info("Context 已取消,关闭客户端: %s", id)
|
||||
rpcClient.Close()
|
||||
}
|
||||
@@ -375,6 +502,9 @@ func startNpcClientWithContext(ctx context.Context, id, server, vkey string, tls
|
||||
// 检查 context 是否已取消
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
if clientLogger != nil {
|
||||
clientLogger.Info("停止 NPC 客户端: %s", id)
|
||||
}
|
||||
logs.Info("停止 NPC 客户端: %s", id)
|
||||
statusMu.Lock()
|
||||
delete(clientConnected, id)
|
||||
@@ -387,6 +517,8 @@ func startNpcClientWithContext(ctx context.Context, id, server, vkey string, tls
|
||||
delete(clients, id)
|
||||
}
|
||||
runningMu.Unlock()
|
||||
// 关闭客户端日志
|
||||
closeClientLogger(id)
|
||||
return
|
||||
case <-time.After(5 * time.Second):
|
||||
// 继续重新连接
|
||||
@@ -459,3 +591,114 @@ func getStartupError(addr, key string, err error) error {
|
||||
}
|
||||
return errors.New("npc 启动失败: " + err.Error())
|
||||
}
|
||||
|
||||
// GetConnectionLogs 获取指定客户端的连接日志(从全局日志文件读取并过滤,带缓存)
|
||||
func (a *App) GetConnectionLogs(clientId string) ([]ConnectionLog, error) {
|
||||
// 检查缓存是否有效
|
||||
logsCacheMu.RLock()
|
||||
if cachedLogs, exists := logsCache[clientId]; exists {
|
||||
if cacheTime, ok := logsCacheTime[clientId]; ok {
|
||||
if time.Since(cacheTime) < logsCacheTTL {
|
||||
// 缓存仍然有效
|
||||
logsCacheMu.RUnlock()
|
||||
logs.Debug("使用缓存日志,clientId=%s,缓存时间=%v", clientId, time.Since(cacheTime))
|
||||
return cachedLogs, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
logsCacheMu.RUnlock()
|
||||
|
||||
// 缓存过期或不存在,重新读取日志
|
||||
logs.Info("重新读取日志,clientId=%s", clientId)
|
||||
|
||||
// 读取全局日志文件
|
||||
globalLogsDir := getLogsPath()
|
||||
globalLogFile := filepath.Join(globalLogsDir, "npc.log")
|
||||
|
||||
logs.Debug("GetConnectionLogs called for clientId=%s, logFile=%s", clientId, globalLogFile)
|
||||
|
||||
data, err := os.ReadFile(globalLogFile)
|
||||
if err != nil {
|
||||
// 如果文件不存在或读取失败,返回空日志
|
||||
logs.Error("读取日志文件失败: %v", err)
|
||||
return []ConnectionLog{}, nil
|
||||
}
|
||||
|
||||
logContent := string(data)
|
||||
if logContent == "" {
|
||||
logs.Debug("日志文件为空")
|
||||
return []ConnectionLog{}, nil
|
||||
}
|
||||
|
||||
// 从 clientId 中提取密钥 (格式: addr|key)
|
||||
parts := strings.Split(clientId, "|")
|
||||
var vkey string
|
||||
if len(parts) == 2 {
|
||||
vkey = parts[1]
|
||||
} else {
|
||||
// 如果格式不对,返回空
|
||||
logs.Warn("无效的 clientId 格式: %s", clientId)
|
||||
return []ConnectionLog{}, nil
|
||||
}
|
||||
|
||||
var result []ConnectionLog
|
||||
lines := strings.Split(logContent, "\n")
|
||||
|
||||
for _, line := range lines {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
// 检查这条日志是否属于指定的客户端(通过检查 vkey 是否在日志中)
|
||||
if !strings.Contains(line, vkey) {
|
||||
continue
|
||||
}
|
||||
|
||||
// 判断日志类型
|
||||
logType := "info"
|
||||
if strings.Contains(line, "[E]") {
|
||||
logType = "error"
|
||||
} else if strings.Contains(line, "[W]") {
|
||||
logType = "warning"
|
||||
} else if strings.Contains(line, "成功") || strings.Contains(line, "connected") || strings.Contains(line, "Success") {
|
||||
logType = "success"
|
||||
}
|
||||
|
||||
// 提取时间戳(日志格式通常是:2026-01-09 11:04:56 或 11:04:56)
|
||||
var timestamp string
|
||||
timeFields := strings.Fields(line)
|
||||
if len(timeFields) >= 2 {
|
||||
// 尝试获取前两个字段作为日期和时间
|
||||
timestamp = timeFields[0] + " " + timeFields[1]
|
||||
} else if len(timeFields) >= 1 {
|
||||
timestamp = timeFields[0]
|
||||
}
|
||||
|
||||
log := ConnectionLog{
|
||||
Timestamp: timestamp,
|
||||
Message: line,
|
||||
Type: logType,
|
||||
ClientId: clientId,
|
||||
}
|
||||
|
||||
result = append(result, log)
|
||||
}
|
||||
|
||||
// 更新缓存
|
||||
logsCacheMu.Lock()
|
||||
logsCache[clientId] = result
|
||||
logsCacheTime[clientId] = time.Now()
|
||||
logsCacheMu.Unlock()
|
||||
|
||||
logs.Debug("为 clientId=%s 返回 %d 条日志", clientId, len(result))
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ClearConnectionLogs 清除指定客户端的连接日志
|
||||
// 目前无法从全局日志文件中删除特定客户端的日志,这是一个限制
|
||||
func (a *App) ClearConnectionLogs(clientId string) error {
|
||||
// 无法从共享的全局日志中删除特定客户端的日志
|
||||
// 返回 nil 表示操作成功(但实际上没有做任何事)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -92,9 +92,31 @@
|
||||
</div>
|
||||
|
||||
<div v-else-if="activeView === 'logs'" class="view logs-view">
|
||||
<div class="logs-header">
|
||||
<div class="logs-controls">
|
||||
<label>选择客户端:</label>
|
||||
<select v-model="selectedClientId" class="client-select">
|
||||
<option value="">-- 全部客户端 --</option>
|
||||
<option v-for="client in clients" :key="`${client.addr}|${client.key}`" :value="`${client.addr}|${client.key}`">
|
||||
{{ client.name }} ({{ client.addr }})
|
||||
</option>
|
||||
</select>
|
||||
<button class="btn btn-secondary" @click="clearLogs">清空日志</button>
|
||||
<button v-if="!autoScroll" class="btn btn-secondary btn-scroll-to-bottom" @click="scrollToBottom">
|
||||
↓ 回到底部
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="logs-container">
|
||||
<div class="log-content">
|
||||
<p>日志功能开发中...</p>
|
||||
<div class="log-content" ref="logContentRef" @scroll="onLogScroll">
|
||||
<div v-if="filteredLogs.length === 0" class="empty-logs">
|
||||
<p>暂无日志记录</p>
|
||||
</div>
|
||||
<div v-for="(log, index) in filteredLogs" :key="index" :class="['log-item', `log-${log.type}`]">
|
||||
<span class="log-timestamp">{{ log.timestamp }}</span>
|
||||
<span class="log-message">{{ log.message }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -113,7 +135,7 @@
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { ref, onMounted, computed, watch, nextTick } from 'vue'
|
||||
// 直接导入 Wails 生成的 API 绑定
|
||||
import * as AppAPI from '../wailsjs/go/main/App.js'
|
||||
|
||||
@@ -124,7 +146,13 @@ export default {
|
||||
const clients = ref([])
|
||||
const commandInput = ref('')
|
||||
const message = ref(null)
|
||||
const selectedClientId = ref('')
|
||||
const allLogs = ref([])
|
||||
const logContentRef = ref(null)
|
||||
const autoScroll = ref(true)
|
||||
const toggleStates = ref({}) // 记录正在切换的客户端,防止快速重复切换
|
||||
const logCache = ref({}) // 缓存每个客户端的日志,格式: { clientId: lastSeenLogHash }
|
||||
let isLoadingLogs = false // 防止并发加载日志
|
||||
|
||||
// 从直接导入获取 Wails API(使用 let 以便在浏览器中可替换为 mock)
|
||||
let GetShortcuts = AppAPI.GetShortcuts
|
||||
@@ -132,6 +160,8 @@ export default {
|
||||
let RemoveShortcut = AppAPI.RemoveShortcut
|
||||
let ToggleClient = AppAPI.ToggleClient
|
||||
let TestConnection = AppAPI.TestConnection
|
||||
let GetConnectionLogs = AppAPI.GetConnectionLogs
|
||||
let ClearConnectionLogs = AppAPI.ClearConnectionLogs
|
||||
|
||||
// 在普通浏览器里运行时 Wails API 可能不存在,提供简单 mock 方便调试 UI
|
||||
if (!AppAPI || typeof AppAPI.GetShortcuts !== 'function') {
|
||||
@@ -157,6 +187,16 @@ export default {
|
||||
console.log('mock TestConnection', input)
|
||||
return
|
||||
}
|
||||
GetConnectionLogs = async (clientId) => {
|
||||
console.log('mock GetConnectionLogs', clientId)
|
||||
return [
|
||||
{ timestamp: '2024-01-09 10:30:15', message: 'Mock 日志消息', type: 'info', clientId: clientId }
|
||||
]
|
||||
}
|
||||
ClearConnectionLogs = async (clientId) => {
|
||||
console.log('mock ClearConnectionLogs', clientId)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
const initWails = async () => {
|
||||
@@ -331,6 +371,182 @@ export default {
|
||||
}
|
||||
}
|
||||
|
||||
const loadLogs = async () => {
|
||||
// 防止并发加载
|
||||
if (isLoadingLogs) {
|
||||
console.debug('日志已在加载中,跳过本次请求')
|
||||
return
|
||||
}
|
||||
|
||||
isLoadingLogs = true
|
||||
try {
|
||||
console.log('loadLogs called, selectedClientId=', selectedClientId.value)
|
||||
let newLogs = []
|
||||
|
||||
if (selectedClientId.value) {
|
||||
console.log('加载特定客户端日志:', selectedClientId.value)
|
||||
const logs = await GetConnectionLogs(selectedClientId.value)
|
||||
console.log('GetConnectionLogs 返回:', logs ? logs.length + ' 条日志' : '0 条日志')
|
||||
newLogs = logs || []
|
||||
} else {
|
||||
// 获取所有客户端的日志
|
||||
console.log('加载所有客户端日志,总共', clients.value.length, '个客户端')
|
||||
let allClientLogs = []
|
||||
for (const client of clients.value) {
|
||||
const clientId = `${client.addr}|${client.key}`
|
||||
console.log('加载客户端日志:', clientId)
|
||||
const logs = await GetConnectionLogs(clientId)
|
||||
console.log('该客户端返回:', logs ? logs.length + ' 条日志' : '0 条日志')
|
||||
if (logs) {
|
||||
allClientLogs = allClientLogs.concat(logs)
|
||||
}
|
||||
}
|
||||
newLogs = allClientLogs
|
||||
}
|
||||
|
||||
console.log('本次加载新日志数:', newLogs.length)
|
||||
|
||||
// 创建当前日志的唯一标识集合(用于去重)
|
||||
const existingKeys = new Set()
|
||||
allLogs.value.forEach(log => {
|
||||
const logKey = `${log.timestamp}|${log.message}|${log.clientId}`
|
||||
existingKeys.add(logKey)
|
||||
})
|
||||
|
||||
// 筛选出新增的日志
|
||||
const addedLogs = []
|
||||
newLogs.forEach(log => {
|
||||
const logKey = `${log.timestamp}|${log.message}|${log.clientId}`
|
||||
if (!existingKeys.has(logKey)) {
|
||||
addedLogs.push(log)
|
||||
existingKeys.add(logKey)
|
||||
}
|
||||
})
|
||||
|
||||
console.log('新增日志数:', addedLogs.length)
|
||||
|
||||
// 将新增日志添加到现有日志的末尾
|
||||
if (addedLogs.length > 0) {
|
||||
allLogs.value = allLogs.value.concat(addedLogs)
|
||||
|
||||
// 定期进行完整排序,确保顺序正确(每10条新日志排一次)
|
||||
if (allLogs.value.length % 10 === 0) {
|
||||
allLogs.value.sort((a, b) => {
|
||||
// 先按客户端ID排序,再按时间戳排序,最后按消息内容排序
|
||||
if (a.clientId !== b.clientId) {
|
||||
return a.clientId.localeCompare(b.clientId)
|
||||
}
|
||||
if (a.timestamp !== b.timestamp) {
|
||||
return a.timestamp.localeCompare(b.timestamp)
|
||||
}
|
||||
return a.message.localeCompare(b.message)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 限制日志数量,避免内存溢出(最多保留10000条)
|
||||
if (allLogs.value.length > 10000) {
|
||||
// 保留最新的10000条
|
||||
allLogs.value = allLogs.value.slice(allLogs.value.length - 10000)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载日志失败:', error)
|
||||
} finally {
|
||||
isLoadingLogs = false
|
||||
}
|
||||
}
|
||||
|
||||
const filteredLogs = computed(() => {
|
||||
// 只在选择了特定客户端时过滤,否则显示所有日志
|
||||
if (selectedClientId.value) {
|
||||
// 使用缓存避免频繁创建新数组
|
||||
return allLogs.value.filter(log => log.clientId === selectedClientId.value)
|
||||
}
|
||||
return allLogs.value
|
||||
})
|
||||
|
||||
const clearLogs = async () => {
|
||||
if (!confirm('确定要清空日志吗?')) return
|
||||
try {
|
||||
if (selectedClientId.value) {
|
||||
await ClearConnectionLogs(selectedClientId.value)
|
||||
} else {
|
||||
// 清空所有客户端的日志
|
||||
for (const client of clients.value) {
|
||||
const clientId = `${client.addr}|${client.key}`
|
||||
await ClearConnectionLogs(clientId)
|
||||
}
|
||||
}
|
||||
allLogs.value = []
|
||||
showMessage('日志已清空', 'success')
|
||||
} catch (error) {
|
||||
console.error('清空日志失败:', error)
|
||||
showMessage('清空日志失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
// 检查是否在底部
|
||||
const isAtBottom = () => {
|
||||
if (!logContentRef.value) return true
|
||||
const { scrollTop, scrollHeight, clientHeight } = logContentRef.value
|
||||
// 允许5px的误差
|
||||
return scrollHeight - scrollTop - clientHeight <= 5
|
||||
}
|
||||
|
||||
// 滚动到底部
|
||||
const scrollToBottom = () => {
|
||||
nextTick(() => {
|
||||
if (logContentRef.value) {
|
||||
logContentRef.value.scrollTop = logContentRef.value.scrollHeight
|
||||
autoScroll.value = true
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// 用户滚动时检测是否还在底部
|
||||
const onLogScroll = () => {
|
||||
if (!isAtBottom()) {
|
||||
// 用户已滚上去,禁用自动滚动
|
||||
autoScroll.value = false
|
||||
} else {
|
||||
// 用户在底部,启用自动滚动
|
||||
autoScroll.value = true
|
||||
}
|
||||
}
|
||||
|
||||
// 监听日志内容变化,仅在用户在底部时自动滚动
|
||||
// 使用 immediate: false 和防抖逻辑避免频繁更新
|
||||
let scrollTimeout = null
|
||||
watch(filteredLogs, () => {
|
||||
// 清除之前的延时
|
||||
if (scrollTimeout) clearTimeout(scrollTimeout)
|
||||
|
||||
// 延迟 50ms 后执行滚动,避免频繁触发
|
||||
scrollTimeout = setTimeout(() => {
|
||||
if (autoScroll.value) {
|
||||
scrollToBottom()
|
||||
}
|
||||
}, 50)
|
||||
})
|
||||
|
||||
// 监听日志view激活,定期刷新日志
|
||||
let logRefreshInterval = null
|
||||
watch(activeView, (newView) => {
|
||||
// 清除旧的刷新间隔
|
||||
if (logRefreshInterval) {
|
||||
clearInterval(logRefreshInterval)
|
||||
logRefreshInterval = null
|
||||
}
|
||||
|
||||
if (newView === 'logs') {
|
||||
loadLogs()
|
||||
// 设置日志刷新间隔为 3 秒,减少频率避免页面频繁闪烁
|
||||
logRefreshInterval = setInterval(() => {
|
||||
loadLogs()
|
||||
}, 3000)
|
||||
}
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
// 直接初始化,因为 API 是静态导入的
|
||||
initWails()
|
||||
@@ -339,10 +555,21 @@ export default {
|
||||
const refreshInterval = setInterval(() => {
|
||||
loadClients()
|
||||
}, 2000)
|
||||
|
||||
// 如果初始视图是日志,则加载日志
|
||||
if (activeView.value === 'logs') {
|
||||
loadLogs()
|
||||
logRefreshInterval = setInterval(() => {
|
||||
loadLogs()
|
||||
}, 3000)
|
||||
}
|
||||
|
||||
// Cleanup interval on unmount
|
||||
return () => {
|
||||
clearInterval(refreshInterval)
|
||||
if (logRefreshInterval) {
|
||||
clearInterval(logRefreshInterval)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
@@ -351,10 +578,20 @@ export default {
|
||||
clients,
|
||||
commandInput,
|
||||
message,
|
||||
selectedClientId,
|
||||
allLogs,
|
||||
logContentRef,
|
||||
autoScroll,
|
||||
filteredLogs,
|
||||
addConnection,
|
||||
removeClient,
|
||||
toggleClient,
|
||||
getStatusLabel,
|
||||
clearLogs,
|
||||
loadLogs,
|
||||
onLogScroll,
|
||||
scrollToBottom,
|
||||
isAtBottom,
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -489,6 +726,29 @@ export default {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background: #2d3e54;
|
||||
color: #e8eef7;
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background: #3a4d66;
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.btn-secondary:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.btn-scroll-to-bottom {
|
||||
background: #f39c12;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-scroll-to-bottom:hover {
|
||||
background: #e67e22;
|
||||
}
|
||||
|
||||
/* Clients Grid */
|
||||
.clients-grid {
|
||||
display: grid;
|
||||
@@ -665,20 +925,128 @@ export default {
|
||||
.logs-view {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 15px;
|
||||
}
|
||||
|
||||
.logs-container {
|
||||
flex: 1;
|
||||
background: #1a2332;
|
||||
.logs-header {
|
||||
background: #0f1419;
|
||||
border: 1px solid #2d3e54;
|
||||
border-radius: 8px;
|
||||
padding: 15px;
|
||||
}
|
||||
|
||||
.logs-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.logs-controls label {
|
||||
font-size: 14px;
|
||||
color: #a8b5c8;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.client-select {
|
||||
padding: 8px 12px;
|
||||
background: #1a2332;
|
||||
border: 1px solid #2d3e54;
|
||||
border-radius: 6px;
|
||||
color: #e8eef7;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
flex: 1;
|
||||
min-width: 200px;
|
||||
}
|
||||
|
||||
.client-select:hover {
|
||||
border-color: #3a4d66;
|
||||
}
|
||||
|
||||
.client-select:focus {
|
||||
outline: none;
|
||||
border-color: #4a5d76;
|
||||
box-shadow: 0 0 0 2px rgba(74, 93, 118, 0.2);
|
||||
}
|
||||
|
||||
.logs-container {
|
||||
flex: 1;
|
||||
background: #0f1419;
|
||||
border: 1px solid #2d3e54;
|
||||
border-radius: 8px;
|
||||
padding: 15px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 300px;
|
||||
}
|
||||
|
||||
.log-content {
|
||||
flex: 1;
|
||||
font-family: 'Monaco', 'Courier New', monospace;
|
||||
font-size: 13px;
|
||||
color: #a8b5c8;
|
||||
overflow-y: auto;
|
||||
word-break: break-all;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.empty-logs {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
color: #5a6d7f;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.log-item {
|
||||
padding: 6px 0;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.log-timestamp {
|
||||
color: #5a6d7f;
|
||||
flex-shrink: 0;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.log-message {
|
||||
color: #a8b5c8;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.log-info .log-timestamp {
|
||||
color: #5a9fd4;
|
||||
}
|
||||
|
||||
.log-info .log-message {
|
||||
color: #a8b5c8;
|
||||
}
|
||||
|
||||
.log-success .log-timestamp {
|
||||
color: #2ecc71;
|
||||
}
|
||||
|
||||
.log-success .log-message {
|
||||
color: #2ecc71;
|
||||
}
|
||||
|
||||
.log-warning .log-timestamp {
|
||||
color: #f39c12;
|
||||
}
|
||||
|
||||
.log-warning .log-message {
|
||||
color: #f39c12;
|
||||
}
|
||||
|
||||
.log-error .log-timestamp {
|
||||
color: #e74c3c;
|
||||
}
|
||||
|
||||
.log-error .log-message {
|
||||
color: #e74c3c;
|
||||
}
|
||||
|
||||
/* Settings View */
|
||||
|
||||
@@ -6,6 +6,10 @@ export function AddShortcut(arg1:string):Promise<void>;
|
||||
|
||||
export function AddShortcutFromBase64(arg1:string):Promise<void>;
|
||||
|
||||
export function ClearConnectionLogs(arg1:string):Promise<void>;
|
||||
|
||||
export function GetConnectionLogs(arg1:string):Promise<Array<main.ConnectionLog>>;
|
||||
|
||||
export function GetShortcuts():Promise<Array<main.ShortClient>>;
|
||||
|
||||
export function RemoveShortcut(arg1:string,arg2:string,arg3:string):Promise<void>;
|
||||
|
||||
@@ -10,6 +10,14 @@ export function AddShortcutFromBase64(arg1) {
|
||||
return window['go']['main']['App']['AddShortcutFromBase64'](arg1);
|
||||
}
|
||||
|
||||
export function ClearConnectionLogs(arg1) {
|
||||
return window['go']['main']['App']['ClearConnectionLogs'](arg1);
|
||||
}
|
||||
|
||||
export function GetConnectionLogs(arg1) {
|
||||
return window['go']['main']['App']['GetConnectionLogs'](arg1);
|
||||
}
|
||||
|
||||
export function GetShortcuts() {
|
||||
return window['go']['main']['App']['GetShortcuts']();
|
||||
}
|
||||
|
||||
@@ -1,5 +1,23 @@
|
||||
export namespace main {
|
||||
|
||||
export class ConnectionLog {
|
||||
timestamp: string;
|
||||
message: string;
|
||||
type: string;
|
||||
clientId: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new ConnectionLog(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.timestamp = source["timestamp"];
|
||||
this.message = source["message"];
|
||||
this.type = source["type"];
|
||||
this.clientId = source["clientId"];
|
||||
}
|
||||
}
|
||||
export class ShortClient {
|
||||
name: string;
|
||||
addr: string;
|
||||
|
||||
Reference in New Issue
Block a user