feat(proxies): support custom test targets and align feedback lifecycles

Refs #771

Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
Zyy
2026-11-28 17:48:44 +08:00
co-authored by Codex
parent 3ec00a152c
commit 0cfaca2a2b
67 changed files with 1211 additions and 155 deletions
+1
View File
@@ -1762,6 +1762,7 @@ dependencies = [
"thiserror",
"tokio",
"tracing",
"url",
"uuid",
]
+1
View File
@@ -32,6 +32,7 @@ sha2 = "0.11"
subtle = "2.6.1"
thiserror = "2.0.18"
tracing = "0.1.44"
url = "2.5.8"
uuid = { version = "1.23.3", features = ["v4", "v7"] }
cron = "0.17"
chrono-tz = "0.10"
@@ -47,6 +47,7 @@ pub enum MutationAuditOperation {
OutboundProxyUpdate,
OutboundProxyDelete,
OutboundProxyTest,
ProxyTestTargetsUpdate,
AccountGroupPluginReconcile,
ClientApiKeyPluginReconcile,
ProviderAccountImportDocument,
@@ -110,6 +111,7 @@ impl MutationAuditOperation {
Self::OutboundProxyCreate => ("create", "outbound_proxy"),
Self::OutboundProxyUpdate => ("update", "outbound_proxy"),
Self::OutboundProxyDelete => ("delete", "outbound_proxy"),
Self::ProxyTestTargetsUpdate => ("update", "proxy_test_targets"),
Self::OutboundProxyTest => ("test", "outbound_proxy"),
Self::AccountGroupPluginReconcile => ("plugin_reconcile", "account_group"),
Self::ClientApiKeyPluginReconcile => ("plugin_reconcile", "client_api_key"),
@@ -56,6 +56,41 @@ pub struct ProxyAccountPage {
pub page_size: u16,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ProxyTestTarget {
pub name: String,
pub url: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ProxyTestTargets {
pub revision: Revision,
pub targets: Vec<ProxyTestTarget>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TargetProbeResult {
pub latency_ms: u64,
#[serde(flatten)]
pub outcome: TargetProbeOutcome,
}
#[derive(Debug, Serialize)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum TargetProbeOutcome {
Http {
status: u16,
#[serde(rename = "exitIp")]
exit_ip: Option<std::net::IpAddr>,
},
Failed {
message: String,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProxyTestResult {
pub location: ProxyLocationDetection,
@@ -8,7 +8,8 @@ use crate::model::{
AdminError, MutationContext, Revision,
proxies::{
ImportProxyBinding, NewProxy, ProxyAccountListQuery, ProxyAccountPage, ProxyListQuery,
ProxyMutation, ProxyPage, ProxyRecord, ProxyTestResult, UpdateProxy,
ProxyMutation, ProxyPage, ProxyRecord, ProxyTestResult, ProxyTestTargets,
TargetProbeResult, UpdateProxy,
},
};
@@ -21,6 +22,12 @@ pub trait PluginProxyAccess: Send + Sync {
#[async_trait]
pub trait ProxyStore: Send + Sync {
async fn test_targets(&self) -> AdminStoreResult<ProxyTestTargets>;
async fn replace_test_targets(
&self,
settings: &ProxyTestTargets,
context: &MutationContext,
) -> AdminStoreResult<Revision>;
/// 在凭据交换到提交期间保护选定代理的连接配置和测试结果
async fn reserve_import(&self, id: &str) -> AdminStoreResult<ProxyImportReservation>;
async fn list(&self, query: ProxyListQuery) -> AdminStoreResult<ProxyPage>;
@@ -78,5 +85,6 @@ pub enum ProbeRoute<'a> {
#[async_trait]
pub trait ProxyProbe: Send + Sync {
async fn test_target(&self, proxy: &OutboundProxy, endpoint: &str) -> TargetProbeResult;
async fn test(&self, proxy: ProbeRoute<'_>, detect_location: bool) -> ProxyTestResult;
}
@@ -69,6 +69,18 @@ async fn list_proxies(
#[async_trait]
pub trait ProxiesService: Send + Sync {
async fn test_targets(&self) -> Result<ProxyTestTargets, AdminError>;
async fn replace_test_targets(
&self,
settings: ProxyTestTargets,
context: &MutationContext,
) -> Result<ProxyTestTargets, AdminError>;
async fn test_target(
&self,
proxy_id: &str,
name: &str,
revision: Revision,
) -> Result<(String, TargetProbeResult), AdminError>;
async fn create_batch(
&self,
commands: Vec<Result<NewProxy, AdminError>>,
@@ -131,6 +143,12 @@ pub(crate) struct DefaultProxiesService {
}
impl DefaultProxiesService {
fn test_slot(&self) -> Result<tokio::sync::SemaphorePermit<'_>, AdminError> {
self.test_slots
.try_acquire()
.map_err(|_| AdminError::new(AdminErrorKind::RateLimited, "代理测试已达并发上限"))
}
pub(crate) fn new(
store: Arc<dyn ProxyStore>,
probe: Arc<dyn ProxyProbe>,
@@ -151,6 +169,84 @@ impl DefaultProxiesService {
#[async_trait]
impl ProxiesService for DefaultProxiesService {
async fn test_targets(&self) -> Result<ProxyTestTargets, AdminError> {
self.store
.test_targets()
.await
.map_err(|error| map_store_error(error, "proxy test targets"))
}
async fn replace_test_targets(
&self,
mut settings: ProxyTestTargets,
context: &MutationContext,
) -> Result<ProxyTestTargets, AdminError> {
if settings.targets.len() > 32 {
return Err(AdminError::invalid("最多可配置 32 个测试目标"));
}
let mut names = std::collections::HashSet::new();
for target in &mut settings.targets {
target.name = target.name.trim().to_owned();
if target.name.is_empty()
|| target.name.chars().count() > 100
|| target.name.chars().any(char::is_control)
{
return Err(AdminError::invalid("目标名称需要 1 至 100 个字符"));
}
if !names.insert(target.name.as_str()) {
return Err(AdminError::invalid("测试目标名称重复"));
}
let raw = target.url.trim();
let url = url::Url::parse(raw)
.ok()
.filter(|url| {
!raw.chars().any(char::is_control)
&& url.scheme() == "https"
&& url.has_host()
&& url.username().is_empty()
&& url.password().is_none()
&& url.fragment().is_none()
})
.ok_or_else(|| AdminError::invalid("请输入不含凭据和片段的 HTTPS 目标地址"))?;
if raw.len() > 2048 || url.as_str().len() > 2048 {
return Err(AdminError::invalid("目标地址不能超过 2048 字节"));
}
target.url = url.into();
}
settings.revision = self
.store
.replace_test_targets(&settings, context)
.await
.map_err(|error| map_store_error(error, "proxy test targets"))?;
publish_committed(self.snapshot.as_ref(), settings.revision).await?;
Ok(settings)
}
async fn test_target(
&self,
proxy_id: &str,
name: &str,
revision: Revision,
) -> Result<(String, TargetProbeResult), AdminError> {
let _permit = self.test_slot()?;
let settings = self.test_targets().await?;
if settings.revision != revision {
return Err(AdminError::conflict("测试目标已更新,请重新选择"));
}
let target = settings
.targets
.iter()
.find(|target| target.name == name)
.ok_or_else(|| AdminError::not_found("测试目标不存在"))?;
let record = self
.store
.get(proxy_id)
.await
.map_err(|error| map_store_error(error, "proxy"))?;
let result = self.probe.test_target(&record.proxy, &target.url).await;
Ok((record.name, result))
}
async fn create_batch(
&self,
commands: Vec<Result<NewProxy, AdminError>>,
@@ -394,10 +490,7 @@ impl ProxiesService for DefaultProxiesService {
proxy: ProbeRoute<'_>,
detect_location: bool,
) -> Result<ProxyTestResult, AdminError> {
let _permit = self
.test_slots
.try_acquire()
.map_err(|_| AdminError::new(AdminErrorKind::RateLimited, "代理测试已达并发上限"))?;
let _permit = self.test_slot()?;
Ok(self.probe.test(proxy, detect_location).await)
}
@@ -408,10 +501,7 @@ impl ProxiesService for DefaultProxiesService {
detect_location: bool,
context: &MutationContext,
) -> Result<ProxyRecord, AdminError> {
let _permit = self
.test_slots
.try_acquire()
.map_err(|_| AdminError::new(AdminErrorKind::RateLimited, "代理测试已达并发上限"))?;
let _permit = self.test_slot()?;
let record = self
.store
.get(id)
@@ -100,6 +100,20 @@ impl SnapshotControl for Fixture {
#[async_trait]
impl ProxyStore for Fixture {
async fn test_targets(
&self,
) -> gateway_admin::ports::store::AdminStoreResult<
gateway_admin::model::proxies::ProxyTestTargets,
> {
unreachable!()
}
async fn replace_test_targets(
&self,
_: &gateway_admin::model::proxies::ProxyTestTargets,
_: &gateway_admin::model::MutationContext,
) -> gateway_admin::ports::store::AdminStoreResult<gateway_admin::model::Revision> {
unreachable!()
}
async fn reserve_import(&self, _: &str) -> AdminStoreResult<ProxyImportReservation> {
unreachable!()
}
@@ -39,6 +39,20 @@ pub(super) struct TestPluginPorts;
#[async_trait]
impl gateway_admin::ports::proxy::ProxyStore for TestPluginPorts {
async fn test_targets(
&self,
) -> gateway_admin::ports::store::AdminStoreResult<
gateway_admin::model::proxies::ProxyTestTargets,
> {
unreachable!()
}
async fn replace_test_targets(
&self,
_: &gateway_admin::model::proxies::ProxyTestTargets,
_: &gateway_admin::model::MutationContext,
) -> gateway_admin::ports::store::AdminStoreResult<gateway_admin::model::Revision> {
unreachable!()
}
async fn reserve_import(
&self,
_: &str,
@@ -39,6 +39,20 @@ impl ProxyStore for TestProxies {
Err(super::unavailable("proxy"))
}
async fn test_targets(
&self,
) -> gateway_admin::ports::store::AdminStoreResult<
gateway_admin::model::proxies::ProxyTestTargets,
> {
unreachable!()
}
async fn replace_test_targets(
&self,
_: &gateway_admin::model::proxies::ProxyTestTargets,
_: &gateway_admin::model::MutationContext,
) -> gateway_admin::ports::store::AdminStoreResult<gateway_admin::model::Revision> {
unreachable!()
}
async fn reserve_import(
&self,
id: &str,
@@ -194,6 +208,14 @@ async fn plugin_proxy_resolution_requires_enabled_configuration_without_account_
#[async_trait]
impl ProxyProbe for TestProxies {
async fn test_target(
&self,
_: &gateway_core::account::OutboundProxy,
_: &str,
) -> gateway_admin::model::proxies::TargetProbeResult {
unreachable!()
}
async fn test(&self, _: ProbeRoute<'_>, _: bool) -> ProxyTestResult {
panic!("unexpected proxy probe")
}
@@ -487,6 +509,14 @@ impl Drop for ActiveProbe<'_> {
#[async_trait]
impl ProxyProbe for GatedProxyProbe {
async fn test_target(
&self,
_: &gateway_core::account::OutboundProxy,
_: &str,
) -> gateway_admin::model::proxies::TargetProbeResult {
unreachable!()
}
async fn test(&self, _: ProbeRoute<'_>, _: bool) -> ProxyTestResult {
self.active
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
@@ -13,7 +13,7 @@ use gateway_admin::model::{
AdminError as ServiceError, PageSize, Revision,
proxies::{
NewProxy, ProxyAccountListQuery, ProxyBatchResult, ProxyListQuery, ProxyMutation,
ProxyRecord, ProxyTestResult, TestProxy, UpdateProxy,
ProxyRecord, ProxyTestResult, ProxyTestTargets, TestProxy, UpdateProxy,
},
};
use serde::{Deserialize, Serialize};
@@ -260,6 +260,11 @@ where
.route("/api/admin/proxies/delete", post(delete::<S>))
.route("/api/admin/proxies/test", post(test::<S>))
.route("/api/admin/proxies/probe", post(probe::<S>))
.route(
"/api/admin/proxies/targets",
get(test_targets::<S>).post(replace_test_targets::<S>),
)
.route("/api/admin/proxies/targets/test", post(test_target::<S>))
}
fn revision(value: u64) -> Result<Revision, AdminError> {
@@ -546,6 +551,75 @@ where
))
}
async fn test_targets<S>(
_: AdminAuth,
State(state): State<S>,
) -> Result<impl IntoResponse, AdminError>
where
S: SessionState + Send + Sync,
{
let targets = state
.admin_services()
.proxies()
.test_targets()
.await
.map_err(map_error)?;
Ok(AdminResponse::new(
StatusCode::OK,
AdminEnvelope::ok(targets),
))
}
async fn replace_test_targets<S>(
auth: AdminAuth,
State(state): State<S>,
AdminJson(settings): AdminJson<ProxyTestTargets>,
) -> Result<impl IntoResponse, AdminError>
where
S: SessionState + Send + Sync,
{
let targets = state
.admin_services()
.proxies()
.replace_test_targets(settings, &auth.context().mutation_context())
.await
.map_err(map_error)?;
Ok(AdminResponse::new(
StatusCode::OK,
AdminEnvelope::ok(targets),
))
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct TargetTestRequest {
proxy_id: String,
target_name: String,
revision: Revision,
}
async fn test_target<S>(
_: AdminAuth,
State(state): State<S>,
AdminJson(request): AdminJson<TargetTestRequest>,
) -> Result<impl IntoResponse, AdminError>
where
S: SessionState + Send + Sync,
{
let (proxy_name, result) = state
.admin_services()
.proxies()
.test_target(&request.proxy_id, &request.target_name, request.revision)
.await
.map_err(map_error)?;
Ok(AdminResponse::new(
StatusCode::OK,
AdminEnvelope::ok(serde_json::json!({
"proxyName": proxy_name, "result": result,
})),
))
}
async fn probe<S>(
_: AdminAuth,
State(state): State<S>,
@@ -91,8 +91,71 @@ async fn proxy_location_rejects_invalid_and_incomplete_input() {
assert!(created["data"][0]["data"]["record"]["location"].is_null());
}
#[tokio::test]
async fn site_tests_use_saved_targets_and_preserve_the_exit_test() {
let fixture = AdminTestFixture::new().await;
fixture.auth.insert_session("valid-session");
let path = "/api/admin/proxies/targets";
assert_eq!(
request(&fixture, path, None, false).await.0,
StatusCode::UNAUTHORIZED
);
let (_, initial) = request(&fixture, path, None, true).await;
let revision = &initial["data"]["revision"];
let target = json!({"name":"ChatGPT","url":"https://chatgpt.com/cdn-cgi/trace"});
for targets in [
json!([{"name":"A","url":"http://example.org"}]),
json!([{"name":"A","url":"https://user:pass@example.org"}]),
json!([target, target]),
] {
let (status, _) = request(
&fixture,
path,
Some(json!({"revision":revision,"targets":targets})),
true,
)
.await;
assert_eq!(status, StatusCode::BAD_REQUEST);
}
let settings = json!({"revision":revision,"targets":[target]});
let (status, saved) = request(&fixture, path, Some(settings.clone()), true).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(
request(&fixture, path, Some(settings), true).await.0,
StatusCode::CONFLICT
);
let (status, _) = request(
&fixture,
"/api/admin/proxies/create",
Some(json!([{"name":"Office","proxyUrl":"http://proxy.example:8080"}])),
true,
)
.await;
assert_eq!(status, StatusCode::OK);
let run_path = "/api/admin/proxies/targets/test";
let mut run = json!({"proxyId":"proxy_test","targetName":"ChatGPT","revision":revision});
assert_eq!(
request(&fixture, run_path, Some(run.clone()), true).await.0,
StatusCode::CONFLICT
);
run["revision"] = saved["data"]["revision"].clone();
let (status, response) = request(&fixture, run_path, Some(run.clone()), true).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(
response["data"],
json!({"proxyName":"Office","result":{"kind":"http","status":403,"exitIp":null,"latencyMs":18}})
);
let (_, page) = request(&fixture, "/api/admin/proxies", None, true).await;
assert!(page["data"]["items"][0]["lastTest"].is_null());
run["targetName"] = json!("https://another.example");
assert_eq!(
request(&fixture, run_path, Some(run), true).await.0,
StatusCode::NOT_FOUND
);
}
#[derive(Default)]
pub(super) struct MemoryProxies(Mutex<Vec<ProxyRecord>>);
pub(super) struct MemoryProxies(Mutex<Vec<ProxyRecord>>, Mutex<Option<ProxyTestTargets>>);
#[tokio::test]
async fn proxy_enabled_updates_preserve_connection_and_omitted_state() {
@@ -153,6 +216,38 @@ impl ProxyStore for MemoryProxies {
Ok(Revision::new(4).unwrap())
}
async fn test_targets(&self) -> AdminStoreResult<ProxyTestTargets> {
Ok(self
.1
.lock()
.unwrap()
.clone()
.unwrap_or_else(|| ProxyTestTargets {
revision: Revision::new(1).unwrap(),
targets: vec![],
}))
}
async fn replace_test_targets(
&self,
settings: &ProxyTestTargets,
_: &MutationContext,
) -> AdminStoreResult<Revision> {
let mut saved = self.1.lock().unwrap();
let current = saved.as_ref().map_or(1, |value| value.revision.get());
if current != settings.revision.get() {
return Err(AdminStoreError::new(
AdminStoreErrorKind::StaleRevision,
"proxy test targets",
"stale revision",
));
}
let revision = Revision::new(current + 1).unwrap();
*saved = Some(ProxyTestTargets {
revision,
targets: settings.targets.clone(),
});
Ok(revision)
}
async fn reserve_import(
&self,
_: &str,
@@ -348,6 +443,22 @@ pub(super) struct SuccessfulProbe;
#[async_trait]
impl ProxyProbe for SuccessfulProbe {
async fn test_target(
&self,
proxy: &gateway_core::account::OutboundProxy,
endpoint: &str,
) -> gateway_admin::model::proxies::TargetProbeResult {
assert_eq!(proxy.expose_url(), "http://proxy.example:8080/");
assert_eq!(endpoint, "https://chatgpt.com/cdn-cgi/trace");
TargetProbeResult {
latency_ms: 18,
outcome: TargetProbeOutcome::Http {
status: 403,
exit_ip: None,
},
}
}
async fn test(&self, proxy: ProbeRoute<'_>, detect_location: bool) -> ProxyTestResult {
if let ProbeRoute::Proxy(proxy) = proxy {
assert_eq!(
+66 -13
View File
@@ -8,7 +8,9 @@ use std::{
use async_trait::async_trait;
use gateway_admin::{
model::proxies::{ProxyLocationDetection, ProxyTestResult},
model::proxies::{
ProxyLocationDetection, ProxyTestResult, TargetProbeOutcome, TargetProbeResult,
},
ports::proxy::{ProbeRoute, ProxyProbe},
};
use gateway_core::account::RequestLocation;
@@ -50,6 +52,17 @@ impl Default for HttpProxyProbe {
}
}
async fn read_probe_body(mut response: reqwest::Response) -> Result<Vec<u8>, &'static str> {
let mut body = Vec::new();
while let Some(chunk) = response.chunk().await.map_err(|_| "出口检测响应读取失败")? {
if body.len() + chunk.len() > 1024 {
return Err("出口检测响应过大");
}
body.extend_from_slice(&chunk);
}
Ok(body)
}
impl HttpProxyProbe {
#[must_use]
pub fn new(endpoint: impl Into<String>) -> Self {
@@ -82,23 +95,31 @@ impl HttpProxyProbe {
self
}
async fn exit_ip_at(
async fn request(
&self,
proxy: ProbeRoute<'_>,
endpoint: &str,
) -> Result<IpAddr, &'static str> {
) -> Result<reqwest::Response, &'static str> {
let builder = probe_client(proxy)?
.connect_timeout(Duration::from_secs(5))
.timeout(Duration::from_secs(12))
.redirect(reqwest::redirect::Policy::none());
let client = (self.build_client)(builder)?;
let mut response = client.get(endpoint).send().await.map_err(|error| {
client.get(endpoint).send().await.map_err(|error| {
if error.is_timeout() {
"出口连接超时"
} else {
"出口连接失败"
}
})?;
})
}
async fn exit_ip_at(
&self,
proxy: ProbeRoute<'_>,
endpoint: &str,
) -> Result<IpAddr, &'static str> {
let response = self.request(proxy, endpoint).await?;
if !response.status().is_success() {
return Err(
if response.status() == reqwest::StatusCode::PROXY_AUTHENTICATION_REQUIRED {
@@ -108,14 +129,7 @@ impl HttpProxyProbe {
},
);
}
let mut body = Vec::new();
while let Some(chunk) = response.chunk().await.map_err(|_| "出口检测响应读取失败")?
{
if body.len() + chunk.len() > 1024 {
return Err("出口检测响应过大");
}
body.extend_from_slice(&chunk);
}
let body = read_probe_body(response).await?;
#[derive(Deserialize)]
struct Response {
ip: IpAddr,
@@ -396,6 +410,45 @@ impl HttpProxyProbe {
#[async_trait]
impl ProxyProbe for HttpProxyProbe {
async fn test_target(
&self,
proxy: &gateway_core::account::OutboundProxy,
endpoint: &str,
) -> TargetProbeResult {
let started = Instant::now();
let response = self.request(ProbeRoute::Proxy(proxy), endpoint).await;
// 耗时截至收到响应头,可选的 trace 正文不影响站点状态与延迟
let latency_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX);
let outcome = match response {
Ok(response) => {
let status = response.status();
let exit_ip = if status.is_success() && response.url().path() == "/cdn-cgi/trace" {
read_probe_body(response).await.ok().and_then(|body| {
std::str::from_utf8(&body)
.ok()?
.lines()
.find_map(|line| line.strip_prefix("ip="))?
.parse()
.ok()
})
} else {
None
};
TargetProbeOutcome::Http {
status: status.as_u16(),
exit_ip,
}
}
Err(message) => TargetProbeOutcome::Failed {
message: message.to_owned(),
},
};
TargetProbeResult {
latency_ms,
outcome,
}
}
async fn test(&self, proxy: ProbeRoute<'_>, detect_location: bool) -> ProxyTestResult {
let mut result = self.test_connection(proxy).await;
if detect_location {
@@ -9,6 +9,52 @@ use wiremock::{
matchers::{any, header, path},
};
#[tokio::test]
async fn site_probe_reports_the_first_http_status_and_only_parses_bounded_trace_responses() {
use gateway_admin::model::proxies::TargetProbeOutcome;
for (endpoint, status, body, ip) in [
("/", 403, "ip=192.0.2.1".to_owned(), None),
("/", 302, String::new(), None),
(
"/cdn-cgi/trace",
200,
"ip=2001:db8::1\nloc=US\n".to_owned(),
Some("2001:db8::1"),
),
(
"/cdn-cgi/trace",
200,
format!("ip=192.0.2.1\n{}", "x".repeat(1024)),
None,
),
("/cdn-cgi/trace", 200, "ip=invalid".to_owned(), None),
] {
let server = MockServer::start().await;
Mock::given(path(endpoint))
.respond_with(
ResponseTemplate::new(status)
.insert_header("Location", "http://other.invalid/")
.set_body_string(body),
)
.expect(1)
.mount(&server)
.await;
let proxy = OutboundProxy::parse(&server.uri()).unwrap();
let result = HttpProxyProbe::default()
.test_target(&proxy, &format!("http://target.invalid{endpoint}"))
.await;
let TargetProbeOutcome::Http {
status: actual,
exit_ip,
} = result.outcome
else {
panic!("expected HTTP response")
};
assert_eq!(actual, status);
assert_eq!(exit_ip, ip.map(|ip| ip.parse().unwrap()));
}
}
#[tokio::test]
async fn proxy_probe_supports_ipv4_and_ipv6_proxies_and_exit_addresses() {
for (listen_address, exit_ip) in [
@@ -951,6 +951,14 @@ impl PricingSource for UnusedAdminRuntime {
#[async_trait]
impl ProxyProbe for UnusedAdminRuntime {
async fn test_target(
&self,
_: &gateway_core::account::OutboundProxy,
_: &str,
) -> gateway_admin::model::proxies::TargetProbeResult {
unreachable!()
}
async fn test(
&self,
_: gateway_admin::ports::proxy::ProbeRoute<'_>,
@@ -403,6 +403,59 @@ async fn audit(
#[async_trait]
impl ProxyStore for PgProxyRepository {
async fn test_targets(&self) -> AdminStoreResult<ProxyTestTargets> {
let (revision, targets) = sqlx::query_as::<_, (i64, sqlx::types::Json<Vec<ProxyTestTarget>>)>(
"select proxy_test_targets_revision, proxy_test_targets from runtime_settings where id = 1"
).fetch_one(&self.pool).await.map_err(|source| store_error(unavailable(source)))?;
Ok(ProxyTestTargets {
revision: AdminRevision::new(revision.try_into().map_err(|_| store_error(invalid()))?)
.map_err(|_| store_error(invalid()))?,
targets: targets.0,
})
}
async fn replace_test_targets(
&self,
settings: &ProxyTestTargets,
context: &MutationContext,
) -> AdminStoreResult<AdminRevision> {
let mut transaction = self
.pool
.begin()
.await
.map_err(|source| store_error(unavailable(source)))?;
let revision = bump_config_revision_in_transaction(&mut transaction)
.await
.map_err(store_error)?;
let updated = sqlx::query("update runtime_settings set proxy_test_targets = $1, proxy_test_targets_revision = $2 where id = 1 and proxy_test_targets_revision = $3")
.bind(sqlx::types::Json(&settings.targets))
.bind(i64::try_from(revision.get()).map_err(|_| store_error(invalid()))?)
.bind(i64::try_from(settings.revision.get()).map_err(|_| store_error(invalid()))?)
.execute(&mut *transaction).await.map_err(|source| store_error(unavailable(source)))?;
if updated.rows_affected() == 0 {
return Err(AdminStoreError::new(
gateway_admin::ports::store::AdminStoreErrorKind::StaleRevision,
"proxy test targets",
"stale revision",
));
}
audit(
&mut transaction,
context,
MutationAuditOperation::ProxyTestTargetsUpdate,
"1",
&["targets"],
revision,
)
.await
.map_err(store_error)?;
transaction
.commit()
.await
.map_err(|source| store_error(unavailable(source)))?;
admin_revision(revision)
}
async fn remove_account(
&self,
proxy_id: &str,
@@ -18,6 +18,36 @@ use gateway_store::postgres::{
use super::{TestDatabase, admin_account_store, provider_accounts::account};
#[tokio::test]
async fn proxy_test_targets_survive_reload_and_reject_stale_replacements() {
let Some(database) = TestDatabase::create("proxy_targets").await else {
return;
};
let repository = PgProxyRepository::new(database.pool.clone());
let mut settings = repository.test_targets().await.unwrap();
assert!(settings.targets.is_empty());
settings.targets.push(ProxyTestTarget {
name: "ChatGPT".into(),
url: "https://chatgpt.com/cdn-cgi/trace".into(),
});
let revision = repository
.replace_test_targets(&settings, &context())
.await
.unwrap();
let stale = repository
.replace_test_targets(&settings, &context())
.await
.unwrap_err();
assert_eq!(stale.kind(), AdminStoreErrorKind::StaleRevision);
let saved = PgProxyRepository::new(database.pool.clone())
.test_targets()
.await
.unwrap();
assert_eq!(saved.revision, revision);
assert_eq!(saved.targets, settings.targets);
database.close().await;
}
#[tokio::test]
async fn proxy_location_is_shared_preserved_cleared_and_removed_with_binding() {
use gateway_core::account::{ProviderAccountStore, RequestLocation};
+1
View File
@@ -47,3 +47,4 @@ e115a71b80faa08be4cf4f8747eec01e7b855ad3d8aa9622ca70b57300847b54 0046_account_a
98070edbfc34e71e403810fbb8db3bd18e7e241caeda2e952af022cd98ecdb6b 0047_request_plan_display.sql
709df48f4dd067332177fb8bee15c5e75d4666a0dc9c7a8e48f8480a01a99908 0048_openai_runtime_settings.sql
c7ade39b6c5026c1a728bf4e3e0d64c5d5b6aba1cf6fa13a64ca2b79172ab56c 0049_client_key_validity.sql
d715793026842c42a17c2846bec46bd9f01e256b10594b33765bea8ac374e380 0050_proxy_test_targets.sql
@@ -0,0 +1,3 @@
alter table runtime_settings
add column proxy_test_targets jsonb not null default '[]'::jsonb,
add column proxy_test_targets_revision bigint not null default 1 check (proxy_test_targets_revision > 0);
+6
View File
@@ -1497,6 +1497,8 @@ Search 的选号限制不约束插件在选号后主动改写正文。
| `POST` | `/api/admin/proxies/update` | `{ id, revision, name, enabled?, proxyUrl?, location?, autoLocation?, maxWebsocketConnections? }` | `{ record, configRevision }` |
| `POST` | `/api/admin/proxies/probe` | `{ proxyUrl, useDeploymentProxy?, detectLocation? }` | 测试未保存的地址、部署默认出口或服务器直连出口,返回连通性及可选位置结果,不创建代理 |
| `POST` | `/api/admin/proxies/test` | `[{ id, revision, detectLocation? }]` | 逐项结果数组,成功项的 `data` 为最新代理记录 |
| `GET` / `POST` | `/api/admin/proxies/targets` | GET 读取;POST 用 `{ revision, targets: [{ name, url }] }` 替换 | 返回当前目标列表及其版本,版本冲突返回 409 |
| `POST` | `/api/admin/proxies/targets/test` | `{ proxyId, targetName, revision }`,版本取自目标列表 | `{ proxyName, result }`,仅返回本次站点诊断 |
| `POST` | `/api/admin/proxies/delete` | `{ id, revision }` | `{ configRevision }` |
`probe` 的 `proxyUrl` 必填,空字符串默认测试服务器直连,同时传 `useDeploymentProxy: true` 则测试部署默认出口。指定代理地址时不能同时传 `useDeploymentProxy: true`;非空值须为合法代理 URL,`null`、省略或非法地址均拒绝。
@@ -1572,6 +1574,10 @@ API 的 `autoLocation` 默认为 `false`;开启时使用已检测位置,测
客户端实际本机时区不受影响,工具读取本机时区后的输出仍可包含真实值;排查见
[时区与客户端环境信息](../deploy/README.md#时区与客户端环境信息)
站点测试目标在部署内共享,最多 32 项。名称去除首尾空白后唯一,长度为 1–100 个字符;地址为最多 2048 字节的 HTTPS URL,不含用户凭据或片段。测试只接受已保存的代理和目标名称,目标配置变化后重新读取列表。管理端可选择多条代理测试同一目标,同时发起最多两条请求,与出口探测共用后端并发额度
站点测试发起 GET 并保留首个 HTTP 状态。收到响应时 `result` 包含 `kind: "http"`、`status`、`latencyMs` 和可空的 `exitIp`;只有成功的 `/cdn-cgi/trace` 响应才尝试读取 `ip=`。连接失败时返回 `kind: "failed"`、`latencyMs` 和 `message`。结果只在当次请求返回,代理的 `lastTest` 和检测位置仍由出口探测维护
测试经代理并发访问 IPv4 专用端点 `https://api.ipify.org?format=json` 与 IPv6 专用端点 `https://api6.ipify.org?format=json`,
分别验证并记录双栈出口(IPv4 与 IPv6 地址),在任一地址族可用时即判定连接成功。超时 15 秒,每进程最多同时测试 4 条。
解析位置时还会向 `https://ipwho.is/<出口 IP>` 查询地理位置,出口 IP 会发送给该第三方服务;
+1
View File
@@ -1180,6 +1180,7 @@ client,OIDC 的 JWKS 缓存与单飞归属对应出口状态。凭据变更后
出口测试结果属于诊断信息,不作为选择、授权或导入绑定的准入条件。
双栈出口并发检测,延迟对应首选可用出口的 HTTP 探测耗时(IPv4 优先),不包含另一地址族失败的等待;
检测仍等待两个地址族完成或超时,以保留双栈可用性结果。两者均失败时,延迟为整体检测耗时。
管理员配置的站点测试目标由代理管理模块持有。站点探测复用出口和并发额度,结果仅用于当次诊断;持久化出口和位置仍由双栈探测更新。
代理启停由代理记录独立持有;关闭时保留绑定、连接配置和位置规则,账号执行使用部署默认出口,
不使用该代理的位置覆盖,重新启用后恢复原出口。
连接配置改变时在同一事务内同步关联账号并清除旧测试结果。
+1 -1
View File
@@ -17,7 +17,7 @@
},
"dependencies": {
"@boxicons/vue": "1.0.1",
"@codex-proxy/ui": "github:zyycn/codex-proxy-ui#v0.13.4",
"@codex-proxy/ui": "github:zyycn/codex-proxy-ui#v0.13.5",
"@fontsource-variable/inter": "^5.3.0",
"@fontsource-variable/jetbrains-mono": "^5.3.0",
"@lucide/vue": "^1.77.0",
+6 -6
View File
@@ -195,8 +195,8 @@ importers:
specifier: 1.0.1
version: 1.0.1(vue@3.5.46(typescript@6.0.3))
'@codex-proxy/ui':
specifier: github:zyycn/codex-proxy-ui#v0.13.4
version: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/ac8114d16c0341c66e9c360f797c1ae77d2e0d5d(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)
specifier: github:zyycn/codex-proxy-ui#v0.13.5
version: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/8228b10d8f4b02bda468a075f7f87358630c0581(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)
'@fontsource-variable/inter':
specifier: ^5.3.0
version: 5.3.0
@@ -456,9 +456,9 @@ packages:
resolution: {integrity: sha512-dlT1m5e/0yUL0kRNcQn7yGLVThkgbB0Ga/1AmfDDC/8ik6AIiSf2QLQO2zPYvefsHP0aFgxO93cVLCCfDp7kzQ==}
engines: {node: '>= 20.12.0'}
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/ac8114d16c0341c66e9c360f797c1ae77d2e0d5d':
resolution: {gitHosted: true, integrity: sha512-6VttYlRECaLbR39j3VXBAradAwxo4PACMiorKz8WyVTnRWqKnvMxt2zhxu1GTHmQ9jJFg8Y/spfCuFP3P/Ym/Q==, tarball: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/ac8114d16c0341c66e9c360f797c1ae77d2e0d5d}
version: 0.13.4
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/8228b10d8f4b02bda468a075f7f87358630c0581':
resolution: {gitHosted: true, integrity: sha512-LtGKbhViL9fixVJSCtEUZHDx+/13VOOUK1PMJHl6tlrxyNm8OR7s0tcMpmb3se+/v/F2gfZ0He/3n4a6fanUUA==, tarball: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/8228b10d8f4b02bda468a075f7f87358630c0581}
version: 0.13.5
engines: {node: '>=24'}
peerDependencies:
vite: ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0
@@ -3590,7 +3590,7 @@ snapshots:
fast-wrap-ansi: 0.2.2
sisteransi: 1.0.5
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/ac8114d16c0341c66e9c360f797c1ae77d2e0d5d(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)':
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/8228b10d8f4b02bda468a075f7f87358630c0581(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)':
dependencies:
'@ant-design/colors': 8.0.1
'@ant-design/fast-color': 3.0.1
+44
View File
@@ -197,3 +197,47 @@ export function probeProxy(data: ProxyProbeParam, options: RequestOptions = {})
...options,
})
}
export interface ProxyTestTarget {
name: string
url: string
}
export interface ProxyTestTargets {
revision: number
targets: ProxyTestTarget[]
}
export type TargetProbeResult = { latencyMs: number } & (
| { kind: 'http', status: number, exitIp: string | null }
| { kind: 'failed', message: string }
)
export function getProxyTestTargets(options: RequestOptions = {}) {
return request<ProxyTestTargets>({
url: '/api/admin/proxies/targets',
method: 'GET',
...options,
})
}
export function saveProxyTestTargets(data: ProxyTestTargets, options: RequestOptions = {}) {
return request<ProxyTestTargets>({
url: '/api/admin/proxies/targets',
method: 'POST',
data,
retry: false,
...options,
})
}
export function testProxyTarget(data: { proxyId: string, targetName: string, revision: number }, options: RequestOptions = {}) {
return request<{ proxyName: string, result: TargetProbeResult }>({
url: '/api/admin/proxies/targets/test',
method: 'POST',
data,
timeout: 20000,
retry: false,
...options,
})
}
@@ -10,7 +10,7 @@ import ProviderSelect from '@/components/ProviderSelect.vue'
const props = defineProps<{ provider?: BuiltinProvider }>()
const emit = defineEmits<{
select: [provider: BuiltinProvider]
afterLeave: []
closed: []
}>()
const open = defineModel<boolean>({ default: false })
const selectedProvider = shallowRef<BuiltinProvider>('openai')
@@ -28,7 +28,7 @@ function select() {
:title="t('keys.configuration.importTo')"
:description="t('keys.configuration.selectImportTool')"
width="24rem"
@closed="emit('afterLeave')"
@closed="emit('closed')"
>
<div class="grid gap-2">
<ProviderSelect v-if="!provider" v-model="selectedProvider" :aria-label="t('keys.configuration.platform')" />
@@ -10,7 +10,7 @@ import ProviderSelect from '@/components/ProviderSelect.vue'
import { buildCcSwitchImportDeeplink, buildClientConfig, resolveServiceRootUrl } from './client'
const props = defineProps<{ title?: string, apiKey: { name?: string, key?: string } | null }>()
const emit = defineEmits<{ copy: [text: string], afterLeave: [] }>()
const emit = defineEmits<{ copy: [text: string], closed: [] }>()
const open = defineModel<boolean>({ default: false })
const { t } = useI18n({ useScope: 'global' })
const showImport = shallowRef(false)
@@ -44,7 +44,7 @@ function importToClient() {
</script>
<template>
<ZDialog v-model="open" :title="title ?? t('keys.configuration.title')" width="46rem" @closed="showImport = false; emit('afterLeave')">
<ZDialog v-model="open" destroy-on-close :title="title ?? t('keys.configuration.title')" width="46rem" @close="showImport = false" @closed="emit('closed')">
<div class="grid min-w-0 gap-3">
<div class="flex flex-wrap items-center justify-between gap-2">
<ProviderSelect v-model="provider" :aria-label="t('keys.configuration.platform')" />
@@ -74,5 +74,5 @@ function importToClient() {
</ZButton>
</template>
</ZDialog>
<ClientImportModal v-if="open" v-model="showImport" :provider="provider" @select="importToClient" />
<ClientImportModal v-model="showImport" :provider="provider" @select="importToClient" />
</template>
+17
View File
@@ -174,6 +174,23 @@
"enableFirst": "Enable this proxy before assigning accounts",
"assignAction": "Assign ({count})",
"assigned": "Assigned {count} account to “{name}” | Assigned {count} accounts to “{name}”"
},
"targets": {
"manage": "Manage sites",
"name": "Site name",
"address": "HTTPS URL",
"remove": "Remove site",
"add": "Add site",
"skipped": "Skipped",
"custom": "Custom test",
"site": "Test site",
"run": "Run test",
"empty": "No test sites yet",
"shared": "These sites are shared by all proxies",
"accessDenied": "Access denied",
"redirect": "Redirect",
"detectedRegion": "Detected region",
"includeSelected": "Test all {count} selected proxies"
}
}
}
@@ -174,6 +174,23 @@
"enableFirst": "启用此代理后可分配账号",
"assignAction": "分配 ({count})",
"assigned": "已将 {count} 个账号分配至“{name}”"
},
"targets": {
"manage": "管理站点",
"name": "站点名称",
"address": "HTTPS 地址",
"remove": "移除站点",
"add": "添加站点",
"skipped": "已跳过",
"custom": "自定义测试",
"site": "测试站点",
"run": "开始测试",
"empty": "还没有测试站点",
"shared": "所有代理共用这份站点列表",
"accessDenied": "拒绝访问",
"redirect": "重定向",
"detectedRegion": "已识别地区",
"includeSelected": "测试勾选的 {count} 个代理"
}
}
}
@@ -174,6 +174,23 @@
"enableFirst": "啟用此代理後可分配賬號",
"assignAction": "分配 ({count})",
"assigned": "已將 {count} 個賬號分配至“{name}”"
},
"targets": {
"manage": "管理站點",
"name": "站點名稱",
"address": "HTTPS 位址",
"remove": "移除站點",
"add": "新增站點",
"skipped": "已略過",
"custom": "自訂測試",
"site": "測試站點",
"run": "開始測試",
"empty": "還沒有測試站點",
"shared": "所有代理共用這份站點列表",
"accessDenied": "拒絕存取",
"redirect": "重新導向",
"detectedRegion": "已識別地區",
"includeSelected": "測試勾選的 {count} 個代理"
}
}
}
@@ -3,7 +3,7 @@ import type { AccountGroupRef, AccountModelAccess } from '@/api'
import { ZButton, ZDialog, ZForm, ZFormItem, ZSegmented } from '@codex-proxy/ui'
import { computed, useTemplateRef, watch } from 'vue'
import { computed, useTemplateRef } from 'vue'
import { useI18n } from 'vue-i18n'
import { useAccountSettingsFormRules } from '../composables/useAccountSettingsFormRules'
import AccountSettingsFields from './AccountSettingsFields.vue'
@@ -44,8 +44,6 @@ const rules = useAccountSettingsFormRules(() => form.value, {
editedFields: () => props.editedFields,
})
watch(open, () => formRef.value?.clearValidate())
async function requestSave() {
if (props.saving || !props.selectedCount || props.groupsLoading || !await formRef.value?.validate().catch(() => false))
return
@@ -81,10 +79,12 @@ const schedulingMode = computed({
<template>
<ZDialog
v-model="open"
destroy-on-close
:title="t('accounts.batchEdit.title')"
:description="t('accounts.batchEdit.selectionTitle', { count: selectedCount })"
width="48rem"
:show-close="!saving" :close-on-click-modal="!saving" :close-on-press-escape="!saving"
@open="formRef?.clearValidate()"
>
<ZForm ref="formElement" :model="form" :rules="rules" :validate-on-rule-change="false" scroll-to-error focus-on-error novalidate @submit="requestSave">
<AccountSettingsFields
@@ -4,7 +4,7 @@ import type { Account, AccountConnectionUpdate, AccountGroupRef, AccountModelAcc
import type { AccountConnectionForm } from '@/providers/accounts'
import { ZButton, ZDialog, ZForm } from '@codex-proxy/ui'
import { computed, useTemplateRef, watch } from 'vue'
import { computed, useTemplateRef } from 'vue'
import { useI18n } from 'vue-i18n'
import AccountPlanBadge from '@/components/account-plan-badge/index.vue'
import ProviderIconGroup from '@/components/ProviderIconGroup.vue'
@@ -53,8 +53,6 @@ const rules = useAccountSettingsFormRules(() => form.value, {
})
const saveDisabled = computed(() => !props.account || props.groupsLoading || (!!connectionComponent.value && !connection.value?.canSave))
watch(open, () => formRef.value?.clearValidate())
async function requestSave() {
if (props.saving || saveDisabled.value || !await formRef.value?.validate().catch(() => false))
return
@@ -65,9 +63,11 @@ async function requestSave() {
<template>
<ZDialog
v-model="open"
destroy-on-close
:title="t('accounts.editor.title')"
width="52rem"
:show-close="!saving" :close-on-click-modal="!saving" :close-on-press-escape="!saving"
@open="formRef?.clearValidate()"
>
<ZForm v-if="account" ref="formElement" :model="form" :rules="rules" :validate-on-rule-change="false" scroll-to-error focus-on-error novalidate @submit="requestSave">
<div
@@ -35,7 +35,7 @@ const props = withDefaults(defineProps<{
account: null,
})
const emit = defineEmits<{ create: [document?: Record<string, unknown>], generateOauth: [], afterLeave: [] }>()
const emit = defineEmits<{ create: [document?: Record<string, unknown>], generateOauth: [], closed: [] }>()
const { t } = useI18n({ useScope: 'global' })
@@ -102,12 +102,13 @@ async function continueToImport() {
<template>
<ZDialog
v-model="open"
destroy-on-close
:title="view.modal.title"
:description="view.modal.description"
:type="view.modal.type"
:width="view.modal.width"
:show-close="!busy" :close-on-click-modal="!busy" :close-on-press-escape="!busy"
@closed="emit('afterLeave')"
@closed="emit('closed')"
>
<template #icon>
<Settings2 v-if="view.configuring" class="text-z-text" :size="20" aria-hidden="true" />
@@ -17,7 +17,7 @@ const props = defineProps<{
error: string
}>()
const emit = defineEmits<{ select: [id: string], stop: [], viewAccounts: [], afterLeave: [] }>()
const emit = defineEmits<{ select: [id: string], stop: [], viewAccounts: [], closed: [] }>()
const { t } = useI18n({ useScope: 'global' })
@@ -48,7 +48,7 @@ function handleRetentionKeydown(event: KeyboardEvent) {
</script>
<template>
<ZDialog v-model="open" :title="t('accounts.filters.importTasks')" :description="t('accounts.importTasks.description')" width="48rem" @closed="emit('afterLeave')">
<ZDialog v-model="open" :title="t('accounts.filters.importTasks')" :description="t('accounts.importTasks.description')" width="48rem" @closed="emit('closed')">
<ZEmpty v-if="!tasks.length && !error" class="min-h-[min(20rem,50dvh)] content-center" :icon="ListTodo" :title="loading ? t('accounts.importTasks.loadingImportTasks') : t('accounts.importTasks.noImportTasks')" :description="t('accounts.importTasks.empty')" />
<div v-else-if="tasks.length" class="min-h-[min(20rem,50dvh)] min-w-0">
<div v-if="tasks.length > 1" class="mb-5">
@@ -78,6 +78,7 @@ function handleExplanationKeydown(event: KeyboardEvent) {
<template>
<ZDialog
v-model="open"
destroy-on-close
:title="t('accounts.quotaForecast.quotaForecast')"
:description="t('accounts.quotaForecast.periodHelp')"
width="36rem"
+2 -2
View File
@@ -417,7 +417,7 @@ const {
:error="importTaskError"
@select="importTasks.select"
@stop="importTasks.stop"
@after-leave="importTasks.refresh(true)"
@closed="importTasks.refresh(true)"
@view-accounts="showImportTasks = false; loadAccounts()"
/>
@@ -433,7 +433,7 @@ const {
:saving="creatingAccount"
@create="handleCreate"
@generate-oauth="handleAuthorizeOAuth"
@after-leave="clearCreate"
@closed="clearCreate"
/>
<AccountEditModal
@@ -5,7 +5,7 @@ import type { AccountGroupFormValue } from '../composables/useAccountGroups'
import type { AccountGroup } from '@/api'
import type { BuiltinProvider } from '@/providers/catalog'
import { normalizeRgbaHexColor, ZButton, ZColorPicker, ZDialog, ZEmpty, ZForm, ZFormItem, ZInput, ZSegmented, ZTextarea } from '@codex-proxy/ui'
import { computed, shallowRef, useTemplateRef, watch } from 'vue'
import { computed, shallowRef, useTemplateRef } from 'vue'
import { useI18n } from 'vue-i18n'
import AccountModelAccessField from '@/components/account-model-access-field/index.vue'
@@ -51,11 +51,10 @@ const rules = computed<FormRules<AccountGroupFormValue>>(() => ({
message: t('groups.actions.selectValidGroupingColor'),
},
}))
watch(open, (visible) => {
function initializeForm() {
provider.value = 'openai'
formRef.value?.clearValidate()
if (visible)
provider.value = 'openai'
})
}
async function requestSave() {
if (props.saving || !await formRef.value?.validate().catch(() => false))
@@ -83,10 +82,12 @@ const description = computed(() => props.group
<template>
<ZDialog
v-model="open"
destroy-on-close
:title="title"
:description="description"
width="42rem"
:show-close="!saving" :close-on-click-modal="!saving" :close-on-press-escape="!saving"
@open="initializeForm"
>
<ZForm ref="formElement" :model="form" :rules="rules" class="sm:grid-cols-[minmax(0,1fr)_fit-content(10rem)] sm:gap-x-6 md:grid-cols-[minmax(0,1fr)_fit-content(11rem)]" scroll-to-error focus-on-error novalidate @submit="requestSave">
<ZFormItem prop="name" :show-message="false" :label="t('groups.editor.groupName')" required>
+1 -1
View File
@@ -49,6 +49,6 @@ const { showConfig, configKey, configuring, openConfig, copyConfig } = useKeyCon
<KeyUsageRecords v-model:kind="kind" :rows="items" :pagination="{ currentPage, pageSize, total }" :loading="recordsLoading" @page-change="changePage" @page-size-change="changePageSize" />
</div>
</ZScrollbar>
<ApiKeyConfigModal v-model="showConfig" :title="t('usage.header.keyConfiguration')" :api-key="configKey" @copy="copyConfig" @after-leave="configKey = null" />
<ApiKeyConfigModal v-model="showConfig" :title="t('usage.header.keyConfiguration')" :api-key="configKey" @copy="copyConfig" @closed="configKey = null" />
</main>
</template>
@@ -195,7 +195,9 @@ async function applyChanges() {
<template>
<ZDialog
v-model="open" :title="t('keys.batch.edit')" :description="t('keys.batch.description', { count: keys.length })" width="48rem" type="info"
v-model="open"
destroy-on-close
:title="t('keys.batch.edit')" :description="t('keys.batch.description', { count: keys.length })" width="48rem" type="info"
:show-close="!loading" :close-on-click-modal="!loading" :close-on-press-escape="!loading"
>
<template #icon>
@@ -12,7 +12,7 @@ defineProps<{ createdKey: string }>()
const emit = defineEmits<{
copy: [text: string]
importClient: [provider: BuiltinProvider]
afterLeave: []
closed: []
}>()
const { t } = useI18n({ useScope: 'global' })
@@ -24,11 +24,12 @@ const showImport = shallowRef(false)
<template>
<ZDialog
v-model="open"
destroy-on-close
:title="t('keys.created.apiKeyCreated')"
:description="t('keys.created.description')"
type="success"
width="36rem"
@closed="showImport = false; emit('afterLeave')"
@close="showImport = false" @closed="emit('closed')"
>
<div class="flex flex-col gap-4">
<div class="rounded-z bg-z-warning-container px-4 py-3">
@@ -63,5 +64,5 @@ const showImport = shallowRef(false)
</ZButton>
</template>
</ZDialog>
<ClientImportModal v-if="open" v-model="showImport" @select="emit('importClient', $event)" />
<ClientImportModal v-model="showImport" @select="emit('importClient', $event)" />
</template>
@@ -6,7 +6,7 @@ import type { BuiltinProvider } from '@/providers/catalog'
import { ZButton, ZDialog, ZForm, ZFormItem, ZInput } from '@codex-proxy/ui'
import { KeyRound } from '@lucide/vue'
import { computed, nextTick, shallowRef, useTemplateRef, watch } from 'vue'
import { computed, nextTick, shallowRef, useTemplateRef } from 'vue'
import { useI18n } from 'vue-i18n'
import AccountGroupCheckboxGrid from '@/components/AccountGroupCheckboxGrid.vue'
import ProviderSettingsSection from '@/components/ProviderSettingsSection.vue'
@@ -28,7 +28,7 @@ const props = defineProps<{
const emit = defineEmits<{
save: []
afterLeave: []
closed: []
}>()
const { t } = useI18n({ useScope: 'global' })
@@ -47,11 +47,10 @@ const installationSeedError = computed(() => isValidInstallationSeed(form.value.
? ''
: t('settings.clientProfile.invalidInstallationSeed'))
watch(open, (visible) => {
function initializeForm() {
provider.value = 'openai'
formRef.value?.clearValidate()
if (visible)
provider.value = 'openai'
})
}
async function requestSave() {
if (props.saving)
@@ -82,12 +81,14 @@ function updatePeerSharing(key: keyof ApiKeyPeerSharing, value: boolean) {
<template>
<ZDialog
v-model="open"
destroy-on-close
:title="title"
:description="t('keys.editor.description')"
type="info"
width="48rem"
:show-close="!saving" :close-on-click-modal="!saving" :close-on-press-escape="!saving"
@closed="emit('afterLeave')"
@open="initializeForm"
@closed="emit('closed')"
>
<template #icon>
<KeyRound class="text-z-text" :size="20" aria-hidden="true" />
@@ -15,7 +15,7 @@ import { formatCompactNumber, formatInteger, formatUsd } from '@/utils/format'
import ApiKeyModelUsageTable from './ApiKeyModelUsageTable.vue'
const props = defineProps<{ apiKey: ApiKey }>()
const emit = defineEmits<{ close: [] }>()
const emit = defineEmits<{ closed: [] }>()
const { t } = useI18n({ useScope: 'global' })
const open = shallowRef(true)
const trend = useTemplateRef<HTMLElement>('trend')
@@ -188,7 +188,7 @@ watch([
</script>
<template>
<ZDialog v-model="open" :title="t('keys.statistics.heading', { name: apiKey.name })" width="70rem" @closed="emit('close')">
<ZDialog v-model="open" :title="t('keys.statistics.heading', { name: apiKey.name })" width="70rem" @closed="emit('closed')">
<div class="grid min-w-0 gap-3">
<div class="flex shrink-0 flex-wrap items-center justify-between gap-2">
<ZSegmented v-model="metric" size="small" :options="metrics" :aria-label="t('keys.statistics.metric')" />
+5 -5
View File
@@ -275,7 +275,7 @@ watch([showFormModal, showBatchEdit], ([editor, batch]) => {
:editing="Boolean(editingKey)"
:saving="savingKey"
@save="requestSave"
@after-leave="clearCustomKey"
@closed="clearCustomKey"
/>
<ApiKeyCreatedModal
@@ -283,10 +283,10 @@ watch([showFormModal, showBatchEdit], ([editor, batch]) => {
:created-key="createdKey"
@copy="copyToClipboard"
@import-client="importCreatedKey"
@after-leave="clearCreatedKey"
@closed="clearCreatedKey"
/>
<ApiKeyStatisticsModal v-if="statisticsKey" :api-key="statisticsKey" @close="statisticsKey = null" />
<ApiKeyStatisticsModal v-if="statisticsKey" :api-key="statisticsKey" @closed="statisticsKey = null" />
<ApiKeyBudgetResetModal
v-model="showBudgetResetModal"
@@ -298,13 +298,13 @@ watch([showFormModal, showBatchEdit], ([editor, batch]) => {
v-model="showUseKeyModal"
:api-key="selectedUseKey"
@copy="copyToClipboard"
@after-leave="selectedUseKey = null"
@closed="selectedUseKey = null"
/>
<ClientImportModal
v-model="showImportKeyModal"
@select="importSelectedKey"
@after-leave="selectedImportKey = null"
@closed="selectedImportKey = null"
/>
<ZConfirmDialog
@@ -141,7 +141,7 @@ function clearSecrets() {
</script>
<template>
<ZDialog v-model="open" :title="versionChanged ? t('plugins.configuration.switchTo', { version: artifact?.metadata.version }) : t('plugins.configuration.pluginSettings')" :description="artifact ? `${artifact.metadata.displayName} · ${artifact.metadata.version}` : undefined" width="48rem" :show-close="!saving" :close-on-click-modal="!saving" :close-on-press-escape="!saving" @closed="clearSecrets">
<ZDialog v-model="open" destroy-on-close :title="versionChanged ? t('plugins.configuration.switchTo', { version: artifact?.metadata.version }) : t('plugins.configuration.pluginSettings')" :description="artifact ? `${artifact.metadata.displayName} · ${artifact.metadata.version}` : undefined" width="48rem" :show-close="!saving" :close-on-click-modal="!saving" :close-on-press-escape="!saving" @closed="clearSecrets">
<div v-if="artifact && instance" class="grid gap-5">
<div v-if="error" role="alert" class="grid gap-1 text-z-sm text-z-warning-text">
<span>{{ error }}</span>
@@ -39,6 +39,18 @@ const { t } = useI18n({ useScope: 'global' })
const open = defineModel<boolean>({ required: true })
const section = shallowRef('configurations')
let navigateAfterClose: (() => void) | undefined
function openPluginPage(navigate: () => void) {
navigateAfterClose = navigate
open.value = false
}
function finishClose() {
navigateAfterClose?.()
navigateAfterClose = undefined
}
const sections = computed(() => ([
{
label: t('navigation.overview'),
@@ -73,14 +85,16 @@ function configurationNotes(instance: PluginInstance) {
return notes
}
watch(open, (value) => {
if (value)
if (value) {
navigateAfterClose = undefined
section.value = props.initialSection
}
})
watch(() => props.initialSection, value => section.value = value)
</script>
<template>
<ZDialog v-model="open" :title="plugin?.artifact.metadata.displayName ?? t('plugins.details.pluginDetails')" :description="plugin?.artifact.metadata.description" width="42rem" :show-close="!busy" :close-on-click-modal="!busy" :close-on-press-escape="!busy">
<ZDialog v-model="open" :title="plugin?.artifact.metadata.displayName ?? t('plugins.details.pluginDetails')" :description="plugin?.artifact.metadata.description" width="42rem" :show-close="!busy" :close-on-click-modal="!busy" :close-on-press-escape="!busy" @closed="finishClose">
<div v-if="plugin" class="grid gap-5">
<div class="flex flex-wrap items-center gap-3">
<ZSegmented v-model="section" :options="sections" :aria-label="t('plugins.details.pluginDetailsSection')" />
@@ -126,9 +140,11 @@ watch(() => props.initialSection, value => section.value = value)
<PluginRuntimeLoad v-if="instance.runtime.load" :load="instance.runtime.load" :revision="instance.runtime.actualRevision" />
<div class="flex flex-wrap items-center gap-2">
<div v-if="configurationStatus(instance) === 'enabled'" class="mr-auto flex min-w-0 flex-wrap items-center gap-2">
<RouterLink v-for="page in viewByInstance.get(instance.id)?.pages ?? []" :key="page.id" :to="pluginPageLocation(viewByInstance.get(instance.id)!, page)" class="inline-flex h-z-control-sm min-w-0 items-center gap-1.5 rounded-z bg-z-primary-container px-2.5 text-z-sm leading-none text-z-primary-on-container no-underline outline-none transition-colors hover:bg-z-primary-container-hover focus-visible:ring-2 focus-visible:ring-z-control-outline motion-reduce:transition-none" @click="open = false">
<span class="truncate">{{ page.title }}</span>
<ArrowUpRight class="size-3.5 shrink-0" />
<RouterLink v-for="page in viewByInstance.get(instance.id)?.pages ?? []" :key="page.id" v-slot="{ href, navigate }" :to="pluginPageLocation(viewByInstance.get(instance.id)!, page)" custom>
<a :href="href" class="inline-flex h-z-control-sm min-w-0 items-center gap-1.5 rounded-z bg-z-primary-container px-2.5 text-z-sm leading-none text-z-primary-on-container no-underline outline-none transition-colors hover:bg-z-primary-container-hover focus-visible:ring-2 focus-visible:ring-z-control-outline motion-reduce:transition-none" @click.left.exact.prevent="openPluginPage(navigate)">
<span class="truncate">{{ page.title }}</span>
<ArrowUpRight class="size-3.5 shrink-0" />
</a>
</RouterLink>
</div>
<ZIconButton v-if="instance.configurationRequired || (currentArtifact && hasPluginSettings(currentArtifact))" size="small" variant="solid" :aria-label="t('plugins.details.settings')" :disabled="busy" @click="$emit('edit', instance)">
@@ -441,15 +441,6 @@ function githubQueryKey() {
})
}
watch(open, (isOpen) => {
if (isOpen) {
reset()
}
else {
rememberDraft()
}
})
function clearCredentials() {
credentialDraft.value = null
}
@@ -493,10 +484,13 @@ watch(
<template>
<ZDialog
v-model="open"
destroy-on-close
:title="updateSource ? t('plugins.installation.updatePlugin') : t('plugins.installation.installPlugin')"
:description="acceptanceArtifact ? t('plugins.installation.installDescription') : updateSource ? t('plugins.installation.switchDescription') : t('plugins.installation.sourceHelp')"
width="36rem"
:show-close="!busy" :close-on-click-modal="!busy" :close-on-press-escape="!busy"
@open="reset"
@close="rememberDraft"
@closed="clearCredentials"
>
<ZSegmented
@@ -38,7 +38,7 @@ watch(() => props.plan, () => {
</script>
<template>
<ZDialog v-model="open" :title="t('plugins.rollback.rollBackPluginVersion')" :description="t('plugins.rollback.description')" width="36rem" :show-close="!saving" :close-on-click-modal="!saving" :close-on-press-escape="!saving">
<ZDialog v-model="open" destroy-on-close :title="t('plugins.rollback.rollBackPluginVersion')" :description="t('plugins.rollback.description')" width="36rem" :show-close="!saving" :close-on-click-modal="!saving" :close-on-press-escape="!saving">
<ZForm class="grid gap-4">
<ZFormItem :label="t('plugins.catalog.currentVersion')">
<p class="m-0 break-all text-z-sm text-z-text">
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { ZButton, ZDialog } from '@codex-proxy/ui'
import { onMounted, shallowRef } from 'vue'
import { shallowRef } from 'vue'
import { useI18n } from 'vue-i18n'
import { useCopyText } from '@/composables/useCopyText'
@@ -9,12 +9,7 @@ defineEmits<{ closed: [] }>()
const { t } = useI18n({ useScope: 'global' })
const copyText = useCopyText()
const open = shallowRef(false)
// 确认框按请求挂载,挂载后打开才会触发入场动画
onMounted(() => {
open.value = true
})
const open = shallowRef(true)
function openLink() {
window.open(props.link.href, '_blank', 'noopener,noreferrer')
@@ -2,7 +2,7 @@
import type { OutboundProxyRecord } from '@/api'
import { ZIconButton, ZMenuItem } from '@codex-proxy/ui'
import { Pencil, Power, Trash2, Wifi } from '@lucide/vue'
import { Globe, Pencil, Power, Trash2, Wifi } from '@lucide/vue'
import { useI18n } from 'vue-i18n'
import RowActionMenu from '@/components/RowActionMenu.vue'
@@ -15,6 +15,7 @@ defineProps<{
const emit = defineEmits<{
test: [proxy: OutboundProxyRecord]
testTarget: []
edit: [proxy: OutboundProxyRecord]
toggle: [proxy: OutboundProxyRecord]
delete: [proxy: OutboundProxyRecord]
@@ -32,6 +33,12 @@ const { t } = useI18n({ useScope: 'global' })
<Pencil class="size-3.5 text-z-link" />
</ZIconButton>
<RowActionMenu :label="t('proxies.actions.moreActionsFor', { name: proxy.name })" menu-class="w-36 p-1.5" :disabled="testing || updating" :loading="updating">
<ZMenuItem :disabled="batchTesting || testing || updating" @click="emit('testTarget')">
<template #icon>
<Globe class="size-3.5 text-z-text-quaternary" />
</template>
{{ t('proxies.targets.custom') }}
</ZMenuItem>
<ZMenuItem :disabled="testing || updating" @click="emit('toggle', proxy)">
<template #icon>
<Power class="size-3.5" :class="proxy.enabled ? 'text-z-warning' : 'text-z-success'" />
@@ -0,0 +1,147 @@
<script setup lang="ts">
import type { TargetTestProxy } from '../composables/useProxyTargetTest'
import type { ProxyTestTarget, ProxyTestTargets } from '@/api'
import { ZButton, ZCheckbox, ZDialog, ZSelect } from '@codex-proxy/ui'
import { Settings2 } from '@lucide/vue'
import { computed, ref, shallowRef } from 'vue'
import { useI18n } from 'vue-i18n'
import { getProxyTestTargets, saveProxyTestTargets } from '@/api'
import { ApiError } from '@/api/request'
import { useRequestState } from '@/composables/useRequestState'
import { useProxyTargetTest } from '../composables/useProxyTargetTest'
import ProxyTargetEditor from './ProxyTargetEditor.vue'
import ProxyTargetResultCard from './ProxyTargetResultCard.vue'
const props = defineProps<{ proxy: TargetTestProxy, selectedProxies: TargetTestProxy[] }>()
const emit = defineEmits<{ closed: [] }>()
const { t } = useI18n({ useScope: 'global' })
const open = shallowRef(true)
const includeSelection = shallowRef(false)
const settings = shallowRef<ProxyTestTargets>()
const selected = shallowRef<string>()
const draft = ref<ProxyTestTarget[]>()
const stale = shallowRef(false)
const catalog = useRequestState()
const { loading, error } = catalog
const testProxies = computed(() => includeSelection.value
? props.selectedProxies
: [props.proxy])
const { byProxyId, clearResults, running, start, cancel } = useProxyTargetTest(() => {
stale.value = true
})
const options = computed(() => settings.value?.targets.map(({ name, url }) => ({ label: name, value: name, description: url })) ?? [])
function accept(data: ProxyTestTargets) {
settings.value = data
if (!data.targets.some(target => target.name === selected.value))
selected.value = data.targets[0]?.name
clearResults()
stale.value = false
}
async function load() {
const id = catalog.start()
try {
const data = await getProxyTestTargets({ silent: true, signal: catalog.signal })
if (catalog.isCurrent(id)) {
accept(data)
if (draft.value)
edit()
}
}
catch (cause) {
catalog.fail(id, cause)
}
finally {
catalog.finish(id)
}
}
function edit() {
const targets = settings.value?.targets ?? []
draft.value = targets.length
? targets.map(target => ({ ...target }))
: [
{ name: '', url: '' },
]
}
async function save() {
if (!draft.value || !settings.value || stale.value || loading.value)
return
const id = catalog.start()
try {
const data = await saveProxyTestTargets({ revision: settings.value.revision, targets: draft.value }, { signal: catalog.signal, silent: true })
if (catalog.isCurrent(id)) {
accept(data)
draft.value = undefined
}
}
catch (cause) {
catalog.fail(id, cause)
if (cause instanceof ApiError && cause.status === 409)
stale.value = true
}
finally {
catalog.finish(id)
}
}
function cancelRequests() {
catalog.invalidate({ resetLoading: false })
cancel({ resetLoading: false })
}
function test() {
if (!settings.value || !selected.value || running.value || stale.value)
return
void start(testProxies.value, selected.value, settings.value.revision)
}
</script>
<template>
<ZDialog v-model="open" :title="t(draft ? 'proxies.targets.manage' : 'proxies.targets.custom')" :description="draft ? t('proxies.targets.shared') : undefined" width="38rem" :show-close="!draft || !loading" :close-on-click-modal="!draft || !loading" :close-on-press-escape="!draft || !loading" @open="load" @close="cancelRequests" @closed="emit('closed')">
<ProxyTargetEditor v-if="draft" v-model="draft" :disabled="loading || stale" />
<template v-else-if="settings">
<div v-if="selected" class="grid gap-2">
<span class="text-z-sm font-emphasis text-z-text">{{ t('proxies.targets.site') }}</span>
<ZSelect v-model="selected" class="w-full" :aria-label="t('proxies.targets.site')" :options="options" :disabled="running || loading || stale" @change="clearResults" />
</div>
<p v-else class="m-0 text-z-sm text-z-text-secondary">
{{ t('proxies.targets.empty') }}
</p>
<ZCheckbox v-if="props.selectedProxies.length && selected" v-model="includeSelection" class="mt-3" :disabled="running || loading" :label="t('proxies.targets.includeSelected', { count: props.selectedProxies.length })" @update:model-value="clearResults" />
</template>
<p v-else-if="loading" class="m-0 text-z-sm text-z-text-secondary" role="status">
{{ t('common.status.loading') }}
</p>
<p v-if="error" class="m-0 text-z-sm text-z-error" role="alert">
{{ error }}
</p>
<ul v-if="!draft" class="mt-5 mb-0 grid list-none gap-2 p-0" aria-live="polite">
<ProxyTargetResultCard v-for="item in testProxies" :key="item.id" :proxy="item" :row="byProxyId.get(item.id)" :batch-running="running" />
</ul>
<template #footer>
<ZButton v-if="!draft && selected" class="mr-auto" :disabled="running || loading || stale" @click="edit">
<template #icon>
<Settings2 class="size-4" />
</template>
{{ t('proxies.targets.manage') }}
</ZButton>
<ZButton v-if="draft" :disabled="loading" @click="draft = undefined; error = ''">
{{ t('common.actions.cancel') }}
</ZButton>
<ZButton v-if="stale || (!settings && !loading)" :disabled="running" :loading="loading" @click="load">
{{ t('common.actions.refresh') }}
</ZButton>
<ZButton v-else-if="draft" type="primary" :loading="loading" @click="save">
{{ t('common.actions.save') }}
</ZButton>
<ZButton v-else-if="settings && !selected" type="primary" @click="edit">
{{ t('proxies.targets.add') }}
</ZButton>
<ZButton v-else-if="selected" type="primary" :loading="running" :disabled="loading" @click="test">
{{ t('proxies.targets.run') }}
</ZButton>
</template>
</ZDialog>
</template>
@@ -0,0 +1,28 @@
<script setup lang="ts">
import type { ProxyTestTarget } from '@/api'
import { ZButton, ZIconButton, ZInput } from '@codex-proxy/ui'
import { Plus, Trash2 } from '@lucide/vue'
import { useI18n } from 'vue-i18n'
defineProps<{ disabled: boolean }>()
const targets = defineModel<ProxyTestTarget[]>({ required: true })
const { t } = useI18n({ useScope: 'global' })
</script>
<template>
<div class="grid gap-3">
<div v-for="(target, index) in targets" :key="index" class="flex items-center gap-2">
<div class="grid min-w-0 flex-1 gap-2 sm:grid-cols-[1fr_2fr]">
<ZInput v-model="target.name" maxlength="100" :disabled="disabled" :aria-label="t('proxies.targets.name')" :placeholder="t('proxies.targets.name')" />
<ZInput v-model="target.url" maxlength="2048" :disabled="disabled" :aria-label="t('proxies.targets.address')" :placeholder="t('proxies.targets.address')" />
</div>
<ZIconButton :aria-label="t('proxies.targets.remove')" :disabled="disabled" @click="targets.splice(index, 1)">
<Trash2 class="size-4" />
</ZIconButton>
</div>
<ZButton class="justify-self-start" :disabled="disabled || targets.length >= 32" @click="targets.push({ name: '', url: '' })">
<Plus class="size-4" />
{{ t('proxies.targets.add') }}
</ZButton>
</div>
</template>
@@ -0,0 +1,89 @@
<script setup lang="ts">
import type { ProxyTargetTestRow, TargetTestProxy } from '../composables/useProxyTargetTest'
import { ZTag } from '@codex-proxy/ui'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { countryName, proxyExitLocation } from '../utils/location'
const props = defineProps<{ proxy: TargetTestProxy, row?: ProxyTargetTestRow, batchRunning: boolean }>()
const { t } = useI18n({ useScope: 'global' })
const exitIp = computed(() => props.row?.result?.kind === 'http'
? props.row.result.exitIp
: null)
const location = computed(() => {
const ip = exitIp.value
const detected = props.proxy.detectedLocation
if (!ip || !detected || (ip !== detected.exitIpv4 && ip !== detected.exitIpv6))
return null
return proxyExitLocation(props.proxy)
})
const failure = computed(() => props.row?.result?.kind === 'failed'
? props.row.result.message
: props.row?.error)
function httpLabel(status: number) {
if (status >= 200 && status < 300)
return t('common.status.success')
if (status === 403)
return t('proxies.targets.accessDenied')
if (status === 429)
return t('common.status.rateLimited')
if (status >= 300 && status < 400)
return t('proxies.targets.redirect')
return ''
}
</script>
<template>
<li class="min-w-0 rounded-z-card bg-z-fill-quaternary px-4 py-3">
<div class="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1.5">
<strong class="min-w-0 grow basis-44 text-z-sm font-emphasis wrap-anywhere text-z-text">{{ row?.name ?? proxy.name }}</strong>
<ZTag v-if="row?.result?.kind === 'http'" :type="row.result.status >= 500 ? 'danger' : row.result.status >= 300 ? 'warning' : 'success'" size="small">
HTTP {{ row.result.status }} {{ httpLabel(row.result.status) }}
</ZTag>
<ZTag v-else-if="row?.result?.kind === 'failed' || row?.error" type="danger" size="small">
{{ row?.result?.kind === 'failed' ? t('proxies.region.connectionFailed') : t('common.status.failed') }}
</ZTag>
<span v-else-if="!row" class="text-z-xs text-z-text-secondary">{{ t('proxies.page.notTested') }}</span>
<span v-else class="text-z-xs text-z-text-secondary">{{ row.running ? t('proxies.page.underTest') : batchRunning ? t('common.status.pending') : t('proxies.targets.skipped') }}</span>
</div>
<dl class="mt-3 mb-0 flex flex-wrap items-start gap-x-7 gap-y-2 text-z-sm">
<div v-if="proxy.endpoint" class="grid min-w-0 gap-0.5">
<dt class="text-z-xs text-z-text-secondary">
{{ t('proxies.editor.proxyAddress') }}
</dt>
<dd class="m-0 font-mono font-medium wrap-anywhere text-z-text">
{{ proxy.endpoint }}
</dd>
</div>
<div class="grid min-w-0 gap-0.5">
<dt class="text-z-xs text-z-text-secondary">
{{ t('proxies.fields.exitIp') }}
</dt>
<dd class="m-0 flex flex-wrap items-baseline gap-x-1.5">
<span class="font-mono font-medium wrap-anywhere text-z-text">{{ exitIp ?? '—' }}</span>
<span v-if="exitIp" class="text-z-xs text-z-text-secondary">{{ exitIp.includes(':') ? 'IPv6' : 'IPv4' }}</span>
</dd>
</div>
<div class="grid gap-0.5">
<dt class="text-z-xs text-z-text-secondary">
{{ t('proxies.fields.latency') }}
</dt>
<dd class="m-0 font-medium whitespace-nowrap text-z-text tabular-nums">
{{ row?.result ? `${row.result.latencyMs} ms` : '—' }}
</dd>
</div>
<div v-if="location" class="grid min-w-0 gap-0.5">
<dt class="text-z-xs text-z-text-secondary">
{{ t('proxies.targets.detectedRegion') }}
</dt>
<dd class="m-0 font-medium wrap-anywhere text-z-text">
{{ countryName(location.country) }} · {{ location.city }}
</dd>
</div>
</dl>
<p v-if="failure" class="mt-2 mb-0 text-z-sm wrap-anywhere text-z-error-text">
{{ failure }}
</p>
</li>
</template>
@@ -5,7 +5,7 @@ import type { ProxyTestExecutor } from '../../composables/useProxyBatchTest'
import type { OutboundProxyRecord, OutboundProxyTest, RequestLocation } from '@/api'
import { ZButton, ZCheckbox, ZDialog, ZForm, ZFormItem, ZInput, ZSegmented, ZSwitch } from '@codex-proxy/ui'
import { Save, Square, Wifi } from '@lucide/vue'
import { computed, shallowRef, useTemplateRef, watch } from 'vue'
import { computed, shallowRef, useTemplateRef } from 'vue'
import { useI18n } from 'vue-i18n'
import RequestLocationDetectButton from '@/components/RequestLocationDetectButton.vue'
import RequestLocationFields from '@/components/RequestLocationFields.vue'
@@ -27,7 +27,7 @@ const emit = defineEmits<{
save: []
test: []
detectLocation: []
afterLeave: []
closed: []
}>()
const { t } = useI18n({ useScope: 'global' })
@@ -132,23 +132,21 @@ async function requestProbe(detect = false) {
emit('test')
}
watch(open, (value) => {
function initializeForm() {
mode.value = 'single'
testAfterCreate.value = true
batch.clear()
formRef.value?.clearValidate()
if (value) {
mode.value = 'single'
testAfterCreate.value = true
batch.clear()
}
})
}
function clearForm() {
batch.clear()
emit('afterLeave')
emit('closed')
}
</script>
<template>
<ZDialog v-model="open" :title="title" :description="proxy ? undefined : t('proxies.editor.createDescription')" width="42rem" :show-close="!busy" :close-on-click-modal="!busy" :close-on-press-escape="!busy" @closed="clearForm">
<ZDialog v-model="open" destroy-on-close :title="title" :description="proxy ? undefined : t('proxies.editor.createDescription')" width="42rem" :show-close="!busy" :close-on-click-modal="!busy" :close-on-press-escape="!busy" @open="initializeForm" @closed="clearForm">
<ZSegmented v-if="!proxy" v-model="mode" :options="modeOptions" :disabled="busy" :aria-label="t('proxies.editor.methodLabel')" class="mb-5 w-full" />
<ZForm v-if="single" ref="formElement" :model="form" :rules="rules" scroll-to-error focus-on-error novalidate @submit="requestSave">
<ZFormItem prop="name" :show-message="false" :label="t('proxies.editor.nameLabel')" required>
@@ -0,0 +1,61 @@
import type { OutboundProxyRecord, TargetProbeResult } from '@/api'
import { computed, ref } from 'vue'
import { testProxyTarget } from '@/api'
import { ApiError } from '@/api/request'
import { useRequestState } from '@/composables/useRequestState'
import { errorMessage } from '@/utils/operation'
export type TargetTestProxy = Pick<OutboundProxyRecord, 'id' | 'name'> & Partial<Pick<OutboundProxyRecord, 'endpoint' | 'detectedLocation' | 'lastTest'>>
export type ProxyTargetTestRow = Pick<TargetTestProxy, 'id' | 'name'> & { result: TargetProbeResult | null, error: string, running: boolean }
export function useProxyTargetTest(onStale: () => void) {
const request = useRequestState()
const rows = ref<ProxyTargetTestRow[]>([])
async function start(proxies: TargetTestProxy[], targetName: string, revision: number) {
rows.value = proxies.map(({ id, name }) => ({
id,
name,
result: null,
error: '',
running: false,
}))
const run = request.start()
let stop = false
for (let offset = 0; offset < rows.value.length && !stop && request.isCurrent(run); offset += 2) {
await Promise.all(rows.value.slice(offset, offset + 2).map(async (row) => {
row.running = true
try {
const data = await testProxyTarget({ proxyId: row.id, targetName, revision }, { silent: true, signal: request.signal })
if (request.isCurrent(run)) {
row.name = data.proxyName
row.result = data.result
}
}
catch (cause) {
if (!request.isCurrent(run))
return
row.error = errorMessage(cause)
if (cause instanceof ApiError && ([401, 403, 409, 429].includes(cause.status) || cause.status >= 500 || cause.kind === 'network' || cause.kind === 'timeout')) {
stop = true
if (cause.status === 409)
onStale()
}
}
finally {
if (request.isCurrent(run))
row.running = false
}
}))
}
request.finish(run)
}
return {
byProxyId: computed(() => new Map(rows.value.map(row => [row.id, row]))),
clearResults: () => { rows.value = [] },
running: request.loading,
start,
cancel: request.invalidate,
}
}
+15 -2
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import type { TargetTestProxy } from './composables/useProxyTargetTest'
import type { OutboundProxyRecord } from '@/api'
import { ZButton, ZCard, ZCheckbox, ZConfirmDialog, ZInput, ZPageHeader, ZPagination, ZTable, ZTag } from '@codex-proxy/ui'
@@ -10,6 +11,7 @@ import ProxyAccountsModal from './components/proxy-accounts-modal/index.vue'
import ProxyFormModal from './components/proxy-form-modal/index.vue'
import ProxyActions from './components/ProxyActions.vue'
import ProxyRegion from './components/ProxyRegion.vue'
import ProxyTargetDialog from './components/ProxyTargetDialog.vue'
import { useProxies } from './composables/useProxies'
import { useProxyBatchTesting } from './composables/useProxyBatchTesting'
import { proxyColumns } from './constants'
@@ -60,6 +62,16 @@ const { busy: batchTesting, start: testSelectedProxies } = useProxyBatchTesting(
reload: () => loadProxies({ silent: true }),
})
const targetTest = shallowRef<{ proxy: OutboundProxyRecord, selectedProxies: TargetTestProxy[] }>()
function openTargetTest(proxy: OutboundProxyRecord) {
const byId = new Map(proxies.value.map(row => [row.id, row]))
const selectedProxies = selectedIds.value.has(proxy.id) && selectedIds.value.size > 1
? selectedRowKeys.value.map(id => byId.get(id) ?? { id, name: id })
: []
targetTest.value = { proxy, selectedProxies }
}
watch(search, () => {
selectedIds.value = new Set()
})
@@ -155,7 +167,7 @@ watch(search, () => {
{{ row.lastTestAtDisplay ?? '-' }}
</template>
<template #actions="{ row }">
<ProxyActions :proxy="row" :testing="testingIds.has(row.id)" :batch-testing="batchTesting" :updating="updatingIds.has(row.id)" @test="checkProxy" @edit="openForm" @toggle="toggleEnabled" @delete="requestDelete" />
<ProxyActions :proxy="row" :testing="testingIds.has(row.id)" :batch-testing="batchTesting" :updating="updatingIds.has(row.id)" @test-target="openTargetTest(row)" @test="checkProxy" @edit="openForm" @toggle="toggleEnabled" @delete="requestDelete" />
</template>
</ZTable>
<ZPagination v-bind="pagination" :disabled="loading" @current-change="setPage" @size-change="setPageSize" />
@@ -163,6 +175,7 @@ watch(search, () => {
</template>
</ZCard>
<ProxyTargetDialog v-if="targetTest" v-bind="targetTest" @closed="targetTest = undefined" />
<ProxyFormModal
v-model="showForm"
v-model:name="form.name"
@@ -180,7 +193,7 @@ watch(search, () => {
@save="save"
@test="testConnection"
@detect-location="detectLocation"
@after-leave="clearCredentials"
@closed="clearCredentials"
/>
<ZConfirmDialog v-model="showDisable" :title="t('proxies.actions.disableProxy')" :confirm-text="t('proxies.actions.disableProxy')" :loading="disabling" @confirm="confirmDisable">
<p class="m-0">
+1 -1
View File
@@ -3,7 +3,7 @@ import { numberLocale } from '@/utils/format'
const flags = import.meta.glob<string>('/node_modules/circle-flags/flags/??.svg', { eager: true, import: 'default', query: '?url&no-inline' })
export function proxyExitLocation(proxy: OutboundProxyRecord) {
export function proxyExitLocation(proxy: Partial<Pick<OutboundProxyRecord, 'detectedLocation' | 'lastTest'>>) {
const detected = proxy.detectedLocation
const test = proxy.lastTest
if (!detected || !test?.success || test.location.status === 'failed' || test.location.status === 'conflict')
@@ -43,7 +43,7 @@ async function confirm() {
</script>
<template>
<ZDialog v-model="open" :title="t('settings.rotation.quotaResetPrioritySettings')" :description="t('settings.resetPriority.description')" width="36rem">
<ZDialog v-model="open" destroy-on-close :title="t('settings.rotation.quotaResetPrioritySettings')" :description="t('settings.resetPriority.description')" width="36rem">
<ZForm :id="formId" ref="formElement" class="gap-5" :model="{ resetWindowWeights: draft }" novalidate @submit="confirm">
<ResetWindowWeightsFields v-model="draft" :submitted="submitted" :help="t('settings.resetPriority.windowHelp')" />
</ZForm>
@@ -125,7 +125,7 @@ async function confirm() {
</script>
<template>
<ZDialog v-model="open" :title="t('settings.rotation.smartSchedulingSettings')" :description="t('settings.scheduling.description')" width="36rem">
<ZDialog v-model="open" destroy-on-close :title="t('settings.rotation.smartSchedulingSettings')" :description="t('settings.scheduling.description')" width="36rem">
<ZForm :id="formId" ref="formElement" class="gap-5" :model="{ ...draft, resetWindowWeights: windows }" novalidate @submit="confirm">
<section v-for="group in groups" :key="group.id" class="grid gap-3">
<h3 class="m-0 text-z font-emphasis">
@@ -19,13 +19,12 @@ const { loading, result } = preview
const output = computed(() => result.value
? JSON.stringify({ body: result.value.body, headers: result.value.headers, turnMetadata: result.value.turnMetadata }, null, 2)
: '')
watch(open, (value) => {
preview.invalidate()
function resetPreview(value: string) {
sample.value = value
? JSON.stringify(exampleRequest(), null, 2)
: ''
localError.value = ''
})
preview.invalidate()
}
watch([
sample,
() => props.policy,
@@ -41,7 +40,15 @@ async function test() {
</script>
<template>
<ZDialog v-model="open" :title="t('settings.privacy.preview.testRules')" :description="t('settings.privacy.preview.description')" width="48rem">
<ZDialog
v-model="open"
:title="t('settings.privacy.preview.testRules')"
:description="t('settings.privacy.preview.description')"
width="48rem"
@open="resetPreview(JSON.stringify(exampleRequest(), null, 2))"
@close="preview.cancel"
@closed="resetPreview('')"
>
<div class="grid gap-3">
<div class="grid min-w-0 gap-3 sm:grid-cols-2">
<ZFormItem :label="t('settings.privacy.preview.requestSample')">
@@ -40,19 +40,19 @@ const processed = computed(() => result.value
: '')
const outcome = computed(() => result.value?.outcomes[0])
watch(open, (value) => {
preview.invalidate()
function initializeEditor() {
selectedIndex.value = 0
draft.value = cloneDeep(props.rule ?? newRule())
fixedValues.value = draft.value.steps.map(step => JSON.stringify(step.value))
sample.value = JSON.stringify(exampleRequest(), null, 2)
}
function clearPreview() {
sample.value = ''
localError.value = ''
if (value) {
selectedIndex.value = 0
draft.value = cloneDeep(props.rule ?? newRule())
fixedValues.value = draft.value.steps.map(step => JSON.stringify(step.value))
sample.value = JSON.stringify(exampleRequest(), null, 2)
}
else {
sample.value = ''
}
})
preview.invalidate()
}
watch([draft, sample, fixedValues], () => {
preview.invalidate()
localError.value = ''
@@ -141,7 +141,15 @@ async function apply() {
</script>
<template>
<ZDialog v-model="open" :title="isNew ? t('settings.privacy.addRule') : t('settings.privacy.rules.editRule')" :description="t('settings.privacy.rules.description')" width="64rem">
<ZDialog
v-model="open"
:title="isNew ? t('settings.privacy.addRule') : t('settings.privacy.rules.editRule')"
:description="t('settings.privacy.rules.description')"
width="64rem"
@open="initializeEditor"
@close="preview.cancel"
@closed="clearPreview"
>
<div class="grid gap-4">
<ZFormItem :label="t('settings.privacy.rules.ruleName')" required>
<ZInput v-model="draft.name" :placeholder="t('settings.privacy.rules.namePlaceholder')" :aria-label="t('settings.privacy.rules.ruleName')" maxlength="64" />
@@ -27,6 +27,7 @@ export function usePrivacyPreview() {
loading: state.loading,
result,
run,
cancel: () => state.invalidate({ resetLoading: false }),
invalidate,
}
}
@@ -88,7 +88,7 @@ async function submit() {
</script>
<template>
<ZDialog v-model="open" :title="t('settings.password.changeAdministratorPassword')" :description="t('settings.password.changeDescription')" width="28rem" :show-close="!loading" :close-on-click-modal="!loading" :close-on-press-escape="!loading" @closed="clearForm">
<ZDialog v-model="open" destroy-on-close :title="t('settings.password.changeAdministratorPassword')" :description="t('settings.password.changeDescription')" width="28rem" :show-close="!loading" :close-on-click-modal="!loading" :close-on-press-escape="!loading" @closed="clearForm">
<ZForm :id="formId" ref="formElement" class="gap-5" :model="form" :rules="rules" :validate-on-rule-change="false" focus-on-error novalidate @submit="submit">
<ZFormItem prop="currentPassword" :label="t('settings.password.currentPassword')">
<ZInput v-model="form.currentPassword" :validate-event="submitted" type="password" autocomplete="current-password" :placeholder="t('settings.password.enterCurrentPassword')" :disabled="loading" maxlength="4096" @input="revalidateDependentField('newPassword')" />
@@ -1,11 +1,12 @@
import type { Ref } from 'vue'
import { useConfirmDialog, useEventListener } from '@vueuse/core'
import { onScopeDispose, shallowRef, watch } from 'vue'
import { onScopeDispose, shallowRef } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
export function useSettingsLeaveGuard(hasChanges: Readonly<Ref<boolean>>) {
const showLeaveConfirm = shallowRef(false)
const { reveal, confirm: confirmLeave, cancel: cancelLeave } = useConfirmDialog(showLeaveConfirm)
const { reveal, confirm, cancel } = useConfirmDialog(showLeaveConfirm)
let discardChanges = false
let pending: Promise<boolean> | undefined
onBeforeRouteLeave((to) => {
@@ -17,16 +18,25 @@ export function useSettingsLeaveGuard(hasChanges: Readonly<Ref<boolean>>) {
return pending
})
// 关闭按钮、遮罩与 Esc 都按继续编辑处理,不能留下未完成的路由导航
watch(showLeaveConfirm, (open) => {
if (!open)
cancelLeave()
})
function confirmLeave() {
discardChanges = true
showLeaveConfirm.value = false
}
// 等退场完成再决定导航,避免路由切换提前卸载确认框。
function finishLeave() {
if (discardChanges)
confirm()
else
cancel()
discardChanges = false
}
useEventListener(() => hasChanges.value ? window : undefined, 'beforeunload', (event: BeforeUnloadEvent) => {
event.preventDefault()
event.returnValue = ''
})
onScopeDispose(cancelLeave)
onScopeDispose(cancel)
return { showLeaveConfirm, confirmLeave }
return { showLeaveConfirm, confirmLeave, finishLeave }
}
+3 -2
View File
@@ -161,7 +161,7 @@ function resetForm() {
}
const backupSection = useTemplateRef<InstanceType<typeof SettingsBackupSection>>('backupSection')
const hasUnsavedChanges = computed(() => hasChanges.value || !!backupSection.value?.hasChanges)
const { showLeaveConfirm, confirmLeave } = useSettingsLeaveGuard(hasUnsavedChanges)
const { showLeaveConfirm, confirmLeave, finishLeave } = useSettingsLeaveGuard(hasUnsavedChanges)
watch(section, (value) => {
visited.add(value)
@@ -342,7 +342,8 @@ watch(() => !loading.value && route.hash === '#reset-credits', async (ready) =>
:description="t('settings.page.unsavedChanges.description')"
:confirm-text="t('settings.page.unsavedChanges.leave')"
:cancel-text="t('settings.page.unsavedChanges.stay')"
@confirm="confirmLeave()"
@confirm="confirmLeave"
@closed="finishLeave"
/>
</div>
</template>
@@ -17,7 +17,7 @@ import UsageStatusCodeBadge from './UsageStatusCodeBadge.vue'
const props = defineProps<{ record: UsageRecordDetail | null, loading?: boolean, error?: string }>()
const emit = defineEmits<{ retry: [] }>()
const emit = defineEmits<{ retry: [], close: [] }>()
const { t } = useI18n({ useScope: 'global' })
@@ -177,7 +177,7 @@ const attempts = computed(() => (props.record?.attempts ?? []).map(attempt => ({
</script>
<template>
<ZDialog v-model="open" :title="t('usage.error.errorDetails')" :description="t('usage.error.description')" type="danger" width="64rem">
<ZDialog v-model="open" destroy-on-close :title="t('usage.error.errorDetails')" :description="t('usage.error.description')" type="danger" width="64rem" @close="emit('close')">
<UsageDetailState v-if="loading || error" variant="error" :loading="!!loading" :error="error" @retry="emit('retry')" />
<div v-else-if="record" class="grid min-w-0 gap-3">
<UsageErrorDiagnosis :record="record" />
@@ -35,7 +35,7 @@ const props = defineProps<{
error?: string
}>()
const emit = defineEmits<{ retry: [] }>()
const emit = defineEmits<{ retry: [], close: [] }>()
const { t } = useI18n({ useScope: 'global' })
@@ -562,10 +562,12 @@ const tokenDonutOption = computed<EChartsOption>(() => {
<template>
<ZDialog
v-model="open"
destroy-on-close
:title="t('usage.request.usageRecordDetails')"
:description="t('usage.request.description')"
type="info"
width="64rem"
@close="emit('close')"
>
<UsageDetailState v-if="loading || error" :loading="!!loading" :error="error" @retry="emit('retry')" />
<div v-else-if="record" class="grid min-w-0 gap-3">
@@ -1,5 +1,5 @@
import type { UsageListRecord, UsageRecordDetail } from '@/api'
import { computed, shallowRef, watch } from 'vue'
import { computed, shallowRef } from 'vue'
import { getUsageRecordDetail } from '@/api'
import { useRequestState } from '@/composables/useRequestState'
import { isErrorUsageRecord } from '../utils/detail'
@@ -35,11 +35,6 @@ export function useUsageRecordDetail() {
void loadDetail()
}
watch(showDetailModal, (open) => {
if (!open)
request.invalidate({ resetLoading: false })
}, { flush: 'sync' })
return {
showDetailModal,
selectedUsageRecord,
@@ -48,5 +43,6 @@ export function useUsageRecordDetail() {
detailError: request.error,
handleViewDetail,
reloadDetail: loadDetail,
cancelDetail: () => request.invalidate({ resetLoading: false }),
}
}
+2 -2
View File
@@ -76,7 +76,7 @@ const {
errorOrigin,
})
const { showDetailModal, selectedUsageRecord, detailIsError, detailLoading, detailError, handleViewDetail, reloadDetail } = useUsageRecordDetail()
const { showDetailModal, selectedUsageRecord, detailIsError, detailLoading, detailError, handleViewDetail, reloadDetail, cancelDetail } = useUsageRecordDetail()
const detailComponent = computed(() => detailIsError.value
? UsageErrorDetailModal
: UsageRecordDetailModal)
@@ -198,6 +198,6 @@ watch(timeRange, () => {
</template>
</ZCard>
<component :is="detailComponent" v-model="showDetailModal" :record="selectedUsageRecord" :loading="detailLoading" :error="detailError" @retry="reloadDetail" />
<component :is="detailComponent" v-model="showDetailModal" :record="selectedUsageRecord" :loading="detailLoading" :error="detailError" @retry="reloadDetail" @close="cancelDetail" />
</div>
</template>