12 커밋 444b05cac9 ... 887fca86ec

작성자 SHA1 메시지 날짜
  MHSanaei 887fca86ec fix(fail2ban): escape % in 3x-ipl action date format (#4218) 19 시간 전
  MHSanaei 6efc4b0665 Revert "perf(frontend): code-split heavy components to improve LCP" 20 시간 전
  MHSanaei 94a7dbfe3c fix(docker): pin frontend stage to BUILDPLATFORM and drop removed buildx input 21 시간 전
  qwardo e2649f98df fix(arch): correct x-ui service path (#4213) 21 시간 전
  MHSanaei 3d839e0ee1 v3.0.0 21 시간 전
  MHSanaei a96612f595 feat(xray/dns): align DNS settings with Xray docs + UI polish 21 시간 전
  MHSanaei 8e7d215b4a feat(nodes): traffic-writer queue, full-mirror sync, WS event fixes 22 시간 전
  Qiaochu Hu 24cd271486 Fix overly permissive file permissions (os.ModePerm) (#4207) 23 시간 전
  Qiaochu Hu dee2525d5f Fix silently ignored errors in password migration seeder (#4206) 23 시간 전
  Qiaochu Hu 81b4ae5661 Fix silently ignored error when saving outbound test URL setting (#4209) 23 시간 전
  Ali Fotouhi 9cbba130ab fix(xray): clear outbound test state on delete to prevent result bleed (#4205) 1 일 전
  MHSanaei cf5767acd1 i18n: localize sidebar theme toggle, xray-status badge, and nodes menu 1 일 전
87개의 변경된 파일1851개의 추가작업 그리고 1578개의 파일을 삭제
  1. 0 2
      .github/workflows/docker.yml
  2. 2 0
      .gitignore
  3. 2 2
      DockerEntrypoint.sh
  4. 1 1
      Dockerfile
  5. 2 2
      README.ar_EG.md
  6. 2 2
      README.es_ES.md
  7. 2 2
      README.fa_IR.md
  8. 2 2
      README.md
  9. 2 2
      README.ru_RU.md
  10. 2 2
      README.zh_CN.md
  11. 1 1
      config/version
  12. 33 6
      database/db.go
  13. 15 38
      frontend/src/components/AppSidebar.vue
  14. 6 2
      frontend/src/components/CustomStatistic.vue
  15. 21 31
      frontend/src/components/DateTimePicker.vue
  16. 71 103
      frontend/src/components/FinalMaskForm.vue
  17. 3 10
      frontend/src/components/InfinityIcon.vue
  18. 5 23
      frontend/src/components/PromptModal.vue
  19. 6 2
      frontend/src/components/SettingListItem.vue
  20. 16 66
      frontend/src/components/Sparkline.vue
  21. 15 4
      frontend/src/components/TableSortable.vue
  22. 7 8
      frontend/src/components/TextModal.vue
  23. 6 3
      frontend/src/components/ThemeSwitch.vue
  24. 1 1
      frontend/src/composables/useWebSocket.js
  25. 1 8
      frontend/src/models/status.js
  26. 1 1
      frontend/src/pages/inbounds/ClientFormModal.vue
  27. 12 3
      frontend/src/pages/inbounds/ClientRowTable.vue
  28. 4 12
      frontend/src/pages/inbounds/InboundFormModal.vue
  29. 8 14
      frontend/src/pages/inbounds/InboundInfoModal.vue
  30. 21 11
      frontend/src/pages/inbounds/InboundList.vue
  31. 15 14
      frontend/src/pages/inbounds/InboundsPage.vue
  32. 1 6
      frontend/src/pages/inbounds/QrPanel.vue
  33. 11 2
      frontend/src/pages/inbounds/useInbounds.js
  34. 62 27
      frontend/src/pages/index/LogModal.vue
  35. 8 8
      frontend/src/pages/index/StatusCard.vue
  36. 3 6
      frontend/src/pages/index/SystemHistoryModal.vue
  37. 33 7
      frontend/src/pages/index/XrayLogModal.vue
  38. 14 7
      frontend/src/pages/index/XrayStatusCard.vue
  39. 2 3
      frontend/src/pages/login/LoginPage.vue
  40. 7 28
      frontend/src/pages/nodes/NodeFormModal.vue
  41. 6 24
      frontend/src/pages/nodes/NodeHistoryPanel.vue
  42. 17 18
      frontend/src/pages/nodes/NodeList.vue
  43. 10 37
      frontend/src/pages/nodes/NodesPage.vue
  44. 1 6
      frontend/src/pages/settings/SecurityTab.vue
  45. 19 21
      frontend/src/pages/settings/SettingsPage.vue
  46. 38 34
      frontend/src/pages/sub/SubPage.vue
  47. 2 12
      frontend/src/pages/xray/BalancerFormModal.vue
  48. 103 0
      frontend/src/pages/xray/DnsPresetsModal.vue
  49. 71 49
      frontend/src/pages/xray/DnsServerModal.vue
  50. 197 59
      frontend/src/pages/xray/DnsTab.vue
  51. 3 7
      frontend/src/pages/xray/OutboundFormModal.vue
  52. 76 57
      frontend/src/pages/xray/OutboundsTab.vue
  53. 37 28
      frontend/src/pages/xray/RoutingTab.vue
  54. 35 23
      frontend/src/pages/xray/RuleFormModal.vue
  55. 38 24
      frontend/src/pages/xray/WarpModal.vue
  56. 51 82
      frontend/src/pages/xray/XrayPage.vue
  57. 0 25
      web/controller/node.go
  58. 4 1
      web/controller/xray_setting.go
  59. 5 30
      web/job/node_heartbeat_job.go
  60. 114 57
      web/job/node_traffic_sync_job.go
  61. 1 0
      web/job/xray_traffic_job.go
  62. 3 42
      web/runtime/local.go
  63. 0 39
      web/runtime/manager.go
  64. 3 89
      web/runtime/remote.go
  65. 0 42
      web/runtime/runtime.go
  66. 266 213
      web/service/inbound.go
  67. 0 46
      web/service/node.go
  68. 1 2
      web/service/server.go
  69. 87 0
      web/service/traffic_writer.go
  70. 17 1
      web/translation/ar-EG.json
  71. 16 1
      web/translation/en-US.json
  72. 17 1
      web/translation/es-ES.json
  73. 16 1
      web/translation/fa-IR.json
  74. 17 1
      web/translation/id-ID.json
  75. 17 1
      web/translation/ja-JP.json
  76. 17 1
      web/translation/pt-BR.json
  77. 17 1
      web/translation/ru-RU.json
  78. 17 1
      web/translation/tr-TR.json
  79. 17 1
      web/translation/uk-UA.json
  80. 17 1
      web/translation/vi-VN.json
  81. 17 1
      web/translation/zh-CN.json
  82. 17 1
      web/translation/zh-TW.json
  83. 6 7
      web/web.go
  84. 6 12
      web/websocket/hub.go
  85. 2 2
      x-ui.service.arch
  86. 2 2
      x-ui.sh
  87. 2 3
      xray/process.go

+ 0 - 2
.github/workflows/docker.yml

@@ -36,8 +36,6 @@ jobs:
 
       - name: Set up Docker Buildx
         uses: docker/setup-buildx-action@v4
-        with:
-          install: true
 
       - name: Login to Docker Hub
         uses: docker/login-action@v4

+ 2 - 0
.gitignore

@@ -33,6 +33,8 @@ Thumbs.db
 # Ignore Go build files
 *.exe
 x-ui.db
+x-ui.db-shm
+x-ui.db-wal
 
 # Ignore Docker specific files
 docker-compose.override.yml

+ 2 - 2
DockerEntrypoint.sh

@@ -43,10 +43,10 @@ actionstop = <iptables> -D <chain> -p <protocol> -j f2b-<name>
 actioncheck = <iptables> -n -L <chain> | grep -q 'f2b-<name>[ \t]'
 
 actionban = <iptables> -I f2b-<name> 1 -s <ip> -j <blocktype>
-            echo "\$(date +"%Y/%m/%d %H:%M:%S")   BAN   [Email] = <F-USER> [IP] = <ip> banned for <bantime> seconds." >> $LOG_FOLDER/3xipl-banned.log
+            echo "\$(date +"%%Y/%%m/%%d %%H:%%M:%%S")   BAN   [Email] = <F-USER> [IP] = <ip> banned for <bantime> seconds." >> $LOG_FOLDER/3xipl-banned.log
 
 actionunban = <iptables> -D f2b-<name> -s <ip> -j <blocktype>
-              echo "\$(date +"%Y/%m/%d %H:%M:%S")   UNBAN   [Email] = <F-USER> [IP] = <ip> unbanned." >> $LOG_FOLDER/3xipl-banned.log
+              echo "\$(date +"%%Y/%%m/%%d %%H:%%M:%%S")   UNBAN   [Email] = <F-USER> [IP] = <ip> unbanned." >> $LOG_FOLDER/3xipl-banned.log
 
 [Init]
 name = default

+ 1 - 1
Dockerfile

@@ -1,7 +1,7 @@
 # ========================================================
 # Stage: Frontend (Vite)
 # ========================================================
-FROM node:22-alpine AS frontend
+FROM --platform=$BUILDPLATFORM node:22-alpine AS frontend
 WORKDIR /src/frontend
 COPY frontend/package.json frontend/package-lock.json ./
 RUN npm ci

+ 2 - 2
README.ar_EG.md

@@ -12,8 +12,8 @@
 [![GO Version](https://img.shields.io/github/go-mod/go-version/mhsanaei/3x-ui.svg)](#)
 [![Downloads](https://img.shields.io/github/downloads/mhsanaei/3x-ui/total.svg)](https://github.com/MHSanaei/3x-ui/releases/latest)
 [![License](https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true)](https://www.gnu.org/licenses/gpl-3.0.en.html)
-[![Go Reference](https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v2.svg)](https://pkg.go.dev/github.com/mhsanaei/3x-ui/v2)
-[![Go Report Card](https://goreportcard.com/badge/github.com/mhsanaei/3x-ui/v2)](https://goreportcard.com/report/github.com/mhsanaei/3x-ui/v2)
+[![Go Reference](https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v3.svg)](https://pkg.go.dev/github.com/mhsanaei/3x-ui/v3)
+[![Go Report Card](https://goreportcard.com/badge/github.com/mhsanaei/3x-ui/v3)](https://goreportcard.com/report/github.com/mhsanaei/3x-ui/v3)
 
 **3X-UI** — لوحة تحكم متقدمة مفتوحة المصدر تعتمد على الويب مصممة لإدارة خادم Xray-core. توفر واجهة سهلة الاستخدام لتكوين ومراقبة بروتوكولات VPN والوكيل المختلفة.
 

+ 2 - 2
README.es_ES.md

@@ -12,8 +12,8 @@
 [![GO Version](https://img.shields.io/github/go-mod/go-version/mhsanaei/3x-ui.svg)](#)
 [![Downloads](https://img.shields.io/github/downloads/mhsanaei/3x-ui/total.svg)](https://github.com/MHSanaei/3x-ui/releases/latest)
 [![License](https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true)](https://www.gnu.org/licenses/gpl-3.0.en.html)
-[![Go Reference](https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v2.svg)](https://pkg.go.dev/github.com/mhsanaei/3x-ui/v2)
-[![Go Report Card](https://goreportcard.com/badge/github.com/mhsanaei/3x-ui/v2)](https://goreportcard.com/report/github.com/mhsanaei/3x-ui/v2)
+[![Go Reference](https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v3.svg)](https://pkg.go.dev/github.com/mhsanaei/3x-ui/v3)
+[![Go Report Card](https://goreportcard.com/badge/github.com/mhsanaei/3x-ui/v3)](https://goreportcard.com/report/github.com/mhsanaei/3x-ui/v3)
 
 **3X-UI** — panel de control avanzado basado en web de código abierto diseñado para gestionar el servidor Xray-core. Ofrece una interfaz fácil de usar para configurar y monitorear varios protocolos VPN y proxy.
 

+ 2 - 2
README.fa_IR.md

@@ -12,8 +12,8 @@
 [![GO Version](https://img.shields.io/github/go-mod/go-version/mhsanaei/3x-ui.svg)](#)
 [![Downloads](https://img.shields.io/github/downloads/mhsanaei/3x-ui/total.svg)](https://github.com/MHSanaei/3x-ui/releases/latest)
 [![License](https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true)](https://www.gnu.org/licenses/gpl-3.0.en.html)
-[![Go Reference](https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v2.svg)](https://pkg.go.dev/github.com/mhsanaei/3x-ui/v2)
-[![Go Report Card](https://goreportcard.com/badge/github.com/mhsanaei/3x-ui/v2)](https://goreportcard.com/report/github.com/mhsanaei/3x-ui/v2)
+[![Go Reference](https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v3.svg)](https://pkg.go.dev/github.com/mhsanaei/3x-ui/v3)
+[![Go Report Card](https://goreportcard.com/badge/github.com/mhsanaei/3x-ui/v3)](https://goreportcard.com/report/github.com/mhsanaei/3x-ui/v3)
 
 **3X-UI** — یک پنل کنترل پیشرفته مبتنی بر وب با کد باز که برای مدیریت سرور Xray-core طراحی شده است. این پنل یک رابط کاربری آسان برای پیکربندی و نظارت بر پروتکل‌های مختلف VPN و پراکسی ارائه می‌دهد.
 

+ 2 - 2
README.md

@@ -12,8 +12,8 @@
 [![GO Version](https://img.shields.io/github/go-mod/go-version/mhsanaei/3x-ui.svg)](#)
 [![Downloads](https://img.shields.io/github/downloads/mhsanaei/3x-ui/total.svg)](https://github.com/MHSanaei/3x-ui/releases/latest)
 [![License](https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true)](https://www.gnu.org/licenses/gpl-3.0.en.html)
-[![Go Reference](https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v2.svg)](https://pkg.go.dev/github.com/mhsanaei/3x-ui/v2)
-[![Go Report Card](https://goreportcard.com/badge/github.com/mhsanaei/3x-ui/v2)](https://goreportcard.com/report/github.com/mhsanaei/3x-ui/v2)
+[![Go Reference](https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v3.svg)](https://pkg.go.dev/github.com/mhsanaei/3x-ui/v3)
+[![Go Report Card](https://goreportcard.com/badge/github.com/mhsanaei/3x-ui/v3)](https://goreportcard.com/report/github.com/mhsanaei/3x-ui/v3)
 
 **3X-UI** — advanced, open-source web-based control panel designed for managing Xray-core server. It offers a user-friendly interface for configuring and monitoring various VPN and proxy protocols.
 

+ 2 - 2
README.ru_RU.md

@@ -12,8 +12,8 @@
 [![GO Version](https://img.shields.io/github/go-mod/go-version/mhsanaei/3x-ui.svg)](#)
 [![Downloads](https://img.shields.io/github/downloads/mhsanaei/3x-ui/total.svg)](https://github.com/MHSanaei/3x-ui/releases/latest)
 [![License](https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true)](https://www.gnu.org/licenses/gpl-3.0.en.html)
-[![Go Reference](https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v2.svg)](https://pkg.go.dev/github.com/mhsanaei/3x-ui/v2)
-[![Go Report Card](https://goreportcard.com/badge/github.com/mhsanaei/3x-ui/v2)](https://goreportcard.com/report/github.com/mhsanaei/3x-ui/v2)
+[![Go Reference](https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v3.svg)](https://pkg.go.dev/github.com/mhsanaei/3x-ui/v3)
+[![Go Report Card](https://goreportcard.com/badge/github.com/mhsanaei/3x-ui/v3)](https://goreportcard.com/report/github.com/mhsanaei/3x-ui/v3)
 
 **3X-UI** — продвинутая панель управления с открытым исходным кодом на основе веб-интерфейса, разработанная для управления сервером Xray-core. Предоставляет удобный интерфейс для настройки и мониторинга различных VPN и прокси-протоколов.
 

+ 2 - 2
README.zh_CN.md

@@ -12,8 +12,8 @@
 [![GO Version](https://img.shields.io/github/go-mod/go-version/mhsanaei/3x-ui.svg)](#)
 [![Downloads](https://img.shields.io/github/downloads/mhsanaei/3x-ui/total.svg)](https://github.com/MHSanaei/3x-ui/releases/latest)
 [![License](https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true)](https://www.gnu.org/licenses/gpl-3.0.en.html)
-[![Go Reference](https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v2.svg)](https://pkg.go.dev/github.com/mhsanaei/3x-ui/v2)
-[![Go Report Card](https://goreportcard.com/badge/github.com/mhsanaei/3x-ui/v2)](https://goreportcard.com/report/github.com/mhsanaei/3x-ui/v2)
+[![Go Reference](https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v3.svg)](https://pkg.go.dev/github.com/mhsanaei/3x-ui/v3)
+[![Go Report Card](https://goreportcard.com/badge/github.com/mhsanaei/3x-ui/v3)](https://goreportcard.com/report/github.com/mhsanaei/3x-ui/v3)
 
 **3X-UI** — 一个基于网页的高级开源控制面板,专为管理 Xray-core 服务器而设计。它提供了用户友好的界面,用于配置和监控各种 VPN 和代理协议。
 

+ 1 - 1
config/version

@@ -1 +1 @@
-2.9.4
+3.0.0

+ 33 - 6
database/db.go

@@ -6,11 +6,11 @@ import (
 	"bytes"
 	"errors"
 	"io"
-	"io/fs"
 	"log"
 	"os"
 	"path"
 	"slices"
+	"time"
 
 	"github.com/mhsanaei/3x-ui/v3/config"
 	"github.com/mhsanaei/3x-ui/v3/database/model"
@@ -89,11 +89,17 @@ func runSeeders(isUsersEmpty bool) error {
 		return db.Create(hashSeeder).Error
 	} else {
 		var seedersHistory []string
-		db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &seedersHistory)
+		if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &seedersHistory).Error; err != nil {
+			log.Printf("Error fetching seeder history: %v", err)
+			return err
+		}
 
 		if !slices.Contains(seedersHistory, "UserPasswordHash") && !isUsersEmpty {
 			var users []model.User
-			db.Find(&users)
+			if err := db.Find(&users).Error; err != nil {
+				log.Printf("Error fetching users for password migration: %v", err)
+				return err
+			}
 
 			for _, user := range users {
 				hashedPassword, err := crypto.HashPasswordAsBcrypt(user.Password)
@@ -101,7 +107,10 @@ func runSeeders(isUsersEmpty bool) error {
 					log.Printf("Error hashing password for user '%s': %v", user.Username, err)
 					return err
 				}
-				db.Model(&user).Update("password", hashedPassword)
+				if err := db.Model(&user).Update("password", hashedPassword).Error; err != nil {
+					log.Printf("Error updating password for user '%s': %v", user.Username, err)
+					return err
+				}
 			}
 
 			hashSeeder := &model.HistoryOfSeeders{
@@ -124,7 +133,7 @@ func isTableEmpty(tableName string) (bool, error) {
 // InitDB sets up the database connection, migrates models, and runs seeders.
 func InitDB(dbPath string) error {
 	dir := path.Dir(dbPath)
-	err := os.MkdirAll(dir, fs.ModePerm)
+	err := os.MkdirAll(dir, 0755)
 	if err != nil {
 		return err
 	}
@@ -140,11 +149,29 @@ func InitDB(dbPath string) error {
 	c := &gorm.Config{
 		Logger: gormLogger,
 	}
-	db, err = gorm.Open(sqlite.Open(dbPath), c)
+	dsn := dbPath + "?_journal_mode=WAL&_busy_timeout=10000&_synchronous=NORMAL&_txlock=immediate"
+	db, err = gorm.Open(sqlite.Open(dsn), c)
 	if err != nil {
 		return err
 	}
 
+	sqlDB, err := db.DB()
+	if err != nil {
+		return err
+	}
+	if _, err := sqlDB.Exec("PRAGMA journal_mode=WAL"); err != nil {
+		return err
+	}
+	if _, err := sqlDB.Exec("PRAGMA busy_timeout=10000"); err != nil {
+		return err
+	}
+	if _, err := sqlDB.Exec("PRAGMA synchronous=NORMAL"); err != nil {
+		return err
+	}
+	sqlDB.SetMaxOpenConns(8)
+	sqlDB.SetMaxIdleConns(4)
+	sqlDB.SetConnMaxLifetime(time.Hour)
+
 	if err := initModels(); err != nil {
 		return err
 	}

+ 15 - 38
frontend/src/components/AppSidebar.vue

@@ -50,12 +50,12 @@ const prefix = props.basePath?.startsWith('/') ? props.basePath : `/${props.base
 // Labels are i18n-driven so the sidebar matches the locale picked
 // in panel settings without a page reload of the sidebar component.
 const tabs = computed(() => [
-  { key: `${prefix}panel/`,         icon: 'dashboard', title: t('menu.dashboard') },
-  { key: `${prefix}panel/inbounds`, icon: 'user',      title: t('menu.inbounds') },
-  { key: `${prefix}panel/nodes`,    icon: 'cluster',   title: t('menu.nodes') },
-  { key: `${prefix}panel/settings`, icon: 'setting',   title: t('menu.settings') },
-  { key: `${prefix}panel/xray`,     icon: 'tool',      title: t('menu.xray') },
-  { key: `${prefix}logout`,         icon: 'logout',    title: t('logout') },
+  { key: `${prefix}panel/`, icon: 'dashboard', title: t('menu.dashboard') },
+  { key: `${prefix}panel/inbounds`, icon: 'user', title: t('menu.inbounds') },
+  { key: `${prefix}panel/nodes`, icon: 'cluster', title: t('menu.nodes') },
+  { key: `${prefix}panel/settings`, icon: 'setting', title: t('menu.settings') },
+  { key: `${prefix}panel/xray`, icon: 'tool', title: t('menu.xray') },
+  { key: `${prefix}logout`, icon: 'logout', title: t('logout') },
 ]);
 
 const activeTab = ref([props.requestUri]);
@@ -90,20 +90,9 @@ function closeDrawer() {
 
 <template>
   <div class="ant-sidebar">
-    <a-layout-sider
-      :theme="currentTheme"
-      collapsible
-      :collapsed="collapsed"
-      breakpoint="md"
-      @collapse="onCollapse"
-    >
+    <a-layout-sider :theme="currentTheme" collapsible :collapsed="collapsed" breakpoint="md" @collapse="onCollapse">
       <ThemeSwitch />
-      <a-menu
-        :theme="currentTheme"
-        mode="inline"
-        :selected-keys="activeTab"
-        @click="({ key }) => openLink(key)"
-      >
+      <a-menu :theme="currentTheme" mode="inline" :selected-keys="activeTab" @click="({ key }) => openLink(key)">
         <a-menu-item v-for="tab in tabs" :key="tab.key">
           <component :is="iconByName[tab.icon]" />
           <span>{{ tab.title }}</span>
@@ -111,22 +100,10 @@ function closeDrawer() {
       </a-menu>
     </a-layout-sider>
 
-    <a-drawer
-      placement="left"
-      :closable="false"
-      :open="drawerOpen"
-      :wrap-class-name="currentTheme"
-      :wrap-style="{ padding: 0 }"
-      :style="{ height: '100%' }"
-      @close="closeDrawer"
-    >
+    <a-drawer placement="left" :closable="false" :open="drawerOpen" :wrap-class-name="currentTheme"
+      :wrap-style="{ padding: 0 }" :style="{ height: '100%' }" @close="closeDrawer">
       <ThemeSwitch />
-      <a-menu
-        :theme="currentTheme"
-        mode="inline"
-        :selected-keys="activeTab"
-        @click="({ key }) => openLink(key)"
-      >
+      <a-menu :theme="currentTheme" mode="inline" :selected-keys="activeTab" @click="({ key }) => openLink(key)">
         <a-menu-item v-for="tab in tabs" :key="tab.key">
           <component :is="iconByName[tab.icon]" />
           <span>{{ tab.title }}</span>
@@ -142,7 +119,7 @@ function closeDrawer() {
 </template>
 
 <style scoped>
-.ant-sidebar > .ant-layout-sider {
+.ant-sidebar>.ant-layout-sider {
   height: 100%;
 }
 
@@ -171,12 +148,12 @@ function closeDrawer() {
   /* On mobile the drawer is the menu — hide the inline sider's content
    * + the collapse trigger so the sider stops taking layout space and
    * leaves no remnant button next to the page. */
-  .ant-sidebar > .ant-layout-sider :deep(.ant-layout-sider-children),
-  .ant-sidebar > .ant-layout-sider :deep(.ant-layout-sider-trigger) {
+  .ant-sidebar>.ant-layout-sider :deep(.ant-layout-sider-children),
+  .ant-sidebar>.ant-layout-sider :deep(.ant-layout-sider-trigger) {
     display: none;
   }
 
-  .ant-sidebar > .ant-layout-sider {
+  .ant-sidebar>.ant-layout-sider {
     flex: 0 0 0 !important;
     max-width: 0 !important;
     min-width: 0 !important;

+ 6 - 2
frontend/src/components/CustomStatistic.vue

@@ -7,8 +7,12 @@ defineProps({
 
 <template>
   <a-statistic :title="title" :value="value">
-    <template #prefix><slot name="prefix" /></template>
-    <template #suffix><slot name="suffix" /></template>
+    <template #prefix>
+      <slot name="prefix" />
+    </template>
+    <template #suffix>
+      <slot name="suffix" />
+    </template>
   </a-statistic>
 </template>
 

+ 21 - 31
frontend/src/components/DateTimePicker.vue

@@ -1,9 +1,17 @@
 <script setup>
-import { computed, defineAsyncComponent } from 'vue';
+import { computed } from 'vue';
 import dayjs from 'dayjs';
+import PersianDatePicker from 'vue3-persian-datetime-picker';
 import { useDatepicker } from '@/composables/useDatepicker.js';
 
-const PersianDatePicker = defineAsyncComponent(() => import('vue3-persian-datetime-picker'));
+// Drop-in replacement for <a-date-picker> that swaps to a real Jalali
+// calendar (vue3-persian-datetime-picker, backed by moment-jalaali)
+// when the panel's "Calendar Type" setting is `jalalian`.
+//
+// The v-model contract matches AD-Vue: the parent works with a dayjs
+// object (or null). For the persian picker we serialize to/from the
+// `YYYY-MM-DD HH:mm:ss` string it expects so callers don't need to
+// know which renderer is active.
 
 const props = defineProps({
   value: { type: [Object, null], default: null },
@@ -51,29 +59,11 @@ function onAntChange(next) {
 </script>
 
 <template>
-  <PersianDatePicker
-    v-if="isJalali"
-    v-model="stringValue"
-    :format="ISO_FORMAT"
-    :display-format="persianDisplayFormat"
-    :placeholder="placeholder"
-    :disabled="disabled"
-    color="#1677ff"
-    auto-submit
-    append-to="body"
-    input-class="ant-input persian-datepicker-input"
-    class="jalali-datepicker"
-  />
-  <a-date-picker
-    v-else
-    :value="value"
-    :show-time="showTime ? { format: 'HH:mm:ss' } : false"
-    :format="format"
-    :placeholder="placeholder"
-    :disabled="disabled"
-    :style="{ width: '100%' }"
-    @update:value="onAntChange"
-  />
+  <PersianDatePicker v-if="isJalali" v-model="stringValue" :format="ISO_FORMAT" :display-format="persianDisplayFormat"
+    :placeholder="placeholder" :disabled="disabled" color="#1677ff" auto-submit append-to="body"
+    input-class="ant-input persian-datepicker-input" class="jalali-datepicker" />
+  <a-date-picker v-else :value="value" :show-time="showTime ? { format: 'HH:mm:ss' } : false" :format="format"
+    :placeholder="placeholder" :disabled="disabled" :style="{ width: '100%' }" @update:value="onAntChange" />
 </template>
 
 <style scoped>
@@ -142,8 +132,8 @@ function onAntChange(next) {
   background: #fff;
   color: rgba(0, 0, 0, 0.88);
   box-shadow: 0 6px 16px 0 rgba(0, 0, 0, 0.08),
-              0 3px 6px -4px rgba(0, 0, 0, 0.12),
-              0 9px 28px 8px rgba(0, 0, 0, 0.05);
+    0 3px 6px -4px rgba(0, 0, 0, 0.12),
+    0 9px 28px 8px rgba(0, 0, 0, 0.05);
   border-radius: 8px;
   overflow: hidden;
 }
@@ -166,7 +156,7 @@ function onAntChange(next) {
 }
 
 .vpd-wrapper .vpd-body .vpd-month-label,
-.vpd-wrapper .vpd-body .vpd-month-label > span {
+.vpd-wrapper .vpd-body .vpd-month-label>span {
   color: rgba(0, 0, 0, 0.88);
 }
 
@@ -271,8 +261,8 @@ body.dark .vpd-wrapper .vpd-content {
   background: #1a2c4d;
   color: rgba(255, 255, 255, 0.88);
   box-shadow: 0 6px 16px 0 rgba(0, 0, 0, 0.32),
-              0 3px 6px -4px rgba(0, 0, 0, 0.48),
-              0 9px 28px 8px rgba(0, 0, 0, 0.2);
+    0 3px 6px -4px rgba(0, 0, 0, 0.48),
+    0 9px 28px 8px rgba(0, 0, 0, 0.2);
 }
 
 body.dark .vpd-wrapper .vpd-body {
@@ -281,7 +271,7 @@ body.dark .vpd-wrapper .vpd-body {
 }
 
 body.dark .vpd-wrapper .vpd-body .vpd-month-label,
-body.dark .vpd-wrapper .vpd-body .vpd-month-label > span {
+body.dark .vpd-wrapper .vpd-body .vpd-month-label>span {
   color: rgba(255, 255, 255, 0.88);
 }
 

+ 71 - 103
frontend/src/components/FinalMaskForm.vue

@@ -66,27 +66,23 @@ function newNoiseItem() {
 </script>
 
 <template>
-  <a-form
-    v-if="showTcp || showUdp || showQuic"
-    :colon="false"
-    :label-col="{ md: { span: 8 } }"
-    :wrapper-col="{ md: { span: 14 } }"
-  >
+  <a-form v-if="showTcp || showUdp || showQuic" :colon="false" :label-col="{ md: { span: 8 } }"
+    :wrapper-col="{ md: { span: 14 } }">
     <!-- ============================== TCP MASKS ============================== -->
     <template v-if="showTcp">
       <a-form-item label="TCP Masks">
         <a-button type="primary" size="small" @click="stream.addTcpMask('fragment')">
-          <template #icon><PlusOutlined /></template>
+          <template #icon>
+            <PlusOutlined />
+          </template>
         </a-button>
       </a-form-item>
 
       <template v-for="(mask, mIdx) in (stream.finalmask.tcp || [])" :key="`tcp-${mIdx}`">
         <a-divider :style="{ margin: '0' }">
           TCP Mask {{ mIdx + 1 }}
-          <DeleteOutlined
-            :style="{ color: 'rgb(255, 77, 79)', cursor: 'pointer', marginLeft: '8px' }"
-            @click="stream.delTcpMask(mIdx)"
-          />
+          <DeleteOutlined :style="{ color: 'rgb(255, 77, 79)', cursor: 'pointer', marginLeft: '8px' }"
+            @click="stream.delTcpMask(mIdx)" />
         </a-divider>
 
         <a-form-item label="Type">
@@ -144,16 +140,16 @@ function newNoiseItem() {
           <!-- Clients -->
           <a-form-item label="Clients">
             <a-button type="primary" size="small" @click="mask.settings.clients.push([newClientServerItem()])">
-              <template #icon><PlusOutlined /></template>
+              <template #icon>
+                <PlusOutlined />
+              </template>
             </a-button>
           </a-form-item>
           <template v-for="(group, gi) in mask.settings.clients" :key="`tcp-cg-${mIdx}-${gi}`">
             <a-divider :style="{ margin: '0' }">
               Clients Group {{ gi + 1 }}
-              <DeleteOutlined
-                :style="{ color: 'rgb(255, 77, 79)', cursor: 'pointer', marginLeft: '8px' }"
-                @click="mask.settings.clients.splice(gi, 1)"
-              />
+              <DeleteOutlined :style="{ color: 'rgb(255, 77, 79)', cursor: 'pointer', marginLeft: '8px' }"
+                @click="mask.settings.clients.splice(gi, 1)" />
             </a-divider>
             <template v-for="(item, ii) in group" :key="`tcp-ci-${mIdx}-${gi}-${ii}`">
               <a-form-item label="Type">
@@ -177,13 +173,12 @@ function newNoiseItem() {
               </template>
               <a-form-item v-else label="Packet">
                 <a-input-group v-if="item.type === 'base64'" compact>
-                  <a-input
-                    v-model:value="item.packet"
-                    placeholder="binary data"
-                    :style="{ width: 'calc(100% - 32px)' }"
-                  />
+                  <a-input v-model:value="item.packet" placeholder="binary data"
+                    :style="{ width: 'calc(100% - 32px)' }" />
                   <a-button @click="item.packet = RandomUtil.randomBase64()">
-                    <template #icon><ReloadOutlined /></template>
+                    <template #icon>
+                      <ReloadOutlined />
+                    </template>
                   </a-button>
                 </a-input-group>
                 <a-input v-else v-model:value="item.packet" placeholder="binary data" />
@@ -194,16 +189,16 @@ function newNoiseItem() {
           <!-- Servers -->
           <a-form-item label="Servers">
             <a-button type="primary" size="small" @click="mask.settings.servers.push([newClientServerItem()])">
-              <template #icon><PlusOutlined /></template>
+              <template #icon>
+                <PlusOutlined />
+              </template>
             </a-button>
           </a-form-item>
           <template v-for="(group, gi) in mask.settings.servers" :key="`tcp-sg-${mIdx}-${gi}`">
             <a-divider :style="{ margin: '0' }">
               Servers Group {{ gi + 1 }}
-              <DeleteOutlined
-                :style="{ color: 'rgb(255, 77, 79)', cursor: 'pointer', marginLeft: '8px' }"
-                @click="mask.settings.servers.splice(gi, 1)"
-              />
+              <DeleteOutlined :style="{ color: 'rgb(255, 77, 79)', cursor: 'pointer', marginLeft: '8px' }"
+                @click="mask.settings.servers.splice(gi, 1)" />
             </a-divider>
             <template v-for="(item, ii) in group" :key="`tcp-si-${mIdx}-${gi}-${ii}`">
               <a-form-item label="Type">
@@ -227,13 +222,12 @@ function newNoiseItem() {
               </template>
               <a-form-item v-else label="Packet">
                 <a-input-group v-if="item.type === 'base64'" compact>
-                  <a-input
-                    v-model:value="item.packet"
-                    placeholder="binary data"
-                    :style="{ width: 'calc(100% - 32px)' }"
-                  />
+                  <a-input v-model:value="item.packet" placeholder="binary data"
+                    :style="{ width: 'calc(100% - 32px)' }" />
                   <a-button @click="item.packet = RandomUtil.randomBase64()">
-                    <template #icon><ReloadOutlined /></template>
+                    <template #icon>
+                      <ReloadOutlined />
+                    </template>
                   </a-button>
                 </a-input-group>
                 <a-input v-else v-model:value="item.packet" placeholder="binary data" />
@@ -248,17 +242,17 @@ function newNoiseItem() {
     <template v-if="showUdp">
       <a-form-item label="UDP Masks">
         <a-button type="primary" size="small" @click="addUdpMaskWithDefault">
-          <template #icon><PlusOutlined /></template>
+          <template #icon>
+            <PlusOutlined />
+          </template>
         </a-button>
       </a-form-item>
 
       <template v-for="(mask, mIdx) in (stream.finalmask.udp || [])" :key="`udp-${mIdx}`">
         <a-divider :style="{ margin: '0' }">
           UDP Mask {{ mIdx + 1 }}
-          <DeleteOutlined
-            :style="{ color: 'rgb(255, 77, 79)', cursor: 'pointer', marginLeft: '8px' }"
-            @click="stream.delUdpMask(mIdx)"
-          />
+          <DeleteOutlined :style="{ color: 'rgb(255, 77, 79)', cursor: 'pointer', marginLeft: '8px' }"
+            @click="stream.delUdpMask(mIdx)" />
         </a-divider>
 
         <a-form-item label="Type">
@@ -290,13 +284,8 @@ function newNoiseItem() {
           <a-input v-model:value="mask.settings.domain" placeholder="e.g., www.example.com" />
         </a-form-item>
         <a-form-item v-if="mask.type === 'xdns'" label="Domains">
-          <a-select
-            v-model:value="mask.settings.domains"
-            mode="tags"
-            :style="{ width: '100%' }"
-            :token-separators="[',']"
-            placeholder="e.g., www.example.com"
-          />
+          <a-select v-model:value="mask.settings.domains" mode="tags" :style="{ width: '100%' }"
+            :token-separators="[',']" placeholder="e.g., www.example.com" />
         </a-form-item>
 
         <!-- Noise -->
@@ -306,16 +295,16 @@ function newNoiseItem() {
           </a-form-item>
           <a-form-item label="Noise">
             <a-button type="primary" size="small" @click="mask.settings.noise.push(newNoiseItem())">
-              <template #icon><PlusOutlined /></template>
+              <template #icon>
+                <PlusOutlined />
+              </template>
             </a-button>
           </a-form-item>
           <template v-for="(n, ni) in mask.settings.noise" :key="`udp-noise-${mIdx}-${ni}`">
             <a-divider :style="{ margin: '0' }">
               Noise {{ ni + 1 }}
-              <DeleteOutlined
-                :style="{ color: 'rgb(255, 77, 79)', cursor: 'pointer', marginLeft: '8px' }"
-                @click="mask.settings.noise.splice(ni, 1)"
-              />
+              <DeleteOutlined :style="{ color: 'rgb(255, 77, 79)', cursor: 'pointer', marginLeft: '8px' }"
+                @click="mask.settings.noise.splice(ni, 1)" />
             </a-divider>
             <a-form-item label="Type">
               <a-select :value="n.type" @change="(t) => changeItemType(n, t)">
@@ -335,13 +324,11 @@ function newNoiseItem() {
             </template>
             <a-form-item v-else label="Packet">
               <a-input-group v-if="n.type === 'base64'" compact>
-                <a-input
-                  v-model:value="n.packet"
-                  placeholder="binary data"
-                  :style="{ width: 'calc(100% - 32px)' }"
-                />
+                <a-input v-model:value="n.packet" placeholder="binary data" :style="{ width: 'calc(100% - 32px)' }" />
                 <a-button @click="n.packet = RandomUtil.randomBase64()">
-                  <template #icon><ReloadOutlined /></template>
+                  <template #icon>
+                    <ReloadOutlined />
+                  </template>
                 </a-button>
               </a-input-group>
               <a-input v-else v-model:value="n.packet" placeholder="binary data" />
@@ -356,16 +343,16 @@ function newNoiseItem() {
         <template v-if="mask.type === 'header-custom'">
           <a-form-item label="Client">
             <a-button type="primary" size="small" @click="mask.settings.client.push(newUdpClientServerItem())">
-              <template #icon><PlusOutlined /></template>
+              <template #icon>
+                <PlusOutlined />
+              </template>
             </a-button>
           </a-form-item>
           <template v-for="(c, ci) in mask.settings.client" :key="`udp-c-${mIdx}-${ci}`">
             <a-divider :style="{ margin: '0' }">
               Client {{ ci + 1 }}
-              <DeleteOutlined
-                :style="{ color: 'rgb(255, 77, 79)', cursor: 'pointer', marginLeft: '8px' }"
-                @click="mask.settings.client.splice(ci, 1)"
-              />
+              <DeleteOutlined :style="{ color: 'rgb(255, 77, 79)', cursor: 'pointer', marginLeft: '8px' }"
+                @click="mask.settings.client.splice(ci, 1)" />
             </a-divider>
             <a-form-item label="Type">
               <a-select :value="c.type" @change="(t) => changeItemType(c, t)">
@@ -385,13 +372,11 @@ function newNoiseItem() {
             </template>
             <a-form-item v-else label="Packet">
               <a-input-group v-if="c.type === 'base64'" compact>
-                <a-input
-                  v-model:value="c.packet"
-                  placeholder="binary data"
-                  :style="{ width: 'calc(100% - 32px)' }"
-                />
+                <a-input v-model:value="c.packet" placeholder="binary data" :style="{ width: 'calc(100% - 32px)' }" />
                 <a-button @click="c.packet = RandomUtil.randomBase64()">
-                  <template #icon><ReloadOutlined /></template>
+                  <template #icon>
+                    <ReloadOutlined />
+                  </template>
                 </a-button>
               </a-input-group>
               <a-input v-else v-model:value="c.packet" placeholder="binary data" />
@@ -401,16 +386,16 @@ function newNoiseItem() {
           <a-divider :style="{ margin: '0' }" />
           <a-form-item label="Server">
             <a-button type="primary" size="small" @click="mask.settings.server.push(newUdpClientServerItem())">
-              <template #icon><PlusOutlined /></template>
+              <template #icon>
+                <PlusOutlined />
+              </template>
             </a-button>
           </a-form-item>
           <template v-for="(s, si) in mask.settings.server" :key="`udp-s-${mIdx}-${si}`">
             <a-divider :style="{ margin: '0' }">
               Server {{ si + 1 }}
-              <DeleteOutlined
-                :style="{ color: 'rgb(255, 77, 79)', cursor: 'pointer', marginLeft: '8px' }"
-                @click="mask.settings.server.splice(si, 1)"
-              />
+              <DeleteOutlined :style="{ color: 'rgb(255, 77, 79)', cursor: 'pointer', marginLeft: '8px' }"
+                @click="mask.settings.server.splice(si, 1)" />
             </a-divider>
             <a-form-item label="Type">
               <a-select :value="s.type" @change="(t) => changeItemType(s, t)">
@@ -430,13 +415,11 @@ function newNoiseItem() {
             </template>
             <a-form-item v-else label="Packet">
               <a-input-group v-if="s.type === 'base64'" compact>
-                <a-input
-                  v-model:value="s.packet"
-                  placeholder="binary data"
-                  :style="{ width: 'calc(100% - 32px)' }"
-                />
+                <a-input v-model:value="s.packet" placeholder="binary data" :style="{ width: 'calc(100% - 32px)' }" />
                 <a-button @click="s.packet = RandomUtil.randomBase64()">
-                  <template #icon><ReloadOutlined /></template>
+                  <template #icon>
+                    <ReloadOutlined />
+                  </template>
                 </a-button>
               </a-input-group>
               <a-input v-else v-model:value="s.packet" placeholder="binary data" />
@@ -502,39 +485,24 @@ function newNoiseItem() {
           <a-switch v-model:checked="stream.finalmask.quicParams.disablePathMTUDiscovery" />
         </a-form-item>
         <a-form-item label="Max Incoming Streams">
-          <a-input-number
-            v-model:value="stream.finalmask.quicParams.maxIncomingStreams"
-            :min="8"
-            placeholder="1024 = default"
-          />
+          <a-input-number v-model:value="stream.finalmask.quicParams.maxIncomingStreams" :min="8"
+            placeholder="1024 = default" />
         </a-form-item>
         <a-form-item label="Init Stream Window">
-          <a-input-number
-            v-model:value="stream.finalmask.quicParams.initStreamReceiveWindow"
-            :min="16384"
-            placeholder="8388608 = default"
-          />
+          <a-input-number v-model:value="stream.finalmask.quicParams.initStreamReceiveWindow" :min="16384"
+            placeholder="8388608 = default" />
         </a-form-item>
         <a-form-item label="Max Stream Window">
-          <a-input-number
-            v-model:value="stream.finalmask.quicParams.maxStreamReceiveWindow"
-            :min="16384"
-            placeholder="8388608 = default"
-          />
+          <a-input-number v-model:value="stream.finalmask.quicParams.maxStreamReceiveWindow" :min="16384"
+            placeholder="8388608 = default" />
         </a-form-item>
         <a-form-item label="Init Conn Window">
-          <a-input-number
-            v-model:value="stream.finalmask.quicParams.initConnectionReceiveWindow"
-            :min="16384"
-            placeholder="20971520 = default"
-          />
+          <a-input-number v-model:value="stream.finalmask.quicParams.initConnectionReceiveWindow" :min="16384"
+            placeholder="20971520 = default" />
         </a-form-item>
         <a-form-item label="Max Conn Window">
-          <a-input-number
-            v-model:value="stream.finalmask.quicParams.maxConnectionReceiveWindow"
-            :min="16384"
-            placeholder="20971520 = default"
-          />
+          <a-input-number v-model:value="stream.finalmask.quicParams.maxConnectionReceiveWindow" :min="16384"
+            placeholder="20971520 = default" />
         </a-form-item>
       </template>
     </template>

+ 3 - 10
frontend/src/components/InfinityIcon.vue

@@ -10,16 +10,9 @@ defineProps({
 </script>
 
 <template>
-  <svg
-    :width="width"
-    :height="height"
-    viewBox="0 0 640 512"
-    fill="currentColor"
-    aria-hidden="true"
-    style="vertical-align: -1px; display: inline-block;"
-  >
+  <svg :width="width" :height="height" viewBox="0 0 640 512" fill="currentColor" aria-hidden="true"
+    style="vertical-align: -1px; display: inline-block;">
     <path
-      d="M484.4 96C407 96 349.2 164.1 320 208.5C290.8 164.1 233 96 155.6 96C69.75 96 0 167.8 0 256s69.75 160 155.6 160C233.1 416 290.8 347.9 320 303.5C349.2 347.9 407 416 484.4 416C570.3 416 640 344.2 640 256S570.3 96 484.4 96zM155.6 368C96.25 368 48 317.8 48 256s48.25-112 107.6-112c67.75 0 120.5 82.25 137.1 112C276 285.8 223.4 368 155.6 368zM484.4 368c-67.75 0-120.5-82.25-137.1-112C364 226.2 416.6 144 484.4 144C543.8 144 592 194.2 592 256S543.8 368 484.4 368z"
-    />
+      d="M484.4 96C407 96 349.2 164.1 320 208.5C290.8 164.1 233 96 155.6 96C69.75 96 0 167.8 0 256s69.75 160 155.6 160C233.1 416 290.8 347.9 320 303.5C349.2 347.9 407 416 484.4 416C570.3 416 640 344.2 640 256S570.3 96 484.4 96zM155.6 368C96.25 368 48 317.8 48 256s48.25-112 107.6-112c67.75 0 120.5 82.25 137.1 112C276 285.8 223.4 368 155.6 368zM484.4 368c-67.75 0-120.5-82.25-137.1-112C364 226.2 416.6 144 484.4 144C543.8 144 592 194.2 592 256S543.8 368 484.4 368z" />
   </svg>
 </template>

+ 5 - 23
frontend/src/components/PromptModal.vue

@@ -43,28 +43,10 @@ function onKeydown(e) {
 </script>
 
 <template>
-  <a-modal
-    :open="open"
-    :title="title"
-    :ok-text="okText"
-    cancel-text="Cancel"
-    :mask-closable="false"
-    :confirm-loading="loading"
-    @ok="ok"
-    @cancel="close"
-  >
-    <a-textarea
-      v-if="type === 'textarea'"
-      v-model:value="value"
-      :auto-size="{ minRows: 10, maxRows: 20 }"
-      autofocus
-      @keydown="onKeydown"
-    />
-    <a-input
-      v-else
-      v-model:value="value"
-      autofocus
-      @keydown="onKeydown"
-    />
+  <a-modal :open="open" :title="title" :ok-text="okText" cancel-text="Cancel" :mask-closable="false"
+    :confirm-loading="loading" @ok="ok" @cancel="close">
+    <a-textarea v-if="type === 'textarea'" v-model:value="value" :auto-size="{ minRows: 10, maxRows: 20 }" autofocus
+      @keydown="onKeydown" />
+    <a-input v-else v-model:value="value" autofocus @keydown="onKeydown" />
   </a-modal>
 </template>

+ 6 - 2
frontend/src/components/SettingListItem.vue

@@ -19,8 +19,12 @@ const padding = computed(() =>
     <a-row :gutter="[8, 16]">
       <a-col :xs="24" :lg="12">
         <a-list-item-meta>
-          <template #title><slot name="title" /></template>
-          <template #description><slot name="description" /></template>
+          <template #title>
+            <slot name="title" />
+          </template>
+          <template #description>
+            <slot name="description" />
+          </template>
         </a-list-item-meta>
       </a-col>
       <a-col :xs="24" :lg="12">

+ 16 - 66
frontend/src/components/Sparkline.vue

@@ -220,16 +220,8 @@ const gradId = `spkGrad-${Math.random().toString(36).slice(2, 9)}`;
 </script>
 
 <template>
-  <svg
-    ref="svgRef"
-    width="100%"
-    :height="height"
-    :viewBox="viewBoxAttr"
-    preserveAspectRatio="none"
-    class="sparkline-svg"
-    @mousemove="onMouseMove"
-    @mouseleave="onMouseLeave"
-  >
+  <svg ref="svgRef" width="100%" :height="height" :viewBox="viewBoxAttr" preserveAspectRatio="none"
+    class="sparkline-svg" @mousemove="onMouseMove" @mouseleave="onMouseLeave">
     <defs>
       <linearGradient :id="gradId" x1="0" y1="0" x2="0" y2="1">
         <stop offset="0%" :stop-color="stroke" :stop-opacity="fillOpacity" />
@@ -238,70 +230,28 @@ const gradId = `spkGrad-${Math.random().toString(36).slice(2, 9)}`;
     </defs>
 
     <g v-if="showGrid">
-      <line
-        v-for="(g, i) in gridLines"
-        :key="i"
-        :x1="g.x1" :y1="g.y1" :x2="g.x2" :y2="g.y2"
-        :stroke="gridColor" stroke-width="1"
-        class="cpu-grid-line"
-      />
+      <line v-for="(g, i) in gridLines" :key="i" :x1="g.x1" :y1="g.y1" :x2="g.x2" :y2="g.y2" :stroke="gridColor"
+        stroke-width="1" class="cpu-grid-line" />
     </g>
 
     <g v-if="showAxes">
-      <text
-        v-for="(t, i) in yTicks"
-        :key="'y' + i"
-        class="cpu-grid-y-text"
-        :x="Math.max(0, paddingLeft - 4)"
-        :y="t.y + 4"
-        text-anchor="end"
-        font-size="10"
-      >{{ t.label }}</text>
-      <text
-        v-for="(t, i) in xTicks"
-        :key="'x' + i"
-        class="cpu-grid-x-text"
-        :x="t.x"
-        :y="paddingTop + drawHeight + 14"
-        text-anchor="middle"
-        font-size="10"
-      >{{ t.label }}</text>
+      <text v-for="(t, i) in yTicks" :key="'y' + i" class="cpu-grid-y-text" :x="Math.max(0, paddingLeft - 4)"
+        :y="t.y + 4" text-anchor="end" font-size="10">{{ t.label }}</text>
+      <text v-for="(t, i) in xTicks" :key="'x' + i" class="cpu-grid-x-text" :x="t.x" :y="paddingTop + drawHeight + 14"
+        text-anchor="middle" font-size="10">{{ t.label }}</text>
     </g>
 
     <path v-if="areaPath" :d="areaPath" :fill="`url(#${gradId})`" stroke="none" />
-    <polyline
-      :points="pointsStr"
-      fill="none"
-      :stroke="stroke"
-      :stroke-width="strokeWidth"
-      stroke-linecap="round"
-      stroke-linejoin="round"
-    />
-    <circle
-      v-if="showMarker && lastPoint"
-      :cx="lastPoint[0]" :cy="lastPoint[1]"
-      :r="markerRadius"
-      :fill="stroke"
-    />
+    <polyline :points="pointsStr" fill="none" :stroke="stroke" :stroke-width="strokeWidth" stroke-linecap="round"
+      stroke-linejoin="round" />
+    <circle v-if="showMarker && lastPoint" :cx="lastPoint[0]" :cy="lastPoint[1]" :r="markerRadius" :fill="stroke" />
 
     <g v-if="showTooltip && hoverIdx >= 0 && pointsArr[hoverIdx]">
-      <line
-        class="cpu-grid-h-line"
-        :x1="pointsArr[hoverIdx][0]" :x2="pointsArr[hoverIdx][0]"
-        :y1="paddingTop" :y2="paddingTop + drawHeight"
-        stroke="rgba(0,0,0,0.2)" stroke-width="1"
-      />
-      <circle
-        :cx="pointsArr[hoverIdx][0]" :cy="pointsArr[hoverIdx][1]"
-        r="3.5" :fill="stroke"
-      />
-      <text
-        class="cpu-grid-text"
-        :x="pointsArr[hoverIdx][0]"
-        :y="paddingTop + 12"
-        text-anchor="middle"
-        font-size="11"
-      >{{ fmtHoverText() }}</text>
+      <line class="cpu-grid-h-line" :x1="pointsArr[hoverIdx][0]" :x2="pointsArr[hoverIdx][0]" :y1="paddingTop"
+        :y2="paddingTop + drawHeight" stroke="rgba(0,0,0,0.2)" stroke-width="1" />
+      <circle :cx="pointsArr[hoverIdx][0]" :cy="pointsArr[hoverIdx][1]" r="3.5" :fill="stroke" />
+      <text class="cpu-grid-text" :x="pointsArr[hoverIdx][0]" :y="paddingTop + 12" text-anchor="middle"
+        font-size="11">{{ fmtHoverText() }}</text>
     </g>
   </svg>
 </template>

+ 15 - 4
frontend/src/components/TableSortable.vue

@@ -266,33 +266,44 @@ export default defineComponent({
   user-select: none;
   touch-action: none;
 }
+
 .sortable-icon:hover {
   color: rgba(255, 255, 255, 0.85);
   background: rgba(255, 255, 255, 0.06);
 }
-.sortable-icon:active { cursor: grabbing; }
+
+.sortable-icon:active {
+  cursor: grabbing;
+}
+
 .sortable-icon:focus-visible {
   outline: 2px solid #008771;
   outline-offset: 2px;
 }
 
-.light .sortable-icon { color: rgba(0, 0, 0, 0.45); }
+.light .sortable-icon {
+  color: rgba(0, 0, 0, 0.45);
+}
+
 .light .sortable-icon:hover {
   color: rgba(0, 0, 0, 0.85);
   background: rgba(0, 0, 0, 0.05);
 }
 
-.sortable-table-dragging .sortable-source-row > td {
+.sortable-table-dragging .sortable-source-row>td {
   background: rgba(0, 135, 113, 0.10) !important;
   transition: background-color 0.18s ease;
 }
+
 .sortable-table-dragging .sortable-source-row .routing-index,
 .sortable-table-dragging .sortable-source-row .outbound-index {
   opacity: 0.45;
 }
-.sortable-table-dragging .sortable-row > td {
+
+.sortable-table-dragging .sortable-row>td {
   transition: background-color 0.18s ease;
 }
+
 .sortable-table-dragging,
 .sortable-table-dragging * {
   user-select: none;

+ 7 - 8
frontend/src/components/TextModal.vue

@@ -39,19 +39,18 @@ function download(content, name) {
 
 <template>
   <a-modal :open="open" :title="title" :closable="true" @cancel="close">
-    <a-textarea
-      :value="content"
-      readonly
-      :auto-size="{ minRows: 10, maxRows: 20 }"
-      class="text-modal-content"
-    />
+    <a-textarea :value="content" readonly :auto-size="{ minRows: 10, maxRows: 20 }" class="text-modal-content" />
     <template #footer>
       <a-button v-if="fileName" @click="download(content, fileName)">
-        <template #icon><DownloadOutlined /></template>
+        <template #icon>
+          <DownloadOutlined />
+        </template>
         {{ fileName }}
       </a-button>
       <a-button type="primary" @click="copy(content)">
-        <template #icon><CopyOutlined /></template>
+        <template #icon>
+          <CopyOutlined />
+        </template>
         Copy
       </a-button>
     </template>

+ 6 - 3
frontend/src/components/ThemeSwitch.vue

@@ -1,8 +1,11 @@
 <script setup>
 import { computed } from 'vue';
+import { useI18n } from 'vue-i18n';
 import { BulbFilled, BulbOutlined } from '@ant-design/icons-vue';
 import { theme, currentTheme, toggleTheme, toggleUltra, pauseAnimationsUntilLeave } from '@/composables/useTheme.js';
 
+const { t } = useI18n();
+
 const BulbIcon = computed(() => (theme.isDark ? BulbFilled : BulbOutlined));
 
 function onDarkChange() {
@@ -22,17 +25,17 @@ function onUltraClick() {
       <template #title>
         <span>
           <component :is="BulbIcon" />
-          <span class="theme-label">Theme</span>
+          <span class="theme-label">{{ t('menu.theme') }}</span>
         </span>
       </template>
 
       <a-menu-item id="change-theme" class="ant-menu-theme-switch">
-        <span>Dark</span>
+        <span>{{ t('menu.dark') }}</span>
         <a-switch :style="{ marginLeft: '2px' }" size="small" :checked="theme.isDark" @change="onDarkChange" />
       </a-menu-item>
 
       <a-menu-item v-if="theme.isDark" id="change-theme-ultra" class="ant-menu-theme-switch">
-        <span>Ultra dark</span>
+        <span>{{ t('menu.ultraDark') }}</span>
         <a-checkbox :style="{ marginLeft: '2px' }" :checked="theme.isUltra" @click="onUltraClick" />
       </a-menu-item>
     </a-sub-menu>

+ 1 - 1
frontend/src/composables/useWebSocket.js

@@ -24,7 +24,7 @@ function getSharedClient() {
 //   useWebSocket({
 //     traffic: (payload) => applyTrafficEvent(payload),
 //     client_stats: (payload) => applyClientStatsEvent(payload),
-//     invalidate: ({ dataType }) => { if (dataType === 'inbounds') refresh(); },
+//     invalidate: ({ type }) => { if (type === 'inbounds') refresh(); },
 //   });
 //
 // Built-in lifecycle events ('connected' / 'disconnected' / 'error')

+ 1 - 8
frontend/src/models/status.js

@@ -27,12 +27,6 @@ const XRAY_STATE_COLORS = {
   error: 'red',
 };
 
-const XRAY_STATE_MESSAGES = {
-  running: 'Xray is running',
-  stop: 'Xray is stopped',
-  error: 'Xray error',
-};
-
 export class Status {
   constructor(data) {
     this.cpu = new CurTotal(0, 0);
@@ -51,7 +45,7 @@ export class Status {
     this.uptime = 0;
     this.appUptime = 0;
     this.appStats = { threads: 0, mem: 0, uptime: 0 };
-    this.xray = { state: 'stop', stateMsg: '', errorMsg: '', version: '', color: '' };
+    this.xray = { state: 'stop', errorMsg: '', version: '', color: '' };
 
     if (data == null) return;
 
@@ -73,6 +67,5 @@ export class Status {
     this.appStats = data.appStats ?? this.appStats;
     this.xray = { ...this.xray, ...(data.xray || {}) };
     this.xray.color = XRAY_STATE_COLORS[this.xray.state] ?? 'gray';
-    this.xray.stateMsg = XRAY_STATE_MESSAGES[this.xray.state] ?? 'Unknown';
   }
 }

+ 1 - 1
frontend/src/pages/inbounds/ClientFormModal.vue

@@ -362,7 +362,7 @@ const title = computed(() =>
       <a-form-item v-else>
         <template #label>
           <a-tooltip :title="t('pages.inbounds.leaveBlankToNeverExpire')">{{ t('pages.inbounds.expireDate')
-            }}</a-tooltip>
+          }}</a-tooltip>
         </template>
         <DateTimePicker v-model:value="expiryDate" />
         <a-tag v-if="mode === 'edit' && isExpired" color="red">{{ t('depleted') }}</a-tag>

+ 12 - 3
frontend/src/pages/inbounds/ClientRowTable.vue

@@ -291,8 +291,8 @@ function rowKey(client) {
               {{ IntlUtil.formatRelativeTime(client.expiryTime) }}
             </a-tag>
           </a-popover>
-          <a-tag v-else :color="ColorUtils.userExpiryColor(expireDiff, client, isDarkTheme)"
-            :style="{ border: 'none' }" class="infinite-tag">
+          <a-tag v-else :color="ColorUtils.userExpiryColor(expireDiff, client, isDarkTheme)" :style="{ border: 'none' }"
+            class="infinite-tag">
             <InfinityIcon />
           </a-tag>
         </div>
@@ -373,7 +373,9 @@ function rowKey(client) {
             <a-tag v-else-if="client.expiryTime < 0" color="green">
               {{ -client.expiryTime / 86400000 }}d ({{ t('pages.client.delayedStart') }})
             </a-tag>
-            <a-tag v-else color="purple"><InfinityIcon /></a-tag>
+            <a-tag v-else color="purple">
+              <InfinityIcon />
+            </a-tag>
           </div>
         </div>
       </div>
@@ -561,6 +563,7 @@ function rowKey(client) {
   flex-direction: column;
   gap: 6px;
 }
+
 :global(body.dark) .client-card {
   border-color: rgba(255, 255, 255, 0.1);
 }
@@ -571,6 +574,7 @@ function rowKey(client) {
   gap: 8px;
   min-width: 0;
 }
+
 .client-card-head .client-email {
   flex: 1;
   min-width: 0;
@@ -580,6 +584,7 @@ function rowKey(client) {
   overflow: hidden;
   text-overflow: ellipsis;
 }
+
 .client-card-actions {
   margin-left: auto;
   display: flex;
@@ -587,6 +592,7 @@ function rowKey(client) {
   gap: 8px;
   flex-shrink: 0;
 }
+
 .client-card-actions .row-icon {
   font-size: 20px;
   padding: 4px;
@@ -605,12 +611,14 @@ function rowKey(client) {
   flex-direction: column;
   gap: 4px;
 }
+
 .client-card-foot .stat-row {
   display: flex;
   align-items: center;
   flex-wrap: wrap;
   gap: 6px;
 }
+
 .client-card-foot .stat-label {
   font-size: 10px;
   text-transform: uppercase;
@@ -619,6 +627,7 @@ function rowKey(client) {
   min-width: 96px;
   flex-shrink: 0;
 }
+
 .client-card-foot :deep(.ant-tag) {
   margin: 0;
 }

+ 4 - 12
frontend/src/pages/inbounds/InboundFormModal.vue

@@ -560,19 +560,11 @@ watch(
             <a-input v-model:value="dbForm.remark" />
           </a-form-item>
           <a-form-item :label="t('pages.inbounds.deployTo')">
-            <a-select
-              v-model:value="dbForm.nodeId"
-              :disabled="mode === 'edit'"
-              :placeholder="t('pages.inbounds.localPanel')"
-              allow-clear
-            >
+            <a-select v-model:value="dbForm.nodeId" :disabled="mode === 'edit'"
+              :placeholder="t('pages.inbounds.localPanel')" allow-clear>
               <a-select-option :value="null">{{ t('pages.inbounds.localPanel') }}</a-select-option>
-              <a-select-option
-                v-for="n in selectableNodes"
-                :key="n.id"
-                :value="n.id"
-                :disabled="n.status === 'offline'"
-              >
+              <a-select-option v-for="n in selectableNodes" :key="n.id" :value="n.id"
+                :disabled="n.status === 'offline'">
                 {{ n.name }}{{ n.status === 'offline' ? ' (offline)' : '' }}
               </a-select-option>
             </a-select>

+ 8 - 14
frontend/src/pages/inbounds/InboundInfoModal.vue

@@ -327,14 +327,16 @@ const showSubscriptionTab = computed(
               <tr>
                 <td>{{ t('pages.inbounds.createdAt') }}</td>
                 <td>
-                  <a-tag v-if="clientSettings.created_at">{{ IntlUtil.formatDate(clientSettings.created_at, datepicker) }}</a-tag>
+                  <a-tag v-if="clientSettings.created_at">{{ IntlUtil.formatDate(clientSettings.created_at, datepicker)
+                  }}</a-tag>
                   <a-tag v-else>-</a-tag>
                 </td>
               </tr>
               <tr>
                 <td>{{ t('pages.inbounds.updatedAt') }}</td>
                 <td>
-                  <a-tag v-if="clientSettings.updated_at">{{ IntlUtil.formatDate(clientSettings.updated_at, datepicker) }}</a-tag>
+                  <a-tag v-if="clientSettings.updated_at">{{ IntlUtil.formatDate(clientSettings.updated_at, datepicker)
+                  }}</a-tag>
                   <a-tag v-else>-</a-tag>
                 </td>
               </tr>
@@ -356,7 +358,7 @@ const showSubscriptionTab = computed(
                   <div class="ip-log">
                     <div v-if="clientIpsArray.length > 0">
                       <a-tag v-for="(item, idx) in clientIpsArray" :key="idx" color="blue" class="ip-log-row">{{ item
-                        }}</a-tag>
+                      }}</a-tag>
                     </div>
                     <a-tag v-else>{{ clientIpsText || t('tgbot.noIpRecord') }}</a-tag>
                   </div>
@@ -472,7 +474,7 @@ const showSubscriptionTab = computed(
                 </a-tooltip>
               </div>
               <a :href="subJsonLink" target="_blank" rel="noopener noreferrer" class="link-panel-anchor">{{ subJsonLink
-                }}</a>
+              }}</a>
             </div>
           </template>
         </a-tab-pane>
@@ -627,11 +629,7 @@ const showSubscriptionTab = computed(
               <dd><a-tag class="value-tag">{{ inbound.settings.ip }}</a-tag></dd>
             </div>
             <template v-if="inbound.settings.auth === 'password' && inbound.settings.accounts?.length">
-              <div
-                v-for="(account, idx) in inbound.settings.accounts"
-                :key="idx"
-                class="info-row"
-              >
+              <div v-for="(account, idx) in inbound.settings.accounts" :key="idx" class="info-row">
                 <dt>{{ t('username') }} #{{ idx + 1 }}</dt>
                 <dd class="account-row">
                   <a-tag color="green" class="value-tag">{{ account.user }}</a-tag>
@@ -651,11 +649,7 @@ const showSubscriptionTab = computed(
 
           <!-- HTTP accounts -->
           <dl v-if="dbInbound.isHTTP && inbound.settings.accounts?.length" class="info-list info-list-block">
-            <div
-              v-for="(account, idx) in inbound.settings.accounts"
-              :key="idx"
-              class="info-row"
-            >
+            <div v-for="(account, idx) in inbound.settings.accounts" :key="idx" class="info-row">
               <dt>{{ t('username') }} #{{ idx + 1 }}</dt>
               <dd class="account-row">
                 <a-tag color="green" class="value-tag">{{ account.user }}</a-tag>

+ 21 - 11
frontend/src/pages/inbounds/InboundList.vue

@@ -276,8 +276,7 @@ function showQrCodeMenu(dbInbound) {
             <span class="card-id">#{{ record.id }}</span>
             <span class="tag-name">{{ record.remark }}</span>
             <div class="card-actions" @click.stop>
-              <a-switch :checked="record.enable" size="small"
-                @change="(next) => onSwitchEnable(record, next)" />
+              <a-switch :checked="record.enable" size="small" @change="(next) => onSwitchEnable(record, next)" />
               <a-dropdown :trigger="['click']" placement="bottomRight">
                 <MoreOutlined class="row-action-trigger" @click.prevent />
                 <template #overlay>
@@ -391,17 +390,17 @@ function showQrCodeMenu(dbInbound) {
                 :color="ColorUtils.usageColor(Date.now(), expireDiff, record._expiryTime)">
                 {{ IntlUtil.formatRelativeTime(record.expiryTime) }}
               </a-tag>
-              <a-tag v-else color="purple"><InfinityIcon /></a-tag>
+              <a-tag v-else color="purple">
+                <InfinityIcon />
+              </a-tag>
             </div>
           </div>
 
           <!-- Expanded client list (multi-user only) -->
           <div v-if="record.isMultiUser() && isExpanded(record.id)" class="card-clients">
-            <ClientRowTable :db-inbound="record" :is-mobile="true"
-              :traffic-diff="trafficDiff" :expire-diff="expireDiff" :online-clients="onlineClients"
-              :last-online-map="lastOnlineMap" :is-dark-theme="isDarkTheme"
-              @edit-client="(p) => emit('edit-client', p)"
-              @qrcode-client="(p) => emit('qrcode-client', p)"
+            <ClientRowTable :db-inbound="record" :is-mobile="true" :traffic-diff="trafficDiff" :expire-diff="expireDiff"
+              :online-clients="onlineClients" :last-online-map="lastOnlineMap" :is-dark-theme="isDarkTheme"
+              @edit-client="(p) => emit('edit-client', p)" @qrcode-client="(p) => emit('qrcode-client', p)"
               @info-client="(p) => emit('info-client', p)"
               @reset-traffic-client="(p) => emit('reset-traffic-client', p)"
               @delete-client="(p) => emit('delete-client', p)"
@@ -412,8 +411,7 @@ function showQrCodeMenu(dbInbound) {
 
       <!-- ====================== Desktop: a-table ======================== -->
       <a-table v-else :columns="columns" :data-source="visibleInbounds" :row-key="(r) => r.id"
-        :pagination="paginationFor(visibleInbounds)" :scroll="{ x: 1000 }"
-        :style="{ marginTop: '10px' }" size="small"
+        :pagination="paginationFor(visibleInbounds)" :scroll="{ x: 1000 }" :style="{ marginTop: '10px' }" size="small"
         :row-class-name="(r) => (r.isMultiUser() ? '' : 'hide-expand-icon')">
         <!-- Per-inbound client list, expanded by clicking the row's
              default expand chevron. Hidden via row-class-name for
@@ -697,6 +695,7 @@ function showQrCodeMenu(dbInbound) {
   flex-direction: column;
   gap: 8px;
 }
+
 :global(body.dark) .inbound-card {
   background: rgba(255, 255, 255, 0.03);
   border-color: rgba(255, 255, 255, 0.1);
@@ -709,10 +708,12 @@ function showQrCodeMenu(dbInbound) {
   cursor: pointer;
   user-select: none;
 }
+
 .card-id {
   font-size: 11px;
   opacity: 0.6;
 }
+
 .tag-name {
   font-weight: 600;
   flex: 1;
@@ -721,18 +722,21 @@ function showQrCodeMenu(dbInbound) {
   text-overflow: ellipsis;
   white-space: nowrap;
 }
+
 .card-actions {
   display: flex;
   align-items: center;
   gap: 8px;
   flex-shrink: 0;
 }
+
 .card-expand {
   font-size: 12px;
   opacity: 0.6;
   transition: transform 150ms ease;
   flex-shrink: 0;
 }
+
 .card-expand.is-expanded {
   transform: rotate(90deg);
 }
@@ -742,12 +746,14 @@ function showQrCodeMenu(dbInbound) {
   flex-direction: column;
   gap: 6px;
 }
+
 .stat-row {
   display: flex;
   align-items: center;
   flex-wrap: wrap;
   gap: 6px;
 }
+
 .stat-label {
   font-size: 10px;
   text-transform: uppercase;
@@ -756,6 +762,7 @@ function showQrCodeMenu(dbInbound) {
   min-width: 96px;
   flex-shrink: 0;
 }
+
 .card-stats :deep(.ant-tag) {
   margin: 0;
 }
@@ -777,10 +784,12 @@ function showQrCodeMenu(dbInbound) {
     padding: 0 12px;
     min-height: 44px;
   }
+
   :deep(.ant-card-head-title),
   :deep(.ant-card-extra) {
     padding: 8px 0;
   }
+
   :deep(.ant-card-body) {
     padding: 8px;
   }
@@ -790,7 +799,8 @@ function showQrCodeMenu(dbInbound) {
     flex-wrap: wrap;
     gap: 6px;
   }
-  .filter-bar.mobile > * {
+
+  .filter-bar.mobile>* {
     margin-bottom: 0;
   }
 

+ 15 - 14
frontend/src/pages/inbounds/InboundsPage.vue

@@ -1,5 +1,5 @@
 <script setup>
-import { computed, defineAsyncComponent, onMounted, ref } from 'vue';
+import { computed, onMounted, ref } from 'vue';
 import { useI18n } from 'vue-i18n';
 import { Modal, message } from 'ant-design-vue';
 import {
@@ -18,17 +18,16 @@ import AppSidebar from '@/components/AppSidebar.vue';
 import CustomStatistic from '@/components/CustomStatistic.vue';
 import { useNodeList } from '@/composables/useNodeList.js';
 import InboundList from './InboundList.vue';
+import InboundFormModal from './InboundFormModal.vue';
+import ClientFormModal from './ClientFormModal.vue';
+import ClientBulkModal from './ClientBulkModal.vue';
+import InboundInfoModal from './InboundInfoModal.vue';
+import QrCodeModal from './QrCodeModal.vue';
+import TextModal from '@/components/TextModal.vue';
+import PromptModal from '@/components/PromptModal.vue';
 import { useInbounds } from './useInbounds.js';
 import { useWebSocket } from '@/composables/useWebSocket.js';
 
-const InboundFormModal = defineAsyncComponent(() => import('./InboundFormModal.vue'));
-const ClientFormModal = defineAsyncComponent(() => import('./ClientFormModal.vue'));
-const ClientBulkModal = defineAsyncComponent(() => import('./ClientBulkModal.vue'));
-const InboundInfoModal = defineAsyncComponent(() => import('./InboundInfoModal.vue'));
-const QrCodeModal = defineAsyncComponent(() => import('./QrCodeModal.vue'));
-const TextModal = defineAsyncComponent(() => import('@/components/TextModal.vue'));
-const PromptModal = defineAsyncComponent(() => import('@/components/PromptModal.vue'));
-
 const { t } = useI18n();
 
 const {
@@ -50,6 +49,7 @@ const {
   applyTrafficEvent,
   applyClientStatsEvent,
   applyInvalidate,
+  applyInboundsEvent,
 } = useInbounds();
 
 // Live updates over WebSocket — replaces the old 5s polling loop.
@@ -60,6 +60,7 @@ useWebSocket({
   traffic: applyTrafficEvent,
   client_stats: applyClientStatsEvent,
   invalidate: applyInvalidate,
+  inbounds: applyInboundsEvent,
 });
 const { isMobile } = useMediaQuery();
 // Node list lives on the central panel; the Inbounds page consumes
@@ -606,11 +607,11 @@ function onRowAction({ key, dbInbound }) {
               <!-- Inbound list — toolbar, search/filter, columns, row actions -->
               <a-col :span="24">
                 <InboundList :db-inbounds="dbInbounds" :client-count="clientCount" :online-clients="onlineClients"
-                  :last-online-map="lastOnlineMap" :is-dark-theme="themeState.isDark"
-                  :expire-diff="expireDiff" :traffic-diff="trafficDiff" :page-size="pageSize" :is-mobile="isMobile"
-                  :sub-enable="subSettings.enable" :nodes-by-id="nodesById" @refresh="refresh" @add-inbound="onAddInbound"
-                  @general-action="onGeneralAction" @row-action="onRowAction" @edit-client="onEditClient"
-                  @qrcode-client="onQrcodeClient" @info-client="onInfoClient"
+                  :last-online-map="lastOnlineMap" :is-dark-theme="themeState.isDark" :expire-diff="expireDiff"
+                  :traffic-diff="trafficDiff" :page-size="pageSize" :is-mobile="isMobile"
+                  :sub-enable="subSettings.enable" :nodes-by-id="nodesById" @refresh="refresh"
+                  @add-inbound="onAddInbound" @general-action="onGeneralAction" @row-action="onRowAction"
+                  @edit-client="onEditClient" @qrcode-client="onQrcodeClient" @info-client="onInfoClient"
                   @reset-traffic-client="onResetTrafficClient" @delete-client="onDeleteClient"
                   @toggle-enable-client="onToggleEnableClient" />
               </a-col>

+ 1 - 6
frontend/src/pages/inbounds/QrPanel.vue

@@ -107,11 +107,7 @@ function download() {
       </a-tooltip>
     </div>
     <div v-if="showQr" class="qr-panel-canvas">
-      <canvas
-        ref="canvas"
-        :style="{ width: `${size}px`, height: `${size}px` }"
-        @click="copy"
-      />
+      <canvas ref="canvas" :style="{ width: `${size}px`, height: `${size}px` }" @click="copy" />
     </div>
   </div>
 </template>
@@ -154,5 +150,4 @@ function download() {
   image-rendering: pixelated;
   image-rendering: crisp-edges;
 }
-
 </style>

+ 11 - 2
frontend/src/pages/inbounds/useInbounds.js

@@ -191,6 +191,8 @@ export function useInbounds() {
         if (typeof upd.up === 'number') ib.up = upd.up;
         if (typeof upd.down === 'number') ib.down = upd.down;
         if (typeof upd.allTime === 'number') ib.allTime = upd.allTime;
+        if (typeof upd.total === 'number') ib.total = upd.total;
+        if (typeof upd.enable === 'boolean') ib.enable = upd.enable;
         touched = true;
       }
     }
@@ -209,14 +211,15 @@ export function useInbounds() {
           if (typeof upd.up === 'number') stat.up = upd.up;
           if (typeof upd.down === 'number') stat.down = upd.down;
           if (typeof upd.total === 'number') stat.total = upd.total;
+          if (typeof upd.allTime === 'number') stat.allTime = upd.allTime;
           if (typeof upd.expiryTime === 'number') stat.expiryTime = upd.expiryTime;
+          if (typeof upd.enable === 'boolean') stat.enable = upd.enable;
           touched = true;
         }
       }
     }
 
     if (touched) {
-      // shallowRef → trigger reactivity by reassigning the same array.
       dbInbounds.value = [...dbInbounds.value];
       rebuildClientCount();
     }
@@ -228,11 +231,16 @@ export function useInbounds() {
   // re-fetch via REST".
   function applyInvalidate(payload) {
     if (!payload || typeof payload !== 'object') return;
-    if (payload.dataType === 'inbounds') {
+    if (payload.type === 'inbounds') {
       refresh();
     }
   }
 
+  function applyInboundsEvent(payload) {
+    if (!Array.isArray(payload)) return;
+    setInbounds(payload);
+  }
+
   // Recompute the per-inbound roll-up after any in-place mutation.
   // Cheap because rollupClients only iterates a single inbound's
   // clients + clientStats arrays.
@@ -319,5 +327,6 @@ export function useInbounds() {
     applyTrafficEvent,
     applyClientStatsEvent,
     applyInvalidate,
+    applyInboundsEvent,
   };
 }

+ 62 - 27
frontend/src/pages/index/LogModal.vue

@@ -89,8 +89,8 @@ const modalWidth = computed(() => (isMobile.value ? '100vw' : '800px'));
 </script>
 
 <template>
-  <a-modal :open="open" :closable="true" :footer="null" :width="modalWidth"
-    :class="{ 'logmodal-mobile': isMobile }" @cancel="close">
+  <a-modal :open="open" :closable="true" :footer="null" :width="modalWidth" :class="{ 'logmodal-mobile': isMobile }"
+    @cancel="close">
     <template #title>
       {{ t('pages.index.logs') }}
       <SyncOutlined :spin="loading" class="reload-icon" @click="refresh" />
@@ -178,6 +178,7 @@ const modalWidth = computed(() => (isMobile.value ? '100vw' : '800px'));
   flex-wrap: wrap;
   row-gap: 8px;
 }
+
 .log-toolbar .download-item {
   margin-left: auto;
 }
@@ -185,12 +186,12 @@ const modalWidth = computed(() => (isMobile.value ? '100vw' : '800px'));
 .log-container {
   /* Per-theme palette — overridden in body.dark / [data-theme="ultra-dark"]
      below so each level keeps ≥4.5:1 contrast against the container. */
-  --log-stamp:   #3c89e8;
-  --log-debug:   #3c89e8;
-  --log-info:    #008771;
-  --log-notice:  #008771;
+  --log-stamp: #3c89e8;
+  --log-debug: #3c89e8;
+  --log-info: #008771;
+  --log-notice: #008771;
   --log-warning: #f37b24;
-  --log-error:   #e04141;
+  --log-error: #e04141;
   --log-unknown: #595959;
   --log-divider: rgba(128, 128, 128, 0.18);
 
@@ -208,14 +209,37 @@ const modalWidth = computed(() => (isMobile.value ? '100vw' : '800px'));
   background: rgba(0, 0, 0, 0.04);
 }
 
-.log-stamp { color: var(--log-stamp); }
-.log-level { margin-left: 4px; }
-.level-debug   { color: var(--log-debug); }
-.level-info    { color: var(--log-info); }
-.level-notice  { color: var(--log-notice); }
-.level-warning { color: var(--log-warning); }
-.level-error   { color: var(--log-error); }
-.level-unknown { color: var(--log-unknown); }
+.log-stamp {
+  color: var(--log-stamp);
+}
+
+.log-level {
+  margin-left: 4px;
+}
+
+.level-debug {
+  color: var(--log-debug);
+}
+
+.level-info {
+  color: var(--log-info);
+}
+
+.level-notice {
+  color: var(--log-notice);
+}
+
+.level-warning {
+  color: var(--log-warning);
+}
+
+.level-error {
+  color: var(--log-error);
+}
+
+.level-unknown {
+  color: var(--log-unknown);
+}
 
 .log-container-mobile {
   padding: 8px;
@@ -229,7 +253,7 @@ const modalWidth = computed(() => (isMobile.value ? '100vw' : '800px'));
   padding: 20px 0;
 }
 
-.log-line + .log-line {
+.log-line+.log-line {
   margin-top: 2px;
 }
 
@@ -237,7 +261,11 @@ const modalWidth = computed(() => (isMobile.value ? '100vw' : '800px'));
   border-bottom: 1px solid var(--log-divider);
   padding: 8px 0;
 }
-.log-card:last-child { border-bottom: 0; }
+
+.log-card:last-child {
+  border-bottom: 0;
+}
+
 .log-card-head {
   display: flex;
   align-items: center;
@@ -245,6 +273,7 @@ const modalWidth = computed(() => (isMobile.value ? '100vw' : '800px'));
   gap: 8px;
   margin-bottom: 4px;
 }
+
 .log-time {
   display: inline-flex;
   align-items: baseline;
@@ -253,11 +282,13 @@ const modalWidth = computed(() => (isMobile.value ? '100vw' : '800px'));
   font-size: 12px;
   letter-spacing: 0.02em;
 }
+
 .log-date {
   font-size: 10px;
   font-weight: 500;
   opacity: 0.55;
 }
+
 .log-level-badge {
   display: inline-block;
   font-size: 10px;
@@ -270,10 +301,12 @@ const modalWidth = computed(() => (isMobile.value ? '100vw' : '800px'));
   white-space: nowrap;
   background: color-mix(in srgb, currentColor 14%, transparent);
 }
+
 .log-body {
   font-size: 12px;
   word-break: break-word;
 }
+
 .log-body-text {
   margin-left: 4px;
 }
@@ -283,23 +316,23 @@ const modalWidth = computed(() => (isMobile.value ? '100vw' : '800px'));
   border-color: rgba(255, 255, 255, 0.1);
   color: rgba(255, 255, 255, 0.88);
 
-  --log-stamp:   #6aa6ee;
-  --log-debug:   #6aa6ee;
-  --log-info:    #4ed3a6;
-  --log-notice:  #4ed3a6;
+  --log-stamp: #6aa6ee;
+  --log-debug: #6aa6ee;
+  --log-info: #4ed3a6;
+  --log-notice: #4ed3a6;
   --log-warning: #ffb872;
-  --log-error:   #ff7575;
+  --log-error: #ff7575;
   --log-unknown: #b5b5b5;
   --log-divider: rgba(255, 255, 255, 0.1);
 }
 
 :global([data-theme="ultra-dark"]) .log-container {
-  --log-stamp:   #7fb6f1;
-  --log-debug:   #7fb6f1;
-  --log-info:    #5fd9b0;
-  --log-notice:  #5fd9b0;
+  --log-stamp: #7fb6f1;
+  --log-debug: #7fb6f1;
+  --log-info: #5fd9b0;
+  --log-notice: #5fd9b0;
   --log-warning: #ffcc88;
-  --log-error:   #ff8a8a;
+  --log-error: #ff8a8a;
   --log-unknown: #c4c4c4;
   --log-divider: rgba(255, 255, 255, 0.12);
 }
@@ -310,10 +343,12 @@ const modalWidth = computed(() => (isMobile.value ? '100vw' : '800px'));
   padding-bottom: 0 !important;
   max-width: 100vw !important;
 }
+
 :global(.logmodal-mobile .ant-modal-content) {
   border-radius: 0;
   height: 100vh;
 }
+
 :global(.logmodal-mobile .ant-modal-body) {
   padding: 12px;
 }

+ 8 - 8
frontend/src/pages/index/StatusCard.vue

@@ -30,8 +30,8 @@ const trailColor = 'rgba(128, 128, 128, 0.25)';
       <a-col :xs="24" :md="12">
         <a-row>
           <a-col :span="12" class="text-center">
-            <a-progress type="dashboard" status="normal" :stroke-color="status.cpu.color"
-              :trail-color="trailColor" :percent="status.cpu.percent" :width="gaugeSize" />
+            <a-progress type="dashboard" status="normal" :stroke-color="status.cpu.color" :trail-color="trailColor"
+              :percent="status.cpu.percent" :width="gaugeSize" />
             <div>
               <b>{{ t('pages.index.cpu') }}:</b> {{ CPUFormatter.cpuCoreFormat(status.cpuCores) }}
               <a-tooltip>
@@ -46,8 +46,8 @@ const trailColor = 'rgba(128, 128, 128, 0.25)';
           </a-col>
 
           <a-col :span="12" class="text-center">
-            <a-progress type="dashboard" status="normal" :stroke-color="status.mem.color"
-              :trail-color="trailColor" :percent="status.mem.percent" :width="gaugeSize" />
+            <a-progress type="dashboard" status="normal" :stroke-color="status.mem.color" :trail-color="trailColor"
+              :percent="status.mem.percent" :width="gaugeSize" />
             <div>
               <b>{{ t('pages.index.memory') }}:</b> {{ SizeFormatter.sizeFormat(status.mem.current) }} /
               {{ SizeFormatter.sizeFormat(status.mem.total) }}
@@ -60,8 +60,8 @@ const trailColor = 'rgba(128, 128, 128, 0.25)';
       <a-col :xs="24" :md="12">
         <a-row>
           <a-col :span="12" class="text-center">
-            <a-progress type="dashboard" status="normal" :stroke-color="status.swap.color"
-              :trail-color="trailColor" :percent="status.swap.percent" :width="gaugeSize" />
+            <a-progress type="dashboard" status="normal" :stroke-color="status.swap.color" :trail-color="trailColor"
+              :percent="status.swap.percent" :width="gaugeSize" />
             <div>
               <b>{{ t('pages.index.swap') }}:</b> {{ SizeFormatter.sizeFormat(status.swap.current) }} /
               {{ SizeFormatter.sizeFormat(status.swap.total) }}
@@ -69,8 +69,8 @@ const trailColor = 'rgba(128, 128, 128, 0.25)';
           </a-col>
 
           <a-col :span="12" class="text-center">
-            <a-progress type="dashboard" status="normal" :stroke-color="status.disk.color"
-              :trail-color="trailColor" :percent="status.disk.percent" :width="gaugeSize" />
+            <a-progress type="dashboard" status="normal" :stroke-color="status.disk.color" :trail-color="trailColor"
+              :percent="status.disk.percent" :width="gaugeSize" />
             <div>
               <b>{{ t('pages.index.storage') }}:</b> {{ SizeFormatter.sizeFormat(status.disk.current) }} /
               {{ SizeFormatter.sizeFormat(status.disk.total) }}

+ 3 - 6
frontend/src/pages/index/SystemHistoryModal.vue

@@ -130,12 +130,9 @@ watch([activeKey, bucket], () => {
       <div class="cpu-chart-meta">
         Timeframe: {{ bucket }} sec per point (total {{ points.length }} points)
       </div>
-      <Sparkline :data="points" :labels="labels" :vb-width="840" :height="220"
-        :stroke="strokeColor" :stroke-width="2.2"
-        :show-grid="true" :show-axes="true" :tick-count-x="5"
-        :max-points="points.length || 1"
-        :fill-opacity="0.18" :marker-radius="3.2" :show-tooltip="true"
-        :value-min="0" :value-max="activeMetric?.valueMax ?? null"
+      <Sparkline :data="points" :labels="labels" :vb-width="840" :height="220" :stroke="strokeColor" :stroke-width="2.2"
+        :show-grid="true" :show-axes="true" :tick-count-x="5" :max-points="points.length || 1" :fill-opacity="0.18"
+        :marker-radius="3.2" :show-tooltip="true" :value-min="0" :value-max="activeMetric?.valueMax ?? null"
         :y-formatter="yFormatter" />
     </div>
   </a-modal>

+ 33 - 7
frontend/src/pages/index/XrayLogModal.vue

@@ -161,7 +161,12 @@ const modalWidth = computed(() => (isMobile.value ? '100vw' : '80vw'));
       <table v-else class="xraylog-table">
         <thead>
           <tr>
-            <th>Date</th><th>From</th><th>To</th><th>Inbound</th><th>Outbound</th><th>Email</th>
+            <th>Date</th>
+            <th>From</th>
+            <th>To</th>
+            <th>Inbound</th>
+            <th>Outbound</th>
+            <th>Email</th>
           </tr>
         </thead>
         <tbody>
@@ -190,9 +195,11 @@ const modalWidth = computed(() => (isMobile.value ? '100vw' : '80vw'));
   flex-wrap: wrap;
   row-gap: 8px;
 }
+
 .log-toolbar .filter-item {
   flex: 1 1 160px;
 }
+
 .log-toolbar .download-item {
   margin-left: auto;
 }
@@ -201,7 +208,7 @@ const modalWidth = computed(() => (isMobile.value ? '100vw' : '80vw'));
   /* Per-theme palette — overridden in body.dark / [data-theme="ultra-dark"]
      below so blocked/proxy rows keep ≥4.5:1 contrast on darker surfaces. */
   --log-blocked: #e04141;
-  --log-proxy:   #3c89e8;
+  --log-proxy: #3c89e8;
   --log-divider: rgba(128, 128, 128, 0.18);
 
   margin-top: 12px;
@@ -215,6 +222,7 @@ const modalWidth = computed(() => (isMobile.value ? '100vw' : '80vw'));
   border-radius: 6px;
   background: rgba(0, 0, 0, 0.04);
 }
+
 .log-container-mobile {
   padding: 8px;
   font-size: 12px;
@@ -231,7 +239,10 @@ const modalWidth = computed(() => (isMobile.value ? '100vw' : '80vw'));
   border-bottom: 1px solid var(--log-divider);
   padding: 8px 0;
 }
-.log-card:last-child { border-bottom: 0; }
+
+.log-card:last-child {
+  border-bottom: 0;
+}
 
 .log-card-head {
   display: flex;
@@ -240,11 +251,13 @@ const modalWidth = computed(() => (isMobile.value ? '100vw' : '80vw'));
   gap: 8px;
   margin-bottom: 4px;
 }
+
 .log-time {
   font-weight: 600;
   font-size: 12px;
   letter-spacing: 0.02em;
 }
+
 .log-event-tag {
   margin: 0;
   font-size: 10px;
@@ -260,9 +273,11 @@ const modalWidth = computed(() => (isMobile.value ? '100vw' : '80vw'));
   font-size: 12px;
   margin-bottom: 4px;
 }
+
 .log-addr {
   word-break: break-all;
 }
+
 .log-arrow {
   opacity: 0.5;
 }
@@ -274,12 +289,14 @@ const modalWidth = computed(() => (isMobile.value ? '100vw' : '80vw'));
   font-size: 11px;
   opacity: 0.75;
 }
+
 .log-meta-pair {
   display: inline-flex;
   align-items: baseline;
   gap: 4px;
   word-break: break-all;
 }
+
 .log-meta-key {
   font-size: 10px;
   text-transform: uppercase;
@@ -293,13 +310,13 @@ const modalWidth = computed(() => (isMobile.value ? '100vw' : '80vw'));
   color: rgba(255, 255, 255, 0.88);
 
   --log-blocked: #ff7575;
-  --log-proxy:   #6aa6ee;
+  --log-proxy: #6aa6ee;
   --log-divider: rgba(255, 255, 255, 0.1);
 }
 
 :global([data-theme="ultra-dark"]) .log-container {
   --log-blocked: #ff8a8a;
-  --log-proxy:   #7fb6f1;
+  --log-proxy: #7fb6f1;
   --log-divider: rgba(255, 255, 255, 0.12);
 }
 
@@ -309,10 +326,12 @@ const modalWidth = computed(() => (isMobile.value ? '100vw' : '80vw'));
   padding-bottom: 0 !important;
   max-width: 100vw !important;
 }
+
 :global(.xraylog-modal-mobile .ant-modal-content) {
   border-radius: 0;
   height: 100vh;
 }
+
 :global(.xraylog-modal-mobile .ant-modal-body) {
   padding: 12px;
 }
@@ -321,11 +340,18 @@ const modalWidth = computed(() => (isMobile.value ? '100vw' : '80vw'));
   border-collapse: collapse;
   width: 100%;
 }
+
 .xraylog-table td,
 .xraylog-table th {
   padding: 2px 15px;
   text-align: left;
 }
-.xraylog-table .log-row-1 { color: var(--log-blocked); }
-.xraylog-table .log-row-2 { color: var(--log-proxy); }
+
+.xraylog-table .log-row-1 {
+  color: var(--log-blocked);
+}
+
+.xraylog-table .log-row-2 {
+  color: var(--log-proxy);
+}
 </style>

+ 14 - 7
frontend/src/pages/index/XrayStatusCard.vue

@@ -1,4 +1,5 @@
 <script setup>
+import { computed } from 'vue';
 import { useI18n } from 'vue-i18n';
 import {
   BarsOutlined,
@@ -9,7 +10,7 @@ import {
 
 const { t } = useI18n();
 
-defineProps({
+const props = defineProps({
   status: { type: Object, required: true },
   isMobile: { type: Boolean, default: false },
   ipLimitEnable: { type: Boolean, default: false },
@@ -17,10 +18,16 @@ defineProps({
 
 defineEmits(['stop-xray', 'restart-xray', 'open-logs', 'open-xray-logs', 'open-version-switch']);
 
-// Map xray.color → which animation class to apply on the badge dot.
-// The legacy .xray-*-animation classes only override the badge ring
-// color; the actual pulsing comes from .xray-processing-animation
-// (which animates .ant-badge-status-dot via @keyframes runningAnimation).
+const XRAY_STATE_KEYS = {
+  running: 'pages.index.xrayStatusRunning',
+  stop: 'pages.index.xrayStatusStop',
+  error: 'pages.index.xrayStatusError',
+};
+
+const stateText = computed(() =>
+  t(XRAY_STATE_KEYS[props.status.xray.state] ?? 'pages.index.xrayStatusUnknown'),
+);
+
 function badgeAnimationClass(color) {
   if (color === 'green') return 'xray-running-animation';
   if (color === 'orange') return 'xray-stop-animation';
@@ -43,7 +50,7 @@ function badgeAnimationClass(color) {
     <template #extra>
       <template v-if="status.xray.state !== 'error'">
         <a-badge status="processing" :class="['xray-processing-animation', badgeAnimationClass(status.xray.color)]"
-          :text="status.xray.stateMsg" :color="status.xray.color" />
+          :text="stateText" :color="status.xray.color" />
       </template>
       <template v-else>
         <a-popover>
@@ -60,7 +67,7 @@ function badgeAnimationClass(color) {
               {{ line }}
             </span>
           </template>
-          <a-badge status="processing" :text="status.xray.stateMsg" :color="status.xray.color"
+          <a-badge status="processing" :text="stateText" :color="status.xray.color"
             :class="['xray-processing-animation', 'xray-error-animation']" />
         </a-popover>
       </template>

+ 2 - 3
frontend/src/pages/login/LoginPage.vue

@@ -1,5 +1,5 @@
 <script setup>
-import { computed, defineAsyncComponent, onBeforeUnmount, onMounted, reactive, ref } from 'vue';
+import { computed, onBeforeUnmount, onMounted, reactive, ref } from 'vue';
 import { useI18n } from 'vue-i18n';
 import { UserOutlined, LockOutlined, KeyOutlined, SettingOutlined } from '@ant-design/icons-vue';
 
@@ -9,8 +9,7 @@ import {
   currentTheme,
   theme as themeState,
 } from '@/composables/useTheme.js';
-
-const ThemeSwitchLogin = defineAsyncComponent(() => import('@/components/ThemeSwitchLogin.vue'));
+import ThemeSwitchLogin from '@/components/ThemeSwitchLogin.vue';
 
 const { t } = useI18n();
 

+ 7 - 28
frontend/src/pages/nodes/NodeFormModal.vue

@@ -111,17 +111,8 @@ async function onSave() {
 </script>
 
 <template>
-  <a-modal
-    :open="open"
-    :title="title"
-    :confirm-loading="submitting"
-    :ok-text="t('save')"
-    :cancel-text="t('cancel')"
-    :mask-closable="false"
-    width="640px"
-    @ok="onSave"
-    @cancel="close"
-  >
+  <a-modal :open="open" :title="title" :confirm-loading="submitting" :ok-text="t('save')" :cancel-text="t('cancel')"
+    :mask-closable="false" width="640px" @ok="onSave" @cancel="close">
     <a-form layout="vertical" :model="form">
       <a-row :gutter="16">
         <a-col :span="12">
@@ -171,10 +162,7 @@ async function onSave() {
       </a-row>
 
       <a-form-item :label="t('pages.nodes.apiToken')" required>
-        <a-input-password
-          v-model:value="form.apiToken"
-          :placeholder="t('pages.nodes.apiTokenPlaceholder')"
-        />
+        <a-input-password v-model:value="form.apiToken" :placeholder="t('pages.nodes.apiTokenPlaceholder')" />
         <div class="hint">{{ t('pages.nodes.apiTokenHint') }}</div>
       </a-form-item>
 
@@ -183,20 +171,11 @@ async function onSave() {
           {{ t('pages.nodes.testConnection') }}
         </a-button>
         <div v-if="testResult" class="test-result">
-          <a-alert
-            v-if="testResult.status === 'online'"
-            type="success"
-            show-icon
+          <a-alert v-if="testResult.status === 'online'" type="success" show-icon
             :message="t('pages.nodes.connectionOk', { ms: testResult.latencyMs })"
-            :description="testResult.xrayVersion ? `Xray ${testResult.xrayVersion}` : undefined"
-          />
-          <a-alert
-            v-else
-            type="error"
-            show-icon
-            :message="t('pages.nodes.connectionFailed')"
-            :description="testResult.error"
-          />
+            :description="testResult.xrayVersion ? `Xray ${testResult.xrayVersion}` : undefined" />
+          <a-alert v-else type="error" show-icon :message="t('pages.nodes.connectionFailed')"
+            :description="testResult.error" />
         </div>
       </div>
     </a-form>

+ 6 - 24
frontend/src/pages/nodes/NodeHistoryPanel.vue

@@ -79,33 +79,15 @@ watch(() => props.node?.id, (a, b) => {
   <div class="node-history-panel">
     <div class="series">
       <div class="series-title">{{ t('pages.nodes.cpu') }}</div>
-      <Sparkline
-        :data="cpuPoints"
-        :labels="cpuLabels"
-        :vb-width="640" :height="120"
-        stroke="#008771"
-        :show-grid="true" :show-axes="true"
-        :tick-count-x="4"
-        :max-points="cpuPoints.length || 1"
-        :fill-opacity="0.18"
-        :marker-radius="2.6"
-        :show-tooltip="true"
-      />
+      <Sparkline :data="cpuPoints" :labels="cpuLabels" :vb-width="640" :height="120" stroke="#008771" :show-grid="true"
+        :show-axes="true" :tick-count-x="4" :max-points="cpuPoints.length || 1" :fill-opacity="0.18"
+        :marker-radius="2.6" :show-tooltip="true" />
     </div>
     <div class="series">
       <div class="series-title">{{ t('pages.nodes.mem') }}</div>
-      <Sparkline
-        :data="memPoints"
-        :labels="memLabels"
-        :vb-width="640" :height="120"
-        stroke="#7c4dff"
-        :show-grid="true" :show-axes="true"
-        :tick-count-x="4"
-        :max-points="memPoints.length || 1"
-        :fill-opacity="0.18"
-        :marker-radius="2.6"
-        :show-tooltip="true"
-      />
+      <Sparkline :data="memPoints" :labels="memLabels" :vb-width="640" :height="120" stroke="#7c4dff" :show-grid="true"
+        :show-axes="true" :tick-count-x="4" :max-points="memPoints.length || 1" :fill-opacity="0.18"
+        :marker-radius="2.6" :show-tooltip="true" />
     </div>
   </div>
 </template>

+ 17 - 18
frontend/src/pages/nodes/NodeList.vue

@@ -76,19 +76,15 @@ function formatPct(p) {
   <a-card size="small" hoverable>
     <div class="toolbar">
       <a-button type="primary" @click="emit('add')">
-        <template #icon><PlusOutlined /></template>
+        <template #icon>
+          <PlusOutlined />
+        </template>
         {{ t('pages.nodes.addNode') }}
       </a-button>
     </div>
 
-    <a-table
-      :data-source="dataSource"
-      :pagination="false"
-      :loading="loading"
-      :scroll="{ x: 'max-content' }"
-      size="middle"
-      row-key="id"
-    >
+    <a-table :data-source="dataSource" :pagination="false" :loading="loading" :scroll="{ x: 'max-content' }"
+      size="middle" row-key="id">
       <template #expandedRowRender="{ record }">
         <NodeHistoryPanel :node="record" />
       </template>
@@ -110,7 +106,8 @@ function formatPct(p) {
       <a-table-column :title="t('pages.nodes.status')" data-index="status" align="center">
         <template #default="{ record }">
           <a-space :size="4">
-            <a-badge :status="statusColor(record.status) === 'green' ? 'success' : (statusColor(record.status) === 'red' ? 'error' : 'default')" />
+            <a-badge
+              :status="statusColor(record.status) === 'green' ? 'success' : (statusColor(record.status) === 'red' ? 'error' : 'default')" />
             <span>{{ t(`pages.nodes.statusValues.${record.status || 'unknown'}`) }}</span>
             <a-tooltip v-if="record.lastError" :title="record.lastError">
               <ExclamationCircleOutlined style="color: #faad14" />
@@ -150,11 +147,7 @@ function formatPct(p) {
 
       <a-table-column :title="t('pages.nodes.enable')" data-index="enable" align="center" :width="80">
         <template #default="{ record }">
-          <a-switch
-            :checked="record.enable"
-            size="small"
-            @change="(v) => emit('toggle-enable', record, v)"
-          />
+          <a-switch :checked="record.enable" size="small" @change="(v) => emit('toggle-enable', record, v)" />
         </template>
       </a-table-column>
 
@@ -163,17 +156,23 @@ function formatPct(p) {
           <a-space>
             <a-tooltip :title="t('pages.nodes.probe')">
               <a-button type="text" size="small" @click="emit('probe', record)">
-                <template #icon><ThunderboltOutlined /></template>
+                <template #icon>
+                  <ThunderboltOutlined />
+                </template>
               </a-button>
             </a-tooltip>
             <a-tooltip :title="t('edit')">
               <a-button type="text" size="small" @click="emit('edit', record)">
-                <template #icon><EditOutlined /></template>
+                <template #icon>
+                  <EditOutlined />
+                </template>
               </a-button>
             </a-tooltip>
             <a-tooltip :title="t('delete')">
               <a-button type="text" size="small" danger @click="emit('delete', record)">
-                <template #icon><DeleteOutlined /></template>
+                <template #icon>
+                  <DeleteOutlined />
+                </template>
               </a-button>
             </a-tooltip>
           </a-space>

+ 10 - 37
frontend/src/pages/nodes/NodesPage.vue

@@ -100,10 +100,7 @@ async function onToggleEnable(node, next) {
 
 <template>
   <a-config-provider :theme="antdThemeConfig">
-    <a-layout
-      class="nodes-page"
-      :class="{ 'is-dark': themeState.isDark, 'is-ultra': themeState.isUltra }"
-    >
+    <a-layout class="nodes-page" :class="{ 'is-dark': themeState.isDark, 'is-ultra': themeState.isUltra }">
       <AppSidebar :base-path="basePath" :request-uri="requestUri" />
 
       <a-layout class="content-shell">
@@ -117,40 +114,29 @@ async function onToggleEnable(node, next) {
                 <a-card size="small" hoverable class="summary-card">
                   <a-row :gutter="[16, 12]">
                     <a-col :sm="12" :md="6">
-                      <CustomStatistic
-                        :title="t('pages.nodes.totalNodes')"
-                        :value="String(totals.total)"
-                      >
+                      <CustomStatistic :title="t('pages.nodes.totalNodes')" :value="String(totals.total)">
                         <template #prefix>
                           <CloudServerOutlined />
                         </template>
                       </CustomStatistic>
                     </a-col>
                     <a-col :sm="12" :md="6">
-                      <CustomStatistic
-                        :title="t('pages.nodes.onlineNodes')"
-                        :value="String(totals.online)"
-                      >
+                      <CustomStatistic :title="t('pages.nodes.onlineNodes')" :value="String(totals.online)">
                         <template #prefix>
                           <CheckCircleOutlined style="color: #52c41a" />
                         </template>
                       </CustomStatistic>
                     </a-col>
                     <a-col :sm="12" :md="6">
-                      <CustomStatistic
-                        :title="t('pages.nodes.offlineNodes')"
-                        :value="String(totals.offline)"
-                      >
+                      <CustomStatistic :title="t('pages.nodes.offlineNodes')" :value="String(totals.offline)">
                         <template #prefix>
                           <CloseCircleOutlined style="color: #ff4d4f" />
                         </template>
                       </CustomStatistic>
                     </a-col>
                     <a-col :sm="12" :md="6">
-                      <CustomStatistic
-                        :title="t('pages.nodes.avgLatency')"
-                        :value="totals.avgLatency > 0 ? `${totals.avgLatency} ms` : '-'"
-                      >
+                      <CustomStatistic :title="t('pages.nodes.avgLatency')"
+                        :value="totals.avgLatency > 0 ? `${totals.avgLatency} ms` : '-'">
                         <template #prefix>
                           <ThunderboltOutlined />
                         </template>
@@ -162,29 +148,16 @@ async function onToggleEnable(node, next) {
 
               <!-- Node table -->
               <a-col :span="24">
-                <NodeList
-                  :nodes="nodes"
-                  :loading="loading"
-                  :is-mobile="isMobile"
-                  @add="onAdd"
-                  @edit="onEdit"
-                  @delete="onDelete"
-                  @probe="onProbe"
-                  @toggle-enable="onToggleEnable"
-                />
+                <NodeList :nodes="nodes" :loading="loading" :is-mobile="isMobile" @add="onAdd" @edit="onEdit"
+                  @delete="onDelete" @probe="onProbe" @toggle-enable="onToggleEnable" />
               </a-col>
             </a-row>
           </a-spin>
         </a-layout-content>
       </a-layout>
 
-      <NodeFormModal
-        v-model:open="formOpen"
-        :mode="formMode"
-        :node="formNode"
-        :test-connection="testConnection"
-        :save="onSave"
-      />
+      <NodeFormModal v-model:open="formOpen" :mode="formMode" :node="formNode" :test-connection="testConnection"
+        :save="onSave" />
     </a-layout>
   </a-config-provider>
 </template>

+ 1 - 6
frontend/src/pages/settings/SecurityTab.vue

@@ -221,12 +221,7 @@ function toggleTwoFactor() {
         <template #title>{{ t('pages.nodes.apiToken') }}</template>
         <template #description>{{ t('pages.nodes.apiTokenHint') }}</template>
         <template #control>
-          <a-input-password
-            :value="apiToken"
-            readonly
-            :loading="apiTokenLoading"
-            style="min-width: 240px"
-          />
+          <a-input-password :value="apiToken" readonly :loading="apiTokenLoading" style="min-width: 240px" />
         </template>
       </SettingListItem>
       <a-list-item>

+ 19 - 21
frontend/src/pages/settings/SettingsPage.vue

@@ -96,27 +96,25 @@ function rebuildUrlAfterRestart() {
   return url.toString();
 }
 
-async function restartPanel() {
-  await new Promise((resolve, reject) => {
-    Modal.confirm({
-      title: 'Restart panel',
-      content: 'Restart the panel now? Your session will reconnect once it comes back.',
-      okText: 'Restart',
-      cancelText: 'Cancel',
-      onOk: () => resolve(),
-      onCancel: () => reject(new Error('cancelled')),
-    });
-  }).catch(() => null);
-
-  spinning.value = true;
-  try {
-    const msg = await HttpUtil.post('/panel/setting/restartPanel');
-    if (!msg?.success) return;
-    await PromiseUtil.sleep(5000);
-    window.location.replace(rebuildUrlAfterRestart());
-  } finally {
-    spinning.value = false;
-  }
+function restartPanel() {
+  Modal.confirm({
+    title: t('pages.settings.restartPanel'),
+    content: t('pages.settings.restartPanelDesc'),
+    okText: t('pages.settings.restartPanel'),
+    okButtonProps: { danger: true },
+    cancelText: t('cancel'),
+    async onOk() {
+      spinning.value = true;
+      try {
+        const msg = await HttpUtil.post('/panel/setting/restartPanel');
+        if (!msg?.success) return;
+        await PromiseUtil.sleep(5000);
+        window.location.replace(rebuildUrlAfterRestart());
+      } finally {
+        spinning.value = false;
+      }
+    },
+  });
 }
 
 // Conf alerts mirror the legacy banner — pure derivation off allSetting.

+ 38 - 34
frontend/src/pages/sub/SubPage.vue

@@ -163,11 +163,8 @@ const themeClass = computed(() => ({
                       <ThemeSwitchLogin />
                       <span>{{ t('pages.settings.language') }}</span>
                       <a-select v-model:value="lang" class="lang-select" @change="onLangChange">
-                        <a-select-option
-                          v-for="l in LanguageManager.supportedLanguages"
-                          :key="l.value"
-                          :value="l.value"
-                        >
+                        <a-select-option v-for="l in LanguageManager.supportedLanguages" :key="l.value"
+                          :value="l.value">
                           <span :aria-label="l.name">{{ l.icon }}</span>
                           &nbsp;&nbsp;<span>{{ l.name }}</span>
                         </a-select-option>
@@ -175,7 +172,9 @@ const themeClass = computed(() => ({
                     </a-space>
                   </template>
                   <a-button shape="circle">
-                    <template #icon><SettingOutlined /></template>
+                    <template #icon>
+                      <SettingOutlined />
+                    </template>
                   </a-button>
                 </a-popover>
               </template>
@@ -185,12 +184,7 @@ const themeClass = computed(() => ({
                 <a-col :xs="24" :sm="subJsonUrl || subClashUrl ? 12 : 24" class="qr-col">
                   <div class="qr-box">
                     <a-tag color="purple" class="qr-tag">{{ t('pages.settings.subSettings') }}</a-tag>
-                    <canvas
-                      ref="subQr"
-                      class="qr-canvas"
-                      :title="t('copy')"
-                      @click="copy(subUrl)"
-                    />
+                    <canvas ref="subQr" class="qr-canvas" :title="t('copy')" @click="copy(subUrl)" />
                   </div>
                 </a-col>
                 <a-col v-if="subJsonUrl" :xs="24" :sm="12" class="qr-col">
@@ -198,23 +192,13 @@ const themeClass = computed(() => ({
                     <a-tag color="purple" class="qr-tag">
                       {{ t('pages.settings.subSettings') }} JSON
                     </a-tag>
-                    <canvas
-                      ref="subJsonQr"
-                      class="qr-canvas"
-                      :title="t('copy')"
-                      @click="copy(subJsonUrl)"
-                    />
+                    <canvas ref="subJsonQr" class="qr-canvas" :title="t('copy')" @click="copy(subJsonUrl)" />
                   </div>
                 </a-col>
                 <a-col v-if="subClashUrl" :xs="24" :sm="12" class="qr-col">
                   <div class="qr-box">
                     <a-tag color="purple" class="qr-tag">Clash / Mihomo</a-tag>
-                    <canvas
-                      ref="subClashQr"
-                      class="qr-canvas"
-                      :title="t('copy')"
-                      @click="copy(subClashUrl)"
-                    />
+                    <canvas ref="subClashQr" class="qr-canvas" :title="t('copy')" @click="copy(subClashUrl)" />
                   </div>
                 </a-col>
               </a-row>
@@ -248,12 +232,7 @@ const themeClass = computed(() => ({
 
               <!-- ============== Individual links ============== -->
               <div v-if="links.length" class="links-section">
-                <div
-                  v-for="(link, idx) in links"
-                  :key="link"
-                  class="link-row"
-                  @click="copy(link)"
-                >
+                <div v-for="(link, idx) in links" :key="link" class="link-row" @click="copy(link)">
                   <a-tag color="purple" class="link-tag">{{ linkName(link, idx) }}</a-tag>
                   <div class="link-box">
                     <CopyOutlined class="link-copy-icon" />
@@ -267,12 +246,15 @@ const themeClass = computed(() => ({
                 <a-col :xs="24" :sm="12" class="app-col">
                   <a-dropdown :trigger="['click']">
                     <a-button :block="isMobile" size="large" type="primary">
-                      <AndroidOutlined /> Android <DownOutlined />
+                      <AndroidOutlined /> Android
+                      <DownOutlined />
                     </a-button>
                     <template #overlay>
                       <a-menu>
-                        <a-menu-item key="android-v2box" @click="open(`v2box://install-sub?url=${encodeURIComponent(subUrl)}&name=${encodeURIComponent(sId)}`)">V2Box</a-menu-item>
-                        <a-menu-item key="android-v2rayng" @click="open(`v2rayng://install-config?url=${encodeURIComponent(subUrl)}`)">V2RayNG</a-menu-item>
+                        <a-menu-item key="android-v2box"
+                          @click="open(`v2box://install-sub?url=${encodeURIComponent(subUrl)}&name=${encodeURIComponent(sId)}`)">V2Box</a-menu-item>
+                        <a-menu-item key="android-v2rayng"
+                          @click="open(`v2rayng://install-config?url=${encodeURIComponent(subUrl)}`)">V2RayNG</a-menu-item>
                         <a-menu-item key="android-singbox" @click="copy(subUrl)">Sing-box</a-menu-item>
                         <a-menu-item key="android-v2raytun" @click="copy(subUrl)">V2RayTun</a-menu-item>
                         <a-menu-item key="android-npvtunnel" @click="copy(subUrl)">NPV Tunnel</a-menu-item>
@@ -284,7 +266,8 @@ const themeClass = computed(() => ({
                 <a-col :xs="24" :sm="12" class="app-col">
                   <a-dropdown :trigger="['click']">
                     <a-button :block="isMobile" size="large" type="primary">
-                      <AppleOutlined /> iOS <DownOutlined />
+                      <AppleOutlined /> iOS
+                      <DownOutlined />
                     </a-button>
                     <template #overlay>
                       <a-menu>
@@ -314,14 +297,17 @@ const themeClass = computed(() => ({
   min-height: 100vh;
   background: var(--bg-page);
 }
+
 .subscription-page.is-dark {
   --bg-page: #0a1222;
   --bg-card: #151f31;
 }
+
 .subscription-page.is-dark.is-ultra {
   --bg-page: #050505;
   --bg-card: #0c0e12;
 }
+
 .subscription-page :deep(.ant-layout),
 .subscription-page :deep(.ant-layout-content) {
   background: transparent;
@@ -339,10 +325,12 @@ const themeClass = computed(() => ({
 .qr-row {
   margin-bottom: 12px;
 }
+
 .qr-col {
   display: flex;
   justify-content: center;
 }
+
 .qr-box {
   display: inline-flex;
   flex-direction: column;
@@ -350,11 +338,13 @@ const themeClass = computed(() => ({
   gap: 4px;
   width: 220px;
 }
+
 .qr-tag {
   width: 100%;
   text-align: center;
   margin: 0;
 }
+
 .qr-canvas {
   cursor: pointer;
   background: #fff;
@@ -370,16 +360,19 @@ const themeClass = computed(() => ({
 .info-table {
   margin-top: 12px;
 }
+
 .info-table :deep(.ant-descriptions-view),
 .info-table :deep(.ant-descriptions-view) table,
 .info-table :deep(.ant-descriptions-view) th,
 .info-table :deep(.ant-descriptions-view) td {
   border-color: rgba(0, 0, 0, 0.18) !important;
 }
+
 .info-table :deep(tbody > tr > th),
 .info-table :deep(tbody > tr > td) {
   border-bottom: 1px solid rgba(0, 0, 0, 0.18) !important;
 }
+
 .info-table :deep(tbody > tr:last-child > th),
 .info-table :deep(tbody > tr:last-child > td) {
   border-bottom: none !important;
@@ -391,10 +384,12 @@ const themeClass = computed(() => ({
 .is-dark .info-table :deep(.ant-descriptions-view) td {
   border-color: rgba(255, 255, 255, 0.18) !important;
 }
+
 .is-dark .info-table :deep(tbody > tr > th),
 .is-dark .info-table :deep(tbody > tr > td) {
   border-bottom: 1px solid rgba(255, 255, 255, 0.18) !important;
 }
+
 .is-dark .info-table :deep(tbody > tr:last-child > th),
 .is-dark .info-table :deep(tbody > tr:last-child > td) {
   border-bottom: none !important;
@@ -404,17 +399,20 @@ const themeClass = computed(() => ({
 .links-section {
   margin-top: 16px;
 }
+
 .link-row {
   position: relative;
   margin-bottom: 16px;
   text-align: center;
 }
+
 .link-tag {
   margin-bottom: -10px;
   position: relative;
   z-index: 2;
   box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
 }
+
 .link-box {
   cursor: pointer;
   border-radius: 12px;
@@ -430,19 +428,23 @@ const themeClass = computed(() => ({
   background: rgba(0, 0, 0, 0.03);
   border: 1px solid rgba(0, 0, 0, 0.08);
 }
+
 .link-box:hover {
   background: rgba(0, 0, 0, 0.05);
   border-color: rgba(0, 0, 0, 0.14);
 }
+
 .link-copy-icon {
   margin-right: 6px;
   opacity: 0.6;
 }
+
 .is-dark .link-box {
   background: rgba(0, 0, 0, 0.2);
   border-color: rgba(255, 255, 255, 0.1);
   color: rgba(255, 255, 255, 0.85);
 }
+
 .is-dark .link-box:hover {
   background: rgba(0, 0, 0, 0.3);
   border-color: rgba(255, 255, 255, 0.2);
@@ -452,6 +454,7 @@ const themeClass = computed(() => ({
 .apps-row {
   margin-top: 24px;
 }
+
 .app-col {
   text-align: center;
 }
@@ -459,6 +462,7 @@ const themeClass = computed(() => ({
 .settings-popover {
   min-width: 220px;
 }
+
 .lang-select {
   width: 100%;
 }

+ 2 - 12
frontend/src/pages/xray/BalancerFormModal.vue

@@ -95,12 +95,7 @@ const okText = computed(() =>
   <a-modal :open="open" :title="title" :ok-text="okText" :cancel-text="t('close')"
     :ok-button-props="{ disabled: !isValid }" :mask-closable="false" @ok="onOk" @cancel="close">
     <a-form :colon="false" :label-col="{ md: { span: 8 } }" :wrapper-col="{ md: { span: 14 } }">
-      <a-form-item
-        label="Tag"
-        :validate-status="tagValidateStatus"
-        :help="tagHelp"
-        has-feedback
-      >
+      <a-form-item label="Tag" :validate-status="tagValidateStatus" :help="tagHelp" has-feedback>
         <a-input v-model:value="form.tag" placeholder="unique balancer tag" />
       </a-form-item>
 
@@ -110,12 +105,7 @@ const okText = computed(() =>
         </a-select>
       </a-form-item>
 
-      <a-form-item
-        label="Selector"
-        :validate-status="selectorValidateStatus"
-        :help="selectorHelp"
-        has-feedback
-      >
+      <a-form-item label="Selector" :validate-status="selectorValidateStatus" :help="selectorHelp" has-feedback>
         <a-select v-model:value="form.selector" mode="tags" :token-separators="[',']">
           <a-select-option v-for="tag in outboundTags" :key="tag" :value="tag">{{ tag }}</a-select-option>
         </a-select>

+ 103 - 0
frontend/src/pages/xray/DnsPresetsModal.vue

@@ -0,0 +1,103 @@
+<script setup>
+import { computed } from 'vue';
+import { useI18n } from 'vue-i18n';
+
+const { t } = useI18n();
+
+const props = defineProps({
+  open: { type: Boolean, default: false },
+});
+
+const emit = defineEmits(['update:open', 'install']);
+
+const PRESETS = [
+  {
+    name: 'Google DNS',
+    family: false,
+    data: [
+      '8.8.8.8',
+      '8.8.4.4',
+      '2001:4860:4860::8888',
+      '2001:4860:4860::8844',
+    ],
+  },
+  {
+    name: 'Cloudflare DNS',
+    family: false,
+    data: [
+      '1.1.1.1',
+      '1.0.0.1',
+      '2606:4700:4700::1111',
+      '2606:4700:4700::1001',
+    ],
+  },
+  {
+    name: 'AdGuard DNS',
+    family: false,
+    data: [
+      '94.140.14.14',
+      '94.140.15.15',
+      '2a10:50c0::ad1:ff',
+      '2a10:50c0::ad2:ff',
+    ],
+  },
+  {
+    name: 'AdGuard Family DNS',
+    family: true,
+    data: [
+      '94.140.14.15',
+      '94.140.15.16',
+      '2a10:50c0::bad1:ff',
+      '2a10:50c0::bad2:ff',
+    ],
+  },
+  {
+    name: 'Cloudflare Family DNS',
+    family: true,
+    data: [
+      '1.1.1.3',
+      '1.0.0.3',
+      '2606:4700:4700::1113',
+      '2606:4700:4700::1003',
+    ],
+  },
+];
+
+const title = computed(() => t('pages.xray.dns.dnsPresetTitle'));
+
+function close() { emit('update:open', false); }
+function install(preset) {
+  emit('install', [...preset.data]);
+}
+</script>
+
+<template>
+  <a-modal :open="open" :title="title" :footer="null" :mask-closable="false" @cancel="close">
+    <a-list bordered>
+      <a-list-item v-for="preset in PRESETS" :key="preset.name" class="preset-row">
+        <a-space size="small" align="center">
+          <a-tag :color="preset.family ? 'purple' : 'green'">
+            {{ preset.family ? t('pages.xray.dns.dnsPresetFamily') : 'DNS' }}
+          </a-tag>
+          <span class="preset-name">{{ preset.name }}</span>
+        </a-space>
+        <a-button type="primary" size="small" @click="install(preset)">
+          {{ t('install') }}
+        </a-button>
+      </a-list-item>
+    </a-list>
+  </a-modal>
+</template>
+
+<style scoped>
+.preset-row {
+  display: flex;
+  align-items: center;
+  justify-content: space-between;
+  gap: 8px;
+}
+
+.preset-name {
+  font-weight: 500;
+}
+</style>

+ 71 - 49
frontend/src/pages/xray/DnsServerModal.vue

@@ -5,11 +5,6 @@ import { PlusOutlined, MinusOutlined } from '@ant-design/icons-vue';
 
 const { t } = useI18n();
 
-// DNS server add/edit modal — mirrors web/html/modals/xray_dns_modal.html.
-// The legacy panel allowed both string-form ("8.8.8.8") and object-form
-// servers; we always edit as an object and the parent can decide
-// whether to collapse to a string when nothing besides address is set.
-
 const props = defineProps({
   open: { type: Boolean, default: false },
   server: { type: [Object, String, null], default: null },
@@ -22,12 +17,17 @@ const DEFAULT_SERVER = () => ({
   address: 'localhost',
   port: 53,
   domains: [],
-  expectIPs: [],
+  expectedIPs: [],
   unexpectedIPs: [],
   queryStrategy: 'UseIP',
-  skipFallback: true,
+  skipFallback: false,
   disableCache: false,
   finalQuery: false,
+  tag: '',
+  clientIP: '',
+  serveStale: false,
+  serveExpiredTTL: 0,
+  timeoutMs: 4000,
 });
 
 const STRATEGIES = ['UseSystem', 'UseIP', 'UseIPv4', 'UseIPv6'];
@@ -42,45 +42,53 @@ watch(() => props.open, (next) => {
     form.address = props.server;
     return;
   }
-  // Object — copy fields, defaulting missing arrays to empty.
+  const incoming = props.server;
   Object.assign(form, {
     ...DEFAULT_SERVER(),
-    ...props.server,
-    domains: [...(props.server.domains || [])],
-    expectIPs: [...(props.server.expectIPs || [])],
-    unexpectedIPs: [...(props.server.unexpectedIPs || [])],
+    ...incoming,
+    domains: [...(incoming.domains || [])],
+    expectedIPs: [...(incoming.expectedIPs || incoming.expectIPs || [])],
+    unexpectedIPs: [...(incoming.unexpectedIPs || [])],
   });
 });
 
 function close() { emit('update:open', false); }
 
 function onOk() {
-  // If the user only set an address (everything else default), emit a
-  // bare string — that's the wire shape the legacy panel uses for
-  // servers like "8.8.8.8" and keeps the JSON tidy.
   const isPlain = form.domains.length === 0
-    && form.expectIPs.length === 0
+    && form.expectedIPs.length === 0
     && form.unexpectedIPs.length === 0
     && form.port === 53
     && form.queryStrategy === 'UseIP'
-    && form.skipFallback === true
+    && form.skipFallback === false
     && form.disableCache === false
-    && form.finalQuery === false;
+    && form.finalQuery === false
+    && !form.tag
+    && !form.clientIP
+    && form.serveStale === false
+    && form.serveExpiredTTL === 0
+    && form.timeoutMs === 4000;
   if (isPlain) {
     emit('confirm', form.address);
-  } else {
-    emit('confirm', {
-      address: form.address,
-      port: form.port,
-      domains: [...form.domains].filter(Boolean),
-      expectIPs: [...form.expectIPs].filter(Boolean),
-      unexpectedIPs: [...form.unexpectedIPs].filter(Boolean),
-      queryStrategy: form.queryStrategy,
-      skipFallback: form.skipFallback,
-      disableCache: form.disableCache,
-      finalQuery: form.finalQuery,
-    });
+    return;
   }
+  const out = {
+    address: form.address,
+    port: form.port,
+    domains: [...form.domains].filter(Boolean),
+    expectedIPs: [...form.expectedIPs].filter(Boolean),
+    unexpectedIPs: [...form.unexpectedIPs].filter(Boolean),
+    queryStrategy: form.queryStrategy,
+    skipFallback: form.skipFallback,
+    disableCache: form.disableCache,
+    finalQuery: form.finalQuery,
+    serveStale: form.serveStale,
+    serveExpiredTTL: form.serveExpiredTTL,
+    timeoutMs: form.timeoutMs,
+  };
+  if (form.tag) out.tag = form.tag;
+  if (form.clientIP) out.clientIP = form.clientIP;
+  emit('confirm', out);
 }
 
 const title = computed(() =>
@@ -89,15 +97,8 @@ const title = computed(() =>
 </script>
 
 <template>
-  <a-modal
-    :open="open"
-    :title="title"
-    :ok-text="t('confirm')"
-    :cancel-text="t('close')"
-    :mask-closable="false"
-    @ok="onOk"
-    @cancel="close"
-  >
+  <a-modal :open="open" :title="title" :ok-text="t('confirm')" :cancel-text="t('close')" :mask-closable="false"
+    @ok="onOk" @cancel="close">
     <a-form :colon="false" :label-col="{ md: { span: 8 } }" :wrapper-col="{ md: { span: 14 } }">
       <a-form-item :label="t('pages.inbounds.address')">
         <a-input v-model:value="form.address" />
@@ -105,17 +106,28 @@ const title = computed(() =>
       <a-form-item :label="t('pages.inbounds.port')">
         <a-input-number v-model:value="form.port" :min="1" :max="65535" />
       </a-form-item>
+      <a-form-item :label="t('pages.xray.dns.tag')">
+        <a-input v-model:value="form.tag" />
+      </a-form-item>
+      <a-form-item :label="t('pages.xray.dns.clientIp')">
+        <a-input v-model:value="form.clientIP" />
+      </a-form-item>
       <a-form-item :label="t('pages.xray.dns.strategy')">
         <a-select v-model:value="form.queryStrategy" :style="{ width: '100%' }">
           <a-select-option v-for="s in STRATEGIES" :key="s" :value="s">{{ s }}</a-select-option>
         </a-select>
       </a-form-item>
+      <a-form-item :label="t('pages.xray.dns.timeoutMs')">
+        <a-input-number v-model:value="form.timeoutMs" :min="0" :step="500" />
+      </a-form-item>
 
       <a-divider :style="{ margin: '5px 0' }" />
 
       <a-form-item :label="t('pages.xray.dns.domains')">
         <a-button size="small" type="primary" @click="form.domains.push('')">
-          <template #icon><PlusOutlined /></template>
+          <template #icon>
+            <PlusOutlined />
+          </template>
         </a-button>
         <template v-for="(_, idx) in form.domains" :key="`d${idx}`">
           <a-input v-model:value="form.domains[idx]" :style="{ marginTop: '4px' }">
@@ -127,13 +139,15 @@ const title = computed(() =>
       </a-form-item>
 
       <a-form-item :label="t('pages.xray.dns.expectIPs')">
-        <a-button size="small" type="primary" @click="form.expectIPs.push('')">
-          <template #icon><PlusOutlined /></template>
+        <a-button size="small" type="primary" @click="form.expectedIPs.push('')">
+          <template #icon>
+            <PlusOutlined />
+          </template>
         </a-button>
-        <template v-for="(_, idx) in form.expectIPs" :key="`e${idx}`">
-          <a-input v-model:value="form.expectIPs[idx]" :style="{ marginTop: '4px' }">
+        <template v-for="(_, idx) in form.expectedIPs" :key="`e${idx}`">
+          <a-input v-model:value="form.expectedIPs[idx]" :style="{ marginTop: '4px' }">
             <template #addonAfter>
-              <MinusOutlined @click="form.expectIPs.splice(idx, 1)" />
+              <MinusOutlined @click="form.expectedIPs.splice(idx, 1)" />
             </template>
           </a-input>
         </template>
@@ -141,7 +155,9 @@ const title = computed(() =>
 
       <a-form-item :label="t('pages.xray.dns.unexpectIPs')">
         <a-button size="small" type="primary" @click="form.unexpectedIPs.push('')">
-          <template #icon><PlusOutlined /></template>
+          <template #icon>
+            <PlusOutlined />
+          </template>
         </a-button>
         <template v-for="(_, idx) in form.unexpectedIPs" :key="`u${idx}`">
           <a-input v-model:value="form.unexpectedIPs[idx]" :style="{ marginTop: '4px' }">
@@ -154,14 +170,20 @@ const title = computed(() =>
 
       <a-divider :style="{ margin: '5px 0' }" />
 
-      <a-form-item label="Skip fallback">
+      <a-form-item :label="t('pages.xray.dns.skipFallback')">
         <a-switch v-model:checked="form.skipFallback" />
       </a-form-item>
+      <a-form-item :label="t('pages.xray.dns.finalQuery')">
+        <a-switch v-model:checked="form.finalQuery" />
+      </a-form-item>
       <a-form-item :label="t('pages.xray.dns.disableCache')">
         <a-switch v-model:checked="form.disableCache" />
       </a-form-item>
-      <a-form-item label="Final query">
-        <a-switch v-model:checked="form.finalQuery" />
+      <a-form-item :label="t('pages.xray.dns.serveStale')">
+        <a-switch v-model:checked="form.serveStale" />
+      </a-form-item>
+      <a-form-item :label="t('pages.xray.dns.serveExpiredTTL')">
+        <a-input-number v-model:value="form.serveExpiredTTL" :min="0" :step="60" />
       </a-form-item>
     </a-form>
   </a-modal>

+ 197 - 59
frontend/src/pages/xray/DnsTab.vue

@@ -1,31 +1,27 @@
 <script setup>
-import { computed, ref } from 'vue';
+import { computed, ref, watch } from 'vue';
 import { useI18n } from 'vue-i18n';
+import { Modal } from 'ant-design-vue';
 import {
   PlusOutlined,
   MoreOutlined,
   EditOutlined,
   DeleteOutlined,
+  MenuOutlined,
 } from '@ant-design/icons-vue';
 
 import SettingListItem from '@/components/SettingListItem.vue';
 import DnsServerModal from './DnsServerModal.vue';
+import DnsPresetsModal from './DnsPresetsModal.vue';
 
 const { t } = useI18n();
 
-// Structured DNS editor — mirrors web/html/settings/xray/dns.html.
-// Master enable switch + general DNS options + per-server table with
-// add/edit/delete (modal flow), plus a Fake DNS table. Both lists
-// flow through templateSettings.dns / .fakedns reactively so the
-// useXraySetting composable picks every edit up via its deep watch.
-
 const props = defineProps({
   templateSettings: { type: Object, default: null },
 });
 
 const STRATEGIES = ['UseSystem', 'UseIP', 'UseIPv4', 'UseIPv6'];
 
-// ============== Master toggle ==============
 const enableDNS = computed({
   get: () => !!props.templateSettings?.dns,
   set: (next) => {
@@ -40,6 +36,9 @@ const enableDNS = computed({
         disableFallbackIfMatch: false,
         useSystemHosts: false,
         enableParallelQuery: false,
+        serveStale: false,
+        serveExpiredTTL: 0,
+        hosts: {},
         servers: [],
       };
       props.templateSettings.fakedns = null;
@@ -50,7 +49,6 @@ const enableDNS = computed({
   },
 });
 
-// ============== Field bridges ==============
 function dnsField(field, fallback) {
   return computed({
     get: () => props.templateSettings?.dns?.[field] ?? fallback,
@@ -68,8 +66,53 @@ const dnsDisableFallback = dnsField('disableFallback', false);
 const dnsDisableFallbackIfMatch = dnsField('disableFallbackIfMatch', false);
 const dnsEnableParallelQuery = dnsField('enableParallelQuery', false);
 const dnsUseSystemHosts = dnsField('useSystemHosts', false);
+const dnsServeStale = dnsField('serveStale', false);
+const dnsServeExpiredTTL = dnsField('serveExpiredTTL', 0);
+
+const hostsList = ref([]);
+
+function hydrateHostsFromBackend() {
+  const src = props.templateSettings?.dns?.hosts || {};
+  hostsList.value = Object.entries(src).map(([domain, val]) => ({
+    domain,
+    values: Array.isArray(val) ? [...val] : [String(val)],
+  }));
+}
+
+function syncHostsToBackend() {
+  if (!props.templateSettings?.dns) return;
+  const obj = {};
+  for (const row of hostsList.value) {
+    if (!row.domain) continue;
+    const vals = (row.values || []).filter(Boolean);
+    if (vals.length === 0) continue;
+    obj[row.domain] = vals.length === 1 ? vals[0] : vals;
+  }
+  if (Object.keys(obj).length > 0) {
+    props.templateSettings.dns.hosts = obj;
+  } else if ('hosts' in props.templateSettings.dns) {
+    delete props.templateSettings.dns.hosts;
+  }
+}
+
+watch(
+  () => !!props.templateSettings?.dns,
+  (enabled) => {
+    if (enabled) hydrateHostsFromBackend();
+    else hostsList.value = [];
+  },
+  { immediate: true },
+);
+
+watch(hostsList, syncHostsToBackend, { deep: true });
+
+function addHost() {
+  hostsList.value.push({ domain: '', values: [] });
+}
+function deleteHost(idx) {
+  hostsList.value.splice(idx, 1);
+}
 
-// ============== DNS server table ==============
 const dnsServers = computed(() => {
   const list = props.templateSettings?.dns?.servers || [];
   return list.map((s, idx) => ({ key: idx, server: s }));
@@ -79,7 +122,7 @@ const dnsColumns = computed(() => [
   { title: '#', key: 'action', align: 'center', width: 60 },
   { title: t('pages.inbounds.address'), key: 'address', align: 'left' },
   { title: t('pages.xray.dns.domains'), key: 'domains', align: 'left' },
-  { title: t('pages.xray.dns.expectIPs'), key: 'expectIPs', align: 'left' },
+  { title: t('pages.xray.dns.expectIPs'), key: 'expectedIPs', align: 'left' },
 ]);
 
 function addrFor(server) {
@@ -88,8 +131,10 @@ function addrFor(server) {
 function domainsFor(server) {
   return typeof server === 'object' ? (server.domains || []).join(',') : '';
 }
-function expectIPsFor(server) {
-  return typeof server === 'object' ? (server.expectIPs || []).join(',') : '';
+function expectedIPsFor(server) {
+  if (typeof server !== 'object' || !server) return '';
+  const list = server.expectedIPs || server.expectIPs || [];
+  return Array.isArray(list) ? list.join(',') : '';
 }
 
 // ============== Server modal ==============
@@ -122,6 +167,27 @@ function onServerConfirm(value) {
 function deleteServer(idx) {
   props.templateSettings.dns.servers.splice(idx, 1);
 }
+function clearAllServers() {
+  if (!props.templateSettings?.dns) return;
+  Modal.confirm({
+    title: t('pages.xray.dns.clearAllTitle'),
+    content: t('pages.xray.dns.clearAllConfirm'),
+    okText: t('delete'),
+    okButtonProps: { danger: true },
+    cancelText: t('cancel'),
+    onOk() {
+      props.templateSettings.dns.servers = [];
+    },
+  });
+}
+
+const presetsModalOpen = ref(false);
+function openPresets() { presetsModalOpen.value = true; }
+function onPresetInstall(serverList) {
+  if (!props.templateSettings?.dns) return;
+  props.templateSettings.dns.servers = serverList;
+  presetsModalOpen.value = false;
+}
 
 // ============== Fake DNS table ==============
 const DEFAULT_FAKEDNS = () => ({ ipPool: '198.18.0.0/15', poolSize: 65535 });
@@ -239,32 +305,102 @@ function updateFakednsField(idx, field, value) {
             <a-switch v-model:checked="dnsUseSystemHosts" />
           </template>
         </SettingListItem>
+
+        <SettingListItem paddings="small">
+          <template #title>{{ t('pages.xray.dns.serveStale') }}</template>
+          <template #description>{{ t('pages.xray.dns.serveStaleDesc') }}</template>
+          <template #control>
+            <a-switch v-model:checked="dnsServeStale" />
+          </template>
+        </SettingListItem>
+
+        <SettingListItem paddings="small">
+          <template #title>{{ t('pages.xray.dns.serveExpiredTTL') }}</template>
+          <template #description>{{ t('pages.xray.dns.serveExpiredTTLDesc') }}</template>
+          <template #control>
+            <a-input-number v-model:value="dnsServeExpiredTTL" :min="0" :step="60" :style="{ width: '100%' }" />
+          </template>
+        </SettingListItem>
       </template>
     </a-collapse-panel>
 
-    <!-- ============== DNS servers ============== -->
-    <a-collapse-panel v-if="enableDNS" key="2" header="DNS">
-      <a-empty v-if="dnsServers.length === 0" :description="t('emptyDnsDesc')">
-        <a-button type="primary" @click="openAddServer">
-          <template #icon><PlusOutlined /></template>
-          {{ t('pages.xray.dns.add') }}
+    <!-- ============== Hosts ============== -->
+    <a-collapse-panel v-if="enableDNS" key="hosts" :header="t('pages.xray.dns.hosts')">
+      <a-empty v-if="hostsList.length === 0" :description="t('pages.xray.dns.hostsEmpty')">
+        <a-button type="primary" @click="addHost">
+          <template #icon>
+            <PlusOutlined />
+          </template>
+          {{ t('pages.xray.dns.hostsAdd') }}
         </a-button>
       </a-empty>
 
       <template v-else>
         <a-space direction="vertical" size="middle" :style="{ width: '100%' }">
+          <a-button type="primary" @click="addHost">
+            <template #icon>
+              <PlusOutlined />
+            </template>
+            {{ t('pages.xray.dns.hostsAdd') }}
+          </a-button>
+          <div v-for="(row, idx) in hostsList" :key="`h${idx}`" class="hosts-row">
+            <a-input v-model:value="row.domain" :placeholder="t('pages.xray.dns.hostsDomain')"
+              :style="{ flex: '1 1 220px' }" />
+            <a-select v-model:value="row.values" mode="tags" :placeholder="t('pages.xray.dns.hostsValues')"
+              :style="{ flex: '2 1 320px' }" :token-separators="[',', ' ']" />
+            <a-button danger @click="deleteHost(idx)">
+              <template #icon>
+                <DeleteOutlined />
+              </template>
+            </a-button>
+          </div>
+        </a-space>
+      </template>
+    </a-collapse-panel>
+
+    <!-- ============== DNS servers ============== -->
+    <a-collapse-panel v-if="enableDNS" key="2" header="DNS">
+      <a-empty v-if="dnsServers.length === 0" :description="t('emptyDnsDesc')">
+        <a-space>
           <a-button type="primary" @click="openAddServer">
-            <template #icon><PlusOutlined /></template>
+            <template #icon>
+              <PlusOutlined />
+            </template>
             {{ t('pages.xray.dns.add') }}
           </a-button>
-          <a-table
-            :columns="dnsColumns"
-            :data-source="dnsServers"
-            :row-key="(r) => r.key"
-            :pagination="false"
-            size="small"
-            bordered
-          >
+          <a-button @click="openPresets">
+            <template #icon>
+              <MenuOutlined />
+            </template>
+            {{ t('pages.xray.dns.usePreset') }}
+          </a-button>
+        </a-space>
+      </a-empty>
+
+      <template v-else>
+        <a-space direction="vertical" size="middle" :style="{ width: '100%' }">
+          <a-space wrap>
+            <a-button type="primary" @click="openAddServer">
+              <template #icon>
+                <PlusOutlined />
+              </template>
+              {{ t('pages.xray.dns.add') }}
+            </a-button>
+            <a-button @click="openPresets">
+              <template #icon>
+                <MenuOutlined />
+              </template>
+              {{ t('pages.xray.dns.usePreset') }}
+            </a-button>
+            <a-button danger @click="clearAllServers">
+              <template #icon>
+                <DeleteOutlined />
+              </template>
+              {{ t('pages.xray.dns.clearAll') }}
+            </a-button>
+          </a-space>
+          <a-table :columns="dnsColumns" :data-source="dnsServers" :row-key="(r) => r.key" :pagination="false"
+            size="small" bordered>
             <template #bodyCell="{ column, record, index }">
               <template v-if="column.key === 'action'">
                 <a-space :size="6">
@@ -292,8 +428,8 @@ function updateFakednsField(idx, field, value) {
               <template v-else-if="column.key === 'domains'">
                 <span class="muted">{{ domainsFor(record.server) }}</span>
               </template>
-              <template v-else-if="column.key === 'expectIPs'">
-                <span class="muted">{{ expectIPsFor(record.server) }}</span>
+              <template v-else-if="column.key === 'expectedIPs'">
+                <span class="muted">{{ expectedIPsFor(record.server) }}</span>
               </template>
             </template>
           </a-table>
@@ -305,7 +441,9 @@ function updateFakednsField(idx, field, value) {
     <a-collapse-panel v-if="enableDNS" key="3" header="Fake DNS">
       <a-empty v-if="fakeDnsList.length === 0" :description="t('emptyFakeDnsDesc')">
         <a-button type="primary" @click="addFakedns">
-          <template #icon><PlusOutlined /></template>
+          <template #icon>
+            <PlusOutlined />
+          </template>
           {{ t('pages.xray.fakedns.add') }}
         </a-button>
       </a-empty>
@@ -313,17 +451,13 @@ function updateFakednsField(idx, field, value) {
       <template v-else>
         <a-space direction="vertical" size="middle" :style="{ width: '100%' }">
           <a-button type="primary" @click="addFakedns">
-            <template #icon><PlusOutlined /></template>
+            <template #icon>
+              <PlusOutlined />
+            </template>
             {{ t('pages.xray.fakedns.add') }}
           </a-button>
-          <a-table
-            :columns="fakednsColumns"
-            :data-source="fakeDnsList"
-            :row-key="(r) => r.key"
-            :pagination="false"
-            size="small"
-            bordered
-          >
+          <a-table :columns="fakednsColumns" :data-source="fakeDnsList" :row-key="(r) => r.key" :pagination="false"
+            size="small" bordered>
             <template #bodyCell="{ column, record, index }">
               <template v-if="column.key === 'action'">
                 <a-space :size="6">
@@ -334,19 +468,12 @@ function updateFakednsField(idx, field, value) {
                 </a-space>
               </template>
               <template v-else-if="column.key === 'ipPool'">
-                <a-input
-                  :value="record.ipPool"
-                  size="small"
-                  @change="(e) => updateFakednsField(index, 'ipPool', e.target.value)"
-                />
+                <a-input :value="record.ipPool" size="small"
+                  @change="(e) => updateFakednsField(index, 'ipPool', e.target.value)" />
               </template>
               <template v-else-if="column.key === 'poolSize'">
-                <a-input-number
-                  :value="record.poolSize"
-                  :min="1"
-                  size="small"
-                  @change="(v) => updateFakednsField(index, 'poolSize', v)"
-                />
+                <a-input-number :value="record.poolSize" :min="1" size="small"
+                  @change="(v) => updateFakednsField(index, 'poolSize', v)" />
               </template>
             </template>
           </a-table>
@@ -355,12 +482,9 @@ function updateFakednsField(idx, field, value) {
     </a-collapse-panel>
   </a-collapse>
 
-  <DnsServerModal
-    v-model:open="serverModalOpen"
-    :server="editingServer"
-    :is-edit="editingIndex != null"
-    @confirm="onServerConfirm"
-  />
+  <DnsServerModal v-model:open="serverModalOpen" :server="editingServer" :is-edit="editingIndex != null"
+    @confirm="onServerConfirm" />
+  <DnsPresetsModal v-model:open="presetsModalOpen" @install="onPresetInstall" />
 </template>
 
 <style scoped>
@@ -368,6 +492,20 @@ function updateFakednsField(idx, field, value) {
   font-weight: 500;
   opacity: 0.7;
 }
-.muted { opacity: 0.7; word-break: break-all; }
-.danger { color: #ff4d4f; }
+
+.muted {
+  opacity: 0.7;
+  word-break: break-all;
+}
+
+.danger {
+  color: #ff4d4f;
+}
+
+.hosts-row {
+  display: flex;
+  gap: 8px;
+  align-items: center;
+  flex-wrap: wrap;
+}
 </style>

+ 3 - 7
frontend/src/pages/xray/OutboundFormModal.vue

@@ -343,8 +343,7 @@ function regenerateWgKeys() {
               <a-input-number v-model:value="outbound.settings.userLevel" :min="0" :style="{ width: '100%' }" />
             </a-form-item>
             <a-form-item label="Rules">
-              <a-button size="small" type="primary"
-                @click="outbound.settings.rules.push(new Outbound.DNSRule())">
+              <a-button size="small" type="primary" @click="outbound.settings.rules.push(new Outbound.DNSRule())">
                 <template #icon>
                   <PlusOutlined />
                 </template>
@@ -955,11 +954,8 @@ function regenerateWgKeys() {
         <!-- Gated by canEnableStream() so TCP masks don't leak into
              Freedom / Blackhole / DNS / Socks / HTTP / Wireguard outbounds
              (they don't have a stream config at all). Matches legacy. -->
-        <FinalMaskForm
-          v-if="outbound.stream && outbound.canEnableStream()"
-          :stream="outbound.stream"
-          :protocol="proto"
-        />
+        <FinalMaskForm v-if="outbound.stream && outbound.canEnableStream()" :stream="outbound.stream"
+          :protocol="proto" />
       </a-tab-pane>
 
       <!-- ============================== JSON ============================== -->

+ 76 - 57
frontend/src/pages/xray/OutboundsTab.vue

@@ -48,7 +48,7 @@ const inboundTagOptions = computed(() => {
   return [...out];
 });
 
-const emit = defineEmits(['reset-traffic', 'test', 'show-warp', 'show-nord']);
+const emit = defineEmits(['reset-traffic', 'test', 'show-warp', 'show-nord', 'delete']);
 
 // === Modal state ====================================================
 const modalOpen = ref(false);
@@ -86,7 +86,7 @@ function confirmDelete(idx) {
     okText: t('delete'),
     okType: 'danger',
     cancelText: t('cancel'),
-    onOk: () => { props.templateSettings.outbounds.splice(idx, 1); },
+    onOk: () => { emit('delete', idx); },
   });
 }
 function setFirst(idx) {
@@ -180,29 +180,32 @@ const rows = computed(() => {
       <a-col :xs="24" :sm="14">
         <a-space size="small">
           <a-button type="primary" @click="openAdd">
-            <template #icon><PlusOutlined /></template>
+            <template #icon>
+              <PlusOutlined />
+            </template>
             <span v-if="!isMobile">{{ t('pages.xray.Outbounds') }}</span>
           </a-button>
           <a-button type="primary" @click="emit('show-warp')">
-            <template #icon><CloudOutlined /></template>
+            <template #icon>
+              <CloudOutlined />
+            </template>
             WARP
           </a-button>
           <a-button type="primary" @click="emit('show-nord')">
-            <template #icon><ApiOutlined /></template>
+            <template #icon>
+              <ApiOutlined />
+            </template>
             NordVPN
           </a-button>
         </a-space>
       </a-col>
       <a-col :xs="24" :sm="10" class="toolbar-right">
-        <a-popconfirm
-          placement="topRight"
-          :ok-text="t('reset')"
-          :cancel-text="t('cancel')"
-          :title="t('pages.inbounds.resetAllTrafficContent')"
-          @confirm="emit('reset-traffic', '-alltags-')"
-        >
+        <a-popconfirm placement="topRight" :ok-text="t('reset')" :cancel-text="t('cancel')"
+          :title="t('pages.inbounds.resetAllTrafficContent')" @confirm="emit('reset-traffic', '-alltags-')">
           <a-button>
-            <template #icon><RetweetOutlined /></template>
+            <template #icon>
+              <RetweetOutlined />
+            </template>
           </a-button>
         </a-popconfirm>
       </a-col>
@@ -220,8 +223,7 @@ const rows = computed(() => {
             </a-tooltip>
             <a-tag color="green">{{ record.protocol }}</a-tag>
             <template
-              v-if="[Protocols.VMess, Protocols.VLESS, Protocols.Trojan, Protocols.Shadowsocks].includes(record.protocol)"
-            >
+              v-if="[Protocols.VMess, Protocols.VLESS, Protocols.Trojan, Protocols.Shadowsocks].includes(record.protocol)">
               <a-tag>{{ record.streamSettings?.network }}</a-tag>
               <a-tag v-if="showSecurity(record.streamSettings?.security)" color="purple">
                 {{ record.streamSettings.security }}
@@ -267,15 +269,11 @@ const rows = computed(() => {
               <span v-else>failed</span>
             </span>
             <LoadingOutlined v-else-if="isTesting(index)" />
-            <a-button
-              type="primary"
-              shape="circle"
-              size="small"
-              :loading="isTesting(index)"
-              :disabled="isUntestable(record) || isTesting(index)"
-              @click="emit('test', index)"
-            >
-              <template #icon><ThunderboltOutlined /></template>
+            <a-button type="primary" shape="circle" size="small" :loading="isTesting(index)"
+              :disabled="isUntestable(record) || isTesting(index)" @click="emit('test', index)">
+              <template #icon>
+                <ThunderboltOutlined />
+              </template>
             </a-button>
           </span>
         </div>
@@ -283,14 +281,7 @@ const rows = computed(() => {
     </template>
 
     <!-- Desktop: table -->
-    <a-table
-      v-else
-      :columns="columns"
-      :data-source="rows"
-      :row-key="(r) => r.key"
-      :pagination="false"
-      size="small"
-    >
+    <a-table v-else :columns="columns" :data-source="rows" :row-key="(r) => r.key" :pagination="false" size="small">
       <template #bodyCell="{ column, record, index }">
         <template v-if="column.key === 'action'">
           <div class="action-cell">
@@ -333,8 +324,7 @@ const rows = computed(() => {
             <div class="protocol-line">
               <a-tag color="green">{{ record.protocol }}</a-tag>
               <template
-                v-if="[Protocols.VMess, Protocols.VLESS, Protocols.Trojan, Protocols.Shadowsocks].includes(record.protocol)"
-              >
+                v-if="[Protocols.VMess, Protocols.VLESS, Protocols.Trojan, Protocols.Shadowsocks].includes(record.protocol)">
                 <a-tag>{{ record.streamSettings?.network }}</a-tag>
                 <a-tag v-if="showSecurity(record.streamSettings?.security)" color="purple">
                   {{ record.streamSettings.security }}
@@ -374,38 +364,34 @@ const rows = computed(() => {
 
         <template v-else-if="column.key === 'test'">
           <a-tooltip :title="t('check')">
-            <a-button
-              type="primary"
-              shape="circle"
-              :loading="isTesting(index)"
-              :disabled="isUntestable(record) || isTesting(index)"
-              @click="emit('test', index)"
-            >
-              <template #icon><ThunderboltOutlined /></template>
+            <a-button type="primary" shape="circle" :loading="isTesting(index)"
+              :disabled="isUntestable(record) || isTesting(index)" @click="emit('test', index)">
+              <template #icon>
+                <ThunderboltOutlined />
+              </template>
             </a-button>
           </a-tooltip>
         </template>
       </template>
     </a-table>
 
-    <OutboundFormModal
-      v-model:open="modalOpen"
-      :outbound="editingOutbound"
-      :existing-tags="existingTags"
-      :inbound-tags="inboundTagOptions"
-      @confirm="onConfirm"
-    />
+    <OutboundFormModal v-model:open="modalOpen" :outbound="editingOutbound" :existing-tags="existingTags"
+      :inbound-tags="inboundTagOptions" @confirm="onConfirm" />
   </a-space>
 </template>
 
 <style scoped>
-.toolbar-right { display: flex; justify-content: flex-end; }
+.toolbar-right {
+  display: flex;
+  justify-content: flex-end;
+}
 
 .card-empty {
   text-align: center;
   opacity: 0.4;
   padding: 16px 0;
 }
+
 .outbound-card {
   border: 1px solid rgba(128, 128, 128, 0.2);
   border-radius: 8px;
@@ -415,24 +401,28 @@ const rows = computed(() => {
   flex-direction: column;
   gap: 8px;
 }
+
 .card-head {
   display: flex;
   align-items: flex-start;
   justify-content: space-between;
   gap: 8px;
 }
+
 .card-identity {
   display: flex;
   flex-wrap: wrap;
   align-items: center;
   gap: 6px;
 }
+
 .card-num {
   font-weight: 500;
   opacity: 0.7;
   min-width: 18px;
   text-align: right;
 }
+
 .tag-name {
   font-weight: 500;
   max-width: 200px;
@@ -441,6 +431,7 @@ const rows = computed(() => {
   white-space: nowrap;
   display: inline-block;
 }
+
 .protocol-line {
   display: inline-flex;
   flex-wrap: wrap;
@@ -452,12 +443,14 @@ const rows = computed(() => {
   flex-wrap: wrap;
   gap: 4px;
 }
+
 .address-pill {
   font-size: 11px;
   padding: 2px 6px;
   border-radius: 4px;
   background: rgba(0, 0, 0, 0.05);
 }
+
 :global(body.dark) .address-pill {
   background: rgba(255, 255, 255, 0.06);
 }
@@ -467,6 +460,7 @@ const rows = computed(() => {
   align-items: center;
   gap: 6px;
 }
+
 .row-index {
   font-weight: 500;
   opacity: 0.7;
@@ -487,6 +481,7 @@ const rows = computed(() => {
   gap: 12px;
   flex-wrap: wrap;
 }
+
 .card-test {
   margin-left: auto;
   display: inline-flex;
@@ -494,9 +489,20 @@ const rows = computed(() => {
   gap: 8px;
 }
 
-.traffic-up { color: #008771; font-size: 12px; }
-.traffic-down { color: #3c89e8; font-size: 12px; }
-.traffic-sep { display: inline-block; width: 4px; }
+.traffic-up {
+  color: #008771;
+  font-size: 12px;
+}
+
+.traffic-down {
+  color: #3c89e8;
+  font-size: 12px;
+}
+
+.traffic-sep {
+  display: inline-block;
+  width: 4px;
+}
 
 .pill-ok,
 .pill-fail {
@@ -507,9 +513,22 @@ const rows = computed(() => {
   border-radius: 12px;
   font-size: 12px;
 }
-.pill-ok { color: #008771; background: rgba(0, 135, 113, 0.12); }
-.pill-fail { color: #e04141; background: rgba(224, 65, 65, 0.12); }
 
-.empty { opacity: 0.4; }
-.danger { color: #ff4d4f; }
+.pill-ok {
+  color: #008771;
+  background: rgba(0, 135, 113, 0.12);
+}
+
+.pill-fail {
+  color: #e04141;
+  background: rgba(224, 65, 65, 0.12);
+}
+
+.empty {
+  opacity: 0.4;
+}
+
+.danger {
+  color: #ff4d4f;
+}
 </style>

+ 37 - 28
frontend/src/pages/xray/RoutingTab.vue

@@ -169,19 +169,14 @@ const columns = computed(() => (props.isMobile ? mobileColumns.value : desktopCo
 <template>
   <a-space direction="vertical" size="middle" :style="{ width: '100%' }">
     <a-button type="primary" @click="openAdd">
-      <template #icon><PlusOutlined /></template>
+      <template #icon>
+        <PlusOutlined />
+      </template>
       {{ t('pages.xray.Routings') }}
     </a-button>
 
-    <a-table
-      :columns="columns"
-      :data-source="rows"
-      :row-key="(r) => r.key"
-      :pagination="false"
-      :scroll="isMobile ? {} : { x: 1000 }"
-      size="small"
-      class="routing-table"
-    >
+    <a-table :columns="columns" :data-source="rows" :row-key="(r) => r.key" :pagination="false"
+      :scroll="isMobile ? {} : { x: 1000 }" size="small" class="routing-table">
       <template #bodyCell="{ column, record, index }">
         <!-- ============== # / actions ============== -->
         <template v-if="column.key === 'action'">
@@ -218,21 +213,24 @@ const columns = computed(() => (props.isMobile ? mobileColumns.value : desktopCo
               <span class="criterion-row">
                 <span class="criterion-label">IP</span>
                 <span class="criterion-value">{{ csv(record.sourceIP)[0] }}</span>
-                <span v-if="csv(record.sourceIP).length > 1" class="criterion-more">+{{ csv(record.sourceIP).length - 1 }}</span>
+                <span v-if="csv(record.sourceIP).length > 1" class="criterion-more">+{{ csv(record.sourceIP).length - 1
+                  }}</span>
               </span>
             </a-tooltip>
             <a-tooltip v-if="record.sourcePort" :title="`Source port: ${record.sourcePort}`">
               <span class="criterion-row">
                 <span class="criterion-label">Port</span>
                 <span class="criterion-value">{{ csv(record.sourcePort)[0] }}</span>
-                <span v-if="csv(record.sourcePort).length > 1" class="criterion-more">+{{ csv(record.sourcePort).length - 1 }}</span>
+                <span v-if="csv(record.sourcePort).length > 1" class="criterion-more">+{{ csv(record.sourcePort).length
+                  - 1 }}</span>
               </span>
             </a-tooltip>
             <a-tooltip v-if="record.vlessRoute" :title="`VLESS route: ${record.vlessRoute}`">
               <span class="criterion-row">
                 <span class="criterion-label">VLESS</span>
                 <span class="criterion-value">{{ csv(record.vlessRoute)[0] }}</span>
-                <span v-if="csv(record.vlessRoute).length > 1" class="criterion-more">+{{ csv(record.vlessRoute).length - 1 }}</span>
+                <span v-if="csv(record.vlessRoute).length > 1" class="criterion-more">+{{ csv(record.vlessRoute).length
+                  - 1 }}</span>
               </span>
             </a-tooltip>
             <span v-if="!record.sourceIP && !record.sourcePort && !record.vlessRoute" class="criterion-empty">—</span>
@@ -246,14 +244,16 @@ const columns = computed(() => (props.isMobile ? mobileColumns.value : desktopCo
               <span class="criterion-row">
                 <span class="criterion-label">L4</span>
                 <span class="criterion-value">{{ csv(record.network)[0] }}</span>
-                <span v-if="csv(record.network).length > 1" class="criterion-more">+{{ csv(record.network).length - 1 }}</span>
+                <span v-if="csv(record.network).length > 1" class="criterion-more">+{{ csv(record.network).length - 1
+                  }}</span>
               </span>
             </a-tooltip>
             <a-tooltip v-if="record.protocol" :title="`Protocol: ${record.protocol}`">
               <span class="criterion-row">
                 <span class="criterion-label">Protocol</span>
                 <span class="criterion-value">{{ csv(record.protocol)[0] }}</span>
-                <span v-if="csv(record.protocol).length > 1" class="criterion-more">+{{ csv(record.protocol).length - 1 }}</span>
+                <span v-if="csv(record.protocol).length > 1" class="criterion-more">+{{ csv(record.protocol).length - 1
+                  }}</span>
               </span>
             </a-tooltip>
             <a-tooltip v-if="record.attrs" :title="`Attrs: ${record.attrs}`">
@@ -280,14 +280,16 @@ const columns = computed(() => (props.isMobile ? mobileColumns.value : desktopCo
               <span class="criterion-row">
                 <span class="criterion-label">Domain</span>
                 <span class="criterion-value">{{ csv(record.domain)[0] }}</span>
-                <span v-if="csv(record.domain).length > 1" class="criterion-more">+{{ csv(record.domain).length - 1 }}</span>
+                <span v-if="csv(record.domain).length > 1" class="criterion-more">+{{ csv(record.domain).length - 1
+                  }}</span>
               </span>
             </a-tooltip>
             <a-tooltip v-if="record.port" :title="`Destination port: ${record.port}`">
               <span class="criterion-row">
                 <span class="criterion-label">Port</span>
                 <span class="criterion-value">{{ csv(record.port)[0] }}</span>
-                <span v-if="csv(record.port).length > 1" class="criterion-more">+{{ csv(record.port).length - 1 }}</span>
+                <span v-if="csv(record.port).length > 1" class="criterion-more">+{{ csv(record.port).length - 1
+                  }}</span>
               </span>
             </a-tooltip>
             <span v-if="!record.ip && !record.domain && !record.port" class="criterion-empty">—</span>
@@ -301,14 +303,16 @@ const columns = computed(() => (props.isMobile ? mobileColumns.value : desktopCo
               <span class="criterion-row">
                 <span class="criterion-label">Tag</span>
                 <span class="criterion-value">{{ csv(record.inboundTag)[0] }}</span>
-                <span v-if="csv(record.inboundTag).length > 1" class="criterion-more">+{{ csv(record.inboundTag).length - 1 }}</span>
+                <span v-if="csv(record.inboundTag).length > 1" class="criterion-more">+{{ csv(record.inboundTag).length
+                  - 1 }}</span>
               </span>
             </a-tooltip>
             <a-tooltip v-if="record.user" :title="`User: ${record.user}`">
               <span class="criterion-row">
                 <span class="criterion-label">User</span>
                 <span class="criterion-value">{{ csv(record.user)[0] }}</span>
-                <span v-if="csv(record.user).length > 1" class="criterion-more">+{{ csv(record.user).length - 1 }}</span>
+                <span v-if="csv(record.user).length > 1" class="criterion-more">+{{ csv(record.user).length - 1
+                  }}</span>
               </span>
             </a-tooltip>
             <span v-if="!record.inboundTag && !record.user" class="criterion-empty">—</span>
@@ -332,14 +336,8 @@ const columns = computed(() => (props.isMobile ? mobileColumns.value : desktopCo
       </template>
     </a-table>
 
-    <RuleFormModal
-      v-model:open="ruleModalOpen"
-      :rule="editingRule"
-      :inbound-tags="inboundTagOptions"
-      :outbound-tags="outboundTagOptions"
-      :balancer-tags="balancerTagOptions"
-      @confirm="onRuleConfirm"
-    />
+    <RuleFormModal v-model:open="ruleModalOpen" :rule="editingRule" :inbound-tags="inboundTagOptions"
+      :outbound-tags="outboundTagOptions" :balancer-tags="balancerTagOptions" @confirm="onRuleConfirm" />
   </a-space>
 </template>
 
@@ -349,6 +347,7 @@ const columns = computed(() => (props.isMobile ? mobileColumns.value : desktopCo
   align-items: center;
   gap: 6px;
 }
+
 .row-index {
   font-weight: 500;
   opacity: 0.7;
@@ -362,30 +361,36 @@ const columns = computed(() => (props.isMobile ? mobileColumns.value : desktopCo
   gap: 2px;
   font-size: 12px;
 }
+
 .criterion-row {
   display: inline-flex;
   align-items: baseline;
   gap: 4px;
   white-space: nowrap;
 }
+
 .criterion-label {
   font-size: 10px;
   text-transform: uppercase;
   opacity: 0.55;
   letter-spacing: 0.04em;
 }
+
 .criterion-value {
   font-weight: 500;
 }
+
 .criterion-more {
   font-size: 11px;
   padding: 0 5px;
   border-radius: 8px;
   background: rgba(0, 0, 0, 0.06);
 }
+
 :global(body.dark) .criterion-more {
   background: rgba(255, 255, 255, 0.1);
 }
+
 .criterion-empty {
   opacity: 0.4;
 }
@@ -395,15 +400,19 @@ const columns = computed(() => (props.isMobile ? mobileColumns.value : desktopCo
   flex-direction: column;
   gap: 2px;
 }
+
 .target-row {
   display: flex;
   align-items: center;
   gap: 4px;
 }
+
 .target-icon {
   font-size: 12px;
   opacity: 0.6;
 }
 
-.danger { color: #ff4d4f; }
+.danger {
+  color: #ff4d4f;
+}
 </style>

+ 35 - 23
frontend/src/pages/xray/RuleFormModal.vue

@@ -137,21 +137,14 @@ const PROTOCOLS = ['http', 'tls', 'bittorrent', 'quic'];
 </script>
 
 <template>
-  <a-modal
-    :open="open"
-    :title="title"
-    :ok-text="okText"
-    :cancel-text="t('close')"
-    :mask-closable="false"
-    width="640px"
-    @ok="onOk"
-    @cancel="close"
-  >
+  <a-modal :open="open" :title="title" :ok-text="okText" :cancel-text="t('close')" :mask-closable="false" width="640px"
+    @ok="onOk" @cancel="close">
     <a-form :colon="false" :label-col="{ md: { span: 8 } }" :wrapper-col="{ md: { span: 14 } }">
       <a-form-item>
         <template #label>
           <a-tooltip title="Comma-separated list">
-            Source IPs <QuestionCircleOutlined />
+            Source IPs
+            <QuestionCircleOutlined />
           </a-tooltip>
         </template>
         <a-input v-model:value="form.sourceIP" placeholder="0.0.0.0/8, fc00::/7, geoip:ir" />
@@ -160,7 +153,8 @@ const PROTOCOLS = ['http', 'tls', 'bittorrent', 'quic'];
       <a-form-item>
         <template #label>
           <a-tooltip title="Comma-separated list">
-            Source port <QuestionCircleOutlined />
+            Source port
+            <QuestionCircleOutlined />
           </a-tooltip>
         </template>
         <a-input v-model:value="form.sourcePort" placeholder="53,443,1000-2000" />
@@ -169,7 +163,8 @@ const PROTOCOLS = ['http', 'tls', 'bittorrent', 'quic'];
       <a-form-item>
         <template #label>
           <a-tooltip title="Comma-separated list">
-            VLESS route <QuestionCircleOutlined />
+            VLESS route
+            <QuestionCircleOutlined />
           </a-tooltip>
         </template>
         <a-input v-model:value="form.vlessRoute" placeholder="53,443,1000-2000" />
@@ -189,7 +184,9 @@ const PROTOCOLS = ['http', 'tls', 'bittorrent', 'quic'];
 
       <a-form-item label="Attributes">
         <a-button size="small" @click="form.attrs.push(['', ''])">
-          <template #icon><PlusOutlined /></template>
+          <template #icon>
+            <PlusOutlined />
+          </template>
         </a-button>
       </a-form-item>
       <a-form-item :wrapper-col="{ span: 24 }">
@@ -199,35 +196,45 @@ const PROTOCOLS = ['http', 'tls', 'bittorrent', 'quic'];
           </a-input>
           <a-input :style="{ width: '45%' }" v-model:value="attr[1]" placeholder="Value" />
           <a-button @click="form.attrs.splice(idx, 1)">
-            <template #icon><MinusOutlined /></template>
+            <template #icon>
+              <MinusOutlined />
+            </template>
           </a-button>
         </a-input-group>
       </a-form-item>
 
       <a-form-item>
         <template #label>
-          <a-tooltip title="Comma-separated list">IP <QuestionCircleOutlined /></a-tooltip>
+          <a-tooltip title="Comma-separated list">IP
+            <QuestionCircleOutlined />
+          </a-tooltip>
         </template>
         <a-input v-model:value="form.ip" placeholder="0.0.0.0/8, fc00::/7, geoip:ir" />
       </a-form-item>
 
       <a-form-item>
         <template #label>
-          <a-tooltip title="Comma-separated list">Domain <QuestionCircleOutlined /></a-tooltip>
+          <a-tooltip title="Comma-separated list">Domain
+            <QuestionCircleOutlined />
+          </a-tooltip>
         </template>
         <a-input v-model:value="form.domain" placeholder="google.com, geosite:cn" />
       </a-form-item>
 
       <a-form-item>
         <template #label>
-          <a-tooltip title="Comma-separated list">User <QuestionCircleOutlined /></a-tooltip>
+          <a-tooltip title="Comma-separated list">User
+            <QuestionCircleOutlined />
+          </a-tooltip>
         </template>
         <a-input v-model:value="form.user" placeholder="email address" />
       </a-form-item>
 
       <a-form-item>
         <template #label>
-          <a-tooltip title="Comma-separated list">Port <QuestionCircleOutlined /></a-tooltip>
+          <a-tooltip title="Comma-separated list">Port
+            <QuestionCircleOutlined />
+          </a-tooltip>
         </template>
         <a-input v-model:value="form.port" placeholder="53,443,1000-2000" />
       </a-form-item>
@@ -240,18 +247,21 @@ const PROTOCOLS = ['http', 'tls', 'bittorrent', 'quic'];
 
       <a-form-item label="Outbound tag">
         <a-select v-model:value="form.outboundTag">
-          <a-select-option v-for="tag in outboundTags" :key="tag || '__empty'" :value="tag">{{ tag || '(none)' }}</a-select-option>
+          <a-select-option v-for="tag in outboundTags" :key="tag || '__empty'" :value="tag">{{ tag || '(none)'
+            }}</a-select-option>
         </a-select>
       </a-form-item>
 
       <a-form-item>
         <template #label>
           <a-tooltip title="Routes traffic through one of the configured load balancers">
-            Balancer tag <QuestionCircleOutlined />
+            Balancer tag
+            <QuestionCircleOutlined />
           </a-tooltip>
         </template>
         <a-select v-model:value="form.balancerTag">
-          <a-select-option v-for="tag in balancerTags" :key="tag || '__empty'" :value="tag">{{ tag || '(none)' }}</a-select-option>
+          <a-select-option v-for="tag in balancerTags" :key="tag || '__empty'" :value="tag">{{ tag || '(none)'
+            }}</a-select-option>
         </a-select>
       </a-form-item>
     </a-form>
@@ -259,5 +269,7 @@ const PROTOCOLS = ['http', 'tls', 'bittorrent', 'quic'];
 </template>
 
 <style scoped>
-.mb-8 { margin-bottom: 8px; }
+.mb-8 {
+  margin-bottom: 8px;
+}
 </style>

+ 38 - 24
frontend/src/pages/xray/WarpModal.vue

@@ -182,14 +182,7 @@ const hasConfig = computed(() => !ObjectUtil.isEmpty(warpConfig.value));
 </script>
 
 <template>
-  <a-modal
-    :open="open"
-    title="Cloudflare WARP"
-    :footer="null"
-    :closable="true"
-    :mask-closable="true"
-    @cancel="close"
-  >
+  <a-modal :open="open" title="Cloudflare WARP" :footer="null" :closable="true" :mask-closable="true" @cancel="close">
     <!-- WARP / NordVPN provisioning forms keep technical wire labels in
          English on purpose: they map directly to API field names users
          look up in vendor docs. Only the primary action buttons +
@@ -197,7 +190,9 @@ const hasConfig = computed(() => !ObjectUtil.isEmpty(warpConfig.value));
     <!-- Not registered yet → single Create CTA -->
     <template v-if="!hasWarp">
       <a-button type="primary" :loading="loading" @click="register">
-        <template #icon><ApiOutlined /></template>
+        <template #icon>
+          <ApiOutlined />
+        </template>
         Create WARP account
       </a-button>
     </template>
@@ -226,7 +221,9 @@ const hasConfig = computed(() => !ObjectUtil.isEmpty(warpConfig.value));
       </table>
 
       <a-button :loading="loading" type="primary" danger class="mt-8" @click="delConfig">
-        <template #icon><DeleteOutlined /></template>
+        <template #icon>
+          <DeleteOutlined />
+        </template>
         Delete account
       </a-button>
 
@@ -237,13 +234,8 @@ const hasConfig = computed(() => !ObjectUtil.isEmpty(warpConfig.value));
           <a-form :colon="false" :label-col="{ md: { span: 6 } }" :wrapper-col="{ md: { span: 14 } }">
             <a-form-item label="Key">
               <a-input v-model:value="warpPlus" placeholder="26-char WARP+ key" />
-              <a-button
-                type="primary"
-                class="mt-8"
-                :disabled="warpPlus.length < 26"
-                :loading="loading"
-                @click="updateLicense"
-              >Update</a-button>
+              <a-button type="primary" class="mt-8" :disabled="warpPlus.length < 26" :loading="loading"
+                @click="updateLicense">Update</a-button>
             </a-form-item>
           </a-form>
         </a-collapse-panel>
@@ -251,7 +243,9 @@ const hasConfig = computed(() => !ObjectUtil.isEmpty(warpConfig.value));
 
       <a-divider class="zero-margin">Account info</a-divider>
       <a-button class="my-8" :loading="loading" type="primary" @click="getConfig">
-        <template #icon><SyncOutlined /></template>
+        <template #icon>
+          <SyncOutlined />
+        </template>
         Refresh
       </a-button>
 
@@ -305,7 +299,9 @@ const hasConfig = computed(() => !ObjectUtil.isEmpty(warpConfig.value));
         <template v-else>
           <a-tag color="orange">Disabled</a-tag>
           <a-button type="primary" :loading="loading" class="ml-8" @click="addOutbound">
-            <template #icon><PlusOutlined /></template>
+            <template #icon>
+              <PlusOutlined />
+            </template>
             Add outbound
           </a-button>
         </template>
@@ -320,28 +316,46 @@ const hasConfig = computed(() => !ObjectUtil.isEmpty(warpConfig.value));
   width: 100%;
   border-collapse: collapse;
 }
+
 .warp-data-table td {
   padding: 4px 8px;
   word-break: break-all;
   font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
   font-size: 12px;
 }
+
 .warp-data-table td:first-child {
   font-family: inherit;
   font-weight: 500;
   white-space: nowrap;
   width: 130px;
 }
+
 .row-odd {
   background: rgba(0, 0, 0, 0.03);
 }
+
 :global(body.dark) .row-odd {
   background: rgba(255, 255, 255, 0.04);
 }
 
-.zero-margin { margin: 0; }
-.my-8 { margin: 8px 0; }
-.mt-8 { margin-top: 8px; }
-.my-10 { margin: 10px 0; }
-.ml-8 { margin-left: 8px; }
+.zero-margin {
+  margin: 0;
+}
+
+.my-8 {
+  margin: 8px 0;
+}
+
+.mt-8 {
+  margin-top: 8px;
+}
+
+.my-10 {
+  margin: 10px 0;
+}
+
+.ml-8 {
+  margin-left: 8px;
+}
 </style>

+ 51 - 82
frontend/src/pages/xray/XrayPage.vue

@@ -57,6 +57,15 @@ async function onTestOutbound(idx) {
   if (outbound) await testOutbound(idx, outbound);
 }
 
+function onDeleteOutbound(idx) {
+  templateSettings.value.outbounds.splice(idx, 1);
+  outboundTestStates.value = Object.fromEntries(
+    Object.entries(outboundTestStates.value)
+      .filter(([k]) => Number(k) !== idx)
+      .map(([k, v]) => [Number(k) > idx ? Number(k) - 1 : Number(k), v]),
+  );
+}
+
 // === Advanced tab — radio-driven view ==============================
 // Mirrors the legacy advanced page: a 4-way radio toggles which slice
 // of the xray config the textarea edits — the full config, just the
@@ -198,10 +207,7 @@ function confirmRestart() {
 
 <template>
   <a-config-provider :theme="antdThemeConfig">
-    <a-layout
-      class="xray-page"
-      :class="{ 'is-dark': themeState.isDark, 'is-ultra': themeState.isUltra }"
-    >
+    <a-layout class="xray-page" :class="{ 'is-dark': themeState.isDark, 'is-ultra': themeState.isUltra }">
       <AppSidebar :base-path="basePath" :request-uri="requestUri" />
 
       <a-layout class="content-shell">
@@ -209,12 +215,7 @@ function confirmRestart() {
           <a-spin :spinning="spinning || !fetched" :delay="200" tip="Loading…" size="large">
             <div v-if="!fetched" class="loading-spacer" />
 
-            <a-result
-              v-else-if="fetchError"
-              status="error"
-              :title="t('somethingWentWrong')"
-              :sub-title="fetchError"
-            >
+            <a-result v-else-if="fetchError" status="error" :title="t('somethingWentWrong')" :sub-title="fetchError">
               <template #extra>
                 <a-button type="primary" @click="fetchAll">{{ t('check') }}</a-button>
               </template>
@@ -245,11 +246,7 @@ function confirmRestart() {
                       </a-col>
                       <a-col :xs="24" :sm="10" class="header-info">
                         <a-back-top :target="scrollTarget" :visibility-height="200" />
-                        <a-alert
-                          type="warning"
-                          show-icon
-                          :message="t('pages.settings.infoDesc')"
-                        />
+                        <a-alert type="warning" show-icon :message="t('pages.settings.infoDesc')" />
                       </a-col>
                     </a-row>
                   </a-card>
@@ -262,55 +259,35 @@ function confirmRestart() {
                       <template #tab>
                         <SettingOutlined /> <span>{{ t('pages.xray.basicTemplate') }}</span>
                       </template>
-                      <BasicsTab
-                        :template-settings="templateSettings"
-                        :outbound-test-url="outboundTestUrl"
-                        :warp-exist="warpExist"
-                        :nord-exist="nordExist"
-                        @update:outbound-test-url="(v) => (outboundTestUrl = v)"
-                        @show-warp="showWarp"
-                        @show-nord="showNord"
-                        @reset-default="resetToDefault"
-                      />
+                      <BasicsTab :template-settings="templateSettings" :outbound-test-url="outboundTestUrl"
+                        :warp-exist="warpExist" :nord-exist="nordExist"
+                        @update:outbound-test-url="(v) => (outboundTestUrl = v)" @show-warp="showWarp"
+                        @show-nord="showNord" @reset-default="resetToDefault" />
                     </a-tab-pane>
 
                     <a-tab-pane key="tpl-routing" class="tab-pane">
                       <template #tab>
                         <SwapOutlined /> <span>{{ t('pages.xray.Routings') }}</span>
                       </template>
-                      <RoutingTab
-                        :template-settings="templateSettings"
-                        :inbound-tags="inboundTags"
-                        :client-reverse-tags="clientReverseTags"
-                        :is-mobile="isMobile"
-                      />
+                      <RoutingTab :template-settings="templateSettings" :inbound-tags="inboundTags"
+                        :client-reverse-tags="clientReverseTags" :is-mobile="isMobile" />
                     </a-tab-pane>
 
                     <a-tab-pane key="tpl-outbound" class="tab-pane">
                       <template #tab>
                         <UploadOutlined /> <span>{{ t('pages.xray.Outbounds') }}</span>
                       </template>
-                      <OutboundsTab
-                        :template-settings="templateSettings"
-                        :outbounds-traffic="outboundsTraffic"
-                        :outbound-test-states="outboundTestStates"
-                        :inbound-tags="inboundTags"
-                        :is-mobile="isMobile"
-                        @reset-traffic="resetOutboundsTraffic"
-                        @test="onTestOutbound"
-                        @show-warp="showWarp"
-                        @show-nord="showNord"
-                      />
+                      <OutboundsTab :template-settings="templateSettings" :outbounds-traffic="outboundsTraffic"
+                        :outbound-test-states="outboundTestStates" :inbound-tags="inboundTags" :is-mobile="isMobile"
+                        @reset-traffic="resetOutboundsTraffic" @test="onTestOutbound" @delete="onDeleteOutbound"
+                        @show-warp="showWarp" @show-nord="showNord" />
                     </a-tab-pane>
 
                     <a-tab-pane key="tpl-balancer" class="tab-pane">
                       <template #tab>
                         <ClusterOutlined /> <span>{{ t('pages.xray.Balancers') }}</span>
                       </template>
-                      <BalancersTab
-                        :template-settings="templateSettings"
-                        :client-reverse-tags="clientReverseTags"
-                      />
+                      <BalancersTab :template-settings="templateSettings" :client-reverse-tags="clientReverseTags" />
                     </a-tab-pane>
 
                     <a-tab-pane key="tpl-dns" class="tab-pane">
@@ -324,27 +301,16 @@ function confirmRestart() {
                       <template #tab>
                         <CodeOutlined /> <span>{{ t('pages.xray.advancedTemplate') }}</span>
                       </template>
-                      <a-list-item-meta
-                        :title="t('pages.xray.Template')"
-                        :description="t('pages.xray.TemplateDesc')"
-                      />
-                      <a-radio-group
-                        v-model:value="advSettings"
-                        button-style="solid"
-                        :size="isMobile ? 'small' : 'middle'"
-                        :style="{ margin: '12px 0' }"
-                      >
+                      <a-list-item-meta :title="t('pages.xray.Template')" :description="t('pages.xray.TemplateDesc')" />
+                      <a-radio-group v-model:value="advSettings" button-style="solid"
+                        :size="isMobile ? 'small' : 'middle'" :style="{ margin: '12px 0' }">
                         <a-radio-button value="xraySetting">{{ t('pages.xray.completeTemplate') }}</a-radio-button>
                         <a-radio-button value="inboundSettings">{{ t('pages.xray.Inbounds') }}</a-radio-button>
                         <a-radio-button value="outboundSettings">{{ t('pages.xray.Outbounds') }}</a-radio-button>
                         <a-radio-button value="routingRuleSettings">{{ t('pages.xray.Routings') }}</a-radio-button>
                       </a-radio-group>
-                      <a-textarea
-                        v-model:value="advancedText"
-                        :auto-size="{ minRows: 18, maxRows: 40 }"
-                        spellcheck="false"
-                        class="json-editor"
-                      />
+                      <a-textarea v-model:value="advancedText" :auto-size="{ minRows: 18, maxRows: 40 }"
+                        spellcheck="false" class="json-editor" />
                     </a-tab-pane>
                   </a-tabs>
                 </a-col>
@@ -354,21 +320,11 @@ function confirmRestart() {
         </a-layout-content>
       </a-layout>
 
-      <WarpModal
-        v-model:open="warpOpen"
-        :template-settings="templateSettings"
-        @add-outbound="onAddOutbound"
-        @reset-outbound="onResetOutbound"
-        @remove-outbound="onRemoveOutboundByTag"
-      />
-      <NordModal
-        v-model:open="nordOpen"
-        :template-settings="templateSettings"
-        @add-outbound="onAddOutbound"
-        @reset-outbound="onResetOutbound"
-        @remove-outbound="onRemoveOutboundByIndex"
-        @remove-routing-rules="onRemoveRoutingRules"
-      />
+      <WarpModal v-model:open="warpOpen" :template-settings="templateSettings" @add-outbound="onAddOutbound"
+        @reset-outbound="onResetOutbound" @remove-outbound="onRemoveOutboundByTag" />
+      <NordModal v-model:open="nordOpen" :template-settings="templateSettings" @add-outbound="onAddOutbound"
+        @reset-outbound="onResetOutbound" @remove-outbound="onRemoveOutboundByIndex"
+        @remove-routing-rules="onRemoveRoutingRules" />
     </a-layout>
   </a-config-provider>
 </template>
@@ -397,23 +353,36 @@ function confirmRestart() {
   background: transparent;
 }
 
-.content-shell { background: transparent; }
-.content-area { padding: 24px; }
+.content-shell {
+  background: transparent;
+}
+
+.content-area {
+  padding: 24px;
+}
 
-.loading-spacer { min-height: calc(100vh - 120px); }
+.loading-spacer {
+  min-height: calc(100vh - 120px);
+}
 
 .header-row {
   display: flex;
   flex-wrap: wrap;
   align-items: center;
 }
-.header-actions { padding: 4px; }
+
+.header-actions {
+  padding: 4px;
+}
+
 .header-info {
   display: flex;
   justify-content: flex-end;
 }
 
-.tab-pane { padding-top: 20px; }
+.tab-pane {
+  padding-top: 20px;
+}
 
 .restart-icon {
   font-size: 16px;

+ 0 - 25
web/controller/node.go

@@ -13,15 +13,10 @@ import (
 	"github.com/gin-gonic/gin"
 )
 
-// NodeController exposes CRUD + probe endpoints for managing remote
-// 3x-ui panels registered as nodes. All routes mount under
-// /panel/api/nodes/ via APIController.initRouter and inherit its
-// session-or-bearer auth from checkAPIAuth.
 type NodeController struct {
 	nodeService service.NodeService
 }
 
-// NewNodeController creates the controller and wires its routes onto g.
 func NewNodeController(g *gin.RouterGroup) *NodeController {
 	a := &NodeController{}
 	a.initRouter(g)
@@ -37,14 +32,8 @@ func (a *NodeController) initRouter(g *gin.RouterGroup) {
 	g.POST("/del/:id", a.del)
 	g.POST("/setEnable/:id", a.setEnable)
 
-	// /test takes a transient payload (no DB write) so the user can
-	// validate connectivity before saving the node.
 	g.POST("/test", a.test)
-	// /probe/:id triggers a synchronous probe of an already-saved node
-	// without waiting for the next 10s heartbeat tick.
 	g.POST("/probe/:id", a.probe)
-	// /history/:id/:metric/:bucket returns up to 60 averaged buckets of
-	// the per-node CPU or Mem time series collected by the heartbeat job.
 	g.GET("/history/:id/:metric/:bucket", a.history)
 }
 
@@ -115,8 +104,6 @@ func (a *NodeController) del(c *gin.Context) {
 	jsonMsg(c, I18nWeb(c, "pages.nodes.toasts.delete"), nil)
 }
 
-// setEnable accepts a JSON body { "enable": bool } so the toggle
-// switch can flip a node without sending the whole record back.
 func (a *NodeController) setEnable(c *gin.Context) {
 	id, err := strconv.Atoi(c.Param("id"))
 	if err != nil {
@@ -137,18 +124,12 @@ func (a *NodeController) setEnable(c *gin.Context) {
 	jsonMsg(c, I18nWeb(c, "pages.nodes.toasts.update"), nil)
 }
 
-// test runs Probe against a transient Node payload without writing to
-// the DB. Used by the form modal to validate connectivity before save.
 func (a *NodeController) test(c *gin.Context) {
 	n := &model.Node{}
 	if err := c.ShouldBind(n); err != nil {
 		jsonMsg(c, I18nWeb(c, "pages.nodes.toasts.test"), err)
 		return
 	}
-	// Reuse normalize-style defaults so the form can leave scheme/basePath
-	// blank and still get a sensible probe URL. We do this by round-tripping
-	// through Create's validator without the DB write — a tiny duplication
-	// here vs. exposing normalize publicly.
 	if n.Scheme == "" {
 		n.Scheme = "https"
 	}
@@ -162,9 +143,6 @@ func (a *NodeController) test(c *gin.Context) {
 	jsonObj(c, patch.ToUI(err == nil), nil)
 }
 
-// probe triggers a one-off probe against a saved node and persists
-// the result so the dashboard updates immediately, without waiting
-// for the next heartbeat tick.
 func (a *NodeController) probe(c *gin.Context) {
 	id, err := strconv.Atoi(c.Param("id"))
 	if err != nil {
@@ -188,9 +166,6 @@ func (a *NodeController) probe(c *gin.Context) {
 	jsonObj(c, patch.ToUI(probeErr == nil), nil)
 }
 
-// history returns averaged buckets of the per-node CPU/Mem time-series.
-// Mirrors the system-level /panel/api/server/history/:metric/:bucket
-// endpoint so the frontend can reuse the same fetch logic.
 func (a *NodeController) history(c *gin.Context) {
 	id, err := strconv.Atoi(c.Param("id"))
 	if err != nil {

+ 4 - 1
web/controller/xray_setting.go

@@ -104,7 +104,10 @@ func (a *XraySettingController) updateSetting(c *gin.Context) {
 	if outboundTestUrl == "" {
 		outboundTestUrl = "https://www.google.com/generate_204"
 	}
-	_ = a.SettingService.SetXrayOutboundTestUrl(outboundTestUrl)
+	if err := a.SettingService.SetXrayOutboundTestUrl(outboundTestUrl); err != nil {
+		jsonMsg(c, I18nWeb(c, "pages.settings.toasts.modifySettings"), err)
+		return
+	}
 	jsonMsg(c, I18nWeb(c, "pages.settings.toasts.modifySettings"), nil)
 }
 

+ 5 - 30
web/job/node_heartbeat_job.go

@@ -11,37 +11,22 @@ import (
 	"github.com/mhsanaei/3x-ui/v3/web/websocket"
 )
 
-// nodeHeartbeatConcurrency caps how many remote panels we probe at once.
-// Plenty of headroom for typical deployments (tens of nodes) without
-// letting a misconfigured run open thousands of sockets at once.
-const nodeHeartbeatConcurrency = 32
-
-// nodeHeartbeatRequestTimeout bounds a single probe. The cron is @every 10s,
-// so this needs to stay well under that to avoid run pile-up.
-const nodeHeartbeatRequestTimeout = 6 * time.Second
+const (
+	nodeHeartbeatConcurrency    = 32
+	nodeHeartbeatRequestTimeout = 4 * time.Second
+)
 
-// NodeHeartbeatJob probes every enabled remote node once per cron tick
-// and persists the result. Disabled nodes are skipped entirely so a
-// long-broken node can be parked without burning sockets every 10s.
 type NodeHeartbeatJob struct {
 	nodeService service.NodeService
-
-	// Coarse mutex prevents two ticks running concurrently if probes
-	// pile up under network failure. The next tick simply skips when
-	// the previous one is still draining.
-	running sync.Mutex
+	running     sync.Mutex
 }
 
-// NewNodeHeartbeatJob constructs a heartbeat job. The robfig/cron
-// scheduler will hand the same instance to every tick, so the
-// running mutex carries across runs as intended.
 func NewNodeHeartbeatJob() *NodeHeartbeatJob {
 	return &NodeHeartbeatJob{}
 }
 
 func (j *NodeHeartbeatJob) Run() {
 	if !j.running.TryLock() {
-		// Previous tick still in flight — skip this one.
 		return
 	}
 	defer j.running.Unlock()
@@ -71,10 +56,6 @@ func (j *NodeHeartbeatJob) Run() {
 	}
 	wg.Wait()
 
-	// Push the fresh list to any open Nodes page over WebSocket so the
-	// status / latency / cpu / mem cells update without the user clicking
-	// refresh. Skip the DB read entirely when no browser is connected —
-	// matches the gating pattern in xray_traffic_job.
 	if !websocket.HasClients() {
 		return
 	}
@@ -86,10 +67,6 @@ func (j *NodeHeartbeatJob) Run() {
 	websocket.BroadcastNodes(updated)
 }
 
-// probeOne runs a single probe and persists the result. We deliberately
-// don't return errors — partial failures across the node set should not
-// abort other probes, and the LastError column carries the message for
-// the UI to surface.
 func (j *NodeHeartbeatJob) probeOne(n *model.Node) {
 	ctx, cancel := context.WithTimeout(context.Background(), nodeHeartbeatRequestTimeout)
 	defer cancel()
@@ -100,8 +77,6 @@ func (j *NodeHeartbeatJob) probeOne(n *model.Node) {
 		patch.Status = "online"
 	}
 	if updErr := j.nodeService.UpdateHeartbeat(n.Id, patch); updErr != nil {
-		// A row deleted mid-tick produces "rows affected = 0", which
-		// gorm reports as nil — so any error we get here is real.
 		logger.Warning("node heartbeat: update node", n.Id, "failed:", updErr)
 	}
 }

+ 114 - 57
web/job/node_traffic_sync_job.go

@@ -12,41 +12,67 @@ import (
 	"github.com/mhsanaei/3x-ui/v3/web/websocket"
 )
 
-// nodeTrafficSyncConcurrency caps how many nodes we sync simultaneously.
-// Each sync does three HTTP calls in series, so the wall-clock budget
-// per node is the request timeout below — keeping the cap modest avoids
-// flooding the network while still getting through dozens of nodes
-// inside a 10s tick.
-const nodeTrafficSyncConcurrency = 8
-
-// nodeTrafficSyncRequestTimeout bounds the per-node sync. Three probes
-// in series at 8s each would blow past the cron interval, so the budget
-// here covers the whole snapshot — FetchTrafficSnapshot internally caps
-// each HTTP call at the runtime's own 10s ceiling but uses ctx for the
-// outer total.
-const nodeTrafficSyncRequestTimeout = 8 * time.Second
-
-// NodeTrafficSyncJob pulls absolute traffic + online stats from every
-// enabled, currently-online remote node and merges them into the central
-// DB. Mirrors NodeHeartbeatJob's structure: TryLock to skip pile-ups,
-// errgroup-style fan-out with a concurrency cap, per-node ctx timeout.
-//
-// Offline nodes are skipped entirely — the heartbeat job already owns
-// status tracking, and we'd just waste sockets retrying a node we know
-// is unreachable. As soon as heartbeat marks a node online again, the
-// next traffic tick picks it up.
+const (
+	nodeTrafficSyncConcurrency    = 8
+	nodeTrafficSyncRequestTimeout = 4 * time.Second
+)
+
 type NodeTrafficSyncJob struct {
 	nodeService    service.NodeService
 	inboundService service.InboundService
+	running        sync.Mutex
+	structural     atomicBool
+}
+
+type atomicBool struct {
+	mu sync.Mutex
+	v  bool
+}
+
+func (a *atomicBool) set() {
+	a.mu.Lock()
+	a.v = true
+	a.mu.Unlock()
+}
+
+func (a *atomicBool) takeAndReset() bool {
+	a.mu.Lock()
+	v := a.v
+	a.v = false
+	a.mu.Unlock()
+	return v
+}
+
+type emailSet struct {
+	mu sync.Mutex
+	m  map[string]struct{}
+}
+
+func newEmailSet() *emailSet { return &emailSet{m: make(map[string]struct{})} }
+
+func (s *emailSet) addAll(emails []string) {
+	if len(emails) == 0 {
+		return
+	}
+	s.mu.Lock()
+	for _, e := range emails {
+		if e != "" {
+			s.m[e] = struct{}{}
+		}
+	}
+	s.mu.Unlock()
+}
 
-	// Coarse mutex prevents two ticks running concurrently if a single
-	// sync stalls past the 10s cron interval (rare but possible when
-	// many nodes are slow simultaneously).
-	running sync.Mutex
+func (s *emailSet) slice() []string {
+	s.mu.Lock()
+	defer s.mu.Unlock()
+	out := make([]string, 0, len(s.m))
+	for e := range s.m {
+		out = append(out, e)
+	}
+	return out
 }
 
-// NewNodeTrafficSyncJob builds a singleton sync job. Cron hands the same
-// instance to every tick so the running mutex is preserved across runs.
 func NewNodeTrafficSyncJob() *NodeTrafficSyncJob {
 	return &NodeTrafficSyncJob{}
 }
@@ -59,8 +85,6 @@ func (j *NodeTrafficSyncJob) Run() {
 
 	mgr := runtime.GetManager()
 	if mgr == nil {
-		// Server still booting — pre-Manager runs are normal during
-		// the first few seconds of startup.
 		return
 	}
 
@@ -73,6 +97,7 @@ func (j *NodeTrafficSyncJob) Run() {
 		return
 	}
 
+	touched := newEmailSet()
 	sem := make(chan struct{}, nodeTrafficSyncConcurrency)
 	var wg sync.WaitGroup
 	for _, n := range nodes {
@@ -84,37 +109,54 @@ func (j *NodeTrafficSyncJob) Run() {
 		go func(n *model.Node) {
 			defer wg.Done()
 			defer func() { <-sem }()
-			j.syncOne(mgr, n)
+			j.syncOne(mgr, n, touched)
 		}(n)
 	}
 	wg.Wait()
 
-	// One broadcast per tick, batched across all nodes — frontend code
-	// is invariant to whether the rows came from local xray or a node,
-	// so we reuse the same WebSocket envelope XrayTrafficJob uses.
-	if websocket.HasClients() {
-		online := j.inboundService.GetOnlineClients()
-		if online == nil {
-			online = []string{}
-		}
-		lastOnline, err := j.inboundService.GetClientsLastOnline()
-		if err != nil {
-			logger.Warning("node traffic sync: get last-online failed:", err)
-		}
-		if lastOnline == nil {
-			lastOnline = map[string]int64{}
+	if !websocket.HasClients() {
+		return
+	}
+
+	online := j.inboundService.GetOnlineClients()
+	if online == nil {
+		online = []string{}
+	}
+	lastOnline, err := j.inboundService.GetClientsLastOnline()
+	if err != nil {
+		logger.Warning("node traffic sync: get last-online failed:", err)
+	}
+	if lastOnline == nil {
+		lastOnline = map[string]int64{}
+	}
+	websocket.BroadcastTraffic(map[string]any{
+		"onlineClients": online,
+		"lastOnlineMap": lastOnline,
+	})
+
+	clientStats := map[string]any{}
+	if emails := touched.slice(); len(emails) > 0 {
+		if stats, err := j.inboundService.GetActiveClientTraffics(emails); err != nil {
+			logger.Warning("node traffic sync: get client traffics for websocket failed:", err)
+		} else if len(stats) > 0 {
+			clientStats["clients"] = stats
 		}
-		websocket.BroadcastTraffic(map[string]any{
-			"onlineClients": online,
-			"lastOnlineMap": lastOnline,
-		})
+	}
+	if summary, err := j.inboundService.GetInboundsTrafficSummary(); err != nil {
+		logger.Warning("node traffic sync: get inbounds summary for websocket failed:", err)
+	} else if len(summary) > 0 {
+		clientStats["inbounds"] = summary
+	}
+	if len(clientStats) > 0 {
+		websocket.BroadcastClientStats(clientStats)
+	}
+
+	if j.structural.takeAndReset() {
+		websocket.BroadcastInvalidate(websocket.MessageTypeInbounds)
 	}
 }
 
-// syncOne fetches and merges one node's snapshot. Errors are logged
-// per-node and don't propagate; one slow node shouldn't keep the rest
-// from running.
-func (j *NodeTrafficSyncJob) syncOne(mgr *runtime.Manager, n *model.Node) {
+func (j *NodeTrafficSyncJob) syncOne(mgr *runtime.Manager, n *model.Node, touched *emailSet) {
 	ctx, cancel := context.WithTimeout(context.Background(), nodeTrafficSyncRequestTimeout)
 	defer cancel()
 
@@ -126,12 +168,27 @@ func (j *NodeTrafficSyncJob) syncOne(mgr *runtime.Manager, n *model.Node) {
 	snap, err := rt.FetchTrafficSnapshot(ctx)
 	if err != nil {
 		logger.Warning("node traffic sync: fetch from", n.Name, "failed:", err)
-		// Drop node-online contribution so a hiccup doesn't leave the
-		// online filter showing stale clients indefinitely.
 		j.inboundService.ClearNodeOnlineClients(n.Id)
 		return
 	}
-	if err := j.inboundService.SetRemoteTraffic(n.Id, snap); err != nil {
+	changed, err := j.inboundService.SetRemoteTraffic(n.Id, snap)
+	if err != nil {
 		logger.Warning("node traffic sync: merge for", n.Name, "failed:", err)
+		return
+	}
+	if changed {
+		j.structural.set()
+	}
+	for _, ib := range snap.Inbounds {
+		if ib == nil {
+			continue
+		}
+		emails := make([]string, 0, len(ib.ClientStats))
+		for _, cs := range ib.ClientStats {
+			if cs.Email != "" {
+				emails = append(emails, cs.Email)
+			}
+		}
+		touched.addAll(emails)
 	}
 }

+ 1 - 0
web/job/xray_traffic_job.go

@@ -54,6 +54,7 @@ func (j *XrayTrafficJob) Run() {
 				j.xrayService.SetToNeedRestart()
 			}
 		}
+		websocket.BroadcastInvalidate(websocket.MessageTypeInbounds)
 	}
 	if ExternalTrafficInformEnable, err := j.settingService.GetExternalTrafficInformEnable(); ExternalTrafficInformEnable {
 		j.informTrafficToExternalAPI(traffics, clientTraffics)

+ 3 - 42
web/runtime/local.go

@@ -10,45 +10,22 @@ import (
 	"github.com/mhsanaei/3x-ui/v3/xray"
 )
 
-// LocalDeps wires the runtime to the panel's xray process and the
-// service.XrayService restart trigger via callbacks. We use callbacks
-// (not an interface to *service.XrayService) because the runtime
-// package would otherwise cycle-import service.
 type LocalDeps struct {
-	// APIPort returns the xray gRPC API port the local engine is
-	// currently listening on. Returns 0 when xray isn't running yet —
-	// callers should treat that as a transient error.
-	APIPort func() int
-	// SetNeedRestart trips the panel's "restart xray on next cron tick"
-	// flag. Mirrors how InboundController.addInbound calls
-	// xrayService.SetToNeedRestart() today.
+	APIPort        func() int
 	SetNeedRestart func()
 }
 
-// Local implements Runtime against the panel's own xray process. Each
-// call follows the existing inbound.go pattern: open a gRPC client,
-// run one operation, close. Per-call init keeps the connection state
-// scoped so a stuck call can't leak across operations.
 type Local struct {
 	deps LocalDeps
-
-	// Serialise gRPC operations — xray's HandlerService isn't documented
-	// as concurrent-safe and the existing InboundService implicitly
-	// runs one op at a time per request. This matches that.
-	mu sync.Mutex
+	mu   sync.Mutex
 }
 
-// NewLocal builds a Local runtime. deps.APIPort and deps.SetNeedRestart
-// are required; callers that want a no-op restart can pass `func(){}`.
 func NewLocal(deps LocalDeps) *Local {
 	return &Local{deps: deps}
 }
 
 func (l *Local) Name() string { return "local" }
 
-// withAPI runs fn against a freshly-initialised XrayAPI client and
-// guarantees Close() afterwards. Returns an error if the gRPC port
-// isn't available yet (xray still starting / stopped).
 func (l *Local) withAPI(fn func(api *xray.XrayAPI) error) error {
 	l.mu.Lock()
 	defer l.mu.Unlock()
@@ -82,17 +59,8 @@ func (l *Local) DelInbound(_ context.Context, ib *model.Inbound) error {
 }
 
 func (l *Local) UpdateInbound(ctx context.Context, oldIb, newIb *model.Inbound) error {
-	// xray-core has no in-place inbound update — drop and re-add.
-	// Matches what InboundService.UpdateInbound did inline.
-	if err := l.DelInbound(ctx, oldIb); err != nil {
-		// Best-effort: continue to AddInbound so a transient remove
-		// failure (e.g. inbound already gone) doesn't strand us. The
-		// caller's needRestart fallback will reconcile from config.
-		_ = err
-	}
+	_ = l.DelInbound(ctx, oldIb)
 	if !newIb.Enable {
-		// Disabled inbounds aren't pushed to xray; we already removed
-		// the old one above.
 		return nil
 	}
 	return l.AddInbound(ctx, newIb)
@@ -117,13 +85,6 @@ func (l *Local) RestartXray(_ context.Context) error {
 	return nil
 }
 
-// Reset methods are intentional no-ops for Local. The central DB UPDATE
-// that runs in InboundService.Reset* before this call has already zeroed
-// the counters that xray reads; on the next stats poll the gRPC service
-// will pick up matching values. Pre-Phase-1 the panel never issued an
-// xrayApi reset call here either — keeping the same shape avoids a
-// behaviour change for single-panel users.
-
 func (l *Local) ResetClientTraffic(_ context.Context, _ *model.Inbound, _ string) error {
 	return nil
 }

+ 0 - 39
web/runtime/manager.go

@@ -8,14 +8,6 @@ import (
 	"github.com/mhsanaei/3x-ui/v3/database/model"
 )
 
-// Manager is the entry point for service code that needs a Runtime.
-// One singleton lives in the package-level `manager` var, set at
-// server bootstrap (web.go calls SetManager once). InboundService and
-// friends read it via GetManager().
-//
-// Local runs forever; Remotes are built lazily per nodeID and cached.
-// Cache invalidation runs on node Update/Delete (NodeService hooks
-// InvalidateNode) so a token rotation surfaces the next call.
 type Manager struct {
 	local Runtime
 
@@ -23,9 +15,6 @@ type Manager struct {
 	remotes map[int]*Remote
 }
 
-// NewManager wires the singleton with the deps Local needs. The runtime
-// package can't import service so the caller (web.go) supplies the
-// callbacks that bridge into XrayService.
 func NewManager(localDeps LocalDeps) *Manager {
 	return &Manager{
 		local:   NewLocal(localDeps),
@@ -33,10 +22,6 @@ func NewManager(localDeps LocalDeps) *Manager {
 	}
 }
 
-// RuntimeFor picks the right adapter for an inbound based on NodeID.
-// Returns local when nodeID is nil; otherwise looks up the node row
-// (or returns the cached Remote for it). The caller does not need to
-// know which kind they got — that's the point of the abstraction.
 func (m *Manager) RuntimeFor(nodeID *int) (Runtime, error) {
 	if nodeID == nil {
 		return m.local, nil
@@ -48,8 +33,6 @@ func (m *Manager) RuntimeFor(nodeID *int) (Runtime, error) {
 	}
 	m.mu.RUnlock()
 
-	// Cache miss — load the node row and build a Remote. We re-check
-	// under the write lock to avoid duplicate construction under load.
 	m.mu.Lock()
 	defer m.mu.Unlock()
 	if rt, ok := m.remotes[*nodeID]; ok {
@@ -67,16 +50,8 @@ func (m *Manager) RuntimeFor(nodeID *int) (Runtime, error) {
 	return rt, nil
 }
 
-// Local returns the singleton local runtime. Used by code that needs
-// to operate on the panel's own xray regardless of which inbound it
-// came from (e.g. on-demand restart from the UI).
 func (m *Manager) Local() Runtime { return m.local }
 
-// RemoteFor returns the Remote adapter for an already-loaded node row.
-// Differs from RuntimeFor in two ways: it skips the DB lookup (caller
-// hands in the node), and it returns the concrete *Remote so callers
-// like NodeTrafficSyncJob can reach FetchTrafficSnapshot, which the
-// Runtime interface doesn't expose.
 func (m *Manager) RemoteFor(node *model.Node) (*Remote, error) {
 	if node == nil {
 		return nil, errors.New("node is nil")
@@ -98,18 +73,12 @@ func (m *Manager) RemoteFor(node *model.Node) (*Remote, error) {
 	return rt, nil
 }
 
-// InvalidateNode drops the cached Remote for nodeID so the next
-// RuntimeFor call rebuilds it from the (possibly updated) node row.
-// Called from NodeService.Update / Delete.
 func (m *Manager) InvalidateNode(nodeID int) {
 	m.mu.Lock()
 	defer m.mu.Unlock()
 	delete(m.remotes, nodeID)
 }
 
-// loadNode reads a node row directly from the DB. Kept package-local
-// to avoid pulling NodeService into the runtime — service depends on
-// runtime, not the other way around.
 func loadNode(id int) (*model.Node, error) {
 	db := database.GetDB()
 	n := &model.Node{}
@@ -119,25 +88,17 @@ func loadNode(id int) (*model.Node, error) {
 	return n, nil
 }
 
-// Singleton wiring -------------------------------------------------------
-
 var (
 	managerMu sync.RWMutex
 	manager   *Manager
 )
 
-// SetManager installs the process-wide Manager. web.go calls this once
-// during NewServer. Tests can call it again with a stub.
 func SetManager(m *Manager) {
 	managerMu.Lock()
 	defer managerMu.Unlock()
 	manager = m
 }
 
-// GetManager returns the installed Manager, or nil before SetManager
-// has run. Callers should treat nil as "still booting" — the existing
-// behaviour for code paths that only run on the local engine continues
-// to work via a pre-wired fallback set up in init() below.
 func GetManager() *Manager {
 	managerMu.RLock()
 	defer managerMu.RUnlock()

+ 3 - 89
web/runtime/remote.go

@@ -18,13 +18,8 @@ import (
 	"github.com/mhsanaei/3x-ui/v3/logger"
 )
 
-// remoteHTTPTimeout bounds a single remote API call. Generous enough for
-// a slow node under load, short enough that a wedged remote doesn't
-// block the central panel's UI thread for the user.
 const remoteHTTPTimeout = 10 * time.Second
 
-// remoteHTTPClient is shared so repeated calls to the same node reuse
-// connections. Per-request timeouts are set via context.
 var remoteHTTPClient = &http.Client{
 	Transport: &http.Transport{
 		MaxIdleConns:        64,
@@ -33,22 +28,12 @@ var remoteHTTPClient = &http.Client{
 	},
 }
 
-// envelope mirrors entity.Msg without depending on the entity package
-// (avoids a cycle on the controller side that pulls in this runtime).
 type envelope struct {
 	Success bool            `json:"success"`
 	Msg     string          `json:"msg"`
 	Obj     json.RawMessage `json:"obj"`
 }
 
-// Remote implements Runtime by calling the existing /panel/api/inbounds/*
-// endpoints on a remote 3x-ui panel. The remote is authenticated as
-// the central panel via its per-node Bearer token.
-//
-// remoteIDByTag caches the {tag → remote inbound id} mapping so the
-// hot path (update/delete/addClient) avoids /list lookups. The cache
-// is in-memory and rebuilt lazily on first miss after a process restart
-// or InvalidateNode call.
 type Remote struct {
 	node *model.Node
 
@@ -56,10 +41,6 @@ type Remote struct {
 	remoteIDByTag map[string]int
 }
 
-// NewRemote constructs a Remote runtime for one node. The node pointer
-// is cached; callers that mutate node config (via NodeService.Update)
-// must drop the runtime through Manager.InvalidateNode so a fresh one
-// picks up the new fields.
 func NewRemote(n *model.Node) *Remote {
 	return &Remote{
 		node:          n,
@@ -69,8 +50,6 @@ func NewRemote(n *model.Node) *Remote {
 
 func (r *Remote) Name() string { return "node:" + r.node.Name }
 
-// baseURL composes the panel root for r.node, e.g. https://1.2.3.4:2053/
-// Always ends in '/' so callers can append "panel/api/...".
 func (r *Remote) baseURL() string {
 	bp := r.node.BasePath
 	if bp == "" {
@@ -82,13 +61,6 @@ func (r *Remote) baseURL() string {
 	return fmt.Sprintf("%s://%s:%d%s", r.node.Scheme, r.node.Address, r.node.Port, bp)
 }
 
-// do issues an HTTP request against the remote panel and decodes the
-// entity.Msg envelope. Returns an error for transport failures, non-2xx
-// responses, or {success:false} bodies.
-//
-// body may be nil. For application/x-www-form-urlencoded calls (the
-// existing controllers bind via c.ShouldBind which prefers form-encoded)
-// pass url.Values; for JSON pass any other type and we'll marshal it.
 func (r *Remote) do(ctx context.Context, method, path string, body any) (*envelope, error) {
 	if r.node.ApiToken == "" {
 		return nil, errors.New("node has no API token configured")
@@ -102,7 +74,6 @@ func (r *Remote) do(ctx context.Context, method, path string, body any) (*envelo
 	)
 	switch b := body.(type) {
 	case nil:
-		// nothing
 	case url.Values:
 		reqBody = strings.NewReader(b.Encode())
 		contentType = "application/x-www-form-urlencoded"
@@ -151,10 +122,6 @@ func (r *Remote) do(ctx context.Context, method, path string, body any) (*envelo
 	return &env, nil
 }
 
-// resolveRemoteID returns the remote panel's local inbound ID for the
-// given tag. Cache-backed; on miss it hits /panel/api/inbounds/list and
-// repopulates the whole map (one-shot list is cheaper than per-tag
-// lookups when several inbounds need resolving in sequence).
 func (r *Remote) resolveRemoteID(ctx context.Context, tag string) (int, error) {
 	if id, ok := r.cacheGet(tag); ok {
 		return id, nil
@@ -187,9 +154,6 @@ func (r *Remote) cacheDel(tag string) {
 	delete(r.remoteIDByTag, tag)
 }
 
-// refreshRemoteIDs replaces the in-memory tag→id map with whatever the
-// node currently has. Called on cache miss; also a useful recovery path
-// when the remote panel is rebuilt or we get a "not found" on update.
 func (r *Remote) refreshRemoteIDs(ctx context.Context) error {
 	env, err := r.do(ctx, http.MethodGet, "panel/api/inbounds/list", nil)
 	if err != nil {
@@ -216,17 +180,11 @@ func (r *Remote) refreshRemoteIDs(ctx context.Context) error {
 }
 
 func (r *Remote) AddInbound(ctx context.Context, ib *model.Inbound) error {
-	// Strip NodeID from the wire payload so the remote stores a "local"
-	// row from its own perspective. We also ship the full model.Inbound
-	// minus runtime metadata. Tag is preserved so central + remote agree
-	// on the identifier — relies on InboundController being patched to
-	// not overwrite a non-empty Tag.
 	payload := wireInbound(ib)
 	env, err := r.do(ctx, http.MethodPost, "panel/api/inbounds/add", payload)
 	if err != nil {
 		return err
 	}
-	// Response body contains the saved inbound (with the remote's Id).
 	var created struct {
 		Id  int    `json:"id"`
 		Tag string `json:"tag"`
@@ -242,9 +200,7 @@ func (r *Remote) AddInbound(ctx context.Context, ib *model.Inbound) error {
 func (r *Remote) DelInbound(ctx context.Context, ib *model.Inbound) error {
 	id, err := r.resolveRemoteID(ctx, ib.Tag)
 	if err != nil {
-		// Already gone on remote — treat as success so a sync after a
-		// remote panel reset doesn't strand the central panel.
-		logger.Warning("remote DelInbound: tag", ib.Tag, "not found on", r.node.Name, "— treating as success")
+		logger.Warning("remote DelInbound: tag", ib.Tag, "not found on", r.node.Name)
 		return nil
 	}
 	if _, err := r.do(ctx, http.MethodPost, "panel/api/inbounds/del/"+strconv.Itoa(id), nil); err != nil {
@@ -255,21 +211,14 @@ func (r *Remote) DelInbound(ctx context.Context, ib *model.Inbound) error {
 }
 
 func (r *Remote) UpdateInbound(ctx context.Context, oldIb, newIb *model.Inbound) error {
-	// The remote's old row is keyed by oldIb.Tag (tags can change on
-	// edit if listen/port changed). We update by remote-id so the row
-	// keeps its identity even when its tag flips.
 	id, err := r.resolveRemoteID(ctx, oldIb.Tag)
 	if err != nil {
-		// Remote lost the row — fall back to add. This can happen if
-		// the node panel was reset; we'd rather end up with the inbound
-		// existing than fail the user's update.
 		return r.AddInbound(ctx, newIb)
 	}
 	payload := wireInbound(newIb)
 	if _, err := r.do(ctx, http.MethodPost, "panel/api/inbounds/update/"+strconv.Itoa(id), payload); err != nil {
 		return err
 	}
-	// Tag may have changed — remap the cache.
 	if oldIb.Tag != newIb.Tag {
 		r.cacheDel(oldIb.Tag)
 	}
@@ -277,18 +226,6 @@ func (r *Remote) UpdateInbound(ctx context.Context, oldIb, newIb *model.Inbound)
 	return nil
 }
 
-// AddUser pushes a single client into the remote inbound's settings JSON.
-// We can't reuse the central panel's xrayApi.AddUser shape directly
-// because the remote's HTTP endpoint expects {id, settings} where
-// settings is a JSON string with a "clients":[...] array. The central
-// panel's InboundService has already updated its own settings JSON
-// before calling us, so we just ship the new full settings to the
-// remote via /update — simpler than reconstructing the partial AddUser
-// payload remote-side.
-//
-// Caller passes the full updated *model.Inbound on the same code path
-// AddUser is called from in InboundService. To avoid changing the
-// Runtime interface for that, AddUser/RemoveUser delegate to UpdateInbound.
 func (r *Remote) AddUser(ctx context.Context, ib *model.Inbound, _ map[string]any) error {
 	return r.UpdateInbound(ctx, ib, ib)
 }
@@ -305,8 +242,7 @@ func (r *Remote) RestartXray(ctx context.Context) error {
 func (r *Remote) ResetClientTraffic(ctx context.Context, ib *model.Inbound, email string) error {
 	id, err := r.resolveRemoteID(ctx, ib.Tag)
 	if err != nil {
-		// Already gone on remote — central reset is enough.
-		logger.Warning("remote ResetClientTraffic: tag", ib.Tag, "not found on", r.node.Name, "— treating as success")
+		logger.Warning("remote ResetClientTraffic: tag", ib.Tag, "not found on", r.node.Name)
 		return nil
 	}
 	_, err = r.do(ctx, http.MethodPost,
@@ -318,7 +254,7 @@ func (r *Remote) ResetClientTraffic(ctx context.Context, ib *model.Inbound, emai
 func (r *Remote) ResetInboundClientTraffics(ctx context.Context, ib *model.Inbound) error {
 	id, err := r.resolveRemoteID(ctx, ib.Tag)
 	if err != nil {
-		logger.Warning("remote ResetInboundClientTraffics: tag", ib.Tag, "not found on", r.node.Name, "— treating as success")
+		logger.Warning("remote ResetInboundClientTraffics: tag", ib.Tag, "not found on", r.node.Name)
 		return nil
 	}
 	_, err = r.do(ctx, http.MethodPost,
@@ -331,22 +267,12 @@ func (r *Remote) ResetAllTraffics(ctx context.Context) error {
 	return err
 }
 
-// TrafficSnapshot is what NodeTrafficSyncJob pulls from a remote node
-// every cron tick. Inbounds carry absolute up/down/all_time + ClientStats
-// (the same shape /panel/api/inbounds/list returns); the two map fields
-// come from the dedicated /onlines and /lastOnline endpoints.
 type TrafficSnapshot struct {
 	Inbounds      []*model.Inbound
 	OnlineEmails  []string
 	LastOnlineMap map[string]int64
 }
 
-// FetchTrafficSnapshot pulls the three pieces in series. Sequential is
-// fine because the cron job already fans out across nodes — adding
-// per-node parallelism on top would just thrash the remote.
-//
-// Not on the Runtime interface: only the sync job needs it, and Local
-// has no equivalent (XrayTrafficJob already covers the local engine).
 func (r *Remote) FetchTrafficSnapshot(ctx context.Context) (*TrafficSnapshot, error) {
 	snap := &TrafficSnapshot{LastOnlineMap: map[string]int64{}}
 
@@ -360,9 +286,6 @@ func (r *Remote) FetchTrafficSnapshot(ctx context.Context) (*TrafficSnapshot, er
 
 	envOnlines, err := r.do(ctx, http.MethodPost, "panel/api/inbounds/onlines", nil)
 	if err != nil {
-		// Onlines/lastOnline are nice-to-have. A failure here shouldn't
-		// invalidate the inbound counter merge — log and continue with
-		// empty values, the next tick may succeed.
 		logger.Warning("remote", r.node.Name, "onlines fetch failed:", err)
 	} else if len(envOnlines.Obj) > 0 {
 		_ = json.Unmarshal(envOnlines.Obj, &snap.OnlineEmails)
@@ -378,17 +301,8 @@ func (r *Remote) FetchTrafficSnapshot(ctx context.Context) (*TrafficSnapshot, er
 	return snap, nil
 }
 
-// wireInbound builds the request body for /panel/api/inbounds/add and
-// /update. Mirrors the form fields the existing InboundController
-// expects via c.ShouldBind — we use form-encoded to match exactly.
-//
-// We deliberately omit Id (remote assigns its own), UserId (remote's
-// fallback user takes over), NodeID (the remote sees itself as local),
-// and ClientStats (those are joined-table data the remote rebuilds).
 func wireInbound(ib *model.Inbound) url.Values {
 	v := url.Values{}
-	v.Set("up", strconv.FormatInt(ib.Up, 10))
-	v.Set("down", strconv.FormatInt(ib.Down, 10))
 	v.Set("total", strconv.FormatInt(ib.Total, 10))
 	v.Set("remark", ib.Remark)
 	v.Set("enable", strconv.FormatBool(ib.Enable))

+ 0 - 42
web/runtime/runtime.go

@@ -1,12 +1,3 @@
-// Package runtime abstracts the live xray engine that an inbound's
-// configuration is shipped to. Two implementations exist: Local talks
-// to the panel's own xray via gRPC (the original behaviour); Remote
-// talks to another 3x-ui panel's HTTP API as a managed Node.
-//
-// InboundService picks a Runtime per-inbound based on Inbound.NodeID.
-// The point of the abstraction is to keep `if node != nil` checks out
-// of the service code as Phase 2/3 features (traffic sync, subscription
-// per-node) build on top.
 package runtime
 
 import (
@@ -15,52 +6,19 @@ import (
 	"github.com/mhsanaei/3x-ui/v3/database/model"
 )
 
-// Runtime is the live-engine adapter for one inbound's worth of
-// operations. Implementations must be safe for concurrent use — the
-// service layer does not synchronise calls.
 type Runtime interface {
-	// Name identifies the adapter in logs ("local", "node:<name>").
 	Name() string
 
-	// AddInbound deploys an inbound to the engine. The Tag field on ib
-	// is treated as the source of truth for identifying the inbound on
-	// the remote side; Local ignores it.
 	AddInbound(ctx context.Context, ib *model.Inbound) error
-
-	// DelInbound removes the inbound identified by ib.Tag.
 	DelInbound(ctx context.Context, ib *model.Inbound) error
-
-	// UpdateInbound replaces the existing inbound with newIb. oldIb
-	// carries the previous config so the adapter can compute a minimal
-	// diff (Local: drop+add by tag; Remote: HTTP update by remote-id).
 	UpdateInbound(ctx context.Context, oldIb, newIb *model.Inbound) error
 
-	// AddUser hot-adds a client to the inbound identified by ib.Tag.
-	// userMap matches the shape that xray.XrayAPI.AddUser already takes
-	// — keys: email, id, password, auth, security, flow, cipher.
 	AddUser(ctx context.Context, ib *model.Inbound, userMap map[string]any) error
-
-	// RemoveUser hot-removes the client by email from ib's inbound.
 	RemoveUser(ctx context.Context, ib *model.Inbound, email string) error
 
-	// RestartXray asks the engine to fully restart. For Local this just
-	// flips the SetToNeedRestart flag and lets the cron pick it up; for
-	// Remote it issues an HTTP POST to /panel/api/server/restartXrayService.
 	RestartXray(ctx context.Context) error
 
-	// ResetClientTraffic zeros the up/down counters for one client on the
-	// engine. Local: no-op — the central DB UPDATE that runs before this
-	// call is sufficient, and xray's gRPC stats counter resets on the next
-	// poll. Remote: HTTP POST so the next traffic sync doesn't pull the
-	// pre-reset absolute back from the node.
 	ResetClientTraffic(ctx context.Context, ib *model.Inbound, email string) error
-
-	// ResetInboundClientTraffics zeros every client of one inbound. Same
-	// Local/Remote split as ResetClientTraffic.
 	ResetInboundClientTraffics(ctx context.Context, ib *model.Inbound) error
-
-	// ResetAllTraffics zeros every inbound counter on the engine. Used by
-	// the panel-wide "reset all traffic" action; called once per affected
-	// node so that nodes with no inbounds for the current panel are skipped.
 	ResetAllTraffics(ctx context.Context) error
 }

+ 266 - 213
web/service/inbound.go

@@ -23,25 +23,10 @@ import (
 	"gorm.io/gorm/clause"
 )
 
-// InboundService provides business logic for managing Xray inbound configurations.
-// It handles CRUD operations for inbounds, client management, traffic monitoring,
-// and integration with the Xray API for real-time updates.
 type InboundService struct {
-	// xrayApi is retained for backwards compatibility with bulk paths
-	// that still talk to the local engine directly (e.g. traffic-reset
-	// jobs that scope to NodeID IS NULL inbounds anyway). New code paths
-	// route through runtimeFor() instead so they can target remote nodes.
 	xrayApi xray.XrayAPI
 }
 
-// runtimeFor returns the Runtime adapter for an inbound's destination
-// engine. Returns the local runtime when the inbound has no NodeID
-// (legacy/local inbounds); otherwise the cached Remote for that node.
-//
-// nil is returned only when the runtime Manager hasn't been wired yet
-// (extremely early bootstrap). Callers treat nil as a transient error
-// and either fall back to needRestart=true or surface "panel still
-// starting" upstream.
 func (s *InboundService) runtimeFor(ib *model.Inbound) (runtime.Runtime, error) {
 	mgr := runtime.GetManager()
 	if mgr == nil {
@@ -399,10 +384,6 @@ func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, boo
 	if inbound.Enable {
 		rt, rterr := s.runtimeFor(inbound)
 		if rterr != nil {
-			// Fail-fast on remote routing errors. Assign to the named
-			// `err` so the deferred tx handler rolls back the central
-			// DB row that tx.Save just inserted — otherwise we'd leave
-			// an orphan that the user sees succeed despite the toast.
 			err = rterr
 			return inbound, false, err
 		}
@@ -411,12 +392,9 @@ func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, boo
 		} else {
 			logger.Debug("Unable to add inbound on", rt.Name(), ":", err1)
 			if inbound.NodeID != nil {
-				// Remote add failed — roll back so central + node stay
-				// in sync (no row on either side).
 				err = err1
 				return inbound, false, err
 			}
-			// Local: keep the existing fall-through-to-restart behaviour.
 			needRestart = true
 		}
 	}
@@ -424,25 +402,13 @@ func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, boo
 	return inbound, needRestart, err
 }
 
-// DelInbound deletes an inbound configuration by ID.
-// It removes the inbound from the database and the running Xray instance if active.
-// Returns whether Xray needs restart and any error.
 func (s *InboundService) DelInbound(id int) (bool, error) {
 	db := database.GetDB()
 
 	needRestart := false
-	// Load the full inbound (not just the tag) so we know its NodeID and
-	// can route the runtime call to the right engine. Skip-on-not-found
-	// preserves the old "no-op when DB row doesn't exist" behaviour.
 	var ib model.Inbound
 	loadErr := db.Model(model.Inbound{}).Where("id = ? and enable = ?", id, true).First(&ib).Error
 	if loadErr == nil {
-		// Delete is best-effort on the runtime side: the user's intent is
-		// to get rid of the inbound, so a missing node row, an offline
-		// node, or a remote-side "already gone" should NEVER block the
-		// central DB cleanup. Worst case the remote keeps an orphan that
-		// the user can clean up manually — far less painful than the row
-		// being stuck on central.
 		rt, rterr := s.runtimeFor(&ib)
 		if rterr != nil {
 			logger.Warning("DelInbound: runtime lookup failed, deleting central row anyway:", rterr)
@@ -531,11 +497,6 @@ func (s *InboundService) SetInboundEnable(id int, enable bool) (bool, error) {
 	}
 	inbound.Enable = enable
 
-	// Sync xray runtime via the Runtime adapter. For local inbounds we
-	// also rebuild the runtime config (drops clients flagged as disabled
-	// in ClientTraffic) so the live xray sees the same filtered view it
-	// did pre-refactor. Remote runtimes ship the unfiltered inbound —
-	// the remote panel does its own filtering before pushing to its xray.
 	needRestart := false
 	rt, rterr := s.runtimeFor(inbound)
 	if rterr != nil {
@@ -573,9 +534,6 @@ func (s *InboundService) SetInboundEnable(id int, enable bool) (bool, error) {
 	return needRestart, nil
 }
 
-// UpdateInbound modifies an existing inbound configuration.
-// It validates changes, updates the database, and syncs with the running Xray instance.
-// Returns the updated inbound, whether Xray needs restart, and any error.
 func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
 	exist, err := s.checkPortConflict(inbound, inbound.Id)
 	if err != nil {
@@ -667,8 +625,6 @@ func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound,
 		}
 	}
 
-	oldInbound.Up = inbound.Up
-	oldInbound.Down = inbound.Down
 	oldInbound.Total = inbound.Total
 	oldInbound.Remark = inbound.Remark
 	oldInbound.Enable = inbound.Enable
@@ -696,13 +652,9 @@ func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound,
 		}
 		needRestart = true
 	} else {
-		// Use a snapshot of the OLD tag so the remote can resolve its
-		// remote-id even when the new tag has changed (port/listen edit).
 		oldSnapshot := *oldInbound
 		oldSnapshot.Tag = tag
 		if oldInbound.NodeID == nil {
-			// Local: keep the old del-then-add-filtered behaviour to
-			// preserve runtime client filtering.
 			if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 == nil {
 				logger.Debug("Old inbound deleted on", rt.Name(), ":", tag)
 			}
@@ -719,10 +671,6 @@ func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound,
 				}
 			}
 		} else {
-			// Remote: a single UpdateInbound call (the Remote adapter
-			// resolves remote-id by old tag, then POSTs /update/{id}).
-			// Assign to the outer `err` on failure so the deferred tx
-			// handler rolls back the central DB write.
 			if !inbound.Enable {
 				if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 != nil {
 					err = err2
@@ -851,13 +799,15 @@ func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inb
 			return err
 		}
 	}
-	// Added clients — create their stats rows.
 	for i := range newClients {
 		email := newClients[i].Email
 		if email == "" {
 			continue
 		}
 		if _, existed := oldEmails[email]; existed {
+			if err := s.UpdateClientStat(tx, email, &newClients[i]); err != nil {
+				return err
+			}
 			continue
 		}
 		if err := s.AddClientStat(tx, oldInbound.Id, &newClients[i]); err != nil {
@@ -964,9 +914,6 @@ func (s *InboundService) AddInboundClient(data *model.Inbound) (bool, error) {
 		}
 		needRestart = true
 	} else if oldInbound.NodeID == nil {
-		// Local: per-client AddUser keeps existing connections alive
-		// (incremental hot-add). Walk every new client; on any failure
-		// fall back to needRestart so cron rebuilds from scratch.
 		for _, client := range clients {
 			if len(client.Email) == 0 {
 				needRestart = true
@@ -997,11 +944,6 @@ func (s *InboundService) AddInboundClient(data *model.Inbound) (bool, error) {
 			}
 		}
 	} else {
-		// Remote: a single UpdateInbound ships the new clients in one
-		// HTTP round-trip rather than N. Settings are already mutated
-		// in-memory (oldInbound.Settings) so the remote sees the final
-		// state. Per-client ClientStat rows still need the central DB
-		// update so the loop runs that branch first.
 		for _, client := range clients {
 			if len(client.Email) > 0 {
 				s.AddClientStat(tx, data.Id, &client)
@@ -1318,8 +1260,6 @@ func (s *InboundService) DelInboundClient(inboundId int, clientId string) (bool,
 					needRestart = true
 				}
 			} else {
-				// Remote: settings already mutated above; one UpdateInbound
-				// ships the post-deletion state to the node.
 				if err1 := rt.UpdateInbound(context.Background(), oldInbound, oldInbound); err1 != nil {
 					return false, err1
 				}
@@ -1530,8 +1470,6 @@ func (s *InboundService) UpdateInboundClient(data *model.Inbound, clientId strin
 			}
 			needRestart = true
 		} else if oldInbound.NodeID == nil {
-			// Local: paired Remove+Add on the live xray, keeping other
-			// clients online (full-restart fallback on partial failure).
 			if oldClients[clientIndex].Enable {
 				err1 := rt.RemoveUser(context.Background(), oldInbound, oldEmail)
 				if err1 == nil {
@@ -1565,7 +1503,6 @@ func (s *InboundService) UpdateInboundClient(data *model.Inbound, clientId strin
 				}
 			}
 		} else {
-			// Remote: settings already mutated; one UpdateInbound suffices.
 			if err1 := rt.UpdateInbound(context.Background(), oldInbound, oldInbound); err1 != nil {
 				err = err1
 				return false, err
@@ -1578,43 +1515,69 @@ func (s *InboundService) UpdateInboundClient(data *model.Inbound, clientId strin
 	return needRestart, tx.Save(oldInbound).Error
 }
 
-// resetGracePeriodMs is the window after a reset during which incoming
-// traffic snapshots from the node are ignored if they would resurrect
-// non-zero counters. Three sync ticks (10s each) is enough headroom for
-// the central → node reset HTTP call to land before the next pull.
 const resetGracePeriodMs int64 = 30000
 
-// SetRemoteTraffic merges absolute counters from a remote node into the
-// central DB. Unlike AddTraffic, which adds deltas pulled from the local
-// xray gRPC stats endpoint, this SETs the values — the node already has
-// the canonical absolute value and we just mirror it.
-//
-// Rows in the post-reset grace window are skipped if the snapshot would
-// regress them, so a user-initiated reset survives until the propagation
-// HTTP call has completed on the node. After the grace window expires
-// the snapshot wins regardless (the node is authoritative for the
-// inbounds it hosts).
-func (s *InboundService) SetRemoteTraffic(nodeID int, snap *runtime.TrafficSnapshot) error {
+func (s *InboundService) SetRemoteTraffic(nodeID int, snap *runtime.TrafficSnapshot) (bool, error) {
+	var structuralChange bool
+	err := submitTrafficWrite(func() error {
+		var inner error
+		structuralChange, inner = s.setRemoteTrafficLocked(nodeID, snap)
+		return inner
+	})
+	return structuralChange, err
+}
+
+func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.TrafficSnapshot) (bool, error) {
 	if snap == nil || nodeID <= 0 {
-		return nil
+		return false, nil
 	}
 	db := database.GetDB()
 	now := time.Now().UnixMilli()
 
-	// Load central inbounds for this node so we can resolve tag→id and
-	// honour the per-inbound grace window. One query covers every row
-	// touched in this tick.
 	var central []model.Inbound
 	if err := db.Model(model.Inbound{}).
 		Where("node_id = ?", nodeID).
 		Find(&central).Error; err != nil {
-		return err
+		return false, err
 	}
 	tagToCentral := make(map[string]*model.Inbound, len(central))
 	for i := range central {
 		tagToCentral[central[i].Tag] = &central[i]
 	}
 
+	var centralClientStats []xray.ClientTraffic
+	if len(central) > 0 {
+		ids := make([]int, 0, len(central))
+		for i := range central {
+			ids = append(ids, central[i].Id)
+		}
+		if err := db.Model(xray.ClientTraffic{}).
+			Where("inbound_id IN ?", ids).
+			Find(&centralClientStats).Error; err != nil {
+			return false, err
+		}
+	}
+	type csKey struct {
+		inboundID int
+		email     string
+	}
+	centralCS := make(map[csKey]*xray.ClientTraffic, len(centralClientStats))
+	for i := range centralClientStats {
+		centralCS[csKey{centralClientStats[i].InboundId, centralClientStats[i].Email}] = &centralClientStats[i]
+	}
+
+	var defaultUserId int
+	if len(central) > 0 {
+		defaultUserId = central[0].UserId
+	} else {
+		var u model.User
+		if err := db.Model(model.User{}).Order("id asc").First(&u).Error; err == nil {
+			defaultUserId = u.Id
+		} else {
+			defaultUserId = 1
+		}
+	}
+
 	tx := db.Begin()
 	committed := false
 	defer func() {
@@ -1623,42 +1586,101 @@ func (s *InboundService) SetRemoteTraffic(nodeID int, snap *runtime.TrafficSnaps
 		}
 	}()
 
-	// Per-inbound counter merge. Skip rows whose central allTime is
-	// suspiciously lower than the snapshot AND we're inside the grace
-	// window — that's the "reset hit central but not the node yet"
-	// pattern we want to defer until next tick.
+	structuralChange := false
+
+	snapTags := make(map[string]struct{}, len(snap.Inbounds))
 	for _, snapIb := range snap.Inbounds {
 		if snapIb == nil {
 			continue
 		}
+		snapTags[snapIb.Tag] = struct{}{}
+
 		c, ok := tagToCentral[snapIb.Tag]
 		if !ok {
-			continue // node has an inbound the central doesn't know about — ignore
-		}
-		snapAllTime := snapIb.AllTime
-		if snapAllTime == 0 {
-			snapAllTime = snapIb.Up + snapIb.Down
+			newIb := model.Inbound{
+				UserId:         defaultUserId,
+				NodeID:         &nodeID,
+				Tag:            snapIb.Tag,
+				Listen:         snapIb.Listen,
+				Port:           snapIb.Port,
+				Protocol:       snapIb.Protocol,
+				Settings:       snapIb.Settings,
+				StreamSettings: snapIb.StreamSettings,
+				Sniffing:       snapIb.Sniffing,
+				TrafficReset:   snapIb.TrafficReset,
+				Enable:         snapIb.Enable,
+				Remark:         snapIb.Remark,
+				Total:          snapIb.Total,
+				ExpiryTime:     snapIb.ExpiryTime,
+				Up:             snapIb.Up,
+				Down:           snapIb.Down,
+				AllTime:        snapIb.AllTime,
+			}
+			if err := tx.Create(&newIb).Error; err != nil {
+				logger.Warning("setRemoteTraffic: create central inbound for tag", snapIb.Tag, "failed:", err)
+				continue
+			}
+			tagToCentral[snapIb.Tag] = &newIb
+			structuralChange = true
+			continue
 		}
+
 		inGrace := c.LastTrafficResetTime > 0 && now-c.LastTrafficResetTime < resetGracePeriodMs
-		if inGrace && snapAllTime > c.AllTime {
-			logger.Debug("SetRemoteTraffic: skipping inbound", c.Id, "in reset grace window")
-			continue
+
+		updates := map[string]any{
+			"enable":          snapIb.Enable,
+			"remark":          snapIb.Remark,
+			"listen":          snapIb.Listen,
+			"port":            snapIb.Port,
+			"protocol":        snapIb.Protocol,
+			"total":           snapIb.Total,
+			"expiry_time":     snapIb.ExpiryTime,
+			"settings":        snapIb.Settings,
+			"stream_settings": snapIb.StreamSettings,
+			"sniffing":        snapIb.Sniffing,
+			"traffic_reset":   snapIb.TrafficReset,
+		}
+		if !inGrace || (snapIb.Up+snapIb.Down) <= (c.Up+c.Down) {
+			updates["up"] = snapIb.Up
+			updates["down"] = snapIb.Down
+		}
+		if snapIb.AllTime > c.AllTime {
+			updates["all_time"] = snapIb.AllTime
+		}
+
+		if c.Settings != snapIb.Settings ||
+			c.Remark != snapIb.Remark ||
+			c.Listen != snapIb.Listen ||
+			c.Port != snapIb.Port ||
+			c.Total != snapIb.Total ||
+			c.ExpiryTime != snapIb.ExpiryTime ||
+			c.Enable != snapIb.Enable {
+			structuralChange = true
 		}
+
 		if err := tx.Model(model.Inbound{}).
 			Where("id = ?", c.Id).
-			Updates(map[string]any{
-				"up":       snapIb.Up,
-				"down":     snapIb.Down,
-				"all_time": snapAllTime,
-			}).Error; err != nil {
-			return err
+			Updates(updates).Error; err != nil {
+			return false, err
 		}
 	}
 
-	// Per-client merge. The snapshot's ClientStats are nested under
-	// each Inbound, so flatten before walking. Each client_traffics row
-	// is keyed by (inbound_id, email) — we resolve inbound_id from the
-	// central inbound row matched above.
+	for _, c := range central {
+		if _, kept := snapTags[c.Tag]; kept {
+			continue
+		}
+		if err := tx.Where("inbound_id = ?", c.Id).
+			Delete(&xray.ClientTraffic{}).Error; err != nil {
+			return false, err
+		}
+		if err := tx.Where("id = ?", c.Id).
+			Delete(&model.Inbound{}).Error; err != nil {
+			return false, err
+		}
+		delete(tagToCentral, c.Tag)
+		structuralChange = true
+	}
+
 	for _, snapIb := range snap.Inbounds {
 		if snapIb == nil {
 			continue
@@ -1667,52 +1689,105 @@ func (s *InboundService) SetRemoteTraffic(nodeID int, snap *runtime.TrafficSnaps
 		if !ok {
 			continue
 		}
-		// Honour the same grace window for client rows: if the parent
-		// inbound was just reset, leave its clients alone too.
 		inGrace := c.LastTrafficResetTime > 0 && now-c.LastTrafficResetTime < resetGracePeriodMs
+
+		snapEmails := make(map[string]struct{}, len(snapIb.ClientStats))
 		for _, cs := range snapIb.ClientStats {
-			snapAllTime := cs.AllTime
-			if snapAllTime == 0 {
-				snapAllTime = cs.Up + cs.Down
-			}
-			if inGrace {
-				// Skip client rows whose snapshot would push counters
-				// back up; allow rows that are zero on the node side
-				// (those are normal — node was reset alongside central).
-				if snapAllTime > 0 {
-					continue
+			snapEmails[cs.Email] = struct{}{}
+
+			existing := centralCS[csKey{c.Id, cs.Email}]
+			if existing == nil {
+				if err := tx.Create(&xray.ClientTraffic{
+					InboundId:  c.Id,
+					Email:      cs.Email,
+					Enable:     cs.Enable,
+					Total:      cs.Total,
+					ExpiryTime: cs.ExpiryTime,
+					Reset:      cs.Reset,
+					Up:         cs.Up,
+					Down:       cs.Down,
+					AllTime:    cs.AllTime,
+					LastOnline: cs.LastOnline,
+				}).Error; err != nil {
+					return false, err
+				}
+				structuralChange = true
+				continue
+			}
+
+			if existing.Enable != cs.Enable ||
+				existing.Total != cs.Total ||
+				existing.ExpiryTime != cs.ExpiryTime ||
+				existing.Reset != cs.Reset {
+				structuralChange = true
+			}
+
+			allTime := existing.AllTime
+			if cs.AllTime > allTime {
+				allTime = cs.AllTime
+			}
+
+			if inGrace && cs.Up+cs.Down > 0 {
+				if err := tx.Exec(
+					`UPDATE client_traffics
+					 SET enable = ?, total = ?, expiry_time = ?, reset = ?, all_time = ?
+					 WHERE inbound_id = ? AND email = ?`,
+					cs.Enable, cs.Total, cs.ExpiryTime, cs.Reset, allTime, c.Id, cs.Email,
+				).Error; err != nil {
+					return false, err
 				}
+				continue
 			}
-			// MAX(last_online, ?) so a momentary clock skew on the node
-			// can't regress the central row's last-seen timestamp.
+
 			if err := tx.Exec(
 				`UPDATE client_traffics
-				 SET up = ?, down = ?, all_time = ?, last_online = MAX(last_online, ?)
+				 SET up = ?, down = ?, enable = ?, total = ?, expiry_time = ?, reset = ?,
+				     all_time = ?, last_online = MAX(last_online, ?)
 				 WHERE inbound_id = ? AND email = ?`,
-				cs.Up, cs.Down, snapAllTime, cs.LastOnline, c.Id, cs.Email,
+				cs.Up, cs.Down, cs.Enable, cs.Total, cs.ExpiryTime, cs.Reset, allTime,
+				cs.LastOnline, c.Id, cs.Email,
 			).Error; err != nil {
-				return err
+				return false, err
+			}
+		}
+
+		for k, existing := range centralCS {
+			if k.inboundID != c.Id {
+				continue
+			}
+			if _, kept := snapEmails[k.email]; kept {
+				continue
 			}
+			if err := tx.Where("inbound_id = ? AND email = ?", c.Id, existing.Email).
+				Delete(&xray.ClientTraffic{}).Error; err != nil {
+				return false, err
+			}
+			structuralChange = true
 		}
 	}
 
 	if err := tx.Commit().Error; err != nil {
-		return err
+		return false, err
 	}
 	committed = true
 
-	// Push the node's online-clients contribution into xray.Process so
-	// GetOnlineClients returns the union of local + every node. Empty
-	// list still calls Set so a node that just had everyone disconnect
-	// updates promptly.
 	if p != nil {
 		p.SetNodeOnlineClients(nodeID, snap.OnlineEmails)
 	}
 
-	return nil
+	return structuralChange, nil
+}
+
+func (s *InboundService) AddTraffic(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (needRestart bool, clientsDisabled bool, err error) {
+	err = submitTrafficWrite(func() error {
+		var inner error
+		needRestart, clientsDisabled, inner = s.addTrafficLocked(inboundTraffics, clientTraffics)
+		return inner
+	})
+	return
 }
 
-func (s *InboundService) AddTraffic(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (bool, bool, error) {
+func (s *InboundService) addTrafficLocked(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (bool, bool, error) {
 	var err error
 	db := database.GetDB()
 	tx := db.Begin()
@@ -1767,7 +1842,7 @@ func (s *InboundService) addInboundTraffic(tx *gorm.DB, traffics []*xray.Traffic
 
 	for _, traffic := range traffics {
 		if traffic.IsInbound {
-			err = tx.Model(&model.Inbound{}).Where("tag = ?", traffic.Tag).
+			err = tx.Model(&model.Inbound{}).Where("tag = ? AND node_id IS NULL", traffic.Tag).
 				Updates(map[string]any{
 					"up":       gorm.Expr("up + ?", traffic.Up),
 					"down":     gorm.Expr("down + ?", traffic.Down),
@@ -1797,7 +1872,10 @@ func (s *InboundService) addClientTraffic(tx *gorm.DB, traffics []*xray.ClientTr
 		emails = append(emails, traffic.Email)
 	}
 	dbClientTraffics := make([]*xray.ClientTraffic, 0, len(traffics))
-	err = tx.Model(xray.ClientTraffic{}).Where("email IN (?)", emails).Find(&dbClientTraffics).Error
+	err = tx.Model(xray.ClientTraffic{}).
+		Where("email IN (?) AND inbound_id IN (?)", emails,
+			tx.Model(&model.Inbound{}).Select("id").Where("node_id IS NULL")).
+		Find(&dbClientTraffics).Error
 	if err != nil {
 		return err
 	}
@@ -1911,7 +1989,10 @@ func (s *InboundService) autoRenewClients(tx *gorm.DB) (bool, int64, error) {
 	now := time.Now().Unix() * 1000
 	var err, err1 error
 
-	err = tx.Model(xray.ClientTraffic{}).Where("reset > 0 and expiry_time > 0 and expiry_time <= ?", now).Find(&traffics).Error
+	err = tx.Model(xray.ClientTraffic{}).
+		Where("reset > 0 and expiry_time > 0 and expiry_time <= ?", now).
+		Where("inbound_id IN (?)", tx.Model(&model.Inbound{}).Select("id").Where("node_id IS NULL")).
+		Find(&traffics).Error
 	if err != nil {
 		return false, 0, err
 	}
@@ -2017,7 +2098,7 @@ func (s *InboundService) disableInvalidInbounds(tx *gorm.DB) (bool, int64, error
 		var tags []string
 		err := tx.Table("inbounds").
 			Select("inbounds.tag").
-			Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
+			Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ? and node_id IS NULL", now, true).
 			Scan(&tags).Error
 		if err != nil {
 			return false, 0, err
@@ -2036,7 +2117,7 @@ func (s *InboundService) disableInvalidInbounds(tx *gorm.DB) (bool, int64, error
 	}
 
 	result := tx.Model(model.Inbound{}).
-		Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
+		Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ? and node_id IS NULL", now, true).
 		Update("enable", false)
 	err := result.Error
 	count := result.RowsAffected
@@ -2050,6 +2131,7 @@ func (s *InboundService) disableInvalidClients(tx *gorm.DB) (bool, int64, error)
 	var depletedRows []xray.ClientTraffic
 	err := tx.Model(xray.ClientTraffic{}).
 		Where("((total > 0 AND up + down >= total) OR (expiry_time > 0 AND expiry_time <= ?)) AND enable = ?", now, true).
+		Where("inbound_id IN (?)", tx.Model(&model.Inbound{}).Select("id").Where("node_id IS NULL")).
 		Find(&depletedRows).Error
 	if err != nil {
 		return false, 0, err
@@ -2152,6 +2234,7 @@ func (s *InboundService) disableInvalidClients(tx *gorm.DB) (bool, int64, error)
 
 	result := tx.Model(xray.ClientTraffic{}).
 		Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
+		Where("inbound_id IN (?)", tx.Model(&model.Inbound{}).Select("id").Where("node_id IS NULL")).
 		Update("enable", false)
 	err = result.Error
 	count := result.RowsAffected
@@ -2163,8 +2246,6 @@ func (s *InboundService) disableInvalidClients(tx *gorm.DB) (bool, int64, error)
 		return needRestart, count, nil
 	}
 
-	// Mirror enable=false + the row's authoritative quota/expiry into every
-	// (inbound, email) we just removed via the API.
 	inboundEmailMap := make(map[int]map[string]struct{})
 	for _, t := range targets {
 		if inboundEmailMap[t.InboundId] == nil {
@@ -2744,22 +2825,24 @@ func (s *InboundService) ResetClientTrafficLimitByEmail(clientEmail string, tota
 }
 
 func (s *InboundService) ResetClientTrafficByEmail(clientEmail string) error {
-	db := database.GetDB()
-
-	// Reset traffic stats in ClientTraffic table
-	result := db.Model(xray.ClientTraffic{}).
-		Where("email = ?", clientEmail).
-		Updates(map[string]any{"enable": true, "up": 0, "down": 0})
-
-	err := result.Error
-	if err != nil {
-		return err
-	}
+	return submitTrafficWrite(func() error {
+		db := database.GetDB()
+		return db.Model(xray.ClientTraffic{}).
+			Where("email = ?", clientEmail).
+			Updates(map[string]any{"enable": true, "up": 0, "down": 0}).Error
+	})
+}
 
-	return nil
+func (s *InboundService) ResetClientTraffic(id int, clientEmail string) (needRestart bool, err error) {
+	err = submitTrafficWrite(func() error {
+		var inner error
+		needRestart, inner = s.resetClientTrafficLocked(id, clientEmail)
+		return inner
+	})
+	return
 }
 
-func (s *InboundService) ResetClientTraffic(id int, clientEmail string) (bool, error) {
+func (s *InboundService) resetClientTrafficLocked(id int, clientEmail string) (bool, error) {
 	needRestart := false
 
 	traffic, err := s.GetClientTrafficByEmail(clientEmail)
@@ -2825,18 +2908,11 @@ func (s *InboundService) ResetClientTraffic(id int, clientEmail string) (bool, e
 		return false, err
 	}
 
-	// Stamp last_traffic_reset_time on the parent inbound so the next
-	// NodeTrafficSyncJob tick honours the grace window and doesn't pull
-	// the pre-reset absolute back from the node.
 	now := time.Now().UnixMilli()
 	_ = db.Model(model.Inbound{}).
 		Where("id = ?", id).
 		Update("last_traffic_reset_time", now).Error
 
-	// Propagate to the remote node if this inbound is node-managed.
-	// Best-effort: an offline node shouldn't block a user-driven reset
-	// — the central DB is already zeroed and the next successful sync
-	// (within the grace window) will re-pull whatever the node has.
 	inbound, err := s.GetInbound(id)
 	if err == nil && inbound != nil && inbound.NodeID != nil {
 		if rt, rterr := s.runtimeFor(inbound); rterr == nil {
@@ -2852,6 +2928,12 @@ func (s *InboundService) ResetClientTraffic(id int, clientEmail string) (bool, e
 }
 
 func (s *InboundService) ResetAllClientTraffics(id int) error {
+	return submitTrafficWrite(func() error {
+		return s.resetAllClientTrafficsLocked(id)
+	})
+}
+
+func (s *InboundService) resetAllClientTrafficsLocked(id int) error {
 	db := database.GetDB()
 	now := time.Now().Unix() * 1000
 
@@ -2889,19 +2971,12 @@ func (s *InboundService) ResetAllClientTraffics(id int) error {
 		return err
 	}
 
-	// Propagate to remote nodes after the central DB is settled. Single
-	// inbound: one rt.ResetInboundClientTraffics call. id == -1 (all
-	// inbounds across panel): walk every node-managed inbound and call
-	// the per-inbound endpoint — there's no panel-wide endpoint that
-	// only resets clients without zeroing inbound counters.
 	var inbounds []model.Inbound
 	q := db.Model(model.Inbound{}).Where("node_id IS NOT NULL")
 	if id != -1 {
 		q = q.Where("id = ?", id)
 	}
 	if err := q.Find(&inbounds).Error; err != nil {
-		// Failed to discover which inbounds to propagate to — central
-		// DB is already correct, log and move on.
 		logger.Warning("ResetAllClientTraffics: discover node inbounds failed:", err)
 		return nil
 	}
@@ -2920,6 +2995,12 @@ func (s *InboundService) ResetAllClientTraffics(id int) error {
 }
 
 func (s *InboundService) ResetAllTraffics() error {
+	return submitTrafficWrite(func() error {
+		return s.resetAllTrafficsLocked()
+	})
+}
+
+func (s *InboundService) resetAllTrafficsLocked() error {
 	db := database.GetDB()
 	now := time.Now().UnixMilli()
 
@@ -2933,10 +3014,6 @@ func (s *InboundService) ResetAllTraffics() error {
 		return err
 	}
 
-	// Propagate to every node that has at least one inbound on this
-	// panel. We can't blanket-call rt.ResetAllTraffics because that
-	// would also zero traffic for inbounds the node hosts but the
-	// central panel doesn't know about — instead reset per inbound.
 	var inbounds []model.Inbound
 	if err := db.Model(model.Inbound{}).
 		Where("node_id IS NOT NULL").
@@ -2959,13 +3036,12 @@ func (s *InboundService) ResetAllTraffics() error {
 }
 
 func (s *InboundService) ResetInboundTraffic(id int) error {
-	db := database.GetDB()
-
-	result := db.Model(model.Inbound{}).
-		Where("id = ?", id).
-		Updates(map[string]any{"up": 0, "down": 0})
-
-	return result.Error
+	return submitTrafficWrite(func() error {
+		db := database.GetDB()
+		return db.Model(model.Inbound{}).
+			Where("id = ?", id).
+			Updates(map[string]any{"up": 0, "down": 0}).Error
+	})
 }
 
 func (s *InboundService) DelDepletedClients(id int) (err error) {
@@ -3229,11 +3305,6 @@ func chunkInts(s []int, size int) [][]int {
 	return out
 }
 
-// GetActiveClientTraffics returns the absolute ClientTraffic rows for the given
-// emails. Used by the WebSocket delta path to push per-client absolute
-// counters without re-serializing the full inbound list. The query is chunked
-// to stay under SQLite's bind-variable limit on very large active sets.
-// Empty input returns (nil, nil).
 func (s *InboundService) GetActiveClientTraffics(emails []string) ([]*xray.ClientTraffic, error) {
 	uniq := uniqueNonEmptyStrings(emails)
 	if len(uniq) == 0 {
@@ -3251,9 +3322,6 @@ func (s *InboundService) GetActiveClientTraffics(emails []string) ([]*xray.Clien
 	return traffics, nil
 }
 
-// InboundTrafficSummary is the minimal projection of an inbound's traffic
-// counters used by the WebSocket delta path. Excludes Settings/StreamSettings
-// blobs so the broadcast stays compact even with many inbounds.
 type InboundTrafficSummary struct {
 	Id      int   `json:"id"`
 	Up      int64 `json:"up"`
@@ -3263,9 +3331,6 @@ type InboundTrafficSummary struct {
 	Enable  bool  `json:"enable"`
 }
 
-// GetInboundsTrafficSummary returns inbound-level absolute traffic counters
-// (no per-client expansion). Companion to GetActiveClientTraffics — together
-// they replace the heavy "full inbound list" broadcast on each cron tick.
 func (s *InboundService) GetInboundsTrafficSummary() ([]InboundTrafficSummary, error) {
 	db := database.GetDB()
 	var summaries []InboundTrafficSummary
@@ -3293,26 +3358,20 @@ func (s *InboundService) GetClientTrafficByEmail(email string) (traffic *xray.Cl
 }
 
 func (s *InboundService) UpdateClientTrafficByEmail(email string, upload int64, download int64) error {
-	db := database.GetDB()
-
-	// Keep all_time monotonic: it represents historical cumulative usage and
-	// must never be less than the currently-tracked up+down. Without this,
-	// the UI showed "Общий трафик" (allTime) below the live consumed value
-	// after admins manually edited a client's counters.
-	result := db.Model(xray.ClientTraffic{}).
-		Where("email = ?", email).
-		Updates(map[string]any{
-			"up":       upload,
-			"down":     download,
-			"all_time": gorm.Expr("CASE WHEN COALESCE(all_time, 0) < ? THEN ? ELSE all_time END", upload+download, upload+download),
-		})
-
-	err := result.Error
-	if err != nil {
-		logger.Warningf("Error updating ClientTraffic with email %s: %v", email, err)
+	return submitTrafficWrite(func() error {
+		db := database.GetDB()
+		err := db.Model(xray.ClientTraffic{}).
+			Where("email = ?", email).
+			Updates(map[string]any{
+				"up":       upload,
+				"down":     download,
+				"all_time": gorm.Expr("CASE WHEN COALESCE(all_time, 0) < ? THEN ? ELSE all_time END", upload+download, upload+download),
+			}).Error
+		if err != nil {
+			logger.Warningf("Error updating ClientTraffic with email %s: %v", email, err)
+		}
 		return err
-	}
-	return nil
+	})
 }
 
 func (s *InboundService) GetClientTrafficByID(id string) ([]xray.ClientTraffic, error) {
@@ -3642,18 +3701,12 @@ func (s *InboundService) GetOnlineClients() []string {
 	return p.GetOnlineClients()
 }
 
-// SetNodeOnlineClients records a remote node's online-clients list on
-// the panel-wide xray.Process so GetOnlineClients returns the union of
-// local + every node's contribution. Called by NodeTrafficSyncJob.
 func (s *InboundService) SetNodeOnlineClients(nodeID int, emails []string) {
 	if p != nil {
 		p.SetNodeOnlineClients(nodeID, emails)
 	}
 }
 
-// ClearNodeOnlineClients drops one node's contribution to the online
-// set. Used when the per-node sync probe fails so a downed node
-// doesn't keep its clients listed as online forever.
 func (s *InboundService) ClearNodeOnlineClients(nodeID int) {
 	if p != nil {
 		p.ClearNodeOnlineClients(nodeID)

+ 0 - 46
web/service/node.go

@@ -16,10 +16,6 @@ import (
 	"github.com/mhsanaei/3x-ui/v3/web/runtime"
 )
 
-// HeartbeatPatch is the slice of fields a single Probe() result writes
-// back to a Node row. We pass it as a struct (not a *model.Node) so the
-// heartbeat path can't accidentally clobber configuration columns the
-// user just edited.
 type HeartbeatPatch struct {
 	Status        string
 	LastHeartbeat int64
@@ -31,13 +27,8 @@ type HeartbeatPatch struct {
 	LastError     string
 }
 
-// NodeService manages remote 3x-ui nodes registered with this panel.
-// It owns CRUD for the Node model and the HTTP probe used by both the
-// heartbeat job and the on-demand "test connection" UI action.
 type NodeService struct{}
 
-// httpClient is shared so repeated probes reuse TCP/TLS connections.
-// Timeout is per-request, set on each Do() via context.
 var nodeHTTPClient = &http.Client{
 	Transport: &http.Transport{
 		MaxIdleConns:        64,
@@ -62,8 +53,6 @@ func (s *NodeService) GetById(id int) (*model.Node, error) {
 	return n, nil
 }
 
-// normalize fills in defaults and trims accidental whitespace before save.
-// Pulled out so Create and Update share the same rules.
 func (s *NodeService) normalize(n *model.Node) error {
 	n.Name = strings.TrimSpace(n.Name)
 	n.Address = strings.TrimSpace(n.Address)
@@ -109,9 +98,6 @@ func (s *NodeService) Update(id int, in *model.Node) error {
 	if err := db.Where("id = ?", id).First(existing).Error; err != nil {
 		return err
 	}
-	// Only persist user-controlled columns. Heartbeat fields stay where
-	// the heartbeat job last wrote them so a no-op edit doesn't blank
-	// the dashboard out for ten seconds.
 	updates := map[string]any{
 		"name":      in.Name,
 		"remark":    in.Remark,
@@ -125,8 +111,6 @@ func (s *NodeService) Update(id int, in *model.Node) error {
 	if err := db.Model(model.Node{}).Where("id = ?", id).Updates(updates).Error; err != nil {
 		return err
 	}
-	// Drop any cached Remote so the next inbound op picks up the fresh
-	// address/token. Cheap to do unconditionally — the next miss rebuilds.
 	if mgr := runtime.GetManager(); mgr != nil {
 		mgr.InvalidateNode(id)
 	}
@@ -141,8 +125,6 @@ func (s *NodeService) Delete(id int) error {
 	if mgr := runtime.GetManager(); mgr != nil {
 		mgr.InvalidateNode(id)
 	}
-	// Drop in-memory series so a freshly created node with the same id
-	// doesn't inherit stale points (sqlite reuses ids freely).
 	nodeMetrics.drop(nodeMetricKey(id, "cpu"))
 	nodeMetrics.drop(nodeMetricKey(id, "mem"))
 	return nil
@@ -153,9 +135,6 @@ func (s *NodeService) SetEnable(id int, enable bool) error {
 	return db.Model(model.Node{}).Where("id = ?", id).Update("enable", enable).Error
 }
 
-// UpdateHeartbeat persists the slice of fields written by a probe. We
-// don't touch updated_at via gorm autoUpdateTime here — that field is
-// reserved for user-driven config edits.
 func (s *NodeService) UpdateHeartbeat(id int, p HeartbeatPatch) error {
 	db := database.GetDB()
 	updates := map[string]any{
@@ -171,9 +150,6 @@ func (s *NodeService) UpdateHeartbeat(id int, p HeartbeatPatch) error {
 	if err := db.Model(model.Node{}).Where("id = ?", id).Updates(updates).Error; err != nil {
 		return err
 	}
-	// Only record online ticks. Offline probes carry zeroed cpu/mem and
-	// would draw a misleading dip on the chart; the gap on the x-axis is
-	// the truthful representation of "we couldn't reach the node".
 	if p.Status == "online" {
 		now := time.Unix(p.LastHeartbeat, 0)
 		nodeMetrics.append(nodeMetricKey(id, "cpu"), now, p.CpuPct)
@@ -182,28 +158,14 @@ func (s *NodeService) UpdateHeartbeat(id int, p HeartbeatPatch) error {
 	return nil
 }
 
-// nodeMetricKey is the namespacing used inside the singleton ring buffer
-// so per-node metrics don't collide with each other or with the system
-// metrics in the sibling singleton.
 func nodeMetricKey(id int, metric string) string {
 	return "node:" + strconv.Itoa(id) + ":" + metric
 }
 
-// AggregateNodeMetric returns up to maxPoints averaged buckets for one
-// node's metric (currently "cpu" or "mem"). Output shape matches
-// AggregateSystemMetric: {"t": unixSec, "v": value}.
 func (s *NodeService) AggregateNodeMetric(id int, metric string, bucketSeconds int, maxPoints int) []map[string]any {
 	return nodeMetrics.aggregate(nodeMetricKey(id, metric), bucketSeconds, maxPoints)
 }
 
-// Probe issues a single GET to the node's /panel/api/server/status and
-// returns a HeartbeatPatch. On error the patch is zero-valued except
-// for LastError; the caller is responsible for setting Status="offline".
-//
-// The remote endpoint requires authentication: we send the per-node
-// ApiToken as a Bearer token, which the remote APIController.checkAPIAuth
-// validates. Calls without a token would just get a 404, which masks
-// the existence of the API entirely.
 func (s *NodeService) Probe(ctx context.Context, n *model.Node) (HeartbeatPatch, error) {
 	patch := HeartbeatPatch{LastHeartbeat: time.Now().Unix()}
 	url := fmt.Sprintf("%s://%s:%d%spanel/api/server/status",
@@ -233,16 +195,10 @@ func (s *NodeService) Probe(ctx context.Context, n *model.Node) (HeartbeatPatch,
 		return patch, errors.New(patch.LastError)
 	}
 
-	// The remote wraps Status in entity.Msg. We decode into a typed
-	// envelope rather than map[string]any so a schema change on the
-	// remote shows up as a Go error instead of a silent zero-fill.
 	var envelope struct {
 		Success bool   `json:"success"`
 		Msg     string `json:"msg"`
 		Obj     *struct {
-			Cpu uint64 `json:"-"`
-			// Status fields we care about. Decode CPU/Mem nested
-			// structs minimally — anything else gets discarded.
 			CpuPct float64 `json:"cpu"`
 			Mem    struct {
 				Current uint64 `json:"current"`
@@ -272,8 +228,6 @@ func (s *NodeService) Probe(ctx context.Context, n *model.Node) (HeartbeatPatch,
 	return patch, nil
 }
 
-// EnvelopeForUI is the shape a frontend test-connection action expects.
-// Pulling it out keeps the controller dumb.
 type ProbeResultUI struct {
 	Status      string  `json:"status"`
 	LatencyMs   int     `json:"latencyMs"`

+ 1 - 2
web/service/server.go

@@ -7,7 +7,6 @@ import (
 	"encoding/json"
 	"fmt"
 	"io"
-	"io/fs"
 	"mime/multipart"
 	"net/http"
 	"os"
@@ -660,7 +659,7 @@ func (s *ServerService) UpdateXray(version string) error {
 		defer zipFile.Close()
 		os.MkdirAll(filepath.Dir(fileName), 0755)
 		os.Remove(fileName)
-		file, err := os.OpenFile(fileName, os.O_CREATE|os.O_RDWR|os.O_TRUNC, fs.ModePerm)
+		file, err := os.OpenFile(fileName, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0755)
 		if err != nil {
 			return err
 		}

+ 87 - 0
web/service/traffic_writer.go

@@ -0,0 +1,87 @@
+package service
+
+import (
+	"context"
+	"errors"
+	"fmt"
+	"sync"
+	"time"
+
+	"github.com/mhsanaei/3x-ui/v3/logger"
+)
+
+const (
+	trafficWriterQueueSize     = 256
+	trafficWriterSubmitTimeout = 5 * time.Second
+)
+
+type trafficWriteRequest struct {
+	apply func() error
+	done  chan error
+}
+
+var (
+	twQueue  chan *trafficWriteRequest
+	twCtx    context.Context
+	twCancel context.CancelFunc
+	twDone   chan struct{}
+	twOnce   sync.Once
+)
+
+func StartTrafficWriter() {
+	twOnce.Do(func() {
+		twQueue = make(chan *trafficWriteRequest, trafficWriterQueueSize)
+		twCtx, twCancel = context.WithCancel(context.Background())
+		twDone = make(chan struct{})
+		go runTrafficWriter()
+	})
+}
+
+func StopTrafficWriter() {
+	if twCancel != nil {
+		twCancel()
+		<-twDone
+	}
+}
+
+func runTrafficWriter() {
+	defer close(twDone)
+	for {
+		select {
+		case req := <-twQueue:
+			req.done <- safeApply(req.apply)
+		case <-twCtx.Done():
+			for {
+				select {
+				case req := <-twQueue:
+					req.done <- safeApply(req.apply)
+				default:
+					return
+				}
+			}
+		}
+	}
+}
+
+func safeApply(fn func() error) (err error) {
+	defer func() {
+		if r := recover(); r != nil {
+			err = fmt.Errorf("traffic writer panic: %v", r)
+			logger.Error(err.Error())
+		}
+	}()
+	return fn()
+}
+
+func submitTrafficWrite(fn func() error) error {
+	if twQueue == nil {
+		return safeApply(fn)
+	}
+	req := &trafficWriteRequest{apply: fn, done: make(chan error, 1)}
+	select {
+	case twQueue <- req:
+	case <-time.After(trafficWriterSubmitTimeout):
+		return errors.New("traffic writer queue full")
+	}
+	return <-req.done
+}

+ 17 - 1
web/translation/ar-EG.json

@@ -94,6 +94,7 @@
     "ultraDark": "داكن جدًا",
     "dashboard": "نظرة عامة",
     "inbounds": "الإدخالات",
+    "nodes": "النودز",
     "settings": "إعدادات البانل",
     "xray": "إعدادات Xray",
     "logout": "تسجيل خروج",
@@ -753,7 +754,22 @@
         "useSystemHostsDesc": "استخدام ملف hosts من نظام مثبت",
         "usePreset": "استخدام النموذج",
         "dnsPresetTitle": "قوالب DNS",
-        "dnsPresetFamily": "العائلي"
+        "dnsPresetFamily": "العائلي",
+        "serveStale": "تقديم النتائج المنتهية",
+        "serveStaleDesc": "إرجاع نتائج الكاش المنتهية الصلاحية أثناء التحديث في الخلفية",
+        "serveExpiredTTL": "مدة صلاحية النتائج المنتهية",
+        "serveExpiredTTLDesc": "مدة صلاحية إدخالات الكاش المنتهية بالثواني؛ 0 = لا تنتهي أبدًا",
+        "timeoutMs": "المهلة (مللي ثانية)",
+        "skipFallback": "تخطي الاحتياطي",
+        "finalQuery": "الاستعلام النهائي",
+        "hosts": "Hosts",
+        "hostsAdd": "إضافة Host",
+        "hostsEmpty": "لم يتم تعريف أي Host",
+        "hostsDomain": "النطاق (مثل domain:example.com)",
+        "hostsValues": "عنوان IP أو نطاق — اكتب واضغط Enter",
+        "clearAll": "حذف الكل",
+        "clearAllTitle": "حذف جميع خوادم DNS؟",
+        "clearAllConfirm": "سيؤدي هذا إلى إزالة جميع خوادم DNS من القائمة. لا يمكن التراجع عن هذا الإجراء."
       },
       "fakedns": {
         "add": "أضف Fake DNS",

+ 16 - 1
web/translation/en-US.json

@@ -752,9 +752,24 @@
         "unexpectIPs": "Unexpect IPs",
         "useSystemHosts": "Use System Hosts",
         "useSystemHostsDesc": "Use the hosts file from an installed system",
+        "serveStale": "Serve Stale",
+        "serveStaleDesc": "Return expired cached results while refreshing in the background",
+        "serveExpiredTTL": "Serve Expired TTL",
+        "serveExpiredTTLDesc": "Validity (seconds) of stale cache entries; 0 = never expire",
+        "timeoutMs": "Timeout (ms)",
+        "skipFallback": "Skip Fallback",
+        "finalQuery": "Final Query",
+        "hosts": "Hosts",
+        "hostsAdd": "Add Host",
+        "hostsEmpty": "No host overrides defined",
+        "hostsDomain": "Domain (e.g. domain:example.com)",
+        "hostsValues": "IP or domain — type and press Enter",
         "usePreset": "Use Preset",
         "dnsPresetTitle": "DNS Presets",
-        "dnsPresetFamily": "Family"
+        "dnsPresetFamily": "Family",
+        "clearAll": "Delete All",
+        "clearAllTitle": "Delete all DNS servers?",
+        "clearAllConfirm": "This removes every DNS server from the list. This cannot be undone."
       },
       "fakedns": {
         "add": "Add Fake DNS",

+ 17 - 1
web/translation/es-ES.json

@@ -94,6 +94,7 @@
     "ultraDark": "Ultra Oscuro",
     "dashboard": "Estado del Sistema",
     "inbounds": "Entradas",
+    "nodes": "Nodos",
     "settings": "Configuraciones",
     "xray": "Ajustes Xray",
     "logout": "Cerrar Sesión",
@@ -753,7 +754,22 @@
         "useSystemHostsDesc": "Usar el archivo hosts de un sistema instalado",
         "usePreset": "Usar plantilla",
         "dnsPresetTitle": "Plantillas DNS",
-        "dnsPresetFamily": "Familiar"
+        "dnsPresetFamily": "Familiar",
+        "serveStale": "Servir caducados",
+        "serveStaleDesc": "Devolver resultados caducados de la caché mientras se actualiza en segundo plano",
+        "serveExpiredTTL": "TTL de caducados",
+        "serveExpiredTTLDesc": "Validez (segundos) de las entradas caducadas en la caché; 0 = nunca caduca",
+        "timeoutMs": "Tiempo de espera (ms)",
+        "skipFallback": "Omitir respaldo",
+        "finalQuery": "Consulta final",
+        "hosts": "Hosts",
+        "hostsAdd": "Agregar Host",
+        "hostsEmpty": "No hay Hosts definidos",
+        "hostsDomain": "Dominio (ej. domain:example.com)",
+        "hostsValues": "IP o dominio — escribe y presiona Enter",
+        "clearAll": "Eliminar todos",
+        "clearAllTitle": "¿Eliminar todos los servidores DNS?",
+        "clearAllConfirm": "Esto eliminará todos los servidores DNS de la lista. No se puede deshacer."
       },
       "fakedns": {
         "add": "Agregar DNS Falso",

+ 16 - 1
web/translation/fa-IR.json

@@ -752,9 +752,24 @@
         "unexpectIPs": "آی‌پی‌های غیرمنتظره",
         "useSystemHosts": "استفاده از Hosts سیستم",
         "useSystemHostsDesc": "استفاده از فایل hosts یک سیستم نصب‌شده",
+        "serveStale": "ارائه نتایج منقضی",
+        "serveStaleDesc": "بازگرداندن نتایج منقضی کش هنگام بروزرسانی در پس‌زمینه",
+        "serveExpiredTTL": "TTL نتایج منقضی",
+        "serveExpiredTTLDesc": "مدت اعتبار نتایج منقضی به ثانیه؛ ۰ یعنی هرگز منقضی نمی‌شود",
+        "timeoutMs": "زمان انتظار (میلی‌ثانیه)",
+        "skipFallback": "رد کردن Fallback",
+        "finalQuery": "پرس‌وجوی نهایی",
+        "hosts": "Hosts",
+        "hostsAdd": "افزودن Host",
+        "hostsEmpty": "هیچ Host تعریف نشده",
+        "hostsDomain": "دامنه (مثلاً domain:example.com)",
+        "hostsValues": "آی‌پی یا دامنه — تایپ کنید و Enter بزنید",
         "usePreset": "استفاده از پیش‌تنظیم",
         "dnsPresetTitle": "پیش‌تنظیم‌های DNS",
-        "dnsPresetFamily": "خانوادگی"
+        "dnsPresetFamily": "خانوادگی",
+        "clearAll": "حذف همه",
+        "clearAllTitle": "حذف همه سرورهای DNS؟",
+        "clearAllConfirm": "این کار همه سرورهای DNS را از لیست حذف می‌کند و قابل بازگشت نیست."
       },
       "fakedns": {
         "add": "افزودن دی‌ان‌اس جعلی",

+ 17 - 1
web/translation/id-ID.json

@@ -94,6 +94,7 @@
     "ultraDark": "Sangat Gelap",
     "dashboard": "Ikhtisar",
     "inbounds": "Masuk",
+    "nodes": "Node",
     "settings": "Pengaturan Panel",
     "xray": "Konfigurasi Xray",
     "logout": "Keluar",
@@ -753,7 +754,22 @@
         "useSystemHostsDesc": "Gunakan file hosts dari sistem yang terinstal",
         "usePreset": "Gunakan templat",
         "dnsPresetTitle": "Templat DNS",
-        "dnsPresetFamily": "Keluarga"
+        "dnsPresetFamily": "Keluarga",
+        "serveStale": "Sajikan Kedaluwarsa",
+        "serveStaleDesc": "Mengembalikan hasil cache yang kedaluwarsa saat memperbarui di latar belakang",
+        "serveExpiredTTL": "TTL Kedaluwarsa",
+        "serveExpiredTTLDesc": "Masa berlaku (detik) entri cache kedaluwarsa; 0 = tidak pernah kedaluwarsa",
+        "timeoutMs": "Batas waktu (ms)",
+        "skipFallback": "Lewati Fallback",
+        "finalQuery": "Kueri Akhir",
+        "hosts": "Hosts",
+        "hostsAdd": "Tambah Host",
+        "hostsEmpty": "Tidak ada Host yang ditentukan",
+        "hostsDomain": "Domain (mis. domain:example.com)",
+        "hostsValues": "IP atau domain — ketik dan tekan Enter",
+        "clearAll": "Hapus Semua",
+        "clearAllTitle": "Hapus semua server DNS?",
+        "clearAllConfirm": "Ini akan menghapus semua server DNS dari daftar. Tidak dapat dibatalkan."
       },
       "fakedns": {
         "add": "Tambahkan DNS Palsu",

+ 17 - 1
web/translation/ja-JP.json

@@ -94,6 +94,7 @@
     "ultraDark": "ウルトラダーク",
     "dashboard": "ダッシュボード",
     "inbounds": "インバウンド一覧",
+    "nodes": "ノード",
     "settings": "パネル設定",
     "xray": "Xray設定",
     "logout": "ログアウト",
@@ -753,7 +754,22 @@
         "useSystemHostsDesc": "インストール済みシステムのhostsファイルを使用する",
         "usePreset": "テンプレートを使用",
         "dnsPresetTitle": "DNSテンプレート",
-        "dnsPresetFamily": "ファミリー"
+        "dnsPresetFamily": "ファミリー",
+        "serveStale": "期限切れキャッシュを使用",
+        "serveStaleDesc": "バックグラウンドで更新中に期限切れキャッシュ結果を返す",
+        "serveExpiredTTL": "期限切れTTL",
+        "serveExpiredTTLDesc": "期限切れキャッシュエントリの有効期間(秒)。0 = 無期限",
+        "timeoutMs": "タイムアウト (ms)",
+        "skipFallback": "フォールバックをスキップ",
+        "finalQuery": "最終クエリ",
+        "hosts": "Hosts",
+        "hostsAdd": "Host を追加",
+        "hostsEmpty": "Host が定義されていません",
+        "hostsDomain": "ドメイン (例: domain:example.com)",
+        "hostsValues": "IP またはドメイン — 入力して Enter",
+        "clearAll": "すべて削除",
+        "clearAllTitle": "すべての DNS サーバを削除しますか?",
+        "clearAllConfirm": "リストからすべての DNS サーバが削除されます。この操作は元に戻せません。"
       },
       "fakedns": {
         "add": "フェイクDNS追加",

+ 17 - 1
web/translation/pt-BR.json

@@ -94,6 +94,7 @@
     "ultraDark": "Ultra Escuro",
     "dashboard": "Visão Geral",
     "inbounds": "Inbounds",
+    "nodes": "Nós",
     "settings": "Panel Settings",
     "xray": "Xray Configs",
     "logout": "Sair",
@@ -753,7 +754,22 @@
         "useSystemHostsDesc": "Usar o arquivo hosts de um sistema instalado",
         "usePreset": "Usar modelo",
         "dnsPresetTitle": "Modelos DNS",
-        "dnsPresetFamily": "Familiar"
+        "dnsPresetFamily": "Familiar",
+        "serveStale": "Servir Expirados",
+        "serveStaleDesc": "Retornar resultados expirados do cache enquanto atualiza em segundo plano",
+        "serveExpiredTTL": "TTL de Expirados",
+        "serveExpiredTTLDesc": "Validade (segundos) das entradas expiradas no cache; 0 = nunca expira",
+        "timeoutMs": "Tempo limite (ms)",
+        "skipFallback": "Ignorar Fallback",
+        "finalQuery": "Consulta Final",
+        "hosts": "Hosts",
+        "hostsAdd": "Adicionar Host",
+        "hostsEmpty": "Nenhum Host definido",
+        "hostsDomain": "Domínio (ex. domain:example.com)",
+        "hostsValues": "IP ou domínio — digite e pressione Enter",
+        "clearAll": "Remover Todos",
+        "clearAllTitle": "Remover todos os servidores DNS?",
+        "clearAllConfirm": "Isso remove todos os servidores DNS da lista. Não pode ser desfeito."
       },
       "fakedns": {
         "add": "Adicionar Fake DNS",

+ 17 - 1
web/translation/ru-RU.json

@@ -94,6 +94,7 @@
     "ultraDark": "Очень темная",
     "dashboard": "Дашборд",
     "inbounds": "Подключения",
+    "nodes": "Узлы",
     "settings": "Настройки",
     "xray": "Настройки Xray",
     "logout": "Выход",
@@ -753,7 +754,22 @@
         "useSystemHostsDesc": "Использовать файл hosts из установленной системы",
         "usePreset": "Использовать шаблон",
         "dnsPresetTitle": "Шаблоны DNS",
-        "dnsPresetFamily": "Семейный"
+        "dnsPresetFamily": "Семейный",
+        "serveStale": "Использовать устаревшие",
+        "serveStaleDesc": "Возвращать устаревшие результаты из кэша во время обновления в фоне",
+        "serveExpiredTTL": "TTL устаревших",
+        "serveExpiredTTLDesc": "Срок действия (секунды) устаревших записей кэша; 0 = бессрочно",
+        "timeoutMs": "Тайм-аут (мс)",
+        "skipFallback": "Пропустить Fallback",
+        "finalQuery": "Финальный запрос",
+        "hosts": "Hosts",
+        "hostsAdd": "Добавить Host",
+        "hostsEmpty": "Host не определены",
+        "hostsDomain": "Домен (напр. domain:example.com)",
+        "hostsValues": "IP или домен — введите и нажмите Enter",
+        "clearAll": "Удалить все",
+        "clearAllTitle": "Удалить все DNS-серверы?",
+        "clearAllConfirm": "Все DNS-серверы будут удалены из списка. Это действие нельзя отменить."
       },
       "fakedns": {
         "add": "Создать Fake DNS",

+ 17 - 1
web/translation/tr-TR.json

@@ -94,6 +94,7 @@
     "ultraDark": "Ultra Koyu",
     "dashboard": "Genel Bakış",
     "inbounds": "Gelenler",
+    "nodes": "Düğümler",
     "settings": "Panel Ayarları",
     "xray": "Xray Yapılandırmaları",
     "logout": "Çıkış Yap",
@@ -753,7 +754,22 @@
         "useSystemHostsDesc": "Yüklü bir sistemden hosts dosyasını kullan",
         "usePreset": "Şablon kullan",
         "dnsPresetTitle": "DNS Şablonları",
-        "dnsPresetFamily": "Aile"
+        "dnsPresetFamily": "Aile",
+        "serveStale": "Süresi Dolmuş Sonuçları Sun",
+        "serveStaleDesc": "Arka planda yenilenirken süresi dolmuş önbellek sonuçlarını döndür",
+        "serveExpiredTTL": "Süresi Dolmuş TTL",
+        "serveExpiredTTLDesc": "Süresi dolmuş önbellek girdilerinin geçerlilik süresi (saniye); 0 = asla",
+        "timeoutMs": "Zaman aşımı (ms)",
+        "skipFallback": "Yedekleri Atla",
+        "finalQuery": "Son Sorgu",
+        "hosts": "Hosts",
+        "hostsAdd": "Host Ekle",
+        "hostsEmpty": "Tanımlı Host yok",
+        "hostsDomain": "Alan adı (ör. domain:example.com)",
+        "hostsValues": "IP veya alan adı — yazıp Enter'a basın",
+        "clearAll": "Tümünü Sil",
+        "clearAllTitle": "Tüm DNS sunucularını sil?",
+        "clearAllConfirm": "Bu, tüm DNS sunucularını listeden kaldırır. Geri alınamaz."
       },
       "fakedns": {
         "add": "Sahte DNS Ekle",

+ 17 - 1
web/translation/uk-UA.json

@@ -94,6 +94,7 @@
     "ultraDark": "Ультра темна",
     "dashboard": "Огляд",
     "inbounds": "Вхідні",
+    "nodes": "Вузли",
     "settings": "Параметри панелі",
     "xray": "Конфігурації Xray",
     "logout": "Вийти",
@@ -753,7 +754,22 @@
         "useSystemHostsDesc": "Використовувати файл hosts з встановленої системи",
         "usePreset": "Використати шаблон",
         "dnsPresetTitle": "Шаблони DNS",
-        "dnsPresetFamily": "Сімейний"
+        "dnsPresetFamily": "Сімейний",
+        "serveStale": "Видавати застарілі",
+        "serveStaleDesc": "Повертати застарілі результати з кешу під час фонового оновлення",
+        "serveExpiredTTL": "TTL застарілих",
+        "serveExpiredTTLDesc": "Термін дії (секунди) застарілих записів кешу; 0 = ніколи",
+        "timeoutMs": "Тайм-аут (мс)",
+        "skipFallback": "Пропустити Fallback",
+        "finalQuery": "Фінальний запит",
+        "hosts": "Hosts",
+        "hostsAdd": "Додати Host",
+        "hostsEmpty": "Host не визначено",
+        "hostsDomain": "Домен (напр. domain:example.com)",
+        "hostsValues": "IP або домен — введіть і натисніть Enter",
+        "clearAll": "Видалити всі",
+        "clearAllTitle": "Видалити всі DNS-сервери?",
+        "clearAllConfirm": "Усі DNS-сервери буде видалено зі списку. Дію не можна скасувати."
       },
       "fakedns": {
         "add": "Додати підроблений DNS",

+ 17 - 1
web/translation/vi-VN.json

@@ -94,6 +94,7 @@
     "ultraDark": "Siêu tối",
     "dashboard": "Trạng thái hệ thống",
     "inbounds": "Đầu vào khách hàng",
+    "nodes": "Nút",
     "settings": "Cài đặt bảng điều khiển",
     "logout": "Đăng xuất",
     "xray": "Cài đặt Xray",
@@ -753,7 +754,22 @@
         "useSystemHostsDesc": "Sử dụng file hosts từ hệ thống đã cài đặt",
         "usePreset": "Dùng mẫu",
         "dnsPresetTitle": "Mẫu DNS",
-        "dnsPresetFamily": "Gia đình"
+        "dnsPresetFamily": "Gia đình",
+        "serveStale": "Phục vụ kết quả hết hạn",
+        "serveStaleDesc": "Trả về kết quả cache đã hết hạn trong khi làm mới ở chế độ nền",
+        "serveExpiredTTL": "TTL hết hạn",
+        "serveExpiredTTLDesc": "Thời gian hiệu lực (giây) của các mục cache hết hạn; 0 = không bao giờ hết hạn",
+        "timeoutMs": "Thời gian chờ (ms)",
+        "skipFallback": "Bỏ qua Fallback",
+        "finalQuery": "Truy vấn cuối",
+        "hosts": "Hosts",
+        "hostsAdd": "Thêm Host",
+        "hostsEmpty": "Chưa có Host nào",
+        "hostsDomain": "Tên miền (vd. domain:example.com)",
+        "hostsValues": "IP hoặc tên miền — nhập và nhấn Enter",
+        "clearAll": "Xóa tất cả",
+        "clearAllTitle": "Xóa tất cả máy chủ DNS?",
+        "clearAllConfirm": "Thao tác này sẽ xóa toàn bộ máy chủ DNS khỏi danh sách. Không thể hoàn tác."
       },
       "fakedns": {
         "add": "Thêm DNS giả",

+ 17 - 1
web/translation/zh-CN.json

@@ -94,6 +94,7 @@
     "ultraDark": "超暗色",
     "dashboard": "系统状态",
     "inbounds": "入站列表",
+    "nodes": "节点",
     "settings": "面板设置",
     "xray": "Xray 设置",
     "logout": "退出登录",
@@ -753,7 +754,22 @@
         "useSystemHostsDesc": "使用已安装系统的hosts文件",
         "usePreset": "使用模板",
         "dnsPresetTitle": "DNS模板",
-        "dnsPresetFamily": "家庭"
+        "dnsPresetFamily": "家庭",
+        "serveStale": "提供过期结果",
+        "serveStaleDesc": "在后台刷新时返回过期的缓存结果",
+        "serveExpiredTTL": "过期TTL",
+        "serveExpiredTTLDesc": "过期缓存条目的有效期(秒);0 = 永不过期",
+        "timeoutMs": "超时 (毫秒)",
+        "skipFallback": "跳过回退",
+        "finalQuery": "最终查询",
+        "hosts": "Hosts",
+        "hostsAdd": "添加 Host",
+        "hostsEmpty": "未定义任何 Host",
+        "hostsDomain": "域名 (例如 domain:example.com)",
+        "hostsValues": "IP 或域名 — 输入后按 Enter",
+        "clearAll": "删除全部",
+        "clearAllTitle": "删除所有 DNS 服务器?",
+        "clearAllConfirm": "此操作将从列表中删除所有 DNS 服务器,且无法撤销。"
       },
       "fakedns": {
         "add": "添加假 DNS",

+ 17 - 1
web/translation/zh-TW.json

@@ -94,6 +94,7 @@
     "ultraDark": "超深色",
     "dashboard": "系統狀態",
     "inbounds": "入站列表",
+    "nodes": "節點",
     "settings": "面板設定",
     "xray": "Xray 設定",
     "logout": "退出登入",
@@ -753,7 +754,22 @@
         "useSystemHostsDesc": "使用已安裝系統的hosts檔案",
         "usePreset": "使用範本",
         "dnsPresetTitle": "DNS範本",
-        "dnsPresetFamily": "家庭"
+        "dnsPresetFamily": "家庭",
+        "serveStale": "提供過期結果",
+        "serveStaleDesc": "在背景重新整理時傳回過期的快取結果",
+        "serveExpiredTTL": "過期TTL",
+        "serveExpiredTTLDesc": "過期快取項目的有效期(秒);0 = 永不過期",
+        "timeoutMs": "逾時 (毫秒)",
+        "skipFallback": "跳過回退",
+        "finalQuery": "最終查詢",
+        "hosts": "Hosts",
+        "hostsAdd": "新增 Host",
+        "hostsEmpty": "未定義任何 Host",
+        "hostsDomain": "網域 (例如 domain:example.com)",
+        "hostsValues": "IP 或網域 — 輸入後按 Enter",
+        "clearAll": "全部刪除",
+        "clearAllTitle": "刪除所有 DNS 伺服器?",
+        "clearAllConfirm": "此操作將從清單中刪除所有 DNS 伺服器,無法復原。"
       },
       "fakedns": {
         "add": "新增假 DNS",

+ 6 - 7
web/web.go

@@ -280,19 +280,15 @@ func (s *Server) startTask() {
 
 	go func() {
 		time.Sleep(time.Second * 5)
-		// Statistics every 10 seconds, start the delay for 5 seconds for the first time, and staggered with the time to restart xray
-		s.cron.AddJob("@every 10s", job.NewXrayTrafficJob())
+		s.cron.AddJob("@every 5s", job.NewXrayTrafficJob())
 	}()
 
 	// check client ips from log file every 10 sec
 	s.cron.AddJob("@every 10s", job.NewCheckClientIpJob())
 
-	// Probe every enabled remote node every 10 sec
-	s.cron.AddJob("@every 10s", job.NewNodeHeartbeatJob())
+	s.cron.AddJob("@every 5s", job.NewNodeHeartbeatJob())
 
-	// Pull traffic + online-clients from every online node every 10 sec
-	// and merge absolute counters into the central DB.
-	s.cron.AddJob("@every 10s", job.NewNodeTrafficSyncJob())
+	s.cron.AddJob("@every 5s", job.NewNodeTrafficSyncJob())
 
 	// check client ips from log file every day
 	s.cron.AddJob("@daily", job.NewClearLogsJob())
@@ -363,6 +359,8 @@ func (s *Server) Start() (err error) {
 	if err != nil {
 		return err
 	}
+	service.StartTrafficWriter()
+
 	s.cron = cron.New(cron.WithLocation(loc), cron.WithSeconds())
 	s.cron.Start()
 
@@ -447,6 +445,7 @@ func (s *Server) Stop() error {
 	if s.cron != nil {
 		s.cron.Stop()
 	}
+	service.StopTrafficWriter()
 	if s.tgbotService.IsRunning() {
 		s.tgbotService.Stop()
 	}

+ 6 - 12
web/websocket/hub.go

@@ -43,8 +43,8 @@ const (
 	// rapid mutations cannot drown the hub. Bursts within the interval are
 	// dropped (not coalesced); the next broadcast outside the window delivers
 	// the latest state. Only message types in throttledMessageTypes are gated —
-	// heartbeat and real-time signals (status, traffic, client_stats,
-	// notification, xray_state, invalidate) bypass this so they are never delayed.
+	// heartbeat and one-shot signals (status, notification, xray_state,
+	// invalidate) bypass this so they are never delayed.
 	minBroadcastInterval = 250 * time.Millisecond
 
 	// hubRestartAttempts caps panic-recovery restarts. After this many
@@ -103,19 +103,13 @@ func NewHub() *Hub {
 	}
 }
 
-// throttledMessageTypes is the explicit allow-list of message types subject to
-// the per-type rate limit. Everything else (status, traffic, client_stats,
-// notification, xray_state, invalidate) is heartbeat- or signal-class and must
-// not be delayed. Keeping the set explicit (vs. an exclusion list) makes the
-// intent obvious when new message types are added — by default they bypass.
 var throttledMessageTypes = map[MessageType]struct{}{
-	MessageTypeInbounds:  {},
-	MessageTypeOutbounds: {},
+	MessageTypeInbounds:    {},
+	MessageTypeOutbounds:   {},
+	MessageTypeTraffic:     {},
+	MessageTypeClientStats: {},
 }
 
-// shouldThrottle returns true if a broadcast of msgType is rate-limited and
-// happened within minBroadcastInterval of the previous one. Only message types
-// in throttledMessageTypes are gated.
 func (h *Hub) shouldThrottle(msgType MessageType) bool {
 	if _, gated := throttledMessageTypes[msgType]; !gated {
 		return false

+ 2 - 2
x-ui.service.arch

@@ -7,8 +7,8 @@ Wants=network.target
 EnvironmentFile=-/etc/conf.d/x-ui
 Environment="XRAY_VMESS_AEAD_FORCED=false"
 Type=simple
-WorkingDirectory=/usr/lib/x-ui/
-ExecStart=/usr/lib/x-ui/x-ui
+WorkingDirectory=/usr/local/x-ui/
+ExecStart=/usr/local/x-ui/x-ui
 ExecReload=kill -USR1 $MAINPID
 Restart=on-failure
 RestartSec=5s

+ 2 - 2
x-ui.sh

@@ -2109,10 +2109,10 @@ actionstop = <iptables> -D <chain> -p <protocol> -j f2b-<name>
 actioncheck = <iptables> -n -L <chain> | grep -q 'f2b-<name>[ \t]'
 
 actionban = <iptables> -I f2b-<name> 1 -s <ip> -j <blocktype>
-            echo "\$(date +"%Y/%m/%d %H:%M:%S")   BAN   [Email] = <F-USER> [IP] = <ip> banned for <bantime> seconds." >> ${iplimit_banned_log_path}
+            echo "\$(date +"%%Y/%%m/%%d %%H:%%M:%%S")   BAN   [Email] = <F-USER> [IP] = <ip> banned for <bantime> seconds." >> ${iplimit_banned_log_path}
 
 actionunban = <iptables> -D f2b-<name> -s <ip> -j <blocktype>
-              echo "\$(date +"%Y/%m/%d %H:%M:%S")   UNBAN   [Email] = <F-USER> [IP] = <ip> unbanned." >> ${iplimit_banned_log_path}
+              echo "\$(date +"%%Y/%%m/%%d %%H:%%M:%%S")   UNBAN   [Email] = <F-USER> [IP] = <ip> unbanned." >> ${iplimit_banned_log_path}
 
 [Init]
 name = default

+ 2 - 3
xray/process.go

@@ -5,7 +5,6 @@ import (
 	"encoding/json"
 	"errors"
 	"fmt"
-	"io/fs"
 	"os"
 	"os/exec"
 	"runtime"
@@ -321,7 +320,7 @@ func (p *process) Start() (err error) {
 	if p.configPath != "" {
 		configPath = p.configPath
 	}
-	err = os.WriteFile(configPath, data, fs.ModePerm)
+	err = os.WriteFile(configPath, data, 0644)
 	if err != nil {
 		return common.NewErrorf("Failed to write configuration file: %v", err)
 	}
@@ -381,5 +380,5 @@ func (p *process) Stop() error {
 // writeCrashReport writes a crash report to the binary folder with a timestamped filename.
 func writeCrashReport(m []byte) error {
 	crashReportPath := config.GetBinFolderPath() + "/core_crash_" + time.Now().Format("20060102_150405") + ".log"
-	return os.WriteFile(crashReportPath, m, os.ModePerm)
+	return os.WriteFile(crashReportPath, m, 0644)
 }