chore: import upstream snapshot with attribution
This commit is contained in:
@@ -0,0 +1,410 @@
|
||||
import { existsSync, writeFileSync, unlinkSync, mkdirSync, realpathSync } from "node:fs";
|
||||
import { execFileSync, execSync } from "node:child_process";
|
||||
import { homedir } from "node:os";
|
||||
import { join, dirname } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const APP_LABEL = "com.omniroute.autostart";
|
||||
const WIN_REG_VALUE = "OmniRoute";
|
||||
const LINUX_SERVICE_NAME = "omniroute.service";
|
||||
const LINUX_DESKTOP_NAME = "omniroute.desktop";
|
||||
|
||||
function resolveCliPath() {
|
||||
const candidates = [];
|
||||
if (process.argv[1]) candidates.push(process.argv[1]);
|
||||
try {
|
||||
const which = execSync("command -v omniroute 2>/dev/null", { encoding: "utf8" }).trim();
|
||||
if (which) candidates.push(which);
|
||||
} catch {
|
||||
// command -v unavailable
|
||||
}
|
||||
candidates.push(join(dirname(fileURLToPath(import.meta.url)), "..", "..", "omniroute.mjs"));
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (!candidate) continue;
|
||||
try {
|
||||
const resolved = realpathSync(candidate);
|
||||
if (resolved.endsWith("omniroute.mjs") && existsSync(resolved)) return resolved;
|
||||
} catch {
|
||||
// try next candidate
|
||||
}
|
||||
}
|
||||
|
||||
const fallback = candidates[candidates.length - 1];
|
||||
return existsSync(fallback) ? fallback : null;
|
||||
}
|
||||
|
||||
function quoteExecArg(value) {
|
||||
if (!/[ \t"'\\]/.test(value)) return value;
|
||||
return `"${value.replace(/(["\\])/g, "\\$1")}"`;
|
||||
}
|
||||
|
||||
function buildServeExecLine(cliPath, { tray = false } = {}) {
|
||||
const parts = [quoteExecArg(process.execPath), quoteExecArg(cliPath), "serve", "--no-open"];
|
||||
if (tray) parts.push("--tray");
|
||||
return parts.join(" ");
|
||||
}
|
||||
|
||||
function isGraphicalLinuxSession() {
|
||||
if (process.env.DISPLAY || process.env.WAYLAND_DISPLAY) return true;
|
||||
if (process.env.XDG_CURRENT_DESKTOP) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
function userHomeDir() {
|
||||
return process.env.HOME || homedir();
|
||||
}
|
||||
|
||||
function linuxSystemdUnitPath() {
|
||||
return join(userHomeDir(), ".config", "systemd", "user", LINUX_SERVICE_NAME);
|
||||
}
|
||||
|
||||
function linuxDesktopPath() {
|
||||
return join(userHomeDir(), ".config", "autostart", LINUX_DESKTOP_NAME);
|
||||
}
|
||||
|
||||
function runUserSystemctl(args, { ignoreFailure = true } = {}) {
|
||||
try {
|
||||
execFileSync("systemctl", ["--user", ...args], { stdio: "ignore" });
|
||||
return true;
|
||||
} catch (err) {
|
||||
if (!ignoreFailure) throw err;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isSystemdUserAvailable() {
|
||||
try {
|
||||
execFileSync("systemctl", ["--user", "--version"], { stdio: "ignore" });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isSystemdServiceEnabled() {
|
||||
if (!existsSync(linuxSystemdUnitPath())) return false;
|
||||
try {
|
||||
execFileSync("systemctl", ["--user", "is-enabled", LINUX_SERVICE_NAME], { stdio: "ignore" });
|
||||
return true;
|
||||
} catch {
|
||||
// systemctl --user can't query the bus (headless environments / CI runners).
|
||||
// Treat the presence of the unit file as the source of truth, matching the
|
||||
// fallback used in enableLinux() where unit-file existence counts as success.
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
function tryEnableLinger() {
|
||||
try {
|
||||
const user =
|
||||
process.env.USER ||
|
||||
process.env.LOGNAME ||
|
||||
execFileSync("whoami", { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
|
||||
if (!user) return false;
|
||||
execFileSync("loginctl", ["enable-linger", user], { stdio: "ignore" });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function writeLinuxSystemdUnit(cliPath) {
|
||||
const unitDir = dirname(linuxSystemdUnitPath());
|
||||
mkdirSync(unitDir, { recursive: true });
|
||||
const envFile = join(userHomeDir(), ".omniroute", ".env");
|
||||
const lines = [
|
||||
"[Unit]",
|
||||
"Description=OmniRoute AI proxy router",
|
||||
"After=network-online.target",
|
||||
"Wants=network-online.target",
|
||||
"",
|
||||
"[Service]",
|
||||
"Type=simple",
|
||||
`ExecStart=${buildServeExecLine(cliPath, { tray: false })}`,
|
||||
"Restart=on-failure",
|
||||
"RestartSec=5",
|
||||
];
|
||||
if (existsSync(envFile)) lines.push(`EnvironmentFile=-${envFile}`);
|
||||
lines.push("", "[Install]", "WantedBy=default.target", "");
|
||||
writeFileSync(linuxSystemdUnitPath(), `${lines.join("\n")}\n`, { mode: 0o644 });
|
||||
}
|
||||
|
||||
function writeLinuxDesktopEntry(cliPath) {
|
||||
const dir = dirname(linuxDesktopPath());
|
||||
mkdirSync(dir, { recursive: true });
|
||||
const desktop =
|
||||
[
|
||||
"[Desktop Entry]",
|
||||
"Type=Application",
|
||||
"Name=OmniRoute",
|
||||
"Comment=AI proxy router with auto fallback",
|
||||
`Exec=${buildServeExecLine(cliPath, { tray: true })}`,
|
||||
"Terminal=false",
|
||||
"Hidden=false",
|
||||
"X-GNOME-Autostart-enabled=true",
|
||||
].join("\n") + "\n";
|
||||
writeFileSync(linuxDesktopPath(), desktop, { mode: 0o644 });
|
||||
}
|
||||
|
||||
export function getAutostartStatus() {
|
||||
if (process.platform === "linux") {
|
||||
const systemdUnit = linuxSystemdUnitPath();
|
||||
const desktopFile = linuxDesktopPath();
|
||||
const systemdUnitExists = existsSync(systemdUnit);
|
||||
const systemdEnabled = isSystemdServiceEnabled() || systemdUnitExists;
|
||||
const desktopEnabled = existsSync(desktopFile);
|
||||
const enabled = systemdEnabled || desktopEnabled;
|
||||
let mechanism = null;
|
||||
if (systemdEnabled) mechanism = "systemd-user";
|
||||
else if (desktopEnabled) mechanism = "xdg-desktop";
|
||||
return {
|
||||
enabled,
|
||||
mechanism,
|
||||
systemdUnit: systemdUnitExists ? systemdUnit : null,
|
||||
desktopFile: desktopEnabled ? desktopFile : null,
|
||||
linger: tryReadLingerEnabled(),
|
||||
};
|
||||
}
|
||||
return { enabled: isAutostartEnabled(), mechanism: null };
|
||||
}
|
||||
|
||||
function tryReadLingerEnabled() {
|
||||
try {
|
||||
const user = process.env.USER || process.env.LOGNAME;
|
||||
if (!user) return null;
|
||||
const out = execFileSync("loginctl", ["show-user", user, "-p", "Linger"], {
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
});
|
||||
return out.includes("Linger=yes");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function enable() {
|
||||
if (process.platform === "darwin") return enableMac();
|
||||
if (process.platform === "win32") return enableWin();
|
||||
if (process.platform === "linux") return enableLinux();
|
||||
return false;
|
||||
}
|
||||
|
||||
export function disable() {
|
||||
if (process.platform === "darwin") return disableMac();
|
||||
if (process.platform === "win32") return disableWin();
|
||||
if (process.platform === "linux") return disableLinux();
|
||||
return false;
|
||||
}
|
||||
|
||||
export function isAutostartEnabled() {
|
||||
if (process.platform === "darwin") return isEnabledMac();
|
||||
if (process.platform === "win32") return isEnabledWin();
|
||||
if (process.platform === "linux") return isEnabledLinux();
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure parse of `launchctl list <label>` output: true only when the agent's
|
||||
* "PID" line matches the given process id. launchctl prints the running PID for
|
||||
* a managed Aqua agent; a loaded-but-not-running agent omits the key entirely.
|
||||
*
|
||||
* Exported for unit testing — the darwin branch can't execute on the Linux CI.
|
||||
*/
|
||||
export function parseAgentSelfFromLaunchctl(output, pid) {
|
||||
if (!output) return false;
|
||||
const match = output.match(/"PID"\s*=\s*(\d+)/);
|
||||
return !!(match && parseInt(match[1], 10) === pid);
|
||||
}
|
||||
|
||||
/**
|
||||
* True when `runList()` (which should run `launchctl list <label>`) succeeds,
|
||||
* i.e. launchd actually recognizes the agent. A plist sitting on disk that
|
||||
* launchd never loaded must NOT count as enabled — checking file existence
|
||||
* alone makes the tray menu lie ("✓ Enabled" while launchd has the agent in a
|
||||
* failed state or never loaded it).
|
||||
*
|
||||
* `runList` is injectable so the parse/branch logic is testable without a real
|
||||
* launchctl on the (Linux) CI runner.
|
||||
*/
|
||||
export function isLaunchdAgentLoaded(runList) {
|
||||
try {
|
||||
runList();
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true when the current Node process IS the running instance launchd is
|
||||
* managing under our agent label.
|
||||
*
|
||||
* `launchctl unload`/`load -w` for a user-domain agent sends SIGTERM to the
|
||||
* running process. When the running OmniRoute cli was itself spawned by the
|
||||
* autostart launchd agent (autostart was enabled, then the machine rebooted,
|
||||
* then the user clicked the tray "Disable Autostart" item), an unload would
|
||||
* kill the very process executing the click handler — the tray icon would
|
||||
* silently disappear instead of the menu label flipping. Enable/disable skip
|
||||
* launchctl in that case; the on-disk plist change is what matters for the next
|
||||
* login, and launchd already has us loaded under our own PID.
|
||||
*/
|
||||
function isAgentSelfMac() {
|
||||
try {
|
||||
const output = execFileSync("launchctl", ["list", APP_LABEL], {
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
timeout: 3000,
|
||||
});
|
||||
return parseAgentSelfFromLaunchctl(output, process.pid);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function enableMac() {
|
||||
const plistDir = join(homedir(), "Library", "LaunchAgents");
|
||||
mkdirSync(plistDir, { recursive: true });
|
||||
const plistPath = join(plistDir, `${APP_LABEL}.plist`);
|
||||
const cliPath = resolveCliPath();
|
||||
if (!cliPath) return false;
|
||||
const plist = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0"><dict>
|
||||
<key>Label</key><string>${APP_LABEL}</string>
|
||||
<key>ProgramArguments</key><array>
|
||||
<string>${process.execPath}</string>
|
||||
<string>${cliPath}</string>
|
||||
<string>serve</string>
|
||||
<string>--tray</string>
|
||||
<string>--no-open</string>
|
||||
</array>
|
||||
<key>RunAtLoad</key><true/>
|
||||
<key>KeepAlive</key><false/>
|
||||
</dict></plist>`;
|
||||
writeFileSync(plistPath, plist, { mode: 0o644 });
|
||||
// If we're already the running agent, launchctl load/unload would SIGTERM us.
|
||||
// The plist is updated on disk and launchd already has us loaded under our own
|
||||
// PID — nothing more to do for the current session.
|
||||
if (isAgentSelfMac()) return existsSync(plistPath);
|
||||
try {
|
||||
execSync("launchctl load -w " + JSON.stringify(plistPath), { stdio: "ignore" });
|
||||
} catch {}
|
||||
return existsSync(plistPath);
|
||||
}
|
||||
|
||||
function disableMac() {
|
||||
const plistPath = join(homedir(), "Library", "LaunchAgents", `${APP_LABEL}.plist`);
|
||||
// Don't kill ourselves: when the current process is the running agent,
|
||||
// `launchctl unload` sends SIGTERM and a user clicking "Disable Autostart"
|
||||
// from the tray would lose the tray icon instead of just flipping the label.
|
||||
// Removing the plist file is enough to stop the agent at the next login.
|
||||
if (!isAgentSelfMac()) {
|
||||
try {
|
||||
execSync("launchctl unload -w " + JSON.stringify(plistPath), { stdio: "ignore" });
|
||||
} catch {}
|
||||
}
|
||||
try {
|
||||
unlinkSync(plistPath);
|
||||
} catch {}
|
||||
return !existsSync(plistPath);
|
||||
}
|
||||
|
||||
function isEnabledMac() {
|
||||
const plistPath = join(homedir(), "Library", "LaunchAgents", `${APP_LABEL}.plist`);
|
||||
if (!existsSync(plistPath)) return false;
|
||||
// The plist file existing is not enough — launchd must actually recognize the
|
||||
// agent, otherwise the tray menu reports "Enabled" for an inert/failed agent.
|
||||
return isLaunchdAgentLoaded(() =>
|
||||
execFileSync("launchctl", ["list", APP_LABEL], {
|
||||
stdio: ["ignore", "ignore", "ignore"],
|
||||
timeout: 3000,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function enableWin() {
|
||||
const cliPath = resolveCliPath();
|
||||
if (!cliPath) return false;
|
||||
const value = `"${process.execPath}" "${cliPath}" serve --tray --no-open`;
|
||||
try {
|
||||
execSync(
|
||||
`reg add HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run /v ${WIN_REG_VALUE} /t REG_SZ /d "${value}" /f`,
|
||||
{ stdio: "ignore", windowsHide: true }
|
||||
);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function disableWin() {
|
||||
try {
|
||||
execSync(
|
||||
`reg delete HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run /v ${WIN_REG_VALUE} /f`,
|
||||
{ stdio: "ignore", windowsHide: true }
|
||||
);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isEnabledWin() {
|
||||
try {
|
||||
const out = execSync(
|
||||
`reg query HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run /v ${WIN_REG_VALUE}`,
|
||||
{ stdio: "pipe", windowsHide: true, encoding: "utf8" }
|
||||
);
|
||||
return out.includes(WIN_REG_VALUE);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function enableLinux() {
|
||||
const cliPath = resolveCliPath();
|
||||
if (!cliPath) return false;
|
||||
|
||||
const graphicalSession = isGraphicalLinuxSession();
|
||||
const systemdAvailable = isSystemdUserAvailable();
|
||||
|
||||
if (!graphicalSession && !systemdAvailable) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let ok = false;
|
||||
|
||||
if (graphicalSession) {
|
||||
writeLinuxDesktopEntry(cliPath);
|
||||
ok = true;
|
||||
} else if (systemdAvailable) {
|
||||
writeLinuxSystemdUnit(cliPath);
|
||||
runUserSystemctl(["daemon-reload"]);
|
||||
ok = runUserSystemctl(["enable", LINUX_SERVICE_NAME]) || existsSync(linuxSystemdUnitPath());
|
||||
runUserSystemctl(["start", LINUX_SERVICE_NAME]);
|
||||
tryEnableLinger();
|
||||
}
|
||||
|
||||
return ok || isEnabledLinux();
|
||||
}
|
||||
|
||||
function disableLinux() {
|
||||
if (isSystemdUserAvailable()) {
|
||||
runUserSystemctl(["disable", "--now", LINUX_SERVICE_NAME]);
|
||||
runUserSystemctl(["daemon-reload"]);
|
||||
}
|
||||
try {
|
||||
unlinkSync(linuxSystemdUnitPath());
|
||||
} catch {}
|
||||
try {
|
||||
unlinkSync(linuxDesktopPath());
|
||||
} catch {}
|
||||
return !isEnabledLinux();
|
||||
}
|
||||
|
||||
function isEnabledLinux() {
|
||||
if (isSystemdServiceEnabled()) return true;
|
||||
if (existsSync(linuxSystemdUnitPath())) return true;
|
||||
return existsSync(linuxDesktopPath());
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Tray autostart — delegates to autostart.mjs (single implementation).
|
||||
*/
|
||||
import { enable, disable, isAutostartEnabled, getAutostartStatus } from "./autostart.mjs";
|
||||
|
||||
export async function enableAutoStart(): Promise<boolean> {
|
||||
return enable();
|
||||
}
|
||||
|
||||
export async function disableAutoStart(): Promise<boolean> {
|
||||
return disable();
|
||||
}
|
||||
|
||||
export async function isAutoStartEnabled(): Promise<boolean> {
|
||||
return isAutostartEnabled();
|
||||
}
|
||||
|
||||
export { getAutostartStatus };
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 713 B |
@@ -0,0 +1,28 @@
|
||||
import { isTraySupported, initSystrayUnix, killSystrayUnix } from "./traySystray.mjs";
|
||||
import { initWinTray, killWinTray } from "./trayWindows.mjs";
|
||||
|
||||
let active = null;
|
||||
|
||||
export { isTraySupported };
|
||||
|
||||
export async function initTray({ port, onQuit, onOpenDashboard, onShowLogs }) {
|
||||
if (!isTraySupported()) return null;
|
||||
const ctx = { port, onQuit, onOpenDashboard, onShowLogs };
|
||||
// initSystrayUnix is async: it lazily installs/loads systray2 from the runtime
|
||||
// dir (trayRuntime.ts) rather than from node_modules. (#4605)
|
||||
active = process.platform === "win32" ? initWinTray(ctx) : await initSystrayUnix(ctx);
|
||||
return active;
|
||||
}
|
||||
|
||||
export function killTray() {
|
||||
if (!active) return;
|
||||
try {
|
||||
if (process.platform === "win32") killWinTray(active);
|
||||
else killSystrayUnix(active);
|
||||
} catch {}
|
||||
active = null;
|
||||
}
|
||||
|
||||
export function isTrayActive() {
|
||||
return active !== null;
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
# OmniRoute tray icon for Windows using NotifyIcon (zero binary, AV-safe)
|
||||
# IPC: stdin JSON commands, stdout JSON events
|
||||
param([string]$IconPath, [string]$Tooltip)
|
||||
|
||||
Add-Type -AssemblyName System.Windows.Forms
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||
[Console]::InputEncoding = [System.Text.Encoding]::UTF8
|
||||
$OutputEncoding = [System.Text.Encoding]::UTF8
|
||||
|
||||
$script:notifyIcon = New-Object System.Windows.Forms.NotifyIcon
|
||||
if ($IconPath -and (Test-Path $IconPath)) {
|
||||
if ($IconPath.ToLower().EndsWith('.ico')) {
|
||||
$script:notifyIcon.Icon = New-Object System.Drawing.Icon($IconPath)
|
||||
} else {
|
||||
# Accepts .png and other bitmap formats via GDI+ handle conversion
|
||||
$bitmap = New-Object System.Drawing.Bitmap($IconPath)
|
||||
$handle = $bitmap.GetHicon()
|
||||
$script:notifyIcon.Icon = [System.Drawing.Icon]::FromHandle($handle)
|
||||
$bitmap.Dispose()
|
||||
}
|
||||
} else {
|
||||
$script:notifyIcon.Icon = [System.Drawing.SystemIcons]::Application
|
||||
}
|
||||
$script:notifyIcon.Text = $Tooltip
|
||||
$script:notifyIcon.Visible = $true
|
||||
|
||||
$script:menu = New-Object System.Windows.Forms.ContextMenuStrip
|
||||
$script:notifyIcon.ContextMenuStrip = $script:menu
|
||||
$script:items = @()
|
||||
|
||||
function Write-Event($obj) {
|
||||
$json = $obj | ConvertTo-Json -Compress
|
||||
[Console]::Out.WriteLine($json)
|
||||
[Console]::Out.Flush()
|
||||
}
|
||||
|
||||
function Add-MenuItem($index, $title, $enabled) {
|
||||
$item = New-Object System.Windows.Forms.ToolStripMenuItem
|
||||
$item.Text = $title
|
||||
$item.Enabled = $enabled
|
||||
$idx = $index
|
||||
$item.Add_Click({ Write-Event @{ type = "click"; index = $idx } }.GetNewClosure())
|
||||
$script:menu.Items.Add($item) | Out-Null
|
||||
$script:items += $item
|
||||
}
|
||||
|
||||
function Update-MenuItem($index, $title, $enabled) {
|
||||
if ($index -lt $script:items.Count) {
|
||||
$script:items[$index].Text = $title
|
||||
$script:items[$index].Enabled = $enabled
|
||||
}
|
||||
}
|
||||
|
||||
function Set-Tooltip($text) {
|
||||
if ($text.Length -gt 63) { $text = $text.Substring(0, 63) }
|
||||
$script:notifyIcon.Text = $text
|
||||
}
|
||||
|
||||
# Read commands from stdin on a timer to keep the Windows message loop alive
|
||||
$reader = [Console]::In
|
||||
$script:running = $true
|
||||
$timer = New-Object System.Windows.Forms.Timer
|
||||
$timer.Interval = 100
|
||||
$timer.Add_Tick({
|
||||
while ($reader.Peek() -ge 0) {
|
||||
$line = $reader.ReadLine()
|
||||
if ($null -eq $line) {
|
||||
$script:notifyIcon.Visible = $false
|
||||
[System.Windows.Forms.Application]::Exit()
|
||||
return
|
||||
}
|
||||
try {
|
||||
$cmd = $line | ConvertFrom-Json
|
||||
switch ($cmd.type) {
|
||||
"setMenu" {
|
||||
$script:menu.Items.Clear()
|
||||
$script:items = @()
|
||||
for ($i = 0; $i -lt $cmd.items.Count; $i++) {
|
||||
$it = $cmd.items[$i]
|
||||
Add-MenuItem $i $it.title $it.enabled
|
||||
}
|
||||
}
|
||||
"updateItem" { Update-MenuItem $cmd.index $cmd.title $cmd.enabled }
|
||||
"setTooltip" { Set-Tooltip $cmd.text }
|
||||
"quit" {
|
||||
$script:notifyIcon.Visible = $false
|
||||
[System.Windows.Forms.Application]::Exit()
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
})
|
||||
$timer.Start()
|
||||
|
||||
Write-Event @{ type = "ready" }
|
||||
[System.Windows.Forms.Application]::Run()
|
||||
@@ -0,0 +1,186 @@
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { join, dirname } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { initWindowsTray, type WinTrayHandle } from "./trayWin.ts";
|
||||
import { enableAutoStart, disableAutoStart, isAutoStartEnabled } from "./autostart.ts";
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
export interface MenuItem {
|
||||
title: string;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export interface TrayOptions {
|
||||
port: number;
|
||||
onQuit: () => void;
|
||||
onOpenDashboard: () => void;
|
||||
}
|
||||
|
||||
export interface TrayInstance {
|
||||
update(items: MenuItem[]): void;
|
||||
setTooltip(text: string): void;
|
||||
destroy(): void;
|
||||
}
|
||||
|
||||
// Minimal 16x16 OmniRoute icon as base64 PNG (fallback when file missing)
|
||||
const FALLBACK_ICON_BASE64 =
|
||||
"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAALEwAACxMBAJqcGAAAAHpJREFUOE9jYBgFgwEwMjIy/Gdg+P8fyP4PxP8ZGBgEcBnGyMjIsICBgSEAhyH/gfgBUNN8XJoZsdkCVL8Ah+b/QPwbqvkBMvk/AwMDAzYX/GdgYAhAN+A/SICRWAMYGfFEJSMjzriEiwDR/xmIa2RkZCSqnZERb3QCAAo3KxzxbKe1AAAAAElFTkSuQmCC";
|
||||
|
||||
export function getIconPath(): string {
|
||||
const isWin = process.platform === "win32";
|
||||
// On Windows prefer .ico but fall back to .png (tray.ps1 handles both via GDI+)
|
||||
const candidates = isWin ? ["icon.ico", "icon.png"] : ["icon.png"];
|
||||
for (const iconFile of candidates) {
|
||||
const iconPath = join(__dirname, iconFile);
|
||||
if (existsSync(iconPath)) return iconPath;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
export function getIconBase64(): string {
|
||||
const iconPath = getIconPath();
|
||||
if (iconPath) {
|
||||
try {
|
||||
return readFileSync(iconPath).toString("base64");
|
||||
} catch {
|
||||
// fall through to default
|
||||
}
|
||||
}
|
||||
return FALLBACK_ICON_BASE64;
|
||||
}
|
||||
|
||||
export function isTraySupported(): boolean {
|
||||
const p = process.platform;
|
||||
if (!["darwin", "win32", "linux"].includes(p)) return false;
|
||||
if (p === "linux" && !process.env.DISPLAY) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
export function buildMenuItems(args: { port: number; autostartEnabled: boolean }): MenuItem[] {
|
||||
return [
|
||||
{ title: "Open OmniRoute Dashboard", enabled: true },
|
||||
{ title: `Port: ${args.port}`, enabled: false },
|
||||
{ title: args.autostartEnabled ? "Disable Autostart" : "Enable Autostart", enabled: true },
|
||||
{ title: "Quit OmniRoute", enabled: true },
|
||||
];
|
||||
}
|
||||
|
||||
const MENU_INDEX = {
|
||||
OPEN_DASHBOARD: 0,
|
||||
PORT: 1,
|
||||
AUTOSTART_TOGGLE: 2,
|
||||
QUIT: 3,
|
||||
} as const;
|
||||
|
||||
export async function initTray(options: TrayOptions): Promise<TrayInstance | null> {
|
||||
if (!isTraySupported()) return null;
|
||||
if (process.platform === "win32") return initWindowsTrayInstance(options);
|
||||
return initUnixTray(options);
|
||||
}
|
||||
|
||||
async function initWindowsTrayInstance(options: TrayOptions): Promise<TrayInstance | null> {
|
||||
const iconPath = getIconPath();
|
||||
if (!iconPath) return null;
|
||||
let autostartEnabled = await isAutoStartEnabled();
|
||||
let handle: WinTrayHandle | null = null;
|
||||
handle = initWindowsTray({
|
||||
iconPath,
|
||||
tooltip: `OmniRoute :${options.port}`,
|
||||
onEvent: async (evt) => {
|
||||
if (evt.type !== "click") return;
|
||||
switch (evt.index) {
|
||||
case MENU_INDEX.OPEN_DASHBOARD:
|
||||
options.onOpenDashboard();
|
||||
break;
|
||||
case MENU_INDEX.AUTOSTART_TOGGLE: {
|
||||
if (autostartEnabled) await disableAutoStart();
|
||||
else await enableAutoStart();
|
||||
autostartEnabled = !autostartEnabled;
|
||||
handle?.update(buildMenuItems({ port: options.port, autostartEnabled }));
|
||||
break;
|
||||
}
|
||||
case MENU_INDEX.QUIT:
|
||||
options.onQuit();
|
||||
break;
|
||||
}
|
||||
},
|
||||
});
|
||||
if (!handle) return null;
|
||||
handle.update(buildMenuItems({ port: options.port, autostartEnabled }));
|
||||
return {
|
||||
update: (items) => handle!.update(items),
|
||||
setTooltip: (text) => handle!.setTooltip(text),
|
||||
destroy: () => handle!.destroy(),
|
||||
};
|
||||
}
|
||||
|
||||
async function initUnixTray(options: TrayOptions): Promise<TrayInstance | null> {
|
||||
const { loadSystray } = await import("../runtime/trayRuntime.ts");
|
||||
const SysTray = await loadSystray();
|
||||
if (!SysTray) return null;
|
||||
let autostartEnabled = await isAutoStartEnabled();
|
||||
const menuItems = buildMenuItems({ port: options.port, autostartEnabled });
|
||||
const systray = new SysTray({
|
||||
menu: {
|
||||
icon: getIconBase64(),
|
||||
// isTemplateIcon: false on darwin — the bundled icon.png is a full-color
|
||||
// RGBA logo; template mode would render it as a solid white square
|
||||
// because macOS template icons only use the alpha channel. (PR #1080)
|
||||
isTemplateIcon: false,
|
||||
title: "OmniRoute",
|
||||
tooltip: `OmniRoute :${options.port}`,
|
||||
items: menuItems.map((it) => ({
|
||||
title: it.title,
|
||||
tooltip: "",
|
||||
checked: false,
|
||||
enabled: it.enabled,
|
||||
})),
|
||||
},
|
||||
debug: false,
|
||||
copyDir: false,
|
||||
});
|
||||
systray.onClick(async (action: { seq_id: number }) => {
|
||||
switch (action.seq_id) {
|
||||
case MENU_INDEX.OPEN_DASHBOARD:
|
||||
options.onOpenDashboard();
|
||||
break;
|
||||
case MENU_INDEX.AUTOSTART_TOGGLE: {
|
||||
if (autostartEnabled) await disableAutoStart();
|
||||
else await enableAutoStart();
|
||||
autostartEnabled = !autostartEnabled;
|
||||
systray.sendAction({
|
||||
type: "update-item",
|
||||
item: {
|
||||
title: autostartEnabled ? "Disable Autostart" : "Enable Autostart",
|
||||
enabled: true,
|
||||
checked: false,
|
||||
tooltip: "",
|
||||
},
|
||||
seq_id: MENU_INDEX.AUTOSTART_TOGGLE,
|
||||
});
|
||||
break;
|
||||
}
|
||||
case MENU_INDEX.QUIT:
|
||||
options.onQuit();
|
||||
break;
|
||||
}
|
||||
});
|
||||
return {
|
||||
update: (items) => {
|
||||
items.forEach((it, idx) => {
|
||||
systray.sendAction({
|
||||
type: "update-item",
|
||||
item: { title: it.title, enabled: it.enabled, checked: false, tooltip: "" },
|
||||
seq_id: idx,
|
||||
});
|
||||
});
|
||||
},
|
||||
setTooltip: () => {
|
||||
/* systray2 does not support runtime tooltip change */
|
||||
},
|
||||
// Pass false so systray2's kill does NOT call process.exit(0) before the
|
||||
// rest of cleanup (server SIGKILL, MITM/tunnel cleanup) runs. (PR #1080)
|
||||
destroy: () => systray.kill(false),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { join, dirname } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { isAutostartEnabled } from "./autostart.mjs";
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
const MENU_INDEX = { STATUS: 0, DASHBOARD: 1, LOGS: 2, AUTOSTART: 3, QUIT: 4 };
|
||||
|
||||
export function isTraySupported() {
|
||||
const p = process.platform;
|
||||
if (!["darwin", "linux", "win32"].includes(p)) return false;
|
||||
if (p === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// systray2 is NOT a static dependency — it is lazily installed into
|
||||
// ~/.omniroute/runtime by trayRuntime.ts (loadSystray). The previous inline
|
||||
// loader called `require("module")`, which throws `ReferenceError: require is
|
||||
// not defined` in this ESM file (package "type":"module"); the throw was
|
||||
// silently swallowed, so the tray never appeared on macOS/Linux with no error
|
||||
// printed (#4605, regressed in v3.8.34). Delegate to the runtime loader, which
|
||||
// resolves systray2 from the runtime dir and surfaces install/import failures.
|
||||
async function loadSystray2() {
|
||||
const { loadSystray } = await import("../runtime/trayRuntime.ts");
|
||||
return loadSystray();
|
||||
}
|
||||
|
||||
function getIconBase64() {
|
||||
// Icon ships at bin/cli/tray/icon.png — the previous "icons/icon.png" path
|
||||
// never existed, so the tray was created with an empty icon (#4605).
|
||||
const iconPath = join(__dirname, "icon.png");
|
||||
if (existsSync(iconPath)) return readFileSync(iconPath).toString("base64");
|
||||
return "";
|
||||
}
|
||||
|
||||
export async function initSystrayUnix(
|
||||
{ port, onQuit, onOpenDashboard, onShowLogs },
|
||||
loadCtor = loadSystray2
|
||||
) {
|
||||
const SysTray = await loadCtor();
|
||||
if (!SysTray) return null;
|
||||
|
||||
const autostartEnabled = isAutostartEnabled();
|
||||
const items = [
|
||||
{ title: `OmniRoute • port ${port}`, tooltip: "Server running", enabled: false },
|
||||
{ title: "Open Dashboard", enabled: true },
|
||||
{ title: "Show Logs", enabled: true },
|
||||
{
|
||||
title: autostartEnabled ? "✓ Auto-start (click to disable)" : "Enable Auto-start",
|
||||
enabled: true,
|
||||
},
|
||||
{ title: "Quit OmniRoute", enabled: true },
|
||||
];
|
||||
|
||||
let tray;
|
||||
try {
|
||||
tray = new SysTray({
|
||||
menu: {
|
||||
icon: getIconBase64(),
|
||||
// isTemplateIcon must be false: icon.png is a full-color RGBA logo, and
|
||||
// macOS template mode uses only the alpha channel → a solid white square
|
||||
// (the icon looked "missing" even when the tray loaded). (PR #1080)
|
||||
isTemplateIcon: false,
|
||||
title: "",
|
||||
tooltip: `OmniRoute — port ${port}`,
|
||||
items,
|
||||
},
|
||||
debug: false,
|
||||
copyDir: false,
|
||||
});
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
tray.onClick(async (action) => {
|
||||
if (action.seq_id === MENU_INDEX.DASHBOARD) {
|
||||
onOpenDashboard?.();
|
||||
} else if (action.seq_id === MENU_INDEX.LOGS) {
|
||||
onShowLogs?.();
|
||||
} else if (action.seq_id === MENU_INDEX.AUTOSTART) {
|
||||
const { enable, disable, isAutostartEnabled: isEnabled } = await import("./autostart.mjs");
|
||||
const wasOn = isEnabled();
|
||||
if (wasOn) disable();
|
||||
else enable();
|
||||
const nowOn = !wasOn;
|
||||
tray.sendAction({
|
||||
type: "update-item",
|
||||
item: {
|
||||
title: nowOn ? "✓ Auto-start (click to disable)" : "Enable Auto-start",
|
||||
enabled: true,
|
||||
},
|
||||
seq_id: MENU_INDEX.AUTOSTART,
|
||||
});
|
||||
} else if (action.seq_id === MENU_INDEX.QUIT) {
|
||||
onQuit?.();
|
||||
}
|
||||
});
|
||||
|
||||
tray.ready().catch((err) => {
|
||||
process.stderr.write(`[omniroute][tray] systray2 failed: ${err?.message ?? String(err)}\n`);
|
||||
});
|
||||
|
||||
return tray;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the Go systray2 child subprocess PID from a tray instance.
|
||||
* systray2 exposes the spawned binary either as the `_process` field or via a
|
||||
* `process()` accessor depending on version. Returns the numeric PID or null.
|
||||
*/
|
||||
export function getSystrayChildPid(tray) {
|
||||
if (!tray) return null;
|
||||
try {
|
||||
const proc = tray._process || (typeof tray.process === "function" ? tray.process() : null);
|
||||
if (proc && typeof proc.pid === "number") return proc.pid;
|
||||
} catch {}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function killSystrayUnix(tray) {
|
||||
try {
|
||||
// systray2.kill(false) closes the IPC channel but leaves the Go tray binary
|
||||
// subprocess running, which keeps an orphan NSStatusItem on macOS and blocks
|
||||
// a freshly spawned tray (e.g. on respawn / hide-to-tray) from registering.
|
||||
// SIGKILL the child PID directly first, then close IPC.
|
||||
const pid = getSystrayChildPid(tray);
|
||||
if (pid) {
|
||||
try {
|
||||
process.kill(pid, "SIGKILL");
|
||||
} catch {}
|
||||
}
|
||||
tray.kill(false);
|
||||
} catch {}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { join, dirname } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const PS1_PATH = join(__dirname, "tray.ps1");
|
||||
|
||||
export interface WinTrayEvent {
|
||||
type: "click" | "ready" | "error";
|
||||
index?: number;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface WinTrayOptions {
|
||||
iconPath: string;
|
||||
tooltip: string;
|
||||
onEvent: (evt: WinTrayEvent) => void;
|
||||
}
|
||||
|
||||
export interface WinTrayHandle {
|
||||
update(items: Array<{ title: string; enabled: boolean }>): void;
|
||||
setTooltip(text: string): void;
|
||||
destroy(): void;
|
||||
}
|
||||
|
||||
export function initWindowsTray(opts: WinTrayOptions): WinTrayHandle | null {
|
||||
let child: ChildProcess;
|
||||
try {
|
||||
child = spawn(
|
||||
"powershell.exe",
|
||||
[
|
||||
"-NoLogo",
|
||||
"-NoProfile",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-File",
|
||||
PS1_PATH,
|
||||
"-IconPath",
|
||||
opts.iconPath,
|
||||
"-Tooltip",
|
||||
opts.tooltip,
|
||||
],
|
||||
{ stdio: ["pipe", "pipe", "pipe"], windowsHide: true }
|
||||
);
|
||||
} catch (err) {
|
||||
opts.onEvent({ type: "error", error: String(err) });
|
||||
return null;
|
||||
}
|
||||
|
||||
child.stdout?.setEncoding("utf-8");
|
||||
let buffer = "";
|
||||
child.stdout?.on("data", (chunk: string) => {
|
||||
buffer += chunk;
|
||||
let nl: number;
|
||||
while ((nl = buffer.indexOf("\n")) >= 0) {
|
||||
const line = buffer.slice(0, nl).trim();
|
||||
buffer = buffer.slice(nl + 1);
|
||||
if (!line) continue;
|
||||
try {
|
||||
const evt = JSON.parse(line) as WinTrayEvent;
|
||||
opts.onEvent(evt);
|
||||
} catch {
|
||||
// ignore malformed JSON lines
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
child.on("error", (err) => opts.onEvent({ type: "error", error: err.message }));
|
||||
|
||||
function send(cmd: object): void {
|
||||
if (!child.stdin?.writable) return;
|
||||
child.stdin.write(JSON.stringify(cmd) + "\n");
|
||||
}
|
||||
|
||||
return {
|
||||
update(items) {
|
||||
send({ type: "setMenu", items });
|
||||
},
|
||||
setTooltip(text) {
|
||||
send({ type: "setTooltip", text });
|
||||
},
|
||||
destroy() {
|
||||
try {
|
||||
send({ type: "quit" });
|
||||
} catch {
|
||||
// already dead
|
||||
}
|
||||
setTimeout(() => child.kill(), 500);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { writeFileSync, unlinkSync, existsSync } from "node:fs";
|
||||
|
||||
const OMNIROUTE_IPC_PORT_BASE = 29128;
|
||||
|
||||
export function initWinTray({ port, onQuit, onOpenDashboard, onShowLogs }) {
|
||||
if (process.platform !== "win32") return null;
|
||||
|
||||
const ipcPort = OMNIROUTE_IPC_PORT_BASE + (port % 1000);
|
||||
const scriptPath = join(tmpdir(), `omniroute-tray-${process.pid}.ps1`);
|
||||
|
||||
const ps1 = `
|
||||
Add-Type -AssemblyName System.Windows.Forms
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
|
||||
$tray = New-Object System.Windows.Forms.NotifyIcon
|
||||
$tray.Text = "OmniRoute - Port ${port}"
|
||||
$tray.Icon = [System.Drawing.SystemIcons]::Application
|
||||
$tray.Visible = $true
|
||||
|
||||
$menu = New-Object System.Windows.Forms.ContextMenuStrip
|
||||
|
||||
$mDash = $menu.Items.Add("Open Dashboard")
|
||||
$mDash.add_Click({ [System.Net.Sockets.TcpClient]::new("127.0.0.1", ${ipcPort}).Close(); Write-Host "DASHBOARD" })
|
||||
|
||||
$mLogs = $menu.Items.Add("Show Logs")
|
||||
$mLogs.add_Click({ Write-Host "LOGS" })
|
||||
|
||||
$mAutostart = $menu.Items.Add("Enable Auto-start")
|
||||
$mAutostart.add_Click({ Write-Host "AUTOSTART" })
|
||||
|
||||
$mQuit = $menu.Items.Add("Quit OmniRoute")
|
||||
$mQuit.add_Click({ Write-Host "QUIT"; [System.Windows.Forms.Application]::Exit() })
|
||||
|
||||
$tray.ContextMenuStrip = $menu
|
||||
[System.Windows.Forms.Application]::Run()
|
||||
$tray.Dispose()
|
||||
`.trim();
|
||||
|
||||
writeFileSync(scriptPath, ps1, "utf8");
|
||||
|
||||
const proc = spawn("powershell.exe", ["-NonInteractive", "-File", scriptPath], {
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
windowsHide: true,
|
||||
detached: false,
|
||||
shell: false,
|
||||
});
|
||||
|
||||
proc.stdout.on("data", async (data) => {
|
||||
const line = data.toString().trim();
|
||||
if (line === "DASHBOARD") onOpenDashboard?.();
|
||||
else if (line === "LOGS") onShowLogs?.();
|
||||
else if (line === "AUTOSTART") {
|
||||
const { enable, disable, isAutostartEnabled } = await import("./autostart.mjs");
|
||||
if (isAutostartEnabled()) disable();
|
||||
else enable();
|
||||
} else if (line === "QUIT") onQuit?.();
|
||||
});
|
||||
|
||||
proc.on("exit", () => {
|
||||
try {
|
||||
if (existsSync(scriptPath)) unlinkSync(scriptPath);
|
||||
} catch {}
|
||||
});
|
||||
|
||||
return proc;
|
||||
}
|
||||
|
||||
export function killWinTray(proc) {
|
||||
try {
|
||||
proc.kill("SIGTERM");
|
||||
} catch {}
|
||||
}
|
||||
Reference in New Issue
Block a user