Files
proxy-suite-flake/windows/crates/ps-gui/src/ui/autoproxy.rs
T
faumarayandClaude Opus 5.5 95ec15e14a windows: autoProxy routes slow sites, and has a page in the app
As upstream's sampler and slow judge: every minute, eleven Clash API
snapshots a second apart; a site whose best direct transfer never beat
slowBelowKiBps three times is owed an exit, and gets the first, in probe
order, that answers it as well as direct does (probe --via); routed
slow, it moves on after crawling twice there, and with no exit left it
stays direct for a TTL. Here the Clash API is always on, so it works
whatever the selection.

The app's autoProxy page: on or off, a site probed or learned, the sites
routed (forget one or all), the exits (bad ones marked), the exclusions
and the slowness threshold. tools/screenshots.sh takes every page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 16:47:45 +03:00

339 lines
16 KiB
Rust

//! autoProxy: on or off; a site probed through each exit, or learned now; the sites it routed
//! and through what, each forgotten on its own; the exits, bad ones marked; what it never
//! touches, and how slow a site must be to be moved.
use std::time::{Duration, Instant};
use gpui_kit::assets::IconName;
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState};
use gpui_kit::component::notification::Notification;
use gpui_kit::component::switch::Switch;
use gpui_kit::component::tag::Tag;
use gpui_kit::component::*;
use gpui_kit::*;
use ps_client::edits;
use ps_ipc::Request;
use serde_json::{Value, json};
use super::widgets::{card, hint, page};
use crate::model::Model;
pub struct AutoProxyPage {
model: Entity<Model>,
site: Entity<InputState>,
exclude: Entity<TextareaState>,
slow: Entity<InputState>,
/// What the service listed last, or why it could not.
list: Result<Value, String>,
loaded_at: Option<Instant>,
/// The last probe: its answer, or that it runs.
probe: Option<Result<Value, String>>,
probing: bool,
/// The exclusions and threshold the inputs were last filled from (see the DPI page).
shown: (String, String),
_subscriptions: Vec<Subscription>,
}
impl AutoProxyPage {
pub fn new(model: Entity<Model>, window: &mut Window, cx: &mut Context<Self>) -> Self {
let site = cx.new(|cx| InputState::new(window, cx).placeholder("example.com"));
let exclude = cx.new(|cx| TextareaState::new(window, cx).rows(4).placeholder("intranet.example — one per line"));
let slow = cx.new(|cx| InputState::new(window, cx).placeholder("150"));
let subscriptions = vec![cx.observe_in(&model, window, |this, _, window, cx| {
this.sync(window, cx);
// The listing with the service's own refresh, every few seconds at most.
if this.loaded_at.is_none_or(|t| t.elapsed() > Duration::from_secs(5)) {
this.load(cx);
}
})];
let mut this = Self {
model,
site,
exclude,
slow,
list: Ok(Value::Null),
loaded_at: None,
probe: None,
probing: false,
shown: Default::default(),
_subscriptions: subscriptions,
};
this.sync(window, cx);
this.load(cx);
this
}
fn sync(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let a = self.model.read(cx).config()["proxy"]["autoProxy"].clone();
let exclude = a["exclude"].as_array().into_iter().flatten().filter_map(Value::as_str).collect::<Vec<_>>().join("\n");
let slow = a["slowBelowKiBps"].as_u64().map(|n| n.to_string()).unwrap_or_default();
let fresh = (exclude, slow);
if fresh != self.shown {
if self.exclude.read(cx).value() == self.shown.0.as_str() {
let v = fresh.0.clone();
self.exclude.update(cx, |s, cx| s.set_value(v, window, cx));
}
if self.slow.read(cx).value() == self.shown.1.as_str() {
let v = fresh.1.clone();
self.slow.update(cx, |s, cx| s.set_value(v, window, cx));
}
self.shown = fresh;
}
}
fn load(&mut self, cx: &mut Context<Self>) {
self.loaded_at = Some(Instant::now());
let job = self.model.read(cx).bridge().call(Request::AutoList);
cx.spawn(async move |this, cx| {
let r = job.await;
this.update(cx, |this, cx| {
this.list = r.map_err(|e| format!("{e:#}"));
cx.notify();
})
.ok();
})
.detach();
}
fn site(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<String> {
let site = self.site.read(cx).value().trim().trim_start_matches("https://").trim_start_matches("http://").trim_end_matches('/').to_owned();
if site.is_empty() {
window.push_notification(Notification::error("Type a site first: example.com"), cx);
return None;
}
Some(site)
}
fn probe(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(target) = self.site(window, cx) else { return };
self.probing = true;
self.probe = None;
cx.notify();
let job = self.model.read(cx).bridge().call(Request::AutoProbe { target, exits: None, via: None, keep_going: true });
cx.spawn(async move |this, cx| {
let r = job.await;
this.update(cx, |this, cx| {
this.probing = false;
this.probe = Some(r.map_err(|e| format!("{e:#}")));
cx.notify();
})
.ok();
})
.detach();
}
fn learn(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(site) = self.site(window, cx) else { return };
let site = site.split('/').next().unwrap_or("").to_owned();
self.model.update(cx, |m, cx| m.request(format!("{site}: probed now, routed if it needs it"), Request::AutoLearn { hosts: vec![site] }, cx));
}
fn forget(&mut self, domain: Option<String>, cx: &mut Context<Self>) {
let what = domain.as_ref().map_or("Everything learned is forgotten".to_owned(), |d| format!("{d} is forgotten"));
let job = self.model.read(cx).bridge().call(Request::AutoForget { domain });
let model = self.model.clone();
cx.spawn(async move |this, cx| {
let r = job.await;
model.update(cx, |m, cx| m.track(what, async move { r.map(drop) }, cx));
this.update(cx, |this, cx| this.load(cx)).ok();
})
.detach();
}
fn save(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let exclude: Vec<String> = self.exclude.read(cx).value().lines().map(|l| l.trim().to_owned()).filter(|l| !l.is_empty()).collect();
let slow_text = self.slow.read(cx).value().trim().to_owned();
let Ok(slow) = (if slow_text.is_empty() { Ok(0) } else { slow_text.parse::<u32>() }) else {
window.push_notification(Notification::error(format!("“{slow_text}” is not a speed in KiB/s (0 turns it off)")), cx);
return;
};
self.shown = (self.exclude.read(cx).value().to_string(), self.slow.read(cx).value().to_string());
self.model.update(cx, |m, cx| {
m.edit(
"autoProxy saved",
move |c| {
edits::set_path(c, &["proxy", "autoProxy", "exclude"], json!(exclude));
edits::set_path(c, &["proxy", "autoProxy", "slowBelowKiBps"], json!(slow));
Ok(())
},
cx,
)
});
}
}
fn row(cx: &App) -> Div {
div().h_flex().gap_3().items_center().py_2().border_t_1().border_color(cx.theme().border)
}
impl Render for AutoProxyPage {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let m = self.model.read(cx);
let a = m.config()["proxy"]["autoProxy"].clone();
let body = page("autoProxy", cx);
if m.config().is_null() {
return body.child(hint("Waiting for the service…", cx));
}
let list = self.list.clone();
let on = a["enable"] == true;
let model = self.model.clone();
let enable = Switch::new("ap-enable").checked(on).on_change(move |on, _, cx| {
let on = *on;
model.update(cx, |m, cx| {
m.edit(
if on { "autoProxy is on" } else { "autoProxy is off" },
move |c| {
edits::set_path(c, &["proxy", "autoProxy", "enable"], on.into());
Ok(())
},
cx,
)
})
});
let running = list.as_ref().is_ok_and(|l| l["running"] == true);
let state = match (on, running) {
(false, _) => Tag::secondary().child("off"),
(true, false) => Tag::warning().child("waiting for the local proxy"),
(true, true) => Tag::success().child("running"),
};
let about = card("autoProxy", Some(enable.into_any_element()), cx)
.child(div().h_flex().child(state))
.child(hint(
"It probes the sites your apps reach directly through each exit, direct first. A site blocked directly but reached through an exit is routed through it; one that crawls directly can move to an exit that carries it faster. Blocks zapret can fix stay direct.",
cx,
));
let probing = self.probing;
let mut try_card = card("Probe or learn a site", None, cx)
.child(hint("Probe: how it answers through each exit, nothing changed. Learn: probe it now and route it if it needs it.", cx))
.child(
div()
.h_flex()
.gap_2()
.child(div().flex_1().min_w_0().child(Input::new(&self.site)))
.child(
Button::new("ap-probe")
.small()
.icon(IconName::Gauge)
.label(if probing { "Probing…" } else { "Probe" })
.disabled(probing || !running)
.on_click(cx.listener(|this, _, window, cx| this.probe(window, cx))),
)
.child(Button::new("ap-learn").small().primary().icon(IconName::Plus).label("Learn").disabled(!running).on_click(cx.listener(|this, _, window, cx| this.learn(window, cx)))),
);
match &self.probe {
Some(Ok(p)) => {
let verdict = p["verdict"].as_str().unwrap_or("");
let text = match verdict {
"ok" => "Reachable directly: nothing to do".to_owned(),
"destination" => format!("Blocked directly: routed through {}", p["exit"].as_str().unwrap_or("an exit")),
"censor" => "Cut on the way: zapret's to fix, left direct".to_owned(),
"both-fail" => "Fails through every exit: not a block".to_owned(),
"unreachable" => "No exit reaches it at all".to_owned(),
v => v.to_owned(),
};
try_card = try_card.child(div().font_medium().child(text));
for r in p["rows"].as_array().into_iter().flatten() {
let f = &r["fetch"];
let what = match f["status"].as_u64() {
Some(s) => format!("{s}, {} bytes{}", f["bytes"], f["block"].as_str().filter(|b| !b.is_empty()).map(|b| format!(", {b} page")).unwrap_or_default()),
None => format!("no answer ({})", f["error"].as_str().unwrap_or("")),
};
let judgement = r["judgement"].as_str().unwrap_or("");
let tag = match judgement {
"ok" => Tag::success(),
"dead" => Tag::danger(),
_ => Tag::warning(),
};
try_card = try_card.child(
row(cx)
.text_sm()
.child(div().w(px(150.)).truncate().child(r["tag"].as_str().unwrap_or("").to_owned()))
.child(div().w(px(100.)).text_color(cx.theme().muted_foreground).child(r["path"].as_str().unwrap_or("").to_owned()))
.child(div().flex_1().min_w_0().truncate().child(what))
.child(tag.child(judgement.to_owned())),
);
}
}
Some(Err(e)) => try_card = try_card.child(div().text_sm().text_color(cx.theme().danger).child(e.clone())),
None => {}
}
let mut routed = card(
"Routed sites",
Some(
div()
.h_flex()
.gap_2()
.child(Button::new("ap-reload").small().icon(IconName::RefreshCw).on_click(cx.listener(|this, _, _, cx| this.load(cx))))
.child(Button::new("ap-clear").small().ghost().icon(IconName::Trash).label("Forget all").on_click(cx.listener(|this, _, _, cx| this.forget(None, cx))))
.into_any_element(),
),
cx,
);
match &list {
Err(e) => routed = routed.child(div().text_sm().text_color(cx.theme().danger).child(e.clone())),
Ok(l) => {
let domains = l["domains"].as_array().cloned().unwrap_or_default();
if domains.is_empty() {
routed = routed.child(hint("Nothing routed yet.", cx));
}
for (i, d) in domains.iter().enumerate() {
let domain = d["domain"].as_str().unwrap_or("").to_owned();
let why = if d["verdict"] == "slow" { Tag::warning().child("slow") } else { Tag::danger().child("blocked") };
let forget = domain.clone();
routed = routed.child(
row(cx)
.child(div().flex_1().min_w_0().truncate().font_medium().child(domain))
.child(why)
.child(div().w(px(160.)).truncate().text_sm().child(format!("via {}", d["exit"].as_str().unwrap_or(""))))
.child(Button::new(("ap-forget", i)).small().ghost().icon(IconName::Trash).on_click(cx.listener(move |this, _, _, cx| this.forget(Some(forget.clone()), cx)))),
);
}
let censored = l["censored"].as_array().map_or_else(|| l["censored"].as_u64().unwrap_or(0) as usize, Vec::len);
routed = routed.child(hint(
format!(
"{} site(s) judged; {censored} left to zapret; {} waiting to be probed; {} crawling, to be moved.",
l["hostsJudged"].as_u64().unwrap_or(0),
l["backlog"].as_u64().unwrap_or(0),
l["slowWaiting"].as_u64().unwrap_or(0)
),
cx,
));
}
}
let mut exits = card("Exits", None, cx).child(hint("Probed one per network first. One that two sites refused is bad, and probed last.", cx));
if let Ok(l) = &list {
for e in l["exits"].as_array().into_iter().flatten() {
let bad = e["bad"] == true;
exits = exits.child(
row(cx)
.child(div().w(px(180.)).truncate().font_medium().child(e["tag"].as_str().unwrap_or("").to_owned()))
.child(div().flex_1().min_w_0().truncate().text_sm().text_color(cx.theme().muted_foreground).child(format!(
"{} {}",
e["ip"].as_str().unwrap_or(""),
e["asn"].as_str().unwrap_or("")
)))
.child(if bad { Tag::danger().child("bad") } else { Tag::success().child("ok") }),
);
}
}
let options = card("Options", Some(Button::new("ap-save").small().label("Save").on_click(cx.listener(|this, _, window, cx| this.save(window, cx))).into_any_element()), cx)
.child(
div()
.h_flex()
.gap_4()
.items_start()
.child(div().v_flex().gap_1().flex_1().child(div().text_sm().child("Never probe or route (with their subdomains)")).child(Textarea::new(&self.exclude)))
.child(div().v_flex().gap_1().w(px(220.)).child(div().text_sm().child("Move sites slower than (KiB/s, 0: never)")).child(Input::new(&self.slow))),
)
.child(hint("Everything else (interval, exits, ports) is in Settings, under proxy.autoProxy.", cx));
body.child(about).child(try_card).child(routed).child(exits).child(options)
}
}