Skip to content

A modern and elegant dashboard for network traffic visualization and analysis.

feat: Enhance service worker caching and WebSocket connection robustness, and refine UI component displays.

luolei2429a144e578
diff --git a/README.en.md b/README.en.md
index 2b25545..c068fc2 100644
--- a/README.en.md
+++ b/README.en.md
@@ -33,6 +33,7 @@
- [📖 First Use](#-first-use)
- [🔧 Port Conflict Resolution](#-port-conflict-resolution)
- [🐳 Docker Configuration](#-docker-configuration)
+- [🌐 Reverse Proxy & Tunnel](#-reverse-proxy--tunnel)
- [❓ FAQ](#-faq)
- [📁 Project Structure](#-project-structure)
- [🛠️ Tech Stack](#️-tech-stack)
@@ -56,7 +57,7 @@
### Option 1: Docker Compose (Recommended)
-Create a `docker-compose.yml` file:
+#### Scenario A: Minimal deployment (only expose 3000)
```yaml
services:
@@ -66,16 +67,31 @@ services:
restart: unless-stopped
ports:
- "3000:3000" # Web UI
- - "3001:3001" # API
- - "3002:3002" # WebSocket
volumes:
- ./data:/app/data
environment:
- NODE_ENV=production
- # External ports (optional; defaults are 3000/3001/3002)
- - WEB_EXTERNAL_PORT=3000
- - API_EXTERNAL_PORT=3001
- - WS_EXTERNAL_PORT=3002
+ - DB_PATH=/app/data/stats.db
+```
+
+> This mode is fully upgrade-compatible and works out of the box.
+> If WS is not routed, the app falls back to HTTP polling automatically.
+
+#### Scenario B: Real-time WebSocket (recommended with reverse proxy)
+
+```yaml
+services:
+ clash-master:
+ image: foru17/clash-master:latest
+ container_name: clash-master
+ restart: unless-stopped
+ ports:
+ - "3000:3000" # Web UI
+ - "3002:3002" # WebSocket (for Nginx / Tunnel forwarding)
+ volumes:
+ - ./data:/app/data
+ environment:
+ - NODE_ENV=production
- DB_PATH=/app/data/stats.db
```
@@ -89,24 +105,19 @@ Open <http://localhost:3000> to get started.
### Option 2: Docker Run
-**Minimal (recommended, only Web exposed):**
-
```bash
+# Minimal (only 3000)
docker run -d \
--name clash-master \
-p 3000:3000 \
-v $(pwd)/data:/app/data \
--restart unless-stopped \
foru17/clash-master:latest
-```
-
-**Optional (only if you need direct API / WebSocket access):**
-```bash
+# Real-time WS (with reverse proxy)
docker run -d \
--name clash-master \
-p 3000:3000 \
- -p 3001:3001 \
-p 3002:3002 \
-v $(pwd)/data:/app/data \
--restart unless-stopped \
@@ -115,8 +126,8 @@ docker run -d \
Open <http://localhost:3000> to get started.
-> The frontend uses same-origin `/api` by default, so only port 3000 is required.
-> Only expose 3001/3002 if you need direct API/WS access or do not proxy `/api`/`/ws` in Nginx.
+> The frontend uses same-origin `/api` by default, so port 3001 is usually not required externally.
+> For real-time WS, your reverse proxy/tunnel must be able to reach port `3002`. If not, the app falls back to ~5s HTTP polling.
> If you use custom external ports with `docker run`, also pass:
> `-e WEB_EXTERNAL_PORT=8080 -e API_EXTERNAL_PORT=8081 -e WS_EXTERNAL_PORT=8082`
@@ -183,7 +194,7 @@ Create a `.env` file in the same directory as `docker-compose.yml`:
```env
WEB_EXTERNAL_PORT=8080 # Change Web UI port
API_EXTERNAL_PORT=8081 # Change API port
-WS_EXTERNAL_PORT=8082 # Change WebSocket port
+WS_EXTERNAL_PORT=8082 # Change WebSocket external port (only for direct access)
```
Then restart:
@@ -200,8 +211,7 @@ Now access <http://localhost:8080>
```yaml
ports:
- "8080:3000" # External 8080 → Internal 3000
- - "8081:3001" # External 8081 → Internal 3001
- - "8082:3002" # External 8082 → Internal 3002
+ - "8082:3002" # External 8082 → Internal 3002 (for proxy/tunnel WS forwarding)
```
> Note: the frontend reads external ports at runtime, so `NEXT_PUBLIC_WS_PORT` is no longer required.
@@ -221,11 +231,106 @@ The script will automatically detect and suggest available ports.
| Port | Purpose | External Required | Description |
| :--: | :-------: | :---------------: | :---------- |
| 3000 | Web UI | ✅ | Frontend entry point |
-| 3001 | API | Optional | Only needed for direct access/debug; frontend uses `/api` by default |
-| 3002 | WebSocket | Optional | Real-time updates; can be proxied via Nginx `/ws` |
+| 3001 | API | Optional | Frontend uses same-origin `/api` by default; usually no external exposure needed |
+| 3002 | WebSocket | Optional | Real-time push endpoint; recommended to forward via reverse proxy/tunnel |
+
+### Environment Variables (Docker)
+
+| Variable | Default | Purpose | When to set |
+| :-- | :-- | :-- | :-- |
+| `WEB_PORT` | `3000` | Web service listen port (inside container) | Usually unchanged |
+| `API_PORT` | `3001` | API service listen port (inside container) | Usually unchanged |
+| `COLLECTOR_WS_PORT` | `3002` | WS service listen port (inside container) | Usually unchanged |
+| `DB_PATH` | `/app/data/stats.db` | SQLite data path | Custom data path |
+| `WEB_EXTERNAL_PORT` | `3000` | Runtime-exposed external web port | When external mapping changes |
+| `API_EXTERNAL_PORT` | `3001` | Runtime-exposed external API port | Only for direct API access |
+| `WS_EXTERNAL_PORT` | `3002` | Runtime-exposed external WS port | Only for direct WS access |
+| `NEXT_PUBLIC_API_URL` | empty | Override frontend API base URL | When API is not same-origin |
+| `NEXT_PUBLIC_WS_URL` | auto `/_cm_ws` | Override frontend WS URL | Only if you want custom WS path/host |
+
+### API / WS Resolution Priority
+
+1. API: `runtime-config(API_URL)` → `NEXT_PUBLIC_API_URL` → same-origin `/api`
+2. WS: `runtime-config(WS_URL)` → `NEXT_PUBLIC_WS_URL` → auto detection
+3. Default already uses same-origin `/_cm_ws`; no manual env required for normal deployments
+
+## 🌐 Reverse Proxy & Tunnel
+
+Recommended approach: keep Web and WS under the same domain, with path routing:
+`/` → `3000`, `/_cm_ws` → `3002`.
+
+### Nginx Standard Example
+
+```nginx
+server {
+ listen 443 ssl http2;
+ server_name clash.example.com;
+
+ location / {
+ proxy_pass http://<clash-master-host>:3000;
+ proxy_http_version 1.1;
+ proxy_set_header Host $host;
+ proxy_set_header X-Real-IP $remote_addr;
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ }
+
+ location ^~ /_cm_ws {
+ proxy_pass http://<clash-master-host>:3002;
+ proxy_http_version 1.1;
+ proxy_set_header Upgrade $http_upgrade;
+ proxy_set_header Connection "upgrade";
+ proxy_set_header Host $host;
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ proxy_read_timeout 86400;
+ proxy_send_timeout 86400;
+ proxy_buffering off;
+ }
+}
+```
-> You only need to reverse-proxy the Web UI in Nginx. The frontend uses same-origin `/api` by default,
-> so 3001/3002 do not need to be exposed or configured unless you want direct API/WS access.
+Optional env override:
+
+```env
+# Not required by default (already /_cm_ws)
+# NEXT_PUBLIC_WS_URL=/custom_ws
+```
+
+### Cloudflare Tunnel Standard Example
+
+`~/.cloudflared/config.yml`:
+
+```yaml
+tunnel: <your-tunnel-name-or-id>
+credentials-file: /path/to/<credentials>.json
+
+ingress:
+ - hostname: clash.example.com
+ path: /_cm_ws*
+ service: http://localhost:3002
+ - hostname: clash.example.com
+ path: /*
+ service: http://localhost:3000
+ - service: http_status:404
+```
+
+Run:
+
+```bash
+cloudflared tunnel --config ~/.cloudflared/config.yml run <your-tunnel-name-or-id>
+```
+
+For Zero Trust dashboard-managed routes (token mode), configure the same two routes and keep `/_cm_ws*` above `/*`.
+
+### Key Notes
+
+1. Do not use `ws` (without leading slash) as WS path; it can overmatch and cause `/_next/static/...` → `426 Upgrade Required`
+2. WS route must be above catch-all `/*`
+3. `NEXT_PUBLIC_WS_URL` is optional by default; if customized, restart frontend/container after changes
+4. Mapping only `3000` still works, but falls back to HTTP polling (~5s), with less real-time responsiveness
+5. `beacon.min.js` failures (Cloudflare analytics script) are typically unrelated to app API/WS data flow
+6. No extra `/api` reverse-proxy rule is required in most setups; frontend uses same-origin `/api` and app handles internal forwarding to `3001`
### Multi-Architecture Support
@@ -262,6 +367,24 @@ docker compose up -d
2. Service is restarted: `docker compose restart`
3. You're using the new port (e.g., `http://localhost:8080`)
+### Q: Will upgrading break users who only expose `3000:3000`?
+
+**A:** No. Core functionality remains available.
+If WS is not routed, the app automatically falls back to HTTP polling.
+
+### Q: If WS forwarding is not configured, will it affect usage?
+
+**A:** Core features and data display still work.
+The difference is real-time experience: without WS, updates are polling-based (about every 5 seconds).
+
+### Q: Why do I see `/_next/static/... 426 Upgrade Required`?
+
+**A:** WS route matching is usually too broad and static assets are being forwarded to the WS port. Check:
+
+1. In Cloudflare Tunnel / Nginx, do not use `ws` as path; use `/_cm_ws*`
+2. WS route priority must be above `/*`
+3. If `NEXT_PUBLIC_WS_URL` is manually set, ensure it matches your proxy path (for example `/_cm_ws`)
+
### Q: Failed to connect to OpenClash?
**A:** Check the following:
diff --git a/README.md b/README.md
index d384945..6f2e830 100644
--- a/README.md
+++ b/README.md
@@ -32,6 +32,7 @@
- [📖 首次使用](#-首次使用)
- [🔧 端口冲突解决](#-端口冲突解决)
- [🐳 Docker 配置](#-docker-配置)
+- [🌐 反向代理与 Tunnel](#-反向代理与-tunnel)
- [❓ 常见问题](#-常见问题)
- [📁 项目结构](#-项目结构)
- [🛠️ 技术栈](#️-技术栈)
@@ -41,7 +42,7 @@
### 方式一:Docker Compose(推荐)
-创建 `docker-compose.yml`:
+#### 场景 A:最简部署(仅暴露 3000)
```yaml
services:
@@ -51,16 +52,31 @@ services:
restart: unless-stopped
ports:
- "3000:3000" # Web UI
- - "3001:3001" # API
- - "3002:3002" # WebSocket
volumes:
- ./data:/app/data
environment:
- NODE_ENV=production
- # 外部端口(可选,默认即为 3000/3001/3002)
- - WEB_EXTERNAL_PORT=3000
- - API_EXTERNAL_PORT=3001
- - WS_EXTERNAL_PORT=3002
+ - DB_PATH=/app/data/stats.db
+```
+
+> 该模式完全兼容升级,页面可用。
+> 未打通 WS 时会自动回退到 HTTP 轮询刷新。
+
+#### 场景 B:实时 WebSocket(推荐,配合反向代理)
+
+```yaml
+services:
+ clash-master:
+ image: foru17/clash-master:latest
+ container_name: clash-master
+ restart: unless-stopped
+ ports:
+ - "3000:3000" # Web UI
+ - "3002:3002" # WebSocket(供 Nginx / Tunnel 转发)
+ volumes:
+ - ./data:/app/data
+ environment:
+ - NODE_ENV=production
- DB_PATH=/app/data/stats.db
```
@@ -75,33 +91,26 @@ docker compose up -d
### 方式二:Docker 直接运行
```bash
-**最简(推荐,仅 Web 反代):**
-
-```bash
+# 最简(仅 3000)
docker run -d \
--name clash-master \
-p 3000:3000 \
-v $(pwd)/data:/app/data \
--restart unless-stopped \
foru17/clash-master:latest
-```
-
-**可选(直连 API / WebSocket 时才需要):**
-```bash
+# 实时 WS(配合反代)
docker run -d \
--name clash-master \
-p 3000:3000 \
- -p 3001:3001 \
-p 3002:3002 \
-v $(pwd)/data:/app/data \
--restart unless-stopped \
foru17/clash-master:latest
```
-> 默认前端走同域 `/api`,所以只需要暴露 3000。
-> 只有当你需要直连 API / WS 或未配置 Nginx `/api` / `/ws` 反代时,才需要暴露 3001/3002。
-```
+> 默认前端 API 走同域 `/api`,通常不需要额外暴露 3001。
+> 若希望 WebSocket 实时生效,需要让反代层可以访问 `3002`;未打通时会回退到 HTTP 轮询(约 5 秒级)。
访问 <http://localhost:3000>
@@ -170,7 +179,7 @@ pnpm dev
```env
WEB_EXTERNAL_PORT=8080 # 修改 Web UI 端口
API_EXTERNAL_PORT=8081 # 修改 API 端口
-WS_EXTERNAL_PORT=8082 # 修改 WebSocket 端口
+WS_EXTERNAL_PORT=8082 # 修改 WebSocket 外部端口(仅直连时需要)
```
然后重启:
@@ -187,8 +196,7 @@ docker compose up -d
```yaml
ports:
- "8080:3000" # 外部 8080 → 内部 3000
- - "8081:3001" # 外部 8081 → 内部 3001
- - "8082:3002" # 外部 8082 → 内部 3002
+ - "8082:3002" # 外部 8082 → 内部 3002(给反代/Tunnel 转发 WS)
```
> 说明:前端会在运行时读取外部端口配置,无需再设置 `NEXT_PUBLIC_WS_PORT`。
@@ -208,11 +216,106 @@ curl -fsSL https://raw.githubusercontent.com/foru17/clash-master/main/setup.sh |
| 端口 | 用途 | 外部必需 | 说明 |
| :--: | :-------: | :------: | :--- |
| 3000 | Web 界面 | ✅ | 前端访问入口 |
-| 3001 | API 接口 | 可选 | 仅直连/调试时需要;前端默认走 `/api` |
-| 3002 | WebSocket | 可选 | 实时数据推送;可通过 Nginx `/ws` 代理 |
+| 3001 | API 接口 | 可选 | 前端默认同域 `/api`,一般无需暴露 |
+| 3002 | WebSocket | 可选 | 实时推送端口,建议仅给反代层转发,不直接公网暴露 |
+
+### 环境变量说明(Docker)
+
+| 变量名 | 默认值 | 作用 | 何时设置 |
+| :-- | :-- | :-- | :-- |
+| `WEB_PORT` | `3000` | 前端服务监听端口(容器内) | 一般不用改 |
+| `API_PORT` | `3001` | API 服务监听端口(容器内) | 一般不用改 |
+| `COLLECTOR_WS_PORT` | `3002` | WS 服务监听端口(容器内) | 一般不用改 |
+| `DB_PATH` | `/app/data/stats.db` | SQLite 数据文件路径 | 自定义数据目录时 |
+| `WEB_EXTERNAL_PORT` | `3000` | 运行时注入给前端显示/拼接用的外部 Web 端口 | 外部映射端口变更时 |
+| `API_EXTERNAL_PORT` | `3001` | 运行时注入给前端的 API 外部端口 | 仅直连 API 时 |
+| `WS_EXTERNAL_PORT` | `3002` | 运行时注入给前端的 WS 外部端口 | 仅直连 WS 时 |
+| `NEXT_PUBLIC_API_URL` | 空 | 强制前端 API 基地址(覆盖默认 `/api`) | API 不走同域时 |
+| `NEXT_PUBLIC_WS_URL` | 自动 `/_cm_ws` | 自定义前端 WS 地址(覆盖默认) | 仅在你想改默认路径/域名时 |
+
+### API / WS 地址解析优先级
+
+1. API:`runtime-config(API_URL)` → `NEXT_PUBLIC_API_URL` → 默认同域 `/api`
+2. WS:`runtime-config(WS_URL)` → `NEXT_PUBLIC_WS_URL` → 自动推断
+3. 默认即使用同域 `/_cm_ws`,无需手动配置;仅在自定义路由时再设置 `NEXT_PUBLIC_WS_URL`
+
+## 🌐 反向代理与 Tunnel
+
+推荐将 Web 页面与 WS 都放在同一个域名下,通过不同路径转发:`/` → `3000`,`/_cm_ws` → `3002`。
+
+### Nginx 标准示例(推荐)
+
+```nginx
+server {
+ listen 443 ssl http2;
+ server_name clash.example.com;
+
+ location / {
+ proxy_pass http://<clash-master-host>:3000;
+ proxy_http_version 1.1;
+ proxy_set_header Host $host;
+ proxy_set_header X-Real-IP $remote_addr;
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ }
+
+ location ^~ /_cm_ws {
+ proxy_pass http://<clash-master-host>:3002;
+ proxy_http_version 1.1;
+ proxy_set_header Upgrade $http_upgrade;
+ proxy_set_header Connection "upgrade";
+ proxy_set_header Host $host;
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ proxy_read_timeout 86400;
+ proxy_send_timeout 86400;
+ proxy_buffering off;
+ }
+}
+```
-> 只配置主站 Web 的 Nginx 反代即可:前端默认同域访问 `/api`,无需额外暴露或配置 3001/3002。
-> 如需直连 API/WS,可设置 `API_URL` / `WS_URL`,或暴露对应端口。
+配套 Docker 环境变量:
+
+```env
+# 默认无需配置(已默认 /_cm_ws)
+# 如需自定义可设置:
+# NEXT_PUBLIC_WS_URL=/custom_ws
+```
+
+### Cloudflare Tunnel 标准示例
+
+`~/.cloudflared/config.yml`:
+
+```yaml
+tunnel: <your-tunnel-name-or-id>
+credentials-file: /path/to/<credentials>.json
+
+ingress:
+ - hostname: clash.example.com
+ path: /_cm_ws*
+ service: http://localhost:3002
+ - hostname: clash.example.com
+ path: /*
+ service: http://localhost:3000
+ - service: http_status:404
+```
+
+启动:
+
+```bash
+cloudflared tunnel --config ~/.cloudflared/config.yml run <your-tunnel-name-or-id>
+```
+
+如果使用 Zero Trust Dashboard 托管路由(token 方式),请在 Dashboard 中配置同样两条规则,并保证 `/_cm_ws*` 在 `/*` 之前。
+
+### 关键注意事项
+
+1. 不要把 WS 路径写成 `ws`(无前导 `/`),容易误匹配静态资源,导致 `/_next/static/...` 返回 `426 Upgrade Required`
+2. WS 路由必须高于 catch-all 路由(`/*`)
+3. 默认不需要配置 `NEXT_PUBLIC_WS_URL`;如你自定义了该变量,修改后需重启前端进程/容器
+4. 容器仅映射 `3000` 也能正常用,但会自动回退到 HTTP 轮询(约 5 秒级),实时性弱于 WS
+5. `beacon.min.js` 等第三方脚本失败通常不影响主数据链路(API/WS)
+6. 默认不需要单独配置 `/api` 反代:前端会同域访问 `/api` 并由应用内部转发到 `3001`
### 多架构支持
@@ -249,6 +352,24 @@ docker compose up -d
2. 重启了服务:`docker compose restart`
3. 访问时使用了新端口(如 `http://localhost:8080`)
+### Q: 从旧版升级到 WebSocket 版,只映射 `3000:3000` 会不兼容吗?
+
+**A:** 不会。页面功能仍可用,未打通 WS 时会自动回退为 HTTP 轮询。
+如需完整实时能力,请按上文配置反代路径(如 `/_cm_ws`)并将其转发到 `3002`。
+
+### Q: 如果没有配置 WS 的外部转发,会影响使用吗?
+
+**A:** 不影响核心功能和数据展示。系统会自动回退到 HTTP 轮询刷新。
+差异主要是实时体验:WS 模式更即时;未打通 WS 时刷新频率约为 5 秒级。
+
+### Q: 为什么会出现 `/_next/static/... 426 Upgrade Required`?
+
+**A:** 通常是 WS 路由匹配过宽,把静态资源误转发到 WS 端口了。请检查:
+
+1. Cloudflare Tunnel / Nginx 的 WS 路径不要写成 `ws`,应使用 `/_cm_ws*`
+2. WS 路由优先级必须高于 `/*`
+3. 若你手动设置了 `NEXT_PUBLIC_WS_URL`,需确保与反代路径一致(例如都为 `/_cm_ws`)
+
### Q: 连接 OpenClash 失败?
**A:** 检查以下几点:
diff --git a/apps/web/app/[locale]/page.tsx b/apps/web/app/[locale]/page.tsx
index f26580f..3cbcc7c 100644
--- a/apps/web/app/[locale]/page.tsx
+++ b/apps/web/app/[locale]/page.tsx
@@ -748,17 +748,14 @@ export default function DashboardPage() {
aria-label={autoRefresh ? dashboardT("autoRefresh") : dashboardT("paused")}
className={cn(
"h-9 w-9 rounded-full transition-colors",
- autoRefresh && (!wsEnabled || wsConnected)
+ autoRefresh
? "text-emerald-600 hover:bg-emerald-500/10"
- : autoRefresh && wsEnabled && !wsConnected
- ? "text-amber-600 hover:bg-amber-500/10"
- : "text-muted-foreground hover:bg-muted",
+ : "text-muted-foreground hover:bg-muted",
)}>
<RefreshCw
className={cn(
"w-4 h-4",
- autoRefresh && (!wsEnabled || wsConnected) && "text-emerald-500",
- autoRefresh && wsEnabled && !wsConnected && "text-amber-500",
+ autoRefresh && "text-emerald-500",
)}
style={
autoRefresh
diff --git a/apps/web/components/interactive-proxy-stats.tsx b/apps/web/components/interactive-proxy-stats.tsx
index d339f28..b69ddee 100644
--- a/apps/web/components/interactive-proxy-stats.tsx
+++ b/apps/web/components/interactive-proxy-stats.tsx
@@ -320,12 +320,12 @@ export function InteractiveProxyStats({
const barPercent = (item.value / maxTotal) * 100;
const isSelected = selectedProxy === item.rawName;
const badgeColor = item.rank === 0 ? "bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400" : item.rank === 1 ? "bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300" : item.rank === 2 ? "bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400" : "bg-muted text-muted-foreground";
+ const rawDisplayName = item.rawName || item.name;
return (
<button key={item.rawName} onClick={() => handleProxyClick(item.rawName)} className={cn("w-full p-2.5 rounded-xl border text-left transition-all duration-200", isSelected ? "border-primary bg-primary/5 ring-1 ring-primary/20" : "border-border/50 bg-card/50 hover:bg-card hover:border-primary/30")}>
<div className="flex items-center gap-2 mb-1.5">
<span className={cn("w-5 h-5 rounded-md text-[10px] font-bold flex items-center justify-center shrink-0", badgeColor)}>{item.rank + 1}</span>
- <CountryFlag country={item.countryCode} className="h-3.5 w-5" />
- <span className="flex-1 text-sm font-medium truncate" title={item.name}>{item.name}</span>
+ <span className="flex-1 text-sm font-medium truncate" title={rawDisplayName}>{rawDisplayName}</span>
<span className="text-sm font-bold tabular-nums shrink-0">{formatBytes(item.value)}</span>
</div>
<div className="pl-7 space-y-1">
diff --git a/apps/web/components/rule-chain-flow.tsx b/apps/web/components/rule-chain-flow.tsx
index e697870..19e2d90 100644
--- a/apps/web/components/rule-chain-flow.tsx
+++ b/apps/web/components/rule-chain-flow.tsx
@@ -108,8 +108,10 @@ const MergedAnimatedFlowEdge = memo(function MergedAnimatedFlowEdge({
? "rgba(16, 185, 129, 0.3)"
: "rgba(129, 140, 248, 0.3)";
- // Particles only when actively highlighted (not dimmed, not showAll overview, and not zero-traffic)
- const showParticles = !dimmed && !showAll && !zeroTraffic;
+ // Keep motion only for active traffic links.
+ // Panorama and focused mode share the same three-dot particle style.
+ const showFlowMotion = !dimmed && !zeroTraffic;
+ const motionDuration = "2s";
return (
<g
@@ -131,11 +133,11 @@ const MergedAnimatedFlowEdge = memo(function MergedAnimatedFlowEdge({
strokeWidth={1.5}
strokeLinecap="round"
/>
- {showParticles && (
+ {showFlowMotion && (
<>
- <circle r="3.5" fill={dotColor} opacity="0.9">
+ <circle r={3.5} fill={dotColor} opacity={0.9}>
<animateMotion
- dur="2s"
+ dur={motionDuration}
repeatCount="indefinite"
path={edgePath}
begin="0s"
@@ -143,7 +145,7 @@ const MergedAnimatedFlowEdge = memo(function MergedAnimatedFlowEdge({
</circle>
<circle r="2.5" fill={dotColor} opacity="0.5">
<animateMotion
- dur="2s"
+ dur={motionDuration}
repeatCount="indefinite"
path={edgePath}
begin="0.66s"
@@ -151,7 +153,7 @@ const MergedAnimatedFlowEdge = memo(function MergedAnimatedFlowEdge({
</circle>
<circle r="1.5" fill={dotColor} opacity="0.25">
<animateMotion
- dur="2s"
+ dur={motionDuration}
repeatCount="indefinite"
path={edgePath}
begin="1.33s"
diff --git a/apps/web/components/sw-register.tsx b/apps/web/components/sw-register.tsx
index 526e617..a35820a 100644
--- a/apps/web/components/sw-register.tsx
+++ b/apps/web/components/sw-register.tsx
@@ -10,6 +10,25 @@ export function ServiceWorkerRegister() {
const [waitingWorker, setWaitingWorker] = useState<ServiceWorker | null>(null);
useEffect(() => {
+ if (!("serviceWorker" in navigator)) return;
+
+ // Do not run SW in development, it interferes with HMR and tunnel debugging.
+ if (process.env.NODE_ENV !== "production") {
+ navigator.serviceWorker
+ .getRegistrations()
+ .then((registrations) => {
+ registrations.forEach((registration) => {
+ registration.unregister().catch(() => {
+ // Best effort cleanup only
+ });
+ });
+ })
+ .catch(() => {
+ // Ignore cleanup failures in dev
+ });
+ return;
+ }
+
if ("serviceWorker" in navigator) {
// Register service worker
navigator.serviceWorker
@@ -34,11 +53,16 @@ export function ServiceWorkerRegister() {
});
// Listen for messages from service worker
- navigator.serviceWorker.addEventListener("message", (event) => {
+ const onMessage = (event: MessageEvent) => {
if (event.data && event.data.type === "SKIP_WAITING") {
window.location.reload();
}
- });
+ };
+ navigator.serviceWorker.addEventListener("message", onMessage);
+
+ return () => {
+ navigator.serviceWorker.removeEventListener("message", onMessage);
+ };
}
}, []);
diff --git a/apps/web/lib/websocket.ts b/apps/web/lib/websocket.ts
index f86156b..7658d12 100644
--- a/apps/web/lib/websocket.ts
+++ b/apps/web/lib/websocket.ts
@@ -59,15 +59,39 @@ function getRuntimeConfig(): RuntimeConfig | undefined {
return (window as any).__RUNTIME_CONFIG__ as RuntimeConfig | undefined;
}
-function getWsUrl(): string {
+function normalizeWsUrl(rawUrl: string, runtime?: RuntimeConfig): string {
+ if (typeof window === 'undefined') return rawUrl;
+ const trimmed = rawUrl.trim();
+ if (!trimmed) return trimmed;
+
+ const wsProtocol = window.location.protocol === 'https:' ? 'wss' : 'ws';
+
+ if (trimmed.startsWith('/')) {
+ const host = runtime?.WS_HOST || window.location.host;
+ return `${wsProtocol}://${host}${trimmed}`;
+ }
+
+ if (/^https?:\/\//i.test(trimmed)) {
+ return trimmed.replace(/^http/i, 'ws');
+ }
+
+ return trimmed;
+}
+
+function getWsUrlCandidates(): string[] {
const runtime = getRuntimeConfig();
const wsPort = runtime?.WS_PORT || process.env.NEXT_PUBLIC_WS_PORT || '3002';
- if (runtime?.WS_URL) return runtime.WS_URL;
- if (process.env.NEXT_PUBLIC_WS_URL) return process.env.NEXT_PUBLIC_WS_URL;
+ if (runtime?.WS_URL) return [normalizeWsUrl(runtime.WS_URL, runtime)];
+ if (process.env.NEXT_PUBLIC_WS_URL) return [normalizeWsUrl(process.env.NEXT_PUBLIC_WS_URL, runtime)];
if (typeof window !== 'undefined') {
- return `${window.location.protocol === 'https:' ? 'wss' : 'ws'}://${runtime?.WS_HOST || window.location.hostname}:${wsPort}`;
+ const wsProtocol = window.location.protocol === 'https:' ? 'wss' : 'ws';
+ const hostForPort = runtime?.WS_HOST || window.location.hostname;
+ const directUrl = `${wsProtocol}://${hostForPort}:${wsPort}`;
+ const hostForPath = runtime?.WS_HOST || window.location.host;
+ const pathUrl = `${wsProtocol}://${hostForPath}/_cm_ws`;
+ return [pathUrl, directUrl];
}
- return `ws://localhost:${wsPort}`;
+ return [`ws://localhost:${wsPort}`];
}
export function useStatsWebSocket(options: UseStatsWebSocketOptions = {}) {
@@ -111,6 +135,7 @@ export function useStatsWebSocket(options: UseStatsWebSocketOptions = {}) {
const pingIntervalRef = useRef<NodeJS.Timeout | null>(null);
const lastPingTimeRef = useRef<number>(0);
const reconnectAttemptsRef = useRef<number>(0);
+ const wsUrlIndexRef = useRef<number>(0);
const maxReconnectDelayMs = 30000;
const onMessageRef = useRef(options.onMessage);
const onConnectRef = useRef(options.onConnect);
@@ -153,17 +178,24 @@ export function useStatsWebSocket(options: UseStatsWebSocketOptions = {}) {
setStatus('connecting');
- const wsUrl = getWsUrl();
+ const wsUrls = getWsUrlCandidates();
+ if (wsUrlIndexRef.current >= wsUrls.length) {
+ wsUrlIndexRef.current = 0;
+ }
+ const wsUrl = wsUrls[wsUrlIndexRef.current]!;
console.log('[WebSocket] Connecting to:', wsUrl);
try {
const ws = new WebSocket(wsUrl);
wsRef.current = ws;
+ let opened = false;
ws.onopen = () => {
+ opened = true;
console.log('[WebSocket] Connected successfully');
setStatus('connected');
reconnectAttemptsRef.current = 0;
+ wsUrlIndexRef.current = 0;
onConnectRef.current?.();
// Start ping interval
@@ -205,6 +237,15 @@ export function useStatsWebSocket(options: UseStatsWebSocketOptions = {}) {
pingIntervalRef.current = null;
}
+ // Try alternate endpoint (e.g. /_cm_ws <-> :3002) before backoff reconnect.
+ if (!opened && wsUrlIndexRef.current < wsUrls.length - 1) {
+ wsUrlIndexRef.current += 1;
+ reconnectTimerRef.current = setTimeout(() => {
+ connect();
+ }, 200);
+ return;
+ }
+
// Auto reconnect with exponential backoff.
const delay = Math.min(3000 * Math.pow(2, reconnectAttemptsRef.current), maxReconnectDelayMs);
reconnectAttemptsRef.current++;
@@ -300,6 +341,7 @@ export function useStatsWebSocket(options: UseStatsWebSocketOptions = {}) {
const disconnect = useCallback(() => {
reconnectAttemptsRef.current = 0;
+ wsUrlIndexRef.current = 0;
cleanup();
setStatus('disconnected');
}, [cleanup]);
diff --git a/apps/web/public/sw.js b/apps/web/public/sw.js
index 737a516..c489527 100644
--- a/apps/web/public/sw.js
+++ b/apps/web/public/sw.js
@@ -33,30 +33,41 @@ self.addEventListener("activate", (event) => {
// Fetch event - network first strategy
self.addEventListener("fetch", (event) => {
+ const url = new URL(event.request.url);
+
// Skip non-GET requests
if (event.request.method !== "GET") return;
-
+
+ // Cache only same-origin http(s) requests.
+ if (url.origin !== self.location.origin) return;
+ if (url.protocol !== "http:" && url.protocol !== "https:") return;
+
// Skip API requests
- if (event.request.url.includes("/api/")) return;
-
+ if (url.pathname.startsWith("/api/")) return;
+
+ // Skip dev HMR stream endpoints.
+ if (url.pathname.startsWith("/_next/webpack-hmr")) return;
+
event.respondWith(
fetch(event.request)
.then((response) => {
- // Clone the response
- const responseToCache = response.clone();
-
// Cache successful GET requests
if (response.status === 200) {
- caches.open(CACHE_NAME).then((cache) => {
- cache.put(event.request, responseToCache);
- });
+ const responseToCache = response.clone();
+ event.waitUntil(
+ caches.open(CACHE_NAME)
+ .then((cache) => cache.put(event.request, responseToCache))
+ .catch(() => {
+ // Ignore cache write failures
+ }),
+ );
}
-
+
return response;
})
.catch(() => {
// Fallback to cache if network fails
- return caches.match(event.request);
+ return caches.match(event.request).then((cached) => cached || Response.error());
}),
);
});
diff --git a/package.json b/package.json
index 30f306a..1f0dba4 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "clash-master",
- "version": "1.1.3",
+ "version": "1.1.4",
"private": true,
"workspaces": [
"apps/*",