mirror of
https://github.com/yynxxxxx/Codex-X.git
synced 2026-10-19 06:09:33 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8661ce85a1 | ||
|
|
0381c5351d | ||
|
|
f7aa94cb1b | ||
|
|
d1f0df031d | ||
|
|
ecde8c1344 | ||
|
|
f6feba9a8d | ||
|
|
19222f9cc9 | ||
|
|
e6e68f8d92 | ||
|
|
4c56b05894 | ||
|
|
a107ad22f8 | ||
|
|
3e2e27b77e | ||
|
|
2babfa6ced | ||
|
|
e9c52aa8cb | ||
|
|
26ebeb8618 | ||
|
|
e5634c3204 | ||
|
|
14885c9a0e | ||
|
|
918ad405b6 | ||
|
|
5368e2dad3 | ||
|
|
5a9ec0581c | ||
|
|
726de0fe63 | ||
|
|
7d0b2891b9 | ||
|
|
4c2cb51c59 | ||
|
|
b796b4d2cd | ||
|
|
16f64e3982 | ||
|
|
4772287fe1 | ||
|
|
163285cf32 | ||
|
|
d5f4a6572b | ||
|
|
bca9d0af55 | ||
|
|
ed5bdad63f | ||
|
|
47a13c8674 | ||
|
|
5dd375ce97 | ||
|
|
16380882a0 | ||
|
|
9c75c4295d | ||
|
|
b0585e61be | ||
|
|
f2bf8bc73f | ||
|
|
96b24f7b81 | ||
|
|
392b2b1bd5 | ||
|
|
0e28260197 | ||
|
|
edd399c079 | ||
|
|
460f629925 | ||
|
|
3970bbeb10 | ||
|
|
999b66a901 |
@@ -177,7 +177,7 @@ jobs:
|
||||
- name: Windows x64
|
||||
platform: windows-latest
|
||||
macos: false
|
||||
args: --bundles msi
|
||||
args: --bundles nsis
|
||||
asset_pattern: Codex-X-[version]-windows-x64[ext]
|
||||
|
||||
steps:
|
||||
@@ -186,6 +186,16 @@ jobs:
|
||||
with:
|
||||
ref: ${{ needs.prepare.outputs.tag }}
|
||||
|
||||
- name: Checkout Windows test harness tooling
|
||||
if: matrix.platform == 'windows-latest'
|
||||
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
|
||||
with:
|
||||
ref: ${{ github.sha }}
|
||||
path: .ci-tools
|
||||
sparse-checkout: scripts/ensure-test-common-controls.ps1
|
||||
sparse-checkout-cone-mode: false
|
||||
persist-credentials: false
|
||||
|
||||
- name: Install Linux dependencies
|
||||
if: matrix.platform == 'ubuntu-22.04'
|
||||
run: |
|
||||
@@ -221,9 +231,33 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Check frontend types and regressions
|
||||
run: |
|
||||
pnpm --dir apps/desktop typecheck
|
||||
node --test apps/desktop/tests/*.test.mjs
|
||||
|
||||
- name: Verify Windows SDK test tooling
|
||||
if: matrix.platform == 'windows-latest'
|
||||
run: |
|
||||
command -v openssl
|
||||
openssl version
|
||||
|
||||
- name: Test Windows filesystem compatibility
|
||||
if: matrix.platform == 'windows-latest'
|
||||
run: cargo test --manifest-path apps/desktop/src-tauri/Cargo.toml --lib --locked -- --test-threads=1
|
||||
shell: pwsh
|
||||
run: |
|
||||
$artifacts = Join-Path $env:RUNNER_TEMP 'codexx-test-artifacts.json'
|
||||
cargo test --release --manifest-path apps/desktop/src-tauri/Cargo.toml --lib --locked --no-run --message-format=json > $artifacts
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
$harness = ./.ci-tools/scripts/ensure-test-common-controls.ps1 -CargoJson $artifacts -OutputDirectory $env:RUNNER_TEMP | ConvertFrom-Json
|
||||
Write-Host "Running all tests in $($harness.testExecutable)"
|
||||
$env:PATH = "$(Split-Path -Parent $harness.testExecutable);$env:PATH"
|
||||
Push-Location apps/desktop/src-tauri
|
||||
try {
|
||||
& $harness.testExecutable --test-threads=1
|
||||
$testExitCode = $LASTEXITCODE
|
||||
} finally { Pop-Location }
|
||||
if ($testExitCode -ne 0) { exit $testExitCode }
|
||||
|
||||
- name: Import Apple signing certificate and notarization key
|
||||
if: matrix.macos
|
||||
@@ -316,7 +350,7 @@ jobs:
|
||||
releaseAssetNamePattern: ${{ matrix.asset_pattern }}
|
||||
uploadUpdaterJson: true
|
||||
uploadUpdaterSignatures: true
|
||||
updaterJsonPreferNsis: false
|
||||
updaterJsonPreferNsis: true
|
||||
retryAttempts: 3
|
||||
|
||||
- name: Verify updater signatures were generated
|
||||
@@ -328,6 +362,14 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Test Windows installation and legacy MSI migration
|
||||
if: matrix.platform == 'windows-latest'
|
||||
shell: pwsh
|
||||
run: |
|
||||
$installers = @(Get-ChildItem apps/desktop/src-tauri/target/release/bundle/nsis -Filter '*.exe')
|
||||
if ($installers.Count -ne 1) { throw 'Expected one NSIS installer.' }
|
||||
./scripts/windows-install-smoke.ps1 -Installer $installers[0].FullName
|
||||
|
||||
- name: Verify signed and notarized macOS bundles
|
||||
if: matrix.macos
|
||||
run: |
|
||||
@@ -360,7 +402,7 @@ jobs:
|
||||
cat > "$portable_dir/README-portable.txt" <<'EOF'
|
||||
Codex-X Windows Portable
|
||||
|
||||
Double click Codex-X.exe to run. No MSI installation is required.
|
||||
Double click Codex-X.exe to run. No installation is required.
|
||||
The portable edition uses manual downloads instead of in-app installation.
|
||||
Keep Codex-X.portable next to Codex-X.exe so the app can identify this edition.
|
||||
Microsoft Edge WebView2 Runtime is required; Windows 10/11 usually already includes it.
|
||||
@@ -435,6 +477,7 @@ jobs:
|
||||
--repository "$GITHUB_REPOSITORY" \
|
||||
--release-tag "$RELEASE_TAG" \
|
||||
--rewrite-download-urls \
|
||||
--migrate-windows-to-nsis \
|
||||
--require-signature-assets
|
||||
gh release upload "$RELEASE_TAG" latest.json --clobber
|
||||
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
name: Windows installer verification
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- 'codex/windows-updater-*'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: windows-installer-check-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
windows-installer:
|
||||
name: Verify Windows update migration
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 45
|
||||
defaults:
|
||||
run:
|
||||
shell: pwsh
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5
|
||||
- uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1
|
||||
with:
|
||||
version: 10.26.0
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
- uses: dtolnay/rust-toolchain@4be7066ada62dd38de10e7b70166bc74ed198c30
|
||||
with:
|
||||
toolchain: stable
|
||||
- uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32
|
||||
with:
|
||||
workspaces: apps/desktop/src-tauri
|
||||
cache-on-failure: true
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm --dir apps/desktop typecheck
|
||||
- run: node --test apps/desktop/tests/*.test.mjs
|
||||
- name: Verify SDK TLS fixture tooling
|
||||
run: |
|
||||
$openssl = Get-Command openssl -ErrorAction Stop
|
||||
& $openssl.Source version
|
||||
- name: Run Windows release tests
|
||||
run: |
|
||||
$artifacts = Join-Path $env:RUNNER_TEMP 'codexx-test-artifacts.json'
|
||||
cargo test --release --manifest-path apps/desktop/src-tauri/Cargo.toml --lib --locked --no-run --message-format=json > $artifacts
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
$harness = ./scripts/ensure-test-common-controls.ps1 -CargoJson $artifacts -OutputDirectory $env:RUNNER_TEMP | ConvertFrom-Json
|
||||
Write-Host "Running all tests in $($harness.testExecutable)"
|
||||
$env:PATH = "$(Split-Path -Parent $harness.testExecutable);$env:PATH"
|
||||
Push-Location apps/desktop/src-tauri
|
||||
try {
|
||||
& $harness.testExecutable --test-threads=1
|
||||
$testExitCode = $LASTEXITCODE
|
||||
} finally { Pop-Location }
|
||||
if ($testExitCode -ne 0) { exit $testExitCode }
|
||||
- name: Diagnose failed Windows test loader
|
||||
if: failure()
|
||||
run: ./scripts/windows-dll-diagnostics.ps1 -RunHarnessList
|
||||
- name: Retain Windows loader diagnostics
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
with:
|
||||
name: windows-loader-diagnostics
|
||||
path: ${{ runner.temp }}/codexx-dll-diagnostics
|
||||
retention-days: 7
|
||||
if-no-files-found: warn
|
||||
- name: Build test installer without publishing or release signing credentials
|
||||
run: |
|
||||
Set-Content -Path "$env:RUNNER_TEMP\installer-check.json" -Value '{"bundle":{"createUpdaterArtifacts":false}}' -Encoding utf8
|
||||
pnpm --dir apps/desktop tauri build --debug --bundles nsis --config "$env:RUNNER_TEMP\installer-check.json" --ci
|
||||
- name: Test real MSI migration and subsequent updates
|
||||
run: |
|
||||
$installers = @(Get-ChildItem apps/desktop/src-tauri/target/debug/bundle/nsis -Filter '*.exe')
|
||||
if ($installers.Count -ne 1) { throw 'Expected one Windows installer.' }
|
||||
./scripts/windows-install-smoke.ps1 -Installer $installers[0].FullName
|
||||
@@ -0,0 +1,24 @@
|
||||
name: Windows MSI API probe
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ['codex/windows-updater-*']
|
||||
paths: ['scripts/windows-msi-probe.ps1', '.github/workflows/windows-msi-probe.yml']
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
msi-probe:
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5
|
||||
- shell: pwsh
|
||||
run: |
|
||||
if (-not (Test-Path "${env:ProgramFiles(x86)}\NSIS\makensis.exe")) {
|
||||
choco install nsis --yes --no-progress
|
||||
}
|
||||
- shell: pwsh
|
||||
run: ./scripts/windows-msi-probe.ps1
|
||||
+44
-1
@@ -2,7 +2,50 @@
|
||||
|
||||
记录 Codex-X 的新功能、体验改进和问题修复。
|
||||
|
||||
## [v0.3.19] - 2026-09-18
|
||||
## [v0.3.27] - 2026-10-17
|
||||
|
||||
- 会话同步期间可启用或切换供应商;每次同步固定开始时的目标,完成后按当前供应商更新状态。
|
||||
- 识别 Codex 保留 `.jsonl` 逻辑路径、实际使用 `.jsonl.zst` 的压缩会话;同步、预览、导出及删除兼容压缩存储,保留流式处理、备份和并发修改保护。
|
||||
- 状态检查省去整文件改写快照与重压,减少同步中重复的完整日志扫描。
|
||||
- 会话按历史工作目录分组时保留原路径拼写,不再探测或打开项目目录,减少触发“文稿”等目录的权限提示。
|
||||
- 新增「Codex 简体中文」开关,读取 Codex 实际语言配置,重启后应用待生效的选择,关闭时恢复原语言或自动检测;支持 macOS,以及经过官方身份验证的 Windows Store 版和独立安装版(Store 版仅支持默认 `CODEX_HOME`)。
|
||||
- 统一设置页和操作提示中的「重启 Codex」入口,同时应用待生效的语言设置;改进进程退出与启动确认,减少首次重启失败、再次点击才成功的问题。
|
||||
- 供应商卡片新增 DeepSeek、OpenRouter、硅基流动和 Moonshot 余额查询,区分账户余额与 Key 剩余额度,支持后台定时更新、手动刷新和查看最近查询时间。
|
||||
- 余额刷新复用同一凭据的并发请求,按实际查询时间安排后续刷新,避免手动查询或读取缓存推迟后台更新;金额保留十进制精度,查询失败时保留此前余额并显示失败状态。
|
||||
- 官方账号编辑支持读取单个标准 `auth.json` 文件到编辑区,校验后由用户保存。
|
||||
- 重启 Codex 失败时保留错误详情,支持手动关闭,便于定位失败原因。
|
||||
|
||||
## [v0.3.26] - 2026-10-09
|
||||
|
||||
- 安装版在线更新的主通道失败后,自动通过官方 GitHub API 获取更新清单和安装包,继续由原生更新器检查版本、平台和签名;不再因一次检查失败就静默改为仅手动下载。
|
||||
|
||||
- 供应商新增上游协议选择,本地路由可将 Chat Completions、Claude Messages 和 Gemini 原生请求/响应转换为 Codex 使用的 Responses,支持图片、工具调用及流式输出。
|
||||
- 模型获取和连接检测按所选协议发送认证与 Headers;从 CC Switch 导入时保留显式协议选择。
|
||||
- 配置检查显示文件、行列、参数和具体处理建议;切回官方账号后可安全修复旧会话缺失的供应商定义。
|
||||
- 供应商页面新增自定义 Headers 编辑,支持固定值和环境变量,并在对应行显示校验错误;可选择 Claude Code / Kilo Code 的 User-Agent 预设,填写提示按请求头用途区分。
|
||||
- 使用协议转换时,退出和更新保留本地路由与恢复记录,重开后恢复相同协议;关闭路由前提示切回原生 Responses/官方,避免无效直连。
|
||||
|
||||
## [v0.3.24] - 2026-10-01
|
||||
|
||||
- 会话管理新增工作文件夹侧栏、文件夹与会话置顶,并使用虚拟列表减少大量会话的渲染开销。
|
||||
- 会话日志改为流式读取和磁盘快照处理,大日志及超长单条记录也能同步;读取、写入或复查失败时明确报错并执行安全回滚,避免日志、数据库索引与同步状态不一致。
|
||||
- 修复文件夹路径大小写混淆导致显示错误会话、置顶联动和缓存串用的问题,按实际文件系统身份区分目录或合并同目录别名。
|
||||
- 置顶按 Codex 配置目录分别保存,文件夹暂时不可读或重建后按原始路径保留置顶。旧 PR 预览版的 v1 置顶缓存不自动迁移,需重新置顶。
|
||||
|
||||
- 修复 Windows 下会话索引原子替换被文件句柄阻止的问题。
|
||||
|
||||
## [v0.3.22] - 2026-09-30
|
||||
|
||||
- 修复第三方模型被错误识别为“仅文本”而无法输入图片的问题,并自动升级旧版生成的模型目录。需供应商模型本身支持图片,更新菜单后重启 Codex 生效。
|
||||
- 供应商卡片支持上下拖动排序并自动保存,重启后保留顺序;也可聚焦左侧手柄后使用上下箭头移动。
|
||||
- 在供应商卡片显示已选模型名称,设置映射别名时同时保留真实模型 ID。
|
||||
- 补充 Ultra 思考强度的 Codex 设置提示,并修复旧模型目录遗漏图片或完整思考强度的问题。
|
||||
|
||||
## [v0.3.21] - 2026-09-23
|
||||
|
||||
- 优化 Windows 在线更新,缩短安装等待;旧版可自动迁移,正常更新无需重启电脑,账号和配置保留。
|
||||
|
||||
## [v0.3.20] - 2026-09-18
|
||||
|
||||
- 新增「设置 → 路由与故障转移」:可管理本地路由、安排供应商优先顺序,并在服务异常时自动切换;支持调整超时和重试参数,官方登录也可使用本地路由。
|
||||
- 修复添加或切换第三方供应商时,MCP、桌面设置等配置丢失的问题。
|
||||
|
||||
@@ -118,7 +118,7 @@
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><b>跨平台使用</b></td>
|
||||
<td align="left">提供 macOS Apple Silicon / Intel、Windows MSI / 便携版和 Linux 安装包;安装版可在应用内直接下载、校验并安装更新,便携版继续使用手动下载。</td>
|
||||
<td align="left">提供 macOS Apple Silicon / Intel、Windows EXE / 便携版和 Linux 安装包;安装版可在应用内直接下载、校验并安装更新,便携版继续使用手动下载。</td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
@@ -238,7 +238,8 @@ Codex-X 现在不只是“几套内置 Prompt”的启动器,而是一个可
|
||||
- 保存多个可命名的官方 Codex 登录配置与第三方供应商,随时查看当前正在使用哪一个
|
||||
- 点击“复制”直接新增独立副本,无需确认或进入编辑页;名称可稍后修改
|
||||
- 切换前可检测连接,并可获取模型进行测试
|
||||
- 在同一页面编辑 Base URL、API Key、Model、Wire API 和完整 TOML
|
||||
- 在同一页面编辑 Base URL、API Key、Model、上游接口协议、Headers 和完整 TOML
|
||||
- 本地路由支持 Responses、Chat Completions、Claude Messages、Gemini 原生接口,使用方式与边界见[供应商协议说明](docs/PROVIDER_PROTOCOLS.md)
|
||||
- 从 cc-switch 导入时自动区分新增、更新、合并与跳过;相同 URL + Key 不再重复显示
|
||||
- 切回 OpenAI Official 时保留当前官方登录态,第三方配置也不会凭空消失
|
||||
|
||||
@@ -335,7 +336,7 @@ Codex-X 现在不只是“几套内置 Prompt”的启动器,而是一个可
|
||||
|
||||
- macOS Apple Silicon `.dmg`
|
||||
- macOS Intel `.dmg`
|
||||
- Windows `.msi`
|
||||
- Windows `.exe`(安装到当前用户,后续更新无需管理员权限)
|
||||
- Windows Portable `.zip`
|
||||
- Linux `.deb` / `.rpm` / `.AppImage`
|
||||
- GitHub Releases 自动构建发布
|
||||
|
||||
+29
-1
@@ -28,4 +28,32 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
SOFTWARE.
|
||||
|
||||
## Tauri Windows installer template
|
||||
|
||||
Source: https://github.com/tauri-apps/tauri/blob/tauri-cli-v2.11.4/crates/tauri-bundler/src/bundle/windows/templates/installer.nsi
|
||||
|
||||
Codex-X adapts the Tauri CLI v2.11.4 NSIS template for current-user installation, verified legacy MSI migration, update handoff and installation diagnostics.
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2017 - Present Tauri Apps Contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "codex-x",
|
||||
"version": "0.3.19",
|
||||
"version": "0.3.27",
|
||||
"private": true,
|
||||
"description": "Codex Switch & Instruct desktop manager",
|
||||
"type": "module",
|
||||
|
||||
Generated
+76
-1
@@ -492,7 +492,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "codex-x"
|
||||
version = "0.3.19"
|
||||
version = "0.3.27"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
@@ -514,10 +514,13 @@ dependencies = [
|
||||
"tauri-plugin-process",
|
||||
"tauri-plugin-single-instance",
|
||||
"tauri-plugin-updater",
|
||||
"tempfile",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"toml_edit 0.22.27",
|
||||
"tungstenite",
|
||||
"ureq",
|
||||
"windows-sys 0.61.2",
|
||||
"zip 2.4.2",
|
||||
"zstd",
|
||||
]
|
||||
@@ -717,6 +720,12 @@ dependencies = [
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "data-encoding"
|
||||
version = "2.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
|
||||
|
||||
[[package]]
|
||||
name = "dbus"
|
||||
version = "0.9.12"
|
||||
@@ -2718,6 +2727,15 @@ version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
|
||||
|
||||
[[package]]
|
||||
name = "ppv-lite86"
|
||||
version = "0.2.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
|
||||
dependencies = [
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "precomputed-hash"
|
||||
version = "0.1.1"
|
||||
@@ -2815,6 +2833,35 @@ version = "6.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
|
||||
dependencies = [
|
||||
"rand_chacha",
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_chacha"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
|
||||
dependencies = [
|
||||
"ppv-lite86",
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raw-window-handle"
|
||||
version = "0.6.2"
|
||||
@@ -3386,6 +3433,17 @@ dependencies = [
|
||||
"stable_deref_trait",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha1"
|
||||
version = "0.10.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.10.9"
|
||||
@@ -4392,6 +4450,23 @@ version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
|
||||
|
||||
[[package]]
|
||||
name = "tungstenite"
|
||||
version = "0.28.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8628dcc84e5a09eb3d8423d6cb682965dea9133204e8fb3efee74c2a0c259442"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"data-encoding",
|
||||
"http",
|
||||
"httparse",
|
||||
"log",
|
||||
"rand",
|
||||
"sha1",
|
||||
"thiserror 2.0.18",
|
||||
"utf-8",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "typeid"
|
||||
version = "1.0.3"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "codex-x"
|
||||
version = "0.3.19"
|
||||
version = "0.3.27"
|
||||
description = "Codex Switch & Instruct desktop manager"
|
||||
authors = ["yynxxxxx"]
|
||||
license = "MIT"
|
||||
@@ -19,7 +19,7 @@ tauri = { version = "2.8.2", features = ["tray-icon"] }
|
||||
tauri-plugin-process = "2.3.1"
|
||||
tauri-plugin-updater = "2.10.1"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
serde_json = { version = "1.0", features = ["arbitrary_precision"] }
|
||||
base64 = "0.22"
|
||||
toml_edit = "0.22"
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
@@ -45,3 +45,11 @@ getrandom = "0.2"
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "time", "net"] }
|
||||
flate2 = "1"
|
||||
zstd = "0.13"
|
||||
tempfile = "3.27"
|
||||
tungstenite = { version = "0.28", default-features = false, features = ["handshake"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tauri = { version = "2.8.2", features = ["test"] }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "=0.61.2", features = ["Win32_Foundation", "Win32_Storage_FileSystem"] }
|
||||
|
||||
@@ -7,9 +7,6 @@
|
||||
"core:default",
|
||||
"core:window:allow-start-dragging",
|
||||
"updater:allow-check",
|
||||
"updater:allow-download",
|
||||
"updater:allow-install",
|
||||
"updater:allow-download-and-install",
|
||||
"process:allow-restart"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2017 - Present Tauri Apps Contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -7,7 +7,7 @@ use std::path::{Path, PathBuf};
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
use std::time::Duration;
|
||||
|
||||
const APP_DB_SCHEMA_VERSION: i64 = 7;
|
||||
const APP_DB_SCHEMA_VERSION: i64 = 9;
|
||||
|
||||
struct DatabaseInitializer {
|
||||
migration_lock: Mutex<()>,
|
||||
@@ -149,6 +149,7 @@ fn initialize_schema(conn: &Connection) -> Result<()> {
|
||||
wire_api TEXT NOT NULL DEFAULT 'responses',
|
||||
requires_openai_auth INTEGER NOT NULL DEFAULT 1,
|
||||
model_mappings_json TEXT NOT NULL DEFAULT '[]',
|
||||
upstream_api TEXT,
|
||||
source TEXT NOT NULL DEFAULT 'manual',
|
||||
source_id TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
@@ -228,6 +229,11 @@ fn initialize_schema(conn: &Connection) -> Result<()> {
|
||||
codex_dir TEXT PRIMARY KEY,
|
||||
profile_id TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS provider_card_orders (
|
||||
codex_dir TEXT PRIMARY KEY,
|
||||
order_json TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);",
|
||||
)
|
||||
.map_err(|e| CodexxError::Database(e.to_string()))?;
|
||||
@@ -255,6 +261,12 @@ fn initialize_schema(conn: &Connection) -> Result<()> {
|
||||
"model_mappings_json",
|
||||
"ALTER TABLE providers ADD COLUMN model_mappings_json TEXT NOT NULL DEFAULT '[]'",
|
||||
)?;
|
||||
ensure_sqlite_column(
|
||||
conn,
|
||||
"providers",
|
||||
"upstream_api",
|
||||
"ALTER TABLE providers ADD COLUMN upstream_api TEXT",
|
||||
)?;
|
||||
conn.execute_batch(
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS idx_providers_source_identity
|
||||
ON providers(source, source_id)
|
||||
@@ -434,6 +446,180 @@ mod tests {
|
||||
remove_test_db(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_seven_database_adds_card_order_preferences_without_changing_provider_data() {
|
||||
let path = test_db_path("provider-card-order-v8");
|
||||
let initializer = DatabaseInitializer::new();
|
||||
let legacy = initializer.open_at(&path).unwrap();
|
||||
legacy.execute_batch(
|
||||
"INSERT INTO providers
|
||||
(id, provider_name, base_url, model, api_key, created_at, updated_at)
|
||||
VALUES ('existing', 'Existing provider', 'https://fixture.test/v1', 'fixture-model',
|
||||
'fixture-key', 'original-created', 'original-updated');
|
||||
INSERT INTO official_profiles
|
||||
(codex_dir, id, provider_name, created_at, updated_at)
|
||||
VALUES ('/fixture/config', 'existing-account', 'Existing account', 'created', 'updated');
|
||||
DROP TABLE provider_card_orders;
|
||||
PRAGMA user_version = 7;",
|
||||
)
|
||||
.unwrap();
|
||||
let before = crate::providers::list_saved_providers_on_connection(&legacy).unwrap();
|
||||
drop(legacy);
|
||||
|
||||
let migrated = initializer.open_at(&path).unwrap();
|
||||
assert_eq!(schema_version(&migrated).unwrap(), APP_DB_SCHEMA_VERSION);
|
||||
assert_eq!(
|
||||
crate::providers::list_saved_providers_on_connection(&migrated).unwrap(),
|
||||
before
|
||||
);
|
||||
let timestamps: (String, String) = migrated
|
||||
.query_row(
|
||||
"SELECT created_at, updated_at FROM providers WHERE id = 'existing'",
|
||||
[],
|
||||
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
timestamps,
|
||||
("original-created".into(), "original-updated".into())
|
||||
);
|
||||
assert_eq!(
|
||||
migrated
|
||||
.query_row(
|
||||
"SELECT provider_name FROM official_profiles WHERE id = 'existing-account'",
|
||||
[],
|
||||
|row| row.get::<_, String>(0)
|
||||
)
|
||||
.unwrap(),
|
||||
"Existing account"
|
||||
);
|
||||
assert_eq!(
|
||||
migrated
|
||||
.query_row("SELECT COUNT(*) FROM provider_card_orders", [], |row| row
|
||||
.get::<_, i64>(
|
||||
0
|
||||
))
|
||||
.unwrap(),
|
||||
0
|
||||
);
|
||||
drop(migrated);
|
||||
remove_test_db(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_eight_migration_keeps_provider_data_and_defaults_upstream_api_to_null() {
|
||||
let path = test_db_path("provider-upstream-api-v9");
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
let legacy = Connection::open(&path).unwrap();
|
||||
legacy
|
||||
.execute_batch(
|
||||
"CREATE TABLE providers (
|
||||
id TEXT PRIMARY KEY,
|
||||
provider_name TEXT NOT NULL,
|
||||
base_url TEXT NOT NULL,
|
||||
model TEXT NOT NULL,
|
||||
api_key TEXT,
|
||||
toml_config TEXT,
|
||||
wire_api TEXT NOT NULL DEFAULT 'responses',
|
||||
requires_openai_auth INTEGER NOT NULL DEFAULT 1,
|
||||
model_mappings_json TEXT NOT NULL DEFAULT '[]',
|
||||
source TEXT NOT NULL DEFAULT 'manual',
|
||||
source_id TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
INSERT INTO providers
|
||||
(id, provider_name, base_url, model, api_key, toml_config, wire_api,
|
||||
requires_openai_auth, model_mappings_json, source, source_id,
|
||||
created_at, updated_at)
|
||||
VALUES
|
||||
('legacy-responses', 'Existing Responses provider', 'https://responses.fixture/v1',
|
||||
'existing-model', 'fixture-secret', 'model_provider = \"custom\"', 'responses',
|
||||
1, '[{\"displayName\":\"Mapped model\",\"model\":\"upstream-model\"}]',
|
||||
'cc-switch', 'fixture-source-row', 'original-created', 'original-updated'),
|
||||
('legacy-chat', 'Existing Chat provider', 'https://chat.fixture/v1',
|
||||
'chat-model', NULL, NULL, 'chat',
|
||||
0, '[]', 'manual', NULL, 'chat-created', 'chat-updated');
|
||||
PRAGMA user_version = 8;",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(schema_version(&legacy).unwrap(), 8);
|
||||
assert!(!table_column_set(&legacy, "providers")
|
||||
.unwrap()
|
||||
.contains("upstream_api"));
|
||||
let snapshot = |conn: &Connection| {
|
||||
let mut statement = conn
|
||||
.prepare(
|
||||
"SELECT id, provider_name, base_url, model, api_key, toml_config,
|
||||
wire_api, requires_openai_auth, model_mappings_json,
|
||||
source, source_id, created_at, updated_at
|
||||
FROM providers ORDER BY id",
|
||||
)
|
||||
.unwrap();
|
||||
let rows = statement
|
||||
.query_map([], |row| {
|
||||
(0..13)
|
||||
.map(|index| row.get::<_, rusqlite::types::Value>(index))
|
||||
.collect::<rusqlite::Result<Vec<_>>>()
|
||||
})
|
||||
.unwrap();
|
||||
rows.collect::<rusqlite::Result<Vec<_>>>().unwrap()
|
||||
};
|
||||
let before = snapshot(&legacy);
|
||||
drop(legacy);
|
||||
|
||||
let initializer = DatabaseInitializer::new();
|
||||
let migrated = initializer.open_at(&path).unwrap();
|
||||
assert_eq!(schema_version(&migrated).unwrap(), 9);
|
||||
assert!(table_column_set(&migrated, "providers")
|
||||
.unwrap()
|
||||
.contains("upstream_api"));
|
||||
assert_eq!(
|
||||
snapshot(&migrated),
|
||||
before,
|
||||
"all pre-existing provider columns must survive migration unchanged"
|
||||
);
|
||||
let upstream_values = migrated
|
||||
.prepare("SELECT upstream_api FROM providers ORDER BY id")
|
||||
.unwrap()
|
||||
.query_map([], |row| row.get::<_, Option<String>>(0))
|
||||
.unwrap()
|
||||
.collect::<rusqlite::Result<Vec<_>>>()
|
||||
.unwrap();
|
||||
assert_eq!(upstream_values, vec![None, None]);
|
||||
let providers = crate::providers::list_saved_providers_on_connection(&migrated).unwrap();
|
||||
assert_eq!(providers.len(), 2);
|
||||
let responses = providers
|
||||
.iter()
|
||||
.find(|provider| provider.id == "legacy-responses")
|
||||
.unwrap();
|
||||
assert!(responses.upstream_api.is_none());
|
||||
assert_eq!(responses.api_key.as_deref(), Some("fixture-secret"));
|
||||
assert_eq!(responses.model_mappings.len(), 1);
|
||||
assert_eq!(responses.model_mappings[0].model, "upstream-model");
|
||||
drop(migrated);
|
||||
|
||||
let reopened = DatabaseInitializer::new().open_at(&path).unwrap();
|
||||
assert_eq!(schema_version(&reopened).unwrap(), 9);
|
||||
assert_eq!(
|
||||
snapshot(&reopened),
|
||||
before,
|
||||
"reopening must leave migrated provider data unchanged"
|
||||
);
|
||||
assert_eq!(
|
||||
reopened
|
||||
.query_row(
|
||||
"SELECT COUNT(*) FROM providers WHERE upstream_api IS NULL",
|
||||
[],
|
||||
|row| row.get::<_, i64>(0)
|
||||
)
|
||||
.unwrap(),
|
||||
2
|
||||
);
|
||||
drop(reopened);
|
||||
remove_test_db(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_one_database_migrates_new_metadata_tables_without_data_loss() {
|
||||
let path = test_db_path("skills-mcp-notes-migration");
|
||||
|
||||
@@ -0,0 +1,667 @@
|
||||
//! Keep downloads and verification in the signed Tauri updater, but own the
|
||||
//! Windows handoff. The stock updater exits immediately and skips our routing
|
||||
//! shutdown; it also cannot report installation progress after that exit.
|
||||
|
||||
use serde::Serialize;
|
||||
use std::fs::{self, File, OpenOptions};
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
use tauri::{ipc::Channel, Manager, ResourceId, Webview};
|
||||
use tauri_plugin_updater::Update;
|
||||
|
||||
#[cfg(any(test, target_os = "windows"))]
|
||||
#[path = "windows_update.rs"]
|
||||
mod windows;
|
||||
|
||||
static UPDATING: AtomicBool = AtomicBool::new(false);
|
||||
// 0: not installing, 1: installer preparation/write, 2: Windows handoff.
|
||||
static INSTALLATION_PHASE: AtomicU8 = AtomicU8::new(0);
|
||||
const DOWNLOAD_TIMEOUT_MS: u64 = 10 * 60 * 1000;
|
||||
|
||||
struct InstallationExitGuard<'a>(&'a AtomicU8);
|
||||
impl<'a> InstallationExitGuard<'a> {
|
||||
fn begin(phase: &'a AtomicU8) -> Self {
|
||||
phase.store(1, Ordering::Release);
|
||||
Self(phase)
|
||||
}
|
||||
#[cfg(any(test, target_os = "windows"))]
|
||||
fn handed_off(self) {
|
||||
self.0.store(2, Ordering::Release);
|
||||
std::mem::forget(self);
|
||||
}
|
||||
}
|
||||
impl Drop for InstallationExitGuard<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(0, Ordering::Release);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn defer_exit_during_installation() -> bool {
|
||||
INSTALLATION_PHASE.load(Ordering::Acquire) == 1
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize)]
|
||||
#[serde(tag = "event", content = "data")]
|
||||
pub(crate) enum AppUpdateEvent {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
Started {
|
||||
content_length: Option<u64>,
|
||||
},
|
||||
#[serde(rename_all = "camelCase")]
|
||||
Progress {
|
||||
chunk_length: usize,
|
||||
},
|
||||
Verifying,
|
||||
#[allow(dead_code)] // Emitted by the Windows handoff; other platforms install in place.
|
||||
Preparing,
|
||||
Installing,
|
||||
#[allow(dead_code)]
|
||||
HandedOff,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub(crate) enum FailureStage {
|
||||
Download,
|
||||
Verify,
|
||||
Prepare,
|
||||
Install,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct UpdateFailure {
|
||||
stage: FailureStage,
|
||||
message: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
log_path: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct InstallResult {
|
||||
restart_required: bool,
|
||||
}
|
||||
|
||||
struct UpdateLease<'a>(&'a AtomicBool);
|
||||
impl<'a> UpdateLease<'a> {
|
||||
fn acquire(flag: &'a AtomicBool) -> Result<Self, UpdateFailure> {
|
||||
flag.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
|
||||
.map_err(|_| {
|
||||
failure(
|
||||
FailureStage::Prepare,
|
||||
"已有更新正在进行,请等待当前操作完成。",
|
||||
None,
|
||||
)
|
||||
})?;
|
||||
Ok(Self(flag))
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
fn handoff(self) {
|
||||
// Never permit a second installer while the original app is exiting.
|
||||
std::mem::forget(self);
|
||||
}
|
||||
}
|
||||
impl Drop for UpdateLease<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(false, Ordering::Release);
|
||||
}
|
||||
}
|
||||
|
||||
fn failure(stage: FailureStage, message: &str, log: Option<&UpdateLog>) -> UpdateFailure {
|
||||
UpdateFailure {
|
||||
stage,
|
||||
message: message.into(),
|
||||
log_path: log.map(|log| log.path.to_string_lossy().into_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Check before changing the installed application on every platform. The
|
||||
/// converted supplier cannot resume through a raw Responses endpoint after exit.
|
||||
fn install_with_route_preflight<T>(
|
||||
check: impl FnOnce() -> Result<(), ()>,
|
||||
install: impl FnOnce() -> Result<T, UpdateFailure>,
|
||||
log: &UpdateLog,
|
||||
) -> Result<T, UpdateFailure> {
|
||||
if check().is_err() {
|
||||
log.record("routing_recovery_preflight_failed");
|
||||
return Err(failure(
|
||||
FailureStage::Prepare,
|
||||
"更新前未能确认连接配置可恢复,安装尚未开始。请检查路由配置后重试。",
|
||||
Some(log),
|
||||
));
|
||||
}
|
||||
install()
|
||||
}
|
||||
|
||||
/// This log contains only our fixed stage names and version, never URLs,
|
||||
/// headers, auth/config contents or raw network/parser error messages.
|
||||
struct UpdateLog {
|
||||
path: PathBuf,
|
||||
file: Mutex<File>,
|
||||
}
|
||||
impl UpdateLog {
|
||||
fn create(dir: &Path, version: &str) -> std::io::Result<Self> {
|
||||
let version = semver::Version::parse(version).map_err(|_| {
|
||||
std::io::Error::new(std::io::ErrorKind::InvalidInput, "invalid version")
|
||||
})?;
|
||||
fs::create_dir_all(dir)?;
|
||||
let mut nonce = [0u8; 8];
|
||||
getrandom::getrandom(&mut nonce)
|
||||
.map_err(|_| std::io::Error::other("random source unavailable"))?;
|
||||
let nonce: String = nonce.iter().map(|b| format!("{b:02x}")).collect();
|
||||
let path = dir.join(format!(
|
||||
"update-{}-{}-{nonce}.log",
|
||||
chrono::Utc::now().format("%Y%m%d-%H%M%S"),
|
||||
std::process::id()
|
||||
));
|
||||
let mut options = OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
options.mode(0o600);
|
||||
}
|
||||
let file = Mutex::new(options.open(&path)?);
|
||||
let log = Self { path, file };
|
||||
log.record(&format!("target_version={version}"));
|
||||
Ok(log)
|
||||
}
|
||||
fn record(&self, stage: &str) {
|
||||
if let Ok(mut file) = self.file.lock() {
|
||||
let _ = writeln!(file, "{} {stage}", chrono::Utc::now().to_rfc3339());
|
||||
let _ = file.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn timeout_ms(value: Option<u64>) -> u64 {
|
||||
value
|
||||
.unwrap_or(DOWNLOAD_TIMEOUT_MS)
|
||||
.clamp(30_000, DOWNLOAD_TIMEOUT_MS)
|
||||
}
|
||||
|
||||
enum DownloadAttemptFailure {
|
||||
Transport,
|
||||
Verification,
|
||||
}
|
||||
|
||||
async fn download_attempt(
|
||||
update: &Update,
|
||||
on_event: &Channel<AppUpdateEvent>,
|
||||
log: &UpdateLog,
|
||||
) -> Result<Vec<u8>, DownloadAttemptFailure> {
|
||||
let finished = AtomicBool::new(false);
|
||||
let mut started = false;
|
||||
update
|
||||
.download(
|
||||
|chunk_length, content_length| {
|
||||
if !started {
|
||||
started = true;
|
||||
let _ = on_event.send(AppUpdateEvent::Started { content_length });
|
||||
}
|
||||
let _ = on_event.send(AppUpdateEvent::Progress { chunk_length });
|
||||
},
|
||||
|| {
|
||||
finished.store(true, Ordering::Release);
|
||||
log.record("verifying_signature");
|
||||
let _ = on_event.send(AppUpdateEvent::Verifying);
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
if finished.load(Ordering::Acquire) {
|
||||
DownloadAttemptFailure::Verification
|
||||
} else {
|
||||
DownloadAttemptFailure::Transport
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async fn download_with_recovery(
|
||||
update: &Update,
|
||||
mut candidates: Vec<reqwest::Url>,
|
||||
on_event: &Channel<AppUpdateEvent>,
|
||||
log: &UpdateLog,
|
||||
) -> Result<Vec<u8>, UpdateFailure> {
|
||||
match download_attempt(update, on_event, log).await {
|
||||
Ok(bytes) => return Ok(bytes),
|
||||
Err(DownloadAttemptFailure::Verification) => {
|
||||
log.record("signature_verification_failed");
|
||||
return Err(failure(
|
||||
FailureStage::Verify,
|
||||
"更新包校验未通过,未启动安装。请重新检查在线更新。",
|
||||
Some(log),
|
||||
));
|
||||
}
|
||||
Err(DownloadAttemptFailure::Transport) => log.record("primary_download_transport_failed"),
|
||||
}
|
||||
if candidates.is_empty() {
|
||||
match crate::app_update_channel::discover_download_candidates(update).await {
|
||||
Ok(found) => candidates = found,
|
||||
Err(_) => log.record("official_api_asset_lookup_failed"),
|
||||
}
|
||||
}
|
||||
for candidate in candidates {
|
||||
let alternate = match crate::app_update_channel::api_download_update(update, &candidate) {
|
||||
Ok(alternate) => alternate,
|
||||
Err(_) => continue,
|
||||
};
|
||||
log.record("retrying_download_via_official_api");
|
||||
match download_attempt(&alternate, on_event, log).await {
|
||||
Ok(bytes) => {
|
||||
log.record("official_api_download_verified");
|
||||
return Ok(bytes);
|
||||
}
|
||||
Err(DownloadAttemptFailure::Verification) => {
|
||||
log.record("signature_verification_failed");
|
||||
return Err(failure(
|
||||
FailureStage::Verify,
|
||||
"更新包校验未通过,未启动安装。请重新检查在线更新。",
|
||||
Some(log),
|
||||
));
|
||||
}
|
||||
Err(DownloadAttemptFailure::Transport) => {
|
||||
log.record("official_api_download_transport_failed")
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(failure(
|
||||
FailureStage::Download,
|
||||
"在线更新的主通道和官方备用通道均未能完成下载。请检查网络或代理后重试。",
|
||||
Some(log),
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) async fn verify_download_recovery_for_test(
|
||||
update: &Update,
|
||||
candidates: Vec<reqwest::Url>,
|
||||
) -> Result<Vec<u8>, UpdateFailure> {
|
||||
let temporary = tempfile::tempdir().expect("temporary updater test log");
|
||||
let log = UpdateLog::create(temporary.path(), &update.version).expect("updater test log");
|
||||
let channel = Channel::new(|_| Ok(()));
|
||||
let bytes = download_with_recovery(update, candidates, &channel, &log).await?;
|
||||
// Exercise the Windows staging handoff with verified fixture bytes only.
|
||||
// Dropping this private temporary file never executes an installer.
|
||||
let staged = windows::StagedInstaller::create(&bytes)
|
||||
.expect("verified synthetic Windows packet stages successfully");
|
||||
drop(staged);
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// No installer is launched until all preparation succeeds. If launch fails,
|
||||
/// restore routing while the original app and single-instance lock still live.
|
||||
#[cfg(any(test, target_os = "windows"))]
|
||||
fn prepared_install<T>(
|
||||
prepare: impl FnOnce() -> Result<(), ()>,
|
||||
launch: impl FnOnce() -> Result<T, ()>,
|
||||
resume: impl FnOnce() -> Result<(), ()>,
|
||||
log: &UpdateLog,
|
||||
) -> Result<T, UpdateFailure> {
|
||||
if prepare().is_err() {
|
||||
log.record("prepare_failed");
|
||||
let resumed = resume().is_ok();
|
||||
log.record(if resumed {
|
||||
"routing_resumed"
|
||||
} else {
|
||||
"routing_resume_failed"
|
||||
});
|
||||
return Err(failure(
|
||||
FailureStage::Prepare,
|
||||
if resumed {
|
||||
"更新前未能恢复路由配置,安装尚未启动。请检查配置文件后重试。"
|
||||
} else {
|
||||
"更新前的路由清理未完成,安装尚未启动。请检查路由设置后重试。"
|
||||
},
|
||||
Some(log),
|
||||
));
|
||||
}
|
||||
match launch() {
|
||||
Ok(result) => Ok(result),
|
||||
Err(()) => {
|
||||
log.record("installer_launch_failed");
|
||||
let resumed = resume().is_ok();
|
||||
log.record(if resumed {
|
||||
"routing_resumed"
|
||||
} else {
|
||||
"routing_resume_failed"
|
||||
});
|
||||
Err(failure(
|
||||
FailureStage::Install,
|
||||
if resumed {
|
||||
"无法启动更新安装器,原有路由已恢复。请重试或打开下载页安装。"
|
||||
} else {
|
||||
"无法启动更新安装器。请检查路由设置;也可打开下载页安装。"
|
||||
},
|
||||
Some(log),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub(crate) async fn install_app_update(
|
||||
webview: Webview,
|
||||
update_rid: ResourceId,
|
||||
on_event: Channel<AppUpdateEvent>,
|
||||
timeout: Option<u64>,
|
||||
headers: Option<Vec<(String, String)>>,
|
||||
) -> Result<InstallResult, UpdateFailure> {
|
||||
let _lease = UpdateLease::acquire(&UPDATING)?;
|
||||
let (mut update, download_candidates) = if let Ok(owned) =
|
||||
webview
|
||||
.resources_table()
|
||||
.get::<crate::app_update_channel::OwnedOnlineUpdate>(update_rid)
|
||||
{
|
||||
(owned.update.clone(), owned.download_candidates.clone())
|
||||
} else {
|
||||
let update = webview
|
||||
.resources_table()
|
||||
.get::<Update>(update_rid)
|
||||
.map_err(|_| {
|
||||
failure(
|
||||
FailureStage::Prepare,
|
||||
"更新信息已失效,请重新检查更新。",
|
||||
None,
|
||||
)
|
||||
})?;
|
||||
((*update).clone(), Vec::new())
|
||||
};
|
||||
// The metadata-check timeout must not become the package-download limit.
|
||||
update.timeout = Some(Duration::from_millis(timeout_ms(timeout)));
|
||||
if let Some(headers) = headers {
|
||||
update.headers.clear();
|
||||
for (name, value) in headers {
|
||||
let name = reqwest::header::HeaderName::from_bytes(name.as_bytes())
|
||||
.map_err(|_| failure(FailureStage::Prepare, "更新请求参数无效。", None))?;
|
||||
let value = reqwest::header::HeaderValue::from_str(&value)
|
||||
.map_err(|_| failure(FailureStage::Prepare, "更新请求参数无效。", None))?;
|
||||
update.headers.append(name, value);
|
||||
}
|
||||
}
|
||||
let dir = crate::paths::app_home()
|
||||
.map_err(|_| failure(FailureStage::Prepare, "无法读取更新日志目录。", None))?
|
||||
.join("update-logs");
|
||||
let log = UpdateLog::create(&dir, &update.version).map_err(|_| {
|
||||
failure(
|
||||
FailureStage::Prepare,
|
||||
"无法创建更新日志,请检查文件夹权限后重试。",
|
||||
None,
|
||||
)
|
||||
})?;
|
||||
log.record("download_started");
|
||||
let bytes = download_with_recovery(&update, download_candidates, &on_event, &log).await?;
|
||||
log.record("signature_verified");
|
||||
let exit_guard = InstallationExitGuard::begin(&INSTALLATION_PHASE);
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let app = webview.app_handle().clone();
|
||||
let result = install_windows(app, bytes, on_event, log, exit_guard).await;
|
||||
if result.is_ok() {
|
||||
_lease.handoff();
|
||||
}
|
||||
result
|
||||
}
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
{
|
||||
let _ = on_event.send(AppUpdateEvent::Preparing);
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let _exit_guard = exit_guard;
|
||||
install_with_route_preflight(
|
||||
|| crate::failover::begin_update_handoff().map_err(|_| ()),
|
||||
|| {
|
||||
let _ = on_event.send(AppUpdateEvent::Installing);
|
||||
log.record("install_started");
|
||||
update.install(bytes).map_err(|_| {
|
||||
log.record("install_failed");
|
||||
if crate::failover::resume_after_failed_update().is_err() {
|
||||
log.record("routing_resume_failed");
|
||||
}
|
||||
failure(
|
||||
FailureStage::Install,
|
||||
"安装更新未完成,请重试或前往下载页安装。",
|
||||
Some(&log),
|
||||
)
|
||||
})
|
||||
},
|
||||
&log,
|
||||
)?;
|
||||
// The application bytes are already installed. A recovery warning
|
||||
// must not turn this into an install retry or a second installer.
|
||||
if crate::failover::resume_after_failed_update().is_err() {
|
||||
log.record("routing_resume_failed_after_install_restart_required");
|
||||
}
|
||||
log.record("install_finished_restart_required");
|
||||
Ok(InstallResult {
|
||||
restart_required: true,
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(|_| {
|
||||
let _ = crate::failover::resume_after_failed_update();
|
||||
failure(
|
||||
FailureStage::Install,
|
||||
"安装更新未完成,请重新打开软件后检查更新。",
|
||||
None,
|
||||
)
|
||||
})?
|
||||
}
|
||||
}
|
||||
|
||||
// Compile this path in host tests too: staging/Command/IPC use portable Rust,
|
||||
// so Windows handoff type errors are caught before the Windows build starts.
|
||||
#[cfg(any(test, target_os = "windows"))]
|
||||
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||
async fn install_windows(
|
||||
app: tauri::AppHandle,
|
||||
bytes: Vec<u8>,
|
||||
on_event: Channel<AppUpdateEvent>,
|
||||
log: UpdateLog,
|
||||
exit_guard: InstallationExitGuard<'static>,
|
||||
) -> Result<InstallResult, UpdateFailure> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
// Stage bytes before changing live routes. Only signed .exe payloads
|
||||
// from this release pipeline are supported by the new Windows flow.
|
||||
let installer = windows::StagedInstaller::create(&bytes).map_err(|_| {
|
||||
failure(
|
||||
FailureStage::Install,
|
||||
"无法准备 Windows 更新包,请检查磁盘空间或前往下载页安装。",
|
||||
Some(&log),
|
||||
)
|
||||
})?;
|
||||
let _ = on_event.send(AppUpdateEvent::Preparing);
|
||||
log.record("preparing_route_shutdown");
|
||||
install_with_route_preflight(
|
||||
|| crate::failover::ensure_shutdown_allowed().map_err(|_| ()),
|
||||
|| {
|
||||
prepared_install(
|
||||
|| crate::failover::shutdown_all().map_err(|_| ()),
|
||||
|| {
|
||||
let _ = on_event.send(AppUpdateEvent::Installing);
|
||||
log.record("launching_installer");
|
||||
installer.launch(std::process::id()).map_err(|_| ())
|
||||
},
|
||||
|| crate::failover::resume_after_failed_update().map_err(|_| ()),
|
||||
&log,
|
||||
)
|
||||
},
|
||||
&log,
|
||||
)?;
|
||||
log.record("installer_handed_off");
|
||||
let _ = on_event.send(AppUpdateEvent::HandedOff);
|
||||
// Normal Tauri exit destroys windows/tray/single-instance lock. The
|
||||
// new installer waits for this PID before touching installed files.
|
||||
exit_guard.handed_off();
|
||||
app.exit(0);
|
||||
Ok(InstallResult {
|
||||
restart_required: false,
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(|_| {
|
||||
failure(
|
||||
FailureStage::Install,
|
||||
"更新准备过程被中断,请重新打开 Codex-X 后检查更新。",
|
||||
None,
|
||||
)
|
||||
})?
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::RefCell;
|
||||
|
||||
#[test]
|
||||
fn installation_exit_guard_releases_on_failure_and_allows_windows_handoff() {
|
||||
let phase = AtomicU8::new(0);
|
||||
{
|
||||
let _guard = InstallationExitGuard::begin(&phase);
|
||||
assert_eq!(phase.load(Ordering::Acquire), 1);
|
||||
}
|
||||
assert_eq!(phase.load(Ordering::Acquire), 0);
|
||||
InstallationExitGuard::begin(&phase).handed_off();
|
||||
assert_eq!(phase.load(Ordering::Acquire), 2);
|
||||
assert_ne!(phase.load(Ordering::Acquire), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_recovery_preflight_blocks_install_before_application_bytes_change() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let log = UpdateLog::create(temp.path(), "0.4.0").unwrap();
|
||||
let app = temp.path().join("fixture-app");
|
||||
fs::write(&app, b"original fixture").unwrap();
|
||||
let error = install_with_route_preflight(
|
||||
|| Err(()),
|
||||
|| {
|
||||
fs::write(&app, b"replacement fixture").unwrap();
|
||||
Ok(())
|
||||
},
|
||||
&log,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.stage, FailureStage::Prepare);
|
||||
assert!(error.message.contains("可恢复"));
|
||||
assert!(error.message.contains("安装尚未开始"));
|
||||
assert_eq!(fs::read(&app).unwrap(), b"original fixture");
|
||||
let stages = fs::read_to_string(&log.path).unwrap();
|
||||
assert!(stages.contains("routing_recovery_preflight_failed"));
|
||||
assert!(!stages.contains("install_started"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_route_preflight_installs_once_and_preserves_installer_errors() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let log = UpdateLog::create(temp.path(), "0.4.0").unwrap();
|
||||
let calls = RefCell::new(vec![]);
|
||||
let error = install_with_route_preflight(
|
||||
|| {
|
||||
calls.borrow_mut().push("check");
|
||||
Ok(())
|
||||
},
|
||||
|| {
|
||||
calls.borrow_mut().push("install");
|
||||
Err::<(), _>(failure(
|
||||
FailureStage::Install,
|
||||
"fixture install error",
|
||||
Some(&log),
|
||||
))
|
||||
},
|
||||
&log,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(*calls.borrow(), vec!["check", "install"]);
|
||||
assert_eq!(error.stage, FailureStage::Install);
|
||||
assert_eq!(error.message, "fixture install error");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_update_at_a_time_and_errors_release_the_guard() {
|
||||
let flag = AtomicBool::new(false);
|
||||
let first = UpdateLease::acquire(&flag).unwrap();
|
||||
assert!(UpdateLease::acquire(&flag).is_err());
|
||||
drop(first);
|
||||
assert!(UpdateLease::acquire(&flag).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_download_has_its_own_bounded_timeout() {
|
||||
assert_eq!(timeout_ms(None), 600_000);
|
||||
assert_eq!(timeout_ms(Some(15_000)), 30_000);
|
||||
assert_eq!(timeout_ms(Some(u64::MAX)), 600_000);
|
||||
assert_eq!(timeout_ms(Some(120_000)), 120_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handoff_never_launches_on_failed_prepare_and_resumes_on_launch_failure() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let log = UpdateLog::create(temp.path(), "0.4.0").unwrap();
|
||||
let calls = RefCell::new(vec![]);
|
||||
let fail = prepared_install(
|
||||
|| {
|
||||
calls.borrow_mut().push("prepare");
|
||||
Err(())
|
||||
},
|
||||
|| {
|
||||
calls.borrow_mut().push("launch");
|
||||
Ok(())
|
||||
},
|
||||
|| {
|
||||
calls.borrow_mut().push("resume");
|
||||
Ok(())
|
||||
},
|
||||
&log,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(fail.stage, FailureStage::Prepare);
|
||||
assert_eq!(*calls.borrow(), vec!["prepare", "resume"]);
|
||||
calls.borrow_mut().clear();
|
||||
let fail = prepared_install(
|
||||
|| {
|
||||
calls.borrow_mut().push("prepare");
|
||||
Ok(())
|
||||
},
|
||||
|| {
|
||||
calls.borrow_mut().push("launch");
|
||||
Err::<(), _>(())
|
||||
},
|
||||
|| {
|
||||
calls.borrow_mut().push("resume");
|
||||
Err(())
|
||||
},
|
||||
&log,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(fail.stage, FailureStage::Install);
|
||||
assert_eq!(*calls.borrow(), vec!["prepare", "launch", "resume"]);
|
||||
assert!(fail.message.contains("检查路由设置"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn successful_handoff_does_not_resume_routing() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let log = UpdateLog::create(temp.path(), "0.4.0").unwrap();
|
||||
assert_eq!(
|
||||
prepared_install(|| Ok(()), || Ok(42), || panic!("must not resume"), &log).unwrap(),
|
||||
42
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn logs_are_unique_and_reject_untrusted_version_text() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let first = UpdateLog::create(temp.path(), "0.4.0").unwrap();
|
||||
let second = UpdateLog::create(temp.path(), "0.4.0").unwrap();
|
||||
assert_ne!(first.path, second.path);
|
||||
assert!(UpdateLog::create(temp.path(), "0.4.0\nsecret").is_err());
|
||||
first.record("signature_verified");
|
||||
assert!(fs::read_to_string(&first.path)
|
||||
.unwrap()
|
||||
.contains("signature_verified"));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,488 @@
|
||||
//! Windows desktop discovery and activation. This module deliberately uses
|
||||
//! Windows' registered package/signature/process APIs, never executable names
|
||||
//! alone, before stopping a process or attaching to its debugging endpoint.
|
||||
#![cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||
|
||||
use base64::Engine;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct WindowsDesktopApp {
|
||||
pub(crate) path: PathBuf,
|
||||
pub(crate) executable: PathBuf,
|
||||
pub(crate) bundle_id: String,
|
||||
pub(crate) name: String,
|
||||
pub(crate) version: String,
|
||||
}
|
||||
|
||||
fn stamps() -> &'static Mutex<HashMap<u32, String>> {
|
||||
static STAMPS: OnceLock<Mutex<HashMap<u32, String>>> = OnceLock::new();
|
||||
STAMPS.get_or_init(|| Mutex::new(HashMap::new()))
|
||||
}
|
||||
|
||||
fn powershell(script: &str, data: Value, timeout: Duration) -> Result<Value, String> {
|
||||
let system_root = std::env::var_os("SystemRoot").ok_or("无法定位 Windows 系统目录")?;
|
||||
let executable =
|
||||
PathBuf::from(system_root).join("System32/WindowsPowerShell/v1.0/powershell.exe");
|
||||
let encoded = base64::engine::general_purpose::STANDARD
|
||||
.encode(serde_json::to_vec(&data).map_err(|_| "无法编码 Windows 客户端操作参数")?);
|
||||
// All variable input is JSON data. Paths and config values are never
|
||||
// interpolated as PowerShell source or passed through a command shell.
|
||||
let source = format!(
|
||||
"$ErrorActionPreference='Stop'; $ProgressPreference='SilentlyContinue'; \
|
||||
[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false); \
|
||||
$data=([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('{encoded}')) | ConvertFrom-Json);\n\
|
||||
{COMMON}\n{script}"
|
||||
);
|
||||
let output = crate::platform::desktop_command_output(
|
||||
&executable,
|
||||
&[
|
||||
"-NoLogo",
|
||||
"-NoProfile",
|
||||
"-NonInteractive",
|
||||
"-Command",
|
||||
&source,
|
||||
],
|
||||
timeout,
|
||||
)?;
|
||||
if !output.status.success() {
|
||||
let details = String::from_utf8_lossy(&output.stderr)
|
||||
.chars()
|
||||
.take(1800)
|
||||
.collect::<String>();
|
||||
return Err(format!("Windows Codex 操作未完成:{}", details.trim()));
|
||||
}
|
||||
serde_json::from_slice(&output.stdout).map_err(|_| "Windows 未返回有效的客户端操作结果".into())
|
||||
}
|
||||
|
||||
const COMMON: &str = r#"
|
||||
function FullPath($path) { [IO.Path]::GetFullPath([string]$path).TrimEnd('\') }
|
||||
function SamePath($left, $right) {
|
||||
[string]::Equals((FullPath $left), (FullPath $right), [StringComparison]::OrdinalIgnoreCase)
|
||||
}
|
||||
function ProcessStamp($process) {
|
||||
if ($null -eq $process.CreationDate) { throw 'Cannot verify the process creation time.' }
|
||||
$process.CreationDate.ToUniversalTime().Ticks.ToString([Globalization.CultureInfo]::InvariantCulture)
|
||||
}
|
||||
function AppProcesses($exe) {
|
||||
$processes=@(Get-CimInstance Win32_Process -Filter "Name='Codex.exe' OR Name='ChatGPT.exe'")
|
||||
if (@($processes | Where-Object { -not $_.ExecutablePath }).Count -gt 0) {
|
||||
throw 'A Codex/ChatGPT process path is inaccessible. Use matching non-elevated permissions before restarting.'
|
||||
}
|
||||
@($processes | Where-Object { SamePath $_.ExecutablePath $exe })
|
||||
}
|
||||
function MainProcesses($exe) {
|
||||
@(AppProcesses $exe | Where-Object {
|
||||
if ($null -eq $_.CommandLine) { throw 'Cannot verify the desktop process command line.' }
|
||||
$_.CommandLine -notmatch '(?i)(?:^|\s)--type(?:=|\s)' -and
|
||||
$_.CommandLine -notmatch '(?i)(?:^|\s)--crashpad-handler(?:\s|$)'
|
||||
})
|
||||
}
|
||||
function BoundProcess($entry, $exe) {
|
||||
$process=Get-Process -Id $entry.ProcessId -ErrorAction SilentlyContinue
|
||||
if ($null -eq $process) { return $null }
|
||||
try {
|
||||
# Holding this handle pins the process object/PID through the subsequent
|
||||
# identity checks and CloseMainWindow/Kill call.
|
||||
$null=$process.Handle
|
||||
$created=$process.StartTime.ToUniversalTime().Ticks
|
||||
$expected=[long](ProcessStamp $entry)
|
||||
if (-not (SamePath $process.MainModule.FileName $exe) -or
|
||||
[Math]::Abs($created-$expected) -ge 10) { $process.Dispose(); return $null }
|
||||
# CIM timestamps have microsecond precision, while StartTime has 100ns.
|
||||
return $process
|
||||
} catch { $process.Dispose(); return $null }
|
||||
}
|
||||
function IsDesktopExe($exe) {
|
||||
$leaf=[IO.Path]::GetFileName([string]$exe)
|
||||
($leaf -ieq 'Codex.exe' -or $leaf -ieq 'ChatGPT.exe') -and
|
||||
(Test-Path -LiteralPath $exe -PathType Leaf) -and
|
||||
(Test-Path -LiteralPath (Join-Path ([IO.Path]::GetDirectoryName($exe)) 'resources\app.asar') -PathType Leaf)
|
||||
}
|
||||
function TrustedStandalone($exe) {
|
||||
if (-not (IsDesktopExe $exe)) { return $false }
|
||||
$signature=Get-AuthenticodeSignature -LiteralPath $exe
|
||||
if ($signature.Status -ne 'Valid' -or $null -eq $signature.SignerCertificate) { return $false }
|
||||
$publisher=$signature.SignerCertificate.GetNameInfo([Security.Cryptography.X509Certificates.X509NameType]::SimpleName,$false)
|
||||
@('OpenAI OpCo, LLC','OpenAI, L.L.C.') -ccontains $publisher
|
||||
}
|
||||
function TrustedPackage($package) {
|
||||
$null -ne $package -and
|
||||
@('OpenAI.Codex','OpenAI.CodexBeta','OpenAI.ChatGPT-Desktop') -ccontains [string]$package.Name -and
|
||||
[string]$package.PublisherId -ceq '2p2nqsd0c76g0' -and
|
||||
[string]$package.PackageFamilyName -ceq ($package.Name+'_2p2nqsd0c76g0') -and
|
||||
[string]$package.Status -eq 'Ok' -and [string]$package.SignatureKind -eq 'Store' -and
|
||||
-not $package.IsDevelopmentMode
|
||||
}
|
||||
function PackageApp($package) {
|
||||
$root=FullPath $package.InstallLocation
|
||||
$manifest=Get-AppxPackageManifest -Package $package.PackageFullName
|
||||
foreach ($entry in @($manifest.Package.Applications.Application)) {
|
||||
if (-not $entry.Executable -or -not $entry.Id) { continue }
|
||||
$exe=FullPath (Join-Path $root ([string]$entry.Executable))
|
||||
if (-not $exe.StartsWith($root+'\',[StringComparison]::OrdinalIgnoreCase)) { continue }
|
||||
if (-not (IsDesktopExe $exe)) { continue }
|
||||
return [pscustomobject]@{path=$root;executable=$exe;bundleId=($package.PackageFamilyName+'!'+$entry.Id);
|
||||
name=$(if($package.Name -eq 'OpenAI.ChatGPT-Desktop'){'ChatGPT'}else{'Codex'});version=[string]$package.Version}
|
||||
}
|
||||
return $null
|
||||
}
|
||||
function ValidateApp($app) {
|
||||
if (-not (IsDesktopExe $app.executable)) { throw 'The selected path is not the official Electron desktop application.' }
|
||||
if ([string]$app.bundleId -eq 'OpenAI.Codex.Standalone') {
|
||||
if (-not (SamePath ([IO.Path]::GetDirectoryName($app.executable)) $app.path) -or
|
||||
-not (TrustedStandalone $app.executable)) { throw 'The desktop executable has no valid OpenAI publisher signature.' }
|
||||
return
|
||||
}
|
||||
$principal=[Security.Principal.WindowsPrincipal]::new([Security.Principal.WindowsIdentity]::GetCurrent())
|
||||
if ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
|
||||
throw 'Microsoft Store activation requires Codex-X to run without administrator elevation. No client was stopped.'
|
||||
}
|
||||
$family=([string]$app.bundleId).Split('!')[0]
|
||||
$package=@(Get-AppxPackage | Where-Object { [string]$_.PackageFamilyName -ceq $family }) | Select-Object -First 1
|
||||
if (-not (TrustedPackage $package)) { throw 'The official signed Microsoft Store package is no longer registered.' }
|
||||
$registered=PackageApp $package
|
||||
if ($null -eq $registered -or $registered.bundleId -cne $app.bundleId -or
|
||||
-not (SamePath $registered.path $app.path) -or
|
||||
-not (SamePath $registered.executable $app.executable)) { throw 'The registered Store application identity has changed.' }
|
||||
}
|
||||
function Emit($result) { ConvertTo-Json -InputObject $result -Depth 6 -Compress }
|
||||
"#;
|
||||
|
||||
pub(crate) fn detect() -> Result<WindowsDesktopApp, String> {
|
||||
type Cached = (Instant, Result<WindowsDesktopApp, String>);
|
||||
static CACHE: OnceLock<Mutex<Option<Cached>>> = OnceLock::new();
|
||||
let mut cache = CACHE
|
||||
.get_or_init(|| Mutex::new(None))
|
||||
.lock()
|
||||
.map_err(|_| "Windows 客户端检测状态忙")?;
|
||||
if let Some((recorded, value)) = cache.as_ref() {
|
||||
let ttl = if value.is_ok() { 30 } else { 10 };
|
||||
if recorded.elapsed() < Duration::from_secs(ttl) {
|
||||
return value.clone();
|
||||
}
|
||||
}
|
||||
let value = detect_fresh();
|
||||
*cache = Some((Instant::now(), value.clone()));
|
||||
value
|
||||
}
|
||||
|
||||
pub(crate) fn detect_fresh() -> Result<WindowsDesktopApp, String> {
|
||||
let result = powershell(
|
||||
r#"
|
||||
$candidates=New-Object 'System.Collections.Generic.List[object]'
|
||||
foreach ($package in @(Get-AppxPackage | Sort-Object -Property Version -Descending)) {
|
||||
if (-not (TrustedPackage $package)) { continue }
|
||||
try { $app=PackageApp $package } catch { continue }
|
||||
if ($null -ne $app) { $candidates.Add($app) }
|
||||
}
|
||||
if ($env:LOCALAPPDATA) {
|
||||
$roots=@('OpenAI\Codex\bin','OpenAI\Codex','Programs\OpenAI\Codex','Programs\Codex')
|
||||
$seen=@{}
|
||||
foreach ($relative in $roots) {
|
||||
$root=Join-Path $env:LOCALAPPDATA $relative
|
||||
$directories=@($root,(Join-Path $root 'app'))
|
||||
if (Test-Path -LiteralPath $root -PathType Container) {
|
||||
foreach ($child in @(Get-ChildItem -LiteralPath $root -Directory -ErrorAction SilentlyContinue | Select-Object -First 32)) {
|
||||
$directories+=@($child.FullName,(Join-Path $child.FullName 'app'))
|
||||
}
|
||||
}
|
||||
foreach ($directory in $directories) {
|
||||
foreach ($leaf in @('Codex.exe','ChatGPT.exe')) {
|
||||
$exe=Join-Path $directory $leaf
|
||||
$key=$exe.ToLowerInvariant()
|
||||
if ($seen.ContainsKey($key)) { continue }; $seen[$key]=$true
|
||||
if (-not (TrustedStandalone $exe)) { continue }
|
||||
$version=(Get-Item -LiteralPath $exe).VersionInfo.ProductVersion
|
||||
$candidates.Add([pscustomobject]@{path=(FullPath $directory);executable=(FullPath $exe);
|
||||
bundleId='OpenAI.Codex.Standalone';name='Codex';version=[string]$version})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
$running=@()
|
||||
foreach ($app in $candidates) {
|
||||
$main=@(MainProcesses $app.executable)
|
||||
if ($main.Count -gt 1) { throw 'Multiple desktop instances are running. Keep one instance before restarting.' }
|
||||
if ($main.Count -eq 1) { $running+=,$app }
|
||||
}
|
||||
if ($running.Count -gt 1) { throw 'Multiple official desktop installations are running. Keep one before restarting.' }
|
||||
if ($running.Count -eq 1) { Emit $running[0]; exit }
|
||||
if ($candidates.Count -eq 0) { throw 'No verified OpenAI Codex Store package or signed standalone installation was found.' }
|
||||
Emit $candidates[0]
|
||||
"#,
|
||||
Value::Null,
|
||||
Duration::from_secs(25),
|
||||
)?;
|
||||
serde_json::from_value(result).map_err(|_| "Windows 客户端安装信息无效".into())
|
||||
}
|
||||
|
||||
pub(crate) fn validate(app: &WindowsDesktopApp) -> Result<(), String> {
|
||||
powershell(
|
||||
"ValidateApp $data.app; Emit $true",
|
||||
json!({"app":app}),
|
||||
Duration::from_secs(15),
|
||||
)
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
pub(crate) fn validate_launch(app: &WindowsDesktopApp, home: &Path) -> Result<(), String> {
|
||||
if app.bundle_id != "OpenAI.Codex.Standalone" {
|
||||
let default = dirs::home_dir()
|
||||
.ok_or("无法确认 Windows 默认 Codex 配置目录")?
|
||||
.join(".codex");
|
||||
let requested = crate::paths::normalized_path_scope(home);
|
||||
let expected = crate::paths::normalized_path_scope(&default);
|
||||
if requested != expected {
|
||||
return Err("Windows Store 版无法通过安全激活传入自定义 CODEX_HOME;请使用默认 .codex 目录或官方独立安装版。客户端尚未退出。".into());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn pids(app: &WindowsDesktopApp) -> Result<Vec<u32>, String> {
|
||||
let value = powershell(
|
||||
"Emit @(AppProcesses $data.app.executable | ForEach-Object { [uint32]$_.ProcessId })",
|
||||
json!({"app":app}),
|
||||
Duration::from_secs(8),
|
||||
)?;
|
||||
serde_json::from_value(value).map_err(|_| "无法确认 Windows 客户端进程".into())
|
||||
}
|
||||
|
||||
pub(crate) fn quit(app: &WindowsDesktopApp) -> Result<(), String> {
|
||||
powershell(
|
||||
r#"
|
||||
ValidateApp $data.app
|
||||
$main=@(MainProcesses $data.app.executable)
|
||||
if ($main.Count -gt 1) { throw 'Multiple desktop instances are running; none was stopped.' }
|
||||
foreach ($entry in $main) {
|
||||
$process=BoundProcess $entry $data.app.executable
|
||||
if ($null -ne $process) {
|
||||
try { $null=$process.CloseMainWindow() } finally { $process.Dispose() }
|
||||
}
|
||||
}
|
||||
$grace=[DateTime]::UtcNow.AddSeconds(2)
|
||||
while ([DateTime]::UtcNow -lt $grace -and @(AppProcesses $data.app.executable).Count -gt 0) { Start-Sleep -Milliseconds 100 }
|
||||
# The user explicitly requested a restart. If a tray/renderer remains, stop
|
||||
# only processes whose live executable path still matches this verified app.
|
||||
foreach ($entry in @(AppProcesses $data.app.executable)) {
|
||||
$process=BoundProcess $entry $data.app.executable
|
||||
if ($null -ne $process) {
|
||||
try { $process.Kill() } catch { } finally { $process.Dispose() }
|
||||
}
|
||||
}
|
||||
$deadline=[DateTime]::UtcNow.AddSeconds(8); $emptySince=$null
|
||||
do {
|
||||
if (@(AppProcesses $data.app.executable).Count -eq 0) {
|
||||
if ($null -eq $emptySince) { $emptySince=[DateTime]::UtcNow }
|
||||
if (([DateTime]::UtcNow-$emptySince).TotalMilliseconds -ge 500) { Emit $true; exit }
|
||||
} else { $emptySince=$null }
|
||||
Start-Sleep -Milliseconds 100
|
||||
} while ([DateTime]::UtcNow -lt $deadline)
|
||||
throw 'The selected desktop processes did not stop; relaunch was cancelled.'
|
||||
"#,
|
||||
json!({"app":app}),
|
||||
Duration::from_secs(20),
|
||||
)
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
pub(crate) fn launch(
|
||||
app: &WindowsDesktopApp,
|
||||
home: Option<&Path>,
|
||||
port: Option<u16>,
|
||||
) -> Result<u32, String> {
|
||||
if let Some(home) = home {
|
||||
validate_launch(app, home)?;
|
||||
}
|
||||
if app.bundle_id == "OpenAI.Codex.Standalone" {
|
||||
return launch_standalone(app, home, port);
|
||||
}
|
||||
let result = powershell(
|
||||
r#"
|
||||
ValidateApp $data.app
|
||||
if (@(AppProcesses $data.app.executable).Count -gt 0) { throw 'The desktop application is still stopping; no duplicate instance was launched.' }
|
||||
$arguments=''
|
||||
if ($null -ne $data.port) { $arguments='--remote-debugging-port='+[string]$data.port+' --remote-debugging-address=127.0.0.1' }
|
||||
Add-Type -TypeDefinition @'
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
[ComImport, Guid("2e941141-7f97-4756-ba1d-9decde894a3d"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
interface ICodexActivationManager {
|
||||
[PreserveSig] int ActivateApplication([MarshalAs(UnmanagedType.LPWStr)] string appId,
|
||||
[MarshalAs(UnmanagedType.LPWStr)] string arguments, uint options, out uint processId);
|
||||
}
|
||||
public static class CodexPackageActivation {
|
||||
public static uint Start(string appId, string arguments) {
|
||||
var manager=(ICodexActivationManager)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("45ba127d-10a8-46ea-8ab7-56ea9078943c")));
|
||||
try { uint processId; int result=manager.ActivateApplication(appId, arguments, 0, out processId);
|
||||
Marshal.ThrowExceptionForHR(result); return processId; }
|
||||
finally { Marshal.FinalReleaseComObject(manager); }
|
||||
}
|
||||
}
|
||||
'@ | Out-Null
|
||||
$started=[CodexPackageActivation]::Start([string]$data.app.bundleId,$arguments)
|
||||
if ($started -eq 0) { throw 'Windows did not return an activated process id.' }
|
||||
$created=''; $deadline=[DateTime]::UtcNow.AddSeconds(5)
|
||||
do {
|
||||
$process=Get-CimInstance Win32_Process -Filter ('ProcessId='+$started)
|
||||
if ($null -ne $process -and $process.ExecutablePath) {
|
||||
if (-not (SamePath $process.ExecutablePath $data.app.executable)) { throw 'Windows activated a different executable; no debugging connection was made.' }
|
||||
$created=ProcessStamp $process; break
|
||||
}
|
||||
Start-Sleep -Milliseconds 100
|
||||
} while ([DateTime]::UtcNow -lt $deadline)
|
||||
if (-not $created) { throw 'Windows activation returned but the official desktop process did not start.' }
|
||||
Emit @{pid=$started;created=$created}
|
||||
"#,
|
||||
json!({"app":app,"home":home,"port":port}),
|
||||
Duration::from_secs(20),
|
||||
)?;
|
||||
remember_started(result)
|
||||
}
|
||||
|
||||
fn remember_started(result: Value) -> Result<u32, String> {
|
||||
let pid = result["pid"]
|
||||
.as_u64()
|
||||
.and_then(|value| u32::try_from(value).ok())
|
||||
.filter(|pid| *pid != 0)
|
||||
.ok_or("Windows 未确认已启动的客户端进程")?;
|
||||
let created = result["created"]
|
||||
.as_str()
|
||||
.filter(|value| !value.is_empty())
|
||||
.ok_or("Windows 未确认客户端进程身份")?;
|
||||
let mut tracked = stamps().lock().map_err(|_| "Windows 进程状态忙")?;
|
||||
if tracked.len() >= 16 {
|
||||
tracked.clear();
|
||||
}
|
||||
tracked.insert(pid, created.to_owned());
|
||||
Ok(pid)
|
||||
}
|
||||
|
||||
fn launch_standalone(
|
||||
app: &WindowsDesktopApp,
|
||||
home: Option<&Path>,
|
||||
port: Option<u16>,
|
||||
) -> Result<u32, String> {
|
||||
powershell(
|
||||
"ValidateApp $data.app; if (@(AppProcesses $data.app.executable).Count -gt 0) { throw 'The desktop is still stopping; no duplicate was launched.' }; Emit $true",
|
||||
json!({"app":app}),
|
||||
Duration::from_secs(15),
|
||||
)?;
|
||||
let arguments = port
|
||||
.map(|port| {
|
||||
vec![
|
||||
format!("--remote-debugging-port={port}"),
|
||||
"--remote-debugging-address=127.0.0.1".to_owned(),
|
||||
]
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let args: Vec<_> = arguments.iter().map(String::as_str).collect();
|
||||
let mut command = crate::platform::program_command(&app.executable, &args);
|
||||
command
|
||||
.current_dir(&app.path)
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null());
|
||||
if let Some(home) = home {
|
||||
command.env("CODEX_HOME", home);
|
||||
}
|
||||
let mut child = command
|
||||
.spawn()
|
||||
.map_err(|_| "无法启动已验证的 Windows Codex 客户端")?;
|
||||
let pid = child.id();
|
||||
let result = powershell(
|
||||
r#"
|
||||
$deadline=[DateTime]::UtcNow.AddSeconds(5)
|
||||
do {
|
||||
$process=Get-CimInstance Win32_Process -Filter ('ProcessId='+[uint32]$data.pid)
|
||||
if ($null -ne $process -and $process.ExecutablePath) {
|
||||
if (-not (SamePath $process.ExecutablePath $data.app.executable)) { throw 'The newly started process has an unexpected executable.' }
|
||||
Emit @{pid=[uint32]$data.pid;created=(ProcessStamp $process)}; exit
|
||||
}
|
||||
Start-Sleep -Milliseconds 100
|
||||
} while ([DateTime]::UtcNow -lt $deadline)
|
||||
throw 'The signed desktop executable did not remain running.'
|
||||
"#,
|
||||
json!({"app":app,"pid":pid}),
|
||||
Duration::from_secs(10),
|
||||
).and_then(remember_started);
|
||||
if result.is_err() {
|
||||
// Child owns the original Windows process handle, so cleanup cannot
|
||||
// terminate an unrelated process after a recycled PID.
|
||||
let _ = child.kill();
|
||||
let _ = child.try_wait();
|
||||
}
|
||||
// Windows has no zombie-process wait requirement. Dropping Child releases
|
||||
// our process/thread handles while the GUI keeps its own lifetime.
|
||||
drop(child);
|
||||
result
|
||||
}
|
||||
|
||||
pub(crate) fn verify_process(app: &WindowsDesktopApp, pid: u32) -> Result<(), String> {
|
||||
let created = stamps()
|
||||
.lock()
|
||||
.map_err(|_| "Windows 进程状态忙")?
|
||||
.get(&pid)
|
||||
.cloned()
|
||||
.ok_or("该客户端进程不属于本次受控启动")?;
|
||||
powershell(
|
||||
r#"
|
||||
$process=Get-CimInstance Win32_Process -Filter ('ProcessId='+[uint32]$data.pid)
|
||||
if ($null -eq $process -or -not $process.ExecutablePath -or
|
||||
-not (SamePath $process.ExecutablePath $data.app.executable) -or
|
||||
(ProcessStamp $process) -cne [string]$data.created) { throw 'The activated desktop process identity has changed.' }
|
||||
Emit $true
|
||||
"#,
|
||||
json!({"app":app,"pid":pid,"created":created}),
|
||||
Duration::from_secs(8),
|
||||
)
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
pub(crate) fn verify_listener(app: &WindowsDesktopApp, pid: u32, port: u16) -> Result<(), String> {
|
||||
let created = stamps()
|
||||
.lock()
|
||||
.map_err(|_| "Windows 进程状态忙")?
|
||||
.get(&pid)
|
||||
.cloned()
|
||||
.ok_or("该客户端进程不属于本次受控启动")?;
|
||||
powershell(
|
||||
r#"
|
||||
$process=Get-CimInstance Win32_Process -Filter ('ProcessId='+[uint32]$data.pid)
|
||||
if ($null -eq $process -or -not $process.ExecutablePath -or
|
||||
-not (SamePath $process.ExecutablePath $data.app.executable) -or
|
||||
(ProcessStamp $process) -cne [string]$data.created) { throw 'The activated desktop process identity has changed.' }
|
||||
$listeners=@(Get-NetTCPConnection -State Listen -LocalPort ([uint16]$data.port) -ErrorAction SilentlyContinue)
|
||||
if ($listeners.Count -eq 0) { throw 'The official desktop has not opened its debugging port.' }
|
||||
foreach ($listener in $listeners) {
|
||||
if ($listener.LocalAddress -cne '127.0.0.1' -or [uint32]$listener.OwningProcess -ne [uint32]$data.pid) {
|
||||
throw 'The debugging port is not exclusively owned by the activated process on 127.0.0.1.'
|
||||
}
|
||||
}
|
||||
$after=Get-CimInstance Win32_Process -Filter ('ProcessId='+[uint32]$data.pid)
|
||||
if ($null -eq $after -or -not $after.ExecutablePath -or
|
||||
-not (SamePath $after.ExecutablePath $data.app.executable) -or
|
||||
(ProcessStamp $after) -cne [string]$data.created) { throw 'The desktop process changed while its port was being verified.' }
|
||||
Emit $true
|
||||
"#,
|
||||
json!({"app":app,"pid":pid,"port":port,"created":created}),
|
||||
Duration::from_secs(8),
|
||||
)
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
pub(crate) fn restart() -> Result<(String, bool), String> {
|
||||
let app = detect_fresh()?;
|
||||
validate(&app)?;
|
||||
let was_running = !pids(&app)?.is_empty();
|
||||
quit(&app)?;
|
||||
launch(&app, None, None)?;
|
||||
Ok((app.name, was_running))
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,280 @@
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::io::Read;
|
||||
use std::net::{Ipv4Addr, SocketAddr, TcpStream};
|
||||
use std::time::{Duration, Instant};
|
||||
use tungstenite::{client, Message, WebSocket};
|
||||
|
||||
const MAX_RESPONSE: usize = 512 * 1024;
|
||||
|
||||
#[derive(Clone, Deserialize)]
|
||||
pub(super) struct Target {
|
||||
pub(super) id: String,
|
||||
#[serde(rename = "type")]
|
||||
kind: String,
|
||||
url: String,
|
||||
#[serde(rename = "webSocketDebuggerUrl")]
|
||||
socket: Option<String>,
|
||||
}
|
||||
|
||||
pub(super) fn app_origin(url: &str) -> bool {
|
||||
reqwest::Url::parse(url).is_ok_and(|url| {
|
||||
url.scheme() == "app"
|
||||
&& url.host_str() == Some("-")
|
||||
&& url.port().is_none()
|
||||
&& url.username().is_empty()
|
||||
&& url.password().is_none()
|
||||
&& matches!(url.path(), "/" | "/index.html")
|
||||
})
|
||||
}
|
||||
|
||||
fn socket_url(value: &str, port: u16) -> Result<reqwest::Url, String> {
|
||||
let url = reqwest::Url::parse(value).map_err(|_| "调试目标地址无效")?;
|
||||
if url.scheme() != "ws"
|
||||
|| url.host_str() != Some("127.0.0.1")
|
||||
|| url.port() != Some(port)
|
||||
|| !url.username().is_empty()
|
||||
|| url.password().is_some()
|
||||
|| url.query().is_some()
|
||||
|| url.fragment().is_some()
|
||||
|| !url.path().starts_with("/devtools/page/")
|
||||
|| url.path().trim_start_matches("/devtools/page/").is_empty()
|
||||
{
|
||||
return Err("调试目标超出指定本机端口,未执行语言脚本。".into());
|
||||
}
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
pub(super) fn targets(port: u16) -> Result<Vec<Target>, String> {
|
||||
crate::remote::ensure_crypto_provider();
|
||||
let client = reqwest::blocking::Client::builder()
|
||||
.no_proxy()
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.timeout(Duration::from_secs(2))
|
||||
.build()
|
||||
.map_err(|_| "无法初始化本机语言兼容连接")?;
|
||||
let response = client
|
||||
.get(format!("http://127.0.0.1:{port}/json/list"))
|
||||
.send()
|
||||
.map_err(|_| "客户端未开放本机调试通道;此版本可能不支持兼容模式。")?;
|
||||
if !response.status().is_success() {
|
||||
return Err("客户端调试通道尚未就绪".into());
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
response
|
||||
.take((MAX_RESPONSE + 1) as u64)
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|_| "无法读取调试目标")?;
|
||||
if bytes.len() > MAX_RESPONSE {
|
||||
return Err("客户端返回的调试目标超过安全限制".into());
|
||||
}
|
||||
let targets: Vec<Target> =
|
||||
serde_json::from_slice(&bytes).map_err(|_| "客户端未返回有效的调试目标")?;
|
||||
if targets.len() > 128 {
|
||||
return Err("客户端调试目标过多,未继续连接".into());
|
||||
}
|
||||
Ok(targets
|
||||
.into_iter()
|
||||
.filter(|target| {
|
||||
target.kind == "page" && app_origin(&target.url) && target.socket.is_some()
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub(super) struct Session {
|
||||
socket: WebSocket<TcpStream>,
|
||||
next_id: u64,
|
||||
script: String,
|
||||
}
|
||||
impl Session {
|
||||
pub(super) fn connect(target: &Target, port: u16) -> Result<Self, String> {
|
||||
if target.kind != "page" || !app_origin(&target.url) {
|
||||
return Err("不是官方客户端的本地界面目标".into());
|
||||
}
|
||||
let url = socket_url(target.socket.as_deref().ok_or("目标没有调试连接")?, port)?;
|
||||
let stream = TcpStream::connect_timeout(
|
||||
&SocketAddr::from((Ipv4Addr::LOCALHOST, port)),
|
||||
Duration::from_secs(2),
|
||||
)
|
||||
.map_err(|_| "本机调试连接未建立")?;
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(2)))
|
||||
.map_err(|_| "无法设置调试读取超时")?;
|
||||
stream
|
||||
.set_write_timeout(Some(Duration::from_secs(2)))
|
||||
.map_err(|_| "无法设置调试写入超时")?;
|
||||
let (mut socket, _) = client(url.as_str(), stream)
|
||||
.map_err(|_| "客户端拒绝了安全调试连接;未降低客户端安全设置。")?;
|
||||
socket.set_config(|config| {
|
||||
config.max_message_size = Some(MAX_RESPONSE);
|
||||
config.max_frame_size = Some(MAX_RESPONSE);
|
||||
});
|
||||
Ok(Self {
|
||||
socket,
|
||||
next_id: 0,
|
||||
script: String::new(),
|
||||
})
|
||||
}
|
||||
pub(super) fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
|
||||
self.next_id += 1;
|
||||
let id = self.next_id;
|
||||
self.socket
|
||||
.send(Message::Text(
|
||||
json!({"id":id,"method":method,"params":params})
|
||||
.to_string()
|
||||
.into(),
|
||||
))
|
||||
.map_err(|_| "语言兼容命令发送失败")?;
|
||||
let deadline = Instant::now() + Duration::from_secs(4);
|
||||
while Instant::now() < deadline {
|
||||
match self.socket.read().map_err(|_| "语言兼容连接中断或超时")? {
|
||||
Message::Text(text) => {
|
||||
if text.len() > MAX_RESPONSE {
|
||||
return Err("调试返回内容超过限制".into());
|
||||
}
|
||||
let event: Value =
|
||||
serde_json::from_str(&text).map_err(|_| "调试返回格式无效")?;
|
||||
if event.get("id").and_then(Value::as_u64) != Some(id) {
|
||||
continue;
|
||||
}
|
||||
if event.get("error").is_some() {
|
||||
return Err("当前客户端不支持所需的界面兼容命令".into());
|
||||
}
|
||||
return Ok(event.get("result").cloned().unwrap_or(Value::Null));
|
||||
}
|
||||
Message::Ping(bytes) => {
|
||||
self.socket
|
||||
.send(Message::Pong(bytes))
|
||||
.map_err(|_| "调试连接中断")?;
|
||||
}
|
||||
Message::Close(_) => return Err("客户端关闭了语言兼容连接".into()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Err("等待界面兼容结果超时".into())
|
||||
}
|
||||
pub(super) fn install(&mut self, source: &str) -> Result<(), String> {
|
||||
let origin=self.evaluate("(()=>{try{const u=new URL(location.href);return {allowed:window===window.top&&u.protocol==='app:'&&u.host==='-'&&!u.username&&!u.password&&['/','/index.html'].includes(u.pathname)};}catch{return {allowed:false};}})()")?;
|
||||
if origin.get("allowed").and_then(Value::as_bool) != Some(true) {
|
||||
return Err("目标页面来源在连接后已改变,未注册脚本或重载页面。".into());
|
||||
}
|
||||
self.call("Page.enable", json!({}))?;
|
||||
let result = self.call(
|
||||
"Page.addScriptToEvaluateOnNewDocument",
|
||||
json!({"source":source}),
|
||||
)?;
|
||||
self.script = result
|
||||
.get("identifier")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or("客户端未确认兼容脚本注册")?
|
||||
.to_owned();
|
||||
self.call("Page.reload", json!({"ignoreCache":false}))?;
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn evaluate(&mut self, source: &str) -> Result<Value, String> {
|
||||
let result=self.call("Runtime.evaluate",json!({"expression":source,"returnByValue":true,"awaitPromise":true,"userGesture":false}))?;
|
||||
if result.get("exceptionDetails").is_some() {
|
||||
return Err("客户端界面不支持此语言兼容模式,未报告应用成功。".into());
|
||||
}
|
||||
Ok(result
|
||||
.pointer("/result/value")
|
||||
.cloned()
|
||||
.unwrap_or(Value::Null))
|
||||
}
|
||||
}
|
||||
impl Drop for Session {
|
||||
fn drop(&mut self) {
|
||||
if !self.script.is_empty() {
|
||||
let script = self.script.clone();
|
||||
let _ = self.call(
|
||||
"Page.removeScriptToEvaluateOnNewDocument",
|
||||
json!({"identifier":script}),
|
||||
);
|
||||
}
|
||||
let _ = self.socket.close(None);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn rejects_browser_targets_remote_websockets_and_credentials() {
|
||||
assert!(app_origin("app://-/index.html?initialRoute=%2Fsettings"));
|
||||
for origin in [
|
||||
"https://chatgpt.com/",
|
||||
"http://127.0.0.1/index.html",
|
||||
"app://other/index.html",
|
||||
"app://user@-/index.html",
|
||||
"app://-/browser.html",
|
||||
] {
|
||||
assert!(!app_origin(origin));
|
||||
}
|
||||
assert!(socket_url("ws://127.0.0.1:4567/devtools/page/fixture", 4567).is_ok());
|
||||
for url in [
|
||||
"ws://localhost:4567/devtools/page/x",
|
||||
"ws://127.0.0.1:4568/devtools/page/x",
|
||||
"ws://127.0.0.1:4567/devtools/browser/x",
|
||||
"ws://user@127.0.0.1:4567/devtools/page/x",
|
||||
"wss://127.0.0.1:4567/devtools/page/x",
|
||||
] {
|
||||
assert!(socket_url(url, 4567).is_err());
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn simulated_cdp_registers_main_world_script_and_returns_only_fixture_status() {
|
||||
let listener = std::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let server = std::thread::spawn(move || {
|
||||
let (stream, _) = listener.accept().unwrap();
|
||||
let mut socket = tungstenite::accept(stream).unwrap();
|
||||
for (index, expected) in [
|
||||
"Runtime.evaluate",
|
||||
"Page.enable",
|
||||
"Page.addScriptToEvaluateOnNewDocument",
|
||||
"Page.reload",
|
||||
"Runtime.evaluate",
|
||||
"Page.removeScriptToEvaluateOnNewDocument",
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let Message::Text(text) = socket.read().unwrap() else {
|
||||
panic!("expected command")
|
||||
};
|
||||
let request: Value = serde_json::from_str(&text).unwrap();
|
||||
assert_eq!(request["method"], expected);
|
||||
let result = match expected {
|
||||
"Page.addScriptToEvaluateOnNewDocument" => {
|
||||
assert!(request["params"].get("worldName").is_none());
|
||||
json!({"identifier":"fixture-script"})
|
||||
}
|
||||
"Runtime.evaluate" if index == 0 => {
|
||||
json!({"result":{"value":{"allowed":true}}})
|
||||
}
|
||||
"Runtime.evaluate" => json!({"result":{"value":{"ready":true}}}),
|
||||
_ => json!({}),
|
||||
};
|
||||
socket
|
||||
.send(Message::Text(
|
||||
json!({"id":request["id"],"result":result})
|
||||
.to_string()
|
||||
.into(),
|
||||
))
|
||||
.unwrap();
|
||||
}
|
||||
});
|
||||
let target = Target {
|
||||
id: "fixture".into(),
|
||||
kind: "page".into(),
|
||||
url: "app://-/index.html".into(),
|
||||
socket: Some(format!("ws://127.0.0.1:{port}/devtools/page/fixture")),
|
||||
};
|
||||
{
|
||||
let mut session = Session::connect(&target, port).unwrap();
|
||||
session.install("/* fixture i18n script */").unwrap();
|
||||
assert_eq!(session.evaluate("fixtureStatus()").unwrap()["ready"], true);
|
||||
}
|
||||
server.join().unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
//! The locale compatibility launcher never modifies or re-signs the app bundle.
|
||||
use std::path::{Path, PathBuf};
|
||||
#[cfg(test)]
|
||||
static REAPED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||
|
||||
fn process_reaper() -> Result<&'static std::sync::mpsc::Sender<std::process::Child>, String> {
|
||||
static REAPER: std::sync::OnceLock<
|
||||
Result<std::sync::mpsc::Sender<std::process::Child>, String>,
|
||||
> = std::sync::OnceLock::new();
|
||||
REAPER
|
||||
.get_or_init(|| {
|
||||
let (sender, receiver) = std::sync::mpsc::channel::<std::process::Child>();
|
||||
std::thread::Builder::new()
|
||||
.name("codex-language-process-reaper".into())
|
||||
.spawn(move || {
|
||||
let mut children: Vec<std::process::Child> = Vec::new();
|
||||
loop {
|
||||
match receiver.recv_timeout(std::time::Duration::from_millis(200)) {
|
||||
Ok(child) => children.push(child),
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
|
||||
Err(_) => break,
|
||||
}
|
||||
children.retain_mut(|child| match child.try_wait() {
|
||||
Ok(None) => true,
|
||||
Ok(Some(_)) => {
|
||||
#[cfg(test)]
|
||||
REAPED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
false
|
||||
}
|
||||
Err(_) => false,
|
||||
});
|
||||
}
|
||||
})
|
||||
.map_err(|_| "无法初始化客户端进程回收线程,尚未退出客户端。".to_owned())?;
|
||||
Ok(sender)
|
||||
})
|
||||
.as_ref()
|
||||
.map_err(Clone::clone)
|
||||
}
|
||||
|
||||
pub(crate) fn prepare_launch() -> Result<(), String> {
|
||||
process_reaper().map(|_| ())
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct DesktopApp {
|
||||
pub(crate) path: PathBuf,
|
||||
pub(crate) executable: PathBuf,
|
||||
pub(crate) bundle_id: String,
|
||||
pub(crate) name: String,
|
||||
pub(crate) version: String,
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn windows_app(app: &DesktopApp) -> crate::platform::desktop_windows::WindowsDesktopApp {
|
||||
crate::platform::desktop_windows::WindowsDesktopApp {
|
||||
path: app.path.clone(),
|
||||
executable: app.executable.clone(),
|
||||
bundle_id: app.bundle_id.clone(),
|
||||
name: app.name.clone(),
|
||||
version: app.version.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn command(program: &str, args: &[&str]) -> Result<String, String> {
|
||||
let output = crate::platform::locale_platform_command(Path::new(program), args)?;
|
||||
Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
|
||||
}
|
||||
|
||||
pub(crate) fn detect() -> Result<DesktopApp, String> {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let app = crate::platform::locale_desktop_app()?;
|
||||
Ok(DesktopApp {
|
||||
path: app.0,
|
||||
executable: app.1,
|
||||
bundle_id: app.2,
|
||||
name: app.3,
|
||||
version: app.4,
|
||||
})
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let app = crate::platform::desktop_windows::detect()?;
|
||||
Ok(DesktopApp {
|
||||
path: app.path,
|
||||
executable: app.executable,
|
||||
bundle_id: app.bundle_id,
|
||||
name: app.name,
|
||||
version: app.version,
|
||||
})
|
||||
}
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
{
|
||||
Err("当前平台尚未实现可验证官方进程的界面语言启动器。".into())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn detect_for_operation() -> Result<DesktopApp, String> {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let app = crate::platform::desktop_windows::detect_fresh()?;
|
||||
Ok(DesktopApp {
|
||||
path: app.path,
|
||||
executable: app.executable,
|
||||
bundle_id: app.bundle_id,
|
||||
name: app.name,
|
||||
version: app.version,
|
||||
})
|
||||
}
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
{
|
||||
detect()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn validate(app: &DesktopApp) -> Result<(), String> {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
if !matches!(
|
||||
app.bundle_id.as_str(),
|
||||
"com.openai.codex" | "com.openai.codex.beta"
|
||||
) {
|
||||
return Err("不是受支持的官方 Codex 客户端".into());
|
||||
}
|
||||
let path = app.path.to_str().ok_or("客户端路径无效")?;
|
||||
crate::platform::locale_platform_command(
|
||||
Path::new("/usr/bin/codesign"),
|
||||
&["--verify", "--strict", path],
|
||||
)?;
|
||||
let details = crate::platform::locale_platform_command(
|
||||
Path::new("/usr/bin/codesign"),
|
||||
&["--display", "--verbose=4", path],
|
||||
)?;
|
||||
let info = String::from_utf8_lossy(&details.stderr);
|
||||
if !info.lines().any(|line| line == "TeamIdentifier=2DC432GLL2") {
|
||||
return Err("无法确认客户端为 OpenAI 官方签名,未重启或连接客户端。".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
crate::platform::desktop_windows::validate(&windows_app(app))
|
||||
}
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
{
|
||||
let _ = app;
|
||||
Err("当前平台不支持安全的语言兼容启动".into())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn validate_launch(app: &DesktopApp, home: &Path) -> Result<(), String> {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
crate::platform::desktop_windows::validate_launch(&windows_app(app), home)
|
||||
}
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
{
|
||||
let _ = (app, home);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn quit(app: &DesktopApp) -> Result<(), String> {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
crate::platform::locale_quit_desktop(&app.executable, &app.bundle_id)
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
crate::platform::desktop_windows::quit(&windows_app(app))
|
||||
}
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
{
|
||||
let _ = app;
|
||||
Err("当前平台不支持安全的语言兼容启动".into())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn ensure_stopped(app: &DesktopApp) -> Result<(), String> {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
if !crate::platform::locale_desktop_pids(&app.executable)?.is_empty() {
|
||||
return Err("客户端在保存语言前重新启动,已取消写入;请完全退出后重试。".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
if !crate::platform::desktop_windows::pids(&windows_app(app))?.is_empty() {
|
||||
return Err("客户端在保存语言前重新启动,已取消写入;请完全退出后重试。".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
{
|
||||
let _ = app;
|
||||
Err("当前平台不支持安全的语言兼容启动".into())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn quit_spawned(app: &DesktopApp, pid: u32) -> Result<(), String> {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
if !crate::platform::locale_desktop_pids(&app.executable)?.contains(&pid) {
|
||||
return Err("刚启动的官方进程身份已改变,未自动退出其它实例;请手动恢复。".into());
|
||||
}
|
||||
quit(app)
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
crate::platform::desktop_windows::verify_process(&windows_app(app), pid)?;
|
||||
quit(app)
|
||||
}
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
{
|
||||
let _ = (app, pid);
|
||||
Err("当前平台不支持安全的客户端恢复".into())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn launch(app: &DesktopApp, home: &Path, port: Option<u16>) -> Result<u32, String> {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
return crate::platform::desktop_windows::launch(&windows_app(app), Some(home), port);
|
||||
}
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
{
|
||||
let mut command = std::process::Command::new(&app.executable);
|
||||
command
|
||||
.env("CODEX_HOME", home)
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null());
|
||||
if let Some(port) = port {
|
||||
command.args([
|
||||
format!("--remote-debugging-port={port}"),
|
||||
"--remote-debugging-address=127.0.0.1".into(),
|
||||
]);
|
||||
}
|
||||
let reaper = process_reaper()?;
|
||||
let child = command
|
||||
.spawn()
|
||||
.map_err(|_| "无法启动官方客户端,请手动打开客户端后重试。")?;
|
||||
let pid = child.id();
|
||||
reaper
|
||||
.send(child)
|
||||
.map_err(|_| "客户端已启动,但进程监督不可用;请手动恢复并重试。")?;
|
||||
Ok(pid)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn verify_listener(app: &DesktopApp, pid: u32, port: u16) -> Result<(), String> {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let ids = crate::platform::locale_desktop_pids(&app.executable)?;
|
||||
if !ids.contains(&pid) {
|
||||
return Err("官方客户端进程已经改变,已停止语言兼容连接。".into());
|
||||
}
|
||||
let output = command(
|
||||
"/usr/sbin/lsof",
|
||||
&["-nP", &format!("-iTCP:{port}"), "-sTCP:LISTEN", "-Fpn"],
|
||||
)?;
|
||||
verify_listener_output(&output, pid, port)
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
crate::platform::desktop_windows::verify_listener(&windows_app(app), pid, port)
|
||||
}
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
{
|
||||
let _ = (app, pid, port);
|
||||
Err("当前平台无法验证调试端口归属".into())
|
||||
}
|
||||
}
|
||||
|
||||
fn verify_listener_output(output: &str, pid: u32, port: u16) -> Result<(), String> {
|
||||
let mut current = None;
|
||||
let mut verified = false;
|
||||
for line in output.lines() {
|
||||
if let Some(p) = line.strip_prefix('p') {
|
||||
current = p.parse::<u32>().ok();
|
||||
}
|
||||
if let Some(address) = line.strip_prefix('n') {
|
||||
if current != Some(pid) || address != format!("127.0.0.1:{port}") {
|
||||
return Err("调试端口不属于指定官方进程或未限制在本机,未执行任何注入。".into());
|
||||
}
|
||||
verified = true;
|
||||
}
|
||||
}
|
||||
if !verified {
|
||||
return Err("官方客户端尚未开放可验证的本机调试端口;此构建可能不支持运行时兼容。".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn listener_must_match_pid_and_ipv4_loopback() {
|
||||
assert!(verify_listener_output("p123\nn127.0.0.1:4567\n", 123, 4567).is_ok());
|
||||
for input in [
|
||||
"p456\nn127.0.0.1:4567\n",
|
||||
"p123\nn*:4567\n",
|
||||
"p123\nn192.168.1.2:4567\n",
|
||||
"p123\nn127.0.0.1:8888\n",
|
||||
"",
|
||||
] {
|
||||
assert!(verify_listener_output(input, 123, 4567).is_err());
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn spawned_fixture_children_are_waited_by_the_reaper() {
|
||||
let before = REAPED.load(std::sync::atomic::Ordering::Relaxed);
|
||||
let child = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.arg("--list")
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
process_reaper().unwrap().send(child).unwrap();
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
|
||||
while REAPED.load(std::sync::atomic::Ordering::Relaxed) <= before
|
||||
&& std::time::Instant::now() < deadline
|
||||
{
|
||||
std::thread::sleep(std::time::Duration::from_millis(25));
|
||||
}
|
||||
assert!(REAPED.load(std::sync::atomic::Ordering::Relaxed) > before);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
/* Independently implemented locale compatibility. No application files change. */
|
||||
(function (options) {
|
||||
"use strict";
|
||||
let page;
|
||||
try { page = new URL(location.href); } catch { return { installed: false, reason: "unsupported_origin" }; }
|
||||
if (page.protocol !== "app:" || page.hostname !== "-" || page.port || page.username || page.password ||
|
||||
!["/", "/index.html"].includes(page.pathname) || window !== window.top) {
|
||||
return { installed: false, reason: "unsupported_origin" };
|
||||
}
|
||||
if (!options || !["zh-CN", "en-US"].includes(options.locale) ||
|
||||
typeof options.owner !== "string" || !/^[a-f0-9]{64}$/.test(options.owner)) {
|
||||
return { installed: false, reason: "invalid_options" };
|
||||
}
|
||||
const marker = "__CODEXX_LOCALE_RUNTIME_V1__";
|
||||
if (window[marker]?.owner === options.owner) return window[marker].status();
|
||||
if (window[marker]) return { installed: false, reason: "another_owner" };
|
||||
const layerName = "72216192";
|
||||
const changes = [];
|
||||
const clients = new Map();
|
||||
const views = new WeakMap();
|
||||
const registries = new WeakSet();
|
||||
const observed = new WeakMap();
|
||||
let enabled = true;
|
||||
let timer;
|
||||
let messagesSeen = false;
|
||||
function isMessages(name) {
|
||||
try { const url = new URL(name); return url.protocol === "app:" && url.host === "-" && !url.username && !url.password && /^\/assets\/zh-CN-[a-zA-Z0-9_-]+\.js$/.test(url.pathname); }
|
||||
catch { return false; }
|
||||
}
|
||||
const resourceObserver = typeof PerformanceObserver === "function" ? new PerformanceObserver(list => {
|
||||
messagesSeen ||= list.getEntries().some(entry => isMessages(entry.name));
|
||||
}) : null;
|
||||
try { resourceObserver?.observe({ type: "resource", buffered: true }); } catch { /* optional API */ }
|
||||
|
||||
function change(object, name, value) {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(object, name);
|
||||
if (descriptor && !descriptor.configurable && !descriptor.writable) return false;
|
||||
try {
|
||||
Object.defineProperty(object, name, descriptor && !descriptor.configurable ? { value } : { configurable: true, writable: true, value });
|
||||
changes.push(() => {
|
||||
if (object[name] !== value) return;
|
||||
if (descriptor) Object.defineProperty(object, name, descriptor);
|
||||
else delete object[name];
|
||||
});
|
||||
return true;
|
||||
} catch { return false; }
|
||||
}
|
||||
function translatedLayer(layer) {
|
||||
if (!layer || typeof layer.get !== "function") return layer;
|
||||
if (views.has(layer)) return views.get(layer);
|
||||
const read = layer.get.bind(layer);
|
||||
const translatedRead = (parameter, ...args) =>
|
||||
enabled && parameter === "enable_i18n" ? true : read(parameter, ...args);
|
||||
const methods = new Map();
|
||||
// A forwarding facade also works for frozen SDK results. A proxy directly
|
||||
// wrapping a frozen own `get` would violate JavaScript proxy invariants.
|
||||
const view = new Proxy(Object.create(Object.getPrototypeOf(layer)), {
|
||||
get(_target, key) {
|
||||
if (key === "get") return translatedRead;
|
||||
const result = Reflect.get(layer, key, layer);
|
||||
if (typeof result !== "function") return result;
|
||||
if (methods.get(key)?.original !== result) methods.set(key, { original: result, bound: result.bind(layer) });
|
||||
return methods.get(key).bound;
|
||||
},
|
||||
has(_target, key) { return key in layer; },
|
||||
ownKeys() { return Reflect.ownKeys(layer); },
|
||||
getOwnPropertyDescriptor(_target, key) {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(layer, key);
|
||||
return descriptor ? { ...descriptor, configurable: true } : undefined;
|
||||
},
|
||||
});
|
||||
views.set(layer, view);
|
||||
return view;
|
||||
}
|
||||
function hook(client) {
|
||||
if (!enabled) return;
|
||||
if (!client || typeof client !== "object") return;
|
||||
const previous = clients.get(client);
|
||||
if (previous?.waiting) return;
|
||||
if (previous && previous.replacement === client.getLayer) return;
|
||||
// The SDK registers its client from the base constructor, before the
|
||||
// derived constructor assigns getLayer. Intercept that later assignment so
|
||||
// React's first memoized language evaluation already sees the override.
|
||||
if (typeof client.getLayer !== "function") {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(client, "getLayer");
|
||||
if (descriptor && !descriptor.configurable) return;
|
||||
let raw;
|
||||
let wrapped;
|
||||
const getter = () => wrapped;
|
||||
const setter = next => {
|
||||
raw = next;
|
||||
wrapped = typeof next === "function" ? wrap(client, next) : next;
|
||||
clients.set(client, { replacement: wrapped, waiting: false });
|
||||
};
|
||||
Object.defineProperty(client, "getLayer", { configurable: true, enumerable: descriptor?.enumerable ?? true, get: getter, set: setter });
|
||||
clients.set(client, { waiting: true });
|
||||
changes.push(() => {
|
||||
if (Object.getOwnPropertyDescriptor(client, "getLayer")?.get !== getter) return;
|
||||
if (descriptor && Object.hasOwn(descriptor, "value")) Object.defineProperty(client, "getLayer", { ...descriptor, value: raw });
|
||||
else if (descriptor) Object.defineProperty(client, "getLayer", descriptor);
|
||||
else if (raw === undefined) delete client.getLayer;
|
||||
else Object.defineProperty(client, "getLayer", { configurable: true, enumerable: true, writable: true, value: raw });
|
||||
});
|
||||
return;
|
||||
}
|
||||
const original = client.getLayer;
|
||||
const replacement = wrap(client, original);
|
||||
if (change(client, "getLayer", replacement)) {
|
||||
clients.set(client, { replacement });
|
||||
try { client.$emt?.({ name: "values_updated" }); } catch { /* optional SDK hook */ }
|
||||
}
|
||||
}
|
||||
function wrap(_client, original) {
|
||||
return function (name, ...args) {
|
||||
const result = original.call(this, name, ...args);
|
||||
return enabled && name === layerName ? translatedLayer(result) : result;
|
||||
};
|
||||
}
|
||||
function observe(object, key, receive) {
|
||||
let keys = observed.get(object);
|
||||
if (keys?.has(key)) { receive(object[key]); return; }
|
||||
const descriptor = Object.getOwnPropertyDescriptor(object, key);
|
||||
if (descriptor && !descriptor.configurable) { receive(object[key]); return; }
|
||||
if (!keys) { keys = new Set(); observed.set(object, keys); }
|
||||
keys.add(key);
|
||||
let current = object[key];
|
||||
const getter = () => current;
|
||||
const setter = next => {
|
||||
if (descriptor?.set) descriptor.set.call(object, next);
|
||||
current = descriptor?.get ? descriptor.get.call(object) : next;
|
||||
if (enabled) receive(current);
|
||||
};
|
||||
Object.defineProperty(object, key, { configurable: true, enumerable: descriptor?.enumerable ?? true, get: getter, set: setter });
|
||||
changes.push(() => {
|
||||
if (Object.getOwnPropertyDescriptor(object, key)?.get !== getter) return;
|
||||
if (descriptor && !Object.hasOwn(descriptor, "value")) Object.defineProperty(object, key, descriptor);
|
||||
else if (descriptor) Object.defineProperty(object, key, { ...descriptor, value: current });
|
||||
else if (current === undefined) delete object[key];
|
||||
else Object.defineProperty(object, key, { configurable: true, enumerable: true, writable: true, value: current });
|
||||
});
|
||||
receive(current);
|
||||
}
|
||||
function registryAppeared(registry) {
|
||||
if (!enabled || !registry || typeof registry !== "object" || registries.has(registry)) return;
|
||||
registries.add(registry);
|
||||
observe(registry, "firstInstance", hook);
|
||||
observe(registry, "instances", instances => {
|
||||
if (!instances || typeof instances !== "object") return;
|
||||
// Observe SDK registration without changing the dictionary's identity.
|
||||
for (const [key, client] of Object.entries(instances).slice(0, 16)) {
|
||||
hook(client);
|
||||
observe(instances, key, hook);
|
||||
}
|
||||
});
|
||||
}
|
||||
function scan() {
|
||||
const current = new Set();
|
||||
if (!enabled) return current;
|
||||
const registry = window.__STATSIG__;
|
||||
if (!registry || typeof registry !== "object") return current;
|
||||
if (registry.firstInstance) { hook(registry.firstInstance); current.add(registry.firstInstance); }
|
||||
if (registry.instances && typeof registry.instances === "object") {
|
||||
for (const client of Object.values(registry.instances).slice(0, 16)) { hook(client); current.add(client); }
|
||||
}
|
||||
return current;
|
||||
}
|
||||
const state = {
|
||||
owner: options.owner,
|
||||
status() {
|
||||
const current = scan();
|
||||
let gate = false;
|
||||
for (const client of current) {
|
||||
try { gate ||= client.getLayer(layerName, { disableExposureLog: true }).get("enable_i18n", false) === true; }
|
||||
catch { /* unsupported client instance */ }
|
||||
}
|
||||
const language = document.documentElement?.lang || "";
|
||||
const normalized = String(language).replace(/_/g, "-").toLowerCase();
|
||||
const locale = options.locale === "zh-CN" ? ["zh-cn", "zh-hans", "zh-hans-cn"].includes(normalized) : /^en(?:-|$)/i.test(normalized);
|
||||
const messages = options.locale === "en-US" || messagesSeen || performance.getEntriesByType("resource").some(entry => isMessages(entry.name));
|
||||
return { installed: enabled, ready: enabled && gate && locale && messages,
|
||||
locale: options.locale, clients: current.size, gate, languageMatches: locale, messagesLoaded: messages };
|
||||
},
|
||||
restore() {
|
||||
enabled = false;
|
||||
clearInterval(timer);
|
||||
resourceObserver?.disconnect();
|
||||
for (const undo of changes.reverse()) { try { undo(); } catch { /* preserve later changes */ } }
|
||||
if (window[marker] === state) delete window[marker];
|
||||
return { restored: true };
|
||||
},
|
||||
};
|
||||
Object.defineProperty(window, marker, { configurable: true, value: state });
|
||||
observe(window, "__STATSIG__", registryAppeared);
|
||||
scan();
|
||||
timer = setInterval(scan, 100);
|
||||
return state.status();
|
||||
})(__CODEXX_LANGUAGE_CONFIG__)
|
||||
@@ -13,7 +13,7 @@ use std::fs;
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
use toml_edit::{value, DocumentMut, Item, TableLike};
|
||||
use toml_edit::{value, DocumentMut, ImDocument, Item, Key, Table, TableLike};
|
||||
|
||||
const MAX_CONFIG_BYTES: u64 = 2 * 1024 * 1024;
|
||||
const BUILTIN_PROVIDERS: &[&str] = &[
|
||||
@@ -31,6 +31,11 @@ pub(crate) struct ConfigHealthIssue {
|
||||
pub(crate) title: String,
|
||||
pub(crate) description: String,
|
||||
pub(crate) repairable: bool,
|
||||
pub(crate) path: String,
|
||||
pub(crate) line: Option<usize>,
|
||||
pub(crate) column: Option<usize>,
|
||||
pub(crate) key: String,
|
||||
pub(crate) suggestion: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
@@ -277,18 +282,35 @@ fn fingerprint(
|
||||
format!("{:x}", digest.finalize())
|
||||
}
|
||||
|
||||
fn key_path(parts: &[&str]) -> String {
|
||||
parts
|
||||
.iter()
|
||||
.map(|part| Key::new(*part).to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join(".")
|
||||
}
|
||||
|
||||
fn add_issue(
|
||||
report: &mut ConfigHealthReport,
|
||||
code: &str,
|
||||
title: &str,
|
||||
description: &str,
|
||||
repair: Option<&str>,
|
||||
key: &[&str],
|
||||
suggestion: &str,
|
||||
) {
|
||||
report.issues.push(ConfigHealthIssue {
|
||||
code: code.to_string(),
|
||||
title: title.to_string(),
|
||||
description: description.to_string(),
|
||||
repairable: repair.is_some(),
|
||||
path: config_path(Path::new(&report.codex_dir))
|
||||
.display()
|
||||
.to_string(),
|
||||
line: None,
|
||||
column: None,
|
||||
key: key_path(key),
|
||||
suggestion: suggestion.to_string(),
|
||||
});
|
||||
if let Some(summary) = repair {
|
||||
if !report
|
||||
@@ -301,6 +323,136 @@ fn add_issue(
|
||||
}
|
||||
}
|
||||
|
||||
fn line_column(text: &str, offset: usize) -> (usize, usize) {
|
||||
let mut offset = offset.min(text.len());
|
||||
while !text.is_char_boundary(offset) {
|
||||
offset -= 1;
|
||||
}
|
||||
let prefix = &text[..offset];
|
||||
(
|
||||
prefix.bytes().filter(|byte| *byte == b'\n').count() + 1,
|
||||
prefix
|
||||
.rsplit('\n')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.chars()
|
||||
.count()
|
||||
+ 1,
|
||||
)
|
||||
}
|
||||
|
||||
fn locate_issues(report: &mut ConfigHealthReport, source: &ImDocument<&str>) {
|
||||
for issue in &mut report.issues {
|
||||
let Ok(keys) = Key::parse(&issue.key) else {
|
||||
continue;
|
||||
};
|
||||
let mut item = source.as_item();
|
||||
let mut offset = None;
|
||||
for (index, key) in keys.iter().enumerate() {
|
||||
let Some(table) = item.as_table_like() else {
|
||||
offset = None;
|
||||
break;
|
||||
};
|
||||
let Some(next) = table.get(key.get()) else {
|
||||
offset = None;
|
||||
break;
|
||||
};
|
||||
if index + 1 == keys.len() {
|
||||
offset = table
|
||||
.key(key.get())
|
||||
.and_then(Key::span)
|
||||
.map(|span| span.start)
|
||||
.or_else(|| next.span().map(|span| span.start));
|
||||
}
|
||||
item = next;
|
||||
}
|
||||
if let Some(offset) = offset {
|
||||
let (line, column) = line_column(source.raw(), offset);
|
||||
issue.line = Some(line);
|
||||
issue.column = Some(column);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Recover only TOML key names, never values or the parser's source-line display.
|
||||
// An invalid key/header is identified as document syntax rather than guessed.
|
||||
fn delimiter_outside_quotes(text: &str, delimiter: char) -> Option<usize> {
|
||||
let mut quote = None;
|
||||
let mut escaped = false;
|
||||
for (offset, character) in text.char_indices() {
|
||||
if escaped {
|
||||
escaped = false;
|
||||
continue;
|
||||
}
|
||||
if quote == Some('"') && character == '\\' {
|
||||
escaped = true;
|
||||
continue;
|
||||
}
|
||||
if quote == Some(character) {
|
||||
quote = None;
|
||||
continue;
|
||||
}
|
||||
if quote.is_some() {
|
||||
continue;
|
||||
}
|
||||
if character == '\'' || character == '"' {
|
||||
quote = Some(character);
|
||||
} else if character == delimiter {
|
||||
return Some(offset);
|
||||
} else if character == '#' {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn syntax_key(text: &str, offset: usize) -> Vec<String> {
|
||||
let error_line = line_column(text, offset).0;
|
||||
let mut section: Vec<String> = Vec::new();
|
||||
let mut current = vec!["<TOML 文档结构>".to_string()];
|
||||
for line in text.lines().take(error_line) {
|
||||
let line = line.trim();
|
||||
if line.is_empty() || line.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
if line.starts_with('[') {
|
||||
let body = line.trim_start_matches('[');
|
||||
let candidate = delimiter_outside_quotes(body, ']').map_or(body, |end| &body[..end]);
|
||||
if let Ok(keys) = Key::parse(candidate) {
|
||||
section = keys.iter().map(|key| key.get().to_string()).collect();
|
||||
current = section.clone();
|
||||
} else {
|
||||
current = vec!["<TOML 表头>".to_string()];
|
||||
}
|
||||
} else if let Some(equal) = delimiter_outside_quotes(line, '=') {
|
||||
if let Ok(keys) = Key::parse(line[..equal].trim()) {
|
||||
current = section
|
||||
.iter()
|
||||
.cloned()
|
||||
.chain(keys.iter().map(|key| key.get().to_string()))
|
||||
.collect();
|
||||
}
|
||||
}
|
||||
}
|
||||
current
|
||||
}
|
||||
|
||||
fn syntax_suggestion(message: &str) -> &'static str {
|
||||
if message.contains("duplicate") {
|
||||
"同一配置范围内的参数或表重复定义;保留一处正确定义,合并需要保留的内容后重新检查。"
|
||||
} else if message.contains("string") || message.contains("quote") {
|
||||
"检查此参数的引号是否成对;单行字符串不能直接换行,需换行时使用 TOML 三引号字符串。"
|
||||
} else if message.contains("array") || message.contains("expected `]`") {
|
||||
"检查此参数的数组是否以 ] 结束,各元素之间是否有逗号;修正后重新检查。"
|
||||
} else if message.contains("table") || message.contains("expected `.`") {
|
||||
"检查表头的方括号与点分参数名;例如 [model_providers.custom],同一张表不能重复定义。"
|
||||
} else if message.contains("expected `=`") {
|
||||
"参数必须写成 参数名 = 值;补齐等号并使用 TOML 支持的值格式后重新检查。"
|
||||
} else {
|
||||
"检查标记位置的引号、逗号和括号是否配对,参数应写成 参数名 = 值;修正后重新检查。"
|
||||
}
|
||||
}
|
||||
|
||||
fn bool_replacement(item: &Item) -> Option<bool> {
|
||||
match item.as_str()?.trim().to_ascii_lowercase().as_str() {
|
||||
"true" => Some(true),
|
||||
@@ -336,8 +488,10 @@ fn check_provider_table(
|
||||
report,
|
||||
"provider-table-type",
|
||||
"供应商配置格式不正确",
|
||||
"有一条供应商配置不是有效的配置表,请在供应商页面重新检查配置。",
|
||||
"此供应商的定义不是 TOML 配置表。",
|
||||
None,
|
||||
&["model_providers", id],
|
||||
"将此项改为 [model_providers.供应商标识] 配置表,并恢复原有参数;现有值无法确定,需手动确认。",
|
||||
);
|
||||
return;
|
||||
};
|
||||
@@ -355,8 +509,10 @@ fn check_provider_table(
|
||||
report,
|
||||
"provider-name-missing",
|
||||
"供应商配置缺少名称",
|
||||
"有一条供应商配置没有填写名称,可使用它现有的标识补齐显示名称。",
|
||||
"此供应商的 name 缺失或为空。",
|
||||
(!id.trim().is_empty()).then_some("根据供应商标识补齐缺失的显示名称"),
|
||||
&["model_providers", id, "name"],
|
||||
&format!("补齐 name = {},保留供应商标识与其他参数。", value(id)),
|
||||
);
|
||||
}
|
||||
for key in ["name", "base_url"] {
|
||||
@@ -365,8 +521,14 @@ fn check_provider_table(
|
||||
report,
|
||||
"provider-text-type",
|
||||
"供应商文字配置格式不正确",
|
||||
"供应商名称或接口地址应为文字,暂时无法自动判断正确内容。",
|
||||
&format!("{key} 应为 TOML 字符串,现有值的类型不正确。"),
|
||||
None,
|
||||
&["model_providers", id, key],
|
||||
if key == "name" {
|
||||
"将 name 改为带引号的供应商显示名称,例如 name = \"My API\"。"
|
||||
} else {
|
||||
"将 base_url 改为带引号的接口地址,例如 base_url = \"https://供应商地址/v1\";地址需向供应商确认。"
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -386,16 +548,20 @@ fn check_provider_table(
|
||||
report,
|
||||
"provider-boolean-text",
|
||||
"供应商开关格式不正确",
|
||||
"有一项开关被写成了文字,可能导致 Codex 无法加载配置。",
|
||||
&format!("{key} 被写成了字符串,Codex 需要布尔值。"),
|
||||
Some("将写成文字的开关恢复为正确格式"),
|
||||
&["model_providers", id, key],
|
||||
&format!("将 {key} 改为 {replacement}(不带引号),保留当前开关含义。"),
|
||||
);
|
||||
} else {
|
||||
add_issue(
|
||||
report,
|
||||
"provider-boolean-type",
|
||||
"供应商开关无法识别",
|
||||
"有一项开关不是有效的开启或关闭值,需要手动确认。",
|
||||
&format!("{key} 不是布尔值,也无法确定其开启或关闭含义。"),
|
||||
None,
|
||||
&["model_providers", id, key],
|
||||
&format!("确认所需状态后将 {key} 写为 true 或 false(不带引号)。"),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -420,6 +586,8 @@ fn check_provider_table(
|
||||
"DeepSeek 的连接方式需要调整",
|
||||
"DeepSeek 官方接口不支持当前开启的 WebSocket 连接,可能先报错并多次重试,再正常回复。",
|
||||
Some("将 DeepSeek 官方接口改用 HTTP 连接,避免发送消息时反复重试"),
|
||||
&["model_providers", id, "supports_websockets"],
|
||||
"将 supports_websockets 改为 false,让 DeepSeek 官方接口使用 HTTP。",
|
||||
);
|
||||
}
|
||||
if let Some(item) = table.get_mut("wire_api") {
|
||||
@@ -439,6 +607,8 @@ fn check_provider_table(
|
||||
"供应商接口格式拼写不正确",
|
||||
"接口格式中存在多余空格或大小写错误,可能导致 Codex 无法加载配置。",
|
||||
Some("修正接口格式的空格或大小写"),
|
||||
&["model_providers", id, "wire_api"],
|
||||
"将 wire_api 规范为 \"responses\",去掉多余空格并使用小写。",
|
||||
);
|
||||
} else {
|
||||
add_issue(
|
||||
@@ -447,6 +617,8 @@ fn check_provider_table(
|
||||
"供应商接口格式不受支持",
|
||||
"当前 Codex 需要 Responses 接口。请向供应商确认支持的接口,或使用兼容的转接服务。",
|
||||
None,
|
||||
&["model_providers", id, "wire_api"],
|
||||
"先向供应商确认支持 Responses API;支持时设置 wire_api = \"responses\",否则选择兼容供应商。不能仅改名称来转换协议。",
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -462,6 +634,8 @@ fn check_provider_table(
|
||||
"官方登录的认证设置不完整",
|
||||
"已发现官方登录信息,但这条官方供应商配置没有启用登录认证。",
|
||||
Some("为官方登录补齐认证开关"),
|
||||
&["model_providers", id, "requires_openai_auth"],
|
||||
"设置 requires_openai_auth = true,使用已确认的 ChatGPT 登录信息。",
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -487,6 +661,64 @@ fn complete_alias_candidate(item: &Item) -> bool {
|
||||
|| table.get("requires_openai_auth").and_then(Item::as_bool) == Some(true))
|
||||
}
|
||||
|
||||
// A historical provider ID may be routed to the user's explicitly selected
|
||||
// official login only when neither root nor provider fields select other auth
|
||||
// or endpoints. No saved accounts, backups or credentials are borrowed.
|
||||
fn official_history_alias(doc: &DocumentMut, chatgpt_auth: bool) -> Option<Item> {
|
||||
if !chatgpt_auth
|
||||
|| [
|
||||
"base_url",
|
||||
"experimental_bearer_token",
|
||||
"auth",
|
||||
"env_key",
|
||||
"env_key_instructions",
|
||||
"http_headers",
|
||||
"env_http_headers",
|
||||
"query_params",
|
||||
"api_base",
|
||||
"chatgpt_base_url",
|
||||
"api_key",
|
||||
"openai_api_key",
|
||||
"auth_mode",
|
||||
"tokens",
|
||||
"env_vars",
|
||||
]
|
||||
.iter()
|
||||
.any(|key| doc.contains_key(key))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let providers = match doc.get("model_providers") {
|
||||
None => None,
|
||||
Some(item) => Some(item.as_table_like()?),
|
||||
};
|
||||
let selected = match doc.get("model_provider") {
|
||||
Some(item) => item.as_str()?,
|
||||
None => "openai",
|
||||
};
|
||||
if doc
|
||||
.get("forced_login_method")
|
||||
.is_some_and(|item| item.as_str() != Some("chatgpt"))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
if let Some(item) = providers.and_then(|providers| providers.get(selected)) {
|
||||
let table = item.as_table_like()?;
|
||||
return (is_official_login_table(table, chatgpt_auth)
|
||||
&& !table.contains_key("query_params")
|
||||
&& complete_alias_candidate(item))
|
||||
.then(|| item.clone());
|
||||
}
|
||||
if selected != "openai" {
|
||||
return None;
|
||||
}
|
||||
let mut table = Table::new();
|
||||
table.insert("name", value("OpenAI"));
|
||||
table.insert("requires_openai_auth", value(true));
|
||||
table.insert("wire_api", value("responses"));
|
||||
Some(Item::Table(table))
|
||||
}
|
||||
|
||||
fn collect_provider_reference(
|
||||
item: Option<&Item>,
|
||||
references: &mut Vec<String>,
|
||||
@@ -500,6 +732,8 @@ fn collect_provider_reference(
|
||||
"选用的供应商设置不正确",
|
||||
"供应商标识应为非空文字,请在供应商页面重新选择后保存。",
|
||||
None,
|
||||
&["model_provider"],
|
||||
"将 model_provider 设置为已定义的非空供应商标识,例如 \"openai\" 或 [model_providers.custom] 对应的 \"custom\";需先确认所选供应商。",
|
||||
);
|
||||
return;
|
||||
};
|
||||
@@ -538,6 +772,8 @@ fn analyze(
|
||||
"暂时无法检查配置",
|
||||
message,
|
||||
None,
|
||||
&["<配置文件>"],
|
||||
"检查显示路径对应文件的存在性、文件类型、读取权限与大小后重试。",
|
||||
);
|
||||
return (report, None);
|
||||
}
|
||||
@@ -549,45 +785,36 @@ fn analyze(
|
||||
&mut report,
|
||||
"config-encoding",
|
||||
"配置文件的文字编码不正确",
|
||||
"配置文件需要使用 UTF-8 编码,请手动检查后保存。",
|
||||
"配置文件需要使用 UTF-8 编码。",
|
||||
None,
|
||||
&["<文件编码>"],
|
||||
"在文本编辑器中按原编码打开此文件,再以 UTF-8 编码保存;编码无法可靠判断,不能自动转换。",
|
||||
);
|
||||
return (report, None);
|
||||
};
|
||||
let mut doc = match text.parse::<DocumentMut>() {
|
||||
let source = match ImDocument::parse(text) {
|
||||
Ok(doc) => doc,
|
||||
Err(error) => {
|
||||
report.status = "issues";
|
||||
// TOML's normal Display embeds entire source lines, including credentials.
|
||||
let description = error
|
||||
.span()
|
||||
.map(|span| {
|
||||
let mut offset = span.start.min(text.len());
|
||||
while !text.is_char_boundary(offset) {
|
||||
offset -= 1;
|
||||
}
|
||||
let prefix = &text[..offset];
|
||||
let line = prefix.bytes().filter(|byte| *byte == b'\n').count() + 1;
|
||||
let column = prefix
|
||||
.rsplit('\n')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.chars()
|
||||
.count()
|
||||
+ 1;
|
||||
format!("配置文件第 {line} 行、第 {column} 列附近有格式错误,需要手动检查。")
|
||||
})
|
||||
.unwrap_or_else(|| "配置文件中存在格式错误,需要手动检查。".to_string());
|
||||
let offset = error.span().map_or(0, |span| span.start);
|
||||
let (line, column) = line_column(text, offset);
|
||||
let keys = syntax_key(text, offset);
|
||||
let keys: Vec<_> = keys.iter().map(String::as_str).collect();
|
||||
add_issue(
|
||||
&mut report,
|
||||
"config-syntax",
|
||||
"配置文件格式不正确",
|
||||
&description,
|
||||
&format!("配置文件第 {line} 行、第 {column} 列附近存在 TOML 语法错误。"),
|
||||
None,
|
||||
&keys,
|
||||
syntax_suggestion(error.message()),
|
||||
);
|
||||
report.issues[0].line = Some(line);
|
||||
report.issues[0].column = Some(column);
|
||||
return (report, None);
|
||||
}
|
||||
};
|
||||
let mut doc = source.clone().into_mut();
|
||||
let mut references = Vec::new();
|
||||
collect_provider_reference(doc.get("model_provider"), &mut references, &mut report);
|
||||
// Profile loading changed between Codex versions. Leave legacy inline
|
||||
@@ -602,8 +829,10 @@ fn analyze(
|
||||
&mut report,
|
||||
"providers-table-type",
|
||||
"供应商列表格式不正确",
|
||||
"model_providers 应为配置表,暂时无法自动恢复原有供应商。",
|
||||
"model_providers 应为 TOML 配置表,现有值的类型不正确。",
|
||||
None,
|
||||
&["model_providers"],
|
||||
"恢复 [model_providers.供应商标识] 配置表与原有参数;现有内容无法可靠还原,需手动确认。",
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -640,9 +869,27 @@ fn analyze(
|
||||
.filter(|id| !BUILTIN_PROVIDERS.contains(id))
|
||||
.and_then(|id| providers.and_then(|providers| providers.get(id)))
|
||||
.is_some_and(complete_alias_candidate);
|
||||
if missing.len() == 1 && candidates.len() == 1 && (!history_only || selected_custom_exists)
|
||||
{
|
||||
let source_name: String = candidates[0]
|
||||
let official_alias = history_only
|
||||
.then(|| official_history_alias(&doc, chatgpt_auth))
|
||||
.flatten();
|
||||
let selected_official_style = doc
|
||||
.get("model_provider")
|
||||
.and_then(Item::as_str)
|
||||
.and_then(|id| providers.and_then(|providers| providers.get(id)))
|
||||
.and_then(Item::as_table_like)
|
||||
.is_some_and(|table| {
|
||||
table.get("name").and_then(Item::as_str) == Some("OpenAI")
|
||||
&& !table.contains_key("base_url")
|
||||
});
|
||||
let source = official_alias.clone().or_else(|| {
|
||||
(missing.len() == 1
|
||||
&& candidates.len() == 1
|
||||
&& (!history_only || (selected_custom_exists && !selected_official_style)))
|
||||
.then(|| candidates[0].clone())
|
||||
});
|
||||
let first_routing_summary = report.repair_summary.len();
|
||||
if let Some(source) = source {
|
||||
let source_name: String = source
|
||||
.as_table_like()
|
||||
.and_then(|table| table.get("name"))
|
||||
.and_then(Item::as_str)
|
||||
@@ -651,38 +898,51 @@ fn analyze(
|
||||
.filter(|ch| !ch.is_control())
|
||||
.take(60)
|
||||
.collect();
|
||||
doc.get_mut("model_providers")
|
||||
.and_then(Item::as_table_like_mut)
|
||||
.expect("candidate implies table")
|
||||
.insert(&missing[0], candidates[0].clone());
|
||||
if history_only {
|
||||
let summary =
|
||||
format!("让受影响的旧会话沿用当前供应商「{source_name}」,并保留原会话");
|
||||
add_issue(&mut report, "session-provider-definition-missing", "旧会话使用的供应商缺少配置", &format!("有些旧会话仍引用已缺失的供应商。修复后,这些会话将沿用当前供应商「{source_name}」,原会话会保留。"), Some(&summary));
|
||||
} else {
|
||||
let summary = format!("使用现有供应商「{source_name}」的配置补齐缺失的对应关系");
|
||||
add_issue(&mut report, "provider-definition-missing", "选用的供应商缺少配置", &format!("供应商标识与现有配置不对应。将使用现有供应商「{source_name}」的配置补齐对应关系,并保留原配置。"), Some(&summary));
|
||||
if doc.get("model_providers").is_none() {
|
||||
doc.as_table_mut()
|
||||
.insert("model_providers", Item::Table(Table::new()));
|
||||
}
|
||||
// Keep routing decisions visible in the compact startup notice.
|
||||
if let Some(summary) = report.repair_summary.pop() {
|
||||
report.repair_summary.insert(0, summary);
|
||||
for id in &missing {
|
||||
doc.get_mut("model_providers")
|
||||
.and_then(Item::as_table_like_mut)
|
||||
.expect("safe source requires a valid provider table")
|
||||
.insert(id, source.clone());
|
||||
let summary = if history_only {
|
||||
format!("补齐 [model_providers.{}],让旧会话沿用当前供应商「{source_name}」,并保留原会话", Key::new(id.as_str()))
|
||||
} else {
|
||||
format!(
|
||||
"使用现有供应商「{source_name}」补齐 [model_providers.{}],并保留原配置",
|
||||
Key::new(id.as_str())
|
||||
)
|
||||
};
|
||||
let description = if history_only {
|
||||
format!("旧会话仍引用供应商标识 {},但 config.toml 中缺少对应的配置表。修复后,这些会话将沿用当前供应商「{source_name}」。", Key::new(id.as_str()))
|
||||
} else {
|
||||
format!(
|
||||
"model_provider 选中的供应商 {} 缺少对应的配置表。",
|
||||
Key::new(id.as_str())
|
||||
)
|
||||
};
|
||||
add_issue(&mut report,
|
||||
if history_only { "session-provider-definition-missing" } else { "provider-definition-missing" },
|
||||
if history_only { "旧会话使用的供应商缺少配置" } else { "选用的供应商缺少配置" },
|
||||
&description, Some(&summary), &["model_providers", id],
|
||||
&format!("新增 {},复制已确认的当前{}供应商「{source_name}」参数;保留 model_provider、原有表和会话数据库。",
|
||||
key_path(&["model_providers", id]), if official_alias.is_some() { "官方登录" } else { "" }));
|
||||
}
|
||||
// Keep all routing decisions before smaller value corrections.
|
||||
let routing = report.repair_summary.split_off(first_routing_summary);
|
||||
report.repair_summary.splice(0..0, routing);
|
||||
} else {
|
||||
add_issue(
|
||||
&mut report,
|
||||
if history_only {
|
||||
"session-provider-definition-missing"
|
||||
} else {
|
||||
"provider-definition-missing"
|
||||
},
|
||||
if history_only {
|
||||
"旧会话使用的供应商缺少配置"
|
||||
} else {
|
||||
"选用的供应商缺少配置"
|
||||
},
|
||||
"未找到唯一可确认的供应商配置,请在供应商页面重新选择并启用,或手动补齐原配置。",
|
||||
None,
|
||||
);
|
||||
for id in &missing {
|
||||
add_issue(&mut report,
|
||||
if history_only { "session-provider-definition-missing" } else { "provider-definition-missing" },
|
||||
if history_only { "旧会话使用的供应商缺少配置" } else { "选用的供应商缺少配置" },
|
||||
&format!("{} 引用了供应商标识 {},但 {} 未定义,且无法确认应使用哪个来源。",
|
||||
if history_only { "旧会话" } else { "model_provider" }, Key::new(id.as_str()), key_path(&["model_providers", id])),
|
||||
None, &["model_providers", id],
|
||||
&format!("手动补齐 [{}] 的原供应商参数;若希望旧会话改用官方,请先启用官方配置并完成 ChatGPT 登录后重新检查。多个中转来源不会自动合并。", key_path(&["model_providers", id])));
|
||||
}
|
||||
}
|
||||
}
|
||||
report.status = if report.issues.is_empty() {
|
||||
@@ -704,10 +964,13 @@ fn analyze(
|
||||
&mut report,
|
||||
"config-linked-file",
|
||||
"配置文件由链接指向其他位置",
|
||||
"请打开原配置文件进行修改,以保留已有的文件链接。",
|
||||
"此 config.toml 是文件链接,不能安全替换链接本身。",
|
||||
None,
|
||||
&["<文件链接>"],
|
||||
"使用「查看配置」打开链接指向的原文件,按上述参数建议修复后重新检查。",
|
||||
);
|
||||
}
|
||||
locate_issues(&mut report, &source);
|
||||
let replacement = report.can_repair.then(|| doc.to_string());
|
||||
(report, replacement)
|
||||
}
|
||||
@@ -1163,7 +1426,263 @@ mod tests {
|
||||
assert_eq!(report.status, "issues");
|
||||
assert!(json.contains("第 2 行"));
|
||||
assert!(!json.contains("super-private-secret"));
|
||||
assert!(!json.contains("experimental_bearer_token"));
|
||||
let issue = &report.issues[0];
|
||||
assert_eq!(issue.path, config_path(&fixture.0).display().to_string());
|
||||
assert_eq!(issue.line, Some(2));
|
||||
assert!(issue.column.is_some_and(|column| column > 0));
|
||||
assert_eq!(issue.key, "experimental_bearer_token");
|
||||
assert!(!issue.suggestion.is_empty());
|
||||
assert!(!issue.repairable);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagnostics_locate_the_original_parameter_and_give_an_exact_fix() {
|
||||
let fixture = Fixture::new("# 注释\nmodel_provider='custom'\n[model_providers.custom]\nname='My API'\nbase_url='https://fixture.example/v1'\n supports_websockets = 'TRUE' # 保留\nwire_api = 'chat'\n");
|
||||
let report = fixture.check();
|
||||
let boolean = report
|
||||
.issues
|
||||
.iter()
|
||||
.find(|issue| issue.code == "provider-boolean-text")
|
||||
.unwrap();
|
||||
assert_eq!(boolean.path, config_path(&fixture.0).display().to_string());
|
||||
assert_eq!((boolean.line, boolean.column), (Some(6), Some(3)));
|
||||
assert_eq!(boolean.key, "model_providers.custom.supports_websockets");
|
||||
assert!(boolean.suggestion.contains("supports_websockets 改为 true"));
|
||||
let protocol = report
|
||||
.issues
|
||||
.iter()
|
||||
.find(|issue| issue.code == "provider-protocol-unsupported")
|
||||
.unwrap();
|
||||
assert_eq!((protocol.line, protocol.column), (Some(7), Some(1)));
|
||||
assert_eq!(protocol.key, "model_providers.custom.wire_api");
|
||||
assert!(protocol.suggestion.contains("Responses API"));
|
||||
assert!(!protocol.repairable);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dotted_inline_and_quoted_provider_keys_keep_precise_locations() {
|
||||
for (text, line, column) in [
|
||||
("model_providers.\"with.dot\".name=9\n", 1, 28),
|
||||
("model_providers = { \"with.dot\" = { name = 9 } }\n", 1, 36),
|
||||
("[model_providers.\"with.dot\"]\nname=9\n", 2, 1),
|
||||
] {
|
||||
let fixture = Fixture::new(text);
|
||||
let report = fixture.check();
|
||||
let issue = report
|
||||
.issues
|
||||
.iter()
|
||||
.find(|issue| issue.code == "provider-text-type")
|
||||
.unwrap();
|
||||
assert_eq!(issue.key, "model_providers.\"with.dot\".name");
|
||||
assert_eq!(
|
||||
(issue.line, issue.column),
|
||||
(Some(line), Some(column)),
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_definition_has_no_invented_line_and_names_each_provider() {
|
||||
let fixture = Fixture::new("model_provider='openai'\n");
|
||||
fixture.sessions(&["old_proxy_a", "old_proxy_b"]);
|
||||
let report = fixture.check();
|
||||
assert_eq!(report.issues.len(), 2);
|
||||
assert!(!report.can_repair);
|
||||
for issue in &report.issues {
|
||||
assert_eq!(issue.path, config_path(&fixture.0).display().to_string());
|
||||
assert_eq!((issue.line, issue.column), (None, None));
|
||||
assert!(issue.key.starts_with("model_providers.old_proxy_"));
|
||||
assert!(issue.description.contains(&issue.key));
|
||||
assert!(issue.suggestion.contains(&issue.key));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn syntax_errors_include_parameter_context_and_safe_actionable_suggestions() {
|
||||
let text = "model_provider='custom'\n[model_providers.custom]\nname='OpenAI'\nexperimental_bearer_token = 'never-echo-this-secret\n";
|
||||
let fixture = Fixture::new(text);
|
||||
let report = fixture.check();
|
||||
let issue = &report.issues[0];
|
||||
assert_eq!(
|
||||
issue.key,
|
||||
"model_providers.custom.experimental_bearer_token"
|
||||
);
|
||||
assert_eq!(issue.line, Some(4));
|
||||
assert!(issue.column.is_some());
|
||||
assert!(issue.suggestion.contains("引号"));
|
||||
assert!(!serde_json::to_string(&report)
|
||||
.unwrap()
|
||||
.contains("never-echo-this-secret"));
|
||||
assert!(!fixture.repair(&report).changed);
|
||||
assert_eq!(fixture.text(), text);
|
||||
assert!(!fixture.0.join(".codexx-test-backups").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn syntax_context_respects_delimiters_inside_quoted_keys() {
|
||||
let text = "[model_providers.\"name]with=chars\"]\n\"key=with]chars\" = 'secret-without-closing-quote\n";
|
||||
let keys = syntax_key(text, text.len() - 1);
|
||||
assert_eq!(
|
||||
keys,
|
||||
["model_providers", "name]with=chars", "key=with]chars"]
|
||||
);
|
||||
assert!(!key_path(&keys.iter().map(String::as_str).collect::<Vec<_>>()).contains("secret"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builtin_official_login_can_repair_all_missing_history_aliases_without_touching_sessions() {
|
||||
for selection in ["model_provider='openai'\n", ""] {
|
||||
let original = format!(
|
||||
"{selection}model='official-model'\n[mcp_servers.fixture]\ncommand='fixture-mcp'\n"
|
||||
);
|
||||
let fixture = Fixture::new(&original);
|
||||
fixture.login();
|
||||
fixture.sessions(&["old_proxy_a", "old_proxy_b", "openai"]);
|
||||
let db_before = fs::read(fixture.0.join("state_5.sqlite")).unwrap();
|
||||
let auth_before = fs::read(auth_path(&fixture.0)).unwrap();
|
||||
let report = fixture.check();
|
||||
assert!(report.can_repair);
|
||||
assert_eq!(report.issues.len(), 2);
|
||||
assert!(report
|
||||
.repair_summary
|
||||
.iter()
|
||||
.all(|summary| summary.contains("OpenAI")));
|
||||
assert_eq!(fixture.text(), original);
|
||||
let repaired = fixture.repair(&report);
|
||||
assert!(repaired.changed);
|
||||
assert_eq!(repaired.report.status, "healthy");
|
||||
let backup = fixture
|
||||
.0
|
||||
.join(".codexx-test-backups")
|
||||
.join(repaired.backup_id.unwrap())
|
||||
.join("config.toml");
|
||||
assert_eq!(fs::read_to_string(backup).unwrap(), original);
|
||||
let doc = fixture.text().parse::<DocumentMut>().unwrap();
|
||||
assert_eq!(
|
||||
doc.get("model_provider").and_then(Item::as_str),
|
||||
if selection.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some("openai")
|
||||
}
|
||||
);
|
||||
assert_eq!(doc["model"].as_str(), Some("official-model"));
|
||||
assert_eq!(
|
||||
doc["mcp_servers"]["fixture"]["command"].as_str(),
|
||||
Some("fixture-mcp")
|
||||
);
|
||||
for id in ["old_proxy_a", "old_proxy_b"] {
|
||||
assert_eq!(doc["model_providers"][id]["name"].as_str(), Some("OpenAI"));
|
||||
assert_eq!(
|
||||
doc["model_providers"][id]["wire_api"].as_str(),
|
||||
Some("responses")
|
||||
);
|
||||
assert_eq!(
|
||||
doc["model_providers"][id]["requires_openai_auth"].as_bool(),
|
||||
Some(true)
|
||||
);
|
||||
assert!(doc["model_providers"][id]
|
||||
.as_table_like()
|
||||
.unwrap()
|
||||
.get("base_url")
|
||||
.is_none());
|
||||
}
|
||||
assert_eq!(
|
||||
fs::read(fixture.0.join("state_5.sqlite")).unwrap(),
|
||||
db_before
|
||||
);
|
||||
assert_eq!(fs::read(auth_path(&fixture.0)).unwrap(), auth_before);
|
||||
assert!(!fixture.repair(&repaired.report).changed);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_custom_official_login_can_repair_history_with_multiple_inactive_sources() {
|
||||
let original = "model_provider='custom'\n[model_providers.custom]\nname='OpenAI'\nrequires_openai_auth=true\nsupports_websockets=true\nwire_api='responses'\n[model_providers.inactive]\nname='Inactive proxy'\nbase_url='https://inactive.fixture/v1'\n";
|
||||
let fixture = Fixture::new(original);
|
||||
fixture.login();
|
||||
fixture.sessions(&["old_proxy_a", "old_proxy_b"]);
|
||||
let report = fixture.check();
|
||||
assert!(report.can_repair);
|
||||
assert_eq!(fixture.repair(&report).report.status, "healthy");
|
||||
let doc = fixture.text().parse::<DocumentMut>().unwrap();
|
||||
assert_eq!(doc["model_provider"].as_str(), Some("custom"));
|
||||
assert_eq!(
|
||||
doc["model_providers"]["old_proxy_a"]["supports_websockets"].as_bool(),
|
||||
Some(true)
|
||||
);
|
||||
assert_eq!(
|
||||
doc["model_providers"]["inactive"]["base_url"].as_str(),
|
||||
Some("https://inactive.fixture/v1")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn official_history_repair_requires_login_and_unambiguous_current_routing() {
|
||||
for text in [
|
||||
"model_provider='openai'\n",
|
||||
"model_provider='custom'\n[model_providers.custom]\nname='OpenAI'\nrequires_openai_auth=true\nwire_api='responses'\n",
|
||||
] {
|
||||
let fixture = Fixture::new(text);
|
||||
fixture.sessions(&["old_proxy"]);
|
||||
assert!(!fixture.check().can_repair, "{text}");
|
||||
assert_eq!(fixture.text(), text);
|
||||
}
|
||||
for root in [
|
||||
"base_url='https://proxy.fixture'",
|
||||
"env_key='FIXTURE_API_KEY'",
|
||||
"http_headers={Authorization='Bearer fixture'}",
|
||||
"forced_login_method='api'",
|
||||
"model_provider=5",
|
||||
] {
|
||||
let original = if root.starts_with("model_provider") {
|
||||
format!("{root}\n")
|
||||
} else {
|
||||
format!("model_provider='openai'\n{root}\n")
|
||||
};
|
||||
let fixture = Fixture::new(&original);
|
||||
fixture.login();
|
||||
fixture.sessions(&["old_proxy"]);
|
||||
let report = fixture.check();
|
||||
assert!(!report.can_repair, "{root}");
|
||||
assert!(!fixture.repair(&report).changed);
|
||||
assert_eq!(fixture.text(), original);
|
||||
}
|
||||
for extra in [
|
||||
"env_key='FIXTURE_API_KEY'",
|
||||
"http_headers={Authorization='Bearer fixture'}",
|
||||
"query_params={token='fixture'}",
|
||||
] {
|
||||
let original = format!("model_provider='custom'\n[model_providers.custom]\nname='OpenAI'\nrequires_openai_auth=true\nwire_api='responses'\n{extra}\n");
|
||||
let fixture = Fixture::new(&original);
|
||||
fixture.login();
|
||||
fixture.sessions(&["old_proxy"]);
|
||||
assert!(!fixture.check().can_repair, "{extra}");
|
||||
assert_eq!(fixture.text(), original);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_removal_and_external_edit_cancel_official_alias_repairs() {
|
||||
let original = "model_provider='openai'\n";
|
||||
let fixture = Fixture::new(original);
|
||||
fixture.login();
|
||||
fixture.sessions(&["old_proxy"]);
|
||||
let report = fixture.check();
|
||||
assert!(report.can_repair);
|
||||
let result = repair_with_before_write(&fixture.0, &report.fingerprint, || {
|
||||
fs::remove_file(auth_path(&fixture.0)).unwrap();
|
||||
});
|
||||
assert!(result.is_err());
|
||||
assert_eq!(fixture.text(), original);
|
||||
fixture.login();
|
||||
let report = fixture.check();
|
||||
let result = repair_with_before_write(&fixture.0, &report.fingerprint, || {
|
||||
fs::write(config_path(&fixture.0), "# external edit\n").unwrap();
|
||||
});
|
||||
assert!(result.is_err());
|
||||
assert_eq!(fixture.text(), "# external edit\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -141,6 +141,13 @@ pub(crate) fn report_failover_lifecycle_error(app: &tauri::AppHandle, title: &st
|
||||
|
||||
pub(crate) fn handle_run_event(app: &tauri::AppHandle, event: tauri::RunEvent) {
|
||||
if let tauri::RunEvent::ExitRequested { api, .. } = &event {
|
||||
if crate::app_update::defer_exit_during_installation() {
|
||||
// The installed bundle or updater handoff is being changed. A
|
||||
// normal Quit must not interrupt it; Windows marks its authorized
|
||||
// handoff before requesting process exit.
|
||||
api.prevent_exit();
|
||||
return;
|
||||
}
|
||||
if let Err(error) = crate::failover::shutdown_all() {
|
||||
// Keep the listener alive when restoring the direct route failed.
|
||||
// Exiting here would strand Codex on a local address with no server.
|
||||
@@ -149,7 +156,9 @@ pub(crate) fn handle_run_event(app: &tauri::AppHandle, event: tauri::RunEvent) {
|
||||
report_failover_lifecycle_error(
|
||||
app,
|
||||
"暂时无法退出 Codex-X",
|
||||
&format!("自动切换的连接配置还未恢复,Codex-X 将继续运行。\n\n{error}\n\n请检查配置文件是否被占用,再重试退出。"),
|
||||
&format!(
|
||||
"路由仍需保持可用,Codex-X 将继续运行。\n\n{error}\n\n请按提示处理后再退出。"
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
use super::config::{self, RoutingTuning, MAX_QUEUE, ROUTE_GENERATION_HEADER, ROUTE_TOKEN_HEADER};
|
||||
use super::native_official;
|
||||
use super::protocol::UpstreamApi;
|
||||
use super::proxy::{ProxyHandle, ProxyOptions, ProxyRoute, ProxySelectionEvent, ProxySnapshot};
|
||||
use crate::error::{CodexxError, Result};
|
||||
use crate::file_io::parse_toml_document;
|
||||
@@ -84,6 +85,8 @@ struct ProxyJournal {
|
||||
table_existed: bool,
|
||||
#[serde(default = "default_true")]
|
||||
providers_existed: bool,
|
||||
#[serde(default)]
|
||||
requires_conversion: bool,
|
||||
}
|
||||
|
||||
#[derive(Default, Clone, Serialize, Deserialize)]
|
||||
@@ -552,9 +555,8 @@ fn provider_models(provider: &SavedProvider) -> Vec<String> {
|
||||
}
|
||||
|
||||
fn route(provider: &SavedProvider) -> Result<ProxyRoute> {
|
||||
if provider.wire_api != "responses" {
|
||||
return Err(CodexxError::Config("需要支持 Responses 的供应商".into()));
|
||||
}
|
||||
let protocol =
|
||||
UpstreamApi::from_provider(provider.upstream_api.as_deref(), &provider.wire_api)?;
|
||||
let url = reqwest::Url::parse(provider.base_url.trim())
|
||||
.map_err(|_| CodexxError::Config("供应商地址无效".into()))?;
|
||||
if !matches!(url.scheme(), "http" | "https")
|
||||
@@ -624,9 +626,6 @@ fn route(provider: &SavedProvider) -> Result<ProxyRoute> {
|
||||
);
|
||||
}
|
||||
}
|
||||
if provider.requires_openai_auth && api_key.is_none() {
|
||||
return Err(CodexxError::Config("请先填写该供应商的 API Key".into()));
|
||||
}
|
||||
if let Some(key) = &api_key {
|
||||
reqwest::header::HeaderValue::from_str(&format!("Bearer {key}"))
|
||||
.map_err(|_| CodexxError::Config("供应商 API Key 格式不正确".into()))?;
|
||||
@@ -643,7 +642,6 @@ fn route(provider: &SavedProvider) -> Result<ProxyRoute> {
|
||||
| "content-length"
|
||||
| "transfer-encoding"
|
||||
| "cookie"
|
||||
| "authorization"
|
||||
| "proxy-authorization"
|
||||
| "origin"
|
||||
) {
|
||||
@@ -670,7 +668,21 @@ fn route(provider: &SavedProvider) -> Result<ProxyRoute> {
|
||||
}
|
||||
}
|
||||
}
|
||||
if provider.requires_openai_auth
|
||||
&& api_key.is_none()
|
||||
&& !headers.iter().any(|(name, _)| {
|
||||
matches!(
|
||||
name.to_ascii_lowercase().as_str(),
|
||||
"authorization" | "x-api-key" | "x-goog-api-key"
|
||||
)
|
||||
})
|
||||
{
|
||||
return Err(CodexxError::Config(
|
||||
"请先填写该供应商的 API Key 或认证请求头".into(),
|
||||
));
|
||||
}
|
||||
Ok(ProxyRoute {
|
||||
protocol,
|
||||
official: None,
|
||||
id: provider.id.clone(),
|
||||
name: provider.provider_name.clone(),
|
||||
@@ -900,6 +912,7 @@ fn attach_route(dir: &Path, record: &mut Record, runtime: &mut Running) -> Resul
|
||||
official: primary.official.is_some(),
|
||||
table_existed: original.is_some(),
|
||||
providers_existed: direct.get("model_providers").is_some(),
|
||||
requires_conversion: primary.protocol.requires_routing(),
|
||||
};
|
||||
replace_table(
|
||||
&mut direct,
|
||||
@@ -1155,7 +1168,10 @@ pub(crate) fn get_status(config_dir: Option<String>) -> Result<FailoverStatus> {
|
||||
let dir = directory(config_dir)?;
|
||||
let mut runtimes = lock_manager()?;
|
||||
let mut record = load_record(&dir)?;
|
||||
if let Some(runtime) = runtimes.get_mut(&dir) {
|
||||
if let Some(runtime) = runtimes
|
||||
.get_mut(&dir)
|
||||
.filter(|_| !SHUTTING_DOWN.load(Ordering::Acquire))
|
||||
{
|
||||
inspect_external_change(&dir, &mut record, runtime)?;
|
||||
}
|
||||
status_locked(&dir, record, runtimes.get(&dir))
|
||||
@@ -1177,6 +1193,14 @@ pub(crate) fn save_settings(
|
||||
if let Some(runtime) = runtimes.get_mut(&dir) {
|
||||
inspect_external_change(&dir, &mut old, runtime)?;
|
||||
}
|
||||
if (!settings.router_enabled || !settings.takeover_enabled)
|
||||
&& runtimes
|
||||
.get(&dir)
|
||||
.and_then(|runtime| runtime.journal.as_ref())
|
||||
.is_some_and(|journal| journal.requires_conversion)
|
||||
{
|
||||
return Err(CodexxError::Config("当前供应商需要协议转换。请先切换到 Responses 供应商或官方账号,再关闭 Codex 接管或路由服务。".into()));
|
||||
}
|
||||
if let Some(runtime) = runtimes.get(&dir) {
|
||||
if settings.router_enabled
|
||||
&& (config::listen_ip(&settings.listen_address)? != runtime.proxy.listen_address()
|
||||
@@ -1289,27 +1313,47 @@ pub(crate) fn with_provider_change<T>(
|
||||
) -> Result<T> {
|
||||
let dir = directory(config_dir)?;
|
||||
let mut runtimes = lock_manager()?;
|
||||
if SHUTTING_DOWN.load(Ordering::Acquire) {
|
||||
return Err(CodexxError::Config(
|
||||
"Codex-X 正在退出或交接更新,未更改供应商配置".into(),
|
||||
));
|
||||
}
|
||||
let mut record = load_record(&dir)?;
|
||||
let Some(runtime) = runtimes.get_mut(&dir) else {
|
||||
drop(runtimes);
|
||||
recover_stale_route(Some(dir.display().to_string()))?;
|
||||
// A converted stale route cannot be restored to a supplier's raw URL.
|
||||
// The explicit provider action can replace it with a new valid route.
|
||||
if !record
|
||||
.journals
|
||||
.iter()
|
||||
.any(|journal| journal.requires_conversion)
|
||||
{
|
||||
recover_stale_route(Some(dir.display().to_string()))?;
|
||||
}
|
||||
return action();
|
||||
};
|
||||
let reconnect = runtime.journal.is_some() && record.settings.takeover_enabled;
|
||||
let checkpoint = FileCheckpoint::capture(&dir)?;
|
||||
let old_record = record.clone();
|
||||
let old_journal = runtime.journal.clone();
|
||||
let old_routes = runtime.routes.clone();
|
||||
let old_options = runtime.options.clone();
|
||||
if reconnect {
|
||||
detach_route(&dir, &record, runtime)?;
|
||||
}
|
||||
let result = action();
|
||||
if reconnect {
|
||||
if let Err(error) = attach_route(&dir, &mut record, runtime) {
|
||||
record.settings.takeover_enabled = false;
|
||||
record.message = Some(format!(
|
||||
"供应商操作已结束,但重新接管失败;当前使用直连:{error}"
|
||||
));
|
||||
save_record(&dir, &record)?;
|
||||
let expected = FileCheckpoint::capture(&dir)?;
|
||||
checkpoint.restore(&dir, &expected)?;
|
||||
save_record(&dir, &old_record)?;
|
||||
runtime.journal = old_journal;
|
||||
update_runtime(runtime, old_routes, old_options)?;
|
||||
changed(&dir);
|
||||
return match result {
|
||||
Ok(_) => Err(CodexxError::Config(record.message.unwrap())),
|
||||
Ok(_) => Err(CodexxError::Config(format!(
|
||||
"供应商重新接管失败,已恢复原配置和路由:{error}"
|
||||
))),
|
||||
Err(original) => Err(original),
|
||||
};
|
||||
}
|
||||
@@ -1318,11 +1362,53 @@ pub(crate) fn with_provider_change<T>(
|
||||
result
|
||||
}
|
||||
|
||||
/// Call at the IPC boundary before with_provider_change acquires the manager
|
||||
/// lock. Internal P1/failover changes already run under validated takeover.
|
||||
pub(crate) fn ensure_conversion_route(
|
||||
config_dir: Option<String>,
|
||||
provider: &SavedProvider,
|
||||
) -> Result<()> {
|
||||
let conversion =
|
||||
UpstreamApi::from_provider(provider.upstream_api.as_deref(), &provider.wire_api)?
|
||||
.requires_routing();
|
||||
let dir = directory(config_dir)?;
|
||||
let runtimes = lock_manager()?;
|
||||
let record = load_record(&dir)?;
|
||||
if runtimes
|
||||
.get(&dir)
|
||||
.is_some_and(|runtime| runtime.journal.is_some())
|
||||
{
|
||||
route(provider)?;
|
||||
}
|
||||
if !conversion {
|
||||
return Ok(());
|
||||
}
|
||||
if !record.settings.router_enabled
|
||||
|| !record.settings.takeover_enabled
|
||||
|| runtimes
|
||||
.get(&dir)
|
||||
.is_none_or(|runtime| runtime.journal.is_none())
|
||||
{
|
||||
return Err(CodexxError::Config(
|
||||
"该供应商需要协议转换。请先开启路由总开关和 Codex 请求接管,再启用该供应商。".into(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn recover_stale_route(config_dir: Option<String>) -> Result<()> {
|
||||
let dir = directory(config_dir)?;
|
||||
let record = load_record(&dir)?;
|
||||
if dir.exists() && !record.journals.is_empty() {
|
||||
let _guard = acquire_live_config_lock(&dir)?;
|
||||
let doc = read_document(&dir)?.1;
|
||||
if record
|
||||
.journals
|
||||
.iter()
|
||||
.any(|journal| journal.requires_conversion && owned_route(&doc, journal))
|
||||
{
|
||||
return Err(CodexxError::Config("当前供应商需要协议转换,不能恢复为直连。请重新启动路由服务,或切换到 Responses 供应商/官方账号。".into()));
|
||||
}
|
||||
restore_owned_locked(&dir, &record)?;
|
||||
}
|
||||
Ok(())
|
||||
@@ -1337,6 +1423,16 @@ fn refresh_routes_locked(dir: &Path, record: &mut Record, runtime: &mut Running)
|
||||
{
|
||||
Ok(()) => Ok(()),
|
||||
Err(error) => {
|
||||
if runtime
|
||||
.journal
|
||||
.as_ref()
|
||||
.is_some_and(|journal| journal.requires_conversion)
|
||||
{
|
||||
record.message=Some(format!("协议转换供应商配置不可用,已保留原路由;请修正配置或切换到 Responses 供应商:{error}"));
|
||||
save_record(dir, record)?;
|
||||
changed(dir);
|
||||
return Ok(());
|
||||
}
|
||||
detach_route(dir, record, runtime)?;
|
||||
record.settings.takeover_enabled = false;
|
||||
record.message = Some(format!("当前供应商配置不可用,已恢复直连:{error}"));
|
||||
@@ -1348,6 +1444,11 @@ fn refresh_routes_locked(dir: &Path, record: &mut Record, runtime: &mut Running)
|
||||
}
|
||||
pub(crate) fn refresh_saved_routes() -> Result<()> {
|
||||
let mut runtimes = lock_manager()?;
|
||||
if SHUTTING_DOWN.load(Ordering::Acquire) {
|
||||
return Err(CodexxError::Config(
|
||||
"Codex-X 正在退出或交接更新,未更改路由配置".into(),
|
||||
));
|
||||
}
|
||||
for (dir, runtime) in runtimes.iter_mut() {
|
||||
let mut record = load_record(dir)?;
|
||||
refresh_routes_locked(dir, &mut record, runtime)?;
|
||||
@@ -1370,6 +1471,9 @@ fn record_selection(
|
||||
notice: SelectionNotice,
|
||||
runtimes: &mut HashMap<PathBuf, Running>,
|
||||
) -> Result<()> {
|
||||
if SHUTTING_DOWN.load(Ordering::Acquire) {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(runtime) = runtimes.get_mut(¬ice.dir) else {
|
||||
return Ok(());
|
||||
};
|
||||
@@ -1425,6 +1529,9 @@ fn record_selection(
|
||||
*original.as_table_mut() = table;
|
||||
let mut next = journal.clone();
|
||||
next.primary_id = provider.id.clone();
|
||||
next.requires_conversion =
|
||||
UpstreamApi::from_provider(provider.upstream_api.as_deref(), &provider.wire_api)?
|
||||
.requires_routing();
|
||||
next.original_table = original.to_string();
|
||||
next.lease_id = Some(random_token()?);
|
||||
let _guard = acquire_live_config_lock(¬ice.dir)?;
|
||||
@@ -1486,8 +1593,14 @@ fn stored_directories() -> Result<Vec<PathBuf>> {
|
||||
.query_map([], |row| row.get::<_, String>(0))
|
||||
.map_err(|e| CodexxError::Database(e.to_string()))?
|
||||
.map(|row| {
|
||||
row.map(PathBuf::from)
|
||||
.map_err(|e| CodexxError::Database(e.to_string()))
|
||||
let scope = row.map_err(|e| CodexxError::Database(e.to_string()))?;
|
||||
// Database scopes use lowercase forward slashes on Windows. They
|
||||
// are comparison keys, not the canonical native paths used by the
|
||||
// running-instance map (including Windows' verbatim \\?\ prefix).
|
||||
// Rehydrate using the same path resolution as interactive IPC.
|
||||
#[cfg(target_os = "windows")]
|
||||
let scope = scope.replace('/', "\\");
|
||||
directory(Some(scope))
|
||||
})
|
||||
.collect();
|
||||
paths
|
||||
@@ -1500,7 +1613,16 @@ pub(crate) fn initialize() -> Result<()> {
|
||||
}
|
||||
let mut record = load_record(&dir)?;
|
||||
let desired = record.settings.takeover_enabled;
|
||||
if !record.journals.is_empty() && dir.exists() {
|
||||
let converted_owned = if dir.exists() {
|
||||
let doc = read_document(&dir)?.1;
|
||||
record
|
||||
.journals
|
||||
.iter()
|
||||
.any(|journal| journal.requires_conversion && owned_route(&doc, journal))
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if !converted_owned && !record.journals.is_empty() && dir.exists() {
|
||||
let _guard = acquire_live_config_lock(&dir)?;
|
||||
restore_owned_locked(&dir, &record)?;
|
||||
}
|
||||
@@ -1512,6 +1634,11 @@ pub(crate) fn initialize() -> Result<()> {
|
||||
match normalized_settings(record.settings.clone()) {
|
||||
Ok(settings) => record.settings = settings,
|
||||
Err(error) => {
|
||||
if converted_owned {
|
||||
record.message=Some(format!("协议转换路由无法启动,已保留本地接管配置;请检查端口或切换到 Responses 供应商:{error}"));
|
||||
save_record(&dir, &record)?;
|
||||
continue;
|
||||
}
|
||||
record.settings.router_enabled = false;
|
||||
record.settings.takeover_enabled = false;
|
||||
record.message = Some(format!("路由设置需要检查,当前使用直连:{error}"));
|
||||
@@ -1542,6 +1669,11 @@ pub(crate) fn initialize() -> Result<()> {
|
||||
saved?;
|
||||
}
|
||||
Err(error) => {
|
||||
if converted_owned {
|
||||
record.message=Some(format!("协议转换路由无法启动,已保留本地接管配置;请检查端口或切换到 Responses 供应商:{error}"));
|
||||
save_record(&dir, &record)?;
|
||||
continue;
|
||||
}
|
||||
record.settings.router_enabled = false;
|
||||
record.settings.takeover_enabled = false;
|
||||
record.message = Some(format!("路由未启动,当前使用直连:{error}"));
|
||||
@@ -1561,6 +1693,9 @@ fn ensure_watcher() {
|
||||
let Ok(mut runtimes) = lock_manager() else {
|
||||
continue;
|
||||
};
|
||||
if SHUTTING_DOWN.load(Ordering::Acquire) {
|
||||
continue;
|
||||
}
|
||||
let events: Vec<_> = notices()
|
||||
.1
|
||||
.lock()
|
||||
@@ -1586,17 +1721,82 @@ fn ensure_watcher() {
|
||||
});
|
||||
});
|
||||
}
|
||||
fn shutdown_allowed_locked(runtimes: &HashMap<PathBuf, Running>) -> Result<()> {
|
||||
for (dir, runtime) in runtimes {
|
||||
let Some(journal) = runtime.journal.as_ref() else {
|
||||
continue;
|
||||
};
|
||||
let doc = read_document(dir)?.1;
|
||||
if journal.requires_conversion && owned_route(&doc, journal) {
|
||||
let record = load_record(dir)?;
|
||||
let persisted=record.journals.iter().find(|saved| saved.requires_conversion && saved.primary_id==journal.primary_id && saved.provider_key==journal.provider_key && saved.token==journal.token && saved.lease_id==journal.lease_id && owned_route(&doc,saved))
|
||||
.ok_or_else(||CodexxError::Config("转换路由的恢复记录缺失,服务继续运行;请重新启用 Codex 接管后重试退出或更新。".into()))?;
|
||||
original_table(persisted)?;
|
||||
} else if !journal.requires_conversion {
|
||||
// Validate the existing native restore projection without writing.
|
||||
restored_document(&doc, journal)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Read-only check for exit/update callers before they modify the application.
|
||||
pub(crate) fn ensure_shutdown_allowed() -> Result<()> {
|
||||
let runtimes = lock_manager()?;
|
||||
shutdown_allowed_locked(&runtimes)
|
||||
}
|
||||
|
||||
/// Freeze configuration mutations during an update while keeping active
|
||||
/// requests and the listener alive until the installer needs the process exit.
|
||||
pub(crate) fn begin_update_handoff() -> Result<()> {
|
||||
let runtimes = lock_manager()?;
|
||||
shutdown_allowed_locked(&runtimes)?;
|
||||
SHUTTING_DOWN.store(true, Ordering::Release);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn shutdown_all() -> Result<()> {
|
||||
SHUTTING_DOWN.store(true, Ordering::Release);
|
||||
let result = (|| -> Result<()> {
|
||||
let mut runtimes = lock_manager()?;
|
||||
shutdown_allowed_locked(&runtimes)?;
|
||||
let dirs: Vec<_> = runtimes.keys().cloned().collect();
|
||||
for dir in dirs {
|
||||
let record = load_record(&dir)?;
|
||||
let mut record = load_record(&dir)?;
|
||||
if let Some(runtime) = runtimes.get_mut(&dir) {
|
||||
detach_route(&dir, &record, runtime)?;
|
||||
if let Some(journal) = runtime
|
||||
.journal
|
||||
.as_ref()
|
||||
.filter(|journal| journal.requires_conversion)
|
||||
{
|
||||
let previous_settings = record.settings.clone();
|
||||
let previous_message = record.message.clone();
|
||||
let doc = read_document(&dir)?.1;
|
||||
if !selected_owned_route(&doc, journal) {
|
||||
// An explicit external selection is kept exactly as it
|
||||
// is; the next launch must not take it over implicitly.
|
||||
record.settings.takeover_enabled = false;
|
||||
record.message = Some(
|
||||
"退出时检测到外部供应商配置,已原样保留;下次启动不会自动接管该配置。"
|
||||
.into(),
|
||||
);
|
||||
} else {
|
||||
record.settings.router_enabled = true;
|
||||
record.settings.takeover_enabled = true;
|
||||
record.settings.listen_address = runtime.proxy.listen_address().to_string();
|
||||
record.settings.listen_port = runtime.proxy.port();
|
||||
}
|
||||
if record.settings != previous_settings || record.message != previous_message {
|
||||
save_record(&dir, &record)?;
|
||||
}
|
||||
// Keep the owned loopback overlay and recovery journal.
|
||||
// initialize reconnects it on the next app launch. Restoring
|
||||
// this supplier's raw URL would send an invalid /responses.
|
||||
} else {
|
||||
detach_route(&dir, &record, runtime)?;
|
||||
}
|
||||
}
|
||||
// Keep desired settings for next launch; restore first, stop last.
|
||||
// All required writes/validation finish before stopping a listener.
|
||||
if let Some(runtime) = runtimes.remove(&dir) {
|
||||
runtime.proxy.shutdown();
|
||||
}
|
||||
@@ -1609,6 +1809,46 @@ pub(crate) fn shutdown_all() -> Result<()> {
|
||||
result
|
||||
}
|
||||
|
||||
/// Only an update handoff that has not launched an installer may resume the
|
||||
/// saved routes. A successful handoff keeps the shutdown gate closed until exit.
|
||||
pub(crate) fn resume_after_failed_update() -> Result<()> {
|
||||
SHUTTING_DOWN.store(false, Ordering::Release);
|
||||
let expected: Vec<_> = stored_directories()?
|
||||
.into_iter()
|
||||
.map(|dir| load_record(&dir).map(|record| (dir, record.settings)))
|
||||
.collect::<Result<_>>()?;
|
||||
let initialized = initialize();
|
||||
let runtimes = lock_manager()?;
|
||||
let mut recovered = initialized.is_ok();
|
||||
for (dir, settings) in expected {
|
||||
if !settings.router_enabled {
|
||||
continue;
|
||||
}
|
||||
let active = runtimes.get(&dir);
|
||||
let restored = active.is_some()
|
||||
&& (!settings.takeover_enabled
|
||||
|| active.is_some_and(|runtime| runtime.journal.is_some()));
|
||||
if !restored {
|
||||
recovered = false;
|
||||
// Startup is allowed to degrade to direct mode. An unsuccessful
|
||||
// update must not silently turn the user's saved preferences off.
|
||||
let mut record = load_record(&dir)?;
|
||||
record.settings = settings;
|
||||
record.message = Some(
|
||||
"更新未启动,原路由暂时无法恢复;设置已保留,请检查端口或配置后重新启用。".into(),
|
||||
);
|
||||
save_record(&dir, &record)?;
|
||||
changed(&dir);
|
||||
}
|
||||
}
|
||||
initialized?;
|
||||
if recovered {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(CodexxError::Config("更新未启动,部分路由尚未恢复".into()))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "tests.rs"]
|
||||
mod tests;
|
||||
|
||||
@@ -2,10 +2,14 @@ mod circuit_breaker;
|
||||
pub(crate) mod config;
|
||||
mod controller;
|
||||
pub(crate) mod native_official;
|
||||
pub(crate) mod protocol;
|
||||
mod proxy;
|
||||
|
||||
pub(crate) use controller::resume_after_failed_update;
|
||||
|
||||
pub(crate) use controller::{
|
||||
attach_app_handle, direct_document, get_status, initialize, recover_stale_route,
|
||||
refresh_saved_routes, reset_health, save_settings, shutdown_all, with_provider_change,
|
||||
FailoverSettings, FailoverStatus,
|
||||
attach_app_handle, begin_update_handoff, direct_document, ensure_conversion_route,
|
||||
ensure_shutdown_allowed, get_status, initialize, recover_stale_route, refresh_saved_routes,
|
||||
reset_health, save_settings, shutdown_all, with_provider_change, FailoverSettings,
|
||||
FailoverStatus,
|
||||
};
|
||||
|
||||
@@ -182,6 +182,7 @@ pub(crate) fn route_for_current(dir: &Path) -> Result<Option<ProxyRoute>> {
|
||||
.into_iter()
|
||||
.collect::<HashSet<_>>();
|
||||
Ok(Some(ProxyRoute {
|
||||
protocol: super::protocol::UpstreamApi::Responses,
|
||||
id: format!("official:{profile_id}"),
|
||||
name,
|
||||
base_url,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,455 @@
|
||||
use super::{encode_thinking, ToolContext, UpstreamApi};
|
||||
use serde_json::{json, Value};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
pub(crate) fn error_message(value: &Value) -> Option<String> {
|
||||
let error = value.get("error").filter(|v| !v.is_null()).or_else(|| {
|
||||
(value.get("type").and_then(Value::as_str) == Some("error")).then_some(value)
|
||||
})?;
|
||||
Some(
|
||||
error
|
||||
.as_str()
|
||||
.map(str::to_owned)
|
||||
.or_else(|| {
|
||||
error
|
||||
.get("message")
|
||||
.or_else(|| error.get("detail"))
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_owned)
|
||||
})
|
||||
.unwrap_or_else(|| error.to_string()),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn convert_response(
|
||||
api: UpstreamApi,
|
||||
body: &Value,
|
||||
context: &ToolContext,
|
||||
requested_model: &str,
|
||||
) -> std::result::Result<Value, String> {
|
||||
if let Some(error) = error_message(body) {
|
||||
return Err(error);
|
||||
}
|
||||
match api {
|
||||
UpstreamApi::Responses => Ok(body.clone()),
|
||||
UpstreamApi::ChatCompletions => chat_response(body, context, requested_model),
|
||||
UpstreamApi::AnthropicMessages => anthropic_response(body, context, requested_model),
|
||||
UpstreamApi::Gemini => gemini_response(body, context, requested_model),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn response_id(id: Option<&str>) -> String {
|
||||
if let Some(id) = id.filter(|s| !s.is_empty()) {
|
||||
let digest = Sha256::digest(id.as_bytes());
|
||||
return format!(
|
||||
"resp_codexx_{}",
|
||||
digest
|
||||
.iter()
|
||||
.take(12)
|
||||
.map(|b| format!("{b:02x}"))
|
||||
.collect::<String>()
|
||||
);
|
||||
}
|
||||
format!(
|
||||
"resp_codexx_{}",
|
||||
chrono::Utc::now().timestamp_nanos_opt().unwrap_or_default()
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn envelope(
|
||||
id: &str,
|
||||
model: &str,
|
||||
status: &str,
|
||||
output: Vec<Value>,
|
||||
usage: Value,
|
||||
reason: Option<&str>,
|
||||
) -> Value {
|
||||
let mut value = json!({"id":id,"object":"response","created_at":chrono::Utc::now().timestamp(),"model":model,"status":status,"output":output,"usage":usage,"error":null,"incomplete_details":null});
|
||||
if let Some(reason) = reason {
|
||||
value["incomplete_details"] = json!({"reason":reason});
|
||||
}
|
||||
value
|
||||
}
|
||||
|
||||
pub(super) fn text_item(id: &str, text: &str) -> Value {
|
||||
json!({"id":id,"type":"message","role":"assistant","status":"completed","content":[{"type":"output_text","text":text,"annotations":[]}]})
|
||||
}
|
||||
|
||||
pub(super) fn reasoning_item(id: &str, text: &str, state: Option<Value>) -> Value {
|
||||
let mut value = json!({"id":id,"type":"reasoning","summary":if text.is_empty(){json!([])}else{json!([{"type":"summary_text","text":text}])}});
|
||||
if let Some(state) = state {
|
||||
value["encrypted_content"] = json!(encode_thinking(&state));
|
||||
}
|
||||
value
|
||||
}
|
||||
|
||||
pub(super) fn tool_item(
|
||||
context: &ToolContext,
|
||||
id: &str,
|
||||
call_id: &str,
|
||||
upstream_name: &str,
|
||||
arguments: &str,
|
||||
) -> std::result::Result<Value, String> {
|
||||
if upstream_name.is_empty() {
|
||||
return Err("上游工具调用缺少名称".into());
|
||||
}
|
||||
let spec = context.names.get(upstream_name);
|
||||
let mut value = if spec.is_some_and(|s| s.custom) {
|
||||
let arguments: Value =
|
||||
serde_json::from_str(arguments).map_err(|_| "上游 custom 工具参数不是有效的 JSON")?;
|
||||
let input = arguments
|
||||
.get("input")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or("上游 custom 工具参数缺少 input 文字")?;
|
||||
json!({"id":id,"type":"custom_tool_call","call_id":call_id,"name":spec.unwrap().name,"input":input,"status":"completed"})
|
||||
} else {
|
||||
let parsed: Value =
|
||||
serde_json::from_str(arguments).map_err(|_| "上游工具参数不是有效的 JSON")?;
|
||||
if !parsed.is_object() {
|
||||
return Err("上游工具参数须是 JSON 对象".into());
|
||||
}
|
||||
json!({"id":id,"type":"function_call","call_id":call_id,"name":spec.map_or(upstream_name,|s|s.name.as_str()),"arguments":arguments,"status":"completed"})
|
||||
};
|
||||
if let Some(namespace) = spec.and_then(|s| s.namespace.as_deref()) {
|
||||
value["namespace"] = json!(namespace);
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
pub(super) fn terminal(
|
||||
api: UpstreamApi,
|
||||
reason: Option<&str>,
|
||||
) -> (&'static str, Option<&'static str>) {
|
||||
match (api, reason) {
|
||||
(_, Some("length" | "max_tokens" | "MAX_TOKENS" | "model_context_window_exceeded")) => {
|
||||
("incomplete", Some("max_output_tokens"))
|
||||
}
|
||||
(
|
||||
_,
|
||||
Some(
|
||||
"content_filter" | "refusal" | "SAFETY" | "BLOCKLIST" | "PROHIBITED_CONTENT"
|
||||
| "RECITATION" | "SPII" | "IMAGE_SAFETY",
|
||||
),
|
||||
) => ("incomplete", Some("content_filter")),
|
||||
(_, Some("MALFORMED_FUNCTION_CALL" | "UNEXPECTED_TOOL_CALL")) => {
|
||||
("incomplete", Some("tool_call_error"))
|
||||
}
|
||||
_ => ("completed", None),
|
||||
}
|
||||
}
|
||||
|
||||
fn tokens(value: Option<&Value>) -> u64 {
|
||||
value.and_then(Value::as_u64).unwrap_or(0)
|
||||
}
|
||||
pub(super) fn usage(api: UpstreamApi, value: Option<&Value>) -> Value {
|
||||
let empty = json!({});
|
||||
let u = value.unwrap_or(&empty);
|
||||
let (input, output, cached, reasoning, write) = match api {
|
||||
UpstreamApi::ChatCompletions => (
|
||||
tokens(u.get("prompt_tokens")),
|
||||
tokens(u.get("completion_tokens")),
|
||||
tokens(u.pointer("/prompt_tokens_details/cached_tokens"))
|
||||
.max(tokens(u.get("prompt_cache_hit_tokens"))),
|
||||
tokens(u.pointer("/completion_tokens_details/reasoning_tokens")),
|
||||
tokens(u.get("cache_creation_input_tokens")),
|
||||
),
|
||||
UpstreamApi::AnthropicMessages => {
|
||||
let cached = tokens(u.get("cache_read_input_tokens"));
|
||||
let write = tokens(u.get("cache_creation_input_tokens"));
|
||||
(
|
||||
tokens(u.get("input_tokens"))
|
||||
.saturating_add(cached)
|
||||
.saturating_add(write),
|
||||
tokens(u.get("output_tokens")),
|
||||
cached,
|
||||
tokens(u.get("thinking_tokens")),
|
||||
write,
|
||||
)
|
||||
}
|
||||
UpstreamApi::Gemini => {
|
||||
let reasoning = tokens(u.get("thoughtsTokenCount"));
|
||||
(
|
||||
tokens(u.get("promptTokenCount")),
|
||||
tokens(u.get("candidatesTokenCount")).saturating_add(reasoning),
|
||||
tokens(u.get("cachedContentTokenCount")),
|
||||
reasoning,
|
||||
0,
|
||||
)
|
||||
}
|
||||
UpstreamApi::Responses => return u.clone(),
|
||||
};
|
||||
json!({"input_tokens":input,"output_tokens":output,"total_tokens":input.saturating_add(output),"input_tokens_details":{"cached_tokens":cached,"cache_write_tokens":write},"output_tokens_details":{"reasoning_tokens":reasoning}})
|
||||
}
|
||||
|
||||
fn chat_response(
|
||||
body: &Value,
|
||||
context: &ToolContext,
|
||||
model: &str,
|
||||
) -> std::result::Result<Value, String> {
|
||||
let choice = body
|
||||
.get("choices")
|
||||
.and_then(Value::as_array)
|
||||
.and_then(|v| v.first())
|
||||
.ok_or("Chat 响应缺少 choices")?;
|
||||
let message = choice.get("message").ok_or("Chat 响应缺少 message")?;
|
||||
let id = response_id(body.get("id").and_then(Value::as_str));
|
||||
let mut output = Vec::new();
|
||||
if let Some(thinking) = chat_reasoning(message) {
|
||||
output.push(reasoning_item(&format!("rs_{id}"), &thinking, None));
|
||||
}
|
||||
let text = match message.get("content") {
|
||||
Some(Value::String(text)) => text.clone(),
|
||||
Some(Value::Array(parts)) => {
|
||||
let mut text = String::new();
|
||||
for part in parts {
|
||||
if matches!(
|
||||
part.get("type").and_then(Value::as_str),
|
||||
Some("text" | "output_text")
|
||||
) {
|
||||
text.push_str(
|
||||
part.get("text")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or("Chat 文字内容缺少 text")?,
|
||||
);
|
||||
} else {
|
||||
return Err("Chat 响应含不能转换的非文字内容".into());
|
||||
}
|
||||
}
|
||||
text
|
||||
}
|
||||
_ => String::new(),
|
||||
};
|
||||
if !text.is_empty() {
|
||||
output.push(text_item(&format!("msg_{id}"), &text));
|
||||
}
|
||||
if let Some(refusal) = message.get("refusal").and_then(Value::as_str) {
|
||||
output.push(json!({"id":format!("msg_refusal_{id}"),"type":"message","role":"assistant","status":"completed","content":[{"type":"refusal","refusal":refusal}]}));
|
||||
}
|
||||
if let Some(calls) = message.get("tool_calls").and_then(Value::as_array) {
|
||||
for (index, call) in calls.iter().enumerate() {
|
||||
let function = call.get("function").ok_or("Chat 工具调用缺少 function")?;
|
||||
let call_id = call
|
||||
.get("id")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_owned)
|
||||
.unwrap_or_else(|| format!("call_{id}_{index}"));
|
||||
output.push(tool_item(
|
||||
context,
|
||||
&format!("fc_{id}_{index}"),
|
||||
&call_id,
|
||||
function.get("name").and_then(Value::as_str).unwrap_or(""),
|
||||
function
|
||||
.get("arguments")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("{}"),
|
||||
)?);
|
||||
}
|
||||
}
|
||||
if let Some(call) = message.get("function_call") {
|
||||
output.push(tool_item(
|
||||
context,
|
||||
&format!("fc_{id}_legacy"),
|
||||
&format!("call_{id}_legacy"),
|
||||
call.get("name").and_then(Value::as_str).unwrap_or(""),
|
||||
call.get("arguments")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("{}"),
|
||||
)?);
|
||||
}
|
||||
let reason = choice
|
||||
.get("finish_reason")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or("Chat 响应缺少 finish_reason,无法确认完整完成")?;
|
||||
let (status, incomplete) = terminal(UpstreamApi::ChatCompletions, Some(reason));
|
||||
Ok(envelope(
|
||||
&id,
|
||||
body.get("model").and_then(Value::as_str).unwrap_or(model),
|
||||
status,
|
||||
output,
|
||||
usage(UpstreamApi::ChatCompletions, body.get("usage")),
|
||||
incomplete,
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) fn chat_reasoning(value: &Value) -> Option<String> {
|
||||
value
|
||||
.get("reasoning_content")
|
||||
.or_else(|| value.get("reasoning"))
|
||||
.and_then(|v| match v {
|
||||
Value::String(s) if !s.is_empty() => Some(s.clone()),
|
||||
Value::Array(items) => Some(
|
||||
items
|
||||
.iter()
|
||||
.filter_map(|v| v.get("text").and_then(Value::as_str))
|
||||
.collect::<Vec<_>>()
|
||||
.join(""),
|
||||
),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn anthropic_response(
|
||||
body: &Value,
|
||||
context: &ToolContext,
|
||||
model: &str,
|
||||
) -> std::result::Result<Value, String> {
|
||||
let blocks = body
|
||||
.get("content")
|
||||
.and_then(Value::as_array)
|
||||
.ok_or("Anthropic 响应缺少 content")?;
|
||||
let id = response_id(body.get("id").and_then(Value::as_str));
|
||||
let mut output = Vec::new();
|
||||
for (index, block) in blocks.iter().enumerate() {
|
||||
match block.get("type").and_then(Value::as_str) {
|
||||
Some("text") => output.push(text_item(
|
||||
&format!("msg_{id}_{index}"),
|
||||
block.get("text").and_then(Value::as_str).unwrap_or(""),
|
||||
)),
|
||||
Some("thinking" | "redacted_thinking") => output.push(reasoning_item(
|
||||
&format!("rs_{id}_{index}"),
|
||||
block.get("thinking").and_then(Value::as_str).unwrap_or(""),
|
||||
Some(json!({"protocol":"anthropic","block":block})),
|
||||
)),
|
||||
Some("tool_use") => {
|
||||
let call_id = block
|
||||
.get("id")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or("Anthropic tool_use 缺少 id")?;
|
||||
output.push(tool_item(
|
||||
context,
|
||||
&format!("fc_{id}_{index}"),
|
||||
call_id,
|
||||
block.get("name").and_then(Value::as_str).unwrap_or(""),
|
||||
&block
|
||||
.get("input")
|
||||
.cloned()
|
||||
.unwrap_or_else(|| json!({}))
|
||||
.to_string(),
|
||||
)?);
|
||||
}
|
||||
Some(other) => return Err(format!("无法转换 Anthropic 输出类型 {other}")),
|
||||
None => return Err("Anthropic content 缺少类型".into()),
|
||||
}
|
||||
}
|
||||
let reason = body
|
||||
.get("stop_reason")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or("Anthropic 响应缺少 stop_reason,无法确认完整完成")?;
|
||||
let (status, incomplete) = terminal(UpstreamApi::AnthropicMessages, Some(reason));
|
||||
Ok(envelope(
|
||||
&id,
|
||||
body.get("model").and_then(Value::as_str).unwrap_or(model),
|
||||
status,
|
||||
output,
|
||||
usage(UpstreamApi::AnthropicMessages, body.get("usage")),
|
||||
incomplete,
|
||||
))
|
||||
}
|
||||
|
||||
fn gemini_response(
|
||||
body: &Value,
|
||||
context: &ToolContext,
|
||||
model: &str,
|
||||
) -> std::result::Result<Value, String> {
|
||||
if let Some(block) = body
|
||||
.pointer("/promptFeedback/blockReason")
|
||||
.and_then(Value::as_str)
|
||||
{
|
||||
return Err(format!("Gemini 拒绝了输入:{block}"));
|
||||
}
|
||||
let candidate = body
|
||||
.get("candidates")
|
||||
.and_then(Value::as_array)
|
||||
.and_then(|v| v.first())
|
||||
.ok_or("Gemini 响应缺少 candidates")?;
|
||||
let parts = candidate
|
||||
.pointer("/content/parts")
|
||||
.and_then(Value::as_array);
|
||||
if context.single_tool
|
||||
&& parts
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|part| part.get("functionCall").is_some())
|
||||
.count()
|
||||
> 1
|
||||
{
|
||||
return Err("Gemini 返回了多个并行工具调用,而本次请求禁止并行;未向 Codex 返回任何可执行工具,请重试".into());
|
||||
}
|
||||
let id = response_id(body.get("responseId").and_then(Value::as_str));
|
||||
let mut output = Vec::new();
|
||||
let signed: Vec<Value> = parts
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.enumerate()
|
||||
.filter(|(_, part)| {
|
||||
part.get("thoughtSignature").is_some()
|
||||
&& part.get("thought").and_then(Value::as_bool) != Some(true)
|
||||
})
|
||||
.map(|(index, part)| {
|
||||
let mut part = part.clone();
|
||||
if part.get("text").is_some() {
|
||||
part["codex_item_id"] = json!(format!("msg_{id}_{index}"));
|
||||
}
|
||||
if part.get("functionCall").is_some() && part.pointer("/functionCall/id").is_none() {
|
||||
part["functionCall"]["id"] = json!(format!("call_{id}_{index}"));
|
||||
}
|
||||
part
|
||||
})
|
||||
.collect();
|
||||
if !signed.is_empty() {
|
||||
output.push(reasoning_item(
|
||||
&format!("rs_sig_{id}"),
|
||||
"",
|
||||
Some(json!({"protocol":"gemini","parts":signed})),
|
||||
));
|
||||
}
|
||||
for (index, part) in parts.into_iter().flatten().enumerate() {
|
||||
if let Some(text) = part.get("text").and_then(Value::as_str) {
|
||||
output.push(
|
||||
if part.get("thought").and_then(Value::as_bool) == Some(true) {
|
||||
reasoning_item(
|
||||
&format!("rs_{id}_{index}"),
|
||||
text,
|
||||
Some(json!({"protocol":"gemini","parts":[part]})),
|
||||
)
|
||||
} else {
|
||||
text_item(&format!("msg_{id}_{index}"), text)
|
||||
},
|
||||
);
|
||||
} else if let Some(call) = part.get("functionCall") {
|
||||
let call_id = call
|
||||
.get("id")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_owned)
|
||||
.unwrap_or_else(|| format!("call_{id}_{index}"));
|
||||
output.push(tool_item(
|
||||
context,
|
||||
&format!("fc_{id}_{index}"),
|
||||
&call_id,
|
||||
call.get("name").and_then(Value::as_str).unwrap_or(""),
|
||||
&call
|
||||
.get("args")
|
||||
.cloned()
|
||||
.unwrap_or_else(|| json!({}))
|
||||
.to_string(),
|
||||
)?);
|
||||
} else if part.get("thoughtSignature").is_none() {
|
||||
return Err("Gemini 返回了不能转换为 Codex 输出的多模态内容".into());
|
||||
}
|
||||
}
|
||||
let reason = candidate
|
||||
.get("finishReason")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or("Gemini 响应缺少 finishReason,无法确认完整完成")?;
|
||||
let (status, incomplete) = terminal(UpstreamApi::Gemini, Some(reason));
|
||||
Ok(envelope(
|
||||
&id,
|
||||
body.get("modelVersion")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or(model),
|
||||
status,
|
||||
output,
|
||||
usage(UpstreamApi::Gemini, body.get("usageMetadata")),
|
||||
incomplete,
|
||||
))
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,484 @@
|
||||
use super::*;
|
||||
use std::io::{self, Read};
|
||||
|
||||
fn prepared(api: UpstreamApi, body: Value) -> PreparedRequest {
|
||||
prepare(api, &serde_json::to_vec(&body).unwrap(), false).unwrap()
|
||||
}
|
||||
fn request(api: UpstreamApi, body: Value) -> Value {
|
||||
serde_json::from_slice(&prepared(api, body).bytes).unwrap()
|
||||
}
|
||||
fn events(text: &str) -> Vec<Value> {
|
||||
text.lines()
|
||||
.filter_map(|line| line.strip_prefix("data: "))
|
||||
.map(|line| serde_json::from_str(line).unwrap())
|
||||
.collect()
|
||||
}
|
||||
|
||||
struct ByteReader(Vec<u8>, usize);
|
||||
impl Read for ByteReader {
|
||||
fn read(&mut self, output: &mut [u8]) -> io::Result<usize> {
|
||||
if self.1 == self.0.len() {
|
||||
return Ok(0);
|
||||
}
|
||||
output[0] = self.0[self.1];
|
||||
self.1 += 1;
|
||||
Ok(1)
|
||||
}
|
||||
}
|
||||
fn streamed(api: UpstreamApi, input: &str, context: ToolContext) -> String {
|
||||
let mut reader = ResponseStream::new(
|
||||
ByteReader(input.as_bytes().to_vec(), 0),
|
||||
api,
|
||||
context,
|
||||
"fixture".into(),
|
||||
);
|
||||
let mut text = String::new();
|
||||
reader.read_to_string(&mut text).unwrap();
|
||||
text
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_conversions_preserve_roles_media_tools_and_parallel_results() {
|
||||
let body = json!({"model":"fixture","instructions":"system instruction","max_output_tokens":7000,"input":[
|
||||
{"role":"developer","content":"developer instruction"},
|
||||
{"role":"user","content":[{"type":"input_text","text":"inspect this"},{"type":"input_image","image_url":"data:image/png;base64,aGVsbG8="}]},
|
||||
{"type":"function_call","call_id":"call-1","namespace":"functions","name":"read","arguments":"{\"path\":\"x\"}"},
|
||||
{"type":"custom_tool_call","call_id":"call-2","name":"apply_patch","input":"*** Begin Patch\n*** End Patch"},
|
||||
{"type":"function_call_output","call_id":"call-1","output":"file text"},
|
||||
{"type":"custom_tool_call_output","call_id":"call-2","output":[{"type":"input_text","text":"patched"},{"type":"input_image","image_url":"data:image/png;base64,aGVsbG8="}]}
|
||||
],"tools":[{"type":"namespace","name":"functions","tools":[{"type":"function","name":"read","parameters":{"type":"object","properties":{"path":{"type":"string"}}}}]},{"type":"custom","name":"apply_patch","description":"Apply a patch","format":{"type":"grammar","syntax":"lark","definition":"start: /.+/"}}]});
|
||||
let chat = request(UpstreamApi::ChatCompletions, body.clone());
|
||||
assert_eq!(chat["messages"][0]["role"], "system");
|
||||
assert_eq!(chat["messages"][1]["role"], "system");
|
||||
assert_eq!(
|
||||
chat["messages"][2]["content"][1]["image_url"]["url"],
|
||||
"data:image/png;base64,aGVsbG8="
|
||||
);
|
||||
assert_eq!(
|
||||
chat["messages"][3]["tool_calls"].as_array().unwrap().len(),
|
||||
2
|
||||
);
|
||||
assert_eq!(chat["messages"][4]["tool_call_id"], "call-1");
|
||||
assert_eq!(chat["messages"][5]["tool_call_id"], "call-2");
|
||||
assert_eq!(chat["messages"][6]["role"], "user");
|
||||
assert!(chat["tools"][0]["function"]["name"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.starts_with("functions__read_"));
|
||||
assert!(chat["tools"][1]["function"]["description"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("grammar"));
|
||||
let anthropic = request(UpstreamApi::AnthropicMessages, body.clone());
|
||||
assert!(anthropic["system"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("developer instruction"));
|
||||
assert_eq!(anthropic["max_tokens"], 7000);
|
||||
assert_eq!(
|
||||
anthropic["messages"][0]["content"][1]["source"]["media_type"],
|
||||
"image/png"
|
||||
);
|
||||
assert_eq!(
|
||||
anthropic["messages"][1]["content"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.len(),
|
||||
2
|
||||
);
|
||||
assert_eq!(
|
||||
anthropic["messages"][2]["content"][1]["content"][1]["type"],
|
||||
"image"
|
||||
);
|
||||
let gemini = request(UpstreamApi::Gemini, body);
|
||||
assert_eq!(
|
||||
gemini["systemInstruction"]["parts"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.len(),
|
||||
2
|
||||
);
|
||||
assert_eq!(
|
||||
gemini["contents"][0]["parts"][1]["inlineData"]["mimeType"],
|
||||
"image/png"
|
||||
);
|
||||
assert_eq!(
|
||||
gemini["contents"][1]["parts"][0]["functionCall"]["id"],
|
||||
"call-1"
|
||||
);
|
||||
assert_eq!(
|
||||
gemini["contents"][2]["parts"][0]["functionResponse"]["id"],
|
||||
"call-1"
|
||||
);
|
||||
assert_eq!(
|
||||
gemini["contents"][2]["parts"][0]["functionResponse"]["name"],
|
||||
gemini["contents"][1]["parts"][0]["functionCall"]["name"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_responses_server_state_is_explicit_and_native_bytes_are_unchanged() {
|
||||
for api in [
|
||||
UpstreamApi::ChatCompletions,
|
||||
UpstreamApi::AnthropicMessages,
|
||||
UpstreamApi::Gemini,
|
||||
] {
|
||||
for body in [
|
||||
json!({"model":"fixture","input":"x","previous_response_id":"resp-remote"}),
|
||||
json!({"model":"fixture","input":[{"type":"reasoning","encrypted_content":"opaque-upstream-ciphertext"}]}),
|
||||
json!({"model":"fixture","input":[{"type":"item_reference","id":"remote-item"}]}),
|
||||
] {
|
||||
let bytes = serde_json::to_vec(&body).unwrap();
|
||||
assert!(prepare(api, &bytes, false).is_err());
|
||||
assert_eq!(
|
||||
prepare(UpstreamApi::Responses, &bytes, false)
|
||||
.unwrap()
|
||||
.bytes,
|
||||
bytes
|
||||
);
|
||||
}
|
||||
assert!(prepare(api, br#"{"model":"fixture","input":"x"}"#, true)
|
||||
.unwrap_err()
|
||||
.contains("compact"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn namespace_and_custom_tools_restore_original_codex_shapes() {
|
||||
let prepared = prepared(
|
||||
UpstreamApi::ChatCompletions,
|
||||
json!({"model":"fixture","input":"x","tools":[{"type":"namespace","name":"functions","tools":[{"type":"function","name":"read"}]},{"type":"custom","name":"apply_patch"}]}),
|
||||
);
|
||||
let name = prepared.context.upstream_name("read", Some("functions"));
|
||||
let body = json!({"id":"chat-1","choices":[{"finish_reason":"tool_calls","message":{"tool_calls":[{"id":"a","function":{"name":name,"arguments":"{}"}},{"id":"b","function":{"name":"apply_patch","arguments":"{\"input\":\"patch text\"}"}}]}}],"usage":{"prompt_tokens":3,"completion_tokens":4}});
|
||||
let converted = convert_response(
|
||||
UpstreamApi::ChatCompletions,
|
||||
&body,
|
||||
&prepared.context,
|
||||
"fixture",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(converted["output"][0]["namespace"], "functions");
|
||||
assert_eq!(converted["output"][0]["name"], "read");
|
||||
assert_eq!(converted["output"][1]["type"], "custom_tool_call");
|
||||
assert_eq!(converted["output"][1]["input"], "patch text");
|
||||
assert_eq!(converted["usage"]["total_tokens"], 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chat_sse_crosses_utf8_crlf_and_fragmented_function_json() {
|
||||
let context = prepared(
|
||||
UpstreamApi::ChatCompletions,
|
||||
json!({"model":"fixture","input":"x","tools":[{"type":"function","name":"read"}]}),
|
||||
)
|
||||
.context;
|
||||
let input=concat!("data: {\"id\":\"c\",\"choices\":[{\"delta\":{\"content\":\"中文🙂\"}}]}\r\n\r\n", "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"call-x\",\"function\":{\"name\":\"read\",\"arguments\":\"{\\\"x\\\":\"}}]}}]}\r\n\r\n", "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"1}\"}}]},\"finish_reason\":\"tool_calls\"}]}\r\n\r\n", "data: {\"choices\":[],\"usage\":{\"prompt_tokens\":5,\"completion_tokens\":2}}\r\n\r\n", "data: [DONE]\r\n\r\n");
|
||||
let output = streamed(UpstreamApi::ChatCompletions, input, context);
|
||||
let events = events(&output);
|
||||
assert!(events
|
||||
.iter()
|
||||
.any(|v| v["type"] == "response.output_text.delta" && v["delta"] == "中文🙂"));
|
||||
let response = &events.last().unwrap()["response"];
|
||||
assert_eq!(response["status"], "completed");
|
||||
assert_eq!(response["output"][1]["call_id"], "call-x");
|
||||
assert_eq!(response["output"][1]["arguments"], "{\"x\":1}");
|
||||
assert_eq!(response["usage"]["total_tokens"], 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stream_error_before_output_returns_error_and_after_output_emits_failed() {
|
||||
let error = "event: error\ndata: {\"error\":{\"message\":\"fixture outage\"}}\n\n";
|
||||
let mut early = ResponseStream::new(
|
||||
io::Cursor::new(error),
|
||||
UpstreamApi::ChatCompletions,
|
||||
ToolContext::default(),
|
||||
"fixture".into(),
|
||||
);
|
||||
let mut bytes = Vec::new();
|
||||
assert!(early.read_to_end(&mut bytes).is_err());
|
||||
assert!(bytes.is_empty());
|
||||
let output = streamed(
|
||||
UpstreamApi::ChatCompletions,
|
||||
&format!("data: {{\"choices\":[{{\"delta\":{{\"content\":\"partial\"}}}}]}}\n\n{error}"),
|
||||
ToolContext::default(),
|
||||
);
|
||||
let events = events(&output);
|
||||
assert_eq!(events.last().unwrap()["type"], "response.failed");
|
||||
assert!(events.iter().all(|v| v["type"] != "response.completed"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stream_eof_without_terminal_signal_is_incomplete() {
|
||||
for (api, input) in [
|
||||
(
|
||||
UpstreamApi::ChatCompletions,
|
||||
"data: {\"choices\":[{\"delta\":{\"content\":\"partial\"}}]}\n\n",
|
||||
),
|
||||
(
|
||||
UpstreamApi::Gemini,
|
||||
"data: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"partial\"}]}}]}\n\n",
|
||||
),
|
||||
] {
|
||||
let output = streamed(api, input, ToolContext::default());
|
||||
let events = events(&output);
|
||||
assert_eq!(events.last().unwrap()["type"], "response.incomplete");
|
||||
assert_eq!(
|
||||
events.last().unwrap()["response"]["incomplete_details"]["reason"],
|
||||
"stream_truncated"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anthropic_thinking_signature_and_gemini_tool_signature_round_trip() {
|
||||
let ctx = prepared(
|
||||
UpstreamApi::Gemini,
|
||||
json!({"model":"fixture","input":"x","tools":[{"type":"function","name":"read"}]}),
|
||||
)
|
||||
.context;
|
||||
let anthropic = json!({"id":"m","type":"message","content":[{"type":"thinking","thinking":"analysis","signature":"signed-thinking"},{"type":"tool_use","id":"call-a","name":"read","input":{}}],"stop_reason":"tool_use","usage":{"input_tokens":2,"output_tokens":3,"cache_read_input_tokens":5}});
|
||||
let response =
|
||||
convert_response(UpstreamApi::AnthropicMessages, &anthropic, &ctx, "fixture").unwrap();
|
||||
assert_eq!(response["usage"]["input_tokens"], 7);
|
||||
let mut history = vec![json!({"role":"user","content":"inspect"})];
|
||||
history.extend(response["output"].as_array().unwrap().clone());
|
||||
history.push(json!({"type":"function_call_output","call_id":"call-a","output":"done"}));
|
||||
let anthropic_req = request(
|
||||
UpstreamApi::AnthropicMessages,
|
||||
json!({"model":"fixture","input":history}),
|
||||
);
|
||||
assert_eq!(
|
||||
anthropic_req["messages"][1]["content"][0]["signature"],
|
||||
"signed-thinking"
|
||||
);
|
||||
let gemini = json!({"responseId":"g","candidates":[{"content":{"parts":[{"functionCall":{"name":"read","args":{}},"thoughtSignature":"signed-function"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":2,"candidatesTokenCount":3,"thoughtsTokenCount":4}});
|
||||
let response = convert_response(UpstreamApi::Gemini, &gemini, &ctx, "fixture").unwrap();
|
||||
let call = response["output"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|v| v["type"] == "function_call")
|
||||
.unwrap();
|
||||
let mut history = vec![json!({"role":"user","content":"inspect"})];
|
||||
history.extend(response["output"].as_array().unwrap().clone());
|
||||
history.push(json!({"type":"function_call_output","call_id":call["call_id"],"output":"done"}));
|
||||
let request = request(
|
||||
UpstreamApi::Gemini,
|
||||
json!({"model":"fixture","input":history}),
|
||||
);
|
||||
assert_eq!(request["contents"][1]["parts"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(
|
||||
request["contents"][1]["parts"][0]["thoughtSignature"],
|
||||
"signed-function"
|
||||
);
|
||||
assert_eq!(response["usage"]["output_tokens"], 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stream_json_fallback_and_length_reason_are_truthful() {
|
||||
let input = r#"{"id":"chat","choices":[{"message":{"content":"truncated"},"finish_reason":"length"}],"usage":{"prompt_tokens":2,"completion_tokens":3}}"#;
|
||||
let output = streamed(UpstreamApi::ChatCompletions, input, ToolContext::default());
|
||||
let events = events(&output);
|
||||
assert_eq!(events.last().unwrap()["type"], "response.incomplete");
|
||||
assert_eq!(
|
||||
events.last().unwrap()["response"]["incomplete_details"]["reason"],
|
||||
"max_output_tokens"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gemini_signed_text_chunks_replay_on_the_matching_assistant_message() {
|
||||
let input="data: {\"responseId\":\"g\",\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"hello \"}]}}]}\n\ndata: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"world\",\"thoughtSignature\":\"signature\"}]},\"finishReason\":\"STOP\"}]}\n\n";
|
||||
let output = streamed(UpstreamApi::Gemini, input, ToolContext::default());
|
||||
let ev = events(&output);
|
||||
let response = &ev.last().unwrap()["response"];
|
||||
let mut history = vec![json!({"role":"user","content":"hello world"})];
|
||||
history.extend(response["output"].as_array().unwrap().clone());
|
||||
history.push(json!({"role":"user","content":"continue"}));
|
||||
let converted = request(
|
||||
UpstreamApi::Gemini,
|
||||
json!({"model":"gemini-2.5-pro","input":history}),
|
||||
);
|
||||
assert!(converted["contents"][0]["parts"][0]
|
||||
.get("thoughtSignature")
|
||||
.is_none());
|
||||
assert_eq!(converted["contents"][1]["parts"][0]["text"], "hello world");
|
||||
assert_eq!(
|
||||
converted["contents"][1]["parts"][0]["thoughtSignature"],
|
||||
"signature"
|
||||
);
|
||||
let mut history = vec![json!({"role":"user","content":"OK"})];
|
||||
for (id, sig) in [("g1", "sig1"), ("g2", "sig2")] {
|
||||
let converted=convert_response(UpstreamApi::Gemini,&json!({"responseId":id,"candidates":[{"content":{"parts":[{"text":"OK","thoughtSignature":sig}]},"finishReason":"STOP"}]}),&ToolContext::default(),"fixture").unwrap();
|
||||
history.extend(converted["output"].as_array().unwrap().clone());
|
||||
history.push(json!({"role":"user","content":"OK"}));
|
||||
}
|
||||
let converted = request(
|
||||
UpstreamApi::Gemini,
|
||||
json!({"model":"fixture","input":history}),
|
||||
);
|
||||
assert_eq!(
|
||||
converted["contents"][1]["parts"][0]["thoughtSignature"],
|
||||
"sig1"
|
||||
);
|
||||
assert_eq!(
|
||||
converted["contents"][3]["parts"][0]["thoughtSignature"],
|
||||
"sig2"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gemini_single_tool_constraint_buffers_tools_and_rejects_parallel_execution() {
|
||||
let prepared = prepared(
|
||||
UpstreamApi::Gemini,
|
||||
json!({"model":"gemini-2.5-pro","input":"x","parallel_tool_calls":false,"tools":[{"type":"function","name":"read"}]}),
|
||||
);
|
||||
let request: Value = serde_json::from_slice(&prepared.bytes).unwrap();
|
||||
assert!(request["systemInstruction"]["parts"][0]["text"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("at most one"));
|
||||
let response = json!({"candidates":[{"content":{"parts":[{"functionCall":{"name":"read","args":{}}},{"functionCall":{"name":"read","args":{}}}]},"finishReason":"STOP"}]});
|
||||
assert!(
|
||||
convert_response(UpstreamApi::Gemini, &response, &prepared.context, "fixture").is_err()
|
||||
);
|
||||
let input = format!("data: {response}\n\n");
|
||||
let mut stream = ResponseStream::new(
|
||||
ByteReader(input.into_bytes(), 0),
|
||||
UpstreamApi::Gemini,
|
||||
prepared.context.clone(),
|
||||
"fixture".into(),
|
||||
);
|
||||
let mut bytes = Vec::new();
|
||||
assert!(stream.read_to_end(&mut bytes).is_err());
|
||||
assert!(bytes.is_empty());
|
||||
let input=format!("data: {{\"candidates\":[{{\"content\":{{\"parts\":[{{\"text\":\"planning\"}}]}}}}]}}\n\ndata: {response}\n\n");
|
||||
let output = streamed(UpstreamApi::Gemini, &input, prepared.context.clone());
|
||||
let ev = events(&output);
|
||||
assert_eq!(ev.last().unwrap()["type"], "response.failed");
|
||||
assert!(ev
|
||||
.iter()
|
||||
.all(|v| v["type"] != "response.output_item.done" || v["item"]["type"] != "function_call"));
|
||||
let single="data: {\"candidates\":[{\"content\":{\"parts\":[{\"functionCall\":{\"name\":\"read\",\"args\":{}}}]},\"finishReason\":\"STOP\"}]}\n\n";
|
||||
let output = streamed(UpstreamApi::Gemini, single, prepared.context);
|
||||
assert_eq!(
|
||||
events(&output).last().unwrap()["type"],
|
||||
"response.completed"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chat_parallel_results_keep_media_after_all_tool_responses_and_reasoning_on_call() {
|
||||
let body = json!({"model":"fixture","input":[{"role":"user","content":"x"},{"type":"reasoning","summary":[{"text":"analysis"}]},{"role":"assistant","content":"Let me check"},{"type":"function_call","call_id":"a","name":"read","arguments":"{}"},{"type":"function_call","call_id":"b","name":"read","arguments":"{}"},{"type":"function_call_output","call_id":"a","output":[{"type":"input_image","image_url":"data:image/png;base64,aGVsbG8="}]},{"type":"function_call_output","call_id":"b","output":"done"}]});
|
||||
let converted = request(UpstreamApi::ChatCompletions, body);
|
||||
let messages = converted["messages"].as_array().unwrap();
|
||||
assert_eq!(messages[1]["reasoning_content"], "analysis");
|
||||
assert_eq!(messages[1]["content"][0]["text"], "Let me check");
|
||||
assert_eq!(messages[1]["tool_calls"].as_array().unwrap().len(), 2);
|
||||
assert_eq!(messages[2]["tool_call_id"], "a");
|
||||
assert_eq!(messages[3]["tool_call_id"], "b");
|
||||
assert_eq!(messages[4]["role"], "user");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn structured_output_and_unsupported_parameters_are_explicit() {
|
||||
let body = json!({"model":"fixture","input":"x","text":{"format":{"type":"json_schema","name":"test","strict":true,"schema":{"type":"object","properties":{"ok":{"type":"boolean"}}}}}});
|
||||
let chat = request(UpstreamApi::ChatCompletions, body.clone());
|
||||
assert_eq!(chat["response_format"]["json_schema"]["strict"], true);
|
||||
let anth = request(UpstreamApi::AnthropicMessages, body.clone());
|
||||
assert_eq!(anth["output_config"]["format"]["schema"]["type"], "object");
|
||||
let gem = request(UpstreamApi::Gemini, body);
|
||||
assert_eq!(
|
||||
gem["generationConfig"]["responseMimeType"],
|
||||
"application/json"
|
||||
);
|
||||
assert_eq!(
|
||||
gem["generationConfig"]["responseJsonSchema"]["type"],
|
||||
"object"
|
||||
);
|
||||
for body in [
|
||||
json!({"model":"fixture","input":"x","unknown_setting":1}),
|
||||
json!({"model":"fixture","input":"x","tools":{}}),
|
||||
json!({"model":"fixture","input":"x","tool_choice":"required"}),
|
||||
json!({"model":"fixture","input":"x","tools":[{"type":"function","name":"read"},{"type":"function","name":"read"}]}),
|
||||
] {
|
||||
assert!(prepare(
|
||||
UpstreamApi::ChatCompletions,
|
||||
&serde_json::to_vec(&body).unwrap(),
|
||||
false
|
||||
)
|
||||
.is_err());
|
||||
}
|
||||
assert!(prepare(
|
||||
UpstreamApi::AnthropicMessages,
|
||||
&serde_json::to_vec(
|
||||
&json!({"model":"fixture","input":"x","temperature":0.2,"reasoning":{"effort":"high"}})
|
||||
)
|
||||
.unwrap(),
|
||||
false
|
||||
)
|
||||
.unwrap_err()
|
||||
.contains("temperature"));
|
||||
let ultra = request(
|
||||
UpstreamApi::AnthropicMessages,
|
||||
json!({"model":"fixture","input":"x","max_output_tokens":80000,"reasoning":{"effort":"ultra"}}),
|
||||
);
|
||||
assert_eq!(ultra["thinking"]["budget_tokens"], 32768);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminal_sse_does_not_consume_late_error_or_transport_reset() {
|
||||
struct ResetAfter(Vec<Vec<u8>>, usize);
|
||||
impl Read for ResetAfter {
|
||||
fn read(&mut self, bytes: &mut [u8]) -> io::Result<usize> {
|
||||
if self.1 == self.0.len() {
|
||||
return Err(io::Error::new(io::ErrorKind::ConnectionReset, "late reset"));
|
||||
}
|
||||
let chunk = &self.0[self.1];
|
||||
bytes[..chunk.len()].copy_from_slice(chunk);
|
||||
self.1 += 1;
|
||||
Ok(chunk.len())
|
||||
}
|
||||
}
|
||||
let chunks = vec![
|
||||
b"data: {\"choices\":[{\"delta\":{\"content\":\"hello\"}}]}\n\n".to_vec(),
|
||||
b"data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n"
|
||||
.to_vec(),
|
||||
b"event: error\ndata: {\"error\":{\"message\":\"late\"}}\n\n".to_vec(),
|
||||
];
|
||||
let mut stream = ResponseStream::new(
|
||||
ResetAfter(chunks, 0),
|
||||
UpstreamApi::ChatCompletions,
|
||||
ToolContext::default(),
|
||||
"fixture".into(),
|
||||
);
|
||||
let mut output = String::new();
|
||||
stream.read_to_string(&mut output).unwrap();
|
||||
let ev = events(&output);
|
||||
assert_eq!(
|
||||
ev.iter()
|
||||
.filter(|v| v["type"] == "response.completed")
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
assert!(ev.iter().all(|v| v["type"] != "response.failed"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_stream_fallback_has_empty_added_items_before_deltas() {
|
||||
let input = r#"{"id":"chat","choices":[{"message":{"content":"hello","tool_calls":[{"id":"a","function":{"name":"read","arguments":"{\"x\":1}"}}]},"finish_reason":"tool_calls"}]}"#;
|
||||
let output = streamed(UpstreamApi::ChatCompletions, input, ToolContext::default());
|
||||
let ev = events(&output);
|
||||
let added = ev
|
||||
.iter()
|
||||
.filter(|v| v["type"] == "response.output_item.added")
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(added[0]["item"]["status"], "in_progress");
|
||||
assert_eq!(added[0]["item"]["content"], json!([]));
|
||||
assert_eq!(added[1]["item"]["arguments"], "");
|
||||
let part = ev
|
||||
.iter()
|
||||
.find(|v| v["type"] == "response.content_part.added")
|
||||
.unwrap();
|
||||
assert_eq!(part["part"]["text"], "");
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
use super::circuit_breaker::{CircuitBreaker, CircuitBreakerConfig};
|
||||
use super::config::RoutingTuning;
|
||||
use super::native_official::{OfficialRequestAuth, OfficialRouteSpec};
|
||||
use super::protocol::{self, UpstreamApi};
|
||||
use crate::error::{CodexxError, Result};
|
||||
use serde::Serialize;
|
||||
use serde_json::{json, Value};
|
||||
@@ -35,6 +36,7 @@ pub(crate) struct ProxyRoute {
|
||||
pub(crate) headers: Vec<(String, String)>,
|
||||
pub(crate) models: HashSet<String>,
|
||||
pub(crate) official: Option<OfficialRouteSpec>,
|
||||
pub(crate) protocol: UpstreamApi,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize)]
|
||||
@@ -435,6 +437,7 @@ fn reject_self_routes(routes: &[ProxyRoute], address: IpAddr, port: u16) -> Resu
|
||||
|
||||
fn same_transport(left: &ProxyRoute, right: &ProxyRoute) -> bool {
|
||||
left.base_url == right.base_url
|
||||
&& left.protocol == right.protocol
|
||||
&& left.api_key == right.api_key
|
||||
&& left.headers == right.headers
|
||||
&& left.models == right.models
|
||||
@@ -1026,7 +1029,64 @@ fn upstream_url(route: &ProxyRoute, data: &RequestData) -> Option<String> {
|
||||
let base_path = url.path().trim_end_matches('/');
|
||||
// Saved base_url is the API prefix, matching Codex's own /responses join.
|
||||
// Do not invent /v1 for vendor endpoints that deliberately omit it.
|
||||
url.set_path(&format!("{base_path}/{}", data.suffix));
|
||||
let path = match route.protocol {
|
||||
UpstreamApi::Responses => format!("{base_path}/{}", data.suffix),
|
||||
UpstreamApi::ChatCompletions => {
|
||||
if base_path.ends_with("/chat/completions") {
|
||||
base_path.to_owned()
|
||||
} else {
|
||||
format!(
|
||||
"{}/chat/completions",
|
||||
if base_path.is_empty() {
|
||||
"/v1"
|
||||
} else {
|
||||
base_path
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
UpstreamApi::AnthropicMessages => {
|
||||
if base_path.ends_with("/messages") {
|
||||
base_path.to_owned()
|
||||
} else if base_path.ends_with("/v1") {
|
||||
format!("{base_path}/messages")
|
||||
} else {
|
||||
format!("{base_path}/v1/messages")
|
||||
}
|
||||
}
|
||||
UpstreamApi::Gemini => {
|
||||
let model = data
|
||||
.model
|
||||
.as_deref()?
|
||||
.strip_prefix("models/")
|
||||
.unwrap_or(data.model.as_deref()?);
|
||||
if model.is_empty() || model.contains('/') || model.contains(':') {
|
||||
return None;
|
||||
}
|
||||
let model =
|
||||
percent_encoding::utf8_percent_encode(model, percent_encoding::NON_ALPHANUMERIC)
|
||||
.to_string();
|
||||
let method = if data.streaming {
|
||||
"streamGenerateContent"
|
||||
} else {
|
||||
"generateContent"
|
||||
};
|
||||
if base_path.contains("/models/") {
|
||||
let (prefix, _) = base_path.rsplit_once("/models/")?;
|
||||
format!("{prefix}/models/{model}:{method}")
|
||||
} else {
|
||||
format!(
|
||||
"{}/models/{model}:{method}",
|
||||
if base_path.is_empty() {
|
||||
"/v1beta"
|
||||
} else {
|
||||
base_path
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
};
|
||||
url.set_path(&path);
|
||||
let query = match (url.query(), data.query.as_deref()) {
|
||||
(Some(base), Some(request)) if !base.is_empty() && !request.is_empty() => {
|
||||
Some(format!("{base}&{request}"))
|
||||
@@ -1036,6 +1096,9 @@ fn upstream_url(route: &ProxyRoute, data: &RequestData) -> Option<String> {
|
||||
(None, None) => None,
|
||||
};
|
||||
url.set_query(query.as_deref());
|
||||
if route.protocol == UpstreamApi::Gemini && data.streaming {
|
||||
url.query_pairs_mut().append_pair("alt", "sse");
|
||||
}
|
||||
Some(url.into())
|
||||
}
|
||||
|
||||
@@ -1108,6 +1171,7 @@ struct UpstreamResponse {
|
||||
headers: reqwest::header::HeaderMap,
|
||||
deadline: Option<Instant>,
|
||||
next_timeout: Option<Duration>,
|
||||
idle_timeout: Option<Duration>,
|
||||
pending: Vec<u8>,
|
||||
offset: usize,
|
||||
}
|
||||
@@ -1123,6 +1187,7 @@ impl Read for UpstreamResponse {
|
||||
let count = bytes.len().min(self.pending.len() - self.offset);
|
||||
bytes[..count].copy_from_slice(&self.pending[self.offset..self.offset + count]);
|
||||
self.offset += count;
|
||||
self.next_timeout = self.idle_timeout;
|
||||
return Ok(count);
|
||||
}
|
||||
let deadline = match (self.deadline, idle_deadline) {
|
||||
@@ -1167,6 +1232,7 @@ fn request_upstream(
|
||||
data: &RequestData,
|
||||
timing: RequestTimeouts,
|
||||
official: Option<&OfficialRequestAuth>,
|
||||
body: &[u8],
|
||||
) -> std::result::Result<UpstreamResponse, ()> {
|
||||
let mut effective = route.clone();
|
||||
if let Some(auth) = official {
|
||||
@@ -1216,11 +1282,61 @@ fn request_upstream(
|
||||
reqwest::header::HeaderValue::from_str(account).map_err(|_| ())?,
|
||||
);
|
||||
}
|
||||
} else if let Some(key) = route.api_key.as_deref().filter(|key| !key.is_empty()) {
|
||||
let mut value =
|
||||
reqwest::header::HeaderValue::from_str(&format!("Bearer {key}")).map_err(|_| ())?;
|
||||
value.set_sensitive(true);
|
||||
headers.insert(reqwest::header::AUTHORIZATION, value);
|
||||
} else {
|
||||
// Supplier credentials belong to its route snapshot. Neither local
|
||||
// router authentication nor another protocol's default key is reused.
|
||||
for name in [
|
||||
"authorization",
|
||||
"x-api-key",
|
||||
"x-goog-api-key",
|
||||
"chatgpt-account-id",
|
||||
] {
|
||||
headers.remove(name);
|
||||
}
|
||||
if route.protocol == UpstreamApi::AnthropicMessages {
|
||||
headers.insert(
|
||||
"anthropic-version",
|
||||
reqwest::header::HeaderValue::from_static("2023-06-01"),
|
||||
);
|
||||
}
|
||||
let custom_auth = route.headers.iter().any(|(name, _)| {
|
||||
matches!(
|
||||
name.to_ascii_lowercase().as_str(),
|
||||
"authorization" | "x-api-key" | "x-goog-api-key"
|
||||
)
|
||||
});
|
||||
if let Some(key) = route
|
||||
.api_key
|
||||
.as_deref()
|
||||
.filter(|key| !key.is_empty() && !custom_auth)
|
||||
{
|
||||
let (name, text) = match route.protocol {
|
||||
UpstreamApi::Responses | UpstreamApi::ChatCompletions => {
|
||||
("authorization", format!("Bearer {key}"))
|
||||
}
|
||||
UpstreamApi::AnthropicMessages => ("x-api-key", key.to_owned()),
|
||||
UpstreamApi::Gemini => ("x-goog-api-key", key.to_owned()),
|
||||
};
|
||||
let mut value = reqwest::header::HeaderValue::from_str(&text).map_err(|_| ())?;
|
||||
value.set_sensitive(true);
|
||||
headers.insert(
|
||||
reqwest::header::HeaderName::from_bytes(name.as_bytes()).map_err(|_| ())?,
|
||||
value,
|
||||
);
|
||||
}
|
||||
// Explicit supplier headers override defaults. Client headers are
|
||||
// restricted independently and cannot override supplier credentials.
|
||||
for (name, value) in &route.headers {
|
||||
if !forbidden_upstream_header(name)
|
||||
&& !name.eq_ignore_ascii_case(super::config::ROUTE_TOKEN_HEADER)
|
||||
&& !name.eq_ignore_ascii_case(super::config::ROUTE_GENERATION_HEADER)
|
||||
{
|
||||
headers.insert(
|
||||
reqwest::header::HeaderName::from_bytes(name.as_bytes()).map_err(|_| ())?,
|
||||
reqwest::header::HeaderValue::from_str(value).map_err(|_| ())?,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
headers.insert(
|
||||
reqwest::header::CONTENT_TYPE,
|
||||
@@ -1241,7 +1357,7 @@ fn request_upstream(
|
||||
let request = if data.model.is_none() {
|
||||
client.get(&url)
|
||||
} else {
|
||||
client.post(&url).body(data.bytes.clone())
|
||||
client.post(&url).body(body.to_vec())
|
||||
}
|
||||
.headers(headers);
|
||||
let started = Instant::now();
|
||||
@@ -1275,6 +1391,7 @@ fn request_upstream(
|
||||
} else {
|
||||
None
|
||||
},
|
||||
idle_timeout: if data.streaming { timing.idle } else { None },
|
||||
pending: Vec::new(),
|
||||
offset: 0,
|
||||
})
|
||||
@@ -1328,6 +1445,82 @@ fn buffered_response(mut response: UpstreamResponse) -> io::Result<BufferedRespo
|
||||
})
|
||||
}
|
||||
|
||||
fn bridge_buffered(
|
||||
mut response: BufferedResponse,
|
||||
route: &ProxyRoute,
|
||||
prepared: &protocol::PreparedRequest,
|
||||
) -> io::Result<BufferedResponse> {
|
||||
if route.protocol == UpstreamApi::Responses {
|
||||
return Ok(response);
|
||||
}
|
||||
let body: Value = serde_json::from_slice(&response.bytes)
|
||||
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "上游响应不是有效的 JSON"))?;
|
||||
if response.status >= 300 {
|
||||
let message = protocol::error_message(&body).unwrap_or_else(|| body.to_string());
|
||||
response.bytes = serde_json::to_vec(
|
||||
&json!({"error":{"type":"upstream_error","code":"upstream_error","message":message}}),
|
||||
)
|
||||
.unwrap_or_default();
|
||||
} else {
|
||||
let body =
|
||||
protocol::convert_response(route.protocol, &body, &prepared.context, &prepared.model)
|
||||
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
|
||||
response.bytes = serde_json::to_vec(&body).map_err(io::Error::other)?;
|
||||
}
|
||||
response
|
||||
.headers
|
||||
.retain(|(name, _)| !name.eq_ignore_ascii_case("content-type"));
|
||||
response
|
||||
.headers
|
||||
.push(("content-type".into(), "application/json".into()));
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
fn bridge_nonstream_sse(
|
||||
response: UpstreamResponse,
|
||||
route: &ProxyRoute,
|
||||
prepared: &protocol::PreparedRequest,
|
||||
) -> io::Result<BufferedResponse> {
|
||||
let mut headers = downstream_headers(&response);
|
||||
let mut reader = protocol::ResponseStream::new(
|
||||
response,
|
||||
route.protocol,
|
||||
prepared.context.clone(),
|
||||
prepared.model.clone(),
|
||||
);
|
||||
let bytes = read_bounded(&mut reader, MAX_BODY_BYTES)?;
|
||||
let text = std::str::from_utf8(&bytes)
|
||||
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "转换后的 SSE 不是 UTF-8"))?;
|
||||
let event = text
|
||||
.lines()
|
||||
.rev()
|
||||
.filter_map(|line| line.strip_prefix("data: "))
|
||||
.filter_map(|data| serde_json::from_str::<Value>(data).ok())
|
||||
.find(|v| {
|
||||
matches!(
|
||||
v.get("type").and_then(Value::as_str),
|
||||
Some("response.completed" | "response.incomplete" | "response.failed")
|
||||
)
|
||||
})
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "上游 SSE 缺少完成事件"))?;
|
||||
if event["type"] == "response.failed" {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
event
|
||||
.pointer("/response/error/message")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("上游 SSE 失败"),
|
||||
));
|
||||
}
|
||||
headers.retain(|(name, _)| !name.eq_ignore_ascii_case("content-type"));
|
||||
headers.push(("content-type".into(), "application/json".into()));
|
||||
Ok(BufferedResponse {
|
||||
status: 200,
|
||||
headers,
|
||||
bytes: serde_json::to_vec(&event["response"]).map_err(io::Error::other)?,
|
||||
})
|
||||
}
|
||||
|
||||
struct Permit {
|
||||
breaker: Option<Arc<CircuitBreaker>>,
|
||||
half_open: bool,
|
||||
@@ -1520,6 +1713,17 @@ fn handle_request(mut request: Request, shared: &Arc<Shared>) {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if data.model.is_none()
|
||||
&& config
|
||||
.routes
|
||||
.first()
|
||||
.is_some_and(|route| route.protocol.requires_routing())
|
||||
{
|
||||
let mut models: Vec<_> = config.routes[0].models.iter().cloned().collect();
|
||||
models.sort();
|
||||
respond_buffered(request,BufferedResponse {status:200,headers:vec![("content-type".into(),"application/json".into())],bytes:serde_json::to_vec(&json!({"object":"list","data":models.into_iter().map(|id|json!({"id":id,"object":"model","owned_by":"supplier"})).collect::<Vec<_>>()})).unwrap_or_default()});
|
||||
return;
|
||||
}
|
||||
let automatic = config.options.auto_failover_enabled && !official;
|
||||
let max_attempts = if automatic {
|
||||
config.options.tuning.max_retries.saturating_add(1) as usize
|
||||
@@ -1529,6 +1733,7 @@ fn handle_request(mut request: Request, shared: &Arc<Shared>) {
|
||||
let timing = timeouts(shared, &config.options, official);
|
||||
let mut attempted = 0;
|
||||
let mut last_response = None;
|
||||
let mut last_bridge_error = None;
|
||||
for (index, route) in config.routes.iter().enumerate() {
|
||||
if shared.stopped.load(Ordering::Acquire) {
|
||||
fail_request(shared);
|
||||
@@ -1541,11 +1746,37 @@ fn handle_request(mut request: Request, shared: &Arc<Shared>) {
|
||||
if index > 0 && (!automatic || data.primary_only) {
|
||||
break;
|
||||
}
|
||||
let prepared = match if data.model.is_none() {
|
||||
Ok(protocol::PreparedRequest {
|
||||
bytes: data.bytes.clone(),
|
||||
context: protocol::ToolContext::default(),
|
||||
model: String::new(),
|
||||
})
|
||||
} else {
|
||||
protocol::prepare(
|
||||
route.protocol,
|
||||
&data.bytes,
|
||||
data.suffix == "responses/compact",
|
||||
)
|
||||
} {
|
||||
Ok(prepared) => prepared,
|
||||
Err(message) => {
|
||||
fail_request(shared);
|
||||
respond_error(request, 400, &message);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let Some(mut permit) = Permit::acquire(&breakers, route, automatic) else {
|
||||
continue;
|
||||
};
|
||||
attempted += 1;
|
||||
let mut response = match request_upstream(route, &data, timing, official_auth.as_ref()) {
|
||||
let response = match request_upstream(
|
||||
route,
|
||||
&data,
|
||||
timing,
|
||||
official_auth.as_ref(),
|
||||
&prepared.bytes,
|
||||
) {
|
||||
Ok(response) => response,
|
||||
Err(()) => {
|
||||
set_attempt_failure(
|
||||
@@ -1572,7 +1803,7 @@ fn handle_request(mut request: Request, shared: &Arc<Shared>) {
|
||||
Some(status),
|
||||
"供应商暂时不可用",
|
||||
);
|
||||
last_response = Some(response);
|
||||
last_response = Some((response, route.clone(), prepared));
|
||||
continue;
|
||||
}
|
||||
if (300..=399).contains(&status) {
|
||||
@@ -1595,7 +1826,9 @@ fn handle_request(mut request: Request, shared: &Arc<Shared>) {
|
||||
if let Some(health) = lock(&shared.statistics).health.get_mut(&route.id) {
|
||||
health.last_status = Some(status);
|
||||
}
|
||||
match buffered_response(response) {
|
||||
match buffered_response(response)
|
||||
.and_then(|response| bridge_buffered(response, route, &prepared))
|
||||
{
|
||||
Ok(response) => respond_buffered(request, response),
|
||||
Err(_) => respond_error(request, 502, "供应商响应无法读取"),
|
||||
};
|
||||
@@ -1614,11 +1847,49 @@ fn handle_request(mut request: Request, shared: &Arc<Shared>) {
|
||||
.trim()
|
||||
.eq_ignore_ascii_case("text/event-stream")
|
||||
});
|
||||
if !data.streaming && streaming && route.protocol.requires_routing() {
|
||||
match bridge_nonstream_sse(response, route, &prepared) {
|
||||
Ok(response) => {
|
||||
set_success(shared, &config, route, &mut permit, index, status);
|
||||
respond_buffered(request, response);
|
||||
return;
|
||||
}
|
||||
Err(error) => {
|
||||
last_bridge_error = Some(error.to_string());
|
||||
set_attempt_failure(
|
||||
shared,
|
||||
&config,
|
||||
route,
|
||||
&mut permit,
|
||||
Some(status),
|
||||
"供应商 SSE 返回无法转换为完整 JSON",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
if streaming {
|
||||
let headers = downstream_headers(&response);
|
||||
let mut headers = downstream_headers(&response);
|
||||
if route.protocol.requires_routing() {
|
||||
headers.retain(|(name, _)| !name.eq_ignore_ascii_case("content-type"));
|
||||
headers.push(("content-type".into(), "text/event-stream".into()));
|
||||
}
|
||||
let mut bridge_failure = None;
|
||||
let mut reader: Box<dyn Read + Send + Sync> = if route.protocol.requires_routing() {
|
||||
let converted = protocol::ResponseStream::new(
|
||||
response,
|
||||
route.protocol,
|
||||
prepared.context,
|
||||
prepared.model,
|
||||
);
|
||||
bridge_failure = Some(converted.failure_flag());
|
||||
Box::new(converted)
|
||||
} else {
|
||||
Box::new(response)
|
||||
};
|
||||
let mut first = [0; 16 * 1024];
|
||||
let count = match response.read(&mut first) {
|
||||
Ok(0) | Err(_) => {
|
||||
let count = match reader.read(&mut first) {
|
||||
Ok(0) => {
|
||||
set_attempt_failure(
|
||||
shared,
|
||||
&config,
|
||||
@@ -1632,20 +1903,31 @@ fn handle_request(mut request: Request, shared: &Arc<Shared>) {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Err(error) => {
|
||||
if route.protocol.requires_routing() {
|
||||
last_bridge_error = Some(error.to_string());
|
||||
}
|
||||
set_attempt_failure(
|
||||
shared,
|
||||
&config,
|
||||
route,
|
||||
&mut permit,
|
||||
Some(status),
|
||||
"供应商首包读取或协议转换失败",
|
||||
);
|
||||
if official {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Ok(count) => count,
|
||||
};
|
||||
response.next_timeout = timing.idle;
|
||||
set_success(shared, &config, route, &mut permit, index, status);
|
||||
if matches!(
|
||||
stream_response(
|
||||
request,
|
||||
status,
|
||||
headers,
|
||||
&first[..count],
|
||||
Box::new(response)
|
||||
),
|
||||
stream_response(request, status, headers, &first[..count], reader),
|
||||
StreamOutcome::UpstreamFailure
|
||||
) {
|
||||
) || bridge_failure.is_some_and(|flag| flag.load(Ordering::Acquire))
|
||||
{
|
||||
// Like CC Switch, after the committed first chunk this is a
|
||||
// downstream stream failure, never a fresh provider attempt.
|
||||
let mut stats = lock(&shared.statistics);
|
||||
@@ -1653,13 +1935,18 @@ fn handle_request(mut request: Request, shared: &Arc<Shared>) {
|
||||
}
|
||||
return;
|
||||
}
|
||||
match buffered_response(response) {
|
||||
match buffered_response(response)
|
||||
.and_then(|response| bridge_buffered(response, route, &prepared))
|
||||
{
|
||||
Ok(response) => {
|
||||
set_success(shared, &config, route, &mut permit, index, status);
|
||||
respond_buffered(request, response);
|
||||
return;
|
||||
}
|
||||
Err(_) => {
|
||||
Err(error) => {
|
||||
if route.protocol.requires_routing() {
|
||||
last_bridge_error = Some(error.to_string());
|
||||
}
|
||||
set_attempt_failure(
|
||||
shared,
|
||||
&config,
|
||||
@@ -1675,11 +1962,15 @@ fn handle_request(mut request: Request, shared: &Arc<Shared>) {
|
||||
}
|
||||
}
|
||||
fail_request(shared);
|
||||
if let Some(response) = last_response {
|
||||
match buffered_response(response) {
|
||||
if let Some((response, route, prepared)) = last_response {
|
||||
match buffered_response(response)
|
||||
.and_then(|response| bridge_buffered(response, &route, &prepared))
|
||||
{
|
||||
Ok(response) => respond_buffered(request, response),
|
||||
Err(_) => respond_error(request, 502, "暂时无法连接可用供应商,请稍后重试"),
|
||||
}
|
||||
} else if let Some(error) = last_bridge_error {
|
||||
respond_error(request, 502, &format!("上游协议转换失败:{error}"));
|
||||
} else if attempted > 0 {
|
||||
respond_error(request, 502, "暂时无法连接可用供应商,请稍后重试");
|
||||
} else {
|
||||
@@ -1928,6 +2219,7 @@ mod tests {
|
||||
headers: Vec::new(),
|
||||
models: HashSet::from([MODEL.to_string()]),
|
||||
official: None,
|
||||
protocol: UpstreamApi::Responses,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1935,6 +2227,180 @@ mod tests {
|
||||
ProxyHandle::start_with_timeout(0, TOKEN.into(), routes, Duration::from_secs(2)).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn protocol_bridges_use_correct_endpoints_auth_and_codex_json() {
|
||||
for (api, reply) in [
|
||||
(
|
||||
UpstreamApi::ChatCompletions,
|
||||
r#"{"id":"chat","model":"fixture-model","choices":[{"message":{"content":"chat reply"},"finish_reason":"stop"}],"usage":{"prompt_tokens":2,"completion_tokens":3}}"#,
|
||||
),
|
||||
(
|
||||
UpstreamApi::AnthropicMessages,
|
||||
r#"{"id":"anth","model":"fixture-model","type":"message","content":[{"type":"text","text":"anthropic reply"}],"stop_reason":"end_turn","usage":{"input_tokens":2,"output_tokens":3}}"#,
|
||||
),
|
||||
(
|
||||
UpstreamApi::Gemini,
|
||||
r#"{"responseId":"gem","candidates":[{"content":{"parts":[{"text":"gemini reply"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":2,"candidatesTokenCount":3}}"#,
|
||||
),
|
||||
] {
|
||||
let upstream = Upstream::json(200, reply);
|
||||
let mut supplier = route("converted", &upstream, "fixture-secret");
|
||||
supplier.protocol = api;
|
||||
let proxy = start(vec![supplier]);
|
||||
let body: Value =
|
||||
serde_json::from_str(&request(&proxy, &payload()).into_string().unwrap()).unwrap();
|
||||
assert_eq!(body["object"], "response");
|
||||
assert_eq!(body["status"], "completed");
|
||||
assert_eq!(body["usage"]["total_tokens"], 5);
|
||||
let calls = upstream.observed();
|
||||
let seen = &calls[0];
|
||||
let converted: Value = serde_json::from_slice(&seen.body).unwrap();
|
||||
match api {
|
||||
UpstreamApi::ChatCompletions => {
|
||||
assert_eq!(seen.target, "/v1/chat/completions");
|
||||
assert_eq!(seen.headers["authorization"], "Bearer fixture-secret");
|
||||
assert_eq!(converted["messages"][0]["content"], "fixture prompt");
|
||||
}
|
||||
UpstreamApi::AnthropicMessages => {
|
||||
assert_eq!(seen.target, "/v1/messages");
|
||||
assert_eq!(seen.headers["x-api-key"], "fixture-secret");
|
||||
assert_eq!(seen.headers["anthropic-version"], "2023-06-01");
|
||||
assert!(!seen.headers.contains_key("authorization"));
|
||||
assert_eq!(converted["max_tokens"], 8192);
|
||||
}
|
||||
UpstreamApi::Gemini => {
|
||||
assert!(seen.target.starts_with("/v1beta/models/fixture"));
|
||||
assert!(seen.target.ends_with(":generateContent"));
|
||||
assert_eq!(seen.headers["x-goog-api-key"], "fixture-secret");
|
||||
assert!(!seen.headers.contains_key("authorization"));
|
||||
assert_eq!(converted["contents"][0]["role"], "user");
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
assert!(!seen.headers.values().any(|v| v.contains(TOKEN)));
|
||||
let models = client()
|
||||
.get(&format!("http://127.0.0.1:{}/v1/models", proxy.port()))
|
||||
.set("Authorization", &format!("Bearer {TOKEN}"))
|
||||
.call()
|
||||
.unwrap()
|
||||
.into_string()
|
||||
.unwrap();
|
||||
let models: Value = serde_json::from_str(&models).unwrap();
|
||||
assert_eq!(models["object"], "list");
|
||||
assert_eq!(models["data"][0]["id"], MODEL);
|
||||
assert_eq!(upstream.observed().len(), 1);
|
||||
proxy.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converted_routes_reject_remote_state_and_compaction_without_upstream_request() {
|
||||
let upstream = Upstream::json(200, "{}");
|
||||
let mut supplier = route("converted", &upstream, "fixture-secret");
|
||||
supplier.protocol = UpstreamApi::Gemini;
|
||||
let proxy = start(vec![supplier]);
|
||||
let error = client()
|
||||
.post(&format!("http://127.0.0.1:{}/v1/responses", proxy.port()))
|
||||
.set("Authorization", &format!("Bearer {TOKEN}"))
|
||||
.set("Content-Type", "application/json")
|
||||
.send_string(
|
||||
&json!({"model":MODEL,"input":"x","previous_response_id":"opaque-server-state"})
|
||||
.to_string(),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(matches!(error, ureq::Error::Status(400, _)));
|
||||
let error = client()
|
||||
.post(&format!(
|
||||
"http://127.0.0.1:{}/v1/responses/compact",
|
||||
proxy.port()
|
||||
))
|
||||
.set("Authorization", &format!("Bearer {TOKEN}"))
|
||||
.set("Content-Type", "application/json")
|
||||
.send_string(&json!({"model":MODEL,"input":"x"}).to_string())
|
||||
.unwrap_err();
|
||||
assert!(matches!(error, ureq::Error::Status(400, _)));
|
||||
assert!(upstream.observed().is_empty());
|
||||
proxy.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn early_bridge_sse_error_can_fail_over_but_committed_output_is_not_replayed() {
|
||||
let early = Upstream::serve(|stream| {
|
||||
let data = "event: error\ndata: {\"error\":{\"message\":\"fixture outage\"}}\n\n";
|
||||
write!(stream,"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{data}",data.len()).unwrap();
|
||||
});
|
||||
let backup = Upstream::json(
|
||||
200,
|
||||
r#"{"id":"backup","choices":[{"message":{"content":"recovered"},"finish_reason":"stop"}]}"#,
|
||||
);
|
||||
let mut first = route("early", &early, "one");
|
||||
first.protocol = UpstreamApi::ChatCompletions;
|
||||
let mut second = route("backup", &backup, "two");
|
||||
second.protocol = UpstreamApi::ChatCompletions;
|
||||
let proxy = start(vec![first, second]);
|
||||
let result = request(&proxy, &stream_payload()).into_string().unwrap();
|
||||
assert!(result.contains("response.completed"));
|
||||
assert!(result.contains("recovered"));
|
||||
assert_eq!(backup.observed().len(), 1);
|
||||
proxy.shutdown();
|
||||
let (release, await_release) = mpsc::channel();
|
||||
let late = Upstream::serve(move |stream| {
|
||||
let first="data: {\"id\":\"partial\",\"choices\":[{\"delta\":{\"content\":\"committed\"}}]}\n\n";
|
||||
write!(stream,"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n{:x}\r\n{first}\r\n",first.len()).unwrap();
|
||||
stream.flush().unwrap();
|
||||
await_release.recv_timeout(Duration::from_secs(3)).unwrap();
|
||||
let error = "event: error\ndata: {\"error\":{\"message\":\"late outage\"}}\n\n";
|
||||
write!(stream, "{:x}\r\n{error}\r\n0\r\n\r\n", error.len()).unwrap();
|
||||
});
|
||||
let untouched = Upstream::json(200, "{}");
|
||||
let mut first = route("late", &late, "one");
|
||||
first.protocol = UpstreamApi::ChatCompletions;
|
||||
let proxy = start(vec![first, route("untouched", &untouched, "two")]);
|
||||
let result = request(&proxy, &stream_payload());
|
||||
release.send(()).unwrap();
|
||||
let result = result.into_string().unwrap();
|
||||
// The client can receive EOF before the worker publishes final statistics.
|
||||
eventually(|| proxy.snapshot().in_flight == 0);
|
||||
assert!(result.contains("response.failed"));
|
||||
assert!(!result.contains("response.completed"));
|
||||
assert!(untouched.observed().is_empty());
|
||||
assert!(proxy.snapshot().last_error.is_some());
|
||||
proxy.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gemini_stream_endpoint_converts_sse_and_preserves_function_call() {
|
||||
let upstream = Upstream::serve(|stream| {
|
||||
let events = [
|
||||
json!({"responseId":"g","candidates":[{"content":{"parts":[{"text":"中文🙂"}]}}]}),
|
||||
json!({"candidates":[{"content":{"parts":[{"functionCall":{"name":"read","args":{"path":"x"}},"thoughtSignature":"fixture-signature"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":5,"candidatesTokenCount":2}}),
|
||||
];
|
||||
let body = events
|
||||
.iter()
|
||||
.map(|event| format!("data: {event}\r\n\r\n"))
|
||||
.collect::<String>();
|
||||
write!(stream,"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n").unwrap();
|
||||
for chunk in body.as_bytes().chunks(1) {
|
||||
write!(stream, "1\r\n").unwrap();
|
||||
stream.write_all(chunk).unwrap();
|
||||
stream.write_all(b"\r\n").unwrap();
|
||||
}
|
||||
stream.write_all(b"0\r\n\r\n").unwrap();
|
||||
});
|
||||
let mut supplier = route("gemini", &upstream, "secret");
|
||||
supplier.protocol = UpstreamApi::Gemini;
|
||||
let proxy = start(vec![supplier]);
|
||||
let bytes=serde_json::to_vec(&json!({"model":MODEL,"input":"x","stream":true,"tools":[{"type":"function","name":"read"}]})).unwrap();
|
||||
let output = request(&proxy, &bytes).into_string().unwrap();
|
||||
assert!(output.contains("response.completed"));
|
||||
assert!(output.contains("中文🙂"));
|
||||
assert!(output.contains("function_call"));
|
||||
assert!(output.contains("encrypted_content"));
|
||||
let seen = &upstream.observed()[0];
|
||||
assert!(seen.target.contains(":streamGenerateContent?alt=sse"));
|
||||
proxy.shutdown();
|
||||
}
|
||||
|
||||
fn client() -> ureq::Agent {
|
||||
ureq::AgentBuilder::new()
|
||||
.try_proxy_from_env(false)
|
||||
@@ -2357,7 +2823,11 @@ mod tests {
|
||||
let started = Instant::now();
|
||||
proxy.shutdown();
|
||||
assert!(started.elapsed() < Duration::from_millis(500));
|
||||
assert!(TcpStream::connect((std::net::Ipv4Addr::LOCALHOST, proxy.port())).is_err());
|
||||
// Windows can delay a refused connect beyond this fixture's 2-second
|
||||
// stream-idle timeout. Bound the probe while the upstream is paused so
|
||||
// it tests listener shutdown rather than causing an unrelated timeout.
|
||||
let stopped_address = SocketAddr::new(proxy.listen_address(), proxy.port());
|
||||
assert!(TcpStream::connect_timeout(&stopped_address, Duration::from_millis(100)).is_err());
|
||||
release.send(()).unwrap();
|
||||
let mut last = String::new();
|
||||
reader.read_to_string(&mut last).unwrap();
|
||||
|
||||
@@ -27,6 +27,7 @@ impl Fixture {
|
||||
api_key: Some(format!("fixture-provider-secret-{index}")),
|
||||
toml_config: None,
|
||||
wire_api: "responses".into(),
|
||||
upstream_api: None,
|
||||
requires_openai_auth: false,
|
||||
model_mappings: vec![],
|
||||
};
|
||||
@@ -373,6 +374,458 @@ fn failed_manual_switch_reattaches_original_route() {
|
||||
assert_eq!(status.primary.unwrap().id, fixture.providers[0].id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converted_provider_requires_live_takeover_and_shutdown_preserves_bridge() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let mut fixture = Fixture::new();
|
||||
fixture.providers[1].upstream_api = Some("gemini".into());
|
||||
fixture.providers[1] =
|
||||
crate::providers::save_provider_inner(fixture.providers[1].clone()).unwrap();
|
||||
assert!(ensure_conversion_route(fixture.scope(), &fixture.providers[1]).is_err());
|
||||
fixture.enable();
|
||||
ensure_conversion_route(fixture.scope(), &fixture.providers[1]).unwrap();
|
||||
with_provider_change(fixture.scope(), || {
|
||||
crate::providers::activate_saved_provider_inner(
|
||||
fixture.scope(),
|
||||
fixture.providers[1].id.clone(),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
let before = FileCheckpoint::capture(&fixture.dir).unwrap();
|
||||
let mut disabled = get_status(fixture.scope()).unwrap().settings;
|
||||
disabled.router_enabled = false;
|
||||
assert!(save_settings(fixture.scope(), disabled)
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string()
|
||||
.contains("协议转换"));
|
||||
shutdown_all().unwrap();
|
||||
let after = FileCheckpoint::capture(&fixture.dir).unwrap();
|
||||
assert_eq!(before.config, after.config);
|
||||
assert_eq!(before.auth, after.auth);
|
||||
assert_eq!(before.selected, after.selected);
|
||||
assert!(!get_status(fixture.scope()).unwrap().running);
|
||||
assert!(fixture.text().contains("127.0.0.1"));
|
||||
resume_after_failed_update().unwrap();
|
||||
assert!(get_status(fixture.scope()).unwrap().takeover_active);
|
||||
with_provider_change(fixture.scope(), || {
|
||||
crate::providers::activate_saved_provider_inner(
|
||||
fixture.scope(),
|
||||
fixture.providers[0].id.clone(),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
stop(&fixture);
|
||||
assert!(!get_status(fixture.scope()).unwrap().running);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shutdown_preflight_is_read_only_for_native_and_converted_routes() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let mut fixture = Fixture::new();
|
||||
fixture.enable();
|
||||
let before = FileCheckpoint::capture(&fixture.dir).unwrap();
|
||||
assert!(!SHUTTING_DOWN.load(Ordering::Acquire));
|
||||
ensure_shutdown_allowed().unwrap();
|
||||
assert!(!SHUTTING_DOWN.load(Ordering::Acquire));
|
||||
assert_eq!(
|
||||
before.config,
|
||||
FileCheckpoint::capture(&fixture.dir).unwrap().config
|
||||
);
|
||||
fixture.providers[1].upstream_api = Some("gemini".into());
|
||||
fixture.providers[1] =
|
||||
crate::providers::save_provider_inner(fixture.providers[1].clone()).unwrap();
|
||||
with_provider_change(fixture.scope(), || {
|
||||
crate::providers::activate_saved_provider_inner(
|
||||
fixture.scope(),
|
||||
fixture.providers[1].id.clone(),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
let before = FileCheckpoint::capture(&fixture.dir).unwrap();
|
||||
let (routes, revision, instance) = {
|
||||
let runtimes = lock_manager().unwrap();
|
||||
let runtime = runtimes.get(&fixture.dir).unwrap();
|
||||
(
|
||||
runtime.routes.clone(),
|
||||
runtime.proxy.revision(),
|
||||
runtime.instance_id,
|
||||
)
|
||||
};
|
||||
for flag in [false, true] {
|
||||
SHUTTING_DOWN.store(flag, Ordering::Release);
|
||||
ensure_shutdown_allowed().unwrap();
|
||||
assert_eq!(SHUTTING_DOWN.load(Ordering::Acquire), flag);
|
||||
let after = FileCheckpoint::capture(&fixture.dir).unwrap();
|
||||
assert_eq!(before.config, after.config);
|
||||
assert_eq!(before.auth, after.auth);
|
||||
assert_eq!(before.selected, after.selected);
|
||||
let runtimes = lock_manager().unwrap();
|
||||
let runtime = runtimes.get(&fixture.dir).unwrap();
|
||||
assert!(runtime.routes == routes);
|
||||
assert_eq!(runtime.proxy.revision(), revision);
|
||||
assert_eq!(runtime.instance_id, instance);
|
||||
assert!(runtime.journal.is_some());
|
||||
}
|
||||
SHUTTING_DOWN.store(false, Ordering::Release);
|
||||
}
|
||||
|
||||
fn converted_fixture(api: &str) -> Fixture {
|
||||
let mut fixture = Fixture::new();
|
||||
fixture.providers[1].upstream_api = Some(api.into());
|
||||
fixture.providers[1] =
|
||||
crate::providers::save_provider_inner(fixture.providers[1].clone()).unwrap();
|
||||
let mut settings = fixture.settings();
|
||||
settings.auto_failover_enabled = false;
|
||||
save_settings(fixture.scope(), settings).unwrap();
|
||||
with_provider_change(fixture.scope(), || {
|
||||
crate::providers::activate_saved_provider_inner(
|
||||
fixture.scope(),
|
||||
fixture.providers[1].id.clone(),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
fixture
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converted_normal_exit_restarts_the_owned_bridge_without_direct_restore() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let fixture = converted_fixture("gemini");
|
||||
let before = FileCheckpoint::capture(&fixture.dir).unwrap();
|
||||
let settings = get_status(fixture.scope()).unwrap().settings;
|
||||
ensure_shutdown_allowed().unwrap();
|
||||
shutdown_all().unwrap();
|
||||
let after = FileCheckpoint::capture(&fixture.dir).unwrap();
|
||||
assert_eq!(before.config, after.config);
|
||||
assert_eq!(before.auth, after.auth);
|
||||
assert_eq!(before.selected, after.selected);
|
||||
assert!(!lock_manager().unwrap().contains_key(&fixture.dir));
|
||||
assert!(SHUTTING_DOWN.load(Ordering::Acquire));
|
||||
let called = std::cell::Cell::new(false);
|
||||
assert!(with_provider_change(fixture.scope(), || {
|
||||
called.set(true);
|
||||
Ok(())
|
||||
})
|
||||
.is_err());
|
||||
assert!(!called.get());
|
||||
SHUTTING_DOWN.store(false, Ordering::Release);
|
||||
initialize().unwrap();
|
||||
let status = get_status(fixture.scope()).unwrap();
|
||||
assert!(status.running && status.takeover_active);
|
||||
assert_eq!(status.settings, settings);
|
||||
let runtimes = lock_manager().unwrap();
|
||||
let runtime = runtimes.get(&fixture.dir).unwrap();
|
||||
assert_eq!(runtime.routes[0].protocol, UpstreamApi::Gemini);
|
||||
assert!(runtime.journal.as_ref().unwrap().requires_conversion);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_handoff_freezes_mutations_without_stopping_native_or_converted_listener() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
for conversion in [false, true] {
|
||||
let fixture = if conversion {
|
||||
converted_fixture("anthropic_messages")
|
||||
} else {
|
||||
let fixture = Fixture::new();
|
||||
fixture.enable();
|
||||
fixture
|
||||
};
|
||||
let before = FileCheckpoint::capture(&fixture.dir).unwrap();
|
||||
let (revision, instance) = {
|
||||
let runtimes = lock_manager().unwrap();
|
||||
let runtime = runtimes.get(&fixture.dir).unwrap();
|
||||
(runtime.proxy.revision(), runtime.instance_id)
|
||||
};
|
||||
begin_update_handoff().unwrap();
|
||||
assert!(SHUTTING_DOWN.load(Ordering::Acquire));
|
||||
let called = std::cell::Cell::new(false);
|
||||
assert!(with_provider_change(fixture.scope(), || {
|
||||
called.set(true);
|
||||
fs::write(crate::config_path(&fixture.dir), "changed").unwrap();
|
||||
Ok(())
|
||||
})
|
||||
.is_err());
|
||||
assert!(!called.get());
|
||||
assert!(save_settings(fixture.scope(), fixture.settings()).is_err());
|
||||
assert!(refresh_saved_routes().is_err());
|
||||
let after = FileCheckpoint::capture(&fixture.dir).unwrap();
|
||||
assert_eq!(before.config, after.config);
|
||||
assert_eq!(before.auth, after.auth);
|
||||
assert_eq!(before.selected, after.selected);
|
||||
{
|
||||
let runtimes = lock_manager().unwrap();
|
||||
let runtime = runtimes.get(&fixture.dir).unwrap();
|
||||
assert_eq!(runtime.proxy.revision(), revision);
|
||||
assert_eq!(runtime.instance_id, instance);
|
||||
assert!(runtime.journal.is_some());
|
||||
}
|
||||
resume_after_failed_update().unwrap();
|
||||
assert!(!SHUTTING_DOWN.load(Ordering::Acquire));
|
||||
{
|
||||
let runtimes = lock_manager().unwrap();
|
||||
let runtime = runtimes.get(&fixture.dir).unwrap();
|
||||
assert_eq!(runtime.proxy.revision(), revision);
|
||||
assert_eq!(runtime.instance_id, instance);
|
||||
}
|
||||
with_provider_change(fixture.scope(), || Ok(())).unwrap();
|
||||
assert!(get_status(fixture.scope()).unwrap().takeover_active);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converted_stopped_update_handoff_resumes_the_same_protocol_and_settings() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let fixture = converted_fixture("anthropic_messages");
|
||||
let before = FileCheckpoint::capture(&fixture.dir).unwrap();
|
||||
let settings = get_status(fixture.scope()).unwrap().settings;
|
||||
shutdown_all().unwrap();
|
||||
assert!(!lock_manager().unwrap().contains_key(&fixture.dir));
|
||||
assert_eq!(
|
||||
before.config,
|
||||
FileCheckpoint::capture(&fixture.dir).unwrap().config
|
||||
);
|
||||
resume_after_failed_update().unwrap();
|
||||
assert!(!SHUTTING_DOWN.load(Ordering::Acquire));
|
||||
let status = get_status(fixture.scope()).unwrap();
|
||||
assert!(status.running && status.takeover_active);
|
||||
assert_eq!(status.settings, settings);
|
||||
assert_eq!(
|
||||
lock_manager().unwrap().get(&fixture.dir).unwrap().routes[0].protocol,
|
||||
UpstreamApi::AnthropicMessages
|
||||
);
|
||||
assert_eq!(
|
||||
before.auth,
|
||||
FileCheckpoint::capture(&fixture.dir).unwrap().auth
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converted_shutdown_keeps_external_selection_and_does_not_reattach_it() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
for detach_before_shutdown in [false, true] {
|
||||
let fixture = converted_fixture("gemini");
|
||||
let journal = lock_manager()
|
||||
.unwrap()
|
||||
.get(&fixture.dir)
|
||||
.unwrap()
|
||||
.journal
|
||||
.clone()
|
||||
.unwrap();
|
||||
let auth = fs::read(fixture.dir.join("auth.json")).unwrap();
|
||||
if !detach_before_shutdown {
|
||||
// Freeze the watcher before the external edit so this case covers
|
||||
// shutdown seeing the converted journal itself, deterministically.
|
||||
begin_update_handoff().unwrap();
|
||||
}
|
||||
let mut doc = parsed(&fixture);
|
||||
doc["model_provider"] = value("external");
|
||||
let mut table = Table::new();
|
||||
table["name"] = value("External fixture");
|
||||
table["base_url"] = value("https://external-fixture.example.test/v1");
|
||||
table["wire_api"] = value("responses");
|
||||
table["requires_openai_auth"] = value(false);
|
||||
replace_table(&mut doc, "external", table).unwrap();
|
||||
let external = doc.to_string();
|
||||
let detached_doc = restored_document(&doc, &journal).unwrap();
|
||||
// Independently verify that the projection only changes our inactive
|
||||
// provider table, not the external selection/table or any user config.
|
||||
let mut unmanaged_before = doc.clone();
|
||||
let mut unmanaged_after = detached_doc.clone();
|
||||
for document in [&mut unmanaged_before, &mut unmanaged_after] {
|
||||
document
|
||||
.get_mut("model_providers")
|
||||
.and_then(Item::as_table_mut)
|
||||
.unwrap()
|
||||
.remove(&journal.provider_key);
|
||||
}
|
||||
assert_eq!(unmanaged_after.to_string(), unmanaged_before.to_string());
|
||||
let detached = detached_doc.to_string();
|
||||
fs::write(crate::config_path(&fixture.dir), &external).unwrap();
|
||||
let expected = if detach_before_shutdown {
|
||||
// The production watcher is allowed to clean its inactive owned
|
||||
// overlay after an external selection. Complete that same path
|
||||
// synchronously rather than racing its three-second scan.
|
||||
refresh_saved_routes().unwrap();
|
||||
assert_eq!(fixture.text(), detached);
|
||||
assert!(lock_manager()
|
||||
.unwrap()
|
||||
.get(&fixture.dir)
|
||||
.unwrap()
|
||||
.journal
|
||||
.is_none());
|
||||
detached
|
||||
} else {
|
||||
external
|
||||
};
|
||||
shutdown_all().unwrap();
|
||||
assert_eq!(fixture.text(), expected);
|
||||
assert_eq!(
|
||||
parsed(&fixture)["model_provider"].as_str(),
|
||||
Some("external")
|
||||
);
|
||||
assert_eq!(fs::read(fixture.dir.join("auth.json")).unwrap(), auth);
|
||||
assert!(!load_record(&fixture.dir).unwrap().settings.takeover_enabled);
|
||||
SHUTTING_DOWN.store(false, Ordering::Release);
|
||||
initialize().unwrap();
|
||||
assert_eq!(fixture.text(), expected);
|
||||
assert_eq!(fs::read(fixture.dir.join("auth.json")).unwrap(), auth);
|
||||
let runtime = lock_manager().unwrap().remove(&fixture.dir).unwrap();
|
||||
assert!(runtime.journal.is_none());
|
||||
runtime.proxy.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converted_shutdown_failure_keeps_files_listener_and_mutation_gate_open() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let fixture = converted_fixture("gemini");
|
||||
let before = FileCheckpoint::capture(&fixture.dir).unwrap();
|
||||
let record = load_record(&fixture.dir).unwrap();
|
||||
let mut missing = record.clone();
|
||||
missing.journals.clear();
|
||||
save_record(&fixture.dir, &missing).unwrap();
|
||||
assert!(ensure_shutdown_allowed().is_err());
|
||||
assert!(begin_update_handoff().is_err());
|
||||
assert!(!SHUTTING_DOWN.load(Ordering::Acquire));
|
||||
assert!(shutdown_all().is_err());
|
||||
assert!(!SHUTTING_DOWN.load(Ordering::Acquire));
|
||||
assert!(lock_manager().unwrap().contains_key(&fixture.dir));
|
||||
assert_eq!(
|
||||
before.config,
|
||||
FileCheckpoint::capture(&fixture.dir).unwrap().config
|
||||
);
|
||||
save_record(&fixture.dir, &record).unwrap();
|
||||
let mut stale_settings = record.clone();
|
||||
stale_settings.settings.takeover_enabled = false;
|
||||
save_record(&fixture.dir, &stale_settings).unwrap();
|
||||
let conn = crate::app_db::open().unwrap();
|
||||
conn.execute_batch("CREATE TRIGGER reject_conversion_shutdown BEFORE UPDATE ON provider_failover BEGIN SELECT RAISE(ABORT,'fixture-conversion-shutdown-failure'); END;").unwrap();
|
||||
let result = shutdown_all();
|
||||
conn.execute_batch("DROP TRIGGER reject_conversion_shutdown")
|
||||
.unwrap();
|
||||
assert!(result
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("fixture-conversion-shutdown-failure"));
|
||||
assert!(!SHUTTING_DOWN.load(Ordering::Acquire));
|
||||
assert!(lock_manager().unwrap().contains_key(&fixture.dir));
|
||||
let after = FileCheckpoint::capture(&fixture.dir).unwrap();
|
||||
assert_eq!(before.config, after.config);
|
||||
assert_eq!(before.auth, after.auth);
|
||||
assert_eq!(before.selected, after.selected);
|
||||
save_record(&fixture.dir, &record).unwrap();
|
||||
with_provider_change(fixture.scope(), || Ok(())).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converted_reattach_failure_restores_complete_files_selection_and_runtime() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let mut fixture = Fixture::new();
|
||||
fixture.providers[1].upstream_api = Some("anthropic_messages".into());
|
||||
fixture.providers[1] =
|
||||
crate::providers::save_provider_inner(fixture.providers[1].clone()).unwrap();
|
||||
fixture.enable();
|
||||
with_provider_change(fixture.scope(), || {
|
||||
crate::providers::activate_saved_provider_inner(
|
||||
fixture.scope(),
|
||||
fixture.providers[1].id.clone(),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
let before = FileCheckpoint::capture(&fixture.dir).unwrap();
|
||||
let result = with_provider_change(fixture.scope(), || {
|
||||
fs::write(crate::config_path(&fixture.dir), "not valid = [toml").unwrap();
|
||||
fs::write(
|
||||
crate::auth_path(&fixture.dir),
|
||||
r#"{"OPENAI_API_KEY":"replacement-fixture"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
Ok(())
|
||||
});
|
||||
assert!(result.unwrap_err().to_string().contains("恢复原配置"));
|
||||
let after = FileCheckpoint::capture(&fixture.dir).unwrap();
|
||||
assert_eq!(before.config, after.config);
|
||||
assert_eq!(before.auth, after.auth);
|
||||
assert_eq!(before.selected, after.selected);
|
||||
assert_eq!(before.common_handled, after.common_handled);
|
||||
let status = get_status(fixture.scope()).unwrap();
|
||||
assert!(status.running && status.takeover_active);
|
||||
assert_eq!(status.primary.unwrap().id, fixture.providers[1].id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converted_route_restart_keeps_protocol_and_stale_recovery_never_restores_raw_url() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let mut fixture = Fixture::new();
|
||||
fixture.providers[1].upstream_api = Some("gemini".into());
|
||||
fixture.providers[1] =
|
||||
crate::providers::save_provider_inner(fixture.providers[1].clone()).unwrap();
|
||||
let mut settings = fixture.settings();
|
||||
settings.auto_failover_enabled = false;
|
||||
save_settings(fixture.scope(), settings).unwrap();
|
||||
with_provider_change(fixture.scope(), || {
|
||||
crate::providers::activate_saved_provider_inner(
|
||||
fixture.scope(),
|
||||
fixture.providers[1].id.clone(),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
let original = fixture.text();
|
||||
let runtime = lock_manager().unwrap().remove(&fixture.dir).unwrap();
|
||||
runtime.proxy.shutdown();
|
||||
assert!(recover_stale_route(fixture.scope())
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("协议转换"));
|
||||
assert_eq!(fixture.text(), original);
|
||||
initialize().unwrap();
|
||||
let status = get_status(fixture.scope()).unwrap();
|
||||
assert!(status.running && status.takeover_active);
|
||||
assert!(fixture.text().contains("127.0.0.1"));
|
||||
assert_eq!(
|
||||
lock_manager().unwrap().get(&fixture.dir).unwrap().routes[0].protocol,
|
||||
UpstreamApi::Gemini
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failover_to_converted_provider_preserves_close_guard() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let mut fixture = Fixture::new();
|
||||
fixture.providers[1].upstream_api = Some("gemini".into());
|
||||
fixture.providers[1] =
|
||||
crate::providers::save_provider_inner(fixture.providers[1].clone()).unwrap();
|
||||
fixture.enable();
|
||||
let mut runtimes = lock_manager().unwrap();
|
||||
let runtime = runtimes.get(&fixture.dir).unwrap();
|
||||
let notice = SelectionNotice {
|
||||
dir: fixture.dir.clone(),
|
||||
instance_id: runtime.instance_id,
|
||||
token: runtime.token.clone(),
|
||||
event: ProxySelectionEvent {
|
||||
provider_id: fixture.providers[1].id.clone(),
|
||||
revision: runtime.proxy.revision(),
|
||||
},
|
||||
};
|
||||
record_selection(notice, &mut runtimes).unwrap();
|
||||
assert!(
|
||||
runtimes
|
||||
.get(&fixture.dir)
|
||||
.unwrap()
|
||||
.journal
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.requires_conversion
|
||||
);
|
||||
drop(runtimes);
|
||||
let before = fixture.text();
|
||||
let mut disabled = get_status(fixture.scope()).unwrap().settings;
|
||||
disabled.takeover_enabled = false;
|
||||
assert!(save_settings(fixture.scope(), disabled).is_err());
|
||||
assert_eq!(fixture.text(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restore_keeps_external_edits_and_does_not_leave_local_headers() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
@@ -435,6 +888,57 @@ fn failed_restore_keeps_the_listener_alive() {
|
||||
stop(&fixture);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_update_handoff_resumes_saved_routes_and_reopens_mutation_gate() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let fixture = Fixture::new();
|
||||
let before = fixture.enable();
|
||||
let auth = fs::read(crate::auth_path(&fixture.dir)).unwrap();
|
||||
shutdown_all().unwrap();
|
||||
assert!(!get_status(fixture.scope()).unwrap().running);
|
||||
assert!(!fixture.text().contains("http://127.0.0.1:"));
|
||||
resume_after_failed_update().unwrap();
|
||||
let after = get_status(fixture.scope()).unwrap();
|
||||
assert!(after.running && after.takeover_active);
|
||||
assert_eq!(after.settings, before.settings);
|
||||
assert_eq!(fs::read(crate::auth_path(&fixture.dir)).unwrap(), auth);
|
||||
stop(&fixture);
|
||||
assert!(!get_status(fixture.scope()).unwrap().running);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_update_recovery_reports_busy_port_without_erasing_saved_preferences() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let fixture = Fixture::new();
|
||||
let before = fixture.enable();
|
||||
shutdown_all().unwrap();
|
||||
let occupied =
|
||||
std::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, fixture.port)).unwrap();
|
||||
assert!(resume_after_failed_update().is_err());
|
||||
let status = get_status(fixture.scope()).unwrap();
|
||||
assert!(!status.running);
|
||||
assert_eq!(status.settings, before.settings);
|
||||
assert!(!fixture.text().contains("http://127.0.0.1:"));
|
||||
drop(occupied);
|
||||
resume_after_failed_update().unwrap();
|
||||
assert!(get_status(fixture.scope()).unwrap().takeover_active);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persisted_directory_scopes_resolve_to_the_interactive_runtime_key() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
let fixture = Fixture::new();
|
||||
fixture.enable();
|
||||
let scope = normalized_path_scope(&fixture.dir);
|
||||
let stored = stored_directories().unwrap();
|
||||
let restored = stored
|
||||
.iter()
|
||||
.find(|dir| normalized_path_scope(dir) == scope)
|
||||
.unwrap();
|
||||
assert_eq!(*restored, directory(fixture.scope()).unwrap());
|
||||
assert!(lock_manager().unwrap().contains_key(restored));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_restores_and_rejects_queued_enabling_then_restart_resumes_same_port() {
|
||||
let _guard = crate::app_db::test_db_guard();
|
||||
|
||||
@@ -14,8 +14,11 @@ use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
mod app_db;
|
||||
mod app_update;
|
||||
mod app_update_channel;
|
||||
mod backups;
|
||||
mod ccswitch;
|
||||
mod codex_language;
|
||||
mod config_health;
|
||||
mod config_migration;
|
||||
mod constants;
|
||||
@@ -28,6 +31,7 @@ mod live_config;
|
||||
mod paths;
|
||||
mod platform;
|
||||
mod prompts;
|
||||
mod provider_balance;
|
||||
mod providers;
|
||||
mod remote;
|
||||
mod sessions;
|
||||
@@ -237,6 +241,12 @@ pub(crate) fn sanitize_id(input: &str) -> String {
|
||||
}
|
||||
|
||||
fn default_codex_dir() -> Result<PathBuf> {
|
||||
// Explicit app-only override for isolated native validation and portable setups.
|
||||
if let Ok(value) = std::env::var("CODEXX_CONFIG_DIR") {
|
||||
if let Some(path) = codex_dir_from_text(&value)? {
|
||||
return Ok(path);
|
||||
}
|
||||
}
|
||||
if let Ok(value) = std::env::var("CODEX_HOME") {
|
||||
if let Some(path) = codex_dir_from_text(&value)? {
|
||||
return Ok(path);
|
||||
@@ -567,6 +577,67 @@ async fn open_codex_config_file(config_dir: Option<String>) -> Result<()> {
|
||||
.map_err(|_| CodexxError::Config("打开配置文件失败,请稍后重试。".to_string()))?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn refresh_provider_balance(
|
||||
config_dir: Option<String>,
|
||||
source: String,
|
||||
provider_id: String,
|
||||
) -> Result<provider_balance::ProviderBalanceResult> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
provider_balance::refresh_provider_balance_inner(config_dir, source, provider_id)
|
||||
})
|
||||
.await
|
||||
.map_err(|_| CodexxError::Config("刷新供应商余额失败,请稍后重试。".into()))?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn get_provider_balances(
|
||||
config_dir: Option<String>,
|
||||
) -> Result<Vec<provider_balance::ProviderBalanceResult>> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
provider_balance::get_provider_balances_inner(config_dir)
|
||||
})
|
||||
.await
|
||||
.map_err(|_| CodexxError::Config("读取供应商余额失败,请稍后重试。".into()))?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn get_codex_language_status(
|
||||
config_dir: Option<String>,
|
||||
) -> Result<codex_language::LanguageStatus> {
|
||||
tauri::async_runtime::spawn_blocking(move || codex_language::get_status(config_dir))
|
||||
.await
|
||||
.map_err(|_| CodexxError::Config("读取 Codex 界面语言状态失败,请重试。".into()))?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn save_codex_language_preferences(
|
||||
config_dir: Option<String>,
|
||||
locale: codex_language::Locale,
|
||||
enabled: bool,
|
||||
) -> Result<codex_language::LanguageStatus> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
codex_language::save_preferences(config_dir, locale, enabled)
|
||||
})
|
||||
.await
|
||||
.map_err(|_| CodexxError::Config("保存 Codex 界面语言偏好失败,请重试。".into()))?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn apply_codex_language_preferences(
|
||||
config_dir: Option<String>,
|
||||
restore: bool,
|
||||
) -> Result<codex_language::LanguageStatus> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let codex_dir = resolve_codex_dir(config_dir.clone())?;
|
||||
sessions::with_session_maintenance(&codex_dir, || {
|
||||
codex_language::apply(config_dir, restore)
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(|_| CodexxError::Config("应用 Codex 界面语言失败,请查看状态后重试。".into()))?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn get_session_sync_status(
|
||||
config_dir: Option<String>,
|
||||
@@ -652,11 +723,18 @@ async fn get_about_info(config_dir: Option<String>) -> Result<AboutInfo> {
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn restart_codex_desktop() -> std::result::Result<CodexDesktopRestartResult, String> {
|
||||
let (app_name, was_running) =
|
||||
tauri::async_runtime::spawn_blocking(platform::restart_codex_desktop)
|
||||
.await
|
||||
.map_err(|error| format!("重启 Codex 桌面客户端失败: {error}"))??;
|
||||
async fn restart_codex_desktop(
|
||||
config_dir: Option<String>,
|
||||
) -> std::result::Result<CodexDesktopRestartResult, String> {
|
||||
let (app_name, was_running) = tauri::async_runtime::spawn_blocking(move || {
|
||||
let codex_dir = resolve_codex_dir(config_dir.clone()).map_err(|e| e.to_string())?;
|
||||
sessions::with_session_maintenance(&codex_dir, || {
|
||||
codex_language::restart_client(config_dir)
|
||||
})
|
||||
.map_err(|e| e.to_string())
|
||||
})
|
||||
.await
|
||||
.map_err(|error| format!("重启 Codex 桌面客户端失败: {error}"))??;
|
||||
Ok(CodexDesktopRestartResult {
|
||||
app_name,
|
||||
was_running,
|
||||
@@ -937,6 +1015,25 @@ async fn list_saved_providers() -> Result<Vec<SavedProvider>> {
|
||||
.map_err(|e| CodexxError::Config(format!("读取供应商列表失败: {e}")))?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn get_provider_order(config_dir: Option<String>) -> Result<Vec<String>> {
|
||||
tauri::async_runtime::spawn_blocking(move || providers::get_provider_order_inner(config_dir))
|
||||
.await
|
||||
.map_err(|error| CodexxError::Config(format!("读取供应商排序失败: {error}")))?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn save_provider_order(
|
||||
config_dir: Option<String>,
|
||||
order: Vec<String>,
|
||||
) -> Result<Vec<String>> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
providers::save_provider_order_inner(config_dir, order)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| CodexxError::Config(format!("保存供应商排序失败: {error}")))?
|
||||
}
|
||||
|
||||
enum ActiveProviderSelectionUpdate {
|
||||
Set(String),
|
||||
ClearIfOfficial,
|
||||
@@ -1011,6 +1108,19 @@ async fn build_provider_toml_draft(
|
||||
.map_err(|e| CodexxError::Config(format!("生成供应商 TOML 失败: {e}")))?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn read_provider_headers(config_text: String) -> Result<Vec<providers::ProviderHeader>> {
|
||||
providers::read_provider_headers_inner(config_text)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn update_provider_headers(
|
||||
config_text: String,
|
||||
headers: Vec<providers::ProviderHeader>,
|
||||
) -> Result<String> {
|
||||
providers::update_provider_headers_inner(config_text, headers)
|
||||
}
|
||||
|
||||
fn save_provider_command_inner(provider: SavedProvider) -> Result<SavedProvider> {
|
||||
let saved = save_provider_inner(provider)?;
|
||||
failover::refresh_saved_routes().map_err(|error| {
|
||||
@@ -1095,6 +1205,11 @@ async fn activate_saved_provider(
|
||||
provider_id: String,
|
||||
) -> Result<ActionResult> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let provider = providers::list_saved_providers_inner()?
|
||||
.into_iter()
|
||||
.find(|provider| provider.id == provider_id)
|
||||
.ok_or_else(|| CodexxError::Config("供应商不存在".to_string()))?;
|
||||
failover::ensure_conversion_route(config_dir.clone(), &provider)?;
|
||||
failover::with_provider_change(config_dir.clone(), || {
|
||||
let result = providers::activate_saved_provider_inner(config_dir, provider_id.clone())?;
|
||||
Ok(finish_provider_selection(
|
||||
@@ -1114,6 +1229,9 @@ async fn save_active_provider(
|
||||
apply_common_config: Option<bool>,
|
||||
) -> Result<ActionResult> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let provider =
|
||||
providers::normalize_saved_provider_for_save(&providers::open_store()?, provider)?;
|
||||
failover::ensure_conversion_route(config_dir.clone(), &provider)?;
|
||||
let result = failover::with_provider_change(config_dir.clone(), || {
|
||||
let provider_id = provider.id.clone();
|
||||
let result = if apply_common_config.unwrap_or(false) {
|
||||
@@ -1147,6 +1265,24 @@ async fn delete_saved_provider(id: String, config_dir: Option<String>) -> Result
|
||||
.map_err(|e| CodexxError::Config(format!("删除供应商失败: {e}")))?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn repair_provider_model_catalog(
|
||||
config_dir: Option<String>,
|
||||
) -> Result<providers::model_catalog::ProviderModelCatalogRepairResult> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let codex_dir = resolve_codex_dir(config_dir)?;
|
||||
let changed = providers::model_catalog::upgrade_owned_model_catalog(&codex_dir)?;
|
||||
Ok(providers::model_catalog::ProviderModelCatalogRepairResult {
|
||||
changed,
|
||||
message: changed.then(|| {
|
||||
"已修复供应商模型菜单的图片输入和思考强度,请重启 Codex 后使用".to_string()
|
||||
}),
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(|e| CodexxError::Config(format!("修复供应商模型菜单失败: {e}")))?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn get_codex_state(config_dir: Option<String>) -> Result<CodexState> {
|
||||
tauri::async_runtime::spawn_blocking(move || get_codex_state_inner(config_dir))
|
||||
@@ -1531,20 +1667,46 @@ async fn save_provider_toml_config(
|
||||
async fn test_provider_connection(
|
||||
base_url: String,
|
||||
api_key: Option<String>,
|
||||
upstream_api: Option<String>,
|
||||
config_text: Option<String>,
|
||||
) -> Result<ProviderConnectionResult> {
|
||||
tauri::async_runtime::spawn_blocking(move || test_provider_connection_inner(base_url, api_key))
|
||||
.await
|
||||
.map_err(|e| CodexxError::Config(format!("测试连接失败: {e}")))?
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
if upstream_api.is_none() && config_text.is_none() {
|
||||
test_provider_connection_inner(base_url, api_key)
|
||||
} else {
|
||||
providers::test_provider_connection_with_protocol_inner(
|
||||
base_url,
|
||||
api_key,
|
||||
upstream_api,
|
||||
config_text,
|
||||
)
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|e| CodexxError::Config(format!("测试连接失败: {e}")))?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn fetch_provider_models(
|
||||
base_url: String,
|
||||
api_key: Option<String>,
|
||||
upstream_api: Option<String>,
|
||||
config_text: Option<String>,
|
||||
) -> Result<ProviderModelsResult> {
|
||||
tauri::async_runtime::spawn_blocking(move || fetch_provider_models_inner(base_url, api_key))
|
||||
.await
|
||||
.map_err(|e| CodexxError::Config(format!("获取模型列表失败: {e}")))?
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
if upstream_api.is_none() && config_text.is_none() {
|
||||
fetch_provider_models_inner(base_url, api_key)
|
||||
} else {
|
||||
providers::fetch_provider_models_with_protocol_inner(
|
||||
base_url,
|
||||
api_key,
|
||||
upstream_api,
|
||||
config_text,
|
||||
)
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|e| CodexxError::Config(format!("获取模型列表失败: {e}")))?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -1767,6 +1929,8 @@ pub fn run() {
|
||||
})
|
||||
.on_window_event(desktop_lifecycle::handle_window_event)
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
app_update_channel::check_online_app_update,
|
||||
app_update::install_app_update,
|
||||
get_about_info,
|
||||
restart_codex_desktop,
|
||||
check_app_update,
|
||||
@@ -1785,6 +1949,11 @@ pub fn run() {
|
||||
check_codex_config,
|
||||
repair_codex_config,
|
||||
open_codex_config_file,
|
||||
refresh_provider_balance,
|
||||
get_provider_balances,
|
||||
get_codex_language_status,
|
||||
save_codex_language_preferences,
|
||||
apply_codex_language_preferences,
|
||||
get_session_sync_status,
|
||||
sync_sessions_provider,
|
||||
delete_codex_sessions,
|
||||
@@ -1800,8 +1969,12 @@ pub fn run() {
|
||||
delete_saved_prompt,
|
||||
enable_saved_prompt,
|
||||
list_saved_providers,
|
||||
get_provider_order,
|
||||
save_provider_order,
|
||||
get_provider_config_base,
|
||||
build_provider_toml_draft,
|
||||
read_provider_headers,
|
||||
update_provider_headers,
|
||||
save_provider,
|
||||
duplicate_provider,
|
||||
update_codex_context_window,
|
||||
@@ -1813,6 +1986,7 @@ pub fn run() {
|
||||
activate_saved_provider,
|
||||
delete_saved_provider,
|
||||
get_codex_state,
|
||||
repair_provider_model_catalog,
|
||||
switch_official_provider,
|
||||
list_official_profiles,
|
||||
get_official_profile,
|
||||
|
||||
@@ -7,6 +7,9 @@ use std::sync::{mpsc, OnceLock};
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[path = "codex_desktop_windows.rs"]
|
||||
pub(crate) mod desktop_windows;
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
use std::env;
|
||||
|
||||
@@ -36,7 +39,7 @@ const CODEX_DESKTOP_COMMAND_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const CODEX_DESKTOP_QUIT_TIMEOUT: Duration = Duration::from_secs(8);
|
||||
#[cfg(target_os = "macos")]
|
||||
const CODEX_DESKTOP_POLL_INTERVAL: Duration = Duration::from_millis(100);
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
#[cfg(test)]
|
||||
const WINDOWS_RESTART_RESULT_PREFIX: &str = "CODEX_X_DESKTOP_RESTART";
|
||||
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
@@ -816,96 +819,209 @@ fn macos_main_process_ids(
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn desktop_command_output(
|
||||
program: &Path,
|
||||
args: &[&str],
|
||||
timeout: Duration,
|
||||
) -> Result<Output, String> {
|
||||
run_program_with_timeout(program, args, Some(Instant::now() + timeout), timeout)
|
||||
.ok_or_else(|| "客户端系统操作超时,未继续重启或连接客户端。".into())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn wait_macos_stopped(executable: &Path) -> Result<(), String> {
|
||||
let deadline = Instant::now() + CODEX_DESKTOP_QUIT_TIMEOUT;
|
||||
let mut empty_since = None;
|
||||
while Instant::now() < deadline {
|
||||
let pids = match macos_main_process_ids(executable, Some(deadline)) {
|
||||
Ok(pids) => pids,
|
||||
Err(_) if Instant::now() >= deadline => break,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
if pids.is_empty() {
|
||||
let since = empty_since.get_or_insert_with(Instant::now);
|
||||
if since.elapsed() >= Duration::from_millis(500) {
|
||||
return Ok(());
|
||||
}
|
||||
} else {
|
||||
empty_since = None;
|
||||
}
|
||||
thread::sleep(CODEX_DESKTOP_POLL_INTERVAL);
|
||||
}
|
||||
Err("Codex/ChatGPT 客户端未正常退出,已取消重新启动;请先结束当前任务后重试。".into())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn launch_macos_codex_app(app: &MacosCodexApp) -> Result<(), String> {
|
||||
let deadline = Instant::now()
|
||||
.checked_add(CODEX_DESKTOP_COMMAND_TIMEOUT)
|
||||
.ok_or_else(|| "创建 Codex/ChatGPT 启动超时时间失败".to_string())?;
|
||||
let bundle_path = app
|
||||
.bundle_path
|
||||
.to_str()
|
||||
.ok_or_else(|| "Codex/ChatGPT 客户端路径不是有效文本".to_string())?;
|
||||
let output = run_program_with_timeout(
|
||||
Path::new("/usr/bin/open"),
|
||||
&["-a", bundle_path],
|
||||
Some(deadline),
|
||||
CODEX_DESKTOP_COMMAND_TIMEOUT,
|
||||
.ok_or("Codex 客户端路径不是有效文本")?;
|
||||
let mut last_error = "未确认 Codex 客户端已启动".to_owned();
|
||||
for attempt in 0..2 {
|
||||
let output = desktop_command_output(
|
||||
Path::new("/usr/bin/open"),
|
||||
&["-n", "-a", bundle_path],
|
||||
CODEX_DESKTOP_COMMAND_TIMEOUT,
|
||||
);
|
||||
let accepted = output.as_ref().is_ok_and(|output| output.status.success());
|
||||
if let Ok(output) = &output {
|
||||
if !output.status.success() {
|
||||
let message = String::from_utf8_lossy(&output.stderr).trim().to_owned();
|
||||
if !message.is_empty() {
|
||||
last_error = message;
|
||||
}
|
||||
}
|
||||
} else if let Err(error) = output {
|
||||
last_error = error;
|
||||
}
|
||||
// LaunchServices can acknowledge a launch before a process appears,
|
||||
// or report a stale quit/launch error after the new process starts.
|
||||
let deadline = Instant::now()
|
||||
+ if accepted {
|
||||
CODEX_DESKTOP_QUIT_TIMEOUT
|
||||
} else {
|
||||
Duration::from_millis(750)
|
||||
};
|
||||
let mut observed = None;
|
||||
while Instant::now() < deadline {
|
||||
let pids = match macos_main_process_ids(&app.executable_path, Some(deadline)) {
|
||||
Ok(pids) => pids,
|
||||
Err(_) if Instant::now() >= deadline => break,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
if !pids.is_empty() {
|
||||
let (previous, since) =
|
||||
observed.get_or_insert_with(|| (pids.clone(), Instant::now()));
|
||||
if *previous == pids && since.elapsed() >= Duration::from_millis(200) {
|
||||
return Ok(());
|
||||
}
|
||||
if *previous != pids {
|
||||
*previous = pids;
|
||||
*since = Instant::now();
|
||||
}
|
||||
} else {
|
||||
observed = None;
|
||||
}
|
||||
thread::sleep(CODEX_DESKTOP_POLL_INTERVAL);
|
||||
}
|
||||
if accepted || attempt == 1 {
|
||||
break;
|
||||
}
|
||||
// Retry only an unacknowledged launch with no surviving main process.
|
||||
// Never open a second instance after LaunchServices confirmed one.
|
||||
}
|
||||
Err(format!("启动 Codex/ChatGPT 未完成:{last_error}"))
|
||||
}
|
||||
|
||||
// Narrow helpers shared with the opt-in locale launcher. They do not quit or
|
||||
// launch anything until the explicit locale apply command calls them.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(crate) fn locale_platform_command(program: &Path, args: &[&str]) -> Result<Output, String> {
|
||||
let deadline = Instant::now() + CODEX_DESKTOP_COMMAND_TIMEOUT;
|
||||
let output =
|
||||
run_program_with_timeout(program, args, Some(deadline), CODEX_DESKTOP_COMMAND_TIMEOUT)
|
||||
.ok_or("客户端操作超时,未继续应用语言兼容。")?;
|
||||
if !output.status.success() {
|
||||
return Err("客户端操作未完成,请检查官方客户端状态后重试。".into());
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(crate) fn locale_desktop_app() -> Result<(PathBuf, PathBuf, String, String, String), String> {
|
||||
let deadline = Some(Instant::now() + CODEX_DESKTOP_COMMAND_TIMEOUT);
|
||||
let apps: Vec<_> = macos_codex_apps(deadline)?
|
||||
.into_iter()
|
||||
.filter(|app| {
|
||||
matches!(
|
||||
app.bundle_id.as_str(),
|
||||
"com.openai.codex" | "com.openai.codex.beta"
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let mut running = Vec::new();
|
||||
for app in &apps {
|
||||
if !macos_main_process_ids(&app.executable_path, deadline)?.is_empty() {
|
||||
running.push(app);
|
||||
}
|
||||
}
|
||||
if running.len() > 1 {
|
||||
return Err("检测到多个官方客户端实例,请先保留一个实例再应用界面语言。".into());
|
||||
}
|
||||
let app = running
|
||||
.first()
|
||||
.copied()
|
||||
.or_else(|| apps.first())
|
||||
.ok_or("未找到官方 Codex 客户端")?;
|
||||
let version = macos_info_plist_version(&app.bundle_path).unwrap_or_else(|| "unknown".into());
|
||||
Ok((
|
||||
app.bundle_path.clone(),
|
||||
app.executable_path.clone(),
|
||||
app.bundle_id.clone(),
|
||||
app.app_name.clone(),
|
||||
version,
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(crate) fn locale_desktop_pids(executable: &Path) -> Result<Vec<u32>, String> {
|
||||
macos_main_process_ids(
|
||||
executable,
|
||||
Some(Instant::now() + CODEX_DESKTOP_COMMAND_TIMEOUT),
|
||||
)
|
||||
.ok_or_else(|| "启动 Codex/ChatGPT 客户端失败或超时".to_string())?;
|
||||
if output.status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(crate) fn locale_quit_desktop(executable: &Path, bundle_id: &str) -> Result<(), String> {
|
||||
if !MACOS_CODEX_BUNDLE_IDS.contains(&bundle_id) {
|
||||
return Err("不支持的客户端身份".into());
|
||||
}
|
||||
if locale_desktop_pids(executable)?.is_empty() {
|
||||
return wait_macos_stopped(executable);
|
||||
}
|
||||
let requested = locale_platform_command(
|
||||
Path::new("/usr/bin/osascript"),
|
||||
&[
|
||||
"-e",
|
||||
&format!("tell application id \"{bundle_id}\" to quit"),
|
||||
],
|
||||
);
|
||||
// Apple Events may lose the connection while the application exits. An
|
||||
// error from osascript is not proof that the exact selected process lives.
|
||||
match wait_macos_stopped(executable) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(error) => Err(requested
|
||||
.err()
|
||||
.map(|request| format!("{request};{error}"))
|
||||
.unwrap_or(error)),
|
||||
}
|
||||
let message = String::from_utf8_lossy(&output.stderr).trim().to_string();
|
||||
Err(if message.is_empty() {
|
||||
"启动 Codex/ChatGPT 客户端失败".to_string()
|
||||
} else {
|
||||
format!("启动 Codex/ChatGPT 客户端失败: {message}")
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn restart_codex_desktop() -> Result<(String, bool), String> {
|
||||
let detection_deadline = Instant::now()
|
||||
.checked_add(CODEX_DESKTOP_COMMAND_TIMEOUT)
|
||||
.ok_or_else(|| "创建 Codex/ChatGPT 检测超时时间失败".to_string())?;
|
||||
let apps = macos_codex_apps(Some(detection_deadline))?;
|
||||
let detection_deadline = Some(Instant::now() + CODEX_DESKTOP_COMMAND_TIMEOUT);
|
||||
let apps = macos_codex_apps(detection_deadline)?;
|
||||
let mut first_installed = None;
|
||||
let mut running_app = None;
|
||||
let mut running = Vec::new();
|
||||
for app in apps {
|
||||
let is_running =
|
||||
!macos_main_process_ids(&app.executable_path, Some(detection_deadline))?.is_empty();
|
||||
if is_running {
|
||||
running_app = Some(app);
|
||||
break;
|
||||
}
|
||||
if first_installed.is_none() {
|
||||
if !macos_main_process_ids(&app.executable_path, detection_deadline)?.is_empty() {
|
||||
running.push(app);
|
||||
} else if first_installed.is_none() {
|
||||
first_installed = Some(app);
|
||||
}
|
||||
}
|
||||
let was_running = running_app.is_some();
|
||||
let app = running_app
|
||||
if running.len() > 1 {
|
||||
return Err("检测到多个官方 Codex 客户端,请先保留一个再重启。".into());
|
||||
}
|
||||
let was_running = !running.is_empty();
|
||||
let app = running
|
||||
.pop()
|
||||
.or(first_installed)
|
||||
.ok_or_else(|| "未找到可重启的 Codex/ChatGPT 桌面客户端".to_string())?;
|
||||
if !was_running {
|
||||
launch_macos_codex_app(&app)?;
|
||||
return Ok((app.app_name, false));
|
||||
}
|
||||
|
||||
let quit_script = format!("tell application id \"{}\" to quit", app.bundle_id);
|
||||
let command_deadline = Instant::now()
|
||||
.checked_add(CODEX_DESKTOP_COMMAND_TIMEOUT)
|
||||
.ok_or_else(|| "创建 Codex/ChatGPT 退出命令超时时间失败".to_string())?;
|
||||
let output = run_program_with_timeout(
|
||||
Path::new("/usr/bin/osascript"),
|
||||
&["-e", quit_script.as_str()],
|
||||
Some(command_deadline),
|
||||
CODEX_DESKTOP_COMMAND_TIMEOUT,
|
||||
)
|
||||
.ok_or_else(|| "请求 Codex/ChatGPT 客户端正常退出失败或超时".to_string())?;
|
||||
if !output.status.success() {
|
||||
let message = String::from_utf8_lossy(&output.stderr).trim().to_string();
|
||||
return Err(if message.is_empty() {
|
||||
"请求 Codex/ChatGPT 客户端正常退出失败".to_string()
|
||||
} else {
|
||||
format!("请求 Codex/ChatGPT 客户端正常退出失败: {message}")
|
||||
});
|
||||
}
|
||||
|
||||
let quit_deadline = Instant::now()
|
||||
.checked_add(CODEX_DESKTOP_QUIT_TIMEOUT)
|
||||
.ok_or_else(|| "创建 Codex/ChatGPT 退出等待时间失败".to_string())?;
|
||||
loop {
|
||||
if macos_main_process_ids(&app.executable_path, Some(quit_deadline))?.is_empty() {
|
||||
break;
|
||||
}
|
||||
if Instant::now() >= quit_deadline {
|
||||
return Err("Codex/ChatGPT 客户端未在限定时间内正常退出,已取消重新启动".to_string());
|
||||
}
|
||||
thread::sleep(CODEX_DESKTOP_POLL_INTERVAL);
|
||||
}
|
||||
|
||||
.ok_or("未找到可重启的 Codex 客户端")?;
|
||||
locale_quit_desktop(&app.executable_path, &app.bundle_id)?;
|
||||
launch_macos_codex_app(&app)?;
|
||||
Ok((app.app_name, true))
|
||||
Ok((app.app_name, was_running))
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
@@ -913,7 +1029,7 @@ fn macos_app_version(_deadline: Option<Instant>) -> Option<String> {
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
#[cfg(test)]
|
||||
fn parse_windows_restart_result(output: &str) -> Option<(String, bool)> {
|
||||
output.lines().rev().find_map(|line| {
|
||||
let payload = line
|
||||
@@ -934,7 +1050,7 @@ fn parse_windows_restart_result(output: &str) -> Option<(String, bool)> {
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
#[cfg(test)]
|
||||
fn windows_restart_script() -> String {
|
||||
let identities = WINDOWS_CODEX_PACKAGE_IDENTITIES
|
||||
.iter()
|
||||
@@ -1026,35 +1142,7 @@ $runningFlag = if ($wasRunning) { '1' } else { '0' }
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
pub fn restart_codex_desktop() -> Result<(String, bool), String> {
|
||||
let script = windows_restart_script();
|
||||
let timeout = CODEX_DESKTOP_QUIT_TIMEOUT + CODEX_DESKTOP_COMMAND_TIMEOUT;
|
||||
let deadline = Instant::now()
|
||||
.checked_add(timeout)
|
||||
.ok_or_else(|| "创建 Codex/ChatGPT 重启超时时间失败".to_string())?;
|
||||
let output = run_program_with_timeout(
|
||||
Path::new("powershell.exe"),
|
||||
&[
|
||||
"-NoProfile",
|
||||
"-NonInteractive",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-Command",
|
||||
script.as_str(),
|
||||
],
|
||||
Some(deadline),
|
||||
timeout,
|
||||
)
|
||||
.ok_or_else(|| "重启 Codex/ChatGPT 客户端失败或超时".to_string())?;
|
||||
if !output.status.success() {
|
||||
let message = String::from_utf8_lossy(&output.stderr).trim().to_string();
|
||||
return Err(if message.is_empty() {
|
||||
"重启 Codex/ChatGPT 客户端失败".to_string()
|
||||
} else {
|
||||
format!("重启 Codex/ChatGPT 客户端失败: {message}")
|
||||
});
|
||||
}
|
||||
parse_windows_restart_result(&String::from_utf8_lossy(&output.stdout))
|
||||
.ok_or_else(|| "无法确认 Codex/ChatGPT 客户端的重启结果".to_string())
|
||||
desktop_windows::restart()
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
|
||||
@@ -0,0 +1,860 @@
|
||||
//! Read-only balances for saved providers and the current native provider.
|
||||
//! Request destinations are fixed official URLs, never supplied over IPC.
|
||||
use crate::error::{CodexxError, Result};
|
||||
use crate::providers::{self, SavedProvider};
|
||||
use chrono::{SecondsFormat, Utc};
|
||||
use reqwest::blocking::Client;
|
||||
use reqwest::header::{HeaderValue, ACCEPT, AUTHORIZATION};
|
||||
use serde::Serialize;
|
||||
use serde_json::Value;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::HashMap;
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Condvar, Mutex, OnceLock};
|
||||
use std::time::{Duration, Instant};
|
||||
use toml_edit::{DocumentMut, Item};
|
||||
|
||||
const SUCCESS_TTL: Duration = Duration::from_secs(300);
|
||||
const FAILURE_TTL: Duration = Duration::from_secs(60);
|
||||
const REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const MAX_RESPONSE_BYTES: u64 = 64 * 1024;
|
||||
const MAX_CACHE_ENTRIES: usize = 256;
|
||||
|
||||
#[derive(Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct BalanceAmount {
|
||||
pub(crate) currency: String,
|
||||
/// Exact base-10 text. Never route financial values through f64.
|
||||
pub(crate) amount: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct ProviderBalanceResult {
|
||||
pub(crate) source: String,
|
||||
pub(crate) provider_id: String,
|
||||
pub(crate) vendor: Option<&'static str>,
|
||||
pub(crate) supported: bool,
|
||||
pub(crate) balance_kind: Option<&'static str>,
|
||||
pub(crate) balances: Vec<BalanceAmount>,
|
||||
pub(crate) checked_at: Option<String>,
|
||||
pub(crate) error_code: Option<&'static str>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Vendor {
|
||||
DeepSeek,
|
||||
OpenRouter,
|
||||
SiliconFlow,
|
||||
Moonshot,
|
||||
}
|
||||
impl Vendor {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::DeepSeek => "deepseek",
|
||||
Self::OpenRouter => "openrouter",
|
||||
Self::SiliconFlow => "siliconflow",
|
||||
Self::Moonshot => "moonshot",
|
||||
}
|
||||
}
|
||||
fn endpoint(self) -> &'static str {
|
||||
match self {
|
||||
Self::DeepSeek => "https://api.deepseek.com/user/balance",
|
||||
Self::OpenRouter => "https://openrouter.ai/api/v1/key",
|
||||
Self::SiliconFlow => "https://api.siliconflow.cn/v1/user/info",
|
||||
Self::Moonshot => "https://api.moonshot.cn/v1/users/me/balance",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn vendor_for_provider(provider: &SavedProvider) -> Option<Vendor> {
|
||||
// This flag controls Codex authentication, and legacy third-party routes
|
||||
// can also set it. Eligibility comes from the official API URL below;
|
||||
// official login profiles are never enumerated by this module.
|
||||
let url = reqwest::Url::parse(provider.base_url.trim()).ok()?;
|
||||
if url.scheme() != "https"
|
||||
|| !url.username().is_empty()
|
||||
|| url.password().is_some()
|
||||
|| url.port().is_some_and(|port| port != 443)
|
||||
|| url.query().is_some()
|
||||
|| url.fragment().is_some()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let path = url.path().trim_end_matches('/');
|
||||
let normal_path = matches!(
|
||||
path,
|
||||
"" | "/v1" | "/v1/chat/completions" | "/v1/responses" | "/v1/messages"
|
||||
);
|
||||
match url.host_str()? {
|
||||
"api.deepseek.com" if normal_path => Some(Vendor::DeepSeek),
|
||||
"api.siliconflow.cn" if normal_path => Some(Vendor::SiliconFlow),
|
||||
"api.moonshot.cn" if normal_path => Some(Vendor::Moonshot),
|
||||
"openrouter.ai"
|
||||
if matches!(
|
||||
path,
|
||||
"" | "/api/v1"
|
||||
| "/api/v1/chat/completions"
|
||||
| "/api/v1/responses"
|
||||
| "/api/v1/messages"
|
||||
) =>
|
||||
{
|
||||
Some(Vendor::OpenRouter)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn environment_value(name: &str) -> std::result::Result<String, &'static str> {
|
||||
let mut bytes = name.bytes();
|
||||
if !bytes
|
||||
.next()
|
||||
.is_some_and(|b| b.is_ascii_alphabetic() || b == b'_')
|
||||
|| !bytes.all(|b| b.is_ascii_alphanumeric() || b == b'_')
|
||||
{
|
||||
return Err("invalid_credential");
|
||||
}
|
||||
std::env::var(name).map_err(|_| "missing_key")
|
||||
}
|
||||
|
||||
fn credential(
|
||||
provider: &SavedProvider,
|
||||
detected: bool,
|
||||
) -> std::result::Result<String, &'static str> {
|
||||
let doc = provider
|
||||
.toml_config
|
||||
.as_deref()
|
||||
.filter(|text| !text.trim().is_empty())
|
||||
.map(|text| {
|
||||
text.parse::<DocumentMut>()
|
||||
.map_err(|_| "invalid_configuration")
|
||||
})
|
||||
.transpose()?;
|
||||
let table = doc.as_ref().and_then(|doc| {
|
||||
let id = doc
|
||||
.get("model_provider")
|
||||
.and_then(Item::as_str)
|
||||
.unwrap_or(&provider.id);
|
||||
doc.get("model_providers")?
|
||||
.as_table_like()?
|
||||
.get(id)?
|
||||
.as_table_like()
|
||||
});
|
||||
// Only the official API's Bearer credential is relevant. Do not forward
|
||||
// arbitrary provider headers (Host, cookies, routing headers, etc.).
|
||||
let mut custom_authorization = None;
|
||||
if let Some(table) = table {
|
||||
for (field, from_env) in [("http_headers", false), ("env_http_headers", true)] {
|
||||
if let Some(item) = table.get(field) {
|
||||
let headers = item.as_table_like().ok_or("invalid_configuration")?;
|
||||
for (name, item) in headers.iter() {
|
||||
if name.eq_ignore_ascii_case("authorization") {
|
||||
if custom_authorization.is_some() {
|
||||
return Err("invalid_credential");
|
||||
}
|
||||
let value = item.as_str().ok_or("invalid_credential")?;
|
||||
custom_authorization = Some(if from_env {
|
||||
environment_value(value)?
|
||||
} else {
|
||||
value.to_string()
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// The detected-provider helper may carry a legacy auth.json fallback key.
|
||||
// An explicit native env_key must take precedence over that fallback, so an
|
||||
// unrelated credential cannot win over the route's own environment key.
|
||||
let native_key = if detected && custom_authorization.is_none() {
|
||||
if let Some(key) = table
|
||||
.and_then(|table| table.get("experimental_bearer_token"))
|
||||
.and_then(Item::as_str)
|
||||
.filter(|key| !key.trim().is_empty())
|
||||
{
|
||||
Some(key.to_string())
|
||||
} else if let Some(name) = table
|
||||
.and_then(|table| table.get("env_key"))
|
||||
.and_then(Item::as_str)
|
||||
{
|
||||
Some(environment_value(name)?)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let key = if let Some(authorization) = custom_authorization {
|
||||
let (scheme, key) = authorization.split_once(' ').ok_or("invalid_credential")?;
|
||||
if !scheme.eq_ignore_ascii_case("bearer") {
|
||||
return Err("invalid_credential");
|
||||
}
|
||||
key.to_string()
|
||||
} else if let Some(key) = native_key {
|
||||
key
|
||||
} else if let Some(key) = provider
|
||||
.api_key
|
||||
.as_deref()
|
||||
.filter(|key| !key.trim().is_empty())
|
||||
{
|
||||
key.to_string()
|
||||
} else if let Some(key) = table
|
||||
.and_then(|table| table.get("experimental_bearer_token"))
|
||||
.and_then(Item::as_str)
|
||||
.filter(|key| !key.trim().is_empty())
|
||||
.map(ToString::to_string)
|
||||
.or_else(|| {
|
||||
doc.as_ref()
|
||||
.and_then(|doc| providers::experimental_bearer_token_from_doc(doc, None))
|
||||
})
|
||||
{
|
||||
key
|
||||
} else if let Some(name) = table
|
||||
.and_then(|table| table.get("env_key"))
|
||||
.and_then(Item::as_str)
|
||||
{
|
||||
environment_value(name)?
|
||||
} else {
|
||||
return Err("missing_key");
|
||||
};
|
||||
let key = key.trim();
|
||||
if key.is_empty() {
|
||||
return Err("missing_key");
|
||||
}
|
||||
if key.len() > 16 * 1024 || key.bytes().any(|b| b <= 0x20 || b == 0x7f) {
|
||||
return Err("invalid_credential");
|
||||
}
|
||||
Ok(key.to_string())
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct BalanceValue {
|
||||
kind: Option<&'static str>,
|
||||
balances: Vec<BalanceAmount>,
|
||||
checked_at: String,
|
||||
error: Option<&'static str>,
|
||||
}
|
||||
impl BalanceValue {
|
||||
fn failure(error: &'static str) -> Self {
|
||||
Self {
|
||||
kind: None,
|
||||
balances: Vec::new(),
|
||||
checked_at: Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true),
|
||||
error: Some(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
type CacheEntry = Mutex<Option<(Instant, BalanceValue)>>;
|
||||
fn cache() -> &'static Mutex<HashMap<String, Arc<CacheEntry>>> {
|
||||
static CACHE: OnceLock<Mutex<HashMap<String, Arc<CacheEntry>>>> = OnceLock::new();
|
||||
CACHE.get_or_init(|| Mutex::new(HashMap::new()))
|
||||
}
|
||||
|
||||
fn cached_balance(vendor: Vendor, key: &str, force: bool, requested_at: Instant) -> BalanceValue {
|
||||
let mut digest = Sha256::new();
|
||||
digest.update(vendor.endpoint().as_bytes());
|
||||
digest.update([0]);
|
||||
digest.update(key.as_bytes());
|
||||
let identity = format!("{:x}", digest.finalize());
|
||||
let slot = {
|
||||
let mut entries = cache().lock().unwrap_or_else(|p| p.into_inner());
|
||||
if !entries.contains_key(&identity) && entries.len() >= MAX_CACHE_ENTRIES {
|
||||
entries.retain(|_, entry| {
|
||||
Arc::strong_count(entry) > 1
|
||||
|| entry.try_lock().map_or(true, |value| {
|
||||
value
|
||||
.as_ref()
|
||||
.is_some_and(|(at, _)| at.elapsed() < SUCCESS_TTL)
|
||||
})
|
||||
});
|
||||
}
|
||||
if !entries.contains_key(&identity) && entries.len() >= MAX_CACHE_ENTRIES {
|
||||
return BalanceValue::failure("busy");
|
||||
}
|
||||
Arc::clone(
|
||||
entries
|
||||
.entry(identity)
|
||||
.or_insert_with(|| Arc::new(Mutex::new(None))),
|
||||
)
|
||||
};
|
||||
// A lock per credential, held for the bounded request, deduplicates copies
|
||||
// and overlapping IPC calls without blocking unrelated accounts.
|
||||
let mut entry = slot.lock().unwrap_or_else(|p| p.into_inner());
|
||||
if let Some((at, value)) = entry.as_ref() {
|
||||
let ttl = if value.error.is_some() {
|
||||
FAILURE_TTL
|
||||
} else {
|
||||
SUCCESS_TTL
|
||||
};
|
||||
// A manual refresh bypasses an older TTL entry, but not a request
|
||||
// that finished after this IPC call began. Queued copies of the same
|
||||
// credential therefore share one refresh rather than serially forcing
|
||||
// another HTTP request after acquiring this lock.
|
||||
if *at >= requested_at || (!force && at.elapsed() < ttl) {
|
||||
return value.clone();
|
||||
}
|
||||
}
|
||||
let value = request_balance(vendor, key).unwrap_or_else(BalanceValue::failure);
|
||||
*entry = Some((Instant::now(), value.clone()));
|
||||
value
|
||||
}
|
||||
|
||||
fn json_request(
|
||||
client: &Client,
|
||||
url: &'static str,
|
||||
key: &str,
|
||||
) -> std::result::Result<Value, &'static str> {
|
||||
let mut authorization =
|
||||
HeaderValue::from_str(&format!("Bearer {key}")).map_err(|_| "invalid_credential")?;
|
||||
authorization.set_sensitive(true);
|
||||
let response = client
|
||||
.get(url)
|
||||
.header(ACCEPT, "application/json")
|
||||
.header(AUTHORIZATION, authorization)
|
||||
.send()
|
||||
.map_err(|error| {
|
||||
if error.is_timeout() {
|
||||
"timeout"
|
||||
} else {
|
||||
"network_error"
|
||||
}
|
||||
})?;
|
||||
let status = response.status();
|
||||
if !status.is_success() {
|
||||
return Err(match status.as_u16() {
|
||||
300..=399 => "redirect_blocked",
|
||||
401 => "authentication_failed",
|
||||
403 => "permission_denied",
|
||||
429 => "rate_limited",
|
||||
_ => "http_error",
|
||||
});
|
||||
}
|
||||
if response
|
||||
.content_length()
|
||||
.is_some_and(|size| size > MAX_RESPONSE_BYTES)
|
||||
{
|
||||
return Err("response_too_large");
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
response
|
||||
.take(MAX_RESPONSE_BYTES + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|_| "network_error")?;
|
||||
if bytes.len() as u64 > MAX_RESPONSE_BYTES {
|
||||
return Err("response_too_large");
|
||||
}
|
||||
// serde_json's arbitrary_precision feature preserves the original numeric
|
||||
// lexeme, including OpenRouter and Moonshot's JSON number balances.
|
||||
serde_json::from_slice(&bytes).map_err(|_| "invalid_response")
|
||||
}
|
||||
|
||||
fn amount(currency: &str, value: &Value) -> std::result::Result<BalanceAmount, &'static str> {
|
||||
Ok(BalanceAmount {
|
||||
currency: currency.to_string(),
|
||||
amount: Decimal::from_value(value)?.text(),
|
||||
})
|
||||
}
|
||||
|
||||
fn request_balance(vendor: Vendor, key: &str) -> std::result::Result<BalanceValue, &'static str> {
|
||||
crate::remote::ensure_crypto_provider();
|
||||
// Same fresh-client system/ENV proxy behavior and five-second timeout as
|
||||
// remote_client, with credentials additionally confined by no redirects.
|
||||
let client = Client::builder()
|
||||
.timeout(REQUEST_TIMEOUT)
|
||||
.user_agent("Codex-X")
|
||||
.https_only(true)
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.build()
|
||||
.map_err(|_| "network_error")?;
|
||||
let payload = json_request(&client, vendor.endpoint(), key)?;
|
||||
let mut kind = "balance";
|
||||
let balances = match vendor {
|
||||
// https://api-docs.deepseek.com/api/get-user-balance
|
||||
Vendor::DeepSeek => {
|
||||
let infos = payload
|
||||
.get("balance_infos")
|
||||
.and_then(Value::as_array)
|
||||
.filter(|items| !items.is_empty() && items.len() <= 4)
|
||||
.ok_or("invalid_response")?;
|
||||
let mut balances = Vec::new();
|
||||
for info in infos {
|
||||
let currency = info
|
||||
.get("currency")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|currency| matches!(*currency, "CNY" | "USD"))
|
||||
.ok_or("invalid_response")?;
|
||||
if balances
|
||||
.iter()
|
||||
.any(|item: &BalanceAmount| item.currency == currency)
|
||||
{
|
||||
return Err("invalid_response");
|
||||
}
|
||||
balances.push(amount(
|
||||
currency,
|
||||
info.get("total_balance").ok_or("invalid_response")?,
|
||||
)?);
|
||||
}
|
||||
balances
|
||||
}
|
||||
// https://openrouter.ai/docs/api/api-reference/api-keys/get-current-key
|
||||
// https://openrouter.ai/docs/api/api-reference/credits/get-credits
|
||||
Vendor::OpenRouter => {
|
||||
let data = payload.get("data").ok_or("invalid_response")?;
|
||||
let remaining = data.get("limit_remaining").ok_or("invalid_response")?;
|
||||
if !remaining.is_null() {
|
||||
kind = "credit_limit";
|
||||
vec![amount("USD", remaining)?]
|
||||
} else {
|
||||
// Management permission may be unavailable to ordinary model
|
||||
// keys. Surface its short error code, never request a new key.
|
||||
let credits = json_request(&client, "https://openrouter.ai/api/v1/credits", key)?;
|
||||
let data = credits.get("data").ok_or("invalid_response")?;
|
||||
let total =
|
||||
Decimal::from_value(data.get("total_credits").ok_or("invalid_response")?)?;
|
||||
let usage =
|
||||
Decimal::from_value(data.get("total_usage").ok_or("invalid_response")?)?;
|
||||
vec![BalanceAmount {
|
||||
currency: "USD".into(),
|
||||
amount: total.subtract(usage)?.text(),
|
||||
}]
|
||||
}
|
||||
}
|
||||
// Official CN OpenAPI: github.com/siliconflow/siliconcloud/openapi.yaml
|
||||
// CN monetary units: docs.siliconflow.cn/docs/userguide/faqs/rate-limit-and-upgradation
|
||||
Vendor::SiliconFlow => {
|
||||
if payload.get("status").and_then(Value::as_bool) != Some(true)
|
||||
|| payload.get("code").and_then(Value::as_u64) != Some(20000)
|
||||
{
|
||||
return Err("api_error");
|
||||
}
|
||||
vec![amount(
|
||||
"CNY",
|
||||
payload
|
||||
.get("data")
|
||||
.and_then(|data| data.get("totalBalance"))
|
||||
.ok_or("invalid_response")?,
|
||||
)?]
|
||||
}
|
||||
// https://platform.moonshot.cn/docs/api/balance (CN keys only)
|
||||
Vendor::Moonshot => {
|
||||
if payload.get("status").and_then(Value::as_bool) != Some(true)
|
||||
|| payload.get("code").and_then(Value::as_u64) != Some(0)
|
||||
{
|
||||
return Err("api_error");
|
||||
}
|
||||
vec![amount(
|
||||
"CNY",
|
||||
payload
|
||||
.get("data")
|
||||
.and_then(|data| data.get("available_balance"))
|
||||
.ok_or("invalid_response")?,
|
||||
)?]
|
||||
}
|
||||
};
|
||||
Ok(BalanceValue {
|
||||
kind: Some(kind),
|
||||
balances,
|
||||
checked_at: Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true),
|
||||
error: None,
|
||||
})
|
||||
}
|
||||
|
||||
struct Decimal {
|
||||
units: i128,
|
||||
scale: u32,
|
||||
}
|
||||
impl Decimal {
|
||||
fn from_value(value: &Value) -> std::result::Result<Self, &'static str> {
|
||||
let text = match value {
|
||||
Value::String(text) => text.clone(),
|
||||
Value::Number(number) => number.to_string(),
|
||||
_ => return Err("invalid_response"),
|
||||
};
|
||||
Self::parse(&text)
|
||||
}
|
||||
fn parse(text: &str) -> std::result::Result<Self, &'static str> {
|
||||
if text.is_empty() || text.len() > 128 || text.trim() != text {
|
||||
return Err("invalid_response");
|
||||
}
|
||||
let (negative, unsigned) = text
|
||||
.strip_prefix('-')
|
||||
.map_or((false, text), |text| (true, text));
|
||||
let (mantissa, exponent) = match unsigned.find(['e', 'E']) {
|
||||
Some(index) => (
|
||||
&unsigned[..index],
|
||||
unsigned[index + 1..]
|
||||
.parse::<i32>()
|
||||
.map_err(|_| "invalid_response")?,
|
||||
),
|
||||
None => (unsigned, 0),
|
||||
};
|
||||
if exponent.unsigned_abs() > 36 {
|
||||
return Err("invalid_response");
|
||||
}
|
||||
let (integer, fraction) = mantissa
|
||||
.split_once('.')
|
||||
.map_or((mantissa, ""), |parts| parts);
|
||||
if integer.is_empty()
|
||||
|| !integer.bytes().all(|b| b.is_ascii_digit())
|
||||
|| !fraction.bytes().all(|b| b.is_ascii_digit())
|
||||
|| (mantissa.contains('.') && fraction.is_empty())
|
||||
{
|
||||
return Err("invalid_response");
|
||||
}
|
||||
let digits = format!("{integer}{fraction}");
|
||||
let mut units = digits.parse::<i128>().map_err(|_| "invalid_response")?;
|
||||
if negative {
|
||||
units = -units;
|
||||
}
|
||||
let scale = fraction.len() as i32 - exponent;
|
||||
let scale = if scale < 0 {
|
||||
units = units
|
||||
.checked_mul(
|
||||
10_i128
|
||||
.checked_pow((-scale) as u32)
|
||||
.ok_or("invalid_response")?,
|
||||
)
|
||||
.ok_or("invalid_response")?;
|
||||
0
|
||||
} else if scale > 36 {
|
||||
return Err("invalid_response");
|
||||
} else {
|
||||
scale as u32
|
||||
};
|
||||
Ok(Self { units, scale }.normalized())
|
||||
}
|
||||
fn normalized(mut self) -> Self {
|
||||
while self.scale > 0 && self.units % 10 == 0 {
|
||||
self.units /= 10;
|
||||
self.scale -= 1;
|
||||
}
|
||||
self
|
||||
}
|
||||
fn subtract(self, other: Self) -> std::result::Result<Self, &'static str> {
|
||||
let scale = self.scale.max(other.scale);
|
||||
let align = |number: Self| {
|
||||
number
|
||||
.units
|
||||
.checked_mul(10_i128.checked_pow(scale - number.scale)?)
|
||||
};
|
||||
let units = align(self)
|
||||
.and_then(|left| align(other).and_then(|right| left.checked_sub(right)))
|
||||
.ok_or("invalid_response")?;
|
||||
Ok(Self { units, scale }.normalized())
|
||||
}
|
||||
fn text(&self) -> String {
|
||||
let digits = self.units.unsigned_abs().to_string();
|
||||
let sign = if self.units < 0 { "-" } else { "" };
|
||||
if self.scale == 0 {
|
||||
return format!("{sign}{digits}");
|
||||
}
|
||||
let scale = self.scale as usize;
|
||||
if digits.len() <= scale {
|
||||
format!("{sign}0.{}{digits}", "0".repeat(scale - digits.len()))
|
||||
} else {
|
||||
let at = digits.len() - scale;
|
||||
format!("{sign}{}.{}", &digits[..at], &digits[at..])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn provider_result(
|
||||
source: &str,
|
||||
provider: &SavedProvider,
|
||||
force: bool,
|
||||
requested_at: Instant,
|
||||
) -> ProviderBalanceResult {
|
||||
let mut result = ProviderBalanceResult {
|
||||
source: source.into(),
|
||||
provider_id: if source == "detected" {
|
||||
format!("detected-{}", provider.id)
|
||||
} else {
|
||||
provider.id.clone()
|
||||
},
|
||||
vendor: None,
|
||||
supported: false,
|
||||
balance_kind: None,
|
||||
balances: Vec::new(),
|
||||
checked_at: None,
|
||||
error_code: None,
|
||||
};
|
||||
let Some(vendor) = vendor_for_provider(provider) else {
|
||||
return result;
|
||||
};
|
||||
result.vendor = Some(vendor.name());
|
||||
result.supported = true;
|
||||
let key = match credential(provider, source == "detected") {
|
||||
Ok(key) => key,
|
||||
Err(code) => {
|
||||
result.error_code = Some(code);
|
||||
return result;
|
||||
}
|
||||
};
|
||||
let value = cached_balance(vendor, &key, force, requested_at);
|
||||
result.balance_kind = value.kind;
|
||||
result.balances = value.balances;
|
||||
result.checked_at = Some(value.checked_at);
|
||||
result.error_code = value.error;
|
||||
result
|
||||
}
|
||||
|
||||
fn read_balances_at(
|
||||
home: &Path,
|
||||
continue_query: &(dyn Fn() -> bool + Sync),
|
||||
) -> Result<Vec<ProviderBalanceResult>> {
|
||||
let mut targets: Vec<_> = providers::list_saved_providers_inner()
|
||||
.map_err(|_| CodexxError::Config("读取已保存供应商失败,请稍后重试。".into()))?
|
||||
.into_iter()
|
||||
.map(|provider| ("local", provider))
|
||||
.collect();
|
||||
if let Some(provider) = providers::detected_live_custom_provider(home)
|
||||
.map_err(|_| CodexxError::Config("读取当前供应商配置失败,请检查配置格式后重试。".into()))?
|
||||
{
|
||||
targets.push(("detected", provider));
|
||||
}
|
||||
if targets.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
// Bound concurrent network work. Duplicate account credentials still share
|
||||
// the same cache lock even when represented by multiple cards/sources.
|
||||
let workers = targets.len().min(4);
|
||||
let batches = std::thread::scope(|scope| {
|
||||
let handles: Vec<_> = (0..workers)
|
||||
.map(|offset| {
|
||||
let targets = &targets;
|
||||
scope.spawn(move || {
|
||||
(offset..targets.len())
|
||||
.step_by(workers)
|
||||
.take_while(|_| continue_query())
|
||||
.map(|index| {
|
||||
(
|
||||
index,
|
||||
provider_result(
|
||||
targets[index].0,
|
||||
&targets[index].1,
|
||||
false,
|
||||
Instant::now(),
|
||||
),
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
handles
|
||||
.into_iter()
|
||||
.map(|handle| {
|
||||
handle
|
||||
.join()
|
||||
.map_err(|_| CodexxError::Config("读取供应商余额失败,请稍后重试。".into()))
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()
|
||||
})?;
|
||||
let mut results: Vec<_> = batches.into_iter().flatten().collect();
|
||||
results.sort_by_key(|(index, _)| *index);
|
||||
Ok(results.into_iter().map(|(_, result)| result).collect())
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct MonitorTarget {
|
||||
home: PathBuf,
|
||||
scope: String,
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct MonitorState {
|
||||
target: Option<MonitorTarget>,
|
||||
next_refresh: Option<Instant>,
|
||||
}
|
||||
|
||||
struct BalanceMonitor {
|
||||
state: Mutex<MonitorState>,
|
||||
changed: Condvar,
|
||||
}
|
||||
|
||||
fn refresh_delay(result: &Result<Vec<ProviderBalanceResult>>) -> Duration {
|
||||
let Ok(rows) = result else {
|
||||
return FAILURE_TTL;
|
||||
};
|
||||
let now = Utc::now();
|
||||
rows.iter()
|
||||
.filter(|row| row.supported)
|
||||
.map(|row| {
|
||||
let ttl = if row.error_code.is_some() {
|
||||
FAILURE_TTL
|
||||
} else {
|
||||
SUCCESS_TTL
|
||||
};
|
||||
let elapsed = row
|
||||
.checked_at
|
||||
.as_deref()
|
||||
.and_then(|text| chrono::DateTime::parse_from_rfc3339(text).ok())
|
||||
.map(|checked| {
|
||||
now.signed_duration_since(checked.with_timezone(&Utc))
|
||||
.to_std()
|
||||
.unwrap_or(Duration::ZERO)
|
||||
});
|
||||
elapsed.map_or(ttl, |elapsed| {
|
||||
// checkedAt is second-precision; allow one extra second so
|
||||
// the credential cache's monotonic TTL has certainly expired.
|
||||
// Reading warm/manual-refresh results must not reset a full TTL.
|
||||
ttl.saturating_sub(elapsed)
|
||||
.saturating_add(Duration::from_secs(1))
|
||||
})
|
||||
})
|
||||
.min()
|
||||
.unwrap_or(SUCCESS_TTL)
|
||||
}
|
||||
|
||||
impl BalanceMonitor {
|
||||
fn select(&self, home: PathBuf) -> u64 {
|
||||
let scope = crate::paths::normalized_path_scope(&home);
|
||||
let mut state = self.state.lock().unwrap_or_else(|p| p.into_inner());
|
||||
if let Some(target) = &state.target {
|
||||
if target.scope == scope {
|
||||
return target.generation;
|
||||
}
|
||||
}
|
||||
let generation = state
|
||||
.target
|
||||
.as_ref()
|
||||
.map_or(1, |target| target.generation.wrapping_add(1));
|
||||
state.target = Some(MonitorTarget {
|
||||
home,
|
||||
scope,
|
||||
generation,
|
||||
});
|
||||
// The selecting IPC call performs the first query. Schedule only once
|
||||
// it has completed, rather than racing it or counting from its start.
|
||||
state.next_refresh = None;
|
||||
self.changed.notify_one();
|
||||
generation
|
||||
}
|
||||
|
||||
fn is_current(&self, generation: u64) -> bool {
|
||||
self.state
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.target
|
||||
.as_ref()
|
||||
.is_some_and(|target| target.generation == generation)
|
||||
}
|
||||
|
||||
fn completed(&self, generation: u64, delay: Duration, native: bool) {
|
||||
let mut state = self.state.lock().unwrap_or_else(|p| p.into_inner());
|
||||
if state
|
||||
.target
|
||||
.as_ref()
|
||||
.is_some_and(|target| target.generation == generation)
|
||||
&& (native || state.next_refresh.is_none())
|
||||
{
|
||||
// Reading a warm cache from the renderer must not continually
|
||||
// postpone the independent native deadline.
|
||||
state.next_refresh = Some(Instant::now() + delay);
|
||||
self.changed.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
fn run(&self) {
|
||||
loop {
|
||||
let target = {
|
||||
let mut state = self.state.lock().unwrap_or_else(|p| p.into_inner());
|
||||
loop {
|
||||
if let (Some(target), Some(deadline)) =
|
||||
(state.target.clone(), state.next_refresh)
|
||||
{
|
||||
let now = Instant::now();
|
||||
if now >= deadline {
|
||||
state.next_refresh = None;
|
||||
break target;
|
||||
}
|
||||
let (next, _) = self
|
||||
.changed
|
||||
.wait_timeout(state, deadline.saturating_duration_since(now))
|
||||
.unwrap_or_else(|p| p.into_inner());
|
||||
state = next;
|
||||
} else {
|
||||
state = self.changed.wait(state).unwrap_or_else(|p| p.into_inner());
|
||||
}
|
||||
}
|
||||
};
|
||||
// Re-enumerate current saved/native providers every round. A scope
|
||||
// change cancels queued old work between cards; active HTTP calls
|
||||
// retain their existing bounded timeout and official-only URLs.
|
||||
let result = read_balances_at(&target.home, &|| self.is_current(target.generation));
|
||||
self.completed(target.generation, refresh_delay(&result), true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn native_monitor() -> Result<&'static Arc<BalanceMonitor>> {
|
||||
static MONITOR: OnceLock<std::result::Result<Arc<BalanceMonitor>, String>> = OnceLock::new();
|
||||
MONITOR
|
||||
.get_or_init(|| {
|
||||
let monitor = Arc::new(BalanceMonitor {
|
||||
state: Mutex::new(MonitorState::default()),
|
||||
changed: Condvar::new(),
|
||||
});
|
||||
let worker = Arc::clone(&monitor);
|
||||
std::thread::Builder::new()
|
||||
.name("provider-balance-monitor".into())
|
||||
.spawn(move || worker.run())
|
||||
.map_err(|_| "无法启动供应商余额后台刷新,请重启 Codex-X 后重试。".to_string())?;
|
||||
Ok(monitor)
|
||||
})
|
||||
.as_ref()
|
||||
.map_err(|message| CodexxError::Config(message.clone()))
|
||||
}
|
||||
|
||||
/// The IPC wrapper should run this blocking function on spawn_blocking.
|
||||
/// No URL, API key, arbitrary header or official account ID is accepted.
|
||||
pub(crate) fn get_provider_balances_inner(
|
||||
config_dir: Option<String>,
|
||||
) -> Result<Vec<ProviderBalanceResult>> {
|
||||
let home = crate::resolve_codex_dir(config_dir)?;
|
||||
let monitor = native_monitor()?;
|
||||
let generation = monitor.select(home.clone());
|
||||
let result = read_balances_at(&home, &|| monitor.is_current(generation));
|
||||
monitor.completed(generation, refresh_delay(&result), false);
|
||||
result
|
||||
}
|
||||
|
||||
/// Refresh a single persisted/current card. All connection details are read
|
||||
/// again from trusted local provider storage, never accepted from the caller.
|
||||
pub(crate) fn refresh_provider_balance_inner(
|
||||
config_dir: Option<String>,
|
||||
source: String,
|
||||
provider_id: String,
|
||||
) -> Result<ProviderBalanceResult> {
|
||||
// Include provider lookup in the concurrency window: overlapping calls
|
||||
// may spend different amounts of time reading the store/current config.
|
||||
let requested_at = Instant::now();
|
||||
if !matches!(source.as_str(), "local" | "detected") {
|
||||
return Err(CodexxError::Config(
|
||||
"仅支持刷新已保存或当前检测到的第三方供应商余额。".into(),
|
||||
));
|
||||
}
|
||||
let home = crate::resolve_codex_dir(config_dir)?;
|
||||
let provider = if source == "local" {
|
||||
providers::list_saved_providers_inner()
|
||||
.map_err(|_| CodexxError::Config("读取已保存供应商失败,请稍后重试。".into()))?
|
||||
.into_iter()
|
||||
.find(|provider| provider.id == provider_id)
|
||||
} else {
|
||||
providers::detected_live_custom_provider(&home)
|
||||
.map_err(|_| {
|
||||
CodexxError::Config("读取当前供应商配置失败,请检查配置格式后重试。".into())
|
||||
})?
|
||||
.filter(|provider| format!("detected-{}", provider.id) == provider_id)
|
||||
}
|
||||
.ok_or_else(|| {
|
||||
CodexxError::Config("该供应商已不存在或当前配置已改变,请刷新供应商列表。".into())
|
||||
})?;
|
||||
if vendor_for_provider(&provider).is_none() {
|
||||
return Err(CodexxError::Config("该供应商不支持余额刷新。".into()));
|
||||
}
|
||||
// Deliberately leave the independent five-minute monitor deadline alone.
|
||||
Ok(provider_result(&source, &provider, true, requested_at))
|
||||
}
|
||||
@@ -6,6 +6,7 @@ use super::{
|
||||
};
|
||||
use crate::ccswitch::{ccswitch_db_candidates, default_ccswitch_db_path};
|
||||
use crate::error::{CodexxError, Result};
|
||||
use crate::failover::protocol::UpstreamApi;
|
||||
use crate::sqlite_utils::table_column_set;
|
||||
use crate::string_value;
|
||||
use crate::toml_utils::ensure_table;
|
||||
@@ -43,6 +44,7 @@ pub(crate) struct CcSwitchCodexRow {
|
||||
pub(crate) name: String,
|
||||
pub(crate) settings_config: String,
|
||||
pub(crate) category: Option<String>,
|
||||
pub(crate) meta: Option<String>,
|
||||
}
|
||||
|
||||
pub(crate) fn is_official_ccswitch_row(row: &CcSwitchCodexRow) -> bool {
|
||||
@@ -60,8 +62,13 @@ pub(crate) fn read_ccswitch_codex_rows(conn: &Connection) -> Result<Vec<CcSwitch
|
||||
} else {
|
||||
"NULL"
|
||||
};
|
||||
let meta_column = if provider_columns.contains("meta") {
|
||||
"meta"
|
||||
} else {
|
||||
"NULL"
|
||||
};
|
||||
let provider_query = format!(
|
||||
"SELECT id, name, settings_config, {category_column} FROM providers
|
||||
"SELECT id, name, settings_config, {category_column}, {meta_column} FROM providers
|
||||
WHERE app_type = 'codex' ORDER BY sort_index ASC, created_at ASC"
|
||||
);
|
||||
let mut stmt = conn
|
||||
@@ -74,6 +81,7 @@ pub(crate) fn read_ccswitch_codex_rows(conn: &Connection) -> Result<Vec<CcSwitch
|
||||
name: row.get::<_, String>(1)?,
|
||||
settings_config: row.get::<_, String>(2)?,
|
||||
category: row.get::<_, Option<String>>(3)?,
|
||||
meta: row.get::<_, Option<String>>(4)?,
|
||||
})
|
||||
})
|
||||
.map_err(|e| CodexxError::Database(e.to_string()))?;
|
||||
@@ -116,6 +124,94 @@ fn ccswitch_auth_api_key(settings: &Value) -> Option<String> {
|
||||
.map(ToString::to_string)
|
||||
}
|
||||
|
||||
fn explicit_ccswitch_api_format(
|
||||
row: &CcSwitchCodexRow,
|
||||
object: &Value,
|
||||
prefix: &str,
|
||||
) -> Result<Option<(String, String)>> {
|
||||
for key in ["apiFormat", "api_format"] {
|
||||
let Some(value) = object.get(key).filter(|value| !value.is_null()) else {
|
||||
continue;
|
||||
};
|
||||
let field = format!("{prefix}.{key}");
|
||||
let text = value.as_str().ok_or_else(|| {
|
||||
CodexxError::Config(format!(
|
||||
"cc-switch 供应商 {} 的 {field} 必须是协议名称文本",
|
||||
row.id
|
||||
))
|
||||
})?;
|
||||
if !text.trim().is_empty() {
|
||||
return Ok(Some((text.trim().to_string(), field)));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn ccswitch_upstream_api(
|
||||
row: &CcSwitchCodexRow,
|
||||
settings: &Value,
|
||||
wire_api: &str,
|
||||
provider_id: Option<&str>,
|
||||
) -> Result<Option<String>> {
|
||||
let mut selected = None;
|
||||
if let Some(text) = row.meta.as_deref().filter(|text| !text.trim().is_empty()) {
|
||||
let meta: Value = serde_json::from_str(text).map_err(|_| {
|
||||
CodexxError::Config(format!("cc-switch 供应商 {} 的 meta 不是有效 JSON", row.id))
|
||||
})?;
|
||||
if !meta.is_null() && !meta.is_object() {
|
||||
return Err(CodexxError::Config(format!(
|
||||
"cc-switch 供应商 {} 的 meta 必须是 JSON 对象",
|
||||
row.id
|
||||
)));
|
||||
}
|
||||
selected = explicit_ccswitch_api_format(row, &meta, "meta")?;
|
||||
}
|
||||
if selected.is_none() {
|
||||
if let Some(meta) = settings.get("meta").filter(|meta| !meta.is_null()) {
|
||||
if !meta.is_object() {
|
||||
return Err(CodexxError::Config(format!(
|
||||
"cc-switch 供应商 {} 的 settings.meta 必须是 JSON 对象",
|
||||
row.id
|
||||
)));
|
||||
}
|
||||
selected = explicit_ccswitch_api_format(row, meta, "settings.meta")?;
|
||||
}
|
||||
}
|
||||
if selected.is_none() {
|
||||
selected = explicit_ccswitch_api_format(row, settings, "settings")?;
|
||||
}
|
||||
let explicit = selected.is_some();
|
||||
let (format, field) = selected.unwrap_or_else(|| {
|
||||
(
|
||||
wire_api.trim().to_string(),
|
||||
format!(
|
||||
"config.model_providers.{}.wire_api",
|
||||
provider_id.unwrap_or("<当前供应商>")
|
||||
),
|
||||
)
|
||||
});
|
||||
let protocol = UpstreamApi::from_provider(Some(&format), "responses").map_err(|_| {
|
||||
CodexxError::Config(format!(
|
||||
"cc-switch 供应商 {} 的 {field} 上游协议不受支持;请选择 Responses、Chat Completions、Anthropic Messages 或 Gemini",
|
||||
row.id
|
||||
))
|
||||
})?;
|
||||
// An old native template says nothing about a locally selected bridge.
|
||||
// Leave None so a refresh can retain Codex-X's independent metadata.
|
||||
if !explicit && protocol == UpstreamApi::Responses {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(
|
||||
match protocol {
|
||||
UpstreamApi::Responses => "responses",
|
||||
UpstreamApi::ChatCompletions => "chat_completions",
|
||||
UpstreamApi::AnthropicMessages => "anthropic_messages",
|
||||
UpstreamApi::Gemini => "gemini",
|
||||
}
|
||||
.to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) fn codex_section_from_table(
|
||||
id: &str,
|
||||
table: &Table,
|
||||
@@ -285,6 +381,12 @@ fn ccswitch_provider_template(
|
||||
}
|
||||
providers.insert(provider_id, Item::Table(table));
|
||||
}
|
||||
let table = providers
|
||||
.get_mut(provider_id)
|
||||
.and_then(Item::as_table_mut)?;
|
||||
if table.get("wire_api").and_then(Item::as_str) != Some("responses") {
|
||||
table["wire_api"] = value("responses");
|
||||
}
|
||||
strip_provider_bearer_tokens(&mut doc);
|
||||
Some(doc.to_string().trim_end().to_string())
|
||||
}
|
||||
@@ -292,9 +394,18 @@ fn ccswitch_provider_template(
|
||||
pub(crate) fn build_ccswitch_codex_provider(
|
||||
row: &CcSwitchCodexRow,
|
||||
global_sections: &HashMap<String, CcSwitchCodexSection>,
|
||||
) -> Option<SavedProvider> {
|
||||
let settings: Value = serde_json::from_str(&row.settings_config).ok()?;
|
||||
let section = select_ccswitch_section_for_row(row, &settings, global_sections)?;
|
||||
) -> Result<Option<SavedProvider>> {
|
||||
let Ok(settings) = serde_json::from_str::<Value>(&row.settings_config) else {
|
||||
ccswitch_upstream_api(row, &Value::Null, "responses", None)?;
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(section) = select_ccswitch_section_for_row(row, &settings, global_sections) else {
|
||||
// A configured but unsupported protocol should not be hidden behind
|
||||
// the generic incomplete-provider warning.
|
||||
ccswitch_upstream_api(row, &settings, "responses", None)?;
|
||||
return Ok(None);
|
||||
};
|
||||
let upstream_api = ccswitch_upstream_api(row, &settings, §ion.wire_api, Some(§ion.id))?;
|
||||
let api_key = ccswitch_auth_api_key(&settings).or(section.experimental_bearer_token.clone());
|
||||
let provider_name = section
|
||||
.name
|
||||
@@ -304,19 +415,25 @@ pub(crate) fn build_ccswitch_codex_provider(
|
||||
(!name.is_empty()).then(|| name.to_string())
|
||||
})
|
||||
.unwrap_or_else(|| row.id.clone());
|
||||
let model = section.model.clone()?;
|
||||
let toml_config = ccswitch_provider_template(&settings, §ion, &provider_name, &model)?;
|
||||
Some(SavedProvider {
|
||||
let Some(model) = section.model.clone() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(toml_config) = ccswitch_provider_template(&settings, §ion, &provider_name, &model)
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(Some(SavedProvider {
|
||||
id: custom_provider_id(&row.id),
|
||||
provider_name,
|
||||
base_url: section.base_url,
|
||||
model,
|
||||
api_key,
|
||||
toml_config: Some(toml_config),
|
||||
wire_api: section.wire_api,
|
||||
wire_api: "responses".to_string(),
|
||||
requires_openai_auth: section.requires_openai_auth,
|
||||
upstream_api,
|
||||
model_mappings: Vec::new(),
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) fn import_ccswitch_codex_providers_inner(path: Option<String>) -> Result<ImportResult> {
|
||||
@@ -388,7 +505,7 @@ pub(crate) fn import_ccswitch_codex_providers_inner(path: Option<String>) -> Res
|
||||
));
|
||||
continue;
|
||||
}
|
||||
match build_ccswitch_codex_provider(&row, &global_sections) {
|
||||
match build_ccswitch_codex_provider(&row, &global_sections)? {
|
||||
Some(provider) => {
|
||||
let provider = normalize_saved_provider(provider)?;
|
||||
let result =
|
||||
@@ -521,6 +638,249 @@ mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn protocol_row(format: Option<&str>) -> CcSwitchCodexRow {
|
||||
CcSwitchCodexRow {
|
||||
id: "protocol-fixture".into(),
|
||||
name: "Protocol fixture".into(),
|
||||
settings_config: json!({
|
||||
"auth": {"OPENAI_API_KEY": "fixture-api-key"},
|
||||
"config": "# keep imported comment\nmodel_provider='custom'\nmodel='fixture-model'\n[model_providers.custom]\nname='Protocol fixture'\nbase_url='https://neutral-gateway.example.test/custom-api-prefix'\nwire_api='responses'\nrequires_openai_auth=false\nhttp_headers={X-Title='Fixture title'}\n[mcp_servers.keep]\ncommand='fixture-server'\n",
|
||||
}).to_string(),
|
||||
category: None,
|
||||
meta: format.map(|format| json!({"apiFormat":format}).to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn fixture_ccswitch_database(with_meta: bool) -> (tempfile::TempDir, Connection) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let conn = Connection::open(dir.path().join("fixture-ccswitch.db")).unwrap();
|
||||
let optional = if with_meta {
|
||||
"category TEXT, meta TEXT,"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
conn.execute_batch(&format!(
|
||||
"CREATE TABLE providers (id TEXT, name TEXT, app_type TEXT, settings_config TEXT, {optional} sort_index INTEGER, created_at INTEGER);"
|
||||
)).unwrap();
|
||||
(dir, conn)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn current_database_reads_metadata_and_builds_all_four_protocols_without_endpoint_guessing() {
|
||||
let (_dir, conn) = fixture_ccswitch_database(true);
|
||||
for (index, (format, canonical)) in [
|
||||
("openai_responses", "responses"),
|
||||
("openai_chat", "chat_completions"),
|
||||
("anthropic", "anthropic_messages"),
|
||||
("gemini", "gemini"),
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let mut row = protocol_row(Some(format));
|
||||
row.id = format!("protocol-{index}");
|
||||
conn.execute(
|
||||
"INSERT INTO providers (id,name,app_type,settings_config,meta,sort_index,created_at) VALUES (?1,?2,'codex',?3,?4,?5,1)",
|
||||
rusqlite::params![row.id,row.name,row.settings_config,row.meta,index],
|
||||
).unwrap();
|
||||
let read = read_ccswitch_codex_rows(&conn).unwrap().pop().unwrap();
|
||||
let provider = build_ccswitch_codex_provider(&read, &HashMap::new())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(provider.upstream_api.as_deref(), Some(canonical));
|
||||
assert_eq!(provider.wire_api, "responses");
|
||||
assert_eq!(
|
||||
provider.base_url,
|
||||
"https://neutral-gateway.example.test/custom-api-prefix"
|
||||
);
|
||||
let text = provider.toml_config.unwrap();
|
||||
assert!(text.contains("# keep imported comment"));
|
||||
let doc = text.parse::<DocumentMut>().unwrap();
|
||||
let table = doc["model_providers"]["custom"].as_table().unwrap();
|
||||
assert_eq!(table["wire_api"].as_str(), Some("responses"));
|
||||
assert_eq!(
|
||||
table["http_headers"]["X-Title"].as_str(),
|
||||
Some("Fixture title")
|
||||
);
|
||||
assert!(table.get("upstream_api").is_none());
|
||||
assert!(table.get("apiFormat").is_none());
|
||||
assert_eq!(
|
||||
doc["mcp_servers"]["keep"]["command"].as_str(),
|
||||
Some("fixture-server")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_database_without_metadata_columns_preserves_absence_and_uses_settings_formats() {
|
||||
let (_dir, conn) = fixture_ccswitch_database(false);
|
||||
let mut row = protocol_row(None);
|
||||
let mut settings: Value = serde_json::from_str(&row.settings_config).unwrap();
|
||||
settings["api_format"] = json!("anthropic_messages");
|
||||
row.settings_config = settings.to_string();
|
||||
conn.execute(
|
||||
"INSERT INTO providers (id,name,app_type,settings_config,sort_index,created_at) VALUES (?1,?2,'codex',?3,0,1)",
|
||||
rusqlite::params![row.id,row.name,row.settings_config],
|
||||
).unwrap();
|
||||
let read = read_ccswitch_codex_rows(&conn).unwrap().pop().unwrap();
|
||||
assert!(read.category.is_none());
|
||||
assert!(read.meta.is_none());
|
||||
let provider = build_ccswitch_codex_provider(&read, &HashMap::new())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(provider.upstream_api.as_deref(), Some("anthropic_messages"));
|
||||
let native = build_ccswitch_codex_provider(&protocol_row(None), &HashMap::new())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(native.upstream_api.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn protocol_metadata_priority_is_database_meta_then_nested_settings_then_settings_format() {
|
||||
let mut row = protocol_row(Some("openai_chat"));
|
||||
let mut settings: Value = serde_json::from_str(&row.settings_config).unwrap();
|
||||
settings["meta"] = json!({"apiFormat":"anthropic"});
|
||||
settings["apiFormat"] = json!("gemini");
|
||||
settings["api_format"] = json!("responses");
|
||||
row.settings_config = settings.to_string();
|
||||
let db = build_ccswitch_codex_provider(&row, &HashMap::new())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(db.upstream_api.as_deref(), Some("chat_completions"));
|
||||
row.meta = None;
|
||||
let nested = build_ccswitch_codex_provider(&row, &HashMap::new())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(nested.upstream_api.as_deref(), Some("anthropic_messages"));
|
||||
settings.as_object_mut().unwrap().remove("meta");
|
||||
row.settings_config = settings.to_string();
|
||||
let camel = build_ccswitch_codex_provider(&row, &HashMap::new())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(camel.upstream_api.as_deref(), Some("gemini"));
|
||||
settings.as_object_mut().unwrap().remove("apiFormat");
|
||||
row.settings_config = settings.to_string();
|
||||
let snake = build_ccswitch_codex_provider(&row, &HashMap::new())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(snake.upstream_api.as_deref(), Some("responses"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_metadata_overrides_legacy_wire_format_and_legacy_chat_migrates_native_toml() {
|
||||
let mut row = protocol_row(None);
|
||||
row.settings_config = row
|
||||
.settings_config
|
||||
.replace("wire_api='responses'", "wire_api='chat'");
|
||||
let legacy = build_ccswitch_codex_provider(&row, &HashMap::new())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(legacy.upstream_api.as_deref(), Some("chat_completions"));
|
||||
assert_eq!(legacy.wire_api, "responses");
|
||||
assert_eq!(
|
||||
legacy.toml_config.unwrap().parse::<DocumentMut>().unwrap()["model_providers"]
|
||||
["custom"]["wire_api"]
|
||||
.as_str(),
|
||||
Some("responses")
|
||||
);
|
||||
row.meta = Some(json!({"apiFormat":"openai_responses"}).to_string());
|
||||
let explicit = build_ccswitch_codex_provider(&row, &HashMap::new())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(explicit.upstream_api.as_deref(), Some("responses"));
|
||||
row.settings_config = row
|
||||
.settings_config
|
||||
.replace("wire_api='chat'", "wire_api='unknown-wire'");
|
||||
let overridden = build_ccswitch_codex_provider(&row, &HashMap::new())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(overridden.upstream_api.as_deref(), Some("responses"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_protocol_metadata_reports_its_provider_and_field_without_echoing_credentials() {
|
||||
for (meta, settings_format, key) in [
|
||||
(Some("future_protocol"), None, "meta.apiFormat"),
|
||||
(None, Some("future_protocol"), "settings.api_format"),
|
||||
] {
|
||||
let mut row = protocol_row(meta);
|
||||
if let Some(format) = settings_format {
|
||||
let mut settings: Value = serde_json::from_str(&row.settings_config).unwrap();
|
||||
settings["api_format"] = json!(format);
|
||||
row.settings_config = settings.to_string();
|
||||
}
|
||||
let error = build_ccswitch_codex_provider(&row, &HashMap::new())
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(error.contains(&row.id));
|
||||
assert!(error.contains(key));
|
||||
assert!(error.contains("不受支持"));
|
||||
assert!(!error.contains("fixture-api-key"));
|
||||
}
|
||||
let mut row = protocol_row(None);
|
||||
row.settings_config = row
|
||||
.settings_config
|
||||
.replace("wire_api='responses'", "wire_api='future_wire'");
|
||||
let error = build_ccswitch_codex_provider(&row, &HashMap::new())
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(error.contains("config.model_providers.custom.wire_api"));
|
||||
row.meta = Some(json!({"apiFormat":"future_protocol"}).to_string());
|
||||
row.settings_config = json!({"apiFormat":"responses","config":""}).to_string();
|
||||
assert!(build_ccswitch_codex_provider(&row, &HashMap::new()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_metadata_and_non_text_protocol_fields_are_rejected_without_raw_json() {
|
||||
for meta in ["{fixture-private-meta", "[]", "{\"apiFormat\":42}"] {
|
||||
let mut row = protocol_row(None);
|
||||
row.meta = Some(meta.to_string());
|
||||
let error = build_ccswitch_codex_provider(&row, &HashMap::new())
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(error.contains("meta"));
|
||||
assert!(!error.contains("fixture-private-meta"));
|
||||
assert!(!error.contains("fixture-api-key"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refreshing_old_native_input_keeps_the_local_protocol_but_an_explicit_choice_replaces_it() {
|
||||
let conn = Connection::open_in_memory().unwrap();
|
||||
conn.execute_batch("CREATE TABLE providers (id TEXT PRIMARY KEY,provider_name TEXT NOT NULL,base_url TEXT NOT NULL,model TEXT NOT NULL,api_key TEXT,toml_config TEXT,wire_api TEXT NOT NULL,requires_openai_auth INTEGER NOT NULL,model_mappings_json TEXT NOT NULL,upstream_api TEXT,source TEXT NOT NULL,source_id TEXT,created_at TEXT NOT NULL,updated_at TEXT NOT NULL);").unwrap();
|
||||
let original = normalize_saved_provider(
|
||||
build_ccswitch_codex_provider(&protocol_row(Some("openai_chat")), &HashMap::new())
|
||||
.unwrap()
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
upsert_ccswitch_provider_on_connection(&conn, original, "protocol-fixture").unwrap();
|
||||
let old_input = build_ccswitch_codex_provider(&protocol_row(None), &HashMap::new())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(old_input.upstream_api.is_none());
|
||||
let retained = upsert_ccswitch_provider_on_connection(
|
||||
&conn,
|
||||
normalize_saved_provider(old_input).unwrap(),
|
||||
"protocol-fixture",
|
||||
)
|
||||
.unwrap()
|
||||
.provider;
|
||||
assert_eq!(retained.upstream_api.as_deref(), Some("chat_completions"));
|
||||
let explicit =
|
||||
build_ccswitch_codex_provider(&protocol_row(Some("openai_responses")), &HashMap::new())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let replaced = upsert_ccswitch_provider_on_connection(
|
||||
&conn,
|
||||
normalize_saved_provider(explicit).unwrap(),
|
||||
"protocol-fixture",
|
||||
)
|
||||
.unwrap()
|
||||
.provider;
|
||||
assert_eq!(replaced.upstream_api.as_deref(), Some("responses"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_import_round_trips_complete_config_without_bearer_tokens() {
|
||||
let settings_config = json!({
|
||||
@@ -540,6 +900,8 @@ wire_api = "responses"
|
||||
requires_openai_auth = false
|
||||
experimental_bearer_token = "sk-from-config"
|
||||
request_max_retries = 7
|
||||
http_headers = { "HTTP-Referer" = "https://header.example.test", "User-Agent" = "Fixture agent" }
|
||||
env_http_headers = { "X-Project" = "PROJECT_ID" }
|
||||
|
||||
[model_providers.other]
|
||||
name = "Other provider"
|
||||
@@ -576,10 +938,12 @@ command = "docs-server"
|
||||
name: " Sky2_free ".to_string(),
|
||||
settings_config,
|
||||
category: None,
|
||||
meta: None,
|
||||
};
|
||||
|
||||
let provider =
|
||||
build_ccswitch_codex_provider(&row, &HashMap::new()).expect("build cc-switch provider");
|
||||
let provider = build_ccswitch_codex_provider(&row, &HashMap::new())
|
||||
.expect("valid cc-switch provider")
|
||||
.expect("build cc-switch provider");
|
||||
assert_eq!(provider.id, "magicai-123");
|
||||
assert_eq!(provider.provider_name, "Sky2api");
|
||||
assert_eq!(provider.base_url, "https://proxy.example.com/v1");
|
||||
@@ -607,6 +971,18 @@ command = "docs-server"
|
||||
doc["model_providers"]["custom"]["request_max_retries"].as_integer(),
|
||||
Some(7)
|
||||
);
|
||||
assert_eq!(
|
||||
doc["model_providers"]["custom"]["http_headers"]["HTTP-Referer"].as_str(),
|
||||
Some("https://header.example.test")
|
||||
);
|
||||
assert_eq!(
|
||||
doc["model_providers"]["custom"]["http_headers"]["User-Agent"].as_str(),
|
||||
Some("Fixture agent")
|
||||
);
|
||||
assert_eq!(
|
||||
doc["model_providers"]["custom"]["env_http_headers"]["X-Project"].as_str(),
|
||||
Some("PROJECT_ID")
|
||||
);
|
||||
assert_eq!(
|
||||
doc["model_providers"]["other"]["base_url"].as_str(),
|
||||
Some("https://other.example.com/v1")
|
||||
@@ -665,9 +1041,12 @@ requires_openai_auth = false
|
||||
})
|
||||
.to_string(),
|
||||
category: None,
|
||||
meta: None,
|
||||
};
|
||||
|
||||
assert!(build_ccswitch_codex_provider(&row, &HashMap::new()).is_none());
|
||||
assert!(build_ccswitch_codex_provider(&row, &HashMap::new())
|
||||
.unwrap()
|
||||
.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -697,8 +1076,11 @@ requires_openai_auth = false
|
||||
})
|
||||
.to_string(),
|
||||
category: None,
|
||||
meta: None,
|
||||
};
|
||||
|
||||
assert!(build_ccswitch_codex_provider(&row, &global_sections).is_none());
|
||||
assert!(build_ccswitch_codex_provider(&row, &global_sections)
|
||||
.unwrap()
|
||||
.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
use crate::error::{CodexxError, Result};
|
||||
use crate::failover::protocol::UpstreamApi;
|
||||
#[cfg(test)]
|
||||
use crate::remote::ensure_crypto_provider;
|
||||
use crate::remote::{remote_client, remote_request_error, RemoteSource};
|
||||
use reqwest::blocking::Client;
|
||||
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::cmp::Ordering;
|
||||
use std::collections::HashMap;
|
||||
use std::time::Instant;
|
||||
use toml_edit::{DocumentMut, Item};
|
||||
|
||||
const MODELS_SOURCE_KEY: &str = "获取模型列表";
|
||||
|
||||
@@ -46,18 +49,31 @@ struct ModelPayload {
|
||||
created: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct GeminiModelsPayload {
|
||||
models: Vec<GeminiModelPayload>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct GeminiModelPayload {
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
supported_generation_methods: Vec<String>,
|
||||
}
|
||||
|
||||
enum ProviderModelsAttempt {
|
||||
Success(ProviderModelsResult),
|
||||
HttpError { status: u16, duration_ms: u128 },
|
||||
}
|
||||
|
||||
fn provider_models_url(base_url: &str) -> Result<reqwest::Url> {
|
||||
fn provider_base_url(base_url: &str) -> Result<reqwest::Url> {
|
||||
let trimmed = base_url.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Err(CodexxError::Config("base_url 不能为空".to_string()));
|
||||
}
|
||||
|
||||
let mut url = reqwest::Url::parse(trimmed)
|
||||
let url = reqwest::Url::parse(trimmed)
|
||||
.map_err(|_| CodexxError::Config("base_url 格式不正确".to_string()))?;
|
||||
if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
|
||||
return Err(CodexxError::Config(
|
||||
@@ -65,6 +81,11 @@ fn provider_models_url(base_url: &str) -> Result<reqwest::Url> {
|
||||
));
|
||||
}
|
||||
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
fn provider_models_url(base_url: &str) -> Result<reqwest::Url> {
|
||||
let mut url = provider_base_url(base_url)?;
|
||||
let segments = url
|
||||
.path_segments()
|
||||
.ok_or_else(|| CodexxError::Config("base_url 格式不正确".to_string()))?
|
||||
@@ -93,6 +114,97 @@ fn provider_models_url(base_url: &str) -> Result<reqwest::Url> {
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
fn provider_models_url_with_protocol(
|
||||
base_url: &str,
|
||||
protocol: UpstreamApi,
|
||||
) -> Result<reqwest::Url> {
|
||||
if protocol != UpstreamApi::Gemini {
|
||||
let mut url = provider_base_url(base_url)?;
|
||||
let path = url.path().trim_end_matches('/');
|
||||
let suffix = match protocol {
|
||||
UpstreamApi::Responses => "/responses",
|
||||
UpstreamApi::ChatCompletions => "/chat/completions",
|
||||
UpstreamApi::AnthropicMessages => "/messages",
|
||||
UpstreamApi::Gemini => unreachable!(),
|
||||
};
|
||||
if let Some(prefix) = path.strip_suffix(suffix) {
|
||||
let prefix = prefix.to_string();
|
||||
url.set_path(&prefix);
|
||||
}
|
||||
return provider_models_url(url.as_str());
|
||||
}
|
||||
let mut url = provider_base_url(base_url)?;
|
||||
let path = url.path().trim_end_matches('/');
|
||||
// A pasted generateContent endpoint still points to the same API prefix.
|
||||
let prefix = path
|
||||
.split_once("/models/")
|
||||
.map_or(path, |(prefix, _)| prefix);
|
||||
let path = if prefix.ends_with("/models") {
|
||||
prefix.to_string()
|
||||
} else if prefix.ends_with("/v1") || prefix.ends_with("/v1beta") {
|
||||
format!("{prefix}/models")
|
||||
} else {
|
||||
format!("{prefix}/v1beta/models")
|
||||
};
|
||||
url.set_path(&path);
|
||||
url.set_fragment(None);
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
fn provider_models_headers_with_env(
|
||||
config_text: Option<&str>,
|
||||
resolve_env: impl Fn(&str) -> Option<String>,
|
||||
) -> Result<HeaderMap> {
|
||||
let Some(config_text) = config_text.filter(|text| !text.trim().is_empty()) else {
|
||||
return Ok(HeaderMap::new());
|
||||
};
|
||||
let doc = config_text
|
||||
.parse::<DocumentMut>()
|
||||
.map_err(|_| CodexxError::Config("供应商 TOML 无效,请先修正配置".into()))?;
|
||||
let id = doc
|
||||
.get("model_provider")
|
||||
.and_then(Item::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|id| !id.is_empty())
|
||||
.ok_or_else(|| CodexxError::Config("供应商 TOML 缺少 model_provider".into()))?;
|
||||
let table = doc
|
||||
.get("model_providers")
|
||||
.and_then(Item::as_table)
|
||||
.and_then(|providers| providers.get(id))
|
||||
.and_then(Item::as_table)
|
||||
.ok_or_else(|| CodexxError::Config("供应商 TOML 缺少当前供应商配置表".into()))?;
|
||||
super::store::validate_provider_header_table(table)?;
|
||||
let mut headers = HeaderMap::new();
|
||||
for header in super::store::read_provider_headers_inner(config_text.to_string())? {
|
||||
let text = match header.source {
|
||||
super::store::ProviderHeaderSource::Static => header.value,
|
||||
super::store::ProviderHeaderSource::Env => {
|
||||
resolve_env(&header.value).ok_or_else(|| {
|
||||
CodexxError::Config(format!(
|
||||
"供应商 Header ({}) 所需的环境变量不可用",
|
||||
header.name
|
||||
))
|
||||
})?
|
||||
}
|
||||
};
|
||||
let name = HeaderName::from_bytes(header.name.as_bytes())
|
||||
.map_err(|_| CodexxError::Config("供应商 Header 名称无效".into()))?;
|
||||
let mut value = HeaderValue::from_str(&text).map_err(|_| {
|
||||
CodexxError::Config(format!(
|
||||
"供应商 Header ({}) 值无效,不能包含换行或控制字符",
|
||||
header.name
|
||||
))
|
||||
})?;
|
||||
value.set_sensitive(true);
|
||||
headers.insert(name, value);
|
||||
}
|
||||
Ok(headers)
|
||||
}
|
||||
|
||||
fn provider_models_headers(config_text: Option<&str>) -> Result<HeaderMap> {
|
||||
provider_models_headers_with_env(config_text, |name| std::env::var(name).ok())
|
||||
}
|
||||
|
||||
fn parse_created(value: Option<serde_json::Value>) -> Option<i64> {
|
||||
value.and_then(|value| {
|
||||
value
|
||||
@@ -158,10 +270,42 @@ fn natural_model_id_cmp(left: &str, right: &str) -> Ordering {
|
||||
fn parse_models(body: &str) -> Result<Vec<ProviderModel>> {
|
||||
let payload: ModelsPayload = serde_json::from_str(body)
|
||||
.map_err(|_| CodexxError::Config("模型列表返回格式不正确".to_string()))?;
|
||||
Ok(normalize_models(payload.data))
|
||||
}
|
||||
|
||||
fn parse_models_with_protocol(body: &str, protocol: UpstreamApi) -> Result<Vec<ProviderModel>> {
|
||||
if protocol != UpstreamApi::Gemini {
|
||||
return parse_models(body);
|
||||
}
|
||||
let payload: GeminiModelsPayload = serde_json::from_str(body)
|
||||
.map_err(|_| CodexxError::Config("模型列表返回格式不正确".to_string()))?;
|
||||
let models = payload
|
||||
.models
|
||||
.into_iter()
|
||||
.filter(|model| {
|
||||
model
|
||||
.supported_generation_methods
|
||||
.iter()
|
||||
.any(|method| method == "generateContent")
|
||||
})
|
||||
.map(|model| ModelPayload {
|
||||
id: model
|
||||
.name
|
||||
.trim()
|
||||
.strip_prefix("models/")
|
||||
.unwrap_or(model.name.trim())
|
||||
.to_string(),
|
||||
created: None,
|
||||
})
|
||||
.collect();
|
||||
Ok(normalize_models(models))
|
||||
}
|
||||
|
||||
fn normalize_models(payload: Vec<ModelPayload>) -> Vec<ProviderModel> {
|
||||
let mut models = Vec::<ProviderModel>::new();
|
||||
let mut indexes = HashMap::<String, usize>::new();
|
||||
|
||||
for model in payload.data {
|
||||
for model in payload {
|
||||
let id = model.id.trim();
|
||||
if id.is_empty() {
|
||||
continue;
|
||||
@@ -187,22 +331,70 @@ fn parse_models(body: &str) -> Result<Vec<ProviderModel>> {
|
||||
.then_with(|| natural_model_id_cmp(&right.id, &left.id))
|
||||
});
|
||||
|
||||
Ok(models)
|
||||
models
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn request_provider_models_with_client(
|
||||
client: &Client,
|
||||
base_url: &str,
|
||||
api_key: Option<&str>,
|
||||
) -> Result<ProviderModelsAttempt> {
|
||||
let url = provider_models_url(base_url)?;
|
||||
request_provider_models_with_protocol_client(
|
||||
client,
|
||||
base_url,
|
||||
api_key,
|
||||
UpstreamApi::Responses,
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
fn request_provider_models_with_protocol_client(
|
||||
client: &Client,
|
||||
base_url: &str,
|
||||
api_key: Option<&str>,
|
||||
protocol: UpstreamApi,
|
||||
config_text: Option<&str>,
|
||||
) -> Result<ProviderModelsAttempt> {
|
||||
let headers = provider_models_headers(config_text)?;
|
||||
request_provider_models_with_headers(client, base_url, api_key, protocol, headers)
|
||||
}
|
||||
|
||||
fn request_provider_models_with_headers(
|
||||
client: &Client,
|
||||
base_url: &str,
|
||||
api_key: Option<&str>,
|
||||
protocol: UpstreamApi,
|
||||
headers: HeaderMap,
|
||||
) -> Result<ProviderModelsAttempt> {
|
||||
let url = provider_models_url_with_protocol(base_url, protocol)?;
|
||||
let source = RemoteSource::new(MODELS_SOURCE_KEY, url.as_str(), Some("application/json"));
|
||||
let mut request = client
|
||||
.get(url.as_str())
|
||||
.header(reqwest::header::ACCEPT, "application/json");
|
||||
if let Some(api_key) = api_key.map(str::trim).filter(|key| !key.is_empty()) {
|
||||
request = request.bearer_auth(api_key);
|
||||
if protocol == UpstreamApi::AnthropicMessages {
|
||||
request = request.header("anthropic-version", "2023-06-01");
|
||||
}
|
||||
let custom_auth = ["authorization", "x-api-key", "x-goog-api-key"]
|
||||
.iter()
|
||||
.any(|name| headers.contains_key(*name));
|
||||
if let Some(api_key) = api_key
|
||||
.map(str::trim)
|
||||
.filter(|key| !key.is_empty() && !custom_auth)
|
||||
{
|
||||
let (name, text) = match protocol {
|
||||
UpstreamApi::Responses | UpstreamApi::ChatCompletions => {
|
||||
("authorization", format!("Bearer {api_key}"))
|
||||
}
|
||||
UpstreamApi::AnthropicMessages => ("x-api-key", api_key.to_string()),
|
||||
UpstreamApi::Gemini => ("x-goog-api-key", api_key.to_string()),
|
||||
};
|
||||
let mut value = HeaderValue::from_str(&text)
|
||||
.map_err(|_| CodexxError::Config("供应商 API Key 格式不正确".into()))?;
|
||||
value.set_sensitive(true);
|
||||
request = request.header(name, value);
|
||||
}
|
||||
request = request.headers(headers);
|
||||
|
||||
let started = Instant::now();
|
||||
let response = request
|
||||
@@ -221,15 +413,21 @@ fn request_provider_models_with_client(
|
||||
.text()
|
||||
.map_err(|_| CodexxError::Config("模型列表读取失败".to_string()))?;
|
||||
Ok(ProviderModelsAttempt::Success(ProviderModelsResult {
|
||||
models: parse_models(&body)?,
|
||||
models: parse_models_with_protocol(&body, protocol)?,
|
||||
status,
|
||||
duration_ms,
|
||||
}))
|
||||
}
|
||||
|
||||
fn request_provider_models(base_url: &str, api_key: Option<&str>) -> Result<ProviderModelsAttempt> {
|
||||
fn request_provider_models_with_protocol(
|
||||
base_url: &str,
|
||||
api_key: Option<&str>,
|
||||
upstream_api: Option<&str>,
|
||||
config_text: Option<&str>,
|
||||
) -> Result<ProviderModelsAttempt> {
|
||||
let protocol = UpstreamApi::from_provider(upstream_api, "responses")?;
|
||||
let client = remote_client()?;
|
||||
request_provider_models_with_client(&client, base_url, api_key)
|
||||
request_provider_models_with_protocol_client(&client, base_url, api_key, protocol, config_text)
|
||||
}
|
||||
|
||||
pub(crate) fn provider_status_result(status: u16, duration_ms: u128) -> ProviderConnectionResult {
|
||||
@@ -251,7 +449,21 @@ pub(crate) fn test_provider_connection_inner(
|
||||
base_url: String,
|
||||
api_key: Option<String>,
|
||||
) -> Result<ProviderConnectionResult> {
|
||||
match request_provider_models(&base_url, api_key.as_deref())? {
|
||||
test_provider_connection_with_protocol_inner(base_url, api_key, None, None)
|
||||
}
|
||||
|
||||
pub(crate) fn test_provider_connection_with_protocol_inner(
|
||||
base_url: String,
|
||||
api_key: Option<String>,
|
||||
upstream_api: Option<String>,
|
||||
config_text: Option<String>,
|
||||
) -> Result<ProviderConnectionResult> {
|
||||
match request_provider_models_with_protocol(
|
||||
&base_url,
|
||||
api_key.as_deref(),
|
||||
upstream_api.as_deref(),
|
||||
config_text.as_deref(),
|
||||
)? {
|
||||
ProviderModelsAttempt::Success(result) => {
|
||||
Ok(provider_status_result(result.status, result.duration_ms))
|
||||
}
|
||||
@@ -266,7 +478,21 @@ pub(crate) fn fetch_provider_models_inner(
|
||||
base_url: String,
|
||||
api_key: Option<String>,
|
||||
) -> Result<ProviderModelsResult> {
|
||||
match request_provider_models(&base_url, api_key.as_deref())? {
|
||||
fetch_provider_models_with_protocol_inner(base_url, api_key, None, None)
|
||||
}
|
||||
|
||||
pub(crate) fn fetch_provider_models_with_protocol_inner(
|
||||
base_url: String,
|
||||
api_key: Option<String>,
|
||||
upstream_api: Option<String>,
|
||||
config_text: Option<String>,
|
||||
) -> Result<ProviderModelsResult> {
|
||||
match request_provider_models_with_protocol(
|
||||
&base_url,
|
||||
api_key.as_deref(),
|
||||
upstream_api.as_deref(),
|
||||
config_text.as_deref(),
|
||||
)? {
|
||||
ProviderModelsAttempt::Success(result) => Ok(result),
|
||||
ProviderModelsAttempt::HttpError { status, .. } => {
|
||||
Err(CodexxError::Config(if matches!(status, 401 | 403) {
|
||||
@@ -434,4 +660,204 @@ mod tests {
|
||||
assert!(!message.contains(&base_url));
|
||||
server.join().expect("join mock server");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn protocol_model_urls_preserve_api_prefix_and_do_not_repeat_versions() {
|
||||
for (protocol, base, expected) in [
|
||||
(UpstreamApi::Responses, "https://example.test/v1/responses", "https://example.test/v1/models"),
|
||||
(UpstreamApi::ChatCompletions, "https://example.test/v1/chat/completions", "https://example.test/v1/models"),
|
||||
(UpstreamApi::AnthropicMessages, "https://example.test", "https://example.test/v1/models"),
|
||||
(UpstreamApi::AnthropicMessages, "https://example.test/anthropic/v1/messages", "https://example.test/anthropic/v1/models"),
|
||||
(UpstreamApi::Gemini, "https://example.test", "https://example.test/v1beta/models"),
|
||||
(UpstreamApi::Gemini, "https://example.test/v1beta", "https://example.test/v1beta/models"),
|
||||
(UpstreamApi::Gemini, "https://example.test/v1beta/", "https://example.test/v1beta/models"),
|
||||
(UpstreamApi::Gemini, "https://example.test/v1", "https://example.test/v1/models"),
|
||||
(UpstreamApi::Gemini, "https://example.test/api/google/v1/models", "https://example.test/api/google/v1/models"),
|
||||
(UpstreamApi::Gemini, "https://example.test/api/google/v1beta/models/gemini-2.5-pro:generateContent?route=fixture#ignored", "https://example.test/api/google/v1beta/models?route=fixture"),
|
||||
(UpstreamApi::Gemini, "https://example.test/api/google", "https://example.test/api/google/v1beta/models"),
|
||||
] {
|
||||
assert_eq!(provider_models_url_with_protocol(base, protocol).unwrap().as_str(), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chat_and_anthropic_models_use_their_protocol_authentication() {
|
||||
for (protocol, auth) in [
|
||||
(
|
||||
UpstreamApi::ChatCompletions,
|
||||
"authorization: bearer fixture-protocol-key",
|
||||
),
|
||||
(
|
||||
UpstreamApi::AnthropicMessages,
|
||||
"x-api-key: fixture-protocol-key",
|
||||
),
|
||||
] {
|
||||
let (url, server) = serve_once(200, r#"{"data":[{"id":"fixture-model"}]}"#);
|
||||
let attempt = request_provider_models_with_protocol_client(
|
||||
&direct_client(),
|
||||
&url,
|
||||
Some("fixture-protocol-key"),
|
||||
protocol,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let ProviderModelsAttempt::Success(result) = attempt else {
|
||||
panic!("expected model list")
|
||||
};
|
||||
assert_eq!(result.models[0].id, "fixture-model");
|
||||
let request = server.join().unwrap().to_ascii_lowercase();
|
||||
assert!(request.starts_with("get /v1/models http/1.1"));
|
||||
assert!(request.contains(auth));
|
||||
if protocol == UpstreamApi::AnthropicMessages {
|
||||
assert!(request.contains("anthropic-version: 2023-06-01"));
|
||||
assert!(!request.contains("authorization:"));
|
||||
} else {
|
||||
assert!(!request.contains("x-api-key:"));
|
||||
}
|
||||
assert!(!request.contains("x-goog-api-key:"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gemini_models_use_google_header_and_include_only_generate_content_models() {
|
||||
let body = r#"{"models":[{"name":"models/gemini-2.5-pro","supportedGenerationMethods":["generateContent","countTokens"]},{"name":"models/text-embedding-004","supportedGenerationMethods":["embedContent"]},{"name":" models/gemini-2.5-flash ","supportedGenerationMethods":["generateContent"]},{"name":"models/gemini-2.5-pro","supportedGenerationMethods":["generateContent"]},{"name":"models/count-only","supportedGenerationMethods":["countTokens"]}]}"#;
|
||||
let (url, server) = serve_once(200, body);
|
||||
let attempt = request_provider_models_with_protocol_client(
|
||||
&direct_client(),
|
||||
&format!("{url}/v1beta"),
|
||||
Some("fixture-google-key"),
|
||||
UpstreamApi::Gemini,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let ProviderModelsAttempt::Success(result) = attempt else {
|
||||
panic!("expected Gemini model list")
|
||||
};
|
||||
assert_eq!(
|
||||
result
|
||||
.models
|
||||
.iter()
|
||||
.map(|model| model.id.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
["gemini-2.5-pro", "gemini-2.5-flash"]
|
||||
);
|
||||
let request = server.join().unwrap().to_ascii_lowercase();
|
||||
assert!(request.starts_with("get /v1beta/models http/1.1"));
|
||||
assert!(request.contains("x-goog-api-key: fixture-google-key"));
|
||||
assert!(!request.contains("authorization:"));
|
||||
assert!(!request.contains("x-api-key:"));
|
||||
assert!(!request
|
||||
.lines()
|
||||
.next()
|
||||
.unwrap()
|
||||
.contains("fixture-google-key"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn static_and_environment_headers_are_applied_to_model_discovery() {
|
||||
let config = "model_provider='custom'\n[model_providers.custom]\nhttp_headers={User-Agent='Fixture agent',HTTP-Referer='https://fixture.example.test'}\nenv_http_headers={X-Project='FIXTURE_PROJECT'}\n";
|
||||
let headers = provider_models_headers_with_env(Some(config), |name| {
|
||||
(name == "FIXTURE_PROJECT").then(|| "fixture-project-value".to_string())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(!format!("{headers:?}").contains("fixture-project-value"));
|
||||
let (url, server) = serve_once(200, r#"{"data":[]}"#);
|
||||
request_provider_models_with_headers(
|
||||
&direct_client(),
|
||||
&url,
|
||||
Some("fixture-api-key"),
|
||||
UpstreamApi::Responses,
|
||||
headers,
|
||||
)
|
||||
.unwrap();
|
||||
let request = server.join().unwrap().to_ascii_lowercase();
|
||||
assert!(request.contains("user-agent: fixture agent"));
|
||||
assert!(request.contains("http-referer: https://fixture.example.test"));
|
||||
assert!(request.contains("x-project: fixture-project-value"));
|
||||
assert!(request.contains("authorization: bearer fixture-api-key"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_auth_and_anthropic_version_headers_override_request_defaults() {
|
||||
let config = "model_provider='custom'\n[model_providers.custom]\nhttp_headers={Authorization='Bearer fixture-custom-auth',anthropic-version='2099-01-01'}\n";
|
||||
let (url, server) = serve_once(200, r#"{"data":[]}"#);
|
||||
request_provider_models_with_protocol_client(
|
||||
&direct_client(),
|
||||
&url,
|
||||
Some("fixture-unused-key"),
|
||||
UpstreamApi::AnthropicMessages,
|
||||
Some(config),
|
||||
)
|
||||
.unwrap();
|
||||
let request = server.join().unwrap().to_ascii_lowercase();
|
||||
assert!(request.contains("authorization: bearer fixture-custom-auth"));
|
||||
assert!(request.contains("anthropic-version: 2099-01-01"));
|
||||
assert!(!request.contains("anthropic-version: 2023-06-01"));
|
||||
assert!(!request.contains("x-api-key:"));
|
||||
assert!(!request.contains("fixture-unused-key"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_validation_rejects_duplicates_and_invalid_resolved_values_without_secret_echo() {
|
||||
let duplicate = "model_provider='custom'\n[model_providers.custom]\nhttp_headers={X-Project='fixture-static-secret'}\nenv_http_headers={x-project='FIXTURE_PROJECT'}\n";
|
||||
let error = provider_models_headers_with_env(Some(duplicate), |_| {
|
||||
panic!("validation must happen before resolving environment values")
|
||||
})
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(!error.contains("fixture-static-secret"));
|
||||
assert!(error.contains("重复"));
|
||||
let env = "model_provider='custom'\n[model_providers.custom]\nenv_http_headers={X-Project='FIXTURE_PROJECT'}\n";
|
||||
for resolved in [
|
||||
None,
|
||||
Some("fixture-env-secret\r\nInjected: value".to_string()),
|
||||
] {
|
||||
let error = provider_models_headers_with_env(Some(env), |_| resolved.clone())
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(error.contains("X-Project"));
|
||||
assert!(!error.contains("fixture-env-secret"));
|
||||
assert!(!error.contains("Injected"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gemini_payload_errors_and_authentication_statuses_do_not_echo_private_data() {
|
||||
let (url, server) = serve_once(200, r#"{"models":"fixture-private-response"}"#);
|
||||
let error = request_provider_models_with_protocol_client(
|
||||
&direct_client(),
|
||||
&url,
|
||||
Some("fixture-google-secret"),
|
||||
UpstreamApi::Gemini,
|
||||
None,
|
||||
)
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string();
|
||||
assert!(!error.contains("fixture-private-response"));
|
||||
assert!(!error.contains("fixture-google-secret"));
|
||||
server.join().unwrap();
|
||||
let (url, server) = serve_once(401, r#"{"error":"fixture-auth-private-response"}"#);
|
||||
let attempt = request_provider_models_with_protocol_client(
|
||||
&direct_client(),
|
||||
&url,
|
||||
Some("fixture-anthropic-secret"),
|
||||
UpstreamApi::AnthropicMessages,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let ProviderModelsAttempt::HttpError {
|
||||
status,
|
||||
duration_ms,
|
||||
} = attempt
|
||||
else {
|
||||
panic!("expected authentication status")
|
||||
};
|
||||
let result = provider_status_result(status, duration_ms);
|
||||
assert!(!result.ok);
|
||||
assert_eq!(result.status, Some(401));
|
||||
assert!(!result.message.contains("fixture-auth-private-response"));
|
||||
assert!(!result.message.contains("fixture-anthropic-secret"));
|
||||
server.join().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -583,6 +583,7 @@ pub(crate) fn detected_live_custom_provider(codex_dir: &Path) -> Result<Option<S
|
||||
toml_config: (!toml_config.is_empty()).then_some(toml_config),
|
||||
wire_api: section.wire_api,
|
||||
requires_openai_auth: section.requires_openai_auth,
|
||||
upstream_api: None,
|
||||
model_mappings: Vec::new(),
|
||||
}))
|
||||
}
|
||||
@@ -1203,6 +1204,7 @@ fn merge_provider_toml_into_live_with_policy(
|
||||
"config.toml 缺少 [model_providers.{source_provider_id}]"
|
||||
))
|
||||
})?;
|
||||
super::store::validate_provider_header_table(&source_provider)?;
|
||||
let source_name = source_provider
|
||||
.get("name")
|
||||
.and_then(|item| item.as_str())
|
||||
@@ -1768,6 +1770,52 @@ mod tests {
|
||||
use std::fs;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
#[test]
|
||||
fn header_values_survive_direct_toml_activation_and_invalid_values_are_rejected() {
|
||||
let config = "model_provider='custom'\nmodel='gpt-test'\n[model_providers.custom]\nname='Header fixture'\nbase_url='https://headers.example.test/v1'\nwire_api='responses'\nrequires_openai_auth=false\nhttp_headers={User-Agent='Fixture agent'}\nenv_http_headers={X-Project='PROJECT_ID'}\n";
|
||||
let (doc, _) =
|
||||
merge_provider_toml_into_live(Path::new("fixture.toml"), "", config, None).unwrap();
|
||||
assert_eq!(
|
||||
doc["model_providers"]["custom"]["http_headers"]["User-Agent"].as_str(),
|
||||
Some("Fixture agent")
|
||||
);
|
||||
assert_eq!(
|
||||
doc["model_providers"]["custom"]["env_http_headers"]["X-Project"].as_str(),
|
||||
Some("PROJECT_ID")
|
||||
);
|
||||
let invalid = config.replace(
|
||||
"User-Agent='Fixture agent'",
|
||||
"User-Agent=\"secret\\r\\ninjected\"",
|
||||
);
|
||||
let error = merge_provider_toml_into_live(Path::new("fixture.toml"), "", &invalid, None)
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(error.contains("Header"));
|
||||
assert!(!error.contains("secret"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_api_key_removes_stale_authorization_headers_from_both_sources() {
|
||||
let mut doc = "[custom]\nhttp_headers={Authorization='Bearer stale',X-Trace='keep'}\nenv_http_headers={aUtHoRiZaTiOn='STALE_AUTH',X-Project='PROJECT_ID'}\n".parse::<DocumentMut>().unwrap();
|
||||
let table = doc["custom"].as_table_mut().unwrap();
|
||||
configure_live_provider_auth(table, Some("fixture-key"), false);
|
||||
assert!(table["http_headers"]
|
||||
.as_table_like()
|
||||
.unwrap()
|
||||
.get("Authorization")
|
||||
.is_none());
|
||||
assert!(table["env_http_headers"]
|
||||
.as_table_like()
|
||||
.unwrap()
|
||||
.get("aUtHoRiZaTiOn")
|
||||
.is_none());
|
||||
assert_eq!(table["http_headers"]["X-Trace"].as_str(), Some("keep"));
|
||||
assert_eq!(
|
||||
table["env_http_headers"]["X-Project"].as_str(),
|
||||
Some("PROJECT_ID")
|
||||
);
|
||||
}
|
||||
|
||||
fn active_provider_fixture(
|
||||
tag: u64,
|
||||
id: &str,
|
||||
@@ -1795,6 +1843,7 @@ requires_openai_auth = false
|
||||
)),
|
||||
wire_api: "responses".to_string(),
|
||||
requires_openai_auth: false,
|
||||
upstream_api: None,
|
||||
model_mappings: Vec::new(),
|
||||
}
|
||||
}
|
||||
@@ -2280,6 +2329,7 @@ command = "docs-server"
|
||||
toml_config: None,
|
||||
wire_api: "responses".to_string(),
|
||||
requires_openai_auth: false,
|
||||
upstream_api: None,
|
||||
model_mappings: Vec::new(),
|
||||
},
|
||||
Some(codex_dir.display().to_string()),
|
||||
@@ -2848,7 +2898,7 @@ command = "docs-server"
|
||||
r#"env_key = "STALE_ENV_KEY"
|
||||
env_key_instructions = "Stale environment instructions"
|
||||
auth = { command = "fixture-never-executed" }
|
||||
http_headers = { Authorization = "Bearer stale", "X-Trace" = "keep-static" }
|
||||
http_headers = { "X-Trace" = "keep-static" }
|
||||
env_http_headers = { aUtHoRiZaTiOn = "STALE_AUTH", "X-Project" = "PROJECT_ENV" }
|
||||
"#,
|
||||
);
|
||||
@@ -2907,6 +2957,20 @@ env_http_headers = { aUtHoRiZaTiOn = "STALE_AUTH", "X-Project" = "PROJECT_ENV" }
|
||||
assert_eq!(models[0]["display_name"], "DeepSeek V3");
|
||||
assert_eq!(models[1]["slug"], "deepseek-reasoner");
|
||||
assert_eq!(models[1]["context_window"], 256000);
|
||||
for model in models {
|
||||
assert_eq!(
|
||||
model["input_modalities"],
|
||||
serde_json::json!(["text", "image"])
|
||||
);
|
||||
assert_eq!(
|
||||
model["supported_reasoning_levels"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.last()
|
||||
.unwrap()["effort"],
|
||||
"ultra"
|
||||
);
|
||||
}
|
||||
assert!(!fs::read_to_string(&pointer)
|
||||
.unwrap()
|
||||
.contains("fixture-current-key"));
|
||||
|
||||
@@ -24,8 +24,9 @@ pub(crate) use ccswitch::{
|
||||
#[cfg(test)]
|
||||
pub(crate) use connection::provider_status_result;
|
||||
pub(crate) use connection::{
|
||||
fetch_provider_models_inner, test_provider_connection_inner, ProviderConnectionResult,
|
||||
ProviderModelsResult,
|
||||
fetch_provider_models_inner, fetch_provider_models_with_protocol_inner,
|
||||
test_provider_connection_inner, test_provider_connection_with_protocol_inner,
|
||||
ProviderConnectionResult, ProviderModelsResult,
|
||||
};
|
||||
pub(crate) use live::{
|
||||
activate_saved_provider_inner, build_provider_toml_draft_inner,
|
||||
@@ -59,14 +60,15 @@ pub(crate) use store::{
|
||||
pub(crate) use store::{
|
||||
consolidate_legacy_provider_duplicates_on_connection, custom_provider_id,
|
||||
delete_provider_inner, duplicate_provider_inner, experimental_bearer_token_from_doc,
|
||||
is_placeholder_provider, list_saved_providers_inner, list_saved_providers_on_connection,
|
||||
matching_saved_provider_ids_for_live, matching_saved_provider_ids_for_live_on_connection,
|
||||
normalize_saved_provider, normalize_saved_provider_for_save, provider_template_from_document,
|
||||
reserved_codex_provider_id, rollback_provider_store_inner,
|
||||
save_detected_provider_with_rollback_inner, save_provider_inner,
|
||||
save_provider_with_rollback_inner, strip_provider_bearer_tokens,
|
||||
upsert_ccswitch_provider_on_connection, DuplicateProviderResult, ProviderStoreRollback,
|
||||
ProviderUpsertKind, SavedProvider,
|
||||
get_provider_order_inner, is_placeholder_provider, list_saved_providers_inner,
|
||||
list_saved_providers_on_connection, matching_saved_provider_ids_for_live,
|
||||
matching_saved_provider_ids_for_live_on_connection, normalize_saved_provider,
|
||||
normalize_saved_provider_for_save, provider_template_from_document,
|
||||
read_provider_headers_inner, reserved_codex_provider_id, rollback_provider_store_inner,
|
||||
save_detected_provider_with_rollback_inner, save_provider_inner, save_provider_order_inner,
|
||||
save_provider_with_rollback_inner, strip_provider_bearer_tokens, update_provider_headers_inner,
|
||||
upsert_ccswitch_provider_on_connection, DuplicateProviderResult, ProviderHeader,
|
||||
ProviderStoreRollback, ProviderUpsertKind, SavedProvider,
|
||||
};
|
||||
|
||||
pub(crate) fn open_store() -> Result<Connection> {
|
||||
|
||||
@@ -4,6 +4,10 @@
|
||||
|
||||
use crate::error::{CodexxError, Result};
|
||||
use crate::file_io::{ensure_directory, io_err, write_private_json};
|
||||
use crate::live_config::{
|
||||
acquire_live_config_lock, atomic_write_if_unchanged, ensure_file_snapshot_unchanged,
|
||||
read_file_snapshot, text_from_snapshot,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use sha2::{Digest, Sha256};
|
||||
@@ -37,6 +41,13 @@ pub(crate) struct ProviderModelMapping {
|
||||
pub(crate) context_window: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct ProviderModelCatalogRepairResult {
|
||||
pub(crate) changed: bool,
|
||||
pub(crate) message: Option<String>,
|
||||
}
|
||||
|
||||
fn validate_name(name: &str, label: &str) -> Result<String> {
|
||||
let name = name.trim();
|
||||
if name.is_empty() {
|
||||
@@ -111,8 +122,9 @@ fn model_entry(mapping: &ProviderModelMapping, priority: usize, default_context:
|
||||
// Schema: openai/codex rust-v0.153.4, protocol/src/openai_models.rs,
|
||||
// ModelInfo + ModelsResponse. Keep legacy required fields for older Codex.
|
||||
// Unlike cloning a GPT cache entry, this does not import proprietary model
|
||||
// instructions, hosted tools, service tiers or vision. Expose the same effort
|
||||
// menu for mapped models; the upstream API determines each effort's effect.
|
||||
// instructions, hosted tools or service tiers. Allow image attachments instead
|
||||
// of making the client reject every third-party model before contacting its
|
||||
// provider. The provider determines the supported modalities and efforts.
|
||||
json!({
|
||||
"slug": mapping.model,
|
||||
"display_name": mapping.display_name,
|
||||
@@ -142,7 +154,7 @@ fn model_entry(mapping: &ProviderModelMapping, priority: usize, default_context:
|
||||
"max_context_window": context_window,
|
||||
"effective_context_window_percent": 95,
|
||||
"experimental_supported_tools": [],
|
||||
"input_modalities": ["text"],
|
||||
"input_modalities": ["text", "image"],
|
||||
"supports_search_tool": false,
|
||||
"use_responses_lite": false,
|
||||
"prefer_websockets": false
|
||||
@@ -344,6 +356,15 @@ pub(crate) fn prepare_model_catalog(
|
||||
"source": "codex-x", "format": 1,
|
||||
"provider_hash": format!("{:x}", Sha256::digest(provider_id.as_bytes()))
|
||||
});
|
||||
let path = persist_owned_catalog(codex_dir, &catalog)?;
|
||||
// Change the caller's document only after a complete catalog is available.
|
||||
// The caller owns the live config transaction; no auth/config files are
|
||||
// read or written here, and models_cache.json is intentionally untouched.
|
||||
doc[CATALOG_FIELD] = value(path.to_string_lossy().to_string());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn persist_owned_catalog(codex_dir: &Path, catalog: &Value) -> Result<PathBuf> {
|
||||
let filename = catalog_filename(&catalog)?;
|
||||
let directory = prepare_owned_directory(codex_dir)?;
|
||||
let path = directory.join(filename);
|
||||
@@ -355,22 +376,101 @@ pub(crate) fn prepare_model_catalog(
|
||||
));
|
||||
}
|
||||
let existing = fs::read(&path).map_err(|error| io_err(&path, error))?;
|
||||
if serde_json::from_slice::<Value>(&existing).ok().as_ref() != Some(&catalog) {
|
||||
if serde_json::from_slice::<Value>(&existing).ok().as_ref() != Some(catalog) {
|
||||
return Err(CodexxError::Config(
|
||||
"已生成的模型目录文件被修改,未覆盖原文件".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
write_private_json(&path, &catalog)?
|
||||
write_private_json(&path, catalog)?
|
||||
}
|
||||
Err(error) => return Err(io_err(&path, error)),
|
||||
}
|
||||
// Change the caller's document only after a complete catalog is available.
|
||||
// The caller owns the live config transaction; no auth/config files are
|
||||
// read or written here, and models_cache.json is intentionally untouched.
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// Upgrade a verified Codex-X catalog already selected by an older app. Keep
|
||||
/// the old immutable file available for backups and failed provider switches.
|
||||
/// User catalogs, edited generated files and official configurations are skipped.
|
||||
pub(crate) fn upgrade_owned_model_catalog(codex_dir: &Path) -> Result<bool> {
|
||||
let cfg = crate::config_path(codex_dir);
|
||||
let original = read_file_snapshot(&cfg)?;
|
||||
let text = text_from_snapshot(&cfg, original.as_deref())?;
|
||||
if text.trim().is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
let mut doc = crate::file_io::parse_toml_document(&cfg, &text)?;
|
||||
if super::document_is_official(&doc) {
|
||||
return Ok(false);
|
||||
}
|
||||
let Some(pointer) = doc.get(CATALOG_FIELD).and_then(|item| item.as_str()) else {
|
||||
return Ok(false);
|
||||
};
|
||||
if !is_owned_pointer(codex_dir, pointer) {
|
||||
return Ok(false);
|
||||
}
|
||||
let pointer = Path::new(pointer);
|
||||
let source = if pointer.is_absolute() {
|
||||
pointer.to_path_buf()
|
||||
} else {
|
||||
codex_dir.join(pointer)
|
||||
};
|
||||
let Some(filename) = source.file_name().and_then(|name| name.to_str()) else {
|
||||
return Ok(false);
|
||||
};
|
||||
// Ownership is stronger than the path-only recognition used for removing
|
||||
// stale pointers: only a digest-verified generated catalog may be upgraded.
|
||||
if !has_verified_ownership(&source, filename) {
|
||||
return Ok(false);
|
||||
}
|
||||
let bytes = fs::read(&source).map_err(|error| io_err(&source, error))?;
|
||||
let mut catalog: Value = serde_json::from_slice(&bytes)
|
||||
.map_err(|_| CodexxError::Config("供应商模型目录不是有效的 JSON".into()))?;
|
||||
// Recheck the read snapshot rather than trusting the first verification,
|
||||
// since a user or another process can edit the source between reads.
|
||||
if catalog_filename(&catalog)? != filename {
|
||||
return Ok(false);
|
||||
}
|
||||
let before = catalog.clone();
|
||||
let capabilities = model_entry(
|
||||
&ProviderModelMapping {
|
||||
model: String::new(),
|
||||
display_name: String::new(),
|
||||
context_window: None,
|
||||
},
|
||||
0,
|
||||
DEFAULT_CONTEXT_WINDOW,
|
||||
);
|
||||
for model in catalog["models"]
|
||||
.as_array_mut()
|
||||
.expect("verified catalogs contain a models array")
|
||||
{
|
||||
if !model.is_object() {
|
||||
return Ok(false);
|
||||
}
|
||||
for key in [
|
||||
"input_modalities",
|
||||
"default_reasoning_level",
|
||||
"supported_reasoning_levels",
|
||||
"supports_reasoning_summaries",
|
||||
"supports_reasoning_summary_parameter",
|
||||
"default_reasoning_summary",
|
||||
] {
|
||||
model[key] = capabilities[key].clone();
|
||||
}
|
||||
}
|
||||
if catalog == before {
|
||||
return Ok(false);
|
||||
}
|
||||
let _lock = acquire_live_config_lock(codex_dir)?;
|
||||
ensure_file_snapshot_unchanged(&cfg, original.as_deref())?;
|
||||
ensure_file_snapshot_unchanged(&source, Some(&bytes))?;
|
||||
let path = persist_owned_catalog(codex_dir, &catalog)?;
|
||||
doc[CATALOG_FIELD] = value(path.to_string_lossy().to_string());
|
||||
Ok(())
|
||||
crate::backups::create_backup(codex_dir, "upgrade-provider-model-capabilities")?;
|
||||
atomic_write_if_unchanged(&cfg, original.as_deref(), doc.to_string().as_bytes())?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -418,6 +518,7 @@ mod tests {
|
||||
"deepseek-v4-pro",
|
||||
"vendor/custom-model",
|
||||
"gpt-5.5",
|
||||
"gpt-6-astra",
|
||||
] {
|
||||
let entry = model_entry(&mapping(id, id, None), 0, 128000);
|
||||
let levels: Vec<_> = entry["supported_reasoning_levels"]
|
||||
@@ -537,7 +638,7 @@ mod tests {
|
||||
assert_eq!(model["display_name"], "DeepSeek 常用");
|
||||
assert_eq!(model["context_window"], 131072);
|
||||
assert_eq!(model["apply_patch_tool_type"], Value::Null);
|
||||
assert_eq!(model["input_modalities"], json!(["text"]));
|
||||
assert_eq!(model["input_modalities"], json!(["text", "image"]));
|
||||
assert!(!catalog.to_string().contains("gpt-5.5"));
|
||||
assert!(!catalog.to_string().contains("PRIVATE"));
|
||||
assert!(!catalog.to_string().contains("namespace-secret"));
|
||||
@@ -605,6 +706,148 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
fn legacy_catalog(fixture: &Fixture, doc: &mut DocumentMut) -> (PathBuf, Vec<u8>) {
|
||||
prepare_model_catalog(
|
||||
&fixture.0,
|
||||
"provider",
|
||||
&[
|
||||
mapping("deepseek-flash", "DeepSeek Flash", Some(131072)),
|
||||
mapping("gpt-6-astra", "GPT-6 Astra", Some(1_000_000)),
|
||||
],
|
||||
"deepseek-flash",
|
||||
doc,
|
||||
)
|
||||
.unwrap();
|
||||
let mut legacy = catalog(doc);
|
||||
for model in legacy["models"].as_array_mut().unwrap() {
|
||||
model["input_modalities"] = json!(["text"]);
|
||||
model["supported_reasoning_levels"] = json!([
|
||||
{"effort": "low", "description": "Low effort"},
|
||||
{"effort": "max", "description": "Maximum effort"}
|
||||
]);
|
||||
model["supports_reasoning_summaries"] = json!(false);
|
||||
}
|
||||
let filename = catalog_filename(&legacy).unwrap();
|
||||
let path = owned_catalog_directory(&fixture.0).join(filename);
|
||||
let bytes = serde_json::to_vec(&legacy).unwrap();
|
||||
fs::write(&path, &bytes).unwrap();
|
||||
doc[CATALOG_FIELD] = value(path.to_string_lossy().to_string());
|
||||
(path, bytes)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upgrades_active_legacy_capabilities_without_touching_credentials_or_old_catalog() {
|
||||
let fixture = Fixture::new();
|
||||
let mut doc: DocumentMut = r#"# Keep this comment.
|
||||
model_provider = "custom"
|
||||
model = "deepseek-flash"
|
||||
model_reasoning_effort = "ultra"
|
||||
approval_policy = "never"
|
||||
[model_providers.custom]
|
||||
name = "DeepSeek"
|
||||
base_url = "https://fixture.invalid/v1"
|
||||
wire_api = "responses"
|
||||
"#
|
||||
.parse()
|
||||
.unwrap();
|
||||
let (old_path, old_bytes) = legacy_catalog(&fixture, &mut doc);
|
||||
fs::write(fixture.0.join("config.toml"), doc.to_string()).unwrap();
|
||||
fs::write(fixture.0.join("auth.json"), "untouched-fixture-credential").unwrap();
|
||||
fs::write(fixture.0.join("models_cache.json"), "untouched-model-cache").unwrap();
|
||||
|
||||
assert!(upgrade_owned_model_catalog(&fixture.0).unwrap());
|
||||
let updated: DocumentMut = fs::read_to_string(fixture.0.join("config.toml"))
|
||||
.unwrap()
|
||||
.parse()
|
||||
.unwrap();
|
||||
assert_ne!(path(&updated), old_path);
|
||||
assert_eq!(fs::read(old_path).unwrap(), old_bytes);
|
||||
assert_eq!(updated["model"].as_str(), Some("deepseek-flash"));
|
||||
assert_eq!(updated["model_reasoning_effort"].as_str(), Some("ultra"));
|
||||
assert_eq!(updated["approval_policy"].as_str(), Some("never"));
|
||||
assert!(updated.to_string().contains("# Keep this comment."));
|
||||
assert_eq!(
|
||||
updated["model_providers"]["custom"]["base_url"].as_str(),
|
||||
Some("https://fixture.invalid/v1")
|
||||
);
|
||||
let upgraded = catalog(&updated);
|
||||
assert_eq!(upgraded["models"][0]["slug"], "deepseek-flash");
|
||||
assert_eq!(upgraded["models"][1]["slug"], "gpt-6-astra");
|
||||
assert_eq!(upgraded["models"][0]["context_window"], 131072);
|
||||
assert_eq!(upgraded["models"][1]["context_window"], 1_000_000);
|
||||
for model in upgraded["models"].as_array().unwrap() {
|
||||
assert_eq!(model["input_modalities"], json!(["text", "image"]));
|
||||
assert_eq!(model["supports_reasoning_summaries"], true);
|
||||
assert_eq!(
|
||||
model["supported_reasoning_levels"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.last()
|
||||
.unwrap()["effort"],
|
||||
"ultra"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
fs::read_to_string(fixture.0.join("auth.json")).unwrap(),
|
||||
"untouched-fixture-credential"
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read_to_string(fixture.0.join("models_cache.json")).unwrap(),
|
||||
"untouched-model-cache"
|
||||
);
|
||||
let config_after = fs::read(fixture.0.join("config.toml")).unwrap();
|
||||
assert!(!upgrade_owned_model_catalog(&fixture.0).unwrap());
|
||||
assert_eq!(
|
||||
fs::read(fixture.0.join("config.toml")).unwrap(),
|
||||
config_after
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capability_upgrade_skips_official_and_unverified_catalogs() {
|
||||
let fixture = Fixture::new();
|
||||
let mut doc: DocumentMut = "model_provider = 'custom'\nmodel = 'deepseek-flash'"
|
||||
.parse()
|
||||
.unwrap();
|
||||
let (old_path, old_bytes) = legacy_catalog(&fixture, &mut doc);
|
||||
for provider in ["openai", "custom"] {
|
||||
doc["model_provider"] = value(provider);
|
||||
let config = doc.to_string();
|
||||
fs::write(fixture.0.join("config.toml"), &config).unwrap();
|
||||
if provider == "custom" {
|
||||
let mut modified: Value = serde_json::from_slice(&old_bytes).unwrap();
|
||||
modified["models"][0]["display_name"] = json!("User's own menu");
|
||||
fs::write(&old_path, serde_json::to_vec(&modified).unwrap()).unwrap();
|
||||
}
|
||||
assert!(!upgrade_owned_model_catalog(&fixture.0).unwrap());
|
||||
assert_eq!(
|
||||
fs::read_to_string(fixture.0.join("config.toml")).unwrap(),
|
||||
config
|
||||
);
|
||||
}
|
||||
doc[CATALOG_FIELD] = value("my-models.json");
|
||||
let config = doc.to_string();
|
||||
fs::write(fixture.0.join("config.toml"), &config).unwrap();
|
||||
fs::write(fixture.0.join("my-models.json"), &old_bytes).unwrap();
|
||||
assert!(!upgrade_owned_model_catalog(&fixture.0).unwrap());
|
||||
assert_eq!(
|
||||
fs::read_to_string(fixture.0.join("config.toml")).unwrap(),
|
||||
config
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read(fixture.0.join("my-models.json")).unwrap(),
|
||||
old_bytes
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_config_upgrade_does_not_create_a_codex_home() {
|
||||
let fixture = Fixture::new();
|
||||
let missing = fixture.0.join("missing-codex-home");
|
||||
assert!(!upgrade_owned_model_catalog(&missing).unwrap());
|
||||
assert!(!missing.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabling_removes_only_our_pointer_without_deleting_catalog() {
|
||||
let fixture = Fixture::new();
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,409 @@
|
||||
// Every source, SQLite database, backup and lock in these tests is temporary.
|
||||
fn compress_rollout(logical: &Path) -> std::path::PathBuf {
|
||||
let compressed = logical.with_extension("jsonl.zst");
|
||||
let mut source = fs::File::open(logical).unwrap();
|
||||
let output = fs::File::create(&compressed).unwrap();
|
||||
let mut encoder = zstd::stream::write::Encoder::new(output, 1).unwrap();
|
||||
std::io::copy(&mut source, &mut encoder).unwrap();
|
||||
encoder.finish().unwrap();
|
||||
drop(source);
|
||||
fs::remove_file(logical).unwrap();
|
||||
compressed
|
||||
}
|
||||
|
||||
fn decoded(path: &Path) -> Vec<u8> {
|
||||
let mut source = super::super::super::rollout_stream::decoded_rollout_reader(
|
||||
fs::File::open(path).unwrap(),
|
||||
path,
|
||||
)
|
||||
.unwrap();
|
||||
let mut bytes = Vec::new();
|
||||
source.read_to_end(&mut bytes).unwrap();
|
||||
bytes
|
||||
}
|
||||
|
||||
fn indexed_compressed_fixture(
|
||||
label: &str,
|
||||
) -> (
|
||||
std::path::PathBuf,
|
||||
String,
|
||||
std::path::PathBuf,
|
||||
std::path::PathBuf,
|
||||
) {
|
||||
let dir = temp_codex_dir(label);
|
||||
write_config(&dir, SHARED_SESSION_PROVIDER);
|
||||
let id = "01a0e854-0000-7000-8000-000000000001".to_string();
|
||||
let logical = write_rollout(&dir, &id, "openai");
|
||||
create_thread_database_with_rollout(&dir.join("state_5.sqlite"), &id, "openai", &logical);
|
||||
let compressed = compress_rollout(&logical);
|
||||
(dir, id, logical, compressed)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compressed_logical_reference_syncs_and_keeps_sqlite_alias_and_content() {
|
||||
let (dir, id, logical, compressed) = indexed_compressed_fixture("zst-logical-alias");
|
||||
let mut text = decoded(&compressed);
|
||||
text.extend_from_slice(b"\r\n{\"type\":\"event_msg\",\"payload\":{\"message\":\"untouched\\ntext\",\"unicode\":\"\xe4\xb8\xad\xe6\x96\x87\"}}");
|
||||
fs::write(
|
||||
&compressed,
|
||||
zstd::stream::encode_all(text.as_slice(), 1).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let original = fs::read(&compressed).unwrap();
|
||||
let database = dir.join("state_5.sqlite");
|
||||
Connection::open(&database)
|
||||
.unwrap()
|
||||
.execute("UPDATE threads SET title='renamed title'", [])
|
||||
.unwrap();
|
||||
let status = session_sync_status_inner(Some(dir.display().to_string()), None).unwrap();
|
||||
assert!(status.scan_complete, "{:?}", status.scan_failures);
|
||||
assert!(status.needs_sync);
|
||||
assert_eq!(status.rollout_files, 1);
|
||||
assert_eq!(status.sessions[0].title, "renamed title");
|
||||
assert_eq!(
|
||||
fs::read(&compressed).unwrap(),
|
||||
original,
|
||||
"status is read-only"
|
||||
);
|
||||
let result = sync_sessions_provider_inner(Some(dir.display().to_string()), None).unwrap();
|
||||
assert!(result.status.scan_complete);
|
||||
assert!(!result.status.needs_sync);
|
||||
assert_eq!(result.updated_rollouts, 1);
|
||||
assert_eq!(thread_provider(&database, &id), SHARED_SESSION_PROVIDER);
|
||||
let expected = String::from_utf8(text).unwrap().replace(
|
||||
"\"model_provider\":\"openai\"",
|
||||
"\"model_provider\":\"custom\"",
|
||||
);
|
||||
assert_eq!(decoded(&compressed), expected.as_bytes());
|
||||
let stored: String = Connection::open(&database)
|
||||
.unwrap()
|
||||
.query_row(
|
||||
"SELECT rollout_path FROM threads WHERE id=?1",
|
||||
[&id],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(stored, logical.display().to_string());
|
||||
assert!(
|
||||
!logical.exists(),
|
||||
"sync must not expand or rename logical storage"
|
||||
);
|
||||
let next = fs::read(&compressed).unwrap();
|
||||
let again = sync_sessions_provider_inner(Some(dir.display().to_string()), None).unwrap();
|
||||
assert_eq!(again.updated_rollouts, 0);
|
||||
assert_eq!(again.updated_threads, 0);
|
||||
assert!(again.backup_dir.is_empty());
|
||||
assert_eq!(
|
||||
fs::read(&compressed).unwrap(),
|
||||
next,
|
||||
"matched compressed bytes stay identical"
|
||||
);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_rollout_wins_over_stale_compressed_sibling() {
|
||||
let (dir, id, logical, compressed) = indexed_compressed_fixture("zst-plain-priority");
|
||||
let stale = fs::read(&compressed).unwrap();
|
||||
write_rollout_at(&logical, &id, "openai");
|
||||
let result = sync_sessions_provider_inner(Some(dir.display().to_string()), None).unwrap();
|
||||
assert!(
|
||||
result.status.scan_complete,
|
||||
"{:?}",
|
||||
result.status.scan_failures
|
||||
);
|
||||
assert_eq!(result.updated_rollouts, 1);
|
||||
assert_eq!(result.status.rollout_files, 1);
|
||||
assert_eq!(fs::read(&compressed).unwrap(), stale);
|
||||
assert!(fs::read_to_string(&logical)
|
||||
.unwrap()
|
||||
.contains("\"model_provider\":\"custom\""));
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compressed_archive_and_internal_threads_are_not_promoted_or_modified() {
|
||||
let (dir, id, logical, compressed) = indexed_compressed_fixture("zst-hidden-threads");
|
||||
let database = dir.join("state_5.sqlite");
|
||||
let archived_id = "01a0e854-0000-7000-8000-000000000002";
|
||||
let archived_logical = dir.join(format!(
|
||||
"archived_sessions/rollout-test-{archived_id}.jsonl"
|
||||
));
|
||||
write_rollout_at(&archived_logical, archived_id, "openai");
|
||||
let archived = compress_rollout(&archived_logical);
|
||||
let internal_id = "01a0e854-0000-7000-8000-000000000003";
|
||||
let internal_logical = write_rollout(&dir, internal_id, "openai");
|
||||
fs::write(&internal_logical, format!("{{\"type\":\"session_meta\",\"payload\":{{\"id\":\"{internal_id}\",\"source\":{{\"internal\":\"guardian\"}},\"model_provider\":\"openai\"}}}}\n")).unwrap();
|
||||
let internal = compress_rollout(&internal_logical);
|
||||
let archive_bytes = fs::read(&archived).unwrap();
|
||||
let internal_bytes = fs::read(&internal).unwrap();
|
||||
let conn = Connection::open(&database).unwrap();
|
||||
for (thread, path, archived) in [
|
||||
(archived_id, &archived_logical, 1),
|
||||
(internal_id, &internal_logical, 0),
|
||||
] {
|
||||
conn.execute("INSERT INTO threads(id,model_provider,rollout_path,archived) VALUES(?1,'openai',?2,?3)", (thread, path.display().to_string(), archived)).unwrap();
|
||||
}
|
||||
drop(conn);
|
||||
let catalog = dir.join("sqlite/codex-dev.db");
|
||||
create_catalog_database(&catalog, &[]);
|
||||
let result = sync_sessions_provider_inner(Some(dir.display().to_string()), None).unwrap();
|
||||
assert!(
|
||||
result.status.scan_complete,
|
||||
"{:?}",
|
||||
result.status.scan_failures
|
||||
);
|
||||
assert!(!result.status.needs_sync);
|
||||
assert_eq!(result.updated_rollouts, 1);
|
||||
assert_eq!(thread_provider(&database, &id), SHARED_SESSION_PROVIDER);
|
||||
assert_eq!(thread_provider(&database, internal_id), "openai");
|
||||
assert_eq!(thread_provider(&database, archived_id), "openai");
|
||||
assert_eq!(fs::read(&archived).unwrap(), archive_bytes);
|
||||
assert_eq!(fs::read(&internal).unwrap(), internal_bytes);
|
||||
assert!(catalog_provider_and_visibility(&catalog, internal_id).is_none());
|
||||
assert!(catalog_provider_and_visibility(&catalog, archived_id).is_none());
|
||||
assert_eq!(
|
||||
result
|
||||
.status
|
||||
.sessions
|
||||
.iter()
|
||||
.find(|row| row.id == internal_id)
|
||||
.unwrap()
|
||||
.is_subagent,
|
||||
true
|
||||
);
|
||||
assert!(!logical.exists());
|
||||
assert!(compressed.exists());
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compressed_revert_uses_thread_id_and_current_alias_for_internal_classification() {
|
||||
let dir = temp_codex_dir("zst-revert-identity");
|
||||
write_config(&dir, SHARED_SESSION_PROVIDER);
|
||||
let thread = "01a0e854-0000-7000-8000-000000000004";
|
||||
let rollout = "01a0e854-0000-7000-8000-000000000005";
|
||||
let old = write_rollout(&dir, thread, "openai");
|
||||
fs::write(&old, format!("{{\"type\":\"session_meta\",\"payload\":{{\"id\":\"{thread}\",\"source\":\"subagent\",\"model_provider\":\"openai\"}}}}\n")).unwrap();
|
||||
let old = compress_rollout(&old);
|
||||
let old_bytes = fs::read(&old).unwrap();
|
||||
let current = dir.join(format!(
|
||||
"sessions/2026/10/01/rollout-2026-10-01-{thread}_{rollout}.jsonl"
|
||||
));
|
||||
write_rollout_at(¤t, thread, "openai");
|
||||
let compressed = compress_rollout(¤t);
|
||||
let database = dir.join("state_5.sqlite");
|
||||
create_thread_database_with_rollout(&database, thread, "openai", ¤t);
|
||||
let catalog = dir.join("sqlite/codex-dev.db");
|
||||
create_catalog_database(&catalog, &[]);
|
||||
let result = sync_sessions_provider_inner(Some(dir.display().to_string()), None).unwrap();
|
||||
assert!(
|
||||
result.status.scan_complete,
|
||||
"{:?}",
|
||||
result.status.scan_failures
|
||||
);
|
||||
assert_eq!(result.updated_rollouts, 1);
|
||||
assert_eq!(thread_provider(&database, thread), SHARED_SESSION_PROVIDER);
|
||||
assert!(catalog_provider_and_visibility(&catalog, rollout).is_none());
|
||||
assert_eq!(fs::read(&old).unwrap(), old_bytes);
|
||||
assert!(String::from_utf8(decoded(&compressed))
|
||||
.unwrap()
|
||||
.contains("\"model_provider\":\"custom\""));
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupted_or_truncated_compressed_reference_never_reports_synced() {
|
||||
for invalid in [b"not zstandard".to_vec(), {
|
||||
let mut compressed = zstd::stream::encode_all(&b"{\"type\":\"session_meta\",\"payload\":{\"id\":\"t\",\"model_provider\":\"custom\"}}\n"[..], 1).unwrap();
|
||||
compressed.truncate(compressed.len() - 4);
|
||||
compressed
|
||||
}] {
|
||||
let (dir, id, _logical, compressed) = indexed_compressed_fixture("zst-corrupt");
|
||||
fs::write(&compressed, &invalid).unwrap();
|
||||
let status = session_sync_status_inner(Some(dir.display().to_string()), None).unwrap();
|
||||
assert!(!status.scan_complete);
|
||||
assert!(!status.scan_failures.is_empty());
|
||||
sync_sessions_provider_inner(Some(dir.display().to_string()), None)
|
||||
.expect_err("invalid compressed data blocks every mutation");
|
||||
assert_eq!(thread_provider(&dir.join("state_5.sqlite"), &id), "openai");
|
||||
assert_eq!(fs::read(&compressed).unwrap(), invalid);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compressed_transaction_rollback_restores_exact_original_compressed_bytes() {
|
||||
let (dir, id, _logical, compressed) = indexed_compressed_fixture("zst-rollback");
|
||||
let original = fs::read(&compressed).unwrap();
|
||||
let error = sync_sessions_provider_with_hook(Some(dir.display().to_string()), None, |point| {
|
||||
if point == MutationPoint::AfterSqliteCommit(0) {
|
||||
assert_ne!(fs::read(&compressed).unwrap(), original);
|
||||
return Err(CodexxError::Config("fixture rollback".into()));
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("fixture rollback"));
|
||||
assert_eq!(fs::read(&compressed).unwrap(), original);
|
||||
assert_eq!(thread_provider(&dir.join("state_5.sqlite"), &id), "openai");
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compressed_source_replacement_or_expansion_during_sync_aborts_without_overwrite() {
|
||||
for expansion in [false, true] {
|
||||
for point_to_change in [
|
||||
MutationPoint::BeforeRolloutMutation,
|
||||
MutationPoint::BeforeEachRolloutMutation(0),
|
||||
] {
|
||||
let (dir, id, logical, compressed) =
|
||||
indexed_compressed_fixture("zst-concurrent-representation");
|
||||
let original = fs::read(&compressed).unwrap();
|
||||
let external = format!("{{\"type\":\"session_meta\",\"payload\":{{\"id\":\"{id}\",\"model_provider\":\"external\"}}}}\n").into_bytes();
|
||||
let external_compressed = zstd::stream::encode_all(external.as_slice(), 1).unwrap();
|
||||
sync_sessions_provider_with_hook(Some(dir.display().to_string()), None, |point| {
|
||||
if point == point_to_change {
|
||||
if expansion {
|
||||
fs::write(&logical, &external).unwrap();
|
||||
} else {
|
||||
fs::write(&compressed, &external_compressed).unwrap();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.expect_err("external replacement/expansion must abort synchronization");
|
||||
assert_eq!(thread_provider(&dir.join("state_5.sqlite"), &id), "openai");
|
||||
if expansion {
|
||||
assert_eq!(fs::read(&logical).unwrap(), external);
|
||||
assert_eq!(fs::read(&compressed).unwrap(), original);
|
||||
} else {
|
||||
assert_eq!(fs::read(&compressed).unwrap(), external_compressed);
|
||||
}
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compressed_reference_with_wrong_metadata_id_blocks_sync_without_uuid_reassociation() {
|
||||
let (dir, id, logical, compressed) = indexed_compressed_fixture("zst-wrong-identity");
|
||||
let other = "01a0e854-0000-7000-8000-000000000009";
|
||||
let wrong = format!("{{\"type\":\"session_meta\",\"payload\":{{\"id\":\"{other}\",\"model_provider\":\"openai\"}}}}\n");
|
||||
let bytes = zstd::stream::encode_all(wrong.as_bytes(), 1).unwrap();
|
||||
fs::write(&compressed, &bytes).unwrap();
|
||||
// A different file with the right ID must not replace an explicit current alias.
|
||||
let fallback = dir.join(format!("sessions/history/rollout-old-{id}.jsonl"));
|
||||
write_rollout_at(&fallback, &id, "openai");
|
||||
let status = session_sync_status_inner(Some(dir.display().to_string()), None).unwrap();
|
||||
assert!(!status.scan_complete);
|
||||
assert!(status
|
||||
.scan_failures
|
||||
.iter()
|
||||
.any(|failure| failure.contains("线程 ID 不一致")));
|
||||
sync_sessions_provider_inner(Some(dir.display().to_string()), None).unwrap_err();
|
||||
assert_eq!(fs::read(&compressed).unwrap(), bytes);
|
||||
assert_eq!(thread_provider(&dir.join("state_5.sqlite"), &id), "openai");
|
||||
assert!(!logical.exists());
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn active_reference_moved_to_compressed_archive_is_reported_as_archive_conflict() {
|
||||
let (dir, id, logical, compressed) = indexed_compressed_fixture("zst-archive-conflict");
|
||||
let archived = dir
|
||||
.join("archived_sessions")
|
||||
.join(compressed.file_name().unwrap());
|
||||
fs::create_dir_all(archived.parent().unwrap()).unwrap();
|
||||
fs::rename(&compressed, &archived).unwrap();
|
||||
let bytes = fs::read(&archived).unwrap();
|
||||
let status = session_sync_status_inner(Some(dir.display().to_string()), None).unwrap();
|
||||
assert!(!status.scan_complete);
|
||||
assert!(status
|
||||
.scan_failures
|
||||
.iter()
|
||||
.any(|failure| failure.contains("归档状态不一致")
|
||||
&& failure.contains(&id)
|
||||
&& failure.contains(&logical.display().to_string())
|
||||
&& failure.contains(&archived.display().to_string())));
|
||||
assert!(!status
|
||||
.scan_failures
|
||||
.iter()
|
||||
.any(|failure| failure.contains("均缺失")));
|
||||
sync_sessions_provider_inner(Some(dir.display().to_string()), None).unwrap_err();
|
||||
assert_eq!(fs::read(&archived).unwrap(), bytes);
|
||||
assert_eq!(thread_provider(&dir.join("state_5.sqlite"), &id), "openai");
|
||||
assert!(!logical.exists());
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compressed_expansion_after_commit_preserves_external_plain_log_and_retains_backup() {
|
||||
let (dir, id, logical, compressed) = indexed_compressed_fixture("zst-expansion-after-commit");
|
||||
let external = format!("{{\"type\":\"session_meta\",\"payload\":{{\"id\":\"{id}\",\"model_provider\":\"external\"}}}}\n");
|
||||
let error = sync_sessions_provider_with_hook(Some(dir.display().to_string()), None, |point| {
|
||||
if point == MutationPoint::AfterSqliteCommit(0) {
|
||||
fs::write(&logical, external.as_bytes()).unwrap();
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.expect_err("postcommit expansion must not be mistaken for a successful synchronization");
|
||||
assert!(error.to_string().contains("变化") || error.to_string().contains("回滚"));
|
||||
assert_eq!(fs::read(&logical).unwrap(), external.as_bytes());
|
||||
assert_eq!(thread_provider(&dir.join("state_5.sqlite"), &id), "openai");
|
||||
assert!(compressed.exists());
|
||||
let backups = crate::sessions::provider_sync_backup_root(&dir);
|
||||
assert!(fs::read_dir(backups).unwrap().next().is_some());
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_can_really_switch_during_sync_while_session_target_stays_fixed() {
|
||||
let _app_db_guard = crate::app_db::test_db_guard();
|
||||
let dir = temp_codex_dir("provider-switch-during-session-sync");
|
||||
write_config(&dir, "openai");
|
||||
let id = "01a0e854-0000-7000-8000-000000000011";
|
||||
let logical = write_rollout(&dir, id, "historical-provider");
|
||||
let compressed = compress_rollout(&logical);
|
||||
let database = dir.join("state_5.sqlite");
|
||||
create_thread_database_with_rollout(&database, id, "historical-provider", &logical);
|
||||
let mut switched = false;
|
||||
let result = sync_sessions_provider_with_hook(Some(dir.display().to_string()), None, |point| {
|
||||
if point == MutationPoint::BeforeSqliteLock {
|
||||
crate::providers::switch_provider_inner(crate::providers::ProviderInput {
|
||||
config_dir: Some(dir.display().to_string()),
|
||||
provider_id: Some("session-sync-switch-fixture".into()),
|
||||
provider_name: "Session sync switch fixture".into(),
|
||||
base_url: "https://session-sync-fixture.invalid/v1".into(),
|
||||
model: "fixture-model".into(),
|
||||
api_key: Some("fixture-key-never-sent".into()),
|
||||
wire_api: Some("responses".into()),
|
||||
requires_openai_auth: None,
|
||||
})?;
|
||||
assert_eq!(current_model_provider(&dir, None)?, "custom");
|
||||
switched = true;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(
|
||||
switched,
|
||||
"the real provider switch ran while the maintenance lock was held"
|
||||
);
|
||||
assert_eq!(result.status.target_provider, "openai");
|
||||
assert!(!result.status.needs_sync);
|
||||
assert_eq!(thread_provider(&database, id), "openai");
|
||||
assert!(String::from_utf8(decoded(&compressed))
|
||||
.unwrap()
|
||||
.contains("\"model_provider\":\"openai\""));
|
||||
assert_eq!(current_model_provider(&dir, None).unwrap(), "custom");
|
||||
let current = session_sync_status_inner(Some(dir.display().to_string()), None).unwrap();
|
||||
assert_eq!(current.target_provider, "custom");
|
||||
assert!(
|
||||
current.needs_sync,
|
||||
"a new explicit status read sees the new target, without stale scan caching"
|
||||
);
|
||||
let live_config = fs::read_to_string(dir.join("config.toml")).unwrap();
|
||||
assert!(live_config.contains("https://session-sync-fixture.invalid/v1"));
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,463 @@
|
||||
use super::types::SessionPreview;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::HashMap;
|
||||
#[cfg(unix)]
|
||||
use std::fs::File;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct DirectoryIdentity {
|
||||
key: String,
|
||||
birth_verified: bool,
|
||||
}
|
||||
|
||||
fn filesystem_identity(
|
||||
platform: &[u8],
|
||||
parts: &[&[u8]],
|
||||
birth: Option<SystemTime>,
|
||||
) -> DirectoryIdentity {
|
||||
let mut digest = Sha256::new();
|
||||
digest.update(b"codex-x/session-directory-identity/v1\0");
|
||||
digest.update(platform);
|
||||
digest.update(b"\0");
|
||||
for part in parts {
|
||||
digest.update(part);
|
||||
}
|
||||
if let Some(birth) = birth {
|
||||
digest.update(b"\0birth\0");
|
||||
let (sign, age) = match birth.duration_since(UNIX_EPOCH) {
|
||||
Ok(age) => (b'+', age),
|
||||
Err(before_epoch) => (b'-', before_epoch.duration()),
|
||||
};
|
||||
digest.update([sign]);
|
||||
digest.update(age.as_secs().to_le_bytes());
|
||||
digest.update(age.subsec_nanos().to_le_bytes());
|
||||
} else {
|
||||
digest.update(b"\0no-birth\0");
|
||||
}
|
||||
DirectoryIdentity {
|
||||
key: format!("filesystem:{:x}", digest.finalize()),
|
||||
birth_verified: birth.is_some(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(unix, test))]
|
||||
fn unix_directory_identity(
|
||||
device: u64,
|
||||
inode: u64,
|
||||
birth: Option<SystemTime>,
|
||||
) -> Option<DirectoryIdentity> {
|
||||
// Some virtual or unsupported filesystems expose no usable inode number.
|
||||
if inode == 0 {
|
||||
return None;
|
||||
}
|
||||
Some(filesystem_identity(
|
||||
b"unix",
|
||||
&[&device.to_le_bytes(), &inode.to_le_bytes()],
|
||||
birth,
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(any(windows, test))]
|
||||
fn windows_directory_identity(
|
||||
volume: u64,
|
||||
identifier: &[u8; 16],
|
||||
birth: Option<SystemTime>,
|
||||
) -> Option<DirectoryIdentity> {
|
||||
// The complete 128-bit ID is needed for ReFS; the old 64-bit file index
|
||||
// cannot safely distinguish all directories on that filesystem.
|
||||
if identifier.iter().all(|byte| *byte == 0) {
|
||||
return None;
|
||||
}
|
||||
Some(filesystem_identity(
|
||||
b"windows",
|
||||
&[&volume.to_le_bytes(), identifier],
|
||||
birth,
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn native_directory_identity(path: &Path) -> io::Result<DirectoryIdentity> {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
|
||||
let handle = File::open(path)?;
|
||||
let metadata = handle.metadata()?;
|
||||
if !metadata.is_dir() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"not a directory",
|
||||
));
|
||||
}
|
||||
unix_directory_identity(metadata.dev(), metadata.ino(), metadata.created().ok())
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::Unsupported, "directory has no stable inode"))
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn native_directory_identity(path: &Path) -> io::Result<DirectoryIdentity> {
|
||||
use std::fs::OpenOptions;
|
||||
use std::os::windows::fs::OpenOptionsExt;
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use windows_sys::Win32::Storage::FileSystem::{
|
||||
FileIdInfo, GetFileInformationByHandleEx, FILE_FLAG_BACKUP_SEMANTICS, FILE_ID_INFO,
|
||||
FILE_READ_ATTRIBUTES, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE,
|
||||
};
|
||||
|
||||
// READ_ATTRIBUTES plus BACKUP_SEMANTICS opens directories without requiring
|
||||
// permission to list them. No content is read and no filesystem state is changed.
|
||||
let handle = OpenOptions::new()
|
||||
.read(true)
|
||||
.access_mode(FILE_READ_ATTRIBUTES)
|
||||
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)
|
||||
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
|
||||
.open(path)?;
|
||||
let metadata = handle.metadata()?;
|
||||
if !metadata.is_dir() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"not a directory",
|
||||
));
|
||||
}
|
||||
let mut info = FILE_ID_INFO::default();
|
||||
// The owned read-only handle stays alive while Windows fills this exact
|
||||
// FILE_ID_INFO buffer. Unsupported filesystems return an error and fall back.
|
||||
let succeeded = unsafe {
|
||||
GetFileInformationByHandleEx(
|
||||
handle.as_raw_handle(),
|
||||
FileIdInfo,
|
||||
(&mut info as *mut FILE_ID_INFO).cast(),
|
||||
std::mem::size_of::<FILE_ID_INFO>() as u32,
|
||||
)
|
||||
};
|
||||
if succeeded == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
windows_directory_identity(
|
||||
info.VolumeSerialNumber,
|
||||
&info.FileId.Identifier,
|
||||
metadata.created().ok(),
|
||||
)
|
||||
.ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"directory has no stable file ID",
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
fn native_directory_identity(_path: &Path) -> io::Result<DirectoryIdentity> {
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"directory identity is unavailable",
|
||||
))
|
||||
}
|
||||
|
||||
fn unresolved_directory_identity(path: &str) -> DirectoryIdentity {
|
||||
DirectoryIdentity {
|
||||
key: format!("path:{path}"),
|
||||
birth_verified: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn directory_lookup(path: &str) -> DirectoryIdentity {
|
||||
let filesystem_path = Path::new(path);
|
||||
// Historical relative cwd values cannot be resolved against this app's
|
||||
// process cwd. Check the path kind before opening, including FIFO/device
|
||||
// values that must never be treated as a workspace directory.
|
||||
if !filesystem_path.is_absolute()
|
||||
|| !std::fs::metadata(filesystem_path).is_ok_and(|metadata| metadata.is_dir())
|
||||
{
|
||||
return unresolved_directory_identity(path);
|
||||
}
|
||||
native_directory_identity(filesystem_path)
|
||||
.unwrap_or_else(|_| unresolved_directory_identity(path))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn directory_identity(path: &str) -> String {
|
||||
directory_lookup(path).key
|
||||
}
|
||||
|
||||
fn pin_scope_key(path: &str, identity: &DirectoryIdentity) -> String {
|
||||
if identity.birth_verified {
|
||||
identity.key.clone()
|
||||
} else {
|
||||
format!("path:{path}")
|
||||
}
|
||||
}
|
||||
|
||||
/// The explicitly selected Codex home may use its native identity. Historical
|
||||
/// workspace paths remain lexical: opening or probing them merely to group
|
||||
/// sessions can request access to protected macOS folders such as Documents.
|
||||
/// Preserve their complete spelling on every platform; without inspecting a
|
||||
/// directory, volume defaults cannot exclude per-directory case sensitivity.
|
||||
pub(super) fn session_directory_identities(
|
||||
codex_dir: &Path,
|
||||
sessions: &[SessionPreview],
|
||||
) -> (HashMap<String, String>, String) {
|
||||
let mut identities = HashMap::new();
|
||||
let home = codex_dir.display().to_string();
|
||||
let home_identity = directory_lookup(&home);
|
||||
let pin_scope = pin_scope_key(&home, &home_identity);
|
||||
identities.insert(home.clone(), home_identity.key);
|
||||
for path in sessions.iter().filter_map(|session| session.cwd.as_deref()) {
|
||||
identities
|
||||
.entry(path.to_string())
|
||||
.or_insert_with(|| unresolved_directory_identity(path).key);
|
||||
}
|
||||
(identities, pin_scope)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
struct TestDirectory {
|
||||
path: PathBuf,
|
||||
_directory: tempfile::TempDir,
|
||||
}
|
||||
|
||||
impl TestDirectory {
|
||||
fn new() -> Self {
|
||||
let mut builder = tempfile::Builder::new();
|
||||
builder.prefix("codex-x-directory-identity-");
|
||||
let directory = match std::env::var_os("CODEXX_TEST_CASE_DIRECTORY_ROOT") {
|
||||
Some(root) => builder.tempdir_in(root),
|
||||
None => builder.tempdir(),
|
||||
}
|
||||
.expect("create temporary directory identity fixture");
|
||||
Self {
|
||||
path: directory.path().to_path_buf(),
|
||||
_directory: directory,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn preview(id: &str, cwd: Option<String>) -> SessionPreview {
|
||||
SessionPreview {
|
||||
id: id.to_string(),
|
||||
title: id.to_string(),
|
||||
cwd,
|
||||
model_provider: None,
|
||||
model: None,
|
||||
rollout_path: None,
|
||||
updated_at_ms: None,
|
||||
archived: false,
|
||||
has_user_event: false,
|
||||
is_subagent: false,
|
||||
needs_sync: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn existing_directory_and_lexical_alias_have_the_same_stable_identity() {
|
||||
let fixture = TestDirectory::new();
|
||||
let folder = fixture.path.join("Workspace");
|
||||
fs::create_dir(&folder).unwrap();
|
||||
let direct = directory_identity(&folder.display().to_string());
|
||||
let alias = directory_identity(&folder.join(".").display().to_string());
|
||||
assert!(direct.starts_with("filesystem:"));
|
||||
assert_eq!(direct, alias);
|
||||
assert_eq!(direct, directory_identity(&folder.display().to_string()));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn symbolic_directory_alias_resolves_to_the_same_identity() {
|
||||
let fixture = TestDirectory::new();
|
||||
let folder = fixture.path.join("Workspace");
|
||||
let alias = fixture.path.join("WorkspaceAlias");
|
||||
fs::create_dir(&folder).unwrap();
|
||||
std::os::unix::fs::symlink(&folder, &alias).unwrap();
|
||||
assert_eq!(
|
||||
directory_identity(&folder.display().to_string()),
|
||||
directory_identity(&alias.display().to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn case_only_names_follow_the_actual_fixture_filesystem() {
|
||||
let fixture = TestDirectory::new();
|
||||
let upper = fixture.path.join("CaseDirectory");
|
||||
let lower = fixture.path.join("casedirectory");
|
||||
fs::create_dir(&upper).unwrap();
|
||||
let separate_directories = match fs::create_dir(&lower) {
|
||||
Ok(()) => true,
|
||||
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => false,
|
||||
Err(error) => panic!("create case-only directory fixture: {error}"),
|
||||
};
|
||||
let upper_key = directory_identity(&upper.display().to_string());
|
||||
let lower_key = directory_identity(&lower.display().to_string());
|
||||
assert!(upper_key.starts_with("filesystem:"));
|
||||
assert!(lower_key.starts_with("filesystem:"));
|
||||
if separate_directories {
|
||||
assert_ne!(
|
||||
upper_key, lower_key,
|
||||
"case-sensitive directories must remain distinct"
|
||||
);
|
||||
} else {
|
||||
assert_eq!(
|
||||
upper_key, lower_key,
|
||||
"case aliases of the same directory must match"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_paths_never_borrow_identity_from_the_application_working_directory() {
|
||||
for raw in [".", "./", "src", "foo", "C:Project", " relative\\Name "] {
|
||||
assert_eq!(directory_identity(raw), format!("path:{raw}"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_and_nondirectory_paths_keep_the_complete_original_spelling() {
|
||||
let fixture = TestDirectory::new();
|
||||
for suffix in ["Missing", "missing", "Missing\\Name ", " missing "] {
|
||||
let raw = fixture.path.join(suffix).display().to_string();
|
||||
assert_eq!(directory_identity(&raw), format!("path:{raw}"));
|
||||
}
|
||||
let file = fixture.path.join("a-file");
|
||||
fs::write(&file, b"read-only identity lookup must not alter contents").unwrap();
|
||||
let raw = file.display().to_string();
|
||||
assert_eq!(directory_identity(&raw), format!("path:{raw}"));
|
||||
assert_eq!(
|
||||
fs::read(&file).unwrap(),
|
||||
b"read-only identity lookup must not alter contents"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn unreadable_directory_falls_back_without_normalizing_its_name() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let fixture = TestDirectory::new();
|
||||
let directory = fixture.path.join("UnreadableDirectory");
|
||||
fs::create_dir(&directory).unwrap();
|
||||
fs::set_permissions(&directory, fs::Permissions::from_mode(0)).unwrap();
|
||||
let raw = directory.display().to_string();
|
||||
let readable_by_process = File::open(&directory).is_ok();
|
||||
let identity = directory_identity(&raw);
|
||||
fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
if !readable_by_process {
|
||||
assert_eq!(identity, format!("path:{raw}"));
|
||||
} else {
|
||||
// A privileged test runner can bypass the permission restriction.
|
||||
assert!(identity.starts_with("filesystem:"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_native_identifiers_are_rejected_and_full_windows_file_ids_are_used() {
|
||||
assert!(unix_directory_identity(1, 0, None).is_none());
|
||||
assert!(windows_directory_identity(1, &[0; 16], None).is_none());
|
||||
let mut first = [0; 16];
|
||||
first[0] = 7;
|
||||
let mut second = first;
|
||||
second[15] = 1;
|
||||
assert_ne!(
|
||||
windows_directory_identity(1, &first, None),
|
||||
windows_directory_identity(1, &second, None),
|
||||
"ReFS IDs that differ only beyond the old 64-bit index must not merge"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn creation_generation_includes_epoch_sign_full_seconds_and_nanoseconds() {
|
||||
use std::time::Duration;
|
||||
// Windows SystemTime uses 100 ns intervals; use exactly representable
|
||||
// fractions while still testing that subsecond birth precision matters.
|
||||
let created = UNIX_EPOCH + Duration::new(1234, 100);
|
||||
let original = unix_directory_identity(1, 9, Some(created)).unwrap();
|
||||
assert!(original.birth_verified);
|
||||
assert_eq!(
|
||||
original,
|
||||
unix_directory_identity(1, 9, Some(created)).unwrap()
|
||||
);
|
||||
for new_generation in [
|
||||
UNIX_EPOCH + Duration::new(1234, 200),
|
||||
UNIX_EPOCH + Duration::new(1234 + (1u64 << 32), 100),
|
||||
UNIX_EPOCH - Duration::new(1234, 100),
|
||||
] {
|
||||
assert_ne!(
|
||||
original,
|
||||
unix_directory_identity(1, 9, Some(new_generation)).unwrap(),
|
||||
"reused inode numbers from another directory generation must get different keys"
|
||||
);
|
||||
}
|
||||
let file_id = [7; 16];
|
||||
assert_ne!(
|
||||
windows_directory_identity(1, &file_id, Some(created)),
|
||||
windows_directory_identity(1, &file_id, Some(created + Duration::from_nanos(100)))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persistent_pin_scope_requires_verified_birth_and_preserves_raw_fallback_paths() {
|
||||
let transient = unix_directory_identity(1, 9, None).unwrap();
|
||||
assert!(transient.key.starts_with("filesystem:"));
|
||||
assert!(!transient.birth_verified);
|
||||
for path in ["/Home/Codex", "/Home/codex", "/Home/Codex\\ "] {
|
||||
assert_eq!(pin_scope_key(path, &transient), format!("path:{path}"));
|
||||
}
|
||||
let verified = unix_directory_identity(1, 9, Some(UNIX_EPOCH)).unwrap();
|
||||
assert_eq!(pin_scope_key("/Home/Codex", &verified), verified.key);
|
||||
assert_eq!(pin_scope_key("/Home/codex", &verified), verified.key);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changing_directory_contents_does_not_change_birth_identity_or_pin_scope() {
|
||||
let fixture = TestDirectory::new();
|
||||
let directory = fixture.path.join("Workspace");
|
||||
fs::create_dir(&directory).unwrap();
|
||||
let raw = directory.display().to_string();
|
||||
let before = directory_lookup(&raw);
|
||||
fs::write(directory.join("first.txt"), b"first").unwrap();
|
||||
fs::write(directory.join("first.txt"), b"updated").unwrap();
|
||||
fs::write(directory.join("second.txt"), b"second").unwrap();
|
||||
fs::remove_file(directory.join("first.txt")).unwrap();
|
||||
let after = directory_lookup(&raw);
|
||||
assert_eq!(
|
||||
before, after,
|
||||
"mtime/ctime changes must not replace the directory birth identity"
|
||||
);
|
||||
assert_eq!(pin_scope_key(&raw, &before), pin_scope_key(&raw, &after));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_identities_include_only_its_home_and_loaded_workspaces_and_isolate_homes() {
|
||||
let fixture = TestDirectory::new();
|
||||
let first_home = fixture.path.join("CodexHomeA");
|
||||
let second_home = fixture.path.join("CodexHomeB");
|
||||
let workspace = fixture.path.join("Project");
|
||||
let unused = fixture.path.join("Unused");
|
||||
for directory in [&first_home, &second_home, &workspace, &unused] {
|
||||
fs::create_dir(directory).unwrap();
|
||||
}
|
||||
let config = first_home.join("config.toml");
|
||||
fs::write(&config, b"model_provider = \"openai\"\n").unwrap();
|
||||
let cwd = workspace.display().to_string();
|
||||
let sessions = vec![
|
||||
preview("first", Some(cwd.clone())),
|
||||
preview("second", Some(cwd.clone())),
|
||||
preview("unknown", None),
|
||||
];
|
||||
let (first, first_scope) = session_directory_identities(&first_home, &sessions);
|
||||
let (second, second_scope) = session_directory_identities(&second_home, &sessions);
|
||||
assert_eq!(first.len(), 2);
|
||||
assert!(first.contains_key(&first_home.display().to_string()));
|
||||
assert!(first.contains_key(&cwd));
|
||||
assert!(!first.contains_key(&unused.display().to_string()));
|
||||
assert_ne!(
|
||||
first[&first_home.display().to_string()],
|
||||
second[&second_home.display().to_string()]
|
||||
);
|
||||
assert_ne!(first_scope, second_scope);
|
||||
assert_eq!(first[&cwd], second[&cwd]);
|
||||
assert_eq!(fs::read(&config).unwrap(), b"model_provider = \"openai\"\n");
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
use super::rollout_stream::{decoded_rollout_reader, resolved_rollout_path};
|
||||
use super::storage::{
|
||||
is_canonical_rollout_storage_path, list_session_previews_with_paths, session_project_title,
|
||||
sqlite_candidate_paths,
|
||||
@@ -187,6 +188,7 @@ struct JsonLine<'a, R: BufRead> {
|
||||
buffered: usize,
|
||||
buffer_ends_line: bool,
|
||||
has_content: bool,
|
||||
too_large: bool,
|
||||
}
|
||||
impl<R: BufRead> Read for JsonLine<'_, R> {
|
||||
fn read(&mut self, out: &mut [u8]) -> std::io::Result<usize> {
|
||||
@@ -199,6 +201,7 @@ impl<R: BufRead> Read for JsonLine<'_, R> {
|
||||
return Ok(0);
|
||||
}
|
||||
if self.consumed >= MAX_RECORD_BYTES {
|
||||
self.too_large = true;
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
"record too large",
|
||||
@@ -240,13 +243,16 @@ fn drain_line<R: BufRead>(reader: &mut R) -> std::io::Result<()> {
|
||||
|
||||
fn visit_records(
|
||||
file: &mut File,
|
||||
path: &Path,
|
||||
length: u64,
|
||||
expected_id: &str,
|
||||
mut visitor: impl FnMut(Message) -> Result<()>,
|
||||
) -> Result<usize> {
|
||||
file.seek(SeekFrom::Start(0))
|
||||
.map_err(|error| CodexxError::Config(format!("无法读取会话:{error}")))?;
|
||||
let mut reader = BufReader::new(file.take(length));
|
||||
let decoded =
|
||||
decoded_rollout_reader(file.take(length), path).map_err(|error| io_err(path, error))?;
|
||||
let mut reader = BufReader::new(decoded);
|
||||
let mut malformed = 0;
|
||||
let mut verified_meta = false;
|
||||
loop {
|
||||
@@ -264,8 +270,14 @@ fn visit_records(
|
||||
buffered: 0,
|
||||
buffer_ends_line: false,
|
||||
has_content: false,
|
||||
too_large: false,
|
||||
};
|
||||
let parsed = serde_json::from_reader::<_, Record>(&mut line);
|
||||
if let Err(error) = &parsed {
|
||||
if error.is_io() && !line.too_large {
|
||||
return Err(CodexxError::Config(format!("无法读取会话:{error}")));
|
||||
}
|
||||
}
|
||||
let ended = line.ended;
|
||||
let has_content = line.has_content;
|
||||
if !ended {
|
||||
@@ -315,10 +327,12 @@ fn safe_rollout_path(codex_dir: &Path, session: &SessionPreview) -> Result<PathB
|
||||
} else {
|
||||
codex_dir.join(path)
|
||||
};
|
||||
let path = resolved_rollout_path(&path).map_err(|error| io_err(&path, error))?;
|
||||
let metadata = fs::symlink_metadata(&path).map_err(|error| io_err(&path, error))?;
|
||||
if !metadata.is_file()
|
||||
|| metadata.file_type().is_symlink()
|
||||
|| !path.to_string_lossy().ends_with(".jsonl")
|
||||
|| !(path.to_string_lossy().ends_with(".jsonl")
|
||||
|| path.to_string_lossy().ends_with(".jsonl.zst"))
|
||||
{
|
||||
return Err(CodexxError::Config("不支持此会话文件类型".to_string()));
|
||||
}
|
||||
@@ -351,7 +365,7 @@ fn write_markdown(codex_dir: &Path, session: &SessionPreview, output: &mut File)
|
||||
let mut file = File::open(&path).map_err(|error| io_err(&path, error))?;
|
||||
let length = file.metadata().map_err(|error| io_err(&path, error))?.len();
|
||||
let mut event_counts = HashMap::<[u8; 32], usize>::new();
|
||||
let malformed = visit_records(&mut file, length, &session.id, |message| {
|
||||
let malformed = visit_records(&mut file, &path, length, &session.id, |message| {
|
||||
if message.event {
|
||||
if event_counts.len() >= MAX_MESSAGE_KEYS {
|
||||
return Err(CodexxError::Config(
|
||||
@@ -388,7 +402,7 @@ fn write_markdown(codex_dir: &Path, session: &SessionPreview, output: &mut File)
|
||||
markdown_label(&session.id)
|
||||
))?;
|
||||
let mut count = 0;
|
||||
visit_records(&mut file, length, &session.id, |message| {
|
||||
visit_records(&mut file, &path, length, &session.id, |message| {
|
||||
if !message.event {
|
||||
if let Some(remaining) = event_counts.get_mut(&message_key(&message)) {
|
||||
if *remaining > 0 {
|
||||
@@ -712,6 +726,119 @@ mod tests {
|
||||
json!({"type":"response_item","timestamp":"2026-09-12T10:00:00Z","payload":{"type":"message","role":role,"content":[{"type":if role == "user" { "input_text" } else { "output_text" },"text":body}]}})
|
||||
}
|
||||
|
||||
fn compress_fixture(path: &Path) -> PathBuf {
|
||||
let compressed = path.with_extension("jsonl.zst");
|
||||
let mut input = File::open(path).unwrap();
|
||||
let mut encoder =
|
||||
zstd::stream::write::Encoder::new(File::create(&compressed).unwrap(), 1).unwrap();
|
||||
encoder.include_checksum(true).unwrap();
|
||||
std::io::copy(&mut input, &mut encoder).unwrap();
|
||||
encoder.finish().unwrap();
|
||||
drop(input);
|
||||
fs::remove_file(path).unwrap();
|
||||
compressed
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exports_compressed_logical_reference_with_same_deduplication_and_no_storage_changes() {
|
||||
let fixture = Fixture::new();
|
||||
let path = fixture.add(
|
||||
"compressed",
|
||||
"已改名的会话",
|
||||
&[
|
||||
event("user", "中文问题"),
|
||||
response("user", "中文问题"),
|
||||
response("assistant", "完整回答"),
|
||||
],
|
||||
false,
|
||||
);
|
||||
let expected = fixture.export(&["compressed"], "plain.md").unwrap();
|
||||
let compressed = compress_fixture(&path);
|
||||
let raw_before = fs::read(&compressed).unwrap();
|
||||
let db_before = fs::read(&fixture.database).unwrap();
|
||||
let result = fixture.export(&["compressed"], "compressed.md").unwrap();
|
||||
assert_eq!(
|
||||
fs::read(result.path).unwrap(),
|
||||
fs::read(expected.path).unwrap()
|
||||
);
|
||||
assert_eq!(result.failed_sessions, 0);
|
||||
assert!(result.warnings.is_empty());
|
||||
assert!(!path.exists());
|
||||
assert_eq!(fs::read(compressed).unwrap(), raw_before);
|
||||
assert_eq!(fs::read(&fixture.database).unwrap(), db_before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_prefers_current_plain_file_over_stale_compressed_sibling() {
|
||||
let fixture = Fixture::new();
|
||||
let path = fixture.add("current", "当前会话", &[event("user", "stale body")], false);
|
||||
let compressed = compress_fixture(&path);
|
||||
fs::write(
|
||||
&path,
|
||||
format!(
|
||||
"{}\n{}\n",
|
||||
json!({"type":"session_meta","payload":{"id":"current"}}),
|
||||
event("user", "current body")
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let before = fs::read(&compressed).unwrap();
|
||||
let result = fixture.export(&["current"], "current.md").unwrap();
|
||||
let text = fs::read_to_string(result.path).unwrap();
|
||||
assert!(text.contains("current body"));
|
||||
assert!(!text.contains("stale body"));
|
||||
assert_eq!(fs::read(compressed).unwrap(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_compression_is_an_error_and_preserves_existing_export() {
|
||||
let fixture = Fixture::new();
|
||||
let path = fixture.add(
|
||||
"corrupt",
|
||||
"损坏的压缩会话",
|
||||
&[event("user", "must not publish a partial export")],
|
||||
false,
|
||||
);
|
||||
let compressed = compress_fixture(&path);
|
||||
let mut bytes = fs::read(&compressed).unwrap();
|
||||
let last = bytes.len() - 1;
|
||||
bytes[last] ^= 0x80;
|
||||
fs::write(&compressed, &bytes).unwrap();
|
||||
let destination = fixture.root.join("protected.md");
|
||||
fs::write(&destination, "existing export").unwrap();
|
||||
assert!(fixture.export(&["corrupt"], "protected.md").is_err());
|
||||
assert_eq!(fs::read_to_string(destination).unwrap(), "existing export");
|
||||
assert_eq!(fs::read(compressed).unwrap(), bytes);
|
||||
assert!(fs::read_dir(&fixture.root).unwrap().all(|entry| !entry
|
||||
.unwrap()
|
||||
.file_name()
|
||||
.to_string_lossy()
|
||||
.starts_with(".codex-x-export-")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compressed_identity_mismatch_does_not_export_another_conversation() {
|
||||
let fixture = Fixture::new();
|
||||
let path = fixture.add(
|
||||
"selected",
|
||||
"所选会话",
|
||||
&[event("user", "private fixture")],
|
||||
false,
|
||||
);
|
||||
fs::write(
|
||||
&path,
|
||||
format!(
|
||||
"{}\n{}\n",
|
||||
json!({"type":"session_meta","payload":{"id":"different"}}),
|
||||
event("user", "private fixture")
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
compress_fixture(&path);
|
||||
assert!(fixture.export(&["selected"], "mismatch.md").is_err());
|
||||
assert!(!fixture.root.join("mismatch.md").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exports_markdown_titles_times_and_code_without_system_tools_or_reasoning() {
|
||||
let fixture = Fixture::new();
|
||||
|
||||
@@ -2,8 +2,10 @@ mod app_server;
|
||||
mod backup;
|
||||
mod catalog;
|
||||
mod delete;
|
||||
mod directory_identity;
|
||||
mod export;
|
||||
mod global_state;
|
||||
mod rollout_stream;
|
||||
mod storage;
|
||||
mod sync;
|
||||
mod transaction;
|
||||
@@ -29,3 +31,56 @@ pub(crate) use storage::{
|
||||
};
|
||||
pub(crate) use sync::{session_sync_status_inner, sync_sessions_provider_inner};
|
||||
pub(crate) use types::{SessionSyncResult, SessionSyncStatus};
|
||||
|
||||
/// Serialize operations that can restart the official client with session
|
||||
/// synchronization and deletion, including callers from other windows or IPC.
|
||||
/// Provider activation remains independent of this maintenance lock.
|
||||
pub(crate) fn with_session_maintenance<T>(
|
||||
codex_dir: &std::path::Path,
|
||||
operation: impl FnOnce() -> crate::error::Result<T>,
|
||||
) -> crate::error::Result<T> {
|
||||
let _guard = sync::acquire_session_maintenance_lock(codex_dir)?;
|
||||
operation()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod maintenance_tests {
|
||||
use super::*;
|
||||
use std::cell::Cell;
|
||||
|
||||
#[test]
|
||||
fn maintenance_conflict_never_executes_callback_and_release_allows_retry() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let held = sync::acquire_session_maintenance_lock(directory.path()).unwrap();
|
||||
let called = Cell::new(false);
|
||||
let error = with_session_maintenance(directory.path(), || {
|
||||
called.set(true);
|
||||
Ok(())
|
||||
})
|
||||
.expect_err("another session operation must block the callback");
|
||||
assert!(!called.get());
|
||||
assert!(error.to_string().contains("会话维护正在进行"));
|
||||
drop(held);
|
||||
let result = with_session_maintenance(directory.path(), || {
|
||||
called.set(true);
|
||||
Ok(17)
|
||||
})
|
||||
.unwrap();
|
||||
assert!(called.get());
|
||||
assert_eq!(result, 17);
|
||||
let _available = sync::acquire_session_maintenance_lock(directory.path()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maintenance_guard_releases_when_callback_returns_an_error() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let error = with_session_maintenance(directory.path(), || {
|
||||
Err::<(), _>(crate::error::CodexxError::Config(
|
||||
"fixture operation failed".into(),
|
||||
))
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("fixture operation failed"));
|
||||
let _available = sync::acquire_session_maintenance_lock(directory.path()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,204 @@
|
||||
// Manual release-profile benchmark. It never accepts a user-supplied Codex
|
||||
// directory; all databases, config, histories and backups belong to TempDir.
|
||||
use super::super::super::rollout_stream::decoded_rollout_reader;
|
||||
use std::io::BufReader;
|
||||
use std::time::Instant;
|
||||
|
||||
fn random_ascii(buffer: &mut [u8], seed: &mut u64) {
|
||||
const ASCII: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-";
|
||||
for byte in buffer {
|
||||
*seed ^= *seed << 13;
|
||||
*seed ^= *seed >> 7;
|
||||
*seed ^= *seed << 17;
|
||||
*byte = ASCII[(*seed >> 8) as usize & 63];
|
||||
}
|
||||
}
|
||||
|
||||
fn event_payload(writer: &mut impl Write, size: usize, seed: &mut u64) -> u64 {
|
||||
let prefix = b"{\"type\":\"event_msg\",\"payload\":{\"type\":\"agent_message\",\"message\":\"";
|
||||
let suffix = b"\"}}\n";
|
||||
writer.write_all(prefix).unwrap();
|
||||
let mut buffer = [0; 64 * 1024];
|
||||
let mut remaining = size;
|
||||
while remaining != 0 {
|
||||
let count = remaining.min(buffer.len());
|
||||
random_ascii(&mut buffer[..count], seed);
|
||||
writer.write_all(&buffer[..count]).unwrap();
|
||||
remaining -= count;
|
||||
}
|
||||
writer.write_all(suffix).unwrap();
|
||||
(prefix.len() + size + suffix.len()) as u64
|
||||
}
|
||||
|
||||
fn content_hash(path: &Path) -> [u8; 32] {
|
||||
let file = fs::File::open(path).unwrap();
|
||||
let mut reader = BufReader::new(decoded_rollout_reader(file, path).unwrap());
|
||||
let mut first = Vec::new();
|
||||
reader.read_until(b'\n', &mut first).unwrap();
|
||||
assert!(first.len() < 4096);
|
||||
let first: serde_json::Value = serde_json::from_slice(&first).unwrap();
|
||||
assert_eq!(first["type"], "session_meta");
|
||||
let mut hash = Sha256::new();
|
||||
let mut buffer = [0; 64 * 1024];
|
||||
loop {
|
||||
let count = reader.read(&mut buffer).unwrap();
|
||||
if count == 0 {
|
||||
break;
|
||||
}
|
||||
hash.update(&buffer[..count]);
|
||||
}
|
||||
hash.finalize().into()
|
||||
}
|
||||
|
||||
fn timed<T>(action: impl FnOnce() -> T) -> (T, f64) {
|
||||
let started = Instant::now();
|
||||
let value = action();
|
||||
(value, started.elapsed().as_secs_f64() * 1000.0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "manual release-profile measurement using temporary session fixtures only"]
|
||||
fn measure_session_sync_on_temporary_plain_and_compressed_logs() {
|
||||
const FILES: usize = 24;
|
||||
const LARGE_RECORD_BYTES: usize = 34 * 1024 * 1024;
|
||||
const SMALL_RECORDS_PER_FILE: usize = 1000;
|
||||
const SMALL_RECORD_BYTES: usize = 512;
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let dir = directory.path();
|
||||
write_config(dir, SHARED_SESSION_PROVIDER);
|
||||
let database = dir.join("state_5.sqlite");
|
||||
let conn = Connection::open(&database).unwrap();
|
||||
conn.execute_batch("CREATE TABLE threads(id TEXT PRIMARY KEY, model_provider TEXT NOT NULL, title TEXT, rollout_path TEXT, archived INTEGER NOT NULL DEFAULT 0)").unwrap();
|
||||
let mut raw_bytes = 0u64;
|
||||
let mut raw_compressed_bytes = 0u64;
|
||||
let mut plain_bytes = 0u64;
|
||||
let mut compressed_bytes = 0u64;
|
||||
let mut record_count = 0usize;
|
||||
let mut fixtures = Vec::new();
|
||||
let mut seed = 0x1357_2468_90ab_cdef;
|
||||
for index in 0..FILES {
|
||||
let id = format!("01a0e854-0000-7000-8000-{index:012}");
|
||||
let logical = dir.join(format!("sessions/2026/10/16/rollout-benchmark-{id}.jsonl"));
|
||||
fs::create_dir_all(logical.parent().unwrap()).unwrap();
|
||||
let compressed = index % 2 == 1;
|
||||
let path = if compressed {
|
||||
logical.with_extension("jsonl.zst")
|
||||
} else {
|
||||
logical.clone()
|
||||
};
|
||||
let mut file = fs::File::create(&path).unwrap();
|
||||
let mut encoder = if compressed {
|
||||
Some(zstd::stream::write::Encoder::new(file.try_clone().unwrap(), 1).unwrap())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut output = std::io::BufWriter::new(if let Some(encoder) = encoder.as_mut() {
|
||||
encoder as &mut dyn Write
|
||||
} else {
|
||||
&mut file as &mut dyn Write
|
||||
});
|
||||
let meta = format!("{{\"type\":\"session_meta\",\"payload\":{{\"id\":\"{id}\",\"source\":\"cli\",\"model_provider\":\"openai\"}}}}\n");
|
||||
output.write_all(meta.as_bytes()).unwrap();
|
||||
let mut bytes = meta.len() as u64;
|
||||
record_count += 1;
|
||||
if index < 2 {
|
||||
bytes += event_payload(&mut output, LARGE_RECORD_BYTES, &mut seed);
|
||||
record_count += 1;
|
||||
} else {
|
||||
for _ in 0..SMALL_RECORDS_PER_FILE {
|
||||
bytes += event_payload(&mut output, SMALL_RECORD_BYTES, &mut seed);
|
||||
record_count += 1;
|
||||
}
|
||||
}
|
||||
output.flush().unwrap();
|
||||
drop(output);
|
||||
if let Some(encoder) = encoder {
|
||||
encoder.finish().unwrap();
|
||||
}
|
||||
drop(file);
|
||||
let stored_bytes = fs::metadata(&path).unwrap().len();
|
||||
raw_bytes += bytes;
|
||||
if compressed {
|
||||
compressed_bytes += stored_bytes;
|
||||
raw_compressed_bytes += bytes;
|
||||
} else {
|
||||
plain_bytes += stored_bytes;
|
||||
}
|
||||
conn.execute(
|
||||
"INSERT INTO threads(id,model_provider,title,rollout_path) VALUES(?1,'openai',?1,?2)",
|
||||
(&id, logical.display().to_string()),
|
||||
)
|
||||
.unwrap();
|
||||
let hash = content_hash(&path);
|
||||
fixtures.push((id, logical, path, hash));
|
||||
}
|
||||
drop(conn);
|
||||
let config_dir = Some(dir.display().to_string());
|
||||
let (before, status_before_ms) =
|
||||
timed(|| session_sync_status_inner(config_dir.clone(), None).unwrap());
|
||||
assert!(before.scan_complete, "{:?}", before.scan_failures);
|
||||
assert!(before.needs_sync);
|
||||
assert_eq!(before.rollout_files, FILES);
|
||||
assert_eq!(before.mismatched_sessions, FILES);
|
||||
let (result, sync_ms) =
|
||||
timed(|| sync_sessions_provider_inner(config_dir.clone(), None).unwrap());
|
||||
assert!(
|
||||
result.status.scan_complete,
|
||||
"{:?}",
|
||||
result.status.scan_failures
|
||||
);
|
||||
assert!(!result.status.needs_sync);
|
||||
assert_eq!(result.updated_rollouts, FILES);
|
||||
assert_eq!(result.updated_threads, FILES);
|
||||
let (after, status_after_ms) =
|
||||
timed(|| session_sync_status_inner(config_dir.clone(), None).unwrap());
|
||||
assert!(after.scan_complete);
|
||||
assert!(!after.needs_sync);
|
||||
let raw_hashes = fixtures
|
||||
.iter()
|
||||
.map(|(_, _, path, _)| rollout_digest(path))
|
||||
.collect::<Vec<_>>();
|
||||
let (repeat, idempotent_sync_ms) =
|
||||
timed(|| sync_sessions_provider_inner(config_dir, None).unwrap());
|
||||
assert_eq!(repeat.updated_rollouts, 0);
|
||||
assert_eq!(repeat.updated_threads, 0);
|
||||
assert!(repeat.backup_dir.is_empty());
|
||||
assert!(repeat.status.scan_complete);
|
||||
assert!(!repeat.status.needs_sync);
|
||||
let conn = Connection::open(&database).unwrap();
|
||||
for ((id, logical, path, expected_content_hash), raw_hash) in fixtures.iter().zip(raw_hashes) {
|
||||
assert_eq!(content_hash(path), *expected_content_hash);
|
||||
assert_eq!(
|
||||
rollout_digest(path),
|
||||
raw_hash,
|
||||
"idempotent sync must not recompress matching storage"
|
||||
);
|
||||
let (provider, reference): (String, String) = conn
|
||||
.query_row(
|
||||
"SELECT model_provider,rollout_path FROM threads WHERE id=?1",
|
||||
[id],
|
||||
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(provider, SHARED_SESSION_PROVIDER);
|
||||
assert_eq!(reference, logical.display().to_string());
|
||||
}
|
||||
println!(
|
||||
"SESSION_SYNC_BENCHMARK {}",
|
||||
serde_json::json!({
|
||||
"profile": if cfg!(debug_assertions) { "debug" } else { "release" },
|
||||
"fixture_only": true, "files": FILES, "plain_files": FILES / 2,
|
||||
"compressed_files": FILES / 2, "jsonl_records": record_count,
|
||||
"largest_record_payload_bytes": LARGE_RECORD_BYTES,
|
||||
"decoded_jsonl_bytes": raw_bytes, "plain_stored_bytes": plain_bytes,
|
||||
"compressed_decoded_bytes": raw_compressed_bytes, "compressed_stored_bytes": compressed_bytes,
|
||||
"total_stored_bytes": plain_bytes + compressed_bytes,
|
||||
"status_before_ms": status_before_ms, "sync_ms": sync_ms,
|
||||
"status_after_ms": status_after_ms, "idempotent_sync_ms": idempotent_sync_ms,
|
||||
"updated_rollouts": result.updated_rollouts, "updated_threads": result.updated_threads,
|
||||
"all_content_hashes_preserved": true, "logical_references_unchanged": true,
|
||||
"cache_context": "warm local filesystem after fixture generation; no cache flush",
|
||||
"comparison": "current implementation only; previous implementation did not support compressed rollouts"
|
||||
})
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,9 +1,10 @@
|
||||
use super::backup::{create_provider_sync_backup, prune_provider_sync_backups};
|
||||
use super::catalog::{scan_catalog_internal_thread_ids, scan_catalog_sync, CatalogSyncScan};
|
||||
use super::directory_identity::session_directory_identities;
|
||||
use super::storage::{
|
||||
current_model_provider, discover_sqlite_databases, ensure_sqlite_discovery_writable,
|
||||
list_session_previews_with_paths, rollout_internal_thread_ids, scan_provider_rollouts,
|
||||
scan_rollouts_for_thread_ids, scan_sqlite_with_paths, SqliteDiscovery,
|
||||
inspect_provider_rollouts, list_session_previews_with_paths, rollout_internal_thread_ids,
|
||||
scan_provider_rollouts, scan_sqlite_with_paths, validate_rollout_references, SqliteDiscovery,
|
||||
};
|
||||
use super::transaction::{
|
||||
execute_provider_sync_mutation, mutation_error, prepare_sqlite_updates, rollback_mutation,
|
||||
@@ -27,22 +28,6 @@ fn scan_failure_error(failures: &[String]) -> CodexxError {
|
||||
)
|
||||
}
|
||||
|
||||
fn scan_provider_buckets(
|
||||
codex_dir: &Path,
|
||||
target_provider: &str,
|
||||
sqlite: &SqliteScan,
|
||||
) -> Result<RolloutScan> {
|
||||
let mut rollouts = scan_rollouts_for_thread_ids(
|
||||
codex_dir,
|
||||
target_provider,
|
||||
&sqlite.syncable_thread_ids,
|
||||
&sqlite.rollout_paths_by_thread_id,
|
||||
)?;
|
||||
// Provider synchronization must not repair or rewrite the independent cwd index.
|
||||
rollouts.cwd_by_thread_id.clear();
|
||||
Ok(rollouts)
|
||||
}
|
||||
|
||||
fn scan_legacy_index_warnings(
|
||||
codex_dir: &Path,
|
||||
target_provider: &str,
|
||||
@@ -61,8 +46,7 @@ fn scan_legacy_index_warnings(
|
||||
return Vec::new();
|
||||
}
|
||||
let failures = scan_sqlite_with_paths(&legacy_paths, &RolloutScan::default(), target_provider)
|
||||
.and_then(|sqlite| scan_provider_buckets(codex_dir, target_provider, &sqlite))
|
||||
.map(|scan| scan.scan_failures)
|
||||
.map(|sqlite| validate_rollout_references(codex_dir, &sqlite.rollout_paths_by_thread_id))
|
||||
.unwrap_or_else(|error| vec![error.to_string()]);
|
||||
failures
|
||||
.into_iter()
|
||||
@@ -84,6 +68,7 @@ fn scan_provider_sync_data(
|
||||
codex_dir: &Path,
|
||||
target_provider: &str,
|
||||
discovery: &SqliteDiscovery,
|
||||
stage_changes: bool,
|
||||
) -> Result<ProviderSyncScan> {
|
||||
let active_unclassified = scan_sqlite_with_paths(
|
||||
&discovery.active_paths,
|
||||
@@ -127,13 +112,21 @@ fn scan_provider_sync_data(
|
||||
sqlite.mismatched_thread_ids = mismatched_thread_ids;
|
||||
sqlite.mismatched_threads = sqlite.mismatched_thread_ids.len();
|
||||
|
||||
let indexed_rollouts = if active_sqlite.sqlite_dbs > 0 {
|
||||
scan_provider_buckets(codex_dir, target_provider, &active_sqlite)?
|
||||
} else {
|
||||
scan_provider_buckets(codex_dir, target_provider, &sqlite)?
|
||||
let indexed_rollout_failures = {
|
||||
let authority = if active_sqlite.sqlite_dbs > 0 {
|
||||
&active_sqlite
|
||||
} else {
|
||||
&sqlite
|
||||
};
|
||||
validate_rollout_references(codex_dir, &authority.rollout_paths_by_thread_id)
|
||||
};
|
||||
let legacy_index_warnings = scan_legacy_index_warnings(codex_dir, target_provider, discovery);
|
||||
let mut rollouts = scan_provider_rollouts(
|
||||
let scan_rollouts = if stage_changes {
|
||||
scan_provider_rollouts
|
||||
} else {
|
||||
inspect_provider_rollouts
|
||||
};
|
||||
let mut rollouts = scan_rollouts(
|
||||
codex_dir,
|
||||
target_provider,
|
||||
&excluded_thread_ids,
|
||||
@@ -169,29 +162,23 @@ fn scan_provider_sync_data(
|
||||
let mut scan_failures = discovery.active_scan_failures.clone();
|
||||
scan_failures.extend(active_sqlite.scan_failures.iter().cloned());
|
||||
scan_failures.extend(sqlite.scan_failures.iter().cloned());
|
||||
scan_failures.extend(indexed_rollouts.scan_failures.iter().cloned());
|
||||
scan_failures.extend(indexed_rollout_failures.iter().cloned());
|
||||
// A size/buffer limit means the rollout was not completely inspected.
|
||||
// This is blocking even for an orphan, rather than a success with a warning.
|
||||
scan_failures.extend(rollouts.blocked_failures.iter().cloned());
|
||||
// A failed eligible rollout read/parse is an incomplete check, including
|
||||
// unindexed files. It must not become an apparently successful sync.
|
||||
scan_failures.extend(rollouts.scan_failures.iter().cloned());
|
||||
for path in &discovery.unreadable_paths {
|
||||
scan_failures.push(format!("无法读取会话数据库: {}", path.display()));
|
||||
}
|
||||
|
||||
let indexed_failures = indexed_rollouts
|
||||
.scan_failures
|
||||
.iter()
|
||||
.cloned()
|
||||
.collect::<HashSet<_>>();
|
||||
let mut warnings = rollouts.warnings.clone();
|
||||
// The full provider/index scans below own warnings and blocking failures;
|
||||
// repeating the lightweight identity scan's messages would duplicate them.
|
||||
warnings.extend(active_sqlite.warnings.iter().cloned());
|
||||
warnings.extend(sqlite.warnings.iter().cloned());
|
||||
warnings.extend(legacy_index_warnings);
|
||||
warnings.extend(
|
||||
rollouts
|
||||
.scan_failures
|
||||
.iter()
|
||||
.filter(|failure| !indexed_failures.contains(*failure))
|
||||
.map(|failure| format!("已跳过未进入会话索引的异常文件:{failure}")),
|
||||
);
|
||||
let mut seen = HashSet::new();
|
||||
scan_failures.retain(|failure| seen.insert(failure.clone()));
|
||||
seen.clear();
|
||||
@@ -223,7 +210,7 @@ pub(super) fn session_sync_status_with_discovery(
|
||||
target: String,
|
||||
discovery: &SqliteDiscovery,
|
||||
) -> Result<SessionSyncStatus> {
|
||||
let scan = scan_provider_sync_data(codex_dir, &target, discovery)?;
|
||||
let scan = scan_provider_sync_data(codex_dir, &target, discovery, false)?;
|
||||
let display_sqlite = if scan.active_sqlite.sqlite_dbs > 0 {
|
||||
&scan.active_sqlite
|
||||
} else {
|
||||
@@ -245,8 +232,12 @@ pub(super) fn session_sync_status_with_discovery(
|
||||
Err(error) => {
|
||||
let mut failures = scan.scan_failures.clone();
|
||||
failures.push(format!("无法读取当前活动会话列表: {error}"));
|
||||
let (directory_identities, pin_scope_key) =
|
||||
session_directory_identities(codex_dir, &[]);
|
||||
return Ok(SessionSyncStatus {
|
||||
codex_dir: codex_dir.display().to_string(),
|
||||
directory_identities,
|
||||
pin_scope_key: Some(pin_scope_key),
|
||||
target_provider: target,
|
||||
rollout_files: scan.rollouts.rollout_files,
|
||||
session_meta_count: scan.rollouts.session_meta_count,
|
||||
@@ -284,10 +275,14 @@ pub(super) fn session_sync_status_with_discovery(
|
||||
&& mismatched_ids.contains(&session.id);
|
||||
}
|
||||
let needs_sync = !scan.rollouts.changes.is_empty()
|
||||
|| !scan.rollouts.mismatched_thread_ids.is_empty()
|
||||
|| scan.sqlite.mismatched_threads > 0
|
||||
|| scan.catalog.total_updates() > 0;
|
||||
let (directory_identities, pin_scope_key) = session_directory_identities(codex_dir, &sessions);
|
||||
Ok(SessionSyncStatus {
|
||||
codex_dir: codex_dir.display().to_string(),
|
||||
directory_identities,
|
||||
pin_scope_key: Some(pin_scope_key),
|
||||
target_provider: target,
|
||||
rollout_files: scan.rollouts.rollout_files,
|
||||
session_meta_count: scan.rollouts.session_meta_count,
|
||||
@@ -376,14 +371,10 @@ where
|
||||
if !initial_status.scan_complete {
|
||||
return Err(scan_failure_error(&initial_status.scan_failures));
|
||||
}
|
||||
let preflight_scan = scan_provider_sync_data(&codex_dir, &target_provider, &discovery)?;
|
||||
if !preflight_scan.scan_failures.is_empty() {
|
||||
return Err(scan_failure_error(&preflight_scan.scan_failures));
|
||||
}
|
||||
if preflight_scan.rollouts.changes.is_empty()
|
||||
&& preflight_scan.sqlite.mismatched_threads == 0
|
||||
&& preflight_scan.catalog.total_updates() == 0
|
||||
{
|
||||
// This status already completed the same full scan. Repeating it before
|
||||
// acquiring SQLite locks neither establishes a newer protected snapshot
|
||||
// nor improves the mutation guard; the locked scan below does that.
|
||||
if !initial_status.needs_sync {
|
||||
return Ok(SessionSyncResult {
|
||||
status: initial_status,
|
||||
updated_rollouts: 0,
|
||||
@@ -394,7 +385,7 @@ where
|
||||
|
||||
hook(MutationPoint::BeforeSqliteLock)?;
|
||||
let mut pending_sqlite = prepare_sqlite_updates(&discovery.related_paths)?;
|
||||
let scan = match scan_provider_sync_data(&codex_dir, &target_provider, &discovery) {
|
||||
let scan = match scan_provider_sync_data(&codex_dir, &target_provider, &discovery, true) {
|
||||
Ok(scan) => scan,
|
||||
Err(error) => {
|
||||
rollback_open_transactions(&mut pending_sqlite);
|
||||
@@ -411,6 +402,14 @@ where
|
||||
{
|
||||
rollback_open_transactions(&mut pending_sqlite);
|
||||
let status = session_sync_status_with_discovery(&codex_dir, target_provider, &discovery)?;
|
||||
if !status.scan_complete {
|
||||
return Err(scan_failure_error(&status.scan_failures));
|
||||
}
|
||||
if status.needs_sync {
|
||||
return Err(CodexxError::Config(
|
||||
"会话状态在检查后发生变化,未完成同步;请重新检查。".to_string(),
|
||||
));
|
||||
}
|
||||
return Ok(SessionSyncResult {
|
||||
status,
|
||||
updated_rollouts: 0,
|
||||
@@ -458,25 +457,32 @@ where
|
||||
}
|
||||
};
|
||||
|
||||
let prune_warning = prune_provider_sync_backups(&codex_dir).err();
|
||||
let mut status = session_sync_status_with_discovery(&codex_dir, target_provider, &discovery)
|
||||
.and_then(|status| {
|
||||
if !status.scan_complete {
|
||||
return Err(scan_failure_error(&status.scan_failures));
|
||||
}
|
||||
if status.needs_sync {
|
||||
return Err(CodexxError::Config(
|
||||
"会话日志与索引仍不一致,未完成同步;请重新检查。".to_string(),
|
||||
));
|
||||
}
|
||||
Ok(status)
|
||||
})
|
||||
.map_err(|error| {
|
||||
CodexxError::Config(format!(
|
||||
"同步已完成,但刷新会话列表失败,请重新进入页面:{error}"
|
||||
))
|
||||
let recovery_errors = rollback_mutation(&journal, &mut pending_sqlite);
|
||||
mutation_error(
|
||||
CodexxError::Config(format!("同步后复查未通过,本轮同步未完成:{error}")),
|
||||
recovery_errors,
|
||||
)
|
||||
})?;
|
||||
let prune_warning = prune_provider_sync_backups(&codex_dir).err();
|
||||
status.backup_dir = Some(backup.dir.display().to_string());
|
||||
if prune_warning.is_some() {
|
||||
status
|
||||
.warnings
|
||||
.push("同步已完成,但旧备份暂未清理。".to_string());
|
||||
}
|
||||
if !mutation.skipped_rollouts.is_empty() {
|
||||
status.warnings.push(format!(
|
||||
"有 {} 个会话正在使用,已跳过;退出 Codex 后再同步即可。",
|
||||
mutation.skipped_rollouts.len()
|
||||
));
|
||||
}
|
||||
Ok(SessionSyncResult {
|
||||
status,
|
||||
updated_rollouts: mutation.applied_rollouts,
|
||||
@@ -489,9 +495,22 @@ where
|
||||
mod tests {
|
||||
use super::*;
|
||||
use rusqlite::Connection;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::io::{BufRead, Read, Seek, SeekFrom};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
const SHARED_SESSION_PROVIDER: &str = "custom";
|
||||
const LEGACY_LIMIT: u64 = 32 * 1024 * 1024;
|
||||
|
||||
mod compressed {
|
||||
use super::*;
|
||||
include!("compressed_sync_tests.rs");
|
||||
}
|
||||
|
||||
mod benchmark {
|
||||
use super::*;
|
||||
include!("session_sync_benchmark.rs");
|
||||
}
|
||||
|
||||
fn temp_codex_dir(label: &str) -> std::path::PathBuf {
|
||||
static COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
@@ -676,6 +695,383 @@ mod tests {
|
||||
.expect("write rollout");
|
||||
}
|
||||
|
||||
fn pad_rollout_to_size(path: &Path, size: u64) {
|
||||
let mut file = fs::OpenOptions::new().append(true).open(path).unwrap();
|
||||
let mut remaining = size.checked_sub(file.metadata().unwrap().len()).unwrap();
|
||||
let padding = [b' '; 64 * 1024];
|
||||
while remaining > 0 {
|
||||
let count = remaining.min(padding.len() as u64) as usize;
|
||||
file.write_all(&padding[..count]).unwrap();
|
||||
remaining -= count as u64;
|
||||
}
|
||||
}
|
||||
|
||||
fn rollout_digest(path: &Path) -> Vec<u8> {
|
||||
rollout_digest_from_offset(path, 0)
|
||||
}
|
||||
|
||||
fn rollout_digest_from_offset(path: &Path, offset: u64) -> Vec<u8> {
|
||||
let mut file = fs::File::open(path).unwrap();
|
||||
file.seek(SeekFrom::Start(offset)).unwrap();
|
||||
let mut digest = Sha256::new();
|
||||
let mut buffer = [0; 64 * 1024];
|
||||
loop {
|
||||
let count = file.read(&mut buffer).unwrap();
|
||||
if count == 0 {
|
||||
return digest.finalize().to_vec();
|
||||
}
|
||||
digest.update(&buffer[..count]);
|
||||
}
|
||||
}
|
||||
|
||||
fn append_chat_record(path: &Path) {
|
||||
fs::OpenOptions::new().append(true).open(path).unwrap()
|
||||
.write_all(b"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"message\":\"keep this conversation\"}}\n")
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn read_first_rollout_record(path: &Path) -> String {
|
||||
let mut first_record = String::new();
|
||||
std::io::BufReader::new(fs::File::open(path).unwrap())
|
||||
.read_line(&mut first_record)
|
||||
.unwrap();
|
||||
first_record
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streamed_rollouts_below_at_and_above_legacy_limit_sync_logs_databases_and_catalogs() {
|
||||
for (name, size) in [
|
||||
("normal", 512),
|
||||
("below-old-limit", LEGACY_LIMIT - 1),
|
||||
("exact-old-limit", LEGACY_LIMIT),
|
||||
("above-old-limit", LEGACY_LIMIT + 1),
|
||||
] {
|
||||
let dir = temp_codex_dir(name);
|
||||
write_config(&dir, "custom");
|
||||
let id = "019f6000-0000-7000-8000-000000000701";
|
||||
let rollout = write_rollout(&dir, id, "openai");
|
||||
let old_record_len = read_first_rollout_record(&rollout).len() as u64;
|
||||
append_chat_record(&rollout);
|
||||
pad_rollout_to_size(&rollout, size);
|
||||
let conversation_before = rollout_digest_from_offset(&rollout, old_record_len);
|
||||
let database = dir.join("state_5.sqlite");
|
||||
create_thread_database_with_rollout(&database, id, "openai", &rollout);
|
||||
let catalog = dir.join("sqlite/codex-dev.db");
|
||||
create_catalog_database(&catalog, &[(id, "openai")]);
|
||||
|
||||
let status = session_sync_status_inner(Some(dir.display().to_string()), None).unwrap();
|
||||
assert!(status.scan_complete, "{name}: {:?}", status.scan_failures);
|
||||
assert!(status.needs_sync, "{name}");
|
||||
let result =
|
||||
sync_sessions_provider_inner(Some(dir.display().to_string()), None).unwrap();
|
||||
assert!(
|
||||
result.status.scan_complete && !result.status.needs_sync,
|
||||
"{name}"
|
||||
);
|
||||
assert_eq!(result.updated_rollouts, 1, "{name}");
|
||||
assert_eq!(thread_provider(&database, id), "custom", "{name}");
|
||||
assert_eq!(catalog_provider(&catalog, id), "custom", "{name}");
|
||||
let first_record = read_first_rollout_record(&rollout);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&first_record).unwrap()["payload"]
|
||||
["model_provider"],
|
||||
"custom"
|
||||
);
|
||||
assert_eq!(fs::metadata(&rollout).unwrap().len(), size, "{name}");
|
||||
assert_eq!(
|
||||
rollout_digest_from_offset(&rollout, first_record.len() as u64),
|
||||
conversation_before,
|
||||
"conversation bytes must be preserved: {name}"
|
||||
);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streamed_ninety_seven_mib_single_chat_line_syncs_without_losing_conversation_bytes() {
|
||||
let dir = temp_codex_dir("streamed-97-mib-chat-record");
|
||||
write_config(&dir, "custom");
|
||||
let id = "019f6000-0000-7000-8000-000000000709";
|
||||
let rollout = write_rollout(&dir, id, "openai");
|
||||
let first_record_len = read_first_rollout_record(&rollout).len() as u64;
|
||||
let total_size = 97 * 1024 * 1024u64;
|
||||
let prefix =
|
||||
b"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"message\":\"";
|
||||
let suffix = b"\"}}\n";
|
||||
let mut file = fs::OpenOptions::new().append(true).open(&rollout).unwrap();
|
||||
file.write_all(prefix).unwrap();
|
||||
let mut remaining =
|
||||
total_size - first_record_len - prefix.len() as u64 - suffix.len() as u64;
|
||||
let body_chunk = [b'x'; 64 * 1024];
|
||||
while remaining > 0 {
|
||||
let count = remaining.min(body_chunk.len() as u64) as usize;
|
||||
file.write_all(&body_chunk[..count]).unwrap();
|
||||
remaining -= count as u64;
|
||||
}
|
||||
file.write_all(suffix).unwrap();
|
||||
file.sync_all().unwrap();
|
||||
drop(file);
|
||||
let conversation_before = rollout_digest_from_offset(&rollout, first_record_len);
|
||||
let database = dir.join("state_5.sqlite");
|
||||
create_thread_database_with_rollout(&database, id, "openai", &rollout);
|
||||
let catalog = dir.join("sqlite/codex-dev.db");
|
||||
create_catalog_database(&catalog, &[(id, "openai")]);
|
||||
|
||||
let result = sync_sessions_provider_inner(Some(dir.display().to_string()), None)
|
||||
.expect("a large valid single JSONL record must synchronize successfully");
|
||||
|
||||
assert!(
|
||||
result.status.scan_complete && !result.status.needs_sync,
|
||||
"{:?}",
|
||||
result.status.scan_failures
|
||||
);
|
||||
assert_eq!(result.updated_rollouts, 1);
|
||||
assert_eq!(thread_provider(&database, id), "custom");
|
||||
assert_eq!(catalog_provider(&catalog, id), "custom");
|
||||
let first_record = read_first_rollout_record(&rollout);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&first_record).unwrap()["payload"]
|
||||
["model_provider"],
|
||||
"custom"
|
||||
);
|
||||
assert_eq!(fs::metadata(&rollout).unwrap().len(), total_size);
|
||||
assert_eq!(
|
||||
rollout_digest_from_offset(&rollout, first_record.len() as u64),
|
||||
conversation_before,
|
||||
"the large chat record must retain every original byte"
|
||||
);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streamed_multiple_rollouts_exceeding_legacy_snapshot_budget_sync_together() {
|
||||
let dir = temp_codex_dir("streamed-multi-large-rollout-budget");
|
||||
write_config(&dir, "custom");
|
||||
let ids = [
|
||||
"019f6000-0000-7000-8000-000000000711",
|
||||
"019f6000-0000-7000-8000-000000000712",
|
||||
"019f6000-0000-7000-8000-000000000713",
|
||||
];
|
||||
let file_size = 45 * 1024 * 1024u64;
|
||||
assert!(file_size * ids.len() as u64 > 128 * 1024 * 1024);
|
||||
let mut rollouts = Vec::new();
|
||||
let mut conversation_digests = Vec::new();
|
||||
for id in ids {
|
||||
let rollout = write_rollout(&dir, id, "openai");
|
||||
let first_record_len = read_first_rollout_record(&rollout).len() as u64;
|
||||
append_chat_record(&rollout);
|
||||
pad_rollout_to_size(&rollout, file_size);
|
||||
conversation_digests.push(rollout_digest_from_offset(&rollout, first_record_len));
|
||||
rollouts.push(rollout);
|
||||
}
|
||||
let database = dir.join("state_5.sqlite");
|
||||
create_thread_database_with_rollout(&database, ids[0], "openai", &rollouts[0]);
|
||||
let conn = Connection::open(&database).unwrap();
|
||||
for index in 1..ids.len() {
|
||||
conn.execute(
|
||||
"INSERT INTO threads (id, model_provider, title, rollout_path) VALUES (?1, 'openai', 'large history', ?2)",
|
||||
(ids[index], rollouts[index].display().to_string()),
|
||||
).unwrap();
|
||||
}
|
||||
drop(conn);
|
||||
let catalog = dir.join("sqlite/codex-dev.db");
|
||||
create_catalog_database(&catalog, &ids.map(|id| (id, "openai")));
|
||||
|
||||
let result = sync_sessions_provider_inner(Some(dir.display().to_string()), None)
|
||||
.expect("the combined size of valid rollouts must not block synchronization");
|
||||
|
||||
assert!(
|
||||
result.status.scan_complete && !result.status.needs_sync,
|
||||
"{:?}",
|
||||
result.status.scan_failures
|
||||
);
|
||||
assert_eq!(result.updated_rollouts, ids.len());
|
||||
for index in 0..ids.len() {
|
||||
assert_eq!(thread_provider(&database, ids[index]), "custom");
|
||||
assert_eq!(catalog_provider(&catalog, ids[index]), "custom");
|
||||
let first_record = read_first_rollout_record(&rollouts[index]);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&first_record).unwrap()["payload"]
|
||||
["model_provider"],
|
||||
"custom"
|
||||
);
|
||||
assert_eq!(fs::metadata(&rollouts[index]).unwrap().len(), file_size);
|
||||
assert_eq!(
|
||||
rollout_digest_from_offset(&rollouts[index], first_record.len() as u64),
|
||||
conversation_digests[index],
|
||||
"conversation bytes must remain unchanged for {}",
|
||||
ids[index]
|
||||
);
|
||||
}
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_invalid_jsonl_rollout_reports_parse_failure_and_keeps_indexes_unchanged() {
|
||||
for (name, file_provider, database_provider) in [
|
||||
("file-and-index-old", "openai", "openai"),
|
||||
("index-already-target", "openai", "custom"),
|
||||
("first-record-matches", "custom", "custom"),
|
||||
] {
|
||||
let dir = temp_codex_dir(name);
|
||||
write_config(&dir, "custom");
|
||||
let id = "019f6000-0000-7000-8000-000000000702";
|
||||
let rollout = write_rollout(&dir, id, file_provider);
|
||||
fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.open(&rollout)
|
||||
.unwrap()
|
||||
.set_len(LEGACY_LIMIT + 1)
|
||||
.unwrap();
|
||||
let before = rollout_digest(&rollout);
|
||||
let database = dir.join("state_5.sqlite");
|
||||
create_thread_database_with_rollout(&database, id, database_provider, &rollout);
|
||||
let catalog = dir.join("sqlite/codex-dev.db");
|
||||
create_catalog_database(&catalog, &[(id, database_provider)]);
|
||||
|
||||
let status = session_sync_status_inner(Some(dir.display().to_string()), None).unwrap();
|
||||
assert!(!status.scan_complete, "{name}");
|
||||
assert!(
|
||||
status
|
||||
.scan_failures
|
||||
.iter()
|
||||
.any(|failure| failure.contains("JSONL")),
|
||||
"{name}: {:?}",
|
||||
status.scan_failures
|
||||
);
|
||||
let error =
|
||||
sync_sessions_provider_inner(Some(dir.display().to_string()), None).unwrap_err();
|
||||
assert!(error.to_string().contains("JSONL"), "{name}: {error}");
|
||||
assert_eq!(thread_provider(&database, id), database_provider, "{name}");
|
||||
assert_eq!(catalog_provider(&catalog, id), database_provider, "{name}");
|
||||
assert_eq!(rollout_digest(&rollout), before, "{name}");
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_invalid_orphan_blocks_sync_without_changing_normal_logs_or_indexes() {
|
||||
let dir = temp_codex_dir("large-invalid-orphan-blocked");
|
||||
write_config(&dir, "custom");
|
||||
let ordinary_id = "019f6000-0000-7000-8000-000000000703";
|
||||
let ordinary = write_rollout(&dir, ordinary_id, "openai");
|
||||
let before = fs::read(&ordinary).unwrap();
|
||||
let database = dir.join("state_5.sqlite");
|
||||
create_thread_database_with_rollout(&database, ordinary_id, "openai", &ordinary);
|
||||
let catalog = dir.join("sqlite/codex-dev.db");
|
||||
create_catalog_database(&catalog, &[(ordinary_id, "openai")]);
|
||||
let orphan_id = "019f6000-0000-7000-8000-000000000704";
|
||||
let invalid_orphan = write_rollout(&dir, orphan_id, "openai");
|
||||
fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.open(&invalid_orphan)
|
||||
.unwrap()
|
||||
.set_len(LEGACY_LIMIT + 1)
|
||||
.unwrap();
|
||||
let orphan_before = rollout_digest(&invalid_orphan);
|
||||
|
||||
let status = session_sync_status_inner(Some(dir.display().to_string()), None).unwrap();
|
||||
assert!(!status.scan_complete && status.needs_sync);
|
||||
let error =
|
||||
sync_sessions_provider_inner(Some(dir.display().to_string()), None).unwrap_err();
|
||||
assert!(error.to_string().contains("JSONL"), "{error}");
|
||||
assert_eq!(fs::read(&ordinary).unwrap(), before);
|
||||
assert_eq!(rollout_digest(&invalid_orphan), orphan_before);
|
||||
assert_eq!(thread_provider(&database, ordinary_id), "openai");
|
||||
assert_eq!(catalog_provider(&catalog, ordinary_id), "openai");
|
||||
assert!(catalog_provider_and_visibility(&catalog, orphan_id).is_none());
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_orphan_read_or_parse_cannot_be_reported_as_successful_sync() {
|
||||
for suffix in [b"\xff".as_slice(), b"not-json\n".as_slice()] {
|
||||
let dir = temp_codex_dir("failed-orphan-check-blocks-sync");
|
||||
write_config(&dir, "custom");
|
||||
let id = "019f6000-0000-7000-8000-000000000705";
|
||||
let ordinary = write_rollout(&dir, id, "openai");
|
||||
let original = fs::read(&ordinary).unwrap();
|
||||
let database = dir.join("state_5.sqlite");
|
||||
create_thread_database_with_rollout(&database, id, "openai", &ordinary);
|
||||
let catalog = dir.join("sqlite/codex-dev.db");
|
||||
create_catalog_database(&catalog, &[(id, "openai")]);
|
||||
let orphan = write_rollout(&dir, "019f6000-0000-7000-8000-000000000706", "openai");
|
||||
fs::OpenOptions::new()
|
||||
.append(true)
|
||||
.open(&orphan)
|
||||
.unwrap()
|
||||
.write_all(suffix)
|
||||
.unwrap();
|
||||
let orphan_original = fs::read(&orphan).unwrap();
|
||||
|
||||
let status = session_sync_status_inner(Some(dir.display().to_string()), None).unwrap();
|
||||
assert!(!status.scan_complete && !status.scan_failures.is_empty());
|
||||
assert!(sync_sessions_provider_inner(Some(dir.display().to_string()), None).is_err());
|
||||
assert_eq!(thread_provider(&database, id), "openai");
|
||||
assert_eq!(catalog_provider(&catalog, id), "openai");
|
||||
assert_eq!(fs::read(&ordinary).unwrap(), original);
|
||||
assert_eq!(fs::read(&orphan).unwrap(), orphan_original);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_final_recheck_rolls_back_committed_logs_and_indexes() {
|
||||
for scenario in ["invalid", "large-invalid", "new-mismatch"] {
|
||||
let dir = temp_codex_dir("failed-final-recheck");
|
||||
write_config(&dir, "custom");
|
||||
let id = "019f6000-0000-7000-8000-000000000707";
|
||||
let ordinary = write_rollout(&dir, id, "openai");
|
||||
let original = fs::read(&ordinary).unwrap();
|
||||
let database = dir.join("state_5.sqlite");
|
||||
create_thread_database_with_rollout(&database, id, "openai", &ordinary);
|
||||
let catalog = dir.join("sqlite/codex-dev.db");
|
||||
create_catalog_database(&catalog, &[(id, "openai")]);
|
||||
let late = dir.join("sessions/rollout-test-019f6000-0000-7000-8000-000000000708.jsonl");
|
||||
let mut late_digest = None;
|
||||
|
||||
let error =
|
||||
sync_sessions_provider_with_hook(Some(dir.display().to_string()), None, |point| {
|
||||
if matches!(point, MutationPoint::AfterSqliteCommit(_)) && !late.exists() {
|
||||
if scenario == "invalid" {
|
||||
fs::write(&late, b"\xff").unwrap();
|
||||
} else {
|
||||
write_rollout_at(
|
||||
&late,
|
||||
"019f6000-0000-7000-8000-000000000708",
|
||||
"openai",
|
||||
);
|
||||
if scenario == "large-invalid" {
|
||||
fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.open(&late)
|
||||
.unwrap()
|
||||
.set_len(LEGACY_LIMIT + 1)
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
late_digest = Some(rollout_digest(&late));
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.expect_err("a failed final check must not return a successful sync");
|
||||
|
||||
assert!(
|
||||
error.to_string().contains("同步后复查未通过"),
|
||||
"{scenario}: {error}"
|
||||
);
|
||||
assert_eq!(thread_provider(&database, id), "openai", "{scenario}");
|
||||
assert_eq!(catalog_provider(&catalog, id), "openai", "{scenario}");
|
||||
assert_eq!(fs::read(&ordinary).unwrap(), original, "{scenario}");
|
||||
assert_eq!(
|
||||
rollout_digest(&late),
|
||||
late_digest.unwrap(),
|
||||
"preserve external file: {scenario}"
|
||||
);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn write_subagent_rollout(
|
||||
codex_dir: &Path,
|
||||
id: &str,
|
||||
@@ -975,7 +1371,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_standard_orphan_rollout_does_not_block_active_sessions() {
|
||||
fn malformed_standard_orphan_keeps_check_incomplete_without_mutation() {
|
||||
let codex_dir = temp_codex_dir("malformed-standard-orphan");
|
||||
write_config(&codex_dir, SHARED_SESSION_PROVIDER);
|
||||
let active_id = "019f6000-0000-7000-8000-000000000502";
|
||||
@@ -985,26 +1381,30 @@ mod tests {
|
||||
active_id,
|
||||
SHARED_SESSION_PROVIDER,
|
||||
);
|
||||
write_rollout(&codex_dir, active_id, SHARED_SESSION_PROVIDER);
|
||||
fs::write(
|
||||
codex_dir.join(format!("sessions/rollout-test-{orphan_id}.jsonl")),
|
||||
b"\xff",
|
||||
)
|
||||
.expect("write invalid orphan rollout");
|
||||
let active = write_rollout(&codex_dir, active_id, SHARED_SESSION_PROVIDER);
|
||||
let active_before = fs::read(&active).unwrap();
|
||||
let database = codex_dir.join("state_5.sqlite");
|
||||
let database_before = fs::read(&database).unwrap();
|
||||
let orphan = codex_dir.join(format!("sessions/rollout-test-{orphan_id}.jsonl"));
|
||||
fs::write(&orphan, b"\xff").expect("write invalid orphan rollout");
|
||||
|
||||
let status = session_sync_status_inner(Some(codex_dir.display().to_string()), None)
|
||||
.expect("scan active sessions only");
|
||||
assert!(status.scan_complete, "{:?}", status.scan_failures);
|
||||
assert!(!status.scan_complete);
|
||||
assert!(!status.scan_failures.is_empty());
|
||||
assert_eq!(status.rollout_files, 2);
|
||||
assert_eq!(status.session_meta_count, 1);
|
||||
assert!(!status.needs_sync);
|
||||
assert_eq!(status.warnings.len(), 1);
|
||||
assert!(sync_sessions_provider_inner(Some(codex_dir.display().to_string()), None).is_err());
|
||||
assert_eq!(fs::read(&active).unwrap(), active_before);
|
||||
assert_eq!(fs::read(&database).unwrap(), database_before);
|
||||
assert_eq!(fs::read(&orphan).unwrap(), b"\xff");
|
||||
|
||||
fs::remove_dir_all(codex_dir).expect("remove test directory");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_unreferenced_nonstandard_rollout_does_not_block_active_sessions() {
|
||||
fn malformed_unreferenced_rollout_keeps_check_incomplete_without_mutation() {
|
||||
let codex_dir = temp_codex_dir("malformed-unreferenced-rollout");
|
||||
write_config(&codex_dir, SHARED_SESSION_PROVIDER);
|
||||
let active_id = "019f6000-0000-7000-8000-000000000504";
|
||||
@@ -1013,19 +1413,23 @@ mod tests {
|
||||
active_id,
|
||||
SHARED_SESSION_PROVIDER,
|
||||
);
|
||||
write_rollout(&codex_dir, active_id, SHARED_SESSION_PROVIDER);
|
||||
fs::write(
|
||||
codex_dir.join("sessions/rollout-imported-orphan.jsonl"),
|
||||
b"\xff",
|
||||
)
|
||||
.expect("write invalid unreferenced rollout");
|
||||
let active = write_rollout(&codex_dir, active_id, SHARED_SESSION_PROVIDER);
|
||||
let active_before = fs::read(&active).unwrap();
|
||||
let database = codex_dir.join("state_5.sqlite");
|
||||
let database_before = fs::read(&database).unwrap();
|
||||
let orphan = codex_dir.join("sessions/rollout-imported-orphan.jsonl");
|
||||
fs::write(&orphan, b"\xff").expect("write invalid unreferenced rollout");
|
||||
|
||||
let status = session_sync_status_inner(Some(codex_dir.display().to_string()), None)
|
||||
.expect("scan referenced sessions only");
|
||||
assert!(status.scan_complete, "{:?}", status.scan_failures);
|
||||
assert!(!status.scan_complete);
|
||||
assert!(!status.scan_failures.is_empty());
|
||||
assert_eq!(status.rollout_files, 2);
|
||||
assert_eq!(status.session_meta_count, 1);
|
||||
assert_eq!(status.warnings.len(), 1);
|
||||
assert!(sync_sessions_provider_inner(Some(codex_dir.display().to_string()), None).is_err());
|
||||
assert_eq!(fs::read(&active).unwrap(), active_before);
|
||||
assert_eq!(fs::read(&database).unwrap(), database_before);
|
||||
assert_eq!(fs::read(&orphan).unwrap(), b"\xff");
|
||||
|
||||
fs::remove_dir_all(codex_dir).expect("remove test directory");
|
||||
}
|
||||
|
||||
@@ -2,9 +2,10 @@ use super::catalog::{
|
||||
apply_catalog_updates, catalog_columns, create_catalog_rollback_tables,
|
||||
restore_catalog_updates, CatalogRepairThread,
|
||||
};
|
||||
use super::rollout_stream::ensure_current_rollout_representation;
|
||||
use super::storage::{
|
||||
apply_session_changes, restore_session_changes, rollout_path_has_syncable_identity,
|
||||
rollout_text_is_internal, sqlite_subagent_thread_ids,
|
||||
apply_session_changes_with_hook, hash_rollout_file, restore_session_changes,
|
||||
rollout_path_has_syncable_identity, rollout_text_is_internal, sqlite_subagent_thread_ids,
|
||||
};
|
||||
use super::types::{RolloutScan, SessionFileChange};
|
||||
use crate::error::{CodexxError, Result};
|
||||
@@ -37,6 +38,7 @@ impl SqliteUpdateCounts {
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct MutationJournal {
|
||||
applied_rollouts: Vec<SessionFileChange>,
|
||||
expected_rollout_hashes: HashMap<PathBuf, [u8; 32]>,
|
||||
sqlite_restore_attempts: Vec<SqliteRestoreAttempt>,
|
||||
}
|
||||
|
||||
@@ -285,6 +287,7 @@ where
|
||||
{
|
||||
let mut updated = SqliteUpdateCounts::default();
|
||||
for index in 0..pending.len() {
|
||||
validate_rollout_snapshots(&journal.expected_rollout_hashes)?;
|
||||
let before_commit = sqlite_data_version(&pending[index].observer)?;
|
||||
journal.sqlite_restore_attempts.push(SqliteRestoreAttempt {
|
||||
path: pending[index].path.clone(),
|
||||
@@ -311,6 +314,9 @@ where
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
// The final commit hook can publish an external rollout update as well.
|
||||
// Returning success requires the complete candidate set to remain verified.
|
||||
validate_rollout_snapshots(&journal.expected_rollout_hashes)?;
|
||||
Ok(updated)
|
||||
}
|
||||
|
||||
@@ -418,13 +424,13 @@ pub(super) fn mutation_error(original: CodexxError, recovery_errors: Vec<String>
|
||||
pub(super) enum MutationPoint {
|
||||
BeforeSqliteLock,
|
||||
BeforeRolloutMutation,
|
||||
BeforeEachRolloutMutation(usize),
|
||||
AfterRolloutMutation,
|
||||
AfterSqliteCommit(usize),
|
||||
}
|
||||
|
||||
pub(super) struct MutationResult {
|
||||
pub(super) applied_rollouts: usize,
|
||||
pub(super) skipped_rollouts: Vec<PathBuf>,
|
||||
pub(super) sqlite_updates: SqliteUpdateCounts,
|
||||
}
|
||||
|
||||
@@ -434,7 +440,12 @@ pub(super) struct MutationResult {
|
||||
fn validate_rollout_classification(rollouts: &RolloutScan) -> Result<()> {
|
||||
let mut paths = rollouts.provider_candidate_paths.clone();
|
||||
for change in &rollouts.changes {
|
||||
if rollout_text_is_internal(&change.original_text) {
|
||||
let original_is_internal = if let Some(snapshot) = &change.streamed {
|
||||
!rollout_path_has_syncable_identity(&snapshot.original_path)?
|
||||
} else {
|
||||
rollout_text_is_internal(&change.original_text)
|
||||
};
|
||||
if original_is_internal {
|
||||
return Err(CodexxError::Config(
|
||||
"内部会话不能同步为普通会话。".to_string(),
|
||||
));
|
||||
@@ -452,6 +463,47 @@ fn validate_rollout_classification(rollouts: &RolloutScan) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn expected_rollout_hashes(rollouts: &RolloutScan) -> Result<HashMap<PathBuf, [u8; 32]>> {
|
||||
let mut expected = HashMap::new();
|
||||
for path in &rollouts.provider_candidate_paths {
|
||||
let hash = rollouts.verified_rollout_hashes.get(path).ok_or_else(|| {
|
||||
CodexxError::Config(format!(
|
||||
"缺少会话文件验证快照,已停止同步:{}",
|
||||
path.display()
|
||||
))
|
||||
})?;
|
||||
expected.insert(path.clone(), *hash);
|
||||
}
|
||||
for change in &rollouts.changes {
|
||||
let original_hash = change.original_hash();
|
||||
if expected
|
||||
.get(&change.path)
|
||||
.is_some_and(|hash| *hash != original_hash)
|
||||
{
|
||||
return Err(CodexxError::Config(format!(
|
||||
"会话文件改写快照与扫描结果不一致,已停止同步:{}",
|
||||
change.path.display()
|
||||
)));
|
||||
}
|
||||
// A planned change already carries the scan's verified original snapshot.
|
||||
expected.insert(change.path.clone(), original_hash);
|
||||
}
|
||||
Ok(expected)
|
||||
}
|
||||
|
||||
fn validate_rollout_snapshots(expected: &HashMap<PathBuf, [u8; 32]>) -> Result<()> {
|
||||
for (path, expected_hash) in expected {
|
||||
ensure_current_rollout_representation(path)?;
|
||||
if hash_rollout_file(path).map_err(|error| io_err(path, error))? != *expected_hash {
|
||||
return Err(CodexxError::Config(format!(
|
||||
"会话文件已发生变化,已停止同步;请重新检查会话:{}",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn execute_provider_sync_mutation<F>(
|
||||
rollouts: &RolloutScan,
|
||||
pending_sqlite: &mut [PendingSqliteUpdate],
|
||||
@@ -465,12 +517,35 @@ where
|
||||
F: FnMut(MutationPoint) -> Result<()>,
|
||||
{
|
||||
let result = (|| -> Result<MutationResult> {
|
||||
if !rollouts.blocked_failures.is_empty() {
|
||||
return Err(CodexxError::Config(format!(
|
||||
"会话扫描未完成,已停止同步:{}",
|
||||
rollouts.blocked_failures.join(";")
|
||||
)));
|
||||
}
|
||||
journal.expected_rollout_hashes = expected_rollout_hashes(rollouts)?;
|
||||
hook(MutationPoint::BeforeRolloutMutation)?;
|
||||
validate_rollout_classification(rollouts)?;
|
||||
let (applied_rollouts, skipped_rollouts) = apply_session_changes(&rollouts.changes)?;
|
||||
validate_rollout_snapshots(&journal.expected_rollout_hashes)?;
|
||||
let (applied_rollouts, skipped_rollouts) =
|
||||
apply_session_changes_with_hook(&rollouts.changes, |index| {
|
||||
hook(MutationPoint::BeforeEachRolloutMutation(index))
|
||||
})?;
|
||||
journal.applied_rollouts = applied_rollouts;
|
||||
for change in &journal.applied_rollouts {
|
||||
journal
|
||||
.expected_rollout_hashes
|
||||
.insert(change.path.clone(), change.next_hash());
|
||||
}
|
||||
if !skipped_rollouts.is_empty() {
|
||||
return Err(CodexxError::Config(format!(
|
||||
"有 {} 个会话文件被占用或已发生变化,已停止同步;请退出 Codex 后重新检查会话。",
|
||||
skipped_rollouts.len()
|
||||
)));
|
||||
}
|
||||
hook(MutationPoint::AfterRolloutMutation)?;
|
||||
validate_rollout_classification(rollouts)?;
|
||||
validate_rollout_snapshots(&journal.expected_rollout_hashes)?;
|
||||
apply_sqlite_updates(
|
||||
pending_sqlite,
|
||||
rollouts,
|
||||
@@ -481,7 +556,6 @@ where
|
||||
let sqlite_updates = commit_sqlite_updates(pending_sqlite, journal, hook)?;
|
||||
Ok(MutationResult {
|
||||
applied_rollouts: journal.applied_rollouts.len(),
|
||||
skipped_rollouts,
|
||||
sqlite_updates,
|
||||
})
|
||||
})();
|
||||
|
||||
@@ -2,13 +2,16 @@ use super::*;
|
||||
use crate::sessions::backup::provider_sync_backup_root;
|
||||
use crate::sessions::sync::sync_sessions_provider_with_hook;
|
||||
use rusqlite::{Connection, OpenFlags};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::io::{Read, Seek, SeekFrom, Write};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::mpsc;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
const LARGE_ROLLOUT_TEST_BYTES: u64 = 33 * 1024 * 1024;
|
||||
|
||||
fn temp_dir(name: &str) -> PathBuf {
|
||||
static COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
@@ -73,6 +76,633 @@ fn sqlite_quick_check(path: &Path) -> String {
|
||||
.expect("run quick check")
|
||||
}
|
||||
|
||||
struct RolloutFailureFixture {
|
||||
codex_dir: PathBuf,
|
||||
ids: [&'static str; 2],
|
||||
rollouts: [PathBuf; 2],
|
||||
originals: [Vec<u8>; 2],
|
||||
database: PathBuf,
|
||||
catalog: PathBuf,
|
||||
}
|
||||
|
||||
impl RolloutFailureFixture {
|
||||
fn new(name: &str) -> Self {
|
||||
let codex_dir = temp_dir(name);
|
||||
let ids = [
|
||||
"019f6000-0000-7000-8000-000000000991",
|
||||
"019f6000-0000-7000-8000-000000000992",
|
||||
];
|
||||
let rollouts = ids.map(|id| codex_dir.join(format!("sessions/rollout-test-{id}.jsonl")));
|
||||
let originals = std::array::from_fn(|index| write_rollout(&rollouts[index], ids[index]));
|
||||
let database = codex_dir.join("state_10.sqlite");
|
||||
create_thread_database(&database, ids[0], &rollouts[0]);
|
||||
Connection::open(&database)
|
||||
.unwrap()
|
||||
.execute(
|
||||
"INSERT INTO threads (id, model_provider, rollout_path) VALUES (?1, 'openai', ?2)",
|
||||
(ids[1], rollouts[1].display().to_string()),
|
||||
)
|
||||
.unwrap();
|
||||
let catalog = codex_dir.join("sqlite/codex-dev.db");
|
||||
fs::create_dir_all(catalog.parent().unwrap()).unwrap();
|
||||
let conn = Connection::open(&catalog).unwrap();
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE local_thread_catalog (
|
||||
host_id TEXT NOT NULL, thread_id TEXT NOT NULL, model_provider TEXT NOT NULL,
|
||||
PRIMARY KEY (host_id, thread_id));
|
||||
CREATE TABLE local_thread_catalog_metadata (
|
||||
id INTEGER PRIMARY KEY, catalog_revision INTEGER NOT NULL);
|
||||
INSERT INTO local_thread_catalog_metadata VALUES (1, 7);",
|
||||
)
|
||||
.unwrap();
|
||||
for id in ids {
|
||||
conn.execute(
|
||||
"INSERT INTO local_thread_catalog VALUES ('local', ?1, 'openai')",
|
||||
[id],
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
Self {
|
||||
codex_dir,
|
||||
ids,
|
||||
rollouts,
|
||||
originals,
|
||||
database,
|
||||
catalog,
|
||||
}
|
||||
}
|
||||
|
||||
fn scan(&self) -> RolloutScan {
|
||||
let changes = (0..2)
|
||||
.map(|index| {
|
||||
let original_text = String::from_utf8(self.originals[index].clone()).unwrap();
|
||||
SessionFileChange {
|
||||
path: self.rollouts[index].clone(),
|
||||
next_text: original_text.replace("\"openai\"", "\"custom\""),
|
||||
original_text,
|
||||
original_mtime: None,
|
||||
streamed: None,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
RolloutScan {
|
||||
changes,
|
||||
provider_candidate_paths: self.rollouts.iter().cloned().collect(),
|
||||
verified_rollout_hashes: (0..2)
|
||||
.map(|index| {
|
||||
(
|
||||
self.rollouts[index].clone(),
|
||||
Sha256::digest(&self.originals[index]).into(),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
..RolloutScan::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn set_rollouts_to_target_provider(&mut self) {
|
||||
for index in 0..2 {
|
||||
self.originals[index] = String::from_utf8(self.originals[index].clone())
|
||||
.unwrap()
|
||||
.replace("\"openai\"", "\"custom\"")
|
||||
.into_bytes();
|
||||
fs::write(&self.rollouts[index], &self.originals[index]).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn catalog_provider(&self, id: &str) -> String {
|
||||
Connection::open(&self.catalog)
|
||||
.unwrap()
|
||||
.query_row(
|
||||
"SELECT model_provider FROM local_thread_catalog WHERE thread_id = ?1",
|
||||
[id],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn assert_databases_unchanged(&self) {
|
||||
for id in self.ids {
|
||||
assert_eq!(thread_provider(&self.database, id), "openai");
|
||||
assert_eq!(self.catalog_provider(id), "openai");
|
||||
}
|
||||
let (rows, revision): (i64, i64) = Connection::open(&self.catalog)
|
||||
.unwrap()
|
||||
.query_row(
|
||||
"SELECT (SELECT COUNT(*) FROM local_thread_catalog),
|
||||
(SELECT catalog_revision FROM local_thread_catalog_metadata WHERE id = 1)",
|
||||
[],
|
||||
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!((rows, revision), (2, 7));
|
||||
}
|
||||
|
||||
fn sync_with_hook<F>(&self, hook: F) -> Result<super::super::types::SessionSyncResult>
|
||||
where
|
||||
F: FnMut(MutationPoint) -> Result<()>,
|
||||
{
|
||||
sync_sessions_provider_with_hook(Some(self.codex_dir.display().to_string()), None, hook)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for RolloutFailureFixture {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.codex_dir);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocked_rollout_scan_aborts_before_hooks_or_database_updates() {
|
||||
let fixture = RolloutFailureFixture::new("bounded-blocked-scan");
|
||||
let mut rollouts = fixture.scan();
|
||||
rollouts
|
||||
.blocked_failures
|
||||
.push("会话文件读取失败,未完成扫描".to_string());
|
||||
let mut pending =
|
||||
prepare_sqlite_updates(&[fixture.database.clone(), fixture.catalog.clone()]).unwrap();
|
||||
let mut journal = MutationJournal::default();
|
||||
let mut hook_called = false;
|
||||
let error = execute_provider_sync_mutation(
|
||||
&rollouts,
|
||||
&mut pending,
|
||||
"custom",
|
||||
&HashMap::new(),
|
||||
&fixture.ids.map(str::to_string).into_iter().collect(),
|
||||
&mut journal,
|
||||
&mut |_| {
|
||||
hook_called = true;
|
||||
Ok(())
|
||||
},
|
||||
)
|
||||
.err()
|
||||
.expect("blocked scan must fail");
|
||||
assert!(error.to_string().contains("读取失败"));
|
||||
assert!(!hook_called);
|
||||
assert!(journal.applied_rollouts.is_empty());
|
||||
assert!(rollback_mutation(&journal, &mut pending).is_empty());
|
||||
fixture.assert_databases_unchanged();
|
||||
for index in 0..2 {
|
||||
assert_eq!(
|
||||
fs::read(&fixture.rollouts[index]).unwrap(),
|
||||
fixture.originals[index]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrent_rollout_change_is_rejected_before_file_or_database_updates() {
|
||||
let fixture = RolloutFailureFixture::new("bounded-skip-rollback");
|
||||
let mut external = fixture.originals[1].clone();
|
||||
external.extend_from_slice(
|
||||
b"{\"type\":\"event_msg\",\"payload\":{\"message\":\"keep-new-data\"}}\n",
|
||||
);
|
||||
let error = fixture
|
||||
.sync_with_hook(|point| {
|
||||
if point == MutationPoint::BeforeRolloutMutation {
|
||||
fs::write(&fixture.rollouts[1], &external).unwrap();
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.expect_err("any skipped rollout must abort the full sync");
|
||||
assert!(error.to_string().contains("已停止同步"), "{error}");
|
||||
fixture.assert_databases_unchanged();
|
||||
assert_eq!(
|
||||
fs::read(&fixture.rollouts[0]).unwrap(),
|
||||
fixture.originals[0]
|
||||
);
|
||||
assert_eq!(fs::read(&fixture.rollouts[1]).unwrap(), external);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skipped_rollout_after_first_write_rolls_back_and_never_updates_indexes() {
|
||||
let fixture = RolloutFailureFixture::new("streamed-skip-after-write");
|
||||
let mut external = fixture.originals[1].clone();
|
||||
external.extend_from_slice(
|
||||
b"{\"type\":\"event_msg\",\"payload\":{\"message\":\"keep-external-data\"}}\n",
|
||||
);
|
||||
let mut first_write_observed = false;
|
||||
let error = fixture
|
||||
.sync_with_hook(|point| {
|
||||
if point == MutationPoint::BeforeEachRolloutMutation(1) {
|
||||
first_write_observed = fs::read_to_string(&fixture.rollouts[0])
|
||||
.unwrap()
|
||||
.contains("custom");
|
||||
fs::write(&fixture.rollouts[1], &external).unwrap();
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.expect_err("a skipped second rollout must fail and roll back the first write");
|
||||
assert!(first_write_observed);
|
||||
assert!(error.to_string().contains("已停止同步"), "{error}");
|
||||
fixture.assert_databases_unchanged();
|
||||
assert_eq!(
|
||||
fs::read(&fixture.rollouts[0]).unwrap(),
|
||||
fixture.originals[0]
|
||||
);
|
||||
assert_eq!(fs::read(&fixture.rollouts[1]).unwrap(), external);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rollout_read_failure_after_scan_aborts_without_database_updates() {
|
||||
let fixture = RolloutFailureFixture::new("bounded-read-failure");
|
||||
let error = fixture
|
||||
.sync_with_hook(|point| {
|
||||
if point == MutationPoint::BeforeRolloutMutation {
|
||||
fs::remove_file(&fixture.rollouts[1]).unwrap();
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.expect_err("unreadable full rollout must fail the sync");
|
||||
assert!(error.to_string().contains(fixture.ids[1]), "{error}");
|
||||
fixture.assert_databases_unchanged();
|
||||
assert_eq!(
|
||||
fs::read(&fixture.rollouts[0]).unwrap(),
|
||||
fixture.originals[0]
|
||||
);
|
||||
assert!(
|
||||
!fixture.rollouts[1].exists(),
|
||||
"external deletion must be preserved"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn rollout_atomic_write_failure_restores_earlier_files_without_database_updates() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mut fixture = RolloutFailureFixture::new("streaming-write-failure");
|
||||
let blocked_parent = fixture.codex_dir.join("sessions/zz-write-blocked");
|
||||
fs::create_dir_all(&blocked_parent).unwrap();
|
||||
let second_path = blocked_parent.join(fixture.rollouts[1].file_name().unwrap());
|
||||
fs::rename(&fixture.rollouts[1], &second_path).unwrap();
|
||||
fixture.rollouts[1] = second_path;
|
||||
Connection::open(&fixture.database)
|
||||
.unwrap()
|
||||
.execute(
|
||||
"UPDATE threads SET rollout_path = ?1 WHERE id = ?2",
|
||||
(fixture.rollouts[1].display().to_string(), fixture.ids[1]),
|
||||
)
|
||||
.unwrap();
|
||||
let mut reached_file_mutation = false;
|
||||
let result = fixture.sync_with_hook(|point| {
|
||||
if point == MutationPoint::BeforeEachRolloutMutation(1) {
|
||||
reached_file_mutation = true;
|
||||
fs::set_permissions(&blocked_parent, fs::Permissions::from_mode(0o500)).unwrap();
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
// Always restore the temporary fixture permissions before assertions/drop.
|
||||
fs::set_permissions(&blocked_parent, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let error = result.expect_err("temporary rollout write permission failure must fail sync");
|
||||
assert!(
|
||||
reached_file_mutation,
|
||||
"failure must occur after scan and backup"
|
||||
);
|
||||
assert!(error.to_string().contains("IO error"), "{error}");
|
||||
fixture.assert_databases_unchanged();
|
||||
for index in 0..2 {
|
||||
assert_eq!(
|
||||
fs::read(&fixture.rollouts[index]).unwrap(),
|
||||
fixture.originals[index]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordinary_provider_rewrite_after_mutation_aborts_without_database_or_catalog_changes() {
|
||||
let fixture = RolloutFailureFixture::new("bounded-provider-race");
|
||||
let external = fixture.originals[1].clone();
|
||||
let error = fixture
|
||||
.sync_with_hook(|point| {
|
||||
if point == MutationPoint::AfterRolloutMutation {
|
||||
assert!(fs::read_to_string(&fixture.rollouts[0])
|
||||
.unwrap()
|
||||
.contains("\"custom\""));
|
||||
assert!(fs::read_to_string(&fixture.rollouts[1])
|
||||
.unwrap()
|
||||
.contains("\"custom\""));
|
||||
fs::write(&fixture.rollouts[1], &external).unwrap();
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.expect_err("ordinary provider change after writes must fail sync");
|
||||
assert!(error.to_string().contains("会话文件已发生变化"), "{error}");
|
||||
fixture.assert_databases_unchanged();
|
||||
assert_eq!(
|
||||
fs::read(&fixture.rollouts[0]).unwrap(),
|
||||
fixture.originals[0]
|
||||
);
|
||||
assert_eq!(fs::read(&fixture.rollouts[1]).unwrap(), external);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rollout_snapshot_is_rechecked_before_each_database_commit() {
|
||||
let fixture = RolloutFailureFixture::new("bounded-between-commits");
|
||||
let mut first_committed = false;
|
||||
let error = fixture
|
||||
.sync_with_hook(|point| {
|
||||
if point == MutationPoint::AfterSqliteCommit(0) {
|
||||
first_committed = true;
|
||||
assert!(
|
||||
thread_provider(&fixture.database, fixture.ids[0]) == "custom"
|
||||
|| fixture.catalog_provider(fixture.ids[0]) == "custom"
|
||||
);
|
||||
fs::write(&fixture.rollouts[1], &fixture.originals[1]).unwrap();
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.expect_err("new rollout data before the second commit must abort and restore the first");
|
||||
assert!(first_committed);
|
||||
assert!(error.to_string().contains("会话文件已发生变化"), "{error}");
|
||||
fixture.assert_databases_unchanged();
|
||||
for index in 0..2 {
|
||||
assert_eq!(
|
||||
fs::read(&fixture.rollouts[index]).unwrap(),
|
||||
fixture.originals[index]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rollout_growth_after_scan_is_not_overwritten_or_reported_as_success() {
|
||||
let fixture = RolloutFailureFixture::new("bounded-growth-before-mutation");
|
||||
let enlarged_len = LARGE_ROLLOUT_TEST_BYTES;
|
||||
let error = fixture
|
||||
.sync_with_hook(|point| {
|
||||
if point == MutationPoint::BeforeRolloutMutation {
|
||||
fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.open(&fixture.rollouts[1])
|
||||
.unwrap()
|
||||
.set_len(enlarged_len)
|
||||
.unwrap();
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.expect_err("concurrent growth must invalidate the verified snapshot");
|
||||
assert!(error.to_string().contains("会话文件已发生变化"), "{error}");
|
||||
fixture.assert_databases_unchanged();
|
||||
assert_eq!(
|
||||
fs::read(&fixture.rollouts[0]).unwrap(),
|
||||
fixture.originals[0]
|
||||
);
|
||||
assert_eq!(
|
||||
fs::metadata(&fixture.rollouts[1]).unwrap().len(),
|
||||
enlarged_len
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rollout_growth_after_file_writes_preserves_external_data_and_rolls_back_other_files() {
|
||||
let fixture = RolloutFailureFixture::new("bounded-growth-after-mutation");
|
||||
let marker = b"keep-external-growth";
|
||||
let marker_offset = LARGE_ROLLOUT_TEST_BYTES;
|
||||
let enlarged_len = marker_offset + marker.len() as u64;
|
||||
let error = fixture
|
||||
.sync_with_hook(|point| {
|
||||
if point == MutationPoint::AfterRolloutMutation {
|
||||
let mut external = fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.open(&fixture.rollouts[1])
|
||||
.unwrap();
|
||||
external.set_len(enlarged_len).unwrap();
|
||||
external.seek(SeekFrom::Start(marker_offset)).unwrap();
|
||||
external.write_all(marker).unwrap();
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.expect_err("growth after writes must prevent all database commits");
|
||||
assert!(error.to_string().contains("会话文件已发生变化"), "{error}");
|
||||
fixture.assert_databases_unchanged();
|
||||
assert_eq!(
|
||||
fs::read(&fixture.rollouts[0]).unwrap(),
|
||||
fixture.originals[0]
|
||||
);
|
||||
assert_eq!(
|
||||
fs::metadata(&fixture.rollouts[1]).unwrap().len(),
|
||||
enlarged_len
|
||||
);
|
||||
let mut preserved = fs::File::open(&fixture.rollouts[1]).unwrap();
|
||||
preserved.seek(SeekFrom::Start(marker_offset)).unwrap();
|
||||
let mut restored_marker = vec![0; marker.len()];
|
||||
preserved.read_exact(&mut restored_marker).unwrap();
|
||||
assert_eq!(restored_marker, marker);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rollout_read_failure_after_writes_restores_other_files_and_preserves_external_content() {
|
||||
let fixture = RolloutFailureFixture::new("bounded-read-failure-after-writes");
|
||||
let error = fixture
|
||||
.sync_with_hook(|point| {
|
||||
if point == MutationPoint::AfterRolloutMutation {
|
||||
fs::remove_file(&fixture.rollouts[1]).unwrap();
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.expect_err("full snapshot read failure after writes must abort the sync");
|
||||
assert!(error.to_string().contains(fixture.ids[1]), "{error}");
|
||||
fixture.assert_databases_unchanged();
|
||||
assert_eq!(
|
||||
fs::read(&fixture.rollouts[0]).unwrap(),
|
||||
fixture.originals[0]
|
||||
);
|
||||
assert!(
|
||||
!fixture.rollouts[1].exists(),
|
||||
"external deletion must be preserved"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unchanged_candidate_without_verified_hash_is_rejected_before_mutation() {
|
||||
let fixture = RolloutFailureFixture::new("bounded-unverified-candidate");
|
||||
let mut rollouts = fixture.scan();
|
||||
rollouts.changes.clear();
|
||||
rollouts.verified_rollout_hashes.clear();
|
||||
let mut pending =
|
||||
prepare_sqlite_updates(&[fixture.database.clone(), fixture.catalog.clone()]).unwrap();
|
||||
let mut journal = MutationJournal::default();
|
||||
let mut hook_called = false;
|
||||
let error = execute_provider_sync_mutation(
|
||||
&rollouts,
|
||||
&mut pending,
|
||||
"custom",
|
||||
&HashMap::new(),
|
||||
&fixture.ids.map(str::to_string).into_iter().collect(),
|
||||
&mut journal,
|
||||
&mut |_| {
|
||||
hook_called = true;
|
||||
Ok(())
|
||||
},
|
||||
)
|
||||
.err()
|
||||
.expect("unverified candidate must not take a fresh mutable file as its baseline");
|
||||
assert!(
|
||||
error.to_string().contains("缺少会话文件验证快照"),
|
||||
"{error}"
|
||||
);
|
||||
assert!(!hook_called);
|
||||
fixture.assert_databases_unchanged();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unchanged_candidates_normally_repair_databases_without_rewriting_rollouts() {
|
||||
let mut fixture = RolloutFailureFixture::new("bounded-matched-normal-repair");
|
||||
fixture.set_rollouts_to_target_provider();
|
||||
let result = fixture
|
||||
.sync_with_hook(|_| Ok(()))
|
||||
.expect("matched verified logs permit database repair");
|
||||
assert_eq!(result.updated_rollouts, 0);
|
||||
assert!(result.updated_threads > 0);
|
||||
for index in 0..2 {
|
||||
assert_eq!(
|
||||
thread_provider(&fixture.database, fixture.ids[index]),
|
||||
"custom"
|
||||
);
|
||||
assert_eq!(fixture.catalog_provider(fixture.ids[index]), "custom");
|
||||
assert_eq!(
|
||||
fs::read(&fixture.rollouts[index]).unwrap(),
|
||||
fixture.originals[index]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_unchanged_candidate_repairs_databases_without_rewriting_the_file() {
|
||||
let mut fixture = RolloutFailureFixture::new("streamed-large-matched-repair");
|
||||
fixture.set_rollouts_to_target_provider();
|
||||
let event = b"{\"type\":\"event_msg\",\"payload\":{\"type\":\"user_message\",\"message\":\"unchanged large history\"}}\n";
|
||||
let chunk = event.repeat(512);
|
||||
let mut file = fs::OpenOptions::new()
|
||||
.append(true)
|
||||
.open(&fixture.rollouts[1])
|
||||
.unwrap();
|
||||
let mut original_len = file.metadata().unwrap().len();
|
||||
while original_len <= LARGE_ROLLOUT_TEST_BYTES {
|
||||
file.write_all(&chunk).unwrap();
|
||||
original_len += chunk.len() as u64;
|
||||
}
|
||||
file.sync_all().unwrap();
|
||||
drop(file);
|
||||
let original_hash = hash_rollout_file(&fixture.rollouts[1]).unwrap();
|
||||
|
||||
let result = fixture
|
||||
.sync_with_hook(|_| Ok(()))
|
||||
.expect("large matched files permit database repair");
|
||||
assert_eq!(result.updated_rollouts, 0);
|
||||
assert!(result.updated_threads > 0);
|
||||
for id in fixture.ids {
|
||||
assert_eq!(thread_provider(&fixture.database, id), "custom");
|
||||
assert_eq!(fixture.catalog_provider(id), "custom");
|
||||
}
|
||||
assert_eq!(
|
||||
fs::metadata(&fixture.rollouts[1]).unwrap().len(),
|
||||
original_len
|
||||
);
|
||||
assert_eq!(
|
||||
hash_rollout_file(&fixture.rollouts[1]).unwrap(),
|
||||
original_hash
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unchanged_candidate_provider_changes_before_or_after_mutation_block_database_repair() {
|
||||
for stage in [
|
||||
MutationPoint::BeforeRolloutMutation,
|
||||
MutationPoint::AfterRolloutMutation,
|
||||
] {
|
||||
let mut fixture = RolloutFailureFixture::new("bounded-matched-provider-race");
|
||||
fixture.set_rollouts_to_target_provider();
|
||||
let external = String::from_utf8(fixture.originals[1].clone())
|
||||
.unwrap()
|
||||
.replace("\"custom\"", "\"openai\"")
|
||||
.into_bytes();
|
||||
let error = fixture
|
||||
.sync_with_hook(|point| {
|
||||
if point == stage {
|
||||
fs::write(&fixture.rollouts[1], &external).unwrap();
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.expect_err("changed already-matched candidate must not permit database repair");
|
||||
assert!(error.to_string().contains("会话文件已发生变化"), "{error}");
|
||||
fixture.assert_databases_unchanged();
|
||||
assert_eq!(
|
||||
fs::read(&fixture.rollouts[0]).unwrap(),
|
||||
fixture.originals[0]
|
||||
);
|
||||
assert_eq!(fs::read(&fixture.rollouts[1]).unwrap(), external);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unchanged_candidate_growth_before_or_after_mutation_blocks_database_repair() {
|
||||
for stage in [
|
||||
MutationPoint::BeforeRolloutMutation,
|
||||
MutationPoint::AfterRolloutMutation,
|
||||
] {
|
||||
let mut fixture = RolloutFailureFixture::new("bounded-matched-growth-race");
|
||||
fixture.set_rollouts_to_target_provider();
|
||||
let enlarged_len = LARGE_ROLLOUT_TEST_BYTES;
|
||||
let error = fixture
|
||||
.sync_with_hook(|point| {
|
||||
if point == stage {
|
||||
fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.open(&fixture.rollouts[1])
|
||||
.unwrap()
|
||||
.set_len(enlarged_len)
|
||||
.unwrap();
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.expect_err("changed already-matched candidate must prevent database repair");
|
||||
assert!(error.to_string().contains("会话文件已发生变化"), "{error}");
|
||||
fixture.assert_databases_unchanged();
|
||||
assert_eq!(
|
||||
fs::read(&fixture.rollouts[0]).unwrap(),
|
||||
fixture.originals[0]
|
||||
);
|
||||
assert_eq!(
|
||||
fs::metadata(&fixture.rollouts[1]).unwrap().len(),
|
||||
enlarged_len
|
||||
);
|
||||
let mut external = fs::File::open(&fixture.rollouts[1]).unwrap();
|
||||
let mut prefix = vec![0; fixture.originals[1].len()];
|
||||
external.read_exact(&mut prefix).unwrap();
|
||||
assert_eq!(prefix, fixture.originals[1]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unchanged_candidate_change_after_final_commit_rolls_back_databases_and_preserves_external_log() {
|
||||
let mut fixture = RolloutFailureFixture::new("bounded-matched-final-commit-race");
|
||||
fixture.set_rollouts_to_target_provider();
|
||||
let external = String::from_utf8(fixture.originals[1].clone())
|
||||
.unwrap()
|
||||
.replace("\"custom\"", "\"openai\"")
|
||||
.into_bytes();
|
||||
let mut last_commit_observed = false;
|
||||
let error = fixture
|
||||
.sync_with_hook(|point| {
|
||||
if point == MutationPoint::AfterSqliteCommit(1) {
|
||||
last_commit_observed = true;
|
||||
assert_eq!(thread_provider(&fixture.database, fixture.ids[0]), "custom");
|
||||
assert_eq!(fixture.catalog_provider(fixture.ids[0]), "custom");
|
||||
fs::write(&fixture.rollouts[1], &external).unwrap();
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.expect_err("the final commit hook must not bypass the complete snapshot validation");
|
||||
assert!(last_commit_observed);
|
||||
assert!(error.to_string().contains("会话文件已发生变化"), "{error}");
|
||||
fixture.assert_databases_unchanged();
|
||||
assert_eq!(
|
||||
fs::read(&fixture.rollouts[0]).unwrap(),
|
||||
fixture.originals[0]
|
||||
);
|
||||
assert_eq!(fs::read(&fixture.rollouts[1]).unwrap(), external);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sqlite_update_failure_rolls_back_every_open_database_and_jsonl() {
|
||||
let codex_dir = temp_dir("multi-sqlite-update-failure");
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
use serde::Serialize;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::SystemTime;
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
@@ -23,6 +25,10 @@ pub(crate) struct SessionPreview {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct SessionSyncStatus {
|
||||
pub(crate) codex_dir: String,
|
||||
#[serde(default)]
|
||||
pub(crate) directory_identities: HashMap<String, String>,
|
||||
#[serde(default)]
|
||||
pub(crate) pin_scope_key: Option<String>,
|
||||
pub(crate) target_provider: String,
|
||||
pub(crate) rollout_files: usize,
|
||||
pub(crate) session_meta_count: usize,
|
||||
@@ -60,6 +66,9 @@ pub(crate) struct RolloutScan {
|
||||
pub(crate) mismatched_session_meta: usize,
|
||||
pub(crate) changes: Vec<SessionFileChange>,
|
||||
pub(crate) provider_candidate_paths: HashSet<PathBuf>,
|
||||
/// SHA-256 of every completely validated candidate's original JSONL. Keep
|
||||
/// matched rollouts covered without retaining another copy of their text.
|
||||
pub(crate) verified_rollout_hashes: HashMap<PathBuf, [u8; 32]>,
|
||||
pub(crate) cwd_by_thread_id: HashMap<String, String>,
|
||||
pub(crate) thread_ids: HashSet<String>,
|
||||
/// Non-user threads identified from their own rollout metadata. Retained
|
||||
@@ -68,6 +77,9 @@ pub(crate) struct RolloutScan {
|
||||
pub(crate) mismatched_thread_ids: HashSet<String>,
|
||||
pub(crate) warnings: Vec<String>,
|
||||
pub(crate) scan_failures: Vec<String>,
|
||||
/// Incomplete user-rollout scans that must block Provider/index mutations,
|
||||
/// including unindexed files that would otherwise become only warnings.
|
||||
pub(crate) blocked_failures: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -76,6 +88,24 @@ pub(crate) struct SessionFileChange {
|
||||
pub(crate) original_text: String,
|
||||
pub(crate) next_text: String,
|
||||
pub(crate) original_mtime: Option<SystemTime>,
|
||||
// Production snapshots live on disk; inline text is retained for small fixtures.
|
||||
pub(super) streamed: Option<Arc<super::rollout_stream::StreamedSnapshot>>,
|
||||
}
|
||||
|
||||
impl SessionFileChange {
|
||||
pub(super) fn original_hash(&self) -> [u8; 32] {
|
||||
self.streamed.as_ref().map_or_else(
|
||||
|| Sha256::digest(self.original_text.as_bytes()).into(),
|
||||
|snapshot| snapshot.original_hash,
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn next_hash(&self) -> [u8; 32] {
|
||||
self.streamed.as_ref().map_or_else(
|
||||
|| Sha256::digest(self.next_text.as_bytes()).into(),
|
||||
|snapshot| snapshot.next_hash,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"testOnly": true,
|
||||
"fixturePurpose": "Synthetic fixture for cfg(test) Tauri SDK download and Minisign verification. The 256-byte PE header contains no executable code, sections or entry point. Never install or run it. This public key must never replace the production updater public key. Its private key was generated only in memory and was not saved.",
|
||||
"expectedVersion": "0.3.24",
|
||||
"publicKeyBase64": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDMxOUI5MzI2MzA2QkQ5NUMKUldSYzJXc3dKcE9iTWZrYjhWL1VCZXZ0TWFBNE9IWE9zTENncU5LSFFKaW9wblF4c3VtQXVSSVMK",
|
||||
"signatureBase64": "dW50cnVzdGVkIGNvbW1lbnQ6IHN5bnRoZXRpYyB0ZXN0IHNpZ25hdHVyZTsgbmV2ZXIgdXNlIGZvciBwcm9kdWN0aW9uIHVwZGF0ZXMKUlVSYzJXc3dKcE9iTWRZZ0xROVZ0T3c1SXVuWXYvU3FUbkRrNGowMjNId2FhcnhTeFpIa25DUm80bGdINzd4UEYvcE1mRWxKUHJZeVczQzBiNHlwWjJYZ3Mxcm0yNVJaYmdBPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkxNTA0MDAwCWZpbGU6b25saW5lLXVwZGF0ZS1maXh0dXJlLmV4ZQoxYWxWSVlaWHdYcHlib01YcjdRS1V3RlR4d3FvVFhqMERJWlBGVGR1Z1hyYnZKTFByR1RwaFJjTnRWRGM4d2tLUEsxV01Lcmk5dy9sSzMyVEg0dWRBZz09Cg==",
|
||||
"payloadBase64": "TVoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAFBFAABkhgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQ29kZXgtWCBzeW50aGV0aWMgdXBkYXRlciBmaXh0dXJlOiBubyBzZWN0aW9ucywgbm8gZW50cnkgcG9pbnQsIG5vIGV4ZWN1dGFibGUgY29kZS4gTmV2ZXIgaW5zdGFsbC4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==",
|
||||
"sha256": "7764dacacade2426d04ec977eb28b25ed31f8e272c096c1a9d1e9873d0e49be4"
|
||||
}
|
||||
@@ -134,6 +134,7 @@ fn provider_test_connection() -> Connection {
|
||||
wire_api TEXT NOT NULL DEFAULT 'responses',
|
||||
requires_openai_auth INTEGER NOT NULL DEFAULT 1,
|
||||
model_mappings_json TEXT NOT NULL DEFAULT '[]',
|
||||
upstream_api TEXT,
|
||||
source TEXT NOT NULL DEFAULT 'manual',
|
||||
source_id TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
@@ -160,6 +161,7 @@ fn provider_fixture(
|
||||
api_key: api_key.map(ToString::to_string),
|
||||
toml_config: toml_config.map(ToString::to_string),
|
||||
wire_api: "responses".to_string(),
|
||||
upstream_api: None,
|
||||
requires_openai_auth: true,
|
||||
model_mappings: Vec::new(),
|
||||
}
|
||||
@@ -551,6 +553,7 @@ fn ccswitch_row_reader_supports_legacy_schema_without_category() {
|
||||
name: "OpenAI Official".to_string(),
|
||||
settings_config: "{}".to_string(),
|
||||
category: None,
|
||||
meta: None,
|
||||
};
|
||||
assert!(is_official_ccswitch_row(&official));
|
||||
}
|
||||
@@ -961,6 +964,7 @@ wire_api = "responses"
|
||||
api_key: Some("sk-same".to_string()),
|
||||
toml_config: Some(toml.to_string()),
|
||||
wire_api: "responses".to_string(),
|
||||
upstream_api: None,
|
||||
requires_openai_auth: true,
|
||||
model_mappings: Vec::new(),
|
||||
};
|
||||
@@ -1809,6 +1813,7 @@ enabled = true
|
||||
api_key: Some("sk-provider-a".to_string()),
|
||||
toml_config: Some(provider_a_config.to_string()),
|
||||
wire_api: "responses".to_string(),
|
||||
upstream_api: None,
|
||||
requires_openai_auth: true,
|
||||
model_mappings: Vec::new(),
|
||||
},
|
||||
@@ -1820,6 +1825,7 @@ enabled = true
|
||||
api_key: Some("sk-provider-b".to_string()),
|
||||
toml_config: Some(provider_b_config.to_string()),
|
||||
wire_api: "responses".to_string(),
|
||||
upstream_api: None,
|
||||
requires_openai_auth: true,
|
||||
model_mappings: Vec::new(),
|
||||
},
|
||||
@@ -2730,6 +2736,7 @@ requires_openai_auth = true
|
||||
api_key: None,
|
||||
toml_config: Some(provider_config.to_string()),
|
||||
wire_api: "responses".to_string(),
|
||||
upstream_api: None,
|
||||
requires_openai_auth: true,
|
||||
model_mappings: Vec::new(),
|
||||
})
|
||||
@@ -3198,6 +3205,7 @@ requires_openai_auth = true
|
||||
api_key: Some("sk-duplicate-current".to_string()),
|
||||
toml_config: Some(custom_config.trim_end().to_string()),
|
||||
wire_api: "responses".to_string(),
|
||||
upstream_api: None,
|
||||
requires_openai_auth: true,
|
||||
model_mappings: Vec::new(),
|
||||
};
|
||||
@@ -3656,8 +3664,11 @@ experimental_bearer_token = "sk-from-config"
|
||||
name: "Proxy".to_string(),
|
||||
settings_config,
|
||||
category: None,
|
||||
meta: None,
|
||||
};
|
||||
let provider = build_ccswitch_codex_provider(&row, &HashMap::new()).expect("provider");
|
||||
let provider = build_ccswitch_codex_provider(&row, &HashMap::new())
|
||||
.expect("valid provider")
|
||||
.expect("provider");
|
||||
assert_eq!(provider.id, "openai-custom");
|
||||
assert_eq!(provider.api_key.as_deref(), Some("sk-from-config"));
|
||||
assert_eq!(provider.base_url, "https://proxy.example.com/v1");
|
||||
@@ -3682,6 +3693,7 @@ requires_openai_auth = true
|
||||
})
|
||||
.to_string(),
|
||||
category: None,
|
||||
meta: None,
|
||||
};
|
||||
let magic_row = CcSwitchCodexRow {
|
||||
id: "magicai-1782956845071".to_string(),
|
||||
@@ -3706,6 +3718,7 @@ requires_openai_auth = true
|
||||
})
|
||||
.to_string(),
|
||||
category: None,
|
||||
meta: None,
|
||||
};
|
||||
|
||||
let mut sections = HashMap::new();
|
||||
@@ -3718,8 +3731,12 @@ requires_openai_auth = true
|
||||
}
|
||||
}
|
||||
|
||||
let sky = build_ccswitch_codex_provider(&sky_row, §ions).expect("sky");
|
||||
let magic = build_ccswitch_codex_provider(&magic_row, §ions).expect("magic");
|
||||
let sky = build_ccswitch_codex_provider(&sky_row, §ions)
|
||||
.expect("valid sky provider")
|
||||
.expect("sky");
|
||||
let magic = build_ccswitch_codex_provider(&magic_row, §ions)
|
||||
.expect("valid magic provider")
|
||||
.expect("magic");
|
||||
|
||||
assert_eq!(sky.provider_name, "Sky2api");
|
||||
assert_eq!(sky.base_url, "https://ikuncode.site/v1");
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
//! Windows staging/launching is deliberately separate from MSI service work.
|
||||
//! Only bytes already verified by tauri-plugin-updater reach this module.
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::{self, Write};
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub(super) struct StagedInstaller {
|
||||
dir: tempfile::TempDir,
|
||||
executable: PathBuf,
|
||||
}
|
||||
|
||||
fn is_windows_executable(bytes: &[u8]) -> bool {
|
||||
if bytes.len() < 64 || bytes.get(..2) != Some(b"MZ") {
|
||||
return false;
|
||||
}
|
||||
let offset = u32::from_le_bytes(bytes[60..64].try_into().unwrap()) as usize;
|
||||
offset >= 64
|
||||
&& offset
|
||||
.checked_add(4)
|
||||
.is_some_and(|end| bytes.get(offset..end) == Some(b"PE\0\0"))
|
||||
}
|
||||
|
||||
fn installer_arguments(pid: u32) -> [String; 4] {
|
||||
[
|
||||
"/P".into(),
|
||||
"/R".into(),
|
||||
"/UPDATE".into(),
|
||||
format!("/CODEXXPID={pid}"),
|
||||
]
|
||||
}
|
||||
|
||||
impl StagedInstaller {
|
||||
pub(super) fn create(verified_bytes: &[u8]) -> io::Result<Self> {
|
||||
if !is_windows_executable(verified_bytes) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"expected a verified Windows EXE installer",
|
||||
));
|
||||
}
|
||||
let dir = tempfile::Builder::new()
|
||||
.prefix("Codex-X-update-")
|
||||
.tempdir()?;
|
||||
let executable = dir.path().join("Codex-X-setup.exe");
|
||||
let mut file = OpenOptions::new()
|
||||
.create_new(true)
|
||||
.write(true)
|
||||
.open(&executable)?;
|
||||
file.write_all(verified_bytes)?;
|
||||
file.sync_all()?;
|
||||
drop(file);
|
||||
Ok(Self { dir, executable })
|
||||
}
|
||||
|
||||
pub(super) fn launch(self, parent_pid: u32) -> io::Result<()> {
|
||||
if parent_pid == 0 {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"invalid parent PID",
|
||||
));
|
||||
}
|
||||
// No shell or interpolated command line: Unicode/space-containing user
|
||||
// paths are passed through Rust's native Windows argument quoting.
|
||||
let child = std::process::Command::new(&self.executable)
|
||||
.args(installer_arguments(parent_pid))
|
||||
.current_dir(self.dir.path())
|
||||
.spawn()?;
|
||||
// It owns its visible progress/errors from here, and waits for parent_pid
|
||||
// to exit before migrating or copying files. Never kill system installers.
|
||||
drop(child);
|
||||
let _ = self.dir.keep();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn staging_rejects_msi_html_truncated_and_invalid_pe_payloads() {
|
||||
for bytes in [
|
||||
b"\xd0\xcf\x11\xe0".as_slice(),
|
||||
b"<html>login</html>",
|
||||
b"MZ",
|
||||
&[0; 128],
|
||||
] {
|
||||
assert!(StagedInstaller::create(bytes).is_err());
|
||||
}
|
||||
let mut bytes = vec![0; 128];
|
||||
bytes[..2].copy_from_slice(b"MZ");
|
||||
bytes[60..64].copy_from_slice(&u32::MAX.to_le_bytes());
|
||||
assert!(StagedInstaller::create(&bytes).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installer_staging_is_unique_and_cancel_cleans_only_its_directory() {
|
||||
let mut bytes = vec![0; 128];
|
||||
bytes[..2].copy_from_slice(b"MZ");
|
||||
bytes[60..64].copy_from_slice(&64u32.to_le_bytes());
|
||||
bytes[64..68].copy_from_slice(b"PE\0\0");
|
||||
let a = StagedInstaller::create(&bytes).unwrap();
|
||||
let b = StagedInstaller::create(&bytes).unwrap();
|
||||
assert_ne!(a.dir.path(), b.dir.path());
|
||||
assert_eq!(std::fs::read(&a.executable).unwrap(), bytes);
|
||||
let path = a.dir.path().to_owned();
|
||||
drop(a);
|
||||
assert!(!path.exists());
|
||||
assert!(b.executable.is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launcher_arguments_do_not_forward_user_cli_arguments_or_installer_paths() {
|
||||
assert_eq!(
|
||||
installer_arguments(123),
|
||||
["/P", "/R", "/UPDATE", "/CODEXXPID=123"]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "Codex-X",
|
||||
"version": "0.3.19",
|
||||
"version": "0.3.27",
|
||||
"identifier": "com.yynxxxxx.codexx",
|
||||
"build": {
|
||||
"frontendDist": "../dist",
|
||||
@@ -45,7 +45,18 @@
|
||||
"icons/icon.icns",
|
||||
"icons/icon.ico"
|
||||
],
|
||||
"targets": "all"
|
||||
"targets": "all",
|
||||
"windows": {
|
||||
"nsis": {
|
||||
"installMode": "currentUser",
|
||||
"template": "nsis/installer.nsi",
|
||||
"languages": [
|
||||
"SimpChinese",
|
||||
"English"
|
||||
],
|
||||
"displayLanguageSelector": false
|
||||
}
|
||||
}
|
||||
},
|
||||
"plugins": {
|
||||
"updater": {
|
||||
|
||||
+28
-260
@@ -1,270 +1,38 @@
|
||||
import { useSyncExternalStore } from "react";
|
||||
import {
|
||||
check as checkForTauriUpdate,
|
||||
type CheckOptions,
|
||||
type DownloadEvent,
|
||||
type DownloadOptions,
|
||||
type Update,
|
||||
} from "@tauri-apps/plugin-updater";
|
||||
import { Channel, invoke } from "@tauri-apps/api/core";
|
||||
import { Update } from "@tauri-apps/plugin-updater";
|
||||
import { relaunch } from "@tauri-apps/plugin-process";
|
||||
import { AppUpdaterController, type AppUpdateEvent } from "./appUpdaterController";
|
||||
|
||||
export type AppUpdaterPhase =
|
||||
| "idle"
|
||||
| "checking"
|
||||
| "available"
|
||||
| "downloading"
|
||||
| "installing"
|
||||
| "ready"
|
||||
| "error";
|
||||
export { INITIAL_APP_UPDATER_STATE, isAppUpdateBusy } from "./appUpdaterController";
|
||||
export type { AppUpdaterPhase, AppUpdaterState, AppUpdaterFailure, AppUpdaterCheckResult, AppUpdaterCheckOptions } from "./appUpdaterController";
|
||||
|
||||
export type AppUpdaterFailure = "check" | "download" | "install" | "restart" | null;
|
||||
|
||||
export type AppUpdaterState = Readonly<{
|
||||
phase: AppUpdaterPhase;
|
||||
currentVersion: string | null;
|
||||
latestVersion: string | null;
|
||||
notes: string | null;
|
||||
publishedAt: string | null;
|
||||
downloadedBytes: number;
|
||||
totalBytes: number | null;
|
||||
failure: AppUpdaterFailure;
|
||||
}>;
|
||||
|
||||
export type AppUpdaterCheckResult = "available" | "up-to-date" | "error";
|
||||
|
||||
export type AppUpdaterCheckOptions = CheckOptions & {
|
||||
force?: boolean;
|
||||
};
|
||||
|
||||
export const INITIAL_APP_UPDATER_STATE: AppUpdaterState = {
|
||||
phase: "idle",
|
||||
currentVersion: null,
|
||||
latestVersion: null,
|
||||
notes: null,
|
||||
publishedAt: null,
|
||||
downloadedBytes: 0,
|
||||
totalBytes: null,
|
||||
failure: null,
|
||||
};
|
||||
|
||||
type Listener = () => void;
|
||||
type RetryAction = "check" | "update" | "restart";
|
||||
|
||||
function normalizeByteCount(value: number | undefined): number | null {
|
||||
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : null;
|
||||
}
|
||||
|
||||
class AppUpdaterController {
|
||||
private state: AppUpdaterState = INITIAL_APP_UPDATER_STATE;
|
||||
private readonly listeners = new Set<Listener>();
|
||||
private update: Update | null = null;
|
||||
private checkPromise: Promise<AppUpdaterCheckResult> | null = null;
|
||||
private updatePromise: Promise<AppUpdaterPhase> | null = null;
|
||||
private restartPromise: Promise<AppUpdaterPhase> | null = null;
|
||||
private retryAction: RetryAction = "check";
|
||||
|
||||
readonly getSnapshot = (): AppUpdaterState => this.state;
|
||||
|
||||
readonly subscribe = (listener: Listener): (() => void) => {
|
||||
this.listeners.add(listener);
|
||||
return () => {
|
||||
this.listeners.delete(listener);
|
||||
};
|
||||
};
|
||||
|
||||
readonly check = (options: AppUpdaterCheckOptions = {}): Promise<AppUpdaterCheckResult> => {
|
||||
if (this.checkPromise) return this.checkPromise;
|
||||
|
||||
if (this.isUpdateBusy()) {
|
||||
return Promise.resolve(this.update ? "available" : "error");
|
||||
}
|
||||
|
||||
if (this.update && !options.force) return Promise.resolve("available");
|
||||
|
||||
const { force: _force, ...pluginOptions } = options;
|
||||
this.checkPromise = this.performCheck(pluginOptions).finally(() => {
|
||||
this.checkPromise = null;
|
||||
export const appUpdater = new AppUpdaterController({
|
||||
check: async (options) => {
|
||||
const metadata = await invoke<ConstructorParameters<typeof Update>[0] | null>("check_online_app_update", {
|
||||
timeout: options.timeout,
|
||||
headers: options.headers ? Array.from(new Headers(options.headers).entries()) : undefined,
|
||||
proxy: options.proxy,
|
||||
target: options.target,
|
||||
allowDowngrades: options.allowDowngrades,
|
||||
});
|
||||
return this.checkPromise;
|
||||
};
|
||||
|
||||
readonly downloadAndInstall = (options?: DownloadOptions): Promise<AppUpdaterPhase> => {
|
||||
if (this.updatePromise) return this.updatePromise;
|
||||
if (this.state.phase === "ready") return Promise.resolve("ready");
|
||||
|
||||
if (!this.update) {
|
||||
this.retryAction = "check";
|
||||
this.setState({ phase: "error", failure: "check" });
|
||||
return Promise.resolve("error");
|
||||
}
|
||||
|
||||
this.updatePromise = this.performDownloadAndInstall(this.update, options).finally(() => {
|
||||
this.updatePromise = null;
|
||||
return metadata ? new Update(metadata) : null;
|
||||
},
|
||||
install: async (update, onEvent, options) => {
|
||||
const channel = new Channel<AppUpdateEvent>(onEvent);
|
||||
return invoke<{ restartRequired: boolean }>("install_app_update", {
|
||||
updateRid: update.rid,
|
||||
onEvent: channel,
|
||||
timeout: options?.timeout,
|
||||
headers: options?.headers ? Array.from(new Headers(options.headers).entries()) : undefined,
|
||||
});
|
||||
return this.updatePromise;
|
||||
};
|
||||
|
||||
readonly retry = (): Promise<AppUpdaterCheckResult | AppUpdaterPhase> => {
|
||||
if (this.retryAction === "restart") return this.restart();
|
||||
if (this.retryAction === "update" && this.update) return this.downloadAndInstall();
|
||||
return this.check({ force: true });
|
||||
};
|
||||
|
||||
readonly restart = (): Promise<AppUpdaterPhase> => {
|
||||
if (this.restartPromise) return this.restartPromise;
|
||||
if (this.state.phase !== "ready" && this.state.failure !== "restart") {
|
||||
return Promise.resolve(this.state.phase);
|
||||
}
|
||||
|
||||
this.restartPromise = this.performRestart().finally(() => {
|
||||
this.restartPromise = null;
|
||||
});
|
||||
return this.restartPromise;
|
||||
};
|
||||
|
||||
private isUpdateBusy(): boolean {
|
||||
return this.state.phase === "downloading" || this.state.phase === "installing";
|
||||
}
|
||||
|
||||
private async performCheck(options: CheckOptions): Promise<AppUpdaterCheckResult> {
|
||||
this.retryAction = "check";
|
||||
this.setState({
|
||||
phase: "checking",
|
||||
downloadedBytes: 0,
|
||||
totalBytes: null,
|
||||
failure: null,
|
||||
});
|
||||
|
||||
try {
|
||||
const nextUpdate = await checkForTauriUpdate(options);
|
||||
if (!nextUpdate) {
|
||||
await this.replaceUpdate(null);
|
||||
this.setState({
|
||||
phase: "idle",
|
||||
latestVersion: null,
|
||||
notes: null,
|
||||
publishedAt: null,
|
||||
failure: null,
|
||||
});
|
||||
return "up-to-date";
|
||||
}
|
||||
|
||||
await this.replaceUpdate(nextUpdate);
|
||||
this.retryAction = "update";
|
||||
this.setState({
|
||||
phase: "available",
|
||||
currentVersion: nextUpdate.currentVersion,
|
||||
latestVersion: nextUpdate.version,
|
||||
notes: nextUpdate.body?.trim() || null,
|
||||
publishedAt: nextUpdate.date || null,
|
||||
downloadedBytes: 0,
|
||||
totalBytes: null,
|
||||
failure: null,
|
||||
});
|
||||
return "available";
|
||||
} catch {
|
||||
await this.replaceUpdate(null);
|
||||
this.setState({ phase: "error", failure: "check" });
|
||||
return "error";
|
||||
}
|
||||
}
|
||||
|
||||
private async performDownloadAndInstall(update: Update, options?: DownloadOptions): Promise<AppUpdaterPhase> {
|
||||
this.retryAction = "update";
|
||||
let downloadFinished = false;
|
||||
this.setState({
|
||||
phase: "downloading",
|
||||
downloadedBytes: 0,
|
||||
totalBytes: null,
|
||||
failure: null,
|
||||
});
|
||||
|
||||
try {
|
||||
await update.downloadAndInstall((event) => {
|
||||
if (event.event === "Finished") downloadFinished = true;
|
||||
this.handleDownloadEvent(event);
|
||||
}, options);
|
||||
this.setState({
|
||||
phase: "ready",
|
||||
downloadedBytes: this.state.totalBytes ?? this.state.downloadedBytes,
|
||||
failure: null,
|
||||
});
|
||||
return "ready";
|
||||
} catch {
|
||||
const failedDuringInstall = downloadFinished || this.state.phase === "installing";
|
||||
this.setState({
|
||||
phase: "error",
|
||||
failure: failedDuringInstall ? "install" : "download",
|
||||
});
|
||||
return "error";
|
||||
}
|
||||
}
|
||||
|
||||
private handleDownloadEvent(event: DownloadEvent): void {
|
||||
if (event.event === "Started") {
|
||||
this.setState({
|
||||
phase: "downloading",
|
||||
downloadedBytes: 0,
|
||||
totalBytes: normalizeByteCount(event.data.contentLength),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.event === "Progress") {
|
||||
const nextBytes = this.state.downloadedBytes + Math.max(0, event.data.chunkLength);
|
||||
this.setState({
|
||||
downloadedBytes: this.state.totalBytes === null
|
||||
? nextBytes
|
||||
: Math.min(nextBytes, this.state.totalBytes),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
this.setState({
|
||||
phase: "installing",
|
||||
downloadedBytes: this.state.totalBytes ?? this.state.downloadedBytes,
|
||||
});
|
||||
}
|
||||
|
||||
private async performRestart(): Promise<AppUpdaterPhase> {
|
||||
this.retryAction = "restart";
|
||||
this.setState({ failure: null });
|
||||
try {
|
||||
await relaunch();
|
||||
return "ready";
|
||||
} catch {
|
||||
this.setState({ phase: "error", failure: "restart" });
|
||||
return "error";
|
||||
}
|
||||
}
|
||||
|
||||
private async replaceUpdate(nextUpdate: Update | null): Promise<void> {
|
||||
const previousUpdate = this.update;
|
||||
this.update = nextUpdate;
|
||||
if (!previousUpdate || previousUpdate === nextUpdate) return;
|
||||
|
||||
try {
|
||||
await previousUpdate.close();
|
||||
} catch (error) {
|
||||
console.warn("Unable to release the previous updater resource", error);
|
||||
}
|
||||
}
|
||||
|
||||
private setState(patch: Partial<AppUpdaterState>): void {
|
||||
this.state = { ...this.state, ...patch };
|
||||
this.listeners.forEach((listener) => listener());
|
||||
}
|
||||
}
|
||||
|
||||
export const appUpdater = new AppUpdaterController();
|
||||
},
|
||||
restart: relaunch,
|
||||
setTimer: (callback, delay) => window.setTimeout(callback, delay),
|
||||
clearTimer: (timer) => window.clearTimeout(timer as number),
|
||||
});
|
||||
|
||||
export function useAppUpdater() {
|
||||
const state = useSyncExternalStore(appUpdater.subscribe, appUpdater.getSnapshot, appUpdater.getSnapshot);
|
||||
return {
|
||||
state,
|
||||
check: appUpdater.check,
|
||||
downloadAndInstall: appUpdater.downloadAndInstall,
|
||||
retry: appUpdater.retry,
|
||||
restart: appUpdater.restart,
|
||||
} as const;
|
||||
return { state, check: appUpdater.check, downloadAndInstall: appUpdater.downloadAndInstall, retry: appUpdater.retry, restart: appUpdater.restart } as const;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
import type { CheckOptions, DownloadOptions } from "@tauri-apps/plugin-updater";
|
||||
|
||||
export type AppUpdaterPhase = "idle" | "checking" | "available" | "downloading" | "verifying" | "preparing" | "installing" | "handed-off" | "ready" | "error";
|
||||
export type AppUpdaterCheckFailureKind = "timeout" | "network" | "platform" | "invalid-release" | "public-key" | "unknown";
|
||||
export type AppUpdaterFailure = "check" | "download" | "verify" | "prepare" | "install" | "restart" | null;
|
||||
export type AppUpdaterState = Readonly<{
|
||||
phase: AppUpdaterPhase;
|
||||
currentVersion: string | null;
|
||||
latestVersion: string | null;
|
||||
notes: string | null;
|
||||
publishedAt: string | null;
|
||||
downloadedBytes: number;
|
||||
totalBytes: number | null;
|
||||
failure: AppUpdaterFailure;
|
||||
errorMessage: string | null;
|
||||
checkFailure?: AppUpdaterCheckFailureKind | null;
|
||||
logPath: string | null;
|
||||
takingLonger: boolean;
|
||||
}>;
|
||||
export type AppUpdaterCheckResult = "available" | "up-to-date" | "error";
|
||||
export type AppUpdaterCheckOptions = CheckOptions & { force?: boolean };
|
||||
export type AppUpdateEvent =
|
||||
| { event: "Started"; data: { contentLength?: number } }
|
||||
| { event: "Progress"; data: { chunkLength: number } }
|
||||
| { event: "Verifying" | "Preparing" | "Installing" | "HandedOff" };
|
||||
export type CheckedAppUpdate = {
|
||||
rid: number;
|
||||
currentVersion: string;
|
||||
version: string;
|
||||
body?: string;
|
||||
date?: string;
|
||||
close: () => Promise<void>;
|
||||
};
|
||||
export type AppUpdaterDependencies = {
|
||||
check: (options: CheckOptions) => Promise<CheckedAppUpdate | null>;
|
||||
install: (update: CheckedAppUpdate, onEvent: (event: AppUpdateEvent) => void, options?: DownloadOptions) => Promise<{ restartRequired: boolean }>;
|
||||
restart: () => Promise<void>;
|
||||
setTimer: (callback: () => void, delay: number) => unknown;
|
||||
clearTimer: (timer: unknown) => void;
|
||||
};
|
||||
export const UPDATER_SLOW_NOTICE_MS = 30_000;
|
||||
export const INITIAL_APP_UPDATER_STATE: AppUpdaterState = {
|
||||
phase: "idle", currentVersion: null, latestVersion: null, notes: null, publishedAt: null,
|
||||
downloadedBytes: 0, totalBytes: null, failure: null, errorMessage: null, checkFailure: null, logPath: null, takingLonger: false,
|
||||
};
|
||||
export function isAppUpdateBusy(phase: AppUpdaterPhase): boolean {
|
||||
return ["downloading", "verifying", "preparing", "installing", "handed-off"].includes(phase);
|
||||
}
|
||||
function normalizeByteCount(value: number | undefined): number | null {
|
||||
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : null;
|
||||
}
|
||||
// Plugin errors can contain private endpoints and credentials. Inspect bounded
|
||||
// text only to select one of these fixed explanations; never return that text.
|
||||
export function classifyAppUpdaterCheckError(error: unknown): AppUpdaterCheckFailureKind {
|
||||
let text = "";
|
||||
if (typeof error === "string") text = error;
|
||||
else if (error instanceof Error) text = `${error.name} ${error.message}`;
|
||||
else if (typeof error === "object" && error !== null) {
|
||||
const record = error as Record<string, unknown>;
|
||||
text = ["code", "kind", "type", "name", "message"].map((key) => record[key])
|
||||
.filter((value): value is string => typeof value === "string").join(" ");
|
||||
}
|
||||
text = text.slice(0, 4096).replace(/https?:\/\/[^\s<>"']+/gi, "").toLowerCase();
|
||||
if (/timeout|timed?\s*out|time out|etimedout|deadline exceeded|超时/.test(text)) return "timeout";
|
||||
if (/(?:platform|target)[\s\S]{0,200}(?:not found|missing|unsupported)|unsupported[\s\S]{0,80}(?:architecture|platform|operating system|\bos\b)|unsupportedarch|unsupportedos|targets?notfound|不支持.*(?:平台|系统|架构)/.test(text)) return "platform";
|
||||
if (/release json|(?:invalid|malformed)[^\n]{0,80}(?:release|json|manifest|version)|serialization|semver|invalid updater resource|missing field|expected (?:value|ident)[^\n]{0,80}line|eof while parsing|trailing characters|key must be a string|(?:relative url without a base)|更新信息.*(?:无效|格式)/.test(text)) return "invalid-release";
|
||||
if (/public.?key|pubkey|minisign|signature|invalid base64|base64[^\n]{0,80}(?:invalid|decode)|公钥|签名/.test(text)) return "public-key";
|
||||
if (/network|failed to fetch|error sending request|connection (?:refused|reset|closed)|connect error|dns|tcp|tls|certificate|resolve (?:host|dns)|http (?:error|status)|status code|could not connect|enotfound|econnreset|econnrefused|网络|连接失败/.test(text)) return "network";
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
export function appUpdaterCheckFailureMessage(kind: AppUpdaterCheckFailureKind, lang: "zh" | "en" = "zh"): string {
|
||||
const messages = lang === "zh" ? {
|
||||
timeout: "在线更新检查超时。请检查网络或代理后重试在线检查。",
|
||||
network: "无法连接在线更新服务。请检查网络或代理后重试在线检查。",
|
||||
platform: "更新服务没有提供适用于当前系统或架构的在线安装包。请重试在线检查;也可使用下载页的对应平台安装包。",
|
||||
"invalid-release": "在线更新信息格式无效或未能读取。请重试在线检查;若持续失败,可使用下载页的安装包。",
|
||||
"public-key": "在线更新签名或公钥配置无效。请重试在线检查;若持续失败,请从下载页获取官方安装包。",
|
||||
unknown: "在线更新检查未完成。请重试在线检查;下载页可作为备用。",
|
||||
} : {
|
||||
timeout: "The online update check timed out. Check your network or proxy, then retry the online check.",
|
||||
network: "The online update service could not be reached. Check your network or proxy, then retry the online check.",
|
||||
platform: "The update service did not provide an online installer for this system or architecture. Retry the online check, or use your platform’s installer from the download page.",
|
||||
"invalid-release": "Online update information is invalid or could not be read. Retry the online check; if it keeps failing, use the installer from the download page.",
|
||||
"public-key": "The online update signature or public key configuration is invalid. Retry the online check; if it keeps failing, get the official installer from the download page.",
|
||||
unknown: "The online update check did not finish. Retry the online check; the download page is available as a fallback.",
|
||||
};
|
||||
return messages[kind] ?? messages.unknown;
|
||||
}
|
||||
|
||||
function installationError(error: unknown, fallback: AppUpdaterFailure) {
|
||||
// Only the app's structured installation command supplies user-facing details.
|
||||
// Do not render arbitrary plugin/network errors, which can include private URLs.
|
||||
if (typeof error === "object" && error !== null && "stage" in error && "message" in error) {
|
||||
const data = error as Record<string, unknown>;
|
||||
const stage = ["download", "verify", "prepare", "install"].includes(String(data.stage))
|
||||
? data.stage as AppUpdaterFailure : fallback;
|
||||
return {
|
||||
failure: stage,
|
||||
errorMessage: typeof data.message === "string" ? data.message.slice(0, 1000) : null,
|
||||
logPath: typeof data.logPath === "string" ? data.logPath : null,
|
||||
};
|
||||
}
|
||||
return { failure: fallback, errorMessage: null, logPath: null };
|
||||
}
|
||||
|
||||
export class AppUpdaterController {
|
||||
private state: AppUpdaterState = INITIAL_APP_UPDATER_STATE;
|
||||
private readonly listeners = new Set<() => void>();
|
||||
private readonly dependencies: AppUpdaterDependencies;
|
||||
private update: CheckedAppUpdate | null = null;
|
||||
private checkPromise: Promise<AppUpdaterCheckResult> | null = null;
|
||||
private updatePromise: Promise<AppUpdaterPhase> | null = null;
|
||||
private restartPromise: Promise<AppUpdaterPhase> | null = null;
|
||||
private retryAction: "check" | "update" | "restart" = "check";
|
||||
private slowTimer: unknown = null;
|
||||
private attempt = 0;
|
||||
|
||||
constructor(dependencies: AppUpdaterDependencies) { this.dependencies = dependencies; }
|
||||
readonly getSnapshot = (): AppUpdaterState => this.state;
|
||||
readonly subscribe = (listener: () => void): (() => void) => {
|
||||
this.listeners.add(listener);
|
||||
return () => { this.listeners.delete(listener); };
|
||||
};
|
||||
readonly check = (options: AppUpdaterCheckOptions = {}): Promise<AppUpdaterCheckResult> => {
|
||||
if (this.checkPromise) return this.checkPromise;
|
||||
if (isAppUpdateBusy(this.state.phase) || this.state.phase === "ready") {
|
||||
return Promise.resolve(this.update ? "available" : "error");
|
||||
}
|
||||
if (this.update && !options.force) return Promise.resolve("available");
|
||||
const { force: _force, ...pluginOptions } = options;
|
||||
this.checkPromise = this.performCheck(pluginOptions).finally(() => { this.checkPromise = null; });
|
||||
return this.checkPromise;
|
||||
};
|
||||
readonly downloadAndInstall = (options?: DownloadOptions): Promise<AppUpdaterPhase> => {
|
||||
if (this.updatePromise) return this.updatePromise;
|
||||
if (this.checkPromise) return Promise.resolve(this.state.phase);
|
||||
if (this.state.phase === "ready" || this.state.phase === "handed-off") return Promise.resolve(this.state.phase);
|
||||
if (!this.update) {
|
||||
this.retryAction = "check";
|
||||
this.setState({ phase: "error", failure: "check", checkFailure: "invalid-release", errorMessage: appUpdaterCheckFailureMessage("invalid-release"), latestVersion: null, notes: null, publishedAt: null });
|
||||
return Promise.resolve("error");
|
||||
}
|
||||
this.updatePromise = this.performDownloadAndInstall(this.update, options).finally(() => { this.updatePromise = null; });
|
||||
return this.updatePromise;
|
||||
};
|
||||
readonly retry = (): Promise<AppUpdaterCheckResult | AppUpdaterPhase> => {
|
||||
if (this.retryAction === "restart") return this.restart();
|
||||
if (this.retryAction === "update" && this.update) return this.downloadAndInstall();
|
||||
return this.check({ force: true });
|
||||
};
|
||||
readonly restart = (): Promise<AppUpdaterPhase> => {
|
||||
if (this.restartPromise) return this.restartPromise;
|
||||
if (this.state.phase !== "ready" && this.state.failure !== "restart") return Promise.resolve(this.state.phase);
|
||||
this.restartPromise = this.performRestart().finally(() => { this.restartPromise = null; });
|
||||
return this.restartPromise;
|
||||
};
|
||||
|
||||
private async performCheck(options: CheckOptions): Promise<AppUpdaterCheckResult> {
|
||||
this.retryAction = "check";
|
||||
this.setState({ phase: "checking", downloadedBytes: 0, totalBytes: null, failure: null, errorMessage: null, checkFailure: null, latestVersion: null, notes: null, publishedAt: null, logPath: null, takingLonger: false });
|
||||
try {
|
||||
const nextUpdate = await this.dependencies.check(options);
|
||||
await this.replaceUpdate(nextUpdate);
|
||||
if (nextUpdate && (!Number.isInteger(nextUpdate.rid) || nextUpdate.rid < 0 || nextUpdate.rid > 0xffff_ffff)) {
|
||||
throw new Error("invalid updater resource");
|
||||
}
|
||||
if (!nextUpdate) {
|
||||
this.setState({ phase: "idle", latestVersion: null, notes: null, publishedAt: null });
|
||||
return "up-to-date";
|
||||
}
|
||||
this.retryAction = "update";
|
||||
this.setState({ phase: "available", currentVersion: nextUpdate.currentVersion, latestVersion: nextUpdate.version,
|
||||
notes: nextUpdate.body?.trim() || null, publishedAt: nextUpdate.date || null });
|
||||
return "available";
|
||||
} catch (error) {
|
||||
await this.replaceUpdate(null);
|
||||
const checkFailure = classifyAppUpdaterCheckError(error);
|
||||
this.setState({ phase: "error", failure: "check", checkFailure, errorMessage: appUpdaterCheckFailureMessage(checkFailure), latestVersion: null, notes: null, publishedAt: null });
|
||||
return "error";
|
||||
}
|
||||
}
|
||||
|
||||
private async performDownloadAndInstall(update: CheckedAppUpdate, options?: DownloadOptions): Promise<AppUpdaterPhase> {
|
||||
this.retryAction = "update";
|
||||
const attempt = ++this.attempt;
|
||||
let acceptingEvents = true;
|
||||
let handedOff = false;
|
||||
this.setState({ phase: "downloading", downloadedBytes: 0, totalBytes: null, failure: null, errorMessage: null, checkFailure: null, logPath: null, takingLonger: false });
|
||||
this.armSlowNotice();
|
||||
try {
|
||||
const result = await this.dependencies.install(update, (event) => {
|
||||
if (!acceptingEvents || attempt !== this.attempt || handedOff) return;
|
||||
if (event.event === "HandedOff") handedOff = true;
|
||||
this.handleInstallEvent(event);
|
||||
}, options);
|
||||
// Windows can leave this WebView alive briefly after handing off. The
|
||||
// installer has started, but its success is not yet known; never relaunch it.
|
||||
const phase = handedOff || !result.restartRequired ? "handed-off" : "ready";
|
||||
this.setState({ phase, failure: null, takingLonger: false });
|
||||
if (phase === "handed-off") this.armSlowNotice();
|
||||
return phase;
|
||||
} catch (error) {
|
||||
if (handedOff) return "handed-off";
|
||||
const fallback = this.state.phase === "verifying" ? "verify" : this.state.phase === "preparing" ? "prepare"
|
||||
: this.state.phase === "installing" ? "install" : "download";
|
||||
this.setState({ phase: "error", ...installationError(error, fallback), takingLonger: false });
|
||||
return "error";
|
||||
} finally {
|
||||
acceptingEvents = false;
|
||||
if (this.state.phase !== "handed-off") this.clearSlowNotice();
|
||||
}
|
||||
}
|
||||
private handleInstallEvent(event: AppUpdateEvent): void {
|
||||
if (event.event === "Started") {
|
||||
this.setState({ phase: "downloading", downloadedBytes: 0, totalBytes: normalizeByteCount(event.data.contentLength) });
|
||||
} else if (event.event === "Progress") {
|
||||
const bytes = normalizeByteCount(event.data.chunkLength);
|
||||
if (bytes === null) return;
|
||||
const next = this.state.downloadedBytes + bytes;
|
||||
this.setState({ downloadedBytes: this.state.totalBytes === null ? next : Math.min(next, this.state.totalBytes) });
|
||||
} else {
|
||||
const phase = { Verifying: "verifying", Preparing: "preparing", Installing: "installing", HandedOff: "handed-off" }[event.event] as AppUpdaterPhase;
|
||||
this.setState({ phase, downloadedBytes: this.state.totalBytes ?? this.state.downloadedBytes });
|
||||
}
|
||||
this.armSlowNotice();
|
||||
}
|
||||
private armSlowNotice(): void {
|
||||
this.clearSlowNotice();
|
||||
this.setState({ takingLonger: false });
|
||||
this.slowTimer = this.dependencies.setTimer(() => {
|
||||
this.slowTimer = null;
|
||||
if (isAppUpdateBusy(this.state.phase)) this.setState({ takingLonger: true });
|
||||
}, UPDATER_SLOW_NOTICE_MS);
|
||||
}
|
||||
private clearSlowNotice(): void {
|
||||
if (this.slowTimer !== null) this.dependencies.clearTimer(this.slowTimer);
|
||||
this.slowTimer = null;
|
||||
}
|
||||
private async performRestart(): Promise<AppUpdaterPhase> {
|
||||
this.retryAction = "restart";
|
||||
this.setState({ failure: null, errorMessage: null, checkFailure: null, logPath: null });
|
||||
try { await this.dependencies.restart(); this.setState({ phase: "ready" }); return "ready"; }
|
||||
catch { this.setState({ phase: "error", failure: "restart" }); return "error"; }
|
||||
}
|
||||
private async replaceUpdate(next: CheckedAppUpdate | null): Promise<void> {
|
||||
const previous = this.update;
|
||||
this.update = next;
|
||||
if (previous && previous !== next) {
|
||||
try { await previous.close(); }
|
||||
catch { console.warn("Unable to release the previous updater resource"); }
|
||||
}
|
||||
}
|
||||
private setState(patch: Partial<AppUpdaterState>): void {
|
||||
this.state = { ...this.state, ...patch };
|
||||
this.listeners.forEach((listener) => listener());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import type { CodexLanguageStatus } from "./codexLanguageTypes";
|
||||
|
||||
// Keep the last detected setting across settings-page mounts. Never invent an
|
||||
// initial "off" state while the native configuration is still being read.
|
||||
const statuses = new Map<string, CodexLanguageStatus>();
|
||||
export function cachedCodexLanguageStatus(configDir: string) { return statuses.get(configDir) ?? null; }
|
||||
export function rememberCodexLanguageStatus(configDir: string, status: CodexLanguageStatus) {
|
||||
statuses.set(configDir, status);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
export type CodexLocale = "auto" | "zh-CN" | "en-US";
|
||||
export type CodexLanguageStatus = {
|
||||
locale: string;
|
||||
enabled: boolean;
|
||||
pendingEnabled: boolean | null;
|
||||
supported: boolean;
|
||||
appName: string | null;
|
||||
appVersion: string | null;
|
||||
phase: "inactive" | "pending" | "starting" | "active" | "failed" | "unsupported";
|
||||
message: string;
|
||||
readyPages: number;
|
||||
restoreAvailable: boolean;
|
||||
};
|
||||
@@ -8,9 +8,11 @@ import {
|
||||
RotateCcw,
|
||||
Settings,
|
||||
Sparkles,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
|
||||
import { INITIAL_APP_UPDATER_STATE, type AppUpdaterState } from "../appUpdater";
|
||||
import { INITIAL_APP_UPDATER_STATE, isAppUpdateBusy, type AppUpdaterState } from "../appUpdater";
|
||||
import { appUpdaterCheckFailureMessage } from "../appUpdaterController";
|
||||
import type { Lang, StartupDiagnostics } from "../types";
|
||||
import { Button, ModalShell } from "./ui";
|
||||
|
||||
@@ -19,6 +21,8 @@ export type AppToastProps = {
|
||||
message: string;
|
||||
error: string;
|
||||
loading?: boolean;
|
||||
persistent?: boolean;
|
||||
action?: { label: string; onClick: () => void; disabled?: boolean };
|
||||
onDismissMessage: () => void;
|
||||
onDismissError: () => void;
|
||||
};
|
||||
@@ -28,6 +32,8 @@ export function AppToast({
|
||||
message,
|
||||
error,
|
||||
loading = false,
|
||||
action,
|
||||
persistent = false,
|
||||
onDismissMessage,
|
||||
onDismissError,
|
||||
}: AppToastProps) {
|
||||
@@ -39,11 +45,12 @@ export function AppToast({
|
||||
const [firstLine, ...remainingLines] = activeText.split("\n");
|
||||
const detail = remainingLines.join("\n").trim();
|
||||
const dismiss = isError ? onDismissError : onDismissMessage;
|
||||
const visibleAction = !loading ? action : undefined;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={`${status}:${activeText}`}
|
||||
className={`cx-app-toast cx-app-toast--${status}`}
|
||||
className={`cx-app-toast cx-app-toast--${status}${visibleAction ? " cx-app-toast--actionable" : ""}${persistent ? " cx-app-toast--persistent" : ""}`}
|
||||
role={isError ? "alert" : "status"}
|
||||
aria-live={isError ? "assertive" : "polite"}
|
||||
onAnimationEnd={(event) => {
|
||||
@@ -58,6 +65,10 @@ export function AppToast({
|
||||
<strong>{firstLine || (isError ? (lang === "zh" ? "操作失败" : "Action failed") : "Codex-X")}</strong>
|
||||
{detail && <span>{detail}</span>}
|
||||
</div>
|
||||
{visibleAction && <>
|
||||
<button type="button" className="cx-app-toast-action" onClick={visibleAction.onClick} disabled={visibleAction.disabled}>{visibleAction.label}</button>
|
||||
<button type="button" className="cx-app-toast-dismiss" onClick={dismiss} aria-label={lang === "zh" ? "关闭提示" : "Dismiss notification"}><X size={14} aria-hidden="true" /></button>
|
||||
</>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -102,7 +113,11 @@ export function UpdateDialog({
|
||||
latestVersion: latestVersion ?? null,
|
||||
};
|
||||
const phase = updaterState.phase;
|
||||
const isBusy = phase === "downloading" || phase === "installing";
|
||||
const isBusy = isAppUpdateBusy(phase);
|
||||
const checkFailed = phase === "error" && updaterState.failure === "check";
|
||||
const failureDetails = checkFailed
|
||||
? appUpdaterCheckFailureMessage(updaterState.checkFailure ?? "unknown", lang)
|
||||
: updaterState.errorMessage;
|
||||
const totalBytes = updaterState.totalBytes;
|
||||
const hasKnownProgress = totalBytes !== null && totalBytes > 0;
|
||||
const progress = totalBytes !== null && totalBytes > 0
|
||||
@@ -119,12 +134,18 @@ export function UpdateDialog({
|
||||
: "检测到新版本,可前往下载页获取对应平台的安装包。",
|
||||
downloadingTitle: "正在下载更新",
|
||||
downloadingDescription: "请保持 Codex-X 打开,下载完成后会自动安装。",
|
||||
installingTitle: "正在安装更新",
|
||||
installingDescription: "即将完成,请暂时不要关闭软件。",
|
||||
verifyingTitle: "正在验证安装包",
|
||||
verifyingDescription: "下载已完成,正在确认安装包完整可靠。",
|
||||
preparingTitle: "正在准备更新",
|
||||
preparingDescription: "正在保存状态并恢复连接配置,完成后会自动退出并开始安装。",
|
||||
installingTitle: "正在启动安装程序",
|
||||
installingDescription: "请稍候。如系统询问是否允许安装,请确认授权。",
|
||||
handedOffTitle: "安装程序已启动",
|
||||
handedOffDescription: "Codex-X 即将退出,请在安装窗口继续。首次升级旧版时,系统可能需要一次管理员授权。",
|
||||
readyTitle: "更新已准备好",
|
||||
readyDescription: "重新启动 Codex-X 即可使用新版本。",
|
||||
errorTitle: "更新没有完成",
|
||||
errorDescription: updaterState.failure === "restart"
|
||||
errorTitle: checkFailed ? "在线更新检查失败" : "更新没有完成",
|
||||
errorDescription: checkFailed ? "在线安装尚未开始。请重试在线检查;下载页可作为备用。" : updaterState.failure === "restart"
|
||||
? "软件未能重新启动,请再试一次。"
|
||||
: "请重试;如果仍然失败,也可以前往下载页更新。",
|
||||
idleTitle: "当前已是最新版本",
|
||||
@@ -135,10 +156,20 @@ export function UpdateDialog({
|
||||
close: "关闭",
|
||||
updateNow: "立即更新",
|
||||
downloading: "正在下载",
|
||||
installing: "正在安装",
|
||||
verifying: "验证安装包",
|
||||
preparing: "准备退出",
|
||||
installing: "启动安装程序",
|
||||
handedOff: "等待安装程序",
|
||||
slowTitle: "这一步比平时慢一些",
|
||||
slowDescription: phase === "downloading"
|
||||
? "暂时没有收到新的下载数据,正在等待网络恢复。请勿重复点击更新。"
|
||||
: "仍在等待当前步骤完成。请查看是否有系统授权或安装窗口等待操作,不要重复启动安装。",
|
||||
detailLabel: "失败原因",
|
||||
logLabel: "安装日志",
|
||||
restart: "重新启动",
|
||||
retry: "重试",
|
||||
retry: checkFailed ? "重试在线检查" : "重试",
|
||||
downloadPage: "打开下载页",
|
||||
backupDownloadPage: "打开下载页(备用)",
|
||||
releaseNotes: "本次更新",
|
||||
}
|
||||
: {
|
||||
@@ -150,12 +181,18 @@ export function UpdateDialog({
|
||||
: "A new version is available from the download page for your platform.",
|
||||
downloadingTitle: "Downloading update",
|
||||
downloadingDescription: "Keep Codex-X open. Installation starts automatically after download.",
|
||||
installingTitle: "Installing update",
|
||||
installingDescription: "Almost done. Please keep the app open.",
|
||||
verifyingTitle: "Verifying installer",
|
||||
verifyingDescription: "Download complete. Checking the installer before making changes.",
|
||||
preparingTitle: "Preparing update",
|
||||
preparingDescription: "Saving state and restoring connection settings before exiting to install.",
|
||||
installingTitle: "Starting installer",
|
||||
installingDescription: "Please wait. Approve the installation if your system asks for permission.",
|
||||
handedOffTitle: "Installer started",
|
||||
handedOffDescription: "Codex-X will exit. Continue in the installer window. Upgrading an older installation may ask for administrator permission once.",
|
||||
readyTitle: "Update is ready",
|
||||
readyDescription: "Restart Codex-X to use the new version.",
|
||||
errorTitle: "Update did not finish",
|
||||
errorDescription: updaterState.failure === "restart"
|
||||
errorTitle: checkFailed ? "Online update check failed" : "Update did not finish",
|
||||
errorDescription: checkFailed ? "Online installation has not started. Retry the online check; the download page is available as a fallback." : updaterState.failure === "restart"
|
||||
? "Codex-X could not restart. Please try again."
|
||||
: "Try again, or use the download page if the problem continues.",
|
||||
idleTitle: "Codex-X is up to date",
|
||||
@@ -166,39 +203,40 @@ export function UpdateDialog({
|
||||
close: "Close",
|
||||
updateNow: "Update now",
|
||||
downloading: "Downloading",
|
||||
installing: "Installing",
|
||||
verifying: "Verifying installer",
|
||||
preparing: "Preparing to exit",
|
||||
installing: "Starting installer",
|
||||
handedOff: "Waiting for installer",
|
||||
slowTitle: "Taking a little longer",
|
||||
slowDescription: phase === "downloading"
|
||||
? "Waiting for more download data. Please do not start another update."
|
||||
: "Still waiting for this step to finish. Check for a system permission or installer window requiring your attention. Do not start another installation.",
|
||||
detailLabel: "What went wrong",
|
||||
logLabel: "Installation log",
|
||||
restart: "Restart",
|
||||
retry: "Try again",
|
||||
retry: checkFailed ? "Retry online check" : "Try again",
|
||||
downloadPage: "Open download page",
|
||||
backupDownloadPage: "Open download page (fallback)",
|
||||
releaseNotes: "What's new",
|
||||
};
|
||||
|
||||
const title = phase === "checking"
|
||||
? copy.checkingTitle
|
||||
: phase === "available"
|
||||
? copy.availableTitle
|
||||
: phase === "downloading"
|
||||
? copy.downloadingTitle
|
||||
: phase === "installing"
|
||||
? copy.installingTitle
|
||||
: phase === "ready"
|
||||
? copy.readyTitle
|
||||
: phase === "error"
|
||||
? copy.errorTitle
|
||||
: copy.idleTitle;
|
||||
const description = phase === "checking"
|
||||
? copy.checkingDescription
|
||||
: phase === "available"
|
||||
? copy.availableDescription
|
||||
: phase === "downloading"
|
||||
? copy.downloadingDescription
|
||||
: phase === "installing"
|
||||
? copy.installingDescription
|
||||
: phase === "ready"
|
||||
? copy.readyDescription
|
||||
: phase === "error"
|
||||
? copy.errorDescription
|
||||
: copy.idleDescription;
|
||||
const phaseCopy = {
|
||||
checking: [copy.checkingTitle, copy.checkingDescription],
|
||||
available: [copy.availableTitle, copy.availableDescription],
|
||||
downloading: [copy.downloadingTitle, copy.downloadingDescription],
|
||||
verifying: [copy.verifyingTitle, copy.verifyingDescription],
|
||||
preparing: [copy.preparingTitle, copy.preparingDescription],
|
||||
installing: [copy.installingTitle, copy.installingDescription],
|
||||
"handed-off": [copy.handedOffTitle, copy.handedOffDescription],
|
||||
ready: [copy.readyTitle, copy.readyDescription],
|
||||
error: [copy.errorTitle, copy.errorDescription],
|
||||
idle: [copy.idleTitle, copy.idleDescription],
|
||||
};
|
||||
const [title, description] = phaseCopy[phase];
|
||||
const progressLabel = phase === "downloading" ? copy.downloading
|
||||
: phase === "verifying" ? copy.verifying : phase === "preparing" ? copy.preparing
|
||||
: phase === "handed-off" ? copy.handedOff : phase === "ready" ? copy.restart : copy.installing;
|
||||
const indeterminate = isBusy && (phase !== "downloading" || progress === null);
|
||||
|
||||
const handleClose = () => {
|
||||
if (!isBusy) onClose();
|
||||
@@ -229,7 +267,7 @@ export function UpdateDialog({
|
||||
? (
|
||||
<>
|
||||
<Button variant="secondary" icon={<Download size={16} />} onClick={onDownload}>
|
||||
{copy.downloadPage}
|
||||
{checkFailed ? copy.backupDownloadPage : copy.downloadPage}
|
||||
</Button>
|
||||
<Button icon={<RotateCcw size={16} />} onClick={() => void onRetry?.()}>
|
||||
{copy.retry}
|
||||
@@ -239,7 +277,7 @@ export function UpdateDialog({
|
||||
: isBusy
|
||||
? (
|
||||
<Button disabled icon={<Loader2 className="spin" size={16} />}>
|
||||
{phase === "downloading" ? copy.downloading : copy.installing}
|
||||
{progressLabel}
|
||||
</Button>
|
||||
)
|
||||
: <Button variant="secondary" onClick={handleClose}>{copy.close}</Button>;
|
||||
@@ -272,10 +310,10 @@ export function UpdateDialog({
|
||||
<div><dt>{copy.latest}</dt><dd>{updaterState.latestVersion || latestVersion || "-"}</dd></div>
|
||||
</dl>
|
||||
|
||||
{(phase === "downloading" || phase === "installing" || phase === "ready") && (
|
||||
{(isBusy || phase === "ready") && (
|
||||
<div className="cx-update-progress" aria-live="polite">
|
||||
<div className="cx-update-progress-copy">
|
||||
<span>{phase === "downloading" ? copy.downloading : phase === "installing" ? copy.installing : copy.restart}</span>
|
||||
<span>{progressLabel}</span>
|
||||
<strong>
|
||||
{phase === "downloading"
|
||||
? hasKnownProgress
|
||||
@@ -289,18 +327,31 @@ export function UpdateDialog({
|
||||
</strong>
|
||||
</div>
|
||||
<div
|
||||
className={`cx-update-progress-track${progress === null && phase === "downloading" ? " cx-update-progress-track--indeterminate" : ""}`}
|
||||
className={`cx-update-progress-track${indeterminate ? " cx-update-progress-track--indeterminate" : ""}`}
|
||||
role="progressbar"
|
||||
aria-label={phase === "downloading" ? copy.downloading : copy.installing}
|
||||
aria-label={progressLabel}
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={100}
|
||||
aria-valuenow={phase === "ready" ? 100 : progress ?? undefined}
|
||||
aria-valuenow={phase === "ready" ? 100 : indeterminate ? undefined : progress ?? undefined}
|
||||
>
|
||||
<span style={{ width: phase === "ready" || phase === "installing" ? "100%" : progress === null ? "38%" : `${progress}%` }} />
|
||||
<span style={{ width: phase === "ready" ? "100%" : indeterminate ? "38%" : `${progress}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{updaterState.takingLonger && isBusy && (
|
||||
<section className="cx-update-notes" role="status">
|
||||
<strong>{copy.slowTitle}</strong>
|
||||
<p>{copy.slowDescription}</p>
|
||||
</section>
|
||||
)}
|
||||
{phase === "error" && failureDetails && (
|
||||
<section className="cx-update-notes" role="alert">
|
||||
<strong>{copy.detailLabel}</strong>
|
||||
<p>{failureDetails}</p>
|
||||
{updaterState.logPath && <p className="cx-update-log-path">{copy.logLabel}: {updaterState.logPath}</p>}
|
||||
</section>
|
||||
)}
|
||||
{updaterState.notes && phase !== "checking" && (
|
||||
<section className="cx-update-notes">
|
||||
<strong>{copy.releaseNotes}</strong>
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
Zap,
|
||||
} from "lucide-react";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import type { AppUpdaterPhase } from "../appUpdater";
|
||||
import { isAppUpdateBusy, type AppUpdaterPhase } from "../appUpdater";
|
||||
import { IconButton } from "./ui/IconButton";
|
||||
|
||||
export type AppLanguage = "zh" | "en";
|
||||
@@ -102,11 +102,10 @@ export function AppShell({
|
||||
? (lang === "zh" ? "切换为浅色模式" : "Switch to light mode")
|
||||
: (lang === "zh" ? "切换为深色模式" : "Switch to dark mode");
|
||||
const ThemeIcon = theme === "dark" ? Moon : Sun;
|
||||
const updateActionState = updatePhase === "downloading"
|
||||
|| updatePhase === "installing"
|
||||
const updateActionState = isAppUpdateBusy(updatePhase)
|
||||
|| updatePhase === "ready"
|
||||
|| updatePhase === "available"
|
||||
? updatePhase
|
||||
? (isAppUpdateBusy(updatePhase) && updatePhase !== "downloading" ? "installing" : updatePhase)
|
||||
: hasUpdate
|
||||
? "available"
|
||||
: null;
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { Languages, Loader2 } from "lucide-react";
|
||||
import type { CodexLanguageStatus } from "../codexLanguageTypes";
|
||||
import { Toggle } from "./ui";
|
||||
import { cachedCodexLanguageStatus, rememberCodexLanguageStatus } from "../codexLanguageState";
|
||||
import "../styles/codex-language.css";
|
||||
|
||||
export function CodexLanguageControl({ lang, configDir, active = true, disabled = false, onBusyChange, onPreferencesSaved }: {
|
||||
lang: "zh" | "en";
|
||||
configDir: string;
|
||||
active?: boolean;
|
||||
disabled?: boolean;
|
||||
onBusyChange?: (busy: boolean) => void;
|
||||
onPreferencesSaved?: (status: CodexLanguageStatus) => void;
|
||||
}) {
|
||||
const text = (zh: string, en: string) => lang === "zh" ? zh : en;
|
||||
const [detected, setDetected] = useState(() => ({ configDir, value: cachedCodexLanguageStatus(configDir) }));
|
||||
const status = detected.configDir === configDir ? detected.value : cachedCodexLanguageStatus(configDir);
|
||||
const setStatus = (value: CodexLanguageStatus) => {
|
||||
rememberCodexLanguageStatus(configDir, value);
|
||||
setDetected({ configDir, value });
|
||||
};
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [readError, setReadError] = useState("");
|
||||
const [actionError, setActionError] = useState("");
|
||||
const parentBusy = useRef(disabled);
|
||||
parentBusy.current = disabled;
|
||||
const generation = useRef(0);
|
||||
const operationInFlight = useRef(false);
|
||||
const statusRequest = useRef(0);
|
||||
|
||||
useEffect(() => {
|
||||
generation.current += 1;
|
||||
setDetected({ configDir, value: cachedCodexLanguageStatus(configDir) });
|
||||
setReadError(""); setActionError(""); setBusy(false);
|
||||
}, [configDir]);
|
||||
useEffect(() => () => { generation.current += 1; }, []);
|
||||
|
||||
useEffect(() => {
|
||||
const current = generation.current;
|
||||
let disposed = false;
|
||||
let loading = false;
|
||||
const load = async () => {
|
||||
if (loading || disposed || !active || operationInFlight.current || parentBusy.current) return;
|
||||
loading = true;
|
||||
const request = ++statusRequest.current;
|
||||
try {
|
||||
const next = await invoke<CodexLanguageStatus>("get_codex_language_status", { configDir });
|
||||
if (!disposed && generation.current === current && request === statusRequest.current && !operationInFlight.current && !parentBusy.current) {
|
||||
setStatus(next); setReadError("");
|
||||
}
|
||||
} catch (cause) {
|
||||
if (!disposed && generation.current === current && request === statusRequest.current && !operationInFlight.current && !parentBusy.current) setReadError(String(cause));
|
||||
} finally { loading = false; }
|
||||
};
|
||||
if (active) void load();
|
||||
const interval = active ? window.setInterval(() => { void load(); }, 1800) : undefined;
|
||||
return () => { disposed = true; if (interval !== undefined) window.clearInterval(interval); };
|
||||
}, [configDir, active]);
|
||||
|
||||
const save = async (enabled: boolean) => {
|
||||
if (busy || disabled || operationInFlight.current) return;
|
||||
operationInFlight.current = true;
|
||||
statusRequest.current += 1;
|
||||
onBusyChange?.(true);
|
||||
const current = generation.current;
|
||||
setBusy(true); setActionError("");
|
||||
try {
|
||||
const next = await invoke<CodexLanguageStatus>("save_codex_language_preferences", { configDir, locale: enabled ? "zh-CN" : "auto", enabled });
|
||||
if (current === generation.current) { setStatus(next); setReadError(""); onPreferencesSaved?.(next); }
|
||||
} catch (cause) {
|
||||
if (current === generation.current) setActionError(String(cause));
|
||||
} finally {
|
||||
operationInFlight.current = false;
|
||||
onBusyChange?.(false);
|
||||
if (current === generation.current) setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const pending = status?.pendingEnabled != null;
|
||||
const enabled = status?.pendingEnabled ?? status?.enabled ?? false;
|
||||
const starting = status?.phase === "starting";
|
||||
const blocked = busy || disabled || starting;
|
||||
const error = actionError || readError || (status?.phase === "failed" ? status.message : "");
|
||||
const description = error || (status && !status.supported ? status.message : text(
|
||||
"为 Codex 应用简体中文,重启生效。自动检测当前配置。",
|
||||
"Use Simplified Chinese in Codex after restart. Detects current settings.",
|
||||
));
|
||||
const stateLabel = busy ? text("处理中", "Saving")
|
||||
: readError ? text("检测失败", "Unavailable")
|
||||
: actionError ? text("操作失败", "Failed")
|
||||
: !status ? text("检测中", "Checking")
|
||||
: status.phase === "failed" ? text("应用失败", "Failed")
|
||||
: starting ? text("应用中", "Applying")
|
||||
: pending ? text("待重启", "Restart needed")
|
||||
: enabled ? text("已开启", "On") : text("已关闭", "Off");
|
||||
|
||||
return <section className="cx-page-setting-row cx-codex-language" aria-labelledby="codex-language-title" aria-busy={busy || starting}>
|
||||
<div className="cx-page-setting-icon" aria-hidden="true"><Languages size={18} strokeWidth={1.9} /></div>
|
||||
<div className="cx-page-setting-copy">
|
||||
<strong id="codex-language-title">{text("Codex 简体中文", "Codex Simplified Chinese")}</strong>
|
||||
<p id="codex-language-description" title={description} role={error ? "alert" : undefined} className={error ? "cx-codex-language-error" : undefined}>{description}</p>
|
||||
</div>
|
||||
<div className="cx-page-setting-action cx-codex-language-action">
|
||||
<div className="cx-codex-language-switch">
|
||||
<span className={enabled && !pending && !error ? "cx-codex-language-enabled" : undefined} aria-live="polite">{stateLabel}</span>
|
||||
{status ? <Toggle checked={enabled} disabled={blocked || !status.supported || Boolean(readError)} aria-labelledby="codex-language-title" aria-describedby="codex-language-description" onCheckedChange={next => void save(next)} />
|
||||
: <span className="cx-codex-language-loading" aria-hidden="true"><Loader2 size={15} className="cx-page-spin" /></span>}
|
||||
</div>
|
||||
</div>
|
||||
</section>;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useId } from "react";
|
||||
import { AlertTriangle, CheckCircle2, FileSearch, FolderOpen, Loader2, RefreshCw, Wrench } from "lucide-react";
|
||||
import type { ConfigHealthReport } from "../configHealthTypes";
|
||||
import { configHealthIssueLocation, configHealthRepairUnavailableReason } from "../configHealthPresentation";
|
||||
import type { ConfigHealthIssue, ConfigHealthReport } from "../configHealthTypes";
|
||||
import { Button } from "./ui";
|
||||
import "../styles/config-health.css";
|
||||
|
||||
@@ -15,6 +16,15 @@ export type ConfigHealthPanelProps = {
|
||||
onOpenConfig?: () => void;
|
||||
};
|
||||
|
||||
export function ConfigHealthIssueDetails({ issue, report, lang }: { issue: ConfigHealthIssue; report: ConfigHealthReport; lang: "zh" | "en" }) {
|
||||
const location = configHealthIssueLocation(issue, report, lang);
|
||||
return <>
|
||||
<p className="cx-config-health-location"><code>{location.path}</code><span>{location.position}</span></p>
|
||||
<p className="cx-config-health-key">{lang === "zh" ? "参数:" : "Setting: "}<code>{location.key}</code></p>
|
||||
{issue.suggestion && <p className="cx-config-health-suggestion">{lang === "zh" ? "修复建议:" : "Suggested fix: "}{issue.suggestion}</p>}
|
||||
</>;
|
||||
}
|
||||
|
||||
export function ConfigHealthStatus({ lang, report, checking, repairing, error }: Pick<ConfigHealthPanelProps, "lang" | "report" | "checking" | "repairing" | "error">) {
|
||||
const zh = lang === "zh";
|
||||
const busy = checking || repairing;
|
||||
@@ -60,14 +70,14 @@ export function ConfigHealthPanel({ lang, report, checking, repairing, error, on
|
||||
<ul className="cx-config-health-issues">
|
||||
{report.issues.map((issue, index) => <li key={`${issue.code}-${index}`}>
|
||||
<AlertTriangle size={15} aria-hidden="true" />
|
||||
<div><strong>{issue.title}</strong><p>{issue.description}</p></div>
|
||||
<div><strong>{issue.title}</strong><p>{issue.description}</p><ConfigHealthIssueDetails issue={issue} report={report} lang={lang} /></div>
|
||||
</li>)}
|
||||
</ul>
|
||||
{report.canRepair && report.repairSummary.length > 0 && <div className="cx-config-health-plan">
|
||||
<strong>{zh ? "点击修复后,将进行以下调整:" : "Repair will make these changes:"}</strong>
|
||||
<ul>{report.repairSummary.map((summary, index) => <li key={index}>{summary}</li>)}</ul>
|
||||
</div>}
|
||||
{manualIssues && <p className="cx-config-health-note">{zh ? "部分问题需要手动检查。为保留你的配置,软件不会猜测或覆盖无法确认的内容。" : "Some issues need a manual check. Settings that cannot be determined safely will be left for you to review."}</p>}
|
||||
{manualIssues && <p className="cx-config-health-note">{zh ? "请按每项问题的文件位置与修复建议处理需要手动确认的参数,然后重新检查。" : "Use each issue’s file location and suggested fix to review settings that need manual confirmation, then check again."}</p>}
|
||||
</div>}
|
||||
|
||||
{report?.status === "missing" && <p className="cx-config-health-note">{zh ? "还没有找到配置文件。完成 Codex 登录或启用供应商后,可以再次检查。" : "No configuration file was found. Check again after signing in to Codex or enabling a provider."}</p>}
|
||||
@@ -80,6 +90,7 @@ export function ConfigHealthPanel({ lang, report, checking, repairing, error, on
|
||||
<div className="cx-config-health-actions">
|
||||
{onOpenConfig && (hasIssues || report?.status === "unavailable") && <Button variant="ghost" size="sm" icon={<FolderOpen size={15} />} disabled={busy} onClick={onOpenConfig}>{zh ? "查看配置" : "View configuration"}</Button>}
|
||||
<Button variant="secondary" size="sm" icon={checking ? <Loader2 size={15} className="cx-config-health-spinner" /> : <RefreshCw size={15} />} disabled={busy} onClick={onCheck}>{checking ? (zh ? "检查中" : "Checking") : (zh ? "检查配置" : "Check configuration")}</Button>
|
||||
{hasIssues && !report.canRepair && <Button variant="secondary" size="sm" icon={<Wrench size={15} />} disabled title={configHealthRepairUnavailableReason(report, lang)}>{zh ? "需手动修复" : "Manual repair needed"}</Button>}
|
||||
{report?.canRepair && hasIssues && <Button size="sm" icon={repairing ? <Loader2 size={15} className="cx-config-health-spinner" /> : <Wrench size={15} />} disabled={busy} onClick={onRepair}>{repairing ? (zh ? "修复中" : "Repairing") : (zh ? "修复配置" : "Repair configuration")}</Button>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { AlertTriangle, ArrowRight, Loader2, Wrench, X } from "lucide-react";
|
||||
import { primaryConfigHealthIssue } from "../configHealthPresentation";
|
||||
import { ConfigHealthIssueDetails } from "./ConfigHealthPanel";
|
||||
import type { ConfigHealthReport } from "../configHealthTypes";
|
||||
import { Button } from "./ui";
|
||||
import "../styles/config-health.css";
|
||||
@@ -15,12 +17,14 @@ export type ConfigHealthToastProps = {
|
||||
/** The caller owns notification lifetime; CSS never dismisses this toast. */
|
||||
export function ConfigHealthToast({ lang, report, repairing, onRepair, onDismiss, onOpenSettings }: ConfigHealthToastProps) {
|
||||
const zh = lang === "zh";
|
||||
const issue = primaryConfigHealthIssue(report);
|
||||
return <aside className="cx-config-health-toast" aria-label={zh ? "配置检查提醒" : "Configuration check notification"}>
|
||||
<span className="cx-config-health-toast-icon" aria-hidden="true"><AlertTriangle size={20} /></span>
|
||||
<div className="cx-config-health-toast-content">
|
||||
<div role="status" aria-live="polite" aria-atomic="true">
|
||||
<strong>{repairing ? (zh ? "正在修复 Codex 配置" : "Repairing Codex configuration") : (zh ? "检测到 Codex 配置问题" : "Codex configuration needs attention")}</strong>
|
||||
<p>{(report.canRepair ? report.issues[0]?.title : report.issues[0]?.description) || (zh ? "部分配置可能影响 Codex 正常使用。" : "Some settings may prevent Codex from working correctly.")}</p>
|
||||
<p>{(report.canRepair ? issue?.title : issue?.description) || (zh ? "部分配置可能影响 Codex 正常使用。" : "Some settings may prevent Codex from working correctly.")}</p>
|
||||
{issue && <ConfigHealthIssueDetails issue={issue} report={report} lang={lang} />}
|
||||
{report.canRepair && report.repairSummary[0] && <p className="cx-config-health-toast-plan">{report.repairSummary[0]}</p>}
|
||||
</div>
|
||||
<div className="cx-config-health-toast-actions">
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import { AlertCircle, RefreshCw } from "lucide-react";
|
||||
import type { ProviderBalance } from "../providerBalance";
|
||||
import "../styles/provider-balance.css";
|
||||
|
||||
function errorLabel(code: string | null, zh: boolean) {
|
||||
if (code === "permission_denied") return zh ? "查询权限不足" : "Access denied";
|
||||
if (code === "invalid_credential" || code === "authentication_failed") return zh ? "请检查 API Key" : "Check API key";
|
||||
if (code === "missing_key") return zh ? "未设置 API Key" : "API key missing";
|
||||
if (code === "rate_limited") return zh ? "请求较多,请稍后刷新" : "Rate limited. Try again shortly.";
|
||||
if (code === "timeout" || code === "network_error") return zh ? "网络异常,请稍后刷新" : "Check your connection and retry.";
|
||||
return zh ? "暂时无法查询" : "Temporarily unavailable";
|
||||
}
|
||||
|
||||
function amountText(amount: string) {
|
||||
const match = /^(-?)(\d+)(?:\.(\d+))?$/.exec(amount);
|
||||
if (!match) return amount;
|
||||
const integer = match[2].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
||||
const fraction = (match[3] || "").replace(/0+$/, "").padEnd(2, "0");
|
||||
// Group the exact decimal string; financial values never pass through Number.
|
||||
return `${match[1] === "-" ? "−" : ""}${integer}.${fraction}`;
|
||||
}
|
||||
|
||||
export function ProviderBalanceBadge({ balance, loading, refreshing = false, failed, lang, onRefresh }: {
|
||||
balance?: ProviderBalance;
|
||||
loading: boolean;
|
||||
refreshing?: boolean;
|
||||
failed: boolean;
|
||||
lang: "zh" | "en";
|
||||
onRefresh?: () => void;
|
||||
}) {
|
||||
const zh = lang === "zh";
|
||||
const hasBalance = Boolean(balance?.balances.length);
|
||||
const unavailable = failed || Boolean(balance?.errorCode);
|
||||
const busy = loading || refreshing;
|
||||
const label = balance?.balanceKind === "credit_limit" ? (zh ? "Key 剩余额度" : "Key credit left") : (zh ? "可用余额" : "Available balance");
|
||||
const updated = balance?.checkedAt ? new Date(balance.checkedAt) : null;
|
||||
const updateTime = updated && Number.isFinite(updated.getTime())
|
||||
? updated.toLocaleTimeString(zh ? "zh-CN" : "en-GB", { hour12: false, hour: "2-digit", minute: "2-digit", second: "2-digit" }) : null;
|
||||
const detail = errorLabel(balance?.errorCode ?? null, zh);
|
||||
const hint = [balance?.balanceKind === "credit_limit" ? (zh ? "此 API Key 的剩余额度。" : "Remaining credit for this API key.") : "",
|
||||
unavailable ? detail : "", updateTime ? `${hasBalance ? (zh ? "余额更新于" : "Balance updated") : (zh ? "最近查询于" : "Last checked")} ${updated!.toLocaleString(zh ? "zh-CN" : "en-GB")}` : "",
|
||||
zh ? "后台每 5 分钟自动刷新,也可点击余额旁的按钮立即查询。" : "Refreshes every 5 minutes in the background. Use the refresh button to query now."].filter(Boolean).join("\n");
|
||||
return <section className={`cx-provider-balance${unavailable ? " cx-provider-balance--stale" : ""}`} aria-label={label} aria-busy={busy} title={hint}>
|
||||
<div className="cx-provider-balance-heading">
|
||||
<span>{label}</span>
|
||||
|
||||
</div>
|
||||
<div className="cx-provider-balance-reading">
|
||||
{hasBalance ? <div className={`cx-provider-balance-amounts${balance!.balances.length > 1 ? " cx-provider-balance-amounts--multiple" : ""}`}>
|
||||
{balance!.balances.map(item => <div key={item.currency} className={`cx-provider-balance-value${item.amount.startsWith("-") || /^0(?:\.0+)?$/.test(item.amount) ? " cx-provider-balance-value--empty" : ""}`} title={`${item.amount} ${item.currency}`}>
|
||||
<strong>{amountText(item.amount)}</strong><span>{item.currency}</span>
|
||||
</div>)}
|
||||
</div> : busy ? <div className="cx-provider-balance-placeholder" aria-label={zh ? "正在查询余额" : "Loading balance"}><span /></div>
|
||||
: <div className="cx-provider-balance-unavailable"><AlertCircle size={14} aria-hidden="true" /><span>{detail}</span></div>}
|
||||
<button type="button" className="cx-provider-balance-refresh" disabled={busy || !onRefresh} onClick={onRefresh}
|
||||
title={zh ? "立即刷新余额" : "Refresh balance now"} aria-label={zh ? "刷新余额" : "Refresh balance"}>
|
||||
<RefreshCw size={13} strokeWidth={1.8} className={busy ? "cx-provider-balance-spin" : undefined} aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
<div className={`cx-provider-balance-footer${unavailable && !busy ? " cx-provider-balance-footer--error" : ""}`} aria-live="polite">
|
||||
{busy ? (zh ? "正在刷新…" : "Refreshing…") : <>{unavailable ? (zh ? "刷新失败" : "Refresh failed") : !hasBalance ? (zh ? "尚未更新" : "Not updated") : (zh ? "已更新" : "Updated")}{updateTime && <><span aria-hidden="true"> · </span>{unavailable && hasBalance ? (zh ? "上次 " : "Last ") : ""}<time dateTime={balance!.checkedAt!}>{updateTime}</time></>}</>}
|
||||
</div>
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { ProviderHeadersEditor } from "./ProviderHeadersEditor";
|
||||
import { normalizeProviderHeaders, validateProviderHeaders } from "../providerHeaders";
|
||||
import type { ProviderHeader } from "../providerHeaders";
|
||||
import { createProviderHeadersControl } from "../providerHeadersControl";
|
||||
import type { ProviderHeadersControlState } from "../providerHeadersControl";
|
||||
|
||||
export function ProviderHeadersControl({ lang, configText, disabled = false, onConfigChange, onBusyChange, onValidityChange }: {
|
||||
lang: "zh" | "en";
|
||||
configText: string;
|
||||
disabled?: boolean;
|
||||
onConfigChange: (configText: string) => void;
|
||||
onBusyChange: (busy: boolean) => void;
|
||||
onValidityChange: (valid: boolean) => void;
|
||||
}) {
|
||||
const runtime = useRef({ configText, onConfigChange, onBusyChange, onValidityChange });
|
||||
runtime.current = { configText, onConfigChange, onBusyChange, onValidityChange };
|
||||
const control = useRef<ReturnType<typeof createProviderHeadersControl> | null>(null);
|
||||
const [rows, setRows] = useState<ProviderHeader[]>([]);
|
||||
const [state, setState] = useState<ProviderHeadersControlState>({ busy: true, reading: true, valid: false, error: null });
|
||||
|
||||
useEffect(() => {
|
||||
const instance = createProviderHeadersControl({
|
||||
read: (text) => invoke<ProviderHeader[]>("read_provider_headers", { configText: text }),
|
||||
update: (text, headers) => invoke<string>("update_provider_headers", { configText: text, headers }),
|
||||
getConfigText: () => runtime.current.configText,
|
||||
isValid: (next) => validateProviderHeaders(next).valid,
|
||||
normalize: normalizeProviderHeaders,
|
||||
onRowsChange: setRows,
|
||||
onConfigChange: (text) => runtime.current.onConfigChange(text),
|
||||
onStateChange: (next) => {
|
||||
setState(next);
|
||||
runtime.current.onBusyChange(next.busy);
|
||||
runtime.current.onValidityChange(next.valid);
|
||||
},
|
||||
});
|
||||
control.current = instance;
|
||||
void instance.load(runtime.current.configText);
|
||||
return () => {
|
||||
instance.dispose();
|
||||
if (control.current === instance) control.current = null;
|
||||
runtime.current.onBusyChange(false);
|
||||
runtime.current.onValidityChange(true);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => { void control.current?.load(configText); }, [configText]);
|
||||
|
||||
const errorText = state.error === "read"
|
||||
? lang === "zh" ? "无法读取 Headers,请检查供应商 TOML 后重试。" : "Could not read headers. Check the provider TOML and retry."
|
||||
: lang === "zh" ? "无法更新 Headers,请重试或检查供应商 TOML。" : "Could not update headers. Retry or check the provider TOML.";
|
||||
|
||||
return <div className="cx-provider-headers-control">
|
||||
<ProviderHeadersEditor lang={lang} rows={rows} disabled={disabled || state.reading} onChange={(next) => { void control.current?.changeRows(next); }} />
|
||||
{state.busy && <p className="cx-provider-headers-hint" role="status">{state.reading
|
||||
? lang === "zh" ? "正在读取 Headers…" : "Reading headers…"
|
||||
: lang === "zh" ? "正在更新配置…" : "Updating configuration…"}</p>}
|
||||
{state.error && <div className="cx-provider-headers-feedback"><p className="cx-provider-headers-error" role="status">{errorText}</p><button type="button" className="cx-providers-button cx-providers-button--secondary cx-providers-button--small" disabled={disabled || state.busy} onClick={() => { void control.current?.retry(); }}>{lang === "zh" ? "重试" : "Retry"}</button></div>}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { useId } from "react";
|
||||
import { Plus, Trash2 } from "lucide-react";
|
||||
import {
|
||||
createProviderHeader,
|
||||
removeProviderHeader,
|
||||
updateProviderHeader,
|
||||
validateProviderHeaders,
|
||||
} from "../providerHeaders";
|
||||
import type { ProviderHeader, ProviderHeaderSource } from "../providerHeaders";
|
||||
import { applyProviderHeaderPreset, PROVIDER_HEADER_PRESETS, providerHeaderValuePlaceholder } from "../providerHeaderPresets";
|
||||
import "../styles/provider-headers.css";
|
||||
|
||||
export function ProviderHeadersEditor({ lang, rows, disabled = false, onChange }: {
|
||||
lang: "zh" | "en";
|
||||
rows: readonly ProviderHeader[];
|
||||
disabled?: boolean;
|
||||
onChange: (rows: ProviderHeader[]) => void;
|
||||
}) {
|
||||
const id = useId();
|
||||
const copy = lang === "zh" ? {
|
||||
title: "自定义请求头 Headers", optional: "可选", hint: "按供应商要求设置 User-Agent(客户端标识)或其他附加请求头;不填写时使用默认设置。",
|
||||
presets: "User-Agent 预设", presetHint: "预设只设置 User-Agent,其他请求头保留;已有 User-Agent 会更新为所选固定值。预设是否适用以供应商要求为准。",
|
||||
envHint: "环境变量模式只保存变量名;直连由 Codex 读取,路由由 Codex-X 读取,请在启动对应应用前设置。",
|
||||
add: "添加 Header", empty: "尚未配置自定义 Headers", name: "名称", value: "值", source: "值来源", literal: "固定值", env: "环境变量", remove: "删除 Header",
|
||||
placeholder: "例如 User-Agent", envPlaceholder: "例如 PROVIDER_HEADER_VALUE", fix: "请先修正标红的 Headers,再保存供应商。",
|
||||
row: (index: number) => `第 ${index + 1} 行`,
|
||||
} : {
|
||||
title: "Custom headers", optional: "Optional", hint: "Set User-Agent (client identification) or other HTTP headers required by your provider. Leave them empty to keep the defaults.",
|
||||
presets: "User-Agent presets", presetHint: "Presets set only User-Agent and keep other headers. An existing User-Agent becomes the selected literal value. Check your provider requirements before choosing one.",
|
||||
envHint: "Environment mode saves only the variable name. Set it before launching Codex for direct requests, or Codex-X for routed requests.",
|
||||
add: "Add header", empty: "No custom headers configured", name: "Name", value: "Value", source: "Value source", literal: "Literal value", env: "Environment variable", remove: "Remove header",
|
||||
placeholder: "e.g. User-Agent", envPlaceholder: "e.g. PROVIDER_HEADER_VALUE", fix: "Correct the highlighted headers before saving this provider.",
|
||||
row: (index: number) => `Row ${index + 1}`,
|
||||
};
|
||||
const validation = validateProviderHeaders(rows, lang);
|
||||
const update = (index: number, patch: Partial<ProviderHeader>) => {
|
||||
if (!disabled) onChange(updateProviderHeader(rows, index, patch));
|
||||
};
|
||||
|
||||
return <section className="cx-provider-headers" aria-labelledby={`${id}-title`}>
|
||||
<div className="cx-provider-headers-heading">
|
||||
<div><strong id={`${id}-title`}>{copy.title}<span>{copy.optional}</span></strong><p>{copy.hint}</p></div>
|
||||
<div className="cx-provider-headers-actions">
|
||||
<select className="cx-provider-headers-presets" aria-label={copy.presets} aria-describedby={`${id}-preset-hint`} value="" disabled={disabled} onChange={(event) => {
|
||||
const selected = event.currentTarget.value;
|
||||
if (selected) onChange(applyProviderHeaderPreset(rows, selected));
|
||||
}}>
|
||||
<option value="">{copy.presets}</option>
|
||||
{PROVIDER_HEADER_PRESETS.map((preset) => <option key={preset.id} value={preset.id}>{preset.label[lang]} · {preset.value}</option>)}
|
||||
</select>
|
||||
<button type="button" className="cx-providers-button cx-providers-button--secondary cx-providers-button--small" disabled={disabled} onClick={() => onChange([...rows, createProviderHeader()])}><Plus size={14} aria-hidden="true" />{copy.add}</button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="cx-provider-headers-hint cx-provider-headers-preset-hint" id={`${id}-preset-hint`}>{copy.presetHint}</p>
|
||||
{rows.length === 0 ? <p className="cx-provider-headers-empty">{copy.empty}</p> : <div className="cx-provider-headers-rows">
|
||||
{rows.map((row, index) => {
|
||||
const error = validation.errors[index];
|
||||
return <div key={index} className="cx-provider-header-row" role="group" aria-label={copy.row(index)}>
|
||||
<label className="cx-provider-header-field"><span>{copy.name}</span><input value={row.name} placeholder={copy.placeholder} aria-label={`${copy.name} · ${copy.row(index)}`} aria-invalid={Boolean(error.name)} aria-describedby={error.name ? `${id}-${index}-name-error` : undefined} onChange={(event) => update(index, { name: event.currentTarget.value })} disabled={disabled} autoComplete="off" autoCapitalize="none" spellCheck={false} />{error.name && <small id={`${id}-${index}-name-error`}>{error.name}</small>}</label>
|
||||
<label className="cx-provider-header-field"><span>{copy.source}</span><select value={row.source} aria-label={`${copy.source} · ${copy.row(index)}`} aria-invalid={Boolean(error.source)} aria-describedby={error.source ? `${id}-${index}-source-error` : undefined} onChange={(event) => update(index, { source: event.currentTarget.value as ProviderHeaderSource })} disabled={disabled}><option value="static">{copy.literal}</option><option value="env">{copy.env}</option></select>{error.source && <small id={`${id}-${index}-source-error`}>{error.source}</small>}</label>
|
||||
<label className="cx-provider-header-field"><span>{row.source === "env" ? copy.env : copy.value}</span><input value={row.value} placeholder={row.source === "env" ? copy.envPlaceholder : providerHeaderValuePlaceholder(row.name, lang)} aria-label={`${row.source === "env" ? copy.env : copy.value} · ${copy.row(index)}`} aria-invalid={Boolean(error.value)} aria-describedby={error.value ? `${id}-${index}-value-error` : row.source === "env" ? `${id}-env-hint` : undefined} onChange={(event) => update(index, { value: event.currentTarget.value })} disabled={disabled} autoComplete="off" autoCapitalize="none" spellCheck={false} />{error.value && <small id={`${id}-${index}-value-error`}>{error.value}</small>}</label>
|
||||
<button type="button" className="cx-providers-icon-button cx-providers-icon-button--danger cx-provider-header-remove" title={`${copy.remove} · ${copy.row(index)}`} aria-label={`${copy.remove} · ${copy.row(index)}`} disabled={disabled} onClick={() => onChange(removeProviderHeader(rows, index))}><Trash2 size={14} aria-hidden="true" /></button>
|
||||
</div>;
|
||||
})}
|
||||
</div>}
|
||||
<p className="cx-provider-headers-hint" id={`${id}-env-hint`}>{copy.envHint}</p>
|
||||
{rows.some((row) => row.name.trim().toLowerCase() === "authorization") && <p className="cx-provider-headers-hint">{lang === "zh" ? "直连使用 Authorization Header 认证时,请留空 API Key;填写 API Key 会替换原有 Authorization。" : "For direct Authorization header authentication, leave API Key empty. An explicit API Key replaces the existing Authorization header."}</p>}
|
||||
{!validation.valid && <p className="cx-provider-headers-error" role="status">{copy.fix}</p>}
|
||||
</section>;
|
||||
}
|
||||
@@ -11,6 +11,7 @@ function getCopy(lang: Language) {
|
||||
return lang === "zh" ? {
|
||||
title: "模型映射", optional: "可选", subtitle: "让 Codex 的模型菜单显示这个供应商实际提供的模型。",
|
||||
hint: "适用于支持 Responses 接口的模型。保存并启用后,重启 Codex 更新模型菜单。已有会话会保留原来的模型选择。",
|
||||
capabilities: "模型菜单允许文本与图片输入;实际能力由供应商接口决定。Ultra 还需在 Codex 设置中开启「模型选择器滑块中的 Ultra 选项」。",
|
||||
displayName: "菜单显示名称", displayPlaceholder: "留空使用模型 ID", model: "实际模型 ID", modelPlaceholder: "填写供应商提供的模型 ID",
|
||||
context: "上下文窗口", contextPlaceholder: "可选,如 128000", contextHint: "单位为 Token;留空使用默认值,最大 10,000,000。",
|
||||
addCurrent: "添加当前模型", importModels: "导入已获取模型", addRow: "添加空行", remove: "删除映射",
|
||||
@@ -25,6 +26,7 @@ function getCopy(lang: Language) {
|
||||
} : {
|
||||
title: "Model mappings", optional: "Optional", subtitle: "Show this provider’s actual models in the Codex model menu.",
|
||||
hint: "For models that support the Responses API. Save and enable this provider, then restart Codex to update its model menu. Existing conversations keep their selected model.",
|
||||
capabilities: "The menu allows text and image input; actual support depends on the provider API. To show Ultra, also enable the Ultra option in the model picker slider in Codex settings.",
|
||||
displayName: "Menu display name", displayPlaceholder: "Defaults to the model ID", model: "Actual model ID", modelPlaceholder: "Enter the provider’s model ID",
|
||||
context: "Context window", contextPlaceholder: "Optional, e.g. 128000", contextHint: "In tokens. Leave blank for the default; maximum 10,000,000.",
|
||||
addCurrent: "Add current model", importModels: "Import fetched models", addRow: "Add row", remove: "Remove mapping",
|
||||
@@ -136,6 +138,7 @@ export function ProviderModelMappings({ lang, rows, currentModel, availableModel
|
||||
<summary><ListFilter size={17} aria-hidden="true" /><div><strong>{copy.title}<span>{copy.optional}</span></strong><p>{copy.subtitle}</p></div><span className={`cx-provider-mappings-count${!validation.valid ? " cx-provider-mappings-count--invalid" : ""}`} title={copy.limit}>{validation.size} / {MAX_MAPPINGS}</span><ChevronDown size={16} className="cx-provider-mappings-chevron" aria-hidden="true" /></summary>
|
||||
<div className="cx-provider-mappings-body">
|
||||
<p className="cx-provider-mappings-hint">{copy.hint}</p>
|
||||
<p className="cx-provider-mappings-hint">{copy.capabilities}</p>
|
||||
<div className="cx-provider-mappings-toolbar">
|
||||
<button type="button" className="cx-providers-button cx-providers-button--secondary cx-providers-button--small" onClick={() => add(current)} disabled={disabled || !canAddCurrent} title={currentIncluded ? copy.currentExists : !current ? copy.noCurrent : hasInvalidModelId(current) ? copy.invalidDefault : !canAddCurrent ? copy.limit : undefined}><Plus size={14} aria-hidden="true" />{copy.addCurrent}</button>
|
||||
<button type="button" className="cx-providers-button cx-providers-button--secondary cx-providers-button--small" onClick={importModels} disabled={disabled || !canImport} title={!availableModels.length ? copy.fetchFirst : !candidates.length ? copy.allImported : !canImport ? copy.limit : undefined}><Download size={14} aria-hidden="true" />{copy.importModels}</button>
|
||||
|
||||
@@ -95,7 +95,7 @@ function labelHash(value: string) {
|
||||
return `${(first >>> 0).toString(16)}-${(second >>> 0).toString(16)}`;
|
||||
}
|
||||
export function configHealthIssueKey(report: ConfigHealthReport) {
|
||||
return labelHash(JSON.stringify(report.issues.map(({ code, title, description }) => [code, title, description]).sort()));
|
||||
return labelHash(JSON.stringify(report.issues.map(({ code, title, description, key, suggestion, repairable }) => [code, title, description, key, suggestion, repairable]).sort()));
|
||||
}
|
||||
type StorageLike = Pick<Storage, "getItem" | "setItem">;
|
||||
export function createConfigHealthNoticeRegistry(storage?: StorageLike) {
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { ConfigHealthIssue, ConfigHealthReport } from "./configHealthTypes";
|
||||
|
||||
// Fall back for older backend/fixture reports while retaining exact locations
|
||||
// from the diagnostic command. Missing definitions do not have a source line.
|
||||
export function configHealthIssueLocation(issue: ConfigHealthIssue, report: ConfigHealthReport, lang: "zh" | "en") {
|
||||
const zh = lang === "zh";
|
||||
const path = issue.path || `${report.codexDir.replace(/[\\/]$/, "")}/config.toml`;
|
||||
const position = issue.line != null && issue.line > 0
|
||||
? (zh ? `第 ${issue.line} 行${issue.column != null ? `,第 ${issue.column} 列` : ""}`
|
||||
: `line ${issue.line}${issue.column != null ? `, column ${issue.column}` : ""}`)
|
||||
: !issue.key
|
||||
? (zh ? "旧版报告未提供行列,请重新检查" : "location not supplied; check again")
|
||||
: issue.key.startsWith('"<')
|
||||
? (zh ? "文件层面" : "file level")
|
||||
: (zh ? "未定义,尚无对应行" : "not defined; no source line");
|
||||
return { path, position, key: issue.key || (zh ? "配置文件" : "configuration file") };
|
||||
}
|
||||
|
||||
export function primaryConfigHealthIssue(report: ConfigHealthReport) {
|
||||
return (report.canRepair ? report.issues.find((issue) => issue.repairable) : undefined) ?? report.issues[0];
|
||||
}
|
||||
|
||||
export function configHealthRepairUnavailableReason(report: ConfigHealthReport, lang: "zh" | "en") {
|
||||
return (report.issues.find((issue) => issue.code === "config-linked-file")
|
||||
?? report.issues.find((issue) => !issue.repairable))?.suggestion
|
||||
|| (lang === "zh" ? "现有配置无法可靠确定,请按问题中的建议修改后重新检查。" : "The correct settings cannot be determined safely. Follow the issue's suggestion and check again.");
|
||||
}
|
||||
@@ -3,6 +3,11 @@ export type ConfigHealthIssue = {
|
||||
title: string;
|
||||
description: string;
|
||||
repairable: boolean;
|
||||
path: string;
|
||||
line: number | null;
|
||||
column: number | null;
|
||||
key: string;
|
||||
suggestion: string;
|
||||
};
|
||||
|
||||
export type ConfigHealthReport = {
|
||||
|
||||
+339
-95
@@ -1,3 +1,5 @@
|
||||
import { releaseInfoFromFallback, releaseInfoFromCheckFailure } from "./updateCheckFlow";
|
||||
import { providerUpstreamApi, providerRequiresConversion } from "./providerProtocol";
|
||||
import React from "react";
|
||||
import { flushSync } from "react-dom";
|
||||
import ReactDOM from "react-dom/client";
|
||||
@@ -13,6 +15,7 @@ import { OverviewPage } from "./pages/OverviewPage";
|
||||
import { AboutPage, SettingsPage, TomlConfigPage } from "./pages/UtilityPages";
|
||||
import { PromptsPage } from "./pages/PromptsPage";
|
||||
import { SkillsMcpPage, type SkillsMcpNoteKind } from "./pages/SkillsMcpPage";
|
||||
import { useProviderBalances } from "./providerBalance";
|
||||
import { ProvidersPage, type ProviderCopy, type ProviderRow } from "./pages/ProvidersPage";
|
||||
import { AppShell, type AppTab, type AppTheme } from "./components/AppShell";
|
||||
import {
|
||||
@@ -22,12 +25,14 @@ import {
|
||||
} from "./components/AppDialogs";
|
||||
import { PageTransition } from "./components/PageTransition";
|
||||
import { cx } from "./components/ui";
|
||||
import { appUpdater, useAppUpdater } from "./appUpdater";
|
||||
import { appUpdater, isAppUpdateBusy, useAppUpdater } from "./appUpdater";
|
||||
import { providerProfilesMatch, type ProviderProfile } from "./providerProfiles";
|
||||
import { orderProviderRows } from "./providerRowOrder";
|
||||
import { applyProviderRowOrder, orderProviderRows } from "./providerRowOrder";
|
||||
import { createPresetProvider, getProviderPreset, getProviderPresetVariant } from "./providerPresets";
|
||||
import { validateProviderModelMappings } from "./components/ProviderModelMappings";
|
||||
import { createOfficialProfileMonitor } from "./officialProfileMonitor";
|
||||
import { createSessionStatusTracker, providerActivationIsBusy, readCurrentSessionStatus, sessionStatusContextKey } from "./sessionOperationState";
|
||||
import type { LoadingScope, SessionStatusContext } from "./sessionOperationState";
|
||||
import { useConfigHealth } from "./useConfigHealth";
|
||||
import { ConfigHealthPanel, ConfigHealthStatus } from "./components/ConfigHealthPanel";
|
||||
import { ConfigHealthToast } from "./components/ConfigHealthToast";
|
||||
@@ -129,6 +134,7 @@ const defaultProviderForm: SavedProvider = {
|
||||
apiKey: "",
|
||||
tomlConfig: "",
|
||||
wireApi: "responses",
|
||||
upstreamApi: "responses",
|
||||
requiresOpenaiAuth: false,
|
||||
};
|
||||
|
||||
@@ -140,6 +146,7 @@ const blankProviderForm: SavedProvider = {
|
||||
apiKey: "",
|
||||
tomlConfig: "",
|
||||
wireApi: "responses",
|
||||
upstreamApi: "responses",
|
||||
requiresOpenaiAuth: false,
|
||||
};
|
||||
|
||||
@@ -568,7 +575,7 @@ function buildProviderTomlPreview(provider: SavedProvider) {
|
||||
const providerKey = "custom";
|
||||
const baseUrl = provider.baseUrl.trim().replace(/\/+$/, "");
|
||||
if (!model || !name || !baseUrl) return "";
|
||||
const wireApi = provider.wireApi || "responses";
|
||||
const wireApi = "responses";
|
||||
return [
|
||||
`model_provider = "${tomlEscape(providerKey)}"`,
|
||||
`model = "${tomlEscape(model)}"`,
|
||||
@@ -755,6 +762,7 @@ function App() {
|
||||
const [editingPromptId, setEditingPromptId] = React.useState<string | null>(null);
|
||||
const [editingBuiltinPrompt, setEditingBuiltinPrompt] = React.useState<BuiltinPromptDetail | null>(null);
|
||||
const [savedProviders, setSavedProviders] = React.useState<SavedProvider[]>([]);
|
||||
const [providerOrder, setProviderOrder] = React.useState<{ directory: string; order: string[] }>({ directory: "", order: [] });
|
||||
const [officialProfiles, setOfficialProfiles] = React.useState<OfficialProfileSummary[]>([]);
|
||||
const [editingOfficialProfileId, setEditingOfficialProfileId] = React.useState<string | null>(DEFAULT_OFFICIAL_PROFILE_ID);
|
||||
const [creatingProvider, setCreatingProvider] = React.useState(false);
|
||||
@@ -793,8 +801,10 @@ function App() {
|
||||
const [healthConfigDir, setHealthConfigDir] = React.useState("");
|
||||
const [settingsGeneralRequest, setSettingsGeneralRequest] = React.useState(0);
|
||||
const [loading, setLoading] = React.useState(false);
|
||||
const [providerActivationBusy, setProviderActivationBusy] = React.useState(false);
|
||||
const [refreshing, setRefreshing] = React.useState(true);
|
||||
const [toast, setToast] = React.useState<string>("");
|
||||
const [languageRestartNotice, setLanguageRestartNotice] = React.useState<{ configDir: string; message: string } | null>(null);
|
||||
const [error, setError] = React.useState<string>("");
|
||||
const [providerForm, setProviderForm] = React.useState<SavedProvider>(defaultProviderForm);
|
||||
const [providerTomlDraft, setProviderTomlDraft] = React.useState("");
|
||||
@@ -807,7 +817,9 @@ function App() {
|
||||
const [providerModelsLoading, setProviderModelsLoading] = React.useState(false);
|
||||
const [actionBusy, setActionBusy] = React.useState<string>("");
|
||||
const [skillsMcpNoteBusy, setSkillsMcpNoteBusy] = React.useState("");
|
||||
const [restartCodexError, setRestartCodexError] = React.useState("");
|
||||
const [restartCodexBusy, setRestartCodexBusy] = React.useState(false);
|
||||
React.useEffect(() => { setLanguageRestartNotice(null); setRestartCodexError(""); }, [configDir]);
|
||||
const [promptSyncing, setPromptSyncing] = React.useState(false);
|
||||
const [promptDetailLoading, setPromptDetailLoading] = React.useState(false);
|
||||
const [promptCatalogReady, setPromptCatalogReady] = React.useState(false);
|
||||
@@ -836,8 +848,10 @@ function App() {
|
||||
const officialMonitorReadyRef = React.useRef(false);
|
||||
officialMonitorReadyRef.current = Boolean(state) && !refreshing;
|
||||
const savedProvidersRequestRef = React.useRef(0);
|
||||
const providerOrderRequestRef = React.useRef(0);
|
||||
const loadingGenerationRef = React.useRef(0);
|
||||
const loadingTokensRef = React.useRef(new Set<number>());
|
||||
const loadingTokensRef = React.useRef(new Map<number, LoadingScope>());
|
||||
const languageLoadingTokenRef = React.useRef<number | null>(null);
|
||||
const actionBusyGenerationRef = React.useRef(0);
|
||||
const actionBusyTokensRef = React.useRef(new Map<number, string>());
|
||||
const skillsMcpNoteBusyRef = React.useRef("");
|
||||
@@ -848,7 +862,16 @@ function App() {
|
||||
const refreshRequestRef = React.useRef(0);
|
||||
const aboutLoadKeyRef = React.useRef("");
|
||||
const sessionAutoLoadKeyRef = React.useRef("");
|
||||
const sessionLoadRequestRef = React.useRef(0);
|
||||
const sessionStatusTrackerRef = React.useRef(createSessionStatusTracker());
|
||||
const sessionStateRef = React.useRef(state);
|
||||
sessionStateRef.current = state;
|
||||
const providerActivationRevisionRef = React.useRef(0);
|
||||
const providerActivationInFlightRef = React.useRef(0);
|
||||
const sessionMutationInFlightRef = React.useRef(false);
|
||||
const sessionDeleteBusyRef = React.useRef(false);
|
||||
const sessionRefreshPendingRef = React.useRef(false);
|
||||
const sessionSyncToastPendingRef = React.useRef(false);
|
||||
const refreshSyncedSessionStatusRef = React.useRef<() => Promise<SessionSyncStatus | null>>(async () => null);
|
||||
const promptRefreshInFlightRef = React.useRef<Promise<BuiltinPromptStatus[]> | null>(null);
|
||||
const promptAutoRefreshAttemptedRef = React.useRef(false);
|
||||
const promptCatalogReadyRef = React.useRef(false);
|
||||
@@ -879,6 +902,10 @@ function App() {
|
||||
? activeBuiltinTemplateId
|
||||
: "";
|
||||
|
||||
const syncProviderActivationBusy = React.useCallback(() => {
|
||||
setProviderActivationBusy(providerActivationIsBusy(loadingTokensRef.current.values(), actionBusyTokensRef.current.values()));
|
||||
}, []);
|
||||
|
||||
const syncActionBusy = React.useCallback(() => {
|
||||
let latestToken = -1;
|
||||
let latestAction = "";
|
||||
@@ -889,26 +916,39 @@ function App() {
|
||||
}
|
||||
}
|
||||
setActionBusy(latestAction);
|
||||
}, []);
|
||||
syncProviderActivationBusy();
|
||||
}, [syncProviderActivationBusy]);
|
||||
|
||||
const beginLoading = React.useCallback(() => {
|
||||
const beginLoading = React.useCallback((scope: LoadingScope = "general") => {
|
||||
const token = ++loadingGenerationRef.current;
|
||||
loadingTokensRef.current.add(token);
|
||||
loadingTokensRef.current.set(token, scope);
|
||||
setLoading(true);
|
||||
syncProviderActivationBusy();
|
||||
return token;
|
||||
}, []);
|
||||
}, [syncProviderActivationBusy]);
|
||||
|
||||
const endLoading = React.useCallback((token: number) => {
|
||||
if (!loadingTokensRef.current.delete(token)) return;
|
||||
setLoading(loadingTokensRef.current.size > 0);
|
||||
}, []);
|
||||
syncProviderActivationBusy();
|
||||
}, [syncProviderActivationBusy]);
|
||||
|
||||
const beginActionBusy = React.useCallback((action: string) => {
|
||||
const token = ++actionBusyGenerationRef.current;
|
||||
actionBusyTokensRef.current.set(token, action);
|
||||
setActionBusy(action);
|
||||
syncProviderActivationBusy();
|
||||
return token;
|
||||
}, []);
|
||||
}, [syncProviderActivationBusy]);
|
||||
|
||||
const handleLanguageBusyChange = React.useCallback((busy: boolean) => {
|
||||
if (busy && languageLoadingTokenRef.current === null) {
|
||||
languageLoadingTokenRef.current = beginLoading();
|
||||
} else if (!busy && languageLoadingTokenRef.current !== null) {
|
||||
endLoading(languageLoadingTokenRef.current);
|
||||
languageLoadingTokenRef.current = null;
|
||||
}
|
||||
}, [beginLoading, endLoading]);
|
||||
|
||||
const endActionBusy = React.useCallback((token: number) => {
|
||||
if (!actionBusyTokensRef.current.delete(token)) return;
|
||||
@@ -925,6 +965,36 @@ function App() {
|
||||
if (changed) syncActionBusy();
|
||||
}, [syncActionBusy]);
|
||||
|
||||
const invalidateSessionStatus = React.useCallback(() => {
|
||||
sessionStatusTrackerRef.current.invalidate();
|
||||
sessionAutoLoadKeyRef.current = "";
|
||||
setSessionStatus(null);
|
||||
}, []);
|
||||
|
||||
const getSessionStatusContext = React.useCallback((): SessionStatusContext | null => {
|
||||
const current = sessionStateRef.current;
|
||||
if (!current || providerActivationInFlightRef.current) return null;
|
||||
return {
|
||||
configDir: current.codexDir,
|
||||
targetProvider: current.modelProvider || "openai",
|
||||
providerRevision: providerActivationRevisionRef.current,
|
||||
};
|
||||
}, []);
|
||||
|
||||
const loadCurrentSessionStatus = React.useCallback(() => readCurrentSessionStatus(
|
||||
sessionStatusTrackerRef.current,
|
||||
getSessionStatusContext,
|
||||
(context) => invoke<SessionSyncStatus>("get_session_sync_status", {
|
||||
configDir: context.configDir,
|
||||
targetProvider: context.targetProvider,
|
||||
}),
|
||||
(status) => {
|
||||
setSessionStatus(status);
|
||||
const context = getSessionStatusContext();
|
||||
if (context) sessionAutoLoadKeyRef.current = sessionStatusContextKey(context);
|
||||
},
|
||||
), [getSessionStatusContext]);
|
||||
|
||||
const invalidatePromptDetail = React.useCallback(() => {
|
||||
promptDetailRequestRef.current += 1;
|
||||
setPromptDetailLoading(false);
|
||||
@@ -933,10 +1003,24 @@ function App() {
|
||||
savedProvidersRequestRef.current += 1;
|
||||
setSavedProviders(providers);
|
||||
}, []);
|
||||
React.useEffect(() => {
|
||||
const directory = state?.codexDir || "";
|
||||
const request = ++providerOrderRequestRef.current;
|
||||
if (!directory) { setProviderOrder({ directory: "", order: [] }); return; }
|
||||
void invoke<string[]>("get_provider_order", { configDir: directory }).then((order) => {
|
||||
if (request === providerOrderRequestRef.current) setProviderOrder({ directory, order });
|
||||
}).catch((nextError) => {
|
||||
if (request !== providerOrderRequestRef.current) return;
|
||||
setProviderOrder({ directory, order: [] });
|
||||
setError(String(nextError));
|
||||
});
|
||||
}, [state?.codexDir]);
|
||||
const currentInstructionId = instructionIdFromPath(state?.instructionFile, instructionTemplates);
|
||||
const releaseStatusLabel = React.useMemo(() => {
|
||||
if (updater.state.phase === "downloading") return lang === "zh" ? "下载中" : "Downloading";
|
||||
if (updater.state.phase === "installing") return lang === "zh" ? "安装中" : "Installing";
|
||||
if (updater.state.phase === "verifying") return lang === "zh" ? "验证中" : "Verifying";
|
||||
if (updater.state.phase === "preparing") return lang === "zh" ? "准备更新" : "Preparing update";
|
||||
if (updater.state.phase === "installing" || updater.state.phase === "handed-off") return lang === "zh" ? "安装中" : "Installing";
|
||||
if (updater.state.phase === "ready") return lang === "zh" ? "等待重启" : "Restart required";
|
||||
if (releaseInfo.status === "checking") return lang === "zh" ? "检查中" : "Checking";
|
||||
if (releaseInfo.status === "error") return lang === "zh" ? "失败" : "Failed";
|
||||
@@ -1173,10 +1257,11 @@ function App() {
|
||||
const localRows = React.useMemo(() => {
|
||||
return savedProviders.map((p) => ({
|
||||
...p,
|
||||
model: effectiveActiveProviderId === p.id ? state?.model || p.model : p.model,
|
||||
source: "local" as const,
|
||||
isCurrent: effectiveActiveProviderId === p.id,
|
||||
}));
|
||||
}, [effectiveActiveProviderId, savedProviders]);
|
||||
}, [effectiveActiveProviderId, savedProviders, state?.model]);
|
||||
|
||||
const currentOfficialProfileId = state?.isOfficialProvider
|
||||
? state.activeOfficialProfileId || DEFAULT_OFFICIAL_PROFILE_ID
|
||||
@@ -1199,7 +1284,7 @@ function App() {
|
||||
source: "official",
|
||||
providerName: profile.providerName,
|
||||
baseUrl: "https://chatgpt.com/codex",
|
||||
model: profile.model || "official",
|
||||
model: profile.id === currentOfficialProfileId ? profile.model || state?.model || "" : profile.model || "",
|
||||
apiKey: "",
|
||||
wireApi: "official",
|
||||
requiresOpenaiAuth: true,
|
||||
@@ -1212,7 +1297,7 @@ function App() {
|
||||
});
|
||||
const rows = orderProviderRows(officialRow(defaultProfile), detectedRows, localRows);
|
||||
return [rows[0], ...officialProfiles.filter((profile) => !profile.isDefault).map(officialRow), ...rows.slice(1)];
|
||||
}, [currentOfficialProfileId, detectedRows, lang, localRows, officialProfiles, state?.officialAuthAvailable]);
|
||||
}, [currentOfficialProfileId, detectedRows, lang, localRows, officialProfiles, state?.officialAuthAvailable, state?.model]);
|
||||
|
||||
const findLocalProviderForRow = React.useCallback((row: ProviderRow) => {
|
||||
if (row.source === "official") return undefined;
|
||||
@@ -1239,7 +1324,8 @@ function App() {
|
||||
};
|
||||
}, [findLocalProviderForRow, state?.configText]);
|
||||
|
||||
const providerPageRows = React.useMemo<ProviderRow[]>(() => providerRows.map((row) => {
|
||||
const providerPageRows = React.useMemo<ProviderRow[]>(() => applyProviderRowOrder(providerRows,
|
||||
providerOrder.directory === state?.codexDir ? providerOrder.order : []).map((row) => {
|
||||
const local = findLocalProviderForRow(row);
|
||||
return {
|
||||
id: row.id,
|
||||
@@ -1247,8 +1333,10 @@ function App() {
|
||||
providerName: row.providerName,
|
||||
baseUrl: row.baseUrl,
|
||||
model: row.model,
|
||||
modelDisplayName: local?.modelMappings?.find((mapping) => mapping.model === row.model)?.displayName,
|
||||
apiKey: row.apiKey,
|
||||
wireApi: row.wireApi,
|
||||
upstreamApi: local?.upstreamApi || row.upstreamApi,
|
||||
requiresOpenaiAuth: row.requiresOpenaiAuth,
|
||||
isCurrent: row.isCurrent,
|
||||
isDefaultOfficial: row.isDefaultOfficial,
|
||||
@@ -1264,7 +1352,39 @@ function App() {
|
||||
testable: row.source !== "official",
|
||||
testingKey: `${row.source}-${row.id}`,
|
||||
};
|
||||
}), [findLocalProviderForRow, lang, providerCopySourceForRow, providerRows]);
|
||||
}), [findLocalProviderForRow, lang, providerCopySourceForRow, providerRows, providerOrder, state?.codexDir]);
|
||||
|
||||
const balanceRevision = React.useMemo(() => JSON.stringify([
|
||||
providerRows.filter(row => row.source !== "official").map(row => [row.source, row.id, row.baseUrl, row.apiKey]),
|
||||
savedProviders.map(provider => [provider.id, provider.tomlConfig]),
|
||||
state?.configText,
|
||||
]), [providerRows, savedProviders, state?.configText]);
|
||||
const providerBalances = useProviderBalances(state?.codexDir || configDir, balanceRevision, Boolean(state) && !refreshing);
|
||||
|
||||
const saveProviderOrder = async (order: string[]): Promise<boolean> => {
|
||||
const directory = state?.codexDir;
|
||||
if (!directory || providerOrder.directory !== directory || loadingTokensRef.current.size || actionBusyTokensRef.current.size) return false;
|
||||
const previous = providerOrder;
|
||||
const request = ++providerOrderRequestRef.current;
|
||||
const actionToken = beginActionBusy("reorderProviders");
|
||||
setProviderOrder({ directory, order });
|
||||
try {
|
||||
const saved = await invoke<string[]>("save_provider_order", { configDir: directory, order });
|
||||
if (request === providerOrderRequestRef.current && normalizedConfigDirForComparison(directory) === activeConfigDirKeyRef.current) {
|
||||
setProviderOrder({ directory, order: saved });
|
||||
setToast(lang === "zh" ? "供应商顺序已保存" : "Provider order saved");
|
||||
}
|
||||
return true;
|
||||
} catch (nextError) {
|
||||
if (request === providerOrderRequestRef.current && normalizedConfigDirForComparison(directory) === activeConfigDirKeyRef.current) {
|
||||
setProviderOrder(previous);
|
||||
setError(String(nextError));
|
||||
}
|
||||
return false;
|
||||
} finally {
|
||||
endActionBusy(actionToken);
|
||||
}
|
||||
};
|
||||
|
||||
const visibleSessions = React.useMemo(
|
||||
() => (sessionStatus?.sessions || []).filter((item) => showInternalSessions || !item.isSubagent),
|
||||
@@ -1340,6 +1460,7 @@ function App() {
|
||||
}, [beginLoading, endLoading]);
|
||||
|
||||
const refresh = React.useCallback((includeDiagnostics: boolean) => {
|
||||
if (Array.from(actionBusyTokensRef.current.values()).includes("reorderProviders")) return;
|
||||
invalidatePromptDetail();
|
||||
const requestId = ++refreshRequestRef.current;
|
||||
const profilesRequestId = ++officialProfilesRequestRef.current;
|
||||
@@ -1355,6 +1476,7 @@ function App() {
|
||||
const activeCodexDir = state?.codexDir || configDir;
|
||||
setRefreshing(true);
|
||||
setError("");
|
||||
sessionStateRef.current = null;
|
||||
setState(null);
|
||||
setOfficialProfiles([]);
|
||||
setSessionStatus(null);
|
||||
@@ -1364,7 +1486,7 @@ function App() {
|
||||
setAboutInfo(null);
|
||||
aboutLoadKeyRef.current = "";
|
||||
sessionAutoLoadKeyRef.current = "";
|
||||
sessionLoadRequestRef.current += 1;
|
||||
sessionStatusTrackerRef.current.invalidate();
|
||||
|
||||
if (includeDiagnostics) {
|
||||
setStartupDiagnostics(null);
|
||||
@@ -1387,7 +1509,16 @@ function App() {
|
||||
setStartupDiagnosticsLoading(false);
|
||||
}
|
||||
|
||||
void invoke<CodexState>("get_codex_state", { configDir: resolvedConfigDir })
|
||||
void invoke<{ changed: boolean }>("repair_provider_model_catalog", { configDir: resolvedConfigDir })
|
||||
.then((repair) => {
|
||||
if (repair.changed && requestId === refreshRequestRef.current) {
|
||||
setToast(lang === "zh" ? "已修复第三方模型的图片输入能力,请重启 Codex 加载新菜单" : "Third-party model image input repaired. Restart Codex to reload the model menu.");
|
||||
}
|
||||
})
|
||||
.catch((repairError) => {
|
||||
if (requestId === refreshRequestRef.current) setError(String(repairError));
|
||||
})
|
||||
.then(() => invoke<CodexState>("get_codex_state", { configDir: resolvedConfigDir }))
|
||||
.then((next) => {
|
||||
if (requestId !== refreshRequestRef.current) return;
|
||||
if (normalizedConfigDirForComparison(next.codexDir)
|
||||
@@ -1409,6 +1540,7 @@ function App() {
|
||||
setConfigDir(next.codexDir);
|
||||
setHealthConfigDir(next.codexDir);
|
||||
setConfigDirDraft(next.codexDir);
|
||||
sessionStateRef.current = next;
|
||||
setState(next);
|
||||
setRefreshing(false);
|
||||
|
||||
@@ -1435,7 +1567,7 @@ function App() {
|
||||
setRefreshing(false);
|
||||
setError(String(nextError));
|
||||
});
|
||||
}, [clearActionBusy, configDir, configDirDraft, invalidatePromptDetail, state?.codexDir]);
|
||||
}, [clearActionBusy, configDir, configDirDraft, invalidatePromptDetail, lang, state?.codexDir]);
|
||||
|
||||
// Independent of get_codex_state: this must still work when a broken TOML
|
||||
// prevents the normal app state from loading. No shared loading flags change.
|
||||
@@ -1619,10 +1751,9 @@ function App() {
|
||||
const handleActionResult = (result: ActionResult) => {
|
||||
const profilesRequestId = ++officialProfilesRequestRef.current;
|
||||
const providersRequestId = ++savedProvidersRequestRef.current;
|
||||
sessionStateRef.current = result.state;
|
||||
setState(result.state);
|
||||
setSessionStatus(null);
|
||||
sessionAutoLoadKeyRef.current = "";
|
||||
sessionLoadRequestRef.current += 1;
|
||||
invalidateSessionStatus();
|
||||
setToast(result.message);
|
||||
return Promise.allSettled([
|
||||
invoke<SavedPrompt[]>("list_saved_prompts"),
|
||||
@@ -1856,7 +1987,8 @@ function App() {
|
||||
model: providerForm.model.trim(),
|
||||
apiKey: (providerForm.apiKey || "").trim(),
|
||||
tomlConfig: tomlConfig.trimEnd(),
|
||||
wireApi: providerForm.wireApi || "responses",
|
||||
wireApi: "responses",
|
||||
upstreamApi: providerUpstreamApi(providerForm),
|
||||
requiresOpenaiAuth: providerForm.requiresOpenaiAuth,
|
||||
});
|
||||
|
||||
@@ -1864,6 +1996,9 @@ function App() {
|
||||
if (savedProviders.some((saved) => saved.id === provider.id)) {
|
||||
return invoke<ActionResult>("activate_saved_provider", { configDir: configDir || null, providerId: provider.id });
|
||||
}
|
||||
if (providerRequiresConversion(provider)) {
|
||||
return Promise.reject(lang === "zh" ? "请先保存供应商,并在设置中开启本地路由和配置接管后启用。" : "Save this provider and enable the local router with config takeover in Settings before activating it.");
|
||||
}
|
||||
const tomlConfig = provider.tomlConfig?.trim();
|
||||
if (tomlConfig) {
|
||||
return invoke<ActionResult>("save_provider_toml_config", {
|
||||
@@ -1946,8 +2081,25 @@ function App() {
|
||||
);
|
||||
};
|
||||
|
||||
const activateProvider = async (apply: () => Promise<ActionResult>, success: (result: ActionResult) => void) => {
|
||||
if (!getSessionStatusContext() || providerActivationInFlightRef.current || sessionDeleteBusyRef.current
|
||||
|| providerActivationIsBusy(loadingTokensRef.current.values(), actionBusyTokensRef.current.values())) return;
|
||||
providerActivationInFlightRef.current += 1;
|
||||
providerActivationRevisionRef.current += 1;
|
||||
if (Array.from(actionBusyTokensRef.current.values()).includes("syncSessions")) sessionRefreshPendingRef.current = true;
|
||||
invalidateSessionStatus();
|
||||
try {
|
||||
await call(apply, success);
|
||||
} finally {
|
||||
providerActivationInFlightRef.current -= 1;
|
||||
if (sessionRefreshPendingRef.current && !sessionMutationInFlightRef.current) {
|
||||
await refreshSyncedSessionStatusRef.current();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const switchProvider = (provider: SavedProvider) =>
|
||||
call(
|
||||
activateProvider(
|
||||
() => applyProviderConfig(provider),
|
||||
(result) => {
|
||||
localStorage.setItem(ACTIVE_PROVIDER_KEY, provider.id);
|
||||
@@ -1968,9 +2120,9 @@ function App() {
|
||||
const fetchProviderModels = async () => {
|
||||
const baseUrl = providerForm.baseUrl.trim();
|
||||
const apiKey = (providerForm.apiKey || "").trim();
|
||||
if (!baseUrl || !apiKey) {
|
||||
if (!baseUrl) {
|
||||
setError("");
|
||||
setToast(lang === "zh" ? "请先填写 API 请求地址和 API Key" : "Enter the API URL and API key first");
|
||||
setToast(lang === "zh" ? "请先填写 API 请求地址;认证可使用 API Key 或供应商 Headers" : "Enter the API URL first. Authentication can use an API key or provider headers");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1980,7 +2132,7 @@ function App() {
|
||||
setError("");
|
||||
setToast(lang === "zh" ? "正在获取模型列表..." : "Fetching model list...");
|
||||
try {
|
||||
const result = await invoke<ProviderModelsResult>("fetch_provider_models", { baseUrl, apiKey });
|
||||
const result = await invoke<ProviderModelsResult>("fetch_provider_models", { baseUrl, apiKey, upstreamApi: providerUpstreamApi(providerForm), configText: providerTomlDraft });
|
||||
if (providerModelsRequestRef.current !== requestId) return;
|
||||
setAvailableProviderModels(result.models);
|
||||
setToast(result.models.length > 0
|
||||
@@ -1995,13 +2147,13 @@ function App() {
|
||||
}
|
||||
};
|
||||
|
||||
const testProvider = async (id: string, baseUrl: string, apiKey?: string | null) => {
|
||||
const testProvider = async (id: string, baseUrl: string, apiKey?: string | null, provider?: SavedProvider) => {
|
||||
const actionToken = beginActionBusy("testProvider");
|
||||
setProviderTestingId(id);
|
||||
setError("");
|
||||
setToast(lang === "zh" ? "正在检测连接..." : "Testing connection...");
|
||||
try {
|
||||
const result = await invoke<ProviderConnectionResult>("test_provider_connection", { baseUrl, apiKey: apiKey || null });
|
||||
const result = await invoke<ProviderConnectionResult>("test_provider_connection", { baseUrl, apiKey: apiKey || null, upstreamApi: provider ? providerUpstreamApi(provider) : "responses", configText: provider?.tomlConfig || null });
|
||||
if (result.ok) {
|
||||
setToast(lang === "zh" ? `连接成功,响应延迟 ${result.durationMs}ms` : `Connected, ${result.durationMs}ms latency`);
|
||||
} else {
|
||||
@@ -2020,7 +2172,7 @@ function App() {
|
||||
const saveProviderConfig = saveProviderOnly;
|
||||
|
||||
const switchOfficialProvider = (profileId = DEFAULT_OFFICIAL_PROFILE_ID) =>
|
||||
call(
|
||||
activateProvider(
|
||||
() => invoke<ActionResult>("switch_official_profile", { configDir: configDir || null, profileId }),
|
||||
(result) => {
|
||||
localStorage.removeItem(ACTIVE_PROVIDER_KEY);
|
||||
@@ -2125,9 +2277,11 @@ function App() {
|
||||
|
||||
const checkForUpdates = React.useCallback(async ({ quiet = false }: { quiet?: boolean } = {}) => {
|
||||
setReleaseInfo({ status: "checking" });
|
||||
let nativeCheckAttempted = false;
|
||||
try {
|
||||
if (aboutInfo?.nativeUpdaterSupported !== false) {
|
||||
const updaterResult = await appUpdater.check({ force: !quiet, timeout: 15_000 });
|
||||
nativeCheckAttempted = true;
|
||||
const updaterResult = await appUpdater.check({ force: !quiet, timeout: 30_000 });
|
||||
if (updaterResult === "available") {
|
||||
const snapshot = appUpdater.getSnapshot();
|
||||
const latestVersion = snapshot.latestVersion || "";
|
||||
@@ -2153,25 +2307,27 @@ function App() {
|
||||
latestVersion: aboutInfo?.appVersion,
|
||||
htmlUrl: `https://github.com/${FALLBACK_GITHUB_REPO}/releases/latest`,
|
||||
hasUpdate: false,
|
||||
updateMethod: "native",
|
||||
});
|
||||
if (!quiet) setToast(lang === "zh" ? "当前已是最新版本" : "You are up to date");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Keep the existing lightweight release check as a manual-download fallback for
|
||||
// bootstrap and portable builds that cannot use the native updater yet.
|
||||
// Metadata is useful even when the native channel is unavailable. It
|
||||
// cannot supply an updater RID or replace the signed installation check.
|
||||
const update = await invoke<AppUpdateInfo>("check_app_update");
|
||||
const message = update.hasUpdate
|
||||
? (lang === "zh" ? "发现新版本" : "Update available")
|
||||
: (lang === "zh" ? "当前已是最新版本" : "You are up to date");
|
||||
setReleaseInfo({
|
||||
status: "ok",
|
||||
latestVersion: update.latestVersion,
|
||||
htmlUrl: update.htmlUrl,
|
||||
hasUpdate: update.hasUpdate,
|
||||
updateMethod: update.hasUpdate ? "download" : undefined,
|
||||
});
|
||||
setReleaseInfo(releaseInfoFromFallback(update, nativeCheckAttempted));
|
||||
if (nativeCheckAttempted) {
|
||||
if (quiet && update.hasUpdate) {
|
||||
setToast(lang === "zh"
|
||||
? `发现新版本 ${update.latestVersion},但在线更新检查失败,可重新检查`
|
||||
: `Version ${update.latestVersion} is available, but the in-app update check failed. Retry the check`);
|
||||
} else if (!quiet) {
|
||||
setUpdatePromptOpen(true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (update.hasUpdate) {
|
||||
if (quiet) {
|
||||
setToast(lang === "zh" ? `发现新版本 ${update.latestVersion},可在概览页查看` : `New version ${update.latestVersion} is available`);
|
||||
@@ -2179,14 +2335,15 @@ function App() {
|
||||
setUpdatePromptOpen(true);
|
||||
}
|
||||
} else if (!quiet) {
|
||||
setToast(message);
|
||||
setToast(lang === "zh" ? "当前已是最新版本" : "You are up to date");
|
||||
}
|
||||
} catch {
|
||||
const message = quiet ? (lang === "zh" ? "自动检查失败" : "Auto check failed") : (lang === "zh" ? "检查失败" : "Check failed");
|
||||
setReleaseInfo({
|
||||
status: "error",
|
||||
});
|
||||
if (!quiet) setToast(message);
|
||||
setReleaseInfo(releaseInfoFromCheckFailure(nativeCheckAttempted));
|
||||
if (!quiet && nativeCheckAttempted) {
|
||||
setUpdatePromptOpen(true);
|
||||
} else if (!quiet) {
|
||||
setToast(lang === "zh" ? "检查失败" : "Check failed");
|
||||
}
|
||||
}
|
||||
}, [aboutInfo?.appVersion, aboutInfo?.nativeUpdaterSupported, lang]);
|
||||
|
||||
@@ -2372,19 +2529,22 @@ function App() {
|
||||
};
|
||||
|
||||
const restartCodexDesktop = async () => {
|
||||
if (restartCodexBusyRef.current) return false;
|
||||
if (restartCodexBusyRef.current || loadingTokensRef.current.size || actionBusyTokensRef.current.size) return false;
|
||||
restartCodexBusyRef.current = true;
|
||||
setRestartCodexBusy(true);
|
||||
const actionToken = beginActionBusy("restartCodexDesktop");
|
||||
setError("");
|
||||
setRestartCodexError("");
|
||||
try {
|
||||
const result = await invoke<CodexDesktopRestartResult>("restart_codex_desktop");
|
||||
const result = await invoke<CodexDesktopRestartResult>("restart_codex_desktop", { configDir });
|
||||
setLanguageRestartNotice(null);
|
||||
setToast(result.wasRunning
|
||||
? (lang === "zh" ? `${result.appName} 已重新启动` : `${result.appName} restarted`)
|
||||
: (lang === "zh" ? `${result.appName} 已启动` : `${result.appName} started`));
|
||||
return true;
|
||||
} catch (e) {
|
||||
setError(String(e));
|
||||
setRestartCodexError(String(e));
|
||||
return false;
|
||||
} finally {
|
||||
endActionBusy(actionToken);
|
||||
@@ -2595,7 +2755,8 @@ function App() {
|
||||
const newCustomProviderForm = (configText = providerCreationBase): SavedProvider => ({
|
||||
...blankProviderForm,
|
||||
model: state?.model?.trim() || blankProviderForm.model,
|
||||
wireApi: currentProvider?.wireApi?.trim() || blankProviderForm.wireApi,
|
||||
wireApi: "responses",
|
||||
upstreamApi: providerUpstreamApi(currentProvider || blankProviderForm),
|
||||
requiresOpenaiAuth: currentProvider?.requiresOpenaiAuth ?? blankProviderForm.requiresOpenaiAuth,
|
||||
tomlConfig: configText.trim(),
|
||||
});
|
||||
@@ -2717,7 +2878,8 @@ function App() {
|
||||
model: provider.model,
|
||||
apiKey: provider.apiKey || "",
|
||||
tomlConfig: state?.configText?.trim() || "",
|
||||
wireApi: provider.wireApi || "responses",
|
||||
wireApi: "responses",
|
||||
upstreamApi: providerUpstreamApi(provider),
|
||||
requiresOpenaiAuth: provider.requiresOpenaiAuth,
|
||||
};
|
||||
setProviderForm(next);
|
||||
@@ -2775,13 +2937,14 @@ function App() {
|
||||
};
|
||||
|
||||
const checkSessions = async () => {
|
||||
sessionLoadRequestRef.current += 1;
|
||||
if (!getSessionStatusContext() || loadingTokensRef.current.size || actionBusyTokensRef.current.size || sessionDeleteBusyRef.current) return;
|
||||
sessionStatusTrackerRef.current.invalidate();
|
||||
const actionToken = beginActionBusy("checkSessions");
|
||||
setSessionStatus(null);
|
||||
await call(
|
||||
() => invoke<SessionSyncStatus>("get_session_sync_status", { configDir: configDir || null, targetProvider: null }),
|
||||
loadCurrentSessionStatus,
|
||||
(status) => {
|
||||
setSessionStatus(status);
|
||||
if (!status) return;
|
||||
if (!status.scanComplete) {
|
||||
setToast(status.scanFailures[0] || (lang === "zh" ? "无法确认会话同步状态" : "Unable to verify session sync status"));
|
||||
return;
|
||||
@@ -2797,52 +2960,90 @@ function App() {
|
||||
};
|
||||
|
||||
React.useEffect(() => {
|
||||
if (tab !== "sessions" || refreshing || !state?.codexDir) return;
|
||||
const loadKey = state.codexDir;
|
||||
if (tab !== "sessions" || refreshing || loading) return;
|
||||
const context = getSessionStatusContext();
|
||||
if (!context) return;
|
||||
const loadKey = sessionStatusContextKey(context);
|
||||
if (sessionAutoLoadKeyRef.current === loadKey) return;
|
||||
const requestId = ++sessionLoadRequestRef.current;
|
||||
const actionToken = beginActionBusy("checkSessions");
|
||||
sessionAutoLoadKeyRef.current = loadKey;
|
||||
void invoke<SessionSyncStatus>("get_session_sync_status", {
|
||||
configDir: loadKey,
|
||||
targetProvider: null,
|
||||
})
|
||||
.then((status) => {
|
||||
if (requestId === sessionLoadRequestRef.current) setSessionStatus(status);
|
||||
})
|
||||
void loadCurrentSessionStatus()
|
||||
.catch((sessionError) => {
|
||||
if (requestId !== sessionLoadRequestRef.current) return;
|
||||
sessionAutoLoadKeyRef.current = "";
|
||||
setError(String(sessionError));
|
||||
})
|
||||
.finally(() => {
|
||||
endActionBusy(actionToken);
|
||||
});
|
||||
}, [beginActionBusy, endActionBusy, refreshing, state?.codexDir, tab]);
|
||||
}, [beginActionBusy, endActionBusy, getSessionStatusContext, loadCurrentSessionStatus, loading, refreshing, state?.codexDir, state?.modelProvider, state?.activeSavedProviderId, state?.activeOfficialProfileId, tab]);
|
||||
|
||||
const syncSessions = async () => {
|
||||
sessionLoadRequestRef.current += 1;
|
||||
const refreshSyncedSessionStatus = async () => {
|
||||
if (sessionMutationInFlightRef.current || !getSessionStatusContext()) {
|
||||
sessionRefreshPendingRef.current = true;
|
||||
return null;
|
||||
}
|
||||
sessionRefreshPendingRef.current = false;
|
||||
const loadingToken = beginLoading("sessionSync");
|
||||
const actionToken = beginActionBusy("syncSessions");
|
||||
await call(
|
||||
() => invoke<SessionSyncResult>("sync_sessions_provider", { configDir: configDir || null, targetProvider: null }),
|
||||
(result) => {
|
||||
setSessionStatus(result.status);
|
||||
setSelectedSessionIds([]);
|
||||
if (!result.status.scanComplete) {
|
||||
setToast(result.status.scanFailures[0] || (lang === "zh" ? "无法确认会话同步状态" : "Unable to verify session sync status"));
|
||||
} else if (result.status.needsSync) {
|
||||
const remaining = sessionMismatchCount(result.status);
|
||||
try {
|
||||
const status = await loadCurrentSessionStatus();
|
||||
if (status && sessionSyncToastPendingRef.current) {
|
||||
sessionSyncToastPendingRef.current = false;
|
||||
if (!status.scanComplete) {
|
||||
setToast(status.scanFailures[0] || (lang === "zh" ? "无法确认会话同步状态" : "Unable to verify session sync status"));
|
||||
} else if (status.needsSync) {
|
||||
const remaining = sessionMismatchCount(status);
|
||||
setToast(lang === "zh"
|
||||
? `已同步可写的会话索引,仍有 ${remaining} 条需要重试;聊天内容未改动`
|
||||
: `Writable session indexes were synced; ${remaining} still need retrying. Chat content was not changed.`);
|
||||
? `本轮同步已完成,当前供应商仍有 ${remaining} 条会话需要同步;聊天内容未改动`
|
||||
: `This sync finished; ${remaining} session(s) still need syncing for the current provider. Chat content was not changed.`);
|
||||
} else {
|
||||
setToast(lang === "zh"
|
||||
? "会话索引已全部同步,聊天内容未改动"
|
||||
: "All session indexes are synced. Chat content was not changed.");
|
||||
}
|
||||
},
|
||||
);
|
||||
endActionBusy(actionToken);
|
||||
}
|
||||
return status;
|
||||
} catch (sessionError) {
|
||||
sessionSyncToastPendingRef.current = false;
|
||||
setError(String(sessionError));
|
||||
return null;
|
||||
} finally {
|
||||
endLoading(loadingToken);
|
||||
endActionBusy(actionToken);
|
||||
}
|
||||
};
|
||||
refreshSyncedSessionStatusRef.current = refreshSyncedSessionStatus;
|
||||
|
||||
const syncSessions = async () => {
|
||||
const context = getSessionStatusContext();
|
||||
if (!context || loadingTokensRef.current.size || actionBusyTokensRef.current.size || sessionDeleteBusyRef.current) return;
|
||||
// Capture primitives at the click, before the IPC worker can be queued
|
||||
// behind a provider switch. The backend keeps this target for the whole job.
|
||||
const target = { ...context };
|
||||
sessionStatusTrackerRef.current.invalidate();
|
||||
const actionToken = beginActionBusy("syncSessions");
|
||||
const loadingToken = beginLoading("sessionSync");
|
||||
sessionMutationInFlightRef.current = true;
|
||||
sessionSyncToastPendingRef.current = false;
|
||||
setError("");
|
||||
try {
|
||||
await invoke<SessionSyncResult>("sync_sessions_provider", {
|
||||
configDir: target.configDir,
|
||||
targetProvider: target.targetProvider,
|
||||
});
|
||||
setSelectedSessionIds([]);
|
||||
sessionSyncToastPendingRef.current = true;
|
||||
} catch (syncError) {
|
||||
if (target.configDir === sessionStateRef.current?.codexDir) setError(String(syncError));
|
||||
} finally {
|
||||
sessionMutationInFlightRef.current = false;
|
||||
sessionRefreshPendingRef.current = true;
|
||||
// Never apply the old job's status to a newly active provider. Re-read
|
||||
// the current context, or let the in-flight activation do so on completion.
|
||||
await refreshSyncedSessionStatusRef.current();
|
||||
endLoading(loadingToken);
|
||||
endActionBusy(actionToken);
|
||||
}
|
||||
};
|
||||
|
||||
const toggleSessionSelected = (id: string) => {
|
||||
@@ -2867,7 +3068,10 @@ function App() {
|
||||
};
|
||||
|
||||
const deleteSelectedSessions = async () => {
|
||||
if (!selectedSessionIds.length || sessionDeleteBusy || !sessionDeleteSafetyConfirmed) return;
|
||||
if (!selectedSessionIds.length || sessionDeleteBusyRef.current || !sessionDeleteSafetyConfirmed
|
||||
|| loadingTokensRef.current.size || actionBusyTokensRef.current.size) return;
|
||||
sessionDeleteBusyRef.current = true;
|
||||
const loadingToken = beginLoading();
|
||||
setSessionDeleteBusy(true);
|
||||
setToast("");
|
||||
setError("");
|
||||
@@ -2896,7 +3100,9 @@ function App() {
|
||||
} catch (e) {
|
||||
setError(String(e));
|
||||
} finally {
|
||||
sessionDeleteBusyRef.current = false;
|
||||
setSessionDeleteBusy(false);
|
||||
endLoading(loadingToken);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -2955,8 +3161,18 @@ function App() {
|
||||
message={toast}
|
||||
error={error}
|
||||
loading={Boolean(providerTestingId || providerModelsLoading) && Boolean(toast)}
|
||||
onDismissMessage={() => setToast("")}
|
||||
onDismissError={() => setError("")}
|
||||
persistent={Boolean(error) && error === restartCodexError}
|
||||
action={error && error === restartCodexError ? {
|
||||
label: lang === "zh" ? "重试" : "Retry",
|
||||
onClick: () => { void restartCodexDesktop(); },
|
||||
disabled: restartCodexBusy || loading || Boolean(actionBusy),
|
||||
} : !error && languageRestartNotice?.configDir === configDir && languageRestartNotice.message === toast ? {
|
||||
label: lang === "zh" ? "点我重启" : "Restart now",
|
||||
onClick: () => { void restartCodexDesktop(); },
|
||||
disabled: restartCodexBusy || loading || Boolean(actionBusy),
|
||||
} : undefined}
|
||||
onDismissMessage={() => { setToast(""); setLanguageRestartNotice(null); }}
|
||||
onDismissError={() => { setError(""); setRestartCodexError(""); }}
|
||||
/>
|
||||
{configHealth.noticeVisible && configHealth.notice && <ConfigHealthToast
|
||||
lang={lang}
|
||||
@@ -2979,7 +3195,10 @@ function App() {
|
||||
latestVersion={releaseInfo.latestVersion}
|
||||
onClose={() => setUpdatePromptOpen(false)}
|
||||
onUpdate={releaseInfo.updateMethod === "native" ? updater.downloadAndInstall : undefined}
|
||||
onRetry={releaseInfo.updateMethod === "native" ? updater.retry : undefined}
|
||||
onRetry={releaseInfo.updateMethod === "native" ? async () => {
|
||||
if (updater.state.failure === "check") await checkForUpdates();
|
||||
else await updater.retry();
|
||||
} : undefined}
|
||||
onRestart={releaseInfo.updateMethod === "native" ? updater.restart : undefined}
|
||||
onDownload={() => {
|
||||
setUpdatePromptOpen(false);
|
||||
@@ -3041,7 +3260,7 @@ function App() {
|
||||
? `${state.agentsPath} (${lang === "zh" ? "追加模式" : "append"})`
|
||||
: state.instructionFile)
|
||||
: null}
|
||||
loading={loading || refreshing}
|
||||
loading={loading || refreshing || actionBusy === "reorderProviders"}
|
||||
hasUpdate={Boolean(releaseInfo.status === "ok" && releaseInfo.hasUpdate)}
|
||||
latestVersion={releaseInfo.latestVersion}
|
||||
onConfigDirChange={setConfigDirDraft}
|
||||
@@ -3063,17 +3282,22 @@ function App() {
|
||||
officialProfileIsDefault={editingOfficialProfileId === DEFAULT_OFFICIAL_PROFILE_ID}
|
||||
canLoadCurrentOfficial={Boolean(state.isOfficialProvider)}
|
||||
providerRows={providerPageRows}
|
||||
providerBalances={providerBalances}
|
||||
configDir={configDir}
|
||||
loading={loading}
|
||||
testingId={providerTestingId}
|
||||
actionBusy={actionBusy}
|
||||
activationBusy={providerActivationBusy || refreshing || sessionDeleteBusy}
|
||||
orderBusy={providerOrder.directory !== state.codexDir}
|
||||
onReorderProviders={saveProviderOrder}
|
||||
editingProviderId={editingProviderId || (editingDetectedProvider ? providerForm.id : null)}
|
||||
providerForm={{
|
||||
apiKey: providerForm.apiKey || "",
|
||||
baseUrl: providerForm.baseUrl,
|
||||
providerName: providerForm.providerName,
|
||||
model: providerForm.model,
|
||||
wireApi: providerForm.wireApi,
|
||||
wireApi: "responses",
|
||||
upstreamApi: providerUpstreamApi(providerForm),
|
||||
requiresOpenaiAuth: providerForm.requiresOpenaiAuth,
|
||||
}}
|
||||
officialForm={officialForm}
|
||||
@@ -3114,7 +3338,7 @@ function App() {
|
||||
}}
|
||||
onTestProvider={(row) => {
|
||||
const local = findLocalProviderForRow(row);
|
||||
void testProvider(row.testingKey || `${row.source}-${row.id}`, row.baseUrl, local?.apiKey || row.apiKey || null);
|
||||
void testProvider(row.testingKey || `${row.source}-${row.id}`, row.baseUrl, local?.apiKey || row.apiKey || null, local);
|
||||
}}
|
||||
onEditProvider={(row) => {
|
||||
if (row.source === "official") {
|
||||
@@ -3170,7 +3394,10 @@ function App() {
|
||||
}))}
|
||||
onProviderModelChange={(value) => setProviderForm((current) => ({ ...current, model: value }))}
|
||||
onFetchModels={() => void fetchProviderModels()}
|
||||
onWireApiChange={(value) => setProviderForm((current) => ({ ...current, wireApi: value }))}
|
||||
onUpstreamApiChange={(value) => {
|
||||
resetAvailableProviderModels();
|
||||
setProviderForm((current) => ({ ...current, upstreamApi: value, wireApi: "responses" }));
|
||||
}}
|
||||
onRequiresAuthChange={(value) => setProviderForm((current) => ({ ...current, requiresOpenaiAuth: value }))}
|
||||
onToggleApiKeyVisibility={() => setProviderApiKeyVisible((value) => !value)}
|
||||
onProviderTomlDraftChange={(value, origin = "manual") => {
|
||||
@@ -3179,6 +3406,11 @@ function App() {
|
||||
setProviderTomlDirty(true);
|
||||
if (origin === "manual") setProviderCommonConfigDirty(true);
|
||||
}}
|
||||
onProviderHeadersConfigChange={(value) => {
|
||||
providerDraftRequestRef.current += 1;
|
||||
setProviderTomlDraft(value);
|
||||
setProviderForm((current) => ({ ...current, tomlConfig: value }));
|
||||
}}
|
||||
onResetProviderToml={() => {
|
||||
providerDraftRequestRef.current += 1;
|
||||
setProviderTomlDraft(
|
||||
@@ -3390,8 +3622,7 @@ function App() {
|
||||
? "success"
|
||||
: "neutral",
|
||||
checking: releaseInfo.status === "checking"
|
||||
|| updater.state.phase === "downloading"
|
||||
|| updater.state.phase === "installing",
|
||||
|| isAppUpdateBusy(updater.state.phase),
|
||||
canOpenReleases: Boolean(releaseInfo.htmlUrl),
|
||||
}}
|
||||
onOpenProject={() => openExternalUrl(aboutInfo?.projectUrl || `https://github.com/${FALLBACK_GITHUB_REPO}`)}
|
||||
@@ -3407,6 +3638,19 @@ function App() {
|
||||
configDir={configDir}
|
||||
onChange={async () => { routingRequestRefreshRef.current(); }}
|
||||
generalRequest={settingsGeneralRequest}
|
||||
interactionBusy={loading || refreshing || Boolean(actionBusy) || restartCodexBusy || isAppUpdateBusy(updater.state.phase)}
|
||||
onLanguageBusyChange={handleLanguageBusyChange}
|
||||
onCodexLanguageSaved={(status) => {
|
||||
setError("");
|
||||
if (status.pendingEnabled == null) {
|
||||
setLanguageRestartNotice(null);
|
||||
setToast(lang === "zh" ? "已取消待重启的语言更改" : "Pending language change cancelled");
|
||||
return;
|
||||
}
|
||||
const message = lang === "zh" ? "语言设置已保存,重启 Codex / ChatGPT 后生效" : "Language setting saved. Restart Codex / ChatGPT to apply.";
|
||||
setLanguageRestartNotice({ configDir, message });
|
||||
setToast(message);
|
||||
}}
|
||||
configHealthStatus={<ConfigHealthStatus
|
||||
lang={lang}
|
||||
report={configHealth.report}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
export const MAX_AUTH_IMPORT_BYTES = 1024 * 1024;
|
||||
type ImportErrorCode = "too_large" | "invalid_text" | "invalid_json" | "unsupported_shape";
|
||||
|
||||
export class OfficialAuthImportError extends Error {
|
||||
readonly code: ImportErrorCode;
|
||||
constructor(code: ImportErrorCode) {
|
||||
super(code);
|
||||
this.name = "OfficialAuthImportError";
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
export function parseOfficialAuthImport(bytes: Uint8Array): string {
|
||||
if (bytes.byteLength > MAX_AUTH_IMPORT_BYTES) throw new OfficialAuthImportError("too_large");
|
||||
let text: string;
|
||||
try { text = new TextDecoder("utf-8", { fatal: true }).decode(bytes).replace(/^\uFEFF/, "").trim(); }
|
||||
catch { throw new OfficialAuthImportError("invalid_text"); }
|
||||
let value: unknown;
|
||||
try { value = JSON.parse(text); }
|
||||
catch { throw new OfficialAuthImportError("invalid_json"); }
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) throw new OfficialAuthImportError("unsupported_shape");
|
||||
const auth = value as Record<string, unknown>;
|
||||
const tokens = auth.tokens && typeof auth.tokens === "object" && !Array.isArray(auth.tokens)
|
||||
? auth.tokens as Record<string, unknown> : null;
|
||||
const nonempty = (value: unknown) => typeof value === "string" && Boolean(value.trim());
|
||||
if (["base_url", "baseUrl", "api_base", "endpoint"].some(key => Object.prototype.hasOwnProperty.call(auth, key))
|
||||
|| !(nonempty(auth.OPENAI_API_KEY) || (tokens && [tokens.access_token, tokens.id_token, tokens.refresh_token].some(nonempty)))) {
|
||||
throw new OfficialAuthImportError("unsupported_shape");
|
||||
}
|
||||
// Only load the editor draft. The existing save command validates credentials.
|
||||
return text;
|
||||
}
|
||||
|
||||
export async function readOfficialAuthImport(file: Pick<File, "size" | "arrayBuffer">): Promise<string> {
|
||||
if (file.size > MAX_AUTH_IMPORT_BYTES) throw new OfficialAuthImportError("too_large");
|
||||
return parseOfficialAuthImport(new Uint8Array(await file.arrayBuffer()));
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
EyeOff,
|
||||
FilePlus2,
|
||||
Gauge,
|
||||
GripVertical,
|
||||
Loader2,
|
||||
PencilLine,
|
||||
Plus,
|
||||
@@ -22,12 +23,18 @@ import type { LucideIcon } from "lucide-react";
|
||||
import type { Ref } from "react";
|
||||
import { PageTransition } from "../components/PageTransition";
|
||||
import { OfficialQuotaDialog } from "../components/OfficialQuotaDialog";
|
||||
import { ProviderBalanceBadge } from "../components/ProviderBalanceBadge";
|
||||
import { supportsProviderBalance, type ProviderBalanceState } from "../providerBalance";
|
||||
import { OfficialAccountBadge } from "../components/OfficialAccountBadge";
|
||||
import { ProviderModelMappings, validateProviderModelMappings } from "../components/ProviderModelMappings";
|
||||
import { ProviderHeadersControl } from "../components/ProviderHeadersControl";
|
||||
import { providerUpstreamApi } from "../providerProtocol";
|
||||
import { OfficialAuthImportError, readOfficialAuthImport } from "../officialAuthImport";
|
||||
import { ProviderPresetPicker } from "../components/ProviderPresetPicker";
|
||||
import { PROVIDER_PRESETS, getProviderPreset, getProviderPresetVariant } from "../providerPresets";
|
||||
import { Button, Checkbox, ModalShell } from "../components/ui";
|
||||
import type { ProviderMode, ProviderModelMapping } from "../types";
|
||||
import { moveProviderRow, providerRowKey } from "../providerRowOrder";
|
||||
import "../styles/providers-page.css";
|
||||
|
||||
export type ProviderRowSource = "official" | "local" | "detected";
|
||||
@@ -38,8 +45,10 @@ export type ProviderRow = {
|
||||
providerName: string;
|
||||
baseUrl: string;
|
||||
model: string;
|
||||
modelDisplayName?: string;
|
||||
apiKey?: string;
|
||||
wireApi: string;
|
||||
upstreamApi?: string | null;
|
||||
requiresOpenaiAuth: boolean;
|
||||
isCurrent: boolean;
|
||||
isDefaultOfficial?: boolean;
|
||||
@@ -62,6 +71,7 @@ export type ProviderFormValue = {
|
||||
providerName: string;
|
||||
model: string;
|
||||
wireApi: string;
|
||||
upstreamApi?: string | null;
|
||||
requiresOpenaiAuth: boolean;
|
||||
};
|
||||
|
||||
@@ -146,9 +156,13 @@ export type ProvidersPageProps = {
|
||||
copy: ProviderCopy;
|
||||
mode: ProviderMode;
|
||||
providerRows: readonly ProviderRow[];
|
||||
providerBalances?: ProviderBalanceState;
|
||||
loading: boolean;
|
||||
testingId: string;
|
||||
actionBusy?: string;
|
||||
activationBusy?: boolean;
|
||||
orderBusy?: boolean;
|
||||
onReorderProviders: (order: string[]) => Promise<boolean>;
|
||||
editingProviderId: string | null;
|
||||
creatingProvider: boolean;
|
||||
selectedPresetId: string;
|
||||
@@ -191,10 +205,11 @@ export type ProvidersPageProps = {
|
||||
onProviderNameChange: (value: string) => void;
|
||||
onProviderModelChange: (value: string) => void;
|
||||
onFetchModels: () => void;
|
||||
onWireApiChange: (value: string) => void;
|
||||
onUpstreamApiChange: (value: string) => void;
|
||||
onRequiresAuthChange: (value: boolean) => void;
|
||||
onToggleApiKeyVisibility: () => void;
|
||||
onProviderTomlDraftChange: (value: string, origin?: "manual" | "context") => void;
|
||||
onProviderHeadersConfigChange: (value: string) => void;
|
||||
onResetProviderToml: () => void;
|
||||
onSaveProvider: () => void;
|
||||
};
|
||||
@@ -391,9 +406,12 @@ function ListPage({
|
||||
configDir,
|
||||
copy,
|
||||
providerRows,
|
||||
providerBalances,
|
||||
loading,
|
||||
testingId,
|
||||
actionBusy,
|
||||
activationBusy,
|
||||
orderBusy,
|
||||
onImportCcSwitch,
|
||||
onAddProvider,
|
||||
onEnableProvider,
|
||||
@@ -401,11 +419,77 @@ function ListPage({
|
||||
onEditProvider,
|
||||
onDuplicateProvider,
|
||||
onDeleteProvider,
|
||||
}: Pick<ProvidersPageProps, "lang" | "configDir" | "copy" | "providerRows" | "loading" | "testingId" | "actionBusy" | "onImportCcSwitch" | "onAddProvider" | "onEnableProvider" | "onTestProvider" | "onEditProvider" | "onDuplicateProvider" | "onDeleteProvider">) {
|
||||
onReorderProviders,
|
||||
}: Pick<ProvidersPageProps, "lang" | "configDir" | "copy" | "providerRows" | "providerBalances" | "loading" | "testingId" | "actionBusy" | "activationBusy" | "orderBusy" | "onReorderProviders" | "onImportCcSwitch" | "onAddProvider" | "onEnableProvider" | "onTestProvider" | "onEditProvider" | "onDuplicateProvider" | "onDeleteProvider">) {
|
||||
const [providerToDelete, setProviderToDelete] = useState<ProviderRow | null>(null);
|
||||
const [quotaSelection, setQuotaSelection] = useState<{ id: string; configDir: string; email: string | null } | null>(null);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const providerActionsBusy = loading || Boolean(actionBusy);
|
||||
const providerActivationBusy = activationBusy ?? providerActionsBusy;
|
||||
const sortingDisabled = providerActionsBusy || Boolean(orderBusy) || providerRows.length < 2;
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
const pointerDragRef = useRef<{ key: string; pointerId: number; startY: number; moved: boolean } | null>(null);
|
||||
const pointerPositionRef = useRef({ x: 0, y: 0 });
|
||||
const scrollFrameRef = useRef<number | null>(null);
|
||||
const dropTargetRef = useRef<{ key: string; position: "before" | "after" } | null>(null);
|
||||
const [draggedKey, setDraggedKey] = useState("");
|
||||
const [dropTarget, setDropTarget] = useState<{ key: string; position: "before" | "after" } | null>(null);
|
||||
const finishDrag = () => {
|
||||
if (scrollFrameRef.current !== null) cancelAnimationFrame(scrollFrameRef.current);
|
||||
scrollFrameRef.current = null;
|
||||
pointerDragRef.current = null;
|
||||
dropTargetRef.current = null;
|
||||
setDraggedKey("");
|
||||
setDropTarget(null);
|
||||
};
|
||||
useEffect(() => { finishDrag(); }, [configDir]);
|
||||
useEffect(() => () => { if (scrollFrameRef.current !== null) cancelAnimationFrame(scrollFrameRef.current); }, []);
|
||||
const reorder = async (source: string, target: string, position: "before" | "after") => {
|
||||
const current = providerRows.map(providerRowKey);
|
||||
const next = moveProviderRow(current, source, target, position);
|
||||
if (next.some((key, index) => key !== current[index])) {
|
||||
await onReorderProviders(next);
|
||||
if (document.activeElement === document.body || document.activeElement?.classList.contains("cx-providers-drag-handle")) {
|
||||
const card = Array.from(listRef.current?.querySelectorAll<HTMLElement>("[data-provider-key]") || []).find((item) => item.dataset.providerKey === source);
|
||||
card?.querySelector<HTMLButtonElement>(".cx-providers-drag-handle")?.focus();
|
||||
}
|
||||
}
|
||||
};
|
||||
const updateDropTarget = (clientX: number, clientY: number) => {
|
||||
const list = listRef.current;
|
||||
if (!list) return;
|
||||
const bounds = list.getBoundingClientRect();
|
||||
if (clientX < bounds.left || clientX > bounds.right) {
|
||||
dropTargetRef.current = null;
|
||||
setDropTarget(null);
|
||||
return;
|
||||
}
|
||||
const cards = Array.from(list.querySelectorAll<HTMLElement>("[data-provider-key]"));
|
||||
const card = cards.find((item) => clientY < item.getBoundingClientRect().bottom) || cards[cards.length - 1];
|
||||
if (!card) return;
|
||||
const rect = card.getBoundingClientRect();
|
||||
const target = { key: card.dataset.providerKey!, position: clientY < rect.top + rect.height / 2 ? "before" as const : "after" as const };
|
||||
dropTargetRef.current = target;
|
||||
setDropTarget(target);
|
||||
};
|
||||
const startAutoScroll = () => {
|
||||
if (scrollFrameRef.current !== null) return;
|
||||
const tick = () => {
|
||||
const list = listRef.current;
|
||||
if (!pointerDragRef.current?.moved || !list) { scrollFrameRef.current = null; return; }
|
||||
const { x, y } = pointerPositionRef.current;
|
||||
const bounds = list.getBoundingClientRect();
|
||||
if (x >= bounds.left && x <= bounds.right) {
|
||||
const speed = y < bounds.top + 48 ? -Math.min(16, (bounds.top + 48 - y) / 3)
|
||||
: y > bounds.bottom - 48 ? Math.min(16, (y - bounds.bottom + 48) / 3) : 0;
|
||||
const previous = list.scrollTop;
|
||||
list.scrollTop += speed;
|
||||
if (list.scrollTop !== previous) updateDropTarget(x, y);
|
||||
}
|
||||
scrollFrameRef.current = requestAnimationFrame(tick);
|
||||
};
|
||||
scrollFrameRef.current = requestAnimationFrame(tick);
|
||||
};
|
||||
const quotaProfile = quotaSelection?.configDir === configDir
|
||||
? providerRows.find((row) => row.source === "official" && row.id === quotaSelection.id && row.canQueryQuota && (row.email ?? null) === quotaSelection.email)
|
||||
: undefined;
|
||||
@@ -453,15 +537,60 @@ function ListPage({
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="cx-providers-list" role="list">
|
||||
<p className="cx-providers-sort-hint">{lang === "zh" ? "拖动卡片左侧手柄调整顺序,自动保存。" : "Drag the handle on the left to reorder. Changes save automatically."}</p>
|
||||
<div className="cx-providers-list" role="list" ref={listRef}>
|
||||
{providerRows.length === 0 ? (
|
||||
<div className="cx-providers-empty" role="status">{copy.noProviders}</div>
|
||||
) : providerRows.map((row) => {
|
||||
const balance = providerBalances?.balances.find(item => item.source === row.source && item.providerId === row.id);
|
||||
const showBalance = row.source !== "official" && (balance ? balance.supported : supportsProviderBalance(row.baseUrl));
|
||||
const testingKey = row.testingKey || `${row.source}-${row.id}`;
|
||||
const isTesting = testingId === testingKey;
|
||||
const isProtectedOfficial = row.source === "official" && row.isDefaultOfficial === true;
|
||||
const key = providerRowKey(row);
|
||||
const modelName = row.modelDisplayName || row.model || (lang === "zh" ? "跟随 Codex" : "Follow Codex");
|
||||
return (
|
||||
<article className={`cx-providers-row${row.isCurrent ? " cx-providers-row--current" : ""}${row.source === "official" ? " cx-providers-row--official" : ""}`} key={`${row.source}-${row.id}-${row.baseUrl}`} role="listitem">
|
||||
<article className={`cx-providers-row${row.isCurrent ? " cx-providers-row--current" : ""}${row.source === "official" ? " cx-providers-row--official" : showBalance ? " cx-providers-row--balance" : ""}${draggedKey === key ? " cx-providers-row--dragging" : ""}${dropTarget?.key === key && draggedKey !== key ? ` cx-providers-row--drop-${dropTarget.position}` : ""}`} key={key} role="listitem" data-provider-key={key}>
|
||||
<button type="button" className="cx-providers-drag-handle" disabled={sortingDisabled}
|
||||
aria-label={lang === "zh" ? `排序 ${row.providerName}:拖动或按上下箭头移动` : `Reorder ${row.providerName}: drag or use Up and Down arrows`}
|
||||
title={lang === "zh" ? "拖动排序,也可按上下箭头移动" : "Drag to reorder, or use Up and Down arrows"}
|
||||
onPointerDown={(event) => {
|
||||
if (sortingDisabled || event.button !== 0) return;
|
||||
event.preventDefault();
|
||||
event.currentTarget.focus();
|
||||
event.currentTarget.setPointerCapture(event.pointerId);
|
||||
pointerDragRef.current = { key, pointerId: event.pointerId, startY: event.clientY, moved: false };
|
||||
}}
|
||||
onPointerMove={(event) => {
|
||||
const drag = pointerDragRef.current;
|
||||
if (!drag || drag.pointerId !== event.pointerId || sortingDisabled) return;
|
||||
if (!drag.moved && Math.abs(event.clientY - drag.startY) < 5) return;
|
||||
drag.moved = true;
|
||||
pointerPositionRef.current = { x: event.clientX, y: event.clientY };
|
||||
setDraggedKey(drag.key);
|
||||
updateDropTarget(event.clientX, event.clientY);
|
||||
startAutoScroll();
|
||||
}}
|
||||
onPointerUp={(event) => {
|
||||
const drag = pointerDragRef.current;
|
||||
const target = dropTargetRef.current;
|
||||
if (!drag || drag.pointerId !== event.pointerId) return;
|
||||
finishDrag();
|
||||
if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId);
|
||||
const bounds = listRef.current?.getBoundingClientRect();
|
||||
const inside = bounds && event.clientX >= bounds.left && event.clientX <= bounds.right && event.clientY >= bounds.top && event.clientY <= bounds.bottom;
|
||||
if (drag.moved && target && inside && !sortingDisabled) void reorder(drag.key, target.key, target.position);
|
||||
}}
|
||||
onPointerCancel={finishDrag}
|
||||
onLostPointerCapture={finishDrag}
|
||||
onKeyDown={(event) => {
|
||||
if (sortingDisabled || !["ArrowUp", "ArrowDown"].includes(event.key)) return;
|
||||
event.preventDefault();
|
||||
const index = providerRows.findIndex((entry) => providerRowKey(entry) === key);
|
||||
const target = providerRows[index + (event.key === "ArrowUp" ? -1 : 1)];
|
||||
if (target) void reorder(key, providerRowKey(target), event.key === "ArrowUp" ? "before" : "after");
|
||||
}}
|
||||
><GripVertical size={16} aria-hidden="true" /></button>
|
||||
<ProviderAvatar row={row} />
|
||||
<div className="cx-providers-row-content">
|
||||
<div className="cx-providers-row-main">
|
||||
@@ -474,17 +603,19 @@ function ListPage({
|
||||
)}
|
||||
</div>
|
||||
<code title={row.baseUrl || copy.noBaseUrlLabel}>{row.baseUrl || copy.noBaseUrlLabel}</code>
|
||||
<div className="cx-providers-row-model" title={row.model || modelName}><span>{lang === "zh" ? "模型" : "Model"}</span><b>{modelName}</b>{row.modelDisplayName && row.modelDisplayName !== row.model && <code>{row.model}</code>}</div>
|
||||
{row.source !== "official" && row.meta && <div className="cx-providers-row-meta">{row.meta}</div>}
|
||||
</div>
|
||||
</div>
|
||||
{row.source === "official" && <OfficialAccountBadge lang={lang} email={row.email} planType={row.planType} hasAuth={Boolean(row.hasAuth)} canQueryQuota={Boolean(row.canQueryQuota)} className="cx-providers-login-badge" />}
|
||||
{showBalance && <ProviderBalanceBadge balance={balance} loading={providerBalances?.loading ?? true} refreshing={providerBalances?.refreshingKeys.includes(`${row.source}:${row.id}`)} failed={providerBalances?.failed ?? false} lang={lang} onRefresh={row.source !== "official" && providerBalances ? () => { void providerBalances.refreshBalance(row.source as "local" | "detected", row.id); } : undefined} />}
|
||||
<div className="cx-providers-row-actions">
|
||||
{row.isCurrent && <span className="cx-providers-current-badge"><span aria-hidden="true" />{copy.currentLabel}</span>}
|
||||
<button
|
||||
type="button"
|
||||
className="cx-providers-button cx-providers-button--small cx-providers-button--secondary"
|
||||
onClick={() => onEnableProvider(row)}
|
||||
disabled={providerActionsBusy || row.isCurrent}
|
||||
disabled={providerActivationBusy || row.isCurrent}
|
||||
>
|
||||
{copy.enableLabel}
|
||||
</button>
|
||||
@@ -616,9 +747,15 @@ function OfficialForm({
|
||||
}: Pick<ProvidersPageProps, "lang" | "copy" | "creatingProvider" | "selectedPresetId" | "selectedPresetVariantId" | "onPresetSelect" | "onPresetVariantSelect" | "officialForm" | "officialProfileIsDefault" | "canLoadCurrentOfficial" | "officialAuthRef" | "officialTomlRef" | "officialInfo" | "loading" | "actionBusy" | "onCancelMode" | "onOfficialNameChange" | "onOfficialModelChange" | "onOfficialAuthChange" | "onOfficialConfigChange" | "onSaveOfficial" | "onLoadCcSwitchOfficial" | "onLoadCurrentOfficial" | "onResetOfficial">) {
|
||||
const [resetConfirmOpen, setResetConfirmOpen] = useState(false);
|
||||
const [contextWindowBusy, setContextWindowBusy] = useState(false);
|
||||
const [authImportBusy, setAuthImportBusy] = useState(false);
|
||||
const [authImportError, setAuthImportError] = useState("");
|
||||
const [authImportName, setAuthImportName] = useState("");
|
||||
const authFileRef = useRef<HTMLInputElement>(null);
|
||||
const authImportRequest = useRef(0);
|
||||
useEffect(() => () => { authImportRequest.current += 1; }, []);
|
||||
const loadingCcSwitch = actionBusy === "loadCcSwitchOfficial";
|
||||
const loadingCurrent = actionBusy === "loadCurrentOfficial";
|
||||
const formBusy = loading || actionBusy === "loadOfficialDraft" || loadingCcSwitch || loadingCurrent || contextWindowBusy;
|
||||
const formBusy = loading || actionBusy === "loadOfficialDraft" || loadingCcSwitch || loadingCurrent || contextWindowBusy || authImportBusy;
|
||||
const showDefaultActions = officialProfileIsDefault && !creatingProvider;
|
||||
const profileHint = lang === "zh"
|
||||
? "认证内容可留空;保存并启用后,在 Codex 中完成登录。复制官方供应商会保留原认证,并可修改名称。"
|
||||
@@ -630,6 +767,23 @@ function OfficialForm({
|
||||
onResetOfficial();
|
||||
};
|
||||
|
||||
const importAuthFile = async (file: File) => {
|
||||
if (formBusy) return;
|
||||
const request = ++authImportRequest.current;
|
||||
setAuthImportBusy(true); setAuthImportError(""); setAuthImportName("");
|
||||
try {
|
||||
const text = await readOfficialAuthImport(file);
|
||||
if (request !== authImportRequest.current) return;
|
||||
onOfficialAuthChange(text);
|
||||
setAuthImportName(file.name);
|
||||
} catch (error) {
|
||||
if (request !== authImportRequest.current) return;
|
||||
setAuthImportError(error instanceof OfficialAuthImportError && error.code === "too_large"
|
||||
? (lang === "zh" ? "认证文件超过 1 MiB,请选择单个 auth.json。" : "Choose a single auth.json file smaller than 1 MiB.")
|
||||
: (lang === "zh" ? "请选择有效的单个 Codex auth.json;批量账号或其他工具的封装格式暂不支持。" : "Choose a valid single Codex auth.json. Account arrays and other export formats are not supported yet."));
|
||||
} finally { if (request === authImportRequest.current) setAuthImportBusy(false); }
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<ModeHeader
|
||||
@@ -666,6 +820,17 @@ function OfficialForm({
|
||||
/>
|
||||
</div>
|
||||
<Field label={copy.officialAuthLabel} className="cx-providers-editor-field">
|
||||
<div className="cx-providers-context-heading">
|
||||
<button type="button" className="cx-providers-button cx-providers-button--secondary" disabled={formBusy} onClick={() => authFileRef.current?.click()}>
|
||||
<Download size={14} aria-hidden="true" />{lang === "zh" ? "导入 auth.json 文件" : "Import auth.json file"}
|
||||
</button>
|
||||
<input ref={authFileRef} type="file" accept=".json,application/json" hidden onChange={event => {
|
||||
const file = event.currentTarget.files?.[0]; event.currentTarget.value = "";
|
||||
if (file) void importAuthFile(file);
|
||||
}} />
|
||||
</div>
|
||||
{authImportError && <span className="cx-providers-context-error" role="alert">{authImportError}</span>}
|
||||
{authImportName && <span className="cx-providers-context-hint" role="status">{lang === "zh" ? `已读入 ${authImportName},保存官方账号后生效。` : `Loaded ${authImportName}. Save the official account to apply it.`}</span>}
|
||||
<textarea
|
||||
ref={officialAuthRef}
|
||||
className="cx-providers-code-editor cx-providers-auth-editor"
|
||||
@@ -744,17 +909,21 @@ function ProviderForm({
|
||||
onProviderNameChange,
|
||||
onProviderModelChange,
|
||||
onFetchModels,
|
||||
onWireApiChange,
|
||||
onUpstreamApiChange,
|
||||
onRequiresAuthChange,
|
||||
onToggleApiKeyVisibility,
|
||||
onProviderTomlDraftChange,
|
||||
onProviderHeadersConfigChange,
|
||||
onResetProviderToml,
|
||||
onSaveProvider,
|
||||
}: Pick<ProvidersPageProps, "lang" | "copy" | "creatingProvider" | "selectedPresetId" | "selectedPresetVariantId" | "onPresetSelect" | "onPresetVariantSelect" | "providerForm" | "providerModelMappings" | "onProviderModelMappingsChange" | "loading" | "editingProviderId" | "providerAuthPreview" | "providerTomlDraft" | "providerTomlRef" | "apiKeyVisible" | "availableModels" | "fetchingModels" | "onCancelMode" | "onApiKeyChange" | "onBaseUrlChange" | "onProviderNameChange" | "onProviderModelChange" | "onFetchModels" | "onWireApiChange" | "onRequiresAuthChange" | "onToggleApiKeyVisibility" | "onProviderTomlDraftChange" | "onResetProviderToml" | "onSaveProvider">) {
|
||||
}: Pick<ProvidersPageProps, "lang" | "copy" | "creatingProvider" | "selectedPresetId" | "selectedPresetVariantId" | "onPresetSelect" | "onPresetVariantSelect" | "providerForm" | "providerModelMappings" | "onProviderModelMappingsChange" | "loading" | "editingProviderId" | "providerAuthPreview" | "providerTomlDraft" | "providerTomlRef" | "apiKeyVisible" | "availableModels" | "fetchingModels" | "onCancelMode" | "onApiKeyChange" | "onBaseUrlChange" | "onProviderNameChange" | "onProviderModelChange" | "onFetchModels" | "onUpstreamApiChange" | "onRequiresAuthChange" | "onToggleApiKeyVisibility" | "onProviderTomlDraftChange" | "onProviderHeadersConfigChange" | "onResetProviderToml" | "onSaveProvider">) {
|
||||
const modelListId = useId();
|
||||
const [contextWindowBusy, setContextWindowBusy] = useState(false);
|
||||
const canFetchModels = Boolean(providerForm.baseUrl.trim() && providerForm.apiKey.trim());
|
||||
const formBusy = loading || fetchingModels || contextWindowBusy;
|
||||
const [headersBusy, setHeadersBusy] = useState(false);
|
||||
const [headersValid, setHeadersValid] = useState(true);
|
||||
const [headersRevision, setHeadersRevision] = useState(0);
|
||||
const canFetchModels = Boolean(providerForm.baseUrl.trim());
|
||||
const formBusy = loading || fetchingModels || contextWindowBusy || headersBusy;
|
||||
const mappingsValid = validateProviderModelMappings(providerModelMappings, providerForm.model, lang).valid;
|
||||
|
||||
return (
|
||||
@@ -803,7 +972,7 @@ function ProviderForm({
|
||||
type="button"
|
||||
className="cx-providers-button cx-providers-button--secondary cx-providers-button--small cx-providers-fetch-models"
|
||||
onClick={onFetchModels}
|
||||
disabled={loading || fetchingModels || !canFetchModels}
|
||||
disabled={formBusy || !canFetchModels || !headersValid}
|
||||
title={copy.fetchModelsLabel}
|
||||
aria-label={copy.fetchModelsLabel}
|
||||
>
|
||||
@@ -833,12 +1002,22 @@ function ProviderForm({
|
||||
</>
|
||||
)}
|
||||
</Field>
|
||||
<Field label={copy.wireApiLabel}>
|
||||
<select value={providerForm.wireApi} onChange={(event) => onWireApiChange(event.target.value)} disabled={formBusy}>
|
||||
<option value="responses">responses</option>
|
||||
<option value="chat">chat</option>
|
||||
<Field label={lang === "zh" ? "上游接口协议" : "Upstream API protocol"}>
|
||||
<select value={providerUpstreamApi(providerForm)} onChange={(event) => onUpstreamApiChange(event.target.value)} disabled={formBusy}>
|
||||
<option value="responses">OpenAI Responses</option>
|
||||
<option value="chat_completions">OpenAI Chat Completions</option>
|
||||
<option value="anthropic_messages">Claude Messages</option>
|
||||
<option value="gemini">Gemini generateContent</option>
|
||||
{!["responses", "chat_completions", "anthropic_messages", "gemini"].includes(providerUpstreamApi(providerForm)) && <option value={providerUpstreamApi(providerForm)} disabled>{lang === "zh" ? "不支持的协议,请重新选择" : "Unsupported protocol — choose a supported API"}</option>}
|
||||
</select>
|
||||
</Field>
|
||||
{providerUpstreamApi(providerForm) !== "responses" && (
|
||||
<p className="cx-providers-field--full cx-providers-protocol-hint">
|
||||
{lang === "zh"
|
||||
? "Codex 仍使用 Responses。本协议需在设置中开启本地路由和配置接管;使用期间请保持 Codex-X 运行。关闭路由前请切回 Responses 供应商或官方账号;退出期间请求会暂停,重开后自动恢复。"
|
||||
: "Codex still uses Responses. Enable the local router and config takeover in Settings, and keep Codex-X running. Switch to a Responses provider or official account before disabling the router. Requests pause while Codex-X is closed and resume after reopening."}
|
||||
</p>
|
||||
)}
|
||||
<Checkbox
|
||||
className="cx-providers-checkbox cx-providers-checkbox--full"
|
||||
checked={providerForm.requiresOpenaiAuth}
|
||||
@@ -849,6 +1028,16 @@ function ProviderForm({
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<ProviderHeadersControl
|
||||
key={`headers:${editingProviderId ?? "new-provider"}:${selectedPresetId}:${selectedPresetVariantId}:${headersRevision}`}
|
||||
lang={lang}
|
||||
configText={providerTomlDraft}
|
||||
disabled={loading || fetchingModels || contextWindowBusy}
|
||||
onConfigChange={onProviderHeadersConfigChange}
|
||||
onBusyChange={setHeadersBusy}
|
||||
onValidityChange={setHeadersValid}
|
||||
/>
|
||||
|
||||
<ProviderModelMappings
|
||||
key={editingProviderId ?? "new-provider"}
|
||||
lang={lang}
|
||||
@@ -869,15 +1058,16 @@ function ProviderForm({
|
||||
<div><h3>{copy.tomlTitle}</h3><p>{copy.tomlDescription}</p></div>
|
||||
<div className="cx-providers-context-actions">
|
||||
<ContextWindowControl lang={lang} configText={providerTomlDraft} onConfigChange={(value) => onProviderTomlDraftChange(value, "context")} disabled={formBusy} onBusyChange={setContextWindowBusy} />
|
||||
<button type="button" className="cx-providers-button cx-providers-button--secondary cx-providers-button--small" onClick={onResetProviderToml} disabled={formBusy}><RefreshCw size={14} aria-hidden="true" />{copy.resetTomlLabel}</button>
|
||||
<button type="button" className="cx-providers-button cx-providers-button--secondary cx-providers-button--small" onClick={() => { setHeadersRevision((value) => value + 1); onResetProviderToml(); }} disabled={formBusy}><RefreshCw size={14} aria-hidden="true" />{copy.resetTomlLabel}</button>
|
||||
</div>
|
||||
</div>
|
||||
<textarea ref={providerTomlRef} className="cx-providers-code-editor cx-providers-toml-editor" aria-label={copy.tomlTitle} value={providerTomlDraft} onChange={(event) => onProviderTomlDraftChange(event.target.value)} disabled={formBusy} spellCheck={false} />
|
||||
<textarea ref={providerTomlRef} className="cx-providers-code-editor cx-providers-toml-editor" aria-label={copy.tomlTitle} value={providerTomlDraft} onChange={(event) => { setHeadersRevision((value) => value + 1); onProviderTomlDraftChange(event.target.value); }} disabled={formBusy} spellCheck={false} />
|
||||
</section>
|
||||
|
||||
<div className="cx-providers-form-actions cx-providers-form-actions--save">
|
||||
{!headersValid && <span className="cx-provider-mappings-save-hint">{lang === "zh" ? "请先修正请求头中的错误。" : "Correct the HTTP header errors before saving."}</span>}
|
||||
{!mappingsValid && <span className="cx-provider-mappings-save-hint">{lang === "zh" ? "请先修正模型映射中的错误。" : "Correct the model mapping errors before saving."}</span>}
|
||||
<button type="button" className="cx-providers-button cx-providers-button--primary" onClick={onSaveProvider} disabled={formBusy || !mappingsValid}>
|
||||
<button type="button" className="cx-providers-button cx-providers-button--primary" onClick={onSaveProvider} disabled={formBusy || !mappingsValid || !headersValid}>
|
||||
{loading ? <Loader2 size={15} className="cx-providers-spin" aria-hidden="true" /> : <CheckCircle2 size={15} aria-hidden="true" />}
|
||||
{loading ? copy.savingLabel : copy.saveLabel}
|
||||
</button>
|
||||
|
||||
@@ -1,19 +1,70 @@
|
||||
import {
|
||||
AlertCircle,
|
||||
CheckCircle2,
|
||||
ChevronDown,
|
||||
Download,
|
||||
Folder,
|
||||
FolderTree,
|
||||
History,
|
||||
Info,
|
||||
Loader2,
|
||||
Pin,
|
||||
RefreshCw,
|
||||
Search,
|
||||
Trash2,
|
||||
Zap,
|
||||
} from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Button, Checkbox, ModalShell, cx } from "../components/ui";
|
||||
import {
|
||||
mergeSessionDirectoryGroups,
|
||||
pinnedSessionDirectoryKeys,
|
||||
readSessionPinPreferences,
|
||||
sessionPinStorageKey,
|
||||
sessionsForDirectoryGroup,
|
||||
toggleFolderPins,
|
||||
type SessionDirectoryIdentities,
|
||||
type SessionPinPreferences,
|
||||
} from "../sessionDirectoryIdentity";
|
||||
import "../styles/session-management.css";
|
||||
|
||||
const SESSION_ROW_HEIGHT = 58;
|
||||
const SESSION_COLUMN_HEADER_HEIGHT = 34;
|
||||
const SESSION_VIRTUAL_OVERSCAN_ROWS = 8;
|
||||
const DEFAULT_SESSION_VIEWPORT_HEIGHT = 640;
|
||||
const SESSION_ALL_FOLDERS_KEY = "__codexx_all_folders__";
|
||||
// Defer the browser storage getter so unavailable storage is caught by the reader.
|
||||
const sessionPinStorage = { getItem: (key: string) => localStorage.getItem(key) };
|
||||
|
||||
type ScopedSessionPinPreferences = SessionPinPreferences & {
|
||||
storageKey: string;
|
||||
};
|
||||
|
||||
function folderDisplayName(value: string, missing: string) {
|
||||
if (!value) return missing;
|
||||
const parts = value.replace(/\\/g, "/").split("/").filter(Boolean);
|
||||
return parts[parts.length - 1] || missing;
|
||||
}
|
||||
|
||||
type SessionVirtualRow = {
|
||||
kind: "session";
|
||||
key: string;
|
||||
top: number;
|
||||
height: number;
|
||||
item: SessionPreview;
|
||||
};
|
||||
|
||||
function findVirtualRowIndex(rows: SessionVirtualRow[], offset: number) {
|
||||
let low = 0;
|
||||
let high = rows.length;
|
||||
while (low < high) {
|
||||
const middle = Math.floor((low + high) / 2);
|
||||
if (rows[middle].top + rows[middle].height <= offset) low = middle + 1;
|
||||
else high = middle;
|
||||
}
|
||||
return low;
|
||||
}
|
||||
|
||||
export type Lang = "zh" | "en";
|
||||
|
||||
export type SessionPreview = {
|
||||
@@ -32,6 +83,8 @@ export type SessionPreview = {
|
||||
|
||||
export type SessionSyncStatus = {
|
||||
codexDir: string;
|
||||
directoryIdentities?: SessionDirectoryIdentities;
|
||||
pinScopeKey?: string | null;
|
||||
targetProvider: string;
|
||||
rolloutFiles: number;
|
||||
sessionMetaCount: number;
|
||||
@@ -157,6 +210,7 @@ export function SessionManagementPage({
|
||||
onDeleteSafetyConfirmedChange,
|
||||
}: SessionManagementPageProps) {
|
||||
const isChinese = lang === "zh";
|
||||
const codexDir = sessionStatus?.codexDir || "default";
|
||||
const copy = isChinese
|
||||
? {
|
||||
syncEyebrow: "会话同步",
|
||||
@@ -170,14 +224,14 @@ export function SessionManagementPage({
|
||||
clickToCheck: "点击检查会话",
|
||||
scanIncomplete: "无法确认同步状态,请查看下方原因",
|
||||
needsSync: (count: number) => `有 ${count} 条会话需要同步`,
|
||||
allSynced: "普通会话已同步",
|
||||
allSynced: "全部会话已同步",
|
||||
sessionCount: (count: number) => `${count} 条会话`,
|
||||
local: "本地会话",
|
||||
list: "会话列表",
|
||||
list: "文件夹与会话",
|
||||
shown: (shown: number, total: number) => `展示 ${shown} / ${total} 条`,
|
||||
loaded: (count: number) => `当前加载 ${count} 条`,
|
||||
search: "搜索标题 / 项目 / 供应商 / ID",
|
||||
groupByProject: "按项目路径分组",
|
||||
groupByProject: "文件夹视图",
|
||||
showInternal: (count: number) => `显示内部会话 (${count})`,
|
||||
deleteSelected: "删除选中",
|
||||
exportSelected: "导出选中",
|
||||
@@ -189,6 +243,12 @@ export function SessionManagementPage({
|
||||
selectProject: (path: string, count: number) => `选择项目 ${path} 的 ${count} 条会话`,
|
||||
projectCount: (count: number, truncated: boolean) => `${truncated ? "已加载 " : ""}${count} 条`,
|
||||
projectShown: (shown: number, total: number) => `显示 ${shown} / 共 ${total} 条`,
|
||||
pinFolder: "置顶文件夹",
|
||||
unpinFolder: "取消置顶文件夹",
|
||||
pinSession: "置顶会话",
|
||||
unpinSession: "取消置顶会话",
|
||||
allSessions: "全部会话",
|
||||
folders: "工作文件夹",
|
||||
selectSession: "选择会话",
|
||||
archived: "已归档",
|
||||
internal: "内部",
|
||||
@@ -198,6 +258,7 @@ export function SessionManagementPage({
|
||||
noModel: "未记录",
|
||||
noMatch: "没有匹配的会话。",
|
||||
noSessions: "还没有读取到会话。点击右上角“检查会话”刷新。",
|
||||
loadingMore: "正在加载更多会话…",
|
||||
diagnostics: "诊断信息",
|
||||
diagnosticsCount: (count: number) => `${count} 条 · 点击查看`,
|
||||
deleteTitle: (count: number) => `永久删除 ${count} 条会话`,
|
||||
@@ -224,14 +285,14 @@ export function SessionManagementPage({
|
||||
clickToCheck: "Check sessions to get started",
|
||||
scanIncomplete: "Unable to verify sync status. See the reason below.",
|
||||
needsSync: (count: number) => `${count} session(s) need syncing`,
|
||||
allSynced: "User conversations are synced",
|
||||
allSynced: "All sessions are synced",
|
||||
sessionCount: (count: number) => `${count} sessions`,
|
||||
local: "LOCAL SESSIONS",
|
||||
list: "Sessions",
|
||||
list: "Folders & sessions",
|
||||
shown: (shown: number, total: number) => `${shown} / ${total} shown`,
|
||||
loaded: (count: number) => `${count} loaded`,
|
||||
search: "Search title / project / provider / ID",
|
||||
groupByProject: "Group by project path",
|
||||
groupByProject: "Folder view",
|
||||
showInternal: (count: number) => `Show internal sessions (${count})`,
|
||||
deleteSelected: "Delete selected",
|
||||
exportSelected: "Export selected",
|
||||
@@ -243,6 +304,12 @@ export function SessionManagementPage({
|
||||
selectProject: (path: string, count: number) => `Select ${count} sessions in ${path}`,
|
||||
projectCount: (count: number, truncated: boolean) => `${count}${truncated ? " loaded" : ""}`,
|
||||
projectShown: (shown: number, total: number) => `${shown} / ${total} shown`,
|
||||
pinFolder: "Pin folder",
|
||||
unpinFolder: "Unpin folder",
|
||||
pinSession: "Pin session",
|
||||
unpinSession: "Unpin session",
|
||||
allSessions: "All sessions",
|
||||
folders: "Workspace folders",
|
||||
selectSession: "Select session",
|
||||
archived: "Archived",
|
||||
internal: "Internal",
|
||||
@@ -252,6 +319,7 @@ export function SessionManagementPage({
|
||||
noModel: "Not recorded",
|
||||
noMatch: "No matching sessions.",
|
||||
noSessions: "No sessions loaded. Click Check sessions to refresh.",
|
||||
loadingMore: "Loading more sessions…",
|
||||
diagnostics: "Diagnostics",
|
||||
diagnosticsCount: (count: number) => `${count} · click to view`,
|
||||
deleteTitle: (count: number) => `Permanently delete ${count} session(s)`,
|
||||
@@ -273,10 +341,173 @@ export function SessionManagementPage({
|
||||
...(sessionStatus?.warnings || []).map((message) => ({ message, blocking: false })),
|
||||
];
|
||||
const dialogOpen = sessionDeleteConfirmOpen && selectedSessions.length > 0;
|
||||
const selectedVisibleCount = filteredSessions.filter((item) => selectedSessionSet.has(item.id)).length;
|
||||
const allVisibleSelected = filteredSessions.length > 0 && selectedVisibleCount === filteredSessions.length;
|
||||
const sessionScrollRef = useRef<HTMLDivElement | null>(null);
|
||||
const directoryIdentities = sessionStatus?.directoryIdentities;
|
||||
const pinScopeKey = sessionStatus?.pinScopeKey;
|
||||
const pinStorageKey = useMemo(() => sessionPinStorageKey(codexDir, pinScopeKey), [codexDir, pinScopeKey]);
|
||||
const [pinPreferences, setPinPreferences] = useState<ScopedSessionPinPreferences>({
|
||||
storageKey: "",
|
||||
folders: [],
|
||||
sessions: [],
|
||||
});
|
||||
const [selectedFolderKey, setSelectedFolderKey] = useState(SESSION_ALL_FOLDERS_KEY);
|
||||
const [sessionScrollMetrics, setSessionScrollMetrics] = useState({
|
||||
scrollTop: 0,
|
||||
viewportHeight: DEFAULT_SESSION_VIEWPORT_HEIGHT,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
setPinPreferences({ storageKey: pinStorageKey, ...readSessionPinPreferences(pinStorageKey, sessionPinStorage) });
|
||||
setSelectedFolderKey(SESSION_ALL_FOLDERS_KEY);
|
||||
}, [pinStorageKey]);
|
||||
|
||||
const activePinPreferences = pinPreferences.storageKey === pinStorageKey
|
||||
? pinPreferences
|
||||
: { storageKey: pinStorageKey, folders: [], sessions: [] };
|
||||
const pinnedFolderSet = useMemo(() => pinnedSessionDirectoryKeys(activePinPreferences.folders, directoryIdentities), [activePinPreferences.folders, directoryIdentities]);
|
||||
const pinnedSessionSet = useMemo(() => new Set(activePinPreferences.sessions), [activePinPreferences.sessions]);
|
||||
|
||||
const updatePins = useCallback((kind: "folders" | "sessions", key: string) => {
|
||||
setPinPreferences((current) => {
|
||||
const base = current.storageKey === pinStorageKey
|
||||
? current
|
||||
: { storageKey: pinStorageKey, ...readSessionPinPreferences(pinStorageKey, sessionPinStorage) };
|
||||
const values = new Set(base.sessions);
|
||||
if (kind === "sessions") {
|
||||
if (values.has(key)) values.delete(key);
|
||||
else values.add(key);
|
||||
}
|
||||
const next = kind === "folders"
|
||||
? { ...base, folders: toggleFolderPins(base.folders, key, directoryIdentities) }
|
||||
: { ...base, sessions: Array.from(values) };
|
||||
try {
|
||||
localStorage.setItem(pinStorageKey, JSON.stringify({ folders: next.folders, sessions: next.sessions }));
|
||||
} catch {
|
||||
// Pinning remains available for this run even when localStorage is unavailable.
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, [pinStorageKey, directoryIdentities]);
|
||||
|
||||
const orderedSessionGroups = useMemo(() => mergeSessionDirectoryGroups(groupedSessions, directoryIdentities).map(({ group, folderKey, items }) => {
|
||||
const orderedItems = [...items].sort((left, right) => {
|
||||
const pinnedOrder = Number(pinnedSessionSet.has(right.id)) - Number(pinnedSessionSet.has(left.id));
|
||||
if (pinnedOrder) return pinnedOrder;
|
||||
const recencyOrder = (right.updatedAtMs || 0) - (left.updatedAtMs || 0);
|
||||
return recencyOrder || left.id.localeCompare(right.id);
|
||||
});
|
||||
return {
|
||||
group,
|
||||
folderKey,
|
||||
items: orderedItems,
|
||||
newestAt: orderedItems.reduce((latest, item) => Math.max(latest, item.updatedAtMs || 0), 0),
|
||||
pinned: pinnedFolderSet.has(folderKey),
|
||||
};
|
||||
}).sort((left, right) => {
|
||||
if (!sessionGroupByCwd) return 0;
|
||||
const pinnedOrder = Number(right.pinned) - Number(left.pinned);
|
||||
return pinnedOrder || right.newestAt - left.newestAt || left.group.localeCompare(right.group);
|
||||
}), [groupedSessions, directoryIdentities, pinnedFolderSet, pinnedSessionSet, sessionGroupByCwd]);
|
||||
|
||||
const orderedAllSessions = useMemo(() => [...filteredSessions].sort((left, right) => {
|
||||
const pinnedOrder = Number(pinnedSessionSet.has(right.id)) - Number(pinnedSessionSet.has(left.id));
|
||||
if (pinnedOrder) return pinnedOrder;
|
||||
const recencyOrder = (right.updatedAtMs || 0) - (left.updatedAtMs || 0);
|
||||
return recencyOrder || left.id.localeCompare(right.id);
|
||||
}), [filteredSessions, pinnedSessionSet]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!sessionGroupByCwd || selectedFolderKey === SESSION_ALL_FOLDERS_KEY) return;
|
||||
if (!orderedSessionGroups.some((group) => group.folderKey === selectedFolderKey)) {
|
||||
setSelectedFolderKey(SESSION_ALL_FOLDERS_KEY);
|
||||
}
|
||||
}, [orderedSessionGroups, selectedFolderKey, sessionGroupByCwd]);
|
||||
|
||||
const displayedSessions = useMemo(() => {
|
||||
if (!sessionGroupByCwd || selectedFolderKey === SESSION_ALL_FOLDERS_KEY) return orderedAllSessions;
|
||||
return sessionsForDirectoryGroup(orderedSessionGroups, selectedFolderKey);
|
||||
}, [orderedAllSessions, orderedSessionGroups, selectedFolderKey, sessionGroupByCwd]);
|
||||
const selectedVisibleCount = displayedSessions.filter((item) => selectedSessionSet.has(item.id)).length;
|
||||
const allVisibleSelected = displayedSessions.length > 0 && selectedVisibleCount === displayedSessions.length;
|
||||
const visibleSelectionIsPartial = selectedVisibleCount > 0 && !allVisibleSelected;
|
||||
|
||||
const virtualSessionModel = useMemo(() => {
|
||||
const rows: SessionVirtualRow[] = [];
|
||||
let top = 0;
|
||||
displayedSessions.forEach((item) => {
|
||||
rows.push({
|
||||
kind: "session",
|
||||
key: `session:${item.id}`,
|
||||
top,
|
||||
height: SESSION_ROW_HEIGHT,
|
||||
item,
|
||||
});
|
||||
top += SESSION_ROW_HEIGHT;
|
||||
});
|
||||
return { rows, totalHeight: top };
|
||||
}, [displayedSessions]);
|
||||
|
||||
const visibleSessionRows = useMemo(() => {
|
||||
const viewportHeight = sessionScrollMetrics.viewportHeight || DEFAULT_SESSION_VIEWPORT_HEIGHT;
|
||||
const bodyScrollTop = Math.max(0, sessionScrollMetrics.scrollTop - SESSION_COLUMN_HEADER_HEIGHT);
|
||||
const firstVisibleIndex = findVirtualRowIndex(virtualSessionModel.rows, bodyScrollTop);
|
||||
const lastVisibleIndex = findVirtualRowIndex(virtualSessionModel.rows, bodyScrollTop + viewportHeight);
|
||||
const firstIndex = Math.max(0, firstVisibleIndex - SESSION_VIRTUAL_OVERSCAN_ROWS);
|
||||
const lastIndex = Math.min(
|
||||
virtualSessionModel.rows.length,
|
||||
lastVisibleIndex + SESSION_VIRTUAL_OVERSCAN_ROWS + 1,
|
||||
);
|
||||
return virtualSessionModel.rows.slice(firstIndex, lastIndex);
|
||||
}, [sessionScrollMetrics, virtualSessionModel]);
|
||||
|
||||
const syncSessionScrollMetrics = useCallback(() => {
|
||||
const element = sessionScrollRef.current;
|
||||
if (!element) return;
|
||||
setSessionScrollMetrics((current) => {
|
||||
const next = {
|
||||
scrollTop: element.scrollTop,
|
||||
viewportHeight: element.clientHeight,
|
||||
};
|
||||
return current.scrollTop === next.scrollTop && current.viewportHeight === next.viewportHeight
|
||||
? current
|
||||
: next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleSessionScroll = useCallback(() => {
|
||||
syncSessionScrollMetrics();
|
||||
}, [syncSessionScrollMetrics]);
|
||||
|
||||
useEffect(() => {
|
||||
syncSessionScrollMetrics();
|
||||
const element = sessionScrollRef.current;
|
||||
if (!element) return undefined;
|
||||
if (typeof ResizeObserver === "undefined") {
|
||||
window.addEventListener("resize", syncSessionScrollMetrics);
|
||||
return () => window.removeEventListener("resize", syncSessionScrollMetrics);
|
||||
}
|
||||
const observer = new ResizeObserver(syncSessionScrollMetrics);
|
||||
observer.observe(element);
|
||||
return () => observer.disconnect();
|
||||
}, [active, syncSessionScrollMetrics]);
|
||||
|
||||
useEffect(() => {
|
||||
const element = sessionScrollRef.current;
|
||||
if (!element) return;
|
||||
const maxScrollTop = Math.max(0, element.scrollHeight - element.clientHeight);
|
||||
if (element.scrollTop > maxScrollTop) {
|
||||
element.scrollTop = maxScrollTop;
|
||||
syncSessionScrollMetrics();
|
||||
}
|
||||
}, [syncSessionScrollMetrics, virtualSessionModel.totalHeight]);
|
||||
|
||||
useEffect(() => {
|
||||
const element = sessionScrollRef.current;
|
||||
if (!element) return;
|
||||
element.scrollTop = 0;
|
||||
syncSessionScrollMetrics();
|
||||
}, [selectedFolderKey, sessionGroupByCwd, syncSessionScrollMetrics]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<ModalShell
|
||||
@@ -429,56 +660,102 @@ export function SessionManagementPage({
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{filteredSessions.length > 0 ? (
|
||||
<div className="cx-session-scroll" role="table" aria-label={copy.list}>
|
||||
<div className="cx-session-column-head" role="row">
|
||||
<Checkbox
|
||||
className="cx-session-select-all"
|
||||
checked={allVisibleSelected}
|
||||
indeterminate={visibleSelectionIsPartial}
|
||||
onCheckedChange={(checked) => onSetSessionGroupSelected(filteredSessions, checked)}
|
||||
aria-label={copy.selectAll}
|
||||
disabled={loading || sessionDeleteBusy}
|
||||
/>
|
||||
<span>{isChinese ? "会话" : "Session"}</span>
|
||||
<span>{isChinese ? "更新时间" : "Updated"}</span>
|
||||
<span>{isChinese ? "供应商" : "Provider"}</span>
|
||||
<span>{isChinese ? "模型" : "Model"}</span>
|
||||
<span className="cx-session-id-heading">ID</span>
|
||||
<span className="cx-session-actions-heading">{isChinese ? "导出" : "Export"}</span>
|
||||
</div>
|
||||
<div className="cx-session-table-body">
|
||||
{groupedSessions.map(([group, items]) => {
|
||||
const projectSessions = allSessionsByCwd.get(group) || items;
|
||||
const selectedProjectCount = projectSessions.filter((item) => selectedSessionSet.has(item.id)).length;
|
||||
const projectSelected = projectSessions.length > 0 && selectedProjectCount === projectSessions.length;
|
||||
const projectPartiallySelected = selectedProjectCount > 0 && !projectSelected;
|
||||
const groupCountLabel = items.length === projectSessions.length
|
||||
? copy.projectCount(projectSessions.length, sessionPreviewTruncated)
|
||||
: copy.projectShown(items.length, projectSessions.length);
|
||||
return (
|
||||
<div className="cx-session-group" key={group}>
|
||||
{sessionGroupByCwd && (
|
||||
<label className={cx("cx-session-group-heading", projectSelected && "cx-session-group-heading--selected", projectPartiallySelected && "cx-session-group-heading--partial")}>
|
||||
<input
|
||||
className="cx-session-checkbox"
|
||||
type="checkbox"
|
||||
ref={(input) => {
|
||||
if (input) input.indeterminate = projectPartiallySelected;
|
||||
}}
|
||||
checked={projectSelected}
|
||||
onChange={(event) => onSetSessionGroupSelected(projectSessions, event.target.checked)}
|
||||
aria-label={copy.selectProject(group, projectSessions.length)}
|
||||
/>
|
||||
<span title={group}>{compactPath(group, 96, isChinese ? "未记录路径" : "No path recorded")}</span>
|
||||
<em>{groupCountLabel}</em>
|
||||
</label>
|
||||
)}
|
||||
{items.map((item) => (
|
||||
<div className={cx("cx-session-browser", !sessionGroupByCwd && "cx-session-browser--flat")}>
|
||||
{sessionGroupByCwd && (
|
||||
<aside className="cx-session-folder-tree" aria-label={copy.folders}>
|
||||
<div className="cx-session-tree-heading">
|
||||
<ChevronDown size={14} strokeWidth={2} aria-hidden="true" />
|
||||
<FolderTree size={15} strokeWidth={1.9} aria-hidden="true" />
|
||||
<span>{copy.folders}</span>
|
||||
</div>
|
||||
<div className="cx-session-tree-items" role="tree">
|
||||
<button
|
||||
type="button"
|
||||
role="treeitem"
|
||||
aria-selected={selectedFolderKey === SESSION_ALL_FOLDERS_KEY}
|
||||
className={cx("cx-session-tree-all", selectedFolderKey === SESSION_ALL_FOLDERS_KEY && "cx-session-tree-item--active")}
|
||||
onClick={() => setSelectedFolderKey(SESSION_ALL_FOLDERS_KEY)}
|
||||
>
|
||||
<History size={15} strokeWidth={1.9} aria-hidden="true" />
|
||||
<span>{copy.allSessions}</span>
|
||||
<em>{filteredSessions.length}</em>
|
||||
</button>
|
||||
{orderedSessionGroups.map((folder) => (
|
||||
<div
|
||||
className={cx("cx-session-tree-item", selectedFolderKey === folder.folderKey && "cx-session-tree-item--active")}
|
||||
role="treeitem"
|
||||
aria-selected={selectedFolderKey === folder.folderKey}
|
||||
key={folder.folderKey}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="cx-session-tree-select"
|
||||
onClick={() => setSelectedFolderKey(folder.folderKey)}
|
||||
title={folder.group}
|
||||
>
|
||||
<Folder size={15} strokeWidth={1.8} aria-hidden="true" />
|
||||
<span className="cx-session-folder-copy">
|
||||
<strong>{folderDisplayName(folder.group, isChinese ? "未记录路径" : "No path recorded")}</strong>
|
||||
<small>{compactPath(folder.group, 34, isChinese ? "未记录路径" : "No path recorded")}</small>
|
||||
</span>
|
||||
<em>{folder.items.length}</em>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={cx("cx-session-pin-action", folder.pinned && "cx-session-pin-action--active")}
|
||||
onClick={() => updatePins("folders", folder.items.find((item) => item.cwd)?.cwd || "")}
|
||||
aria-label={folder.pinned ? copy.unpinFolder : copy.pinFolder}
|
||||
title={folder.pinned ? copy.unpinFolder : copy.pinFolder}
|
||||
>
|
||||
<Pin size={13} strokeWidth={1.9} fill={folder.pinned ? "currentColor" : "none"} aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</aside>
|
||||
)}
|
||||
|
||||
<div className="cx-session-results">
|
||||
{displayedSessions.length > 0 ? (
|
||||
<div
|
||||
ref={sessionScrollRef}
|
||||
className="cx-session-scroll"
|
||||
role="table"
|
||||
aria-label={copy.list}
|
||||
onScroll={handleSessionScroll}
|
||||
>
|
||||
<div className="cx-session-column-head" role="row">
|
||||
<Checkbox
|
||||
className="cx-session-select-all"
|
||||
checked={allVisibleSelected}
|
||||
indeterminate={visibleSelectionIsPartial}
|
||||
onCheckedChange={(checked) => onSetSessionGroupSelected(displayedSessions, checked)}
|
||||
aria-label={copy.selectAll}
|
||||
disabled={loading || sessionDeleteBusy}
|
||||
/>
|
||||
<span>{isChinese ? "会话" : "Session"}</span>
|
||||
<span>{isChinese ? "更新时间" : "Updated"}</span>
|
||||
<span>{isChinese ? "供应商" : "Provider"}</span>
|
||||
<span>{isChinese ? "模型" : "Model"}</span>
|
||||
<span className="cx-session-id-heading">ID</span>
|
||||
<span className="cx-session-actions-heading">{isChinese ? "操作" : "Actions"}</span>
|
||||
</div>
|
||||
<div className="cx-session-table-body" style={{ height: virtualSessionModel.totalHeight }}>
|
||||
{visibleSessionRows.map((row) => {
|
||||
const { item } = row;
|
||||
const sessionPinned = pinnedSessionSet.has(item.id);
|
||||
return (
|
||||
<div
|
||||
className={cx("cx-session-row", item.needsSync && !item.isSubagent && "cx-session-row--needs-sync", selectedSessionSet.has(item.id) && "cx-session-row--selected")}
|
||||
key={item.id}
|
||||
className={cx(
|
||||
"cx-session-row",
|
||||
"cx-session-virtual-item",
|
||||
item.needsSync && !item.isSubagent && "cx-session-row--needs-sync",
|
||||
selectedSessionSet.has(item.id) && "cx-session-row--selected",
|
||||
sessionPinned && "cx-session-row--pinned",
|
||||
)}
|
||||
key={row.key}
|
||||
role="row"
|
||||
style={{ top: row.top, height: row.height }}
|
||||
onClick={(event) => {
|
||||
if (!(event.target as HTMLElement).closest("button, input") && !loading && !sessionDeleteBusy) onToggleSessionSelected(item.id);
|
||||
}}
|
||||
@@ -500,35 +777,46 @@ export function SessionManagementPage({
|
||||
{item.isSubagent && <span className="cx-session-state" title={copy.internalHint}>{copy.internal}</span>}
|
||||
{item.needsSync && !item.isSubagent && <span className="cx-session-state cx-session-state--warn">{copy.pending}</span>}
|
||||
</div>
|
||||
{!sessionGroupByCwd && <p title={item.cwd || item.rolloutPath || undefined}>{compactPath(item.cwd || item.rolloutPath, 72, isChinese ? "未记录路径" : "No path recorded")}</p>}
|
||||
{(!sessionGroupByCwd || selectedFolderKey === SESSION_ALL_FOLDERS_KEY) && <p title={item.cwd || item.rolloutPath || undefined}>{compactPath(item.cwd || item.rolloutPath, 72, isChinese ? "未记录路径" : "No path recorded")}</p>}
|
||||
</div>
|
||||
<span className="cx-session-meta cx-session-meta--time" title={item.updatedAtMs ? new Date(item.updatedAtMs).toLocaleString() : undefined}>{formatSessionTime(item.updatedAtMs, lang)}</span>
|
||||
<code className="cx-session-meta cx-session-meta--provider" title={item.modelProvider || undefined}>{item.modelProvider || copy.unknownProvider}</code>
|
||||
<span className="cx-session-meta cx-session-meta--model" title={item.model || undefined}>{item.model || copy.noModel}</span>
|
||||
<small className="cx-session-meta cx-session-meta--id" title={item.id}>#{shortId(item.id)}</small>
|
||||
<button
|
||||
type="button"
|
||||
className="cx-session-row-export"
|
||||
onClick={() => onExportSessions([item.id])}
|
||||
disabled={loading || sessionDeleteBusy || sessionExportBusy}
|
||||
aria-label={`${copy.exportOne}: ${item.title || (isChinese ? "未命名会话" : "Untitled session")}`}
|
||||
title={copy.exportOne}
|
||||
>
|
||||
<Download size={15} strokeWidth={1.9} aria-hidden="true" />
|
||||
</button>
|
||||
<div className="cx-session-row-actions">
|
||||
<button
|
||||
type="button"
|
||||
className={cx("cx-session-pin-action", sessionPinned && "cx-session-pin-action--active")}
|
||||
onClick={() => updatePins("sessions", item.id)}
|
||||
aria-label={sessionPinned ? copy.unpinSession : copy.pinSession}
|
||||
title={sessionPinned ? copy.unpinSession : copy.pinSession}
|
||||
>
|
||||
<Pin size={14} strokeWidth={1.9} fill={sessionPinned ? "currentColor" : "none"} aria-hidden="true" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="cx-session-row-export"
|
||||
onClick={() => onExportSessions([item.id])}
|
||||
disabled={loading || sessionDeleteBusy || sessionExportBusy}
|
||||
aria-label={`${copy.exportOne}: ${item.title || (isChinese ? "未命名会话" : "Untitled session")}`}
|
||||
title={copy.exportOne}
|
||||
>
|
||||
<Download size={15} strokeWidth={1.9} aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="cx-session-empty">
|
||||
<History size={22} strokeWidth={1.7} aria-hidden="true" />
|
||||
<span>{sessionQuery ? copy.noMatch : copy.noSessions}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="cx-session-empty">
|
||||
<History size={22} strokeWidth={1.7} aria-hidden="true" />
|
||||
<span>{sessionQuery ? copy.noMatch : copy.noSessions}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{diagnostics.length ? (
|
||||
|
||||
@@ -18,6 +18,8 @@ import { PageTransition } from "../components/PageTransition";
|
||||
import { Button, ModalShell } from "../components/ui";
|
||||
import { UsageStatisticsPage } from "./UsageStatisticsPage";
|
||||
import { ProviderFailoverPage } from "./ProviderFailoverPage";
|
||||
import type { CodexLanguageStatus } from "../codexLanguageTypes";
|
||||
import { CodexLanguageControl } from "../components/CodexLanguageControl";
|
||||
import "../styles/utility-pages.css";
|
||||
|
||||
export type UtilityLanguage = "zh" | "en";
|
||||
@@ -114,6 +116,9 @@ export type SettingsPageProps = {
|
||||
onRestartCodex: () => Promise<boolean>;
|
||||
recheckBusy?: boolean;
|
||||
restartBusy?: boolean;
|
||||
interactionBusy?: boolean;
|
||||
onLanguageBusyChange?: (busy: boolean) => void;
|
||||
onCodexLanguageSaved?: (status: CodexLanguageStatus) => void;
|
||||
generalRequest?: number;
|
||||
configHealthStatus?: ReactNode;
|
||||
onChange?: () => void | Promise<void>;
|
||||
@@ -167,6 +172,9 @@ export function SettingsPage({
|
||||
onRestartCodex,
|
||||
recheckBusy = false,
|
||||
restartBusy = false,
|
||||
interactionBusy = false,
|
||||
onLanguageBusyChange,
|
||||
onCodexLanguageSaved,
|
||||
generalRequest = 0,
|
||||
configHealthStatus,
|
||||
onChange,
|
||||
@@ -182,7 +190,7 @@ export function SettingsPage({
|
||||
if (!restartBusy) setRestartConfirmOpen(false);
|
||||
};
|
||||
const confirmRestart = async () => {
|
||||
if (restartBusy) return;
|
||||
if (restartBusy || interactionBusy) return;
|
||||
if (await onRestartCodex()) setRestartConfirmOpen(false);
|
||||
};
|
||||
|
||||
@@ -232,6 +240,8 @@ export function SettingsPage({
|
||||
)}
|
||||
/>
|
||||
|
||||
<CodexLanguageControl lang={lang} configDir={configDir} active={active && tab === "general"} disabled={interactionBusy} onBusyChange={onLanguageBusyChange} onPreferencesSaved={onCodexLanguageSaved} />
|
||||
|
||||
<SettingRow
|
||||
icon={Sparkles}
|
||||
title={copy.productTitle}
|
||||
@@ -268,7 +278,7 @@ export function SettingsPage({
|
||||
type="button"
|
||||
className="cx-page-button cx-page-button--secondary"
|
||||
onClick={() => setRestartConfirmOpen(true)}
|
||||
disabled={restartBusy}
|
||||
disabled={restartBusy || interactionBusy}
|
||||
>
|
||||
{restartBusy ? <Loader2 size={15} className="cx-page-spin" aria-hidden="true" /> : <Power size={15} aria-hidden="true" />}
|
||||
{restartBusy ? copy.restartingLabel : copy.restartLabel}
|
||||
@@ -306,7 +316,7 @@ export function SettingsPage({
|
||||
variant="danger"
|
||||
icon={restartBusy ? <Loader2 size={16} className="cx-page-spin" /> : <Power size={16} />}
|
||||
onClick={() => void confirmRestart()}
|
||||
disabled={restartBusy}
|
||||
disabled={restartBusy || interactionBusy}
|
||||
>
|
||||
{restartBusy ? copy.restartingLabel : copy.restartConfirmLabel}
|
||||
</Button>
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
|
||||
export type ProviderBalance = {
|
||||
source: "local" | "detected";
|
||||
providerId: string;
|
||||
vendor: "deepseek" | "openrouter" | "siliconflow" | "moonshot" | null;
|
||||
supported: boolean;
|
||||
balanceKind: "balance" | "credit_limit" | null;
|
||||
balances: { currency: string; amount: string }[];
|
||||
checkedAt: string | null;
|
||||
errorCode: string | null;
|
||||
};
|
||||
export type ProviderBalanceState = {
|
||||
balances: ProviderBalance[];
|
||||
failed: boolean;
|
||||
loading: boolean;
|
||||
refreshingKeys: string[];
|
||||
refreshBalance: (source: "local" | "detected", providerId: string) => Promise<void>;
|
||||
};
|
||||
|
||||
function keepLastBalance(previous: ProviderBalance | undefined, next: ProviderBalance): ProviderBalance {
|
||||
if (next.errorCode && previous?.balances.length) {
|
||||
return { ...next, balances: previous.balances, balanceKind: previous.balanceKind, checkedAt: previous.checkedAt };
|
||||
}
|
||||
if (!next.errorCode && previous?.checkedAt && next.checkedAt && previous.checkedAt > next.checkedAt) return previous;
|
||||
return next;
|
||||
}
|
||||
const REFRESH_INTERVAL = 5 * 60 * 1000;
|
||||
|
||||
// Lives in App, so navigating away from Providers does not stop refreshing.
|
||||
export function useProviderBalances(configDir: string, revision: string, ready: boolean) {
|
||||
const [snapshot, setSnapshot] = useState({ configDir, revision, balances: [] as ProviderBalance[], failed: false, loading: true });
|
||||
const scope = JSON.stringify([configDir, revision]);
|
||||
const scopeRef = useRef(scope);
|
||||
scopeRef.current = scope;
|
||||
const manualInFlight = useRef(new Set<string>());
|
||||
const manualVersions = useRef(new Map<string, number>());
|
||||
const [manualBusy, setManualBusy] = useState<Record<string, boolean>>({});
|
||||
const refreshBalance = useCallback(async (source: "local" | "detected", providerId: string) => {
|
||||
if (!ready) return;
|
||||
const token = JSON.stringify([scope, source, providerId]);
|
||||
if (manualInFlight.current.has(token)) return;
|
||||
manualInFlight.current.add(token);
|
||||
manualVersions.current.set(token, (manualVersions.current.get(token) ?? 0) + 1);
|
||||
setManualBusy(previous => ({ ...previous, [token]: true }));
|
||||
try {
|
||||
const result = await invoke<ProviderBalance>("refresh_provider_balance", { configDir, source, providerId });
|
||||
if (scopeRef.current !== scope) return;
|
||||
setSnapshot(previous => {
|
||||
const matches = (item: ProviderBalance) => item.source === source && item.providerId === providerId;
|
||||
const updated = keepLastBalance(previous.balances.find(matches), result);
|
||||
return { ...previous, failed: false, balances: [...previous.balances.filter(item => !matches(item)), updated] };
|
||||
});
|
||||
} catch {
|
||||
if (scopeRef.current === scope) setSnapshot(previous => ({ ...previous, balances: previous.balances.some(item => item.source === source && item.providerId === providerId)
|
||||
? previous.balances.map(item => item.source === source && item.providerId === providerId ? { ...item, errorCode: "refresh_failed" } : item)
|
||||
: [...previous.balances, { source, providerId, supported: true, vendor: null, balanceKind: null, balances: [], checkedAt: null, errorCode: "refresh_failed" }] }));
|
||||
} finally {
|
||||
manualVersions.current.set(token, (manualVersions.current.get(token) ?? 0) + 1);
|
||||
manualInFlight.current.delete(token);
|
||||
setManualBusy(previous => { const next = { ...previous }; delete next[token]; return next; });
|
||||
}
|
||||
}, [configDir, ready, scope]);
|
||||
useEffect(() => {
|
||||
if (!ready) return;
|
||||
let disposed = false;
|
||||
let inFlight = false;
|
||||
let lastAttempt = 0;
|
||||
let timer: number | undefined;
|
||||
setSnapshot(previous => previous.configDir === configDir && previous.revision === revision
|
||||
? { ...previous, loading: previous.balances.length === 0 }
|
||||
: { configDir, revision, balances: [], failed: false, loading: true });
|
||||
const refresh = async () => {
|
||||
if (disposed || inFlight) return;
|
||||
inFlight = true;
|
||||
if (timer !== undefined) window.clearTimeout(timer);
|
||||
lastAttempt = Date.now();
|
||||
let nextDelay = REFRESH_INTERVAL;
|
||||
const versionsAtStart = new Map(manualVersions.current);
|
||||
const shouldPreserveManual = (item: ProviderBalance) => {
|
||||
const token = JSON.stringify([scope, item.source, item.providerId]);
|
||||
return manualInFlight.current.has(token) || (manualVersions.current.get(token) ?? 0) !== (versionsAtStart.get(token) ?? 0);
|
||||
};
|
||||
try {
|
||||
const balances = await invoke<ProviderBalance[]>("get_provider_balances", { configDir });
|
||||
// A manual query can warm the cache between automatic reads. Follow
|
||||
// the data's timestamp rather than restarting a full five-minute wait.
|
||||
const now = Date.now();
|
||||
for (const item of balances.filter(item => item.supported)) {
|
||||
const ttl = item.errorCode ? 60_000 : REFRESH_INTERVAL;
|
||||
const checked = item.checkedAt ? Date.parse(item.checkedAt) : NaN;
|
||||
const age = Number.isFinite(checked) ? Math.max(0, now - checked) : 0;
|
||||
nextDelay = Math.min(nextDelay, Math.max(1_000, ttl - age + 1_000));
|
||||
}
|
||||
if (!disposed) setSnapshot(previous => ({ configDir, revision, balances: balances.map(next => {
|
||||
const current = previous.balances.find(item => item.source === next.source && item.providerId === next.providerId);
|
||||
return current && shouldPreserveManual(next) ? current : keepLastBalance(current, next);
|
||||
}), failed: false, loading: false }));
|
||||
} catch {
|
||||
nextDelay = 60_000;
|
||||
if (!disposed) setSnapshot(previous => ({ ...previous, loading: false, failed: previous.balances.length === 0, balances: previous.balances.map(item => item.supported && !shouldPreserveManual(item) ? { ...item, errorCode: "refresh_failed" } : item) }));
|
||||
} finally {
|
||||
inFlight = false;
|
||||
lastAttempt = Date.now();
|
||||
if (!disposed) timer = window.setTimeout(() => { void refresh(); }, nextDelay);
|
||||
}
|
||||
};
|
||||
const onWake = () => { if (Date.now() - lastAttempt >= REFRESH_INTERVAL) void refresh(); };
|
||||
void refresh();
|
||||
window.addEventListener("focus", onWake);
|
||||
document.addEventListener("visibilitychange", onWake);
|
||||
return () => { disposed = true; if (timer !== undefined) window.clearTimeout(timer); window.removeEventListener("focus", onWake); document.removeEventListener("visibilitychange", onWake); };
|
||||
}, [configDir, revision, ready, scope]);
|
||||
const visible = snapshot.configDir === configDir && snapshot.revision === revision
|
||||
? snapshot : { configDir, revision, balances: [] as ProviderBalance[], loading: true, failed: false };
|
||||
const refreshingKeys = Object.keys(manualBusy).flatMap(token => {
|
||||
const [requestScope, source, id] = JSON.parse(token) as string[];
|
||||
return requestScope === scope ? [`${source}:${id}`] : [];
|
||||
});
|
||||
return { ...visible, refreshingKeys, refreshBalance };
|
||||
}
|
||||
|
||||
export function supportsProviderBalance(baseUrl: string) {
|
||||
try {
|
||||
const url = new URL(baseUrl);
|
||||
return url.protocol === "https:" && ["api.deepseek.com", "openrouter.ai", "api.siliconflow.cn", "api.moonshot.cn"].includes(url.hostname);
|
||||
} catch { return false; }
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import type { ProviderHeader } from "./providerHeaders";
|
||||
|
||||
export const PROVIDER_HEADER_PRESETS = [
|
||||
{
|
||||
id: "claude_code",
|
||||
label: { zh: "Claude Code", en: "Claude Code" },
|
||||
name: "User-Agent",
|
||||
value: "claude-cli/2.1.161 (external, cli)",
|
||||
},
|
||||
{
|
||||
id: "kilo_code",
|
||||
label: { zh: "Kilo Code", en: "Kilo Code" },
|
||||
name: "User-Agent",
|
||||
value: "Kilo-Code/1.0",
|
||||
},
|
||||
] as const;
|
||||
|
||||
export type ProviderHeaderPresetId = typeof PROVIDER_HEADER_PRESETS[number]["id"];
|
||||
|
||||
/** Unknown IDs are a no-op. A preset changes one UA row and preserves drafts. */
|
||||
export function applyProviderHeaderPreset(rows: readonly ProviderHeader[], id: string): ProviderHeader[] {
|
||||
const preset = PROVIDER_HEADER_PRESETS.find((entry) => entry.id === id);
|
||||
if (!preset) return [...rows];
|
||||
|
||||
let index = rows.findIndex((row) => row.name.trim().toLowerCase() === "user-agent");
|
||||
if (index < 0) index = rows.findIndex((row) => !row.name.trim() && row.value === "");
|
||||
const header: ProviderHeader = { name: preset.name, value: preset.value, source: "static" };
|
||||
if (index < 0) return [...rows, header];
|
||||
return rows.map((row, position) => position === index ? { ...row, ...header } : row);
|
||||
}
|
||||
|
||||
/** Literal examples describe the named header's purpose; environment rows use their own hint. */
|
||||
export function providerHeaderValuePlaceholder(name: string, lang: "zh" | "en"): string {
|
||||
switch (name.trim().toLowerCase()) {
|
||||
case "user-agent":
|
||||
return lang === "zh" ? "例如 claude-cli/2.1.161 (external, cli)" : "e.g. claude-cli/2.1.161 (external, cli)";
|
||||
case "http-referer":
|
||||
return lang === "zh" ? "例如 https://your-app.example" : "e.g. https://your-app.example";
|
||||
case "x-title":
|
||||
case "x-openrouter-title":
|
||||
return lang === "zh" ? "例如 你的应用名称" : "e.g. Your app name";
|
||||
case "authorization":
|
||||
return lang === "zh" ? "例如 Bearer <访问令牌>" : "e.g. Bearer <access token>";
|
||||
case "x-api-key":
|
||||
case "x-goog-api-key":
|
||||
return lang === "zh" ? "例如 供应商提供的 API Key" : "e.g. API key from your provider";
|
||||
default:
|
||||
return lang === "zh" ? "填写该请求头的值" : "Enter this header's value";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
export type ProviderHeaderSource = "static" | "env";
|
||||
|
||||
export type ProviderHeader = {
|
||||
name: string;
|
||||
value: string;
|
||||
source: ProviderHeaderSource;
|
||||
};
|
||||
|
||||
export type ProviderHeaderError = { name?: string; value?: string; source?: string };
|
||||
type Language = "zh" | "en";
|
||||
|
||||
// RFC 9110 field-name tokens. Header values may contain horizontal tabs and
|
||||
// UTF-8 text, matching reqwest's HeaderValue validation on the backend.
|
||||
const HEADER_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
||||
const INVALID_HEADER_VALUE = /[\u0000-\u0008\u000a-\u001f\u007f]/;
|
||||
const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
||||
|
||||
export function createProviderHeader(source: ProviderHeaderSource = "static"): ProviderHeader {
|
||||
return { name: "", value: "", source };
|
||||
}
|
||||
|
||||
export function updateProviderHeader(rows: readonly ProviderHeader[], index: number, patch: Partial<ProviderHeader>): ProviderHeader[] {
|
||||
return rows.map((row, position) => position === index ? { ...row, ...patch } : row);
|
||||
}
|
||||
|
||||
export function removeProviderHeader(rows: readonly ProviderHeader[], index: number): ProviderHeader[] {
|
||||
return rows.filter((_, position) => position !== index);
|
||||
}
|
||||
|
||||
export function validateProviderHeaders(rows: readonly ProviderHeader[], lang: Language = "en") {
|
||||
const counts = new Map<string, number>();
|
||||
for (const row of rows) {
|
||||
const name = row.name.trim().toLowerCase();
|
||||
if (name) counts.set(name, (counts.get(name) ?? 0) + 1);
|
||||
}
|
||||
const errors: ProviderHeaderError[] = rows.map((row) => {
|
||||
const error: ProviderHeaderError = {};
|
||||
const name = row.name.trim();
|
||||
if (!name) error.name = lang === "zh" ? "请填写 Header 名称" : "Enter a header name";
|
||||
else if (!HEADER_NAME.test(name)) error.name = lang === "zh" ? "名称只能使用英文字母、数字和 HTTP 允许的符号" : "Use letters, numbers and valid HTTP header symbols";
|
||||
else if ((counts.get(name.toLowerCase()) ?? 0) > 1) error.name = lang === "zh" ? "此名称重复(不区分大小写),请删除或重命名" : "Duplicate header name (case insensitive). Remove or rename it";
|
||||
if (row.source === "env") {
|
||||
if (!ENV_NAME.test(row.value)) error.value = lang === "zh" ? "请填写环境变量名,如 PROVIDER_PROJECT;仅允许字母、数字和下划线,且不能以数字开头" : "Enter an environment variable name, e.g. PROVIDER_PROJECT, using letters, numbers and underscores, without a leading digit";
|
||||
} else if (row.source === "static") {
|
||||
if (INVALID_HEADER_VALUE.test(row.value)) error.value = lang === "zh" ? "Header 值不能包含换行或控制字符" : "Header values cannot contain line breaks or control characters";
|
||||
} else {
|
||||
error.source = lang === "zh" ? "请选择固定值或环境变量" : "Choose a literal value or environment variable";
|
||||
}
|
||||
return error;
|
||||
});
|
||||
return { errors, valid: errors.every((error) => !error.name && !error.value && !error.source) };
|
||||
}
|
||||
|
||||
/** Normalize only names; changing a value's whitespace can change its meaning. */
|
||||
export function normalizeProviderHeaders(rows: readonly ProviderHeader[]): ProviderHeader[] {
|
||||
if (!validateProviderHeaders(rows).valid) throw new Error("Invalid provider headers");
|
||||
return rows.map((row) => ({ ...row, name: row.name.trim() }));
|
||||
}
|
||||
|
||||
export function findProviderHeader(rows: readonly ProviderHeader[], name: string): ProviderHeader | undefined {
|
||||
const target = name.trim().toLowerCase();
|
||||
return rows.find((row) => row.name.trim().toLowerCase() === target);
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import type { ProviderHeader } from "./providerHeaders";
|
||||
|
||||
export type ProviderHeadersControlState = {
|
||||
busy: boolean;
|
||||
reading: boolean;
|
||||
valid: boolean;
|
||||
error: "read" | "write" | null;
|
||||
};
|
||||
|
||||
type Options = {
|
||||
read: (configText: string) => Promise<ProviderHeader[]>;
|
||||
update: (configText: string, headers: ProviderHeader[]) => Promise<string>;
|
||||
getConfigText: () => string;
|
||||
isValid: (rows: readonly ProviderHeader[]) => boolean;
|
||||
normalize: (rows: readonly ProviderHeader[]) => ProviderHeader[];
|
||||
onRowsChange: (rows: ProviderHeader[]) => void;
|
||||
onConfigChange: (configText: string) => void;
|
||||
onStateChange: (state: ProviderHeadersControlState) => void;
|
||||
};
|
||||
|
||||
/** Keep local drafts and asynchronous TOML patches within the current form. */
|
||||
export function createProviderHeadersControl(options: Options) {
|
||||
let disposed = false;
|
||||
let request = 0;
|
||||
let revision = 0;
|
||||
let source: string | null = null;
|
||||
let rows: ProviderHeader[] = [];
|
||||
let dirty = false;
|
||||
let published: { text: string; revision: number } | null = null;
|
||||
|
||||
const emit = (state: ProviderHeadersControlState) => {
|
||||
if (!disposed) options.onStateChange(state);
|
||||
};
|
||||
const current = (id: number, text: string) => !disposed && request === id && options.getConfigText() === text;
|
||||
const idle = (valid: boolean) => emit({ busy: false, reading: false, valid, error: null });
|
||||
|
||||
async function read(text: string) {
|
||||
const id = ++request;
|
||||
emit({ busy: true, reading: true, valid: false, error: null });
|
||||
try {
|
||||
const result = await options.read(text);
|
||||
if (!current(id, text)) return;
|
||||
rows = result.map((row) => ({ ...row }));
|
||||
options.onRowsChange(rows);
|
||||
idle(options.isValid(rows));
|
||||
} catch {
|
||||
// IPC errors can contain configuration snippets. Only expose the failed
|
||||
// operation, never the raw exception or a resolved environment value.
|
||||
if (current(id, text)) emit({ busy: false, reading: false, valid: false, error: "read" });
|
||||
}
|
||||
}
|
||||
|
||||
async function write(text: string) {
|
||||
const id = ++request;
|
||||
const editedRevision = revision;
|
||||
const headers = options.normalize(rows);
|
||||
emit({ busy: true, reading: false, valid: true, error: null });
|
||||
try {
|
||||
const result = await options.update(text, headers);
|
||||
if (!current(id, text)) return;
|
||||
dirty = false;
|
||||
if (result !== text) {
|
||||
published = { text: result, revision: editedRevision };
|
||||
options.onConfigChange(result);
|
||||
}
|
||||
idle(true);
|
||||
} catch {
|
||||
if (current(id, text)) emit({ busy: false, reading: false, valid: false, error: "write" });
|
||||
}
|
||||
}
|
||||
|
||||
async function load(configText: string) {
|
||||
if (disposed || source === configText) return;
|
||||
source = configText;
|
||||
++request;
|
||||
const echo = published;
|
||||
published = null;
|
||||
if (echo?.text === configText && echo.revision === revision && !dirty) {
|
||||
idle(options.isValid(rows));
|
||||
return;
|
||||
}
|
||||
if (dirty) {
|
||||
// Reapply only edited header fields to the latest source, preserving an
|
||||
// unrelated model, endpoint or TOML change. Invalid rows stay editable.
|
||||
if (options.isValid(rows)) await write(configText);
|
||||
else idle(false);
|
||||
return;
|
||||
}
|
||||
if (!configText.trim()) {
|
||||
emit({ busy: false, reading: true, valid: false, error: null });
|
||||
return;
|
||||
}
|
||||
await read(configText);
|
||||
}
|
||||
|
||||
async function changeRows(next: readonly ProviderHeader[]) {
|
||||
if (disposed) return;
|
||||
++request;
|
||||
++revision;
|
||||
rows = next.map((row) => ({ ...row }));
|
||||
dirty = true;
|
||||
options.onRowsChange(rows);
|
||||
if (!options.isValid(rows)) {
|
||||
idle(false);
|
||||
return;
|
||||
}
|
||||
await write(options.getConfigText());
|
||||
}
|
||||
|
||||
async function retry() {
|
||||
if (disposed) return;
|
||||
const text = options.getConfigText();
|
||||
if (dirty && options.isValid(rows)) await write(text);
|
||||
else if (!dirty) await read(text);
|
||||
}
|
||||
|
||||
return {
|
||||
load,
|
||||
changeRows,
|
||||
retry,
|
||||
dispose() { disposed = true; ++request; },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
export type UpstreamApi = "responses" | "chat_completions" | "anthropic_messages" | "gemini";
|
||||
|
||||
export function providerUpstreamApi(provider: { upstreamApi?: string | null; wireApi?: string }): string {
|
||||
const configured = provider.upstreamApi?.trim().toLowerCase();
|
||||
if (configured === "chat_completions" || configured === "openai_chat") return "chat_completions";
|
||||
if (configured === "anthropic_messages" || configured === "anthropic") return "anthropic_messages";
|
||||
if (configured === "gemini" || configured === "gemini_native") return "gemini";
|
||||
if (configured === "responses") return "responses";
|
||||
if (configured) return configured;
|
||||
const legacy = provider.wireApi?.trim();
|
||||
if (legacy === "chat" || legacy === "chat_completions") return "chat_completions";
|
||||
return !legacy || legacy === "official" ? "responses" : legacy;
|
||||
}
|
||||
|
||||
export function providerRequiresConversion(provider: { upstreamApi?: string | null; wireApi?: string }): boolean {
|
||||
return providerUpstreamApi(provider) !== "responses";
|
||||
}
|
||||
@@ -2,6 +2,33 @@ type OrderedProviderRow = {
|
||||
isCurrent: boolean;
|
||||
};
|
||||
|
||||
type IdentifiedProviderRow = { source: string; id: string };
|
||||
|
||||
export function providerRowKey(row: IdentifiedProviderRow): string {
|
||||
return `${row.source}:${row.id}`;
|
||||
}
|
||||
|
||||
export function applyProviderRowOrder<Row extends IdentifiedProviderRow>(rows: readonly Row[], order: readonly string[]): Row[] {
|
||||
const remaining = new Map(rows.map((row) => [providerRowKey(row), row]));
|
||||
const sorted: Row[] = [];
|
||||
for (const key of order) {
|
||||
const row = remaining.get(key);
|
||||
if (row) {
|
||||
sorted.push(row);
|
||||
remaining.delete(key);
|
||||
}
|
||||
}
|
||||
return [...sorted, ...remaining.values()];
|
||||
}
|
||||
|
||||
export function moveProviderRow(order: readonly string[], source: string, target: string, position: "before" | "after"): string[] {
|
||||
if (source === target || !order.includes(source) || !order.includes(target)) return [...order];
|
||||
const next = order.filter((key) => key !== source);
|
||||
const targetIndex = next.indexOf(target);
|
||||
next.splice(targetIndex + (position === "after" ? 1 : 0), 0, source);
|
||||
return next;
|
||||
}
|
||||
|
||||
export function orderProviderRows<
|
||||
Official extends OrderedProviderRow,
|
||||
Detected extends OrderedProviderRow,
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
export const SESSION_FOLDER_UNKNOWN_KEY = "__codexx_no_workspace__";
|
||||
const SESSION_PINS_STORAGE_PREFIX = "codexx.sessionPins.v2";
|
||||
|
||||
export type SessionDirectoryIdentities = Readonly<Record<string, string>>;
|
||||
export type SessionPinPreferences = { folders: string[]; sessions: string[] };
|
||||
export type SessionDirectoryGroup<T> = { group: string; folderKey: string; items: T[] };
|
||||
|
||||
/** Only the backend can confirm that differently spelled paths name one directory. */
|
||||
export function sessionDirectoryKey(
|
||||
path?: string | null,
|
||||
identities?: SessionDirectoryIdentities,
|
||||
): string {
|
||||
if (path == null || path === "") return SESSION_FOLDER_UNKNOWN_KEY;
|
||||
if (identities && Object.prototype.hasOwnProperty.call(identities, path)) {
|
||||
return identities[path];
|
||||
}
|
||||
// Missing/offline directories keep their exact spelling. Case, backslashes,
|
||||
// roots and spaces can all distinguish legitimate paths on some filesystems.
|
||||
return `path:${path}`;
|
||||
}
|
||||
|
||||
export function sessionPinStorageKey(codexDir: string, verifiedScope?: string | null) {
|
||||
// v1 discarded case and cannot safely assign its pins to a particular home.
|
||||
// A snapshot's file ID alone is not a permanent home identity after deletion.
|
||||
return `${SESSION_PINS_STORAGE_PREFIX}:${encodeURIComponent(verifiedScope || sessionDirectoryKey(codexDir))}`;
|
||||
}
|
||||
|
||||
export function pinnedSessionDirectoryKeys(folders: readonly string[], identities?: SessionDirectoryIdentities): Set<string> {
|
||||
const keys = new Set<string>();
|
||||
for (const stored of folders) {
|
||||
if (stored === SESSION_FOLDER_UNKNOWN_KEY) keys.add(stored);
|
||||
else if (stored.startsWith("path:")) keys.add(sessionDirectoryKey(stored.slice(5), identities));
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
/** Persist original paths so offline/recreated folders retain their pins. */
|
||||
export function toggleFolderPins(
|
||||
folders: readonly string[],
|
||||
path?: string | null,
|
||||
identities?: SessionDirectoryIdentities,
|
||||
): string[] {
|
||||
const currentKey = sessionDirectoryKey(path, identities);
|
||||
const belongsToCurrentFolder = (stored: string) => pinnedSessionDirectoryKeys([stored], identities).has(currentKey);
|
||||
if (folders.some(belongsToCurrentFolder)) return folders.filter((stored) => !belongsToCurrentFolder(stored));
|
||||
return [...new Set([...folders, sessionDirectoryKey(path)])];
|
||||
}
|
||||
|
||||
export function readSessionPinPreferences(
|
||||
storageKey: string,
|
||||
storage: Pick<Storage, "getItem">,
|
||||
): SessionPinPreferences {
|
||||
try {
|
||||
const parsed = JSON.parse(storage.getItem(storageKey) || "{}") as Partial<SessionPinPreferences>;
|
||||
return {
|
||||
folders: Array.isArray(parsed.folders) ? parsed.folders.filter((value): value is string => typeof value === "string") : [],
|
||||
sessions: Array.isArray(parsed.sessions) ? parsed.sessions.filter((value): value is string => typeof value === "string") : [],
|
||||
};
|
||||
} catch {
|
||||
return { folders: [], sessions: [] };
|
||||
}
|
||||
}
|
||||
|
||||
export function mergeSessionDirectoryGroups<T extends { cwd?: string | null }>(
|
||||
groups: ReadonlyArray<readonly [string, readonly T[]]>,
|
||||
identities?: SessionDirectoryIdentities,
|
||||
): SessionDirectoryGroup<T>[] {
|
||||
const result = new Map<string, SessionDirectoryGroup<T>>();
|
||||
for (const [group, items] of groups) {
|
||||
const folderKey = sessionDirectoryKey(items.find((item) => item.cwd)?.cwd, identities);
|
||||
const existing = result.get(folderKey);
|
||||
if (existing) existing.items.push(...items);
|
||||
else result.set(folderKey, { group, folderKey, items: [...items] });
|
||||
}
|
||||
return [...result.values()];
|
||||
}
|
||||
|
||||
export function sessionsForDirectoryGroup<T>(groups: ReadonlyArray<SessionDirectoryGroup<T>>, key: string): T[] {
|
||||
return groups.find((group) => group.folderKey === key)?.items || [];
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
export type LoadingScope = "general" | "sessionSync";
|
||||
|
||||
/** Session maintenance still blocks other UI actions; only activation is exempt. */
|
||||
export function providerActivationIsBusy(loadingScopes: Iterable<LoadingScope>, actions: Iterable<string>): boolean {
|
||||
for (const scope of loadingScopes) if (scope !== "sessionSync") return true;
|
||||
for (const action of actions) if (action !== "syncSessions") return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
export type SessionStatusContext = {
|
||||
configDir: string;
|
||||
targetProvider: string;
|
||||
providerRevision: number;
|
||||
};
|
||||
|
||||
export function sessionStatusContextKey(context: SessionStatusContext): string {
|
||||
return JSON.stringify([context.configDir, context.targetProvider, context.providerRevision]);
|
||||
}
|
||||
|
||||
export function createSessionStatusTracker() {
|
||||
let sequence = 0;
|
||||
return {
|
||||
invalidate() { sequence += 1; },
|
||||
begin(context: SessionStatusContext) {
|
||||
return Object.freeze({ sequence: ++sequence, context: Object.freeze({ ...context }) });
|
||||
},
|
||||
isCurrent(request: { sequence: number; context: SessionStatusContext }, current: SessionStatusContext | null) {
|
||||
return Boolean(current && request.sequence === sequence
|
||||
&& request.context.configDir === current.configDir
|
||||
&& request.context.targetProvider === current.targetProvider
|
||||
&& request.context.providerRevision === current.providerRevision);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function readCurrentSessionStatus<T extends { targetProvider: string }>(
|
||||
tracker: ReturnType<typeof createSessionStatusTracker>,
|
||||
getContext: () => SessionStatusContext | null,
|
||||
read: (context: Readonly<SessionStatusContext>) => Promise<T>,
|
||||
accept: (status: T) => void,
|
||||
): Promise<T | null> {
|
||||
const context = getContext();
|
||||
if (!context) return null;
|
||||
const request = tracker.begin(context);
|
||||
try {
|
||||
const status = await read(request.context);
|
||||
if (!tracker.isCurrent(request, getContext()) || status.targetProvider !== request.context.targetProvider) return null;
|
||||
accept(status);
|
||||
return status;
|
||||
} catch (error) {
|
||||
if (!tracker.isCurrent(request, getContext())) return null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -224,6 +224,12 @@
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.cx-update-notes .cx-update-log-path {
|
||||
margin-top: 8px;
|
||||
overflow-wrap: anywhere;
|
||||
user-select: text;
|
||||
}
|
||||
|
||||
@keyframes cx-update-progress-indeterminate {
|
||||
from { transform: translateX(-110%); }
|
||||
to { transform: translateX(300%); }
|
||||
@@ -414,3 +420,14 @@
|
||||
@keyframes cx-app-dialog-spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
/* Actionable notices allow time to read and click, using the existing toast. */
|
||||
.cx-app-toast--actionable { pointer-events: auto; animation: cx-app-toast-enter 180ms ease-out both, cx-app-toast-exit 180ms ease-in 15s forwards; }
|
||||
.cx-app-toast--actionable:hover, .cx-app-toast--actionable:focus-within { animation-play-state: paused; }
|
||||
.cx-app-toast-action, .cx-app-toast-dismiss { flex-shrink: 0; border: 0; padding: 4px; background: transparent; color: inherit; cursor: pointer; }
|
||||
.cx-app-toast-action { font: inherit; font-size: 12px; font-weight: 600; text-decoration: underline; text-underline-offset: 3px; }
|
||||
.cx-app-toast-dismiss { display: grid; place-items: center; opacity: .65; }
|
||||
.cx-app-toast-action:disabled { cursor: wait; opacity: .5; }
|
||||
.cx-app-toast-action:focus-visible, .cx-app-toast-dismiss:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; border-radius: 3px; }
|
||||
|
||||
.cx-app-toast--persistent { pointer-events: auto; animation: cx-app-toast-enter 180ms ease-out both; }
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
/* Reuse the settings page row, icon, typography and theme tokens. */
|
||||
.cx-page-setting-row.cx-codex-language {
|
||||
grid-template-columns: 40px minmax(0, 1fr) auto;
|
||||
}
|
||||
.cx-codex-language .cx-page-setting-copy p {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.cx-page-setting-action.cx-codex-language-action {
|
||||
grid-column: auto;
|
||||
justify-self: end;
|
||||
display: grid;
|
||||
justify-items: end;
|
||||
gap: 5px;
|
||||
}
|
||||
.cx-codex-language-switch {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
color: var(--cx-page-muted);
|
||||
font-size: 12px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.cx-codex-language-switch .ui-toggle {
|
||||
--ui-accent: var(--cx-page-blue);
|
||||
}
|
||||
.cx-codex-language-enabled { color: var(--cx-page-blue); }
|
||||
.cx-codex-language-loading { width: 40px; height: 23px; display: grid; place-items: center; }
|
||||
.cx-codex-language .cx-page-setting-copy .cx-codex-language-error { color: var(--ui-danger); }
|
||||
@@ -125,3 +125,10 @@
|
||||
@keyframes cx-config-health-enter { from { opacity: 0; transform: translateY(-5px); } to { opacity: 1; transform: translateY(0); } }
|
||||
@keyframes cx-config-health-spin { to { transform: rotate(360deg); } }
|
||||
@media (prefers-reduced-motion: reduce) { .cx-config-health-toast, .cx-config-health-spinner { animation: none; } }
|
||||
|
||||
.cx-config-health-location { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 10px; }
|
||||
.cx-config-health-location code,
|
||||
.cx-config-health-key code { color: var(--cx-health-text); font-size: 11px; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.cx-config-health-location span { flex-shrink: 0; }
|
||||
.cx-config-health-issues p.cx-config-health-suggestion,
|
||||
.cx-config-health-toast-content p.cx-config-health-suggestion { color: var(--cx-health-text); }
|
||||
|
||||
@@ -603,10 +603,56 @@
|
||||
background-clip: padding-box;
|
||||
}
|
||||
|
||||
:root[data-theme="dark"] .cx-session-folder-tree,
|
||||
:root[data-theme="dark"] .cx-session-tree-heading {
|
||||
color: var(--cx-dark-muted);
|
||||
background: var(--cx-dark-surface-raised);
|
||||
border-color: var(--cx-dark-border);
|
||||
}
|
||||
|
||||
:root[data-theme="dark"] .cx-session-results {
|
||||
background: var(--cx-dark-surface);
|
||||
}
|
||||
|
||||
:root[data-theme="dark"] .cx-session-tree-all,
|
||||
:root[data-theme="dark"] .cx-session-tree-item {
|
||||
color: var(--cx-dark-muted);
|
||||
}
|
||||
|
||||
:root[data-theme="dark"] .cx-session-tree-all:hover,
|
||||
:root[data-theme="dark"] .cx-session-tree-item:hover {
|
||||
color: var(--cx-dark-text);
|
||||
background: var(--cx-dark-surface-hover);
|
||||
}
|
||||
|
||||
:root[data-theme="dark"] .cx-session-tree-item--active {
|
||||
color: var(--cx-dark-blue);
|
||||
background: var(--cx-dark-blue-surface);
|
||||
border-color: #5879aa;
|
||||
}
|
||||
|
||||
:root[data-theme="dark"] .cx-session-tree-item--active .cx-session-folder-copy strong {
|
||||
color: var(--cx-dark-blue);
|
||||
}
|
||||
|
||||
:root[data-theme="dark"] .cx-session-group + .cx-session-group {
|
||||
border-top-color: var(--cx-dark-surface-recessed);
|
||||
}
|
||||
|
||||
:root[data-theme="dark"] .cx-session-group-heading--selected,
|
||||
:root[data-theme="dark"] .cx-session-group-heading--partial {
|
||||
color: var(--cx-dark-blue);
|
||||
background: var(--cx-dark-blue-surface);
|
||||
}
|
||||
|
||||
:root[data-theme="dark"] .cx-session-folder-copy strong {
|
||||
color: var(--cx-dark-text);
|
||||
}
|
||||
|
||||
:root[data-theme="dark"] .cx-session-folder-copy small {
|
||||
color: var(--cx-dark-muted);
|
||||
}
|
||||
|
||||
:root[data-theme="dark"] .cx-session-row {
|
||||
background: var(--cx-dark-surface);
|
||||
border-color: var(--cx-dark-border);
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
.cx-provider-balance {
|
||||
--cx-balance-value: #16845a;
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
max-width: 250px;
|
||||
justify-self: center;
|
||||
display: grid;
|
||||
gap: 3px;
|
||||
padding: 0 12px 0 14px;
|
||||
border-left: 1px solid var(--cx-provider-border);
|
||||
}
|
||||
:root[data-theme="dark"] .cx-provider-balance { --cx-balance-value: var(--cx-dark-green); }
|
||||
.cx-provider-balance-heading {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
min-height: 18px;
|
||||
color: var(--cx-provider-muted);
|
||||
font-size: 11px;
|
||||
line-height: 1.3;
|
||||
}
|
||||
.cx-provider-balance-refresh {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
flex: 0 0 22px;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: 5px;
|
||||
color: var(--cx-provider-muted);
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
opacity: .75;
|
||||
transition: opacity 140ms ease, background 140ms ease;
|
||||
}
|
||||
.cx-provider-balance-refresh:hover:not(:disabled) { opacity: 1; background: color-mix(in srgb, currentColor 10%, transparent); }
|
||||
.cx-provider-balance-refresh:focus-visible { outline: 2px solid var(--cx-provider-blue); outline-offset: 2px; opacity: 1; }
|
||||
.cx-provider-balance-refresh:disabled { cursor: default; opacity: .45; }
|
||||
.cx-provider-balance-spin { animation: cx-provider-balance-spin 900ms linear infinite; }
|
||||
.cx-provider-balance-reading { display: flex; align-items: center; gap: 8px; min-width: 0; }
|
||||
.cx-provider-balance-amounts { display: flex; min-width: 0; gap: 14px; align-items: baseline; }
|
||||
.cx-provider-balance-amounts--multiple { flex-wrap: wrap; gap: 3px 12px; }
|
||||
.cx-provider-balance-value { display: flex; align-items: baseline; gap: 6px; min-width: 0; max-width: 100%; }
|
||||
.cx-provider-balance-value strong { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--cx-balance-value); font-size: 21px; font-weight: 650; line-height: 1.25; letter-spacing: -.35px; font-variant-numeric: tabular-nums; }
|
||||
.cx-provider-balance-value > span { flex-shrink: 0; color: var(--cx-provider-muted); font-size: 10px; font-weight: 500; }
|
||||
.cx-provider-balance-amounts--multiple .cx-provider-balance-value strong { font-size: 17px; }
|
||||
.cx-provider-balance-value--empty strong { color: var(--ui-danger); }
|
||||
.cx-provider-balance--stale .cx-provider-balance-value strong { color: var(--cx-provider-text); }
|
||||
.cx-provider-balance-footer { color: var(--cx-provider-muted); font-size: 10px; line-height: 1.4; font-variant-numeric: tabular-nums; }
|
||||
.cx-provider-balance-footer--error { color: var(--ui-warning); }
|
||||
.cx-provider-balance-unavailable { min-height: 26px; display: flex; align-items: center; gap: 6px; color: var(--cx-provider-muted); font-size: 12px; }
|
||||
.cx-provider-balance-unavailable > svg { flex-shrink: 0; color: var(--ui-warning); }
|
||||
.cx-provider-balance-placeholder { display: flex; align-items: center; height: 26px; }
|
||||
.cx-provider-balance-placeholder > span { height: 18px; width: 88px; border-radius: 4px; background: color-mix(in srgb, var(--cx-provider-muted) 14%, transparent); }
|
||||
@keyframes cx-provider-balance-spin { to { transform: rotate(360deg); } }
|
||||
@media (prefers-reduced-motion: reduce) { .cx-provider-balance-spin { animation: none; } }
|
||||
@media (max-width: 760px) { .cx-provider-balance { grid-column: 3; justify-self: start; max-width: 250px; padding: 0; border-left: 0; } }
|
||||
@@ -0,0 +1,39 @@
|
||||
.cx-provider-headers-control { grid-column: 1 / -1; min-width: 0; }
|
||||
.cx-provider-headers-feedback { display: flex; align-items: center; gap: 10px; margin-top: 8px; }
|
||||
.cx-provider-headers-feedback > p { margin: 0; }
|
||||
.cx-provider-headers { grid-column: 1 / -1; min-width: 0; padding: 15px; border: 1px solid var(--cx-provider-border-soft); border-radius: 10px; }
|
||||
.cx-provider-headers-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; margin-bottom: 12px; }
|
||||
.cx-provider-headers-heading > div { min-width: 0; }
|
||||
.cx-provider-headers-heading strong { display: flex; align-items: center; gap: 8px; color: var(--cx-provider-text); font-size: 13px; }
|
||||
.cx-provider-headers-heading strong > span { color: var(--cx-provider-muted); font-size: 10px; font-weight: 500; }
|
||||
.cx-provider-headers-heading p, .cx-provider-headers-hint, .cx-provider-headers-empty { margin: 5px 0 0; color: var(--cx-provider-muted); font-size: 11px; line-height: 1.6; }
|
||||
.cx-provider-headers-actions { display: flex; flex-shrink: 0; flex-wrap: wrap; align-items: center; gap: 8px; }
|
||||
.cx-provider-headers-presets { width: 180px; max-width: 100%; min-height: 32px; padding: 0 9px; border: 1px solid var(--cx-provider-border); border-radius: 6px; background: var(--ui-surface); color: var(--cx-provider-text); font-size: 11px; }
|
||||
.cx-provider-headers-presets:focus-visible { outline: 2px solid var(--cx-provider-blue); outline-offset: 2px; }
|
||||
.cx-provider-headers-presets:disabled { opacity: .6; cursor: not-allowed; }
|
||||
.cx-provider-headers .cx-provider-headers-preset-hint { margin: 0 0 12px; }
|
||||
.cx-provider-headers-rows { display: grid; gap: 10px; }
|
||||
.cx-provider-header-row { display: grid; grid-template-columns: minmax(0, 1fr) minmax(130px, .8fr) minmax(0, 1.5fr) 32px; gap: 9px; align-items: start; }
|
||||
.cx-provider-header-field { display: grid; min-width: 0; gap: 5px; }
|
||||
.cx-provider-header-field > span { color: var(--cx-provider-muted); font-size: 10px; font-weight: 600; line-height: 1.5; }
|
||||
.cx-provider-header-field > input, .cx-provider-header-field > select { width: 100%; min-width: 0; height: 38px; padding: 0 9px; border: 1px solid var(--cx-provider-border); border-radius: 6px; outline: none; background: var(--ui-surface); color: var(--cx-provider-text); font-size: 12px; }
|
||||
.cx-provider-header-field > input::placeholder { color: var(--cx-provider-muted); opacity: .8; font-size: 11px; }
|
||||
.cx-provider-header-field > input:focus, .cx-provider-header-field > select:focus { border-color: var(--cx-provider-blue); box-shadow: 0 0 0 2px color-mix(in srgb, var(--cx-provider-blue) 12%, transparent); }
|
||||
.cx-provider-header-field > [aria-invalid="true"] { border-color: color-mix(in srgb, var(--ui-danger) 65%, var(--cx-provider-border)); }
|
||||
.cx-provider-header-field > small, .cx-provider-headers-error { color: var(--ui-danger); font-size: 10px; line-height: 1.5; overflow-wrap: anywhere; }
|
||||
.cx-provider-header-field > :disabled { opacity: .6; cursor: not-allowed; }
|
||||
.cx-provider-header-remove { margin-top: 22px; }
|
||||
.cx-provider-headers-hint, .cx-provider-headers-error { margin: 10px 0 0; }
|
||||
@media (max-width: 900px) {
|
||||
.cx-provider-header-row { grid-template-columns: minmax(0, 1fr) minmax(130px, .8fr) 32px; }
|
||||
.cx-provider-header-field:nth-child(3) { grid-column: 1 / 3; grid-row: 2; }
|
||||
.cx-provider-header-remove { grid-column: 3; grid-row: 1; }
|
||||
}
|
||||
@media (max-width: 640px) {
|
||||
.cx-provider-headers { padding: 12px; }
|
||||
.cx-provider-headers-heading { flex-wrap: wrap; }
|
||||
.cx-provider-headers-actions { width: 100%; }
|
||||
.cx-provider-header-row { grid-template-columns: minmax(0, 1fr) 32px; }
|
||||
.cx-provider-header-field, .cx-provider-header-field:nth-child(3) { grid-column: 1; grid-row: auto; }
|
||||
.cx-provider-header-remove { grid-column: 2; }
|
||||
}
|
||||
@@ -200,7 +200,7 @@
|
||||
min-width: 0;
|
||||
min-height: 78px;
|
||||
display: grid;
|
||||
grid-template-columns: 42px minmax(0, 1fr) auto;
|
||||
grid-template-columns: 18px 42px minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
padding: 14px 16px;
|
||||
@@ -222,13 +222,28 @@
|
||||
box-shadow: 0 0 0 1px rgba(147, 197, 253, 0.5), 0 3px 10px rgba(37, 99, 235, 0.08);
|
||||
}
|
||||
|
||||
/* Give official account emails their own centered column. Current-state
|
||||
badges can change the actions without moving the email in any row. */
|
||||
.cx-providers-row--official {
|
||||
grid-template-columns: 42px minmax(0, 1fr) minmax(200px, 300px) minmax(310px, 1fr);
|
||||
/* Keep account details and provider balances in the same centered column. */
|
||||
.cx-providers-row--official,
|
||||
.cx-providers-row--balance {
|
||||
grid-template-columns: 18px 42px minmax(0, 1fr) minmax(200px, 300px) minmax(310px, 1fr);
|
||||
}
|
||||
|
||||
.cx-providers-row--official > .cx-providers-login-badge {
|
||||
.cx-providers-sort-hint { margin: -7px 1px 12px; color: var(--cx-provider-muted); font-size: 11px; line-height: 1.5; }
|
||||
.cx-providers-drag-handle { display: grid; place-items: center; width: 22px; height: 34px; margin-left: -2px; padding: 0; border: 0; border-radius: 5px; background: transparent; color: var(--cx-provider-muted); cursor: grab; touch-action: none; user-select: none; }
|
||||
.cx-providers-drag-handle:hover:not(:disabled) { background: var(--cx-provider-blue-soft); color: var(--cx-provider-blue); }
|
||||
.cx-providers-drag-handle:active { cursor: grabbing; }
|
||||
.cx-providers-drag-handle:focus-visible { outline: 2px solid var(--cx-provider-blue); outline-offset: 2px; }
|
||||
.cx-providers-drag-handle:disabled { opacity: .35; cursor: default; }
|
||||
.cx-providers-row--dragging { opacity: .45; }
|
||||
.cx-providers-row--drop-before { box-shadow: inset 0 3px 0 var(--cx-provider-blue); }
|
||||
.cx-providers-row--drop-after { box-shadow: inset 0 -3px 0 var(--cx-provider-blue); }
|
||||
.cx-providers-row-model { display: flex; align-items: baseline; gap: 6px; margin-top: 5px; min-width: 0; font-size: 11px; line-height: 1.5; }
|
||||
.cx-providers-row-model>span { flex-shrink: 0; color: var(--cx-provider-muted); }
|
||||
.cx-providers-row-model>b { font-weight: 550; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--cx-provider-text); }
|
||||
.cx-providers-row-model>code { margin: 0; flex: 0 1 auto; }
|
||||
|
||||
.cx-providers-row--official > .cx-providers-login-badge,
|
||||
.cx-providers-row--balance > .cx-providers-login-badge {
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
justify-self: center;
|
||||
@@ -914,18 +929,20 @@
|
||||
|
||||
@media (max-width: 760px) {
|
||||
.cx-providers-row,
|
||||
.cx-providers-row--official {
|
||||
grid-template-columns: 40px minmax(0, 1fr);
|
||||
.cx-providers-row--official,
|
||||
.cx-providers-row--balance {
|
||||
grid-template-columns: 18px 40px minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.cx-providers-row--official > .cx-providers-login-badge {
|
||||
grid-column: 2;
|
||||
.cx-providers-row--official > .cx-providers-login-badge,
|
||||
.cx-providers-row--balance > .cx-providers-login-badge {
|
||||
grid-column: 3;
|
||||
width: min(300px, 100%);
|
||||
justify-self: start;
|
||||
}
|
||||
|
||||
.cx-providers-row-actions {
|
||||
grid-column: 2;
|
||||
grid-column: 3;
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
@@ -960,3 +977,10 @@
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
.cx-providers-protocol-hint {
|
||||
margin: 0;
|
||||
color: var(--cx-provider-muted);
|
||||
font-size: 12px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
@@ -387,6 +387,146 @@
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.cx-session-browser {
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
height: 0;
|
||||
flex: 1 1 0;
|
||||
display: grid;
|
||||
grid-template-columns: 238px minmax(0, 1fr);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.cx-session-browser--flat {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.cx-session-folder-tree {
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
border-right: 1px solid #e6e9ed;
|
||||
background: #f8f9fb;
|
||||
}
|
||||
|
||||
.cx-session-tree-heading {
|
||||
min-height: 34px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
padding: 0 11px;
|
||||
border-bottom: 1px solid #e6e9ed;
|
||||
color: #767e89;
|
||||
background: #fafbfc;
|
||||
font-size: 10px;
|
||||
font-weight: 720;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.cx-session-tree-items {
|
||||
min-height: 0;
|
||||
display: grid;
|
||||
align-content: start;
|
||||
gap: 2px;
|
||||
overflow-y: auto;
|
||||
padding: 7px;
|
||||
scrollbar-gutter: stable;
|
||||
}
|
||||
|
||||
.cx-session-tree-all,
|
||||
.cx-session-tree-item {
|
||||
min-width: 0;
|
||||
min-height: 36px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 7px;
|
||||
color: #626a75;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.cx-session-tree-all {
|
||||
width: 100%;
|
||||
display: grid;
|
||||
grid-template-columns: 17px minmax(0, 1fr) auto;
|
||||
gap: 7px;
|
||||
align-items: center;
|
||||
padding: 0 8px;
|
||||
font-size: 11px;
|
||||
font-weight: 690;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.cx-session-tree-all em,
|
||||
.cx-session-tree-select em {
|
||||
color: #969da7;
|
||||
font-size: 10px;
|
||||
font-style: normal;
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
.cx-session-tree-item {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) 27px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.cx-session-tree-select {
|
||||
min-width: 0;
|
||||
min-height: 42px;
|
||||
display: grid;
|
||||
grid-template-columns: 17px minmax(0, 1fr) auto;
|
||||
gap: 7px;
|
||||
align-items: center;
|
||||
padding: 4px 3px 4px 8px;
|
||||
overflow: hidden;
|
||||
border: 0;
|
||||
color: inherit;
|
||||
background: transparent;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.cx-session-tree-item > .cx-session-pin-action {
|
||||
width: 25px;
|
||||
height: 25px;
|
||||
border-color: transparent;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.cx-session-tree-all:hover,
|
||||
.cx-session-tree-item:hover {
|
||||
color: #354052;
|
||||
background: #f0f3f7;
|
||||
}
|
||||
|
||||
.cx-session-tree-item--active {
|
||||
border-color: #cfdfff;
|
||||
color: #2454b3;
|
||||
background: #edf4ff;
|
||||
}
|
||||
|
||||
.cx-session-tree-item--active .cx-session-folder-copy strong {
|
||||
color: #2454b3;
|
||||
}
|
||||
|
||||
.cx-session-tree-all:focus-visible,
|
||||
.cx-session-tree-select:focus-visible {
|
||||
outline: 2px solid var(--ui-accent);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
.cx-session-results {
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
background: #ffffff;
|
||||
}
|
||||
|
||||
.cx-session-scroll {
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
@@ -426,7 +566,7 @@
|
||||
.cx-session-column-head,
|
||||
.cx-session-row {
|
||||
display: grid;
|
||||
grid-template-columns: 26px minmax(200px, 1fr) 104px 104px 112px 104px 34px;
|
||||
grid-template-columns: 26px minmax(200px, 1fr) 104px 104px 112px 104px 70px;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
}
|
||||
@@ -456,9 +596,16 @@
|
||||
}
|
||||
|
||||
.cx-session-table-body {
|
||||
position: relative;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.cx-session-virtual-item {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
left: 0;
|
||||
}
|
||||
|
||||
.cx-session-group {
|
||||
min-width: 0;
|
||||
}
|
||||
@@ -470,17 +617,20 @@
|
||||
.cx-session-group-heading {
|
||||
min-width: 0;
|
||||
display: grid;
|
||||
grid-template-columns: 26px minmax(0, 1fr) auto;
|
||||
grid-template-columns: 26px minmax(0, 1fr) auto 30px;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
min-height: 36px;
|
||||
min-height: 44px;
|
||||
padding: 0 12px;
|
||||
border-bottom: 1px solid #eef0f2;
|
||||
color: #737b86;
|
||||
background: #fcfcfd;
|
||||
font-size: 11px;
|
||||
font-weight: 680;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.cx-session-group-heading--separated {
|
||||
border-top: 7px solid #f7f8f9;
|
||||
}
|
||||
|
||||
.cx-session-group-heading--selected,
|
||||
@@ -489,13 +639,61 @@
|
||||
background: #f5f8ff;
|
||||
}
|
||||
|
||||
.cx-session-group-heading > span {
|
||||
.cx-session-group-heading--pinned {
|
||||
box-shadow: inset 3px 0 0 color-mix(in srgb, var(--ui-accent) 72%, transparent);
|
||||
}
|
||||
|
||||
.cx-session-folder-toggle {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
border: 0;
|
||||
color: inherit;
|
||||
background: transparent;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.cx-session-folder-toggle > svg {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.cx-session-folder-copy {
|
||||
min-width: 0;
|
||||
display: grid;
|
||||
gap: 1px;
|
||||
}
|
||||
|
||||
.cx-session-folder-copy strong,
|
||||
.cx-session-folder-copy small {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.cx-session-folder-copy strong {
|
||||
color: #3f4650;
|
||||
font-size: 11.5px;
|
||||
font-weight: 720;
|
||||
}
|
||||
|
||||
.cx-session-folder-copy small {
|
||||
color: #9299a3;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
||||
font-size: 9.5px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.cx-session-folder-toggle:focus-visible {
|
||||
border-radius: 4px;
|
||||
outline: 2px solid var(--ui-accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.cx-session-group-heading em {
|
||||
color: #969ca5;
|
||||
font-size: 10px;
|
||||
@@ -534,6 +732,14 @@
|
||||
background: #edf4ff;
|
||||
}
|
||||
|
||||
.cx-session-row--pinned:not(.cx-session-row--selected) {
|
||||
box-shadow: inset 3px 0 0 color-mix(in srgb, var(--ui-accent) 52%, transparent);
|
||||
}
|
||||
|
||||
.cx-session-row--nested .cx-session-row-copy {
|
||||
padding-left: 4px;
|
||||
}
|
||||
|
||||
.cx-session-row:focus-within {
|
||||
outline: 1px solid rgba(37, 99, 235, 0.38);
|
||||
outline-offset: -1px;
|
||||
@@ -664,7 +870,15 @@
|
||||
color: #4669a8;
|
||||
}
|
||||
|
||||
.cx-session-row-export {
|
||||
.cx-session-row-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.cx-session-row-export,
|
||||
.cx-session-pin-action {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
justify-self: end;
|
||||
@@ -678,22 +892,44 @@
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.cx-session-row-export:hover:not(:disabled) {
|
||||
.cx-session-row-export:hover:not(:disabled),
|
||||
.cx-session-pin-action:hover:not(:disabled) {
|
||||
color: var(--ui-accent);
|
||||
border-color: var(--ui-accent);
|
||||
background: var(--ui-accent-soft);
|
||||
}
|
||||
|
||||
.cx-session-row-export:focus-visible {
|
||||
.cx-session-row-export:focus-visible,
|
||||
.cx-session-pin-action:focus-visible {
|
||||
outline: 2px solid var(--ui-accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.cx-session-row-export:disabled {
|
||||
.cx-session-row-export:disabled,
|
||||
.cx-session-pin-action:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.cx-session-pin-action--active {
|
||||
color: var(--ui-accent);
|
||||
border-color: color-mix(in srgb, var(--ui-accent) 42%, var(--ui-border));
|
||||
background: var(--ui-accent-soft);
|
||||
}
|
||||
|
||||
.cx-session-load-more {
|
||||
min-height: 36px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 7px;
|
||||
padding: 8px 12px;
|
||||
border-top: 1px solid #eef0f2;
|
||||
color: #7e8793;
|
||||
background: #fafbfc;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.cx-session-empty {
|
||||
min-height: 120px;
|
||||
flex: 1 1 auto;
|
||||
@@ -911,9 +1147,17 @@
|
||||
}
|
||||
|
||||
@media (max-width: 1240px) {
|
||||
.cx-session-browser {
|
||||
grid-template-columns: 210px minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.cx-session-browser--flat {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.cx-session-column-head,
|
||||
.cx-session-row {
|
||||
grid-template-columns: 26px minmax(180px, 1fr) 96px 96px 104px 34px;
|
||||
grid-template-columns: 26px minmax(180px, 1fr) 96px 96px 104px 70px;
|
||||
}
|
||||
|
||||
.cx-session-id-heading,
|
||||
@@ -957,9 +1201,23 @@
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
|
||||
.cx-session-browser {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
grid-template-rows: minmax(110px, 30%) minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.cx-session-browser--flat {
|
||||
grid-template-rows: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.cx-session-folder-tree {
|
||||
border-right: 0;
|
||||
border-bottom: 1px solid #e6e9ed;
|
||||
}
|
||||
|
||||
.cx-session-column-head,
|
||||
.cx-session-row {
|
||||
grid-template-columns: 26px minmax(0, 1fr) 82px 34px;
|
||||
grid-template-columns: 26px minmax(0, 1fr) 82px 70px;
|
||||
}
|
||||
|
||||
.cx-session-column-head span:nth-child(n + 4):not(.cx-session-actions-heading),
|
||||
|
||||
@@ -36,6 +36,7 @@ export type SavedProvider = {
|
||||
apiKey?: string;
|
||||
tomlConfig?: string;
|
||||
wireApi: string;
|
||||
upstreamApi?: string | null;
|
||||
requiresOpenaiAuth: boolean;
|
||||
modelMappings?: ProviderModelMapping[];
|
||||
};
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { AppUpdateInfo, ReleaseInfo } from "./types";
|
||||
|
||||
/** Release metadata can identify a version, but does not authorize installation.
|
||||
* An installed edition keeps its native check/retry controls after a failed
|
||||
* signed-channel check; only editions without a native updater use download-only.
|
||||
*/
|
||||
export function releaseInfoFromFallback(update: AppUpdateInfo, nativeCheckAttempted: boolean): ReleaseInfo {
|
||||
return {
|
||||
status: nativeCheckAttempted && !update.hasUpdate ? "error" : "ok",
|
||||
latestVersion: update.latestVersion,
|
||||
htmlUrl: update.htmlUrl,
|
||||
hasUpdate: update.hasUpdate,
|
||||
updateMethod: nativeCheckAttempted ? "native" : update.hasUpdate ? "download" : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function releaseInfoFromCheckFailure(nativeCheckAttempted: boolean): ReleaseInfo {
|
||||
return { status: "error", updateMethod: nativeCheckAttempted ? "native" : undefined };
|
||||
}
|
||||
@@ -155,14 +155,17 @@ export function useConfigHealth(options: {
|
||||
dismiss(); accept(result.report);
|
||||
if (result.report.status === "healthy") registry.current?.clear(result.report);
|
||||
const zh = runtime.current.lang === "zh";
|
||||
const remaining = result.report.issues[0];
|
||||
runtime.current.onHint(result.report.status === "healthy"
|
||||
? (zh ? "配置已检查并修复,请重新打开原来的 Codex 对话。" : "Configuration checked and repaired. Reopen the Codex conversation.")
|
||||
: (zh ? "可自动处理的部分已修复,其余问题可在通用设置中查看。" : "Supported repairs are complete. Review the remaining issues in General settings."));
|
||||
: remaining
|
||||
? `${zh ? "已完成安全修复;仍需处理:" : "Supported repairs are complete; review: "}${remaining.path || `${result.report.codexDir}/config.toml`}${remaining.line ? `:${remaining.line}:${remaining.column || 1}` : ""} · ${remaining.key || remaining.title}。${remaining.suggestion || remaining.description}`
|
||||
: (zh ? "请在通用设置中查看检查结果。" : "Review the check result in General settings."));
|
||||
runtime.current.onRepaired();
|
||||
} catch (cause) {
|
||||
if (current()) {
|
||||
dismiss(); setError(String(cause));
|
||||
runtime.current.onHint(runtime.current.lang === "zh" ? "配置未修复,请到「设置 → 通用设置」查看原因或重新检查。" : "Configuration was not repaired. Review the issue or check again in Settings → General.");
|
||||
runtime.current.onHint(`${runtime.current.lang === "zh" ? "配置未修复:" : "Configuration was not repaired: "}${String(cause)}`);
|
||||
}
|
||||
} finally { if (current()) { busyRef.current = false; setRepairing(false); } }
|
||||
}, [accept, dismiss]);
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { AppUpdaterController, appUpdaterCheckFailureMessage, classifyAppUpdaterCheckError, isAppUpdateBusy, UPDATER_SLOW_NOTICE_MS } from "../src/appUpdaterController.ts";
|
||||
|
||||
function deferred() {
|
||||
let resolve, reject;
|
||||
const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
function fixture() {
|
||||
const counts = { checks: 0, installs: 0, restarts: 0, closes: 0 };
|
||||
const timers = new Map();
|
||||
let timerId = 0;
|
||||
let update = { rid: 12, currentVersion: "0.3.20", version: "0.3.21", body: "Update notes", close: async () => { counts.closes++; } };
|
||||
let operation;
|
||||
let checkOperation;
|
||||
let restartOperation;
|
||||
const controller = new AppUpdaterController({
|
||||
check: async () => { counts.checks++; return checkOperation ? checkOperation.promise : update; },
|
||||
install: (value, onEvent, options) => {
|
||||
counts.installs++;
|
||||
operation = { ...deferred(), value, onEvent, options };
|
||||
return operation.promise;
|
||||
},
|
||||
restart: () => { counts.restarts++; return restartOperation?.promise || Promise.resolve(); },
|
||||
setTimer: (callback, delay) => { assert.equal(delay, UPDATER_SLOW_NOTICE_MS); timers.set(++timerId, callback); return timerId; },
|
||||
clearTimer: (id) => { timers.delete(id); },
|
||||
});
|
||||
return {
|
||||
controller, counts, timers,
|
||||
get operation() { return operation; },
|
||||
setCheckOperation(value) { checkOperation = value; },
|
||||
setRestartOperation(value) { restartOperation = value; },
|
||||
setUpdate(value) { update = value; },
|
||||
waitLonger() { for (const [id, callback] of timers) { timers.delete(id); callback(); } },
|
||||
};
|
||||
}
|
||||
|
||||
test("download, verification and shutdown preparation are distinct; ready requires installation result", async () => {
|
||||
const f = fixture();
|
||||
assert.equal(await f.controller.check(), "available");
|
||||
const job = f.controller.downloadAndInstall({ timeout: 4000 });
|
||||
assert.equal(f.operation.options.timeout, 4000);
|
||||
f.operation.onEvent({ event: "Started", data: { contentLength: 100 } });
|
||||
f.operation.onEvent({ event: "Progress", data: { chunkLength: 100 } });
|
||||
assert.equal(f.controller.getSnapshot().phase, "downloading");
|
||||
for (const [event, phase] of [["Verifying", "verifying"], ["Preparing", "preparing"], ["Installing", "installing"]]) {
|
||||
f.operation.onEvent({ event });
|
||||
assert.equal(f.controller.getSnapshot().phase, phase);
|
||||
assert.equal(isAppUpdateBusy(phase), true);
|
||||
}
|
||||
f.operation.resolve({ restartRequired: true });
|
||||
assert.equal(await job, "ready");
|
||||
assert.equal(f.controller.getSnapshot().phase, "ready");
|
||||
assert.equal(f.timers.size, 0);
|
||||
});
|
||||
|
||||
test("clicking repeatedly and checking during an update cannot launch a second installer", async () => {
|
||||
const f = fixture();
|
||||
await f.controller.check();
|
||||
const job = f.controller.downloadAndInstall();
|
||||
assert.equal(f.controller.downloadAndInstall(), job);
|
||||
assert.equal(f.controller.retry(), job);
|
||||
assert.equal(await f.controller.check({ force: true }), "available");
|
||||
assert.equal(f.counts.checks, 1);
|
||||
f.operation.onEvent({ event: "Preparing" });
|
||||
assert.equal(f.controller.downloadAndInstall(), job);
|
||||
f.operation.resolve({ restartRequired: true });
|
||||
await job;
|
||||
await f.controller.downloadAndInstall();
|
||||
await f.controller.check({ force: true });
|
||||
assert.equal(f.counts.installs, 1);
|
||||
assert.equal(f.counts.checks, 1);
|
||||
assert.equal(f.counts.closes, 0);
|
||||
});
|
||||
|
||||
test("preparation failure is not success; shows safe details and allows a deliberate retry", async () => {
|
||||
const f = fixture();
|
||||
await f.controller.check();
|
||||
const job = f.controller.downloadAndInstall();
|
||||
f.operation.onEvent({ event: "Preparing" });
|
||||
f.operation.reject({ stage: "prepare", message: "无法恢复连接配置,尚未启动安装程序。", logPath: "C:\\Logs\\update.log" });
|
||||
assert.equal(await job, "error");
|
||||
assert.equal(f.controller.getSnapshot().failure, "prepare");
|
||||
assert.equal(f.controller.getSnapshot().errorMessage, "无法恢复连接配置,尚未启动安装程序。");
|
||||
assert.equal(f.controller.getSnapshot().logPath, "C:\\Logs\\update.log");
|
||||
assert.equal(f.timers.size, 0);
|
||||
const retry = f.controller.retry();
|
||||
assert.equal(f.counts.installs, 2);
|
||||
assert.equal(f.controller.getSnapshot().errorMessage, null);
|
||||
f.operation.resolve({ restartRequired: true });
|
||||
assert.equal(await retry, "ready");
|
||||
});
|
||||
|
||||
test("signature rejection never displays success or exposes an arbitrary plugin error", async () => {
|
||||
const f = fixture();
|
||||
await f.controller.check();
|
||||
const job = f.controller.downloadAndInstall();
|
||||
f.operation.onEvent({ event: "Verifying" });
|
||||
f.operation.reject(new Error("signature failed at https://private.example.test?token=secret"));
|
||||
assert.equal(await job, "error");
|
||||
assert.equal(f.controller.getSnapshot().failure, "verify");
|
||||
assert.equal(f.controller.getSnapshot().errorMessage, null);
|
||||
});
|
||||
|
||||
test("successful handoff followed by an IPC disconnect must not offer or start another installation", async () => {
|
||||
const f = fixture();
|
||||
await f.controller.check();
|
||||
const job = f.controller.downloadAndInstall();
|
||||
f.operation.onEvent({ event: "HandedOff" });
|
||||
f.operation.reject(new Error("IPC disconnected as the app exits"));
|
||||
assert.equal(await job, "handed-off");
|
||||
assert.equal(f.controller.getSnapshot().failure, null);
|
||||
assert.equal(isAppUpdateBusy(f.controller.getSnapshot().phase), true);
|
||||
assert.equal(await f.controller.retry(), "handed-off");
|
||||
assert.equal(await f.controller.restart(), "handed-off");
|
||||
f.waitLonger();
|
||||
assert.equal(f.controller.getSnapshot().takingLonger, true);
|
||||
assert.equal(f.counts.installs, 1);
|
||||
assert.equal(f.counts.restarts, 0);
|
||||
});
|
||||
|
||||
test("handoff result without restart remains pending installer completion, not installed", async () => {
|
||||
const f = fixture();
|
||||
await f.controller.check();
|
||||
const job = f.controller.downloadAndInstall();
|
||||
f.operation.resolve({ restartRequired: false });
|
||||
assert.equal(await job, "handed-off");
|
||||
assert.equal(await f.controller.downloadAndInstall(), "handed-off");
|
||||
assert.equal(f.counts.installs, 1);
|
||||
});
|
||||
|
||||
test("slow notices never abort a pending operation and new progress clears the notice", async () => {
|
||||
const f = fixture();
|
||||
await f.controller.check();
|
||||
const job = f.controller.downloadAndInstall();
|
||||
f.waitLonger();
|
||||
assert.equal(f.controller.getSnapshot().takingLonger, true);
|
||||
assert.equal(f.controller.getSnapshot().phase, "downloading");
|
||||
assert.equal(f.controller.retry(), job);
|
||||
f.operation.onEvent({ event: "Progress", data: { chunkLength: 12 } });
|
||||
assert.equal(f.controller.getSnapshot().takingLonger, false);
|
||||
f.operation.onEvent({ event: "Preparing" });
|
||||
f.waitLonger();
|
||||
assert.equal(f.controller.getSnapshot().takingLonger, true);
|
||||
assert.equal(f.controller.getSnapshot().phase, "preparing");
|
||||
assert.equal(f.counts.installs, 1);
|
||||
f.operation.resolve({ restartRequired: true });
|
||||
await job;
|
||||
assert.equal(f.controller.getSnapshot().takingLonger, false);
|
||||
});
|
||||
|
||||
test("late events from a failed attempt do not corrupt the retried download", async () => {
|
||||
const f = fixture();
|
||||
await f.controller.check();
|
||||
const first = f.controller.downloadAndInstall();
|
||||
const old = f.operation;
|
||||
old.reject({ stage: "download", message: "Network unavailable" });
|
||||
await first;
|
||||
const second = f.controller.retry();
|
||||
old.onEvent({ event: "HandedOff" });
|
||||
old.onEvent({ event: "Progress", data: { chunkLength: 900 } });
|
||||
assert.equal(f.controller.getSnapshot().phase, "downloading");
|
||||
assert.equal(f.controller.getSnapshot().downloadedBytes, 0);
|
||||
f.operation.resolve({ restartRequired: true });
|
||||
await second;
|
||||
});
|
||||
|
||||
test("only a confirmed ready update can relaunch, and failed relaunch retries only relaunch", async () => {
|
||||
const f = fixture();
|
||||
await f.controller.check();
|
||||
assert.equal(await f.controller.restart(), "available");
|
||||
const job = f.controller.downloadAndInstall();
|
||||
f.operation.resolve({ restartRequired: true });
|
||||
await job;
|
||||
const failed = deferred();
|
||||
f.setRestartOperation(failed);
|
||||
const restart = f.controller.restart();
|
||||
failed.reject(new Error("blocked"));
|
||||
assert.equal(await restart, "error");
|
||||
assert.equal(f.controller.getSnapshot().failure, "restart");
|
||||
f.setRestartOperation(null);
|
||||
assert.equal(await f.controller.retry(), "ready");
|
||||
assert.equal(f.controller.getSnapshot().phase, "ready");
|
||||
assert.equal(f.counts.restarts, 2);
|
||||
assert.equal(f.counts.installs, 1);
|
||||
});
|
||||
|
||||
test("a pending forced check cannot install its stale update resource", async () => {
|
||||
const f = fixture();
|
||||
await f.controller.check();
|
||||
const next = deferred();
|
||||
f.setCheckOperation(next);
|
||||
const check = f.controller.check({ force: true });
|
||||
assert.equal(await f.controller.downloadAndInstall(), "checking");
|
||||
assert.equal(f.counts.installs, 0);
|
||||
next.resolve(null);
|
||||
await check;
|
||||
assert.equal(f.counts.closes, 1);
|
||||
});
|
||||
|
||||
|
||||
const checkFailures = [
|
||||
["timeout", new Error("error sending request: operation timed out at https://private.fixture.test/update?token=private-secret")],
|
||||
["network", { code: "NetworkError", message: "connection refused; Authorization: Bearer private-secret at https://private.fixture.test" }],
|
||||
["platform", "the platform `windows-x86_64` was not found in the response `platforms` object"],
|
||||
["platform", new Error("Unsupported application architecture, expected x86 or aarch64")],
|
||||
["invalid-release", "Could not fetch a valid release JSON from the remote"],
|
||||
["invalid-release", { code: "Serialization", message: "missing field `signature` at line 1 column 1: private-secret" }],
|
||||
["public-key", "Could not decode public key or signature: private-secret"],
|
||||
["unknown", { message: "Something unexpected happened: private-secret", url: "https://private.fixture.test", authorization: "Bearer private-secret" }],
|
||||
];
|
||||
|
||||
test("check failures are classified into fixed safe explanations in both languages", () => {
|
||||
for (const [kind, cause] of checkFailures) {
|
||||
assert.equal(classifyAppUpdaterCheckError(cause), kind);
|
||||
for (const lang of ["zh", "en"]) {
|
||||
const message = appUpdaterCheckFailureMessage(kind, lang);
|
||||
assert.ok(message.length > 20);
|
||||
assert.ok(!message.includes("private-secret"));
|
||||
assert.ok(!message.includes("https://"));
|
||||
assert.ok(!message.includes("Authorization"));
|
||||
}
|
||||
}
|
||||
for (const cause of [null, undefined, 123, false, {}, { message: {} }]) assert.equal(classifyAppUpdaterCheckError(cause), "unknown");
|
||||
assert.equal(classifyAppUpdaterCheckError("Unrecognized error https://fixture.test/timeout?publickey=secret"), "unknown", "URL text alone must not invent the reason");
|
||||
});
|
||||
|
||||
test("SDK check rejection retains a safe cause without any raw endpoint or credentials", async () => {
|
||||
for (const [kind, cause] of checkFailures) {
|
||||
const f = fixture();
|
||||
const rejected = deferred();
|
||||
f.setCheckOperation(rejected);
|
||||
const job = f.controller.check();
|
||||
rejected.reject(cause);
|
||||
assert.equal(await job, "error");
|
||||
const state = f.controller.getSnapshot();
|
||||
assert.equal(state.phase, "error");
|
||||
assert.equal(state.failure, "check");
|
||||
assert.equal(state.checkFailure, kind);
|
||||
assert.equal(state.errorMessage, appUpdaterCheckFailureMessage(kind));
|
||||
const visible = JSON.stringify(state);
|
||||
for (const secret of ["private-secret", "private.fixture.test", "Authorization", "Bearer"]) assert.ok(!visible.includes(secret));
|
||||
assert.equal(f.counts.installs, 0);
|
||||
}
|
||||
});
|
||||
|
||||
test("failed forced checks release their prior RID and clear stale release details", async () => {
|
||||
const f = fixture();
|
||||
f.setUpdate({ rid: 21, currentVersion: "0.3.21", version: "0.3.24", body: "Old release notes", date: "2026-10-01", close: async () => { f.counts.closes++; } });
|
||||
await f.controller.check();
|
||||
assert.equal(f.controller.getSnapshot().latestVersion, "0.3.24");
|
||||
const failed = deferred();
|
||||
f.setCheckOperation(failed);
|
||||
const job = f.controller.check({ force: true });
|
||||
assert.equal(f.controller.getSnapshot().latestVersion, null);
|
||||
assert.equal(f.controller.getSnapshot().notes, null);
|
||||
failed.reject(new Error("NetworkError: connection refused"));
|
||||
await job;
|
||||
assert.equal(f.counts.closes, 1);
|
||||
assert.equal(f.controller.getSnapshot().failure, "check");
|
||||
assert.equal(f.controller.getSnapshot().checkFailure, "network");
|
||||
for (const field of ["latestVersion", "notes", "publishedAt"]) assert.equal(f.controller.getSnapshot()[field], null);
|
||||
assert.equal(await f.controller.downloadAndInstall(), "error");
|
||||
assert.equal(f.counts.installs, 0, "failed SDK metadata cannot authorize an installer");
|
||||
});
|
||||
|
||||
test("retry checks again and installation requires a newly obtained legal SDK RID", async () => {
|
||||
const f = fixture();
|
||||
const failed = deferred();
|
||||
f.setCheckOperation(failed);
|
||||
const first = f.controller.check();
|
||||
failed.reject(new Error("operation timed out"));
|
||||
await first;
|
||||
const pending = deferred();
|
||||
f.setCheckOperation(pending);
|
||||
const retry = f.controller.retry();
|
||||
assert.equal(f.counts.checks, 2);
|
||||
assert.equal(f.controller.getSnapshot().phase, "checking");
|
||||
assert.equal(await f.controller.downloadAndInstall(), "checking");
|
||||
assert.equal(f.counts.installs, 0);
|
||||
pending.resolve({ rid: 24, currentVersion: "0.3.21", version: "0.3.24", body: "New release", close: async () => { f.counts.closes++; } });
|
||||
assert.equal(await retry, "available");
|
||||
assert.equal(f.controller.getSnapshot().errorMessage, null);
|
||||
assert.equal(f.controller.getSnapshot().checkFailure, null);
|
||||
assert.equal(f.counts.installs, 0, "retrying the check must not automatically install");
|
||||
const installing = f.controller.downloadAndInstall();
|
||||
assert.equal(f.operation.value.rid, 24);
|
||||
assert.equal(f.counts.installs, 1);
|
||||
f.operation.resolve({ restartRequired: true });
|
||||
assert.equal(await installing, "ready");
|
||||
});
|
||||
|
||||
test("invalid SDK resource IDs are closed and can never reach installation", async () => {
|
||||
for (const rid of [-1, NaN, Infinity, 1.5, 0x1_0000_0000, "24", undefined]) {
|
||||
const f = fixture();
|
||||
f.setUpdate({ rid, currentVersion: "0.3.21", version: "0.3.24", close: async () => { f.counts.closes++; } });
|
||||
assert.equal(await f.controller.check(), "error", String(rid));
|
||||
assert.equal(f.controller.getSnapshot().checkFailure, "invalid-release");
|
||||
assert.equal(f.counts.closes, 1);
|
||||
assert.equal(await f.controller.downloadAndInstall(), "error");
|
||||
assert.equal(f.counts.installs, 0);
|
||||
}
|
||||
const f = fixture();
|
||||
f.setUpdate({ rid: 0, currentVersion: "0.3.21", version: "0.3.24", close: async () => { f.counts.closes++; } });
|
||||
assert.equal(await f.controller.check(), "available", "Tauri resource IDs may start at zero");
|
||||
});
|
||||
|
||||
|
||||
test("automatic transport recovery starts a fresh byte count and installs only once", async () => {
|
||||
const f = fixture();
|
||||
await f.controller.check();
|
||||
const job = f.controller.downloadAndInstall();
|
||||
f.operation.onEvent({ event: "Started", data: { contentLength: 100 } });
|
||||
f.operation.onEvent({ event: "Progress", data: { chunkLength: 45 } });
|
||||
assert.equal(f.controller.getSnapshot().downloadedBytes, 45);
|
||||
f.operation.onEvent({ event: "Started", data: { contentLength: 100 } });
|
||||
assert.equal(f.controller.getSnapshot().downloadedBytes, 0);
|
||||
f.operation.onEvent({ event: "Progress", data: { chunkLength: 100 } });
|
||||
f.operation.onEvent({ event: "Verifying" });
|
||||
f.operation.onEvent({ event: "Preparing" });
|
||||
f.operation.onEvent({ event: "HandedOff" });
|
||||
f.operation.resolve({ restartRequired: false });
|
||||
assert.equal(await job, "handed-off");
|
||||
assert.equal(f.counts.installs, 1);
|
||||
assert.equal(f.counts.checks, 1);
|
||||
});
|
||||
@@ -0,0 +1,170 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { createHash } from "node:crypto";
|
||||
import { closeSync, existsSync, openSync, readFileSync, readSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import test from "node:test";
|
||||
import vm from "node:vm";
|
||||
|
||||
// Optional local compatibility evidence. No installed application is launched,
|
||||
// and no bundle is executed or copied into this repository. Only the narrow
|
||||
// SDK registration / getter / compiled memo fragments are extracted at run time.
|
||||
const archive = "/Applications/ChatGPT.app/Contents/Resources/app.asar";
|
||||
const available = process.platform === "darwin" && existsSync(archive);
|
||||
const runtime = readFileSync(new URL("../src-tauri/src/codex_locale_runtime.js", import.meta.url), "utf8");
|
||||
const owner = "c".repeat(64);
|
||||
const marker = "__CODEXX_LOCALE_RUNTIME_V1__";
|
||||
|
||||
function readInstalledEvidence() {
|
||||
const fd = openSync(archive, "r");
|
||||
try {
|
||||
const prefix = Buffer.alloc(16);
|
||||
readSync(fd, prefix, 0, prefix.length, 0);
|
||||
assert.equal(prefix.readUInt32LE(0), 4);
|
||||
const headerSize = prefix.readUInt32LE(12);
|
||||
assert.ok(headerSize > 0 && headerSize < 32 * 1024 * 1024);
|
||||
const header = Buffer.alloc(headerSize);
|
||||
assert.equal(readSync(fd, header, 0, header.length, 16), header.length);
|
||||
const assets = JSON.parse(header.toString()).files.webview.files.assets.files;
|
||||
const base = 8 + prefix.readUInt32LE(4);
|
||||
function asset(pattern) {
|
||||
const matches = Object.entries(assets).filter(([name]) => pattern.test(name));
|
||||
assert.equal(matches.length, 1, `installed asset shape changed: ${pattern}`);
|
||||
const [name, entry] = matches[0];
|
||||
assert.ok(!entry.unpacked && entry.size < 16 * 1024 * 1024);
|
||||
const bytes = Buffer.alloc(entry.size);
|
||||
assert.equal(readSync(fd, bytes, 0, bytes.length, base + Number(entry.offset)), bytes.length);
|
||||
return { name, source: bytes.toString(), sha256: createHash("sha256").update(bytes).digest("hex") };
|
||||
}
|
||||
const shared = asset(/^app-shared-.*\.js$/);
|
||||
// The language consumer's compiled memo is in app-initial, not app-shared.
|
||||
const initial = asset(/^app-initial-.*\.js$/);
|
||||
const plist = readFileSync("/Applications/ChatGPT.app/Contents/Info.plist", "utf8");
|
||||
const plistValue = (key) => plist.match(new RegExp(`<key>${key}</key>\\s*<string>([^<]+)`))?.[1];
|
||||
return { shared, initial, version: plistValue("CFBundleShortVersionString"), build: plistValue("CFBundleVersion") };
|
||||
} finally { closeSync(fd); }
|
||||
}
|
||||
|
||||
function extractedFragments(evidence) {
|
||||
const require = createRequire(new URL("../package.json", import.meta.url));
|
||||
const ts = require("typescript");
|
||||
const shared = evidence.shared.source;
|
||||
function declaration(marker) {
|
||||
const index = shared.indexOf(marker);
|
||||
assert.ok(index >= 0, `installed SDK fragment changed: ${marker}`);
|
||||
// Parse a bounded window; execute only its first complete declaration.
|
||||
const parsed = ts.createSourceFile("fragment.js", shared.slice(index, index + 4096), ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
|
||||
assert.ok(ts.isFunctionDeclaration(parsed.statements[0]));
|
||||
return parsed.statements[0].getText(parsed);
|
||||
}
|
||||
const registration = declaration("function p(e,t){if((0,s._isServerEnv)())return");
|
||||
const useLayer = declaration("function Nyn(");
|
||||
const readLayer = declaration("function Pyn(");
|
||||
const memoIndex = shared.indexOf("_memoize(e,t){");
|
||||
assert.ok(memoIndex >= 0);
|
||||
const parsedMemo = ts.createSourceFile("memo.js", `class Extracted {${shared.slice(memoIndex, memoIndex + 2048)}`, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
|
||||
const memoize = parsedMemo.statements[0].members[0].getText(parsedMemo);
|
||||
const assignmentStart = shared.indexOf("this.getLayer=this._memoize(");
|
||||
const assignmentEnd = shared.indexOf(",this.getParameterStore=", assignmentStart);
|
||||
assert.ok(assignmentStart >= 0 && assignmentEnd > assignmentStart);
|
||||
const assignment = shared.slice(assignmentStart, assignmentEnd);
|
||||
const derivedStart = shared.lastIndexOf("constructor(", assignmentStart);
|
||||
assert.ok(shared.slice(derivedStart, assignmentStart).includes("super("), "the real derived constructor calls super before assigning getLayer");
|
||||
const registerCall = shared.indexOf("p(e,this)");
|
||||
const baseStart = shared.lastIndexOf("constructor(", registerCall);
|
||||
assert.ok(baseStart > 0 && registerCall > baseStart);
|
||||
assert.equal(shared.slice(registerCall, registerCall + 10), "p(e,this)}", "registration is at the end of the real base constructor");
|
||||
const getterStart = shared.indexOf("e._getStatsigGlobal=()=>");
|
||||
const getterEnd = shared.indexOf(",e._getStatsigGlobalFlag", getterStart);
|
||||
const globalsStart = shared.indexOf("var n=`__STATSIG__`,", getterEnd);
|
||||
const globalsEnd = shared.indexOf("a[n]=o", globalsStart) + "a[n]=o".length;
|
||||
assert.ok(getterStart >= 0 && getterEnd > getterStart && globalsStart > getterEnd && globalsEnd > globalsStart);
|
||||
const globalInitialization = `${shared.slice(getterStart, getterEnd)};${shared.slice(globalsStart, globalsEnd)};`;
|
||||
const consumerStart = evidence.initial.source.indexOf("function O9s(");
|
||||
const expressionStart = evidence.initial.source.indexOf("t[0]===s?c=t[1]", consumerStart);
|
||||
const expressionEnd = evidence.initial.source.indexOf(";let l=c", expressionStart);
|
||||
assert.ok(consumerStart >= 0 && expressionStart > consumerStart && expressionEnd > expressionStart);
|
||||
const consumerMemo = evidence.initial.source.slice(expressionStart, expressionEnd);
|
||||
assert.ok(consumerMemo.includes("enable_i18n") && consumerMemo.length < 256);
|
||||
return { registration, useLayer, readLayer, memoize, assignment, globalInitialization, consumerMemo };
|
||||
}
|
||||
|
||||
function isolatedSdk(fragments, installEarly) {
|
||||
const timers = new Map();
|
||||
const sandbox = {
|
||||
URL, location: { href: "app://-/index.html" }, document: { documentElement: { lang: "zh-CN" } },
|
||||
performance: { getEntriesByType: () => [{ name: "app://-/assets/zh-CN-fixture.js" }] },
|
||||
setInterval(callback) { timers.set(1, callback); return 1; }, clearInterval(id) { timers.delete(id); },
|
||||
};
|
||||
sandbox.window = sandbox; sandbox.top = sandbox;
|
||||
const context = vm.createContext(sandbox);
|
||||
const install = () => vm.runInContext(runtime.replace("__CODEXX_LANGUAGE_CONFIG__", JSON.stringify({ locale: "zh-CN", owner })), context, { timeout: 500 });
|
||||
if (installEarly) install();
|
||||
// These are independently supplied stubs, not live SDK stores, React, DOM,
|
||||
// networking, or account data. Extracted code has no bundle/module loader.
|
||||
vm.runInContext(`
|
||||
globalThis.fakeLayer={get:(key,fallback)=>key==='enable_i18n'?false:key==='locale_source'?'IDE':fallback};
|
||||
globalThis.originalCalls=0;
|
||||
const sdkGlobals=(()=>{const e={_getInstance(){}};${fragments.globalInitialization}return e;})();
|
||||
const s={_isServerEnv:()=>false},a={Log:{warn(){throw Error('unexpected duplicate fixture key')}}};
|
||||
const n={_getStatsigGlobal:sdkGlobals._getStatsigGlobal,MemoPrefix:{_layer:'fixture-layer'}};
|
||||
const o={createMemoKey:(...args)=>JSON.stringify(args)},f=1000;
|
||||
${fragments.registration}
|
||||
class Base { constructor(e){this._options={};this._memoCache={};p(e,this)} ${fragments.memoize} }
|
||||
const originalMemoize=Base.prototype._memoize;
|
||||
Base.prototype._memoize=function(...args){const raw=originalMemoize.apply(this,args);this.fixtureOriginalGetLayer=raw;return raw;};
|
||||
class Derived extends Base { constructor(e){super(e);globalThis.registeredBeforeGetter=typeof this.getLayer!=='function';${fragments.assignment}} _getLayerImpl(){originalCalls++;return fakeLayer} }
|
||||
const hookCache=Array(8).fill(Symbol.for('fixture.uninitialized'));
|
||||
const consumerCache=Array(33).fill(Symbol.for('fixture.uninitialized'));
|
||||
const iW={c:()=>hookCache};
|
||||
function rW(){return {client:globalThis.client,getLayer:globalThis.client.getLayer}}
|
||||
${fragments.readLayer}
|
||||
${fragments.useLayer}
|
||||
globalThis.readCompiledLanguage=()=>{const s=Nyn('72216192');let t=consumerCache,c;${fragments.consumerMemo};return c;};
|
||||
globalThis.makeClient=key=>new Derived(key);
|
||||
globalThis.client=makeClient('fixture-key');
|
||||
`, context, { timeout: 500 });
|
||||
return { sandbox, context, timers, install, read: () => vm.runInContext("readCompiledLanguage()", context, { timeout: 500 }) };
|
||||
}
|
||||
|
||||
test("installed SDK registration and compiled first language memo see the early override synchronously", { skip: !available }, (t) => {
|
||||
const evidence = readInstalledEvidence();
|
||||
t.diagnostic(`Installed build ${evidence.version} (${evidence.build}); ${evidence.shared.name}; SHA256 ${evidence.shared.sha256}`);
|
||||
const fragments = extractedFragments(evidence);
|
||||
const f = isolatedSdk(fragments, true);
|
||||
assert.equal(f.sandbox.registeredBeforeGetter, true);
|
||||
assert.equal(f.read(), true, "the first compiled memo sees true without timer ticks or SDK events");
|
||||
assert.equal(f.read(), true);
|
||||
assert.equal(f.sandbox.originalCalls, 1, "the real SDK and React memo keep the initial layer cached");
|
||||
assert.equal(f.sandbox.fakeLayer.get("enable_i18n", false), false);
|
||||
assert.equal(f.sandbox.client.getLayer("72216192").get("locale_source", "wrong"), "IDE");
|
||||
const registry = f.sandbox.__STATSIG__;
|
||||
f.sandbox.__STATSIG__ = registry;
|
||||
f.sandbox.second = vm.runInContext("makeClient('second-fixture-key')", f.context);
|
||||
assert.equal(f.sandbox.second.getLayer("72216192").get("enable_i18n", false), true, "subsequent SDK registrations remain observed");
|
||||
assert.equal(f.sandbox[marker].status().ready, true);
|
||||
f.sandbox[marker].restore();
|
||||
assert.equal(f.sandbox[marker], undefined);
|
||||
assert.equal(f.timers.size, 0);
|
||||
assert.equal(f.sandbox.__STATSIG__, registry);
|
||||
assert.equal(registry.instances["fixture-key"], f.sandbox.client);
|
||||
assert.equal(registry.instances["second-fixture-key"], f.sandbox.second);
|
||||
for (const [object, key] of [[f.sandbox, "__STATSIG__"], [registry, "firstInstance"], [registry, "instances"], [registry.instances, "fixture-key"], [registry.instances, "second-fixture-key"], [f.sandbox.client, "getLayer"], [f.sandbox.second, "getLayer"]]) {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(object, key);
|
||||
assert.ok(descriptor && Object.hasOwn(descriptor, "value"), `restore removes the owned accessor for ${key}`);
|
||||
assert.equal(descriptor.writable, true);
|
||||
assert.equal(descriptor.configurable, true);
|
||||
}
|
||||
assert.equal(f.sandbox.client.getLayer, f.sandbox.client.fixtureOriginalGetLayer);
|
||||
assert.equal(f.sandbox.second.getLayer, f.sandbox.second.fixtureOriginalGetLayer);
|
||||
assert.equal(f.sandbox.client.getLayer("72216192").get("enable_i18n", false), false);
|
||||
assert.equal(f.sandbox.second.getLayer("72216192").get("enable_i18n", false), false);
|
||||
});
|
||||
|
||||
test("installed compiled language memo demonstrates why a timer-only late hook cannot repair its first false value", { skip: !available }, () => {
|
||||
const f = isolatedSdk(extractedFragments(readInstalledEvidence()), false);
|
||||
assert.equal(f.read(), false);
|
||||
f.install();
|
||||
assert.equal(f.sandbox.client.getLayer("72216192").get("enable_i18n", false), true);
|
||||
assert.equal(f.read(), false, "the unchanged React client/layer memo retains the pre-hook false value");
|
||||
f.sandbox[marker].restore();
|
||||
});
|
||||
@@ -0,0 +1,322 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import test from "node:test";
|
||||
import vm from "node:vm";
|
||||
|
||||
const source = readFileSync(new URL("../src-tauri/src/codex_locale_runtime.js", import.meta.url), "utf8");
|
||||
const marker = "__CODEXX_LOCALE_RUNTIME_V1__";
|
||||
const layerName = "72216192";
|
||||
const owner = "a".repeat(64);
|
||||
const languageResource = "app://-/assets/zh-CN-fixture.js";
|
||||
|
||||
class FixtureLayer {
|
||||
#values;
|
||||
constructor(values = {}) { this.#values = { enable_i18n: false, locale_source: "fixture-original", ...values }; this.name = "fixture layer"; }
|
||||
get(parameter, fallback) { return Object.hasOwn(this.#values, parameter) ? this.#values[parameter] : fallback; }
|
||||
readPrivate() { return this.#values.locale_source; }
|
||||
get privateValue() { return this.#values.locale_source; }
|
||||
}
|
||||
class FixtureClient {
|
||||
#layers;
|
||||
constructor(layer = new FixtureLayer()) {
|
||||
this.#layers = { [layerName]: layer, other_layer: new FixtureLayer({ enable_i18n: false }) };
|
||||
this.calls = [];
|
||||
this.events = [];
|
||||
this.gateCalls = [];
|
||||
}
|
||||
getLayer(name, ...options) { this.calls.push({ name, options, receiver: this }); return this.#layers[name]; }
|
||||
checkGate(name) { this.gateCalls.push(name); return this.#layers.other_layer.get("enable_i18n", false); }
|
||||
$emt(event) { this.events.push(event.name); this.onValuesUpdated?.(event); }
|
||||
}
|
||||
|
||||
function fixture({ url = "app://-/index.html", language = "zh-CN", resources = [languageResource], client = new FixtureClient(), registry, iframe = false, observer = true, documentElement = true } = {}) {
|
||||
const parsed = new URL(url);
|
||||
// Location deliberately has no username/password fields: browsers expose
|
||||
// those through new URL(location.href), not through the Location interface.
|
||||
const location = { href: parsed.href, protocol: parsed.protocol, host: parsed.host, hostname: parsed.hostname, port: parsed.port, pathname: parsed.pathname, search: parsed.search, hash: parsed.hash, origin: parsed.origin };
|
||||
const timers = new Map(), scheduled = [], observers = [];
|
||||
let entries = resources.map((name) => ({ name, initiatorType: "script" }));
|
||||
const sandbox = {
|
||||
location, URL,
|
||||
document: { documentElement: documentElement ? { lang: language } : null },
|
||||
performance: { getEntriesByType(type) { assert.equal(type, "resource"); return entries; } },
|
||||
setInterval(callback, interval) { assert.equal(interval, 100); const id = scheduled.length + 1; scheduled.push(callback); timers.set(id, callback); return id; },
|
||||
clearInterval(id) { timers.delete(id); },
|
||||
};
|
||||
if (observer) sandbox.PerformanceObserver = class {
|
||||
constructor(callback) { this.callback = callback; this.active = false; observers.push(this); }
|
||||
observe(options) { assert.equal(options.type, "resource"); this.active = true; if (options.buffered) this.callback({ getEntries: () => entries }); }
|
||||
disconnect() { this.active = false; }
|
||||
};
|
||||
sandbox.window = sandbox;
|
||||
sandbox.top = iframe ? {} : sandbox;
|
||||
sandbox.__STATSIG__ = registry ?? { firstInstance: client, instances: { fixture: client } };
|
||||
const context = vm.createContext(sandbox);
|
||||
return {
|
||||
sandbox, client, timers, observers, scheduled,
|
||||
install(options = { locale: "zh-CN", owner }) { return vm.runInContext(source.replace("__CODEXX_LANGUAGE_CONFIG__", JSON.stringify(options)), context, { timeout: 500 }); },
|
||||
state() { return sandbox[marker]; },
|
||||
tick() { for (const callback of [...timers.values()]) callback(); },
|
||||
emitResources(names) { const delivered = names.map((name) => ({ name, initiatorType: "script" })); for (const current of observers) if (current.active) current.callback({ getEntries: () => delivered }); },
|
||||
clearResources() { entries = []; },
|
||||
};
|
||||
}
|
||||
|
||||
test("only the i18n parameter of the named layer changes; other gates, fields and receivers remain original", () => {
|
||||
const client = new FixtureClient();
|
||||
const layer = client.getLayer(layerName);
|
||||
const other = client.getLayer("other_layer");
|
||||
client.calls.length = 0;
|
||||
const checkGate = client.checkGate;
|
||||
const f = fixture({ client });
|
||||
assert.equal(f.install().ready, true);
|
||||
assert.ok(client.calls.every((call) => call.name === layerName && call.receiver === client));
|
||||
assert.deepEqual(client.gateCalls, [], "the runtime never evaluates unrelated feature gates");
|
||||
assert.equal(client.checkGate, checkGate);
|
||||
assert.equal(client.checkGate("unrelated-account-gate"), false);
|
||||
assert.equal(client.getLayer("other_layer"), other);
|
||||
const view = client.getLayer(layerName);
|
||||
assert.equal(view.get("enable_i18n", false), true);
|
||||
assert.equal(view.get("locale_source", "wrong"), "fixture-original");
|
||||
assert.equal(view.get("unrelated-field", "original fallback"), "original fallback");
|
||||
assert.equal(view.readPrivate(), "fixture-original");
|
||||
assert.equal(view.privateValue, "fixture-original");
|
||||
assert.equal(view.get, view.get, "the i18n getter has a stable reference for React dependencies");
|
||||
assert.equal(view.readPrivate, view.readPrivate, "other bound methods have stable references");
|
||||
const previousBoundMethod = view.readPrivate;
|
||||
layer.readPrivate = function () { return `${this.privateValue}-updated`; };
|
||||
assert.notEqual(view.readPrivate, previousBoundMethod, "a later SDK method replacement is observed");
|
||||
assert.equal(view.readPrivate(), "fixture-original-updated");
|
||||
assert.equal(layer.get("enable_i18n", false), false, "the actual SDK layer data is not mutated");
|
||||
assert.equal(Object.getPrototypeOf(view), Object.getPrototypeOf(layer));
|
||||
f.state().restore();
|
||||
});
|
||||
|
||||
test("frozen layers with immutable own get methods do not violate Proxy invariants", () => {
|
||||
const layer = new FixtureLayer();
|
||||
Object.defineProperty(layer, "get", { value: layer.get, configurable: false, writable: false, enumerable: true });
|
||||
Object.freeze(layer);
|
||||
const f = fixture({ client: new FixtureClient(layer) });
|
||||
assert.equal(f.install().ready, true);
|
||||
const view = f.client.getLayer(layerName);
|
||||
assert.equal(view.get("enable_i18n", false), true);
|
||||
assert.equal(view.readPrivate(), "fixture-original");
|
||||
assert.equal(view.privateValue, "fixture-original");
|
||||
assert.equal("name" in view, true);
|
||||
assert.deepEqual(Object.keys(view), Object.keys(layer));
|
||||
f.state().restore();
|
||||
assert.equal(view.get("enable_i18n", false), false, "held views stop overriding after restoration");
|
||||
});
|
||||
|
||||
test("writable nonconfigurable methods and configurable accessors restore their exact descriptors", () => {
|
||||
for (const accessor of [false, true]) {
|
||||
const client = new FixtureClient();
|
||||
const original = client.getLayer;
|
||||
Object.defineProperty(client, "getLayer", accessor
|
||||
? { configurable: true, enumerable: true, get() { return original; } }
|
||||
: { configurable: false, enumerable: true, writable: true, value: original });
|
||||
const descriptor = Object.getOwnPropertyDescriptor(client, "getLayer");
|
||||
const f = fixture({ client });
|
||||
assert.equal(f.install().ready, true);
|
||||
f.state().restore();
|
||||
assert.deepEqual(Object.getOwnPropertyDescriptor(client, "getLayer"), descriptor);
|
||||
}
|
||||
});
|
||||
|
||||
test("unpatchable client methods fail closed without reporting the compatibility layer ready", () => {
|
||||
const client = new FixtureClient();
|
||||
const original = client.getLayer;
|
||||
Object.defineProperty(client, "getLayer", { configurable: false, writable: false, value: original });
|
||||
const f = fixture({ client });
|
||||
assert.equal(f.install().ready, false);
|
||||
assert.equal(client.getLayer, original);
|
||||
assert.deepEqual(client.events, []);
|
||||
f.state().restore();
|
||||
});
|
||||
|
||||
test("only the top-level official app origin and supported page paths are accepted", () => {
|
||||
for (const url of ["https://chatgpt.com/", "http://127.0.0.1/index.html", "app://other/index.html", "app://-/browser.html", "app://user@-/index.html", "app://user:password@-/index.html", "app://-:123/index.html"]) {
|
||||
const f = fixture({ url });
|
||||
assert.equal(f.install().reason, "unsupported_origin", url);
|
||||
assert.equal(f.state(), undefined);
|
||||
assert.equal(f.timers.size, 0);
|
||||
assert.deepEqual(f.client.events, []);
|
||||
}
|
||||
assert.equal(fixture({ iframe: true }).install().reason, "unsupported_origin");
|
||||
for (const url of ["app://-/", "app://-/index.html?initialRoute=%2Fsettings#fixture"]) {
|
||||
const f = fixture({ url });
|
||||
assert.equal(f.install().installed, true);
|
||||
f.state().restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("unsupported locales and untrusted option shapes cause no hooks", () => {
|
||||
for (const options of [null, {}, { locale: "fr-FR", owner }, { locale: "zh-CN", owner: "not-a-session-id" }, { locale: "zh-CN", owner: '";globalThis.fixtureInjected=true;//' }]) {
|
||||
const f = fixture();
|
||||
assert.equal(f.install(options).reason, "invalid_options");
|
||||
assert.equal(f.state(), undefined);
|
||||
assert.equal(f.sandbox.fixtureInjected, undefined);
|
||||
assert.deepEqual(f.client.events, []);
|
||||
}
|
||||
});
|
||||
|
||||
test("a late SDK singleton notifies subscribers after the narrow hook becomes available", () => {
|
||||
const f = fixture({ registry: {} });
|
||||
assert.equal(f.install().ready, false);
|
||||
const observed = [];
|
||||
f.client.onValuesUpdated = () => observed.push(f.client.getLayer(layerName).get("enable_i18n", false));
|
||||
f.sandbox.__STATSIG__ = { firstInstance: f.client, instances: { same: f.client } };
|
||||
f.tick();
|
||||
assert.equal(f.state().status().ready, true);
|
||||
assert.deepEqual(observed, [true]);
|
||||
assert.deepEqual(f.client.events, ["values_updated"]);
|
||||
f.state().restore();
|
||||
});
|
||||
|
||||
test("early registry and base-constructor registration intercept a later getter assignment before the first read", () => {
|
||||
const f = fixture({ registry: {} });
|
||||
delete f.sandbox.__STATSIG__;
|
||||
assert.equal(f.install().ready, false);
|
||||
const registry = {};
|
||||
f.sandbox.__STATSIG__ = registry;
|
||||
const rawLayer = new FixtureLayer();
|
||||
const original = function () { assert.equal(this, client); return rawLayer; };
|
||||
let missingDuringBase = false;
|
||||
class Base {
|
||||
constructor() {
|
||||
const instances = registry.instances ?? {};
|
||||
instances.fixture = this;
|
||||
registry.firstInstance ||= this;
|
||||
registry.instances = instances;
|
||||
f.sandbox.__STATSIG__ = registry;
|
||||
missingDuringBase = typeof this.getLayer !== "function";
|
||||
}
|
||||
}
|
||||
class Derived extends Base {
|
||||
constructor() { super(); this.getLayer = original; }
|
||||
}
|
||||
const client = new Derived();
|
||||
assert.equal(missingDuringBase, true);
|
||||
assert.equal(client.getLayer(layerName).get("enable_i18n", false), true, "no timer tick or SDK event is needed");
|
||||
assert.equal(client.getLayer(layerName).get("locale_source", "wrong"), "fixture-original");
|
||||
assert.equal(rawLayer.get("enable_i18n", false), false);
|
||||
const laterSdkGetter = function () { return rawLayer; };
|
||||
client.getLayer = laterSdkGetter;
|
||||
assert.equal(client.getLayer(layerName).get("enable_i18n", false), true);
|
||||
f.state().restore();
|
||||
assert.equal(client.getLayer, laterSdkGetter, "restoration preserves the latest SDK-assigned method exactly");
|
||||
assert.equal(f.sandbox.__STATSIG__, registry);
|
||||
assert.equal(registry.instances.fixture, client);
|
||||
for (const [object, key] of [[f.sandbox, "__STATSIG__"], [registry, "firstInstance"], [registry, "instances"], [registry.instances, "fixture"], [client, "getLayer"]]) {
|
||||
assert.ok(Object.hasOwn(Object.getOwnPropertyDescriptor(object, key), "value"), `${key} is no longer an owned accessor`);
|
||||
}
|
||||
});
|
||||
|
||||
test("repeated injection and duplicate registry references never stack hooks or pollers", () => {
|
||||
const f = fixture();
|
||||
f.install();
|
||||
const replacement = f.client.getLayer;
|
||||
f.install(); f.tick(); f.install();
|
||||
assert.equal(f.client.getLayer, replacement);
|
||||
assert.equal(f.timers.size, 1);
|
||||
assert.equal(f.observers.length, 1);
|
||||
assert.deepEqual(f.client.events, ["values_updated"]);
|
||||
assert.equal(f.install({ locale: "zh-CN", owner: "b".repeat(64) }).reason, "another_owner");
|
||||
assert.equal(f.client.getLayer, replacement);
|
||||
f.state().restore();
|
||||
});
|
||||
|
||||
test("restoration removes inherited overrides and old handles or queued scans cannot rehook", () => {
|
||||
const f = fixture();
|
||||
const original = f.client.getLayer;
|
||||
f.install();
|
||||
const state = f.state();
|
||||
const heldView = f.client.getLayer(layerName);
|
||||
const queuedScan = f.scheduled[0];
|
||||
state.restore();
|
||||
assert.equal(f.state(), undefined);
|
||||
assert.equal(f.timers.size, 0);
|
||||
assert.ok(f.observers.every((observer) => !observer.active));
|
||||
assert.equal(Object.hasOwn(f.client, "getLayer"), false);
|
||||
assert.equal(f.client.getLayer, original);
|
||||
assert.equal(heldView.get("enable_i18n", false), false);
|
||||
const events = f.client.events.length;
|
||||
assert.equal(state.status().installed, false);
|
||||
queuedScan(); state.restore();
|
||||
assert.equal(f.client.getLayer, original);
|
||||
assert.equal(Object.hasOwn(f.client, "getLayer"), false);
|
||||
assert.equal(f.client.events.length, events);
|
||||
});
|
||||
|
||||
test("restoration preserves later SDK method replacements", () => {
|
||||
const f = fixture();
|
||||
const original = f.client.getLayer;
|
||||
f.install();
|
||||
const external = function (name, ...args) { return original.call(this, name, ...args); };
|
||||
f.client.getLayer = external;
|
||||
f.tick(); // The SDK replaced its method while compatibility was active.
|
||||
f.state().restore();
|
||||
assert.equal(f.client.getLayer, external);
|
||||
});
|
||||
|
||||
test("readiness follows only current SDK registry clients, not past account instances", () => {
|
||||
const f = fixture();
|
||||
const old = f.client;
|
||||
const original = old.getLayer;
|
||||
f.install();
|
||||
const next = new FixtureClient();
|
||||
f.sandbox.__STATSIG__ = { firstInstance: next, instances: { same: next } };
|
||||
f.tick();
|
||||
assert.equal(f.state().status().clients, 1);
|
||||
assert.equal(f.state().status().ready, true);
|
||||
f.sandbox.__STATSIG__ = {};
|
||||
assert.equal(f.state().status().ready, false);
|
||||
assert.equal(f.state().status().clients, 0);
|
||||
f.state().restore();
|
||||
assert.equal(old.getLayer, original);
|
||||
assert.equal(Object.hasOwn(next, "getLayer"), false);
|
||||
});
|
||||
|
||||
test("readiness requires the selected language and the official bundled translation resource", () => {
|
||||
for (const resources of [[], ["https://other.example/assets/zh-CN-fixture.js"], ["app://other/assets/zh-CN-fixture.js"], ["app://-/different/zh-CN-fixture.js"], ["app://user@-/assets/zh-CN-fixture.js"]]) {
|
||||
const f = fixture({ resources });
|
||||
assert.equal(f.install().ready, false);
|
||||
f.state().restore();
|
||||
}
|
||||
for (const language of ["zh-TW", "zh-HK", "en-US"]) {
|
||||
const f = fixture({ language });
|
||||
assert.equal(f.install().ready, false);
|
||||
f.state().restore();
|
||||
}
|
||||
const english = fixture({ language: "en-US", resources: [] });
|
||||
assert.equal(english.install({ locale: "en-US", owner }).ready, true);
|
||||
english.state().restore();
|
||||
});
|
||||
|
||||
test("observed language resources survive resource-timing buffer eviction", () => {
|
||||
const f = fixture({ resources: [] });
|
||||
assert.equal(f.install().ready, false);
|
||||
f.emitResources([languageResource]);
|
||||
f.clearResources();
|
||||
assert.equal(f.state().status().ready, true);
|
||||
f.state().restore();
|
||||
});
|
||||
|
||||
test("early documents without a documentElement remain unready until the language is present", () => {
|
||||
const f = fixture({ documentElement: false });
|
||||
assert.equal(f.install().ready, false);
|
||||
f.sandbox.document.documentElement = { lang: "zh-CN" };
|
||||
assert.equal(f.state().status().ready, true);
|
||||
f.state().restore();
|
||||
});
|
||||
|
||||
test("the runtime does not access account data, messages, credential storage or network APIs", () => {
|
||||
const f = fixture();
|
||||
for (const [object, names] of [[f.sandbox, ["fetch", "XMLHttpRequest", "localStorage", "sessionStorage"]], [f.client, ["user", "apiKey", "messages", "account"]], [f.sandbox.document, ["body", "cookie"]]]) {
|
||||
for (const name of names) Object.defineProperty(object, name, { configurable: true, get() { assert.fail(`runtime accessed forbidden fixture field ${name}`); } });
|
||||
}
|
||||
assert.equal(f.install().ready, true);
|
||||
assert.equal(f.state().status().ready, true);
|
||||
f.tick();
|
||||
f.state().restore();
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { dirname, join, relative, resolve } from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import test from "node:test";
|
||||
import ts from "typescript";
|
||||
import { createElement } from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { configHealthIssueLocation, primaryConfigHealthIssue, configHealthRepairUnavailableReason } from "../src/configHealthPresentation.ts";
|
||||
import { configHealthIssueKey } from "../src/configHealthMonitor.ts";
|
||||
|
||||
const desktop = dirname(dirname(fileURLToPath(import.meta.url)));
|
||||
const issue = {
|
||||
code: "provider-boolean-text", title: "供应商开关格式不正确", description: "supports_websockets 被写成了字符串。",
|
||||
repairable: true, path: "/fixtures/配置目录/config.toml", line: 7, column: 3,
|
||||
key: "model_providers.custom.supports_websockets", suggestion: "将 supports_websockets 改为 false(不带引号)。",
|
||||
};
|
||||
const report = {
|
||||
codexDir: "/fixtures/配置目录", fingerprint: "fixture-only", status: "issues", issues: [issue],
|
||||
canRepair: true, repairSummary: ["将写成文字的开关恢复为正确格式"], checkedAt: "2026-10-08T00:00:00Z",
|
||||
};
|
||||
|
||||
let components;
|
||||
async function ui() {
|
||||
if (components) return components;
|
||||
components = (async () => {
|
||||
const scratch = await mkdtemp(join(desktop, "tests/.config-health-ui-"));
|
||||
try {
|
||||
const emitted = new Map();
|
||||
async function compile(sourcePath) {
|
||||
if (emitted.has(sourcePath)) return emitted.get(sourcePath);
|
||||
const outputPath = join(scratch, relative(desktop, sourcePath).replace(/\.tsx?$/, ".mjs"));
|
||||
emitted.set(sourcePath, outputPath);
|
||||
const source = await readFile(sourcePath, "utf8");
|
||||
let output = ts.transpileModule(source, {
|
||||
fileName: sourcePath,
|
||||
compilerOptions: { target: ts.ScriptTarget.ES2020, module: ts.ModuleKind.ESNext, jsx: ts.JsxEmit.ReactJSX },
|
||||
}).outputText.replace(/import\s*["'][^"']+\.css["'];?/g, "");
|
||||
for (const match of [...output.matchAll(/\bfrom\s*["'](\.[^"']+)["']/g)]) {
|
||||
const specifier = match[1];
|
||||
const base = resolve(dirname(sourcePath), specifier);
|
||||
let dependency;
|
||||
for (const candidate of [`${base}.ts`, `${base}.tsx`, join(base, "index.ts")]) {
|
||||
try { await readFile(candidate, "utf8"); dependency = candidate; break; } catch { /* Try normal TS module resolution candidates. */ }
|
||||
}
|
||||
assert.ok(dependency, `could not resolve ${specifier} from ${sourcePath}`);
|
||||
const dependencyOutput = await compile(dependency);
|
||||
let replacement = relative(dirname(outputPath), dependencyOutput).replaceAll("\\", "/");
|
||||
if (!replacement.startsWith(".")) replacement = `./${replacement}`;
|
||||
output = output.replaceAll(`"${specifier}"`, `"${replacement}"`).replaceAll(`'${specifier}'`, `'${replacement}'`);
|
||||
}
|
||||
await mkdir(dirname(outputPath), { recursive: true });
|
||||
await writeFile(outputPath, output);
|
||||
return outputPath;
|
||||
}
|
||||
const panel = await compile(join(desktop, "src/components/ConfigHealthPanel.tsx"));
|
||||
const toast = await compile(join(desktop, "src/components/ConfigHealthToast.tsx"));
|
||||
return { ...await import(pathToFileURL(panel).href), ...await import(pathToFileURL(toast).href) };
|
||||
} finally { await rm(scratch, { recursive: true, force: true }); }
|
||||
})();
|
||||
return components;
|
||||
}
|
||||
|
||||
const panelProps = { lang: "zh", report, checking: false, repairing: false, error: "", onCheck() {}, onRepair() {}, onOpenConfig() {} };
|
||||
const toastProps = { lang: "zh", report, repairing: false, onRepair() {}, onDismiss() {}, onOpenSettings() {} };
|
||||
|
||||
test("exact path, original line and column, parameter, and suggestion render in panel and notice", async () => {
|
||||
const { ConfigHealthPanel, ConfigHealthToast } = await ui();
|
||||
for (const [Component, props] of [[ConfigHealthPanel, panelProps], [ConfigHealthToast, toastProps]]) {
|
||||
const html = renderToStaticMarkup(createElement(Component, props));
|
||||
for (const detail of [issue.path, "第 7 行,第 3 列", issue.key, issue.suggestion, "修复配置"]) assert.ok(html.includes(detail), detail);
|
||||
const repairButton = [...html.matchAll(/<button\b[^>]*>[\s\S]*?<\/button>/g)].map(([button]) => button).find((button) => button.includes("修复配置"));
|
||||
assert.ok(repairButton);
|
||||
assert.doesNotMatch(repairButton, /\bdisabled=/);
|
||||
}
|
||||
assert.equal(configHealthIssueLocation(issue, report, "en").position, "line 7, column 3");
|
||||
});
|
||||
|
||||
test("official history repair is actionable and a missing table never claims an invented source line", async () => {
|
||||
const missing = { ...issue, code: "session-provider-definition-missing", title: "旧会话使用的供应商缺少配置", line: null, column: null, key: "model_providers.old_proxy", suggestion: "新增 model_providers.old_proxy,使用当前已确认的 OpenAI 官方登录。" };
|
||||
const official = { ...report, issues: [missing], repairSummary: ["让旧会话沿用当前供应商「OpenAI」"] };
|
||||
const { ConfigHealthPanel, ConfigHealthToast } = await ui();
|
||||
for (const [Component, props] of [[ConfigHealthPanel, panelProps], [ConfigHealthToast, toastProps]]) {
|
||||
const html = renderToStaticMarkup(createElement(Component, { ...props, report: official }));
|
||||
assert.ok(html.includes("修复配置"));
|
||||
assert.ok(html.includes("未定义,尚无对应行"));
|
||||
assert.ok(html.includes("model_providers.old_proxy"));
|
||||
assert.ok(html.includes("OpenAI"));
|
||||
assert.ok(!html.includes("第 7 行"));
|
||||
}
|
||||
});
|
||||
|
||||
test("unsupported values display their precise manual action and explain the unavailable repair button", async () => {
|
||||
const unsupported = { ...issue, repairable: false, key: "model_providers.custom.wire_api", suggestion: "先向供应商确认 Responses API 支持,再设置 wire_api = responses。" };
|
||||
const manual = { ...report, canRepair: false, repairSummary: [], issues: [unsupported] };
|
||||
const { ConfigHealthPanel, ConfigHealthToast } = await ui();
|
||||
const html = renderToStaticMarkup(createElement(ConfigHealthPanel, { ...panelProps, report: manual }));
|
||||
assert.ok(html.includes("需手动修复"));
|
||||
assert.ok(html.includes(unsupported.suggestion));
|
||||
assert.ok(html.includes(`title="${unsupported.suggestion}"`));
|
||||
const manualButton = [...html.matchAll(/<button\b[^>]*>[\s\S]*?<\/button>/g)].map(([button]) => button).find((button) => button.includes("需手动修复"));
|
||||
assert.ok(manualButton);
|
||||
assert.match(manualButton, /\bdisabled=""/);
|
||||
const toast = renderToStaticMarkup(createElement(ConfigHealthToast, { ...toastProps, report: manual }));
|
||||
assert.ok(toast.includes(unsupported.key));
|
||||
assert.ok(toast.includes(unsupported.suggestion));
|
||||
assert.ok(toast.includes("查看设置"));
|
||||
assert.ok(!toast.includes("修复配置"));
|
||||
});
|
||||
|
||||
test("a mixed report advertises a supported issue while the panel retains all manual diagnostics", async () => {
|
||||
const manual = { ...issue, repairable: false, title: "必须手动处理", key: "model_providers.custom.base_url" };
|
||||
const mixed = { ...report, issues: [manual, issue] };
|
||||
assert.equal(primaryConfigHealthIssue(mixed), issue);
|
||||
assert.equal(configHealthRepairUnavailableReason({ ...mixed, canRepair: false }, "zh"), manual.suggestion);
|
||||
const { ConfigHealthToast, ConfigHealthPanel } = await ui();
|
||||
const toast = renderToStaticMarkup(createElement(ConfigHealthToast, { ...toastProps, report: mixed }));
|
||||
assert.ok(toast.includes(issue.key));
|
||||
assert.ok(!toast.includes(manual.key));
|
||||
const panel = renderToStaticMarkup(createElement(ConfigHealthPanel, { ...panelProps, report: mixed }));
|
||||
assert.ok(panel.includes(manual.key));
|
||||
assert.ok(panel.includes(issue.key));
|
||||
});
|
||||
|
||||
test("notification identity follows the parameter and repairability while ignoring source line shifts", () => {
|
||||
assert.equal(configHealthIssueKey(report), configHealthIssueKey({ ...report, issues: [{ ...issue, line: 80, column: 5 }] }));
|
||||
assert.notEqual(configHealthIssueKey(report), configHealthIssueKey({ ...report, issues: [{ ...issue, key: "model_providers.other.supports_websockets" }] }));
|
||||
assert.notEqual(configHealthIssueKey(report), configHealthIssueKey({ ...report, issues: [{ ...issue, repairable: false }] }));
|
||||
});
|
||||
|
||||
test("file-level diagnostics and legacy reports use a usable path without claiming a line", () => {
|
||||
assert.deepEqual(configHealthIssueLocation({ ...issue, key: '"<文件编码>"', line: null, column: null }, report, "zh"), { path: issue.path, position: "文件层面", key: '"<文件编码>"' });
|
||||
const legacy = { code: "legacy", title: "Legacy", description: "Review", repairable: false };
|
||||
assert.equal(configHealthIssueLocation(legacy, { ...report, codexDir: "/fixtures/codex/" }, "en").path, "/fixtures/codex/config.toml");
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user