diff --git a/README.md b/README.md index dfbf5ea..8f54b83 100644 --- a/README.md +++ b/README.md @@ -140,6 +140,9 @@ Secrets and changes need root, or the userControl group. add an outbound at runtime: a URL, or sing-box/XRay JSON (-: stdin), chained through another outbound with --detour; the tag first, or left out to name it after the link + proxy outbounds chain [new tag] + add a copy of an existing outbound that dials through + another one; the original keeps dialing the way it did proxy outbounds rm remove a runtime outbound proxy outbounds disable|enable keep an outbound out of automatic use (selection, autoProxy, pins), or let it back in; declared ones too diff --git a/nix/checks/repo.nix b/nix/checks/repo.nix index 1ca5899..e0ddb2c 100644 --- a/nix/checks/repo.nix +++ b/nix/checks/repo.nix @@ -378,6 +378,8 @@ in 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 + # chain takes the outbound to copy, then the hop it dials through. + has community-de proxy outbounds chain own-vps has outbound inbounds stats --by # Unreadable state loses the values, not the flags. has --qr inbounds sub diff --git a/pkgs/proxy-ctl/proxy_ctl.py b/pkgs/proxy-ctl/proxy_ctl.py index 9b397f1..a9fae2f 100644 --- a/pkgs/proxy-ctl/proxy_ctl.py +++ b/pkgs/proxy-ctl/proxy_ctl.py @@ -62,6 +62,9 @@ Secrets and changes need root, or the userControl group. add an outbound at runtime: a URL, or sing-box/XRay JSON (-: stdin), chained through another outbound with --detour; the tag first, or left out to name it after the link + proxy outbounds chain [new tag] + add a copy of an existing outbound that dials through + another one; the original keeps dialing the way it did proxy outbounds rm remove a runtime outbound proxy outbounds disable|enable keep an outbound out of automatic use (selection, autoProxy, pins), or let it back in; declared ones too @@ -492,6 +495,7 @@ COMPLETE = { "words": { "list": "outbounds, where each came from, and the pick", "add": "add an outbound at runtime: [tag] ", + "chain": "copy an outbound so it dials through another one", "rm": "remove a runtime outbound", "disable": "keep it out of automatic use", "enable": "let a disabled outbound back in", @@ -504,6 +508,8 @@ COMPLETE = { "args": _outbound_choices, "flags": {"--qr": "print a QR code", "--json": "backend JSON", "--config": "client config for this server"}, }, + # The outbound to copy, then the hop; the third word is the new tag, which nothing can suggest. + "proxy outbounds chain": {"args": _outbound_choices, "repeat": True}, "proxy outbounds rm": {"args": lambda: _names(_runtime_tags("outbound"))}, "proxy outbounds disable": {"args": lambda: {t: d for t, d in _outbound_choices().items() if t not in _outbound_disabled()}}, "proxy outbounds enable": {"args": lambda: _names(_outbound_disabled())}, @@ -941,6 +947,8 @@ def cmd_outbounds(verb="list", *args): if not detour: usage("proxy outbounds add [tag] [--detour ]") _runtime_entry_add("outbound", *args, detour=detour) + elif verb == "chain": + cmd_outbound_chain(*args) elif verb in ("rm", "remove", "del"): _runtime_entry_rm("outbound", *args) elif verb == "disable": @@ -952,7 +960,7 @@ def cmd_outbounds(verb="list", *args): elif verb == "link": _outbound_link(*args) else: - usage("proxy outbounds [list|add [tag] |rm |disable |enable |test [tag...]|link ]") + usage("proxy outbounds [list|add [tag] |chain |rm |disable |enable |test [tag...]|link ]") def _outbound_inventory(): @@ -1217,14 +1225,20 @@ def _json_text(value): return json.dumps(value, indent=2, ensure_ascii=False) +def _outbound_share_entry(tag): + """What the socks start script recorded for an outbound: the URL it was given, and its backend JSON.""" + entry = (_read_root_json(_runtime_file("outbound-share.json"), "outbounds").get("outbounds") or {}).get(tag) + if entry is None: + die(f"Unknown outbound: {tag}") + return entry + + def _outbound_link(*args): tag, flag = _share_args(args, ("--qr", "--json", "--config"), "proxy outbounds") if flag == "--config": _config_export(only=tag) return - entry = (_read_root_json(_runtime_file("outbound-share.json"), "outbounds").get("outbounds") or {}).get(tag) - if entry is None: - die(f"Unknown outbound: {tag}") + entry = _outbound_share_entry(tag) if flag == "--json": print(_json_text(_proxy_export().portable_outbound(entry.get("outbound") or {}))) elif not entry.get("url"): @@ -1427,8 +1441,12 @@ def _runtime_tag_for(kind, source): if not name and host: label = _host_label(host) name = label if kind == "subscription" else f"{parts.scheme.lower()}-{label}" - base = re.sub(r"[^A-Za-z0-9._-]+", "-", name).strip("-._")[:RUNTIME_TAG_MAX].strip("-._") - base = base or ("sub" if kind == "subscription" else "outbound") + return _unique_runtime_tag(kind, name, "sub" if kind == "subscription" else "outbound") + + +def _unique_runtime_tag(kind, name, fallback): + """`name` as a tag nothing else has taken: -2, -3... after it.""" + base = re.sub(r"[^A-Za-z0-9._-]+", "-", name).strip("-._")[:RUNTIME_TAG_MAX].strip("-._") or fallback taken = {"proxy", "direct", "block", *_runtime_tags(kind), *(_outbound_tags() if kind == "outbound" else _sub_tags())} tag, n = base, 1 while tag in taken: @@ -1487,6 +1505,39 @@ def _runtime_entry_add(kind, *args, detour=""): _runtime_entry_verify(kind, tag) +def cmd_outbound_chain(tag="", hop="", new_tag="", *_): + """A runtime copy of an existing outbound that dials through another one. + + A detour belongs to the outbound that carries it, so chaining two that already exist + means a third: the original keeps dialing the way it did. + """ + if not tag or not hop: + usage("proxy outbounds chain [new tag]") + _require_outbound_inventory() + tags = _outbound_tags() + if tag not in tags: + die(f"Unknown outbound: {tag}") + if hop not in tags: + die(f"Cannot chain through '{hop}': not an outbound. See: proxy-ctl proxy outbounds") + if tag == hop: + die(f"'{tag}' cannot chain through itself; name another outbound as the hop.") + entry = _outbound_share_entry(tag) + source = _s(entry.get("url") or "") + if not source: + ob = entry.get("outbound") or {} + if not ob: + die(f"Nothing to copy from '{tag}': the backend recorded neither a URL nor JSON for it.") + source = _json_text(_proxy_export().portable_outbound(ob)) + if new_tag: + _check_runtime_tag("outbound", new_tag) + else: + new_tag = _unique_runtime_tag("outbound", f"{tag}-via-{hop}", "chain") + print(f"Tag: {new_tag} (none given; pass one after the hop to choose it)") + if own_hop := _s((_outbound_inventory().get("detours") or {}).get(tag) or ""): + print(f"Note: '{tag}' chains through {own_hop}; the copy chains through {hop} instead.") + _runtime_entry_add("outbound", new_tag, source, detour=hop) + + def _runtime_entry_rm(kind, tag="", *_): if not tag: usage(f"proxy {_runtime_noun(kind)} rm ") diff --git a/pkgs/proxy-ctl/proxy_gui.py b/pkgs/proxy-ctl/proxy_gui.py index d7b364a..1b35e00 100644 --- a/pkgs/proxy-ctl/proxy_gui.py +++ b/pkgs/proxy-ctl/proxy_gui.py @@ -59,12 +59,14 @@ TAB_ICONS = { "apps": "view-app-grid-symbolic", } STATUS_ICONS = {"ok": "emblem-ok-symbolic", "warn": "dialog-warning-symbolic", "bad": "dialog-error-symbolic", "": "network-wired-symbolic"} +TOAST_LINES = 4 # a toast says this much of what ran; the Output button, and `o`, have the whole of it GLOBAL_SHORTCUTS = [ ("f slash", "Filter the rows (list:learned for one column)"), ("Escape", "Clear the filter"), ("Menu F10", "Actions for the selected row (or right-click it)"), ("1...8", "Jump to a tab"), + ("v", "Paste a link: it is added to this tab"), ("w", "How is a domain routed"), ("l", "Follow all logs"), ("o", "Output of the last command"), @@ -297,6 +299,7 @@ class Page(Gtk.Box): self.rows = [] # the last load, unfiltered self.summary_text = "" self.detail_shape = None + self.loaded = False # whether a load has landed here: before that the tab is not empty, it is unread self.summary = Gtk.Label(xalign=0, wrap=True, selectable=True, visible=False, css_classes=["summary", "dim-label"]) @@ -353,6 +356,12 @@ class Page(Gtk.Box): self.empty = Adw.StatusPage(title="Nothing here yet", icon_name=self.tab_icon, visible=False, vexpand=True) self.empty.set_child(self.tab_actions_box()) self.append(self.empty) + # Until this tab has loaded once there is nothing to keep on screen: say it is coming, + # rather than claim the tab is empty. + self.loading = Adw.StatusPage(title="Loading…", visible=True, vexpand=True) + self.loading.set_child(Adw.Spinner(width_request=32, height_request=32, halign=Gtk.Align.CENTER)) + self.append(self.loading) + self.split.set_visible(False) self.popover = None # --- cells --------------------------------------------------------------------- @@ -438,7 +447,7 @@ class Page(Gtk.Box): # --- filling ------------------------------------------------------------------------ def fill(self, rows, summary): - self.rows, self.summary_text = rows, summary + self.rows, self.summary_text, self.loaded = rows, summary, True self.refill() def refill(self): @@ -468,10 +477,12 @@ class Page(Gtk.Box): self.selection.set_selected(pos) break empty = not self.rows and not text + loading = empty and not self.loaded self.split.set_visible(not empty) - self.empty.set_visible(empty) + self.empty.set_visible(empty and not loading) + self.loading.set_visible(loading) self.summary.set_visible(bool(summary) and not empty) - if empty: + if empty and not loading: unreadable = summary.startswith("✗") self.empty.set_title("Cannot read this" if unreadable else "Nothing here yet") self.empty.set_icon_name("dialog-error-symbolic" if unreadable else self.tab_icon) @@ -761,6 +772,7 @@ class Window(Adw.ApplicationWindow): header.pack_start(self.root_badge) menu = Gio.Menu() section = Gio.Menu() + section.append("Paste a link into this tab", "win.paste") section.append("How is a domain routed…", "win.where") section.append("Follow all logs", "win.logs") section.append("Output of the last command", "win.last-output") @@ -809,6 +821,7 @@ class Window(Adw.ApplicationWindow): for name, callback, param in ( ("where", lambda *_: self.where(), None), + ("paste", lambda *_: self.paste(), None), ("logs", lambda *_: self.follow_logs(), None), ("last-output", lambda *_: self.show_last_output(), None), ("shortcuts", lambda *_: self.show_shortcuts(), None), @@ -821,6 +834,7 @@ class Window(Adw.ApplicationWindow): action.connect("activate", callback) self.add_action(action) app.set_accels_for_action("win.filter", ["f"]) + app.set_accels_for_action("win.paste", ["v"]) app.set_accels_for_action("app.elevated", ["e"]) app.set_accels_for_action("win.shortcuts", ["question"]) app.set_accels_for_action("app.reload", ["F5"]) @@ -896,7 +910,13 @@ class Window(Adw.ApplicationWindow): chip.append(Gtk.Label(label=value, css_classes=["chip-value"], ellipsize=Pango.EllipsizeMode.END)) self.status.append(chip) - def fill(self, states, visible, status, tab_id, rows, summary): + def fill(self, states, visible, status, tab_id, rows, summary, stale=False): + # A read that came back empty after a good one keeps what is on screen: every tab + # and row blinking out and back is worse than a banner saying the read failed. + if stale: + self.banner.set_title("Cannot read service states: showing the last good read") + self.banner.set_revealed(True) + return self.show_status(status) unreadable = not states self.banner.set_title("Cannot read service states: is systemd reachable?" if unreadable else "") @@ -919,6 +939,27 @@ class Window(Adw.ApplicationWindow): self.perform(model.WHERE, None) return True + def paste(self): + """Ctrl+V anywhere but a text field: whatever is in the clipboard is added to this tab.""" + if isinstance(self.get_focus(), Gtk.Editable) or self.get_visible_dialog() is not None: + return False + page = self.page() + if page is not None: + self.get_clipboard().read_text_async(None, lambda clipboard, result: self.pasted(page, clipboard, result)) + return True + + def pasted(self, page, clipboard, result): + try: + text = clipboard.read_text_finish(result) + except GLib.Error as e: + self.toast(f"Cannot read the clipboard: {e.message}") + return + argv, what = model.paste_argv(page.tab.id, text) + if argv is None: + self.toast(what) + else: + self.app.run_argv("run", argv, self) + def follow_logs(self): self.app.run_argv("suspend", ["logs"], self) return True @@ -969,7 +1010,20 @@ class Window(Adw.ApplicationWindow): entry.grab_focus() def toast(self, message, output=None, retry=None): - toast = Adw.Toast(title=GLib.markup_escape_text(message), timeout=6) + # A toast title is one ellipsized line, which hides most of what a command said: + # wrap it over a few lines instead, and keep the rest one button (or `o`) away. + label = Gtk.Label( + label=message, + wrap=True, + wrap_mode=Pango.WrapMode.WORD_CHAR, + natural_wrap_mode=Gtk.NaturalWrapMode.WORD, + lines=TOAST_LINES, + ellipsize=Pango.EllipsizeMode.END, + xalign=0, + justify=Gtk.Justification.LEFT, + max_width_chars=64, + ) + toast = Adw.Toast(custom_title=label, timeout=8) if retry: # one button: the output stays a keypress away (o) toast.set_button_label("Retry as Root") toast.connect("button-clicked", lambda *_: retry()) @@ -1171,16 +1225,19 @@ class ProxySuiteGui(Adw.Application): if self.window: self.window.set_busy(False) if generation == self.generation: - self.states = result["states"] - snap = result["snap"] - tree, overall, outbound = result["tray"] - if self.tray: - failed = snap["failed"] if snap 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) + # Nothing read, after a read that worked: keep the last good one, tray and all. + stale = not result["states"] and bool(self.states) + if not stale: + self.states = result["states"] + snap = result["snap"] + tree, overall, outbound = result["tray"] + if self.tray: + failed = snap["failed"] if snap 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: - self.window.fill(self.states, result["visible"], result["status"], *result["tab"]) + self.window.fill(self.states, result["visible"], result["status"], *result["tab"], stale=stale) if self.pending: self.pending = False self.reload() @@ -1280,7 +1337,8 @@ class ProxySuiteGui(Adw.Application): win.copy_text(last, f"Copied: {last}") else: message = f"{last} ({command})" if last else command - win.toast(f"exit {status}: {message}" if status else message, output if len(out) > 1 or status else None, retry) + # Anything it printed is worth a button: the toast shows a few lines of it at most. + win.toast(f"exit {status}: {message}" if status else message, output if out else None, retry) elif status: # From the tray: nothing else would say it failed. note = Gio.Notification.new(f"{command} failed") diff --git a/pkgs/proxy-ctl/proxy_model.py b/pkgs/proxy-ctl/proxy_model.py index 9968538..2dce0bc 100644 --- a/pkgs/proxy-ctl/proxy_model.py +++ b/pkgs/proxy-ctl/proxy_model.py @@ -471,6 +471,13 @@ TABS = [ when=ROW, prompt="[tag] - e.g. de-1 vless://… or just vless://…", ), + Action( + "H", + "chain it through another outbound…", + lambda r, t, _: ["proxy", "outbounds", "chain", r["tag"], *t.split()], + when=ROW, + prompt=" [new tag] - a copy of this one dialing through the hop", + ), Action("d", "remove it", lambda r, *_: ["proxy", "outbounds", "rm", r["tag"]], when=lambda r: r["runtime"], confirm=True), Action( "x", @@ -589,6 +596,39 @@ TABS = [ WHERE = Action("w", "How is a domain routed", lambda r, t, _: ["where", t], prompt="", mode="dialog") +# The share-link schemes scripts/proxy_url_parsers.py parses. http(s) is both an HTTP proxy +# and how a subscription is spelled, so for those the tab pasted into decides. +PROXY_SCHEMES = ("vless", "vmess", "trojan", "ss", "hysteria2", "hy2", "tuic", "anytls", "naive+https", "naive+quic", "socks5", "socks5h", "socks4", "socks4a") +HOST = re.compile(r"(?!-)[A-Za-z0-9-]{1,63}(? 1: + return None, "Paste one link at a time." + scheme = text.split("://", 1)[0].lower() if "://" in text else "" + if scheme in PROXY_SCHEMES: + return [*OUTBOUND_ADD, text], "" + if scheme in ("http", "https"): + return ([*OUTBOUND_ADD, text] if tab_id == "outbounds" else ["proxy", "subs", "add", text]), "" + if scheme: + return None, f"Nothing takes a {scheme}:// link." + if HOST.fullmatch(text) and tab_id in HOST_ARGV: + return [*HOST_ARGV[tab_id], text], "" + return None, "Not a share link, a subscription URL or a host." + def available_tabs(states): return [t.id for t in TABS if _safe(t.available, states, fallback=False)] diff --git a/pkgs/proxy-ctl/proxy_tui.py b/pkgs/proxy-ctl/proxy_tui.py index 14af363..275fb2a 100644 --- a/pkgs/proxy-ctl/proxy_tui.py +++ b/pkgs/proxy-ctl/proxy_tui.py @@ -54,6 +54,7 @@ GLOBAL_KEYS = [ ("← → ⇥", "switch tab; 1-8 jump to one"), ("/", "filter the rows (list:learned for one column); esc clears"), ("click", "a column heading sorts by it, again reverses, a third time unsorts"), + ("paste", "a link in the clipboard is added to this tab"), ("w", "how is a domain routed"), ("L", "follow all logs"), ("o", "output of the last command"), @@ -501,7 +502,13 @@ class ProxyTui(App): # --- reading -------------------------------------------------------------- def action_reload(self): - self.load(self.active_tab()) + tab_id = self.active_tab() + if tab_id not in self.loaded: + # Nothing has landed here yet, and an empty table reads as an empty tab. + widget = self.main.query_one(f"#{tab_id}-summary", Static) + _update(widget, Text("loading…")) + widget.display = True + self.load(tab_id) @work(thread=True, exclusive=True, group="load") def load(self, tab_id): @@ -535,6 +542,11 @@ class ProxyTui(App): widget.display = True def fill_table(self, tab_id, states, visible, status, rows, summary): + # Nothing read, after a read that worked: keep the last good view, so one bad refresh + # does not blink every tab and row out and back. + if not states and self.states: + self.feedback("cannot read service states: showing the last good read", False) + return rows = model.unique_keys(rows) self.loaded[tab_id] = (states, visible, status, rows, summary) self.states, self.status = states, status @@ -623,6 +635,18 @@ class ProxyTui(App): def action_act(self, index): self.perform(self.tabs[self.active_tab()].actions[index], self.selected_row()) + def on_paste(self, event): + """The terminal's paste, bracketed: whatever it carries is added to the tab it lands on. + A prompt or a dialog takes its own paste, so this only fires on the table.""" + if self.screen is not self.main: + return + event.stop() + argv, what = model.paste_argv(self.active_tab(), event.text) + if argv is None: + self.feedback(what, False) + else: + self.run_argv("run", argv) + def action_where(self): self.perform(model.WHERE, None) diff --git a/pkgs/proxy-ctl/test_proxy_ctl.py b/pkgs/proxy-ctl/test_proxy_ctl.py index 2bf1ac8..9bebef6 100644 --- a/pkgs/proxy-ctl/test_proxy_ctl.py +++ b/pkgs/proxy-ctl/test_proxy_ctl.py @@ -580,6 +580,47 @@ class RuntimeEntryTest(EnvTest): self.assertIn("Cannot see the entry for 'de'", err) self.assertNotIn("No runtime outbound", err) + def share(self, outbounds): + """outbound-share.json as the socks start script writes it, beside the inventory.""" + self.write("outbound-share.json", {"outbounds": outbounds}) + + def test_chain_copies_an_existing_outbound_through_a_hop(self): + self.share({"primary": {"url": "vless://u@de.test:443"}, "vless-example": {"url": "vless://u@nl.test:443"}}) + out = ok(ctl.cmd_outbounds, "chain", "primary", "vless-example") + self.assertIn("Tag: primary-via-vless-example", out) + self.assertEqual(ctl.read_text(self.path("outbounds.d/primary-via-vless-example.url")), "vless://u@de.test:443\n") + self.assertEqual(ctl.read_text(self.path("outbounds.d/primary-via-vless-example.detour")), "vless-example\n") + # The original is untouched: a detour belongs to the outbound carrying it. + self.assertFalse(os.path.exists(self.path("outbounds.d/primary.detour"))) + self.assertEqual(self.started, ["proxy-suite-outbound-reload.service"]) + # A name of one's own, and a second copy of the same pair gets its own tag. + ok(ctl.cmd_outbounds, "chain", "primary", "vless-example", "de-via-nl") + self.assertTrue(os.path.exists(self.path("outbounds.d/de-via-nl.url"))) + self.assertIn("Tag: primary-via-vless-example-2", ok(ctl.cmd_outbounds, "chain", "primary", "vless-example")) + + def test_chain_without_a_url_copies_the_backend_json(self): + self.share({"primary": {"outbound": {"tag": "primary", "type": "socks", "server": "1.2.3.4", "routing_mark": 99}}}) + ok(ctl.cmd_outbounds, "chain", "primary", "vless-example", "hop") + written = json.loads(ctl.read_text(self.path("outbounds.d/hop.json"))) + # Portable and untagged: the entry's name is the tag, and the host's mark is not shared. + self.assertEqual(written, {"type": "socks", "server": "1.2.3.4"}) + + def test_chain_refuses_what_it_cannot_chain(self): + self.share({"primary": {"url": "vless://u@de.test:443"}, "vless-example": {}}) + for args, message in ( + (("chain",), "proxy outbounds chain"), + (("chain", "primary"), "proxy outbounds chain"), + (("chain", "primary", "primary"), "cannot chain through itself"), + (("chain", "nope", "primary"), "Unknown outbound: nope"), + (("chain", "primary", "nope"), "Cannot chain through 'nope'"), + (("chain", "vless-example", "primary"), "Nothing to copy from 'vless-example'"), + ): + with self.subTest(args=args): + status, _, err = run(ctl.cmd_outbounds, *args) + self.assertNotEqual(status, 0) + self.assertIn(message, err) + self.assertEqual(os.listdir(self.path("outbounds.d")), []) + def test_rm_takes_the_marker_along(self): ok(ctl.cmd_outbounds, "add", "de", "vless://u@de.test:443") ok(ctl.cmd_outbounds, "disable", "de") diff --git a/pkgs/proxy-ctl/test_proxy_gui.py b/pkgs/proxy-ctl/test_proxy_gui.py index 3596ec8..07c0e5d 100644 --- a/pkgs/proxy-ctl/test_proxy_gui.py +++ b/pkgs/proxy-ctl/test_proxy_gui.py @@ -13,7 +13,7 @@ import proxy_ctl as ctl import proxy_gui as gui import proxy_model as model import proxy_sni as sni -from gi.repository import Gio, GLib +from gi.repository import Adw, Gio, GLib, Gtk sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "icons")) import badges # noqa: E402 @@ -77,6 +77,14 @@ class GuiTest(unittest.TestCase): self.assertTrue(gui.is_badge("status", "ok")) self.assertFalse(gui.is_badge("mark", "★")) + def test_toast_title_is_a_wrapping_label(self): + """A toast's own title is one ellipsized line; the properties the wrapping one needs are there. + Widgets cannot be built here: GTK segfaults without a display.""" + self.assertIsNotNone(Adw.Toast.find_property("custom-title")) + for name in ("wrap", "wrap-mode", "natural-wrap-mode", "lines", "ellipsize", "max-width-chars"): + self.assertIsNotNone(Gtk.Label.find_property(name), name) + self.assertGreater(gui.TOAST_LINES, 1) + def test_ansi(self): self.assertEqual( gui.ansi_segments("\x1b[1;31mfailed\x1b[0m ok\x1b[K"), diff --git a/pkgs/proxy-ctl/test_proxy_model.py b/pkgs/proxy-ctl/test_proxy_model.py index 5a776eb..a0c1767 100644 --- a/pkgs/proxy-ctl/test_proxy_model.py +++ b/pkgs/proxy-ctl/test_proxy_model.py @@ -158,6 +158,31 @@ class ModelTest(unittest.TestCase): self.assertEqual([i.id for i in model.tray_menu(None)], ["status", "open", "sep-0", "quit"]) self.assertEqual(model.icon_name(ctl._overall_state(None)), "proxy-suite-disabled-unknown") + def test_paste_argv(self): + paste = model.paste_argv + self.assertEqual(paste("outbounds", " vless://u@de.test:443#DE\n")[0], ["proxy", "outbounds", "add", "vless://u@de.test:443#DE"]) + # The tab pasted onto does not matter for an unambiguous link. + self.assertEqual(paste("services", "ss://x@a.test:8388")[0], ["proxy", "outbounds", "add", "ss://x@a.test:8388"]) + self.assertEqual(paste("services", '{"type": "socks",\n "server": "1.2.3.4"}')[0][:3], ["proxy", "outbounds", "add"]) + # http(s) is both a subscription and an HTTP proxy: the tab decides. + self.assertEqual(paste("subs", "https://sub.test/s")[0], ["proxy", "subs", "add", "https://sub.test/s"]) + self.assertEqual(paste("services", "https://sub.test/s")[0], ["proxy", "subs", "add", "https://sub.test/s"]) + self.assertEqual(paste("outbounds", "https://u:p@proxy.test:8443")[0], ["proxy", "outbounds", "add", "https://u:p@proxy.test:8443"]) + # A bare host means something only where a tab collects hosts. + self.assertEqual(paste("zapret", "blocked.example")[0], ["zapret", "auto", "add", "blocked.example"]) + self.assertEqual(paste("autoproxy", "blocked.example")[0], ["proxy", "auto", "learn", "blocked.example"]) + for tab, text, why in [ + ("outbounds", "", "Nothing to paste."), + ("outbounds", "vless://a\nvless://b", "one link at a time"), + ("outbounds", "ftp://a.test/x", "ftp:// link"), + ("outbounds", "blocked.example", "Not a share link"), + ("zapret", "not a host", "Not a share link"), + ]: + with self.subTest(text=text): + argv, message = paste(tab, text) + self.assertIsNone(argv) + self.assertIn(why, message) + def test_load_tab(self): tab = next(t for t in model.TABS if t.id == "outbounds") inventory = {"tags": ["a", "b"], "pinned": "b", "detours": {"a": "b"}, "excluded": ["b"]} @@ -166,7 +191,7 @@ class ModelTest(unittest.TestCase): self.assertEqual([(r["tag"], r["mark"], r["notes"]) for r in rows], [("a", "▸", "via b"), ("b", "★", "never picked")]) self.assertIn("Pinned: b", summary) 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", "x", "l", "c", "Q", "J", "F", "X"]) + self.assertEqual([a.key for a in model.applicable(tab, rows[1])], ["u", "t", "D", "T", "n", "h", "H", "x", "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. diff --git a/pkgs/proxy-ctl/test_proxy_tui.py b/pkgs/proxy-ctl/test_proxy_tui.py index 8fb3911..1defae8 100644 --- a/pkgs/proxy-ctl/test_proxy_tui.py +++ b/pkgs/proxy-ctl/test_proxy_tui.py @@ -121,6 +121,25 @@ class TuiTest(unittest.TestCase): asyncio.run(run()) + def test_paste_lands_on_the_tab_it_was_pasted_onto(self): + async def run(): + self.units = {"proxy-suite-socks": "active", **self.units} + app = tui.ProxyTui() + async with app.run_test(size=(100, 30)) as pilot: + await self.settle(app, pilot) + app.main.query_one("#tabs", tui.TabbedContent).active = "outbounds" + await self.settle(app, pilot) + app.post_message(tui.events.Paste("vless://u@de.test:443#DE")) + await pilot.pause() + self.assertEqual(self.ran.pop(), ["proxy", "outbounds", "add", "vless://u@de.test:443#DE"]) + # Whatever else was in the clipboard runs nothing, and the bar says why. + app.post_message(tui.events.Paste("ftp://a.test/x")) + await pilot.pause() + self.assertEqual(self.ran, []) + self.assertIn("ftp:// link", str(app.main.query_one("#feedback").content)) + + asyncio.run(run()) + def test_ui(self): # Not IsolatedAsyncioTestCase: its asyncio debug mode makes Textual crawl. asyncio.run(self.ui())