fix: tools improvements

This commit is contained in:
fufsob committed 2026-09-15 14:44:24 +00:00
1 parent e9b1542085
commit 303821f43a
8 files changed
+233 -89

No files matched your search

+7
View File
@@ -195,6 +195,11 @@
[ "$(cat obd/chained.detour)" = own-vps ]
run proxy outbounds rm chained > /dev/null
[ ! -e obd/chained.detour ]
# A hop left behind does not chain a later entry of the same name.
echo own-vps > obd/unchained.detour
run proxy outbounds add unchained http://example.com:1 > /dev/null
[ ! -e obd/unchained.detour ]
run proxy outbounds rm unchained > /dev/null
# JSON, as `link --json` prints it, lands as <tag>.json without its own tag; stdin too.
run proxy outbounds add from-json '{"type":"trojan","tag":"x","server":"t.test","server_port":443,"password":"p"}' \
@@ -357,6 +362,8 @@
has community-de proxy outbounds test own-vps
has --download proxy outbounds test own-vps --ping
has own-vps proxy auto probe example.com --via
has community-de proxy outbounds add hop https://example.com --detour
has outbound inbounds stats --by
# Unreadable state loses the values, not the flags.
has --qr inbounds sub
+64 -29
View File
@@ -325,7 +325,7 @@ COMPLETE = {
}
},
"status": {"flags": {"--json": "machine-readable state, with the GUI's overall state"}},
"logs": {"args": lambda: _names([*ALL_SERVICES, *map(_awg_service, _awg_profiles())]), "repeat": True},
"logs": {"args": lambda: _names(_snapshot_units()), "repeat": True},
"where": {"args": _autoproxy_choices},
"proxy": {
"words": {
@@ -456,8 +456,10 @@ def _complete_tree(*words):
while rest and f"{path} {rest[0]}".strip() in COMPLETE:
path = f"{path} {rest.pop(0)}".strip()
node = COMPLETE[path]
if rest[-1:] in (["--exits"], ["--via"]):
if rest[-1:] in (["--exits"], ["--via"], ["--detour"]):
return _outbound_choices()
if rest[-1:] == ["--by"]:
return _names(STATS_KINDS)
candidates = {}
if node.get("repeat") or not [w for w in rest if not w.startswith("-")]:
candidates.update(node.get("words", {}))
@@ -529,7 +531,10 @@ BUSY_STATES = ("activating", "deactivating", "reloading")
def _snapshot_units():
return [*ALL_SERVICES, SUBSCRIPTION_UPDATE, *map(_awg_service, _awg_profiles())]
profiles = _awg_profiles()
# WARP as an AmneziaWG outbound has no profile to toggle, but it is a unit that can fail (_warp_unit).
warp = [] if "warp" in profiles else [_awg_service("warp")]
return [*ALL_SERVICES, SUBSCRIPTION_UPDATE, *map(_awg_service, profiles), *warp]
def _status_snapshot(states=None):
@@ -635,11 +640,14 @@ def _svc_status(unit):
def _status_outbound():
"""The pin when there is one, otherwise whatever the backend is dialling."""
pinned = _outbound_inventory().get("pinned")
if pinned:
return f"{_s(pinned)} (pinned)"
return _outbound_current()
"""The pin when there is one, otherwise whatever the backend is dialling, and the hop it chains through."""
inventory = _outbound_inventory()
pinned = _s(inventory.get("pinned") or "")
tag = pinned or _outbound_current()
# ponytail: detours are keyed by the inventory's tags; a `now` named otherwise shows no hop.
hop = (inventory.get("detours") or {}).get(tag) if tag else None
text = f"{tag} via {_s(hop)}" if hop else tag
return f"{text} (pinned)" if pinned else text
def _status_autoproxy():
@@ -683,10 +691,9 @@ def cmd_status(*args):
_status_tray()
return
print("proxy-suite services:")
for svc in ALL_SERVICES:
_svc_status(svc)
for profile in _awg_profiles():
_svc_status(_awg_service(profile))
for svc in _snapshot_units():
if svc != SUBSCRIPTION_UPDATE:
_svc_status(svc)
if svc_exists("proxy-suite-socks"):
print()
print("routing:")
@@ -1195,9 +1202,12 @@ def _runtime_entry_add(kind, tag="", url="", *_, detour=""):
old = os.umask(0o027)
try:
# The hop first: the entry is what the start script looks for.
hop = os.path.join(_runtime_dir(kind), f"{tag}.detour")
if detour:
with open(os.path.join(_runtime_dir(kind), f"{tag}.detour"), "w", encoding="utf-8") as f:
with open(hop, "w", encoding="utf-8") as f:
f.write(f"{detour}\n")
elif os.path.exists(hop):
os.unlink(hop) # left from an earlier entry of this name: it would chain this one too
with open(path, "w", encoding="utf-8") as f:
f.write(f"{url}\n")
except OSError:
@@ -1303,6 +1313,10 @@ def _subscription_list():
_subscription_row(tag, "static")
for tag in runtime:
_subscription_row(tag, "runtime")
next_run = _timer_next_run(f"{SUBSCRIPTION_UPDATE}.timer")
if next_run:
print()
print(f"Next update: {datetime.datetime.fromtimestamp(next_run):%H:%M:%S}, {_in_time(next_run)}")
def cmd_subscription(verb="list", *args):
@@ -1677,19 +1691,27 @@ def cmd_proxy_probe(*args):
# struck by several destinations within a TTL is bad, and probed last.
def _backend_tags():
"""User outbound tag -> the backend's tag, which probe exits and their reputation are keyed by."""
try:
return read_json(_runtime_file("outbound-test.json")).get("outbounds") or {}
except (OSError, ValueError, AttributeError):
return {}
def _backend_tag(tag, backend=None):
return _s((_backend_tags() if backend is None else backend).get(tag) or tag)
def _reputation_by_tag():
"""User tag -> "bad" or "ok" once the prober has judged its exit; {} before it has."""
if env("AUTOPROXY_ENABLED") != "1":
return {}
exits = _autoproxy_state(_autoproxy_dir()).get("exits") or {}
# Exits are keyed by the backend's tag; outbound-test.json maps the user's to it.
try:
backend = read_json(_runtime_file("outbound-test.json")).get("outbounds") or {}
except (OSError, ValueError, AttributeError):
backend = {}
backend = _backend_tags()
out = {}
for tag in _outbound_tags():
e = exits.get(_s(backend.get(tag) or tag))
e = exits.get(_backend_tag(tag, backend))
if isinstance(e, dict) and "strikes" in e:
out[tag] = "bad" if e.get("bad") is True else "ok"
return out
@@ -1734,11 +1756,15 @@ def cmd_proxy_auto(verb="list", *args):
def _autoproxy_next_run():
"""Epoch seconds of the next timer run, None when none is armed.
return _timer_next_run("proxy-suite-autoproxy.timer")
The timer is relative, so only list-timers knows it.
def _timer_next_run(timer):
"""Epoch seconds of the timer's next run, None when none is armed.
The timers are relative, so only list-timers knows it.
"""
_, out = systemctl("list-timers", "-o", "json", "proxy-suite-autoproxy.timer", capture=True, quiet=True)
_, out = systemctl("list-timers", "-o", "json", timer, capture=True, quiet=True)
try:
next_run = json.loads(out)[0].get("next")
except (ValueError, IndexError, AttributeError, TypeError, KeyError):
@@ -2486,8 +2512,8 @@ def _inbound_stats(*args):
print(total.format(name, _human_bytes(down), _human_bytes(up)))
def _inbound_online():
"""Users connected right now with their addresses, then when the others were last seen."""
def _inbound_presence():
"""user -> (state, addresses): "online", "seen <time>" or "never seen"; dies when the stats API is silent."""
status, out = _run(
[env("INBOUNDS_XRAY", "xray"), "api", "statsonlineiplist", f"--server={env('INBOUNDS_API', '127.0.0.1:18536')}", "-all"],
capture=True,
@@ -2509,16 +2535,25 @@ def _inbound_online():
def when(ts):
return datetime.datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M")
row = " {:<20} {:<24} {}"
print(row.format("USER", "STATE", "ADDRESSES"))
presence = {}
for user in sorted(set(online) | set(seen) | known):
ips = online.get(user)
if ips:
print(row.format(user, "online", ", ".join(_s(i.get("ip")) for i in ips)))
presence[user] = ("online", ", ".join(_s(i.get("ip")) for i in ips))
elif user in seen:
print(row.format(user, f"seen {when(seen[user])}", ""))
presence[user] = (f"seen {when(seen[user])}", "")
else:
print(row.format(user, "never seen", ""))
presence[user] = ("never seen", "")
return presence
def _inbound_online():
"""Users connected right now with their addresses, then when the others were last seen."""
row = " {:<20} {:<24} {}"
presence = _inbound_presence()
print(row.format("USER", "STATE", "ADDRESSES"))
for user, (state, addresses) in presence.items():
print(row.format(user, state, addresses))
sys.stdout.flush()
print("A user counts as online while a connection is open; one relayed through a local web server shows as never seen.", file=sys.stderr)
+17 -22
View File
@@ -20,7 +20,7 @@ gi.require_version("Adw", "1")
from gi.repository import Adw, Gdk, Gio, GLib, GObject, Gtk, Pango # noqa: E402
import proxy_model as model # noqa: E402
from proxy_model import CTL, TABS, ctl # noqa: E402
from proxy_model import STATE_ICONS, TABS, ctl # noqa: E402
APP_ID = "io.github.FUFSoB.ProxySuite"
TITLE = "Proxy Suite"
@@ -34,7 +34,6 @@ def refresh_seconds():
return 3
STATE_ICONS = {"active": "●", "inactive": "○", "failed": "✗", "activating": "◐", "deactivating": "◐", "reloading": "◐"}
STATE_CLASSES = {"active": ["success"], "inactive": ["dim-label"], "failed": ["error", "heading"], "activating": ["warning"], "deactivating": ["warning"], "reloading": ["warning"]}
CELL_CLASSES = {
"ok": ["success"],
@@ -46,6 +45,7 @@ CELL_CLASSES = {
"pinned": ["accent"],
"excluded": ["dim-label"],
"queued": ["warning"],
"online": ["success"],
}
TAB_ICONS = {
"services": "system-run-symbolic",
@@ -251,7 +251,7 @@ def cell_text(name, value):
return value, CELL_CLASSES.get(value, [])
BADGE_VALUES = {"ok", "bad", "runtime", "pinned", "excluded", "queued"}
BADGE_VALUES = {"ok", "bad", "runtime", "pinned", "excluded", "queued", "online"}
def is_badge(name, value):
@@ -381,12 +381,9 @@ class Page(Gtk.Box):
label._handler = None
def compare(self, a, b, name):
# Text and digit runs alternate in the same places, so the lists always compare.
ka, kb = model._natural(a.row.get(name)), model._natural(b.row.get(name))
try:
return (ka > kb) - (ka < kb)
except TypeError: # a number against text in the same place
sa, sb = str(ka), str(kb)
return (sa > sb) - (sa < sb)
return (ka > kb) - (ka < kb)
# --- keys -------------------------------------------------------------------------
@@ -722,11 +719,7 @@ class OutputDialog(Adw.Dialog):
self.qr.set_visible(True)
def terminate(self):
if self.proc and self.proc.poll() is None:
try:
os.killpg(self.proc.pid, signal.SIGTERM)
except OSError:
self.proc.terminate()
model.stop(self.proc)
# --- window -------------------------------------------------------------------------------
@@ -774,6 +767,7 @@ class Window(Adw.ApplicationWindow):
view.add_top_bar(header)
self.status = Adw.WrapBox(child_spacing=18, line_spacing=2, css_classes=["status-strip"])
self.status_items = None
view.add_top_bar(self.status)
self.banner = Adw.Banner(title="", revealed=False, button_label="Retry", action_name="app.reload")
view.add_top_bar(self.banner)
@@ -872,6 +866,10 @@ class Window(Adw.ApplicationWindow):
return False
def show_status(self, items):
# Only a change rebuilds the chips: the refresh tick sends the same items every few seconds.
if items == self.status_items:
return
self.status_items = items
while child := self.status.get_first_child():
self.status.remove(child)
for n, (label, value, style) in enumerate(items):
@@ -924,8 +922,7 @@ class Window(Adw.ApplicationWindow):
except (ValueError, IndexError) as e:
self.toast(f"Cannot run that: {e}")
return
confirm = action.confirm(row) if callable(action.confirm) else action.confirm
if confirm:
if model.needs_confirm(action, row):
self.app.confirm(argv, lambda: self.app.run_argv(action.mode, argv, self), self)
else:
self.app.run_argv(action.mode, argv, self)
@@ -1105,7 +1102,8 @@ class ProxySuiteGui(Adw.Application):
model.new_load()
states = model._read_states()
snap = model.snapshot(states) if states else None
tray = (model.tray_menu(snap, model.tray_outbounds(snap)), ctl._overall_state(snap))
outbound = model._safe(ctl._status_outbound, fallback="") if snap and snap["proxy"]["active"] else ""
tray = (model.tray_menu(snap, model.tray_outbounds(snap)), ctl._overall_state(snap), outbound)
result = {"states": states, "snap": snap, "tray": tray}
if tab is not None:
result["visible"] = model.available_tabs(states)
@@ -1120,10 +1118,10 @@ class ProxySuiteGui(Adw.Application):
if generation == self.generation:
self.states = result["states"]
snap = result["snap"]
tree, overall = result["tray"]
tree, overall, outbound = result["tray"]
if self.tray:
failed = snap["failed"] if snap else []
tooltip = overall["label"] + (f"\nFailed: {', '.join(failed)}" if failed else "")
tooltip = overall["label"] + (f"\nOutbound: {outbound}" if outbound else "") + (f"\nFailed: {', '.join(failed)}" if failed else "")
self.tray.update(model.icon_name(overall), tooltip, tree, attention=bool(failed))
self.notify_failures(snap)
if "tab" in result and self.window:
@@ -1188,10 +1186,7 @@ class ProxySuiteGui(Adw.Application):
def stream(self, command, argv, mode, win, dialog, qr):
out = []
try:
p = subprocess.Popen(
[CTL, *argv], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL,
text=True, errors="replace", start_new_session=True,
)
p = model.popen(argv)
if dialog:
GLib.idle_add(lambda: dialog.running(p) and False)
for line in p.stdout:
+81 -15
View File
@@ -8,6 +8,7 @@ die() cannot take a front end down.
import os
import re
import shlex
import signal
import subprocess
import sys
import time
@@ -25,7 +26,7 @@ def _die(message, status=1):
# Clash API calls and systemctl spawns that several readers repeat within one load.
MEMOIZED = ("_outbound_current", "_outbound_inventory", "_autoproxy_state", "_autoproxy_next_run", "svc_state")
MEMOIZED = ("_outbound_current", "_outbound_inventory", "_autoproxy_state", "_timer_next_run", "svc_state")
# proxy_ctl as the CLI has it, before the patching below: its own tests put these back.
CLI_FUNCTIONS = {name: getattr(ctl, name) for name in ("die", *MEMOIZED)}
@@ -78,6 +79,13 @@ def ROW(_):
return True
def needs_confirm(action, row):
return action.confirm(row) if callable(action.confirm) else action.confirm
STATE_ICONS = {"active": "●", "inactive": "○", "failed": "✗", "activating": "◐", "deactivating": "◐", "reloading": "◐"}
# --- readers ------------------------------------------------------------------
@@ -103,6 +111,8 @@ TOGGLES = {
"proxy-suite-tproxy": ["proxy", "tproxy"],
"proxy-suite-ssh-proxy": ["ssh"],
"proxy-suite-warp-tunnel": ["warp"],
# WARP as an AmneziaWG outbound: `proxy-ctl warp`, not `awg`, which only knows global profiles.
"proxy-suite-awg-warp": ["warp"],
"proxy-suite-tg-ws-proxy": ["tg"],
"proxy-suite-zapret": ["zapret"],
}
@@ -114,10 +124,16 @@ ZAPRET_LISTS = (
)
def _awg_profile(row):
"""The global AmneziaWG profile behind a row, or empty."""
name = row["unit"].removeprefix(AWG_PREFIX)
return name if row["unit"].startswith(AWG_PREFIX) and name in ctl._awg_profiles() else ""
def toggle_argv(row, *_):
verb = "off" if row["state"] == "active" else "on"
if row["unit"].startswith(AWG_PREFIX):
return ["awg", verb, row["unit"].removeprefix(AWG_PREFIX)]
if profile := _awg_profile(row):
return ["awg", verb, profile]
return [*TOGGLES[row["unit"]], verb]
@@ -141,6 +157,8 @@ def outbound_rows(_):
inventory = ctl._outbound_inventory()
pinned = ctl._s(inventory.get("pinned") or "")
sources = inventory.get("sources") or {}
detours = inventory.get("detours") or {}
excluded = set(inventory.get("excluded") or [])
current = ctl._outbound_current()
reputation = ctl._reputation_by_tag()
runtime = set(ctl._runtime_tags("outbound"))
@@ -151,6 +169,8 @@ def outbound_rows(_):
"tag": t,
"reputation": reputation.get(t, "-"),
"source": "runtime" if t in runtime else ctl._s(sources.get(t) or "-"),
# As `proxy-ctl proxy outbounds` prints them.
"notes": ", ".join(([f"via {ctl._s(detours[t])}"] if t in detours else []) + (["never picked"] if t in excluded else [])),
"runtime": t in runtime,
}
for t in ctl._outbound_tags()
@@ -180,6 +200,12 @@ def subscription_rows(_):
return rows
def subscription_summary():
text = f"{ctl.SUBSCRIPTION_UPDATE}: {ctl.svc_state(ctl.SUBSCRIPTION_UPDATE) or 'unknown'}"
next_run = ctl._timer_next_run(f"{ctl.SUBSCRIPTION_UPDATE}.timer")
return text + (f", next update {ctl._in_time(next_run)}" if next_run else "")
def autoproxy_rows(_):
state = ctl._autoproxy_state(ctl._autoproxy_dir())
domains = state.get("domains") or {}
@@ -230,10 +256,15 @@ def _cutoff_status():
def inbound_rows(_):
return [
{"key": f"{x.get('tag')}/{x.get('user')}", **{k: ctl._s(x.get(k) or "") for k in ("tag", "user", "type", "port")}}
for x in ctl._inbound_links()
]
links = ctl._inbound_links()
# One XRay API call per load, and only while this tab loads; empty when the API is not answering.
presence = _safe(ctl._inbound_presence, fallback=None) or {}
rows = []
for x in links:
row = {"key": f"{x.get('tag')}/{x.get('user')}", **{k: ctl._s(x.get(k) or "") for k in ("tag", "user", "type", "port")}}
row["online"] = (presence.get(row["user"]) or ("",))[0]
rows.append(row)
return rows
def app_rows(_):
@@ -282,7 +313,8 @@ def filter_rows(rows, columns, text):
def _natural(value):
# "port 443" before "port 2053": digit runs compare as numbers.
return [int(p) if p.isdigit() else p for p in re.split(r"(\d+)", str(value or "").lower())]
# isdecimal, not isdigit: "²" is a digit to isdigit, but neither \d nor int() takes it.
return [int(p) if p.isdecimal() else p for p in re.split(r"(\d+)", str(value or "").lower())]
def _link(row, *extra):
@@ -321,7 +353,7 @@ TABS = [
"space",
"start / stop",
toggle_argv,
when=lambda r: r["unit"] in TOGGLES or r["unit"].startswith(AWG_PREFIX),
when=lambda r: r["unit"] in TOGGLES or bool(_awg_profile(r)),
# proxy off takes tun and tproxy down with it.
confirm=lambda r: r["unit"] == "proxy-suite-socks" and r["state"] == "active",
),
@@ -329,8 +361,8 @@ TABS = [
Action(
"ctrl+r",
"restart it",
lambda r, *_: ["awg", "restart", r["unit"].removeprefix(AWG_PREFIX)],
when=lambda r: r["unit"].startswith(AWG_PREFIX) and r["state"] == "active",
lambda r, *_: ["awg", "restart", _awg_profile(r)],
when=lambda r: bool(_awg_profile(r)) and r["state"] == "active",
),
Action("R", "restart everything running", lambda r, *_: ["restart"], confirm=True),
],
@@ -348,15 +380,31 @@ TABS = [
"outbounds",
"Outbounds",
_socks,
[("mark", ""), ("tag", "Tag"), ("reputation", "Reputation"), ("source", "Source")],
[("mark", ""), ("tag", "Tag"), ("reputation", "Reputation"), ("source", "Source"), ("notes", "Notes")],
outbound_rows,
summary=outbound_summary,
actions=[
Action("p", "pin it", lambda r, *_: ["proxy", "pin", r["tag"]], when=lambda r: r["mark"] != "★"),
Action("u", "unpin: let the selection pick", lambda r, *_: ["proxy", "unpin"], when=lambda r: r["mark"] == "★"),
Action("t", "test it", lambda r, *_: ["proxy", "outbounds", "test", r["tag"]], when=ROW, mode="dialog"),
Action("D", "test its download speed", lambda r, *_: ["proxy", "outbounds", "test", r["tag"], "--download"], when=ROW, mode="dialog"),
Action(
"v",
"probe a domain through it…",
lambda r, t, _: ["proxy", "auto", "probe", t, "--via", ctl._backend_tag(r["tag"])],
when=_enabled("AUTOPROXY_ENABLED"),
prompt="<domain>[/path]",
mode="dialog",
),
Action("T", "test all", lambda r, *_: ["proxy", "outbounds", "test"], mode="dialog"),
Action("n", "add a runtime outbound…", lambda r, t, _: ["proxy", "outbounds", "add", *t.split(None, 1)], prompt="<tag> <url or JSON>"),
Action(
"h",
"add an outbound chained through this one…",
lambda r, t, _: ["proxy", "outbounds", "add", *t.split(None, 1), "--detour", r["tag"]],
when=ROW,
prompt="<tag> <url or JSON>",
),
Action("d", "remove it", lambda r, *_: ["proxy", "outbounds", "rm", r["tag"]], when=lambda r: r["runtime"], confirm=True),
# Credentials: proxy-ctl refuses these without root, and the dialog says so.
Action("l", "its URL", lambda r, *_: ["proxy", "outbounds", "link", r["tag"]], when=ROW, mode="dialog"),
@@ -373,7 +421,7 @@ TABS = [
_socks,
[("tag", "Tag"), ("proxies", "Proxies"), ("updated", "Updated"), ("source", "Source")],
subscription_rows,
summary=lambda: f"proxy-suite-subscription-update: {ctl.svc_state('proxy-suite-subscription-update') or 'unknown'}",
summary=subscription_summary,
actions=[
Action("u", "refetch all", lambda r, *_: ["proxy", "subs", "update"], mode="dialog"),
Action("l", "follow the update's logs", lambda r, *_: ["logs", "proxy-suite-subscription-update"], mode="suspend"),
@@ -422,7 +470,7 @@ TABS = [
"inbounds",
"Inbounds",
_enabled("INBOUNDS_ENABLED"),
[("tag", "Tag"), ("user", "User"), ("type", "Type"), ("port", "Port")],
[("tag", "Tag"), ("user", "User"), ("type", "Type"), ("port", "Port"), ("online", "Online")],
inbound_rows,
summary=lambda: f"proxy-suite-inbounds: {ctl.svc_state('proxy-suite-inbounds') or 'unknown'}",
actions=[
@@ -436,6 +484,8 @@ TABS = [
Action("J", "client's outbound JSON", lambda r, *_: _link(r, "--json"), when=ROW, mode="dialog"),
Action("V", "server's inbound JSON", lambda r, *_: ["inbounds", "link", r["tag"], "--server-json"], when=ROW, mode="dialog"),
Action("t", "traffic per user", lambda r, *_: ["inbounds", "stats"], mode="dialog"),
Action("I", "traffic per inbound", lambda r, *_: ["inbounds", "stats", "--by", "inbound"], mode="dialog"),
Action("O", "traffic per exit", lambda r, *_: ["inbounds", "stats", "--by", "outbound"], mode="dialog"),
Action("o", "who is online", lambda r, *_: ["inbounds", "online"], mode="dialog"),
],
),
@@ -487,6 +537,22 @@ def _capture(argv):
return p.stdout + p.stderr
def popen(argv):
"""proxy-ctl with its output streamed: its own process group, so stop() takes down what it spawned too."""
return subprocess.Popen(
[CTL, *argv], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL,
text=True, errors="replace", start_new_session=True,
)
def stop(proc):
if proc and proc.poll() is None:
try:
os.killpg(proc.pid, signal.SIGTERM)
except OSError:
proc.terminate()
def _safe(fn, *args, fallback=None):
try:
return fn(*args)
@@ -583,7 +649,7 @@ def tray_menu(snap, outbounds=None):
if snap["subscription_update"]["available"]:
busy = snap["subscription_update"]["state"] in ctl.BUSY_STATES
items.append(MenuItem("subs", "Updating subscriptions…" if busy else "Update subscriptions", enabled=not busy, argv=["proxy", "subs", "update"]))
items.append(MenuItem("restart", "Restart active services", argv=["restart"]))
items.append(MenuItem("restart", "Restart active services", argv=["restart"], confirm=True))
items += [_sep(6), MenuItem("quit", "Quit", app="quit")]
return items
+11 -15
View File
@@ -5,7 +5,6 @@ What it shows and does lives in proxy_model, shared with proxy-suite-gui; this i
import shlex
import signal
import subprocess
from rich.text import Text
from textual import events, work
@@ -21,7 +20,7 @@ from textual.widgets import DataTable, Input, Label, OptionList, RichLog, Static
from textual.widgets.option_list import Option
import proxy_model as model
from proxy_model import CTL, TABS, ctl, filter_rows, _natural, _read_states, _safe
from proxy_model import CTL, STATE_ICONS, TABS, ctl, filter_rows, _natural, _read_states, _safe
REFRESH_SECONDS = 3
STATUS_STYLES = {"ok": "b ansi_green", "warn": "b ansi_yellow", "bad": "b ansi_red", "": "b"}
@@ -106,8 +105,7 @@ THEME = Theme(
)
ACCENT = "bold cyan"
STATE_STYLES = {"active": "green", "inactive": "dim", "failed": "bold red", "activating": "yellow", "deactivating": "yellow"}
STATE_ICONS = {"active": "●", "inactive": "○", "failed": "✗", "activating": "◐", "deactivating": "◐"}
STATE_STYLES = {"active": "green", "inactive": "dim", "failed": "bold red", "activating": "yellow", "deactivating": "yellow", "reloading": "yellow"}
CELL_STYLES = {
"ok": "green",
"bad": "red",
@@ -118,6 +116,7 @@ CELL_STYLES = {
"pinned": "cyan",
"excluded": "dim",
"queued": "yellow",
"online": "green",
}
@@ -232,9 +231,9 @@ class Menu(Dialog):
class Output(Dialog):
BINDINGS = [Binding("escape,q", "dismiss", "close"), Binding("c", "copy", "copy")]
def __init__(self, title, text=None):
def __init__(self, title, text=None, wrap=True):
super().__init__()
self.heading, self.initial = title, text
self.heading, self.initial, self.wrap = title, text, wrap
self.proc = None # the streaming command, stopped when the dialog closes
self.text = [] # plain lines, for copying
@@ -242,7 +241,7 @@ class Output(Dialog):
with Vertical(classes="dialog output"):
yield Label(self.heading, classes="dialog-title", markup=False)
# Follow a streaming command; show finished text from its top.
log = RichLog(wrap=True, min_width=1, markup=False, auto_scroll=self.initial is None)
log = RichLog(wrap=self.wrap, min_width=1, markup=False, auto_scroll=self.initial is None)
if self.initial is not None:
text = self.initial if isinstance(self.initial, Text) else Text.from_ansi(self.initial)
self.text.append(text.plain)
@@ -261,8 +260,7 @@ class Output(Dialog):
self.notify("Copied the output.")
def on_unmount(self):
if self.proc and self.proc.poll() is None:
self.proc.terminate()
model.stop(self.proc)
# --- main screen --------------------------------------------------------------
@@ -612,8 +610,7 @@ class ProxyTui(App):
except (ValueError, IndexError) as e: # an unbalanced quote in a typed command
self.feedback(f"Cannot run that: {e}", False)
return
confirm = action.confirm(row) if callable(action.confirm) else action.confirm
if confirm:
if model.needs_confirm(action, row):
self.push_screen(Confirm(f"proxy-ctl {shlex.join(argv)}"), lambda ok: ok and self.run_argv(action.mode, argv))
else:
self.run_argv(action.mode, argv)
@@ -641,7 +638,8 @@ class ProxyTui(App):
pass
self.action_reload()
return
dialog = Output(command) if mode == "dialog" else None
# A wrapped QR code no longer scans: it scrolls sideways instead.
dialog = Output(command, wrap="--qr" not in argv) if mode == "dialog" else None
if dialog:
self.push_screen(dialog)
self.feedback(f"… {command}")
@@ -651,9 +649,7 @@ class ProxyTui(App):
def stream(self, command, argv, dialog, copy=False):
out = []
try:
p = subprocess.Popen(
[CTL, *argv], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, text=True
)
p = model.popen(argv)
if dialog:
dialog.proc = p
for line in p.stdout:
+16
View File
@@ -735,6 +735,22 @@ class StatusSnapshotTest(EnvTest):
self.assertEqual(data["outbound"], "b (pinned)")
self.assertEqual(data["route_mode"], {"available": True, "current": "default", "default": "blacklist"})
def test_warp_over_amneziawg_is_watched(self):
# An outbound WARP profile is no `awg` profile, but its unit can still fail.
self.assertIn("proxy-suite-awg-warp", ctl._snapshot_units())
self.patch("_awg_profiles", lambda: ["warp"])
self.assertEqual(ctl._snapshot_units().count("proxy-suite-awg-warp"), 1)
def test_outbound_with_its_hop(self):
inventory = {"pinned": "", "detours": {"a": "b"}}
self.patch("_outbound_inventory", lambda: inventory)
self.patch("_outbound_current", lambda: "a")
self.assertEqual(ctl._status_outbound(), "a via b")
inventory["pinned"] = "c"
self.assertEqual(ctl._status_outbound(), "c (pinned)")
inventory["detours"]["c"] = "b"
self.assertEqual(ctl._status_outbound(), "c via b (pinned)")
if __name__ == "__main__":
unittest.main()
+30 -3
View File
@@ -47,6 +47,23 @@ class ModelTest(unittest.TestCase):
rows = model.service_rows({"proxy-suite-socks": "active", ctl.SUBSCRIPTION_UPDATE: "inactive"})
self.assertEqual([r["unit"] for r in rows], ["proxy-suite-socks"])
def test_warp_over_amneziawg_toggles_with_warp(self):
tab = model.TABS[0]
row = model.service_rows({"proxy-suite-awg-warp": "inactive"})[0]
keys = lambda: [a.key for a in model.applicable(tab, {**row, "state": "active"})]
self.assertEqual(model.toggle_argv(row), ["warp", "on"]) # an outbound profile: `awg` does not know it
self.assertNotIn("ctrl+r", keys())
with mock.patch.object(ctl, "_awg_profiles", lambda: ["warp"]):
self.assertEqual(model.toggle_argv(row), ["awg", "on", "warp"]) # a global profile named warp
self.assertIn("ctrl+r", keys())
def test_inbound_presence(self):
links = [{"tag": "vless", "user": "alice", "type": "vless", "port": 443}, {"tag": "vless", "user": "bob", "type": "vless", "port": 443}]
with mock.patch.object(ctl, "_inbound_links", lambda: links), mock.patch.object(ctl, "_inbound_presence", lambda: {"alice": ("online", "10.0.0.2")}):
self.assertEqual([r["online"] for r in model.inbound_rows({})], ["online", ""])
with mock.patch.object(ctl, "_inbound_links", lambda: links), mock.patch.object(ctl, "_inbound_presence", lambda: ctl.die("API silent")):
self.assertEqual([r["online"] for r in model.inbound_rows({})], ["", ""])
def test_tray_menu(self):
states = {
"proxy-suite-socks": "active",
@@ -70,6 +87,7 @@ class ModelTest(unittest.TestCase):
self.assertEqual(items["awg-off"].argv, ["awg", "off"])
self.assertEqual(items["zapret"].argv, ["zapret", "on"])
self.assertFalse(items["subs"].enabled) # an update already runs
self.assertTrue(items["restart"].confirm) # as R in the TUI and GUI
self.assertEqual(items["quit"].app, "quit")
def test_tray_menu_without_proxy(self):
@@ -85,11 +103,20 @@ class ModelTest(unittest.TestCase):
def test_load_tab(self):
tab = next(t for t in model.TABS if t.id == "outbounds")
with mock.patch.object(ctl, "_outbound_current", lambda: "a"), mock.patch.object(ctl, "_reputation_by_tag", lambda: {}), mock.patch.object(ctl, "_runtime_tags", lambda kind: []):
inventory = {"tags": ["a", "b"], "pinned": "b", "detours": {"a": "b"}, "excluded": ["b"]}
with mock.patch.object(ctl, "_outbound_current", lambda: "a"), mock.patch.object(ctl, "_reputation_by_tag", lambda: {}), mock.patch.object(ctl, "_runtime_tags", lambda kind: []), mock.patch.object(ctl, "_outbound_inventory", lambda: inventory):
rows, summary = model.load_tab(tab, {})
self.assertEqual([(r["tag"], r["mark"]) for r in rows], [("a", "▸"), ("b", "★")])
self.assertEqual([(r["tag"], r["mark"], r["notes"]) for r in rows], [("a", "▸", "via b"), ("b", "★", "never picked")])
self.assertIn("Pinned: b", summary)
self.assertEqual([a.key for a in model.applicable(tab, rows[1])], ["u", "t", "T", "n", "l", "c", "Q", "J", "F", "X"])
with mock.patch.object(ctl, "env", lambda name, default="": ""):
self.assertEqual([a.key for a in model.applicable(tab, rows[1])], ["u", "t", "D", "T", "n", "h", "l", "c", "Q", "J", "F", "X"])
chain = next(a for a in tab.actions if a.key == "h")
self.assertEqual(chain.argv(rows[1], 'c {"type": "socks"}', {}), ["proxy", "outbounds", "add", "c", '{"type": "socks"}', "--detour", "b"])
# Probe exits go by the backend's tag.
probe = next(a for a in tab.actions if a.key == "v")
with mock.patch.object(ctl, "env", lambda name, default="": "1" if name == "AUTOPROXY_ENABLED" else ""), mock.patch.object(ctl, "_backend_tags", lambda: {"b": "b-backend"}):
self.assertIn(probe, model.applicable(tab, rows[1]))
self.assertEqual(probe.argv(rows[1], "example.com", {}), ["proxy", "auto", "probe", "example.com", "--via", "b-backend"])
broken = model.Tab("x", "X", model.ROW, [], lambda _: ctl.die("backend gone"))
self.assertEqual(model.load_tab(broken, {}), ([], "✗ backend gone"))
+7 -5
View File
@@ -67,6 +67,7 @@ class TuiTest(unittest.TestCase):
self.assertEqual(keys("list:learned"), ["a"]) # by heading
self.assertEqual(keys("kind:pinned LEARNED"), ["b"]) # by field, and every word must match
self.assertEqual(sorted(["port 2053", "port 443"], key=tui._natural), ["port 443", "port 2053"])
self.assertEqual(sorted(["b2", "a1²", "a10"], key=tui._natural), ["a1²", "a10", "b2"]) # ² is text, not a number
# Items never split across lines.
self.assertEqual(tui.pack(["[b]aaa[/]", "bbb", "ccc"], 9), "[b]aaa[/] bbb\nccc")
@@ -264,18 +265,19 @@ class TuiTest(unittest.TestCase):
self.assertEqual(app.rows["inbounds"], {})
self.assertIn("Share links are not readable", str(app.main.query_one("#inbounds-summary").content))
# Closing a dialog stops the command still streaming into it; c copies what it showed.
# Closing a dialog stops the command still streaming into it, and what it spawned; c copies what it showed.
dialog = tui.Output("proxy-ctl proxy outbounds test")
dialog.proc = mock.Mock(**{"poll.return_value": None})
dialog.proc = mock.Mock(pid=4242, **{"poll.return_value": None})
app.push_screen(dialog)
await pilot.pause()
dialog.write("\x1b[32mok\x1b[0m a")
with mock.patch.object(app, "copy_to_clipboard") as copy:
await pilot.press("c")
copy.assert_called_once_with("ok a")
await pilot.press("escape")
await pilot.pause()
dialog.proc.terminate.assert_called_once()
with mock.patch.object(model.os, "killpg") as killpg:
await pilot.press("escape")
await pilot.pause()
killpg.assert_called_once_with(4242, model.signal.SIGTERM)
if __name__ == "__main__":