mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-23 16:00:40 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c99bf1ac35 | ||
|
|
e41fdfc1c5 | ||
|
|
5fced665bf | ||
|
|
7ff77413c8 | ||
|
|
1ee67cd6b2 | ||
|
|
baf9992f99 | ||
|
|
5f7e50a031 | ||
|
|
939ae78c8c | ||
|
|
3039709f36 | ||
|
|
6900da36ee | ||
|
|
e9a5ee7e3b | ||
|
|
58cbb60750 | ||
|
|
b85f944c52 | ||
|
|
d1be306f03 | ||
|
|
aa34d5291d | ||
|
|
56d3078ee8 | ||
|
|
8b69fa4882 | ||
|
|
d05d38718e | ||
|
|
a1954c4746 | ||
|
|
636a3d2a26 | ||
|
|
e9627168a7 | ||
|
|
5a4f49036b | ||
|
|
8041ddab65 | ||
|
|
e645d6d4c9 | ||
|
|
5079700190 | ||
|
|
4db65d8e12 | ||
|
|
da866de2c7 |
@@ -35,7 +35,7 @@ jobs:
|
||||
CPR_TEST_REDIS_URL: redis://127.0.0.1:6379
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:18-bookworm@sha256:bbf83594798e144bff365a9c191c5d779f181fb3135902064ab8ff11918020fc
|
||||
image: postgres:18-bookworm@sha256:194e55feb2597b1465dbee81cc9fd8d204566cd2eb42c8d22fd6c931a38781b1
|
||||
env:
|
||||
POSTGRES_DB: codex_proxy
|
||||
POSTGRES_USER: codex_proxy
|
||||
@@ -49,7 +49,7 @@ jobs:
|
||||
--health-timeout 5s
|
||||
--health-retries 10
|
||||
redis:
|
||||
image: redis:8-alpine@sha256:0bf6577d7774e592b29d093e3ac9390eb91e13d72c21e506afce736de5e0eeb0
|
||||
image: redis:8-alpine@sha256:7958cfbb9d152f87dadfbc89f1b0b15938f0b81ff8982feb327476f4911935c3
|
||||
ports:
|
||||
- 6379:6379
|
||||
options: >-
|
||||
@@ -125,7 +125,7 @@ jobs:
|
||||
run: cargo clippy --all-targets --all-features --locked -- -D warnings
|
||||
|
||||
- name: Setup nextest
|
||||
uses: taiki-e/install-action@cfdb7ed4ccc7c7dce37759eae89dc5674b469b39 # v2.90.3
|
||||
uses: taiki-e/install-action@75a7c0f87bd666af3cdb75c5b9e9d03ab6044e6f # v2.90.6
|
||||
with:
|
||||
tool: cargo-nextest@0.9.143
|
||||
fallback: none
|
||||
|
||||
@@ -115,7 +115,7 @@ jobs:
|
||||
cache-bin: false
|
||||
save-if: ${{ github.event_name != 'pull_request' }}
|
||||
- name: Setup nextest
|
||||
uses: taiki-e/install-action@cfdb7ed4ccc7c7dce37759eae89dc5674b469b39 # v2.90.3
|
||||
uses: taiki-e/install-action@75a7c0f87bd666af3cdb75c5b9e9d03ab6044e6f # v2.90.6
|
||||
with:
|
||||
tool: cargo-nextest@0.9.143
|
||||
fallback: none
|
||||
|
||||
@@ -34,7 +34,7 @@ jobs:
|
||||
ref: ${{ inputs.ref || github.event.pull_request.head.sha || github.sha }}
|
||||
|
||||
- name: Install cargo-audit
|
||||
uses: taiki-e/install-action@cfdb7ed4ccc7c7dce37759eae89dc5674b469b39 # v2.90.3
|
||||
uses: taiki-e/install-action@75a7c0f87bd666af3cdb75c5b9e9d03ab6044e6f # v2.90.6
|
||||
with:
|
||||
tool: cargo-audit@0.22.2
|
||||
fallback: none
|
||||
|
||||
Generated
+44
-54
@@ -292,9 +292,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "aws-sdk-s3"
|
||||
version = "1.159.0"
|
||||
version = "1.161.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8d5c431c5db2f1f6f536c2a19425575e28273859c6ab399d9ac957f73678c7db"
|
||||
checksum = "d9c63e3ca6e56670513469e992759f4a51041603fde329471b29c5c1f5eaeefe"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"aws-credential-types",
|
||||
@@ -328,9 +328,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "aws-sigv4"
|
||||
version = "1.6.5"
|
||||
version = "1.6.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "57a4393e6addc3380632887b0998d06ad5f099ab5c478be0a3eeedecf8604161"
|
||||
checksum = "6c5aa04c533733a77879294f1854c27b3715cc50ea71756d1f6a958702b1a9fb"
|
||||
dependencies = [
|
||||
"aws-credential-types",
|
||||
"aws-smithy-eventstream",
|
||||
@@ -414,9 +414,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "aws-smithy-http-client"
|
||||
version = "1.5.2"
|
||||
version = "1.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "859a81364f8185349c584fb41cd8765a400cf982f447adada590cf008a9f3b85"
|
||||
checksum = "203e36a754ced29dab0d710dab8c4fecf181d78f229e90fa6e75c6406ecb55a3"
|
||||
dependencies = [
|
||||
"aws-smithy-async",
|
||||
"aws-smithy-runtime-api",
|
||||
@@ -460,9 +460,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "aws-smithy-runtime"
|
||||
version = "1.16.3"
|
||||
version = "1.16.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5bc688673e282f42d3152dcd9cacc1a9a75734d7cd39d02e58989276fc750f3c"
|
||||
checksum = "7ed38b842f93dd8220cc8816750c72ce914b22c6eb3df02beb9632333ccb366d"
|
||||
dependencies = [
|
||||
"aws-smithy-async",
|
||||
"aws-smithy-http",
|
||||
@@ -483,9 +483,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "aws-smithy-runtime-api"
|
||||
version = "1.21.0"
|
||||
version = "1.22.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0467a2414e84b1b01e37452896fb3562b93926e81c619eba6ecf27ce9e682a0e"
|
||||
checksum = "c0b79dbb5331ccd297686df811d50ab3f39db171f5c765372a69272a0990b014"
|
||||
dependencies = [
|
||||
"aws-smithy-async",
|
||||
"aws-smithy-runtime-api-macros",
|
||||
@@ -766,9 +766,9 @@ checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
|
||||
|
||||
[[package]]
|
||||
name = "bytes"
|
||||
version = "1.12.1"
|
||||
version = "1.12.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
|
||||
checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c"
|
||||
|
||||
[[package]]
|
||||
name = "bytes-utils"
|
||||
@@ -842,9 +842,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "clap"
|
||||
version = "4.6.7"
|
||||
version = "4.6.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"
|
||||
checksum = "ac230478587d0269d8d6998b82ae69ea51509d55df66d9e92edd1f986904cd4a"
|
||||
dependencies = [
|
||||
"clap_builder",
|
||||
"clap_derive",
|
||||
@@ -864,9 +864,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "clap_derive"
|
||||
version = "4.6.7"
|
||||
version = "4.6.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0"
|
||||
checksum = "895c9d8d2ac2dd8b8a29f3724a14e72aaaa6debcf8c38c82f97305c6a172767a"
|
||||
dependencies = [
|
||||
"heck",
|
||||
"proc-macro2",
|
||||
@@ -1362,7 +1362,7 @@ dependencies = [
|
||||
"digest 0.11.3",
|
||||
"elliptic-curve",
|
||||
"rfc6979",
|
||||
"signature 3.0.0",
|
||||
"signature",
|
||||
"spki",
|
||||
"zeroize",
|
||||
]
|
||||
@@ -1516,9 +1516,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "filetime"
|
||||
version = "0.2.29"
|
||||
version = "0.2.30"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"
|
||||
checksum = "e1255e7a9f1902190d4c10a75f2f7f495d3d3ce13e9ba26e6c48683a0f4dbed7"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
@@ -1592,9 +1592,9 @@ checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"
|
||||
|
||||
[[package]]
|
||||
name = "form_urlencoded"
|
||||
version = "1.2.2"
|
||||
version = "1.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
|
||||
checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e"
|
||||
dependencies = [
|
||||
"percent-encoding",
|
||||
]
|
||||
@@ -1849,7 +1849,6 @@ dependencies = [
|
||||
"bytes",
|
||||
"chrono",
|
||||
"config",
|
||||
"filetime",
|
||||
"flate2",
|
||||
"futures",
|
||||
"gateway-admin",
|
||||
@@ -2601,17 +2600,17 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "jsonwebtoken"
|
||||
version = "11.1.0"
|
||||
version = "12.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e75fe14a82d81e5f5af639997db37d8b96045938a7ac6ab18cdbe1c7467e05e1"
|
||||
checksum = "f347a975eb5fa8f5c4eadce6c1152c11c326cf32cf839fb64ff12d5cb8f4ce8b"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"base64 0.22.1",
|
||||
"getrandom 0.2.17",
|
||||
"base64 0.23.1",
|
||||
"getrandom 0.4.3",
|
||||
"js-sys",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"signature 2.2.0",
|
||||
"signature",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
@@ -3370,9 +3369,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.106"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
@@ -3652,9 +3651,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "redis"
|
||||
version = "1.8.1"
|
||||
version = "1.8.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "db7f3d75b5a3301746bff39a767bf4c5c42506b08513527308b3875bfb64a031"
|
||||
checksum = "4bef8fa589dd53a8a379a7856de1365d0a1be50c6b8aebb5c01c1ec441a2c509"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"arcstr",
|
||||
@@ -3725,9 +3724,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "regex"
|
||||
version = "1.13.1"
|
||||
version = "1.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
|
||||
checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
@@ -3737,9 +3736,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "regex-automata"
|
||||
version = "0.4.18"
|
||||
version = "0.4.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
|
||||
checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
@@ -3754,9 +3753,9 @@ checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973"
|
||||
|
||||
[[package]]
|
||||
name = "regex-syntax"
|
||||
version = "0.8.11"
|
||||
version = "0.8.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
|
||||
checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
|
||||
|
||||
[[package]]
|
||||
name = "reqwest"
|
||||
@@ -4207,15 +4206,6 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "signature"
|
||||
version = "2.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
|
||||
dependencies = [
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "signature"
|
||||
version = "3.0.0"
|
||||
@@ -5110,9 +5100,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
|
||||
|
||||
[[package]]
|
||||
name = "url"
|
||||
version = "2.5.8"
|
||||
version = "2.5.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
|
||||
checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a"
|
||||
dependencies = [
|
||||
"form_urlencoded",
|
||||
"idna",
|
||||
@@ -5140,9 +5130,9 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
|
||||
|
||||
[[package]]
|
||||
name = "uuid"
|
||||
version = "1.29.2"
|
||||
version = "1.29.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bed99139f7dac9b5cfe5f17be4d66dc7079a34dee1d74bcc77217119240e267c"
|
||||
checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64"
|
||||
dependencies = [
|
||||
"getrandom 0.4.3",
|
||||
"js-sys",
|
||||
@@ -5692,9 +5682,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "zeroize"
|
||||
version = "1.9.1"
|
||||
version = "1.9.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
|
||||
checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa"
|
||||
dependencies = [
|
||||
"zeroize_derive",
|
||||
]
|
||||
@@ -5745,9 +5735,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "zip"
|
||||
version = "9.5.1"
|
||||
version = "9.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e3476fd497ac8af5b1ec7b51acab7bef380f7e8dd8e0487595bafd839417a302"
|
||||
checksum = "721c8158b9503b2660291ad3056a20f722deaeed21bb908a9a363d7e17b34f0e"
|
||||
dependencies = [
|
||||
"constant_time_eq",
|
||||
"crc32fast",
|
||||
|
||||
@@ -8,6 +8,7 @@ use super::provider_credentials::ProviderDocument;
|
||||
pub const MAX_FORECAST_HISTORY_POINTS: usize = 128;
|
||||
const MIN_BLOCK_PERCENT: f64 = 5.0;
|
||||
const RECENT_BLOCKS: usize = 3;
|
||||
const MAX_PERCENT_REVERSAL: f64 = 1.0;
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct QuotaForecastUsage {
|
||||
@@ -80,11 +81,55 @@ pub struct QuotaForecastObservation {
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct QuotaForecastPoint {
|
||||
pub started_at: DateTime<Utc>,
|
||||
pub observed_at: DateTime<Utc>,
|
||||
pub reset_at: DateTime<Utc>,
|
||||
pub used_percent: f64,
|
||||
pub usage: QuotaForecastUsage,
|
||||
}
|
||||
|
||||
impl QuotaForecastPoint {
|
||||
fn follows(&self, previous: &Self) -> bool {
|
||||
previous.observed_at <= self.started_at && previous.observed_at < self.observed_at
|
||||
}
|
||||
}
|
||||
|
||||
/// 当前窗口内仍有旧周期记录时,只在旧读数已到期、用量回落且新读数得到印证后重设累计
|
||||
fn cycle_boundary(
|
||||
history: &[QuotaForecastPoint],
|
||||
current: &QuotaForecastPoint,
|
||||
) -> (Option<usize>, bool) {
|
||||
let mut boundary = None;
|
||||
let mut awaiting_confirmation = false;
|
||||
for (index, pair) in history.windows(2).enumerate() {
|
||||
let (older, previous) = (&pair[0], &pair[1]);
|
||||
let first_index = index + 2;
|
||||
let first = history.get(first_index).unwrap_or(current);
|
||||
let before_reset = older.used_percent.min(previous.used_percent);
|
||||
if !previous.follows(older)
|
||||
|| !first.follows(previous)
|
||||
|| older.reset_at <= previous.observed_at
|
||||
|| older.reset_at > first.started_at
|
||||
|| previous.reset_at > first.started_at
|
||||
|| before_reset - first.used_percent <= MAX_PERCENT_REVERSAL
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// 快照可能复用请求读数;只有另一条在新窗口内独立完成的请求能确认换段
|
||||
let confirmation = history
|
||||
.get(first_index + 1..)
|
||||
.and_then(|later| later.iter().find(|next| next.follows(first)));
|
||||
awaiting_confirmation = confirmation.is_none();
|
||||
if confirmation.is_some_and(|next| {
|
||||
next.observed_at < first.reset_at
|
||||
&& before_reset - next.used_percent > MAX_PERCENT_REVERSAL
|
||||
}) {
|
||||
boundary = Some(first_index);
|
||||
}
|
||||
}
|
||||
(boundary, awaiting_confirmation)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum QuotaForecastMethod {
|
||||
Cumulative,
|
||||
@@ -117,7 +162,7 @@ pub fn select_forecast_sample(
|
||||
current: QuotaForecastPoint,
|
||||
mut history: Vec<QuotaForecastPoint>,
|
||||
pending_request_count: u64,
|
||||
interrupted: bool,
|
||||
plan_changed: bool,
|
||||
) -> QuotaForecastSample {
|
||||
history.retain(|point| {
|
||||
start_at <= point.observed_at
|
||||
@@ -126,6 +171,9 @@ pub fn select_forecast_sample(
|
||||
&& (0.0..=100.0).contains(&point.used_percent)
|
||||
});
|
||||
history.sort_by_key(|point| point.observed_at);
|
||||
let (boundary, awaiting_confirmation) = cycle_boundary(&history, ¤t);
|
||||
let history = &history[boundary.unwrap_or(0)..];
|
||||
let interrupted = plan_changed || boundary.is_some();
|
||||
let mut sample = QuotaForecastSample {
|
||||
key,
|
||||
method: QuotaForecastMethod::Cumulative,
|
||||
@@ -136,23 +184,35 @@ pub fn select_forecast_sample(
|
||||
block_count: 0,
|
||||
observation_count: history.len(),
|
||||
pending_request_count,
|
||||
discontinuous: interrupted,
|
||||
discontinuous: interrupted || awaiting_confirmation,
|
||||
cycle_usage: current.usage.clone(),
|
||||
usage: current.usage.clone(),
|
||||
};
|
||||
history.push(current);
|
||||
// 重置边界不在查询起点时,从首个新观测重新计数,避免把旧周期累计带入总量
|
||||
let cycle_baseline = interrupted.then(|| &history[0]);
|
||||
if interrupted {
|
||||
let baseline = history.first().unwrap_or(¤t);
|
||||
let Some(usage) = current.usage.difference(&baseline.usage) else {
|
||||
return sample;
|
||||
};
|
||||
sample.cycle_usage = usage;
|
||||
}
|
||||
if awaiting_confirmation {
|
||||
return sample;
|
||||
}
|
||||
let mut anchors: Vec<&QuotaForecastPoint> = Vec::new();
|
||||
let mut high_water: Option<&QuotaForecastPoint> = None;
|
||||
for point in &history {
|
||||
for point in history.iter().chain(std::iter::once(¤t)) {
|
||||
// 截至快照已过期的读数不能用于预测剩余量,窗口累计仍由上面的周期证据决定
|
||||
if point.reset_at <= current.observed_at {
|
||||
sample.discontinuous = true;
|
||||
continue;
|
||||
}
|
||||
if let Some(previous) = high_water {
|
||||
if point.observed_at <= previous.observed_at {
|
||||
continue;
|
||||
}
|
||||
if point.used_percent < previous.used_percent {
|
||||
// 一个百分点内的回落可能是量化/并发乱序;更大的回落不能跨越
|
||||
if previous.used_percent - point.used_percent <= 1.0 {
|
||||
if previous.used_percent - point.used_percent <= MAX_PERCENT_REVERSAL {
|
||||
continue;
|
||||
}
|
||||
// 同窗口回落不能证明周期重置,只重建采样并保留已记录累计
|
||||
@@ -168,16 +228,6 @@ pub fn select_forecast_sample(
|
||||
anchors.push(point);
|
||||
}
|
||||
}
|
||||
let Some(current) = history.last() else {
|
||||
return sample;
|
||||
};
|
||||
if let Some(baseline) = cycle_baseline {
|
||||
let Some(usage) = current.usage.difference(&baseline.usage) else {
|
||||
sample.discontinuous = true;
|
||||
return sample;
|
||||
};
|
||||
sample.cycle_usage = usage;
|
||||
}
|
||||
if anchors.len() < 2 {
|
||||
return sample;
|
||||
}
|
||||
|
||||
@@ -1057,6 +1057,8 @@ impl AccountsService for DefaultAccountsService {
|
||||
) else {
|
||||
continue;
|
||||
};
|
||||
let reset_at = query.range.end;
|
||||
let window_duration = reset_at - query.range.start;
|
||||
query.range.start = query.range.start.max(stored.account.created_at);
|
||||
if query.range.start >= observed
|
||||
|| observed > now
|
||||
@@ -1066,7 +1068,6 @@ impl AccountsService for DefaultAccountsService {
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let reset_at = query.range.end;
|
||||
query.range.end = observed;
|
||||
let history = self
|
||||
.accounts
|
||||
@@ -1074,27 +1075,37 @@ impl AccountsService for DefaultAccountsService {
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "forecast paired usage"))?;
|
||||
let mut points = Vec::new();
|
||||
let mut interrupted = false;
|
||||
let mut plan_changed = false;
|
||||
for point in history.points {
|
||||
let Some(fact) =
|
||||
provider.quota_forecast_observation(&point.provider_observation, window)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let same_plan = quota
|
||||
.plan_type
|
||||
.as_deref()
|
||||
.zip(fact.plan_type.as_deref())
|
||||
.is_some_and(|(current, previous)| current.eq_ignore_ascii_case(previous));
|
||||
// 仅容纳已观测到的秒级量化抖动,不用宽时间容差合并实际重置
|
||||
// 不匹配的段截断基线;之后的有效观测可以重新积累
|
||||
if !same_plan || (fact.reset_at - reset_at).abs() > Duration::seconds(2) {
|
||||
let (Some(current_plan), Some(previous_plan)) =
|
||||
(quota.plan_type.as_deref(), fact.plan_type.as_deref())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Some(start) = fact.reset_at.checked_sub_signed(window_duration) else {
|
||||
continue;
|
||||
};
|
||||
if point.completed_at >= observed
|
||||
|| point.started_at < query.range.start
|
||||
|| point.completed_at < start
|
||||
|| point.completed_at >= fact.reset_at
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if !current_plan.eq_ignore_ascii_case(previous_plan) {
|
||||
points.clear();
|
||||
interrupted = true;
|
||||
plan_changed = true;
|
||||
continue;
|
||||
}
|
||||
points.push(QuotaForecastPoint {
|
||||
started_at: point.started_at,
|
||||
observed_at: point.completed_at,
|
||||
reset_at: fact.reset_at,
|
||||
used_percent: fact.used_percent,
|
||||
usage: point.usage,
|
||||
});
|
||||
@@ -1103,13 +1114,15 @@ impl AccountsService for DefaultAccountsService {
|
||||
window.key.clone(),
|
||||
query.range.start,
|
||||
QuotaForecastPoint {
|
||||
started_at: observed,
|
||||
observed_at: observed,
|
||||
reset_at,
|
||||
used_percent: percent,
|
||||
usage: history.usage,
|
||||
},
|
||||
points,
|
||||
history.pending_request_count,
|
||||
interrupted,
|
||||
plan_changed,
|
||||
);
|
||||
samples.push(sample);
|
||||
}
|
||||
|
||||
@@ -12,7 +12,9 @@ fn time(minutes: i64) -> DateTime<Utc> {
|
||||
|
||||
fn point(minute: i64, percent: f64, tokens: u64) -> QuotaForecastPoint {
|
||||
QuotaForecastPoint {
|
||||
started_at: time(minute) - Duration::seconds(1),
|
||||
observed_at: time(minute),
|
||||
reset_at: time(7 * 24 * 60),
|
||||
used_percent: percent,
|
||||
usage: QuotaForecastUsage {
|
||||
request_count: minute as u64,
|
||||
@@ -188,7 +190,41 @@ fn repeated_same_window_recoveries_preserve_recorded_cycle_usage() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changed_window_restarts_cycle_totals_at_first_matching_observation() {
|
||||
fn an_expired_deadline_alone_cannot_cut_totals_or_anchor_remaining_usage() {
|
||||
let mut older = point(1, 15.0, 100);
|
||||
older.reset_at = time(3);
|
||||
let mut previous = point(2, 20.0, 200);
|
||||
previous.reset_at = time(3) + Duration::seconds(4);
|
||||
let first = point(4, 25.0, 700);
|
||||
let sample = select(vec![older, previous, first], point(6, 35.0, 900));
|
||||
assert_eq!(sample.cycle_usage.tokens, 900);
|
||||
assert_eq!(sample.baseline_percent, 25.0);
|
||||
assert_eq!(sample.usage.tokens, 200);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copied_concurrent_or_contradictory_readings_cannot_confirm_a_recovery() {
|
||||
let mut older = point(1, 75.0, 100);
|
||||
older.reset_at = time(3);
|
||||
let mut previous = point(2, 85.0, 200);
|
||||
previous.reset_at = time(3);
|
||||
let first = point(4, 5.0, 300);
|
||||
let current = point(6, 40.0, 900);
|
||||
let mut overlapping = point(5, 20.0, 400);
|
||||
overlapping.started_at = first.started_at;
|
||||
for extra in [None, Some(overlapping), Some(current.clone())] {
|
||||
let mut points = vec![older.clone(), previous.clone(), first.clone()];
|
||||
points.extend(extra);
|
||||
let sample = select(points, current.clone());
|
||||
assert_eq!(sample.cycle_usage.tokens, 900);
|
||||
assert!(sample.discontinuous);
|
||||
}
|
||||
let sample = select(vec![older, previous, first, point(5, 86.0, 400)], current);
|
||||
assert_eq!(sample.cycle_usage.tokens, 900);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changed_plan_restarts_cycle_totals_at_first_matching_observation() {
|
||||
let sample = select_forecast_sample(
|
||||
"week".to_owned(),
|
||||
time(0),
|
||||
|
||||
@@ -2576,7 +2576,9 @@ async fn quota_forecast_same_window_reversal_keeps_recorded_usage_in_the_report(
|
||||
usage: usage(index as u64 + 1, tokens),
|
||||
provider_observation: ProviderDocument::new(OpaqueProviderData::new(
|
||||
serde_json::json!({
|
||||
"percent": percent, "reset": reset.to_rfc3339(), "plan": "pro",
|
||||
"percent": percent,
|
||||
"reset": (reset + TimeDelta::seconds(17 * index as i64)).to_rfc3339(),
|
||||
"plan": "pro",
|
||||
})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
@@ -2605,14 +2607,14 @@ async fn quota_forecast_same_window_reversal_keeps_recorded_usage_in_the_report(
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn quota_forecast_mid_cycle_sampling_accepts_small_reset_jitter_but_not_a_changed_bucket() {
|
||||
async fn quota_forecast_keeps_cycle_totals_through_reset_jitter_and_restarts_after_a_reset() {
|
||||
use gateway_admin::model::quota_forecast_sampling::QuotaForecastHistoryPoint;
|
||||
let now = Utc::now();
|
||||
let observed = now - TimeDelta::minutes(1);
|
||||
let reset = now + TimeDelta::days(1);
|
||||
let added = now - TimeDelta::hours(5);
|
||||
let provider = FakeProviderAdmin::new("openai", events());
|
||||
provider.set_quota(ProviderQuota {
|
||||
let mut quota = ProviderQuota {
|
||||
upstream: None,
|
||||
credits: None,
|
||||
plan_type: Some("pro".to_owned()),
|
||||
@@ -2627,67 +2629,102 @@ async fn quota_forecast_mid_cycle_sampling_accepts_small_reset_jitter_but_not_a_
|
||||
role: None,
|
||||
local_usage_attribution: QuotaLocalUsageAttribution::AccountWide,
|
||||
window_seconds: Some(604_800),
|
||||
used_percent: Some(40.0),
|
||||
used_percent: Some(65.0),
|
||||
reset_at: Some(reset),
|
||||
limit_reached: false,
|
||||
local_usage: None,
|
||||
provider_data: None,
|
||||
}],
|
||||
..empty_quota()
|
||||
});
|
||||
};
|
||||
let mut account = account_record("openai");
|
||||
account.created_at = added;
|
||||
let store = FakeAccountStore::with_account(account, events());
|
||||
let make_point = |hours, percent, tokens, delta| {
|
||||
QuotaForecastHistoryPoint {
|
||||
started_at: now - TimeDelta::hours(hours) - TimeDelta::seconds(10),
|
||||
completed_at: now - TimeDelta::hours(hours),
|
||||
usage: QuotaForecastUsage { request_count: tokens / 100, tokens, ..Default::default() },
|
||||
provider_observation: ProviderDocument::new(OpaqueProviderData::new(serde_json::json!({
|
||||
"percent": percent, "reset": (reset + TimeDelta::seconds(delta)).to_rfc3339(), "plan": "pro",
|
||||
}).as_object().unwrap().clone())),
|
||||
}
|
||||
let usage = |tokens| QuotaForecastUsage {
|
||||
request_count: tokens / 100,
|
||||
tokens,
|
||||
known_cost_count: tokens / 100,
|
||||
usd: tokens as f64 / 100.0,
|
||||
..Default::default()
|
||||
};
|
||||
let point_with_plan = |hours, percent, tokens, delta, plan: Option<&str>| {
|
||||
let observation = serde_json::json!({
|
||||
"percent": percent,
|
||||
"reset": (reset + TimeDelta::seconds(delta)).to_rfc3339(),
|
||||
"plan": plan,
|
||||
});
|
||||
QuotaForecastHistoryPoint {
|
||||
started_at: now - TimeDelta::hours(hours) - TimeDelta::seconds(10),
|
||||
completed_at: now - TimeDelta::hours(hours),
|
||||
usage: usage(tokens),
|
||||
provider_observation: ProviderDocument::new(OpaqueProviderData::new(
|
||||
observation.as_object().unwrap().clone(),
|
||||
)),
|
||||
}
|
||||
};
|
||||
let make_point =
|
||||
|hours, percent, tokens, delta| point_with_plan(hours, percent, tokens, delta, Some("pro"));
|
||||
*store.quota_forecast_history.lock().unwrap() = QuotaForecastHistory {
|
||||
points: vec![
|
||||
make_point(3, 20.0, 1_000, 1),
|
||||
make_point(2, 30.0, 1_500, -1),
|
||||
make_point(4, 20.0, 20_000, 0),
|
||||
make_point(3, 58.0, 62_000, 17),
|
||||
make_point(2, 58.0, 62_500, 0),
|
||||
],
|
||||
usage: QuotaForecastUsage {
|
||||
request_count: 20,
|
||||
tokens: 2_000,
|
||||
..Default::default()
|
||||
},
|
||||
usage: usage(70_600),
|
||||
pending_request_count: 1,
|
||||
};
|
||||
let services = accounts_service(provider, store.clone()).await;
|
||||
let result = services
|
||||
.accounts()
|
||||
.quota_forecast(&ProviderAccountId::new("acct_test").unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(result.forecasts[0].unavailable_reason.is_none());
|
||||
assert_eq!(result.forecasts[0].estimated_tokens, Some(5_000));
|
||||
let services = accounts_service(provider.clone(), store.clone()).await;
|
||||
let account_id = ProviderAccountId::new("acct_test").unwrap();
|
||||
let read_report = async || {
|
||||
services
|
||||
.accounts()
|
||||
.quota_forecast(&account_id)
|
||||
.await
|
||||
.unwrap()
|
||||
};
|
||||
// 回放 #759 的金额和百分比,历史与快照各自报告的到期时间偏移时仍应保留整段累计
|
||||
for offset in [0, 3, 6, 7, 17, -23] {
|
||||
quota.windows[0].reset_at = Some(reset + TimeDelta::seconds(offset));
|
||||
provider.set_quota(quota.clone());
|
||||
let report = read_report().await;
|
||||
let week = &report.forecasts[0];
|
||||
let source = week.source.as_ref().unwrap();
|
||||
assert_eq!(source.tokens, Some(70_600));
|
||||
assert_eq!(source.usd, Some(706.0));
|
||||
assert_eq!(week.estimated_tokens, Some(109_956));
|
||||
assert!((week.estimated_usd.unwrap() - (706.0 + 506.0 * 35.0 / 45.0)).abs() < 1e-9);
|
||||
assert!(week.unavailable_reason.is_none());
|
||||
}
|
||||
assert_eq!(store.quota_window_queries()[0].range.start, added);
|
||||
store
|
||||
.quota_forecast_history
|
||||
.lock()
|
||||
.unwrap()
|
||||
.points
|
||||
.push(make_point(1, 35.0, 1_700, 3_600));
|
||||
let result = services
|
||||
.accounts()
|
||||
.quota_forecast(&ProviderAccountId::new("acct_test").unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(result.forecasts[0].estimated_tokens.is_none());
|
||||
assert!(
|
||||
result.forecasts[0]
|
||||
.unavailable_reason
|
||||
.unwrap()
|
||||
.contains("不连续")
|
||||
.push(make_point(1, 62.0, 66_000, 3_600));
|
||||
let result = read_report().await;
|
||||
assert_eq!(
|
||||
result.forecasts[0].source.as_ref().unwrap().tokens,
|
||||
Some(70_600)
|
||||
);
|
||||
// 新额度段已有足够观测后恢复预测,但总量不能带回重置前的累计用量
|
||||
assert!(result.forecasts[0].estimated_tokens.is_some());
|
||||
// 两份旧读数的截止时刻均已过去,新请求开始于旧窗口结束后
|
||||
quota.windows[0].used_percent = Some(40.0);
|
||||
provider.set_quota(quota.clone());
|
||||
*store.quota_forecast_history.lock().unwrap() = QuotaForecastHistory {
|
||||
points: vec![
|
||||
make_point(4, 75.0, 1_000, -90_000),
|
||||
make_point(2, 85.0, 1_500, -90_021),
|
||||
],
|
||||
usage: usage(2_000),
|
||||
..Default::default()
|
||||
};
|
||||
let waiting = read_report().await;
|
||||
assert_eq!(
|
||||
waiting.forecasts[0].source.as_ref().unwrap().tokens,
|
||||
Some(2_000)
|
||||
);
|
||||
assert!(waiting.forecasts[0].estimated_tokens.is_none());
|
||||
let mut first = make_point(1, 5.0, 1_750, 0);
|
||||
first.completed_at = now - TimeDelta::minutes(45);
|
||||
first.started_at = first.completed_at - TimeDelta::seconds(10);
|
||||
@@ -2700,15 +2737,42 @@ async fn quota_forecast_mid_cycle_sampling_accepts_small_reset_jitter_but_not_a_
|
||||
.unwrap()
|
||||
.points
|
||||
.extend([first, next]);
|
||||
let result = services
|
||||
.accounts()
|
||||
.quota_forecast(&ProviderAccountId::new("acct_test").unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let result = read_report().await;
|
||||
let cycle = &result.forecasts[0];
|
||||
assert!(cycle.unavailable_reason.is_none());
|
||||
assert_eq!(cycle.source.as_ref().unwrap().tokens, Some(250));
|
||||
assert_eq!(cycle.estimated_tokens, Some(679));
|
||||
|
||||
for (plan, expected_tokens) in [(None, 2_000), (Some("plus"), 500)] {
|
||||
store.quota_forecast_history.lock().unwrap().points = vec![
|
||||
make_point(4, 20.0, 1_000, 0),
|
||||
point_with_plan(3, 25.0, 1_200, 0, plan),
|
||||
make_point(2, 30.0, 1_500, 0),
|
||||
];
|
||||
let report = read_report().await;
|
||||
assert_eq!(
|
||||
report.forecasts[0].source.as_ref().unwrap().tokens,
|
||||
Some(expected_tokens)
|
||||
);
|
||||
}
|
||||
|
||||
// 上游提前给出新的七天窗口时,直接从新起点查询,首条配对样本前的用量也留在累计中
|
||||
let new_start = now - TimeDelta::hours(1);
|
||||
quota.windows[0].reset_at = Some(new_start + TimeDelta::days(7));
|
||||
provider.set_quota(quota);
|
||||
*store.quota_forecast_history.lock().unwrap() = QuotaForecastHistory {
|
||||
usage: usage(400),
|
||||
..Default::default()
|
||||
};
|
||||
let report = read_report().await;
|
||||
assert_eq!(
|
||||
store.quota_window_queries().last().unwrap().range.start,
|
||||
new_start
|
||||
);
|
||||
assert_eq!(
|
||||
report.forecasts[0].source.as_ref().unwrap().tokens,
|
||||
Some(400)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -643,7 +643,7 @@ async fn dropping_the_connection_aborts_and_drops_the_socket_owner() {
|
||||
assert!(cancellation.is_cancelled());
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
#[tokio::test]
|
||||
async fn idle_connection_reaches_the_official_limit_without_starting_an_execution() {
|
||||
let trace = Arc::new(AtomicFailureTrace::default());
|
||||
let execution = Arc::new(AtomicFailureExecution {
|
||||
@@ -672,8 +672,11 @@ async fn idle_connection_reaches_the_official_limit_without_starting_an_executio
|
||||
let (mut socket, response) = connect_async(request).await.expect("upgrade WebSocket");
|
||||
assert_eq!(response.status(), StatusCode::SWITCHING_PROTOCOLS);
|
||||
|
||||
// 真实 socket 读写期间使用实时时钟,避免 I/O 等待自动耗尽虚拟期限
|
||||
tokio::time::pause();
|
||||
tokio::time::advance(Duration::from_secs(60 * 60)).await;
|
||||
tokio::task::yield_now().await;
|
||||
tokio::time::resume();
|
||||
let text = loop {
|
||||
let message = tokio::time::timeout(Duration::from_secs(1), socket.next())
|
||||
.await
|
||||
|
||||
@@ -50,7 +50,6 @@ tracing-subscriber = { version = "0.3.23", features = ["env-filter", "json"] }
|
||||
yaml-rust2 = "0.13.0"
|
||||
|
||||
[dev-dependencies]
|
||||
filetime = "0.2.27"
|
||||
hyper = { version = "=1.11.1", default-features = false, features = ["server"] }
|
||||
tempfile = "3.27.0"
|
||||
tokio = { version = "1.52.3", default-features = false, features = ["rt-multi-thread", "test-util"] }
|
||||
|
||||
@@ -18,7 +18,6 @@ use std::sync::{
|
||||
};
|
||||
use std::time::Duration;
|
||||
|
||||
use filetime::FileTime;
|
||||
use flate2::{Compression, write::GzEncoder};
|
||||
use futures::StreamExt as _;
|
||||
use gateway_admin::model::{
|
||||
|
||||
@@ -1058,7 +1058,8 @@ async fn update_should_remove_stale_file_lock_and_continue() {
|
||||
)
|
||||
.await;
|
||||
fs::write(fixture.lock(), "stale").expect("lock");
|
||||
filetime::set_file_mtime(fixture.lock(), FileTime::from_unix_time(1, 0)).expect("old mtime");
|
||||
let old_mtime = std::time::SystemTime::UNIX_EPOCH + Duration::from_secs(1);
|
||||
fs::set_times(fixture.lock(), fs::FileTimes::new().set_modified(old_mtime)).expect("old mtime");
|
||||
|
||||
assert_eq!(
|
||||
complete_update(&fixture.service(&server), TARGET_VERSION)
|
||||
|
||||
@@ -985,9 +985,7 @@ impl CodexCredentialAdminService {
|
||||
ParsedCodexAuthentication::ApiKey(data) => {
|
||||
let mut prepared = CodexCredentialAdmin.prepare_api_key(
|
||||
account_id,
|
||||
candidate
|
||||
.name
|
||||
.unwrap_or_else(|| "OpenAI API Key".to_owned()),
|
||||
candidate.name.unwrap_or_else(|| "密钥账号".to_owned()),
|
||||
data,
|
||||
)?;
|
||||
prepared.model_access = candidate.model_access;
|
||||
|
||||
@@ -875,6 +875,15 @@ impl CodexCredentialSelector {
|
||||
only_account,
|
||||
)
|
||||
.await?;
|
||||
let image_primary = binding
|
||||
.as_ref()
|
||||
.filter(|_| {
|
||||
matches!(model, CodexSelectionModel::Image(_))
|
||||
&& affinity_mode == AccountAffinity::Strict
|
||||
&& pinned_account.is_none()
|
||||
})
|
||||
.map(ProviderSessionBinding::account_id)
|
||||
.filter(|id| accounts.iter().any(|account| account.id() == *id));
|
||||
let mut model_access_rejected = 0_usize;
|
||||
let accounts = accounts
|
||||
.into_iter()
|
||||
@@ -1030,6 +1039,14 @@ impl CodexCredentialSelector {
|
||||
.iter()
|
||||
.map(|account| account.id().clone())
|
||||
.collect::<Vec<_>>();
|
||||
// 主账号在授权池内,但未通过 Images 的模型、套餐或协议筛选时,只为本次图片借号
|
||||
let image_primary_to_keep = image_primary.filter(|id| !account_ids.contains(id));
|
||||
if image_primary_to_keep.is_some() && queued_account.is_some() {
|
||||
// 排队期间主账号的资格可能变化,先恢复完整候选再找可用的生图账号
|
||||
refresh_candidates = true;
|
||||
continue 'capacity;
|
||||
}
|
||||
let follow_only = follow_only && image_primary_to_keep.is_none();
|
||||
let rate_limits = if diagnostic {
|
||||
HashMap::new()
|
||||
} else {
|
||||
@@ -1508,7 +1525,7 @@ impl CodexCredentialSelector {
|
||||
}
|
||||
ProviderLeaseAcquisition::Acquired(guard) => guard,
|
||||
};
|
||||
let mut binding_account = account.id();
|
||||
let mut binding_account = image_primary_to_keep.unwrap_or(account.id());
|
||||
if affinity_mode == AccountAffinity::Preferred
|
||||
&& let Some(primary) = binding.as_ref()
|
||||
&& (primary.account_id() == account.id()
|
||||
|
||||
@@ -684,10 +684,11 @@ pub(super) fn websocket_retry_backoff(retry_index: NonZeroU32) -> Duration {
|
||||
}
|
||||
|
||||
pub(super) fn continuation_replay_required_error(reason: &'static str) -> ProviderError {
|
||||
ProviderError::new(
|
||||
ProviderErrorKind::ContinuationRecoveryRequired,
|
||||
UpstreamSendState::NotSent,
|
||||
)
|
||||
continuation_replay_error(reason, UpstreamSendState::NotSent)
|
||||
}
|
||||
|
||||
fn continuation_replay_error(reason: &'static str, send_state: UpstreamSendState) -> ProviderError {
|
||||
ProviderError::new(ProviderErrorKind::ContinuationRecoveryRequired, send_state)
|
||||
.with_continuation_failure(ContinuationFailure::HistoryUnavailable)
|
||||
.with_continuation_recovery_disposition(
|
||||
ContinuationRecoveryDisposition::ClientReplayRequired,
|
||||
@@ -978,10 +979,13 @@ pub(super) fn map_client_error(
|
||||
))
|
||||
}
|
||||
CodexClientError::WebSocket(error) if error.continuation_unavailable_reason().is_some() => {
|
||||
let mut failure = MappedProviderFailure::plain(continuation_replay_required_error(
|
||||
let mut failure = MappedProviderFailure::plain(continuation_replay_error(
|
||||
continuation_unavailable_reason.unwrap_or("scope_unavailable"),
|
||||
websocket_send_state(error),
|
||||
));
|
||||
if let Some(client_visible_error) = websocket_client_visible_error(error) {
|
||||
if !error.message_too_big_close()
|
||||
&& let Some(client_visible_error) = websocket_client_visible_error(error)
|
||||
{
|
||||
failure.error = failure
|
||||
.error
|
||||
.with_client_visible_upstream_error(client_visible_error);
|
||||
@@ -997,8 +1001,9 @@ pub(super) fn map_client_error(
|
||||
if matches!(
|
||||
error.classified(),
|
||||
CodexWebSocketExchangeError::MessageTooLarge
|
||||
) {
|
||||
// 可回退请求已在 transport 内转为 HTTP,剩余预热请求不能重复发送
|
||||
) || error.message_too_big_close()
|
||||
{
|
||||
// 首条文本前可回退的 1009 已在 transport 处理;预热或已收到回复时禁止重放
|
||||
failure.error = failure.error.with_retry_prohibited();
|
||||
}
|
||||
if let CodexWebSocketExchangeError::ConnectionLimitReached(upstream) =
|
||||
@@ -1386,7 +1391,7 @@ fn websocket_diagnostic_message(error: &CodexWebSocketExchangeError) -> Provider
|
||||
CodexWebSocketExchangeError::ConnectionLimitReached(_) => {
|
||||
"OpenAI requested a new WebSocket connection".to_owned()
|
||||
}
|
||||
CodexWebSocketExchangeError::ContinuationUnavailable { reason } => {
|
||||
CodexWebSocketExchangeError::ContinuationUnavailable { reason, .. } => {
|
||||
format!("OpenAI connection-local previous response is unavailable: {reason}")
|
||||
}
|
||||
CodexWebSocketExchangeError::ReceiveIdleTimeout { timeout } => {
|
||||
@@ -1784,6 +1789,10 @@ pub(super) fn account_failure(
|
||||
|
||||
pub(super) fn websocket_send_state(error: &CodexWebSocketExchangeError) -> UpstreamSendState {
|
||||
match error.classified() {
|
||||
CodexWebSocketExchangeError::ContinuationUnavailable {
|
||||
source: Some(source),
|
||||
..
|
||||
} => websocket_send_state(source),
|
||||
CodexWebSocketExchangeError::InvalidRequest(_)
|
||||
| CodexWebSocketExchangeError::Connect { .. }
|
||||
| CodexWebSocketExchangeError::ConnectTimeout { .. }
|
||||
@@ -1839,10 +1848,7 @@ pub(super) fn websocket_error_kind(error: &CodexWebSocketExchangeError) -> Provi
|
||||
// live 流可能包在 PostSendAmbiguous 中;RFC 6455 close 1009 是请求过大
|
||||
CodexWebSocketExchangeError::ClosedBeforeTerminal(_)
|
||||
| CodexWebSocketExchangeError::PostSendAmbiguous { .. } => {
|
||||
if error
|
||||
.close_before_terminal()
|
||||
.is_some_and(|close| close.code() == Some(WEBSOCKET_CLOSE_MESSAGE_TOO_BIG))
|
||||
{
|
||||
if error.message_too_big_close() {
|
||||
ProviderErrorKind::MessageTooBig
|
||||
} else {
|
||||
ProviderErrorKind::Transport
|
||||
|
||||
@@ -87,7 +87,7 @@ use crate::transport::protocol::responses::{
|
||||
};
|
||||
use crate::transport::request::{
|
||||
CodexRequestEncodeError, RequestAccountScope, align_structured_location_fields,
|
||||
encode_generate_payload, scope_request_to_account,
|
||||
apply_codex_request_country, encode_generate_payload, scope_request_to_account,
|
||||
};
|
||||
use crate::transport::session::CodexSessionIdentity;
|
||||
use crate::transport::usage::normalize_service_tier;
|
||||
@@ -1090,6 +1090,10 @@ impl CodexProvider {
|
||||
"after": crate::transport::diagnostics::evidence::request_state(&upstream_request),
|
||||
}));
|
||||
}
|
||||
let location = lease
|
||||
.account()
|
||||
.request_location()
|
||||
.or(context.request_location());
|
||||
if codex_oauth {
|
||||
if matches!(
|
||||
guardian_role,
|
||||
@@ -1104,16 +1108,13 @@ impl CodexProvider {
|
||||
&middleware_headers,
|
||||
context.request_id().as_str(),
|
||||
);
|
||||
apply_codex_request_country(
|
||||
upstream_request.body_mut(),
|
||||
location,
|
||||
context.openai_request_country(),
|
||||
);
|
||||
}
|
||||
let location = lease
|
||||
.account()
|
||||
.request_location()
|
||||
.or(context.request_location());
|
||||
align_structured_location_fields(
|
||||
upstream_request.body_mut(),
|
||||
location,
|
||||
context.openai_request_country(),
|
||||
);
|
||||
align_structured_location_fields(upstream_request.body_mut(), location);
|
||||
let requirement = transport_requirement(&upstream_request);
|
||||
let http_only = lease.transport() == crate::credential::ResponsesTransport::Http;
|
||||
if http_only && requirement.requires_websocket() {
|
||||
|
||||
@@ -374,8 +374,13 @@ impl CodexBackendClient {
|
||||
connection_profile.push_str("\0peer:");
|
||||
connection_profile.push_str(&hex::encode(Sha256::digest(route.as_bytes())));
|
||||
}
|
||||
let pool_key =
|
||||
self.websocket_pool_key(request, context, pool_account_id, &connection_profile);
|
||||
let pool_key = self.websocket_pool_key(
|
||||
request,
|
||||
context,
|
||||
pool_account_id,
|
||||
&connection_profile,
|
||||
opening.connection.headers(),
|
||||
);
|
||||
let pool_log_context = pool_key.as_ref().map(WebSocketPoolLogContext::from_key);
|
||||
let downstream_cancellation = context.response_control.and_then(
|
||||
gateway_core::engine::response_control::ResponseControl::connection_cancellation,
|
||||
@@ -519,24 +524,10 @@ impl CodexBackendClient {
|
||||
..CodexTransportMetrics::default()
|
||||
};
|
||||
prepared.discard().await;
|
||||
let error = match requirement {
|
||||
TransportRequirement::ExactWebSocketContinuation => {
|
||||
Some(CodexWebSocketExchangeError::ContinuationUnavailable {
|
||||
reason: PreviousResponseUnavailableReason::PayloadTooLarge,
|
||||
})
|
||||
}
|
||||
TransportRequirement::ExplicitWebSocketWarmup => {
|
||||
Some(CodexWebSocketExchangeError::MessageTooLarge)
|
||||
}
|
||||
TransportRequirement::HttpRequired
|
||||
| TransportRequirement::WebSocketNewChain
|
||||
| TransportRequirement::PersistedContinuation
|
||||
| TransportRequirement::ExternalUnknown
|
||||
| TransportRequirement::NewChain => None,
|
||||
};
|
||||
if let Some(error) = error {
|
||||
return Err(websocket_exchange_error_to_client_error(error));
|
||||
}
|
||||
check_oversized_websocket_fallback(
|
||||
requirement,
|
||||
CodexWebSocketExchangeError::MessageTooLarge,
|
||||
)?;
|
||||
context.trace.cloned().unwrap_or_default().record(
|
||||
"transport.fallback",
|
||||
serde_json::json!({
|
||||
@@ -587,6 +578,19 @@ impl CodexBackendClient {
|
||||
})
|
||||
}
|
||||
|
||||
async fn http_stream_with_metrics(
|
||||
&self,
|
||||
request: &CodexResponsesRequest,
|
||||
context: CodexRequestContext<'_>,
|
||||
metrics: CodexTransportMetrics,
|
||||
) -> CodexClientResult<CodexBackendStreamingResponse> {
|
||||
let mut response = self
|
||||
.create_response_stream_http_sse(request, context)
|
||||
.await?;
|
||||
merge_preparation_metrics(&mut response.transport_metrics, metrics);
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub(crate) async fn create_response_stream_with_prepared(
|
||||
&self,
|
||||
@@ -607,19 +611,16 @@ impl CodexBackendClient {
|
||||
}),
|
||||
);
|
||||
match route {
|
||||
PreparedResponseRoute::Http => self
|
||||
.create_response_stream_http_sse(request, context)
|
||||
.await
|
||||
.map(|mut response| {
|
||||
merge_preparation_metrics(&mut response.transport_metrics, metrics);
|
||||
response
|
||||
}),
|
||||
PreparedResponseRoute::Http => {
|
||||
self.http_stream_with_metrics(request, context, metrics)
|
||||
.await
|
||||
}
|
||||
PreparedResponseRoute::WebSocket(route) => {
|
||||
let PreparedWebSocketRoute {
|
||||
request: websocket_request,
|
||||
prepared,
|
||||
} = *route;
|
||||
let mut exchange = execute_prepared_response_create_request_stream(
|
||||
let exchange = execute_prepared_response_create_request_stream(
|
||||
&websocket_request,
|
||||
prepared,
|
||||
context.response_control.cloned(),
|
||||
@@ -629,8 +630,29 @@ impl CodexBackendClient {
|
||||
.unwrap_or_default()
|
||||
.exchange("websocket"),
|
||||
)
|
||||
.await
|
||||
.map_err(websocket_exchange_error_to_client_error)?;
|
||||
.await;
|
||||
let mut exchange = match exchange {
|
||||
Err(error) if error.message_too_big_close() => {
|
||||
// 上游已回复本次上传,HTTP 恢复不再占用发送前的建连窗口
|
||||
if let Some(budget) = &self.connection_budget {
|
||||
budget.complete();
|
||||
}
|
||||
check_oversized_websocket_fallback(requirement, error)?;
|
||||
context.trace.cloned().unwrap_or_default().record(
|
||||
"transport.fallback", serde_json::json!({
|
||||
"to": "http_sse", "reason": "websocket_message_too_large", "closeCode": 1009,
|
||||
"requirement": requirement.as_str(), "payloadBytes": websocket_request.payload_text().len(),
|
||||
}),
|
||||
);
|
||||
let mut metrics = metrics;
|
||||
metrics.decision =
|
||||
Some(CodexTransportDecision::Http2WebSocketMessageTooLarge);
|
||||
return self
|
||||
.http_stream_with_metrics(request, context, metrics)
|
||||
.await;
|
||||
}
|
||||
result => result.map_err(websocket_exchange_error_to_client_error)?,
|
||||
};
|
||||
if requirement.allows_connection_restart() {
|
||||
// 前导帧即时交付;连接寿命拒绝仍沿用原有分类与恢复预算
|
||||
let mut boundary_reached = false;
|
||||
@@ -685,6 +707,7 @@ impl CodexBackendClient {
|
||||
context: CodexRequestContext<'_>,
|
||||
pool_account_id: Option<&str>,
|
||||
connection_profile: &str,
|
||||
opening_headers: &[(String, String)],
|
||||
) -> Option<CodexWebSocketPoolKey> {
|
||||
let account_id = pool_account_id.or(context.account_id)?;
|
||||
let conversation_id = request
|
||||
@@ -695,6 +718,7 @@ impl CodexBackendClient {
|
||||
.with_egress_key(&self.egress_key)
|
||||
.with_outbound_proxy(self.outbound_proxy.as_ref())
|
||||
.with_connection_profile(connection_profile)
|
||||
.with_response_exclusions(opening_headers)
|
||||
.with_fedramp_routing(self.fedramp_routing)
|
||||
.with_installation_id(context.installation_id);
|
||||
key = key.with_routing_affinity(self.routing_affinity.as_ref().map(|pin| pin.id()));
|
||||
@@ -705,6 +729,27 @@ impl CodexBackendClient {
|
||||
}
|
||||
}
|
||||
|
||||
fn check_oversized_websocket_fallback(
|
||||
requirement: TransportRequirement,
|
||||
cause: CodexWebSocketExchangeError,
|
||||
) -> CodexClientResult<()> {
|
||||
let error = match requirement {
|
||||
TransportRequirement::ExactWebSocketContinuation => {
|
||||
CodexWebSocketExchangeError::ContinuationUnavailable {
|
||||
reason: PreviousResponseUnavailableReason::PayloadTooLarge,
|
||||
source: cause.message_too_big_close().then(|| Box::new(cause)),
|
||||
}
|
||||
}
|
||||
TransportRequirement::ExplicitWebSocketWarmup => cause,
|
||||
TransportRequirement::HttpRequired
|
||||
| TransportRequirement::WebSocketNewChain
|
||||
| TransportRequirement::PersistedContinuation
|
||||
| TransportRequirement::ExternalUnknown
|
||||
| TransportRequirement::NewChain => return Ok(()),
|
||||
};
|
||||
Err(websocket_exchange_error_to_client_error(error))
|
||||
}
|
||||
|
||||
fn is_websocket_replayable_prelude(frame: &[u8]) -> bool {
|
||||
serde_json::from_slice::<serde_json::Value>(frame)
|
||||
.ok()
|
||||
|
||||
@@ -108,11 +108,12 @@ pub fn encode_generate_request(
|
||||
location: Option<&CodexRequestLocation>,
|
||||
) -> Result<CodexResponsesRequest, CodexRequestEncodeError> {
|
||||
let mut encoded = encode_generate_payload(request, upstream_model)?;
|
||||
align_structured_location_fields(
|
||||
apply_codex_request_country(
|
||||
encoded.body_mut(),
|
||||
location,
|
||||
&OpenAiRequestCountry::default(),
|
||||
);
|
||||
align_structured_location_fields(encoded.body_mut(), location);
|
||||
Ok(encoded)
|
||||
}
|
||||
|
||||
@@ -135,7 +136,7 @@ pub(crate) fn encode_generate_payload(
|
||||
Ok(encoded)
|
||||
}
|
||||
|
||||
pub(crate) fn align_structured_location_fields(
|
||||
pub(crate) fn apply_codex_request_country(
|
||||
body: &mut Map<String, Value>,
|
||||
location: Option<&CodexRequestLocation>,
|
||||
country: &OpenAiRequestCountry,
|
||||
@@ -155,6 +156,12 @@ pub(crate) fn align_structured_location_fields(
|
||||
body.insert("request_country".into(), Value::from(country.as_str()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn align_structured_location_fields(
|
||||
body: &mut Map<String, Value>,
|
||||
location: Option<&CodexRequestLocation>,
|
||||
) {
|
||||
let Some(location) = location else { return };
|
||||
if let Some(input) = body.get_mut("input").and_then(Value::as_array_mut) {
|
||||
for item in input {
|
||||
|
||||
@@ -15,13 +15,25 @@ use super::CodexWebSocketExchangeError;
|
||||
pub(super) const WEBSOCKET_SEND_TIMEOUT: Duration = Duration::from_secs(5 * 60);
|
||||
|
||||
pub(super) enum PumpCommand {
|
||||
Upload {
|
||||
text: tungstenite::Utf8Bytes,
|
||||
deadline: tokio::time::Instant,
|
||||
accepted:
|
||||
oneshot::Sender<oneshot::Receiver<Result<UploadOutcome, CodexWebSocketExchangeError>>>,
|
||||
},
|
||||
Send {
|
||||
message: Message,
|
||||
ack: oneshot::Sender<Result<(), CodexWebSocketExchangeError>>,
|
||||
},
|
||||
}
|
||||
|
||||
pub(super) type SharedMessages = Arc<Mutex<mpsc::Receiver<Result<Message, tungstenite::Error>>>>;
|
||||
pub(super) enum UploadOutcome {
|
||||
Flushed,
|
||||
InterruptedWithReply,
|
||||
}
|
||||
|
||||
pub(super) type SharedMessages =
|
||||
Arc<Mutex<mpsc::Receiver<Result<Message, CodexWebSocketExchangeError>>>>;
|
||||
|
||||
pub(super) struct PumpControl {
|
||||
pub(super) tx_command: mpsc::Sender<PumpCommand>,
|
||||
|
||||
@@ -18,7 +18,7 @@ use super::{
|
||||
exchange::{
|
||||
CodexWebSocketStreamingExchange, WebSocketStreamPoolReturn, stream_websocket_response,
|
||||
},
|
||||
handshake::{connect_pumped_websocket, send_websocket_request, websocket_connection_metadata},
|
||||
handshake::{connect_pumped_websocket, websocket_connection_metadata},
|
||||
model::{
|
||||
CodexWebSocketConnection, CodexWebSocketRequest, PreviousResponseUnavailableReason,
|
||||
ResponseCreateOpening, WebSocketContinuationRequirement,
|
||||
@@ -600,7 +600,10 @@ fn bypass_unavailable_error(reason: WebSocketPoolBypassReason) -> CodexWebSocket
|
||||
fn continuation_unavailable(
|
||||
reason: PreviousResponseUnavailableReason,
|
||||
) -> CodexWebSocketExchangeError {
|
||||
CodexWebSocketExchangeError::ContinuationUnavailable { reason }
|
||||
CodexWebSocketExchangeError::ContinuationUnavailable {
|
||||
reason,
|
||||
source: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn execute_prepared_response_create_request_stream(
|
||||
@@ -631,39 +634,51 @@ pub(crate) async fn execute_prepared_response_create_request_stream(
|
||||
"headers": gateway_core::diagnostics::diagnostic_headers(metadata.diagnostics.trace_headers.iter().map(|(name, value)| (name.as_str(), value.as_str()))),
|
||||
}));
|
||||
trace.capture("upstream.request.body", request.payload_text().as_bytes());
|
||||
if let Err(error) = send_websocket_request(&websocket, request.payload_text()).await {
|
||||
let not_started = matches!(error, CodexWebSocketExchangeError::SendNotStarted);
|
||||
let observation = websocket.observation();
|
||||
let observation = if observation.exit_reason() == "running" {
|
||||
observation.with_exit_reason("outbound_transport_error")
|
||||
} else {
|
||||
observation
|
||||
};
|
||||
trace.record(
|
||||
"upstream.send.failed",
|
||||
serde_json::json!({
|
||||
match websocket
|
||||
.upload(request.payload_text().to_owned().into())
|
||||
.await
|
||||
{
|
||||
Ok(super::control::UploadOutcome::Flushed) => {
|
||||
trace.record("upstream.payload.sent", serde_json::json!({}));
|
||||
}
|
||||
Ok(super::control::UploadOutcome::InterruptedWithReply) => {
|
||||
trace.record(
|
||||
"upstream.upload.interrupted",
|
||||
serde_json::json!({"connectionId": websocket.connection_id().to_string()}),
|
||||
);
|
||||
}
|
||||
Err(error) => {
|
||||
let not_started = matches!(error, CodexWebSocketExchangeError::SendNotStarted);
|
||||
let observation = websocket.observation();
|
||||
let observation = if observation.exit_reason() == "running" {
|
||||
observation.with_exit_reason("outbound_transport_error")
|
||||
} else {
|
||||
observation
|
||||
};
|
||||
trace.record("upstream.send.failed", serde_json::json!({
|
||||
"phase": "websocket_payload", "sendState": if not_started { "not_sent" } else { "ambiguous" },
|
||||
"failureReason": error.transport_failure_reason().unwrap_or(observation.exit_reason()),
|
||||
"connectionId": observation.connection_id().to_string(),
|
||||
"connectionAgeMs": observation.age_ms(),
|
||||
"connectionIdleMs": observation.idle_ms(),
|
||||
"reused": reused,
|
||||
}),
|
||||
);
|
||||
discard_connection(websocket, lease, observation.clone()).await;
|
||||
let error = if not_started {
|
||||
if request.continuation().permits_fresh_connection() {
|
||||
error
|
||||
}));
|
||||
discard_connection(websocket, lease, observation.clone()).await;
|
||||
let error = if not_started {
|
||||
if request.continuation().permits_fresh_connection() {
|
||||
error
|
||||
} else {
|
||||
continuation_unavailable(
|
||||
PreviousResponseUnavailableReason::ReusedConnectionLost,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
continuation_unavailable(PreviousResponseUnavailableReason::ReusedConnectionLost)
|
||||
}
|
||||
} else {
|
||||
post_send_ambiguous(error)
|
||||
};
|
||||
return Err(error.with_connection_observation(observation));
|
||||
post_send_ambiguous(error)
|
||||
};
|
||||
return Err(error.with_connection_observation(observation));
|
||||
}
|
||||
}
|
||||
trace.record("upstream.payload.sent", serde_json::json!({}));
|
||||
let connection_local_available = lease.is_some();
|
||||
let connection_local_available = lease.is_some() && !websocket.is_closed();
|
||||
let pool_return = lease.map(|lease| WebSocketStreamPoolReturn {
|
||||
lease,
|
||||
created_at,
|
||||
@@ -679,7 +694,8 @@ pub(crate) async fn execute_prepared_response_create_request_stream(
|
||||
stream_idle_timeout,
|
||||
trace,
|
||||
response_control,
|
||||
);
|
||||
)
|
||||
.await?;
|
||||
exchange.pool_decision = pool_decision;
|
||||
exchange.connection_local_continuation = connection_local_available;
|
||||
Ok(exchange)
|
||||
|
||||
@@ -84,6 +84,8 @@ pub enum CodexWebSocketExchangeError {
|
||||
#[error("websocket continuation unavailable: {reason}")]
|
||||
ContinuationUnavailable {
|
||||
reason: PreviousResponseUnavailableReason,
|
||||
#[source]
|
||||
source: Option<Box<Self>>,
|
||||
},
|
||||
/// 上游在 terminal 事件前关闭
|
||||
#[error("{0}")]
|
||||
@@ -257,6 +259,10 @@ impl CodexWebSocketExchangeError {
|
||||
source: Some(source),
|
||||
..
|
||||
}
|
||||
| Self::ContinuationUnavailable {
|
||||
source: Some(source),
|
||||
..
|
||||
}
|
||||
| Self::ConnectionObserved { source, .. } => source.diagnostic_cause(),
|
||||
_ => self,
|
||||
}
|
||||
@@ -316,11 +322,21 @@ impl CodexWebSocketExchangeError {
|
||||
source: Some(source),
|
||||
..
|
||||
}
|
||||
| Self::ContinuationUnavailable {
|
||||
source: Some(source),
|
||||
..
|
||||
}
|
||||
| Self::ConnectionObserved { source, .. } => source.close_before_terminal(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn message_too_big_close(&self) -> bool {
|
||||
self.close_before_terminal()
|
||||
.and_then(CodexWebSocketCloseError::code)
|
||||
== Some(WEBSOCKET_CLOSE_MESSAGE_TOO_BIG)
|
||||
}
|
||||
|
||||
pub(crate) fn with_connection_observation(
|
||||
self,
|
||||
observation: WebSocketConnectionObservation,
|
||||
@@ -346,6 +362,10 @@ impl CodexWebSocketExchangeError {
|
||||
| Self::ReusedConnectionDiedBeforeFirstEvent {
|
||||
source: Some(source),
|
||||
..
|
||||
}
|
||||
| Self::ContinuationUnavailable {
|
||||
source: Some(source),
|
||||
..
|
||||
} => source.connection_observation(),
|
||||
_ => None,
|
||||
}
|
||||
@@ -362,7 +382,7 @@ impl CodexWebSocketExchangeError {
|
||||
#[must_use]
|
||||
pub fn continuation_unavailable_reason(&self) -> Option<PreviousResponseUnavailableReason> {
|
||||
match self.classified() {
|
||||
Self::ContinuationUnavailable { reason } => Some(*reason),
|
||||
Self::ContinuationUnavailable { reason, .. } => Some(*reason),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ pub(super) async fn next_websocket_message(
|
||||
receive_timeout: Duration,
|
||||
) -> Result<Option<Message>, CodexWebSocketExchangeError> {
|
||||
match timeout(receive_timeout, websocket.next()).await {
|
||||
Ok(message) => message.transpose().map_err(Into::into),
|
||||
Ok(message) => message.transpose(),
|
||||
Err(_) => Err(CodexWebSocketExchangeError::ReceiveIdleTimeout {
|
||||
timeout: receive_timeout,
|
||||
}),
|
||||
|
||||
@@ -6,7 +6,7 @@ use bytes::Bytes;
|
||||
use gateway_core::diagnostics::{TraceContext, diagnostic_json};
|
||||
use gateway_core::engine::response_control::ResponseControl;
|
||||
use serde_json::json;
|
||||
use tokio::sync::{Mutex, mpsc};
|
||||
use tokio::sync::{Mutex, mpsc, oneshot};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use super::super::{
|
||||
@@ -60,7 +60,7 @@ impl StreamWebSocketDiscardReason {
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::transport::websocket) fn stream_websocket_response(
|
||||
pub(in crate::transport::websocket) async fn stream_websocket_response(
|
||||
mut websocket: PumpedWebSocket,
|
||||
metadata: CodexWebSocketConnectionMetadata,
|
||||
pool_return: Option<WebSocketStreamPoolReturn>,
|
||||
@@ -68,7 +68,7 @@ pub(in crate::transport::websocket) fn stream_websocket_response(
|
||||
stream_idle_timeout: Option<Duration>,
|
||||
trace: TraceContext,
|
||||
response_control: Option<ResponseControl>,
|
||||
) -> CodexWebSocketStreamingExchange {
|
||||
) -> Result<CodexWebSocketStreamingExchange, CodexWebSocketExchangeError> {
|
||||
websocket.bind_control(response_control.as_ref());
|
||||
let downstream_cancellation = response_control
|
||||
.as_ref()
|
||||
@@ -83,6 +83,7 @@ pub(in crate::transport::websocket) fn stream_websocket_response(
|
||||
}));
|
||||
let response_metadata_updates_for_task = Arc::clone(&response_metadata_updates);
|
||||
let (tx, rx) = mpsc::channel(WEBSOCKET_STREAM_BUFFER);
|
||||
let (first_reply, size_rejection) = oneshot::channel();
|
||||
let (task_tracker, shutdown) = pool_return
|
||||
.as_ref()
|
||||
.map(|pool_return| pool_return.lease.stream_task_context())
|
||||
@@ -97,6 +98,7 @@ pub(in crate::transport::websocket) fn stream_websocket_response(
|
||||
pool_return,
|
||||
reused_connection,
|
||||
stream_idle_timeout,
|
||||
first_reply: Some(first_reply),
|
||||
delivery: WebSocketStreamDelivery {
|
||||
trace,
|
||||
shutdown,
|
||||
@@ -118,7 +120,11 @@ pub(in crate::transport::websocket) fn stream_websocket_response(
|
||||
rx.recv().await.map(|item| (item, rx))
|
||||
});
|
||||
|
||||
CodexWebSocketStreamingExchange {
|
||||
// 在暴露传输类型前处理上游对当前请求的明确拒绝;首个文本(含内部元数据)即确定 WS
|
||||
if let Ok(error) = size_rejection.await {
|
||||
return Err(error);
|
||||
}
|
||||
Ok(CodexWebSocketStreamingExchange {
|
||||
routing_affinity: response_metadata.routing_affinity,
|
||||
websocket_connection_id,
|
||||
body: Box::pin(body),
|
||||
@@ -131,7 +137,7 @@ pub(in crate::transport::websocket) fn stream_websocket_response(
|
||||
connection_local_continuation: false,
|
||||
diagnostics: response_metadata.diagnostics,
|
||||
response_metadata: response_metadata.response_metadata,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
struct WebSocketStreamForwardState {
|
||||
@@ -142,6 +148,7 @@ struct WebSocketStreamForwardState {
|
||||
stream_idle_timeout: Option<Duration>,
|
||||
rate_limit_updates: CodexWebSocketRateLimitUpdates,
|
||||
response_metadata_updates: CodexWebSocketResponseMetadataUpdates,
|
||||
first_reply: Option<oneshot::Sender<CodexWebSocketExchangeError>>,
|
||||
delivery: WebSocketStreamDelivery,
|
||||
}
|
||||
|
||||
@@ -195,6 +202,7 @@ async fn forward_websocket_response_stream(state: WebSocketStreamForwardState) {
|
||||
stream_idle_timeout,
|
||||
rate_limit_updates,
|
||||
response_metadata_updates,
|
||||
mut first_reply,
|
||||
delivery,
|
||||
} = state;
|
||||
let trace = &delivery.trace;
|
||||
@@ -255,7 +263,10 @@ async fn forward_websocket_response_stream(state: WebSocketStreamForwardState) {
|
||||
break;
|
||||
};
|
||||
let raw = match message {
|
||||
tungstenite::Message::Text(text) => text.to_string(),
|
||||
tungstenite::Message::Text(text) => {
|
||||
first_reply.take();
|
||||
text.to_string()
|
||||
}
|
||||
tungstenite::Message::Binary(bytes) => {
|
||||
trace.capture("upstream.binary", &bytes);
|
||||
let error = CodexWebSocketExchangeError::UnexpectedBinaryEvent;
|
||||
@@ -296,6 +307,12 @@ async fn forward_websocket_response_stream(state: WebSocketStreamForwardState) {
|
||||
)
|
||||
.await;
|
||||
let error = error.with_connection_observation(observation);
|
||||
if error.message_too_big_close()
|
||||
&& let Some(first_reply) = first_reply.take()
|
||||
{
|
||||
let _ = first_reply.send(error);
|
||||
return;
|
||||
}
|
||||
let error = if reused_connection {
|
||||
reused_stream_receive_error(error)
|
||||
} else {
|
||||
|
||||
@@ -8,7 +8,7 @@ use gateway_protocol::openai::events;
|
||||
use tokio::{io::BufWriter, time::timeout};
|
||||
use tokio_tungstenite::{Connector, MaybeTlsStream, client_async_tls_with_config};
|
||||
use tungstenite::{
|
||||
self, Message,
|
||||
self,
|
||||
extensions::{ExtensionsConfig, compression::deflate::DeflateConfig},
|
||||
handshake::client::Request as WsRequest,
|
||||
http::Response as WsResponse,
|
||||
@@ -35,8 +35,6 @@ use super::{
|
||||
pump::{PumpLogContext, PumpedWebSocket, RawWsStream},
|
||||
};
|
||||
|
||||
use super::control::WEBSOCKET_SEND_TIMEOUT;
|
||||
|
||||
const WEBSOCKET_EXTENSIONS: &str = "permessage-deflate; client_max_window_bits";
|
||||
pub(crate) const WEBSOCKET_CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
|
||||
@@ -165,21 +163,6 @@ pub(super) async fn connect_pumped_websocket(
|
||||
Ok((PumpedWebSocket::new(raw, context, proxy_permit), response))
|
||||
}
|
||||
|
||||
pub(super) async fn send_websocket_request(
|
||||
websocket: &PumpedWebSocket,
|
||||
payload_text: &str,
|
||||
) -> Result<(), CodexWebSocketExchangeError> {
|
||||
timeout(
|
||||
WEBSOCKET_SEND_TIMEOUT,
|
||||
websocket.send(Message::Text(payload_text.to_string().into())),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| CodexWebSocketExchangeError::SendTimeout {
|
||||
timeout: WEBSOCKET_SEND_TIMEOUT,
|
||||
})??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn websocket_connection_metadata(
|
||||
response: &WsResponse<Option<Vec<u8>>>,
|
||||
connection: &CodexWebSocketConnection,
|
||||
|
||||
@@ -11,6 +11,7 @@ mod live;
|
||||
mod model;
|
||||
mod pool;
|
||||
mod pump;
|
||||
mod upload;
|
||||
|
||||
pub use self::{
|
||||
audit::{
|
||||
|
||||
@@ -24,6 +24,7 @@ pub struct CodexWebSocketPoolKey {
|
||||
account_id: String,
|
||||
conversation_id: String,
|
||||
connection_profile: String,
|
||||
response_exclusions: Vec<String>,
|
||||
installation_id: Option<String>,
|
||||
routing_affinity_id: Option<Uuid>,
|
||||
fedramp_routing: bool,
|
||||
@@ -44,6 +45,7 @@ impl CodexWebSocketPoolKey {
|
||||
account_id: account_id.into(),
|
||||
conversation_id: conversation_id.into(),
|
||||
connection_profile: String::new(),
|
||||
response_exclusions: Vec::new(),
|
||||
installation_id: None,
|
||||
routing_affinity_id: None,
|
||||
fedramp_routing: false,
|
||||
@@ -65,6 +67,16 @@ impl CodexWebSocketPoolKey {
|
||||
self
|
||||
}
|
||||
|
||||
/// 上游只在握手时读取响应排除项,精确续接也必须匹配最终发出的头值
|
||||
pub(crate) fn with_response_exclusions(mut self, opening_headers: &[(String, String)]) -> Self {
|
||||
self.response_exclusions = opening_headers
|
||||
.iter()
|
||||
.filter(|(name, _)| name.eq_ignore_ascii_case("x-codex-exclude"))
|
||||
.map(|(_, value)| value.clone())
|
||||
.collect();
|
||||
self
|
||||
}
|
||||
|
||||
/// 隔离同一逻辑会话中由不同下游 WebSocket 驱动的并发响应链
|
||||
pub(crate) fn with_downstream_connection_id(
|
||||
mut self,
|
||||
@@ -111,7 +123,7 @@ impl CodexWebSocketPoolKey {
|
||||
.routing_affinity_id
|
||||
.map(|id| id.to_string())
|
||||
.unwrap_or_default();
|
||||
short_sha256([
|
||||
let parts = [
|
||||
self.base_url.as_str(),
|
||||
self.account_id.as_str(),
|
||||
self.conversation_id.as_str(),
|
||||
@@ -121,7 +133,12 @@ impl CodexWebSocketPoolKey {
|
||||
self.downstream_connection_id.as_str(),
|
||||
self.egress_key.as_str(),
|
||||
routing_affinity.as_str(),
|
||||
])
|
||||
];
|
||||
short_sha256(
|
||||
parts
|
||||
.into_iter()
|
||||
.chain(self.response_exclusions.iter().map(String::as_str)),
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn same_logical_connection(&self, other: &Self) -> bool {
|
||||
@@ -132,6 +149,7 @@ impl CodexWebSocketPoolKey {
|
||||
&& self.egress_key == other.egress_key
|
||||
&& self.routing_affinity_id == other.routing_affinity_id
|
||||
&& self.fedramp_routing == other.fedramp_routing
|
||||
&& self.response_exclusions == other.response_exclusions
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,18 +11,17 @@ use std::sync::{
|
||||
};
|
||||
use std::time::Duration;
|
||||
|
||||
use bytes::Bytes;
|
||||
use futures::{Sink, SinkExt, Stream, StreamExt};
|
||||
use tokio::{sync::mpsc, task::JoinHandle, time::Instant};
|
||||
use tungstenite::{
|
||||
Message,
|
||||
protocol::frame::{Fragment, Frame, coding::Data},
|
||||
};
|
||||
use tungstenite::Message;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{
|
||||
CodexWebSocketCloseError, CodexWebSocketExchangeError,
|
||||
control::{PumpCommand, PumpControl, SharedMessages, send_message},
|
||||
control::{
|
||||
PumpCommand, PumpControl, SharedMessages, UploadOutcome, WEBSOCKET_SEND_TIMEOUT,
|
||||
send_message,
|
||||
},
|
||||
};
|
||||
|
||||
/// 底层 tungstenite WebSocket 流
|
||||
@@ -98,6 +97,20 @@ pub(crate) enum PumpExitReason {
|
||||
}
|
||||
|
||||
impl PumpExitReason {
|
||||
pub(super) fn from_close(message: &Message) -> Option<Self> {
|
||||
let Message::Close(frame) = message else {
|
||||
return None;
|
||||
};
|
||||
Some(Self::UpstreamCloseFrame {
|
||||
close: frame.as_ref().map(|frame| {
|
||||
CodexWebSocketCloseError::new(
|
||||
Some(u16::from(frame.code)),
|
||||
Some(frame.reason.to_string()),
|
||||
)
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
Self::CommandChannelClosed => "command_channel_closed",
|
||||
@@ -180,7 +193,7 @@ impl PumpExitReason {
|
||||
}
|
||||
|
||||
struct PendingInbound {
|
||||
item: Result<Message, tungstenite::Error>,
|
||||
item: Result<Message, CodexWebSocketExchangeError>,
|
||||
exit_reason: Option<PumpExitReason>,
|
||||
}
|
||||
|
||||
@@ -323,6 +336,35 @@ impl PumpedWebSocket {
|
||||
send_message(&self.tx_command, message).await
|
||||
}
|
||||
|
||||
pub(super) async fn upload(
|
||||
&self,
|
||||
text: tungstenite::Utf8Bytes,
|
||||
) -> Result<UploadOutcome, CodexWebSocketExchangeError> {
|
||||
let deadline = Instant::now() + WEBSOCKET_SEND_TIMEOUT;
|
||||
let (accepted, admission) = tokio::sync::oneshot::channel();
|
||||
let result = tokio::time::timeout_at(deadline, async {
|
||||
self.tx_command
|
||||
.send(PumpCommand::Upload {
|
||||
text,
|
||||
deadline,
|
||||
accepted,
|
||||
})
|
||||
.await
|
||||
.map_err(|_| CodexWebSocketExchangeError::SendNotStarted)?;
|
||||
admission
|
||||
.await
|
||||
.map_err(|_| CodexWebSocketExchangeError::SendNotStarted)
|
||||
})
|
||||
.await
|
||||
.map_err(|_| CodexWebSocketExchangeError::SendTimeout {
|
||||
timeout: WEBSOCKET_SEND_TIMEOUT,
|
||||
})??;
|
||||
// 接单后由 pump 执行同一截止时间,调用方不能先超时并丢弃已经读到的上游回复
|
||||
result
|
||||
.await
|
||||
.unwrap_or_else(|_| Err(tungstenite::Error::ConnectionClosed.into()))
|
||||
}
|
||||
|
||||
/// 每轮发送后替换控制 owner,旧执行的弱引用不能控制下一轮连接
|
||||
pub(crate) fn bind_control(&mut self, control: Option<&ResponseControl>) {
|
||||
self.revoke_control();
|
||||
@@ -348,7 +390,7 @@ impl PumpedWebSocket {
|
||||
/// 取出下一帧入站消息(`Ping`/`Pong` 已被 pump 处理,不会到达这里)
|
||||
///
|
||||
/// 返回 `None` 表示连接已结束(pump 已退出且缓冲已排空)
|
||||
pub(crate) async fn next(&mut self) -> Option<Result<Message, tungstenite::Error>> {
|
||||
pub(crate) async fn next(&mut self) -> Option<Result<Message, CodexWebSocketExchangeError>> {
|
||||
self.rx_message.lock().await.recv().await
|
||||
}
|
||||
|
||||
@@ -407,7 +449,7 @@ async fn pump_loop(
|
||||
connection_id: Uuid,
|
||||
mut inner: PumpSocket,
|
||||
mut rx_command: mpsc::Receiver<PumpCommand>,
|
||||
tx_message: mpsc::Sender<Result<Message, tungstenite::Error>>,
|
||||
tx_message: mpsc::Sender<Result<Message, CodexWebSocketExchangeError>>,
|
||||
context: PumpLogContext,
|
||||
closed: Arc<AtomicBool>,
|
||||
lifecycle: Arc<Mutex<PumpLifecycleState>>,
|
||||
@@ -434,7 +476,7 @@ async fn pump_loop(
|
||||
let Some(command) = command else {
|
||||
break 'pump PumpExitReason::CommandChannelClosed;
|
||||
};
|
||||
if let Some(reason) = handle_command(&mut inner.stream, command, closed.load(Ordering::Acquire)).await {
|
||||
if let Some(reason) = handle_command(&mut inner.stream, command, &tx_message, &mut pending_inbound, &closed, &lifecycle).await {
|
||||
break 'pump reason;
|
||||
}
|
||||
}
|
||||
@@ -447,7 +489,7 @@ async fn pump_loop(
|
||||
let Some(command) = command else {
|
||||
break 'pump PumpExitReason::CommandChannelClosed;
|
||||
};
|
||||
if let Some(reason) = handle_command(&mut inner.stream, command, closed.load(Ordering::Acquire)).await {
|
||||
if let Some(reason) = handle_command(&mut inner.stream, command, &tx_message, &mut pending_inbound, &closed, &lifecycle).await {
|
||||
break 'pump reason;
|
||||
}
|
||||
}
|
||||
@@ -493,17 +535,7 @@ async fn pump_loop(
|
||||
}
|
||||
Message::Pong(_) => {}
|
||||
message => {
|
||||
let terminal_reason = match &message {
|
||||
Message::Close(frame) => Some(PumpExitReason::UpstreamCloseFrame {
|
||||
close: frame.as_ref().map(|frame| {
|
||||
CodexWebSocketCloseError::new(
|
||||
Some(u16::from(frame.code)),
|
||||
Some(frame.reason.to_string()),
|
||||
)
|
||||
}),
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
let terminal_reason = PumpExitReason::from_close(&message);
|
||||
if let Some(reason) = &terminal_reason {
|
||||
record_closed(&closed, &lifecycle, reason);
|
||||
}
|
||||
@@ -534,7 +566,7 @@ async fn pump_loop(
|
||||
connection_id,
|
||||
&mut backpressure_events,
|
||||
PendingInbound {
|
||||
item: Err(err),
|
||||
item: Err(err.into()),
|
||||
exit_reason: Some(terminal_reason),
|
||||
},
|
||||
) {
|
||||
@@ -549,8 +581,10 @@ async fn pump_loop(
|
||||
record_closed(&closed, &lifecycle, &reason);
|
||||
// 排队命令尚未进入底层发送,关闭握手前即回绝,避免调用方等待或误判为已发送
|
||||
rx_command.close();
|
||||
while let Ok(PumpCommand::Send { ack, .. }) = rx_command.try_recv() {
|
||||
let _ = ack.send(Err(CodexWebSocketExchangeError::SendNotStarted));
|
||||
while let Ok(command) = rx_command.try_recv() {
|
||||
if let PumpCommand::Send { ack, .. } = command {
|
||||
let _ = ack.send(Err(CodexWebSocketExchangeError::SendNotStarted));
|
||||
}
|
||||
}
|
||||
let observation = {
|
||||
let lifecycle = lifecycle
|
||||
@@ -577,8 +611,8 @@ async fn pump_loop(
|
||||
}
|
||||
|
||||
fn enqueue_inbound(
|
||||
tx_message: &mpsc::Sender<Result<Message, tungstenite::Error>>,
|
||||
pending_inbound: &mut Option<Result<Message, tungstenite::Error>>,
|
||||
tx_message: &mpsc::Sender<Result<Message, CodexWebSocketExchangeError>>,
|
||||
pending_inbound: &mut Option<Result<Message, CodexWebSocketExchangeError>>,
|
||||
connection_id: Uuid,
|
||||
backpressure_events: &mut u64,
|
||||
inbound: PendingInbound,
|
||||
@@ -605,14 +639,72 @@ fn enqueue_inbound(
|
||||
async fn handle_command(
|
||||
inner: &mut RawWsStream,
|
||||
command: PumpCommand,
|
||||
closed: bool,
|
||||
messages: &mpsc::Sender<Result<Message, CodexWebSocketExchangeError>>,
|
||||
pending: &mut Option<Result<Message, CodexWebSocketExchangeError>>,
|
||||
closed: &AtomicBool,
|
||||
lifecycle: &Mutex<PumpLifecycleState>,
|
||||
) -> Option<PumpExitReason> {
|
||||
let PumpCommand::Send { message, ack } = command;
|
||||
let (message, ack) = match command {
|
||||
PumpCommand::Send { message, ack } => (message, ack),
|
||||
PumpCommand::Upload {
|
||||
text,
|
||||
deadline,
|
||||
accepted,
|
||||
} => {
|
||||
let (ack, result) = tokio::sync::oneshot::channel();
|
||||
if closed.load(Ordering::Acquire)
|
||||
|| Instant::now() >= deadline
|
||||
|| accepted.send(result).is_err()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut upload = super::upload::Upload::new(messages, pending.is_some());
|
||||
let write = tokio::time::timeout_at(deadline, upload.send(inner, text)).await;
|
||||
if let Some(activity) = upload.last_activity {
|
||||
record_activity(lifecycle, activity);
|
||||
}
|
||||
let (error, metric_reason) = match write {
|
||||
Ok(Ok(())) => {
|
||||
let _ = ack.send(Ok(UploadOutcome::Flushed));
|
||||
return None;
|
||||
}
|
||||
Ok(Err(error)) => {
|
||||
let reason = transport_metric_reason(&error);
|
||||
(CodexWebSocketExchangeError::Transport(error), reason)
|
||||
}
|
||||
Err(_) => (
|
||||
CodexWebSocketExchangeError::SendTimeout {
|
||||
timeout: WEBSOCKET_SEND_TIMEOUT,
|
||||
},
|
||||
"send_timeout",
|
||||
),
|
||||
};
|
||||
let reason = upload
|
||||
.close
|
||||
.unwrap_or_else(|| PumpExitReason::OutboundTransportError {
|
||||
message: error.to_string(),
|
||||
metric_reason,
|
||||
});
|
||||
record_closed(closed, lifecycle, &reason);
|
||||
let result = if !upload.started {
|
||||
Err(CodexWebSocketExchangeError::SendNotStarted)
|
||||
} else if upload.received_reply {
|
||||
if !matches!(reason, PumpExitReason::UpstreamCloseFrame { .. }) {
|
||||
*pending = Some(Err(error));
|
||||
}
|
||||
Ok(UploadOutcome::InterruptedWithReply)
|
||||
} else {
|
||||
Err(error)
|
||||
};
|
||||
let _ = ack.send(result);
|
||||
return Some(reason);
|
||||
}
|
||||
};
|
||||
// 发送超时或取消后,尚在队列里的业务帧不应继续打到上游
|
||||
if ack.is_closed() {
|
||||
return None;
|
||||
}
|
||||
if closed {
|
||||
if closed.load(Ordering::Acquire) {
|
||||
let _ = ack.send(Err(CodexWebSocketExchangeError::SendNotStarted));
|
||||
return None;
|
||||
}
|
||||
@@ -638,22 +730,13 @@ async fn write_message(
|
||||
inner: &mut RawWsStream,
|
||||
message: Message,
|
||||
) -> Result<(), tungstenite::Error> {
|
||||
const FRAGMENT_BYTES: usize = 1024 * 1024;
|
||||
let mut remaining = match message {
|
||||
Message::Text(text) if text.len() > FRAGMENT_BYTES => Bytes::from(text),
|
||||
other => return inner.send(other).await,
|
||||
};
|
||||
let mut opcode = Data::Text;
|
||||
while !remaining.is_empty() {
|
||||
let payload = remaining.split_to(remaining.len().min(FRAGMENT_BYTES));
|
||||
let fragment = if remaining.is_empty() {
|
||||
Fragment::Final
|
||||
} else {
|
||||
Fragment::More
|
||||
};
|
||||
let frame = Frame::message_fragment(payload, opcode, fragment);
|
||||
inner.send(Message::Frame(frame)).await?;
|
||||
opcode = Data::Continue;
|
||||
match message {
|
||||
Message::Text(text) => {
|
||||
for frame in super::upload::text_frames(text) {
|
||||
inner.send(frame).await?;
|
||||
}
|
||||
}
|
||||
other => inner.send(other).await?,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
//! 上传 response.create 时同时驱动读写,保留与本次上传有关的上游回复
|
||||
|
||||
use std::{
|
||||
future::poll_fn,
|
||||
task::{Context, Poll, ready},
|
||||
};
|
||||
|
||||
use bytes::Bytes;
|
||||
use futures::{SinkExt, StreamExt};
|
||||
use tokio::{sync::mpsc, time::Instant};
|
||||
use tungstenite::{
|
||||
Error, Message, Utf8Bytes,
|
||||
protocol::frame::{Fragment, Frame, coding::Data},
|
||||
};
|
||||
|
||||
use super::{
|
||||
CodexWebSocketExchangeError,
|
||||
pump::{PumpExitReason, RawWsStream},
|
||||
};
|
||||
|
||||
const FRAGMENT_BYTES: usize = 1024 * 1024;
|
||||
const READ_AHEAD_BYTES: usize = 1024 * 1024;
|
||||
const READ_BATCH: usize = 32;
|
||||
|
||||
pub(super) fn text_frames(text: Utf8Bytes) -> impl Iterator<Item = Message> {
|
||||
let (single, mut remaining) = if text.len() <= FRAGMENT_BYTES {
|
||||
(Some(Message::Text(text)), Bytes::new())
|
||||
} else {
|
||||
(None, Bytes::from(text))
|
||||
};
|
||||
let mut opcode = Data::Text;
|
||||
single.into_iter().chain(std::iter::from_fn(move || {
|
||||
if remaining.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let payload = remaining.split_to(remaining.len().min(FRAGMENT_BYTES));
|
||||
let fragment = if remaining.is_empty() {
|
||||
Fragment::Final
|
||||
} else {
|
||||
Fragment::More
|
||||
};
|
||||
let frame = Frame::message_fragment(payload, opcode, fragment);
|
||||
opcode = Data::Continue;
|
||||
Some(Message::Frame(frame))
|
||||
}))
|
||||
}
|
||||
|
||||
pub(super) struct Upload<'a> {
|
||||
messages: &'a mpsc::Sender<Result<Message, CodexWebSocketExchangeError>>,
|
||||
budget: usize,
|
||||
pub(super) last_activity: Option<Instant>,
|
||||
pub(super) started: bool,
|
||||
pub(super) received_reply: bool,
|
||||
pub(super) close: Option<PumpExitReason>,
|
||||
queued_pongs: usize,
|
||||
}
|
||||
|
||||
impl<'a> Upload<'a> {
|
||||
pub(super) fn new(
|
||||
messages: &'a mpsc::Sender<Result<Message, CodexWebSocketExchangeError>>,
|
||||
backpressured: bool,
|
||||
) -> Self {
|
||||
Self {
|
||||
messages,
|
||||
budget: if backpressured { 0 } else { READ_AHEAD_BYTES },
|
||||
last_activity: None,
|
||||
started: false,
|
||||
received_reply: false,
|
||||
close: None,
|
||||
queued_pongs: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_incoming(
|
||||
&mut self,
|
||||
socket: &mut RawWsStream,
|
||||
cx: &mut Context<'_>,
|
||||
recovering: bool,
|
||||
) -> Poll<Result<(), Error>> {
|
||||
if !recovering && self.queued_pongs > 0 && socket.poll_flush_unpin(cx)?.is_ready() {
|
||||
self.queued_pongs = 0;
|
||||
}
|
||||
for _ in 0..READ_BATCH {
|
||||
if self.budget == 0 || self.messages.capacity() == 0 {
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
if !recovering && self.queued_pongs >= READ_BATCH {
|
||||
return Poll::Pending;
|
||||
}
|
||||
let next = socket.poll_next_unpin(cx);
|
||||
if recovering && next.is_pending() {
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
let message = ready!(next).transpose()?.ok_or(Error::ConnectionClosed)?;
|
||||
if !matches!(message, Message::Close(_)) {
|
||||
self.last_activity = Some(Instant::now());
|
||||
}
|
||||
if recovering || !matches!(message, Message::Ping(_) | Message::Pong(_)) {
|
||||
self.budget = self
|
||||
.budget
|
||||
.saturating_sub(message.len() + size_of::<Message>());
|
||||
}
|
||||
match message {
|
||||
Message::Ping(_) => {
|
||||
// tungstenite 已排入自动 Pong,在下一个数据分片前驱动控制帧写出
|
||||
match socket.poll_flush_unpin(cx) {
|
||||
Poll::Ready(Ok(())) => self.queued_pongs = 0,
|
||||
Poll::Ready(Err(error)) if !recovering => return Poll::Ready(Err(error)),
|
||||
_ => self.queued_pongs += 1,
|
||||
}
|
||||
}
|
||||
Message::Pong(_) => {}
|
||||
message => {
|
||||
self.close = PumpExitReason::from_close(&message);
|
||||
// pump 是唯一生产方;读帧前已经确认有队列容量
|
||||
self.messages
|
||||
.try_send(Ok(message))
|
||||
.map_err(|_| Error::ConnectionClosed)?;
|
||||
self.received_reply |= self.started;
|
||||
if self.close.is_some() {
|
||||
return Poll::Ready(Err(Error::ConnectionClosed));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
cx.waker().wake_by_ref();
|
||||
Poll::Pending
|
||||
}
|
||||
|
||||
pub(super) async fn send(
|
||||
&mut self,
|
||||
socket: &mut RawWsStream,
|
||||
text: Utf8Bytes,
|
||||
) -> Result<(), Error> {
|
||||
for frame in text_frames(text) {
|
||||
let mut frame = Some(frame);
|
||||
let mut first_poll = true;
|
||||
let result = poll_fn(|cx| {
|
||||
let read_first = std::mem::take(&mut first_poll);
|
||||
if read_first {
|
||||
let _ = self.poll_incoming(socket, cx, false)?;
|
||||
}
|
||||
let write = (|| {
|
||||
if frame.is_some() {
|
||||
ready!(socket.poll_ready_unpin(cx))?;
|
||||
}
|
||||
if let Some(frame) = frame.take() {
|
||||
let result = socket.start_send_unpin(frame);
|
||||
// I/O 错误可能发生在首帧头已部分写出之后
|
||||
self.started |= matches!(result, Ok(()) | Err(Error::Io(_)));
|
||||
result?;
|
||||
}
|
||||
socket.poll_flush_unpin(cx)
|
||||
})();
|
||||
if !read_first && write.is_pending() {
|
||||
let _ = self.poll_incoming(socket, cx, false)?;
|
||||
}
|
||||
write
|
||||
})
|
||||
.await;
|
||||
if let Err(error) = result {
|
||||
if self.started && !matches!(error, Error::ConnectionClosed) {
|
||||
// 只取已就绪的回复,不能为了等待假设的 Close 延长写入期限
|
||||
let _ = poll_fn(|cx| self.poll_incoming(socket, cx, true)).await;
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1093,6 +1093,7 @@ async fn api_key_import_export_preserves_target_without_oauth_exchange() {
|
||||
.into_accounts()
|
||||
.pop()
|
||||
.unwrap();
|
||||
assert_eq!(restored.account.name(), "relay");
|
||||
let CodexCredentialData::ApiKey(data) =
|
||||
CodexCredentialCodec::decode_complete(&restored.credential).unwrap()
|
||||
else {
|
||||
@@ -1127,6 +1128,7 @@ async fn messages_api_key_import_export_preserves_protocol_and_rejects_websocket
|
||||
.into_accounts()
|
||||
.pop()
|
||||
.unwrap();
|
||||
assert_eq!(imported.account.name(), "密钥账号");
|
||||
let now = Utc::now();
|
||||
let exported = CodexCredentialAdmin
|
||||
.format_cpr_export(vec![ExportManagedCodexCredential {
|
||||
|
||||
@@ -273,6 +273,104 @@ async fn image_model_access_overrides_existing_session_affinity() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn strict_session_images_borrow_within_group_and_account_model_access() {
|
||||
use gateway_core::routing::{AccountGroupId, RoutingGroupSnapshot};
|
||||
|
||||
const TEXT_ONLY: &str = "acct_text_only";
|
||||
let chat = AccountGroupId::new("grp_00000000000000000000000000000001").unwrap();
|
||||
let mixed = AccountGroupId::new("grp_00000000000000000000000000000002").unwrap();
|
||||
let openai = ProviderKind::new("openai").unwrap();
|
||||
let deny_image = policy(AccountModelAccessMode::Denylist, "gpt-image-2");
|
||||
let accounts = [
|
||||
(CPA_ACCOUNT, &chat, AccountModelAccess::all()),
|
||||
(TEXT_ONLY, &mixed, deny_image.clone()),
|
||||
(IMAGE_ACCOUNT, &mixed, AccountModelAccess::all()),
|
||||
]
|
||||
.map(|(id, group, access)| {
|
||||
(
|
||||
ProviderAccountId::new(id).unwrap(),
|
||||
RuntimeAccount::new(openai.clone(), [group.clone()].into()).with_model_access(access),
|
||||
)
|
||||
});
|
||||
let scope = Arc::new(FrozenAccountScope::new(
|
||||
Arc::new(
|
||||
RuntimeAccountDirectory::new(accounts.into())
|
||||
.with_group_model_access([(chat.clone(), deny_image)].into()),
|
||||
),
|
||||
ClientRoutingScope::restricted(
|
||||
vec![
|
||||
RoutingGroupSnapshot::new(chat.clone(), "Chat".into()),
|
||||
RoutingGroupSnapshot::new(mixed.clone(), "Mixed".into()),
|
||||
],
|
||||
[chat, mixed].into(),
|
||||
[openai].into(),
|
||||
)
|
||||
.unwrap(),
|
||||
));
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/codex/responses"))
|
||||
.and(header(
|
||||
"chatgpt-account-id",
|
||||
format!("chatgpt-{CPA_ACCOUNT}"),
|
||||
))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200).set_body_raw(CAPTURE_COMPLETED_SSE, "text/event-stream"),
|
||||
)
|
||||
.expect(3)
|
||||
.mount(&server)
|
||||
.await;
|
||||
for endpoint in ["/codex/images/generations", "/codex/images/edits"] {
|
||||
Mock::given(method("POST"))
|
||||
.and(path(endpoint))
|
||||
.and(header(
|
||||
"chatgpt-account-id",
|
||||
format!("chatgpt-{IMAGE_ACCOUNT}"),
|
||||
))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"data":[]})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
}
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
create_account(&store, CPA_ACCOUNT).await;
|
||||
let provider = provider_with_base_url(&store, server.uri());
|
||||
let send = async |request| {
|
||||
let mut stream = provider
|
||||
.clone()
|
||||
.execute(
|
||||
request,
|
||||
attempt(
|
||||
AccountAttemptContext::new(BTreeSet::new(), None, None)
|
||||
.with_account_scope(scope.clone()),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
while let Some(event) = stream.next().await {
|
||||
event.unwrap();
|
||||
}
|
||||
};
|
||||
let text = |turn| planned_request("openai", super::session_binding::turn_request("root", turn));
|
||||
send(text("first")).await;
|
||||
create_account(&store, TEXT_ONLY).await;
|
||||
create_account(&store, IMAGE_ACCOUNT).await;
|
||||
store.set_scheduling(TEXT_ONLY, None, AccountWeight::new(100).unwrap());
|
||||
let generation = image_operation(
|
||||
ImageRequestKind::Generation,
|
||||
br#"{"session_id":"root","model":"gpt-image-2","prompt":"draw"}"#,
|
||||
);
|
||||
let edit = image_operation(
|
||||
ImageRequestKind::Edit,
|
||||
br#"{"session_id":"root","thread_id":"child","model":"gpt-image-2","prompt":"edit"}"#,
|
||||
);
|
||||
for (image, next_turn) in [(generation, "after-generation"), (edit, "after-edit")] {
|
||||
send(planned_provider_endpoint_request("openai", image)).await;
|
||||
send(text(next_turn)).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn final_image_model_after_middleware_must_be_allowed_by_the_selected_account() {
|
||||
let server = MockServer::start().await;
|
||||
|
||||
@@ -4023,7 +4023,7 @@ async fn repeated_message_too_big_closes_keep_session_on_websocket() {
|
||||
listener.local_addr().expect("listener address")
|
||||
);
|
||||
let server = tokio::spawn(async move {
|
||||
for _ in 0..3 {
|
||||
for index in 0..3 {
|
||||
let (stream, _) = listener
|
||||
.accept()
|
||||
.await
|
||||
@@ -4034,31 +4034,28 @@ async fn repeated_message_too_big_closes_keep_session_on_websocket() {
|
||||
.await
|
||||
.expect("WebSocket request")
|
||||
.expect("valid WebSocket request");
|
||||
let prelude = if index == 0 {
|
||||
json!({"type": "codex.rate_limits"})
|
||||
} else {
|
||||
json!({"type": "response.created", "response": {
|
||||
"id": "resp_before_committed_close", "model": "gpt-5.4"
|
||||
}})
|
||||
};
|
||||
websocket
|
||||
.send(Message::Text(
|
||||
json!({
|
||||
"type": "response.created",
|
||||
"response": {
|
||||
"id": "resp_before_committed_close",
|
||||
"model": "gpt-5.4"
|
||||
}
|
||||
})
|
||||
.to_string()
|
||||
.into(),
|
||||
))
|
||||
.send(Message::text(prelude.to_string()))
|
||||
.await
|
||||
.expect("start WebSocket response");
|
||||
websocket
|
||||
.send(Message::Text(
|
||||
json!({
|
||||
"type": "response.output_text.delta",
|
||||
"delta": "partial output"
|
||||
})
|
||||
.to_string()
|
||||
.into(),
|
||||
))
|
||||
.await
|
||||
.expect("send semantic WebSocket event");
|
||||
.unwrap();
|
||||
if index == 2 {
|
||||
websocket
|
||||
.send(Message::text(
|
||||
json!({
|
||||
"type": "response.output_text.delta", "delta": "partial output"
|
||||
})
|
||||
.to_string(),
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
websocket
|
||||
.close(Some(CloseFrame {
|
||||
code: CloseCode::Size,
|
||||
@@ -5312,6 +5309,15 @@ async fn websocket_upgrade_required_immediately_enables_session_http_fallback()
|
||||
|
||||
#[tokio::test]
|
||||
async fn advertised_size_fallback_preserves_next_request_websocket_for_all_credentials() {
|
||||
check_request_size_fallback(true).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn early_size_close_preserves_next_request_websocket_for_all_credentials() {
|
||||
check_request_size_fallback(false).await;
|
||||
}
|
||||
|
||||
async fn check_request_size_fallback(advertised: bool) {
|
||||
for api_key in [false, true] {
|
||||
for downstream_websocket in [false, true] {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
@@ -5320,13 +5326,31 @@ async fn advertised_size_fallback_preserves_next_request_websocket_for_all_crede
|
||||
let (socket, _) = listener.accept().await.unwrap();
|
||||
let mut websocket =
|
||||
crate::transport::accept_codex_test_websocket_with(socket, |_, response| {
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("x-codex-websocket-max-message-bytes", "1".parse().unwrap());
|
||||
if advertised {
|
||||
response.headers_mut().insert(
|
||||
"x-codex-websocket-max-message-bytes",
|
||||
"1".parse().unwrap(),
|
||||
);
|
||||
}
|
||||
})
|
||||
.await;
|
||||
while let Some(Ok(message)) = websocket.next().await {
|
||||
assert!(!message.is_text(), "size fallback must precede upload");
|
||||
if advertised {
|
||||
while let Some(Ok(message)) = websocket.next().await {
|
||||
assert!(!message.is_text(), "advertised limit must precede upload");
|
||||
}
|
||||
} else {
|
||||
assert!(websocket.next().await.unwrap().unwrap().is_text());
|
||||
// 慢上传可以超过发送前建连预算,上游明确拒绝后仍应完成本次 HTTP 恢复
|
||||
tokio::time::pause();
|
||||
tokio::time::advance(Duration::from_secs(31)).await;
|
||||
tokio::time::resume();
|
||||
websocket
|
||||
.close(Some(CloseFrame {
|
||||
code: CloseCode::Size,
|
||||
reason: "too large".into(),
|
||||
}))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let (mut http, _) = listener.accept().await.unwrap();
|
||||
let request = crate::transport::read_http_request_with_body(&mut http).await;
|
||||
@@ -5383,6 +5407,26 @@ async fn advertised_size_fallback_preserves_next_request_websocket_for_all_crede
|
||||
json!(format!("ws_size_{index}")),
|
||||
)]));
|
||||
}
|
||||
let request_context = RequestAttemptContext::new(
|
||||
ModelRequestId::new(format!("req_size_{index}")).unwrap(),
|
||||
ClientApiKeyId::new("key_openai_contract").unwrap(),
|
||||
)
|
||||
.with_request_location(Some(global_request_location()))
|
||||
.with_connection_budget(
|
||||
gateway_core::engine::connection::ConnectionBudget::with_clock(|| {
|
||||
tokio::time::Instant::now().into_std()
|
||||
}),
|
||||
);
|
||||
let context = AttemptContext::new(
|
||||
request_context,
|
||||
NonZeroU32::MIN,
|
||||
SystemTime::now() + Duration::from_secs(120),
|
||||
account_policy(),
|
||||
AccountAttemptContext::new(BTreeSet::new(), None, None)
|
||||
.with_account_scope(contract_account_scope()),
|
||||
None,
|
||||
CancellationToken::new(),
|
||||
);
|
||||
let mut stream = Arc::clone(&provider)
|
||||
.execute(
|
||||
planned_request(
|
||||
@@ -5411,7 +5455,7 @@ async fn advertised_size_fallback_preserves_next_request_websocket_for_all_crede
|
||||
),
|
||||
),
|
||||
),
|
||||
context(&format!("req_size_{index}"), CancellationToken::new()),
|
||||
context,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -5433,17 +5477,25 @@ async fn advertised_size_fallback_preserves_next_request_websocket_for_all_crede
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn advertised_size_limit_on_reused_connection_requests_client_replay_before_send() {
|
||||
async fn size_rejection_on_reused_connection_requests_client_replay() {
|
||||
for advertised in [true, false] {
|
||||
check_oversized_continuation(advertised).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn check_oversized_continuation(advertised: bool) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let base_url = format!("http://{}", listener.local_addr().unwrap());
|
||||
let server = tokio::spawn(async move {
|
||||
let (socket, _) = listener.accept().await.unwrap();
|
||||
let mut websocket =
|
||||
crate::transport::accept_codex_test_websocket_with(socket, |_, response| {
|
||||
response.headers_mut().insert(
|
||||
"x-codex-websocket-max-message-bytes",
|
||||
"2048".parse().unwrap(),
|
||||
);
|
||||
if advertised {
|
||||
response.headers_mut().insert(
|
||||
"x-codex-websocket-max-message-bytes",
|
||||
"2048".parse().unwrap(),
|
||||
);
|
||||
}
|
||||
})
|
||||
.await;
|
||||
assert!(websocket.next().await.unwrap().unwrap().is_text());
|
||||
@@ -5453,11 +5505,19 @@ async fn advertised_size_limit_on_reused_connection_requests_client_replay_befor
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
while let Some(Ok(message)) = websocket.next().await {
|
||||
assert!(
|
||||
!message.is_text(),
|
||||
"oversized continuation must not be uploaded"
|
||||
);
|
||||
if advertised {
|
||||
while let Some(Ok(message)) = websocket.next().await {
|
||||
assert!(!message.is_text(), "advertised limit must precede upload");
|
||||
}
|
||||
} else {
|
||||
assert!(websocket.next().await.unwrap().unwrap().is_text());
|
||||
websocket
|
||||
.close(Some(CloseFrame {
|
||||
code: CloseCode::Size,
|
||||
reason: "too large".into(),
|
||||
}))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(100), listener.accept())
|
||||
@@ -5542,7 +5602,14 @@ async fn advertised_size_limit_on_reused_connection_requests_client_replay_befor
|
||||
error.kind(),
|
||||
ProviderErrorKind::ContinuationRecoveryRequired
|
||||
);
|
||||
assert_eq!(error.send_state(), UpstreamSendState::NotSent);
|
||||
assert_eq!(
|
||||
error.send_state(),
|
||||
if advertised {
|
||||
UpstreamSendState::NotSent
|
||||
} else {
|
||||
UpstreamSendState::Ambiguous
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
error.continuation_unavailable_reason(),
|
||||
Some("transport_payload_too_large")
|
||||
@@ -5556,7 +5623,13 @@ async fn advertised_size_limit_on_reused_connection_requests_client_replay_befor
|
||||
Some("previous_response_not_found")
|
||||
);
|
||||
assert!(error.upstream_status().is_none());
|
||||
assert!(error.raw_upstream_error().is_none());
|
||||
if advertised {
|
||||
assert!(error.raw_upstream_error().is_none());
|
||||
} else {
|
||||
let close: Value =
|
||||
serde_json::from_str(error.raw_upstream_error().unwrap().as_str()).unwrap();
|
||||
assert_eq!(close["code"], 1009);
|
||||
}
|
||||
assert!(!error.allows_pre_delivery_retry());
|
||||
drop(continuation);
|
||||
server.await.unwrap();
|
||||
@@ -13463,10 +13536,12 @@ async fn downstream_client_markers_preserve_instruction_content() {
|
||||
)]);
|
||||
let sent = capture_client_request(body.clone(), context, api_key).await;
|
||||
let mut expected = body;
|
||||
expected.insert(
|
||||
"request_country".to_owned(),
|
||||
json!(global_request_location().country),
|
||||
);
|
||||
if !api_key {
|
||||
expected.insert(
|
||||
"request_country".to_owned(),
|
||||
json!(global_request_location().country),
|
||||
);
|
||||
}
|
||||
assert_eq!(sent, expected);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,8 +53,7 @@ async fn responses_options_follow_the_selected_upstream_on_both_transports() {
|
||||
"model": "gpt-5.4", "input": "hello",
|
||||
"max_output_tokens": 1, "max_completion_tokens": 32, "max_tokens": 64,
|
||||
"stream_options": {"include_usage": true, "reasoning_summary_delivery": "sequential_cutoff"},
|
||||
"request_country": "US",
|
||||
"client_metadata": {"user": "keep", "request_country": "US"},
|
||||
"client_metadata": {"user": "keep"},
|
||||
"tools": [{"type": "function", "name": "sample", "parameters": {
|
||||
"type": "object", "properties": {"top_p": {"type": "number"}}
|
||||
}}]
|
||||
@@ -86,102 +85,86 @@ async fn responses_options_follow_the_selected_upstream_on_both_transports() {
|
||||
);
|
||||
}
|
||||
assert_eq!(sent["client_metadata"]["user"], "keep");
|
||||
assert_eq!(sent.get("request_country"), Some(&Value::Null));
|
||||
assert_eq!(sent["client_metadata"]["request_country"], "US");
|
||||
assert_eq!(sent["tools"], body["tools"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn request_country_modes_only_change_the_top_level_across_transports() {
|
||||
async fn request_country_follows_the_selected_account_across_transports() {
|
||||
use OpenAiRequestCountry::{Custom, Default, FollowLocation, Passthrough};
|
||||
for (api_key, websocket, policy, input, expected) in [
|
||||
let location = global_request_location();
|
||||
for (policy, location, input, oauth_country) in [
|
||||
(FollowLocation {}, None, None, Some(Value::Null)),
|
||||
(FollowLocation {}, Some(&location), None, Some(json!("NZ"))),
|
||||
(
|
||||
false,
|
||||
false,
|
||||
Default {},
|
||||
Some(&location),
|
||||
Some(json!("CA")),
|
||||
Some(Value::Null),
|
||||
),
|
||||
(true, true, Default {}, None, Some(Value::Null)),
|
||||
(false, true, Passthrough {}, None, None),
|
||||
(Passthrough {}, Some(&location), None, None),
|
||||
(
|
||||
true,
|
||||
false,
|
||||
Passthrough {},
|
||||
Some(Value::Null),
|
||||
Some(Value::Null),
|
||||
),
|
||||
(
|
||||
false,
|
||||
false,
|
||||
Passthrough {},
|
||||
Some(&location),
|
||||
Some(json!("CA")),
|
||||
Some(json!("CA")),
|
||||
),
|
||||
(
|
||||
true,
|
||||
true,
|
||||
FollowLocation {},
|
||||
Some(json!("CA")),
|
||||
Some(json!("NZ")),
|
||||
),
|
||||
(
|
||||
true,
|
||||
false,
|
||||
Custom {
|
||||
country: "JP".into(),
|
||||
},
|
||||
None,
|
||||
Some(json!("JP")),
|
||||
),
|
||||
(
|
||||
false,
|
||||
true,
|
||||
Custom {
|
||||
country: "JP".into(),
|
||||
},
|
||||
Some(&location),
|
||||
Some(Value::Null),
|
||||
Some(json!("JP")),
|
||||
),
|
||||
] {
|
||||
let location = global_request_location();
|
||||
let mut body = json!({
|
||||
"model": "gpt-5.4",
|
||||
"input": "hello",
|
||||
"client_metadata": {"request_country":"business"},
|
||||
"tools": [{"type":"web_search"}],
|
||||
"model": "gpt-5.4", "input": "hello",
|
||||
"client_metadata": {"request_country": "business"},
|
||||
"tools": [{"type": "web_search"}],
|
||||
});
|
||||
if let Some(input) = input {
|
||||
body["request_country"] = input;
|
||||
if let Some(country) = &input {
|
||||
body["request_country"] = country.clone();
|
||||
}
|
||||
for api_key in [false, true] {
|
||||
let expected = if api_key { &input } else { &oauth_country };
|
||||
for websocket in [false, true] {
|
||||
let sent = capture_downstream_with_country(
|
||||
body.clone(),
|
||||
api_key,
|
||||
websocket,
|
||||
false,
|
||||
location.cloned(),
|
||||
policy.clone(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
sent.get("request_country"),
|
||||
expected.as_ref(),
|
||||
"{policy:?}, api_key={api_key}, websocket={websocket}",
|
||||
);
|
||||
assert_eq!(
|
||||
sent.pointer("/client_metadata/request_country"),
|
||||
body.pointer("/client_metadata/request_country"),
|
||||
);
|
||||
assert_eq!(
|
||||
sent.pointer("/tools/0/user_location/country")
|
||||
.and_then(Value::as_str),
|
||||
location.map(|location| location.country.as_str()),
|
||||
);
|
||||
assert_eq!(
|
||||
sent.pointer("/tools/0/user_location/city")
|
||||
.and_then(Value::as_str),
|
||||
location.map(|location| location.city.as_str()),
|
||||
);
|
||||
assert_eq!(
|
||||
sent.pointer("/tools/0/user_location/timezone")
|
||||
.and_then(Value::as_str),
|
||||
location.map(|location| location.timezone.name()),
|
||||
);
|
||||
}
|
||||
}
|
||||
let sent = capture_downstream_with_country(
|
||||
body,
|
||||
api_key,
|
||||
websocket,
|
||||
false,
|
||||
Some(location.clone()),
|
||||
policy,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(sent.get("request_country"), expected.as_ref());
|
||||
assert_eq!(
|
||||
sent.pointer("/client_metadata/request_country"),
|
||||
Some(&json!("business"))
|
||||
);
|
||||
assert_eq!(
|
||||
sent.pointer("/tools/0/user_location/country"),
|
||||
Some(&json!(location.country))
|
||||
);
|
||||
assert_eq!(
|
||||
sent.pointer("/tools/0/user_location/city"),
|
||||
Some(&json!(location.city))
|
||||
);
|
||||
assert_eq!(
|
||||
sent.pointer("/tools/0/user_location/timezone"),
|
||||
Some(&json!(location.timezone.name()))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -146,44 +146,63 @@ async fn advertised_websocket_limit_counts_final_utf8_bytes_and_allows_equality(
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn advertised_websocket_limit_rejects_warmup_without_http_fallback() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let server = tokio::spawn(async move {
|
||||
let (socket, _) = listener.accept().await.unwrap();
|
||||
let mut websocket = accept_codex_test_websocket_with(socket, |_, response| {
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("x-codex-websocket-max-message-bytes", "1".parse().unwrap());
|
||||
})
|
||||
.await;
|
||||
while let Some(Ok(message)) = websocket.next().await {
|
||||
assert!(!message.is_text());
|
||||
}
|
||||
assert!(
|
||||
timeout(Duration::from_millis(100), listener.accept())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
});
|
||||
let backend = CodexBackendClient::new(
|
||||
reqwest::Client::builder().no_proxy().build().unwrap(),
|
||||
format!("http://{addr}"),
|
||||
test_wire_profile(),
|
||||
)
|
||||
.with_websocket_pool(Arc::new(CodexWebSocketPool::default()));
|
||||
let error = backend
|
||||
.create_response(
|
||||
&explicit_websocket_warmup_request("oversized-warmup"),
|
||||
request_context("req_oversized_warmup", Some("chatgpt-account")),
|
||||
async fn websocket_size_rejection_keeps_warmup_on_websocket() {
|
||||
for advertised in [true, false] {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let server = tokio::spawn(async move {
|
||||
let (socket, _) = listener.accept().await.unwrap();
|
||||
let mut websocket = accept_codex_test_websocket_with(socket, |_, response| {
|
||||
if advertised {
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("x-codex-websocket-max-message-bytes", "1".parse().unwrap());
|
||||
}
|
||||
})
|
||||
.await;
|
||||
if advertised {
|
||||
while let Some(Ok(message)) = websocket.next().await {
|
||||
assert!(!message.is_text());
|
||||
}
|
||||
} else {
|
||||
assert!(websocket.next().await.unwrap().unwrap().is_text());
|
||||
websocket
|
||||
.close(Some(CloseFrame {
|
||||
code: CloseCode::Size,
|
||||
reason: "too large".into(),
|
||||
}))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
assert!(
|
||||
timeout(Duration::from_millis(100), listener.accept())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
});
|
||||
let backend = CodexBackendClient::new(
|
||||
reqwest::Client::builder().no_proxy().build().unwrap(),
|
||||
format!("http://{addr}"),
|
||||
test_wire_profile(),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
std::assert_matches!(
|
||||
error,
|
||||
CodexClientError::WebSocket(CodexWebSocketExchangeError::MessageTooLarge)
|
||||
);
|
||||
server.await.unwrap();
|
||||
.with_websocket_pool(Arc::new(CodexWebSocketPool::default()));
|
||||
let error = backend
|
||||
.create_response(
|
||||
&explicit_websocket_warmup_request("oversized-warmup"),
|
||||
request_context("req_oversized_warmup", Some("chatgpt-account")),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
let CodexClientError::WebSocket(error) = error else {
|
||||
panic!("expected WebSocket size rejection")
|
||||
};
|
||||
if advertised {
|
||||
std::assert_matches!(error, CodexWebSocketExchangeError::MessageTooLarge);
|
||||
} else {
|
||||
assert_eq!(error.close_before_terminal().unwrap().code(), Some(1009));
|
||||
}
|
||||
server.await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
async fn reject_websocket_openings(listener: &TcpListener, attempts: usize) {
|
||||
@@ -959,7 +978,8 @@ async fn concurrent_same_handle_should_allow_one_claim_and_advance_the_live_sock
|
||||
std::assert_matches!(
|
||||
concurrent_error,
|
||||
CodexClientError::WebSocket(CodexWebSocketExchangeError::ContinuationUnavailable {
|
||||
reason: PreviousResponseUnavailableReason::ConnectionBusy
|
||||
reason: PreviousResponseUnavailableReason::ConnectionBusy,
|
||||
..
|
||||
})
|
||||
);
|
||||
|
||||
@@ -976,7 +996,8 @@ async fn concurrent_same_handle_should_allow_one_claim_and_advance_the_live_sock
|
||||
std::assert_matches!(
|
||||
stale_error,
|
||||
CodexClientError::WebSocket(CodexWebSocketExchangeError::ContinuationUnavailable {
|
||||
reason: PreviousResponseUnavailableReason::FreshConnectionRequired
|
||||
reason: PreviousResponseUnavailableReason::FreshConnectionRequired,
|
||||
..
|
||||
})
|
||||
);
|
||||
let latest = backend
|
||||
@@ -1148,7 +1169,8 @@ async fn missing_exact_socket_should_fail_without_opening_a_connection() {
|
||||
std::assert_matches!(
|
||||
error,
|
||||
CodexClientError::WebSocket(CodexWebSocketExchangeError::ContinuationUnavailable {
|
||||
reason: PreviousResponseUnavailableReason::FreshConnectionRequired
|
||||
reason: PreviousResponseUnavailableReason::FreshConnectionRequired,
|
||||
..
|
||||
})
|
||||
);
|
||||
assert!(
|
||||
@@ -1182,7 +1204,8 @@ async fn connection_local_continuation_without_a_pool_should_not_open_http_or_we
|
||||
std::assert_matches!(
|
||||
error,
|
||||
CodexClientError::WebSocket(CodexWebSocketExchangeError::ContinuationUnavailable {
|
||||
reason: PreviousResponseUnavailableReason::PoolUnavailable
|
||||
reason: PreviousResponseUnavailableReason::PoolUnavailable,
|
||||
..
|
||||
})
|
||||
);
|
||||
assert!(
|
||||
|
||||
@@ -10,7 +10,13 @@ async fn closed_connection_handoff_rejects_payload_as_not_sent() {
|
||||
let server = tokio::spawn(async move {
|
||||
let (socket, _) = listener.accept().await.unwrap();
|
||||
let mut ws = accept_codex_test_websocket(socket).await;
|
||||
ws.close(None).await.unwrap();
|
||||
// 空闲连接的 1009 早于本次请求首帧,不能触发大小回退
|
||||
ws.close(Some(tungstenite::protocol::CloseFrame {
|
||||
code: tungstenite::protocol::frame::coding::CloseCode::Size,
|
||||
reason: "idle".into(),
|
||||
}))
|
||||
.await
|
||||
.unwrap();
|
||||
// pump 的关闭确认是 best-effort;无业务帧的 EOF 同样能证明连接已退出
|
||||
assert!(
|
||||
matches!(
|
||||
|
||||
@@ -219,31 +219,7 @@ async fn capture_response_create(
|
||||
let address = listener.local_addr().expect("fingerprint server address");
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut stream, _) = listener.accept().await.expect("accept fingerprint client");
|
||||
let opening = read_http_request(&mut stream).await;
|
||||
let websocket_key =
|
||||
read_header_value(&opening, "sec-websocket-key").expect("WebSocket key");
|
||||
let extension = if deflate {
|
||||
"Sec-WebSocket-Extensions: permessage-deflate\r\n"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let response = format!(
|
||||
concat!(
|
||||
"HTTP/1.1 101 Switching Protocols\r\n",
|
||||
"Connection: Upgrade\r\n",
|
||||
"Upgrade: websocket\r\n",
|
||||
"Sec-WebSocket-Accept: {}\r\n",
|
||||
"{}",
|
||||
"\r\n"
|
||||
),
|
||||
derive_accept_key(websocket_key.as_bytes()),
|
||||
extension
|
||||
);
|
||||
stream
|
||||
.write_all(response.as_bytes())
|
||||
.await
|
||||
.expect("write upgrade response");
|
||||
|
||||
let opening = upgrade_raw_socket(&mut stream, deflate).await;
|
||||
let mut frames = Vec::new();
|
||||
loop {
|
||||
let frame = read_client_frame(&mut stream).await;
|
||||
@@ -274,6 +250,34 @@ async fn capture_response_create(
|
||||
server.await.expect("fingerprint server task")
|
||||
}
|
||||
|
||||
async fn upgrade_raw_socket(stream: &mut TcpStream, deflate: bool) -> String {
|
||||
let opening = read_http_request(stream).await;
|
||||
let websocket_key = read_header_value(&opening, "sec-websocket-key").expect("WebSocket key");
|
||||
let extension = if deflate {
|
||||
"Sec-WebSocket-Extensions: permessage-deflate\r\n"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let response = format!(
|
||||
concat!(
|
||||
"HTTP/1.1 101 Switching Protocols\r\n",
|
||||
"Connection: Upgrade\r\n",
|
||||
"Upgrade: websocket\r\n",
|
||||
"Sec-WebSocket-Accept: {}\r\n",
|
||||
"{}",
|
||||
"\r\n"
|
||||
),
|
||||
derive_accept_key(websocket_key.as_bytes()),
|
||||
extension
|
||||
);
|
||||
stream
|
||||
.write_all(response.as_bytes())
|
||||
.await
|
||||
.expect("write upgrade response");
|
||||
|
||||
opening
|
||||
}
|
||||
|
||||
async fn read_client_frame(stream: &mut TcpStream) -> ClientFrame {
|
||||
let first_byte = stream.read_u8().await.expect("frame first byte");
|
||||
let second_byte = stream.read_u8().await.expect("frame second byte");
|
||||
@@ -346,3 +350,190 @@ async fn write_server_text_frame(stream: &mut TcpStream, payload: &str) {
|
||||
.await
|
||||
.expect("write completed frame");
|
||||
}
|
||||
|
||||
fn large_upload_client(addr: std::net::SocketAddr) -> (CodexBackendClient, CodexResponsesRequest) {
|
||||
let client = CodexBackendClient::new(
|
||||
reqwest::Client::builder().no_proxy().build().unwrap(),
|
||||
format!("http://{addr}"),
|
||||
test_wire_profile(),
|
||||
)
|
||||
.with_websocket_pool(Arc::new(CodexWebSocketPool::default()));
|
||||
let mut request = codex_request("gpt-test", "x".repeat(16 * 1024 * 1024), vec![]);
|
||||
request.use_websocket = true;
|
||||
request.local_conversation_id = Some("fragmented-create".into());
|
||||
(client, request)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn fragmented_upload_sends_pong_before_final_continuation() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let (client, request) = large_upload_client(listener.local_addr().unwrap());
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
upgrade_raw_socket(&mut stream, false).await;
|
||||
assert_eq!(read_client_frame(&mut stream).await.first_byte, 0x01);
|
||||
stream.write_all(&[0x89, 1, b'p']).await.unwrap();
|
||||
let mut pong = false;
|
||||
loop {
|
||||
let frame = read_client_frame(&mut stream).await;
|
||||
match frame.first_byte {
|
||||
0x8a => {
|
||||
assert_eq!(frame.payload, b"p");
|
||||
pong = true;
|
||||
}
|
||||
0x00 => {}
|
||||
0x80 => {
|
||||
assert!(pong, "Pong must precede the final data frame");
|
||||
break;
|
||||
}
|
||||
byte => panic!("unexpected frame {byte:x}"),
|
||||
}
|
||||
}
|
||||
write_server_text_frame(
|
||||
&mut stream,
|
||||
&completed_websocket_response("resp_ping_upload", 1, 1),
|
||||
)
|
||||
.await;
|
||||
});
|
||||
timeout(
|
||||
Duration::from_secs(15),
|
||||
client.create_response(&request, request_context("upload-ping", None)),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
server.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn partial_upload_honors_peer_reply_and_keeps_bare_disconnect_ambiguous() {
|
||||
for case in ["size_close", "error_then_close", "disconnect"] {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let (client, request) = large_upload_client(listener.local_addr().unwrap());
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
upgrade_raw_socket(&mut stream, false).await;
|
||||
// 只读首帧的第一个字节,让客户端余下的写入遇到背压
|
||||
assert_eq!(stream.read_u8().await.unwrap(), 0x01);
|
||||
if case == "disconnect" {
|
||||
return;
|
||||
}
|
||||
if case == "error_then_close" {
|
||||
write_server_text_frame(
|
||||
&mut stream,
|
||||
r#"{"type":"error","error":{"code":"rate_limit_exceeded","message":"quota"}}"#,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
stream.write_all(&[0x88, 2, 0x03, 0xf1]).await.unwrap();
|
||||
if case == "size_close" {
|
||||
let (mut http, _) = listener.accept().await.unwrap();
|
||||
let body = read_http_request_with_body(&mut http).await;
|
||||
assert!(body.starts_with(b"POST /codex/responses "));
|
||||
write_completed_sse_response(&mut http).await;
|
||||
} else {
|
||||
tokio::io::copy(&mut stream, &mut tokio::io::sink())
|
||||
.await
|
||||
.ok();
|
||||
}
|
||||
});
|
||||
let result = timeout(
|
||||
Duration::from_secs(15),
|
||||
client.create_response_stream(&request, request_context(case, None)),
|
||||
)
|
||||
.await
|
||||
.expect("upload must not wait for its write timeout");
|
||||
match case {
|
||||
"size_close" => {
|
||||
let mut response = result.unwrap();
|
||||
assert_eq!(
|
||||
response.transport_metrics.decision,
|
||||
Some(CodexTransportDecision::Http2WebSocketMessageTooLarge)
|
||||
);
|
||||
assert_eq!(response.transport, CodexBackendTransport::HttpSse);
|
||||
while let Some(chunk) = response.body.next().await {
|
||||
chunk.unwrap();
|
||||
}
|
||||
}
|
||||
"error_then_close" => {
|
||||
let mut response = result.unwrap();
|
||||
let chunk = response.body.next().await.unwrap().unwrap();
|
||||
assert_eq!(
|
||||
serde_json::from_slice::<Value>(&chunk).unwrap()["error"]["code"],
|
||||
"rate_limit_exceeded"
|
||||
);
|
||||
assert!(response.body.next().await.is_none());
|
||||
}
|
||||
_ => {
|
||||
let err = match result {
|
||||
Err(error) => error,
|
||||
Ok(mut response) => response.body.next().await.unwrap().unwrap_err(),
|
||||
};
|
||||
let CodexClientError::WebSocket(error) = err else {
|
||||
panic!("expected WebSocket failure")
|
||||
};
|
||||
assert!(error.close_before_terminal().is_none());
|
||||
let source = match &error {
|
||||
CodexWebSocketExchangeError::ConnectionObserved { source, .. } => {
|
||||
source.as_ref()
|
||||
}
|
||||
other => other,
|
||||
};
|
||||
assert!(matches!(
|
||||
source,
|
||||
CodexWebSocketExchangeError::PostSendAmbiguous { .. }
|
||||
));
|
||||
}
|
||||
}
|
||||
server.await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn upload_timeout_delivers_buffered_upstream_error() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let (client, request) = large_upload_client(listener.local_addr().unwrap());
|
||||
let (release, released) = tokio::sync::oneshot::channel();
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
upgrade_raw_socket(&mut socket, false).await;
|
||||
assert_eq!(read_client_frame(&mut socket).await.first_byte, 0x01);
|
||||
write_server_text_frame(
|
||||
&mut socket,
|
||||
r#"{"type":"error","error":{"code":"rate_limit_exceeded","message":"quota"}}"#,
|
||||
)
|
||||
.await;
|
||||
socket.write_all(&[0x89, 1, b'p']).await.unwrap();
|
||||
timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
let frame = read_client_frame(&mut socket).await;
|
||||
if frame.first_byte == 0x8a {
|
||||
break;
|
||||
}
|
||||
assert_eq!(frame.first_byte, 0x00);
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("peer error and following Ping should be read during upload");
|
||||
// Pong 证明此前的业务错误已经入队,保留连接直到写超时和错误交付均已完成
|
||||
tokio::time::pause();
|
||||
tokio::time::advance(Duration::from_secs(301)).await;
|
||||
tokio::time::resume();
|
||||
timeout(Duration::from_secs(5), released)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
});
|
||||
let mut response = client
|
||||
.create_response_stream(&request, request_context("upload_timeout_reply", None))
|
||||
.await
|
||||
.unwrap();
|
||||
let frame = response.body.next().await.unwrap().unwrap();
|
||||
assert_eq!(
|
||||
serde_json::from_slice::<Value>(&frame).unwrap()["error"]["code"],
|
||||
"rate_limit_exceeded"
|
||||
);
|
||||
assert!(response.body.next().await.is_none());
|
||||
release.send(()).unwrap();
|
||||
server.await.unwrap();
|
||||
}
|
||||
|
||||
@@ -2047,6 +2047,109 @@ async fn codex_backend_client_should_discard_pooled_websocket_after_unknown_resp
|
||||
assert_eq!(accepted_connections.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn response_exclusions_bind_websocket_reuse_and_exact_continuation() {
|
||||
const EXCLUSIONS: &[&[&str]] = &[
|
||||
&[],
|
||||
&["tools,usage.attribution"],
|
||||
&["tools"],
|
||||
&["tools", "usage.attribution"],
|
||||
&[""],
|
||||
];
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let server = tokio::spawn(async move {
|
||||
let mut handlers = tokio::task::JoinSet::new();
|
||||
for (index, &expected) in EXCLUSIONS.iter().enumerate() {
|
||||
let (stream, _) = listener.accept().await.unwrap();
|
||||
let mut socket = accept_codex_test_websocket_with(stream, |request, _| {
|
||||
let actual: Vec<_> = request
|
||||
.headers()
|
||||
.get_all("x-codex-exclude")
|
||||
.iter()
|
||||
.map(|value| value.to_str().unwrap())
|
||||
.collect();
|
||||
assert_eq!(actual, expected);
|
||||
})
|
||||
.await;
|
||||
handlers.spawn(async move {
|
||||
let mut turn = 0;
|
||||
while let Some(Ok(Message::Text(_))) = socket.next().await {
|
||||
let id = format!("resp_{index}_{turn}");
|
||||
socket
|
||||
.send(Message::Text(
|
||||
completed_websocket_response(&id, 1, 1).into(),
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
turn += 1;
|
||||
}
|
||||
});
|
||||
}
|
||||
drop(listener);
|
||||
while let Some(result) = handlers.join_next().await {
|
||||
result.unwrap();
|
||||
}
|
||||
});
|
||||
let pool = Arc::new(CodexWebSocketPool::new(Duration::from_mins(1)));
|
||||
let backend = CodexBackendClient::new(
|
||||
reqwest::Client::builder().no_proxy().build().unwrap(),
|
||||
format!("http://{addr}"),
|
||||
test_wire_profile(),
|
||||
)
|
||||
.with_websocket_pool(pool.clone());
|
||||
let make_request = |values: &[&str]| {
|
||||
let headers: Vec<_> = values
|
||||
.iter()
|
||||
.map(|&value| ("x-codex-exclude", value))
|
||||
.collect();
|
||||
let mut request = encode_request_with_headers(
|
||||
codex_request_body("gpt-test", "be brief", vec![]),
|
||||
&headers,
|
||||
);
|
||||
request.local_conversation_id = Some("shared-session".into());
|
||||
request.use_websocket = true;
|
||||
request
|
||||
};
|
||||
let context = request_context("req_exclusions", Some("account"));
|
||||
for (index, &values) in EXCLUSIONS.iter().enumerate() {
|
||||
let request = make_request(values);
|
||||
for (turn, expected) in ["new", "reuse"].into_iter().enumerate() {
|
||||
let response = backend.create_response(&request, context).await.unwrap();
|
||||
assert_eq!(
|
||||
response.websocket_pool_decision.unwrap().kind(),
|
||||
expected,
|
||||
"{values:?}"
|
||||
);
|
||||
assert!(response.body.contains(&format!("resp_{index}_{turn}")));
|
||||
}
|
||||
let continue_from_last_response = |mut request: CodexResponsesRequest| {
|
||||
request.set_previous_response_id(Some(format!("resp_{index}_1")));
|
||||
request.previous_response_scope = Some(PreviousResponseScope::ConnectionLocal);
|
||||
request
|
||||
};
|
||||
let changed = make_request(EXCLUSIONS[(index + 1) % EXCLUSIONS.len()]);
|
||||
let error = backend
|
||||
.create_response(&continue_from_last_response(changed), context)
|
||||
.await
|
||||
.expect_err("changed exclusions must require replay");
|
||||
assert!(matches!(
|
||||
error,
|
||||
CodexClientError::WebSocket(CodexWebSocketExchangeError::ContinuationUnavailable {
|
||||
reason: PreviousResponseUnavailableReason::FreshConnectionRequired,
|
||||
..
|
||||
})
|
||||
));
|
||||
let response = backend
|
||||
.create_response(&continue_from_last_response(request), context)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(response.body.contains(&format!("resp_{index}_2")));
|
||||
}
|
||||
pool.shutdown().await;
|
||||
server.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn guardian_header_should_open_a_distinct_websocket() {
|
||||
assert_changed_handshake_opens_distinct_websocket("x-codex-guardian", "reviewer").await;
|
||||
|
||||
@@ -19,7 +19,7 @@ gateway-egress = { path = "../../gateway-egress" }
|
||||
gateway-core = { path = "../../gateway-core" }
|
||||
gateway-protocol = { path = "../../gateway-protocol" }
|
||||
getrandom = "0.4.3"
|
||||
jsonwebtoken = { version = "=11.1.0", default-features = false, features = ["aws_lc_rs"] }
|
||||
jsonwebtoken = { version = "=12.0.0", default-features = false, features = ["aws_lc_rs"] }
|
||||
# 与官方 Grok CLI 一致:reqwest 不启用压缩特性,上游请求不带 accept-encoding。
|
||||
reqwest = { version = "=0.12.28", default-features = false, features = ["stream", "rustls-tls-native-roots", "http2", "socks"] }
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
|
||||
@@ -584,7 +584,7 @@ impl TestKey {
|
||||
.expect("encode deterministic EC key");
|
||||
EncodingKey::from_ec_der(der.as_bytes())
|
||||
} else {
|
||||
EncodingKey::from_secret(b"symmetric-test-key")
|
||||
EncodingKey::from_secret(b"symmetric-test-key").expect("create symmetric test key")
|
||||
};
|
||||
encode(&header, claims, &encoding_key).expect("encode test token")
|
||||
}
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
# PostgreSQL 服务端镜像:备份客户端(pg_dump/pg_restore)从这里取,与 compose 同源、
|
||||
# 版本严格一致。升级数据库版本时只需同步修改这里与 deploy/compose.yaml。
|
||||
ARG POSTGRES_IMAGE=postgres:18-bookworm@sha256:bbf83594798e144bff365a9c191c5d779f181fb3135902064ab8ff11918020fc
|
||||
ARG POSTGRES_IMAGE=postgres:18-bookworm@sha256:194e55feb2597b1465dbee81cc9fd8d204566cd2eb42c8d22fd6c931a38781b1
|
||||
|
||||
FROM node:26.13.1-bookworm-slim@sha256:5df79989ed685e09f0a98019db4cebfb22fb9df1a53c0161664a011f7ff6b0f1 AS frontend-builder
|
||||
|
||||
|
||||
+2
-2
@@ -418,7 +418,7 @@ PostgreSQL/Redis 启动密码。日常校验使用 `config --quiet`
|
||||
| 并发与排队 | “系统设置 → 运行设置”;Key 与账号分别设置排队容量和超时,可选择账号排队失败后换号,见[排队规则](../docs/api.md#并发与排队) |
|
||||
| 账号错误保护 | “系统设置 → 运行设置 → 错误保护”;默认关闭,按[自定义规则](../docs/api.md#账号错误保护)暂停账号调度 |
|
||||
| 全局请求位置 | “系统设置 → 上游配置 → 请求位置覆盖”,默认关闭 |
|
||||
| OpenAI 请求国家 | “系统设置 → 上游配置 → 请求位置覆盖”中默认选中“跟随位置”,可选择“空值”“透传”或“自定义” |
|
||||
| Codex OAuth 请求国家 | “系统设置 → 上游配置 → 请求国家”,默认跟随位置,也可选择“空值”“透传”或“自定义” |
|
||||
| OpenAI OAuth 同步审核模型 | “系统设置 → 上游配置 → 模型映射”中的“专用审核模型”默认开启,关闭后沿用客户端模型。[适用条件](../docs/api.md#正文兼容) |
|
||||
| 代理位置 | “代理管理”;优先于全局位置,全局关闭时仍可独立生效 |
|
||||
|
||||
@@ -438,7 +438,7 @@ PostgreSQL/Redis 启动密码。日常校验使用 `config --quiet`
|
||||
|
||||
在下游导入或编辑 OpenAI API Key 账号,填写上游 API 地址和该 Key,后台自动发现 CPR 互联能力。
|
||||
地址包含自定义前缀时保留完整前缀,后台在该地址下请求 `cpr/link`。
|
||||
列表与详情显示已保存的观测。展开账号可查看上游密钥限制,普通账号并发留空时跟随上游有效的正数上限。启用的 OpenAI API Key 账号可点击「刷新额度」重新识别。上游明确关闭共享或不支持互联时,账号显示为 API,重新识别成功后显示 CPR
|
||||
展开账号行,点击「账号额度」右上角的链环图标可手动检测 CPR 互联。识别成功后账号显示为 CPR,可在「上游额度」查看上游密钥限制和刷新额度。普通账号并发留空时跟随上游有效的正数上限。上游明确关闭共享或不支持互联时,账号显示为 API
|
||||
|
||||
第三方网关通过插件实现相同协议也可被识别,不按软件名称判定兼容。
|
||||
上游明确返回 Key 预算耗尽时,下游暂停该账号;后续同步确认允许使用后自动恢复,普通限流冷却独立保留。
|
||||
|
||||
+2
-2
@@ -11,7 +11,7 @@ services:
|
||||
extends:
|
||||
file: config.yaml
|
||||
service: postgres-credentials
|
||||
image: postgres:18-bookworm@sha256:bbf83594798e144bff365a9c191c5d779f181fb3135902064ab8ff11918020fc
|
||||
image: postgres:18-bookworm@sha256:194e55feb2597b1465dbee81cc9fd8d204566cd2eb42c8d22fd6c931a38781b1
|
||||
restart: unless-stopped
|
||||
# 小内存部署可在此调整数据库预算,保留 UTC 参数,详见 README.md#小内存优化
|
||||
command:
|
||||
@@ -46,7 +46,7 @@ services:
|
||||
extends:
|
||||
file: config.yaml
|
||||
service: redis-credentials
|
||||
image: redis:8-alpine@sha256:0bf6577d7774e592b29d093e3ac9390eb91e13d72c21e506afce736de5e0eeb0
|
||||
image: redis:8-alpine@sha256:7958cfbb9d152f87dadfbc89f1b0b15938f0b81ff8982feb327476f4911935c3
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
- type: bind
|
||||
|
||||
+22
-11
@@ -429,6 +429,9 @@ Messages 费用按管理员显式配置的模型价格计算,未配置时保
|
||||
Images 使用原生非流式 JSON 端点,JSON 请求与响应正文原样转发。
|
||||
`/v1/images/edits` 还接受 `multipart/form-data`,将上传转换为原生 Images JSON 请求
|
||||
|
||||
Key 允许生图时,已绑定分组的 Key 只使用允许该图片模型的启用分组成员。账号自身的模型黑白名单进一步收窄可选范围。
|
||||
采用严格或优先亲和时优先使用会话主账号。主账号在授权池内但模型权限、套餐或上游协议不支持本次生图时,可以临时借用合格账号,后续聊天仍沿用原绑定
|
||||
|
||||
multipart 的 `image` 和 `image[]` 上传按出现顺序组成 `images` 数组,每项为
|
||||
`{"image_url":"data:image/...;base64,..."}`;`mask` 上传转换为同结构的单个对象。
|
||||
图片支持 PNG、JPEG、WebP,根据内容识别格式,原始文件字节直接编码,不缩放或重新编码
|
||||
@@ -516,6 +519,9 @@ Responses 的安装身份通过正文 `client_metadata` 及 turn metadata 发送
|
||||
上述过滤描述原生转发;已信任插件的显式 header 改写可以覆盖账号与画像生成的默认头,
|
||||
不按认证或会话字段名称拦截,边界见 [SDK 请求中间件](../backend/crates/gateway-plugin/sdk/docs/capabilities.md#模型请求与-attempt)
|
||||
|
||||
Responses 透传客户端的 `x-codex-exclude`,由上游按请求省略响应字段。上游 WebSocket 只在握手时读取该头,
|
||||
因此连接池按最终握手中的全部同名头值复用连接。头值变化时,依赖原连接的精确续接需要客户端重放完整历史
|
||||
|
||||
Responses 也不透传 `x-stainless-*`、`Origin`、`Referer`、`sec-ch-ua*` 和 `sec-fetch-*`
|
||||
携带的下游 SDK/浏览器环境或页面来源。过滤规则适用于所有下游客户端,与 User-Agent 无关;
|
||||
原始入站头仍供 CORS、鉴权和本地观测使用。
|
||||
@@ -678,7 +684,11 @@ OpenAI Responses 上游 WS 按握手响应头 `x-codex-websocket-max-message-byt
|
||||
该上限只属于当前上游连接;响应头缺失或无效时不预判超限。显式 warmup 保持 WS 合同,超限时
|
||||
返回 `websocket_message_too_large`,不重复发送或改用 HTTP
|
||||
|
||||
超过当前连接上限的 connection-local WS 续接会在发送前返回 `400 previous_response_not_found`。
|
||||
上传期间网关持续读取上游帧并回复 Ping。上游在本次请求开始发送后、首条响应文本前返回关闭码
|
||||
1009 时,采用与握手超限相同的传输选择。显式 warmup 保留上游关闭错误。收到响应文本(含元数据)后
|
||||
再收到 1009,网关保留原错误,避免重复执行。单独的断管或 TCP 重置按传输失败处理
|
||||
|
||||
超过当前连接上限的 connection-local WS 续接会返回 `400 previous_response_not_found`。
|
||||
上游 HTTP/SSE 在 `store=false` 下成功后,若网关已记录该响应需要完整重放,HTTP 和 WS 客户端携带其
|
||||
`previous_response_id` 继续生成时也会收到同一错误。客户端应清除旧 ID,
|
||||
携带完整历史及工具调用/输出重试。官方 Codex 支持重连 WS 后完整重发,也可能按自身重试预算
|
||||
@@ -1386,7 +1396,7 @@ Key 消费窗口的 `localUsage` 按各自 `[resetAt - windowSeconds, resetAt)`
|
||||
|
||||
- 收到有效快照时显示 CPR 互联。明确返回不支持协议(HTTP 404、405、501),或返回 `403 peer_sharing_disabled` 时,清除互联身份和共享数据,显示普通 API Key
|
||||
- 普通 401/403 保留原识别结果并清除已撤销的共享内容。超时、限流、服务异常或无效响应保留原识别结果和已有观测。无观测时 `observedAt` 与 `pool` 为 `null`,额度窗口为空
|
||||
- 展开可探测的 API Key 后,点击「刷新额度」可重新识别互联。卡片显示已有更新时间,手动刷新结果通过通知反馈。明确不支持协议的连接停止周期探测,共享关闭的连接按授权退避周期复查
|
||||
- 可探测但尚未识别为互联的 API Key 支持手动检测。明确不支持协议的连接停止周期探测,共享关闭的连接按授权退避周期复查
|
||||
|
||||
账号地址、密钥或出口变更使旧观测与识别身份失效,重新识别当前连接。
|
||||
账号停用后停止同步,重新启用后按当前连接的识别结果恢复后台任务
|
||||
@@ -1410,7 +1420,7 @@ Key 预算及其访问状态随互联默认公开,不要求开启 `shareQuota`
|
||||
最多 256 项,每个 ID 最多 256 字节;重复 ID 去重,不接受空白、控制字符、`__` 前缀或 `*` 通配符。
|
||||
允许保存当前上游目录尚未返回的 ID。限制按全局模型映射后的上游 ID 判断,不扩大账号本身的上游权限。
|
||||
管理端刷新目录只更新目录,不修改模型限制。全选与取消全选只作用于上游目录中符合当前搜索条件的模型。
|
||||
账号白名单中,“添加模型”旁的图片按钮可勾选 `gpt-image-2` 和 `gpt-image-1.5`。
|
||||
账号和分组白名单均可一键勾选 `gpt-image-2` 和 `gpt-image-1.5`。
|
||||
自定义模型取消勾选后在本次编辑期间保留,可再次勾选。保存时以最终选中项更新限制,关闭或取消编辑会丢弃草稿。
|
||||
白名单的清理按钮列出当前目录未返回的已选 ID,默认不选中任何项,
|
||||
由管理员确认后从当前表单移除,保存账号后生效。目录未就绪、刷新失败或返回空目录时不能清理,清理也不能将白名单置空。
|
||||
@@ -1508,7 +1518,7 @@ API 的 `autoLocation` 默认为 `false`;开启时使用已检测位置,测
|
||||
只改位置不清空连通性测试结果,也不更改账号凭据版本
|
||||
|
||||
关联账号的 OpenAI/Codex Responses 请求(HTTP/SSE、WebSocket)优先使用代理位置,否则使用全局
|
||||
运行设置中已开启的 `requestLocation`。出站正文的顶层 `request_country` 默认跟随位置,也可在[请求位置](#请求位置)选择“空值”“透传”或“自定义”。
|
||||
运行设置中已开启的 `requestLocation`。Codex OAuth 请求的顶层国家字段由[请求国家策略](#请求位置)控制。
|
||||
位置覆盖同时更新客户端时间上下文的时区和 Web Search 的结构化位置,未启用覆盖时这两项保留客户端原值。
|
||||
全局覆盖按请求冻结,保存后对新请求生效。代理覆盖按每次执行选定的账号解析,包括换号和换出口。
|
||||
位置覆盖不改变 epoch 时间戳、真实出口 IP、服务或管理端时区、数据驻留约束及 xAI 请求
|
||||
@@ -1698,7 +1708,8 @@ RT-only 使用同一形状,只提交 `refreshToken`。不得把真实 token
|
||||
管理端新建表单留空时省略 `notes`。重新授权不接受 `settings`,凭据刷新保留账号设置
|
||||
|
||||
可选 `name` 与编辑名称使用相同的长度和控制字符约束,仅在单份导入数据解析出一个账号时覆盖名称。
|
||||
省略、`null`、留空或多账号导入均保留导入数据或服务商提供的名称;管理端批量导入不提交 `name`
|
||||
省略、`null`、留空或多账号导入均保留导入数据或服务商提供的名称;管理端批量导入不提交 `name`。
|
||||
API Key 账号未指定名称时默认使用「密钥账号」
|
||||
|
||||
账号列表的每个 item 返回轻量 `groups: [{ id, name, enabled }]`
|
||||
|
||||
@@ -1855,7 +1866,7 @@ OpenAI 授权码交换与令牌刷新请求的连接超时为 30 秒,单次上
|
||||
|
||||
样本仅使用当前额度窗口内、账号加入后开始且截至观测时间已完整交付的请求,缓存命中不重复计入输入
|
||||
|
||||
重置或套餐变化后重新积累有效进度,中途加入的账号可在新基线后采样,无需等待下一次重置,职责与断点处理见[额度预测架构](architecture.md#额度预测)
|
||||
重置或套餐变化后重新积累有效进度,中途加入的账号可在新基线后采样。单条历史读数的重置时间偏移不会截断已记录用量。疑似跨周期且仍待确认时,接口保留来源用量并暂停估算,详见[额度预测架构](architecture.md#额度预测)
|
||||
|
||||
预测不参与调度或账单结算,站外消耗、日志清理、异步延迟、未成功交付的上游消耗和模型组合变化均可能造成误差
|
||||
|
||||
@@ -1994,7 +2005,7 @@ GET 和 POST 均返回 `enabled`、`leadMinutes`、`weeklyTriggerRemainingPercen
|
||||
分组详情和完整列表返回 `modelAccess`、`fastMode`、`allowImageGeneration` 和 `allowSubagents`。创建时省略这些字段使用默认值,更新时省略或传 `null` 保留现值。
|
||||
|
||||
`modelAccess` 复用账号的模型规则。默认 `{"mode":"all","models":[]}` 允许成员账号原本可以使用的模型。
|
||||
`allowlist` 和 `denylist` 使用区分大小写的完整模型 ID。编辑器候选取自该组成员账号,账号自身的限制继续生效。
|
||||
`allowlist` 和 `denylist` 使用区分大小写的完整模型 ID。分组与账号共用[模型限制编辑器](#账号模型限制)。可从成员账号的目录勾选模型,也可在创建或编辑分组时手动添加目录外的 ID。分组和账号分别保存规则,账号自身的限制继续生效。
|
||||
Key 绑定多个组时,按模型分别合并启用组中的合格账号。例如两个组分别允许 X 和 Y,X 请求只能使用允许 X 的组内账号。
|
||||
|
||||
`fastMode` 默认跟随客户端。策略合并包括 Key 绑定的禁用分组,优先级依次为 `disabled`、`enabled`、`ultrafast`、`default`。未绑定分组的 Key 跟随客户端
|
||||
@@ -2162,7 +2173,7 @@ OpenAI Key 的 `installationSeed` 接受带连字符的 UUID,保存时规范
|
||||
|
||||
严格亲和下的后代线程始终启用账号排队,沿用 `accountQueueTimeoutSeconds` 和请求截止时间;
|
||||
`maxWaitingPerAccount` 为 0 时使用每队列 1,000 人上限,否则沿用配置的上限。
|
||||
可识别来源的 Search、Images、Live 创建请求采用同样规则,身份与轮次关联见[会话绑定](architecture.md#6-路由账号范围与-continuation)。
|
||||
可识别来源的 Search、Images、Live 创建请求共用会话绑定。主账号缺少本次生图资格时,后代可按 [Images 请求](#images-请求)规则借号。身份与轮次关联见[会话绑定](architecture.md#6-路由账号范围与-continuation)。
|
||||
插件显式选号须通过账号资格与租约检查,见[调度合同](../backend/crates/gateway-plugin/sdk/docs/capabilities.md#路由调度与观察)。普通请求关闭账号排队且没有可用容量时返回 `503` / `account_capacity_unavailable`,
|
||||
与无候选账号的 `no_available_provider` 区分;排队不绕过账号范围、模型权限、RPM 或金额限额
|
||||
|
||||
@@ -2272,7 +2283,7 @@ HTTP 返回 `429`,`error.code` 为 `key_daily_budget_exceeded` 或 `key_weekly
|
||||
关联代理配置了自定义位置时优先使用代理值。保存后通过现有配置发布机制对新请求生效,
|
||||
已开始请求及其重试保持同一份全局值;普通文本、绝对时间戳和数据驻留要求不受影响
|
||||
|
||||
`openaiRequestCountry` 单独控制 OpenAI Responses 出站正文顶层的 `request_country`。保存后对新请求生效。
|
||||
`openaiRequestCountry` 仅控制发往 Codex OAuth 上游的 Responses 请求顶层字段 `request_country`。API Key 上游保留客户端原值,包括显式 `null`,客户端省略时也省略。保存后对新请求生效
|
||||
|
||||
| 管理端选项 | 设置值 | 发往上游的字段 |
|
||||
| --- | --- | --- |
|
||||
@@ -2311,7 +2322,7 @@ JSON 路径支持 `$`、`.成员`、`["带特殊字符的键"]`、`[索引]`、`
|
||||
|
||||
WebSocket 请求头在握手时发送。隐私规则改变握手头时,普通请求按对应连接身份选择连接,
|
||||
处理结果稳定时可继续复用,不因每次执行删除动作而重连。
|
||||
依赖原连接的精确续接保留原连接,规则变更不能撤回已有握手发送的值
|
||||
依赖原连接的精确续接在响应排除项等连接归属条件仍匹配时保留原连接,规则变更不能撤回已有握手发送的值
|
||||
|
||||
例如,`turn_metadata` 范围的 `$.workspaces` 配合 `remove_field` 删除整个工作区映射;
|
||||
`$.workspaces.*.associated_remote_urls.*` 配合 `remove_field` 和 `pattern: "private-org"` 只删除命中的远端;
|
||||
@@ -2385,7 +2396,7 @@ Guardian 以 `subagent_kind` 或 `client_metadata.x-openai-subagent` 值 `guardi
|
||||
主账号被删除、停用或凭据过期、失效、封禁时,在后备账号成功准入时原子迁移绑定
|
||||
额度耗尽且重置时间未知或距离当前时刻超过账号排队时限时迁移,接近重置时保留主绑定,并给刚过重置时间的额度复核同长度宽限
|
||||
原生续接仍固定其状态归属账号
|
||||
- `strict`(严格):同一会话共用账号,后代请求等待当前账号并跟随根请求换号
|
||||
- `strict`(严格):同一会话共用账号,后代请求等待当前账号并跟随根请求换号;[原生 Images](#images-请求) 可按生图资格临时借号
|
||||
|
||||
插件显式选号及原生续写的状态归属约束在三种模式下仍然生效
|
||||
|
||||
|
||||
@@ -361,7 +361,7 @@ Provider 可为模型提供来源账号集合;Core 在公开目录查询时结
|
||||
| `views/<页面>/index.vue`、`views/<页面>/components/` | 页面组合与局部交互;复杂组件按职责拆成目录入口和相邻模块 |
|
||||
| `views/<页面>/composables/` | 页面查询、轮询、表单及操作生命周期 |
|
||||
| `presenter.ts`、页面 `utils/` | 纯展示投影或该页面拥有的业务转换,不启动请求 |
|
||||
| `components/usage/`、`components/account/` | 跨页面复用的用量、健康时间线、套餐和额度窗口展示 |
|
||||
| `components/usage/`、`components/account/` | 跨页面复用的用量、健康时间线、套餐和额度窗口展示,以及账号与分组共用的模型限制编辑器 |
|
||||
| `composables/` | 请求取消与过期结果隔离、分页、选择、异步动作、目录加载等共享机制 |
|
||||
| `i18n/` | Vue I18n 实例、三语资源和应用语言策略;从全局 Composer 派生 UI 库语言,不翻译用户数据或远端自由文本 |
|
||||
| `utils/` | 按用途分开的数据解析、数字与时长格式化、位置校验、客户端配置、插件导航及颜色工具 |
|
||||
@@ -724,7 +724,7 @@ OpenAI Provider 解释官方逻辑 `session_id` 与 `thread_id`,按 Client Key
|
||||
- 严格:根线程及后代共享当前账号;绑定缺失时任意会话请求均可按调度策略首次认领,
|
||||
已有绑定的后代只跟随当前账号,账号不可用时排队,根迁移后重读共享绑定
|
||||
|
||||
可关联的 Search、Images、Live 创建请求共用会话绑定,宽松和优先模式不依赖线程身份分流;严格模式下后代请求保留跟随约束。
|
||||
可关联的 Search、Images、Live 创建请求共用会话绑定。严格模式下,授权池内的主账号未通过原生 Images 的模型、套餐或协议筛选时,根线程和后代均可从合格账号中借号。取得生图账号租约后,按选号时读到的主绑定原子续期;绑定已变化则重新选号。主账号具备生图资格但繁忙时,后代仍跟随主账号排队
|
||||
内置 `round_robin` 在最高可调度权重层按账号 ID 轮换。游标按 Client Key 和 Provider 隔离,在取得租约后推进;有会话绑定时,两者原子提交。并发首绑只占一个位置,亲和命中和插件显式选号不推进游标。插件委托仍走内置轮询,优先模式已有绑定时沿用会话派生的后备顺序
|
||||
插件显式选号由 Core 复核账号资格并取得租约,native continuation 受独立的状态 owner 与安全重放边界约束
|
||||
|
||||
@@ -1165,7 +1165,9 @@ Admin 按卡片与所选指标向 Store 请求计数、金额或分布,缓存
|
||||
- 同一额度窗口内,每累计至少 5 个百分点形成一段,使用最近 3 个完整段及尾部计算合并比值,不平均逐请求的小分母比值
|
||||
- 重复读数不增加段数,大于 1 个百分点的额度回落、累计计数倒退或窗口身份变化会中断采样
|
||||
- 同窗口回落保留已记录累计;触顶后恢复可用不代表新周期,不能据此重设累计基线
|
||||
- OpenAI 的窗口匹配复用限流解析器,核对桶、槽位、时长和明确套餐,只容许最多 2 秒的重置时间抖动
|
||||
- 本周期累计从当前快照的窗口起点查询。OpenAI 历史读数须匹配额度桶、槽位、时长和明确套餐。重置时间的偏移本身不触发换段,已过期的读数不参与剩余量估算
|
||||
- 当前窗口覆盖旧读数时,要有两次独立请求报告的到期时刻均已过去,且随后两次独立请求都显示已用比例回落超过 1 个百分点,才从新段首条读数重新累计。等待第二条读数期间保留累计并暂停估算
|
||||
- 跳过缺少套餐的历史读数,确认套餐变化后从新段重新累计
|
||||
- 重置后从新段重新累计,无法精确归属的用量不补算;只有账号在窗口开始前加入且无已知断点时,才允许以窗口累计量替代增量采样
|
||||
- 历史点抽样不缩减区间累计用量,同一完成时间共用同一累计值
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { Plugin } from 'vite'
|
||||
|
||||
const banner = `
|
||||
██████╗ ██████╗ ██████╗
|
||||
██╔════╝ ██╔══██╗ ██╔══██╗
|
||||
██║ ██████╔╝ ██████╔╝
|
||||
██║ ██╔═══╝ ██╔═██╗
|
||||
╚██████╗ ██║ ██║ ██╗
|
||||
╚═════╝ ╚═╝ ╚═╝ ╚═╝
|
||||
|
||||
https://github.com/zyycn/codex-proxy-rs`
|
||||
|
||||
export function consoleBanner(): Plugin {
|
||||
return {
|
||||
name: 'cpr-console-banner',
|
||||
transformIndexHtml: {
|
||||
order: 'pre',
|
||||
handler: () => [
|
||||
{
|
||||
tag: 'script',
|
||||
attrs: { type: 'module' },
|
||||
children: `console.info(${JSON.stringify(banner)})`,
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -17,10 +17,10 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@boxicons/vue": "1.0.1",
|
||||
"@codex-proxy/ui": "github:zyycn/codex-proxy-ui#v0.13.0",
|
||||
"@codex-proxy/ui": "github:zyycn/codex-proxy-ui#v0.13.1",
|
||||
"@fontsource-variable/inter": "^5.3.0",
|
||||
"@fontsource-variable/jetbrains-mono": "^5.3.0",
|
||||
"@lucide/vue": "^1.73.0",
|
||||
"@lucide/vue": "^1.77.0",
|
||||
"@vueuse/core": "^15.0.0",
|
||||
"@vueuse/integrations": "^15.0.0",
|
||||
"axios": "^1.21.1",
|
||||
@@ -33,8 +33,8 @@
|
||||
"pinia-plugin-persistedstate": "^4.7.1",
|
||||
"semver": "^7.8.6",
|
||||
"sortablejs": "^1.15.7",
|
||||
"vue": "^3.5.45",
|
||||
"vue-i18n": "11.4.20",
|
||||
"vue": "^3.5.46",
|
||||
"vue-i18n": "11.4.23",
|
||||
"vue-router": "^5.5.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
Generated
+184
-131
@@ -193,10 +193,10 @@ importers:
|
||||
dependencies:
|
||||
'@boxicons/vue':
|
||||
specifier: 1.0.1
|
||||
version: 1.0.1(vue@3.5.45(typescript@6.0.3))
|
||||
version: 1.0.1(vue@3.5.46(typescript@6.0.3))
|
||||
'@codex-proxy/ui':
|
||||
specifier: github:zyycn/codex-proxy-ui#v0.13.0
|
||||
version: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/498a491ea97dbb8c5cedbffd97064edab6969341(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.45(typescript@6.0.3))(yaml@2.9.0)
|
||||
specifier: github:zyycn/codex-proxy-ui#v0.13.1
|
||||
version: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/501495d5b1e9d65840d4cdee5e0e228f361613ee(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
|
||||
@@ -204,14 +204,14 @@ importers:
|
||||
specifier: ^5.3.0
|
||||
version: 5.3.0
|
||||
'@lucide/vue':
|
||||
specifier: ^1.73.0
|
||||
version: 1.73.0(vue@3.5.45(typescript@6.0.3))
|
||||
specifier: ^1.77.0
|
||||
version: 1.77.0(vue@3.5.46(typescript@6.0.3))
|
||||
'@vueuse/core':
|
||||
specifier: ^15.0.0
|
||||
version: 15.0.0(vue@3.5.45(typescript@6.0.3))
|
||||
version: 15.0.0(vue@3.5.46(typescript@6.0.3))
|
||||
'@vueuse/integrations':
|
||||
specifier: ^15.0.0
|
||||
version: 15.0.0(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(sortablejs@1.15.7)(vue@3.5.45(typescript@6.0.3))
|
||||
version: 15.0.0(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(sortablejs@1.15.7)(vue@3.5.46(typescript@6.0.3))
|
||||
axios:
|
||||
specifier: ^1.21.1
|
||||
version: 1.21.1(debug@4.4.3)
|
||||
@@ -232,10 +232,10 @@ importers:
|
||||
version: 3.15.1
|
||||
pinia:
|
||||
specifier: ^4.1.0
|
||||
version: 4.1.0(@vue/devtools-api@8.2.1)(typescript@6.0.3)(vue@3.5.45(typescript@6.0.3))
|
||||
version: 4.1.0(@vue/devtools-api@8.2.1)(typescript@6.0.3)(vue@3.5.46(typescript@6.0.3))
|
||||
pinia-plugin-persistedstate:
|
||||
specifier: ^4.7.1
|
||||
version: 4.7.1(pinia@4.1.0(@vue/devtools-api@8.2.1)(typescript@6.0.3)(vue@3.5.45(typescript@6.0.3)))
|
||||
version: 4.7.1(pinia@4.1.0(@vue/devtools-api@8.2.1)(typescript@6.0.3)(vue@3.5.46(typescript@6.0.3)))
|
||||
semver:
|
||||
specifier: ^7.8.6
|
||||
version: 7.8.6
|
||||
@@ -243,24 +243,24 @@ importers:
|
||||
specifier: ^1.15.7
|
||||
version: 1.15.7
|
||||
vue:
|
||||
specifier: ^3.5.45
|
||||
version: 3.5.45(typescript@6.0.3)
|
||||
specifier: ^3.5.46
|
||||
version: 3.5.46(typescript@6.0.3)
|
||||
vue-i18n:
|
||||
specifier: 11.4.20
|
||||
version: 11.4.20(vue@3.5.45(typescript@6.0.3))
|
||||
specifier: 11.4.23
|
||||
version: 11.4.23(vue@3.5.46(typescript@6.0.3))
|
||||
vue-router:
|
||||
specifier: ^5.5.1
|
||||
version: 5.5.1(@vue/compiler-sfc@3.5.45)(pinia@4.1.0(@vue/devtools-api@8.2.1)(typescript@6.0.3)(vue@3.5.45(typescript@6.0.3)))(rolldown@1.2.8)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.45(typescript@6.0.3))
|
||||
version: 5.5.1(@vue/compiler-sfc@3.5.46)(pinia@4.1.0(@vue/devtools-api@8.2.1)(typescript@6.0.3)(vue@3.5.46(typescript@6.0.3)))(rolldown@1.2.8)(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))
|
||||
devDependencies:
|
||||
'@antfu/eslint-config':
|
||||
specifier: ^10.0.0
|
||||
version: 10.0.0(@typescript-eslint/typescript-estree@8.72.0(typescript@6.0.3))(@typescript-eslint/utils@8.72.0(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3))(@vue/compiler-sfc@3.5.45)(eslint-plugin-format@2.0.1(eslint@10.15.0(jiti@2.7.0)))(eslint-plugin-vuejs-accessibility@2.6.3(eslint@10.15.0(jiti@2.7.0))(globals@17.13.0))(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3)
|
||||
version: 10.0.0(@typescript-eslint/typescript-estree@8.72.0(typescript@6.0.3))(@typescript-eslint/utils@8.72.0(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3))(@vue/compiler-sfc@3.5.46)(eslint-plugin-format@2.0.1(eslint@10.15.0(jiti@2.7.0)))(eslint-plugin-vuejs-accessibility@2.6.3(eslint@10.15.0(jiti@2.7.0))(globals@17.13.0))(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3)
|
||||
'@intlify/eslint-plugin-vue-i18n':
|
||||
specifier: 4.5.1
|
||||
version: 4.5.1(eslint@10.15.0(jiti@2.7.0))(jsonc-eslint-parser@3.3.0)(vue-eslint-parser@10.4.1(eslint@10.15.0(jiti@2.7.0)))(yaml-eslint-parser@2.1.0)
|
||||
'@intlify/unplugin-vue-i18n':
|
||||
specifier: 11.2.8
|
||||
version: 11.2.8(typescript@6.0.3)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue-i18n@11.4.20(vue@3.5.45(typescript@6.0.3)))(vue@3.5.45(typescript@6.0.3))
|
||||
version: 11.2.8(typescript@6.0.3)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue-i18n@11.4.23(vue@3.5.46(typescript@6.0.3)))(vue@3.5.46(typescript@6.0.3))
|
||||
'@tailwindcss/vite':
|
||||
specifier: ^4.3.5
|
||||
version: 4.3.5(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))
|
||||
@@ -278,10 +278,10 @@ importers:
|
||||
version: 1.15.9
|
||||
'@vitejs/plugin-vue':
|
||||
specifier: ^6.0.11
|
||||
version: 6.0.11(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.45(typescript@6.0.3))
|
||||
version: 6.0.11(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))
|
||||
'@vue/tsconfig':
|
||||
specifier: ^0.9.1
|
||||
version: 0.9.1(typescript@6.0.3)(vue@3.5.45(typescript@6.0.3))
|
||||
version: 0.9.1(typescript@6.0.3)(vue@3.5.46(typescript@6.0.3))
|
||||
eslint:
|
||||
specifier: ^10.15.0
|
||||
version: 10.15.0(jiti@2.7.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/498a491ea97dbb8c5cedbffd97064edab6969341':
|
||||
resolution: {gitHosted: true, integrity: sha512-/3G0XsMSCcijhwvwHL7HNLLaI9sEL03m0DDX/aVVGvqu13qsqn6rrsoBvSMgxjYgsvfd5ZnzvbI+ZCva8n/rhQ==, tarball: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/498a491ea97dbb8c5cedbffd97064edab6969341}
|
||||
version: 0.13.0
|
||||
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/501495d5b1e9d65840d4cdee5e0e228f361613ee':
|
||||
resolution: {gitHosted: true, integrity: sha512-pPner6XWo+saTWErInK+LLSUxbSmTtd274hrWorFnOfLqDNN2cTwl1UwDsPvaRShl7jy4dVxPC5vDWAgszwdZQ==, tarball: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/501495d5b1e9d65840d4cdee5e0e228f361613ee}
|
||||
version: 0.13.1
|
||||
engines: {node: '>=24'}
|
||||
peerDependencies:
|
||||
vite: ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0
|
||||
@@ -780,16 +780,16 @@ packages:
|
||||
resolution: {integrity: sha512-xB8nMdMRLNx7b0zPvrHy0+N9uq9Vfi1aUxHqWgn2e2/TbjCKy8HfoFpnUXXxVP8I0p1ccd6LFSC3XsFjZ3vweA==}
|
||||
engines: {node: '>= 22'}
|
||||
|
||||
'@intlify/core-base@11.4.20':
|
||||
resolution: {integrity: sha512-i3/0mXXMAjK8SLX/t1l+sG3SIzghYSM2rLnHfMLHqUlKa/ysuwqSkGLU4UQem+SkeAge+5ol5mCMspKIhWfMrg==}
|
||||
'@intlify/core-base@11.4.23':
|
||||
resolution: {integrity: sha512-V8a3BQ7iTVPDetJ/LJfGn3lDx4Ir35OjjO4BLgVrFuL+0egWzwUyfdLIPAEYWlMGdo14eC5p6uk3tSlTYY0YmQ==}
|
||||
engines: {node: '>= 22'}
|
||||
|
||||
'@intlify/devtools-types@11.4.16':
|
||||
resolution: {integrity: sha512-Bl7arICsKgwcSEQuZJun3swenN4jwSpg35lCpijFznYbW9GvkfH4wLxcI5+gz7d/EHqu66UT9CZDIdnQdgMAGg==}
|
||||
engines: {node: '>= 22'}
|
||||
|
||||
'@intlify/devtools-types@11.4.20':
|
||||
resolution: {integrity: sha512-8U2tY0MaWqI47pzSTUuFCFxIvBa6uWguW++4ftjdE7lWaRIKEhAFRDGKKNd5lw8wurerJ0URuZpxifHCduLQ6A==}
|
||||
'@intlify/devtools-types@11.4.23':
|
||||
resolution: {integrity: sha512-zuWkolaeK8ej5z7L9Ss7FLIBHgE8ZF+XcwV1o/vQ7IKagiDg/IosA7fOa2HUFVMW5yT2ugph9rshevHGzcowBQ==}
|
||||
engines: {node: '>= 22'}
|
||||
|
||||
'@intlify/eslint-plugin-vue-i18n@4.5.1':
|
||||
@@ -805,16 +805,16 @@ packages:
|
||||
resolution: {integrity: sha512-p4lDWmBAsi3ja+PuEfPRavYyvqkYn/Upxz7UpnyI9LgIIy8XawcGIDzN+k99Z+99etO3HmDXGeTxnJIJGgSZ+g==}
|
||||
engines: {node: '>= 22'}
|
||||
|
||||
'@intlify/message-compiler@11.4.20':
|
||||
resolution: {integrity: sha512-0pwXAYOG+jGkAJ+H/TPsfeqnHiEqYU99fXN5vlSYdknuBPjo8NEqi0L5WFgmqOnwSPtmIOoi84BDYhrligDcoA==}
|
||||
'@intlify/message-compiler@11.4.23':
|
||||
resolution: {integrity: sha512-HgmnQV/lBBX8KgxoNwngzzq8DLw/jECJgz9eBfQGdkEYte7Bw1RSqhIskcWp0DEWrSg2wijUi6dJjpq1WUD+zg==}
|
||||
engines: {node: '>= 22'}
|
||||
|
||||
'@intlify/shared@11.4.16':
|
||||
resolution: {integrity: sha512-xehmkbEgbbNh/V+d8r3hFup0ViaN29YTJSAfRr28C54rxjyZEO0RNQKqW7VVajj16gLdglotNjiq+sIVNtHGzw==}
|
||||
engines: {node: '>= 22'}
|
||||
|
||||
'@intlify/shared@11.4.20':
|
||||
resolution: {integrity: sha512-qg2pOSUU5Xr2fHZCmluah8h/g/4MG5RfzIZBVR8Id0/c2EKsCPtWvamSiVtwc+4VvYnEGQxZast7uQMTb6jP9A==}
|
||||
'@intlify/shared@11.4.23':
|
||||
resolution: {integrity: sha512-1iqGalDCOlHZ8y7LOC3yisSm52K5AmkTmaNO23XGFYWU6Z1oIX8VeAGRq9rn2KrDFb8nMtQaxNyMa1n8EeDm5g==}
|
||||
engines: {node: '>= 22'}
|
||||
|
||||
'@intlify/unplugin-vue-i18n@11.2.8':
|
||||
@@ -880,8 +880,8 @@ packages:
|
||||
'@keyv/serialize@1.1.1':
|
||||
resolution: {integrity: sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA==}
|
||||
|
||||
'@lucide/vue@1.73.0':
|
||||
resolution: {integrity: sha512-QVVRSgu2rqRX3NAUktT9venW0Bvtr03aCZjhFRLwnV3uqLyR7KCTOx5mMlukhw0aiyjC3D6w2b+fmy4MeM5R3Q==}
|
||||
'@lucide/vue@1.77.0':
|
||||
resolution: {integrity: sha512-B+okr/d8qC2imLzNPJ5tW8Nf7uKC19DgiOafxU0bOMfLnkd5Tkss4GW640+s5FierTJjgl99LpuO40u+yni0qQ==}
|
||||
peerDependencies:
|
||||
vue: '>=3.0.1'
|
||||
|
||||
@@ -1519,18 +1519,30 @@ packages:
|
||||
'@vue/compiler-core@3.5.45':
|
||||
resolution: {integrity: sha512-XGHJrM6ufZARAc/w+tyOswStw9tdKiqCKBScI4gGaNxD+aaGu/HQWgKJ+JItjRLPqenQ7iE7G8AJC7T5ew1p+g==}
|
||||
|
||||
'@vue/compiler-core@3.5.46':
|
||||
resolution: {integrity: sha512-yb+N8/mgBcoeqCJPVyJI/D3OphLrSMXnB3ZQUNmRLU/1fsMW4bFfdJWNi9oIj7+EA3ULKKkP7b/VCpcYQYeiuQ==}
|
||||
|
||||
'@vue/compiler-dom@3.5.44':
|
||||
resolution: {integrity: sha512-W5AoBFWdw1lQAKiHowkfgFKFab82oSRT6sGsPfw/q1GRjsy/ZJFLHGhJyBRIFN9APLTUduDH9U2JAiPOIyKuYg==}
|
||||
|
||||
'@vue/compiler-dom@3.5.45':
|
||||
resolution: {integrity: sha512-LbP2d19GSOYGPmvMBBCVJVlv7TKtjM1Cfeyu3cYia720pknZP+1cLX7H5MVatvruT6MuJhiPuNbQBW/MDn/EwA==}
|
||||
|
||||
'@vue/compiler-dom@3.5.46':
|
||||
resolution: {integrity: sha512-Bj3lCSw3DQnDRDxw115XqdLDd0+18Nftlgd8OXSGG+ud74hxJIE17eYrM+VWgQrTMsvJbLh9Hzf2MkwAzru36Q==}
|
||||
|
||||
'@vue/compiler-sfc@3.5.45':
|
||||
resolution: {integrity: sha512-MKFjb2UX0M/l/jhfzqMLrI8VM4pfvFKG3pqFZkSZFHRLtNld/O4RtUPZFWSwhro/14qP88UQEkWzHxAZAQ0tsw==}
|
||||
|
||||
'@vue/compiler-sfc@3.5.46':
|
||||
resolution: {integrity: sha512-hjUvMxGh+QIgegwksfp6BRBYleE/a8veZHvTR6sa+o+bM4HU+WnrUZlhN0X+pDcsl8Lhwmbu72xPvLMk3XUwog==}
|
||||
|
||||
'@vue/compiler-ssr@3.5.45':
|
||||
resolution: {integrity: sha512-RF5sbZOfYz5AK00tOJUn2PwFXR2fS1u2HVzI8D9VF9rGAFxuGBqg2bB1kJ3ZHMprqSltXnT9MZE1IsqjSM8oew==}
|
||||
|
||||
'@vue/compiler-ssr@3.5.46':
|
||||
resolution: {integrity: sha512-qebChL3aP0m1k+TlSf+fZWvOwAf3flBCi5o+n01ykR3DX4mTIWheFltmoiQ12+z66/4cGeXqbB2P7sPWkGhQNQ==}
|
||||
|
||||
'@vue/devtools-api@6.6.4':
|
||||
resolution: {integrity: sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g==}
|
||||
|
||||
@@ -1546,17 +1558,17 @@ packages:
|
||||
'@vue/language-core@3.3.14':
|
||||
resolution: {integrity: sha512-kRB+3hHg0c+BdD1XLAvwjVMQd5pC05zijSlPDRI3ERvC/s04JlRs5upy2KjeMg/9m9oD5zuMVh9yVvkKfZqoJg==}
|
||||
|
||||
'@vue/reactivity@3.5.45':
|
||||
resolution: {integrity: sha512-WqkyubNWpI4OYBOipSrjIssMdJO8K1i9Zts/Wm8Er10/0msOEwCyWWWvZnAI7WW3kQsTong6DJp8Cbb+vd4cPA==}
|
||||
'@vue/reactivity@3.5.46':
|
||||
resolution: {integrity: sha512-+FHtYTvGxgFoX3oRs7soz6JHizGv50Q26WJN6PWtXuTLXRfkfUpDUTRuoTA/kiZVVt8NMeMpsPQLh9h++ReUjQ==}
|
||||
|
||||
'@vue/runtime-core@3.5.45':
|
||||
resolution: {integrity: sha512-bzIO3+FABjpj85uIKSc+Qnj36/sxDNI3tcH9i6w6xKA1k6e0ejv0G0jMCfeJBvK3yGL5XbJ3DMZj+ClqyCHFYw==}
|
||||
'@vue/runtime-core@3.5.46':
|
||||
resolution: {integrity: sha512-eJUzKAUaHAmtnys/l9qduPzUnBrYMkmsCU7TN+vbSOSpm8kcETT7nacKxIO4MBej/XiOraVzq+lSeZv7o1//jQ==}
|
||||
|
||||
'@vue/runtime-dom@3.5.45':
|
||||
resolution: {integrity: sha512-ZvRTFMDgfqTDYWvJfoVpQTJx1RN5M6l7Pyd6wfdY2NaXzbPQVh9ezeQYFbNPP6bIcRVn2SqSSR25N/jSW69BFw==}
|
||||
'@vue/runtime-dom@3.5.46':
|
||||
resolution: {integrity: sha512-6L7lbBvXTYBFFjIt25a0pgdpmn3Ns8RqUnNVibRzF4bgyiWJvqOhKEV5MXYWKlCttZE3aGeJN8mveo+6IrIKXA==}
|
||||
|
||||
'@vue/server-renderer@3.5.45':
|
||||
resolution: {integrity: sha512-1fNXUHhhsWf4EVL4XixbGBU5mKdiIXJAB82feHRTyPPo6ZUEYWIJuEeUl3mVV6QDBp50HJOX4obLhxYXlrjrzA==}
|
||||
'@vue/server-renderer@3.5.46':
|
||||
resolution: {integrity: sha512-4mc0YWREc6OZ5pDCigvKPDzIUV+aciiH92yvyTS6xaHHxW/80rMceQQn11pYe7OEEBt2YQgYWR9zF8QF30GJUQ==}
|
||||
|
||||
'@vue/shared@3.5.44':
|
||||
resolution: {integrity: sha512-H82XLH0DjmSOdbEwO15x3QTo1f5PWEtv237eLpYKc0mqLu+B8hnq16lFWmuBmNurkeiG3wr+oM1FhOll/YVFRg==}
|
||||
@@ -1564,6 +1576,9 @@ packages:
|
||||
'@vue/shared@3.5.45':
|
||||
resolution: {integrity: sha512-ue9fgHmVNPlP7iW3+cxoBX/Cnlw53dHlVSw0JKGY6z1lObg8pHoj928M2nzG4/yVsMZ3NaRZ2s2z61uC16NDwQ==}
|
||||
|
||||
'@vue/shared@3.5.46':
|
||||
resolution: {integrity: sha512-P1WePbdzHrcIciWtmY2Im9EFhdakd3rZxYqvalOa3SfoxtF35Q8Uhmj1tKn6bWP4utcOpN8ao6BoJUItq0Uf+g==}
|
||||
|
||||
'@vue/tsconfig@0.9.1':
|
||||
resolution: {integrity: sha512-buvjm+9NzLCJL29KY1j1991YYJ5e6275OiK+G4jtmfIb+z4POywbdm0wXusT9adVWqe0xqg70TbI7+mRx4uU9w==}
|
||||
peerDependencies:
|
||||
@@ -1854,8 +1869,8 @@ packages:
|
||||
engines: {node: '>=4'}
|
||||
hasBin: true
|
||||
|
||||
csstype@3.2.3:
|
||||
resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}
|
||||
csstype@3.2.4:
|
||||
resolution: {integrity: sha512-PoKaoPzQapnEoqUSnHx1u6W6ku8CVEgKsnpmmzU3m1nwkidpPBQ8V/Zq2+bWNrsOKoKLwTGdbx6xF7BXP1zLVQ==}
|
||||
|
||||
dayjs@1.11.23:
|
||||
resolution: {integrity: sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ==}
|
||||
@@ -3103,6 +3118,10 @@ packages:
|
||||
resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
source-map-js@1.2.4:
|
||||
resolution: {integrity: sha512-J7ZjMvHd9O1fcT/5V09QWaaSl2BbWx3F6O08spde82Namf9UB0GxRVIPiNbVsdKkoizHiSpTodo3vp2bAy91MA==}
|
||||
engines: {node: '>=6.0.0'}
|
||||
|
||||
source-map@0.7.6:
|
||||
resolution: {integrity: sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==}
|
||||
engines: {node: '>= 12'}
|
||||
@@ -3348,8 +3367,8 @@ packages:
|
||||
peerDependencies:
|
||||
eslint: ^8.57.0 || ^9.0.0 || ^10.0.0
|
||||
|
||||
vue-i18n@11.4.20:
|
||||
resolution: {integrity: sha512-gyUMq9f+5T3ZvmkjWy+0dzKesaTVN95JdRzjJPW0qKrzFKy/NOqA0wMw9MPraMjTAjHmBhhRA4AwQOnoKztPEw==}
|
||||
vue-i18n@11.4.23:
|
||||
resolution: {integrity: sha512-O+H2L/LF9xzklv2PZEqYAaG0rrbQokm6aX6/gPDxdtokBSDhKm+lvEPVbC3hXdvKpN5ICSBWigIkJ06AzCs3Lw==}
|
||||
engines: {node: '>= 22'}
|
||||
peerDependencies:
|
||||
vue: ^3.0.0
|
||||
@@ -3378,8 +3397,8 @@ packages:
|
||||
peerDependencies:
|
||||
typescript: '>=5.0.0'
|
||||
|
||||
vue@3.5.45:
|
||||
resolution: {integrity: sha512-3cvsib8m9c0vB24+MDKsgcW4+Da4xaBl9Z/5Tbm2pmSIsRPxcil4cdXjXlVsmJ2g64XJo5h+IRd7rsdGT9pZaw==}
|
||||
vue@3.5.46:
|
||||
resolution: {integrity: sha512-0kW5CgfjMPBqmH158049SaE1muufp+K/ZyrwvSEwrwYky6QB7zL2y8kXfruneKb9O12eh0xAJL6CVSpzb9o0Kg==}
|
||||
peerDependencies:
|
||||
typescript: '*'
|
||||
peerDependenciesMeta:
|
||||
@@ -3446,7 +3465,7 @@ snapshots:
|
||||
|
||||
'@ant-design/fast-color@3.0.1': {}
|
||||
|
||||
'@antfu/eslint-config@10.0.0(@typescript-eslint/typescript-estree@8.72.0(typescript@6.0.3))(@typescript-eslint/utils@8.72.0(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3))(@vue/compiler-sfc@3.5.45)(eslint-plugin-format@2.0.1(eslint@10.15.0(jiti@2.7.0)))(eslint-plugin-vuejs-accessibility@2.6.3(eslint@10.15.0(jiti@2.7.0))(globals@17.13.0))(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3)':
|
||||
'@antfu/eslint-config@10.0.0(@typescript-eslint/typescript-estree@8.72.0(typescript@6.0.3))(@typescript-eslint/utils@8.72.0(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3))(@vue/compiler-sfc@3.5.46)(eslint-plugin-format@2.0.1(eslint@10.15.0(jiti@2.7.0)))(eslint-plugin-vuejs-accessibility@2.6.3(eslint@10.15.0(jiti@2.7.0))(globals@17.13.0))(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3)':
|
||||
dependencies:
|
||||
'@antfu/install-pkg': 2.1.0
|
||||
'@clack/prompts': 1.8.1
|
||||
@@ -3478,7 +3497,7 @@ snapshots:
|
||||
eslint-plugin-unused-imports: 4.4.1(@typescript-eslint/eslint-plugin@8.72.0(@typescript-eslint/parser@8.72.0(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.15.0(jiti@2.7.0))
|
||||
eslint-plugin-vue: 10.11.1(@stylistic/eslint-plugin@5.10.0(eslint@10.15.0(jiti@2.7.0)))(@typescript-eslint/parser@8.72.0(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.15.0(jiti@2.7.0))(vue-eslint-parser@10.4.1(eslint@10.15.0(jiti@2.7.0)))
|
||||
eslint-plugin-yml: 3.9.0(eslint@10.15.0(jiti@2.7.0))
|
||||
eslint-processor-vue-blocks: 2.0.0(@vue/compiler-sfc@3.5.45)(eslint@10.15.0(jiti@2.7.0))
|
||||
eslint-processor-vue-blocks: 2.0.0(@vue/compiler-sfc@3.5.46)(eslint@10.15.0(jiti@2.7.0))
|
||||
globals: 17.13.0
|
||||
local-pkg: 1.2.1
|
||||
parse-gitignore: 2.0.0
|
||||
@@ -3543,9 +3562,9 @@ snapshots:
|
||||
'@babel/helper-string-parser': 8.0.6
|
||||
'@babel/helper-validator-identifier': 8.0.6
|
||||
|
||||
'@boxicons/vue@1.0.1(vue@3.5.45(typescript@6.0.3))':
|
||||
'@boxicons/vue@1.0.1(vue@3.5.46(typescript@6.0.3))':
|
||||
dependencies:
|
||||
vue: 3.5.45(typescript@6.0.3)
|
||||
vue: 3.5.46(typescript@6.0.3)
|
||||
|
||||
'@cacheable/memory@2.2.0':
|
||||
dependencies:
|
||||
@@ -3571,14 +3590,14 @@ snapshots:
|
||||
fast-wrap-ansi: 0.2.2
|
||||
sisteransi: 1.0.5
|
||||
|
||||
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/498a491ea97dbb8c5cedbffd97064edab6969341(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.45(typescript@6.0.3))(yaml@2.9.0)':
|
||||
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/501495d5b1e9d65840d4cdee5e0e228f361613ee(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
|
||||
'@lucide/vue': 1.73.0(vue@3.5.45(typescript@6.0.3))
|
||||
'@lucide/vue': 1.77.0(vue@3.5.46(typescript@6.0.3))
|
||||
'@rc-component/async-validator': 6.0.0
|
||||
'@vueuse/core': 15.0.0(vue@3.5.45(typescript@6.0.3))
|
||||
'@vueuse/integrations': 15.0.0(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(sortablejs@1.15.7)(vue@3.5.45(typescript@6.0.3))
|
||||
'@vueuse/core': 15.0.0(vue@3.5.46(typescript@6.0.3))
|
||||
'@vueuse/integrations': 15.0.0(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(sortablejs@1.15.7)(vue@3.5.46(typescript@6.0.3))
|
||||
dayjs: 1.11.23
|
||||
dompurify: 3.4.17
|
||||
es-toolkit: 1.53.2
|
||||
@@ -3587,7 +3606,7 @@ snapshots:
|
||||
marked-alert: 2.1.2(marked@18.1.0)
|
||||
postcss-load-config: 6.0.1(jiti@2.7.0)(postcss@8.5.30)(yaml@2.9.0)
|
||||
sortablejs: 1.15.7
|
||||
vue: 3.5.45(typescript@6.0.3)
|
||||
vue: 3.5.46(typescript@6.0.3)
|
||||
optionalDependencies:
|
||||
vite: 8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0)
|
||||
transitivePeerDependencies:
|
||||
@@ -3854,7 +3873,7 @@ snapshots:
|
||||
|
||||
'@humanwhocodes/retry@0.4.3': {}
|
||||
|
||||
'@intlify/bundle-utils@11.2.8(vue-i18n@11.4.20(vue@3.5.45(typescript@6.0.3)))':
|
||||
'@intlify/bundle-utils@11.2.8(vue-i18n@11.4.23(vue@3.5.46(typescript@6.0.3)))':
|
||||
dependencies:
|
||||
'@intlify/message-compiler': 11.4.16
|
||||
'@intlify/shared': 11.4.16
|
||||
@@ -3864,7 +3883,7 @@ snapshots:
|
||||
source-map-js: 1.2.2
|
||||
yaml-eslint-parser: 1.3.2
|
||||
optionalDependencies:
|
||||
vue-i18n: 11.4.20(vue@3.5.45(typescript@6.0.3))
|
||||
vue-i18n: 11.4.23(vue@3.5.46(typescript@6.0.3))
|
||||
|
||||
'@intlify/core-base@11.4.16':
|
||||
dependencies:
|
||||
@@ -3872,21 +3891,21 @@ snapshots:
|
||||
'@intlify/message-compiler': 11.4.16
|
||||
'@intlify/shared': 11.4.16
|
||||
|
||||
'@intlify/core-base@11.4.20':
|
||||
'@intlify/core-base@11.4.23':
|
||||
dependencies:
|
||||
'@intlify/devtools-types': 11.4.20
|
||||
'@intlify/message-compiler': 11.4.20
|
||||
'@intlify/shared': 11.4.20
|
||||
'@intlify/devtools-types': 11.4.23
|
||||
'@intlify/message-compiler': 11.4.23
|
||||
'@intlify/shared': 11.4.23
|
||||
|
||||
'@intlify/devtools-types@11.4.16':
|
||||
dependencies:
|
||||
'@intlify/core-base': 11.4.16
|
||||
'@intlify/shared': 11.4.16
|
||||
|
||||
'@intlify/devtools-types@11.4.20':
|
||||
'@intlify/devtools-types@11.4.23':
|
||||
dependencies:
|
||||
'@intlify/core-base': 11.4.20
|
||||
'@intlify/shared': 11.4.20
|
||||
'@intlify/core-base': 11.4.23
|
||||
'@intlify/shared': 11.4.23
|
||||
|
||||
'@intlify/eslint-plugin-vue-i18n@4.5.1(eslint@10.15.0(jiti@2.7.0))(jsonc-eslint-parser@3.3.0)(vue-eslint-parser@10.4.1(eslint@10.15.0(jiti@2.7.0)))(yaml-eslint-parser@2.1.0)':
|
||||
dependencies:
|
||||
@@ -3917,20 +3936,20 @@ snapshots:
|
||||
'@intlify/shared': 11.4.16
|
||||
source-map-js: 1.2.2
|
||||
|
||||
'@intlify/message-compiler@11.4.20':
|
||||
'@intlify/message-compiler@11.4.23':
|
||||
dependencies:
|
||||
'@intlify/shared': 11.4.20
|
||||
source-map-js: 1.2.2
|
||||
'@intlify/shared': 11.4.23
|
||||
source-map-js: 1.2.4
|
||||
|
||||
'@intlify/shared@11.4.16': {}
|
||||
|
||||
'@intlify/shared@11.4.20': {}
|
||||
'@intlify/shared@11.4.23': {}
|
||||
|
||||
'@intlify/unplugin-vue-i18n@11.2.8(typescript@6.0.3)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue-i18n@11.4.20(vue@3.5.45(typescript@6.0.3)))(vue@3.5.45(typescript@6.0.3))':
|
||||
'@intlify/unplugin-vue-i18n@11.2.8(typescript@6.0.3)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue-i18n@11.4.23(vue@3.5.46(typescript@6.0.3)))(vue@3.5.46(typescript@6.0.3))':
|
||||
dependencies:
|
||||
'@intlify/bundle-utils': 11.2.8(vue-i18n@11.4.20(vue@3.5.45(typescript@6.0.3)))
|
||||
'@intlify/bundle-utils': 11.2.8(vue-i18n@11.4.23(vue@3.5.46(typescript@6.0.3)))
|
||||
'@intlify/shared': 11.4.16
|
||||
'@intlify/vue-i18n-extensions': 9.0.0(@intlify/shared@11.4.16)(vue-i18n@11.4.20(vue@3.5.45(typescript@6.0.3)))(vue@3.5.45(typescript@6.0.3))
|
||||
'@intlify/vue-i18n-extensions': 9.0.0(@intlify/shared@11.4.16)(vue-i18n@11.4.23(vue@3.5.46(typescript@6.0.3)))(vue@3.5.46(typescript@6.0.3))
|
||||
'@rollup/pluginutils': 5.4.0
|
||||
'@typescript-eslint/scope-manager': 8.72.0
|
||||
'@typescript-eslint/typescript-estree': 8.72.0(typescript@6.0.3)
|
||||
@@ -3939,23 +3958,23 @@ snapshots:
|
||||
picocolors: 1.1.1
|
||||
tinyglobby: 0.2.17
|
||||
unplugin: 2.3.11
|
||||
vue: 3.5.45(typescript@6.0.3)
|
||||
vue: 3.5.46(typescript@6.0.3)
|
||||
optionalDependencies:
|
||||
vite: 8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0)
|
||||
vue-i18n: 11.4.20(vue@3.5.45(typescript@6.0.3))
|
||||
vue-i18n: 11.4.23(vue@3.5.46(typescript@6.0.3))
|
||||
transitivePeerDependencies:
|
||||
- rollup
|
||||
- supports-color
|
||||
- typescript
|
||||
|
||||
'@intlify/vue-i18n-extensions@9.0.0(@intlify/shared@11.4.16)(vue-i18n@11.4.20(vue@3.5.45(typescript@6.0.3)))(vue@3.5.45(typescript@6.0.3))':
|
||||
'@intlify/vue-i18n-extensions@9.0.0(@intlify/shared@11.4.16)(vue-i18n@11.4.23(vue@3.5.46(typescript@6.0.3)))(vue@3.5.46(typescript@6.0.3))':
|
||||
dependencies:
|
||||
'@babel/parser': 7.29.9
|
||||
'@vue/compiler-dom': 3.5.44
|
||||
optionalDependencies:
|
||||
'@intlify/shared': 11.4.16
|
||||
vue: 3.5.45(typescript@6.0.3)
|
||||
vue-i18n: 11.4.20(vue@3.5.45(typescript@6.0.3))
|
||||
vue: 3.5.46(typescript@6.0.3)
|
||||
vue-i18n: 11.4.23(vue@3.5.46(typescript@6.0.3))
|
||||
|
||||
'@isaacs/cliui@8.0.2':
|
||||
dependencies:
|
||||
@@ -3995,9 +4014,9 @@ snapshots:
|
||||
|
||||
'@keyv/serialize@1.1.1': {}
|
||||
|
||||
'@lucide/vue@1.73.0(vue@3.5.45(typescript@6.0.3))':
|
||||
'@lucide/vue@1.77.0(vue@3.5.46(typescript@6.0.3))':
|
||||
dependencies:
|
||||
vue: 3.5.45(typescript@6.0.3)
|
||||
vue: 3.5.46(typescript@6.0.3)
|
||||
|
||||
'@napi-rs/wasm-runtime@1.2.6(@emnapi/core@2.0.0-beta.2)(@emnapi/runtime@2.0.0-beta.2)':
|
||||
dependencies:
|
||||
@@ -4401,11 +4420,11 @@ snapshots:
|
||||
'@typescript-eslint/types': 8.72.0
|
||||
eslint-visitor-keys: 5.0.1
|
||||
|
||||
'@vitejs/plugin-vue@6.0.11(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.45(typescript@6.0.3))':
|
||||
'@vitejs/plugin-vue@6.0.11(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))':
|
||||
dependencies:
|
||||
'@rolldown/pluginutils': 1.0.1
|
||||
vite: 8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0)
|
||||
vue: 3.5.45(typescript@6.0.3)
|
||||
vue: 3.5.46(typescript@6.0.3)
|
||||
|
||||
'@vitest/eslint-plugin@1.6.28(@typescript-eslint/eslint-plugin@8.72.0(@typescript-eslint/parser@8.72.0(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.15.0(jiti@2.7.0))(typescript@6.0.3)':
|
||||
dependencies:
|
||||
@@ -4442,7 +4461,7 @@ snapshots:
|
||||
optionalDependencies:
|
||||
typescript: 6.0.3
|
||||
|
||||
'@vue-macros/common@3.1.4(vue@3.5.45(typescript@6.0.3))':
|
||||
'@vue-macros/common@3.1.4(vue@3.5.46(typescript@6.0.3))':
|
||||
dependencies:
|
||||
'@vue/compiler-sfc': 3.5.45
|
||||
ast-kit: 2.2.0
|
||||
@@ -4450,7 +4469,7 @@ snapshots:
|
||||
magic-string-ast: 1.0.3
|
||||
unplugin-utils: 0.3.2
|
||||
optionalDependencies:
|
||||
vue: 3.5.45(typescript@6.0.3)
|
||||
vue: 3.5.46(typescript@6.0.3)
|
||||
|
||||
'@vue/compiler-core@3.5.44':
|
||||
dependencies:
|
||||
@@ -4468,6 +4487,14 @@ snapshots:
|
||||
estree-walker: 2.0.2
|
||||
source-map-js: 1.2.2
|
||||
|
||||
'@vue/compiler-core@3.5.46':
|
||||
dependencies:
|
||||
'@babel/parser': 7.29.13
|
||||
'@vue/shared': 3.5.46
|
||||
entities: 7.0.1
|
||||
estree-walker: 2.0.2
|
||||
source-map-js: 1.2.4
|
||||
|
||||
'@vue/compiler-dom@3.5.44':
|
||||
dependencies:
|
||||
'@vue/compiler-core': 3.5.44
|
||||
@@ -4478,6 +4505,11 @@ snapshots:
|
||||
'@vue/compiler-core': 3.5.45
|
||||
'@vue/shared': 3.5.45
|
||||
|
||||
'@vue/compiler-dom@3.5.46':
|
||||
dependencies:
|
||||
'@vue/compiler-core': 3.5.46
|
||||
'@vue/shared': 3.5.46
|
||||
|
||||
'@vue/compiler-sfc@3.5.45':
|
||||
dependencies:
|
||||
'@babel/parser': 7.29.13
|
||||
@@ -4490,11 +4522,28 @@ snapshots:
|
||||
postcss: 8.5.32
|
||||
source-map-js: 1.2.2
|
||||
|
||||
'@vue/compiler-sfc@3.5.46':
|
||||
dependencies:
|
||||
'@babel/parser': 7.29.13
|
||||
'@vue/compiler-core': 3.5.46
|
||||
'@vue/compiler-dom': 3.5.46
|
||||
'@vue/compiler-ssr': 3.5.46
|
||||
'@vue/shared': 3.5.46
|
||||
estree-walker: 2.0.2
|
||||
magic-string: 0.30.21
|
||||
postcss: 8.5.32
|
||||
source-map-js: 1.2.4
|
||||
|
||||
'@vue/compiler-ssr@3.5.45':
|
||||
dependencies:
|
||||
'@vue/compiler-dom': 3.5.45
|
||||
'@vue/shared': 3.5.45
|
||||
|
||||
'@vue/compiler-ssr@3.5.46':
|
||||
dependencies:
|
||||
'@vue/compiler-dom': 3.5.46
|
||||
'@vue/shared': 3.5.46
|
||||
|
||||
'@vue/devtools-api@6.6.4': {}
|
||||
|
||||
'@vue/devtools-api@8.2.1':
|
||||
@@ -4520,49 +4569,51 @@ snapshots:
|
||||
path-browserify: 1.0.1
|
||||
picomatch: 4.0.7
|
||||
|
||||
'@vue/reactivity@3.5.45':
|
||||
'@vue/reactivity@3.5.46':
|
||||
dependencies:
|
||||
'@vue/shared': 3.5.45
|
||||
'@vue/shared': 3.5.46
|
||||
|
||||
'@vue/runtime-core@3.5.45':
|
||||
'@vue/runtime-core@3.5.46':
|
||||
dependencies:
|
||||
'@vue/reactivity': 3.5.45
|
||||
'@vue/shared': 3.5.45
|
||||
'@vue/reactivity': 3.5.46
|
||||
'@vue/shared': 3.5.46
|
||||
|
||||
'@vue/runtime-dom@3.5.45':
|
||||
'@vue/runtime-dom@3.5.46':
|
||||
dependencies:
|
||||
'@vue/reactivity': 3.5.45
|
||||
'@vue/runtime-core': 3.5.45
|
||||
'@vue/shared': 3.5.45
|
||||
csstype: 3.2.3
|
||||
'@vue/reactivity': 3.5.46
|
||||
'@vue/runtime-core': 3.5.46
|
||||
'@vue/shared': 3.5.46
|
||||
csstype: 3.2.4
|
||||
|
||||
'@vue/server-renderer@3.5.45':
|
||||
'@vue/server-renderer@3.5.46':
|
||||
dependencies:
|
||||
'@vue/compiler-ssr': 3.5.45
|
||||
'@vue/runtime-dom': 3.5.45
|
||||
'@vue/shared': 3.5.45
|
||||
'@vue/compiler-ssr': 3.5.46
|
||||
'@vue/runtime-dom': 3.5.46
|
||||
'@vue/shared': 3.5.46
|
||||
|
||||
'@vue/shared@3.5.44': {}
|
||||
|
||||
'@vue/shared@3.5.45': {}
|
||||
|
||||
'@vue/tsconfig@0.9.1(typescript@6.0.3)(vue@3.5.45(typescript@6.0.3))':
|
||||
'@vue/shared@3.5.46': {}
|
||||
|
||||
'@vue/tsconfig@0.9.1(typescript@6.0.3)(vue@3.5.46(typescript@6.0.3))':
|
||||
optionalDependencies:
|
||||
typescript: 6.0.3
|
||||
vue: 3.5.45(typescript@6.0.3)
|
||||
vue: 3.5.46(typescript@6.0.3)
|
||||
|
||||
'@vueuse/core@15.0.0(vue@3.5.45(typescript@6.0.3))':
|
||||
'@vueuse/core@15.0.0(vue@3.5.46(typescript@6.0.3))':
|
||||
dependencies:
|
||||
'@types/web-bluetooth': 0.0.21
|
||||
'@vueuse/metadata': 15.0.0
|
||||
'@vueuse/shared': 15.0.0(vue@3.5.45(typescript@6.0.3))
|
||||
vue: 3.5.45(typescript@6.0.3)
|
||||
'@vueuse/shared': 15.0.0(vue@3.5.46(typescript@6.0.3))
|
||||
vue: 3.5.46(typescript@6.0.3)
|
||||
|
||||
'@vueuse/integrations@15.0.0(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(sortablejs@1.15.7)(vue@3.5.45(typescript@6.0.3))':
|
||||
'@vueuse/integrations@15.0.0(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(sortablejs@1.15.7)(vue@3.5.46(typescript@6.0.3))':
|
||||
dependencies:
|
||||
'@vueuse/core': 15.0.0(vue@3.5.45(typescript@6.0.3))
|
||||
'@vueuse/shared': 15.0.0(vue@3.5.45(typescript@6.0.3))
|
||||
vue: 3.5.45(typescript@6.0.3)
|
||||
'@vueuse/core': 15.0.0(vue@3.5.46(typescript@6.0.3))
|
||||
'@vueuse/shared': 15.0.0(vue@3.5.46(typescript@6.0.3))
|
||||
vue: 3.5.46(typescript@6.0.3)
|
||||
optionalDependencies:
|
||||
axios: 1.21.1(debug@4.4.3)
|
||||
change-case: 5.4.4
|
||||
@@ -4570,9 +4621,9 @@ snapshots:
|
||||
|
||||
'@vueuse/metadata@15.0.0': {}
|
||||
|
||||
'@vueuse/shared@15.0.0(vue@3.5.45(typescript@6.0.3))':
|
||||
'@vueuse/shared@15.0.0(vue@3.5.46(typescript@6.0.3))':
|
||||
dependencies:
|
||||
vue: 3.5.45(typescript@6.0.3)
|
||||
vue: 3.5.46(typescript@6.0.3)
|
||||
|
||||
acorn-jsx@5.3.2(acorn@8.18.0):
|
||||
dependencies:
|
||||
@@ -4767,7 +4818,7 @@ snapshots:
|
||||
|
||||
cssesc@3.0.0: {}
|
||||
|
||||
csstype@3.2.3: {}
|
||||
csstype@3.2.4: {}
|
||||
|
||||
dayjs@1.11.23: {}
|
||||
|
||||
@@ -5134,9 +5185,9 @@ snapshots:
|
||||
natural-compare: 1.4.0
|
||||
yaml-eslint-parser: 2.1.0
|
||||
|
||||
eslint-processor-vue-blocks@2.0.0(@vue/compiler-sfc@3.5.45)(eslint@10.15.0(jiti@2.7.0)):
|
||||
eslint-processor-vue-blocks@2.0.0(@vue/compiler-sfc@3.5.46)(eslint@10.15.0(jiti@2.7.0)):
|
||||
dependencies:
|
||||
'@vue/compiler-sfc': 3.5.45
|
||||
'@vue/compiler-sfc': 3.5.46
|
||||
eslint: 10.15.0(jiti@2.7.0)
|
||||
|
||||
eslint-scope@9.1.2:
|
||||
@@ -6087,17 +6138,17 @@ snapshots:
|
||||
|
||||
picomatch@4.0.7: {}
|
||||
|
||||
pinia-plugin-persistedstate@4.7.1(pinia@4.1.0(@vue/devtools-api@8.2.1)(typescript@6.0.3)(vue@3.5.45(typescript@6.0.3))):
|
||||
pinia-plugin-persistedstate@4.7.1(pinia@4.1.0(@vue/devtools-api@8.2.1)(typescript@6.0.3)(vue@3.5.46(typescript@6.0.3))):
|
||||
dependencies:
|
||||
defu: 6.1.7
|
||||
optionalDependencies:
|
||||
pinia: 4.1.0(@vue/devtools-api@8.2.1)(typescript@6.0.3)(vue@3.5.45(typescript@6.0.3))
|
||||
pinia: 4.1.0(@vue/devtools-api@8.2.1)(typescript@6.0.3)(vue@3.5.46(typescript@6.0.3))
|
||||
|
||||
pinia@4.1.0(@vue/devtools-api@8.2.1)(typescript@6.0.3)(vue@3.5.45(typescript@6.0.3)):
|
||||
pinia@4.1.0(@vue/devtools-api@8.2.1)(typescript@6.0.3)(vue@3.5.46(typescript@6.0.3)):
|
||||
dependencies:
|
||||
'@vue/devtools-api': 8.2.1
|
||||
nostics: 1.2.0
|
||||
vue: 3.5.45(typescript@6.0.3)
|
||||
vue: 3.5.46(typescript@6.0.3)
|
||||
optionalDependencies:
|
||||
typescript: 6.0.3
|
||||
|
||||
@@ -6136,14 +6187,14 @@ snapshots:
|
||||
dependencies:
|
||||
nanoid: 3.3.20
|
||||
picocolors: 1.1.1
|
||||
source-map-js: 1.2.2
|
||||
source-map-js: 1.2.4
|
||||
optional: true
|
||||
|
||||
postcss@8.5.32:
|
||||
dependencies:
|
||||
nanoid: 3.3.20
|
||||
picocolors: 1.1.1
|
||||
source-map-js: 1.2.2
|
||||
source-map-js: 1.2.4
|
||||
|
||||
prelude-ls@1.2.1: {}
|
||||
|
||||
@@ -6256,6 +6307,8 @@ snapshots:
|
||||
|
||||
source-map-js@1.2.2: {}
|
||||
|
||||
source-map-js@1.2.4: {}
|
||||
|
||||
source-map@0.7.6:
|
||||
optional: true
|
||||
|
||||
@@ -6443,17 +6496,17 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
vue-i18n@11.4.20(vue@3.5.45(typescript@6.0.3)):
|
||||
vue-i18n@11.4.23(vue@3.5.46(typescript@6.0.3)):
|
||||
dependencies:
|
||||
'@intlify/core-base': 11.4.20
|
||||
'@intlify/devtools-types': 11.4.20
|
||||
'@intlify/shared': 11.4.20
|
||||
'@intlify/core-base': 11.4.23
|
||||
'@intlify/devtools-types': 11.4.23
|
||||
'@intlify/shared': 11.4.23
|
||||
'@vue/devtools-api': 6.6.4
|
||||
vue: 3.5.45(typescript@6.0.3)
|
||||
vue: 3.5.46(typescript@6.0.3)
|
||||
|
||||
vue-router@5.5.1(@vue/compiler-sfc@3.5.45)(pinia@4.1.0(@vue/devtools-api@8.2.1)(typescript@6.0.3)(vue@3.5.45(typescript@6.0.3)))(rolldown@1.2.8)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.45(typescript@6.0.3)):
|
||||
vue-router@5.5.1(@vue/compiler-sfc@3.5.46)(pinia@4.1.0(@vue/devtools-api@8.2.1)(typescript@6.0.3)(vue@3.5.46(typescript@6.0.3)))(rolldown@1.2.8)(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)):
|
||||
dependencies:
|
||||
'@vue-macros/common': 3.1.4(vue@3.5.45(typescript@6.0.3))
|
||||
'@vue-macros/common': 3.1.4(vue@3.5.46(typescript@6.0.3))
|
||||
'@vue/devtools-api': 8.2.1
|
||||
ast-walker-scope: 0.10.0
|
||||
chokidar: 6.0.0
|
||||
@@ -6469,10 +6522,10 @@ snapshots:
|
||||
tinyglobby: 0.2.17
|
||||
unplugin: 3.7.0(rolldown@1.2.8)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))
|
||||
unplugin-utils: 0.3.2
|
||||
vue: 3.5.45(typescript@6.0.3)
|
||||
vue: 3.5.46(typescript@6.0.3)
|
||||
optionalDependencies:
|
||||
'@vue/compiler-sfc': 3.5.45
|
||||
pinia: 4.1.0(@vue/devtools-api@8.2.1)(typescript@6.0.3)(vue@3.5.45(typescript@6.0.3))
|
||||
'@vue/compiler-sfc': 3.5.46
|
||||
pinia: 4.1.0(@vue/devtools-api@8.2.1)(typescript@6.0.3)(vue@3.5.46(typescript@6.0.3))
|
||||
vite: 8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0)
|
||||
transitivePeerDependencies:
|
||||
- '@farmfe/core'
|
||||
@@ -6491,13 +6544,13 @@ snapshots:
|
||||
'@vue/language-core': 3.3.14
|
||||
typescript: 6.0.3
|
||||
|
||||
vue@3.5.45(typescript@6.0.3):
|
||||
vue@3.5.46(typescript@6.0.3):
|
||||
dependencies:
|
||||
'@vue/compiler-dom': 3.5.45
|
||||
'@vue/compiler-sfc': 3.5.45
|
||||
'@vue/runtime-dom': 3.5.45
|
||||
'@vue/server-renderer': 3.5.45
|
||||
'@vue/shared': 3.5.45
|
||||
'@vue/compiler-dom': 3.5.46
|
||||
'@vue/compiler-sfc': 3.5.46
|
||||
'@vue/runtime-dom': 3.5.46
|
||||
'@vue/server-renderer': 3.5.46
|
||||
'@vue/shared': 3.5.46
|
||||
optionalDependencies:
|
||||
typescript: 6.0.3
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ const canHover = useMediaQuery('(hover: hover)')
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ZPopover class="h-4 items-center" :trigger="canHover ? 'hover-click' : 'click'" placement="top-start" :hover-delay="240">
|
||||
<ZPopover class="-ms-1.5 h-4 items-center" :trigger="canHover ? 'hover-click' : 'click'" placement="top-start" :hover-delay="240">
|
||||
<template #reference="{ open }">
|
||||
<ZIconButton variant="link" size="small" :aria-label="label" :aria-expanded="open" aria-haspopup="dialog">
|
||||
<CircleAlert class="size-3.5" aria-hidden="true" />
|
||||
|
||||
@@ -23,27 +23,12 @@ const providerIconComponent = computed(() => normalizedProvider.value
|
||||
: undefined)
|
||||
const authenticationIconComponent = computed(() => authenticationIcon(props.authenticationKind))
|
||||
const showAuthenticationKind = computed(() => props.authenticationKind !== undefined)
|
||||
const groupGapClass = computed(() => {
|
||||
if (props.size === 'xs')
|
||||
return 'gap-0.75'
|
||||
return props.size === 'sm'
|
||||
? 'gap-1'
|
||||
: 'gap-2'
|
||||
})
|
||||
const iconContainerClass = computed(() => {
|
||||
if (props.size === 'xs')
|
||||
return 'size-4.5 rounded-md'
|
||||
return props.size === 'sm'
|
||||
? 'size-5 rounded-md'
|
||||
: 'size-7 rounded-lg'
|
||||
})
|
||||
const iconClass = computed(() => {
|
||||
if (props.size === 'xs')
|
||||
return 'size-2.5'
|
||||
return props.size === 'sm'
|
||||
? 'size-3'
|
||||
: 'size-4'
|
||||
})
|
||||
const sizeClasses = {
|
||||
xs: { gap: 'gap-0.75', container: 'size-4.5 rounded-md', icon: 'size-2.5' },
|
||||
sm: { gap: 'gap-1', container: 'size-5 rounded-md', icon: 'size-3' },
|
||||
md: { gap: 'gap-2', container: 'size-7 rounded-lg', icon: 'size-4' },
|
||||
}
|
||||
const classes = computed(() => sizeClasses[props.size])
|
||||
|
||||
const providerLabel = computed(() => formatProviderLabel(props.provider, t('common.providers.unknown')))
|
||||
|
||||
@@ -51,23 +36,23 @@ const authenticationLabel = computed(() => formatAuthenticationLabel(props.authe
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span class="inline-flex items-center whitespace-nowrap" :class="groupGapClass">
|
||||
<span class="inline-flex items-center whitespace-nowrap" :class="classes.gap">
|
||||
<span
|
||||
class="inline-flex shrink-0 items-center justify-center bg-z-fill-secondary/80 text-z-text"
|
||||
:class="iconContainerClass"
|
||||
:class="classes.container"
|
||||
:title="providerLabel"
|
||||
>
|
||||
<component :is="providerIconComponent" v-if="providerIconComponent" :class="iconClass" />
|
||||
<component :is="providerIconComponent" v-if="providerIconComponent" :class="classes.icon" />
|
||||
<span v-else class="text-[10px] font-heavy text-z-text-quaternary">?</span>
|
||||
</span>
|
||||
|
||||
<span
|
||||
v-if="showAuthenticationKind"
|
||||
class="inline-flex shrink-0 items-center justify-center bg-z-fill-secondary/80 text-z-text"
|
||||
:class="iconContainerClass"
|
||||
:class="classes.container"
|
||||
:title="authenticationLabel"
|
||||
>
|
||||
<component :is="authenticationIconComponent" v-if="authenticationIconComponent" :class="iconClass" />
|
||||
<component :is="authenticationIconComponent" v-if="authenticationIconComponent" :class="classes.icon" />
|
||||
<span v-else class="text-[10px] font-heavy text-z-text-quaternary">?</span>
|
||||
</span>
|
||||
|
||||
|
||||
+6
-8
@@ -8,9 +8,9 @@ import { computed, ref, useTemplateRef, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { getAccountGroupModels, getAccountModels, refreshAccountModels } from '@/api'
|
||||
import { useRequestState } from '@/composables/useRequestState'
|
||||
import { accountModelAccessError, accountModelIdError, commonImageModels } from '../utils/modelAccess'
|
||||
import AccountModelCleanupPopover from './AccountModelCleanupPopover.vue'
|
||||
import AccountModelOption from './AccountModelOption.vue'
|
||||
import { accountModelAccessError, accountModelIdError, commonImageModels } from './modelAccess'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
accountId?: string
|
||||
@@ -53,12 +53,10 @@ const modes = computed(() => [
|
||||
},
|
||||
{
|
||||
value: 'allowlist',
|
||||
disabled: props.groupId === null,
|
||||
label: t('accounts.modelAccess.allowlist'),
|
||||
},
|
||||
{
|
||||
value: 'denylist',
|
||||
disabled: props.groupId === null,
|
||||
label: t('accounts.modelAccess.blocklist'),
|
||||
},
|
||||
])
|
||||
@@ -115,7 +113,7 @@ const groups = computed(() => [
|
||||
ids: catalogResults.value,
|
||||
},
|
||||
].filter(group => group.ids.length))
|
||||
const newModelId = computed(() => groupCatalog.value || groups.value.length
|
||||
const newModelId = computed(() => groups.value.length
|
||||
? ''
|
||||
: search.value.trim())
|
||||
const inputError = computed(() => selectionError.value || (newModelId.value && accountModelIdError(newModelId.value)))
|
||||
@@ -301,17 +299,17 @@ watch(search, () => {
|
||||
</ZFormItem>
|
||||
<template v-if="restricted">
|
||||
<div class="flex min-w-0 items-center gap-2">
|
||||
<ZInput ref="searchInput" v-model="search" class="min-w-0 flex-1" :aria-label="groupCatalog ? t('groups.editor.searchModels') : t('accounts.modelAccess.searchOrAddModels')" :placeholder="groupCatalog ? t('groups.editor.searchModels') : t('accounts.modelAccess.searchOrEnterId')" :disabled="disabled" :aria-invalid="Boolean(inputError)" @keydown.enter="handleSearchEnter">
|
||||
<ZInput ref="searchInput" v-model="search" class="min-w-0 flex-1" :aria-label="t('accounts.modelAccess.searchOrAddModels')" :placeholder="t('accounts.modelAccess.searchOrEnterId')" :disabled="disabled" :aria-invalid="Boolean(inputError)" @keydown.enter="handleSearchEnter">
|
||||
<template #prefix>
|
||||
<Search class="size-4" aria-hidden="true" />
|
||||
</template>
|
||||
</ZInput>
|
||||
<ZButton v-if="!groupCatalog" class="shrink-0" :disabled="disabled || !canAdd" @click="addModels([newModelId])">
|
||||
<ZButton class="shrink-0" :disabled="disabled || !canAdd" @click="addModels([newModelId])">
|
||||
<Plus class="size-4" aria-hidden="true" />
|
||||
{{ t('accounts.modelAccess.addModel') }}
|
||||
</ZButton>
|
||||
<ZIconButton
|
||||
v-if="!groupCatalog && mode === 'allowlist'"
|
||||
v-if="mode === 'allowlist'"
|
||||
variant="plain"
|
||||
:aria-label="t('accounts.modelAccess.addImageModels')"
|
||||
:title="t('accounts.modelAccess.addImageModels')"
|
||||
@@ -360,7 +358,7 @@ watch(search, () => {
|
||||
<p v-else-if="mode === 'denylist' && canAdd" class="m-0 text-z-xs text-z-text-secondary">
|
||||
{{ t('accounts.modelAccess.addToDenylistHint') }}
|
||||
</p>
|
||||
<ZEmpty v-else-if="!error && !search" :title="groupCatalog ? t('groups.editor.emptyCatalog') : t('accounts.modelAccess.noModels')" size="small" surface="none" />
|
||||
<ZEmpty v-else-if="!error && !search" :title="t('accounts.modelAccess.noModels')" size="small" surface="none" />
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
@@ -24,20 +24,24 @@ const parsed = computed(() => parseJsonObject(text.value, props.maximumBytes))
|
||||
const error = computed(() => parsed.value.error)
|
||||
const value = computed(() => parsed.value.value)
|
||||
const fields = computed(() => inputFields(props.schema))
|
||||
const hasExtra = computed(() => Object.keys(value.value ?? {}).some(key => !fields.value?.some(field => field.key === key)))
|
||||
const incompatibleValue = computed(() => fields.value?.some((field) => {
|
||||
const item = inputValue(field.key)
|
||||
if (item === undefined)
|
||||
const fieldsByKey = computed(() => new Map(fields.value?.map(field => [field.key, field])))
|
||||
const canUseForm = computed(() => {
|
||||
if (fields.value === null || error.value)
|
||||
return false
|
||||
if (field.values)
|
||||
return !field.values.some(option => option === item)
|
||||
if (field.type === 'number' || field.type === 'integer')
|
||||
return typeof item !== 'number' && typeof item !== 'string'
|
||||
return field.type === 'boolean'
|
||||
? typeof item !== 'boolean'
|
||||
: typeof item !== 'string'
|
||||
}) ?? false)
|
||||
const showJson = computed(() => jsonMode.value || fields.value === null || hasExtra.value || incompatibleValue.value || Boolean(error.value))
|
||||
return Object.entries(value.value ?? {}).every(([key, item]) => {
|
||||
const field = fieldsByKey.value.get(key)
|
||||
if (!field)
|
||||
return false
|
||||
if (field.values)
|
||||
return field.values.some(option => option === item)
|
||||
if (field.type === 'number' || field.type === 'integer')
|
||||
return typeof item === 'number' || typeof item === 'string'
|
||||
return field.type === 'boolean'
|
||||
? typeof item === 'boolean'
|
||||
: typeof item === 'string'
|
||||
})
|
||||
})
|
||||
const showJson = computed(() => jsonMode.value || !canUseForm.value)
|
||||
const empty = computed(() => fields.value?.length === 0 && props.schema.additionalProperties === false && !showJson.value)
|
||||
|
||||
function fieldValue(field: InputField) {
|
||||
@@ -105,8 +109,8 @@ function update(field: InputField, input: string) {
|
||||
}
|
||||
|
||||
async function focusField(key?: string) {
|
||||
const editableField = key && fields.value?.some(field => field.key === key)
|
||||
if (editableField && jsonMode.value && !error.value && !hasExtra.value && !incompatibleValue.value)
|
||||
const editableField = key && fieldsByKey.value.has(key)
|
||||
if (editableField && canUseForm.value)
|
||||
jsonMode.value = false
|
||||
await nextTick()
|
||||
|
||||
@@ -128,7 +132,7 @@ defineExpose({ focusField })
|
||||
<ZForm v-if="showJson">
|
||||
<ZFormItem :label="t('common.form.inputPlaceholder')" :error="error">
|
||||
<template #extra>
|
||||
<ZIconButton v-if="fields !== null" :aria-label="t('common.form.useForm')" class="size-4!" variant="link" :disabled="disabled || Boolean(error) || hasExtra || incompatibleValue" @click="jsonMode = false">
|
||||
<ZIconButton v-if="fields !== null" :aria-label="t('common.form.useForm')" class="size-4!" variant="link" :disabled="disabled || !canUseForm" @click="jsonMode = false">
|
||||
<List class="size-3.5" />
|
||||
</ZIconButton>
|
||||
</template>
|
||||
|
||||
@@ -28,7 +28,6 @@ withDefaults(
|
||||
defineProps<{
|
||||
columns: TableColumn<UsageListRecord>[]
|
||||
rows: UsageListRecord[]
|
||||
requestDetails?: boolean
|
||||
loading?: boolean
|
||||
emptyText?: string
|
||||
}>(),
|
||||
@@ -97,7 +96,7 @@ const { t } = useI18n({ useScope: 'global' })
|
||||
</template>
|
||||
|
||||
<template #createdAtDisplay="{ row }">
|
||||
<UsageTimeCell :value="row.createdAtDisplay" :datetime="requestDetails ? row.createdAt : undefined" />
|
||||
<UsageTimeCell :value="row.createdAtDisplay" :datetime="row.createdAt" />
|
||||
</template>
|
||||
|
||||
<template #clientIp="{ row }">
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
const props = defineProps<{ value: string, datetime?: string }>()
|
||||
const props = defineProps<{ value: string, datetime: string }>()
|
||||
const parts = computed(() => props.value?.split(' '))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<time v-if="datetime && parts?.length === 2" :datetime="datetime" :title="value" class="grid gap-1 font-mono tabular-nums">
|
||||
<time v-if="parts?.length === 2" :datetime="datetime" :title="value" class="grid gap-1 font-mono tabular-nums">
|
||||
<span class="text-z-sm font-bold text-z-text">{{ parts[1] }}</span>
|
||||
<span class="text-z-xs text-z-text-tertiary">{{ parts[0] }}</span>
|
||||
</time>
|
||||
|
||||
@@ -58,6 +58,7 @@ export const usageDataColumns = computed(() => ([
|
||||
key: 'createdAtDisplay',
|
||||
label: t('usage.fields.time'),
|
||||
kind: 'datetime',
|
||||
width: 128,
|
||||
},
|
||||
{
|
||||
key: 'clientIp',
|
||||
|
||||
@@ -139,7 +139,6 @@
|
||||
},
|
||||
"credentials": {
|
||||
"accountName": "Account name",
|
||||
"enterUpstreamName": "Enter the upstream name",
|
||||
"baseUrlHelp": "Enter the API base URL, endpoint paths are appended automatically",
|
||||
"apiPrefix": "API prefix",
|
||||
"apiKeyPlaceholder": "Leave blank to keep the current key",
|
||||
@@ -148,7 +147,6 @@
|
||||
"transportLabel": "Transport",
|
||||
"webSocketHelp": "WS requires upstream support for Responses WebSocket",
|
||||
"messagesTransportHelp": "Messages upstreams use HTTP/SSE",
|
||||
"nameRequired": "Enter an account name",
|
||||
"validation": {
|
||||
"urlLength": "Upstream API URL must not exceed 2,048 characters",
|
||||
"urlFormat": "Enter an HTTP or HTTPS URL without credentials, query parameters, or a fragment",
|
||||
@@ -224,7 +222,7 @@
|
||||
"upstreamCatalog": "Upstream catalog",
|
||||
"selectAll": "Select all",
|
||||
"deselectAll": "Deselect all",
|
||||
"addToDenylistHint": "Saving blocks this ID on the account",
|
||||
"addToDenylistHint": "Add and save to block this model",
|
||||
"loadingModel": "Loading model",
|
||||
"noModels": "No models",
|
||||
"selectOrAddAtLeastOneModel": "Please select or add at least one model",
|
||||
@@ -283,6 +281,7 @@
|
||||
"actions": {
|
||||
"deleteAccount": "Delete account",
|
||||
"moreActions": "More actions",
|
||||
"discoverPeer": "Detect CPR Link",
|
||||
"disableScheduling": "Disable",
|
||||
"enableScheduling": "Enable",
|
||||
"refreshToken": "Refresh token",
|
||||
|
||||
@@ -43,8 +43,6 @@
|
||||
"forceUltrafast": "Force Ultrafast",
|
||||
"subagents": "Collaborative subagents",
|
||||
"memberModels": "Member account models",
|
||||
"searchModels": "Search member models",
|
||||
"emptyCatalog": "Add an account with available models to this group first",
|
||||
"fastModeHelp": "Default follows the client. Disable downgrades both accelerated tiers to standard. A forced tier overrides the client selection when the model supports it.",
|
||||
"subagentsHelp": "Enable lets the client decide when to start a collaborative subagent. Disable rejects requests identified as coming from a collaborative subagent."
|
||||
},
|
||||
|
||||
@@ -315,7 +315,10 @@
|
||||
"day": "d",
|
||||
"location": {
|
||||
"requestCountry": "Request country",
|
||||
"requestCountryDescription": "Choose how Codex requests send the country code",
|
||||
"requestCountryScope": "Applies only to Codex OAuth accounts",
|
||||
"countryHelp": "Request country mode help",
|
||||
"countryMode": "Policy",
|
||||
"countryModes": {
|
||||
"default": "Null",
|
||||
"passthrough": "Pass through",
|
||||
|
||||
@@ -139,7 +139,6 @@
|
||||
},
|
||||
"credentials": {
|
||||
"accountName": "账号名称",
|
||||
"enterUpstreamName": "输入上游名称",
|
||||
"baseUrlHelp": "填写 API 前缀,接口路径会自动追加",
|
||||
"apiPrefix": "API 前缀",
|
||||
"apiKeyPlaceholder": "留空保留当前密钥",
|
||||
@@ -148,7 +147,6 @@
|
||||
"transportLabel": "传输方式",
|
||||
"webSocketHelp": "WS 需要上游支持 Responses WebSocket",
|
||||
"messagesTransportHelp": "Messages 上游使用 HTTP/SSE",
|
||||
"nameRequired": "请输入账号名称",
|
||||
"validation": {
|
||||
"urlLength": "上游 API 地址不能超过 2048 个字符",
|
||||
"urlFormat": "请输入不含认证、查询参数或片段的 HTTP 或 HTTPS 地址",
|
||||
@@ -224,7 +222,7 @@
|
||||
"upstreamCatalog": "上游目录",
|
||||
"selectAll": "全选",
|
||||
"deselectAll": "取消全选",
|
||||
"addToDenylistHint": "保存后,此账号将拒绝该模型",
|
||||
"addToDenylistHint": "添加并保存后将拒绝该模型",
|
||||
"loadingModel": "加载模型中",
|
||||
"noModels": "暂无模型",
|
||||
"selectOrAddAtLeastOneModel": "请至少选择或添加一个模型",
|
||||
@@ -283,6 +281,7 @@
|
||||
"actions": {
|
||||
"deleteAccount": "删除账号",
|
||||
"moreActions": "更多操作",
|
||||
"discoverPeer": "检测 CPR 互联",
|
||||
"disableScheduling": "停用",
|
||||
"enableScheduling": "启用",
|
||||
"refreshToken": "刷新令牌",
|
||||
|
||||
@@ -43,8 +43,6 @@
|
||||
"forceUltrafast": "超快速",
|
||||
"subagents": "协作子代理",
|
||||
"memberModels": "成员账号模型",
|
||||
"searchModels": "搜索成员账号模型",
|
||||
"emptyCatalog": "暂无成员模型,请先将有模型的账号加入分组",
|
||||
"fastModeHelp": "默认跟随客户端。禁用会将加速请求降为标准档。选择快速或超快速时,若模型支持该档位,分组设置会覆盖客户端选择",
|
||||
"subagentsHelp": "启用后由客户端决定是否启动协作子代理。禁用会拒绝可识别的协作子代理请求"
|
||||
},
|
||||
|
||||
@@ -315,7 +315,10 @@
|
||||
"day": "天",
|
||||
"location": {
|
||||
"requestCountry": "请求国家",
|
||||
"requestCountryDescription": "设置 Codex 请求如何发送国家代码",
|
||||
"requestCountryScope": "仅用于 Codex OAuth 账号",
|
||||
"countryHelp": "请求国家模式说明",
|
||||
"countryMode": "策略",
|
||||
"countryModes": {
|
||||
"default": "空值",
|
||||
"passthrough": "透传",
|
||||
|
||||
@@ -139,7 +139,6 @@
|
||||
},
|
||||
"credentials": {
|
||||
"accountName": "賬號名稱",
|
||||
"enterUpstreamName": "輸入上游名稱",
|
||||
"baseUrlHelp": "填寫 API 前綴,接口路徑會自動追加",
|
||||
"apiPrefix": "API 前綴",
|
||||
"apiKeyPlaceholder": "留空保留當前密鑰",
|
||||
@@ -148,7 +147,6 @@
|
||||
"transportLabel": "傳輸方式",
|
||||
"webSocketHelp": "WS 需要上游支持 Responses WebSocket",
|
||||
"messagesTransportHelp": "Messages 上游使用 HTTP/SSE",
|
||||
"nameRequired": "請輸入賬號名稱",
|
||||
"validation": {
|
||||
"urlLength": "上游 API 地址不能超過 2048 個字符",
|
||||
"urlFormat": "請輸入不含認證、查詢參數或片段的 HTTP 或 HTTPS 地址",
|
||||
@@ -224,7 +222,7 @@
|
||||
"upstreamCatalog": "上游目錄",
|
||||
"selectAll": "全選",
|
||||
"deselectAll": "取消全選",
|
||||
"addToDenylistHint": "保存後,此賬號將拒絕該模型",
|
||||
"addToDenylistHint": "加入並儲存後將拒絕此模型",
|
||||
"loadingModel": "加載模型中",
|
||||
"noModels": "暫無模型",
|
||||
"selectOrAddAtLeastOneModel": "請至少選擇或添加一個模型",
|
||||
@@ -283,6 +281,7 @@
|
||||
"actions": {
|
||||
"deleteAccount": "刪除賬號",
|
||||
"moreActions": "更多操作",
|
||||
"discoverPeer": "偵測 CPR 互聯",
|
||||
"disableScheduling": "停用",
|
||||
"enableScheduling": "啓用",
|
||||
"refreshToken": "刷新令牌",
|
||||
|
||||
@@ -43,8 +43,6 @@
|
||||
"forceUltrafast": "超快速",
|
||||
"subagents": "協作子代理",
|
||||
"memberModels": "成員帳號模型",
|
||||
"searchModels": "搜尋成員帳號模型",
|
||||
"emptyCatalog": "暫無成員模型,請先將有模型的帳號加入分組",
|
||||
"fastModeHelp": "預設跟隨用戶端。禁用會將加速請求降為標準檔。選擇快速或超快速時,若模型支援該檔位,分組設定會覆寫用戶端選擇",
|
||||
"subagentsHelp": "啟用後由用戶端決定是否啟動協作子代理。禁用會拒絕可識別的協作子代理請求"
|
||||
},
|
||||
|
||||
@@ -315,7 +315,10 @@
|
||||
"day": "天",
|
||||
"location": {
|
||||
"requestCountry": "請求國家",
|
||||
"requestCountryDescription": "設定 Codex 請求如何傳送國家代碼",
|
||||
"requestCountryScope": "僅用於 Codex OAuth 帳號",
|
||||
"countryHelp": "請求國家模式說明",
|
||||
"countryMode": "策略",
|
||||
"countryModes": {
|
||||
"default": "空值",
|
||||
"passthrough": "透傳",
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { ZFormItem, ZInput } from '@codex-proxy/ui'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
defineProps<{ disabled?: boolean, required?: boolean, placeholder?: string }>()
|
||||
const name = defineModel<string>({ required: true })
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ZFormItem prop="name" :label="t('accounts.credentials.accountName')" :required="required">
|
||||
<ZInput
|
||||
v-model="name"
|
||||
:aria-label="t('accounts.credentials.accountName')"
|
||||
:placeholder="placeholder ?? t('accounts.editor.namePlaceholder')"
|
||||
:disabled="disabled"
|
||||
/>
|
||||
</ZFormItem>
|
||||
</template>
|
||||
@@ -3,9 +3,8 @@ import type { AccountGroupRef, AccountModelAccess } from '@/api'
|
||||
|
||||
import { ZFormItem, ZInput, ZSwitch, ZTextarea } from '@codex-proxy/ui'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import AccountModelAccessField from '@/components/account/model-access/index.vue'
|
||||
import AccountGroupCheckboxGrid from '@/components/AccountGroupCheckboxGrid.vue'
|
||||
import AccountModelAccessField from './AccountModelAccessField.vue'
|
||||
import AccountNameField from './AccountNameField.vue'
|
||||
import AccountProxyField from './AccountProxyField.vue'
|
||||
|
||||
withDefaults(defineProps<{
|
||||
@@ -38,7 +37,14 @@ const selectedGroupIds = defineModel<string[]>('selectedGroupIds', { required: t
|
||||
|
||||
<template>
|
||||
<div class="grid gap-4.5">
|
||||
<AccountNameField v-if="name !== undefined" v-model="name" :disabled="disabled" :placeholder="namePlaceholder" />
|
||||
<ZFormItem v-if="name !== undefined" prop="name" :label="t('accounts.credentials.accountName')">
|
||||
<ZInput
|
||||
v-model="name"
|
||||
:aria-label="t('accounts.credentials.accountName')"
|
||||
:placeholder="namePlaceholder ?? t('accounts.editor.namePlaceholder')"
|
||||
:disabled="disabled"
|
||||
/>
|
||||
</ZFormItem>
|
||||
<slot name="connection" />
|
||||
<AccountModelAccessField v-model="modelAccess" form-prop="modelAccess" :account-id="modelAccountId ?? accountId" :disabled="disabled" :allow-preserve="preserveModelAccess" />
|
||||
<slot name="scheduling">
|
||||
|
||||
@@ -17,7 +17,6 @@ import { useAccountSettingsFormRules } from '../../composables/useAccountSetting
|
||||
import { accountCreateProvider } from '../../utils/accountCreate'
|
||||
import AccountApiKeyFields from '../AccountApiKeyFields.vue'
|
||||
import AccountIdentityCell from '../AccountIdentityCell.vue'
|
||||
import AccountNameField from '../AccountNameField.vue'
|
||||
import AccountImportFields from './AccountImportFields.vue'
|
||||
import AccountOAuthFields from './AccountOAuthFields.vue'
|
||||
import AccountSetupFields from './AccountSetupFields.vue'
|
||||
@@ -186,7 +185,6 @@ async function requestCreate() {
|
||||
@regenerate="emit('generateOauth')"
|
||||
/>
|
||||
<ZForm v-else-if="mode === 'api_key'" ref="formElement" :model="form" :rules="apiKeyRules" scroll-to-error focus-on-error novalidate @submit="requestCreate">
|
||||
<AccountNameField v-model="form.name" required :disabled="busy" :placeholder="t('accounts.credentials.enterUpstreamName')" />
|
||||
<AccountApiKeyFields v-model="form.apiKey" :disabled="busy" />
|
||||
</ZForm>
|
||||
<AccountImportFields
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { Account } from '@/api'
|
||||
|
||||
import { ZEmpty, ZScrollbar } from '@codex-proxy/ui'
|
||||
|
||||
import { ChartNoAxesCombined, RefreshCw, UserRound } from '@lucide/vue'
|
||||
import { ChartNoAxesCombined, Link2, RefreshCw, UserRound } from '@lucide/vue'
|
||||
|
||||
import { computed, shallowRef, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
@@ -38,15 +38,14 @@ const hasUpstreamPool = computed(() => props.account.upstream?.discovered && (
|
||||
))
|
||||
|
||||
const quotaEntries = computed(() => groupedAccountQuotaWindows(
|
||||
orderedPanelQuotaWindows(props.account.upstream?.discovered
|
||||
? props.account.quota.windows.filter(window => window.amount)
|
||||
: props.account.quota.windows),
|
||||
orderedPanelQuotaWindows(props.account.quota.windows.filter(window => window.accountWide)),
|
||||
))
|
||||
const profileOpen = shallowRef(false)
|
||||
const forecastOpen = shallowRef(false)
|
||||
const hasPlanBadge = computed(() => Boolean(props.account.planType) || props.account.authenticationKind === 'api_key')
|
||||
const hasForecast = computed(() => props.account.authenticationKind !== 'api_key')
|
||||
const hasPersonalInfo = computed(() => props.account.capabilities.profile || props.account.capabilities.subscription)
|
||||
const needsPeerDiscovery = computed(() => props.account.upstream?.discovered === false)
|
||||
const canRefresh = computed(() => props.account.capabilities.quotaRefresh || props.account.upstream != null)
|
||||
const hasActions = computed(() => hasPersonalInfo.value || hasForecast.value || canRefresh.value || props.account.capabilities.resetCredits)
|
||||
const lastRefreshed = computed(() => {
|
||||
@@ -114,7 +113,7 @@ watch(hasPersonalInfo, (available) => {
|
||||
</QuotaActionButton>
|
||||
<QuotaActionButton
|
||||
v-if="canRefresh"
|
||||
:label="t('accounts.quotaForecast.refreshQuota')"
|
||||
:label="needsPeerDiscovery ? t('accounts.actions.discoverPeer') : t('accounts.quotaForecast.refreshQuota')"
|
||||
:loading="refreshing"
|
||||
:disabled="refreshing"
|
||||
@click="emit('refreshQuota', account.id)"
|
||||
@@ -122,7 +121,8 @@ watch(hasPersonalInfo, (available) => {
|
||||
<template #loading>
|
||||
<RefreshCw class="size-3.5 animate-spin motion-reduce:animate-none" />
|
||||
</template>
|
||||
<RefreshCw class="size-3.5" />
|
||||
<Link2 v-if="needsPeerDiscovery" class="size-3.5" />
|
||||
<RefreshCw v-else class="size-3.5" />
|
||||
</QuotaActionButton>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -2,28 +2,10 @@ import type { FormRules } from '@codex-proxy/ui'
|
||||
import type { ApiKeyAccountForm } from '../utils/upstreamApiKey'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { accountNameValid } from '../utils/accountName'
|
||||
|
||||
export function useAccountApiKeyFormRules(editing = false) {
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
return computed<FormRules<{ apiKey: ApiKeyAccountForm, name: string }>>(() => ({
|
||||
...(!editing
|
||||
? {
|
||||
name: [
|
||||
{
|
||||
required: true,
|
||||
whitespace: true,
|
||||
trigger: ['blur', 'change'],
|
||||
message: t('accounts.credentials.nameRequired'),
|
||||
},
|
||||
{
|
||||
validator: (_rule: unknown, value: string) => accountNameValid(value),
|
||||
trigger: ['blur', 'change'],
|
||||
message: t('accounts.editor.nameInvalid'),
|
||||
},
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
return computed<FormRules<{ apiKey: ApiKeyAccountForm }>>(() => ({
|
||||
'apiKey.protocol': {
|
||||
required: true,
|
||||
trigger: 'change',
|
||||
|
||||
@@ -76,7 +76,6 @@ export function useAccountOnboarding(options: {
|
||||
data: {
|
||||
provider: 'openai',
|
||||
authentication_kind: 'api_key',
|
||||
name: form.name.trim(),
|
||||
base_url: form.apiKey.base_url.trim(),
|
||||
api_key: form.apiKey.apiKey,
|
||||
protocol: form.apiKey.protocol,
|
||||
|
||||
@@ -2,8 +2,8 @@ import type { FormRules } from '@codex-proxy/ui'
|
||||
import type { AccountModelAccess } from '@/api'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { accountModelAccessError } from '@/components/account/model-access/modelAccess'
|
||||
import { accountNameValid } from '../utils/accountName'
|
||||
import { accountModelAccessError } from '../utils/modelAccess'
|
||||
|
||||
interface AccountSettingsFormValue {
|
||||
name?: string
|
||||
|
||||
@@ -7,9 +7,9 @@ import { normalizeRgbaHexColor, ZButton, ZColorPicker, ZDialog, ZForm, ZFormItem
|
||||
import { computed, useTemplateRef, watch } from 'vue'
|
||||
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import AccountModelAccessField from '@/components/account/model-access/index.vue'
|
||||
import { accountModelAccessError } from '@/components/account/model-access/modelAccess'
|
||||
import HelpPopover from '@/components/HelpPopover.vue'
|
||||
import AccountModelAccessField from '@/views/accounts/components/AccountModelAccessField.vue'
|
||||
import { accountModelAccessError } from '@/views/accounts/utils/modelAccess'
|
||||
import { ACCOUNT_GROUP_COLOR_PRESETS } from '../constants'
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -81,7 +81,7 @@ const description = computed(() => props.group
|
||||
width="42rem"
|
||||
:show-close="!saving" :close-on-click-modal="!saving" :close-on-press-escape="!saving"
|
||||
>
|
||||
<ZForm ref="formElement" :model="form" :rules="rules" class="sm:grid-cols-[minmax(0,1fr)_fit-content(10rem)] sm:gap-x-6" scroll-to-error focus-on-error novalidate @submit="requestSave">
|
||||
<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>
|
||||
<ZInput
|
||||
v-model="form.name"
|
||||
@@ -99,7 +99,7 @@ const description = computed(() => props.group
|
||||
:disabled="saving"
|
||||
/>
|
||||
</ZFormItem>
|
||||
<div class="col-span-full grid grid-cols-2 items-start gap-x-6 gap-y-4.5 sm:grid-cols-subgrid **:[[role=radio]]:px-3.5">
|
||||
<div class="col-span-full grid grid-cols-2 items-start gap-x-6 gap-y-4.5 sm:grid-cols-subgrid **:[[role=radio]]:px-3.5 md:**:[[role=radio]]:px-4.5">
|
||||
<div class="contents sm:flex sm:min-w-0 sm:flex-wrap sm:items-start sm:gap-x-6 sm:gap-y-4.5">
|
||||
<ZFormItem :label="t('groups.editor.fastMode')" class="col-span-full sm:flex-auto">
|
||||
<template #label-extra>
|
||||
|
||||
@@ -65,7 +65,7 @@ const { visibleColumns, columnOptions, setColumnVisible, setColumnOrder, resetCo
|
||||
<UsagePerformanceCell :record="row" />
|
||||
</template>
|
||||
<template #createdAtDisplay="{ row }">
|
||||
<UsageTimeCell :value="row.createdAtDisplay" />
|
||||
<UsageTimeCell :value="row.createdAtDisplay" :datetime="row.createdAt" />
|
||||
</template>
|
||||
<template #clientIp="{ row }">
|
||||
<UsageClientIpCell :record="row" />
|
||||
|
||||
@@ -4,7 +4,7 @@ import type { ProxyBatchItem } from '../utils/batch'
|
||||
import { ZScrollbar } from '@codex-proxy/ui'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { proxyBatchStates } from '../utils/batch'
|
||||
import { proxyBatchStates, summarizeProxyBatch, summarizeProxyTests } from '../utils/batch'
|
||||
import ProxyRegion from './ProxyRegion.vue'
|
||||
|
||||
const props = defineProps<{ items: ProxyBatchItem[], tests?: ProxyBatchItem[] }>()
|
||||
@@ -12,51 +12,61 @@ const props = defineProps<{ items: ProxyBatchItem[], tests?: ProxyBatchItem[] }>
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
|
||||
const testItems = computed(() => props.tests ?? [])
|
||||
|
||||
function resultMessage(item: ProxyBatchItem, test?: ProxyBatchItem) {
|
||||
if (test && test.status !== 'succeeded')
|
||||
return test.message
|
||||
const detection = test?.record?.lastTest?.location
|
||||
if (detection?.status === 'failed')
|
||||
return detection.message
|
||||
return item.status === 'succeeded'
|
||||
? ''
|
||||
: item.message
|
||||
}
|
||||
|
||||
const rows = computed(() => {
|
||||
const tests = new Map(testItems.value.map(item => [item.key, item]))
|
||||
return props.items.map((item) => {
|
||||
const test = item.record
|
||||
? tests.get(item.record.id)
|
||||
: undefined
|
||||
const detection = test?.record?.lastTest?.location
|
||||
const status = (test ?? item).status
|
||||
const state = proxyBatchStates.value[status]
|
||||
let label = state.label
|
||||
if (status === 'succeeded') {
|
||||
label = test
|
||||
? t('proxies.batchTest.connectionIsNormal')
|
||||
: t('proxies.batchTest.addedStatus')
|
||||
}
|
||||
return {
|
||||
item,
|
||||
test,
|
||||
result: test ?? item,
|
||||
message: test && test.status !== 'succeeded'
|
||||
? test.message
|
||||
: detection?.status === 'failed'
|
||||
? detection.message
|
||||
: item.status !== 'succeeded'
|
||||
? item.message
|
||||
: '',
|
||||
label,
|
||||
tone: state.tone,
|
||||
message: resultMessage(item, test),
|
||||
messageTone: status === 'succeeded'
|
||||
? 'text-z-warning-text'
|
||||
: state.tone,
|
||||
}
|
||||
})
|
||||
})
|
||||
const completed = computed(() => props.items.filter(item => !['pending', 'running', 'skipped'].includes(item.status)).length)
|
||||
const created = computed(() => props.items.filter(item => item.status === 'succeeded').length)
|
||||
const invalid = computed(() => props.items.filter(item => item.status === 'failed').length)
|
||||
const succeeded = computed(() => testItems.value.filter(item => item.status === 'succeeded').length)
|
||||
const failed = computed(() => testItems.value.filter(item => item.status === 'failed').length)
|
||||
const allOperations = computed(() => [
|
||||
...props.items,
|
||||
...testItems.value,
|
||||
])
|
||||
const attention = computed(() => allOperations.value.filter(item => ['error', 'conflict', 'busy', 'unknown'].includes(item.status)).length)
|
||||
const skipped = computed(() => allOperations.value.filter(item => item.status === 'skipped').length)
|
||||
const locationPending = computed(() => testItems.value.filter(item => item.status === 'succeeded' && item.record?.lastTest?.location.status !== 'detected').length)
|
||||
|
||||
const additions = computed(() => summarizeProxyBatch(props.items))
|
||||
const connections = computed(() => summarizeProxyTests(testItems.value))
|
||||
const attention = computed(() => additions.value.attention + connections.value.attention)
|
||||
const skipped = computed(() => additions.value.skipped + connections.value.skipped)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="min-w-0 space-y-3" :aria-label="t('proxies.batchTest.resultsTitle')">
|
||||
<div class="flex flex-wrap items-center gap-x-4 gap-y-1 text-z-xs text-z-text-secondary" role="status" aria-live="polite">
|
||||
<span>{{ t('proxies.batchTest.processed') }} <strong class="font-mono font-medium text-z-text">{{ completed }} / {{ items.length }}</strong></span>
|
||||
<span>{{ t('proxies.batchTest.added', { created }) }}</span>
|
||||
<span v-if="invalid">{{ t('proxies.batchTest.invalidFormat', { invalid }) }}</span>
|
||||
<span>{{ t('proxies.batchTest.processed') }} <strong class="font-mono font-medium text-z-text">{{ additions.completed }} / {{ items.length }}</strong></span>
|
||||
<span>{{ t('proxies.batchTest.added', { created: additions.succeeded }) }}</span>
|
||||
<span v-if="additions.failed">{{ t('proxies.batchTest.invalidFormat', { invalid: additions.failed }) }}</span>
|
||||
<template v-if="testItems.length">
|
||||
<span>{{ t('proxies.batchTest.connected', { succeeded }) }}</span>
|
||||
<span>{{ t('proxies.batchTest.connectionFailed', { failed }) }}</span>
|
||||
<span v-if="locationPending">{{ t('proxies.batchTest.locationPending', { locationPending }) }}</span>
|
||||
<span>{{ t('proxies.batchTest.connected', { succeeded: connections.succeeded }) }}</span>
|
||||
<span>{{ t('proxies.batchTest.connectionFailed', { failed: connections.failed }) }}</span>
|
||||
<span v-if="connections.locationPending">{{ t('proxies.batchTest.locationPending', { locationPending: connections.locationPending }) }}</span>
|
||||
</template>
|
||||
<span v-if="attention">{{ t('proxies.batchTest.needsAttention', { attention }) }}</span>
|
||||
<span v-if="skipped">{{ t('proxies.batchTest.skipped', { skipped }) }}</span>
|
||||
@@ -65,9 +75,9 @@ const locationPending = computed(() => testItems.value.filter(item => item.statu
|
||||
<ol class="m-0 list-none space-y-1 p-0">
|
||||
<li v-for="row in rows" :key="row.item.key" class="grid grid-cols-[minmax(0,1fr)_auto] gap-x-3 gap-y-1 rounded-z-sm px-3 py-2.5 odd:bg-z-fill-quaternary">
|
||||
<span class="min-w-0 truncate font-mono text-z-xs text-z-text" :title="row.item.endpoint">{{ row.item.endpoint || t('proxies.batchTest.lineNumber', { key: row.item.key }) }}</span>
|
||||
<span class="flex flex-wrap justify-end gap-x-2 text-z-xs" :class="proxyBatchStates[row.result.status].tone">
|
||||
<span class="flex flex-wrap justify-end gap-x-2 text-z-xs" :class="row.tone">
|
||||
<span v-if="row.test" class="text-z-text-secondary">{{ t('proxies.batchTest.addedStatus') }}</span>
|
||||
<span>{{ row.result.status === 'succeeded' ? row.test ? t('proxies.batchTest.connectionIsNormal') : t('proxies.batchTest.addedStatus') : proxyBatchStates[row.result.status].label }}</span>
|
||||
<span>{{ row.label }}</span>
|
||||
</span>
|
||||
<div class="col-span-2 flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 text-z-xs text-z-text-secondary">
|
||||
<span class="max-w-full truncate" :title="row.item.name">{{ row.item.name }}</span>
|
||||
@@ -76,7 +86,7 @@ const locationPending = computed(() => testItems.value.filter(item => item.statu
|
||||
<span class="whitespace-nowrap">{{ row.test.record.lastTest.latencyMs }} ms</span><span v-if="row.test.record.lastTest.exitIpv4"> · IPv4 {{ row.test.record.lastTest.exitIpv4 }}</span><span v-if="row.test.record.lastTest.exitIpv6"> · IPv6 {{ row.test.record.lastTest.exitIpv6 }}</span>
|
||||
</span>
|
||||
</div>
|
||||
<span v-if="row.message" class="col-span-2 text-z-xs leading-relaxed wrap-anywhere" :class="row.result.status === 'succeeded' ? 'text-z-warning-text' : proxyBatchStates[row.result.status].tone">{{ row.message }}</span>
|
||||
<span v-if="row.message" class="col-span-2 text-z-xs leading-relaxed wrap-anywhere" :class="row.messageTone">{{ row.message }}</span>
|
||||
</li>
|
||||
</ol>
|
||||
</ZScrollbar>
|
||||
|
||||
@@ -4,6 +4,7 @@ import { getProxies } from '@/api'
|
||||
import { useRequestState } from '@/composables/useRequestState'
|
||||
import { t } from '@/i18n'
|
||||
import { notification as ZNotification } from '@/utils/notification'
|
||||
import { summarizeProxyTests } from '../utils/batch'
|
||||
import { useProxyBatchTest } from './useProxyBatchTest'
|
||||
|
||||
export function useProxyBatchTesting(options: { test: ProxyTestExecutor, reload: () => Promise<unknown> }) {
|
||||
@@ -48,23 +49,22 @@ export function useProxyBatchTesting(options: { test: ProxyTestExecutor, reload:
|
||||
await options.reload()
|
||||
if (!request.isCurrent(requestId))
|
||||
return
|
||||
const succeeded = tests.items.value.filter(item => item.status === 'succeeded').length
|
||||
const incomplete = tests.items.value.filter(item => item.status !== 'succeeded')
|
||||
const locationPending = tests.items.value.filter(item => item.status === 'succeeded' && item.record?.lastTest?.location.status !== 'detected').length
|
||||
const { succeeded, locationPending } = summarizeProxyTests(tests.items.value)
|
||||
const incomplete = tests.items.value.length - succeeded
|
||||
const missing = wanted.size - collected.size
|
||||
const summary = [
|
||||
t('proxies.batchTest.batchTestCompletedConnected', { succeeded }),
|
||||
]
|
||||
if (incomplete.length)
|
||||
summary.push(t('proxies.batchTest.unsuccessful', { count: incomplete.length }))
|
||||
if (incomplete)
|
||||
summary.push(t('proxies.batchTest.unsuccessful', { count: incomplete }))
|
||||
if (locationPending)
|
||||
summary.push(t('proxies.batchTest.locationsPending', { locationPending }))
|
||||
if (missing)
|
||||
summary.push(t('proxies.batchTest.proxiesNoLongerAvailable', { missing }))
|
||||
const firstFailure = incomplete.find(item => item.status !== 'skipped')
|
||||
const firstFailure = tests.items.value.find(item => item.status !== 'succeeded' && item.status !== 'skipped')
|
||||
if (firstFailure)
|
||||
summary.push(`${firstFailure.name}:${firstFailure.message}`)
|
||||
const notify = incomplete.length || locationPending || missing
|
||||
const notify = incomplete || locationPending || missing
|
||||
? ZNotification.warning
|
||||
: ZNotification.success
|
||||
notify({
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { OutboundProxyRecord, ProxyBatchResult } from '@/api'
|
||||
import { countBy } from 'es-toolkit'
|
||||
import { computed } from 'vue'
|
||||
import { ApiError } from '@/api/request'
|
||||
import { t } from '@/i18n'
|
||||
@@ -23,6 +24,25 @@ export interface ProxyBatchItem {
|
||||
record?: OutboundProxyRecord
|
||||
}
|
||||
|
||||
export function summarizeProxyBatch(items: ProxyBatchItem[]) {
|
||||
const counts = countBy(items, item => item.status)
|
||||
const skipped = counts.skipped ?? 0
|
||||
return {
|
||||
completed: items.length - (counts.pending ?? 0) - (counts.running ?? 0) - skipped,
|
||||
succeeded: counts.succeeded ?? 0,
|
||||
failed: counts.failed ?? 0,
|
||||
attention: (counts.error ?? 0) + (counts.conflict ?? 0) + (counts.busy ?? 0) + (counts.unknown ?? 0),
|
||||
skipped,
|
||||
}
|
||||
}
|
||||
|
||||
export function summarizeProxyTests(items: ProxyBatchItem[]) {
|
||||
return {
|
||||
...summarizeProxyBatch(items),
|
||||
locationPending: items.filter(item => item.status === 'succeeded' && item.record?.lastTest?.location.status !== 'detected').length,
|
||||
}
|
||||
}
|
||||
|
||||
export interface ProxyBatchInput {
|
||||
line: number
|
||||
raw: string
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
<script setup lang="ts">
|
||||
import type { SelectOption } from '@codex-proxy/ui/select'
|
||||
import type { OpenAiRequestCountry } from '@/api'
|
||||
import { ZCard, ZFormItem, ZSelect } from '@codex-proxy/ui'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import CountryCodeField from '@/components/CountryCodeField.vue'
|
||||
import HelpPopover from '@/components/HelpPopover.vue'
|
||||
|
||||
defineProps<{ disabled: boolean }>()
|
||||
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
const requestCountry = defineModel<OpenAiRequestCountry>({ required: true })
|
||||
const modes = computed<Array<SelectOption<OpenAiRequestCountry['mode']> & { help: string }>>(() => [
|
||||
{
|
||||
value: 'follow_location',
|
||||
label: t('settings.location.countryModes.follow_location'),
|
||||
help: t('settings.location.countryHints.follow_location'),
|
||||
},
|
||||
{
|
||||
value: 'default',
|
||||
label: t('settings.location.countryModes.default'),
|
||||
help: t('settings.location.countryHints.default'),
|
||||
},
|
||||
{
|
||||
value: 'passthrough',
|
||||
label: t('settings.location.countryModes.passthrough'),
|
||||
help: t('settings.location.countryHints.passthrough'),
|
||||
},
|
||||
{
|
||||
value: 'custom',
|
||||
label: t('settings.location.countryModes.custom'),
|
||||
help: t('settings.location.countryHints.custom'),
|
||||
},
|
||||
])
|
||||
|
||||
function setMode(mode: OpenAiRequestCountry['mode'] | undefined) {
|
||||
if (mode && mode !== requestCountry.value.mode) {
|
||||
requestCountry.value = mode === 'custom'
|
||||
? { mode, country: '' }
|
||||
: { mode }
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ZCard :description="t('settings.location.requestCountryDescription')">
|
||||
<template #title>
|
||||
<span class="inline-flex items-center gap-1.5">
|
||||
{{ t('settings.location.requestCountry') }}
|
||||
<HelpPopover :label="t('settings.location.countryHelp')">
|
||||
<p class="mb-2 font-emphasis text-z-text">
|
||||
{{ t('settings.location.requestCountryScope') }}
|
||||
</p>
|
||||
<dl class="grid grid-cols-[auto_1fr] gap-x-3 gap-y-2">
|
||||
<template v-for="mode in modes" :key="mode.value">
|
||||
<dt class="font-emphasis text-z-text">
|
||||
{{ mode.label }}
|
||||
</dt>
|
||||
<dd>{{ mode.help }}</dd>
|
||||
</template>
|
||||
</dl>
|
||||
</HelpPopover>
|
||||
</span>
|
||||
</template>
|
||||
<div class="grid min-w-0 max-w-6xl items-start gap-4.5 sm:grid-cols-2">
|
||||
<ZFormItem :label="t('settings.location.countryMode')">
|
||||
<ZSelect :model-value="requestCountry.mode" :options="modes" :aria-label="t('settings.location.countryMode')" :disabled="disabled" @update:model-value="setMode" />
|
||||
</ZFormItem>
|
||||
<CountryCodeField
|
||||
v-if="requestCountry.mode === 'custom'"
|
||||
:model-value="requestCountry.country"
|
||||
form-prop="openaiRequestCountry.country"
|
||||
:label="t('settings.location.customCountryCode')"
|
||||
:disabled="disabled"
|
||||
@update:model-value="requestCountry = { mode: 'custom', country: $event }"
|
||||
/>
|
||||
</div>
|
||||
</ZCard>
|
||||
</template>
|
||||
@@ -1,12 +1,8 @@
|
||||
<script setup lang="ts">
|
||||
import type { SelectOption } from '@codex-proxy/ui/select'
|
||||
import type { OpenAiRequestCountry, RequestLocation } from '@/api'
|
||||
import type { RequestLocation } from '@/api'
|
||||
|
||||
import { ZCard, ZFormItem, ZSelect, ZSwitch } from '@codex-proxy/ui'
|
||||
import { computed } from 'vue'
|
||||
import { ZCard, ZSwitch } from '@codex-proxy/ui'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import CountryCodeField from '@/components/CountryCodeField.vue'
|
||||
import HelpPopover from '@/components/HelpPopover.vue'
|
||||
import RequestLocationDetectButton from '@/components/RequestLocationDetectButton.vue'
|
||||
import RequestLocationFields from '@/components/RequestLocationFields.vue'
|
||||
|
||||
@@ -18,37 +14,6 @@ const { t } = useI18n({ useScope: 'global' })
|
||||
|
||||
const location = defineModel<RequestLocation>({ required: true })
|
||||
const enabled = defineModel<boolean>('enabled', { required: true })
|
||||
const requestCountry = defineModel<OpenAiRequestCountry>('requestCountry', { required: true })
|
||||
const modes = computed<Array<SelectOption<OpenAiRequestCountry['mode']> & { help: string }>>(() => [
|
||||
{
|
||||
value: 'follow_location',
|
||||
label: t('settings.location.countryModes.follow_location'),
|
||||
help: t('settings.location.countryHints.follow_location'),
|
||||
},
|
||||
{
|
||||
value: 'default',
|
||||
label: t('settings.location.countryModes.default'),
|
||||
help: t('settings.location.countryHints.default'),
|
||||
},
|
||||
{
|
||||
value: 'passthrough',
|
||||
label: t('settings.location.countryModes.passthrough'),
|
||||
help: t('settings.location.countryHints.passthrough'),
|
||||
},
|
||||
{
|
||||
value: 'custom',
|
||||
label: t('settings.location.countryModes.custom'),
|
||||
help: t('settings.location.countryHints.custom'),
|
||||
},
|
||||
])
|
||||
|
||||
function setMode(mode: OpenAiRequestCountry['mode'] | undefined) {
|
||||
if (mode && mode !== requestCountry.value.mode) {
|
||||
requestCountry.value = mode === 'custom'
|
||||
? { mode, country: '' }
|
||||
: { mode }
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -58,34 +23,7 @@ function setMode(mode: OpenAiRequestCountry['mode'] | undefined) {
|
||||
<ZSwitch v-model="enabled" :label="t('settings.location.enableLocationOverlay')" :disabled="disabled" />
|
||||
<RequestLocationDetectButton :loading="detectingLocation" :disabled="disabled" @detect="emit('detectLocation')" />
|
||||
</div>
|
||||
<div class="grid min-w-0 gap-4.5 mt-4 max-w-6xl">
|
||||
<RequestLocationFields v-model="location" :form-prop="enabled ? 'requestLocation' : undefined" :disabled="disabled || !enabled" />
|
||||
<div class="grid gap-4.5 sm:grid-cols-2">
|
||||
<ZFormItem :label="t('settings.location.requestCountry')">
|
||||
<template #label-extra>
|
||||
<HelpPopover :label="t('settings.location.countryHelp')">
|
||||
<dl class="grid grid-cols-[auto_1fr] gap-x-3 gap-y-2">
|
||||
<template v-for="mode in modes" :key="mode.value">
|
||||
<dt class="font-emphasis text-z-text">
|
||||
{{ mode.label }}
|
||||
</dt>
|
||||
<dd>{{ mode.help }}</dd>
|
||||
</template>
|
||||
</dl>
|
||||
</HelpPopover>
|
||||
</template>
|
||||
<ZSelect :model-value="requestCountry.mode" :options="modes" :aria-label="t('settings.location.requestCountry')" :disabled="disabled" @update:model-value="setMode" />
|
||||
</ZFormItem>
|
||||
<CountryCodeField
|
||||
v-if="requestCountry.mode === 'custom'"
|
||||
:model-value="requestCountry.country"
|
||||
form-prop="openaiRequestCountry.country"
|
||||
:label="t('settings.location.customCountryCode')"
|
||||
:disabled="disabled"
|
||||
@update:model-value="requestCountry = { mode: 'custom', country: $event }"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<RequestLocationFields v-model="location" class="mt-4 max-w-6xl" :form-prop="enabled ? 'requestLocation' : undefined" :disabled="disabled || !enabled" />
|
||||
</template>
|
||||
</ZCard>
|
||||
</template>
|
||||
|
||||
@@ -17,6 +17,7 @@ import ConcurrencyPolicyCard from './components/ConcurrencyPolicyCard.vue'
|
||||
import AccountErrorProtectionCard from './components/error-protection/AccountErrorProtectionCard.vue'
|
||||
import ModelAliasesCard from './components/ModelAliasesCard.vue'
|
||||
import PrivacyPolicyCard from './components/privacy/PrivacyPolicyCard.vue'
|
||||
import RequestCountryCard from './components/RequestCountryCard.vue'
|
||||
import RequestHistoryCard from './components/RequestHistoryCard.vue'
|
||||
import RequestLocationCard from './components/RequestLocationCard.vue'
|
||||
import ResetCreditCard from './components/ResetCreditCard.vue'
|
||||
@@ -246,11 +247,11 @@ watch(section, (value) => {
|
||||
<RequestLocationCard
|
||||
v-model="form.requestLocation"
|
||||
v-model:enabled="form.requestLocationEnabled"
|
||||
v-model:request-country="form.openaiRequestCountry"
|
||||
:disabled="disabled"
|
||||
:detecting-location="detectingLocation"
|
||||
@detect-location="detectLocation"
|
||||
/>
|
||||
<RequestCountryCard v-model="form.openaiRequestCountry" :disabled="disabled" />
|
||||
<PrivacyPolicyCard v-model="form.codexPrivacyPolicy" :disabled="disabled" />
|
||||
<ModelAliasesCard
|
||||
:mappings="mappings"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import type { EChartsOption, LineSeriesOption } from 'echarts'
|
||||
import type { EChartsOption } from 'echarts'
|
||||
|
||||
import type { UsageCostMetric, UsageMetricResponse } from '@/api'
|
||||
import { ZCard, ZEmpty, ZSegmented } from '@codex-proxy/ui'
|
||||
@@ -7,12 +7,10 @@ import { ZCard, ZEmpty, ZSegmented } from '@codex-proxy/ui'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import BaseChart from '@/components/charts/BaseChart.vue'
|
||||
import {
|
||||
zeroInactiveValues,
|
||||
} from '@/components/charts/timeSeriesGap'
|
||||
import { zeroInactiveValues } from '@/components/charts/timeSeriesGap'
|
||||
import { chartTooltipContent, tooltipIndex, tooltipRows } from '@/components/charts/tooltip'
|
||||
import { useChartPalette } from '@/composables/useChartPalette'
|
||||
import { decimalDisplayNumber, formatLocalizedCompactNumber as formatCompactNumber, formatPercent, formatUsd } from '@/utils/format'
|
||||
import { decimalDisplayNumber, formatPercent, formatUsd } from '@/utils/format'
|
||||
|
||||
import {
|
||||
formatUsdAxis,
|
||||
@@ -37,23 +35,19 @@ const props = withDefaults(
|
||||
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
|
||||
type UsageChartPalette = ReturnType<typeof useChartPalette>['palette']['value']
|
||||
interface CostSeries {
|
||||
label: string
|
||||
color: string
|
||||
values: (number | null)[]
|
||||
area?: 'strong'
|
||||
tooltipValue: (index: number) => string | null
|
||||
}
|
||||
|
||||
const activeView = defineModel<UsageCostMetric>({ required: true })
|
||||
const { palette } = useChartPalette()
|
||||
const cost = computed(() => props.result?.data.summary ?? null)
|
||||
const points = computed(() => props.result?.data.points ?? [])
|
||||
const costPoints = computed(() => props.result?.metric === 'cost'
|
||||
? props.result.data.points
|
||||
: [])
|
||||
const savingsPoints = computed(() => props.result?.metric === 'savings'
|
||||
? props.result.data.points
|
||||
: [])
|
||||
const cachePoints = computed(() => props.result?.metric === 'cache'
|
||||
? props.result.data.points
|
||||
: [])
|
||||
const requestActivity = computed(() => points.value.map(point => point.requestCount > 0))
|
||||
const hasNoCacheCost = computed(() => costPoints.value.some(point => point.value.noCacheCost != null))
|
||||
const coverageRate = computed(() => {
|
||||
if (!cost.value)
|
||||
return null
|
||||
@@ -79,21 +73,79 @@ const viewOptions = computed(() => ([
|
||||
},
|
||||
]))
|
||||
|
||||
const hasData = computed(() => {
|
||||
if (props.loading || props.result?.metric !== activeView.value)
|
||||
return false
|
||||
if (activeView.value === 'cost')
|
||||
return costPoints.value.some(point => point.value.estimatedCost != null || point.value.noCacheCost != null)
|
||||
if (activeView.value === 'savings')
|
||||
return savingsPoints.value.some(point => point.value != null)
|
||||
return cachePoints.value.some(({ value }) => value.inputTokens > 0 || value.cachedTokenRate > 0 || (value.cacheHitRequestRate ?? 0) > 0)
|
||||
function amountValues(amounts: (string | null)[]) {
|
||||
return zeroInactiveValues(amounts.map(amount => decimalDisplayNumber(amount)), requestActivity.value)
|
||||
}
|
||||
|
||||
function primaryAmountSeries(label: string, amounts: (string | null)[]): CostSeries {
|
||||
return {
|
||||
label,
|
||||
color: palette.value.success,
|
||||
area: 'strong',
|
||||
values: amountValues(amounts),
|
||||
tooltipValue: index => formatUsd(amounts[index] ?? (requestActivity.value[index] === false
|
||||
? '0'
|
||||
: null)),
|
||||
}
|
||||
}
|
||||
|
||||
function rateSeries(label: string, color: string, values: (number | null)[]): CostSeries {
|
||||
return {
|
||||
label,
|
||||
color,
|
||||
values,
|
||||
tooltipValue: index => formatPercent(values[index] ?? null),
|
||||
}
|
||||
}
|
||||
|
||||
const chart = computed<{ hasData: boolean, series: CostSeries[] }>(() => {
|
||||
const response = props.result
|
||||
if (props.loading || !response || response.metric !== activeView.value)
|
||||
return { hasData: false, series: [] }
|
||||
|
||||
if (response.metric === 'cost') {
|
||||
const actual = response.data.points.map(({ value }) => value.estimatedCost)
|
||||
const comparison = response.data.points.map(({ value }) => value.noCacheCost)
|
||||
const hasComparison = comparison.some(amount => amount != null)
|
||||
const series = [
|
||||
primaryAmountSeries(t('usage.cost.actualCost'), actual),
|
||||
]
|
||||
if (hasComparison) {
|
||||
series.push({
|
||||
label: t('usage.cost.withoutCacheEstimate'),
|
||||
color: palette.value.textMuted,
|
||||
values: amountValues(comparison),
|
||||
// 对比曲线允许补零,提示只展示该时间桶实际提供的估算
|
||||
tooltipValue: index => comparison[index] == null
|
||||
? null
|
||||
: formatUsd(comparison[index]),
|
||||
})
|
||||
}
|
||||
return { hasData: hasComparison || actual.some(amount => amount != null), series }
|
||||
}
|
||||
if (response.metric === 'savings') {
|
||||
const savings = response.data.points.map(point => point.value)
|
||||
return {
|
||||
hasData: savings.some(amount => amount != null),
|
||||
series: [
|
||||
primaryAmountSeries(t('usage.cost.cacheSavings'), savings),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
const { points } = response.data
|
||||
return {
|
||||
hasData: points.some(({ value }) => value.inputTokens > 0 || value.cachedTokenRate > 0 || (value.cacheHitRequestRate ?? 0) > 0),
|
||||
series: [
|
||||
rateSeries(t('usage.cost.cacheTokenProportion'), palette.value.normal, points.map(({ value }) => value.cachedTokenRate)),
|
||||
rateSeries(t('usage.cost.hitRequestRate'), palette.value.success, points.map(({ value }) => value.cacheHitRequestRate)),
|
||||
],
|
||||
}
|
||||
})
|
||||
|
||||
const chartOption = computed<EChartsOption>(() => {
|
||||
const theme = palette.value
|
||||
const legend = legendNames()
|
||||
const series = chartSeries(theme)
|
||||
|
||||
const series = chart.value.series
|
||||
return {
|
||||
animationDuration: 240,
|
||||
grid: {
|
||||
@@ -104,157 +156,34 @@ const chartOption = computed<EChartsOption>(() => {
|
||||
outerBoundsMode: 'same',
|
||||
outerBoundsContain: 'axisLabel',
|
||||
},
|
||||
legend: usageLegend(theme, legend),
|
||||
legend: usageLegend(theme, series.map(item => item.label)),
|
||||
tooltip: usageTooltip(theme, formatTooltip),
|
||||
xAxis: usageCategoryAxis(
|
||||
points.value.map(point => point.label),
|
||||
theme,
|
||||
),
|
||||
yAxis: usageValueAxis(theme, axisFormatter(), {
|
||||
min: activeView.value === 'cache'
|
||||
? 0
|
||||
: undefined,
|
||||
max: activeView.value === 'cache'
|
||||
? 1
|
||||
: undefined,
|
||||
}),
|
||||
series,
|
||||
yAxis: activeView.value === 'cache'
|
||||
? usageValueAxis(theme, formatPercent, { min: 0, max: 1 })
|
||||
: usageValueAxis(theme, formatUsdAxis),
|
||||
series: series.flatMap(item => usageGapAwareLineSeries(item.label, item.values, item.color, { area: item.area })),
|
||||
}
|
||||
})
|
||||
|
||||
function legendNames() {
|
||||
if (activeView.value === 'savings') {
|
||||
return [
|
||||
t('usage.cost.cacheSavings'),
|
||||
]
|
||||
}
|
||||
if (activeView.value === 'cache') {
|
||||
return [
|
||||
t('usage.cost.cacheTokenProportion'),
|
||||
t('usage.cost.hitRequestRate'),
|
||||
]
|
||||
}
|
||||
return hasNoCacheCost.value
|
||||
? [
|
||||
t('usage.cost.actualCost'),
|
||||
t('usage.cost.withoutCacheEstimate'),
|
||||
]
|
||||
: [
|
||||
t('usage.cost.actualCost'),
|
||||
]
|
||||
}
|
||||
|
||||
function axisFormatter() {
|
||||
if (activeView.value === 'cost' || activeView.value === 'savings')
|
||||
return formatUsdAxis
|
||||
if (activeView.value === 'cache')
|
||||
return (value: number) => formatPercent(value)
|
||||
return (value: number) => formatCompactNumber(value)
|
||||
}
|
||||
|
||||
function chartSeries(theme: UsageChartPalette): LineSeriesOption[] {
|
||||
if (activeView.value === 'savings') {
|
||||
return [
|
||||
...usageGapAwareLineSeries(
|
||||
t('usage.cost.cacheSavings'),
|
||||
zeroInactiveValues(
|
||||
savingsPoints.value.map(point => decimalDisplayNumber(point.value)),
|
||||
requestActivity.value,
|
||||
),
|
||||
theme.success,
|
||||
{ area: 'strong' },
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
if (activeView.value === 'cache') {
|
||||
return [
|
||||
...usageGapAwareLineSeries(
|
||||
t('usage.cost.cacheTokenProportion'),
|
||||
cachePoints.value.map(point => point.value.cachedTokenRate),
|
||||
theme.normal,
|
||||
),
|
||||
...usageGapAwareLineSeries(
|
||||
t('usage.cost.hitRequestRate'),
|
||||
cachePoints.value.map(point => point.value.cacheHitRequestRate),
|
||||
theme.success,
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
const series = [
|
||||
...usageGapAwareLineSeries(
|
||||
t('usage.cost.actualCost'),
|
||||
zeroInactiveValues(
|
||||
costPoints.value.map(point => decimalDisplayNumber(point.value.estimatedCost)),
|
||||
requestActivity.value,
|
||||
),
|
||||
theme.success,
|
||||
{ area: 'strong' },
|
||||
),
|
||||
]
|
||||
if (hasNoCacheCost.value) {
|
||||
series.push(
|
||||
...usageGapAwareLineSeries(
|
||||
t('usage.cost.withoutCacheEstimate'),
|
||||
zeroInactiveValues(
|
||||
costPoints.value.map(point => decimalDisplayNumber(point.value.noCacheCost)),
|
||||
requestActivity.value,
|
||||
),
|
||||
theme.textMuted,
|
||||
),
|
||||
)
|
||||
}
|
||||
return series
|
||||
}
|
||||
|
||||
function formatTooltip(params: unknown) {
|
||||
const rows = tooltipRows(params)
|
||||
const pointIndex = tooltipIndex(rows[0])
|
||||
const point = points.value[pointIndex]
|
||||
const index = tooltipIndex(tooltipRows(params)[0])
|
||||
const point = points.value[index]
|
||||
if (!point)
|
||||
return ''
|
||||
const theme = palette.value
|
||||
|
||||
if (activeView.value === 'savings') {
|
||||
return chartTooltipContent(point.label, [
|
||||
usageTooltipItem(
|
||||
t('usage.cost.cacheSavings'),
|
||||
formatUsd(costAmount(savingsPoints.value[pointIndex]?.value ?? null, pointIndex)),
|
||||
theme.success,
|
||||
),
|
||||
])
|
||||
}
|
||||
|
||||
if (activeView.value === 'cache') {
|
||||
return chartTooltipContent(point.label, [
|
||||
usageTooltipItem(t('usage.cost.cacheTokenProportion'), formatPercent(cachePoints.value[pointIndex]?.value.cachedTokenRate ?? null), theme.normal),
|
||||
usageTooltipItem(t('usage.cost.hitRequestRate'), formatPercent(cachePoints.value[pointIndex]?.value.cacheHitRequestRate ?? null), theme.success),
|
||||
])
|
||||
}
|
||||
|
||||
const lines = [
|
||||
usageTooltipItem(
|
||||
t('usage.cost.actualCost'),
|
||||
formatUsd(costAmount(costPoints.value[pointIndex]?.value.estimatedCost ?? null, pointIndex)),
|
||||
theme.success,
|
||||
),
|
||||
]
|
||||
if (costPoints.value[pointIndex]?.value.noCacheCost != null) {
|
||||
lines.push(usageTooltipItem(
|
||||
t('usage.cost.withoutCacheEstimate'),
|
||||
formatUsd(costAmount(costPoints.value[pointIndex]?.value.noCacheCost ?? null, pointIndex)),
|
||||
theme.textMuted,
|
||||
))
|
||||
}
|
||||
const lines = chart.value.series.flatMap((series) => {
|
||||
const value = series.tooltipValue(index)
|
||||
return value == null
|
||||
? []
|
||||
: [
|
||||
usageTooltipItem(series.label, value, series.color),
|
||||
]
|
||||
})
|
||||
return chartTooltipContent(point.label, lines)
|
||||
}
|
||||
|
||||
function costAmount(value: string | null, pointIndex: number) {
|
||||
return value ?? (requestActivity.value[pointIndex] === false
|
||||
? '0'
|
||||
: null)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -271,8 +200,8 @@ function costAmount(value: string | null, pointIndex: number) {
|
||||
</template>
|
||||
|
||||
<template #body>
|
||||
<div class="grid min-h-66" :class="hasData ? 'gap-3' : 'flex-1'">
|
||||
<div v-if="hasData && cost" class="grid grid-cols-2 gap-x-1 gap-y-3 rounded-xl bg-z-fill-quaternary/45 p-2 @min-[24rem]/cost:grid-cols-3 @min-[40rem]/cost:grid-cols-5">
|
||||
<div class="grid min-h-66" :class="chart.hasData ? 'gap-3' : 'flex-1'">
|
||||
<div v-if="chart.hasData && cost" class="grid grid-cols-2 gap-x-1 gap-y-3 rounded-xl bg-z-fill-quaternary/45 p-2 @min-[24rem]/cost:grid-cols-3 @min-[40rem]/cost:grid-cols-5">
|
||||
<div class="grid min-w-0 gap-1 px-1.5">
|
||||
<span class="text-[10px] font-bold text-z-text-quaternary" :title="t('usage.billing.totalCost')">{{ t('usage.cost.actualCost') }}</span>
|
||||
<strong class="wrap-anywhere font-mono text-z-sm font-heavy tabular-nums text-z-text">
|
||||
@@ -304,7 +233,7 @@ function costAmount(value: string | null, pointIndex: number) {
|
||||
</strong>
|
||||
</div>
|
||||
</div>
|
||||
<BaseChart v-if="hasData" :option="chartOption" :height="210" />
|
||||
<BaseChart v-if="chart.hasData" :option="chartOption" :height="210" />
|
||||
<ZEmpty
|
||||
v-else
|
||||
size="small"
|
||||
|
||||
@@ -2,25 +2,39 @@ import type { TableColumn } from '@codex-proxy/ui'
|
||||
import type { Ref } from 'vue'
|
||||
import type { UsageListRecord, UsageRecordStatus } from '@/api'
|
||||
import { useTableColumns } from '@codex-proxy/ui'
|
||||
import { clamp, partition } from 'es-toolkit'
|
||||
import { computed } from 'vue'
|
||||
import { usageRecordColumns } from '@/components/usage/shared/columns'
|
||||
import { t } from '@/i18n'
|
||||
|
||||
export function useUsageRecordColumns(status: Ref<UsageRecordStatus>, tableWidth: Readonly<Ref<number>>) {
|
||||
const columns = computed(() => usageRecordColumns.value.map((column) => {
|
||||
if (column.key === 'createdAtDisplay')
|
||||
return { ...column, width: 128 }
|
||||
if (column.key === 'accountEmail')
|
||||
return { ...column, width: 280, hideable: true }
|
||||
return ['clientApiKeyName', 'model', 'reasoningEffort'].includes(column.key)
|
||||
? { ...column, fixedWidth: true }
|
||||
: column
|
||||
type ColumnLayout = Record<string, Pick<TableColumn, 'width' | 'fixedWidth' | 'hideable'>>
|
||||
|
||||
const requestLayout: ColumnLayout = {
|
||||
clientApiKeyName: { fixedWidth: true },
|
||||
accountEmail: { width: 280, hideable: true },
|
||||
model: { fixedWidth: true },
|
||||
reasoningEffort: { fixedWidth: true },
|
||||
}
|
||||
|
||||
const errorActionWidth = 72
|
||||
const maxErrorWidth = 370
|
||||
const errorLayout: ColumnLayout = {
|
||||
...requestLayout,
|
||||
transport: { width: 112 },
|
||||
actions: { width: errorActionWidth },
|
||||
}
|
||||
|
||||
function columnsWithLayout(layout: ColumnLayout) {
|
||||
return usageRecordColumns.value.map(column => ({
|
||||
...column,
|
||||
...layout[column.key],
|
||||
}))
|
||||
const usage = useTableColumns(columns, 'usage-records')
|
||||
}
|
||||
|
||||
export function useUsageRecordColumns(status: Ref<UsageRecordStatus>, tableWidth: Readonly<Ref<number>>) {
|
||||
const usage = useTableColumns(() => columnsWithLayout(requestLayout), 'usage-records')
|
||||
const errors = useTableColumns(() => {
|
||||
const time = columns.value.find(column => column.key === 'createdAtDisplay')!
|
||||
const actionWidth = 72
|
||||
const errorWidth = 370
|
||||
const [time, details] = partition(columnsWithLayout(errorLayout), column => column.key === 'createdAtDisplay')
|
||||
return [
|
||||
{
|
||||
key: 'errorMessage',
|
||||
@@ -28,18 +42,12 @@ export function useUsageRecordColumns(status: Ref<UsageRecordStatus>, tableWidth
|
||||
kind: 'custom',
|
||||
fixed: 'left',
|
||||
minWidth: tableWidth.value
|
||||
? Math.min(errorWidth, Math.max(96, (tableWidth.value - actionWidth) / 2))
|
||||
: errorWidth,
|
||||
? clamp((tableWidth.value - errorActionWidth) / 2, 96, maxErrorWidth)
|
||||
: maxErrorWidth,
|
||||
hideable: false,
|
||||
},
|
||||
time,
|
||||
...columns.value.filter(column => column.key !== time.key).map((column) => {
|
||||
if (column.key === 'transport')
|
||||
return { ...column, width: 112 }
|
||||
if (column.key === 'actions')
|
||||
return { ...column, width: actionWidth }
|
||||
return column
|
||||
}),
|
||||
...time,
|
||||
...details,
|
||||
] satisfies TableColumn<UsageListRecord>[]
|
||||
}, 'usage-error-records')
|
||||
return computed(() => status.value === 'error'
|
||||
|
||||
@@ -171,7 +171,6 @@ watch(timeRange, () => {
|
||||
<UsageRecordsTable
|
||||
class="min-h-0 flex-1"
|
||||
:columns="columns.visibleColumns.value"
|
||||
request-details
|
||||
:rows="records"
|
||||
:loading="loading"
|
||||
:empty-text="t('usage.page.noRequestsMatchTheseFilters')"
|
||||
|
||||
@@ -4,6 +4,7 @@ import VueI18n from '@intlify/unplugin-vue-i18n/vite'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
import { defineConfig, loadEnv } from 'vite'
|
||||
import { consoleBanner } from './build/console-banner.ts'
|
||||
import { pluginBridge } from './build/plugin-bridge.ts'
|
||||
|
||||
export default defineConfig(({ mode }) => {
|
||||
@@ -23,6 +24,7 @@ export default defineConfig(({ mode }) => {
|
||||
source: sourceUi ? uiRoot : undefined,
|
||||
}),
|
||||
pluginBridge(),
|
||||
consoleBanner(),
|
||||
],
|
||||
resolve: {
|
||||
alias: {
|
||||
|
||||
+1
-1
Submodule modules/ui updated: 498a491ea9...501495d5b1
+6
-22
@@ -1,25 +1,9 @@
|
||||
# v3.54.0
|
||||
|
||||
## 新增功能
|
||||
|
||||
- 账号分组可设置模型允许或拒绝列表、子代理权限及 Ultrafast 档位,已有分组默认允许全部模型和子代理
|
||||
- API 密钥支持批量编辑,可查看近 7 天或 30 天的模型用量、费用和请求数,也可将本期日、周预算窗口对齐到指定账号
|
||||
- OpenAI 请求国家默认跟随代理或全局位置,也可在「系统设置 → 上游配置 → 请求位置覆盖」中选择发送空值、透传或指定国家
|
||||
- OpenAI OAuth 同步审核默认优先使用有权限的 `codex-auto-review`,可在「系统设置 → 上游配置 → 模型映射」中关闭「专用审核模型」
|
||||
|
||||
## 优化改进
|
||||
|
||||
- 账号模型白名单可快速添加图片模型,账号额度页区分定时预热和额度重置后的预热
|
||||
- 账号授权或凭据刷新失败时,管理端显示更具体的原因
|
||||
# v3.54.4
|
||||
|
||||
## 问题修复
|
||||
|
||||
- OpenAI Responses 回退到 HTTP/SSE 后,继续使用已失效的响应 ID 会返回 `previous_response_not_found`,客户端可移除旧 ID 并携带完整历史重试
|
||||
- OpenAI OAuth 配额刷新识别到访问令牌被撤销时会使其过期,刷新模型目录时保留凭据错误原因
|
||||
|
||||
## 升级须知
|
||||
|
||||
- 从正式版 `v3.53.1` 可直接升级,已验证分组、密钥和运行设置保留。运行过旧 `0045_account_group_policies` 或 `0046_openai_request_settings` 的源码部署无法直接复用该数据库,需从执行旧迁移前的备份升级,或另行迁移业务数据
|
||||
- 自建管理 API 客户端保存运行设置时,须提交 `resetCreditOnLowWeeklyQuota`、`openaiOauthGuardianReviewModel` 和 `openaiRequestCountry`,可从当前设置读取并原样回传
|
||||
- 管理 API 的账号代理绑定改用 `outboundProxyId`,全局和密钥的客户端身份配置分别改用 `providerRequestProfiles` 和 `providerRequestProfileOverrides`
|
||||
- 读取仪表盘账号用量的客户端请改用 `metric`、`metricValueRaw` 和 `lastUsedRelative`,需要原始时间时读取 `lastUsedAt`
|
||||
- OpenAI Responses 经 WebSocket 上传长会话时,若上游在首条响应文本前因请求过大关闭连接,允许回退的请求会通过同一账号改走 HTTP/SSE
|
||||
- Codex 切换 `x-codex-exclude` 响应字段设置后,WebSocket 按新设置选择连接,依赖旧连接的续接会提示客户端重放完整历史
|
||||
- 严格账号亲和下,聊天主账号缺少生图资格时,主会话和子会话可临时借用有权限的账号生成或编辑图片,后续聊天继续使用原账号
|
||||
- 导入 OpenAI API 密钥账号时,只需在账号设置中填写一次名称,手动导入时留空会使用「密钥账号」
|
||||
- 将后端 `url` 依赖升级至 2.5.9,修复安全公告 `RUSTSEC-2026-0592` 所列问题
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
version: 3.54.0
|
||||
version: 3.54.4
|
||||
published:
|
||||
'3':
|
||||
stable: 3.53.1
|
||||
rc: 3.53.1
|
||||
beta: 3.53.1
|
||||
alpha: 3.53.1
|
||||
stable: 3.54.3
|
||||
rc: 3.54.3
|
||||
beta: 3.54.3
|
||||
alpha: 3.54.3
|
||||
|
||||
Reference in New Issue
Block a user