panrouter 1.1.2 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli.mjs CHANGED
@@ -138,30 +138,39 @@ async function startServer() {
138
138
  console.log("\n 现在可以运行: \x1b[33mclaude \"你好\"\x1b[0m\n");
139
139
  }
140
140
 
141
- // ─── 4. 以托盘模式启动(隐藏窗口 + 系统托盘图标) ────────────────────────
141
+ // ─── 4. 以托盘模式启动(后台守护进程 + 系统托盘) ──────────────────────────
142
142
 
143
+ /**
144
+ * 启动策略:
145
+ * 1. 启动 daemon.mjs (detached, 无窗口)
146
+ * → daemon 启动隐藏的 server.mjs
147
+ * → daemon 启动 tray-manager.ps1 (pipe IPC)
148
+ * → daemon 保持存活直到用户点"退出"
149
+ * 2. cli.mjs 进程立刻退出
150
+ */
143
151
  function startTray() {
144
- const serverPath = path.join(__dirname, "server.mjs");
145
- const trayScript = path.join(__dirname, "tray-manager.ps1");
152
+ const daemonPath = path.join(__dirname, "daemon.mjs");
146
153
 
147
- if (!fs.existsSync(trayScript)) {
148
- log("!!", "未找到 tray-manager.ps1", "red");
154
+ if (!fs.existsSync(daemonPath)) {
155
+ log("!!", "未找到 daemon.mjs", "red");
149
156
  process.exit(1);
150
157
  }
151
158
 
152
159
  log("..", "正在以托盘模式启动 Pan Router...", "yellow");
153
160
 
154
- // 无窗口运行托盘管理器
155
- const child = spawn("powershell", [
156
- "-ExecutionPolicy", "Bypass",
157
- "-WindowStyle", "Hidden",
158
- "-STA",
159
- "-File", trayScript,
160
- "-ServerPath", serverPath,
161
+ const serverPath = path.join(__dirname, "server.mjs");
162
+ const trayPath = path.join(__dirname, "tray-manager.ps1");
163
+
164
+ const child = spawn(process.execPath, [
165
+ daemonPath,
166
+ `--serverPath="${serverPath}"`,
167
+ `--trayPath="${trayPath}"`,
161
168
  ], {
162
169
  cwd: __dirname,
163
170
  stdio: "ignore",
164
171
  detached: true,
172
+ windowsHide: true,
173
+ shell: false,
165
174
  });
166
175
  child.unref();
167
176
 
package/daemon.mjs ADDED
@@ -0,0 +1,178 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Pan Router Daemon — 后台守护进程
5
+ *
6
+ * 由 cli.mjs 以 --tray 参数启动 (detached, hidden)。
7
+ * 管理 server.mjs + tray-manager.ps1, 通过 stdin/stdout JSON 通信。
8
+ *
9
+ * 用法(由 cli.mjs 调用):
10
+ * node daemon.mjs --serverPath="..." --trayPath="..."
11
+ */
12
+
13
+ import { spawn, execSync } from "node:child_process";
14
+ import { createInterface } from "node:readline";
15
+ import { fileURLToPath } from "node:url";
16
+ import path from "node:path";
17
+ import fs from "node:fs";
18
+ import http from "node:http";
19
+
20
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
21
+
22
+ // ─── 解析参数 ────────────────────────────────────
23
+ const serverPath = process.argv.find(a => a.startsWith("--serverPath="))?.split("=")[1];
24
+ const trayPath = process.argv.find(a => a.startsWith("--trayPath="))?.split("=")[1];
25
+ if (!serverPath || !trayPath) { process.exit(1); }
26
+
27
+ const appDir = path.dirname(serverPath);
28
+ const AUTOSTART_NAME = "PanRouter";
29
+ const RUN_KEY = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run";
30
+
31
+ let serverProcess = null;
32
+ let psProcess = null;
33
+
34
+ // ─── 日志 ────────────────────────────────────────
35
+ const LOG = path.join(process.env.TEMP || "/tmp", "panrouter-daemon.log");
36
+ function log(msg) {
37
+ try { fs.appendFileSync(LOG, `${new Date().toISOString().slice(11,19)} ${msg}\n`); } catch {}
38
+ }
39
+
40
+ // ─── 健康检查 ─────────────────────────────────────
41
+ function isOnline() {
42
+ return new Promise(rs => {
43
+ const req = http.get("http://127.0.0.1:50816/health", () => {});
44
+ req.on("response", () => { req.destroy(); rs(true); });
45
+ req.on("error", () => rs(false));
46
+ req.setTimeout(1500, () => { req.destroy(); rs(false); });
47
+ });
48
+ }
49
+
50
+ // ─── 杀掉旧 server 进程 ──────────────────────────
51
+ function killOldServers() {
52
+ try {
53
+ const wmic = spawn("wmic", [
54
+ "process", "where", "name='node.exe'", "get", "ProcessId,CommandLine", "/format:csv"
55
+ ], { stdio: ["ignore", "pipe", "ignore"] });
56
+ let out = "";
57
+ wmic.stdout.on("data", d => out += d.toString());
58
+ wmic.on("close", () => {
59
+ for (const line of out.split("\n")) {
60
+ if (line.includes("server.mjs")) {
61
+ const m = line.match(/(\d+),.*?server\.mjs/);
62
+ if (m) { try { process.kill(parseInt(m[1]), "SIGKILL"); } catch {} }
63
+ }
64
+ }
65
+ });
66
+ } catch {}
67
+ }
68
+
69
+ // ─── 隐藏启动 server.mjs ─────────────────────────
70
+ function startServer() {
71
+ killOldServers();
72
+ serverProcess = spawn("node", [serverPath], {
73
+ cwd: appDir, stdio: ["ignore", "pipe", "pipe"], windowsHide: true, shell: false,
74
+ });
75
+ serverProcess.stdout.on("data", d => log("[srv] " + d.toString().trim()));
76
+ serverProcess.stderr.on("data", d => log("[srv-err] " + d.toString().trim()));
77
+ serverProcess.on("exit", code => log(`Server exited code=${code}`));
78
+ log(`Server started PID=${serverProcess.pid}`);
79
+ }
80
+
81
+ // ─── 命令 → PS 托盘 ─────────────────────────────
82
+ function psSend(cmd) {
83
+ if (psProcess?.stdin?.writable) {
84
+ psProcess.stdin.write(JSON.stringify(cmd) + "\n");
85
+ }
86
+ }
87
+
88
+ // ─── 开机自启动操作 (reg.exe) ────────────────────
89
+ function toggleAutostart() {
90
+ try {
91
+ const out = execSync(`reg query ${RUN_KEY} /v ${AUTOSTART_NAME} 2>nul`, {
92
+ encoding: "utf8", windowsHide: true, timeout: 3000,
93
+ });
94
+ const isOn = !out.toLowerCase().includes("error");
95
+ if (isOn) {
96
+ execSync(`reg delete ${RUN_KEY} /v ${AUTOSTART_NAME} /f 2>nul`, { windowsHide: true, timeout: 3000 });
97
+ psSend({ action: "update-item", index: 2, title: "开机自启动", enabled: true });
98
+ log("Autostart OFF");
99
+ } else {
100
+ const exe = process.execPath;
101
+ const daemon = path.join(__dirname, "daemon.mjs");
102
+ const cmd = `"${exe}" "${daemon}" --serverPath="${serverPath}" --trayPath="${trayPath}"`;
103
+ execSync(`reg add ${RUN_KEY} /v ${AUTOSTART_NAME} /t REG_SZ /d "${cmd}" /f 2>nul`, { windowsHide: true, timeout: 3000 });
104
+ psSend({ action: "update-item", index: 2, title: "✓ 开机自启动", enabled: true });
105
+ log("Autostart ON");
106
+ }
107
+ } catch (e) { log(`Autostart error: ${e.message}`); }
108
+ }
109
+
110
+ // ─── 退出清理 ────────────────────────────────────
111
+ function cleanup() {
112
+ log("Cleanup...");
113
+ try { if (serverProcess && !serverProcess.killed) serverProcess.kill("SIGKILL"); } catch {}
114
+ killOldServers();
115
+ }
116
+
117
+ // ═══════════════ 主流程 ═══════════════
118
+
119
+ log("=== PanRouter Daemon ===");
120
+ log(`serverPath=${serverPath}`);
121
+ log(`trayPath=${trayPath}`);
122
+
123
+ // 1. 启动服务器
124
+ startServer();
125
+
126
+ // 2. 等服务器就绪, 启动托盘
127
+ (async () => {
128
+ let ready = false;
129
+ for (let i = 0; i < 20; i++) {
130
+ if (await isOnline()) { ready = true; break; }
131
+ await new Promise(r => setTimeout(r, 500));
132
+ }
133
+ log(`Server ready=${ready}`);
134
+
135
+ // 3. 启动 PS 托盘 (pipe 连接, 保持 IPC)
136
+ psProcess = spawn("powershell.exe", [
137
+ "-NoProfile", "-ExecutionPolicy", "Bypass",
138
+ "-WindowStyle", "Hidden",
139
+ "-File", trayPath,
140
+ ], {
141
+ stdio: ["pipe", "pipe", "pipe"], windowsHide: true, shell: false,
142
+ });
143
+
144
+ // 读取 PS 事件
145
+ createInterface({ input: psProcess.stdout }).on("line", (line) => {
146
+ try {
147
+ const evt = JSON.parse(line);
148
+ log(`PS: ${line}`);
149
+ if (evt.type === "started") {
150
+ // 发送菜单配置
151
+ psSend({ action: "add-item", index: 0, title: "Pan Router - :50816", enabled: false });
152
+ psSend({ action: "add-item", index: 1, title: "─".repeat(19), enabled: false });
153
+ psSend({ action: "add-item", index: 2, title: "开机自启动", enabled: true });
154
+ psSend({ action: "add-item", index: 3, title: "─".repeat(19), enabled: false });
155
+ psSend({ action: "add-item", index: 4, title: "退出", enabled: true });
156
+ psSend({ action: "set-tooltip", text: "Pan Router | 端口 50816" });
157
+ log("Menu configured");
158
+ }
159
+ if (evt.type === "click" && evt.index === 2) toggleAutostart();
160
+ if (evt.type === "click" && evt.index === 4) {
161
+ log("Exit requested");
162
+ cleanup();
163
+ psSend({ action: "kill" });
164
+ setTimeout(() => process.exit(0), 500);
165
+ }
166
+ } catch (e) { log(`PS parse error: ${e.message}`); }
167
+ });
168
+
169
+ psProcess.on("error", err => log(`PS error: ${err.message}`));
170
+ psProcess.stderr.on("data", d => log(`[ps-err] ${d.toString().trim()}`));
171
+ psProcess.on("exit", code => { log(`PS exited code=${code}`); process.exit(0); });
172
+
173
+ log("Daemon ready");
174
+ process.stdin.resume(); // 保持进程存活
175
+ })();
176
+
177
+ process.on("SIGTERM", () => { cleanup(); setTimeout(() => process.exit(0), 300); });
178
+ process.on("SIGINT", () => { cleanup(); setTimeout(() => process.exit(0), 300); });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "panrouter",
3
- "version": "1.1.2",
3
+ "version": "1.2.0",
4
4
  "description": "让 Claude Code 免费使用 DeepSeek 等模型,无需 API Key",
5
5
  "type": "module",
6
6
  "bin": {
@@ -8,9 +8,9 @@
8
8
  },
9
9
  "files": [
10
10
  "cli.mjs",
11
+ "daemon.mjs",
11
12
  "server.mjs",
12
- "tray-manager.ps1",
13
- "tray-app.cs"
13
+ "tray-manager.ps1"
14
14
  ],
15
15
  "license": "MIT"
16
16
  }
package/tray-manager.ps1 CHANGED
@@ -1,198 +1,111 @@
1
1
  <#
2
2
  .SYNOPSIS
3
- Pan Router 系统托盘管理器
3
+ Pan Router 托盘管理器 (IPC 版)
4
4
  .DESCRIPTION
5
- 在通知区域(右下角)显示图标,隐藏命令窗口。
6
- 右键菜单: 状态, 开机自启动开关, 退出
7
-
8
- 用法(必须 STA):
9
- powershell -ExecutionPolicy Bypass -STA -WindowStyle Hidden -File tray-manager.ps1 -ServerPath "server.mjs"
10
-
11
- 注意: 不能在脚本中弹任何对话框(隐藏窗口下没人点)
5
+ 纯 NotifyIcon 包装器, 通过 stdin/stdout JSON 与父进程通信
6
+
7
+ 支持命令 (stdin):
8
+ {"action":"add-item","index":0,"title":"...","enabled":true}
9
+ {"action":"update-item","index":0,"title":"...","enabled":true}
10
+ {"action":"set-tooltip","text":"..."}
11
+ {"action":"kill"}
12
+
13
+ 事件 (stdout):
14
+ {"type":"started"}
15
+ {"type":"ready"} <- PS 就绪 + STA 已确认
16
+ {"type":"click","index":0}
17
+ {"type":"error","message":"..."}
12
18
  #>
13
19
 
14
- param([string]$ServerPath)
15
-
16
- # ─── 启动即写日志 ──────────────────────────────
17
- $logPath = "$env:TEMP\panrouter-tray.log"
18
- "===" + (Get-Date -Format "HH:mm:ss") + " PanRouter Tray===" | Out-File $logPath
19
- function Log { param($m) (Get-Date -Format "HH:mm:ss") + " " + $m | Out-File -Append $logPath }
20
+ param()
20
21
 
21
- Log "ServerPath=$ServerPath"
22
- Log "Args=$([environment]::CommandLine)"
23
-
24
- # ─── 加载 WinForms ─────────────────────────────
25
22
  Add-Type -AssemblyName System.Windows.Forms
26
23
  Add-Type -AssemblyName System.Drawing
27
- Log "Assemblies loaded"
28
24
 
29
- # ─── 常量 ──────────────────────────────────────
30
- $autostartName = "PanRouter"
31
- $runKeyPath = "Software\Microsoft\Windows\CurrentVersion\Run"
32
- $appDir = Split-Path $ServerPath -Parent
33
- $tooltipText = "Pan Router`n端口 50816 | 运行中"
25
+ $ErrorActionPreference = "Stop"
26
+ [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
27
+
28
+ $script:notifyIcon = New-Object System.Windows.Forms.NotifyIcon
29
+ $script:notifyIcon.Visible = $true
30
+ $script:menu = New-Object System.Windows.Forms.ContextMenuStrip
31
+ $script:notifyIcon.ContextMenuStrip = $script:menu
32
+ $script:items = @()
34
33
 
35
- # ─── 生成图标 ──────────────────────────────────
34
+ function Write-Event($obj) {
35
+ $json = $obj | ConvertTo-Json -Compress
36
+ try {
37
+ [Console]::Out.WriteLine($json)
38
+ [Console]::Out.Flush()
39
+ } catch {}
40
+ }
41
+
42
+ # ─── 生成蓝色 P 图标 (纯内存, 无需 .ico 文件) ──
36
43
  $bmp = New-Object System.Drawing.Bitmap(16, 16)
37
44
  $g = [System.Drawing.Graphics]::FromImage($bmp)
38
45
  $g.SmoothingMode = 'HighQuality'
39
46
  $g.Clear([System.Drawing.Color]::Transparent)
40
47
  $brush = New-Object System.Drawing.SolidBrush([System.Drawing.Color]::FromArgb(0, 120, 215))
41
- $g.FillEllipse($brush, 2, 2, 12, 12)
42
- $font = New-Object System.Drawing.Font("Segoe UI", 8, [System.Drawing.FontStyle]::Bold)
48
+ $g.FillEllipse($brush, 0, 0, 15, 15)
49
+ $font = New-Object System.Drawing.Font("Segoe UI", 8.5, [System.Drawing.FontStyle]::Bold)
43
50
  $fg = New-Object System.Drawing.SolidBrush([System.Drawing.Color]::White)
44
- $g.DrawString("P", $font, $fg, 4, 2.5)
51
+ $g.DrawString("P", $font, $fg, 3, 1.5)
45
52
  $font.Dispose(); $fg.Dispose(); $brush.Dispose(); $g.Dispose()
46
53
  $hIcon = $bmp.GetHicon()
47
54
  $icon = [System.Drawing.Icon]::FromHandle($hIcon)
48
55
  $bmp.Dispose()
49
- Log "Icon generated"
50
56
 
51
- # ─── NotifyIcon ────────────────────────────────
52
- $notifyIcon = New-Object System.Windows.Forms.NotifyIcon
53
- $notifyIcon.Icon = $icon
54
- $notifyIcon.Text = $tooltipText
55
- $notifyIcon.Visible = $true
56
- Log "NotifyIcon visible"
57
+ $script:notifyIcon.Icon = $icon
58
+ $script:notifyIcon.Text = "Pan Router"
59
+
60
+ function Add-MenuItem($index, $title, $enabled) {
61
+ $item = New-Object System.Windows.Forms.ToolStripMenuItem
62
+ $item.Text = $title
63
+ $item.Enabled = $enabled
64
+ $idx = $index
65
+ $item.Add_Click({ Write-Event @{type="click"; index=$idx} }.GetNewClosure())
66
+ $script:menu.Items.Add($item) | Out-Null
67
+ $script:items += $item
68
+ }
57
69
 
58
- # ─── 启动隐藏服务器 ────────────────────────────
59
- function Start-Server {
60
- $psi = New-Object System.Diagnostics.ProcessStartInfo
61
- $psi.FileName = "node"
62
- $psi.Arguments = "`"$ServerPath`""
63
- $psi.WorkingDirectory = $appDir
64
- $psi.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden
65
- $psi.CreateNoWindow = $true
66
- $psi.UseShellExecute = $true # 关键: 不重定向输出, 无缓冲死锁
67
- try {
68
- $p = [System.Diagnostics.Process]::Start($psi)
69
- Log "Server started PID=$($p.Id)"
70
- return $p
71
- } catch {
72
- Log "Server start FAILED: $_"
73
- return $null
70
+ function Update-MenuItem($index, $title, $enabled) {
71
+ if ($index -lt $script:items.Count) {
72
+ $script:items[$index].Text = $title
73
+ $script:items[$index].Enabled = $enabled
74
74
  }
75
75
  }
76
76
 
77
- # ─── 杀掉旧服务器 (wmic, 不依赖 CIM/WMI 版本)
78
- function Stop-OldServer {
79
- try {
80
- $wmicOut = & wmic process where "name='node.exe'" get ProcessId,CommandLine /format:csv 2>$null
81
- foreach ($line in $wmicOut) {
82
- if ($line -match '(\d+),.*?server\.mjs') {
83
- $pid = $Matches[1]
84
- Log "Kill old PID=$pid"
85
- Stop-Process -Id $pid -Force -ErrorAction SilentlyContinue
86
- }
87
- }
88
- } catch { Log "KillOld: $_" }
77
+ function Set-Tooltip($text) {
78
+ if ($text.Length -gt 63) { $text = $text.Substring(0, 63) }
79
+ $script:notifyIcon.Text = $text
89
80
  }
90
81
 
91
- # ─── 健康检查 ──────────────────────────────────
92
- function Test-Online {
82
+ # ─── stdin 轮询 (100ms 间隔) ────────────────────
83
+ $script:timer = New-Object System.Windows.Forms.Timer
84
+ $script:timer.Interval = 100
85
+ $script:timer.Add_Tick({
93
86
  try {
94
- $req = [System.Net.WebRequest]::Create("http://127.0.0.1:50816/health")
95
- $req.Timeout = 1500
96
- $resp = $req.GetResponse()
97
- $resp.Close()
98
- return $true
99
- } catch { return $false }
100
- }
101
-
102
- # ═══════════════ 主流程 ═══════════════
103
-
104
- # 1. 杀旧 + 启动
105
- Stop-OldServer
106
- $serverProcess = Start-Server
107
-
108
- # 2. 前台等待就绪 (10秒超时)
109
- $ready = $false
110
- for ($i = 0; $i -lt 20; $i++) {
111
- Start-Sleep -Milliseconds 500
112
- if (Test-Online) { $ready = $true; break }
113
- }
114
- Log "Server ready=$ready"
115
- if ($ready) {
116
- $notifyIcon.ShowBalloonTip(3000, "Pan Router", "服务器已就绪 (端口 50816)", [System.Windows.Forms.ToolTipIcon]::Info)
117
- }
118
-
119
- # 3. 右键菜单
120
- $menu = New-Object System.Windows.Forms.ContextMenuStrip
121
-
122
- $titleItem = New-Object System.Windows.Forms.ToolStripMenuItem
123
- $titleItem.Text = "Pan Router - :50816"
124
- $titleItem.Enabled = $false
125
- $titleItem.Font = New-Object System.Drawing.Font("Segoe UI", 9, [System.Drawing.FontStyle]::Bold)
126
- $menu.Items.Add($titleItem)
127
- $menu.Items.Add("-")
128
-
129
- $autoStartItem = New-Object System.Windows.Forms.ToolStripMenuItem
130
- $autoStartItem.Text = "开机自启动"
131
- $rk = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($runKeyPath, $true)
132
- $autoStartItem.Checked = ($rk.GetValue($autostartName) -ne $null)
133
- $rk.Close()
134
- $autoStartItem.Add_Click({
135
- $rk2 = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($runKeyPath, $true)
136
- if ($autoStartItem.Checked) {
137
- $rk2.DeleteValue($autostartName, $false)
138
- $autoStartItem.Checked = $false
139
- $notifyIcon.ShowBalloonTip(2000, "Pan Router", "开机自启动已关闭", [System.Windows.Forms.ToolTipIcon]::Info)
140
- Log "Autostart OFF"
141
- } else {
142
- $cmd = "powershell -ExecutionPolicy Bypass -WindowStyle Hidden -STA -File `"$($MyInvocation.MyCommand.Path)`" -ServerPath `"$ServerPath`""
143
- $rk2.SetValue($autostartName, $cmd)
144
- $autoStartItem.Checked = $true
145
- $notifyIcon.ShowBalloonTip(2000, "Pan Router", "开机自启动已开启 ✓", [System.Windows.Forms.ToolTipIcon]::Info)
146
- Log "Autostart ON"
147
- }
148
- $rk2.Close()
149
- })
150
- $menu.Items.Add($autoStartItem)
151
- $menu.Items.Add("-")
152
-
153
- $exitItem = New-Object System.Windows.Forms.ToolStripMenuItem
154
- $exitItem.Text = "退出"
155
- $exitItem.Add_Click({
156
- Log "Exit clicked"
157
- $notifyIcon.Visible = $false
158
- [System.Windows.Forms.Application]::Exit()
159
- })
160
- $menu.Items.Add($exitItem)
161
-
162
- $notifyIcon.ContextMenuStrip = $menu
163
-
164
- # 4. 左键: 状态
165
- $notifyIcon.Add_MouseClick({
166
- if ($_.Button -eq [System.Windows.Forms.MouseButtons]::Left) {
167
- if (Test-Online) {
168
- $notifyIcon.ShowBalloonTip(2000, "Pan Router", "运行正常 ✓ (端口 50816)", [System.Windows.Forms.ToolTipIcon]::Info)
169
- } else {
170
- $notifyIcon.ShowBalloonTip(2000, "Pan Router", "服务器未响应 ⚠", [System.Windows.Forms.ToolTipIcon]::Error)
87
+ while ([Console]::In.Peek() -ne -1) {
88
+ $line = [Console]::In.ReadLine()
89
+ if ([string]::IsNullOrWhiteSpace($line)) { continue }
90
+ $cmd = $line | ConvertFrom-Json
91
+ switch ($cmd.action) {
92
+ "add-item" { Add-MenuItem $cmd.index $cmd.title $cmd.enabled }
93
+ "update-item" { Update-MenuItem $cmd.index $cmd.title $cmd.enabled }
94
+ "set-tooltip" { Set-Tooltip $cmd.text }
95
+ "kill" {
96
+ $script:notifyIcon.Visible = $false
97
+ $script:notifyIcon.Dispose()
98
+ $icon.Dispose()
99
+ [System.Runtime.InteropServices.Marshal]::DestroyIcon($hIcon)
100
+ [System.Windows.Forms.Application]::Exit()
101
+ }
102
+ }
171
103
  }
104
+ } catch {
105
+ Write-Event @{type="error"; message=$_.Exception.Message}
172
106
  }
173
107
  })
108
+ $script:timer.Start()
174
109
 
175
- # 5. 退出清理
176
- [System.Windows.Forms.Application]::ApplicationExit += {
177
- Log "AppExit cleanup"
178
- if ($serverProcess -and !$serverProcess.HasExited) {
179
- $serverProcess.Kill()
180
- $serverProcess.WaitForExit(3000)
181
- Log "Server killed"
182
- }
183
- Stop-OldServer
184
- $notifyIcon.Dispose()
185
- [System.Runtime.InteropServices.Marshal]::DestroyIcon($hIcon)
186
- $icon.Dispose()
187
- }
188
-
189
- # 6. 运行消息循环
190
- Log "Entering message loop"
110
+ Write-Event @{type="started"}
191
111
  [System.Windows.Forms.Application]::Run()
192
- Log "Message loop exited"
193
-
194
- # 7. 循环结束后再清理一次
195
- try {
196
- if ($serverProcess -and !$serverProcess.HasExited) { $serverProcess.Kill() }
197
- Stop-OldServer
198
- } catch {}
package/tray-app.cs DELETED
@@ -1,324 +0,0 @@
1
- /* Pan Router Tray App
2
- * 编译: csc /nologo /target:winexe /reference:System.Windows.Forms.dll /reference:System.Drawing.dll tray-app.cs
3
- *
4
- * 功能: 以系统托盘方式运行 panrouter 服务器, 无窗口
5
- * 右键菜单: 状态, 开机自启动开关, 退出
6
- */
7
-
8
- using System;
9
- using System.Diagnostics;
10
- using System.Drawing;
11
- using System.IO;
12
- using System.Net;
13
- using System.Reflection;
14
- using System.Runtime.InteropServices;
15
- using System.Text;
16
- using System.Threading;
17
- using System.Windows.Forms;
18
-
19
- public class PanRouterTrayApp
20
- {
21
- private static NotifyIcon _notifyIcon;
22
- private static Process _serverProcess;
23
- private static string _serverPath;
24
- private static string _appDir;
25
- private static System.Threading.Timer _healthTimer;
26
- private static StreamWriter _log;
27
- private static readonly string _logPath = Path.Combine(Path.GetTempPath(), "panrouter-tray.log");
28
-
29
- // ─── Win32 API: 隐藏窗口 ──────────────────────
30
- [DllImport("user32.dll")]
31
- private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
32
- private const int SW_HIDE = 0;
33
-
34
- [STAThread]
35
- public static void Main(string[] args)
36
- {
37
- // Parse args
38
- foreach (var a in args)
39
- {
40
- if (a.StartsWith("--serverPath:", StringComparison.OrdinalIgnoreCase))
41
- _serverPath = a.Substring("--serverPath:".Length).Trim('"');
42
- }
43
- if (string.IsNullOrEmpty(_serverPath) || !File.Exists(_serverPath))
44
- {
45
- MessageBox.Show("Pan Router: 找不到 server.mjs", "Pan Router", MessageBoxButtons.OK, MessageBoxIcon.Error);
46
- return;
47
- }
48
- _appDir = Path.GetDirectoryName(_serverPath);
49
-
50
- // Open log
51
- try
52
- {
53
- _log = new StreamWriter(_logPath, false, Encoding.UTF8);
54
- _log.AutoFlush = true;
55
- Log("=== PanRouter Tray App v1 ===");
56
- Log("ServerPath: " + _serverPath);
57
- }
58
- catch { }
59
-
60
- // Kill old servers
61
- KillOldServers();
62
-
63
- // Start hidden server
64
- StartServer();
65
-
66
- // Wait for ready
67
- bool ready = false;
68
- for (int i = 0; i < 20; i++)
69
- {
70
- Thread.Sleep(500);
71
- if (IsOnline()) { ready = true; break; }
72
- }
73
- Log("Server ready=" + ready);
74
-
75
- // Create tray icon
76
- CreateTrayIcon();
77
-
78
- // Show balloon
79
- if (ready)
80
- _notifyIcon.ShowBalloonTip(3000, "Pan Router", "服务器已就绪 (端口 50816)", ToolTipIcon.Info);
81
- else
82
- _notifyIcon.ShowBalloonTip(3000, "Pan Router", "服务器启动异常,查看日志", ToolTipIcon.Warning);
83
-
84
- // Health check every 30s
85
- _healthTimer = new System.Threading.Timer(HealthCheck, null, 30000, 30000);
86
-
87
- // Message loop
88
- Application.Run();
89
- }
90
-
91
- private static void Log(string msg)
92
- {
93
- try { _log?.WriteLine(DateTime.Now.ToString("HH:mm:ss") + " " + msg); } catch { }
94
- }
95
-
96
- // ─── 杀掉旧服务器 ────────────────────────────
97
- private static void KillOldServers()
98
- {
99
- try
100
- {
101
- // Use WMIC via command line to find node.exe processes running server.mjs
102
- var psi = new ProcessStartInfo("wmic", "process where \"name='node.exe'\" get ProcessId,CommandLine /format:csv")
103
- {
104
- CreateNoWindow = true,
105
- WindowStyle = ProcessWindowStyle.Hidden,
106
- UseShellExecute = false,
107
- RedirectStandardOutput = true,
108
- RedirectStandardError = true
109
- };
110
- using (var p = Process.Start(psi))
111
- {
112
- string output = p.StandardOutput.ReadToEnd();
113
- p.WaitForExit(2000);
114
-
115
- foreach (string line in output.Split('\n'))
116
- {
117
- if (line.Contains("server.mjs"))
118
- {
119
- string[] parts = line.Split(',');
120
- if (parts.Length >= 3 && int.TryParse(parts[2].Trim(), out int pid))
121
- {
122
- Log("Killing old server PID=" + pid);
123
- try { Process.GetProcessById(pid)?.Kill(); } catch { }
124
- }
125
- }
126
- }
127
- }
128
- }
129
- catch (Exception ex) { Log("KillOld error: " + ex.Message); }
130
- }
131
-
132
- // ─── 启动隐藏服务器 ───────────────────────────
133
- private static void StartServer()
134
- {
135
- try
136
- {
137
- _serverProcess = new Process();
138
- _serverProcess.StartInfo.FileName = "node";
139
- _serverProcess.StartInfo.Arguments = "\"" + _serverPath + "\"";
140
- _serverProcess.StartInfo.WorkingDirectory = _appDir;
141
- _serverProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
142
- _serverProcess.StartInfo.CreateNoWindow = true;
143
- _serverProcess.StartInfo.UseShellExecute = false;
144
- // Read output so buffer never blocks
145
- _serverProcess.StartInfo.RedirectStandardOutput = true;
146
- _serverProcess.StartInfo.RedirectStandardError = true;
147
- _serverProcess.OutputDataReceived += (s, e) => { if (!string.IsNullOrEmpty(e.Data)) Log("[srv] " + e.Data); };
148
- _serverProcess.ErrorDataReceived += (s, e) => { if (!string.IsNullOrEmpty(e.Data)) Log("[srv-err] " + e.Data); };
149
- _serverProcess.Start();
150
- _serverProcess.BeginOutputReadLine();
151
- _serverProcess.BeginErrorReadLine();
152
- Log("Server started PID=" + _serverProcess.Id);
153
- }
154
- catch (Exception ex)
155
- {
156
- Log("StartServer FAILED: " + ex.Message);
157
- }
158
- }
159
-
160
- // ─── 健康检查 ────────────────────────────────
161
- private static bool IsOnline()
162
- {
163
- try
164
- {
165
- var req = WebRequest.CreateHttp("http://127.0.0.1:50816/health");
166
- req.Timeout = 1500;
167
- using (var resp = req.GetResponse()) { return true; }
168
- }
169
- catch { return false; }
170
- }
171
-
172
- private static void HealthCheck(object state)
173
- {
174
- try
175
- {
176
- if (!IsOnline())
177
- {
178
- Log("Health check FAILED, restarting...");
179
- KillOldServers();
180
- StartServer();
181
- Thread.Sleep(3000);
182
- if (IsOnline())
183
- _notifyIcon.ShowBalloonTip(3000, "Pan Router", "服务器已自动重启 ✓", ToolTipIcon.Info);
184
- else
185
- _notifyIcon.ShowBalloonTip(3000, "Pan Router", "服务器重启失败 ⚠", ToolTipIcon.Error);
186
- }
187
- }
188
- catch (Exception ex) { Log("HealthCheck error: " + ex.Message); }
189
- }
190
-
191
- // ─── 创建托盘图标 ────────────────────────────
192
- private static void CreateTrayIcon()
193
- {
194
- var bmp = new Bitmap(16, 16);
195
- using (var g = Graphics.FromImage(bmp))
196
- {
197
- g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
198
- g.Clear(Color.Transparent);
199
- using (var brush = new SolidBrush(Color.FromArgb(0, 120, 215)))
200
- g.FillEllipse(brush, 0, 0, 15, 15);
201
- using (var font = new Font("Segoe UI", 8.5f, FontStyle.Bold))
202
- using (var fg = new SolidBrush(Color.White))
203
- g.DrawString("P", font, fg, 3, 1.5f);
204
- }
205
- var icon = Icon.FromHandle(bmp.GetHicon());
206
-
207
- _notifyIcon = new NotifyIcon();
208
- _notifyIcon.Icon = icon;
209
- _notifyIcon.Text = "Pan Router\n端口 50816 | 运行中";
210
- _notifyIcon.Visible = true;
211
- Log("Tray icon created");
212
-
213
- // Left click: balloon status
214
- _notifyIcon.MouseClick += (s, e) =>
215
- {
216
- if (e.Button == MouseButtons.Left)
217
- {
218
- bool online = IsOnline();
219
- _notifyIcon.ShowBalloonTip(2000, "Pan Router",
220
- online ? "运行正常 ✓ (端口 50816)" : "服务器未响应 ⚠",
221
- online ? ToolTipIcon.Info : ToolTipIcon.Error);
222
- }
223
- };
224
-
225
- // Right-click menu
226
- var menu = new ContextMenuStrip();
227
-
228
- var titleItem = new ToolStripMenuItem("Pan Router - :50816") { Enabled = false };
229
- titleItem.Font = new Font("Segoe UI", 9, FontStyle.Bold);
230
- menu.Items.Add(titleItem);
231
- menu.Items.Add(new ToolStripSeparator());
232
-
233
- // Autostart
234
- var autoItem = new ToolStripMenuItem("开机自启动");
235
- autoItem.Checked = IsAutostart();
236
- autoItem.Click += (s, e) =>
237
- {
238
- if (autoItem.Checked)
239
- {
240
- SetAutostart(false);
241
- autoItem.Checked = false;
242
- _notifyIcon.ShowBalloonTip(2000, "Pan Router", "开机自启动已关闭", ToolTipIcon.Info);
243
- Log("Autostart OFF");
244
- }
245
- else
246
- {
247
- SetAutostart(true);
248
- autoItem.Checked = true;
249
- _notifyIcon.ShowBalloonTip(2000, "Pan Router", "开机自启动已开启 ✓", ToolTipIcon.Info);
250
- Log("Autostart ON");
251
- }
252
- };
253
- menu.Items.Add(autoItem);
254
- menu.Items.Add(new ToolStripSeparator());
255
-
256
- // Exit
257
- var exitItem = new ToolStripMenuItem("退出");
258
- exitItem.Click += (s, e) =>
259
- {
260
- Log("Exit clicked");
261
- Cleanup();
262
- Application.Exit();
263
- };
264
- menu.Items.Add(exitItem);
265
-
266
- _notifyIcon.ContextMenuStrip = menu;
267
-
268
- // Cleanup on exit
269
- Application.ApplicationExit += (s, e) => { Cleanup(); bmp.Dispose(); };
270
- }
271
-
272
- // ─── 开机自启动 ──────────────────────────────
273
- private static bool IsAutostart()
274
- {
275
- try
276
- {
277
- using (var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run"))
278
- return key?.GetValue("PanRouter") != null;
279
- }
280
- catch { return false; }
281
- }
282
-
283
- private static void SetAutostart(bool enable)
284
- {
285
- try
286
- {
287
- using (var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true))
288
- {
289
- if (enable)
290
- {
291
- var exePath = Assembly.GetExecutingAssembly().Location;
292
- key.SetValue("PanRouter",
293
- $"\"{exePath}\" --serverPath:\"{_serverPath}\"");
294
- }
295
- else
296
- {
297
- key.DeleteValue("PanRouter", false);
298
- }
299
- }
300
- }
301
- catch (Exception ex) { Log("Autostart error: " + ex.Message); }
302
- }
303
-
304
- // ─── 退出清理 ────────────────────────────────
305
- private static void Cleanup()
306
- {
307
- try
308
- {
309
- Log("Cleanup starting...");
310
- _healthTimer?.Dispose();
311
- if (_serverProcess != null && !_serverProcess.HasExited)
312
- {
313
- Log("Killing server PID=" + _serverProcess.Id);
314
- _serverProcess.Kill();
315
- _serverProcess.WaitForExit(3000);
316
- _serverProcess.Dispose();
317
- Log("Server killed");
318
- }
319
- KillOldServers();
320
- try { _log?.Close(); } catch { }
321
- }
322
- catch (Exception ex) { try { _log?.WriteLine("Cleanup error: " + ex.Message); } catch { } }
323
- }
324
- }